@abstractframework/observer 0.2.1 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/assets/index-DPlIqHJ_.css +1 -0
- package/dist/assets/index-qNhYHB2C.js +150 -0
- package/dist/assets/index-qNhYHB2C.js.map +1 -0
- package/dist/index.html +2 -2
- package/package.json +1 -1
- package/dist/assets/index-BYhozpg0.css +0 -1
- package/dist/assets/index-CKmZd-uV.js +0 -150
- package/dist/assets/index-CKmZd-uV.js.map +0 -1
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
var P0=Object.defineProperty;var D0=(e,t,n)=>t in e?P0(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var Gs=(e,t,n)=>D0(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"]'))i(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"&&i(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 i(o){if(o.ep)return;o.ep=!0;const l=n(o);fetch(o.href,l)}})();function hg(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var b_={exports:{}},Zd={},j_={exports:{}},Yt={};/**
|
|
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 ny;function F0(){if(ny)return Yt;ny=1;var e=Symbol.for("react.element"),t=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),i=Symbol.for("react.strict_mode"),o=Symbol.for("react.profiler"),l=Symbol.for("react.provider"),u=Symbol.for("react.context"),c=Symbol.for("react.forward_ref"),f=Symbol.for("react.suspense"),_=Symbol.for("react.memo"),p=Symbol.for("react.lazy"),y=Symbol.iterator;function w(T){return T===null||typeof T!="object"?null:(T=y&&T[y]||T["@@iterator"],typeof T=="function"?T:null)}var x={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},S=Object.assign,j={};function E(T,Q,K){this.props=T,this.context=Q,this.refs=j,this.updater=K||x}E.prototype.isReactComponent={},E.prototype.setState=function(T,Q){if(typeof T!="object"&&typeof T!="function"&&T!=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,T,Q,"setState")},E.prototype.forceUpdate=function(T){this.updater.enqueueForceUpdate(this,T,"forceUpdate")};function A(){}A.prototype=E.prototype;function L(T,Q,K){this.props=T,this.context=Q,this.refs=j,this.updater=K||x}var O=L.prototype=new A;O.constructor=L,S(O,E.prototype),O.isPureReactComponent=!0;var M=Array.isArray,H=Object.prototype.hasOwnProperty,X={current:null},Y={key:!0,ref:!0,__self:!0,__source:!0};function Z(T,Q,K){var J,oe={},fe=null,_e=null;if(Q!=null)for(J in Q.ref!==void 0&&(_e=Q.ref),Q.key!==void 0&&(fe=""+Q.key),Q)H.call(Q,J)&&!Y.hasOwnProperty(J)&&(oe[J]=Q[J]);var we=arguments.length-2;if(we===1)oe.children=K;else if(1<we){for(var Ae=Array(we),Be=0;Be<we;Be++)Ae[Be]=arguments[Be+2];oe.children=Ae}if(T&&T.defaultProps)for(J in we=T.defaultProps,we)oe[J]===void 0&&(oe[J]=we[J]);return{$$typeof:e,type:T,key:fe,ref:_e,props:oe,_owner:X.current}}function re(T,Q){return{$$typeof:e,type:T.type,key:Q,ref:T.ref,props:T.props,_owner:T._owner}}function ie(T){return typeof T=="object"&&T!==null&&T.$$typeof===e}function ue(T){var Q={"=":"=0",":":"=2"};return"$"+T.replace(/[=:]/g,function(K){return Q[K]})}var F=/\/+/g;function C(T,Q){return typeof T=="object"&&T!==null&&T.key!=null?ue(""+T.key):Q.toString(36)}function N(T,Q,K,J,oe){var fe=typeof T;(fe==="undefined"||fe==="boolean")&&(T=null);var _e=!1;if(T===null)_e=!0;else switch(fe){case"string":case"number":_e=!0;break;case"object":switch(T.$$typeof){case e:case t:_e=!0}}if(_e)return _e=T,oe=oe(_e),T=J===""?"."+C(_e,0):J,M(oe)?(K="",T!=null&&(K=T.replace(F,"$&/")+"/"),N(oe,Q,K,"",function(Be){return Be})):oe!=null&&(ie(oe)&&(oe=re(oe,K+(!oe.key||_e&&_e.key===oe.key?"":(""+oe.key).replace(F,"$&/")+"/")+T)),Q.push(oe)),1;if(_e=0,J=J===""?".":J+":",M(T))for(var we=0;we<T.length;we++){fe=T[we];var Ae=J+C(fe,we);_e+=N(fe,Q,K,Ae,oe)}else if(Ae=w(T),typeof Ae=="function")for(T=Ae.call(T),we=0;!(fe=T.next()).done;)fe=fe.value,Ae=J+C(fe,we++),_e+=N(fe,Q,K,Ae,oe);else if(fe==="object")throw Q=String(T),Error("Objects are not valid as a React child (found: "+(Q==="[object Object]"?"object with keys {"+Object.keys(T).join(", ")+"}":Q)+"). If you meant to render a collection of children, use an array instead.");return _e}function P(T,Q,K){if(T==null)return T;var J=[],oe=0;return N(T,J,"","",function(fe){return Q.call(K,fe,oe++)}),J}function D(T){if(T._status===-1){var Q=T._result;Q=Q(),Q.then(function(K){(T._status===0||T._status===-1)&&(T._status=1,T._result=K)},function(K){(T._status===0||T._status===-1)&&(T._status=2,T._result=K)}),T._status===-1&&(T._status=0,T._result=Q)}if(T._status===1)return T._result.default;throw T._result}var ne={current:null},B={transition:null},z={ReactCurrentDispatcher:ne,ReactCurrentBatchConfig:B,ReactCurrentOwner:X};function G(){throw Error("act(...) is not supported in production builds of React.")}return Yt.Children={map:P,forEach:function(T,Q,K){P(T,function(){Q.apply(this,arguments)},K)},count:function(T){var Q=0;return P(T,function(){Q++}),Q},toArray:function(T){return P(T,function(Q){return Q})||[]},only:function(T){if(!ie(T))throw Error("React.Children.only expected to receive a single React element child.");return T}},Yt.Component=E,Yt.Fragment=n,Yt.Profiler=o,Yt.PureComponent=L,Yt.StrictMode=i,Yt.Suspense=f,Yt.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=z,Yt.act=G,Yt.cloneElement=function(T,Q,K){if(T==null)throw Error("React.cloneElement(...): The argument must be a React element, but you passed "+T+".");var J=S({},T.props),oe=T.key,fe=T.ref,_e=T._owner;if(Q!=null){if(Q.ref!==void 0&&(fe=Q.ref,_e=X.current),Q.key!==void 0&&(oe=""+Q.key),T.type&&T.type.defaultProps)var we=T.type.defaultProps;for(Ae in Q)H.call(Q,Ae)&&!Y.hasOwnProperty(Ae)&&(J[Ae]=Q[Ae]===void 0&&we!==void 0?we[Ae]:Q[Ae])}var Ae=arguments.length-2;if(Ae===1)J.children=K;else if(1<Ae){we=Array(Ae);for(var Be=0;Be<Ae;Be++)we[Be]=arguments[Be+2];J.children=we}return{$$typeof:e,type:T.type,key:oe,ref:fe,props:J,_owner:_e}},Yt.createContext=function(T){return T={$$typeof:u,_currentValue:T,_currentValue2:T,_threadCount:0,Provider:null,Consumer:null,_defaultValue:null,_globalName:null},T.Provider={$$typeof:l,_context:T},T.Consumer=T},Yt.createElement=Z,Yt.createFactory=function(T){var Q=Z.bind(null,T);return Q.type=T,Q},Yt.createRef=function(){return{current:null}},Yt.forwardRef=function(T){return{$$typeof:c,render:T}},Yt.isValidElement=ie,Yt.lazy=function(T){return{$$typeof:p,_payload:{_status:-1,_result:T},_init:D}},Yt.memo=function(T,Q){return{$$typeof:_,type:T,compare:Q===void 0?null:Q}},Yt.startTransition=function(T){var Q=B.transition;B.transition={};try{T()}finally{B.transition=Q}},Yt.unstable_act=G,Yt.useCallback=function(T,Q){return ne.current.useCallback(T,Q)},Yt.useContext=function(T){return ne.current.useContext(T)},Yt.useDebugValue=function(){},Yt.useDeferredValue=function(T){return ne.current.useDeferredValue(T)},Yt.useEffect=function(T,Q){return ne.current.useEffect(T,Q)},Yt.useId=function(){return ne.current.useId()},Yt.useImperativeHandle=function(T,Q,K){return ne.current.useImperativeHandle(T,Q,K)},Yt.useInsertionEffect=function(T,Q){return ne.current.useInsertionEffect(T,Q)},Yt.useLayoutEffect=function(T,Q){return ne.current.useLayoutEffect(T,Q)},Yt.useMemo=function(T,Q){return ne.current.useMemo(T,Q)},Yt.useReducer=function(T,Q,K){return ne.current.useReducer(T,Q,K)},Yt.useRef=function(T){return ne.current.useRef(T)},Yt.useState=function(T){return ne.current.useState(T)},Yt.useSyncExternalStore=function(T,Q,K){return ne.current.useSyncExternalStore(T,Q,K)},Yt.useTransition=function(){return ne.current.useTransition()},Yt.version="18.3.1",Yt}var sy;function Lf(){return sy||(sy=1,j_.exports=F0()),j_.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 ry;function z0(){if(ry)return Zd;ry=1;var e=Lf(),t=Symbol.for("react.element"),n=Symbol.for("react.fragment"),i=Object.prototype.hasOwnProperty,o=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,l={key:!0,ref:!0,__self:!0,__source:!0};function u(c,f,_){var p,y={},w=null,x=null;_!==void 0&&(w=""+_),f.key!==void 0&&(w=""+f.key),f.ref!==void 0&&(x=f.ref);for(p in f)i.call(f,p)&&!l.hasOwnProperty(p)&&(y[p]=f[p]);if(c&&c.defaultProps)for(p in f=c.defaultProps,f)y[p]===void 0&&(y[p]=f[p]);return{$$typeof:t,type:c,key:w,ref:x,props:y,_owner:o.current}}return Zd.Fragment=n,Zd.jsx=u,Zd.jsxs=u,Zd}var iy;function B0(){return iy||(iy=1,b_.exports=z0()),b_.exports}var s=B0(),m=Lf();const ve=hg(m);var Fh={},S_={exports:{}},Vr={},k_={exports:{}},N_={};/**
|
|
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 oy;function U0(){return oy||(oy=1,(function(e){function t(B,z){var G=B.length;B.push(z);e:for(;0<G;){var T=G-1>>>1,Q=B[T];if(0<o(Q,z))B[T]=z,B[G]=Q,G=T;else break e}}function n(B){return B.length===0?null:B[0]}function i(B){if(B.length===0)return null;var z=B[0],G=B.pop();if(G!==z){B[0]=G;e:for(var T=0,Q=B.length,K=Q>>>1;T<K;){var J=2*(T+1)-1,oe=B[J],fe=J+1,_e=B[fe];if(0>o(oe,G))fe<Q&&0>o(_e,oe)?(B[T]=_e,B[fe]=G,T=fe):(B[T]=oe,B[J]=G,T=J);else if(fe<Q&&0>o(_e,G))B[T]=_e,B[fe]=G,T=fe;else break e}}return z}function o(B,z){var G=B.sortIndex-z.sortIndex;return G!==0?G:B.id-z.id}if(typeof performance=="object"&&typeof performance.now=="function"){var l=performance;e.unstable_now=function(){return l.now()}}else{var u=Date,c=u.now();e.unstable_now=function(){return u.now()-c}}var f=[],_=[],p=1,y=null,w=3,x=!1,S=!1,j=!1,E=typeof setTimeout=="function"?setTimeout:null,A=typeof clearTimeout=="function"?clearTimeout:null,L=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function O(B){for(var z=n(_);z!==null;){if(z.callback===null)i(_);else if(z.startTime<=B)i(_),z.sortIndex=z.expirationTime,t(f,z);else break;z=n(_)}}function M(B){if(j=!1,O(B),!S)if(n(f)!==null)S=!0,D(H);else{var z=n(_);z!==null&&ne(M,z.startTime-B)}}function H(B,z){S=!1,j&&(j=!1,A(Z),Z=-1),x=!0;var G=w;try{for(O(z),y=n(f);y!==null&&(!(y.expirationTime>z)||B&&!ue());){var T=y.callback;if(typeof T=="function"){y.callback=null,w=y.priorityLevel;var Q=T(y.expirationTime<=z);z=e.unstable_now(),typeof Q=="function"?y.callback=Q:y===n(f)&&i(f),O(z)}else i(f);y=n(f)}if(y!==null)var K=!0;else{var J=n(_);J!==null&&ne(M,J.startTime-z),K=!1}return K}finally{y=null,w=G,x=!1}}var X=!1,Y=null,Z=-1,re=5,ie=-1;function ue(){return!(e.unstable_now()-ie<re)}function F(){if(Y!==null){var B=e.unstable_now();ie=B;var z=!0;try{z=Y(!0,B)}finally{z?C():(X=!1,Y=null)}}else X=!1}var C;if(typeof L=="function")C=function(){L(F)};else if(typeof MessageChannel<"u"){var N=new MessageChannel,P=N.port2;N.port1.onmessage=F,C=function(){P.postMessage(null)}}else C=function(){E(F,0)};function D(B){Y=B,X||(X=!0,C())}function ne(B,z){Z=E(function(){B(e.unstable_now())},z)}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(B){B.callback=null},e.unstable_continueExecution=function(){S||x||(S=!0,D(H))},e.unstable_forceFrameRate=function(B){0>B||125<B?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):re=0<B?Math.floor(1e3/B):5},e.unstable_getCurrentPriorityLevel=function(){return w},e.unstable_getFirstCallbackNode=function(){return n(f)},e.unstable_next=function(B){switch(w){case 1:case 2:case 3:var z=3;break;default:z=w}var G=w;w=z;try{return B()}finally{w=G}},e.unstable_pauseExecution=function(){},e.unstable_requestPaint=function(){},e.unstable_runWithPriority=function(B,z){switch(B){case 1:case 2:case 3:case 4:case 5:break;default:B=3}var G=w;w=B;try{return z()}finally{w=G}},e.unstable_scheduleCallback=function(B,z,G){var T=e.unstable_now();switch(typeof G=="object"&&G!==null?(G=G.delay,G=typeof G=="number"&&0<G?T+G:T):G=T,B){case 1:var Q=-1;break;case 2:Q=250;break;case 5:Q=1073741823;break;case 4:Q=1e4;break;default:Q=5e3}return Q=G+Q,B={id:p++,callback:z,priorityLevel:B,startTime:G,expirationTime:Q,sortIndex:-1},G>T?(B.sortIndex=G,t(_,B),n(f)===null&&B===n(_)&&(j?(A(Z),Z=-1):j=!0,ne(M,G-T))):(B.sortIndex=Q,t(f,B),S||x||(S=!0,D(H))),B},e.unstable_shouldYield=ue,e.unstable_wrapCallback=function(B){var z=w;return function(){var G=w;w=z;try{return B.apply(this,arguments)}finally{w=G}}}})(N_)),N_}var ay;function W0(){return ay||(ay=1,k_.exports=U0()),k_.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 ly;function q0(){if(ly)return Vr;ly=1;var e=Lf(),t=W0();function n(r){for(var a="https://reactjs.org/docs/error-decoder.html?invariant="+r,d=1;d<arguments.length;d++)a+="&args[]="+encodeURIComponent(arguments[d]);return"Minified React error #"+r+"; visit "+a+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}var i=new Set,o={};function l(r,a){u(r,a),u(r+"Capture",a)}function u(r,a){for(o[r]=a,r=0;r<a.length;r++)i.add(a[r])}var c=!(typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),f=Object.prototype.hasOwnProperty,_=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,p={},y={};function w(r){return f.call(y,r)?!0:f.call(p,r)?!1:_.test(r)?y[r]=!0:(p[r]=!0,!1)}function x(r,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:(r=r.toLowerCase().slice(0,5),r!=="data-"&&r!=="aria-");default:return!1}}function S(r,a,d,h){if(a===null||typeof a>"u"||x(r,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(r,a,d,h,v,b,R){this.acceptsBooleans=a===2||a===3||a===4,this.attributeName=h,this.attributeNamespace=v,this.mustUseProperty=d,this.propertyName=r,this.type=a,this.sanitizeURL=b,this.removeEmptyString=R}var E={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(r){E[r]=new j(r,0,!1,r,null,!1,!1)}),[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(r){var a=r[0];E[a]=new j(a,1,!1,r[1],null,!1,!1)}),["contentEditable","draggable","spellCheck","value"].forEach(function(r){E[r]=new j(r,2,!1,r.toLowerCase(),null,!1,!1)}),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(r){E[r]=new j(r,2,!1,r,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(r){E[r]=new j(r,3,!1,r.toLowerCase(),null,!1,!1)}),["checked","multiple","muted","selected"].forEach(function(r){E[r]=new j(r,3,!0,r,null,!1,!1)}),["capture","download"].forEach(function(r){E[r]=new j(r,4,!1,r,null,!1,!1)}),["cols","rows","size","span"].forEach(function(r){E[r]=new j(r,6,!1,r,null,!1,!1)}),["rowSpan","start"].forEach(function(r){E[r]=new j(r,5,!1,r.toLowerCase(),null,!1,!1)});var A=/[\-:]([a-z])/g;function L(r){return r[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(r){var a=r.replace(A,L);E[a]=new j(a,1,!1,r,null,!1,!1)}),"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(r){var a=r.replace(A,L);E[a]=new j(a,1,!1,r,"http://www.w3.org/1999/xlink",!1,!1)}),["xml:base","xml:lang","xml:space"].forEach(function(r){var a=r.replace(A,L);E[a]=new j(a,1,!1,r,"http://www.w3.org/XML/1998/namespace",!1,!1)}),["tabIndex","crossOrigin"].forEach(function(r){E[r]=new j(r,1,!1,r.toLowerCase(),null,!1,!1)}),E.xlinkHref=new j("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1),["src","href","action","formAction"].forEach(function(r){E[r]=new j(r,1,!1,r.toLowerCase(),null,!0,!0)});function O(r,a,d,h){var v=E.hasOwnProperty(a)?E[a]:null;(v!==null?v.type!==0:h||!(2<a.length)||a[0]!=="o"&&a[0]!=="O"||a[1]!=="n"&&a[1]!=="N")&&(S(a,d,v,h)&&(d=null),h||v===null?w(a)&&(d===null?r.removeAttribute(a):r.setAttribute(a,""+d)):v.mustUseProperty?r[v.propertyName]=d===null?v.type===3?!1:"":d:(a=v.attributeName,h=v.attributeNamespace,d===null?r.removeAttribute(a):(v=v.type,d=v===3||v===4&&d===!0?"":""+d,h?r.setAttributeNS(h,a,d):r.setAttribute(a,d))))}var M=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,H=Symbol.for("react.element"),X=Symbol.for("react.portal"),Y=Symbol.for("react.fragment"),Z=Symbol.for("react.strict_mode"),re=Symbol.for("react.profiler"),ie=Symbol.for("react.provider"),ue=Symbol.for("react.context"),F=Symbol.for("react.forward_ref"),C=Symbol.for("react.suspense"),N=Symbol.for("react.suspense_list"),P=Symbol.for("react.memo"),D=Symbol.for("react.lazy"),ne=Symbol.for("react.offscreen"),B=Symbol.iterator;function z(r){return r===null||typeof r!="object"?null:(r=B&&r[B]||r["@@iterator"],typeof r=="function"?r:null)}var G=Object.assign,T;function Q(r){if(T===void 0)try{throw Error()}catch(d){var a=d.stack.trim().match(/\n( *(at )?)/);T=a&&a[1]||""}return`
|
|
34
|
+
`+T+r}var K=!1;function J(r,a){if(!r||K)return"";K=!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(ye){var h=ye}Reflect.construct(r,[],a)}else{try{a.call()}catch(ye){h=ye}r.call(a.prototype)}else{try{throw Error()}catch(ye){h=ye}r()}}catch(ye){if(ye&&h&&typeof ye.stack=="string"){for(var v=ye.stack.split(`
|
|
35
|
+
`),b=h.stack.split(`
|
|
36
|
+
`),R=v.length-1,ee=b.length-1;1<=R&&0<=ee&&v[R]!==b[ee];)ee--;for(;1<=R&&0<=ee;R--,ee--)if(v[R]!==b[ee]){if(R!==1||ee!==1)do if(R--,ee--,0>ee||v[R]!==b[ee]){var se=`
|
|
37
|
+
`+v[R].replace(" at new "," at ");return r.displayName&&se.includes("<anonymous>")&&(se=se.replace("<anonymous>",r.displayName)),se}while(1<=R&&0<=ee);break}}}finally{K=!1,Error.prepareStackTrace=d}return(r=r?r.displayName||r.name:"")?Q(r):""}function oe(r){switch(r.tag){case 5:return Q(r.type);case 16:return Q("Lazy");case 13:return Q("Suspense");case 19:return Q("SuspenseList");case 0:case 2:case 15:return r=J(r.type,!1),r;case 11:return r=J(r.type.render,!1),r;case 1:return r=J(r.type,!0),r;default:return""}}function fe(r){if(r==null)return null;if(typeof r=="function")return r.displayName||r.name||null;if(typeof r=="string")return r;switch(r){case Y:return"Fragment";case X:return"Portal";case re:return"Profiler";case Z:return"StrictMode";case C:return"Suspense";case N:return"SuspenseList"}if(typeof r=="object")switch(r.$$typeof){case ue:return(r.displayName||"Context")+".Consumer";case ie:return(r._context.displayName||"Context")+".Provider";case F:var a=r.render;return r=r.displayName,r||(r=a.displayName||a.name||"",r=r!==""?"ForwardRef("+r+")":"ForwardRef"),r;case P:return a=r.displayName||null,a!==null?a:fe(r.type)||"Memo";case D:a=r._payload,r=r._init;try{return fe(r(a))}catch{}}return null}function _e(r){var a=r.type;switch(r.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 r=a.render,r=r.displayName||r.name||"",a.displayName||(r!==""?"ForwardRef("+r+")":"ForwardRef");case 7:return"Fragment";case 5:return a;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return fe(a);case 8:return a===Z?"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 we(r){switch(typeof r){case"boolean":case"number":case"string":case"undefined":return r;case"object":return r;default:return""}}function Ae(r){var a=r.type;return(r=r.nodeName)&&r.toLowerCase()==="input"&&(a==="checkbox"||a==="radio")}function Be(r){var a=Ae(r)?"checked":"value",d=Object.getOwnPropertyDescriptor(r.constructor.prototype,a),h=""+r[a];if(!r.hasOwnProperty(a)&&typeof d<"u"&&typeof d.get=="function"&&typeof d.set=="function"){var v=d.get,b=d.set;return Object.defineProperty(r,a,{configurable:!0,get:function(){return v.call(this)},set:function(R){h=""+R,b.call(this,R)}}),Object.defineProperty(r,a,{enumerable:d.enumerable}),{getValue:function(){return h},setValue:function(R){h=""+R},stopTracking:function(){r._valueTracker=null,delete r[a]}}}}function We(r){r._valueTracker||(r._valueTracker=Be(r))}function _t(r){if(!r)return!1;var a=r._valueTracker;if(!a)return!0;var d=a.getValue(),h="";return r&&(h=Ae(r)?r.checked?"true":"false":r.value),r=h,r!==d?(a.setValue(r),!0):!1}function Pe(r){if(r=r||(typeof document<"u"?document:void 0),typeof r>"u")return null;try{return r.activeElement||r.body}catch{return r.body}}function et(r,a){var d=a.checked;return G({},a,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:d??r._wrapperState.initialChecked})}function lt(r,a){var d=a.defaultValue==null?"":a.defaultValue,h=a.checked!=null?a.checked:a.defaultChecked;d=we(a.value!=null?a.value:d),r._wrapperState={initialChecked:h,initialValue:d,controlled:a.type==="checkbox"||a.type==="radio"?a.checked!=null:a.value!=null}}function Ye(r,a){a=a.checked,a!=null&&O(r,"checked",a,!1)}function Se(r,a){Ye(r,a);var d=we(a.value),h=a.type;if(d!=null)h==="number"?(d===0&&r.value===""||r.value!=d)&&(r.value=""+d):r.value!==""+d&&(r.value=""+d);else if(h==="submit"||h==="reset"){r.removeAttribute("value");return}a.hasOwnProperty("value")?ct(r,a.type,d):a.hasOwnProperty("defaultValue")&&ct(r,a.type,we(a.defaultValue)),a.checked==null&&a.defaultChecked!=null&&(r.defaultChecked=!!a.defaultChecked)}function Le(r,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=""+r._wrapperState.initialValue,d||a===r.value||(r.value=a),r.defaultValue=a}d=r.name,d!==""&&(r.name=""),r.defaultChecked=!!r._wrapperState.initialChecked,d!==""&&(r.name=d)}function ct(r,a,d){(a!=="number"||Pe(r.ownerDocument)!==r)&&(d==null?r.defaultValue=""+r._wrapperState.initialValue:r.defaultValue!==""+d&&(r.defaultValue=""+d))}var ge=Array.isArray;function De(r,a,d,h){if(r=r.options,a){a={};for(var v=0;v<d.length;v++)a["$"+d[v]]=!0;for(d=0;d<r.length;d++)v=a.hasOwnProperty("$"+r[d].value),r[d].selected!==v&&(r[d].selected=v),v&&h&&(r[d].defaultSelected=!0)}else{for(d=""+we(d),a=null,v=0;v<r.length;v++){if(r[v].value===d){r[v].selected=!0,h&&(r[v].defaultSelected=!0);return}a!==null||r[v].disabled||(a=r[v])}a!==null&&(a.selected=!0)}}function Ke(r,a){if(a.dangerouslySetInnerHTML!=null)throw Error(n(91));return G({},a,{value:void 0,defaultValue:void 0,children:""+r._wrapperState.initialValue})}function Dt(r,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(ge(d)){if(1<d.length)throw Error(n(93));d=d[0]}a=d}a==null&&(a=""),d=a}r._wrapperState={initialValue:we(d)}}function tn(r,a){var d=we(a.value),h=we(a.defaultValue);d!=null&&(d=""+d,d!==r.value&&(r.value=d),a.defaultValue==null&&r.defaultValue!==d&&(r.defaultValue=d)),h!=null&&(r.defaultValue=""+h)}function pn(r){var a=r.textContent;a===r._wrapperState.initialValue&&a!==""&&a!==null&&(r.value=a)}function Wt(r){switch(r){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(r,a){return r==null||r==="http://www.w3.org/1999/xhtml"?Wt(a):r==="http://www.w3.org/2000/svg"&&a==="foreignObject"?"http://www.w3.org/1999/xhtml":r}var dn,Wn=(function(r){return typeof MSApp<"u"&&MSApp.execUnsafeLocalFunction?function(a,d,h,v){MSApp.execUnsafeLocalFunction(function(){return r(a,d,h,v)})}:r})(function(r,a){if(r.namespaceURI!=="http://www.w3.org/2000/svg"||"innerHTML"in r)r.innerHTML=a;else{for(dn=dn||document.createElement("div"),dn.innerHTML="<svg>"+a.valueOf().toString()+"</svg>",a=dn.firstChild;r.firstChild;)r.removeChild(r.firstChild);for(;a.firstChild;)r.appendChild(a.firstChild)}});function Tt(r,a){if(a){var d=r.firstChild;if(d&&d===r.lastChild&&d.nodeType===3){d.nodeValue=a;return}}r.textContent=a}var bn={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},Fn=["Webkit","ms","Moz","O"];Object.keys(bn).forEach(function(r){Fn.forEach(function(a){a=a+r.charAt(0).toUpperCase()+r.substring(1),bn[a]=bn[r]})});function An(r,a,d){return a==null||typeof a=="boolean"||a===""?"":d||typeof a!="number"||a===0||bn.hasOwnProperty(r)&&bn[r]?(""+a).trim():a+"px"}function jn(r,a){r=r.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?r.setProperty(d,v):r[d]=v}}var Ln=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 yn(r,a){if(a){if(Ln[r]&&(a.children!=null||a.dangerouslySetInnerHTML!=null))throw Error(n(137,r));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 Ns(r,a){if(r.indexOf("-")===-1)return typeof a.is=="string";switch(r){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 Gn=null;function rs(r){return r=r.target||r.srcElement||window,r.correspondingUseElement&&(r=r.correspondingUseElement),r.nodeType===3?r.parentNode:r}var Nr=null,Kn=null,ce=null;function be(r){if(r=Wa(r)){if(typeof Nr!="function")throw Error(n(280));var a=r.stateNode;a&&(a=Tc(a),Nr(r.stateNode,r.type,a))}}function Ve(r){Kn?ce?ce.push(r):ce=[r]:Kn=r}function He(){if(Kn){var r=Kn,a=ce;if(ce=Kn=null,be(r),a)for(r=0;r<a.length;r++)be(a[r])}}function st(r,a){return r(a)}function ut(){}var At=!1;function kt(r,a,d){if(At)return r(a,d);At=!0;try{return st(r,a,d)}finally{At=!1,(Kn!==null||ce!==null)&&(ut(),He())}}function Vt(r,a){var d=r.stateNode;if(d===null)return null;var h=Tc(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)||(r=r.type,h=!(r==="button"||r==="input"||r==="select"||r==="textarea")),r=!h;break e;default:r=!1}if(r)return null;if(d&&typeof d!="function")throw Error(n(231,a,typeof d));return d}var dt=!1;if(c)try{var Xt={};Object.defineProperty(Xt,"passive",{get:function(){dt=!0}}),window.addEventListener("test",Xt,Xt),window.removeEventListener("test",Xt,Xt)}catch{dt=!1}function Ut(r,a,d,h,v,b,R,ee,se){var ye=Array.prototype.slice.call(arguments,3);try{a.apply(d,ye)}catch(Me){this.onError(Me)}}var Ct=!1,pt=null,Ot=!1,Ee=null,Ht={onError:function(r){Ct=!0,pt=r}};function Et(r,a,d,h,v,b,R,ee,se){Ct=!1,pt=null,Ut.apply(Ht,arguments)}function an(r,a,d,h,v,b,R,ee,se){if(Et.apply(this,arguments),Ct){if(Ct){var ye=pt;Ct=!1,pt=null}else throw Error(n(198));Ot||(Ot=!0,Ee=ye)}}function $t(r){var a=r,d=r;if(r.alternate)for(;a.return;)a=a.return;else{r=a;do a=r,(a.flags&4098)!==0&&(d=a.return),r=a.return;while(r)}return a.tag===3?d:null}function is(r){if(r.tag===13){var a=r.memoizedState;if(a===null&&(r=r.alternate,r!==null&&(a=r.memoizedState)),a!==null)return a.dehydrated}return null}function os(r){if($t(r)!==r)throw Error(n(188))}function Js(r){var a=r.alternate;if(!a){if(a=$t(r),a===null)throw Error(n(188));return a!==r?null:r}for(var d=r,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 os(v),r;if(b===h)return os(v),a;b=b.sibling}throw Error(n(188))}if(d.return!==h.return)d=v,h=b;else{for(var R=!1,ee=v.child;ee;){if(ee===d){R=!0,d=v,h=b;break}if(ee===h){R=!0,h=v,d=b;break}ee=ee.sibling}if(!R){for(ee=b.child;ee;){if(ee===d){R=!0,d=b,h=v;break}if(ee===h){R=!0,h=b,d=v;break}ee=ee.sibling}if(!R)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?r:a}function Cs(r){return r=Js(r),r!==null?hr(r):null}function hr(r){if(r.tag===5||r.tag===6)return r;for(r=r.child;r!==null;){var a=hr(r);if(a!==null)return a;r=r.sibling}return null}var Xs=t.unstable_scheduleCallback,lo=t.unstable_cancelCallback,xe=t.unstable_shouldYield,Yn=t.unstable_requestPaint,mn=t.unstable_now,co=t.unstable_getCurrentPriorityLevel,Ei=t.unstable_ImmediatePriority,Cr=t.unstable_UserBlockingPriority,mr=t.unstable_NormalPriority,Jr=t.unstable_LowPriority,ot=t.unstable_IdlePriority,sn=null,ms=null;function ai(r){if(ms&&typeof ms.onCommitFiberRoot=="function")try{ms.onCommitFiberRoot(sn,r,void 0,(r.current.flags&128)===128)}catch{}}var as=Math.clz32?Math.clz32:Aa,uo=Math.log,fo=Math.LN2;function Aa(r){return r>>>=0,r===0?32:31-(uo(r)/fo|0)|0}var zn=64,_r=4194304;function Tn(r){switch(r&-r){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 r&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return r&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return r}}function pr(r,a){var d=r.pendingLanes;if(d===0)return 0;var h=0,v=r.suspendedLanes,b=r.pingedLanes,R=d&268435455;if(R!==0){var ee=R&~v;ee!==0?h=Tn(ee):(b&=R,b!==0&&(h=Tn(b)))}else R=d&~v,R!==0?h=Tn(R):b!==0&&(h=Tn(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=r.entangledLanes,a!==0)for(r=r.entanglements,a&=h;0<a;)d=31-as(a),v=1<<d,h|=r[d],a&=~v;return h}function ho(r,a){switch(r){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 Xn(r,a){for(var d=r.suspendedLanes,h=r.pingedLanes,v=r.expirationTimes,b=r.pendingLanes;0<b;){var R=31-as(b),ee=1<<R,se=v[R];se===-1?((ee&d)===0||(ee&h)!==0)&&(v[R]=ho(ee,a)):se<=a&&(r.expiredLanes|=ee),b&=~ee}}function Zs(r){return r=r.pendingLanes&-1073741825,r!==0?r:r&1073741824?1073741824:0}function ls(){var r=zn;return zn<<=1,(zn&4194240)===0&&(zn=64),r}function Xr(r){for(var a=[],d=0;31>d;d++)a.push(r);return a}function _s(r,a,d){r.pendingLanes|=a,a!==536870912&&(r.suspendedLanes=0,r.pingedLanes=0),r=r.eventTimes,a=31-as(a),r[a]=d}function Ta(r,a){var d=r.pendingLanes&~a;r.pendingLanes=a,r.suspendedLanes=0,r.pingedLanes=0,r.expiredLanes&=a,r.mutableReadLanes&=a,r.entangledLanes&=a,a=r.entanglements;var h=r.eventTimes;for(r=r.expirationTimes;0<d;){var v=31-as(d),b=1<<v;a[v]=0,h[v]=-1,r[v]=-1,d&=~b}}function mo(r,a){var d=r.entangledLanes|=a;for(r=r.entanglements;d;){var h=31-as(d),v=1<<h;v&a|r[h]&a&&(r[h]|=a),d&=~v}}var rn=0;function yl(r){return r&=-r,1<r?4<r?(r&268435455)!==0?16:536870912:4:1}var $i,gr,Es,Ma,Er,li=!1,Ai=[],Qs=null,$s=null,$r=null,er=new Map,Ti=new Map,yr=[],ps="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 Mi(r,a){switch(r){case"focusin":case"focusout":Qs=null;break;case"dragenter":case"dragleave":$s=null;break;case"mouseover":case"mouseout":$r=null;break;case"pointerover":case"pointerout":er.delete(a.pointerId);break;case"gotpointercapture":case"lostpointercapture":Ti.delete(a.pointerId)}}function qo(r,a,d,h,v,b){return r===null||r.nativeEvent!==b?(r={blockedOn:a,domEventName:d,eventSystemFlags:h,nativeEvent:b,targetContainers:[v]},a!==null&&(a=Wa(a),a!==null&&gr(a)),r):(r.eventSystemFlags|=h,a=r.targetContainers,v!==null&&a.indexOf(v)===-1&&a.push(v),r)}function wl(r,a,d,h,v){switch(a){case"focusin":return Qs=qo(Qs,r,a,d,h,v),!0;case"dragenter":return $s=qo($s,r,a,d,h,v),!0;case"mouseover":return $r=qo($r,r,a,d,h,v),!0;case"pointerover":var b=v.pointerId;return er.set(b,qo(er.get(b)||null,r,a,d,h,v)),!0;case"gotpointercapture":return b=v.pointerId,Ti.set(b,qo(Ti.get(b)||null,r,a,d,h,v)),!0}return!1}function tr(r){var a=sa(r.target);if(a!==null){var d=$t(a);if(d!==null){if(a=d.tag,a===13){if(a=is(d),a!==null){r.blockedOn=a,Er(r.priority,function(){Es(d)});return}}else if(a===3&&d.stateNode.current.memoizedState.isDehydrated){r.blockedOn=d.tag===3?d.stateNode.containerInfo:null;return}}}r.blockedOn=null}function Ho(r){if(r.blockedOn!==null)return!1;for(var a=r.targetContainers;0<a.length;){var d=ae(r.domEventName,r.eventSystemFlags,a[0],r.nativeEvent);if(d===null){d=r.nativeEvent;var h=new d.constructor(d.type,d);Gn=h,d.target.dispatchEvent(h),Gn=null}else return a=Wa(d),a!==null&&gr(a),r.blockedOn=d,!1;a.shift()}return!0}function Zr(r,a,d){Ho(r)&&d.delete(a)}function cc(){li=!1,Qs!==null&&Ho(Qs)&&(Qs=null),$s!==null&&Ho($s)&&($s=null),$r!==null&&Ho($r)&&($r=null),er.forEach(Zr),Ti.forEach(Zr)}function wr(r,a){r.blockedOn===a&&(r.blockedOn=null,li||(li=!0,t.unstable_scheduleCallback(t.unstable_NormalPriority,cc)))}function _o(r){function a(v){return wr(v,r)}if(0<Ai.length){wr(Ai[0],r);for(var d=1;d<Ai.length;d++){var h=Ai[d];h.blockedOn===r&&(h.blockedOn=null)}}for(Qs!==null&&wr(Qs,r),$s!==null&&wr($s,r),$r!==null&&wr($r,r),er.forEach(a),Ti.forEach(a),d=0;d<yr.length;d++)h=yr[d],h.blockedOn===r&&(h.blockedOn=null);for(;0<yr.length&&(d=yr[0],d.blockedOn===null);)tr(d),d.blockedOn===null&&yr.shift()}var Ws=M.ReactCurrentBatchConfig,Vo=!0;function Go(r,a,d,h){var v=rn,b=Ws.transition;Ws.transition=null;try{rn=1,po(r,a,d,h)}finally{rn=v,Ws.transition=b}}function Ko(r,a,d,h){var v=rn,b=Ws.transition;Ws.transition=null;try{rn=4,po(r,a,d,h)}finally{rn=v,Ws.transition=b}}function po(r,a,d,h){if(Vo){var v=ae(r,a,d,h);if(v===null)Oi(r,a,h,U,d),Mi(r,h);else if(wl(v,r,a,d,h))h.stopPropagation();else if(Mi(r,h),a&4&&-1<ps.indexOf(r)){for(;v!==null;){var b=Wa(v);if(b!==null&&$i(b),b=ae(r,a,d,h),b===null&&Oi(r,a,h,U,d),b===v)break;v=b}v!==null&&h.stopPropagation()}else Oi(r,a,h,null,d)}}var U=null;function ae(r,a,d,h){if(U=null,r=rs(h),r=sa(r),r!==null)if(a=$t(r),a===null)r=null;else if(d=a.tag,d===13){if(r=is(a),r!==null)return r;r=null}else if(d===3){if(a.stateNode.current.memoizedState.isDehydrated)return a.tag===3?a.stateNode.containerInfo:null;r=null}else a!==r&&(r=null);return U=r,null}function je(r){switch(r){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(co()){case Ei:return 1;case Cr:return 4;case mr:case Jr:return 16;case ot:return 536870912;default:return 16}default:return 16}}var Ne=null,ke=null,Ue=null;function ft(){if(Ue)return Ue;var r,a=ke,d=a.length,h,v="value"in Ne?Ne.value:Ne.textContent,b=v.length;for(r=0;r<d&&a[r]===v[r];r++);var R=d-r;for(h=1;h<=R&&a[d-h]===v[b-h];h++);return Ue=v.slice(r,1<h?1-h:void 0)}function at(r){var a=r.keyCode;return"charCode"in r?(r=r.charCode,r===0&&a===13&&(r=13)):r=a,r===10&&(r=13),32<=r||r===13?r:0}function gt(){return!0}function Ft(){return!1}function Gt(r){function a(d,h,v,b,R){this._reactName=d,this._targetInst=v,this.type=h,this.nativeEvent=b,this.target=R,this.currentTarget=null;for(var ee in r)r.hasOwnProperty(ee)&&(d=r[ee],this[ee]=d?d(b):b[ee]);return this.isDefaultPrevented=(b.defaultPrevented!=null?b.defaultPrevented:b.returnValue===!1)?gt:Ft,this.isPropagationStopped=Ft,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=gt)},stopPropagation:function(){var d=this.nativeEvent;d&&(d.stopPropagation?d.stopPropagation():typeof d.cancelBubble!="unknown"&&(d.cancelBubble=!0),this.isPropagationStopped=gt)},persist:function(){},isPersistent:gt}),a}var gs={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(r){return r.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},Mt=Gt(gs),on=G({},gs,{view:0,detail:0}),En=Gt(on),_n,Zn,nr,Qr=G({},on,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:Yu,button:0,buttons:0,relatedTarget:function(r){return r.relatedTarget===void 0?r.fromElement===r.srcElement?r.toElement:r.fromElement:r.relatedTarget},movementX:function(r){return"movementX"in r?r.movementX:(r!==nr&&(nr&&r.type==="mousemove"?(_n=r.screenX-nr.screenX,Zn=r.screenY-nr.screenY):Zn=_n=0,nr=r),_n)},movementY:function(r){return"movementY"in r?r.movementY:Zn}}),Ri=Gt(Qr),Ra=G({},Qr,{dataTransfer:0}),Uf=Gt(Ra),uc=G({},on,{relatedTarget:0}),vl=Gt(uc),dc=G({},gs,{animationName:0,elapsedTime:0,pseudoElement:0}),fc=Gt(dc),hc=G({},gs,{clipboardData:function(r){return"clipboardData"in r?r.clipboardData:window.clipboardData}}),Wf=Gt(hc),Yo=G({},gs,{data:0}),qu=Gt(Yo),Hu={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},Vu={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"},Gu={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function Ku(r){var a=this.nativeEvent;return a.getModifierState?a.getModifierState(r):(r=Gu[r])?!!a[r]:!1}function Yu(){return Ku}var Ju=G({},on,{key:function(r){if(r.key){var a=Hu[r.key]||r.key;if(a!=="Unidentified")return a}return r.type==="keypress"?(r=at(r),r===13?"Enter":String.fromCharCode(r)):r.type==="keydown"||r.type==="keyup"?Vu[r.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:Yu,charCode:function(r){return r.type==="keypress"?at(r):0},keyCode:function(r){return r.type==="keydown"||r.type==="keyup"?r.keyCode:0},which:function(r){return r.type==="keypress"?at(r):r.type==="keydown"||r.type==="keyup"?r.keyCode:0}}),t_=Gt(Ju),qf=G({},Qr,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),mc=Gt(qf),nn=G({},on,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:Yu}),Xu=Gt(nn),n_=G({},gs,{propertyName:0,elapsedTime:0,pseudoElement:0}),Zu=Gt(n_),s_=G({},Qr,{deltaX:function(r){return"deltaX"in r?r.deltaX:"wheelDeltaX"in r?-r.wheelDeltaX:0},deltaY:function(r){return"deltaY"in r?r.deltaY:"wheelDeltaY"in r?-r.wheelDeltaY:"wheelDelta"in r?-r.wheelDelta:0},deltaZ:0,deltaMode:0}),Qu=Gt(s_),r_=[9,13,27,32],Qn=c&&"CompositionEvent"in window,qs=null;c&&"documentMode"in document&&(qs=document.documentMode);var xl=c&&"TextEvent"in window&&!qs,Hf=c&&(!Qn||qs&&8<qs&&11>=qs),La=" ",_c=!1;function Vf(r,a){switch(r){case"keyup":return r_.indexOf(a.keyCode)!==-1;case"keydown":return a.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function ed(r){return r=r.detail,typeof r=="object"&&"data"in r?r.data:null}var go=!1;function td(r,a){switch(r){case"compositionend":return ed(a);case"keypress":return a.which!==32?null:(_c=!0,La);case"textInput":return r=a.data,r===La&&_c?null:r;default:return null}}function Gf(r,a){if(go)return r==="compositionend"||!Qn&&Vf(r,a)?(r=ft(),Ue=ke=Ne=null,go=!1,r):null;switch(r){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 Hf&&a.locale!=="ko"?null:a.data;default:return null}}var pc={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 nd(r){var a=r&&r.nodeName&&r.nodeName.toLowerCase();return a==="input"?!!pc[r.type]:a==="textarea"}function sd(r,a,d,h){Ve(h),a=ta(a,"onChange"),0<a.length&&(d=new Mt("onChange","change",null,d,h),r.push({event:d,listeners:a}))}var bl=null,yo=null;function Kf(r){fi(r,0)}function Ia(r){var a=pi(r);if(_t(a))return r}function i_(r,a){if(r==="change")return a}var gc=!1;if(c){var rd;if(c){var yc="oninput"in document;if(!yc){var Yf=document.createElement("div");Yf.setAttribute("oninput","return;"),yc=typeof Yf.oninput=="function"}rd=yc}else rd=!1;gc=rd&&(!document.documentMode||9<document.documentMode)}function wc(){bl&&(bl.detachEvent("onpropertychange",Jf),yo=bl=null)}function Jf(r){if(r.propertyName==="value"&&Ia(yo)){var a=[];sd(a,yo,r,rs(r)),kt(Kf,a)}}function id(r,a,d){r==="focusin"?(wc(),bl=a,yo=d,bl.attachEvent("onpropertychange",Jf)):r==="focusout"&&wc()}function o_(r){if(r==="selectionchange"||r==="keyup"||r==="keydown")return Ia(yo)}function a_(r,a){if(r==="click")return Ia(a)}function l_(r,a){if(r==="input"||r==="change")return Ia(a)}function Oa(r,a){return r===a&&(r!==0||1/r===1/a)||r!==r&&a!==a}var Ar=typeof Object.is=="function"?Object.is:Oa;function wo(r,a){if(Ar(r,a))return!0;if(typeof r!="object"||r===null||typeof a!="object"||a===null)return!1;var d=Object.keys(r),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)||!Ar(r[v],a[v]))return!1}return!0}function Xf(r){for(;r&&r.firstChild;)r=r.firstChild;return r}function jl(r,a){var d=Xf(r);r=0;for(var h;d;){if(d.nodeType===3){if(h=r+d.textContent.length,r<=a&&h>=a)return{node:d,offset:a-r};r=h}e:{for(;d;){if(d.nextSibling){d=d.nextSibling;break e}d=d.parentNode}d=void 0}d=Xf(d)}}function Jo(r,a){return r&&a?r===a?!0:r&&r.nodeType===3?!1:a&&a.nodeType===3?Jo(r,a.parentNode):"contains"in r?r.contains(a):r.compareDocumentPosition?!!(r.compareDocumentPosition(a)&16):!1:!1}function Pa(){for(var r=window,a=Pe();a instanceof r.HTMLIFrameElement;){try{var d=typeof a.contentWindow.location.href=="string"}catch{d=!1}if(d)r=a.contentWindow;else break;a=Pe(r.document)}return a}function vo(r){var a=r&&r.nodeName&&r.nodeName.toLowerCase();return a&&(a==="input"&&(r.type==="text"||r.type==="search"||r.type==="tel"||r.type==="url"||r.type==="password")||a==="textarea"||r.contentEditable==="true")}function Sl(r){var a=Pa(),d=r.focusedElem,h=r.selectionRange;if(a!==d&&d&&d.ownerDocument&&Jo(d.ownerDocument.documentElement,d)){if(h!==null&&vo(d)){if(a=h.start,r=h.end,r===void 0&&(r=a),"selectionStart"in d)d.selectionStart=a,d.selectionEnd=Math.min(r,d.value.length);else if(r=(a=d.ownerDocument||document)&&a.defaultView||window,r.getSelection){r=r.getSelection();var v=d.textContent.length,b=Math.min(h.start,v);h=h.end===void 0?b:Math.min(h.end,v),!r.extend&&b>h&&(v=h,h=b,b=v),v=jl(d,b);var R=jl(d,h);v&&R&&(r.rangeCount!==1||r.anchorNode!==v.node||r.anchorOffset!==v.offset||r.focusNode!==R.node||r.focusOffset!==R.offset)&&(a=a.createRange(),a.setStart(v.node,v.offset),r.removeAllRanges(),b>h?(r.addRange(a),r.extend(R.node,R.offset)):(a.setEnd(R.node,R.offset),r.addRange(a)))}}for(a=[],r=d;r=r.parentNode;)r.nodeType===1&&a.push({element:r,left:r.scrollLeft,top:r.scrollTop});for(typeof d.focus=="function"&&d.focus(),d=0;d<a.length;d++)r=a[d],r.element.scrollLeft=r.left,r.element.scrollTop=r.top}}var vc=c&&"documentMode"in document&&11>=document.documentMode,xo=null,xc=null,Li=null,bc=!1;function Da(r,a,d){var h=d.window===d?d.document:d.nodeType===9?d:d.ownerDocument;bc||xo==null||xo!==Pe(h)||(h=xo,"selectionStart"in h&&vo(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}),Li&&wo(Li,h)||(Li=h,h=ta(xc,"onSelect"),0<h.length&&(a=new Mt("onSelect","select",null,a,d),r.push({event:a,listeners:h}),a.target=xo)))}function Xo(r,a){var d={};return d[r.toLowerCase()]=a.toLowerCase(),d["Webkit"+r]="webkit"+a,d["Moz"+r]="moz"+a,d}var Fa={animationend:Xo("Animation","AnimationEnd"),animationiteration:Xo("Animation","AnimationIteration"),animationstart:Xo("Animation","AnimationStart"),transitionend:Xo("Transition","TransitionEnd")},jc={},Zf={};c&&(Zf=document.createElement("div").style,"AnimationEvent"in window||(delete Fa.animationend.animation,delete Fa.animationiteration.animation,delete Fa.animationstart.animation),"TransitionEvent"in window||delete Fa.transitionend.transition);function Sc(r){if(jc[r])return jc[r];if(!Fa[r])return r;var a=Fa[r],d;for(d in a)if(a.hasOwnProperty(d)&&d in Zf)return jc[r]=a[d];return r}var kl=Sc("animationend"),ci=Sc("animationiteration"),Zo=Sc("animationstart"),Qf=Sc("transitionend"),Nl=new Map,eh="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 ui(r,a){Nl.set(r,a),l(a,[r])}for(var Qo=0;Qo<eh.length;Qo++){var sr=eh[Qo],bo=sr.toLowerCase(),kc=sr[0].toUpperCase()+sr.slice(1);ui(bo,"on"+kc)}ui(kl,"onAnimationEnd"),ui(ci,"onAnimationIteration"),ui(Zo,"onAnimationStart"),ui("dblclick","onDoubleClick"),ui("focusin","onFocus"),ui("focusout","onBlur"),ui(Qf,"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 di="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(" "),od=new Set("cancel close invalid load scroll toggle".split(" ").concat(di));function za(r,a,d){var h=r.type||"unknown-event";r.currentTarget=d,an(h,a,void 0,r),r.currentTarget=null}function fi(r,a){a=(a&4)!==0;for(var d=0;d<r.length;d++){var h=r[d],v=h.event;h=h.listeners;e:{var b=void 0;if(a)for(var R=h.length-1;0<=R;R--){var ee=h[R],se=ee.instance,ye=ee.currentTarget;if(ee=ee.listener,se!==b&&v.isPropagationStopped())break e;za(v,ee,ye),b=se}else for(R=0;R<h.length;R++){if(ee=h[R],se=ee.instance,ye=ee.currentTarget,ee=ee.listener,se!==b&&v.isPropagationStopped())break e;za(v,ee,ye),b=se}}}if(Ot)throw r=Ee,Ot=!1,Ee=null,r}function gn(r,a){var d=a[Ac];d===void 0&&(d=a[Ac]=new Set);var h=r+"__bubble";d.has(h)||(Hs(a,r,2,!1),d.add(h))}function ea(r,a,d){var h=0;a&&(h|=4),Hs(d,r,h,a)}var Ii="_reactListening"+Math.random().toString(36).slice(2);function Tr(r){if(!r[Ii]){r[Ii]=!0,i.forEach(function(d){d!=="selectionchange"&&(od.has(d)||ea(d,!1,r),ea(d,!0,r))});var a=r.nodeType===9?r:r.ownerDocument;a===null||a[Ii]||(a[Ii]=!0,ea("selectionchange",!1,a))}}function Hs(r,a,d,h){switch(je(a)){case 1:var v=Go;break;case 4:v=Ko;break;default:v=po}d=v.bind(null,a,d,r),v=void 0,!dt||a!=="touchstart"&&a!=="touchmove"&&a!=="wheel"||(v=!0),h?v!==void 0?r.addEventListener(a,d,{capture:!0,passive:v}):r.addEventListener(a,d,!0):v!==void 0?r.addEventListener(a,d,{passive:v}):r.addEventListener(a,d,!1)}function Oi(r,a,d,h,v){var b=h;if((a&1)===0&&(a&2)===0&&h!==null)e:for(;;){if(h===null)return;var R=h.tag;if(R===3||R===4){var ee=h.stateNode.containerInfo;if(ee===v||ee.nodeType===8&&ee.parentNode===v)break;if(R===4)for(R=h.return;R!==null;){var se=R.tag;if((se===3||se===4)&&(se=R.stateNode.containerInfo,se===v||se.nodeType===8&&se.parentNode===v))return;R=R.return}for(;ee!==null;){if(R=sa(ee),R===null)return;if(se=R.tag,se===5||se===6){h=b=R;continue e}ee=ee.parentNode}}h=h.return}kt(function(){var ye=b,Me=rs(d),Re=[];e:{var Te=Nl.get(r);if(Te!==void 0){var Xe=Mt,tt=r;switch(r){case"keypress":if(at(d)===0)break e;case"keydown":case"keyup":Xe=t_;break;case"focusin":tt="focus",Xe=vl;break;case"focusout":tt="blur",Xe=vl;break;case"beforeblur":case"afterblur":Xe=vl;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":Xe=Ri;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":Xe=Uf;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":Xe=Xu;break;case kl:case ci:case Zo:Xe=fc;break;case Qf:Xe=Zu;break;case"scroll":Xe=En;break;case"wheel":Xe=Qu;break;case"copy":case"cut":case"paste":Xe=Wf;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":Xe=mc}var nt=(a&4)!==0,ss=!nt&&r==="scroll",de=nt?Te!==null?Te+"Capture":null:Te;nt=[];for(var le=ye,me;le!==null;){me=le;var Fe=me.stateNode;if(me.tag===5&&Fe!==null&&(me=Fe,de!==null&&(Fe=Vt(le,de),Fe!=null&&nt.push(hi(le,Fe,me)))),ss)break;le=le.return}0<nt.length&&(Te=new Xe(Te,tt,null,d,Me),Re.push({event:Te,listeners:nt}))}}if((a&7)===0){e:{if(Te=r==="mouseover"||r==="pointerover",Xe=r==="mouseout"||r==="pointerout",Te&&d!==Gn&&(tt=d.relatedTarget||d.fromElement)&&(sa(tt)||tt[Fi]))break e;if((Xe||Te)&&(Te=Me.window===Me?Me:(Te=Me.ownerDocument)?Te.defaultView||Te.parentWindow:window,Xe?(tt=d.relatedTarget||d.toElement,Xe=ye,tt=tt?sa(tt):null,tt!==null&&(ss=$t(tt),tt!==ss||tt.tag!==5&&tt.tag!==6)&&(tt=null)):(Xe=null,tt=ye),Xe!==tt)){if(nt=Ri,Fe="onMouseLeave",de="onMouseEnter",le="mouse",(r==="pointerout"||r==="pointerover")&&(nt=mc,Fe="onPointerLeave",de="onPointerEnter",le="pointer"),ss=Xe==null?Te:pi(Xe),me=tt==null?Te:pi(tt),Te=new nt(Fe,le+"leave",Xe,d,Me),Te.target=ss,Te.relatedTarget=me,Fe=null,sa(Me)===ye&&(nt=new nt(de,le+"enter",tt,d,Me),nt.target=me,nt.relatedTarget=ss,Fe=nt),ss=Fe,Xe&&tt)t:{for(nt=Xe,de=tt,le=0,me=nt;me;me=Mr(me))le++;for(me=0,Fe=de;Fe;Fe=Mr(Fe))me++;for(;0<le-me;)nt=Mr(nt),le--;for(;0<me-le;)de=Mr(de),me--;for(;le--;){if(nt===de||de!==null&&nt===de.alternate)break t;nt=Mr(nt),de=Mr(de)}nt=null}else nt=null;Xe!==null&&Nc(Re,Te,Xe,nt,!1),tt!==null&&ss!==null&&Nc(Re,ss,tt,nt,!0)}}e:{if(Te=ye?pi(ye):window,Xe=Te.nodeName&&Te.nodeName.toLowerCase(),Xe==="select"||Xe==="input"&&Te.type==="file")var rt=i_;else if(nd(Te))if(gc)rt=l_;else{rt=o_;var yt=id}else(Xe=Te.nodeName)&&Xe.toLowerCase()==="input"&&(Te.type==="checkbox"||Te.type==="radio")&&(rt=a_);if(rt&&(rt=rt(r,ye))){sd(Re,rt,d,Me);break e}yt&&yt(r,Te,ye),r==="focusout"&&(yt=Te._wrapperState)&&yt.controlled&&Te.type==="number"&&ct(Te,"number",Te.value)}switch(yt=ye?pi(ye):window,r){case"focusin":(nd(yt)||yt.contentEditable==="true")&&(xo=yt,xc=ye,Li=null);break;case"focusout":Li=xc=xo=null;break;case"mousedown":bc=!0;break;case"contextmenu":case"mouseup":case"dragend":bc=!1,Da(Re,d,Me);break;case"selectionchange":if(vc)break;case"keydown":case"keyup":Da(Re,d,Me)}var wt;if(Qn)e:{switch(r){case"compositionstart":var Nt="onCompositionStart";break e;case"compositionend":Nt="onCompositionEnd";break e;case"compositionupdate":Nt="onCompositionUpdate";break e}Nt=void 0}else go?Vf(r,d)&&(Nt="onCompositionEnd"):r==="keydown"&&d.keyCode===229&&(Nt="onCompositionStart");Nt&&(Hf&&d.locale!=="ko"&&(go||Nt!=="onCompositionStart"?Nt==="onCompositionEnd"&&go&&(wt=ft()):(Ne=Me,ke="value"in Ne?Ne.value:Ne.textContent,go=!0)),yt=ta(ye,Nt),0<yt.length&&(Nt=new qu(Nt,r,null,d,Me),Re.push({event:Nt,listeners:yt}),wt?Nt.data=wt:(wt=ed(d),wt!==null&&(Nt.data=wt)))),(wt=xl?td(r,d):Gf(r,d))&&(ye=ta(ye,"onBeforeInput"),0<ye.length&&(Me=new qu("onBeforeInput","beforeinput",null,d,Me),Re.push({event:Me,listeners:ye}),Me.data=wt))}fi(Re,a)})}function hi(r,a,d){return{instance:r,listener:a,currentTarget:d}}function ta(r,a){for(var d=a+"Capture",h=[];r!==null;){var v=r,b=v.stateNode;v.tag===5&&b!==null&&(v=b,b=Vt(r,d),b!=null&&h.unshift(hi(r,b,v)),b=Vt(r,a),b!=null&&h.push(hi(r,b,v))),r=r.return}return h}function Mr(r){if(r===null)return null;do r=r.return;while(r&&r.tag!==5);return r||null}function Nc(r,a,d,h,v){for(var b=a._reactName,R=[];d!==null&&d!==h;){var ee=d,se=ee.alternate,ye=ee.stateNode;if(se!==null&&se===h)break;ee.tag===5&&ye!==null&&(ee=ye,v?(se=Vt(d,b),se!=null&&R.unshift(hi(d,se,ee))):v||(se=Vt(d,b),se!=null&&R.push(hi(d,se,ee)))),d=d.return}R.length!==0&&r.push({event:a,listeners:R})}var Cc=/\r\n?/g,mi=/\u0000|\uFFFD/g;function Pi(r){return(typeof r=="string"?r:""+r).replace(Cc,`
|
|
38
|
+
`).replace(mi,"")}function vr(r,a,d){if(a=Pi(a),Pi(r)!==a&&d)throw Error(n(425))}function Cl(){}var El=null,ad=null;function Ba(r,a){return r==="textarea"||r==="noscript"||typeof a.children=="string"||typeof a.children=="number"||typeof a.dangerouslySetInnerHTML=="object"&&a.dangerouslySetInnerHTML!==null&&a.dangerouslySetInnerHTML.__html!=null}var Ec=typeof setTimeout=="function"?setTimeout:void 0,$l=typeof clearTimeout=="function"?clearTimeout:void 0,ld=typeof Promise=="function"?Promise:void 0,cd=typeof queueMicrotask=="function"?queueMicrotask:typeof ld<"u"?function(r){return ld.resolve(null).then(r).catch(th)}:Ec;function th(r){setTimeout(function(){throw r})}function $c(r,a){var d=a,h=0;do{var v=d.nextSibling;if(r.removeChild(d),v&&v.nodeType===8)if(d=v.data,d==="/$"){if(h===0){r.removeChild(v),_o(a);return}h--}else d!=="$"&&d!=="$?"&&d!=="$!"||h++;d=v}while(d);_o(a)}function Di(r){for(;r!=null;r=r.nextSibling){var a=r.nodeType;if(a===1||a===3)break;if(a===8){if(a=r.data,a==="$"||a==="$!"||a==="$?")break;if(a==="/$")return null}}return r}function nh(r){r=r.previousSibling;for(var a=0;r;){if(r.nodeType===8){var d=r.data;if(d==="$"||d==="$!"||d==="$?"){if(a===0)return r;a--}else d==="/$"&&a++}r=r.previousSibling}return null}var na=Math.random().toString(36).slice(2),_i="__reactFiber$"+na,Ua="__reactProps$"+na,Fi="__reactContainer$"+na,Ac="__reactEvents$"+na,c_="__reactListeners$"+na,sh="__reactHandles$"+na;function sa(r){var a=r[_i];if(a)return a;for(var d=r.parentNode;d;){if(a=d[Fi]||d[_i]){if(d=a.alternate,a.child!==null||d!==null&&d.child!==null)for(r=nh(r);r!==null;){if(d=r[_i])return d;r=nh(r)}return a}r=d,d=r.parentNode}return null}function Wa(r){return r=r[_i]||r[Fi],!r||r.tag!==5&&r.tag!==6&&r.tag!==13&&r.tag!==3?null:r}function pi(r){if(r.tag===5||r.tag===6)return r.stateNode;throw Error(n(33))}function Tc(r){return r[Ua]||null}var ra=[],jo=-1;function ei(r){return{current:r}}function Sn(r){0>jo||(r.current=ra[jo],ra[jo]=null,jo--)}function ln(r,a){jo++,ra[jo]=r.current,r.current=a}var So={},es=ei(So),rr=ei(!1),Rr=So;function qa(r,a){var d=r.type.contextTypes;if(!d)return So;var h=r.stateNode;if(h&&h.__reactInternalMemoizedUnmaskedChildContext===a)return h.__reactInternalMemoizedMaskedChildContext;var v={},b;for(b in d)v[b]=a[b];return h&&(r=r.stateNode,r.__reactInternalMemoizedUnmaskedChildContext=a,r.__reactInternalMemoizedMaskedChildContext=v),v}function ys(r){return r=r.childContextTypes,r!=null}function Mc(){Sn(rr),Sn(es)}function zi(r,a,d){if(es.current!==So)throw Error(n(168));ln(es,a),ln(rr,d)}function ud(r,a,d){var h=r.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,_e(r)||"Unknown",v));return G({},d,h)}function ko(r){return r=(r=r.stateNode)&&r.__reactInternalMemoizedMergedChildContext||So,Rr=es.current,ln(es,r),ln(rr,rr.current),!0}function Ha(r,a,d){var h=r.stateNode;if(!h)throw Error(n(169));d?(r=ud(r,a,Rr),h.__reactInternalMemoizedMergedChildContext=r,Sn(rr),Sn(es),ln(es,r)):Sn(rr),ln(rr,d)}var gi=null,Va=!1,ia=!1;function Rc(r){gi===null?gi=[r]:gi.push(r)}function Ga(r){Va=!0,Rc(r)}function yi(){if(!ia&&gi!==null){ia=!0;var r=0,a=rn;try{var d=gi;for(rn=1;r<d.length;r++){var h=d[r];do h=h(!0);while(h!==null)}gi=null,Va=!1}catch(v){throw gi!==null&&(gi=gi.slice(r+1)),Xs(Ei,yi),v}finally{rn=a,ia=!1}}return null}var Ka=[],No=0,Al=null,Lc=0,Lr=[],ws=0,qn=null,Ir=1,ti="";function oa(r,a){Ka[No++]=Lc,Ka[No++]=Al,Al=r,Lc=a}function rh(r,a,d){Lr[ws++]=Ir,Lr[ws++]=ti,Lr[ws++]=qn,qn=r;var h=Ir;r=ti;var v=32-as(h)-1;h&=~(1<<v),d+=1;var b=32-as(a)+v;if(30<b){var R=v-v%5;b=(h&(1<<R)-1).toString(32),h>>=R,v-=R,Ir=1<<32-as(a)+v|d<<v|h,ti=b+r}else Ir=1<<b|d<<v|h,ti=r}function Tl(r){r.return!==null&&(oa(r,1),rh(r,1,0))}function dd(r){for(;r===Al;)Al=Ka[--No],Ka[No]=null,Lc=Ka[--No],Ka[No]=null;for(;r===qn;)qn=Lr[--ws],Lr[ws]=null,ti=Lr[--ws],Lr[ws]=null,Ir=Lr[--ws],Lr[ws]=null}var As=null,ir=null,wn=!1,Or=null;function fd(r,a){var d=Qt(5,null,null,0);d.elementType="DELETED",d.stateNode=a,d.return=r,a=r.deletions,a===null?(r.deletions=[d],r.flags|=16):a.push(d)}function ih(r,a){switch(r.tag){case 5:var d=r.type;return a=a.nodeType!==1||d.toLowerCase()!==a.nodeName.toLowerCase()?null:a,a!==null?(r.stateNode=a,As=r,ir=Di(a.firstChild),!0):!1;case 6:return a=r.pendingProps===""||a.nodeType!==3?null:a,a!==null?(r.stateNode=a,As=r,ir=null,!0):!1;case 13:return a=a.nodeType!==8?null:a,a!==null?(d=qn!==null?{id:Ir,overflow:ti}:null,r.memoizedState={dehydrated:a,treeContext:d,retryLane:1073741824},d=Qt(18,null,null,0),d.stateNode=a,d.return=r,r.child=d,As=r,ir=null,!0):!1;default:return!1}}function Ic(r){return(r.mode&1)!==0&&(r.flags&128)===0}function Oc(r){if(wn){var a=ir;if(a){var d=a;if(!ih(r,a)){if(Ic(r))throw Error(n(418));a=Di(d.nextSibling);var h=As;a&&ih(r,a)?fd(h,d):(r.flags=r.flags&-4097|2,wn=!1,As=r)}}else{if(Ic(r))throw Error(n(418));r.flags=r.flags&-4097|2,wn=!1,As=r}}}function hd(r){for(r=r.return;r!==null&&r.tag!==5&&r.tag!==3&&r.tag!==13;)r=r.return;As=r}function Pc(r){if(r!==As)return!1;if(!wn)return hd(r),wn=!0,!1;var a;if((a=r.tag!==3)&&!(a=r.tag!==5)&&(a=r.type,a=a!=="head"&&a!=="body"&&!Ba(r.type,r.memoizedProps)),a&&(a=ir)){if(Ic(r))throw md(),Error(n(418));for(;a;)fd(r,a),a=Di(a.nextSibling)}if(hd(r),r.tag===13){if(r=r.memoizedState,r=r!==null?r.dehydrated:null,!r)throw Error(n(317));e:{for(r=r.nextSibling,a=0;r;){if(r.nodeType===8){var d=r.data;if(d==="/$"){if(a===0){ir=Di(r.nextSibling);break e}a--}else d!=="$"&&d!=="$!"&&d!=="$?"||a++}r=r.nextSibling}ir=null}}else ir=As?Di(r.stateNode.nextSibling):null;return!0}function md(){for(var r=ir;r;)r=Di(r.nextSibling)}function Bi(){ir=As=null,wn=!1}function _d(r){Or===null?Or=[r]:Or.push(r)}var u_=M.ReactCurrentBatchConfig;function Ml(r,a,d){if(r=d.ref,r!==null&&typeof r!="function"&&typeof r!="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,r));var v=h,b=""+r;return a!==null&&a.ref!==null&&typeof a.ref=="function"&&a.ref._stringRef===b?a.ref:(a=function(R){var ee=v.refs;R===null?delete ee[b]:ee[b]=R},a._stringRef=b,a)}if(typeof r!="string")throw Error(n(284));if(!d._owner)throw Error(n(290,r))}return r}function Dc(r,a){throw r=Object.prototype.toString.call(a),Error(n(31,r==="[object Object]"?"object with keys {"+Object.keys(a).join(", ")+"}":r))}function Fc(r){var a=r._init;return a(r._payload)}function oh(r){function a(de,le){if(r){var me=de.deletions;me===null?(de.deletions=[le],de.flags|=16):me.push(le)}}function d(de,le){if(!r)return null;for(;le!==null;)a(de,le),le=le.sibling;return null}function h(de,le){for(de=new Map;le!==null;)le.key!==null?de.set(le.key,le):de.set(le.index,le),le=le.sibling;return de}function v(de,le){return de=fs(de,le),de.index=0,de.sibling=null,de}function b(de,le,me){return de.index=me,r?(me=de.alternate,me!==null?(me=me.index,me<le?(de.flags|=2,le):me):(de.flags|=2,le)):(de.flags|=1048576,le)}function R(de){return r&&de.alternate===null&&(de.flags|=2),de}function ee(de,le,me,Fe){return le===null||le.tag!==6?(le=p_(me,de.mode,Fe),le.return=de,le):(le=v(le,me),le.return=de,le)}function se(de,le,me,Fe){var rt=me.type;return rt===Y?Me(de,le,me.props.children,Fe,me.key):le!==null&&(le.elementType===rt||typeof rt=="object"&&rt!==null&&rt.$$typeof===D&&Fc(rt)===le.type)?(Fe=v(le,me.props),Fe.ref=Ml(de,le,me),Fe.return=de,Fe):(Fe=Fo(me.type,me.key,me.props,null,de.mode,Fe),Fe.ref=Ml(de,le,me),Fe.return=de,Fe)}function ye(de,le,me,Fe){return le===null||le.tag!==4||le.stateNode.containerInfo!==me.containerInfo||le.stateNode.implementation!==me.implementation?(le=g_(me,de.mode,Fe),le.return=de,le):(le=v(le,me.children||[]),le.return=de,le)}function Me(de,le,me,Fe,rt){return le===null||le.tag!==7?(le=Hl(me,de.mode,Fe,rt),le.return=de,le):(le=v(le,me),le.return=de,le)}function Re(de,le,me){if(typeof le=="string"&&le!==""||typeof le=="number")return le=p_(""+le,de.mode,me),le.return=de,le;if(typeof le=="object"&&le!==null){switch(le.$$typeof){case H:return me=Fo(le.type,le.key,le.props,null,de.mode,me),me.ref=Ml(de,null,le),me.return=de,me;case X:return le=g_(le,de.mode,me),le.return=de,le;case D:var Fe=le._init;return Re(de,Fe(le._payload),me)}if(ge(le)||z(le))return le=Hl(le,de.mode,me,null),le.return=de,le;Dc(de,le)}return null}function Te(de,le,me,Fe){var rt=le!==null?le.key:null;if(typeof me=="string"&&me!==""||typeof me=="number")return rt!==null?null:ee(de,le,""+me,Fe);if(typeof me=="object"&&me!==null){switch(me.$$typeof){case H:return me.key===rt?se(de,le,me,Fe):null;case X:return me.key===rt?ye(de,le,me,Fe):null;case D:return rt=me._init,Te(de,le,rt(me._payload),Fe)}if(ge(me)||z(me))return rt!==null?null:Me(de,le,me,Fe,null);Dc(de,me)}return null}function Xe(de,le,me,Fe,rt){if(typeof Fe=="string"&&Fe!==""||typeof Fe=="number")return de=de.get(me)||null,ee(le,de,""+Fe,rt);if(typeof Fe=="object"&&Fe!==null){switch(Fe.$$typeof){case H:return de=de.get(Fe.key===null?me:Fe.key)||null,se(le,de,Fe,rt);case X:return de=de.get(Fe.key===null?me:Fe.key)||null,ye(le,de,Fe,rt);case D:var yt=Fe._init;return Xe(de,le,me,yt(Fe._payload),rt)}if(ge(Fe)||z(Fe))return de=de.get(me)||null,Me(le,de,Fe,rt,null);Dc(le,Fe)}return null}function tt(de,le,me,Fe){for(var rt=null,yt=null,wt=le,Nt=le=0,Fs=null;wt!==null&&Nt<me.length;Nt++){wt.index>Nt?(Fs=wt,wt=null):Fs=wt.sibling;var fn=Te(de,wt,me[Nt],Fe);if(fn===null){wt===null&&(wt=Fs);break}r&&wt&&fn.alternate===null&&a(de,wt),le=b(fn,le,Nt),yt===null?rt=fn:yt.sibling=fn,yt=fn,wt=Fs}if(Nt===me.length)return d(de,wt),wn&&oa(de,Nt),rt;if(wt===null){for(;Nt<me.length;Nt++)wt=Re(de,me[Nt],Fe),wt!==null&&(le=b(wt,le,Nt),yt===null?rt=wt:yt.sibling=wt,yt=wt);return wn&&oa(de,Nt),rt}for(wt=h(de,wt);Nt<me.length;Nt++)Fs=Xe(wt,de,Nt,me[Nt],Fe),Fs!==null&&(r&&Fs.alternate!==null&&wt.delete(Fs.key===null?Nt:Fs.key),le=b(Fs,le,Nt),yt===null?rt=Fs:yt.sibling=Fs,yt=Fs);return r&&wt.forEach(function(sl){return a(de,sl)}),wn&&oa(de,Nt),rt}function nt(de,le,me,Fe){var rt=z(me);if(typeof rt!="function")throw Error(n(150));if(me=rt.call(me),me==null)throw Error(n(151));for(var yt=rt=null,wt=le,Nt=le=0,Fs=null,fn=me.next();wt!==null&&!fn.done;Nt++,fn=me.next()){wt.index>Nt?(Fs=wt,wt=null):Fs=wt.sibling;var sl=Te(de,wt,fn.value,Fe);if(sl===null){wt===null&&(wt=Fs);break}r&&wt&&sl.alternate===null&&a(de,wt),le=b(sl,le,Nt),yt===null?rt=sl:yt.sibling=sl,yt=sl,wt=Fs}if(fn.done)return d(de,wt),wn&&oa(de,Nt),rt;if(wt===null){for(;!fn.done;Nt++,fn=me.next())fn=Re(de,fn.value,Fe),fn!==null&&(le=b(fn,le,Nt),yt===null?rt=fn:yt.sibling=fn,yt=fn);return wn&&oa(de,Nt),rt}for(wt=h(de,wt);!fn.done;Nt++,fn=me.next())fn=Xe(wt,de,Nt,fn.value,Fe),fn!==null&&(r&&fn.alternate!==null&&wt.delete(fn.key===null?Nt:fn.key),le=b(fn,le,Nt),yt===null?rt=fn:yt.sibling=fn,yt=fn);return r&&wt.forEach(function(O0){return a(de,O0)}),wn&&oa(de,Nt),rt}function ss(de,le,me,Fe){if(typeof me=="object"&&me!==null&&me.type===Y&&me.key===null&&(me=me.props.children),typeof me=="object"&&me!==null){switch(me.$$typeof){case H:e:{for(var rt=me.key,yt=le;yt!==null;){if(yt.key===rt){if(rt=me.type,rt===Y){if(yt.tag===7){d(de,yt.sibling),le=v(yt,me.props.children),le.return=de,de=le;break e}}else if(yt.elementType===rt||typeof rt=="object"&&rt!==null&&rt.$$typeof===D&&Fc(rt)===yt.type){d(de,yt.sibling),le=v(yt,me.props),le.ref=Ml(de,yt,me),le.return=de,de=le;break e}d(de,yt);break}else a(de,yt);yt=yt.sibling}me.type===Y?(le=Hl(me.props.children,de.mode,Fe,me.key),le.return=de,de=le):(Fe=Fo(me.type,me.key,me.props,null,de.mode,Fe),Fe.ref=Ml(de,le,me),Fe.return=de,de=Fe)}return R(de);case X:e:{for(yt=me.key;le!==null;){if(le.key===yt)if(le.tag===4&&le.stateNode.containerInfo===me.containerInfo&&le.stateNode.implementation===me.implementation){d(de,le.sibling),le=v(le,me.children||[]),le.return=de,de=le;break e}else{d(de,le);break}else a(de,le);le=le.sibling}le=g_(me,de.mode,Fe),le.return=de,de=le}return R(de);case D:return yt=me._init,ss(de,le,yt(me._payload),Fe)}if(ge(me))return tt(de,le,me,Fe);if(z(me))return nt(de,le,me,Fe);Dc(de,me)}return typeof me=="string"&&me!==""||typeof me=="number"?(me=""+me,le!==null&&le.tag===6?(d(de,le.sibling),le=v(le,me),le.return=de,de=le):(d(de,le),le=p_(me,de.mode,Fe),le.return=de,de=le),R(de)):d(de,le)}return ss}var Co=oh(!0),ah=oh(!1),Rl=ei(null),zc=null,Eo=null,Oe=null;function Bn(){Oe=Eo=zc=null}function Ll(r){var a=Rl.current;Sn(Rl),r._currentValue=a}function Bc(r,a,d){for(;r!==null;){var h=r.alternate;if((r.childLanes&a)!==a?(r.childLanes|=a,h!==null&&(h.childLanes|=a)):h!==null&&(h.childLanes&a)!==a&&(h.childLanes|=a),r===d)break;r=r.return}}function $o(r,a){zc=r,Oe=Eo=null,r=r.dependencies,r!==null&&r.firstContext!==null&&((r.lanes&a)!==0&&(lr=!0),r.firstContext=null)}function Pr(r){var a=r._currentValue;if(Oe!==r)if(r={context:r,memoizedValue:a,next:null},Eo===null){if(zc===null)throw Error(n(308));Eo=r,zc.dependencies={lanes:0,firstContext:r}}else Eo=Eo.next=r;return a}var aa=null;function pd(r){aa===null?aa=[r]:aa.push(r)}function gd(r,a,d,h){var v=a.interleaved;return v===null?(d.next=d,pd(a)):(d.next=v.next,v.next=d),a.interleaved=d,wi(r,h)}function wi(r,a){r.lanes|=a;var d=r.alternate;for(d!==null&&(d.lanes|=a),d=r,r=r.return;r!==null;)r.childLanes|=a,d=r.alternate,d!==null&&(d.childLanes|=a),d=r,r=r.return;return d.tag===3?d.stateNode:null}var Ao=!1;function Ya(r){r.updateQueue={baseState:r.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function Ts(r,a){r=r.updateQueue,a.updateQueue===r&&(a.updateQueue={baseState:r.baseState,firstBaseUpdate:r.firstBaseUpdate,lastBaseUpdate:r.lastBaseUpdate,shared:r.shared,effects:r.effects})}function zt(r,a){return{eventTime:r,lane:a,tag:0,payload:null,callback:null,next:null}}function In(r,a,d){var h=r.updateQueue;if(h===null)return null;if(h=h.shared,(Zt&2)!==0){var v=h.pending;return v===null?a.next=a:(a.next=v.next,v.next=a),h.pending=a,wi(r,d)}return v=h.interleaved,v===null?(a.next=a,pd(h)):(a.next=v.next,v.next=a),h.interleaved=a,wi(r,d)}function Ja(r,a,d){if(a=a.updateQueue,a!==null&&(a=a.shared,(d&4194240)!==0)){var h=a.lanes;h&=r.pendingLanes,d|=h,a.lanes=d,mo(r,d)}}function yd(r,a){var d=r.updateQueue,h=r.alternate;if(h!==null&&(h=h.updateQueue,d===h)){var v=null,b=null;if(d=d.firstBaseUpdate,d!==null){do{var R={eventTime:d.eventTime,lane:d.lane,tag:d.tag,payload:d.payload,callback:d.callback,next:null};b===null?v=b=R:b=b.next=R,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},r.updateQueue=d;return}r=d.lastBaseUpdate,r===null?d.firstBaseUpdate=a:r.next=a,d.lastBaseUpdate=a}function To(r,a,d,h){var v=r.updateQueue;Ao=!1;var b=v.firstBaseUpdate,R=v.lastBaseUpdate,ee=v.shared.pending;if(ee!==null){v.shared.pending=null;var se=ee,ye=se.next;se.next=null,R===null?b=ye:R.next=ye,R=se;var Me=r.alternate;Me!==null&&(Me=Me.updateQueue,ee=Me.lastBaseUpdate,ee!==R&&(ee===null?Me.firstBaseUpdate=ye:ee.next=ye,Me.lastBaseUpdate=se))}if(b!==null){var Re=v.baseState;R=0,Me=ye=se=null,ee=b;do{var Te=ee.lane,Xe=ee.eventTime;if((h&Te)===Te){Me!==null&&(Me=Me.next={eventTime:Xe,lane:0,tag:ee.tag,payload:ee.payload,callback:ee.callback,next:null});e:{var tt=r,nt=ee;switch(Te=a,Xe=d,nt.tag){case 1:if(tt=nt.payload,typeof tt=="function"){Re=tt.call(Xe,Re,Te);break e}Re=tt;break e;case 3:tt.flags=tt.flags&-65537|128;case 0:if(tt=nt.payload,Te=typeof tt=="function"?tt.call(Xe,Re,Te):tt,Te==null)break e;Re=G({},Re,Te);break e;case 2:Ao=!0}}ee.callback!==null&&ee.lane!==0&&(r.flags|=64,Te=v.effects,Te===null?v.effects=[ee]:Te.push(ee))}else Xe={eventTime:Xe,lane:Te,tag:ee.tag,payload:ee.payload,callback:ee.callback,next:null},Me===null?(ye=Me=Xe,se=Re):Me=Me.next=Xe,R|=Te;if(ee=ee.next,ee===null){if(ee=v.shared.pending,ee===null)break;Te=ee,ee=Te.next,Te.next=null,v.lastBaseUpdate=Te,v.shared.pending=null}}while(!0);if(Me===null&&(se=Re),v.baseState=se,v.firstBaseUpdate=ye,v.lastBaseUpdate=Me,a=v.shared.interleaved,a!==null){v=a;do R|=v.lane,v=v.next;while(v!==a)}else b===null&&(v.shared.lanes=0);ga|=R,r.lanes=R,r.memoizedState=Re}}function wd(r,a,d){if(r=a.effects,a.effects=null,r!==null)for(a=0;a<r.length;a++){var h=r[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 it={},vi=ei(it),la=ei(it),Il=ei(it);function ca(r){if(r===it)throw Error(n(174));return r}function Uc(r,a){switch(ln(Il,a),ln(la,r),ln(vi,it),r=a.nodeType,r){case 9:case 11:a=(a=a.documentElement)?a.namespaceURI:It(null,"");break;default:r=r===8?a.parentNode:a,a=r.namespaceURI||null,r=r.tagName,a=It(a,r)}Sn(vi),ln(vi,a)}function Xa(){Sn(vi),Sn(la),Sn(Il)}function lh(r){ca(Il.current);var a=ca(vi.current),d=It(a,r.type);a!==d&&(ln(la,r),ln(vi,d))}function vd(r){la.current===r&&(Sn(vi),Sn(la))}var $n=ei(0);function Ui(r){for(var a=r;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===r)break;for(;a.sibling===null;){if(a.return===null||a.return===r)return null;a=a.return}a.sibling.return=a.return,a=a.sibling}return null}var xd=[];function Dr(){for(var r=0;r<xd.length;r++)xd[r]._workInProgressVersionPrimary=null;xd.length=0}var or=M.ReactCurrentDispatcher,Wc=M.ReactCurrentBatchConfig,ua=0,On=null,ts=null,ns=null,Za=!1,Ol=!1,vn=0,ch=0;function cs(){throw Error(n(321))}function Ms(r,a){if(a===null)return!1;for(var d=0;d<a.length&&d<r.length;d++)if(!Ar(r[d],a[d]))return!1;return!0}function qc(r,a,d,h,v,b){if(ua=b,On=a,a.memoizedState=null,a.updateQueue=null,a.lanes=0,or.current=r===null||r.memoizedState===null?h_:gh,r=d(h,v),Ol){b=0;do{if(Ol=!1,vn=0,25<=b)throw Error(n(301));b+=1,ns=ts=null,a.updateQueue=null,or.current=yh,r=d(h,v)}while(Ol)}if(or.current=Xc,a=ts!==null&&ts.next!==null,ua=0,ns=ts=On=null,Za=!1,a)throw Error(n(300));return r}function da(){var r=vn!==0;return vn=0,r}function Fr(){var r={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return ns===null?On.memoizedState=ns=r:ns=ns.next=r,ns}function Rs(){if(ts===null){var r=On.alternate;r=r!==null?r.memoizedState:null}else r=ts.next;var a=ns===null?On.memoizedState:ns.next;if(a!==null)ns=a,ts=r;else{if(r===null)throw Error(n(310));ts=r,r={memoizedState:ts.memoizedState,baseState:ts.baseState,baseQueue:ts.baseQueue,queue:ts.queue,next:null},ns===null?On.memoizedState=ns=r:ns=ns.next=r}return ns}function fa(r,a){return typeof a=="function"?a(r):a}function bd(r){var a=Rs(),d=a.queue;if(d===null)throw Error(n(311));d.lastRenderedReducer=r;var h=ts,v=h.baseQueue,b=d.pending;if(b!==null){if(v!==null){var R=v.next;v.next=b.next,b.next=R}h.baseQueue=v=b,d.pending=null}if(v!==null){b=v.next,h=h.baseState;var ee=R=null,se=null,ye=b;do{var Me=ye.lane;if((ua&Me)===Me)se!==null&&(se=se.next={lane:0,action:ye.action,hasEagerState:ye.hasEagerState,eagerState:ye.eagerState,next:null}),h=ye.hasEagerState?ye.eagerState:r(h,ye.action);else{var Re={lane:Me,action:ye.action,hasEagerState:ye.hasEagerState,eagerState:ye.eagerState,next:null};se===null?(ee=se=Re,R=h):se=se.next=Re,On.lanes|=Me,ga|=Me}ye=ye.next}while(ye!==null&&ye!==b);se===null?R=h:se.next=ee,Ar(h,a.memoizedState)||(lr=!0),a.memoizedState=h,a.baseState=R,a.baseQueue=se,d.lastRenderedState=h}if(r=d.interleaved,r!==null){v=r;do b=v.lane,On.lanes|=b,ga|=b,v=v.next;while(v!==r)}else v===null&&(d.lanes=0);return[a.memoizedState,d.dispatch]}function jd(r){var a=Rs(),d=a.queue;if(d===null)throw Error(n(311));d.lastRenderedReducer=r;var h=d.dispatch,v=d.pending,b=a.memoizedState;if(v!==null){d.pending=null;var R=v=v.next;do b=r(b,R.action),R=R.next;while(R!==v);Ar(b,a.memoizedState)||(lr=!0),a.memoizedState=b,a.baseQueue===null&&(a.baseState=b),d.lastRenderedState=b}return[b,h]}function uh(){}function Hc(r,a){var d=On,h=Rs(),v=a(),b=!Ar(h.memoizedState,v);if(b&&(h.memoizedState=v,lr=!0),h=h.queue,kd(Gc.bind(null,d,h,r),[r]),h.getSnapshot!==a||b||ns!==null&&ns.memoizedState.tag&1){if(d.flags|=2048,Mn(9,dh.bind(null,d,h,v,a),void 0,null),Un===null)throw Error(n(349));(ua&30)!==0||Vc(d,a,v)}return v}function Vc(r,a,d){r.flags|=16384,r={getSnapshot:a,value:d},a=On.updateQueue,a===null?(a={lastEffect:null,stores:null},On.updateQueue=a,a.stores=[r]):(d=a.stores,d===null?a.stores=[r]:d.push(r))}function dh(r,a,d,h){a.value=d,a.getSnapshot=h,fh(a)&&zr(r)}function Gc(r,a,d){return d(function(){fh(a)&&zr(r)})}function fh(r){var a=r.getSnapshot;r=r.value;try{var d=a();return!Ar(r,d)}catch{return!0}}function zr(r){var a=wi(r,1);a!==null&&qr(a,r,1,-1)}function ha(r){var a=Fr();return typeof r=="function"&&(r=r()),a.memoizedState=a.baseState=r,r={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:fa,lastRenderedState:r},a.queue=r,r=r.dispatch=f_.bind(null,On,r),[a.memoizedState,r]}function Mn(r,a,d,h){return r={tag:r,create:a,destroy:d,deps:h,next:null},a=On.updateQueue,a===null?(a={lastEffect:null,stores:null},On.updateQueue=a,a.lastEffect=r.next=r):(d=a.lastEffect,d===null?a.lastEffect=r.next=r:(h=d.next,d.next=r,r.next=h,a.lastEffect=r)),r}function Sd(){return Rs().memoizedState}function Pl(r,a,d,h){var v=Fr();On.flags|=r,v.memoizedState=Mn(1|a,d,void 0,h===void 0?null:h)}function Kc(r,a,d,h){var v=Rs();h=h===void 0?null:h;var b=void 0;if(ts!==null){var R=ts.memoizedState;if(b=R.destroy,h!==null&&Ms(h,R.deps)){v.memoizedState=Mn(a,d,b,h);return}}On.flags|=r,v.memoizedState=Mn(1|a,d,b,h)}function hh(r,a){return Pl(8390656,8,r,a)}function kd(r,a){return Kc(2048,8,r,a)}function Nd(r,a){return Kc(4,2,r,a)}function Cd(r,a){return Kc(4,4,r,a)}function mh(r,a){if(typeof a=="function")return r=r(),a(r),function(){a(null)};if(a!=null)return r=r(),a.current=r,function(){a.current=null}}function _h(r,a,d){return d=d!=null?d.concat([r]):null,Kc(4,4,mh.bind(null,a,r),d)}function Kt(){}function Pn(r,a){var d=Rs();a=a===void 0?null:a;var h=d.memoizedState;return h!==null&&a!==null&&Ms(a,h[1])?h[0]:(d.memoizedState=[r,a],r)}function ar(r,a){var d=Rs();a=a===void 0?null:a;var h=d.memoizedState;return h!==null&&a!==null&&Ms(a,h[1])?h[0]:(r=r(),d.memoizedState=[r,a],r)}function Yc(r,a,d){return(ua&21)===0?(r.baseState&&(r.baseState=!1,lr=!0),r.memoizedState=d):(Ar(d,a)||(d=ls(),On.lanes|=d,ga|=d,r.baseState=!0),a)}function Jc(r,a){var d=rn;rn=d!==0&&4>d?d:4,r(!0);var h=Wc.transition;Wc.transition={};try{r(!1),a()}finally{rn=d,Wc.transition=h}}function Ed(){return Rs().memoizedState}function d_(r,a,d){var h=Zi(r);if(d={lane:h,action:d,hasEagerState:!1,eagerState:null,next:null},$d(r))Qa(a,d);else if(d=gd(r,a,d,h),d!==null){var v=Ps();qr(d,r,h,v),ph(d,a,h)}}function f_(r,a,d){var h=Zi(r),v={lane:h,action:d,hasEagerState:!1,eagerState:null,next:null};if($d(r))Qa(a,v);else{var b=r.alternate;if(r.lanes===0&&(b===null||b.lanes===0)&&(b=a.lastRenderedReducer,b!==null))try{var R=a.lastRenderedState,ee=b(R,d);if(v.hasEagerState=!0,v.eagerState=ee,Ar(ee,R)){var se=a.interleaved;se===null?(v.next=v,pd(a)):(v.next=se.next,se.next=v),a.interleaved=v;return}}catch{}finally{}d=gd(r,a,v,h),d!==null&&(v=Ps(),qr(d,r,h,v),ph(d,a,h))}}function $d(r){var a=r.alternate;return r===On||a!==null&&a===On}function Qa(r,a){Ol=Za=!0;var d=r.pending;d===null?a.next=a:(a.next=d.next,d.next=a),r.pending=a}function ph(r,a,d){if((d&4194240)!==0){var h=a.lanes;h&=r.pendingLanes,d|=h,a.lanes=d,mo(r,d)}}var Xc={readContext:Pr,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},h_={readContext:Pr,useCallback:function(r,a){return Fr().memoizedState=[r,a===void 0?null:a],r},useContext:Pr,useEffect:hh,useImperativeHandle:function(r,a,d){return d=d!=null?d.concat([r]):null,Pl(4194308,4,mh.bind(null,a,r),d)},useLayoutEffect:function(r,a){return Pl(4194308,4,r,a)},useInsertionEffect:function(r,a){return Pl(4,2,r,a)},useMemo:function(r,a){var d=Fr();return a=a===void 0?null:a,r=r(),d.memoizedState=[r,a],r},useReducer:function(r,a,d){var h=Fr();return a=d!==void 0?d(a):a,h.memoizedState=h.baseState=a,r={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:r,lastRenderedState:a},h.queue=r,r=r.dispatch=d_.bind(null,On,r),[h.memoizedState,r]},useRef:function(r){var a=Fr();return r={current:r},a.memoizedState=r},useState:ha,useDebugValue:Kt,useDeferredValue:function(r){return Fr().memoizedState=r},useTransition:function(){var r=ha(!1),a=r[0];return r=Jc.bind(null,r[1]),Fr().memoizedState=r,[a,r]},useMutableSource:function(){},useSyncExternalStore:function(r,a,d){var h=On,v=Fr();if(wn){if(d===void 0)throw Error(n(407));d=d()}else{if(d=a(),Un===null)throw Error(n(349));(ua&30)!==0||Vc(h,a,d)}v.memoizedState=d;var b={value:d,getSnapshot:a};return v.queue=b,hh(Gc.bind(null,h,b,r),[r]),h.flags|=2048,Mn(9,dh.bind(null,h,b,d,a),void 0,null),d},useId:function(){var r=Fr(),a=Un.identifierPrefix;if(wn){var d=ti,h=Ir;d=(h&~(1<<32-as(h)-1)).toString(32)+d,a=":"+a+"R"+d,d=vn++,0<d&&(a+="H"+d.toString(32)),a+=":"}else d=ch++,a=":"+a+"r"+d.toString(32)+":";return r.memoizedState=a},unstable_isNewReconciler:!1},gh={readContext:Pr,useCallback:Pn,useContext:Pr,useEffect:kd,useImperativeHandle:_h,useInsertionEffect:Nd,useLayoutEffect:Cd,useMemo:ar,useReducer:bd,useRef:Sd,useState:function(){return bd(fa)},useDebugValue:Kt,useDeferredValue:function(r){var a=Rs();return Yc(a,ts.memoizedState,r)},useTransition:function(){var r=bd(fa)[0],a=Rs().memoizedState;return[r,a]},useMutableSource:uh,useSyncExternalStore:Hc,useId:Ed,unstable_isNewReconciler:!1},yh={readContext:Pr,useCallback:Pn,useContext:Pr,useEffect:kd,useImperativeHandle:_h,useInsertionEffect:Nd,useLayoutEffect:Cd,useMemo:ar,useReducer:jd,useRef:Sd,useState:function(){return jd(fa)},useDebugValue:Kt,useDeferredValue:function(r){var a=Rs();return ts===null?a.memoizedState=r:Yc(a,ts.memoizedState,r)},useTransition:function(){var r=jd(fa)[0],a=Rs().memoizedState;return[r,a]},useMutableSource:uh,useSyncExternalStore:Hc,useId:Ed,unstable_isNewReconciler:!1};function vs(r,a){if(r&&r.defaultProps){a=G({},a),r=r.defaultProps;for(var d in r)a[d]===void 0&&(a[d]=r[d]);return a}return a}function Zc(r,a,d,h){a=r.memoizedState,d=d(h,a),d=d==null?a:G({},a,d),r.memoizedState=d,r.lanes===0&&(r.updateQueue.baseState=d)}var Dl={isMounted:function(r){return(r=r._reactInternals)?$t(r)===r:!1},enqueueSetState:function(r,a,d){r=r._reactInternals;var h=Ps(),v=Zi(r),b=zt(h,v);b.payload=a,d!=null&&(b.callback=d),a=In(r,b,v),a!==null&&(qr(a,r,v,h),Ja(a,r,v))},enqueueReplaceState:function(r,a,d){r=r._reactInternals;var h=Ps(),v=Zi(r),b=zt(h,v);b.tag=1,b.payload=a,d!=null&&(b.callback=d),a=In(r,b,v),a!==null&&(qr(a,r,v,h),Ja(a,r,v))},enqueueForceUpdate:function(r,a){r=r._reactInternals;var d=Ps(),h=Zi(r),v=zt(d,h);v.tag=2,a!=null&&(v.callback=a),a=In(r,v,h),a!==null&&(qr(a,r,h,d),Ja(a,r,h))}};function Ad(r,a,d,h,v,b,R){return r=r.stateNode,typeof r.shouldComponentUpdate=="function"?r.shouldComponentUpdate(h,b,R):a.prototype&&a.prototype.isPureReactComponent?!wo(d,h)||!wo(v,b):!0}function Td(r,a,d){var h=!1,v=So,b=a.contextType;return typeof b=="object"&&b!==null?b=Pr(b):(v=ys(a)?Rr:es.current,h=a.contextTypes,b=(h=h!=null)?qa(r,v):So),a=new a(d,b),r.memoizedState=a.state!==null&&a.state!==void 0?a.state:null,a.updater=Dl,r.stateNode=a,a._reactInternals=r,h&&(r=r.stateNode,r.__reactInternalMemoizedUnmaskedChildContext=v,r.__reactInternalMemoizedMaskedChildContext=b),a}function wh(r,a,d,h){r=a.state,typeof a.componentWillReceiveProps=="function"&&a.componentWillReceiveProps(d,h),typeof a.UNSAFE_componentWillReceiveProps=="function"&&a.UNSAFE_componentWillReceiveProps(d,h),a.state!==r&&Dl.enqueueReplaceState(a,a.state,null)}function Md(r,a,d,h){var v=r.stateNode;v.props=d,v.state=r.memoizedState,v.refs={},Ya(r);var b=a.contextType;typeof b=="object"&&b!==null?v.context=Pr(b):(b=ys(a)?Rr:es.current,v.context=qa(r,b)),v.state=r.memoizedState,b=a.getDerivedStateFromProps,typeof b=="function"&&(Zc(r,a,b,d),v.state=r.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&&Dl.enqueueReplaceState(v,v.state,null),To(r,d,v,h),v.state=r.memoizedState),typeof v.componentDidMount=="function"&&(r.flags|=4194308)}function el(r,a){try{var d="",h=a;do d+=oe(h),h=h.return;while(h);var v=d}catch(b){v=`
|
|
39
|
+
Error generating stack: `+b.message+`
|
|
40
|
+
`+b.stack}return{value:r,source:a,stack:v,digest:null}}function Rd(r,a,d){return{value:r,source:null,stack:d??null,digest:a??null}}function Ld(r,a){try{console.error(a.value)}catch(d){setTimeout(function(){throw d})}}var m_=typeof WeakMap=="function"?WeakMap:Map;function vh(r,a,d){d=zt(-1,d),d.tag=3,d.payload={element:null};var h=a.value;return d.callback=function(){Lo||(Lo=!0,Xi=h),Ld(r,a)},d}function Id(r,a,d){d=zt(-1,d),d.tag=3;var h=r.type.getDerivedStateFromError;if(typeof h=="function"){var v=a.value;d.payload=function(){return h(v)},d.callback=function(){Ld(r,a)}}var b=r.stateNode;return b!==null&&typeof b.componentDidCatch=="function"&&(d.callback=function(){Ld(r,a),typeof h!="function"&&(Io===null?Io=new Set([this]):Io.add(this));var R=a.stack;this.componentDidCatch(a.value,{componentStack:R!==null?R:""})}),d}function Qc(r,a,d){var h=r.pingCache;if(h===null){h=r.pingCache=new m_;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),r=Ze.bind(null,r,a,d),a.then(r,r))}function xh(r){do{var a;if((a=r.tag===13)&&(a=r.memoizedState,a=a!==null?a.dehydrated!==null:!0),a)return r;r=r.return}while(r!==null);return null}function bh(r,a,d,h,v){return(r.mode&1)===0?(r===a?r.flags|=65536:(r.flags|=128,d.flags|=131072,d.flags&=-52805,d.tag===1&&(d.alternate===null?d.tag=17:(a=zt(-1,1),a.tag=2,In(d,a,1))),d.lanes|=1),r):(r.flags|=65536,r.lanes=v,r)}var eu=M.ReactCurrentOwner,lr=!1;function Hn(r,a,d,h){a.child=r===null?ah(a,null,d,h):Co(a,r.child,d,h)}function Ls(r,a,d,h,v){d=d.render;var b=a.ref;return $o(a,v),h=qc(r,a,d,h,b,v),d=da(),r!==null&&!lr?(a.updateQueue=r.updateQueue,a.flags&=-2053,r.lanes&=~v,Gi(r,a,v)):(wn&&d&&Tl(a),a.flags|=1,Hn(r,a,h,v),a.child)}function us(r,a,d,h,v){if(r===null){var b=d.type;return typeof b=="function"&&!Ds(b)&&b.defaultProps===void 0&&d.compare===null&&d.defaultProps===void 0?(a.tag=15,a.type=b,ni(r,a,b,h,v)):(r=Fo(d.type,null,h,a,a.mode,v),r.ref=a.ref,r.return=a,a.child=r)}if(b=r.child,(r.lanes&v)===0){var R=b.memoizedProps;if(d=d.compare,d=d!==null?d:wo,d(R,h)&&r.ref===a.ref)return Gi(r,a,v)}return a.flags|=1,r=fs(b,h),r.ref=a.ref,r.return=a,a.child=r}function ni(r,a,d,h,v){if(r!==null){var b=r.memoizedProps;if(wo(b,h)&&r.ref===a.ref)if(lr=!1,a.pendingProps=h=b,(r.lanes&v)!==0)(r.flags&131072)!==0&&(lr=!0);else return a.lanes=r.lanes,Gi(r,a,v)}return Br(r,a,d,h,v)}function Wi(r,a,d){var h=a.pendingProps,v=h.children,b=r!==null?r.memoizedState:null;if(h.mode==="hidden")if((a.mode&1)===0)a.memoizedState={baseLanes:0,cachePool:null,transitions:null},ln(pa,cr),cr|=d;else{if((d&1073741824)===0)return r=b!==null?b.baseLanes|d:d,a.lanes=a.childLanes=1073741824,a.memoizedState={baseLanes:r,cachePool:null,transitions:null},a.updateQueue=null,ln(pa,cr),cr|=r,null;a.memoizedState={baseLanes:0,cachePool:null,transitions:null},h=b!==null?b.baseLanes:d,ln(pa,cr),cr|=h}else b!==null?(h=b.baseLanes|d,a.memoizedState=null):h=d,ln(pa,cr),cr|=h;return Hn(r,a,v,d),a.child}function qi(r,a){var d=a.ref;(r===null&&d!==null||r!==null&&r.ref!==d)&&(a.flags|=512,a.flags|=2097152)}function Br(r,a,d,h,v){var b=ys(d)?Rr:es.current;return b=qa(a,b),$o(a,v),d=qc(r,a,d,h,b,v),h=da(),r!==null&&!lr?(a.updateQueue=r.updateQueue,a.flags&=-2053,r.lanes&=~v,Gi(r,a,v)):(wn&&h&&Tl(a),a.flags|=1,Hn(r,a,d,v),a.child)}function jh(r,a,d,h,v){if(ys(d)){var b=!0;ko(a)}else b=!1;if($o(a,v),a.stateNode===null)Vi(r,a),Td(a,d,h),Md(a,d,h,v),h=!0;else if(r===null){var R=a.stateNode,ee=a.memoizedProps;R.props=ee;var se=R.context,ye=d.contextType;typeof ye=="object"&&ye!==null?ye=Pr(ye):(ye=ys(d)?Rr:es.current,ye=qa(a,ye));var Me=d.getDerivedStateFromProps,Re=typeof Me=="function"||typeof R.getSnapshotBeforeUpdate=="function";Re||typeof R.UNSAFE_componentWillReceiveProps!="function"&&typeof R.componentWillReceiveProps!="function"||(ee!==h||se!==ye)&&wh(a,R,h,ye),Ao=!1;var Te=a.memoizedState;R.state=Te,To(a,h,R,v),se=a.memoizedState,ee!==h||Te!==se||rr.current||Ao?(typeof Me=="function"&&(Zc(a,d,Me,h),se=a.memoizedState),(ee=Ao||Ad(a,d,ee,h,Te,se,ye))?(Re||typeof R.UNSAFE_componentWillMount!="function"&&typeof R.componentWillMount!="function"||(typeof R.componentWillMount=="function"&&R.componentWillMount(),typeof R.UNSAFE_componentWillMount=="function"&&R.UNSAFE_componentWillMount()),typeof R.componentDidMount=="function"&&(a.flags|=4194308)):(typeof R.componentDidMount=="function"&&(a.flags|=4194308),a.memoizedProps=h,a.memoizedState=se),R.props=h,R.state=se,R.context=ye,h=ee):(typeof R.componentDidMount=="function"&&(a.flags|=4194308),h=!1)}else{R=a.stateNode,Ts(r,a),ee=a.memoizedProps,ye=a.type===a.elementType?ee:vs(a.type,ee),R.props=ye,Re=a.pendingProps,Te=R.context,se=d.contextType,typeof se=="object"&&se!==null?se=Pr(se):(se=ys(d)?Rr:es.current,se=qa(a,se));var Xe=d.getDerivedStateFromProps;(Me=typeof Xe=="function"||typeof R.getSnapshotBeforeUpdate=="function")||typeof R.UNSAFE_componentWillReceiveProps!="function"&&typeof R.componentWillReceiveProps!="function"||(ee!==Re||Te!==se)&&wh(a,R,h,se),Ao=!1,Te=a.memoizedState,R.state=Te,To(a,h,R,v);var tt=a.memoizedState;ee!==Re||Te!==tt||rr.current||Ao?(typeof Xe=="function"&&(Zc(a,d,Xe,h),tt=a.memoizedState),(ye=Ao||Ad(a,d,ye,h,Te,tt,se)||!1)?(Me||typeof R.UNSAFE_componentWillUpdate!="function"&&typeof R.componentWillUpdate!="function"||(typeof R.componentWillUpdate=="function"&&R.componentWillUpdate(h,tt,se),typeof R.UNSAFE_componentWillUpdate=="function"&&R.UNSAFE_componentWillUpdate(h,tt,se)),typeof R.componentDidUpdate=="function"&&(a.flags|=4),typeof R.getSnapshotBeforeUpdate=="function"&&(a.flags|=1024)):(typeof R.componentDidUpdate!="function"||ee===r.memoizedProps&&Te===r.memoizedState||(a.flags|=4),typeof R.getSnapshotBeforeUpdate!="function"||ee===r.memoizedProps&&Te===r.memoizedState||(a.flags|=1024),a.memoizedProps=h,a.memoizedState=tt),R.props=h,R.state=tt,R.context=se,h=ye):(typeof R.componentDidUpdate!="function"||ee===r.memoizedProps&&Te===r.memoizedState||(a.flags|=4),typeof R.getSnapshotBeforeUpdate!="function"||ee===r.memoizedProps&&Te===r.memoizedState||(a.flags|=1024),h=!1)}return tl(r,a,d,h,b,v)}function tl(r,a,d,h,v,b){qi(r,a);var R=(a.flags&128)!==0;if(!h&&!R)return v&&Ha(a,d,!1),Gi(r,a,b);h=a.stateNode,eu.current=a;var ee=R&&typeof d.getDerivedStateFromError!="function"?null:h.render();return a.flags|=1,r!==null&&R?(a.child=Co(a,r.child,null,b),a.child=Co(a,null,ee,b)):Hn(r,a,ee,b),a.memoizedState=h.state,v&&Ha(a,d,!0),a.child}function Sh(r){var a=r.stateNode;a.pendingContext?zi(r,a.pendingContext,a.pendingContext!==a.context):a.context&&zi(r,a.context,!1),Uc(r,a.containerInfo)}function tu(r,a,d,h,v){return Bi(),_d(v),a.flags|=256,Hn(r,a,d,h),a.child}var Od={dehydrated:null,treeContext:null,retryLane:0};function Pd(r){return{baseLanes:r,cachePool:null,transitions:null}}function Dd(r,a,d){var h=a.pendingProps,v=$n.current,b=!1,R=(a.flags&128)!==0,ee;if((ee=R)||(ee=r!==null&&r.memoizedState===null?!1:(v&2)!==0),ee?(b=!0,a.flags&=-129):(r===null||r.memoizedState!==null)&&(v|=1),ln($n,v&1),r===null)return Oc(a),r=a.memoizedState,r!==null&&(r=r.dehydrated,r!==null)?((a.mode&1)===0?a.lanes=1:r.data==="$!"?a.lanes=8:a.lanes=1073741824,null):(R=h.children,r=h.fallback,b?(h=a.mode,b=a.child,R={mode:"hidden",children:R},(h&1)===0&&b!==null?(b.childLanes=0,b.pendingProps=R):b=Mh(R,h,0,null),r=Hl(r,h,d,null),b.return=a,r.return=a,b.sibling=r,a.child=b,a.child.memoizedState=Pd(d),a.memoizedState=Od,r):Hi(a,R));if(v=r.memoizedState,v!==null&&(ee=v.dehydrated,ee!==null))return kh(r,a,R,h,ee,v,d);if(b){b=h.fallback,R=a.mode,v=r.child,ee=v.sibling;var se={mode:"hidden",children:h.children};return(R&1)===0&&a.child!==v?(h=a.child,h.childLanes=0,h.pendingProps=se,a.deletions=null):(h=fs(v,se),h.subtreeFlags=v.subtreeFlags&14680064),ee!==null?b=fs(ee,b):(b=Hl(b,R,d,null),b.flags|=2),b.return=a,h.return=a,h.sibling=b,a.child=h,h=b,b=a.child,R=r.child.memoizedState,R=R===null?Pd(d):{baseLanes:R.baseLanes|d,cachePool:null,transitions:R.transitions},b.memoizedState=R,b.childLanes=r.childLanes&~d,a.memoizedState=Od,h}return b=r.child,r=b.sibling,h=fs(b,{mode:"visible",children:h.children}),(a.mode&1)===0&&(h.lanes=d),h.return=a,h.sibling=null,r!==null&&(d=a.deletions,d===null?(a.deletions=[r],a.flags|=16):d.push(r)),a.child=h,a.memoizedState=null,h}function Hi(r,a){return a=Mh({mode:"visible",children:a},r.mode,0,null),a.return=r,r.child=a}function Mo(r,a,d,h){return h!==null&&_d(h),Co(a,r.child,null,d),r=Hi(a,a.pendingProps.children),r.flags|=2,a.memoizedState=null,r}function kh(r,a,d,h,v,b,R){if(d)return a.flags&256?(a.flags&=-257,h=Rd(Error(n(422))),Mo(r,a,R,h)):a.memoizedState!==null?(a.child=r.child,a.flags|=128,null):(b=h.fallback,v=a.mode,h=Mh({mode:"visible",children:h.children},v,0,null),b=Hl(b,v,R,null),b.flags|=2,h.return=a,b.return=a,h.sibling=b,a.child=h,(a.mode&1)!==0&&Co(a,r.child,null,R),a.child.memoizedState=Pd(R),a.memoizedState=Od,b);if((a.mode&1)===0)return Mo(r,a,R,null);if(v.data==="$!"){if(h=v.nextSibling&&v.nextSibling.dataset,h)var ee=h.dgst;return h=ee,b=Error(n(419)),h=Rd(b,h,void 0),Mo(r,a,R,h)}if(ee=(R&r.childLanes)!==0,lr||ee){if(h=Un,h!==null){switch(R&-R){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|R))!==0?0:v,v!==0&&v!==b.retryLane&&(b.retryLane=v,wi(r,v),qr(h,r,v,-1))}return I(),h=Rd(Error(n(421))),Mo(r,a,R,h)}return v.data==="$?"?(a.flags|=128,a.child=r.child,a=cn.bind(null,r),v._reactRetry=a,null):(r=b.treeContext,ir=Di(v.nextSibling),As=a,wn=!0,Or=null,r!==null&&(Lr[ws++]=Ir,Lr[ws++]=ti,Lr[ws++]=qn,Ir=r.id,ti=r.overflow,qn=a),a=Hi(a,h.children),a.flags|=4096,a)}function Fd(r,a,d){r.lanes|=a;var h=r.alternate;h!==null&&(h.lanes|=a),Bc(r.return,a,d)}function zd(r,a,d,h,v){var b=r.memoizedState;b===null?r.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 Bd(r,a,d){var h=a.pendingProps,v=h.revealOrder,b=h.tail;if(Hn(r,a,h.children,d),h=$n.current,(h&2)!==0)h=h&1|2,a.flags|=128;else{if(r!==null&&(r.flags&128)!==0)e:for(r=a.child;r!==null;){if(r.tag===13)r.memoizedState!==null&&Fd(r,d,a);else if(r.tag===19)Fd(r,d,a);else if(r.child!==null){r.child.return=r,r=r.child;continue}if(r===a)break e;for(;r.sibling===null;){if(r.return===null||r.return===a)break e;r=r.return}r.sibling.return=r.return,r=r.sibling}h&=1}if(ln($n,h),(a.mode&1)===0)a.memoizedState=null;else switch(v){case"forwards":for(d=a.child,v=null;d!==null;)r=d.alternate,r!==null&&Ui(r)===null&&(v=d),d=d.sibling;d=v,d===null?(v=a.child,a.child=null):(v=d.sibling,d.sibling=null),zd(a,!1,v,d,b);break;case"backwards":for(d=null,v=a.child,a.child=null;v!==null;){if(r=v.alternate,r!==null&&Ui(r)===null){a.child=v;break}r=v.sibling,v.sibling=d,d=v,v=r}zd(a,!0,d,null,b);break;case"together":zd(a,!1,null,null,void 0);break;default:a.memoizedState=null}return a.child}function Vi(r,a){(a.mode&1)===0&&r!==null&&(r.alternate=null,a.alternate=null,a.flags|=2)}function Gi(r,a,d){if(r!==null&&(a.dependencies=r.dependencies),ga|=a.lanes,(d&a.childLanes)===0)return null;if(r!==null&&a.child!==r.child)throw Error(n(153));if(a.child!==null){for(r=a.child,d=fs(r,r.pendingProps),a.child=d,d.return=a;r.sibling!==null;)r=r.sibling,d=d.sibling=fs(r,r.pendingProps),d.return=a;d.sibling=null}return a.child}function nu(r,a,d){switch(a.tag){case 3:Sh(a),Bi();break;case 5:lh(a);break;case 1:ys(a.type)&&ko(a);break;case 4:Uc(a,a.stateNode.containerInfo);break;case 10:var h=a.type._context,v=a.memoizedProps.value;ln(Rl,h._currentValue),h._currentValue=v;break;case 13:if(h=a.memoizedState,h!==null)return h.dehydrated!==null?(ln($n,$n.current&1),a.flags|=128,null):(d&a.child.childLanes)!==0?Dd(r,a,d):(ln($n,$n.current&1),r=Gi(r,a,d),r!==null?r.sibling:null);ln($n,$n.current&1);break;case 19:if(h=(d&a.childLanes)!==0,(r.flags&128)!==0){if(h)return Bd(r,a,d);a.flags|=128}if(v=a.memoizedState,v!==null&&(v.rendering=null,v.tail=null,v.lastEffect=null),ln($n,$n.current),h)break;return null;case 22:case 23:return a.lanes=0,Wi(r,a,d)}return Gi(r,a,d)}var Ud,Wd,su,Nh;Ud=function(r,a){for(var d=a.child;d!==null;){if(d.tag===5||d.tag===6)r.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}},Wd=function(){},su=function(r,a,d,h){var v=r.memoizedProps;if(v!==h){r=a.stateNode,ca(vi.current);var b=null;switch(d){case"input":v=et(r,v),h=et(r,h),b=[];break;case"select":v=G({},v,{value:void 0}),h=G({},h,{value:void 0}),b=[];break;case"textarea":v=Ke(r,v),h=Ke(r,h),b=[];break;default:typeof v.onClick!="function"&&typeof h.onClick=="function"&&(r.onclick=Cl)}yn(d,h);var R;d=null;for(ye in v)if(!h.hasOwnProperty(ye)&&v.hasOwnProperty(ye)&&v[ye]!=null)if(ye==="style"){var ee=v[ye];for(R in ee)ee.hasOwnProperty(R)&&(d||(d={}),d[R]="")}else ye!=="dangerouslySetInnerHTML"&&ye!=="children"&&ye!=="suppressContentEditableWarning"&&ye!=="suppressHydrationWarning"&&ye!=="autoFocus"&&(o.hasOwnProperty(ye)?b||(b=[]):(b=b||[]).push(ye,null));for(ye in h){var se=h[ye];if(ee=v!=null?v[ye]:void 0,h.hasOwnProperty(ye)&&se!==ee&&(se!=null||ee!=null))if(ye==="style")if(ee){for(R in ee)!ee.hasOwnProperty(R)||se&&se.hasOwnProperty(R)||(d||(d={}),d[R]="");for(R in se)se.hasOwnProperty(R)&&ee[R]!==se[R]&&(d||(d={}),d[R]=se[R])}else d||(b||(b=[]),b.push(ye,d)),d=se;else ye==="dangerouslySetInnerHTML"?(se=se?se.__html:void 0,ee=ee?ee.__html:void 0,se!=null&&ee!==se&&(b=b||[]).push(ye,se)):ye==="children"?typeof se!="string"&&typeof se!="number"||(b=b||[]).push(ye,""+se):ye!=="suppressContentEditableWarning"&&ye!=="suppressHydrationWarning"&&(o.hasOwnProperty(ye)?(se!=null&&ye==="onScroll"&&gn("scroll",r),b||ee===se||(b=[])):(b=b||[]).push(ye,se))}d&&(b=b||[]).push("style",d);var ye=b;(a.updateQueue=ye)&&(a.flags|=4)}},Nh=function(r,a,d,h){d!==h&&(a.flags|=4)};function Fl(r,a){if(!wn)switch(r.tailMode){case"hidden":a=r.tail;for(var d=null;a!==null;)a.alternate!==null&&(d=a),a=a.sibling;d===null?r.tail=null:d.sibling=null;break;case"collapsed":d=r.tail;for(var h=null;d!==null;)d.alternate!==null&&(h=d),d=d.sibling;h===null?a||r.tail===null?r.tail=null:r.tail.sibling=null:h.sibling=null}}function Is(r){var a=r.alternate!==null&&r.alternate.child===r.child,d=0,h=0;if(a)for(var v=r.child;v!==null;)d|=v.lanes|v.childLanes,h|=v.subtreeFlags&14680064,h|=v.flags&14680064,v.return=r,v=v.sibling;else for(v=r.child;v!==null;)d|=v.lanes|v.childLanes,h|=v.subtreeFlags,h|=v.flags,v.return=r,v=v.sibling;return r.subtreeFlags|=h,r.childLanes=d,a}function xr(r,a,d){var h=a.pendingProps;switch(dd(a),a.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return Is(a),null;case 1:return ys(a.type)&&Mc(),Is(a),null;case 3:return h=a.stateNode,Xa(),Sn(rr),Sn(es),Dr(),h.pendingContext&&(h.context=h.pendingContext,h.pendingContext=null),(r===null||r.child===null)&&(Pc(a)?a.flags|=4:r===null||r.memoizedState.isDehydrated&&(a.flags&256)===0||(a.flags|=1024,Or!==null&&(mu(Or),Or=null))),Wd(r,a),Is(a),null;case 5:vd(a);var v=ca(Il.current);if(d=a.type,r!==null&&a.stateNode!=null)su(r,a,d,h,v),r.ref!==a.ref&&(a.flags|=512,a.flags|=2097152);else{if(!h){if(a.stateNode===null)throw Error(n(166));return Is(a),null}if(r=ca(vi.current),Pc(a)){h=a.stateNode,d=a.type;var b=a.memoizedProps;switch(h[_i]=a,h[Ua]=b,r=(a.mode&1)!==0,d){case"dialog":gn("cancel",h),gn("close",h);break;case"iframe":case"object":case"embed":gn("load",h);break;case"video":case"audio":for(v=0;v<di.length;v++)gn(di[v],h);break;case"source":gn("error",h);break;case"img":case"image":case"link":gn("error",h),gn("load",h);break;case"details":gn("toggle",h);break;case"input":lt(h,b),gn("invalid",h);break;case"select":h._wrapperState={wasMultiple:!!b.multiple},gn("invalid",h);break;case"textarea":Dt(h,b),gn("invalid",h)}yn(d,b),v=null;for(var R in b)if(b.hasOwnProperty(R)){var ee=b[R];R==="children"?typeof ee=="string"?h.textContent!==ee&&(b.suppressHydrationWarning!==!0&&vr(h.textContent,ee,r),v=["children",ee]):typeof ee=="number"&&h.textContent!==""+ee&&(b.suppressHydrationWarning!==!0&&vr(h.textContent,ee,r),v=["children",""+ee]):o.hasOwnProperty(R)&&ee!=null&&R==="onScroll"&&gn("scroll",h)}switch(d){case"input":We(h),Le(h,b,!0);break;case"textarea":We(h),pn(h);break;case"select":case"option":break;default:typeof b.onClick=="function"&&(h.onclick=Cl)}h=v,a.updateQueue=h,h!==null&&(a.flags|=4)}else{R=v.nodeType===9?v:v.ownerDocument,r==="http://www.w3.org/1999/xhtml"&&(r=Wt(d)),r==="http://www.w3.org/1999/xhtml"?d==="script"?(r=R.createElement("div"),r.innerHTML="<script><\/script>",r=r.removeChild(r.firstChild)):typeof h.is=="string"?r=R.createElement(d,{is:h.is}):(r=R.createElement(d),d==="select"&&(R=r,h.multiple?R.multiple=!0:h.size&&(R.size=h.size))):r=R.createElementNS(r,d),r[_i]=a,r[Ua]=h,Ud(r,a,!1,!1),a.stateNode=r;e:{switch(R=Ns(d,h),d){case"dialog":gn("cancel",r),gn("close",r),v=h;break;case"iframe":case"object":case"embed":gn("load",r),v=h;break;case"video":case"audio":for(v=0;v<di.length;v++)gn(di[v],r);v=h;break;case"source":gn("error",r),v=h;break;case"img":case"image":case"link":gn("error",r),gn("load",r),v=h;break;case"details":gn("toggle",r),v=h;break;case"input":lt(r,h),v=et(r,h),gn("invalid",r);break;case"option":v=h;break;case"select":r._wrapperState={wasMultiple:!!h.multiple},v=G({},h,{value:void 0}),gn("invalid",r);break;case"textarea":Dt(r,h),v=Ke(r,h),gn("invalid",r);break;default:v=h}yn(d,v),ee=v;for(b in ee)if(ee.hasOwnProperty(b)){var se=ee[b];b==="style"?jn(r,se):b==="dangerouslySetInnerHTML"?(se=se?se.__html:void 0,se!=null&&Wn(r,se)):b==="children"?typeof se=="string"?(d!=="textarea"||se!=="")&&Tt(r,se):typeof se=="number"&&Tt(r,""+se):b!=="suppressContentEditableWarning"&&b!=="suppressHydrationWarning"&&b!=="autoFocus"&&(o.hasOwnProperty(b)?se!=null&&b==="onScroll"&&gn("scroll",r):se!=null&&O(r,b,se,R))}switch(d){case"input":We(r),Le(r,h,!1);break;case"textarea":We(r),pn(r);break;case"option":h.value!=null&&r.setAttribute("value",""+we(h.value));break;case"select":r.multiple=!!h.multiple,b=h.value,b!=null?De(r,!!h.multiple,b,!1):h.defaultValue!=null&&De(r,!!h.multiple,h.defaultValue,!0);break;default:typeof v.onClick=="function"&&(r.onclick=Cl)}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 Is(a),null;case 6:if(r&&a.stateNode!=null)Nh(r,a,r.memoizedProps,h);else{if(typeof h!="string"&&a.stateNode===null)throw Error(n(166));if(d=ca(Il.current),ca(vi.current),Pc(a)){if(h=a.stateNode,d=a.memoizedProps,h[_i]=a,(b=h.nodeValue!==d)&&(r=As,r!==null))switch(r.tag){case 3:vr(h.nodeValue,d,(r.mode&1)!==0);break;case 5:r.memoizedProps.suppressHydrationWarning!==!0&&vr(h.nodeValue,d,(r.mode&1)!==0)}b&&(a.flags|=4)}else h=(d.nodeType===9?d:d.ownerDocument).createTextNode(h),h[_i]=a,a.stateNode=h}return Is(a),null;case 13:if(Sn($n),h=a.memoizedState,r===null||r.memoizedState!==null&&r.memoizedState.dehydrated!==null){if(wn&&ir!==null&&(a.mode&1)!==0&&(a.flags&128)===0)md(),Bi(),a.flags|=98560,b=!1;else if(b=Pc(a),h!==null&&h.dehydrated!==null){if(r===null){if(!b)throw Error(n(318));if(b=a.memoizedState,b=b!==null?b.dehydrated:null,!b)throw Error(n(317));b[_i]=a}else Bi(),(a.flags&128)===0&&(a.memoizedState=null),a.flags|=4;Is(a),b=!1}else Or!==null&&(mu(Or),Or=null),b=!0;if(!b)return a.flags&65536?a:null}return(a.flags&128)!==0?(a.lanes=d,a):(h=h!==null,h!==(r!==null&&r.memoizedState!==null)&&h&&(a.child.flags|=8192,(a.mode&1)!==0&&(r===null||($n.current&1)!==0?kn===0&&(kn=3):I())),a.updateQueue!==null&&(a.flags|=4),Is(a),null);case 4:return Xa(),Wd(r,a),r===null&&Tr(a.stateNode.containerInfo),Is(a),null;case 10:return Ll(a.type._context),Is(a),null;case 17:return ys(a.type)&&Mc(),Is(a),null;case 19:if(Sn($n),b=a.memoizedState,b===null)return Is(a),null;if(h=(a.flags&128)!==0,R=b.rendering,R===null)if(h)Fl(b,!1);else{if(kn!==0||r!==null&&(r.flags&128)!==0)for(r=a.child;r!==null;){if(R=Ui(r),R!==null){for(a.flags|=128,Fl(b,!1),h=R.updateQueue,h!==null&&(a.updateQueue=h,a.flags|=4),a.subtreeFlags=0,h=d,d=a.child;d!==null;)b=d,r=h,b.flags&=14680066,R=b.alternate,R===null?(b.childLanes=0,b.lanes=r,b.child=null,b.subtreeFlags=0,b.memoizedProps=null,b.memoizedState=null,b.updateQueue=null,b.dependencies=null,b.stateNode=null):(b.childLanes=R.childLanes,b.lanes=R.lanes,b.child=R.child,b.subtreeFlags=0,b.deletions=null,b.memoizedProps=R.memoizedProps,b.memoizedState=R.memoizedState,b.updateQueue=R.updateQueue,b.type=R.type,r=R.dependencies,b.dependencies=r===null?null:{lanes:r.lanes,firstContext:r.firstContext}),d=d.sibling;return ln($n,$n.current&1|2),a.child}r=r.sibling}b.tail!==null&&mn()>wa&&(a.flags|=128,h=!0,Fl(b,!1),a.lanes=4194304)}else{if(!h)if(r=Ui(R),r!==null){if(a.flags|=128,h=!0,d=r.updateQueue,d!==null&&(a.updateQueue=d,a.flags|=4),Fl(b,!0),b.tail===null&&b.tailMode==="hidden"&&!R.alternate&&!wn)return Is(a),null}else 2*mn()-b.renderingStartTime>wa&&d!==1073741824&&(a.flags|=128,h=!0,Fl(b,!1),a.lanes=4194304);b.isBackwards?(R.sibling=a.child,a.child=R):(d=b.last,d!==null?d.sibling=R:a.child=R,b.last=R)}return b.tail!==null?(a=b.tail,b.rendering=a,b.tail=a.sibling,b.renderingStartTime=mn(),a.sibling=null,d=$n.current,ln($n,h?d&1|2:d&1),a):(Is(a),null);case 22:case 23:return pu(),h=a.memoizedState!==null,r!==null&&r.memoizedState!==null!==h&&(a.flags|=8192),h&&(a.mode&1)!==0?(cr&1073741824)!==0&&(Is(a),a.subtreeFlags&6&&(a.flags|=8192)):Is(a),null;case 24:return null;case 25:return null}throw Error(n(156,a.tag))}function nl(r,a){switch(dd(a),a.tag){case 1:return ys(a.type)&&Mc(),r=a.flags,r&65536?(a.flags=r&-65537|128,a):null;case 3:return Xa(),Sn(rr),Sn(es),Dr(),r=a.flags,(r&65536)!==0&&(r&128)===0?(a.flags=r&-65537|128,a):null;case 5:return vd(a),null;case 13:if(Sn($n),r=a.memoizedState,r!==null&&r.dehydrated!==null){if(a.alternate===null)throw Error(n(340));Bi()}return r=a.flags,r&65536?(a.flags=r&-65537|128,a):null;case 19:return Sn($n),null;case 4:return Xa(),null;case 10:return Ll(a.type._context),null;case 22:case 23:return pu(),null;case 24:return null;default:return null}}var ru=!1,xs=!1,br=typeof WeakSet=="function"?WeakSet:Set,Je=null;function ma(r,a){var d=r.ref;if(d!==null)if(typeof d=="function")try{d(null)}catch(h){Ie(r,a,h)}else d.current=null}function iu(r,a,d){try{d()}catch(h){Ie(r,a,h)}}var Ch=!1;function __(r,a){if(El=Vo,r=Pa(),vo(r)){if("selectionStart"in r)var d={start:r.selectionStart,end:r.selectionEnd};else e:{d=(d=r.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 R=0,ee=-1,se=-1,ye=0,Me=0,Re=r,Te=null;t:for(;;){for(var Xe;Re!==d||v!==0&&Re.nodeType!==3||(ee=R+v),Re!==b||h!==0&&Re.nodeType!==3||(se=R+h),Re.nodeType===3&&(R+=Re.nodeValue.length),(Xe=Re.firstChild)!==null;)Te=Re,Re=Xe;for(;;){if(Re===r)break t;if(Te===d&&++ye===v&&(ee=R),Te===b&&++Me===h&&(se=R),(Xe=Re.nextSibling)!==null)break;Re=Te,Te=Re.parentNode}Re=Xe}d=ee===-1||se===-1?null:{start:ee,end:se}}else d=null}d=d||{start:0,end:0}}else d=null;for(ad={focusedElem:r,selectionRange:d},Vo=!1,Je=a;Je!==null;)if(a=Je,r=a.child,(a.subtreeFlags&1028)!==0&&r!==null)r.return=a,Je=r;else for(;Je!==null;){a=Je;try{var tt=a.alternate;if((a.flags&1024)!==0)switch(a.tag){case 0:case 11:case 15:break;case 1:if(tt!==null){var nt=tt.memoizedProps,ss=tt.memoizedState,de=a.stateNode,le=de.getSnapshotBeforeUpdate(a.elementType===a.type?nt:vs(a.type,nt),ss);de.__reactInternalSnapshotBeforeUpdate=le}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(Fe){Ie(a,a.return,Fe)}if(r=a.sibling,r!==null){r.return=a.return,Je=r;break}Je=a.return}return tt=Ch,Ch=!1,tt}function bs(r,a,d){var h=a.updateQueue;if(h=h!==null?h.lastEffect:null,h!==null){var v=h=h.next;do{if((v.tag&r)===r){var b=v.destroy;v.destroy=void 0,b!==void 0&&iu(a,d,b)}v=v.next}while(v!==h)}}function Ro(r,a){if(a=a.updateQueue,a=a!==null?a.lastEffect:null,a!==null){var d=a=a.next;do{if((d.tag&r)===r){var h=d.create;d.destroy=h()}d=d.next}while(d!==a)}}function ou(r){var a=r.ref;if(a!==null){var d=r.stateNode;switch(r.tag){case 5:r=d;break;default:r=d}typeof a=="function"?a(r):a.current=r}}function qd(r){var a=r.alternate;a!==null&&(r.alternate=null,qd(a)),r.child=null,r.deletions=null,r.sibling=null,r.tag===5&&(a=r.stateNode,a!==null&&(delete a[_i],delete a[Ua],delete a[Ac],delete a[c_],delete a[sh])),r.stateNode=null,r.return=null,r.dependencies=null,r.memoizedProps=null,r.memoizedState=null,r.pendingProps=null,r.stateNode=null,r.updateQueue=null}function Eh(r){return r.tag===5||r.tag===3||r.tag===4}function Hd(r){e:for(;;){for(;r.sibling===null;){if(r.return===null||Eh(r.return))return null;r=r.return}for(r.sibling.return=r.return,r=r.sibling;r.tag!==5&&r.tag!==6&&r.tag!==18;){if(r.flags&2||r.child===null||r.tag===4)continue e;r.child.return=r,r=r.child}if(!(r.flags&2))return r.stateNode}}function si(r,a,d){var h=r.tag;if(h===5||h===6)r=r.stateNode,a?d.nodeType===8?d.parentNode.insertBefore(r,a):d.insertBefore(r,a):(d.nodeType===8?(a=d.parentNode,a.insertBefore(r,d)):(a=d,a.appendChild(r)),d=d._reactRootContainer,d!=null||a.onclick!==null||(a.onclick=Cl));else if(h!==4&&(r=r.child,r!==null))for(si(r,a,d),r=r.sibling;r!==null;)si(r,a,d),r=r.sibling}function Vd(r,a,d){var h=r.tag;if(h===5||h===6)r=r.stateNode,a?d.insertBefore(r,a):d.appendChild(r);else if(h!==4&&(r=r.child,r!==null))for(Vd(r,a,d),r=r.sibling;r!==null;)Vd(r,a,d),r=r.sibling}var js=null,Ur=!1;function xi(r,a,d){for(d=d.child;d!==null;)ri(r,a,d),d=d.sibling}function ri(r,a,d){if(ms&&typeof ms.onCommitFiberUnmount=="function")try{ms.onCommitFiberUnmount(sn,d)}catch{}switch(d.tag){case 5:xs||ma(d,a);case 6:var h=js,v=Ur;js=null,xi(r,a,d),js=h,Ur=v,js!==null&&(Ur?(r=js,d=d.stateNode,r.nodeType===8?r.parentNode.removeChild(d):r.removeChild(d)):js.removeChild(d.stateNode));break;case 18:js!==null&&(Ur?(r=js,d=d.stateNode,r.nodeType===8?$c(r.parentNode,d):r.nodeType===1&&$c(r,d),_o(r)):$c(js,d.stateNode));break;case 4:h=js,v=Ur,js=d.stateNode.containerInfo,Ur=!0,xi(r,a,d),js=h,Ur=v;break;case 0:case 11:case 14:case 15:if(!xs&&(h=d.updateQueue,h!==null&&(h=h.lastEffect,h!==null))){v=h=h.next;do{var b=v,R=b.destroy;b=b.tag,R!==void 0&&((b&2)!==0||(b&4)!==0)&&iu(d,a,R),v=v.next}while(v!==h)}xi(r,a,d);break;case 1:if(!xs&&(ma(d,a),h=d.stateNode,typeof h.componentWillUnmount=="function"))try{h.props=d.memoizedProps,h.state=d.memoizedState,h.componentWillUnmount()}catch(ee){Ie(d,a,ee)}xi(r,a,d);break;case 21:xi(r,a,d);break;case 22:d.mode&1?(xs=(h=xs)||d.memoizedState!==null,xi(r,a,d),xs=h):xi(r,a,d);break;default:xi(r,a,d)}}function zl(r){var a=r.updateQueue;if(a!==null){r.updateQueue=null;var d=r.stateNode;d===null&&(d=r.stateNode=new br),a.forEach(function(h){var v=Rt.bind(null,r,h);d.has(h)||(d.add(h),h.then(v,v))})}}function ii(r,a){var d=a.deletions;if(d!==null)for(var h=0;h<d.length;h++){var v=d[h];try{var b=r,R=a,ee=R;e:for(;ee!==null;){switch(ee.tag){case 5:js=ee.stateNode,Ur=!1;break e;case 3:js=ee.stateNode.containerInfo,Ur=!0;break e;case 4:js=ee.stateNode.containerInfo,Ur=!0;break e}ee=ee.return}if(js===null)throw Error(n(160));ri(b,R,v),js=null,Ur=!1;var se=v.alternate;se!==null&&(se.return=null),v.return=null}catch(ye){Ie(v,a,ye)}}if(a.subtreeFlags&12854)for(a=a.child;a!==null;)Ki(a,r),a=a.sibling}function Ki(r,a){var d=r.alternate,h=r.flags;switch(r.tag){case 0:case 11:case 14:case 15:if(ii(a,r),Wr(r),h&4){try{bs(3,r,r.return),Ro(3,r)}catch(nt){Ie(r,r.return,nt)}try{bs(5,r,r.return)}catch(nt){Ie(r,r.return,nt)}}break;case 1:ii(a,r),Wr(r),h&512&&d!==null&&ma(d,d.return);break;case 5:if(ii(a,r),Wr(r),h&512&&d!==null&&ma(d,d.return),r.flags&32){var v=r.stateNode;try{Tt(v,"")}catch(nt){Ie(r,r.return,nt)}}if(h&4&&(v=r.stateNode,v!=null)){var b=r.memoizedProps,R=d!==null?d.memoizedProps:b,ee=r.type,se=r.updateQueue;if(r.updateQueue=null,se!==null)try{ee==="input"&&b.type==="radio"&&b.name!=null&&Ye(v,b),Ns(ee,R);var ye=Ns(ee,b);for(R=0;R<se.length;R+=2){var Me=se[R],Re=se[R+1];Me==="style"?jn(v,Re):Me==="dangerouslySetInnerHTML"?Wn(v,Re):Me==="children"?Tt(v,Re):O(v,Me,Re,ye)}switch(ee){case"input":Se(v,b);break;case"textarea":tn(v,b);break;case"select":var Te=v._wrapperState.wasMultiple;v._wrapperState.wasMultiple=!!b.multiple;var Xe=b.value;Xe!=null?De(v,!!b.multiple,Xe,!1):Te!==!!b.multiple&&(b.defaultValue!=null?De(v,!!b.multiple,b.defaultValue,!0):De(v,!!b.multiple,b.multiple?[]:"",!1))}v[Ua]=b}catch(nt){Ie(r,r.return,nt)}}break;case 6:if(ii(a,r),Wr(r),h&4){if(r.stateNode===null)throw Error(n(162));v=r.stateNode,b=r.memoizedProps;try{v.nodeValue=b}catch(nt){Ie(r,r.return,nt)}}break;case 3:if(ii(a,r),Wr(r),h&4&&d!==null&&d.memoizedState.isDehydrated)try{_o(a.containerInfo)}catch(nt){Ie(r,r.return,nt)}break;case 4:ii(a,r),Wr(r);break;case 13:ii(a,r),Wr(r),v=r.child,v.flags&8192&&(b=v.memoizedState!==null,v.stateNode.isHidden=b,!b||v.alternate!==null&&v.alternate.memoizedState!==null||(cu=mn())),h&4&&zl(r);break;case 22:if(Me=d!==null&&d.memoizedState!==null,r.mode&1?(xs=(ye=xs)||Me,ii(a,r),xs=ye):ii(a,r),Wr(r),h&8192){if(ye=r.memoizedState!==null,(r.stateNode.isHidden=ye)&&!Me&&(r.mode&1)!==0)for(Je=r,Me=r.child;Me!==null;){for(Re=Je=Me;Je!==null;){switch(Te=Je,Xe=Te.child,Te.tag){case 0:case 11:case 14:case 15:bs(4,Te,Te.return);break;case 1:ma(Te,Te.return);var tt=Te.stateNode;if(typeof tt.componentWillUnmount=="function"){h=Te,d=Te.return;try{a=h,tt.props=a.memoizedProps,tt.state=a.memoizedState,tt.componentWillUnmount()}catch(nt){Ie(h,d,nt)}}break;case 5:ma(Te,Te.return);break;case 22:if(Te.memoizedState!==null){$h(Re);continue}}Xe!==null?(Xe.return=Te,Je=Xe):$h(Re)}Me=Me.sibling}e:for(Me=null,Re=r;;){if(Re.tag===5){if(Me===null){Me=Re;try{v=Re.stateNode,ye?(b=v.style,typeof b.setProperty=="function"?b.setProperty("display","none","important"):b.display="none"):(ee=Re.stateNode,se=Re.memoizedProps.style,R=se!=null&&se.hasOwnProperty("display")?se.display:null,ee.style.display=An("display",R))}catch(nt){Ie(r,r.return,nt)}}}else if(Re.tag===6){if(Me===null)try{Re.stateNode.nodeValue=ye?"":Re.memoizedProps}catch(nt){Ie(r,r.return,nt)}}else if((Re.tag!==22&&Re.tag!==23||Re.memoizedState===null||Re===r)&&Re.child!==null){Re.child.return=Re,Re=Re.child;continue}if(Re===r)break e;for(;Re.sibling===null;){if(Re.return===null||Re.return===r)break e;Me===Re&&(Me=null),Re=Re.return}Me===Re&&(Me=null),Re.sibling.return=Re.return,Re=Re.sibling}}break;case 19:ii(a,r),Wr(r),h&4&&zl(r);break;case 21:break;default:ii(a,r),Wr(r)}}function Wr(r){var a=r.flags;if(a&2){try{e:{for(var d=r.return;d!==null;){if(Eh(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&&(Tt(v,""),h.flags&=-33);var b=Hd(r);Vd(r,b,v);break;case 3:case 4:var R=h.stateNode.containerInfo,ee=Hd(r);si(r,ee,R);break;default:throw Error(n(161))}}catch(se){Ie(r,r.return,se)}r.flags&=-3}a&4096&&(r.flags&=-4097)}function Gd(r,a,d){Je=r,Jn(r)}function Jn(r,a,d){for(var h=(r.mode&1)!==0;Je!==null;){var v=Je,b=v.child;if(v.tag===22&&h){var R=v.memoizedState!==null||ru;if(!R){var ee=v.alternate,se=ee!==null&&ee.memoizedState!==null||xs;ee=ru;var ye=xs;if(ru=R,(xs=se)&&!ye)for(Je=v;Je!==null;)R=Je,se=R.child,R.tag===22&&R.memoizedState!==null?Kd(v):se!==null?(se.return=R,Je=se):Kd(v);for(;b!==null;)Je=b,Jn(b),b=b.sibling;Je=v,ru=ee,xs=ye}_a(r)}else(v.subtreeFlags&8772)!==0&&b!==null?(b.return=v,Je=b):_a(r)}}function _a(r){for(;Je!==null;){var a=Je;if((a.flags&8772)!==0){var d=a.alternate;try{if((a.flags&8772)!==0)switch(a.tag){case 0:case 11:case 15:xs||Ro(5,a);break;case 1:var h=a.stateNode;if(a.flags&4&&!xs)if(d===null)h.componentDidMount();else{var v=a.elementType===a.type?d.memoizedProps:vs(a.type,d.memoizedProps);h.componentDidUpdate(v,d.memoizedState,h.__reactInternalSnapshotBeforeUpdate)}var b=a.updateQueue;b!==null&&wd(a,b,h);break;case 3:var R=a.updateQueue;if(R!==null){if(d=null,a.child!==null)switch(a.child.tag){case 5:d=a.child.stateNode;break;case 1:d=a.child.stateNode}wd(a,R,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 ye=a.alternate;if(ye!==null){var Me=ye.memoizedState;if(Me!==null){var Re=Me.dehydrated;Re!==null&&_o(Re)}}}break;case 19:case 17:case 21:case 22:case 23:case 25:break;default:throw Error(n(163))}xs||a.flags&512&&ou(a)}catch(Te){Ie(a,a.return,Te)}}if(a===r){Je=null;break}if(d=a.sibling,d!==null){d.return=a.return,Je=d;break}Je=a.return}}function $h(r){for(;Je!==null;){var a=Je;if(a===r){Je=null;break}var d=a.sibling;if(d!==null){d.return=a.return,Je=d;break}Je=a.return}}function Kd(r){for(;Je!==null;){var a=Je;try{switch(a.tag){case 0:case 11:case 15:var d=a.return;try{Ro(4,a)}catch(se){Ie(a,d,se)}break;case 1:var h=a.stateNode;if(typeof h.componentDidMount=="function"){var v=a.return;try{h.componentDidMount()}catch(se){Ie(a,v,se)}}var b=a.return;try{ou(a)}catch(se){Ie(a,b,se)}break;case 5:var R=a.return;try{ou(a)}catch(se){Ie(a,R,se)}}}catch(se){Ie(a,a.return,se)}if(a===r){Je=null;break}var ee=a.sibling;if(ee!==null){ee.return=a.return,Je=ee;break}Je=a.return}}var Ah=Math.ceil,Bl=M.ReactCurrentDispatcher,au=M.ReactCurrentOwner,jr=M.ReactCurrentBatchConfig,Zt=0,Un=null,Dn=null,ds=0,cr=0,pa=ei(0),kn=0,Ul=null,ga=0,lu=0,Yi=0,ya=null,Os=null,cu=0,wa=1/0,Ji=null,Lo=!1,Xi=null,Io=null,Oo=!1,Po=null,uu=0,Wl=0,du=null,ql=-1,fu=0;function Ps(){return(Zt&6)!==0?mn():ql!==-1?ql:ql=mn()}function Zi(r){return(r.mode&1)===0?1:(Zt&2)!==0&&ds!==0?ds&-ds:u_.transition!==null?(fu===0&&(fu=ls()),fu):(r=rn,r!==0||(r=window.event,r=r===void 0?16:je(r.type)),r)}function qr(r,a,d,h){if(50<Wl)throw Wl=0,du=null,Error(n(185));_s(r,d,h),((Zt&2)===0||r!==Un)&&(r===Un&&((Zt&2)===0&&(lu|=d),kn===4&&Qi(r,ds)),Vs(r,h),d===1&&Zt===0&&(a.mode&1)===0&&(wa=mn()+500,Va&&yi()))}function Vs(r,a){var d=r.callbackNode;Xn(r,a);var h=pr(r,r===Un?ds:0);if(h===0)d!==null&&lo(d),r.callbackNode=null,r.callbackPriority=0;else if(a=h&-h,r.callbackPriority!==a){if(d!=null&&lo(d),a===1)r.tag===0?Ga(Jd.bind(null,r)):Rc(Jd.bind(null,r)),cd(function(){(Zt&6)===0&&yi()}),d=null;else{switch(yl(h)){case 1:d=Ei;break;case 4:d=Cr;break;case 16:d=mr;break;case 536870912:d=ot;break;default:d=mr}d=xt(d,Yd.bind(null,r))}r.callbackPriority=a,r.callbackNode=d}}function Yd(r,a){if(ql=-1,fu=0,(Zt&6)!==0)throw Error(n(327));var d=r.callbackNode;if(Ce()&&r.callbackNode!==d)return null;var h=pr(r,r===Un?ds:0);if(h===0)return null;if((h&30)!==0||(h&r.expiredLanes)!==0||a)a=q(r,h);else{a=h;var v=Zt;Zt|=2;var b=$();(Un!==r||ds!==a)&&(Ji=null,wa=mn()+500,g(r,a));do try{V();break}catch(ee){k(r,ee)}while(!0);Bn(),Bl.current=b,Zt=v,Dn!==null?a=0:(Un=null,ds=0,a=kn)}if(a!==0){if(a===2&&(v=Zs(r),v!==0&&(h=v,a=hu(r,v))),a===1)throw d=Ul,g(r,0),Qi(r,h),Vs(r,mn()),d;if(a===6)Qi(r,h);else{if(v=r.current.alternate,(h&30)===0&&!Th(v)&&(a=q(r,h),a===2&&(b=Zs(r),b!==0&&(h=b,a=hu(r,b))),a===1))throw d=Ul,g(r,0),Qi(r,h),Vs(r,mn()),d;switch(r.finishedWork=v,r.finishedLanes=h,a){case 0:case 1:throw Error(n(345));case 2:he(r,Os,Ji);break;case 3:if(Qi(r,h),(h&130023424)===h&&(a=cu+500-mn(),10<a)){if(pr(r,0)!==0)break;if(v=r.suspendedLanes,(v&h)!==h){Ps(),r.pingedLanes|=r.suspendedLanes&v;break}r.timeoutHandle=Ec(he.bind(null,r,Os,Ji),a);break}he(r,Os,Ji);break;case 4:if(Qi(r,h),(h&4194240)===h)break;for(a=r.eventTimes,v=-1;0<h;){var R=31-as(h);b=1<<R,R=a[R],R>v&&(v=R),h&=~b}if(h=v,h=mn()-h,h=(120>h?120:480>h?480:1080>h?1080:1920>h?1920:3e3>h?3e3:4320>h?4320:1960*Ah(h/1960))-h,10<h){r.timeoutHandle=Ec(he.bind(null,r,Os,Ji),h);break}he(r,Os,Ji);break;case 5:he(r,Os,Ji);break;default:throw Error(n(329))}}}return Vs(r,mn()),r.callbackNode===d?Yd.bind(null,r):null}function hu(r,a){var d=ya;return r.current.memoizedState.isDehydrated&&(g(r,a).flags|=256),r=q(r,a),r!==2&&(a=Os,Os=d,a!==null&&mu(a)),r}function mu(r){Os===null?Os=r:Os.push.apply(Os,r)}function Th(r){for(var a=r;;){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(!Ar(b(),v))return!1}catch{return!1}}}if(d=a.child,a.subtreeFlags&16384&&d!==null)d.return=a,a=d;else{if(a===r)break;for(;a.sibling===null;){if(a.return===null||a.return===r)return!0;a=a.return}a.sibling.return=a.return,a=a.sibling}}return!0}function Qi(r,a){for(a&=~Yi,a&=~lu,r.suspendedLanes|=a,r.pingedLanes&=~a,r=r.expirationTimes;0<a;){var d=31-as(a),h=1<<d;r[d]=-1,a&=~h}}function Jd(r){if((Zt&6)!==0)throw Error(n(327));Ce();var a=pr(r,0);if((a&1)===0)return Vs(r,mn()),null;var d=q(r,a);if(r.tag!==0&&d===2){var h=Zs(r);h!==0&&(a=h,d=hu(r,h))}if(d===1)throw d=Ul,g(r,0),Qi(r,a),Vs(r,mn()),d;if(d===6)throw Error(n(345));return r.finishedWork=r.current.alternate,r.finishedLanes=a,he(r,Os,Ji),Vs(r,mn()),null}function _u(r,a){var d=Zt;Zt|=1;try{return r(a)}finally{Zt=d,Zt===0&&(wa=mn()+500,Va&&yi())}}function Do(r){Po!==null&&Po.tag===0&&(Zt&6)===0&&Ce();var a=Zt;Zt|=1;var d=jr.transition,h=rn;try{if(jr.transition=null,rn=1,r)return r()}finally{rn=h,jr.transition=d,Zt=a,(Zt&6)===0&&yi()}}function pu(){cr=pa.current,Sn(pa)}function g(r,a){r.finishedWork=null,r.finishedLanes=0;var d=r.timeoutHandle;if(d!==-1&&(r.timeoutHandle=-1,$l(d)),Dn!==null)for(d=Dn.return;d!==null;){var h=d;switch(dd(h),h.tag){case 1:h=h.type.childContextTypes,h!=null&&Mc();break;case 3:Xa(),Sn(rr),Sn(es),Dr();break;case 5:vd(h);break;case 4:Xa();break;case 13:Sn($n);break;case 19:Sn($n);break;case 10:Ll(h.type._context);break;case 22:case 23:pu()}d=d.return}if(Un=r,Dn=r=fs(r.current,null),ds=cr=a,kn=0,Ul=null,Yi=lu=ga=0,Os=ya=null,aa!==null){for(a=0;a<aa.length;a++)if(d=aa[a],h=d.interleaved,h!==null){d.interleaved=null;var v=h.next,b=d.pending;if(b!==null){var R=b.next;b.next=v,h.next=R}d.pending=h}aa=null}return r}function k(r,a){do{var d=Dn;try{if(Bn(),or.current=Xc,Za){for(var h=On.memoizedState;h!==null;){var v=h.queue;v!==null&&(v.pending=null),h=h.next}Za=!1}if(ua=0,ns=ts=On=null,Ol=!1,vn=0,au.current=null,d===null||d.return===null){kn=1,Ul=a,Dn=null;break}e:{var b=r,R=d.return,ee=d,se=a;if(a=ds,ee.flags|=32768,se!==null&&typeof se=="object"&&typeof se.then=="function"){var ye=se,Me=ee,Re=Me.tag;if((Me.mode&1)===0&&(Re===0||Re===11||Re===15)){var Te=Me.alternate;Te?(Me.updateQueue=Te.updateQueue,Me.memoizedState=Te.memoizedState,Me.lanes=Te.lanes):(Me.updateQueue=null,Me.memoizedState=null)}var Xe=xh(R);if(Xe!==null){Xe.flags&=-257,bh(Xe,R,ee,b,a),Xe.mode&1&&Qc(b,ye,a),a=Xe,se=ye;var tt=a.updateQueue;if(tt===null){var nt=new Set;nt.add(se),a.updateQueue=nt}else tt.add(se);break e}else{if((a&1)===0){Qc(b,ye,a),I();break e}se=Error(n(426))}}else if(wn&&ee.mode&1){var ss=xh(R);if(ss!==null){(ss.flags&65536)===0&&(ss.flags|=256),bh(ss,R,ee,b,a),_d(el(se,ee));break e}}b=se=el(se,ee),kn!==4&&(kn=2),ya===null?ya=[b]:ya.push(b),b=R;do{switch(b.tag){case 3:b.flags|=65536,a&=-a,b.lanes|=a;var de=vh(b,se,a);yd(b,de);break e;case 1:ee=se;var le=b.type,me=b.stateNode;if((b.flags&128)===0&&(typeof le.getDerivedStateFromError=="function"||me!==null&&typeof me.componentDidCatch=="function"&&(Io===null||!Io.has(me)))){b.flags|=65536,a&=-a,b.lanes|=a;var Fe=Id(b,ee,a);yd(b,Fe);break e}}b=b.return}while(b!==null)}$e(d)}catch(rt){a=rt,Dn===d&&d!==null&&(Dn=d=d.return);continue}break}while(!0)}function $(){var r=Bl.current;return Bl.current=Xc,r===null?Xc:r}function I(){(kn===0||kn===3||kn===2)&&(kn=4),Un===null||(ga&268435455)===0&&(lu&268435455)===0||Qi(Un,ds)}function q(r,a){var d=Zt;Zt|=2;var h=$();(Un!==r||ds!==a)&&(Ji=null,g(r,a));do try{W();break}catch(v){k(r,v)}while(!0);if(Bn(),Zt=d,Bl.current=h,Dn!==null)throw Error(n(261));return Un=null,ds=0,kn}function W(){for(;Dn!==null;)te(Dn)}function V(){for(;Dn!==null&&!xe();)te(Dn)}function te(r){var a=qe(r.alternate,r,cr);r.memoizedProps=r.pendingProps,a===null?$e(r):Dn=a,au.current=null}function $e(r){var a=r;do{var d=a.alternate;if(r=a.return,(a.flags&32768)===0){if(d=xr(d,a,cr),d!==null){Dn=d;return}}else{if(d=nl(d,a),d!==null){d.flags&=32767,Dn=d;return}if(r!==null)r.flags|=32768,r.subtreeFlags=0,r.deletions=null;else{kn=6,Dn=null;return}}if(a=a.sibling,a!==null){Dn=a;return}Dn=a=r}while(a!==null);kn===0&&(kn=5)}function he(r,a,d){var h=rn,v=jr.transition;try{jr.transition=null,rn=1,pe(r,a,d,h)}finally{jr.transition=v,rn=h}return null}function pe(r,a,d,h){do Ce();while(Po!==null);if((Zt&6)!==0)throw Error(n(327));d=r.finishedWork;var v=r.finishedLanes;if(d===null)return null;if(r.finishedWork=null,r.finishedLanes=0,d===r.current)throw Error(n(177));r.callbackNode=null,r.callbackPriority=0;var b=d.lanes|d.childLanes;if(Ta(r,b),r===Un&&(Dn=Un=null,ds=0),(d.subtreeFlags&2064)===0&&(d.flags&2064)===0||Oo||(Oo=!0,xt(mr,function(){return Ce(),null})),b=(d.flags&15990)!==0,(d.subtreeFlags&15990)!==0||b){b=jr.transition,jr.transition=null;var R=rn;rn=1;var ee=Zt;Zt|=4,au.current=null,__(r,d),Ki(d,r),Sl(ad),Vo=!!El,ad=El=null,r.current=d,Gd(d),Yn(),Zt=ee,rn=R,jr.transition=b}else r.current=d;if(Oo&&(Oo=!1,Po=r,uu=v),b=r.pendingLanes,b===0&&(Io=null),ai(d.stateNode),Vs(r,mn()),a!==null)for(h=r.onRecoverableError,d=0;d<a.length;d++)v=a[d],h(v.value,{componentStack:v.stack,digest:v.digest});if(Lo)throw Lo=!1,r=Xi,Xi=null,r;return(uu&1)!==0&&r.tag!==0&&Ce(),b=r.pendingLanes,(b&1)!==0?r===du?Wl++:(Wl=0,du=r):Wl=0,yi(),null}function Ce(){if(Po!==null){var r=yl(uu),a=jr.transition,d=rn;try{if(jr.transition=null,rn=16>r?16:r,Po===null)var h=!1;else{if(r=Po,Po=null,uu=0,(Zt&6)!==0)throw Error(n(331));var v=Zt;for(Zt|=4,Je=r.current;Je!==null;){var b=Je,R=b.child;if((Je.flags&16)!==0){var ee=b.deletions;if(ee!==null){for(var se=0;se<ee.length;se++){var ye=ee[se];for(Je=ye;Je!==null;){var Me=Je;switch(Me.tag){case 0:case 11:case 15:bs(8,Me,b)}var Re=Me.child;if(Re!==null)Re.return=Me,Je=Re;else for(;Je!==null;){Me=Je;var Te=Me.sibling,Xe=Me.return;if(qd(Me),Me===ye){Je=null;break}if(Te!==null){Te.return=Xe,Je=Te;break}Je=Xe}}}var tt=b.alternate;if(tt!==null){var nt=tt.child;if(nt!==null){tt.child=null;do{var ss=nt.sibling;nt.sibling=null,nt=ss}while(nt!==null)}}Je=b}}if((b.subtreeFlags&2064)!==0&&R!==null)R.return=b,Je=R;else e:for(;Je!==null;){if(b=Je,(b.flags&2048)!==0)switch(b.tag){case 0:case 11:case 15:bs(9,b,b.return)}var de=b.sibling;if(de!==null){de.return=b.return,Je=de;break e}Je=b.return}}var le=r.current;for(Je=le;Je!==null;){R=Je;var me=R.child;if((R.subtreeFlags&2064)!==0&&me!==null)me.return=R,Je=me;else e:for(R=le;Je!==null;){if(ee=Je,(ee.flags&2048)!==0)try{switch(ee.tag){case 0:case 11:case 15:Ro(9,ee)}}catch(rt){Ie(ee,ee.return,rt)}if(ee===R){Je=null;break e}var Fe=ee.sibling;if(Fe!==null){Fe.return=ee.return,Je=Fe;break e}Je=ee.return}}if(Zt=v,yi(),ms&&typeof ms.onPostCommitFiberRoot=="function")try{ms.onPostCommitFiberRoot(sn,r)}catch{}h=!0}return h}finally{rn=d,jr.transition=a}}return!1}function ze(r,a,d){a=el(d,a),a=vh(r,a,1),r=In(r,a,1),a=Ps(),r!==null&&(_s(r,1,a),Vs(r,a))}function Ie(r,a,d){if(r.tag===3)ze(r,r,d);else for(;a!==null;){if(a.tag===3){ze(a,r,d);break}else if(a.tag===1){var h=a.stateNode;if(typeof a.type.getDerivedStateFromError=="function"||typeof h.componentDidCatch=="function"&&(Io===null||!Io.has(h))){r=el(d,r),r=Id(a,r,1),a=In(a,r,1),r=Ps(),a!==null&&(_s(a,1,r),Vs(a,r));break}}a=a.return}}function Ze(r,a,d){var h=r.pingCache;h!==null&&h.delete(a),a=Ps(),r.pingedLanes|=r.suspendedLanes&d,Un===r&&(ds&d)===d&&(kn===4||kn===3&&(ds&130023424)===ds&&500>mn()-cu?g(r,0):Yi|=d),Vs(r,a)}function Ge(r,a){a===0&&((r.mode&1)===0?a=1:(a=_r,_r<<=1,(_r&130023424)===0&&(_r=4194304)));var d=Ps();r=wi(r,a),r!==null&&(_s(r,a,d),Vs(r,d))}function cn(r){var a=r.memoizedState,d=0;a!==null&&(d=a.retryLane),Ge(r,d)}function Rt(r,a){var d=0;switch(r.tag){case 13:var h=r.stateNode,v=r.memoizedState;v!==null&&(d=v.retryLane);break;case 19:h=r.stateNode;break;default:throw Error(n(314))}h!==null&&h.delete(a),Ge(r,d)}var qe;qe=function(r,a,d){if(r!==null)if(r.memoizedProps!==a.pendingProps||rr.current)lr=!0;else{if((r.lanes&d)===0&&(a.flags&128)===0)return lr=!1,nu(r,a,d);lr=(r.flags&131072)!==0}else lr=!1,wn&&(a.flags&1048576)!==0&&rh(a,Lc,a.index);switch(a.lanes=0,a.tag){case 2:var h=a.type;Vi(r,a),r=a.pendingProps;var v=qa(a,es.current);$o(a,d),v=qc(null,a,h,r,v,d);var b=da();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,ys(h)?(b=!0,ko(a)):b=!1,a.memoizedState=v.state!==null&&v.state!==void 0?v.state:null,Ya(a),v.updater=Dl,a.stateNode=v,v._reactInternals=a,Md(a,h,r,d),a=tl(null,a,h,!0,b,d)):(a.tag=0,wn&&b&&Tl(a),Hn(null,a,v,d),a=a.child),a;case 16:h=a.elementType;e:{switch(Vi(r,a),r=a.pendingProps,v=h._init,h=v(h._payload),a.type=h,v=a.tag=Hr(h),r=vs(h,r),v){case 0:a=Br(null,a,h,r,d);break e;case 1:a=jh(null,a,h,r,d);break e;case 11:a=Ls(null,a,h,r,d);break e;case 14:a=us(null,a,h,vs(h.type,r),d);break e}throw Error(n(306,h,""))}return a;case 0:return h=a.type,v=a.pendingProps,v=a.elementType===h?v:vs(h,v),Br(r,a,h,v,d);case 1:return h=a.type,v=a.pendingProps,v=a.elementType===h?v:vs(h,v),jh(r,a,h,v,d);case 3:e:{if(Sh(a),r===null)throw Error(n(387));h=a.pendingProps,b=a.memoizedState,v=b.element,Ts(r,a),To(a,h,null,d);var R=a.memoizedState;if(h=R.element,b.isDehydrated)if(b={element:h,isDehydrated:!1,cache:R.cache,pendingSuspenseBoundaries:R.pendingSuspenseBoundaries,transitions:R.transitions},a.updateQueue.baseState=b,a.memoizedState=b,a.flags&256){v=el(Error(n(423)),a),a=tu(r,a,h,d,v);break e}else if(h!==v){v=el(Error(n(424)),a),a=tu(r,a,h,d,v);break e}else for(ir=Di(a.stateNode.containerInfo.firstChild),As=a,wn=!0,Or=null,d=ah(a,null,h,d),a.child=d;d;)d.flags=d.flags&-3|4096,d=d.sibling;else{if(Bi(),h===v){a=Gi(r,a,d);break e}Hn(r,a,h,d)}a=a.child}return a;case 5:return lh(a),r===null&&Oc(a),h=a.type,v=a.pendingProps,b=r!==null?r.memoizedProps:null,R=v.children,Ba(h,v)?R=null:b!==null&&Ba(h,b)&&(a.flags|=32),qi(r,a),Hn(r,a,R,d),a.child;case 6:return r===null&&Oc(a),null;case 13:return Dd(r,a,d);case 4:return Uc(a,a.stateNode.containerInfo),h=a.pendingProps,r===null?a.child=Co(a,null,h,d):Hn(r,a,h,d),a.child;case 11:return h=a.type,v=a.pendingProps,v=a.elementType===h?v:vs(h,v),Ls(r,a,h,v,d);case 7:return Hn(r,a,a.pendingProps,d),a.child;case 8:return Hn(r,a,a.pendingProps.children,d),a.child;case 12:return Hn(r,a,a.pendingProps.children,d),a.child;case 10:e:{if(h=a.type._context,v=a.pendingProps,b=a.memoizedProps,R=v.value,ln(Rl,h._currentValue),h._currentValue=R,b!==null)if(Ar(b.value,R)){if(b.children===v.children&&!rr.current){a=Gi(r,a,d);break e}}else for(b=a.child,b!==null&&(b.return=a);b!==null;){var ee=b.dependencies;if(ee!==null){R=b.child;for(var se=ee.firstContext;se!==null;){if(se.context===h){if(b.tag===1){se=zt(-1,d&-d),se.tag=2;var ye=b.updateQueue;if(ye!==null){ye=ye.shared;var Me=ye.pending;Me===null?se.next=se:(se.next=Me.next,Me.next=se),ye.pending=se}}b.lanes|=d,se=b.alternate,se!==null&&(se.lanes|=d),Bc(b.return,d,a),ee.lanes|=d;break}se=se.next}}else if(b.tag===10)R=b.type===a.type?null:b.child;else if(b.tag===18){if(R=b.return,R===null)throw Error(n(341));R.lanes|=d,ee=R.alternate,ee!==null&&(ee.lanes|=d),Bc(R,d,a),R=b.sibling}else R=b.child;if(R!==null)R.return=b;else for(R=b;R!==null;){if(R===a){R=null;break}if(b=R.sibling,b!==null){b.return=R.return,R=b;break}R=R.return}b=R}Hn(r,a,v.children,d),a=a.child}return a;case 9:return v=a.type,h=a.pendingProps.children,$o(a,d),v=Pr(v),h=h(v),a.flags|=1,Hn(r,a,h,d),a.child;case 14:return h=a.type,v=vs(h,a.pendingProps),v=vs(h.type,v),us(r,a,h,v,d);case 15:return ni(r,a,a.type,a.pendingProps,d);case 17:return h=a.type,v=a.pendingProps,v=a.elementType===h?v:vs(h,v),Vi(r,a),a.tag=1,ys(h)?(r=!0,ko(a)):r=!1,$o(a,d),Td(a,h,v),Md(a,h,v,d),tl(null,a,h,!0,r,d);case 19:return Bd(r,a,d);case 22:return Wi(r,a,d)}throw Error(n(156,a.tag))};function xt(r,a){return Xs(r,a)}function Nn(r,a,d,h){this.tag=r,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 Qt(r,a,d,h){return new Nn(r,a,d,h)}function Ds(r){return r=r.prototype,!(!r||!r.isReactComponent)}function Hr(r){if(typeof r=="function")return Ds(r)?1:0;if(r!=null){if(r=r.$$typeof,r===F)return 11;if(r===P)return 14}return 2}function fs(r,a){var d=r.alternate;return d===null?(d=Qt(r.tag,a,r.key,r.mode),d.elementType=r.elementType,d.type=r.type,d.stateNode=r.stateNode,d.alternate=r,r.alternate=d):(d.pendingProps=a,d.type=r.type,d.flags=0,d.subtreeFlags=0,d.deletions=null),d.flags=r.flags&14680064,d.childLanes=r.childLanes,d.lanes=r.lanes,d.child=r.child,d.memoizedProps=r.memoizedProps,d.memoizedState=r.memoizedState,d.updateQueue=r.updateQueue,a=r.dependencies,d.dependencies=a===null?null:{lanes:a.lanes,firstContext:a.firstContext},d.sibling=r.sibling,d.index=r.index,d.ref=r.ref,d}function Fo(r,a,d,h,v,b){var R=2;if(h=r,typeof r=="function")Ds(r)&&(R=1);else if(typeof r=="string")R=5;else e:switch(r){case Y:return Hl(d.children,v,b,a);case Z:R=8,v|=8;break;case re:return r=Qt(12,d,a,v|2),r.elementType=re,r.lanes=b,r;case C:return r=Qt(13,d,a,v),r.elementType=C,r.lanes=b,r;case N:return r=Qt(19,d,a,v),r.elementType=N,r.lanes=b,r;case ne:return Mh(d,v,b,a);default:if(typeof r=="object"&&r!==null)switch(r.$$typeof){case ie:R=10;break e;case ue:R=9;break e;case F:R=11;break e;case P:R=14;break e;case D:R=16,h=null;break e}throw Error(n(130,r==null?r:typeof r,""))}return a=Qt(R,d,a,v),a.elementType=r,a.type=h,a.lanes=b,a}function Hl(r,a,d,h){return r=Qt(7,r,h,a),r.lanes=d,r}function Mh(r,a,d,h){return r=Qt(22,r,h,a),r.elementType=ne,r.lanes=d,r.stateNode={isHidden:!1},r}function p_(r,a,d){return r=Qt(6,r,null,a),r.lanes=d,r}function g_(r,a,d){return a=Qt(4,r.children!==null?r.children:[],r.key,a),a.lanes=d,a.stateNode={containerInfo:r.containerInfo,pendingChildren:null,implementation:r.implementation},a}function A0(r,a,d,h,v){this.tag=a,this.containerInfo=r,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=Xr(0),this.expirationTimes=Xr(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Xr(0),this.identifierPrefix=h,this.onRecoverableError=v,this.mutableSourceEagerHydrationData=null}function y_(r,a,d,h,v,b,R,ee,se){return r=new A0(r,a,d,ee,se),a===1?(a=1,b===!0&&(a|=8)):a=0,b=Qt(3,null,null,a),r.current=b,b.stateNode=r,b.memoizedState={element:h,isDehydrated:d,cache:null,transitions:null,pendingSuspenseBoundaries:null},Ya(b),r}function T0(r,a,d){var h=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:X,key:h==null?null:""+h,children:r,containerInfo:a,implementation:d}}function Xg(r){if(!r)return So;r=r._reactInternals;e:{if($t(r)!==r||r.tag!==1)throw Error(n(170));var a=r;do{switch(a.tag){case 3:a=a.stateNode.context;break e;case 1:if(ys(a.type)){a=a.stateNode.__reactInternalMemoizedMergedChildContext;break e}}a=a.return}while(a!==null);throw Error(n(171))}if(r.tag===1){var d=r.type;if(ys(d))return ud(r,d,a)}return a}function Zg(r,a,d,h,v,b,R,ee,se){return r=y_(d,h,!0,r,v,b,R,ee,se),r.context=Xg(null),d=r.current,h=Ps(),v=Zi(d),b=zt(h,v),b.callback=a??null,In(d,b,v),r.current.lanes=v,_s(r,v,h),Vs(r,h),r}function Rh(r,a,d,h){var v=a.current,b=Ps(),R=Zi(v);return d=Xg(d),a.context===null?a.context=d:a.pendingContext=d,a=zt(b,R),a.payload={element:r},h=h===void 0?null:h,h!==null&&(a.callback=h),r=In(v,a,R),r!==null&&(qr(r,v,R,b),Ja(r,v,R)),R}function Lh(r){if(r=r.current,!r.child)return null;switch(r.child.tag){case 5:return r.child.stateNode;default:return r.child.stateNode}}function Qg(r,a){if(r=r.memoizedState,r!==null&&r.dehydrated!==null){var d=r.retryLane;r.retryLane=d!==0&&d<a?d:a}}function w_(r,a){Qg(r,a),(r=r.alternate)&&Qg(r,a)}function M0(){return null}var ey=typeof reportError=="function"?reportError:function(r){console.error(r)};function v_(r){this._internalRoot=r}Ih.prototype.render=v_.prototype.render=function(r){var a=this._internalRoot;if(a===null)throw Error(n(409));Rh(r,a,null,null)},Ih.prototype.unmount=v_.prototype.unmount=function(){var r=this._internalRoot;if(r!==null){this._internalRoot=null;var a=r.containerInfo;Do(function(){Rh(null,r,null,null)}),a[Fi]=null}};function Ih(r){this._internalRoot=r}Ih.prototype.unstable_scheduleHydration=function(r){if(r){var a=Ma();r={blockedOn:null,target:r,priority:a};for(var d=0;d<yr.length&&a!==0&&a<yr[d].priority;d++);yr.splice(d,0,r),d===0&&tr(r)}};function x_(r){return!(!r||r.nodeType!==1&&r.nodeType!==9&&r.nodeType!==11)}function Oh(r){return!(!r||r.nodeType!==1&&r.nodeType!==9&&r.nodeType!==11&&(r.nodeType!==8||r.nodeValue!==" react-mount-point-unstable "))}function ty(){}function R0(r,a,d,h,v){if(v){if(typeof h=="function"){var b=h;h=function(){var ye=Lh(R);b.call(ye)}}var R=Zg(a,h,r,0,null,!1,!1,"",ty);return r._reactRootContainer=R,r[Fi]=R.current,Tr(r.nodeType===8?r.parentNode:r),Do(),R}for(;v=r.lastChild;)r.removeChild(v);if(typeof h=="function"){var ee=h;h=function(){var ye=Lh(se);ee.call(ye)}}var se=y_(r,0,!1,null,null,!1,!1,"",ty);return r._reactRootContainer=se,r[Fi]=se.current,Tr(r.nodeType===8?r.parentNode:r),Do(function(){Rh(a,se,d,h)}),se}function Ph(r,a,d,h,v){var b=d._reactRootContainer;if(b){var R=b;if(typeof v=="function"){var ee=v;v=function(){var se=Lh(R);ee.call(se)}}Rh(a,R,r,v)}else R=R0(d,a,r,v,h);return Lh(R)}$i=function(r){switch(r.tag){case 3:var a=r.stateNode;if(a.current.memoizedState.isDehydrated){var d=Tn(a.pendingLanes);d!==0&&(mo(a,d|1),Vs(a,mn()),(Zt&6)===0&&(wa=mn()+500,yi()))}break;case 13:Do(function(){var h=wi(r,1);if(h!==null){var v=Ps();qr(h,r,1,v)}}),w_(r,1)}},gr=function(r){if(r.tag===13){var a=wi(r,134217728);if(a!==null){var d=Ps();qr(a,r,134217728,d)}w_(r,134217728)}},Es=function(r){if(r.tag===13){var a=Zi(r),d=wi(r,a);if(d!==null){var h=Ps();qr(d,r,a,h)}w_(r,a)}},Ma=function(){return rn},Er=function(r,a){var d=rn;try{return rn=r,a()}finally{rn=d}},Nr=function(r,a,d){switch(a){case"input":if(Se(r,d),a=d.name,d.type==="radio"&&a!=null){for(d=r;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!==r&&h.form===r.form){var v=Tc(h);if(!v)throw Error(n(90));_t(h),Se(h,v)}}}break;case"textarea":tn(r,d);break;case"select":a=d.value,a!=null&&De(r,!!d.multiple,a,!1)}},st=_u,ut=Do;var L0={usingClientEntryPoint:!1,Events:[Wa,pi,Tc,Ve,He,_u]},Xd={findFiberByHostInstance:sa,bundleType:0,version:"18.3.1",rendererPackageName:"react-dom"},I0={bundleType:Xd.bundleType,version:Xd.version,rendererPackageName:Xd.rendererPackageName,rendererConfig:Xd.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:M.ReactCurrentDispatcher,findHostInstanceByFiber:function(r){return r=Cs(r),r===null?null:r.stateNode},findFiberByHostInstance:Xd.findFiberByHostInstance||M0,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 Dh=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!Dh.isDisabled&&Dh.supportsFiber)try{sn=Dh.inject(I0),ms=Dh}catch{}}return Vr.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=L0,Vr.createPortal=function(r,a){var d=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!x_(a))throw Error(n(200));return T0(r,a,null,d)},Vr.createRoot=function(r,a){if(!x_(r))throw Error(n(299));var d=!1,h="",v=ey;return a!=null&&(a.unstable_strictMode===!0&&(d=!0),a.identifierPrefix!==void 0&&(h=a.identifierPrefix),a.onRecoverableError!==void 0&&(v=a.onRecoverableError)),a=y_(r,1,!1,null,null,d,!1,h,v),r[Fi]=a.current,Tr(r.nodeType===8?r.parentNode:r),new v_(a)},Vr.findDOMNode=function(r){if(r==null)return null;if(r.nodeType===1)return r;var a=r._reactInternals;if(a===void 0)throw typeof r.render=="function"?Error(n(188)):(r=Object.keys(r).join(","),Error(n(268,r)));return r=Cs(a),r=r===null?null:r.stateNode,r},Vr.flushSync=function(r){return Do(r)},Vr.hydrate=function(r,a,d){if(!Oh(a))throw Error(n(200));return Ph(null,r,a,!0,d)},Vr.hydrateRoot=function(r,a,d){if(!x_(r))throw Error(n(405));var h=d!=null&&d.hydratedSources||null,v=!1,b="",R=ey;if(d!=null&&(d.unstable_strictMode===!0&&(v=!0),d.identifierPrefix!==void 0&&(b=d.identifierPrefix),d.onRecoverableError!==void 0&&(R=d.onRecoverableError)),a=Zg(a,null,r,1,d??null,v,!1,b,R),r[Fi]=a.current,Tr(r),h)for(r=0;r<h.length;r++)d=h[r],v=d._getVersion,v=v(d._source),a.mutableSourceEagerHydrationData==null?a.mutableSourceEagerHydrationData=[d,v]:a.mutableSourceEagerHydrationData.push(d,v);return new Ih(a)},Vr.render=function(r,a,d){if(!Oh(a))throw Error(n(200));return Ph(null,r,a,!1,d)},Vr.unmountComponentAtNode=function(r){if(!Oh(r))throw Error(n(40));return r._reactRootContainer?(Do(function(){Ph(null,null,r,!1,function(){r._reactRootContainer=null,r[Fi]=null})}),!0):!1},Vr.unstable_batchedUpdates=_u,Vr.unstable_renderSubtreeIntoContainer=function(r,a,d,h){if(!Oh(d))throw Error(n(200));if(r==null||r._reactInternals===void 0)throw Error(n(38));return Ph(r,a,d,!1,h)},Vr.version="18.3.1-next-f1338f8080-20240426",Vr}var cy;function jv(){if(cy)return S_.exports;cy=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(),S_.exports=q0(),S_.exports}var uy;function H0(){if(uy)return Fh;uy=1;var e=jv();return Fh.createRoot=e.createRoot,Fh.hydrateRoot=e.hydrateRoot,Fh}var V0=H0();const G0=hg(V0);async function Sv(e){const t=String(e||"");if(!t)return!1;try{return await navigator.clipboard.writeText(t),!0}catch{try{const n=document.createElement("textarea");return n.value=t,n.style.position="fixed",n.style.left="-9999px",document.body.appendChild(n),n.select(),document.execCommand("copy"),document.body.removeChild(n),!0}catch{return!1}}}const K0=3,Y0=Number.MAX_SAFE_INTEGER;function kv(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Nv(e){return Array.isArray(e)}function J0(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 X0(e){if(e==null)return"";if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}}function Cu({kind:e,children:t}){return s.jsx("span",{className:`json-token ${e}`,children:t})}function Z0(e){const t=JSON.stringify(e.value),n=t.length>96||t.includes("\\n")||t.includes("\\r")||t.includes("\\t"),[i,o]=m.useState(!n||e.expansion_mode==="unfolded");return m.useEffect(()=>{n&&o(e.expansion_mode==="unfolded")},[n,e.expansion_mode,e.expansion_version]),n?s.jsxs("span",{className:`json-string ${i?"open":"collapsed"}`,children:[s.jsx("button",{type:"button",className:"json-string__toggle",onClick:()=>o(l=>!l),"aria-label":i?"Collapse string value":"Expand string value","aria-expanded":i,children:i?"▾":"▸"}),i?s.jsx("span",{className:"json-token string json-string__value",children:t}):s.jsxs("button",{type:"button",className:"json-string__preview",onClick:()=>o(!0),"aria-label":"Expand string value",children:[s.jsx("span",{className:"json-token string json-string__preview_text",children:t}),s.jsx("span",{className:"json-string__suffix",children:"(...)"})]})]}):s.jsx(Cu,{kind:"string",children:t})}function Q0(e,t,n){return e===null?s.jsx(Cu,{kind:"null",children:"null"}):typeof e=="string"?s.jsx(Z0,{value:e,expansion_mode:t,expansion_version:n}):typeof e=="number"?s.jsx(Cu,{kind:"number",children:String(e)}):typeof e=="boolean"?s.jsx(Cu,{kind:"boolean",children:e?"true":"false"}):s.jsx(Cu,{kind:"string",children:JSON.stringify(String(e))})}function ej(e){return Nv(e)?e.length===1?"1 item":`${e.length} items`:kv(e)?Object.keys(e).length===1?"1 key":`${Object.keys(e).length} keys`:""}function Cv(e){const{label:t,value:n,depth:i,collapse_after_depth:o,expansion_mode:l,expansion_version:u,trailing_comma:c}=e,f=i*14,_=kv(n),p=Nv(n),y=_||p,w=i<o,[x,S]=m.useState(w);m.useEffect(()=>{S(w)},[w,u]);const j=t?s.jsxs(s.Fragment,{children:[s.jsx(Cu,{kind:"key",children:JSON.stringify(t)}),": "]}):null;if(!y)return s.jsxs("div",{className:"json-viewer__line",style:{paddingLeft:f},children:[j,Q0(n,l,u),c?",":""]});const E=p?"[":"{",A=p?"]":"}",L=ej(n),O=x?`${E}`:`${E}…${A}${L?` (${L})`:""}`,M=p?n.map((H,X)=>({key:String(X),label:void 0,value:H})):Object.entries(n).map(([H,X])=>({key:H,label:H,value:X}));return s.jsxs("details",{className:"json-viewer__details",open:x,onToggle:H=>S(H.currentTarget.open),children:[s.jsxs("summary",{className:"json-viewer__summary",style:{paddingLeft:f},children:[j,s.jsx("span",{className:"json-viewer__caret","aria-hidden":"true",children:x?"▾":"▸"}),s.jsx("span",{className:"json-viewer__punct",children:O}),!x&&c?s.jsx("span",{className:"json-viewer__punct",children:","}):null]}),x?s.jsx("div",{className:"json-viewer__children",children:M.length===0?s.jsxs("div",{className:"json-viewer__line",style:{paddingLeft:f},children:[s.jsx("span",{className:"json-viewer__punct",children:A}),c?",":""]}):s.jsxs(s.Fragment,{children:[M.map((H,X)=>{const Y=X===M.length-1;return s.jsx(Cv,{label:H.label,value:H.value,depth:i+1,collapse_after_depth:o,expansion_mode:l,expansion_version:u,trailing_comma:!Y},`${i}:${t||"root"}:${H.key}`)}),s.jsxs("div",{className:"json-viewer__line",style:{paddingLeft:f},children:[s.jsx("span",{className:"json-viewer__punct",children:A}),c?",":""]})]})}):null]})}function Ev(e){const{value:t,className:n,showCopy:i=!0}=e,[o,l]=m.useState({mode:"folded",version:0}),u=typeof e.collapseAfterDepth=="number"&&(Number.isFinite(e.collapseAfterDepth)||e.collapseAfterDepth===1/0)&&e.collapseAfterDepth>=0?e.collapseAfterDepth===1/0?Number.MAX_SAFE_INTEGER:Math.trunc(e.collapseAfterDepth):K0,c=o.mode==="unfolded"?Y0:u,f=m.useMemo(()=>typeof t=="string"?J0(t):t,[t]),_=m.useMemo(()=>X0(t),[t]),p=["json-viewer",n].filter(Boolean).join(" ");m.useEffect(()=>{l(w=>({mode:"folded",version:w.version+1}))},[f]);const y=()=>{l(w=>({mode:w.mode==="unfolded"?"folded":"unfolded",version:w.version+1}))};return s.jsxs("div",{className:p,children:[s.jsxs("div",{className:"json-viewer__toolbar",children:[s.jsx("button",{type:"button",className:"json-viewer__btn json-viewer__toggle-all",onClick:y,"aria-expanded":o.mode==="unfolded",children:o.mode==="unfolded"?"Fold all":"Unfold all"}),i?s.jsx("button",{type:"button",className:"json-viewer__btn json-viewer__copy",onClick:()=>void Sv(_),children:"Copy"}):null]}),s.jsx("div",{className:"json-viewer__tree",role:"tree","aria-label":"JSON viewer",children:s.jsx(Cv,{value:f,depth:0,collapse_after_depth:c,expansion_mode:o.mode,expansion_version:o.version,trailing_comma:!1})})]})}function C_(e){const t=[],n=String(e??"");let i=0,o="";const l=()=>{o&&(t.push(o),o="")};for(;i<n.length;){const u=n[i];if(u==="`"){const c=n.indexOf("`",i+1);if(c!==-1){l(),t.push(s.jsx("code",{children:n.slice(i+1,c)},`code:${i}`)),i=c+1;continue}}if(u==="*"&&n[i+1]==="*"){const c=n.indexOf("**",i+2);if(c!==-1){l(),t.push(s.jsx("strong",{children:n.slice(i+2,c)},`bold:${i}`)),i=c+2;continue}}o+=u,i+=1}return l(),t}function tj(e){return String(e??"").replace(/\r\n/g,`
|
|
41
|
+
`).replace(/\r/g,`
|
|
42
|
+
`).split(`
|
|
43
|
+
`)}function nj({text:e,className:t}){const n=tj(e),i=[];let o=0;for(;o<n.length;){const u=n[o],c=String(u??"");if(!c.trim()){o+=1;continue}if(c.trim().startsWith("```")){const w=c.trim().replace(/```/g,"").trim(),x=[];for(o+=1;o<n.length&&!String(n[o]??"").trim().startsWith("```");)x.push(String(n[o]??"")),o+=1;o<n.length&&(o+=1);const S=x.join(`
|
|
44
|
+
`);i.push(s.jsx("pre",{className:"mf-md_pre",children:s.jsx("code",{className:w?`language-${w}`:void 0,children:S})},`pre:${o}`));continue}const f=c.match(/^(#{1,3})\s+(.*)$/);if(f){const y=f[1].length,w=f[2]||"",x=C_(w);y===1?i.push(s.jsx("h1",{children:x},`h1:${o}`)):y===2?i.push(s.jsx("h2",{children:x},`h2:${o}`)):i.push(s.jsx("h3",{children:x},`h3:${o}`)),o+=1;continue}const _=y=>{const w=y.trimStart();return w.startsWith("- ")||w.startsWith("* ")};if(_(c)){const y=[];for(;o<n.length&&_(String(n[o]??""));){const w=String(n[o]??"").trimStart();y.push(w.slice(2)),o+=1}i.push(s.jsx("ul",{className:"mf-md_ul",children:y.map((w,x)=>s.jsx("li",{children:C_(w)},`li:${o}:${x}`))},`ul:${o}`));continue}const p=[];for(;o<n.length&&String(n[o]??"").trim();)p.push(String(n[o]??"")),o+=1;i.push(s.jsx("p",{className:"mf-md_p",children:p.map((y,w)=>s.jsxs(ve.Fragment,{children:[C_(y),w<p.length-1?s.jsx("br",{}):null]},`pl:${o}:${w}`))},`p:${o}`))}const l=["mf-md",t].filter(Boolean).join(" ");return s.jsx("div",{className:l,children:i})}const dy="observe";function kr(e){return!e||typeof e!="object"?null:e}function xp(e,t){const n=String(e||"").replace(/\s+/g," ").trim();return n?n.length<=t?n:`${n.slice(0,Math.max(0,t-1)).trimEnd()}…`:""}function fy(e){const t=kr(e);if(!t)return null;const n=typeof t.role=="string"?String(t.role).trim():"",i=typeof t.content=="string"?String(t.content):"";if(!n||i==="")return null;const o=typeof t.name=="string"?String(t.name).trim():"";return{role:n,content:i,name:o||void 0}}function sj(e){if(Array.isArray(e)){if(e.length===0)return null;const n=[];for(const i of e){const o=fy(i);if(!o)return null;n.push(o)}return n}const t=fy(e);return t?[t]:null}function rj(e){const t=String(e||"").trim();if(!t)return null;const n=t[0],i=t[t.length-1];if(!(n==="{"&&i==="}"||n==="["&&i==="]"))return null;try{const l=JSON.parse(t);return l&&typeof l=="object"||Array.isArray(l)?l:null}catch{return null}}function ij(e){const t=String(e||"");return t.trim()?!!(t.includes("```")||/\n\s*#{1,3}\s+/.test(t)||/\n\s*[-*]\s+/.test(t)||/\n\s*\d+[\.\)]\s+/.test(t)||t.includes("**")||t.includes("`")):!1}function hy({text:e}){const t=String(e||""),n=rj(t);if(n!==null)return s.jsx(Ev,{value:n});const i=t.trim();return i.startsWith("{")||i.startsWith("[")?s.jsx("pre",{className:"run-details-output",children:t||"(none)"}):t.includes(`
|
|
45
|
+
`)||ij(t)?s.jsx("div",{className:"run-details-output",children:s.jsx(nj,{text:t})}):s.jsx("pre",{className:"run-details-output",children:t||"(none)"})}function $v({value:e}){if(e==null)return s.jsx("pre",{className:"run-details-output",children:"(none)"});const t=sj(e);return t?s.jsx("div",{className:"mf-msg-list",children:t.map((n,i)=>s.jsxs("div",{className:"mf-msg",children:[s.jsxs("div",{className:"mf-msg-meta",children:[s.jsx("span",{className:`mf-msg-role ${n.role}`,children:n.role}),n.name?s.jsx("span",{className:"mf-msg-name",children:n.name}):null]}),s.jsx("div",{className:"mf-msg-content",children:s.jsx(hy,{text:n.content})})]},`${n.role}:${i}`))}):typeof e=="string"?s.jsx(hy,{text:e}):s.jsx(Ev,{value:e})}function Av(e){const t=e.effect;return!t||typeof t!="object"?null:t}function _l(e){const t=Av(e);return(t&&typeof t.type=="string"?t.type:"")||"effect"}function zm(e){const t=Av(e),n=t==null?void 0:t.payload;return!n||typeof n!="object"?null:n}function mg(e){const t=e.result;return!t||typeof t!="object"?null:t}function Tv(e){if(_l(e)!=="tool_calls")return[];const n=mg(e),i=n&&Array.isArray(n.results)?n.results:null;if(!i)return[];const o=[];for(const l of i){const u=kr(l);if(!u)continue;const c=typeof u.name=="string"?u.name.trim():"";c&&o.push({call_id:typeof u.call_id=="string"?u.call_id:void 0,name:c,success:!!u.success,output:u.output,error:u.error})}return o}function Mv(e){if(_l(e)!=="tool_calls")return[];const n=zm(e),i=n&&Array.isArray(n.tool_calls)?n.tool_calls:null;if(!i)return[];const o=[];for(const l of i){const u=kr(l);if(!u)continue;const c=typeof u.name=="string"?u.name.trim():"";if(!c)continue;const f=kr(u.args)||kr(u.arguments)||{};o.push({call_id:typeof u.call_id=="string"?u.call_id:void 0,name:c,args:f})}return o}function Bm(e){const t=e.error;if(typeof t=="string")return t.trim();const n=kr(t);if(n){const i=typeof n.message=="string"?n.message.trim():"",o=typeof n.stack=="string"?n.stack.trim():"";return i||o||""}return""}function Rv(e){if(!e)return"";const t=e.reasoning;if(typeof t=="string")return t.trim();const n=kr(t);return n&&typeof n.text=="string"?n.text.trim():""}function Lv(e){const t=_l(e),n=zm(e),i=mg(e),o=(l,u)=>{const c=String(l||"").replace(/\s+/g," ").trim();return c?c.length<=u?c:`${c.slice(0,Math.max(0,u-1)).trimEnd()}…`:""};if(t==="llm_call"){const l=i==null?void 0:i.content,u=typeof l=="string"?l.replace(/\s+/g," ").trim():"",c=Rv(i),f=Array.isArray(i==null?void 0:i.tool_calls)?i.tool_calls:null,p=!!(f&&f.length>0)?c||u:u||c;return o(p,220)}if(t==="tool_calls"){const l=i&&Array.isArray(i.results)?i.results:null;if(!l)return"";const u=l.filter(c=>{var f;return((f=kr(c))==null?void 0:f.success)===!1});return u.length>0?`${u.length} tool call(s) failed`:`${l.length} tool call(s) executed`}return t==="ask_user"&&n&&typeof n.prompt=="string"?String(n.prompt).trim():""}function gm(e){const t=typeof e.status=="string"?e.status:"unknown";return t==="failed"||Bm(e.step)?"failed":t}function oj(e){const t=e.map(n=>gm(n));return t.some(n=>n==="failed")?"failed":t.some(n=>n==="waiting")?"waiting":t.some(n=>n==="running")?"running":"completed"}function E_(e){return e.filter(t=>!t.hidden)}function aj(e){const t=_l(e),n=Bm(e);return E_(t==="llm_call"?[{id:"system",label:"System"},{id:"user",label:"User"},{id:"tools",label:"Tools"},{id:"response",label:"Response"},{id:"reasoning",label:"Reasoning"},{id:"errors",label:"Errors",hidden:!n},{id:"raw",label:"Raw"}]:t==="tool_calls"?[{id:"tools",label:"Tools"},{id:"errors",label:"Errors",hidden:!n},{id:"raw",label:"Raw"}]:[{id:"errors",label:"Errors",hidden:!n},{id:"raw",label:"Raw"}])}function lj(e){const t=_l(e);return t==="llm_call"?"user":t==="tool_calls"?"tools":Bm(e)?"errors":"raw"}function cj(e){const t=new Map,n=zm(e),i=n&&Array.isArray(n.tools)?n.tools:null;if(!i)return t;for(const o of i){const l=kr(o);if(!l)continue;const u=typeof l.name=="string"?l.name.trim():"";if(!u)continue;const f=(Array.isArray(l.parameters)?l.parameters:[]).map(_=>{const p=kr(_);return(p&&typeof p.id=="string"?p.id.trim():"")||""}).filter(Boolean);t.set(u,f)}return t}function Iv(e,t,n){const i=Object.keys(t||{}),o=n&&n.length?n.filter(f=>i.includes(f)):[],l=i.filter(f=>!o.includes(f)).sort(),u=[...o,...l],c=u.slice(0,5).map(f=>{const _=t[f];return typeof _=="string"?`${f}=${JSON.stringify(xp(_,42))}`:typeof _=="number"||typeof _=="boolean"?`${f}=${String(_)}`:_==null?`${f}=null`:`${f}=${xp(JSON.stringify(_),42)}`});return`${e}(${c.join(", ")}${u.length>5?", …":""})`}function uj(e){const t=e.ts?String(e.ts):"";if(!t)return"";try{const n=new Date(t);return Number.isFinite(n.getTime())?n.toLocaleTimeString():""}catch{return""}}function $_({item:e,label:t,toolDefs:n,defaultOpen:i=!1}){const o=e.step,l=_l(o),u=aj(o),c=lj(o),[f,_]=m.useState(c),[p,y]=m.useState(!!i),w=zm(o),x=mg(o),S=Bm(o),j=uj(e),E=e.nodeId?String(e.nodeId):"",A=e.runId?String(e.runId):"",L=l==="tool_calls"?Mv(o):[],O=l==="tool_calls"?Tv(o):[],M=L.map(ie=>Iv(ie.name,ie.args,n.get(ie.name)||null)),X=(()=>{if(f==="raw")return o;if(f==="errors")return S||null;if(l==="llm_call"){const ie=w||{},ue=typeof ie.system_prompt=="string"?String(ie.system_prompt):"",F=typeof ie.prompt=="string"?String(ie.prompt):"",C=kr(x==null?void 0:x.metadata),N=C?kr(C._runtime_observability):null,P=N?kr(N.llm_generate_kwargs):null,D=P&&Array.isArray(P.messages)?P.messages:null,ne=C?kr(C._provider_request):null,B=ne?kr(ne.payload):null,z=B&&Array.isArray(B.messages)?B.messages:null,G=Array.isArray(ie.messages)?ie.messages:[],T=D||z||G,Q=T.filter(J=>String((J==null?void 0:J.role)||"").trim()==="system"),K=T.filter(J=>String((J==null?void 0:J.role)||"").trim()==="user");if(f==="system"){const J=[],oe=ue.trim(),fe=!!oe&&Q.some(_e=>typeof(_e==null?void 0:_e.content)=="string"&&String(_e.content).trim()===oe);return oe&&!fe&&J.push({role:"system",name:"system_prompt",content:ue}),J.push(...Q),J}if(f==="user"){const J=[],oe=F.trim(),fe=!!oe&&K.some(_e=>typeof(_e==null?void 0:_e.content)=="string"&&String(_e.content).trim()===oe);return oe&&!fe&&J.push({role:"user",name:"prompt",content:F}),J.push(...K),J}if(f==="tools")return ie.tools||[];if(f==="response"){const J=x==null?void 0:x.content;if(typeof J=="string"&&J.trim())return J;const oe=x==null?void 0:x.output;if(oe!==void 0)return oe;const fe=Array.isArray(x==null?void 0:x.tool_calls)?x.tool_calls:null;return fe&&fe.length?{tool_calls:fe}:x}if(f==="reasoning")return Rv(x)||null}return l==="tool_calls"&&f==="tools"?{tool_calls:L,tool_signatures:M,results:O}:o})(),Y=Lv(o),Z=gm(e),re=Z==="completed"?"OK":Z==="failed"?"ERROR":Z==="waiting"?"WAITING":Z.toUpperCase();return s.jsxs("details",{className:`agent-trace-entry ${Z}`,open:p,onToggle:ie=>y(ie.currentTarget.open),children:[s.jsxs("summary",{className:"agent-trace-summary",children:[s.jsx("span",{className:`agent-trace-status ${Z}`,children:re}),s.jsx("span",{className:"agent-cycle-stage","data-stage":t,children:t}),s.jsx("span",{className:"agent-trace-kind",children:l}),j?s.jsx("span",{className:"agent-trace-node",children:j}):null,E?s.jsx("span",{className:"agent-trace-node",children:E}):null,A?s.jsx("span",{className:"agent-trace-run",children:A}):null]}),Y?s.jsx("div",{className:"agent-trace-preview",children:Y}):null,s.jsxs("div",{className:"agent-trace-body",children:[s.jsx("div",{className:"agent-trace-tabs",children:u.map(ie=>s.jsx("button",{type:"button",className:`agent-trace-tab ${ie.id===f?"active":""}`,onClick:()=>_(ie.id),children:ie.label},ie.id))}),s.jsx($v,{value:X})]})]})}function dj({acts:e}){const t=e.flatMap(l=>Tv(l.step)),n=t.filter(l=>l.success===!1),i=n.length?`${n.length} error(s)`:t.length?`${t.length} tool result(s)`:"(none)",o=n.length?"failed":"completed";return s.jsxs("details",{className:`agent-trace-entry ${o}`,open:!1,children:[s.jsxs("summary",{className:"agent-trace-summary",children:[s.jsx("span",{className:`agent-trace-status ${o}`,children:n.length?"ERROR":"OK"}),s.jsx("span",{className:"agent-cycle-stage","data-stage":dy,children:dy}),s.jsx("span",{className:"agent-trace-kind",children:"OBSERVATIONS"}),s.jsx("span",{className:"agent-trace-preview-inline",children:i})]}),s.jsx("div",{className:"agent-observe-body",children:t.length===0?s.jsx("div",{className:"agent-observe-empty",children:"(no tool results)"}):s.jsx("div",{className:"agent-observe-results",children:t.map((l,u)=>{const c=l.success?"completed":"failed",f=l.success?"OK":"ERROR",_=l.success?l.output:l.error??l.output;return s.jsxs("details",{className:`agent-observe-result ${c}`,open:!1,children:[s.jsxs("summary",{className:"agent-observe-summary",children:[s.jsx("span",{className:`agent-trace-status ${c}`,children:f}),s.jsx("span",{className:"agent-observe-name",children:l.name}),l.call_id?s.jsx("span",{className:"agent-observe-callid",children:l.call_id}):null]}),s.jsx($v,{value:_})]},`${l.name}:${l.call_id||""}:${u}`)})})})]})}function fj({items:e,subRunId:t,title:n,subtitle:i,onOpenSubRun:o,defaultOpenLatest:l=!0}){const u=m.useMemo(()=>{const y=Array.isArray(e)?e.slice():[];return y.sort((w,x)=>{const S=w.ts?new Date(w.ts).getTime():NaN,j=x.ts?new Date(x.ts).getTime():NaN;return Number.isFinite(S)&&Number.isFinite(j)?S-j:0}),y},[e]),c=m.useMemo(()=>{const y=[];let w=null,x=0;for(const S of u){const j=_l(S.step);if(j==="llm_call"){x+=1,w={id:`cycle:${S.runId}:${x}:${S.ts||""}`,index:x,items:[S],think:S,acts:[],others:[],status:gm(S),ts:S.ts},y.push(w);continue}w||(x+=1,w={id:`cycle:${S.runId}:${x}:${S.ts||""}`,index:x,items:[],think:null,acts:[],others:[],status:gm(S),ts:S.ts},y.push(w)),w.items.push(S),j==="tool_calls"?w.acts.push(S):w.others.push(S),w.status=oj(w.items)}return y},[u]),f=typeof n=="string"&&n.trim()?n.trim():"Agent calls",_=typeof i=="string"&&i.trim()?i.trim():"Live per-effect trace (LLM/tool calls).",p=typeof t=="string"?t.trim():"";return s.jsxs("div",{className:"agent-trace-panel",children:[s.jsxs("div",{className:"agent-trace-header",children:[s.jsx("div",{className:"agent-trace-title",children:f}),s.jsxs("div",{className:"agent-trace-subtitle",children:[_,p?s.jsxs("span",{className:"agent-trace-subrun",children:[" ","sub_run_id: ",p,s.jsx("button",{type:"button",className:"agent-trace-copy",onClick:y=>{y.stopPropagation(),Sv(p)},title:`Copy sub_run_id: ${p}`,"aria-label":"Copy sub run id",children:"⧉"}),o?s.jsx("button",{type:"button",className:"agent-trace-open",onClick:y=>{y.stopPropagation(),o()},title:"Open sub-run",children:"Open"}):null]}):null]})]}),u.length===0?s.jsx("div",{className:"agent-trace-empty",children:"No trace entries yet."}):s.jsxs("div",{className:"agent-cycle-list",children:[s.jsxs("div",{className:"agent-cycle-meta",children:[c.length," cycle(s)"]}),c.map(y=>{const w=y.status,x=w==="completed"?"OK":w==="failed"?"ERROR":w==="waiting"?"WAITING":w.toUpperCase(),S=w==="completed"?"✓":w==="failed"?"✗":"",j=S?`${S} ${x}`:x,E=y.think?Lv(y.think.step):"",A=y.think?cj(y.think.step):new Map,O=y.acts.flatMap(H=>Mv(H.step)).map(H=>Iv(H.name,H.args,A.get(H.name)||null)),M=l&&y.index===c.length;return s.jsxs("details",{className:`agent-cycle ${w}`,open:M,children:[s.jsxs("summary",{className:"agent-cycle-summary",children:[s.jsx("span",{className:`agent-trace-status ${w}`,children:j}),s.jsx("span",{className:"agent-cycle-label",children:"cycle"}),s.jsxs("span",{className:"agent-cycle-index",children:["#",y.index]}),O.length?s.jsxs("span",{className:"agent-trace-badges",children:[O.slice(0,3).map(H=>s.jsx("span",{className:"run-metric-badge metric-tool",title:H,children:xp(H,62)},H)),O.length>3?s.jsxs("span",{className:"run-metric-badge metric-tool",children:["+",O.length-3]}):null]}):null,s.jsx("span",{className:"agent-cycle-spacer"}),E?s.jsx("span",{className:"agent-cycle-preview",children:E}):null]}),s.jsxs("div",{className:"agent-cycle-body",children:[y.think?s.jsx($_,{item:y.think,label:"think",toolDefs:A,defaultOpen:M}):null,y.acts.map(H=>s.jsx($_,{item:H,label:"act",toolDefs:A},H.id)),s.jsx(dj,{acts:y.acts}),y.others.length?s.jsxs("div",{className:"agent-cycle-others",children:[s.jsx("div",{className:"agent-cycle-others-title",children:"other"}),y.others.map(H=>{const X=M&&_l(H.step)==="answer_user";return s.jsx($_,{item:H,label:"other",toolDefs:A,defaultOpen:X},H.id)})]}):null]})]},y.id)})]})]})}function oo(e){return typeof e=="string"?e.trim():""}function hj(e){var t;return oo(e.run_id)||oo((t=e.record)==null?void 0:t.run_id)}function bp(e){return oo(e==null?void 0:e.node_id)}const mj=new Set(["reason","act","observe","thought","think"]);function jp(e){const t=oo(e);if(!t.includes("::"))return t;const n=t.split("::");if(n.length<2)return t;const i=String(n[n.length-1]||"").trim().toLowerCase();return mj.has(i)?n.slice(0,-1).join("::"):t}function Ov(e){var t;return oo((t=e==null?void 0:e.effect)==null?void 0:t.type)}function _j(e){return oo(e==null?void 0:e.status)||"unknown"}function my(e){return oo(e==null?void 0:e.step_id)}function pj(e){return oo(e==null?void 0:e.ended_at)||oo(e==null?void 0:e.started_at)}function gj(e){const t=new Map,n=new Map;for(const o of e){const l=jp(bp(o));if(!l)continue;const u=Ov(o);u==="llm_call"?t.set(l,(t.get(l)||0)+1):u==="tool_calls"&&n.set(l,(n.get(l)||0)+1)}const i=o=>{let l="",u=-1;for(const[c,f]of o)f>u&&(l=c,u=f);return l};return i(t)||i(n)||""}function yj(e,t){const n=oo(t.run_id);if(!n)return{run_id:"",node_id:"",items:[]};const i=(Array.isArray(e)?e:[]).filter(x=>x&&x.record&&hj(x)===n).map(x=>({cursor:x.cursor,record:x.record})).sort((x,S)=>(x.cursor||0)-(S.cursor||0)),o=i.map(x=>x.record),l=jp(oo(t.node_id)),u=l||gj(o),c=new Set(["llm_call","tool_calls","ask_user","answer_user"]);let f=i.filter(x=>c.has(Ov(x.record)));l&&(f=f.filter(x=>jp(bp(x.record))===l));const _=new Map,p=[];for(const x of f){const S=my(x.record);if(!S){p.push(x);continue}const j=_.get(S);(!j||(x.cursor||0)>(j.cursor||0))&&_.set(S,x)}const w=[...p,...Array.from(_.values())].sort((x,S)=>(x.cursor||0)-(S.cursor||0)).map(x=>{const S=x.record,j=bp(S)||"(node?)",E=pj(S),A=my(S);return{id:`ledger:${n}:${x.cursor}:${A||""}`,runId:n,nodeId:j,ts:E||void 0,status:_j(S),step:S}});return{run_id:n,node_id:u,items:w}}function Um(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 wj(e){if(e==null)return"";if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}}function vj(e){const t=String(e.role||"message").trim()||"message",n=String(e.title||"").trim(),i=String(e.ts||"").trim(),o=[t];return n&&o.push(n),i&&o.push(i),o.join(" · ")}function xj(e){return e.endsWith(`
|
|
46
|
+
`)?e:`${e}
|
|
47
|
+
`}function bj(e){return String(e||"").trimStart().startsWith("```")}function jj(e,t){const i=[`# ${String((t==null?void 0:t.heading)||"Chat").trim()||"Chat"}`,""];for(const o of e){const l=vj(o);i.push(`## ${l}`,"");const u=String(o.content||""),c=Um(u);c!==null&&!bj(u)?i.push("```json",wj(c).trimEnd(),"```",""):i.push(xj(u).trimEnd(),""),i.push("---","")}for(;i.length&&!i[i.length-1].trim();)i.pop();return i.length&&i[i.length-1]==="---"&&i.pop(),`${i.join(`
|
|
48
|
+
`).trimEnd()}
|
|
49
|
+
`}async function ic(e){const t=String(e||"");if(!t)return!1;try{return await navigator.clipboard.writeText(t),!0}catch{try{const n=document.createElement("textarea");return n.value=t,n.style.position="fixed",n.style.left="-9999px",document.body.appendChild(n),n.select(),document.execCommand("copy"),document.body.removeChild(n),!0}catch{return!1}}}function Sj(e){const t=String(e.filename||"").trim()||"export.txt",n=String(e.text||""),i=String(e.mime),o=new Blob([n],{type:i}),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 kj=3,Nj=Number.MAX_SAFE_INTEGER;function Pv(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Dv(e){return Array.isArray(e)}function Cj(e){if(e==null)return"";if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}}function Eu({kind:e,children:t}){return s.jsx("span",{className:`pc-json-token ${e}`,children:t})}function Ej(e){const t=JSON.stringify(e.value),n=t.length>96||t.includes("\\n")||t.includes("\\r")||t.includes("\\t"),[i,o]=m.useState(!n||e.expansionMode==="unfolded");return m.useEffect(()=>{n&&o(e.expansionMode==="unfolded")},[n,e.expansionMode,e.expansionVersion]),n?s.jsxs("span",{className:`pc-json-string ${i?"open":"collapsed"}`,children:[s.jsx("button",{type:"button",className:"pc-json-string__toggle",onClick:()=>o(l=>!l),"aria-label":i?"Collapse string value":"Expand string value","aria-expanded":i,children:i?"▾":"▸"}),i?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(Eu,{kind:"string",children:t})}function $j(e,t,n){return e===null?s.jsx(Eu,{kind:"null",children:"null"}):typeof e=="string"?s.jsx(Ej,{value:e,expansionMode:t,expansionVersion:n}):typeof e=="number"?s.jsx(Eu,{kind:"number",children:String(e)}):typeof e=="boolean"?s.jsx(Eu,{kind:"boolean",children:e?"true":"false"}):s.jsx(Eu,{kind:"string",children:JSON.stringify(String(e))})}function Aj(e){return Dv(e)?e.length===1?"1 item":`${e.length} items`:Pv(e)?Object.keys(e).length===1?"1 key":`${Object.keys(e).length} keys`:""}function Fv(e){const{label:t,value:n,depth:i,collapseAfterDepth:o,expansionMode:l,expansionVersion:u,trailingComma:c}=e,f=i*14,_=Pv(n),p=Dv(n),y=_||p,w=i<o,[x,S]=m.useState(w);m.useEffect(()=>{S(w)},[w,u]);const j=t?s.jsxs(s.Fragment,{children:[s.jsx(Eu,{kind:"key",children:JSON.stringify(t)}),": "]}):null;if(!y)return s.jsxs("div",{className:"pc-json-viewer__line",style:{paddingLeft:f},children:[j,$j(n,l,u),c?",":""]});const E=p?"[":"{",A=p?"]":"}",L=Aj(n),O=x?`${E}`:`${E}…${A}${L?` (${L})`:""}`,M=p?n.map((H,X)=>({key:String(X),label:void 0,value:H})):Object.entries(n).map(([H,X])=>({key:H,label:H,value:X}));return s.jsxs("details",{className:"pc-json-viewer__details",open:x,onToggle:H=>S(H.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:O}),!x&&c?s.jsx("span",{className:"pc-json-viewer__punct",children:","}):null]}),x?s.jsx("div",{className:"pc-json-viewer__children",children:M.length===0?s.jsxs("div",{className:"pc-json-viewer__line",style:{paddingLeft:f},children:[s.jsx("span",{className:"pc-json-viewer__punct",children:A}),c?",":""]}):s.jsxs(s.Fragment,{children:[M.map((H,X)=>{const Y=X===M.length-1;return s.jsx(Fv,{label:H.label,value:H.value,depth:i+1,collapseAfterDepth:o,expansionMode:l,expansionVersion:u,trailingComma:!Y},`${i}:${t||"root"}:${H.key}`)}),s.jsxs("div",{className:"pc-json-viewer__line",style:{paddingLeft:f},children:[s.jsx("span",{className:"pc-json-viewer__punct",children:A}),c?",":""]})]})}):null]})}function Tj(e){const t=e.trim();if(!t)return e;if(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))try{return JSON.parse(t)}catch{return e}return e}function fr(e){const{value:t,className:n,showCopy:i=!0}=e,[o,l]=m.useState({mode:"folded",version:0}),u=typeof e.collapseAfterDepth=="number"&&(Number.isFinite(e.collapseAfterDepth)||e.collapseAfterDepth===1/0)&&e.collapseAfterDepth>=0?e.collapseAfterDepth===1/0?Number.MAX_SAFE_INTEGER:Math.trunc(e.collapseAfterDepth):kj,c=o.mode==="unfolded"?Nj:u,f=m.useMemo(()=>typeof t=="string"?Tj(t):t,[t]),_=m.useMemo(()=>Cj(t),[t]),p=["pc-json-viewer",n].filter(Boolean).join(" ");m.useEffect(()=>{l(w=>({mode:"folded",version:w.version+1}))},[f]);const y=()=>{l(w=>({mode:w.mode==="unfolded"?"folded":"unfolded",version:w.version+1}))};return s.jsxs("div",{className:p,children:[s.jsxs("div",{className:"pc-json-viewer__toolbar",children:[s.jsx("button",{type:"button",className:"pc-btn pc-json-viewer__toggle-all",onClick:y,"aria-expanded":o.mode==="unfolded",children:o.mode==="unfolded"?"Fold all":"Unfold all"}),i?s.jsx("button",{type:"button",className:"pc-btn pc-json-viewer__copy",onClick:()=>void ic(_),children:"Copy JSON"}):null]}),s.jsx("div",{className:"pc-json-viewer__tree",role:"tree","aria-label":"JSON viewer",children:s.jsx(Fv,{value:f,depth:0,collapseAfterDepth:c,expansionMode:o.mode,expansionVersion:o.version,trailingComma:!1})})]})}function Qd(e,t){const n=String(e??"");if(!t||!t.needles.length)return[n];const i=[],o=n.toLowerCase();let l=0;for(;l<n.length;){let u=-1,c="";for(let p=0;p<t.needlesLower.length;p++){const y=t.needlesLower[p];if(!y)continue;const w=o.indexOf(y,l);if(w===-1)continue;const x=t.needles[p]||"";x&&(u===-1||w<u||w===u&&x.length>c.length)&&(u=w,c=x)}if(u===-1||!c){i.push(n.slice(l));break}u>l&&i.push(n.slice(l,u));const f=t.hits===0&&t.id?t.id:void 0,_=n.slice(u,u+c.length);i.push(s.jsx("span",{id:f,className:t.className,children:_},`hl:${t.hits}`)),t.hits+=1,l=u+c.length}return i}function zv(e){const t=String(e||"").trim();if(t&&/^(https?:|mailto:|tel:|#|\/)/i.test(t))return t}const Sp="http://same-origin.invalid/";function Mj(e){try{const t=new URL(e,Sp);return t.protocol==="http:"&&t.origin===new URL(Sp).origin}catch{return!1}}function Bv(e){const t=String(e||"").trim();return zv(t)??(t&&Mj(t)?t:void 0)}let ec=null;function Rj(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 i=n??Sp;let o,l;try{o=new URL(i).origin,l=new URL(t,i)}catch{return!1}return l.protocol!=="http:"&&l.protocol!=="https:"?!1:l.origin===o}function Uv(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 ll(e,t){const n=[],i=String(e??"");let o=0,l="";const u=()=>{if(l){for(const c of Qd(l,t))n.push(c);l=""}};for(;o<i.length;){const c=i[o];if(c==="!"&&i[o+1]==="["){const f=i.indexOf("]",o+2);if(f!==-1&&i[f+1]==="("){const _=i.indexOf(")",f+2);if(_!==-1){const p=i.slice(o+2,f),y=Bv(i.slice(f+2,_));if(y&&ec&&!ec(y)){u(),n.push(Uv(`img:${o}`,y,p)),o=_+1;continue}if(y){u(),n.push(s.jsxs("span",{className:"pc-md_image_inline",children:[s.jsx("img",{className:"pc-md_img",src:y,alt:p,loading:"lazy"}),p?s.jsx("span",{className:"pc-md_img_caption",children:t?Qd(p,t):p}):null]},`img:${o}`)),o=_+1;continue}}}}if(c==="["){const f=i.indexOf("]",o+1);if(f!==-1&&i[f+1]==="("){const _=i.indexOf(")",f+2);if(_!==-1){const p=i.slice(o+1,f),y=zv(i.slice(f+2,_));if(y){u(),n.push(s.jsx("a",{className:"pc-md_link",href:y,target:y.startsWith("#")?void 0:"_blank",rel:"noreferrer",children:ll(p,t)},`link:${o}`)),o=_+1;continue}}}}if(c==="`"){const f=i.indexOf("`",o+1);if(f!==-1){u();const _=i.slice(o+1,f);n.push(s.jsx("code",{children:t?Qd(_,t):_},`code:${o}`)),o=f+1;continue}}if(c==="*"&&i[o+1]==="*"){const f=i.indexOf("**",o+2);if(f!==-1){u();const _=i.slice(o+2,f);n.push(s.jsx("strong",{children:t?Qd(_,t):_},`bold:${o}`)),o=f+2;continue}}if(c==="*"&&i[o+1]!=="*"){const f=i.indexOf("*",o+1);if(f!==-1){u();const _=i.slice(o+1,f);n.push(s.jsx("em",{children:t?Qd(_,t):_},`em:${o}`)),o=f+1;continue}}l+=c,o+=1}return u(),n}function Lj(e){return String(e??"").replace(/\r\n/g,`
|
|
50
|
+
`).replace(/\r/g,`
|
|
51
|
+
`).split(`
|
|
52
|
+
`)}function lm(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 Ij(e){const t=[];for(const o of e){const l=lm(o);l?t.push(l):t.length>0&&o.trim()&&(t[t.length-1].content+=` ${o.trim()}`)}const n=[],i=[];for(const o of t){for(;i.length>0&&o.indent<i[i.length-1].indent;)i.pop();let l=i.length>0?i[i.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),i.push({indent:o.indent,node:f}),l=i[i.length-1]}}else if(l&&l.node.ordered!==o.ordered){i.pop();const u=i.length>0?i[i.length-1]:null,c={ordered:o.ordered,start:o.start,items:[]};if(u){const f=u.node.items,_=f[f.length-1];_?_.children.push(c):u.node.items.push({content:"",children:[c]})}else n.push(c);i.push({indent:o.indent,node:c}),l=i[i.length-1]}if(!l){const u={ordered:o.ordered,start:o.start,items:[]};n.push(u),i.push({indent:o.indent,node:u}),l=i[i.length-1]}l.node.items.push({content:o.content,children:[]})}return n}function Wv(e,t,n){const i=e.items.map((o,l)=>s.jsxs("li",{children:[ll(o.content,t),o.children.map((u,c)=>Wv(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:i},n):s.jsx("ul",{className:"pc-md_ul",children:i},n)}function Oj(e,t,n){return Ij(e).map((i,o)=>Wv(i,t,`${n}:${o}`))}function _y(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 py(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(i=>String(i??"").trim());return n.length<2?!1:n.every(i=>/^:?-{3,}:?$/.test(i))}const gy=/^(#{1,5})\s+(.*)$/;function yy(e){return e.trim().startsWith("```")}function wy(e){return e.trimStart().startsWith(">")}function Ni(e){const t=ec;ec=e.images==="link"?e.inlineImage||Rj:null;try{return Pj(e)}finally{ec=t}}function Pj({text:e,className:t,highlight:n,highlights:i,highlightClassName:o,highlightId:l}){const u=Lj(e),c=[],f=[];Array.isArray(i)&&f.push(...i),typeof n=="string"&&n.trim()&&f.push(n);const _=Array.from(new Set(f.map(x=>String(x??"").trim()).filter(Boolean))).filter(x=>x.length>=4),p=_.length?{needles:_,needlesLower:_.map(x=>x.toLowerCase()),className:o||"pc-md_hl",id:l,hits:0}:null;let y=0;for(;y<u.length;){const x=String(u[y]??"");if(!x.trim()){y+=1;continue}const S=x.trim();if(/^([-_*])(\s*\1){2,}$/.test(S)){c.push(s.jsx("hr",{className:"pc-md_hr"},`hr:${y}`)),y+=1;continue}const j=x.match(/^\s*!\[([^\]]*)\]\(([^)]+)\)\s*$/);if(j){const L=Bv(j[2]||"");if(L&&ec&&!ec(L)){c.push(s.jsx("p",{className:"pc-md_p",children:Uv(`img:${y}`,L,j[1]||"")},`p:${y}`)),y+=1;continue}if(L){const O=j[1]||"";c.push(s.jsxs("figure",{className:"pc-md_figure",children:[s.jsx("img",{className:"pc-md_img",src:L,alt:O,loading:"lazy"}),O?s.jsx("figcaption",{children:ll(O,p)}):null]},`figure:${y}`)),y+=1;continue}}if(yy(x)){const O=x.trim().replace(/```/g,"").trim(),M=[];for(y+=1;y<u.length&&!String(u[y]??"").trim().startsWith("```");)M.push(String(u[y]??"")),y+=1;y<u.length&&(y+=1);const H=M.join(`
|
|
53
|
+
`);c.push(s.jsx("pre",{className:"pc-md_pre",children:s.jsx("code",{className:O?`language-${O}`:void 0,children:H})},`pre:${y}`));continue}const E=x.match(gy);if(E){const L=E[1].length,O=E[2]||"",M=ll(O,p);L===1?c.push(s.jsx("h1",{children:M},`h1:${y}`)):L===2?c.push(s.jsx("h2",{children:M},`h2:${y}`)):L===3?c.push(s.jsx("h3",{children:M},`h3:${y}`)):L===4?c.push(s.jsx("h4",{children:M},`h4:${y}`)):c.push(s.jsx("h5",{children:M},`h5:${y}`)),y+=1;continue}if(wy(x)){const L=[];for(;y<u.length&&String(u[y]??"").trimStart().startsWith(">");){const M=String(u[y]??"").trimStart();L.push(M.replace(/^>\s?/,"")),y+=1}c.push(s.jsx("blockquote",{className:"pc-md_quote",children:L.map((O,M)=>s.jsxs(ve.Fragment,{children:[ll(O,p),M<L.length-1?s.jsx("br",{}):null]},`q:${y}:${M}`))},`quote:${y}`));continue}if(x.includes("|")&&y+1<u.length&&py(String(u[y+1]??""))){const L=_y(x),O=Math.max(1,L.length),M=[];for(y+=2;y<u.length;){const H=String(u[y]??"");if(!H.trim()||!H.includes("|"))break;const X=_y(H),Y=[];for(let Z=0;Z<O;Z++)Y.push(X[Z]??"");M.push(Y),y+=1}c.push(s.jsx("div",{className:"pc-md_table_wrap",children:s.jsxs("table",{className:"pc-md_table",children:[s.jsx("thead",{children:s.jsx("tr",{children:L.slice(0,O).map((H,X)=>s.jsx("th",{children:ll(H,p)},`th:${y}:${X}`))})}),s.jsx("tbody",{children:M.map((H,X)=>s.jsx("tr",{children:H.map((Y,Z)=>s.jsx("td",{children:ll(Y,p)},`td:${y}:${X}:${Z}`))},`tr:${y}:${X}`))})]})},`table:${y}`));continue}if(lm(x)){const L=[];for(;y<u.length;){const O=String(u[y]??"");if(!O.trim()||O.trimStart().startsWith("```"))break;if(lm(O)||/^\s{2,}\S/.test(O)){L.push(O),y+=1;continue}break}c.push(s.jsx(ve.Fragment,{children:Oj(L,p,`list:${y}`)},`list:${y}`));continue}const A=[];for(;y<u.length&&String(u[y]??"").trim()&&!(A.length>0&&lm(String(u[y]??"")));){const L=String(u[y]??"");if(A.length>0&&(gy.test(L)||yy(L)||wy(L))||A.length>0&&L.includes("|")&&y+1<u.length&&py(String(u[y+1]??"")))break;A.push(L),y+=1}c.push(s.jsx("p",{className:"pc-md_p",children:A.map((L,O)=>s.jsxs(ve.Fragment,{children:[ll(L,p),O<A.length-1?s.jsx("br",{}):null]},`pl:${y}:${O}`))},`p:${y}`))}const w=["pc-md",t].filter(Boolean).join(" ");return s.jsx("div",{className:w,children:c})}function qv(e){const t=String(e.text??""),n=m.useMemo(()=>Um(t),[t]),i=["pc-chat-content",e.className].filter(Boolean).join(" ");return n!==null?s.jsx("div",{className:i,children:s.jsx(fr,{value:n,collapseAfterDepth:e.jsonCollapseAfterDepth})}):e.renderMarkdown?s.jsx("div",{className:i,children:e.renderMarkdown(t)}):s.jsx("div",{className:i,children:s.jsx(Ni,{text:t,images:e.images,inlineImage:e.inlineImage})})}const Hv=[{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"]}];Hv.map(e=>({id:e.id,label:e.label}));function Dj(e){return`theme-${String(e||"").trim()||"dark"}`}function vy(e){try{const t=document.documentElement,n=Array.from(t.classList).filter(i=>i.startsWith("theme-"));for(const i of n)t.classList.remove(i);t.classList.add(Dj(e))}catch{}}const kp=[{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}],Np=[{id:"compact",label:"Compact",density:.85},{id:"standard",label:"Standard",density:1},{id:"spacious",label:"Spacious",density:1.2}];function Fj(e){const t=String(e).trim();return kp.find(n=>n.id===t)||kp[1]}function zj(e){const t=String(e).trim();return Np.find(n=>n.id===t)||Np[1]}function xy(e){try{const t=document.documentElement,n=Fj(e.font_scale||"md"),i=zj(e.header_density||"standard");t.style.setProperty("--font-scale",String(n.scale)),t.style.setProperty("--header-density",String(i.density))}catch{}}var Vv=jv();function gu(...e){return e.filter(Boolean).join(" ")}function Ou({value:e,options:t,placeholder:n="Select…",disabled:i=!1,loading:o=!1,searchable:l=!0,searchPlaceholder:u="Search…",allowCustom:c=!1,clearable:f=!1,minPopoverWidth:_=240,variant:p="panel",className:y,triggerClassName:w,ariaLabel:x,id:S,includeValueOption:j=!1,onOpen:E,customOptionLabel:A,validateCustomValue:L,onChange:O,renderOption:M,renderValue:H}){const X=m.useRef(null),Y=m.useRef(null),Z=m.useRef(null),re=m.useRef(E),ie=m.useId(),ue=S||`af-select-${ie.replace(/[^a-zA-Z0-9_-]/g,"")}`,F=`${ue}-listbox`,[C,N]=m.useState(!1),[P,D]=m.useState(""),[ne,B]=m.useState(0),[z,G]=m.useState("bottom"),[T,Q]=m.useState({left:0,top:0,width:0});m.useEffect(()=>{re.current=E},[E]);const K=m.useMemo(()=>{if(!j)return t;const ge=String(e??"").trim();return!ge||t.some(De=>De.value===ge)?t:[...t,{value:ge,label:ge}]},[j,t,e]),J=m.useMemo(()=>{const ge=String(e??"");return K.find(De=>De.value===ge)||null},[K,e]),oe=m.useMemo(()=>(J==null?void 0:J.label)||String(e||"").trim()||"",[J,e]),fe=m.useMemo(()=>{const ge=P.trim().toLowerCase();return ge?K.filter(De=>De.label.toLowerCase().includes(ge)||De.value.toLowerCase().includes(ge)):K},[K,P]),_e=m.useMemo(()=>{if(!c)return null;const ge=P.trim();if(!ge||K.some(Dt=>Dt.value===ge))return null;const Ke=(L==null?void 0:L(ge,{options:K}))||"";return{value:ge,label:A?A(ge):`Use "${ge}"`,disabled:!!Ke,reason:Ke}},[c,A,K,P,L]),we=m.useMemo(()=>{const ge=_e?[_e,...fe]:fe;if(ge.length>0)return ge;const De=String(e??"").trim();return o&&De?[{value:De,label:oe||De}]:ge},[_e,fe,o,oe,e]),Ae=m.useCallback(()=>{const ge=X.current;if(!ge)return;const De=ge.getBoundingClientRect(),Ke=Math.max(De.width,_),Dt=Math.max(8,Math.min(De.left,window.innerWidth-Ke-8)),tn=window.innerHeight-De.bottom,pn=De.top,Wt=tn>=220||tn>=pn?"bottom":"top";G(Wt);const It=Wt==="bottom"?De.bottom+6:De.top-6;Q({left:Dt,top:It,width:Ke})},[_]),Be=m.useCallback(()=>{N(!1),D("")},[]);m.useEffect(()=>{var ge;C&&((ge=re.current)==null||ge.call(re))},[C]),m.useEffect(()=>{if(!C)return;Ae();const ge=()=>Ae();return window.addEventListener("resize",ge),window.addEventListener("scroll",ge,!0),()=>{window.removeEventListener("resize",ge),window.removeEventListener("scroll",ge,!0)}},[C,Ae]),m.useEffect(()=>{if(!C)return;const ge=De=>{var Dt,tn;const Ke=De.target;Ke&&((Dt=X.current)!=null&&Dt.contains(Ke)||(tn=Y.current)!=null&&tn.contains(Ke)||Be())};return document.addEventListener("mousedown",ge,!0),()=>document.removeEventListener("mousedown",ge,!0)},[C,Be]),m.useEffect(()=>{if(!C)return;const ge=Math.max(0,we.findIndex(De=>De.value===e));B(ge===-1?0:ge),l&&setTimeout(()=>{var De;return(De=Z.current)==null?void 0:De.focus()},0)},[C,l,e,we]);const We=ge=>{var Ke;const De=we.find(Dt=>Dt.value===ge);De!=null&&De.disabled||(O(ge),Be(),(Ke=X.current)==null||Ke.focus())},_t=ge=>{var De,Ke;if(ge.key==="Escape")return ge.preventDefault(),Be(),(De=X.current)==null||De.focus(),!0;if(ge.key==="Tab")return Be(),(Ke=X.current)==null||Ke.focus(),!1;if(ge.key==="ArrowDown")return ge.preventDefault(),B(Dt=>Math.min(Dt+1,Math.max(0,we.length-1))),!0;if(ge.key==="ArrowUp")return ge.preventDefault(),B(Dt=>Math.max(Dt-1,0)),!0;if(ge.key==="Home")return ge.preventDefault(),B(0),!0;if(ge.key==="End")return ge.preventDefault(),B(Math.max(0,we.length-1)),!0;if(ge.key==="Enter"){ge.preventDefault();const Dt=we[ne];return Dt&&We(Dt.value),!0}return!1},Pe=ge=>{if(!i){if(C){if(_t(ge))return;if(ge.key===" "&&!l){ge.preventDefault();const De=we[ne];De&&We(De.value)}return}(ge.key==="Enter"||ge.key===" "||ge.key==="ArrowDown"||ge.key==="ArrowUp")&&(ge.preventDefault(),N(!0))}},et=!!String(e||"").trim(),lt=et?oe:n,Ye=_e!=null&&_e.disabled?_e.reason||"Unavailable":"",Se=C&&we.length>0?`${ue}-opt-${ne}`:void 0,Le=s.jsx("span",{className:gu("af-select-value",!et&&"af-select-value--placeholder"),children:o&&!et?"Loading…":lt}),ct=H?H(J,String(e||"")):Le;return s.jsxs("span",{className:gu("af-select",p==="pin"?"af-select--pin":"af-select--panel",y),children:[s.jsxs("button",{ref:X,id:ue,type:"button",className:gu("af-select-trigger",f&&et&&"af-select-trigger--clearable",w),disabled:i,onMouseDown:ge=>ge.stopPropagation(),onClick:ge=>{ge.stopPropagation(),!i&&N(De=>!De)},onKeyDown:Pe,role:l?void 0:"combobox","aria-haspopup":"listbox","aria-expanded":C,"aria-controls":C?F:void 0,"aria-activedescendant":l?void 0:Se,"aria-label":x,children:[ct,s.jsx("span",{className:gu("af-select-caret",C&&"af-select-caret--open"),children:"▾"})]}),f&&et?s.jsx("button",{type:"button",className:"af-select-clear-btn","aria-label":"Clear selection",disabled:i,onMouseDown:ge=>{ge.preventDefault(),ge.stopPropagation()},onClick:ge=>{var De;ge.preventDefault(),ge.stopPropagation(),O(""),Be(),(De=X.current)==null||De.focus()},title:"Clear",children:"×"}):null,C?Vv.createPortal(s.jsxs("div",{ref:Y,className:gu("af-select-popover",z==="top"&&"af-select-popover--top"),style:{position:"fixed",left:`${T.left}px`,top:`${T.top}px`,width:`${T.width}px`},onMouseDown:ge=>ge.stopPropagation(),onClick:ge=>ge.stopPropagation(),onWheel:ge=>ge.stopPropagation(),onKeyDown:_t,tabIndex:-1,children:[l?s.jsxs("div",{className:"af-select-search",children:[s.jsx("input",{ref:Z,className:"af-select-search-input",value:P,onChange:ge=>D(ge.target.value),placeholder:u,onKeyDown:_t,role:"combobox","aria-expanded":!0,"aria-controls":F,"aria-activedescendant":Se,"aria-invalid":!!Ye,"aria-describedby":Ye?`${ue}-custom-error`:void 0}),Ye?s.jsx("div",{id:`${ue}-custom-error`,className:"af-select-custom-error",role:"alert",children:Ye}):null]}):null,s.jsx("div",{className:"af-select-options",role:"listbox",id:F,"aria-label":x,children:o&&we.length===0?s.jsx("div",{className:"af-select-empty",children:"Loading…"}):we.length===0?s.jsx("div",{className:"af-select-empty",children:"No results"}):we.map((ge,De)=>{var It;const Ke=ge.value===e,Dt=De===ne,tn=String(ge.group||"").trim(),pn=De>0?String(((It=we[De-1])==null?void 0:It.group)||"").trim():"",Wt=!!tn&&tn!==pn;return s.jsxs(ve.Fragment,{children:[Wt?s.jsx("div",{className:"af-select-group",role:"presentation",children:tn}):null,s.jsx("div",{id:`${ue}-opt-${De}`,role:"option","aria-selected":Ke,className:gu("af-select-option",Ke&&"af-select-option--selected",Dt&&"af-select-option--highlighted",ge.disabled&&"af-select-option--disabled"),title:ge.disabled?ge.reason||"Unavailable":void 0,onMouseEnter:()=>B(De),onMouseDown:dn=>{dn.preventDefault(),dn.stopPropagation()},onClick:()=>We(ge.value),"aria-disabled":ge.disabled?!0:void 0,children:M?M(ge,{selected:Ke,highlighted:Dt}):s.jsxs(s.Fragment,{children:[s.jsxs("span",{className:"af-select-option-label",children:[s.jsx("span",{children:ge.label}),ge.reason?s.jsx("small",{className:"af-select-option-reason",children:ge.reason}):null]}),Ke?s.jsx("span",{className:"af-select-check",children:"✓"}):null]})})]},ge.value)})})]}),document.body):null]})}function Bj(e){const t=new Set,n=[];for(const i of e||[]){if(!i||typeof i!="object")continue;const o=String(i.name||"").trim();!o||t.has(o)||(t.add(o),n.push({name:o,display_name:typeof i.display_name=="string"?i.display_name:void 0}))}return n.sort((i,o)=>i.name.localeCompare(o.name)),n}function Uj(e){const t=new Set,n=[];for(const i of e||[]){const o=String(i||"").trim();!o||t.has(o)||(t.add(o),n.push(o))}return n.sort(),n}function Wj(e){const t=e.disabled===!0,n=e.layout||"stack",i=e.allowGatewayDefault!==!1,o=String(e.gatewayDefaultLabel||"(gateway default)"),l=String(e.providerLabel||"Provider"),u=String(e.modelLabel||"Model"),c=String(e.providerPlaceholder||"(select)"),f=String(e.modelPlaceholder||"(select)"),_=String(e.provider||"").trim(),p=String(e.model||"").trim(),y=Bj(e.providers),w=Uj(e.models),x=t||!!e.loadingProviders,S=t||!!e.loadingModels,j=[...i?[{value:"",label:o}]:[],...y.map(A=>({value:A.name,label:A.display_name?`${A.display_name} (${A.name})`:A.name}))],E=[...i?[{value:"",label:o}]:[],...w.map(A=>({value:A,label:A}))];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(Ou,{value:_,options:j,placeholder:i?o:c,disabled:x,loading:!!e.loadingProviders,searchable:!0,allowCustom:e.allowCustomProvider===!0,clearable:i,variant:"panel",triggerClassName:e.selectClassName,ariaLabel:l,onChange:A=>e.onChange({provider:String(A||"").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(Ou,{value:p,options:E,placeholder:i?o:f,disabled:S,loading:!!e.loadingModels,searchable:!0,allowCustom:e.allowCustomModel===!0,clearable:i,variant:"panel",triggerClassName:e.selectClassName,ariaLabel:u,onChange:A=>e.onChange({provider:_,model:String(A||"").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 by(...e){return e.filter(Boolean).join(" ")}function qj({kicker:e="AbstractGateway connection",title:t="Connect to AbstractGateway",description:n="Sign in with the Gateway user token assigned by the Gateway admin.",statusLabel:i="Gateway token missing",statusTone:o="warn",tokenSourceLabel:l="token: missing",showGatewayUrl:u=!1,gatewayUrl:c="",gatewayUrlPlaceholder:f="http://127.0.0.1:8080",onGatewayUrlChange:_,userId:p,userPlaceholder:y="admin",onUserIdChange:w,token:x,tokenPlaceholder:S="Paste Gateway user token",showToken:j=!1,onTokenChange:E,onShowTokenChange:A,remember:L=!1,rememberLabel:O="Remember this browser",onRememberChange:M,loading:H=!1,submitting:X=!1,submitDisabled:Y=!1,submitLabel:Z="Sign in",submittingLabel:re="Signing in...",closeLabel:ie="Close",signOutLabel:ue="Sign out",showClose:F=!1,showSignOut:C=!1,error:N,message:P,className:D,onSubmit:ne,onClose:B,onSignOut:z}){const G=H||X,T=G||Y||!String(p||"").trim()||!String(x||"").trim(),Q=K=>{K.preventDefault(),!T&&ne()};return s.jsxs("form",{className:by("af-gateway-signin",D),onSubmit:Q,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.jsxs("div",{className:"af-gateway-signin__status-row",children:[s.jsx("span",{className:by("af-gateway-signin__status",`af-gateway-signin__status--${o}`),children:i}),l?s.jsx("span",{className:"af-gateway-signin__source",children:l}):null]}),s.jsxs("div",{className:"af-gateway-signin__form",children:[u?s.jsxs(s.Fragment,{children:[s.jsx("label",{className:"af-gateway-signin__label",htmlFor:"gateway-session-url",children:"Gateway URL"}),s.jsx("input",{id:"gateway-session-url",value:c,onChange:K=>_==null?void 0:_(K.target.value),placeholder:f,autoComplete:"url",disabled:G})]}):null,s.jsx("label",{className:"af-gateway-signin__label",htmlFor:"gateway-session-user",children:"Gateway user"}),s.jsx("input",{id:"gateway-session-user",value:p,onChange:K=>w(K.target.value),placeholder:y,autoComplete:"username",disabled:G}),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:j?"text":"password",value:x,onChange:K=>E(K.target.value),placeholder:S,autoComplete:"current-password",disabled:G}),s.jsx("button",{className:"af-gateway-signin__secondary",type:"button",onClick:()=>A==null?void 0:A(!j),disabled:G,children:j?"Hide":"Show"})]}),s.jsx("label",{className:"af-gateway-signin__label",children:"Browser session"}),s.jsxs("label",{className:"af-gateway-signin__checkbox",children:[s.jsx("input",{type:"checkbox",checked:!!L,onChange:K=>M==null?void 0:M(K.target.checked),disabled:G}),O]})]}),N?s.jsx("div",{className:"af-gateway-signin__message af-gateway-signin__message--error",children:N}):null,!N&&P?s.jsx("div",{className:"af-gateway-signin__message af-gateway-signin__message--ok",children:P}):null,s.jsxs("div",{className:"af-gateway-signin__actions",children:[F?s.jsx("button",{className:"af-gateway-signin__secondary",type:"button",onClick:B,disabled:G,children:ie}):null,C?s.jsx("button",{className:"af-gateway-signin__secondary",type:"button",onClick:()=>void(z==null?void 0:z()),disabled:G,children:ue}):null,s.jsx("button",{className:"af-gateway-signin__primary",type:"submit",disabled:T,children:X?re:Z})]})]})}function Hj(e){return e==="light"?"Light":"Dark"}function Vj(e){const t=e.themes&&e.themes.length?e.themes:Hv,n=e.showSwatches!==!1,i=e.variant||"panel",o=m.useMemo(()=>{const u={};for(const c of t)u[c.id]=c;return u},[t]),l=m.useMemo(()=>t.map(u=>({value:u.id,label:u.label,group:Hj(u.group)})),[t]);return s.jsx(Ou,{value:e.value,options:l,placeholder:e.placeholder||"Select theme…",disabled:e.disabled===!0,searchable:!0,allowCustom:!1,clearable:!1,variant:i,className:e.className,triggerClassName:e.triggerClassName,onChange:u=>e.onChange(String(u||"").trim()),renderValue:(u,c)=>{const f=String(c||"").trim(),_=o[f],p=(_==null?void 0:_.label)||f||e.placeholder||"Select theme…",y=(_==null?void 0:_.swatches)||null,w=!f;return s.jsxs("span",{className:"af-theme-value",children:[s.jsx("span",{className:`af-theme-label ${w?"af-theme-label--placeholder":""}`.trim(),children:p}),n&&y?s.jsx("span",{className:"af-theme-swatches","aria-hidden":"true",children:y.map((x,S)=>s.jsx("span",{className:"af-theme-swatch",style:{background:x}},`${f}:${S}`))}):null]})},renderOption:(u,c)=>{const f=String(u.value||"").trim(),_=o[f],p=(_==null?void 0:_.swatches)||null;return s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"af-theme-option-label",children:u.label}),s.jsxs("span",{className:"af-theme-option-right",children:[n&&p?s.jsx("span",{className:"af-theme-swatches","aria-hidden":"true",children:p.map((y,w)=>s.jsx("span",{className:"af-theme-swatch",style:{background:y}},`${f}:${w}`))}):null,c.selected?s.jsx("span",{className:"af-select-check",children:"✓"}):null]})]})}})}function Gj(e){const t=e.scales&&e.scales.length?e.scales:kp,n=e.variant||"panel",i=m.useMemo(()=>t.map(o=>({value:o.id,label:o.label})),[t]);return s.jsx(Ou,{value:e.value,options:i,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 Kj(e){const t=e.densities&&e.densities.length?e.densities:Np,n=e.variant||"panel",i=m.useMemo(()=>t.map(o=>({value:o.id,label:o.label})),[t]);return s.jsx(Ou,{value:e.value,options:i,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 Yj=new Set(["board","inbox","server","agent","playCircle","list","gear"]);function Jj(e){switch(e){case"chat":return s.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H8l-5 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"});case"plus":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M12 5v14"}),s.jsx("path",{d:"M5 12h14"})]});case"history":return s.jsxs(s.Fragment,{children:[s.jsx("circle",{cx:"12",cy:"12",r:"9"}),s.jsx("path",{d:"M12 7v5l3 3"})]});case"refresh":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M21 12a9 9 0 0 0-15.5-6.4L3 8"}),s.jsx("path",{d:"M3 3v5h5"}),s.jsx("path",{d:"M3 12a9 9 0 0 0 15.5 6.4L21 16"}),s.jsx("path",{d:"M21 21v-5h-5"})]});case"settings":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M4 6h16"}),s.jsx("circle",{cx:"8",cy:"6",r:"2"}),s.jsx("path",{d:"M4 12h16"}),s.jsx("circle",{cx:"16",cy:"12",r:"2"}),s.jsx("path",{d:"M4 18h16"}),s.jsx("circle",{cx:"10",cy:"18",r:"2"})]});case"user":return s.jsxs(s.Fragment,{children:[s.jsx("circle",{cx:"12",cy:"8",r:"4"}),s.jsx("path",{d:"M4 21a8 8 0 0 1 16 0"})]});case"bot":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M12 2v3"}),s.jsx("rect",{x:"5",y:"6",width:"14",height:"14",rx:"3"}),s.jsx("circle",{cx:"9",cy:"13",r:"1",fill:"currentColor",stroke:"none"}),s.jsx("circle",{cx:"15",cy:"13",r:"1",fill:"currentColor",stroke:"none"}),s.jsx("path",{d:"M9 17h6"})]});case"paperclip":return s.jsx("path",{d:"M21.44 11.05l-9.19 9.19a5.5 5.5 0 0 1-7.78-7.78l9.19-9.19a3.5 3.5 0 0 1 4.95 4.95l-9.2 9.19a1.5 1.5 0 0 1-2.12-2.12l8.49-8.48"});case"mic":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M12 14a3 3 0 0 0 3-3V5a3 3 0 0 0-6 0v6a3 3 0 0 0 3 3z"}),s.jsx("path",{d:"M19 11a7 7 0 0 1-14 0"}),s.jsx("path",{d:"M12 18v4"}),s.jsx("path",{d:"M8 22h8"})]});case"speaker":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M11 5L6 9H2v6h4l5 4V5z"}),s.jsx("path",{d:"M15.5 8.5a5 5 0 0 1 0 7"}),s.jsx("path",{d:"M18 6a9 9 0 0 1 0 12"})]});case"pause":return s.jsxs(s.Fragment,{children:[s.jsx("rect",{x:"6",y:"4",width:"4",height:"16",rx:"1",fill:"currentColor",stroke:"none"}),s.jsx("rect",{x:"14",y:"4",width:"4",height:"16",rx:"1",fill:"currentColor",stroke:"none"})]});case"terminal":return s.jsxs(s.Fragment,{children:[s.jsx("rect",{x:"3",y:"4",width:"18",height:"16",rx:"2",ry:"2"}),s.jsx("path",{d:"M7 9l3 3-3 3"}),s.jsx("path",{d:"M12 15h5"})]});case"edit":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M12 20h9"}),s.jsx("path",{d:"M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4 12.5-12.5z"})]});case"download":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),s.jsx("path",{d:"M7 10l5 5 5-5"}),s.jsx("path",{d:"M12 15V3"})]});case"loader":return s.jsx("path",{d:"M21 12a9 9 0 1 1-3.3-6.9"});case"info":return s.jsxs(s.Fragment,{children:[s.jsx("circle",{cx:"12",cy:"12",r:"10"}),s.jsx("path",{d:"M12 16v-4"}),s.jsx("circle",{cx:"12",cy:"8",r:"0.75",fill:"currentColor",stroke:"none"})]});case"warning":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M12 3l10 18H2L12 3z"}),s.jsx("path",{d:"M12 9v4"}),s.jsx("circle",{cx:"12",cy:"17",r:"0.75",fill:"currentColor",stroke:"none"})]});case"error":return s.jsxs(s.Fragment,{children:[s.jsx("circle",{cx:"12",cy:"12",r:"10"}),s.jsx("path",{d:"M15 9l-6 6"}),s.jsx("path",{d:"M9 9l6 6"})]});case"copy":return s.jsxs(s.Fragment,{children:[s.jsx("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2"}),s.jsx("path",{d:"M5 15V5a2 2 0 0 1 2-2h10"})]});case"check":return s.jsx("path",{d:"M20 6L9 17l-5-5"});case"x":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M18 6L6 18"}),s.jsx("path",{d:"M6 6l12 12"})]});case"chevronDown":return s.jsx("path",{d:"M6 9l6 6 6-6"});case"chevronRight":return s.jsx("path",{d:"M9 18l6-6-6-6"});case"trash":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M3 6h18"}),s.jsx("path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"}),s.jsx("path",{d:"M6 6l1 16h10l1-16"}),s.jsx("path",{d:"M10 11v6"}),s.jsx("path",{d:"M14 11v6"})]});case"send":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M22 2L11 13"}),s.jsx("path",{d:"M22 2L15 22l-4-9-9-4 20-7z"})]});case"thumbsUp":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M7 10v11"}),s.jsx("path",{d:"M7 10l4.5-8a2 2 0 0 1 3.6 1.5L14 8h5.2a2 2 0 0 1 2 2.4l-1.6 8a2 2 0 0 1-2 1.6H7"})]});case"thumbsDown":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M17 14V3"}),s.jsx("path",{d:"M17 14l-4.5 8a2 2 0 0 1-3.6-1.5L10 16H4.8a2 2 0 0 1-2-2.4l1.6-8a2 2 0 0 1 2-1.6H17"})]});case"thumbsUpFilled":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M7 10v11"}),s.jsx("path",{d:"M7 10l4.5-8a2 2 0 0 1 3.6 1.5L14 8h5.2a2 2 0 0 1 2 2.4l-1.6 8a2 2 0 0 1-2 1.6H7z",fill:"currentColor",stroke:"none"})]});case"thumbsDownFilled":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M17 14V3"}),s.jsx("path",{d:"M17 14l-4.5 8a2 2 0 0 1-3.6-1.5L10 16H4.8a2 2 0 0 1-2-2.4l1.6-8a2 2 0 0 1 2-1.6H17z",fill:"currentColor",stroke:"none"})]});case"board":return s.jsxs(s.Fragment,{children:[s.jsx("rect",{x:"1.5",y:"2",width:"3.6",height:"12",rx:"1"}),s.jsx("rect",{x:"6.2",y:"2",width:"3.6",height:"8.5",rx:"1"}),s.jsx("rect",{x:"10.9",y:"2",width:"3.6",height:"5.5",rx:"1"})]});case"inbox":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M2 9.5 L4 3.5 h8 l2 6"}),s.jsx("path",{d:"M2 9.5 v3 h12 v-3"}),s.jsx("path",{d:"M2 9.5 h3.4 l1 1.6 h3.2 l1-1.6 H14"})]});case"server":return s.jsxs(s.Fragment,{children:[s.jsx("rect",{x:"2",y:"2.5",width:"12",height:"4.6",rx:"1.2"}),s.jsx("rect",{x:"2",y:"8.9",width:"12",height:"4.6",rx:"1.2"}),s.jsx("circle",{cx:"4.6",cy:"4.8",r:"0.8",fill:"currentColor",stroke:"none"}),s.jsx("circle",{cx:"4.6",cy:"11.2",r:"0.8",fill:"currentColor",stroke:"none"})]});case"agent":return s.jsxs(s.Fragment,{children:[s.jsx("rect",{x:"3",y:"4.5",width:"10",height:"8",rx:"2"}),s.jsx("path",{d:"M8 4.5V2.2"}),s.jsx("circle",{cx:"8",cy:"1.8",r:"0.9",fill:"currentColor",stroke:"none"}),s.jsx("circle",{cx:"5.8",cy:"8.4",r:"0.9",fill:"currentColor",stroke:"none"}),s.jsx("circle",{cx:"10.2",cy:"8.4",r:"0.9",fill:"currentColor",stroke:"none"})]});case"playCircle":return s.jsxs(s.Fragment,{children:[s.jsx("circle",{cx:"8",cy:"8",r:"6.2"}),s.jsx("path",{d:"M6.5 5.6 L11 8 L6.5 10.4 Z",fill:"currentColor",stroke:"none"})]});case"list":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M2.5 4h11"}),s.jsx("path",{d:"M2.5 8h11"}),s.jsx("path",{d:"M2.5 12h7"})]});case"gear":return s.jsxs(s.Fragment,{children:[s.jsx("circle",{cx:"8",cy:"8",r:"2.2"}),s.jsx("path",{d:"M8 1.6v2"}),s.jsx("path",{d:"M8 12.4v2"}),s.jsx("path",{d:"M1.6 8h2"}),s.jsx("path",{d:"M12.4 8h2"}),s.jsx("path",{d:"M3.5 3.5l1.4 1.4"}),s.jsx("path",{d:"M11.1 11.1l1.4 1.4"}),s.jsx("path",{d:"M12.5 3.5l-1.4 1.4"}),s.jsx("path",{d:"M4.9 11.1l-1.4 1.4"})]});case"sparkle":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M12 3l1.9 5.1L19 10l-5.1 1.9L12 17l-1.9-5.1L5 10l5.1-1.9z"}),s.jsx("path",{d:"M18.5 15.5l.8 2.2 2.2.8-2.2.8-.8 2.2-.8-2.2-2.2-.8 2.2-.8z"})]});case"contrast":return s.jsxs(s.Fragment,{children:[s.jsx("circle",{cx:"12",cy:"12",r:"9"}),s.jsx("path",{d:"M12 3a9 9 0 0 1 0 18z",fill:"currentColor",stroke:"none"})]});case"logout":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"}),s.jsx("path",{d:"M16 17l5-5-5-5"}),s.jsx("path",{d:"M21 12H9"})]});case"play":return s.jsx("path",{d:"M7 4.5v15a1 1 0 0 0 1.5.86l12-7.5a1 1 0 0 0 0-1.72l-12-7.5A1 1 0 0 0 7 4.5z",fill:"currentColor",stroke:"none"});case"stop":return s.jsx("rect",{x:"5",y:"5",width:"14",height:"14",rx:"2",fill:"currentColor",stroke:"none"});case"folder":return s.jsx("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"});case"file":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),s.jsx("path",{d:"M14 2v6h6"})]});case"archive":return s.jsxs(s.Fragment,{children:[s.jsx("rect",{x:"2",y:"3",width:"20",height:"5",rx:"1"}),s.jsx("path",{d:"M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8"}),s.jsx("path",{d:"M10 12h4"})]});case"clock":return s.jsxs(s.Fragment,{children:[s.jsx("circle",{cx:"12",cy:"12",r:"10"}),s.jsx("path",{d:"M12 6v6h4"})]});default:return null}}function Qe({name:e,size:t=16,className:n,title:i,...o}){const l=i?void 0:!0,u=Yj.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:i?"img":"presentation",...o,children:[i?s.jsx("title",{children:i}):null,Jj(e)]})}const Cp="api/gateway",If="api/connection/gateway";function bt(e){const t=String(e||"");if(t.startsWith("/"))throw new Error(`gatewayApiPath takes a route relative to the gateway API, got ${JSON.stringify(t)}.`);return t?`${Cp}/${t}`:Cp}function Gv(e,t){const n=String(t||"");if(n.startsWith("/"))throw new Error(`joinBaseUrl takes a relative path, got ${JSON.stringify(n)}.`);let i=String(e??"");for(;i.endsWith("/");)i=i.slice(0,-1);return i?`${i}/${n}`:n}function Xj(e){const t=String(e||""),n=`/${Cp}/`;if(!t.startsWith(n)||t.length===n.length)throw new Error(`Not a gateway API path: ${JSON.stringify(t)} (expected ${JSON.stringify(n)}…).`);const i=t.slice(n.length).split(/[?#]/,1)[0];if(/\\|%2f|%5c/i.test(i))throw new Error(`Not a gateway API path: ${JSON.stringify(t)} (encoded slash or backslash).`);for(const o of i.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)}async function Ep(e=If){const t=await fetch(e),n=await t.json().catch(()=>null);if(!t.ok){const i=n&&typeof n=="object"&&n.detail?String(n.detail):`HTTP ${t.status}`;throw new Error(i)}return n}async function Zj(e,t=If){const n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),i=await n.json().catch(()=>null);if(!n.ok){const o=i&&typeof i=="object"&&i.detail?String(i.detail):`HTTP ${n.status}`;throw new Error(o)}return i}async function Kv(e=If){const t=await fetch(e,{method:"DELETE"});if(!t.ok){const n=await t.json().catch(()=>({})),i=n&&typeof n=="object"&&n.detail?String(n.detail):`HTTP ${t.status}`;throw new Error(i)}}function A_(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 i=t[0],o=t[t.length-1];if(i==='"'&&o==='"'||i==="'"&&o==="'"){t=t.slice(1,-1).trim();continue}break}return t.replace(/\/+$/,"")}function Yv(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,i=(u=t.principal)==null?void 0:u.runtime_id;if(t.ok&&n)return{label:`Signed in as ${n}${i?` · runtime ${i}`:""}`,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 Qj(e){const t=e.connectionPath||If,[n,i]=m.useState(!1),[o,l]=m.useState(!1),[u,c]=m.useState(null),[f,_]=m.useState(!1);m.useEffect(()=>{e.isOpen||_(!1)},[e.isOpen]);const[p,y]=m.useState(e.defaultGatewayUrl||"http://127.0.0.1:8080"),[w,x]=m.useState("admin"),[S,j]=m.useState(""),[E,A]=m.useState(!1),[L,O]=m.useState(!0),[M,H]=m.useState(""),[X,Y]=m.useState(""),Z=m.useMemo(()=>Yv(u),[u]),re=C=>{var N;c(C),(N=e.onStatusChange)==null||N.call(e,C)},ie=m.useRef(!1);if(m.useEffect(()=>{var N;if(!e.isOpen)return;const C=!ie.current;if(ie.current=!0,C&&e.initialStatus!==void 0&&e.initialStatus!==null){const P=e.initialStatus;re(P),typeof P.gateway_url=="string"&&P.gateway_url.trim()&&y(A_(P.gateway_url));const D=(N=P.gateway)==null?void 0:N.principal;D!=null&&D.user_id&&x(D.user_id);return}i(!0),H(""),Ep(t).then(P=>{var ne;re(P),typeof P.gateway_url=="string"&&P.gateway_url.trim()&&y(A_(P.gateway_url));const D=(ne=P.gateway)==null?void 0:ne.principal;D!=null&&D.user_id&&x(D.user_id)}).catch(P=>H(`Failed to load connection status: ${String((P==null?void 0:P.message)||P)}`)).finally(()=>i(!1))},[e.isOpen]),m.useEffect(()=>{if(!e.isOpen)return;const C=N=>{N.key==="Escape"&&!N.defaultPrevented&&!e.blocking&&(N.preventDefault(),e.onClose())};return window.addEventListener("keydown",C),()=>window.removeEventListener("keydown",C)},[e.isOpen,e.blocking,e.onClose]),!e.isOpen||f)return null;const ue=async()=>{l(!0),H(""),Y("");try{const C=A_(p);y(C);const N=await Zj({gateway_url:C,gateway_user_id:w,gateway_token:S,persist:L},t);re(N),j(""),_(!0),e.onClose()}catch(C){H(String((C==null?void 0:C.message)||C))}finally{l(!1)}},F=async()=>{l(!0),H(""),Y("");try{await Kv(t),j("");const C=await Ep(t).catch(()=>null);re(C),Y("Signed out. This browser no longer holds a gateway session.")}catch(C){H(String((C==null?void 0:C.message)||C))}finally{l(!1)}};return s.jsx("div",{className:"af-connect-overlay",role:"presentation",onMouseDown:C=>{!e.blocking&&C.target===C.currentTarget&&e.onClose()},children:s.jsx("div",{className:"af-connect-modal",role:"dialog","aria-modal":"true","aria-label":"Gateway connection",children:s.jsx(qj,{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:Z.label,statusTone:Z.tone,tokenSourceLabel:u!=null&&u.has_session?"token: browser session":"token: missing",showGatewayUrl:!0,gatewayUrl:p,onGatewayUrlChange:C=>y(C),userId:w,onUserIdChange:x,token:S,tokenPlaceholder:u!=null&&u.has_session?"(browser session already signed in)":"Paste Gateway user token",showToken:E,onTokenChange:j,onShowTokenChange:A,remember:L,rememberLabel:"Keep this browser signed in",onRememberChange:O,loading:n,submitting:o,submittingLabel:"Signing in...",showClose:!e.blocking,onClose:e.onClose,showSignOut:!e.blocking&&!!(u!=null&&u.has_session),onSignOut:F,error:M,message:X,onSubmit:ue})})})}function eS(e){return!!(e&&e.ok===!0&&e.has_session===!0)}function tS(e){const t=e||{},n=t.connectionPath||If,i=t.variant||"dismissable",o=m.useRef(t.onStatusChange);o.current=t.onStatusChange;const l=m.useRef(i);l.current=i;const u=m.useRef(!!t.autoOpenMidSession);u.current=!!t.autoOpenMidSession;const[c,f]=m.useState(null),[_,p]=m.useState("loading"),[y,w]=m.useState(!1),x=m.useRef(!1),S=m.useRef(!1),j=m.useRef("loading"),E=m.useRef("none"),A=m.useRef(!1),L=m.useRef(0),O=m.useCallback(N=>{var D;L.current+=1,f(N),(D=o.current)==null||D.call(o,N);const P=eS(N);if(P)p("connected"),j.current="connected",x.current=!1,E.current="none",S.current||w(!1);else if(N!==null){const ne=j.current;p("disconnected"),j.current="disconnected",ne!=="disconnected"&&(E.current=A.current?"signout":ne==="connected"?"mid":"boot");const B=l.current==="blocking"||E.current!=="mid"||u.current;!x.current&&B&&w(!0)}N!==null&&(S.current=P)},[]),M=m.useCallback(async()=>{const N=L.current;try{const P=await Ep(n);if(L.current!==N)return;O(P)}catch{if(L.current!==N)return;O(null)}},[n,O]),[H,X]=m.useState(!1),[Y,Z]=m.useState(null),re=m.useCallback(async()=>{X(!0),Z(null),L.current+=1;let N=null;try{await Kv(n)}catch(P){N=String((P==null?void 0:P.message)||P||"Sign-out request failed")}A.current=!0;try{await M()}finally{A.current=!1}Z(N),X(!1)},[n,M]),ie=m.useRef(!1);m.useEffect(()=>{ie.current||(ie.current=!0,M())},[M]);const ue=m.useCallback(()=>{w(!0)},[]),F=m.useCallback(()=>{const N=j.current;i==="blocking"&&N==="disconnected"||(N==="disconnected"&&(x.current=!0),w(!1))},[i]),C=m.useMemo(()=>({isOpen:y,onClose:F,blocking:i==="blocking"&&_!=="connected",appName:t.appName,connectionPath:n,defaultGatewayUrl:t.defaultGatewayUrl,initialStatus:c,onStatusChange:O}),[y,F,i,_,t.appName,n,t.defaultGatewayUrl,c,O]);return{status:c,phase:_,connected:_==="connected",modalOpen:y,signingOut:H,signOutError:Y,openModal:ue,refresh:M,signOut:re,modalProps:C}}function nS(){try{if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID()}catch{}return`steer-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function sS(){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 rS(e){const t=e.commandsPath||bt("commands"),n=nS(),i=JSON.stringify({command_id:n,run_id:e.runId,type:"inject_guidance",payload:{guidance:e.guidance}}),o=e.csrfToken!==void 0?[e.csrfToken]:sS();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:i}),f=await c.json().catch(()=>null);if(!c.ok){const _=f&&typeof f=="object"&&f.detail?String(f.detail):`HTTP ${c.status}`;if(l=new Error(_),c.status===403&&f&&typeof f=="object"&&f.reason_code==="csrf_required")continue;throw l}return{accepted:!!(f!=null&&f.accepted),duplicate:!!(f!=null&&f.duplicate),seq:Number((f==null?void 0:f.seq)??0)}}throw l||new Error("Steer submit failed")}function iS(e){const[t,n]=m.useState(""),[i,o]=m.useState({kind:"idle"}),l=m.useRef(!1),u=m.useRef(0);m.useEffect(()=>{u.current+=1,o({kind:"idle"})},[e.runId]);const c=!e.disabled&&t.trim().length>0&&i.kind!=="sending",f=m.useMemo(()=>e.parked?"Run is waiting — your guidance delivers at its next wake (steers do not wake runs).":"Delivers at the run's next loop boundary.",[e.parked]),_=async()=>{var x;const y=t.trim();if(!y||l.current||e.disabled)return;l.current=!0;const w=u.current;o({kind:"sending"});try{const S=e.submit?await e.submit(e.runId,y):await rS({runId:e.runId,guidance:y,commandsPath:e.commandsPath});if(u.current!==w)return;if(!S.accepted&&!S.duplicate){o({kind:"error",detail:"The gateway did not accept this steer (accepted=false)."});return}o({kind:"queued",seq:S.seq,duplicate:S.duplicate}),n(""),(x=e.onSent)==null||x.call(e,{...S,guidance:y})}catch(S){u.current===w&&o({kind:"error",detail:String((S==null?void 0:S.message)||S)})}finally{l.current=!1}},p=y=>{y.key==="Enter"&&(y.metaKey||y.ctrlKey)&&(y.preventDefault(),_())};return s.jsxs("div",{className:`af-steer${e.className?` ${e.className}`:""}`,children:[s.jsxs("div",{className:"af-steer__row",children:[s.jsx("textarea",{className:"af-steer__input",value:t,rows:2,placeholder:e.placeholder||"Steer this run…","aria-label":e.ariaLabel||"Steer message",disabled:e.disabled||i.kind==="sending",onChange:y=>{n(y.target.value),(i.kind==="error"||i.kind==="queued")&&o({kind:"idle"})},onKeyDown:p}),s.jsx("button",{type:"button",className:"af-steer__send",disabled:!c,onClick:()=>void _(),title:"Send guidance (Cmd/Ctrl+Enter)",children:i.kind==="sending"?"Sending…":"Steer"})]}),s.jsx("div",{className:"af-steer__status",role:"status","aria-live":"polite",children:i.kind==="queued"?s.jsxs("span",{className:"af-steer__ok",children:[i.duplicate?`Already queued (seq ${i.seq}).`:`Queued (seq ${i.seq}).`," ",f," ","Watch for the steer_seen ack in the run ledger."]}):i.kind==="error"?s.jsx("span",{className:"af-steer__err",children:i.detail}):s.jsx("span",{className:"af-steer__hint",children:f})})]})}function oS(e){const t=e.closeOnEscape!==!1,n=m.useRef(null);return m.useEffect(()=>{if(!e.open||!t)return;const i=o=>{o.key!=="Escape"||o.defaultPrevented||(o.preventDefault(),e.onClose())};return window.addEventListener("keydown",i),()=>window.removeEventListener("keydown",i)},[e.open,t,e.onClose]),m.useEffect(()=>{const i=n.current;i&&(e.open?i.removeAttribute("inert"):i.setAttribute("inert",""))},[e.open]),s.jsxs("div",{ref:n,className:`af-drawer${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 aS={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"},lS={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"}},cS={framework:aS,apps:lS},ym=cS;function uS(){return Object.keys(ym.apps).sort()}function dS(e,t){const n=Object.prototype.hasOwnProperty.call(ym.apps,e)?ym.apps[e]:void 0;if(!n)throw new Error(`appIdentity: unknown application id "${e}" (known: ${uS().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 fS(e,t){const n=ym.framework,i=[["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||[])i.push([String(o),String(l)]);return i}function T_(e){return typeof e=="string"?e.trim():""}function jy(e,t){if(t!=null)return[["Gateway",`unavailable (${String(t).trim()||"unknown error"})`]];const n=e&&typeof e=="object"&&!Array.isArray(e)?e:{},i=T_(n.abstractgateway);if(!i)return[["Gateway","unavailable (the gateway did not report its version)"]];const o=T_(n.abstractframework),l=[["Gateway",`AbstractGateway ${i}`],["Gateway framework",o?`AbstractFramework ${o}`:"not installed on the gateway host"]],u=n.packages&&typeof n.packages=="object"&&!Array.isArray(n.packages)?n.packages:{},c=Object.keys(u).filter(f=>f!=="abstractgateway"&&f!=="abstractframework").sort((f,_)=>f<_?-1:f>_?1:0);for(const f of c){const _=T_(u[f]);_&&l.push([`Gateway package ${f}`,_])}return l}const hS='a[href], button:not(:disabled), input:not(:disabled), select:not(:disabled), textarea:not(:disabled), [tabindex]:not([tabindex="-1"])';function mS(e,t,n){if(e.key!=="Tab"||!t)return;const i=Array.from(t.querySelectorAll(hS));if(i.length===0){e.preventDefault();return}const o=i[0],l=i[i.length-1],u=!!n&&t.contains(n);e.shiftKey?(n===o||!u)&&(e.preventDefault(),l.focus()):(n===l||!u)&&(e.preventDefault(),o.focus())}const _S=/https?:\/\/[^\s<>"]+/g;function pS(e,t){if(e==="Contact")return[{text:t,href:`mailto:${t}`}];const n=[];let i=0;for(const o of t.matchAll(_S)){const l=o.index??0;l>i&&n.push({text:t.slice(i,l)}),n.push({text:o[0],href:o[0]}),i=l+o[0].length}return(i<t.length||n.length===0)&&n.push({text:t.slice(i)}),n}function gS({label:e,value:t}){return s.jsx("span",{children:pS(e,t).map((n,i)=>n.href===void 0?s.jsx(ve.Fragment,{children:n.text},i):n.href.startsWith("mailto:")?s.jsx("a",{className:"af-about__link",href:n.href,children:n.text},i):s.jsx("a",{className:"af-about__link",href:n.href,target:"_blank",rel:"noopener noreferrer",children:n.text},i))})}function yS(e){const t=m.useRef(null),n=m.useRef(null),i=m.useId(),o=m.useRef(e.onClose);if(o.current=e.onClose,m.useEffect(()=>{var _;if(!e.open)return;const c=document.activeElement;(_=t.current)==null||_.focus();const f=p=>{if(!p.defaultPrevented){if(p.key==="Escape"){p.preventDefault(),o.current();return}mS(p,n.current,document.activeElement)}};return window.addEventListener("keydown",f),()=>{window.removeEventListener("keydown",f),c&&typeof c.focus=="function"&&c.focus()}},[e.open]),!e.open)return null;const l=e.title||`About ${e.identity.name}`,u=fS(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":i,onClick:c=>c.stopPropagation(),children:[s.jsx("div",{className:"af-appearance__title",id:i,children:l}),s.jsx("dl",{className:"af-about__rows",children:u.map(([c,f],_)=>s.jsxs("div",{className:"af-about__row",children:[s.jsx("dt",{className:"af-about__label",children:c}),s.jsx("dd",{className:"af-about__value",children:s.jsx(gS,{label:c,value:f})})]},`${_}:${c}`))}),s.jsx("div",{className:"af-appearance__actions",children:s.jsx("button",{ref:t,type:"button",className:"af-appearance__close",onClick:e.onClose,children:"Close"})})]})})}function wS(e){const{connection:t}=e,n=t.phase,i=t.signingOut===!0,[o,l]=m.useState(!1),u=e.about,c=i?"Signing out…":n==="connected"?"Disconnect":n==="loading"?"Connecting…":"Connect",f=n==="connected"?"Disconnect from gateway":n==="loading"?"Checking gateway session…":"Connect to gateway";return s.jsxs("div",{className:`af-topbar${e.className?` ${e.className}`:""}`,role:"group","aria-label":"App actions",children:[e.assistant?s.jsx("button",{type:"button",className:`af-topbar__btn${e.assistant.open?" is-active":""}`,"aria-pressed":e.assistant.open,"aria-label":e.assistant.label||"Open assistant",title:e.assistant.label||"Assistant",onClick:e.assistant.onToggle,children:s.jsx(Qe,{name:"sparkle",size:16})}):null,e.appearance?s.jsx("button",{type:"button",className:"af-topbar__btn","aria-label":e.appearance.label||"Appearance (theme and typography)",title:e.appearance.label||"Appearance",onClick:e.appearance.onOpen,children:s.jsx(Qe,{name:"contrast",size:16})}):null,u?s.jsx("button",{type:"button",className:"af-topbar__btn af-topbar__btn--about","aria-label":u.label||`About ${u.identity.name}`,title:u.label||"About","aria-haspopup":"dialog",onClick:()=>{var _;l(!0),(_=u.onOpen)==null||_.call(u)},children:s.jsx(Qe,{name:"info",size:16})}):null,e.extraActions,s.jsxs("button",{type:"button",className:`af-topbar__pill af-topbar__pill--${n}`,onClick:n==="connected"?t.onDisconnect:t.onConnect,disabled:i,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(yS,{open:o,onClose:()=>l(!1),identity:u.identity,extraRows:u.extraRows}):null]})}const cm={theme:"dark",font_scale:"md",header_density:"standard"};function vS(e){const t=e&&typeof e=="object"?e:{};return{theme:typeof t.theme=="string"&&t.theme?t.theme:cm.theme,font_scale:typeof t.font_scale=="string"&&t.font_scale?t.font_scale:cm.font_scale,header_density:typeof t.header_density=="string"&&t.header_density?t.header_density:cm.header_density}}function xS(e){return`af_appearance_${e}_v1`}function bS(e,t){const n=xS(e),i=m.useMemo(()=>({...cm,...(t==null?void 0:t.defaults)||{}}),[JSON.stringify((t==null?void 0:t.defaults)||{})]),[o,l]=m.useState(()=>{let u=i;try{const c=localStorage.getItem(n)??(t!=null&&t.legacyKey?localStorage.getItem(t.legacyKey):null);c&&(u=vS({...i,...JSON.parse(c)}))}catch{}try{vy(u.theme),xy({font_scale:u.font_scale,header_density:u.header_density})}catch{}return u});return m.useEffect(()=>{vy(o.theme),xy({font_scale:o.font_scale,header_density:o.header_density});try{localStorage.setItem(n,JSON.stringify(o))}catch{}},[n,o]),[o,l]}function jS(e){return m.useEffect(()=>{if(!e.open)return;const t=n=>{n.key!=="Escape"||n.defaultPrevented||(n.preventDefault(),e.onClose())};return window.addEventListener("keydown",t),()=>window.removeEventListener("keydown",t)},[e.open,e.onClose]),e.open?s.jsx("div",{className:"af-appearance-overlay",onClick:e.onClose,role:"presentation",children:s.jsxs("div",{className:"af-appearance",role:"dialog","aria-modal":"true","aria-label":e.title||"Appearance",onClick:t=>t.stopPropagation(),children:[s.jsx("div",{className:"af-appearance__title",children:e.title||"Appearance"}),s.jsx("div",{className:"af-appearance__note",children:e.note||"Stored locally in this browser, per app."}),s.jsxs("div",{className:"af-appearance__grid",children:[s.jsx("label",{className:"af-appearance__label",children:"Theme"}),s.jsx(Vj,{value:e.value.theme,onChange:t=>e.onChange({...e.value,theme:t})}),s.jsx("label",{className:"af-appearance__label",children:"Font size"}),s.jsx(Gj,{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(Kj,{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 SS={diary:"var(--accent)",question:"#e7b45a",dream:"#c084dd",interest:"#7bd88a",lesson:"#6ea8d8",world_model:"#5eead4"};function Sy(e){const t=String(e||"");return t.length>14?`${t.slice(0,10)}…${t.slice(-4)}`:t}function M_(e){const[t,n]=m.useState(!1),[i,o]=m.useState(null),l=m.useRef(!1),u=typeof e.entryId=="string"&&e.entryId.trim()?e.entryId.trim():null,c=e.kind&&SS[e.kind]||"var(--text-muted)",f=m.useCallback(async()=>{if(!(!u||!e.onOpen||l.current)){l.current=!0,n(!0),o(null);try{await e.onOpen(u)}catch(_){o(String((_==null?void 0:_.message)||_||"could not open"))}finally{l.current=!1,n(!1)}}},[u,e.onOpen]);return!u||!e.onOpen?s.jsxs("span",{className:["af-memory-hint","af-memory-hint--text",e.className||""].filter(Boolean).join(" "),title:e.title,children:[s.jsx("span",{className:"af-memory-hint__dot",style:{background:c},"aria-hidden":"true"}),s.jsx("span",{className:"af-memory-hint__label",children:e.label}),u&&e.showId!==!1?s.jsx("code",{className:"af-memory-hint__id",children:Sy(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:Sy(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,i?s.jsx("span",{className:"af-memory-hint__err",role:"alert",children:i}):null]})}const R_=bt("automations"),kS=bt("trigger-sources"),NS=bt("me/email");class ky 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 CS(e,t){const n=t&&typeof t=="object"?t.detail:void 0;if(n&&typeof n=="object"&&!Array.isArray(n)){const i=n;if(typeof i.reason_code=="string"&&i.reason_code&&typeof i.message=="string"){const o={status:e,code:i.reason_code,message:i.message};return typeof i.field=="string"&&(o.field=i.field),typeof i.command_id=="string"&&(o.command_id=i.command_id),o}}return{status:e,code:"invalid_response",message:`The gateway answered HTTP ${e} without an automation error envelope.`}}function L_(e){const t=new URLSearchParams;for(const[i,o]of Object.entries(e))o!==void 0&&t.set(i,String(o));const n=t.toString();return n?`?${n}`:""}function ES(){const e=globalThis.crypto;if(!e||typeof e.randomUUID!="function")throw new Error("automations client: crypto.randomUUID is unavailable; pass options.newId");return e.randomUUID()}function $S(e){const t=e.newId??ES,n=o=>`${R_}/${encodeURIComponent(o)}`;async function i(o,l,u){const c={accept:"application/json",...e.headers?e.headers():{}},f={method:o,headers:c};u!==void 0&&(c["content-type"]="application/json",f.body=JSON.stringify(u));const _=await e.fetch(Gv(e.baseUrl,l),f),p=await _.text();let y,w=!1;if(p)try{y=JSON.parse(p),w=!0}catch{w=!1}if(!_.ok)throw new ky(CS(_.status,y));if(!w||y===null||typeof y!="object")throw new ky({status:_.status,code:"invalid_response",message:`The gateway answered ${o} ${l} with a body that is not a JSON object.`});return y}return{listAutomations:(o={})=>i("GET",`${R_}${L_({status:o.status,cursor:o.cursor,limit:o.limit})}`),getAutomation:o=>i("GET",n(o)),createAutomation:o=>i("POST",R_,o),reviseAutomation:(o,l)=>i("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)=>i("POST",`${n(o)}/commands`,{command_id:l.command_id??t(),type:l.type,...l.payload!==void 0?{payload:l.payload}:{}}),listOccurrences:(o,l={})=>i("GET",`${n(o)}/occurrences${L_({cursor:l.cursor,limit:l.limit})}`),discuss:(o,l)=>i("POST",`${n(o)}/discuss`,{request_id:l.request_id??t(),occurrence_index:l.occurrence_index,prompt:l.prompt}),markSeen:(o,l)=>i("POST",`${n(o)}/seen`,{attention_cursor:l}),listAttention:(o,l={})=>i("GET",`${n(o)}/attention${L_({cursor:l.cursor,limit:l.limit})}`),listTriggerSources:()=>i("GET",kS),getMyEmail:()=>i("GET",NS)}}const AS={pause:"Pause",resume:"Resume",run_now:"Run now",stop_current:"Stop current",revise:"Edit",archive:"Archive",discuss:"Discuss"},TS={pause:`Stop scheduled runs until you resume.
|
|
54
|
+
A run in progress, with its retries, finishes. Run now still works.`,resume:`Restart the schedule at its next time after now.
|
|
55
|
+
Times missed while paused are skipped; resuming does not run it now.`,run_now:`Run it once now, without waiting for the schedule.
|
|
56
|
+
The schedule does not move: the next scheduled run keeps its time, or starts right after this run if its time comes first.
|
|
57
|
+
Does not count toward a run limit. Works while paused; it stays paused.
|
|
58
|
+
Not available while a run is in progress.`,stop_current:`Cancel the run in progress, or its pending retry.
|
|
59
|
+
It ends as cancelled, with no failure notice. The schedule continues.`,revise:`Change the task, schedule or settings.
|
|
60
|
+
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.
|
|
61
|
+
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.
|
|
62
|
+
It has its own workspace (the automation's files are read-only) and never changes the automation.`},MS="Next scheduled run: {time}.",RS="Growing context: later runs see this run in their history.",LS={run_now:{name:"playCircle"}},IS={trigger_label:"When an email arrives",not_set_up:"Email isn't set up — open My email",open_my_email:"open My email",filters_legend:"Only mail that matches (all optional)",from_in:"From these addresses",from_domain_in:"From these domains",to_in:"Sent to these addresses",subject_contains:"Subject contains",has_attachment:"Attachments",has_attachment_any:"any",has_attachment_yes:"only with attachments",has_attachment_no:"only without attachments",list_hint:"Separate entries with commas or new lines. Exact addresses and domains only (no patterns).",every_label:"Check for new mail every",interval_rule:"An automation that runs a model on new mail checks once an hour by default; one that needs no model checks every 60 s. The shortest interval is 60 s.",max_batch_label:"At most this many emails per run",max_batch_hint:"The rest wait for the next run. Each email is read once by this automation; mail that arrived before it was created, or while it is paused, is not processed.",untrusted_hint:"Incoming mail is data, never instructions: the automation acts only on its task. Link-opening tools (fetch_url, browser_probe) always ask for your approval.",notify_label:"Email me the result",notify_hint:"When a run notifies you, or fails for good, the notice is also emailed to you.",recipients_legend:"May send email without asking to",recipients_self:"Only me (default)",recipients_list:"Me and these addresses",recipients_hint:"Sending to anyone else waits for your approval. Your recipient policy in My email still applies."},Jv={labels:AS,hints:TS,run_now_next_run_line:MS,run_now_growing_line:RS,icons:LS,email:IS},OS=/^([1-9][0-9]*)([smhd])$/,PS={s:["second","seconds"],m:["minute","minutes"],h:["hour","hours"],d:["day","days"]};function Of(e){if(typeof e!="string")return null;const t=OS.exec(e);return t?{amount:Number(t[1]),unit:t[2]}:null}function Xv(e){const t=Of(e);if(!t)return`every ${e}`;const[n,i]=PS[t.unit];return t.amount===1?`every ${n}`:`every ${t.amount} ${i}`}function Na(e){if(!e)return"";const t=Date.parse(e);if(Number.isNaN(t))return e;const n=new Date(t).toISOString(),i=n.slice(17,19);return`${n.slice(0,10)} ${n.slice(11,16)}${i==="00"?"":`:${i}`} UTC`}function Zv(e){const t=e;if(typeof t.every!="string")return t.start_at?`once at ${Na(t.start_at)}`:"once, now";const n=[`${Xv(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 ${Na(t.until)}`),n.join(" · ")}function _g(e){return e.source_id==="schedule"&&e.source_version===1?Zv(e.config):e.source_id==="manual"&&e.source_version===1?"manual runs only":Wm(e)?ox(e.config):`${e.source_id}@${e.source_version}`}function Qv(e){return e==="growing"?"Growing — each run sees the previous runs":"Independent — each run starts fresh"}const DS={active:"Active",paused:"Paused",completed:"Completed",failed:"Failed",archived:"Archived"},qt=Jv.email,ex="email.received",tx=1,FS="1h",zS="60s",nx=60,pg=100,$p=1e3,Ny=200,Cy=200,Ey=50;function Wm(e){return!!e&&e.source_id===ex&&e.source_version===tx}function qm(e){return!!e&&e.effective_enabled===!0}function sx(e){const t=[];for(const n of String(e??"").split(/[\s,;]+/)){const i=n.trim().toLowerCase();i&&!t.includes(i)&&t.push(i)}return t}const BS=/[\s<>,;:"()[\]]/;function Ap(e){const t=e.trim().toLowerCase(),n=t.indexOf("@");return n<=0||n===t.length-1?!1:!t.slice(n+1).includes("@")&&!BS.test(t)}function US(e){const t=e.trim().toLowerCase();return!!t&&!t.includes("@")&&t.includes(".")&&!t.startsWith(".")&&!t.endsWith(".")&&!/[\s<>,;:"()[\]/*]/.test(t)}const rx={usesModel:!0,every:null,maxBatch:null,fromIn:"",fromDomainIn:"",toIn:"",subjectContains:"",hasAttachment:"any"};function gg(e){return e?FS:zS}function ix(e){const t=Of(e);return t?t.amount*{s:1,m:60,h:3600,d:86400}[t.unit]:null}function I_(e,t,n,i,o){const l=sx(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"} ${i}.`),l.length>Ny&&o.push(`${t}: at most ${Ny} entries.`),l}function WS(e){const t=[],n={uses_model:e.usesModel};e.every===null?n.every=gg(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&&(ix(n.every)??0)<nx&&t.push("The check interval is at least 60 seconds."),e.maxBatch===null?n.max_batch=pg:!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 i={},o=I_(e.fromIn,qt.from_in,Ap,"an email address",t);o&&(i.from_in=o);const l=I_(e.fromDomainIn,qt.from_domain_in,US,"a domain like example.com",t);l&&(i.from_domain_in=l);const u=I_(e.toIn,qt.to_in,Ap,"an email address",t);u&&(i.to_in=u);const c=e.subjectContains.trim();return c&&(c.length>Cy||/[\r\n]/.test(c)?t.push(`${qt.subject_contains}: one line of at most ${Cy} characters.`):i.subject_contains=c),e.hasAttachment==="yes"?i.has_attachment=!0:e.hasAttachment==="no"&&(i.has_attachment=!1),Object.keys(i).length&&(n.filter=i),{config:n,errors:t}}function ox(e){const t=e,n=t.filter??{},i=["when an email arrives"],o=[...n.from_in??[],...n.from_domain_in??[]];o.length&&i.push(`from ${o.join(", ")}`),n.to_in&&n.to_in.length&&i.push(`to ${n.to_in.join(", ")}`),typeof n.subject_contains=="string"&&n.subject_contains&&i.push(`subject contains “${n.subject_contains}”`),n.has_attachment===!0&&i.push("with attachments"),n.has_attachment===!1&&i.push("without attachments");const l=typeof t.every=="string"?t.every:gg(t.uses_model!==!1);i.push(`checked ${Xv(l)}`);const u=typeof t.max_batch=="number"?t.max_batch:pg;return i.push(`up to ${u} per run`),i.join(" · ")}const yg={mode:"self",addresses:""};function Tp(e){if(e.mode==="self")return{recipients:["self"],errors:[]};const t=[],n=sx(e.addresses).filter(o=>o!=="self");n.length||t.push("Name at least one address the automation may email, or choose Only me.");const i=n.filter(o=>!Ap(o));return i.length&&t.push(`${qt.recipients_list}: ${i.join(", ")} ${i.length===1?"is not an email address":"are not email addresses"}.`),n.length+1>Ey&&t.push(`At most ${Ey-1} addresses.`),{recipients:["self",...n],errors:t}}function qS(e){const t=(e??[]).filter(n=>n!=="self");return t.length?{mode:"list",addresses:t.join(", ")}:{mode:"self",addresses:""}}function HS(e){const t=(e??["self"]).filter(n=>n!=="self");return t.length?`Me and ${t.join(", ")}`:"Only me"}function ax(e){return{channels:e?["console","email"]:["console"]}}function lx(e){return!!e&&Array.isArray(e.channels)&&e.channels.includes("email")}function VS(e){return lx(e)?"In the console and by email":"In the console"}const Bo={pause:"automation.pause",resume:"automation.resume",run_now:"automation.run_now",stop_current:"automation.stop_current",archive:"automation.archive"},GS=new Set(["running","waiting","backoff"]);function KS(e,t=[]){return e.current_occurrence!=null}function cx(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 ux(e,t){const n=Date.parse(e);if(Number.isNaN(n))return"";const i=Math.round((n-t)/6e4);if(i<=0)return"due now";if(i<60)return`in ${i} min`;const o=Math.floor(i/60);return o<24?`in ${o} h${i%60?` ${i%60} min`:""}`:`in ${Math.floor(o/24)} d${o%24?` ${o%24} h`:""}`}function wm(e,t=[],n=!1){const i=new Set(e.capabilities),o=e.status,l=KS(e,t),u=(f,_,p)=>n?{enabled:!1,reason:"Working…"}:e.legacy?{enabled:!1,reason:"Legacy schedule: managed with its existing controls."}:i.has(f)?o==="archived"?{enabled:!1,reason:"Archived: history is kept, nothing runs."}:_?{enabled:!0}:{enabled:!1,reason:p}:{enabled:!1,reason:"Not permitted for this automation."},c=o==="active"||o==="paused";return{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."}:i.has("discuss")?{enabled:!0}:{enabled:!1,reason:"Discussion is not permitted for this automation."}}}function YS(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 JS(e){return[...e].sort((t,n)=>t.index-n.index).map(t=>{const n=YS(t),i=`${t.attempts} ${t.attempts===1?"attempt":"attempts"}`,o=n==="failed"?`Failed after ${i}`:n==="waiting"?"Waiting for you":n==="notified"?"Notified":n==="running"?"Running":null,l=t.status==="completed"&&t.attempts>1?`completed after ${i}`:t.status;return{row:t,tone:n,notable:n==="failed"||n==="waiting"||n==="notified",badge:o,statusText:l,canDiscuss:!GS.has(t.status)}})}function XS(e){const t=e.attention.items;return t.length?t[t.length-1].cursor:null}function dx(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 ZS={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 vm(e){return{title:ZS[e.code]??`The gateway refused the request (${e.code}).`,detail:e.message}}function wg(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 fx(e,t){const n=e.trigger,i=n.source_id==="schedule"||Wm(n)?n.config.every:void 0,o=t?t.target.input_data.prompt:void 0;return{title:e.title,every:typeof i=="string"?i:null,context:e.context_mode,prompt:typeof o=="string"?o:null,toolApproval:t?t.policy.tool_approval:null,notifyEmail:t?lx(t.notify):null,emailRecipients:t?qS(t.policy.email_allowed_recipients):null}}function QS(e,t,n){const i=[],o={},l=t.title.trim();l?l.length>120?i.push("Title is at most 120 characters."):l!==e.title&&(o.title=l):i.push("Title is required.");const u=fx(e,n);if(t.every!==u.every&&t.every!==null){const c=Wm(e.trigger);if(!Of(t.every))i.push("Interval must be a whole number of minutes, hours or days.");else if(c&&(ix(t.every)??0)<nx)i.push("The check interval is at least 60 seconds.");else{const f={...e.trigger.config,every:t.every};c&&delete f.start_at,o.trigger={source_id:e.trigger.source_id,source_version:e.trigger.source_version,config:f}}}if(t.context!==e.context_mode&&(o.context={mode:t.context}),n&&typeof u.prompt=="string"&&typeof t.prompt=="string"&&t.prompt.trim()!==u.prompt.trim()){const c=t.prompt.trim();c?o.target={bundle_ref:n.target.bundle_ref,flow_id:n.target.flow_id,input_data:{...n.target.input_data,prompt:c}}:i.push("Task is required.")}if(n&&t.toolApproval&&t.toolApproval!==u.toolApproval&&(o.policy={tool_approval:t.toolApproval}),n&&typeof t.notifyEmail=="boolean"&&t.notifyEmail!==u.notifyEmail&&(o.notify=ax(t.notifyEmail)),n&&t.emailRecipients){const c=Tp(t.emailRecipients),f=Tp(u.emailRecipients??yg).recipients;c.errors.length?i.push(...c.errors):JSON.stringify(c.recipients)!==JSON.stringify(f)&&(o.policy={...o.policy??{},email_allowed_recipients:c.recipients})}return i.length?{errors:i}:Object.keys(o).length?o:null}const ek=[{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 O_(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 tk(e){const t=e.trim().split(`
|
|
63
|
+
`)[0].trim();return t.length>120?`${t.slice(0,119)}…`:t}function nk(e){const t=[],n={};if(e.when.kind==="once"){const o=O_(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 i=e.when.amount;if(!Number.isInteger(i)||i<1?t.push("The interval must be a whole number of at least 1."):n.every=`${i}${e.when.unit}`,e.startAt){const o=O_(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=O_(e.until);o?n.until=o:t.push("Stop at must be a date and time (UTC).")}return{config:n,errors:t}}function Mp(e,t){const n=[];t.target||n.push("Choose what to run.");const i=e.prompt.trim();i||n.push("Write the task to run.");const o=(e.title??"").trim()||tk(i);o.length>120&&n.push("Title is at most 120 characters.");const l=e.trigger==="email",u=l?WS(e.email??rx):nk(e);n.push(...u.errors);const c=e.emailRecipients&&e.emailRecipients.mode==="list"?Tp(e.emailRecipients):null;if(c&&n.push(...c.errors),n.length||!t.target)return{ok:!1,errors:n};const f={...t.target,input_data:{...t.target.input_data??{},prompt:i}},_={request_id:t.requestId,title:o,target:f,trigger:l?{source_id:ex,source_version:tx,config:u.config}:{source_id:"schedule",source_version:1,config:u.config},context:{mode:e.context},policy:{tool_approval:e.toolApproval??"auto",...c?{email_allowed_recipients:c.recipients}:{}}};return e.notifyEmail===!0&&(_.notify=ax(!0)),{ok:!0,body:_}}const sk="Tools run without asking (you approve them now by creating this automation)";function rk(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 i=n;if(typeof i.name!="string"||!i.arguments||typeof i.arguments!="object"||Array.isArray(i.arguments)||i.call_id!==void 0&&typeof i.call_id!="string")return null;t.push({name:i.name,arguments:i.arguments,...typeof i.call_id=="string"?{call_id:i.call_id}:{}})}return t}function ik(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 hx={ask_user:"Question for you",tool_approval:"Approval needed",event:"Waiting for an event"};class ok{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||ak(n.error))&&this.open.delete(t)}}function ak(e){return wg(e)&&e.status>0&&e.code!=="invalid_response"}function lk(){const e=globalThis.crypto;if(!e||typeof e.randomUUID!="function")throw new Error("crypto.randomUUID is unavailable; pass newId");return e.randomUUID()}class ck{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 $y(e,t){if(!e)return null;for(const n of t){const i=e.querySelector(n);if(i&&i.disabled!==!0&&typeof i.focus=="function")return i}return null}function Rp(e){if(qm(e.status))return null;const t=qt.not_set_up,n=qt.open_my_email,i=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:[i,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 uk(e){const t=e.value,n=c=>e.onChange({...t,...c}),i=c=>`${e.idBase}-email-${c}`,o=Of(gg(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:qt.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:qt.interval_rule}),s.jsxs("label",{className:"af-auto__field",htmlFor:i("batch"),children:[s.jsx("span",{children:qt.max_batch_label}),s.jsx("input",{id:i("batch"),name:"email_max_batch",type:"number",min:1,max:$p,step:1,disabled:u,value:String(t.maxBatch??pg),onChange:c=>n({maxBatch:c.target.value.trim()===""?null:Number(c.target.value)})})]}),s.jsx("p",{className:"af-auto__hint",children:qt.max_batch_hint}),s.jsxs("fieldset",{className:"af-auto__field af-email__filters",disabled:u,children:[s.jsx("legend",{children:qt.filters_legend}),s.jsxs("label",{className:"af-auto__field",htmlFor:i("from"),children:[s.jsx("span",{children:qt.from_in}),s.jsx("input",{id:i("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:i("domain"),children:[s.jsx("span",{children:qt.from_domain_in}),s.jsx("input",{id:i("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:i("to"),children:[s.jsx("span",{children:qt.to_in}),s.jsx("input",{id:i("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:i("subject"),children:[s.jsx("span",{children:qt.subject_contains}),s.jsx("input",{id:i("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:i("attach"),children:[s.jsx("span",{children:qt.has_attachment}),s.jsxs("select",{id:i("attach"),name:"email_has_attachment",value:t.hasAttachment,onChange:c=>n({hasAttachment:c.target.value}),children:[s.jsx("option",{value:"any",children:qt.has_attachment_any}),s.jsx("option",{value:"yes",children:qt.has_attachment_yes}),s.jsx("option",{value:"no",children:qt.has_attachment_no})]})]}),s.jsx("p",{className:"af-auto__hint",children:qt.list_hint})]})]})}function dk(e){const t=i=>`${e.idBase}-email-${i}`,n=e.disabled===!0;return s.jsxs("div",{className:"af-email__options","data-field":"email-options",children:[s.jsxs("label",{className:"af-email__check",children:[s.jsx("input",{type:"checkbox",name:"notify_email",checked:e.notifyEmail,disabled:n,onChange:i=>e.onNotifyEmailChange(i.target.checked)})," ",qt.notify_label]}),s.jsx("p",{className:"af-auto__hint",children:qt.notify_hint}),s.jsxs("fieldset",{className:"af-auto__field",disabled:n,"data-field":"email-recipients",children:[s.jsx("legend",{children:qt.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"})})," ",qt.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"})})," ",qt.recipients_list]}),e.recipients.mode==="list"?s.jsx("textarea",{name:"email_recipient_list","aria-label":qt.recipients_list,rows:2,spellCheck:!1,value:e.recipients.addresses,placeholder:"colleague@example.com",onChange:i=>e.onRecipientsChange({mode:"list",addresses:i.target.value})}):null,s.jsx("p",{className:"af-auto__hint",children:qt.recipients_hint})]})]})}const fk={active:"play",paused:"pause",completed:"check",failed:"error",archived:"archive"};function mx(e){const t=String(e.status),n=fk[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:DS[t]??t}),n?s.jsx(Qe,{name:n,size:e.iconSize??11,className:"af-auto__status-icon"}):null]})}const Lp="Discuss — fork at this occurrence (own workspace, automation files read-only)",Hm=e=>s.jsx("div",{className:"af-auto-text","data-unformatted":"true",children:e});function hk(e){return wg(e)?e:{status:0,code:"client_error",message:e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}}function Ay(e){const t=e.path.split(new RegExp("(?<=[/\\\\_-])"));return s.jsx("code",{className:"af-auto__path-text",children:t.map((n,i)=>s.jsxs(ve.Fragment,{children:[n,i<t.length-1?s.jsx("wbr",{}):null]},i))})}function mk(e,t){const n=e.trigger,i=t.find(o=>o.id===n.source_id&&o.version===n.source_version);return i?"available"in i&&i.available===!1?`Trigger source ${n.source_id}@${n.source_version} is unavailable${i.unavailable_reason?`: ${i.unavailable_reason}`:"."}`:null:`This gateway does not list the trigger source ${n.source_id}@${n.source_version}.`}function _k(e){const t=e.summary,n=cx(t),i=mk(t,e.triggerSources),o=t.next_fire_at?`${Na(t.next_fire_at)} (${ux(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(mx,{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:[_g(t.trigger),i?s.jsxs("span",{className:"af-auto__warn",role:"note",children:[" ",i]}):null]}),s.jsx("dt",{children:"Context"}),s.jsx("dd",{"data-fact":"context",children:Qv(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
|
|
64
|
+
${t.workspace_root}`,"aria-label":`Browse the automation's folder ${t.workspace_root}`,onClick:()=>{var l;return(l=e.onOpenWorkspace)==null?void 0:l.call(e,t.automation_id)},children:[s.jsx(Qe,{name:"folder",size:14,className:"af-auto__path-icon"}),s.jsx(Ay,{path:t.workspace_root})]}):s.jsxs("span",{className:"af-auto__path af-auto__path--static",children:[s.jsx(Qe,{name:"folder",size:14,className:"af-auto__path-icon"}),s.jsx(Ay,{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:dx(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 pk(e){const t=e.definition,n=e.renderText??Hm,i=t.target.input_data.prompt,o=t.policy.retry,l=t.policy.tool_approval;return s.jsxs("details",{className:"af-auto__definition","data-definition-revision":t.revision,open:e.open,children:[s.jsxs("summary",{children:[s.jsx(Qe,{name:"chevronRight",size:14,className:"af-auto__definition-chevron"}),s.jsx(Qe,{name:"file",size:14}),s.jsx("span",{className:"af-auto__definition-title",children:"Definition"}),s.jsxs("span",{className:"af-auto__definition-meta",children:["revision ",t.revision]})]}),s.jsxs("dl",{className:"af-auto__facts",children:[s.jsx("dt",{children:"Target"}),s.jsx("dd",{"data-def":"target",children:s.jsx("code",{children:t.target.workflow_id})}),typeof i=="string"&&i?s.jsxs(s.Fragment,{children:[s.jsx("dt",{children:"Task"}),s.jsx("dd",{"data-def":"prompt",children:n(i)})]}):null,s.jsx("dt",{children:"Trigger"}),s.jsxs("dd",{"data-def":"trigger",children:[t.trigger.source_id,"@",t.trigger.source_version," · ",_g(t.trigger),s.jsx("pre",{className:"af-auto__json",children:JSON.stringify(t.trigger.config,null,2)})]}),s.jsx("dt",{children:"Context"}),s.jsx("dd",{"data-def":"context",children:Qv(t.context.mode)}),s.jsx("dt",{children:"Tools"}),s.jsx("dd",{"data-def":"tool_approval",children:l==="ask"?"Ask before each tool call (ask)":l==="auto"?"Run without asking (auto)":String(l)}),s.jsx("dt",{children:"Notify"}),s.jsx("dd",{"data-def":"notify",children:VS(t.notify)}),s.jsx("dt",{children:"May email"}),s.jsx("dd",{"data-def":"email_allowed_recipients",children:HS(t.policy.email_allowed_recipients)}),s.jsx("dt",{children:"Retries"}),s.jsxs("dd",{"data-def":"retry",children:[o.max_attempts," ",o.max_attempts===1?"attempt":"attempts",", backoff ",o.backoff.initial," ×",o.backoff.factor," up to ",o.backoff.max]}),s.jsx("dt",{children:"Revision"}),s.jsx("dd",{"data-def":"revision",children:t.revision})]})]})}const Pf=Jv,cl=Pf.labels,so={pause:"pause",resume:"play",run_now:Pf.icons.run_now.name,stop_current:"stop",revise:"edit",archive:"archive",discuss:"chat"},Ip=Pf.hints,gk=Pf.run_now_next_run_line,yk=Pf.run_now_growing_line;function _x(e,t){const n=[Ip[e]];return e==="run_now"&&t&&(t.next_fire_at&&n.push(gk.replace("{time}",Na(t.next_fire_at))),t.context_mode==="growing"&&n.push(yk)),n.join(`
|
|
65
|
+
`)}function wk(e,t,n){const i=new Map;for(const u of t){const c=e[u];if(c.enabled)continue;const f=c.reason??"Not available now.";i.set(f,[...i.get(f)??[],u])}const o=[],l={};return[...i.entries()].forEach(([u,c],f)=>{const _=`${n}-why-${f}`;o.push({id:_,text:`${c.map(p=>cl[p]).join(", ")}: ${u}`});for(const p of c)l[p]=_}),{lines:o,describedBy:l}}function dr(e){return s.jsxs(s.Fragment,{children:[s.jsx(Qe,{name:e.icon,size:14,className:"af-auto__btn-icon"}),s.jsx("span",{children:e.label})]})}function vk(e){const t=wm(e.summary,e.occurrences,e.busy),n=[e.summary.status==="paused"?"resume":"pause","run_now","stop_current","revise","archive"],i=wk(t,n,e.idBase??`af-auto-${e.summary.automation_id}`),o=(l,u,c)=>{const f=_x(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}
|
|
66
|
+
${f}`,"aria-description":f,"aria-describedby":i.describedBy[l],"aria-pressed":c==null?void 0:c.pressed,onClick:u,children:s.jsx(dr,{icon:so[l],label:(c==null?void 0:c.label)??cl[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:[e.summary.status==="paused"?o("resume",()=>e.onCommand(Bo.resume)):o("pause",()=>e.onCommand(Bo.pause)),o("run_now",()=>e.onCommand(Bo.run_now)),o("stop_current",()=>e.onCommand(Bo.stop_current)),o("revise",e.onToggleRevise,{pressed:e.reviseOpen,action:"edit"}),o("archive",e.onAskArchive,{danger:!0,label:"Archive…"})]}),s.jsx("span",{className:`af-auto__notice${e.notice?" af-auto__notice--on":""}`,role:"status",tabIndex:-1,children:e.notice?s.jsxs(s.Fragment,{children:[s.jsx(Qe,{name:"check",size:13}),s.jsx("span",{className:"af-auto__notice-text",children:e.notice}),e.onDismissNotice?s.jsx("button",{type:"button",className:"af-auto__icon-btn af-auto__icon-btn--bare","data-action":"dismiss-notice","aria-label":"Dismiss",title:"Dismiss",onClick:e.onDismissNotice,children:s.jsx(Qe,{name:"x",size:12})}):null]}):null})]}),i.lines.length?s.jsxs("p",{className:"af-auto__reasons",children:[s.jsx(Qe,{name:"info",size:12,className:"af-auto__reasons-icon"}),i.lines.map(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(Bo.archive),children:s.jsx(dr,{icon:"archive",label:"Archive"})}),s.jsx("button",{type:"button",className:"af-auto__btn","data-action":"archive-cancel",onClick:e.onCancelArchive,children:s.jsx(dr,{icon:"x",label:"Keep it"})})]})]}):null]})}const Ty=[["m","minutes"],["h","hours"],["d","days"]];function xk(e,t){const n=E=>{const A=e.elements.namedItem(E);return A&&typeof A.value=="string"?A.value:null},i=n("every_amount"),o=n("every_unit"),l=i!==null&&o!==null?`${i.trim()}${o}`:t.every,u=e.elements.namedItem("context"),c=u&&(u.value==="growing"||u.value==="independent")?u.value:t.context,f=n("prompt"),_=e.elements.namedItem("tool_approval"),p=_&&(_.value==="auto"||_.value==="ask")?_.value:t.toolApproval??null,y=e.elements.namedItem("notify_email"),w=y&&typeof y.checked=="boolean"?y.checked:t.notifyEmail??null,x=e.elements.namedItem("email_recipients"),S=n("email_recipient_list"),j=x&&(x.value==="self"||x.value==="list")?{mode:x.value,addresses:S??""}:t.emailRecipients??null;return{title:n("title")??t.title,every:l,context:c,prompt:f??t.prompt??null,toolApproval:p,notifyEmail:w,emailRecipients:j}}function bk(e){const t=fx(e.summary,e.definition),n=t.every?Of(t.every):null,i=n&&n.unit==="s"?[["s","seconds"],...Ty]:Ty,o=`af-auto-revise-${e.summary.automation_id}`,l=qm(e.emailStatus),u=Wm(e.summary.trigger);return s.jsxs("form",{className:"af-auto__revise","aria-labelledby":`${o}-heading`,onSubmit:c=>{c.preventDefault(),e.onSubmit(xk(c.currentTarget,t))},onKeyDown:c=>{c.key==="Escape"&&(c.preventDefault(),e.onCancel())},children:[s.jsxs("h3",{className:"af-auto__form-title",id:`${o}-heading`,children:[s.jsx(Qe,{name:"edit",size:14})," Edit automation"]}),s.jsxs("label",{className:"af-auto__field",htmlFor:`${o}-title`,children:[s.jsx("span",{children:"Title"}),s.jsx("input",{id:`${o}-title`,name:"title",defaultValue:t.title,maxLength:120,required:!0})]}),t.prompt!==null&&t.prompt!==void 0?s.jsxs("label",{className:"af-auto__field",htmlFor:`${o}-prompt`,children:[s.jsx("span",{children:"Task"}),s.jsx("textarea",{id:`${o}-prompt`,name:"prompt",defaultValue:t.prompt,rows:Math.min(10,Math.max(3,t.prompt.split(`
|
|
67
|
+
`).length+1)),required:!0})]}):null,n?s.jsxs("fieldset",{className:"af-auto__field",children:[s.jsx("legend",{children:u?qt.every_label:"Repeat every (UTC)"}),s.jsxs("div",{className:"af-auto__row",children:[s.jsx("input",{name:"every_amount",type:"number",min:1,step:1,defaultValue:n.amount,"aria-label":"Interval amount"}),s.jsx("select",{name:"every_unit",defaultValue:n.unit,"aria-label":"Interval unit",children:i.map(([c,f])=>s.jsx("option",{value:c,children:f},c))})]}),u?s.jsx("p",{className:"af-auto__hint","data-email-rule":"interval",children:qt.interval_rule}):null]}):s.jsx("p",{className:"af-auto__hint",children:"This trigger has no interval to change."}),s.jsxs("fieldset",{className:"af-auto__field",children:[s.jsx("legend",{children:"Context"}),s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:"context",value:"independent",defaultChecked:t.context==="independent"})," Independent — each run starts fresh"]}),s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:"context",value:"growing",defaultChecked:t.context==="growing"})," Growing — each run sees the previous runs"]})]}),t.toolApproval?s.jsxs("fieldset",{className:"af-auto__field",children:[s.jsx("legend",{children:"Tools"}),s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:"tool_approval",value:"auto",defaultChecked:t.toolApproval==="auto"})," Run without asking"]}),s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:"tool_approval",value:"ask",defaultChecked:t.toolApproval==="ask"})," Ask before each tool call"]})]}):null,t.notifyEmail!==null&&t.notifyEmail!==void 0&&t.emailRecipients?s.jsxs("fieldset",{className:"af-auto__field","data-field":"email",children:[s.jsx("legend",{children:"Email"}),l?null:s.jsx(Rp,{status:e.emailStatus,onOpenMyEmail:e.onOpenMyEmail}),s.jsxs("label",{className:"af-email__check",children:[s.jsx("input",{type:"checkbox",name:"notify_email",defaultChecked:t.notifyEmail,disabled:!l&&!t.notifyEmail})," ",qt.notify_label]}),s.jsx("p",{className:"af-auto__hint",children:qt.notify_hint}),s.jsxs("fieldset",{className:"af-auto__field","data-field":"email-recipients",children:[s.jsx("legend",{children:qt.recipients_legend}),s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:"email_recipients",value:"self",defaultChecked:t.emailRecipients.mode==="self"})," ",qt.recipients_self]}),s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:"email_recipients",value:"list",defaultChecked:t.emailRecipients.mode==="list",disabled:!l&&t.emailRecipients.mode!=="list"})," ",qt.recipients_list]}),s.jsx("textarea",{name:"email_recipient_list","aria-label":qt.recipients_list,rows:2,spellCheck:!1,defaultValue:t.emailRecipients.addresses,disabled:!l&&t.emailRecipients.mode!=="list"}),s.jsx("p",{className:"af-auto__hint",children:qt.recipients_hint})]})]}):null,s.jsx("p",{className:"af-auto__hint",children:"Changes apply from the next run; a new interval never fires past ticks."}),e.errors.length?s.jsx("ul",{className:"af-auto__form-errors",role:"alert",children:e.errors.map(c=>s.jsx("li",{children:c},c))}):null,s.jsxs("div",{className:"af-auto__row",children:[s.jsx("button",{type:"submit",className:"af-auto__btn af-auto__btn--primary","data-action":"edit-save",disabled:e.busy,children:s.jsx(dr,{icon:"check",label:"Save changes"})}),s.jsx("button",{type:"button",className:"af-auto__btn","data-action":"edit-cancel",onClick:e.onCancel,children:s.jsx(dr,{icon:"x",label:"Cancel"})})]})]})}function Op(e,t){const n=e.elements.namedItem(t);return n&&typeof n.value=="string"?n.value.trim():""}function jk(e){const t=e.wait,n=`${e.idBase}-${t.run_id}-${t.wait_key}-prompt`,i=u=>e.onAnswerWait(t.run_id,t.wait_key,u),o=e.renderText??Hm,l=u=>s.jsxs("div",{className:"af-auto-wait__prompt",id:n,children:[s.jsx("span",{className:"af-auto-wait__kind",children:hx[t.kind]??"Waiting"}),t.prompt?o(t.prompt):s.jsxs("span",{children:[" ",u]})]});if(t.kind==="tool_approval"){const u=rk(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:()=>i({approved:!0}),children:s.jsx(dr,{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:()=>i({approved:!1}),children:s.jsx(dr,{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=ik(Op(u.currentTarget,"payload"));c.ok?i({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(dr,{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=Op(u.currentTarget,"response");c&&i({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:()=>i({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(dr,{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 Sk(e){const{row:t,tone:n,badge:i,statusText:o}=e.view,l=`af-auto-occ-${t.run_id}`,u=e.renderText??Hm,c=e.discuss.enabled&&e.view.canDiscuss&&!e.busy,f=e.discuss.enabled?e.view.canDiscuss?null:"Available once this occurrence finishes.":e.discuss.reason??"Not available.",_=(w,x)=>e.renderTurn?e.renderTurn({kind:w,role:w==="trigger"?"user":"assistant",text:x,index:t.index,runId:t.run_id}):u(x),p=e.renderTurn?" af-auto-turn--card":"",y=n==="failed"?t.failure?"No answer.":"No answer: the run failed.":n==="waiting"?"Waiting for your answer.":n==="running"?"Running…":"No answer.";return s.jsxs("li",{className:`af-auto-occ af-auto-occ--${n}`,"data-index":t.index,"data-tone":n,"aria-labelledby":`${l}-h`,children:[s.jsxs("div",{className:`af-auto-turn af-auto-turn--trigger${p}`,"data-turn":"trigger",children:[s.jsxs("div",{className:"af-auto-turn__meta",id:`${l}-h`,children:[s.jsxs("span",{className:"af-auto-turn__index",children:["#",t.index]})," · ",t.trigger.summary," · fired ",Na(t.fired_at)]}),s.jsx("div",{className:"af-auto-turn__text",children:_("trigger",t.user_turn)})]}),s.jsxs("div",{className:`af-auto-turn af-auto-turn--answer${p}`,"data-turn":"answer",children:[s.jsxs("div",{className:"af-auto-turn__meta",children:[i?s.jsx("span",{className:`af-auto-badge af-auto-badge--${n}`,children:i}):null,s.jsx("span",{className:"af-auto-turn__status",children:o}),t.finished_at?s.jsxs("span",{children:[" · ",Na(t.finished_at)]}):null]}),t.notify?s.jsxs("div",{className:"af-auto-notify","data-notify":"true",children:[s.jsx("strong",{children:t.notify.title}),t.notify.body?s.jsx("div",{className:"af-auto-notify__body",children:u(t.notify.body)}):null]}):null,t.failure?s.jsxs("div",{className:"af-auto-failure","data-failure":t.failure.reason_code,children:[s.jsx("strong",{children:t.failure.reason_code}),": ",t.failure.message," ",s.jsxs("span",{className:"af-auto-turn__muted",children:["(after ",t.failure.attempts," ",t.failure.attempts===1?"attempt":"attempts",")"]})]}):null,t.answer?s.jsx("div",{className:"af-auto-turn__text",children:_("answer",t.answer)}):s.jsx("div",{className:"af-auto-turn__empty",children:y}),t.artifacts.length?s.jsx("ul",{className:"af-auto-artifacts","aria-label":"Artifacts",children:t.artifacts.map(w=>s.jsxs("li",{children:[e.onOpenResource?s.jsxs("button",{type:"button",className:"af-auto__linkbtn","data-action":"open-artifact",onClick:()=>{var x;return(x=e.onOpenResource)==null?void 0:x.call(e,{kind:"artifact",url:w.url,name:w.name,mimeType:w.mime_type,runId:t.run_id})},children:[s.jsx(Qe,{name:"file",size:13,className:"af-auto__btn-icon"})," ",w.name]}):s.jsx("span",{className:"af-auto-artifact__name",children:w.name})," ",s.jsx("span",{className:"af-auto-turn__muted",children:w.mime_type})]},w.artifact_id))}):null,t.waits.map(w=>s.jsx(jk,{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(dr,{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(dr,{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(dr,{icon:"folder",label:"Workspace"})}):null]})]}),e.discussOpen?s.jsxs("form",{className:"af-auto-discuss","aria-label":`${Lp}, from occurrence ${t.index}`,onSubmit:w=>{w.preventDefault();const x=Op(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(dr,{icon:"send",label:"Start discussion"})}),s.jsx("button",{type:"button",className:"af-auto__btn","data-action":"discuss-cancel",onClick:e.onDiscussCancel,children:s.jsx(dr,{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:Ip.discuss,"aria-description":Ip.discuss,"aria-describedby":f?`${l}-discuss-why`:void 0,onClick:()=>e.onDiscussOpen(t.index),children:s.jsx(dr,{icon:so.discuss,label:Lp})}),f?s.jsx("span",{className:"af-auto__reasons",id:`${l}-discuss-why`,children:f}):null]})]})]})}const kk=5e3,Nk={[Bo.pause]:"Pause sent.",[Bo.resume]:"Resume sent.",[Bo.run_now]:"Run requested.",[Bo.stop_current]:"Stop sent."};function Ck(e){const{summary:t,busy:n}=e,i=e.renderText??Hm,o=m.useId(),l=m.useRef(null),[u,c]=m.useState(!1),f=e.editOpen!==void 0,p=wm(t,e.occurrences,!1).revise.enabled&&(f?e.editOpen===!0:u),y=m.useRef(null);p?(!y.current||y.current.summary.automation_id!==t.automation_id)&&(y.current={summary:t,definition:e.definition}):y.current=null;const w=y.current,x=m.useRef(e.onEditOpenChange);x.current=e.onEditOpenChange;const S=J=>{var oe;f||c(J),(oe=x.current)==null||oe.call(x,J)},[j,E]=m.useState([]),[A,L]=m.useState(!1),[O,M]=m.useState(null),[H,X]=m.useState(null),[Y,Z]=m.useState(null);m.useEffect(()=>{if(!Y)return;const J=setTimeout(()=>Z(null),kk);return()=>clearTimeout(J)},[Y]),m.useEffect(()=>{var oe;if(!p)return;E([]);const J=$y(l.current,['.af-auto__revise [name="title"]']);J==null||J.focus(),(oe=J==null?void 0:J.scrollIntoView)==null||oe.call(J,{block:"nearest"})},[p,t.automation_id]);const[re,ie]=m.useState(null);m.useEffect(()=>{var J;re&&((J=$y(l.current,[...re,".af-auto__notice",".af-auto__title"]))==null||J.focus(),ie(null))},[re]);const ue=m.useRef(null);ue.current||(ue.current=new ok(e.newId??lk));const F=ue.current,C=J=>X(hk(J)),N=(J,oe,fe)=>{X(null),Z(null),oe(F.idFor(J)).then(_e=>{F.settle(J,{ok:!0}),fe(_e)},_e=>{F.settle(J,{ok:!1,error:_e}),C(_e)})},P=XS(t),D=m.useRef(e.onSeen);D.current=e.onSeen;const ne=m.useRef(null);ne.current||(ne.current=new ck),m.useEffect(()=>{const J=ne.current,oe=P?`${t.automation_id}|${P}`:null;if(!P||!J.next(oe,t))return;const fe=t;D.current(P).then(()=>J.succeeded(oe),_e=>{J.failed(oe,fe),C(_e)})});const B=wm(t,e.occurrences,n),z=JS(e.occurrences),G=t.occurrence_count-e.occurrences.length,T=H??e.error??null,Q=T?vm(T):null,K=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(_k,{summary:t,triggerSources:e.triggerSources,titleId:o,nowMs:e.nowMs,onOpenWorkspace:e.onOpenWorkspace}),s.jsx(vk,{summary:t,occurrences:e.occurrences,busy:n,confirmingArchive:A,reviseOpen:p,notice:Y,onDismissNotice:()=>Z(null),idBase:`${o}-ctl`,onCommand:J=>N(`command:${J}`,oe=>e.onCommand(J,void 0,{command_id:oe}),()=>{J===Bo.archive?(L(!1),Z("Archive requested."),ie(['[data-action="archive"]'])):Z(Nk[J]??"Command sent.")}),onToggleRevise:()=>{E([]),S(!p)},onAskArchive:()=>L(!0),onCancelArchive:()=>{L(!1),ie(['[data-action="archive"]'])}}),p&&w?s.jsx(bk,{summary:w.summary,definition:w.definition,busy:n,errors:j,emailStatus:e.emailStatus,onOpenMyEmail:e.onOpenMyEmail,onCancel:()=>{S(!1),ie(['[data-action="edit"]'])},onSubmit:J=>{const oe=w.summary,fe=QS(oe,J,w.definition);if(fe===null){E(["Nothing changed."]);return}if("errors"in fe){E(fe.errors);return}E([]),N(`revise:${oe.revision}:${JSON.stringify(fe)}`,_e=>e.onRevise(fe,oe.revision,{command_id:_e}),()=>{Z("Saved; applies from the next run."),S(!1),ie(['[data-action="edit"]'])})}}):e.definition?s.jsx(pk,{definition:e.definition,renderText:i}):null,Q?s.jsxs("div",{className:"af-auto__error",role:"alert","data-code":T==null?void 0:T.code,children:[s.jsx(Qe,{name:"error",size:14,className:"af-auto__btn-icon"}),s.jsxs("span",{className:"af-auto__error-text",children:[s.jsx("strong",{children:Q.title})," ",s.jsx("span",{children:Q.detail})]}),H?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:()=>X(null),children:s.jsx(Qe,{name:"x",size:12})}):null]}):null,K.items.length||K.waits.length?s.jsx("section",{className:"af-auto__attention","aria-label":"Needs attention",children:s.jsxs("ul",{children:[K.items.map(J=>s.jsxs("li",{className:`af-auto__attention-item af-auto__attention-item--${J.kind}`,"data-cursor":J.cursor,children:[s.jsx("span",{className:`af-auto-badge af-auto-badge--${J.kind==="failure"?"failed":"notified"}`,children:J.kind==="failure"?"Failed":"Notified"})," ",s.jsx("strong",{children:J.title})," ",s.jsxs("span",{className:"af-auto-turn__muted",children:["#",J.index," · ",Na(J.at)]}),J.body?s.jsx("div",{className:"af-auto__attention-body",children:i(J.body)}):null]},J.cursor)),K.waits.map(J=>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":J.kind,children:hx[J.kind]??"Waiting for you"})," ",s.jsxs("span",{className:"af-auto-turn__muted",children:["#",J.index]}),J.prompt?s.jsx("div",{className:"af-auto__attention-body",children:i(J.prompt)}):null]},`${J.run_id}:${J.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(dr,{icon:"history",label:`Load earlier occurrences (${G} more)`})}):null,z.length?s.jsx("ol",{className:"af-auto__timeline","aria-label":"Occurrences",children:z.map(J=>{const oe=`[data-index="${J.row.index}"]`;return s.jsx(Sk,{view:J,busy:n,discuss:B.discuss,renderText:i,renderTurn:e.renderTurn,onOpenWorkspace:e.onOpenWorkspace,onOpenResource:e.onOpenResource?fe=>{var _e;X(null);try{Promise.resolve((_e=e.onOpenResource)==null?void 0:_e.call(e,fe)).catch(C)}catch(we){C(we)}}:void 0,discussOpen:O===J.row.index,onOpenRun:e.onOpenRun,onAnswerWait:(fe,_e,we)=>{X(null),e.onAnswerWait(fe,_e,we).then(()=>Z("Answer sent."),C)},onWaitError:fe=>X({status:0,code:"invalid_payload",message:fe}),onDiscussOpen:M,onDiscussCancel:()=>{M(null),ie([`${oe} [data-action="discuss"]`])},onDiscussSubmit:(fe,_e)=>N(`discuss:${fe}:${_e}`,we=>e.onDiscuss(fe,_e,{request_id:we}),we=>{M(null),Z(`Discussion started (session ${we.session_id}).`),ie([`${oe} [data-action="discuss"]`])})},J.row.run_id)})}):s.jsx("p",{className:"af-auto__empty",children:"No occurrences yet."})]})}function px(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}}function Ek(e){const t=px(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 gx({tool:e,showCopy:t=!0}){const[n,i]=m.useState(!1),o=px(e.arguments),l=Ek(e.arguments),u=["file path","path"].includes(l.label)&&l.value.length>60?`${l.value.split(/[\\/]/).pop()} · ${l.value.slice(0,24)}…`:l.value,c=e.error&&/^File ['"].+['"] does not exist\.?$/.test(e.error)?"File not found. Expand for the exact path.":e.error&&e.error.length>180?`${e.error.slice(0,100)}…${e.error.slice(-70)}`:e.error,f={running:"Running",waiting:"Approval needed",completed:"Done",failed:"Failed"},_=e.startedAt&&e.endedAt?Date.parse(e.endedAt)-Date.parse(e.startedAt):NaN,p=o&&typeof o=="object"&&!Array.isArray(o)?Object.entries(o):null;return s.jsxs("details",{className:`pc-tool-activity pc-tool-activity--${e.status}`,children:[s.jsxs("summary",{className:"pc-tool-activity__summary",children:[s.jsx("span",{className:"pc-tool-activity__state-icon","aria-hidden":"true",children:s.jsx(Qe,{name:e.status==="completed"?"check":e.status==="failed"?"x":e.status==="waiting"?"warning":"loader",size:15})}),s.jsx("strong",{children:e.name}),s.jsx("span",{className:"pc-tool-activity__preview",title:l.value,children:l.value?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"pc-tool-activity__key",children:l.label}),u]}):"No parameters"}),s.jsx("span",{className:"pc-tool-activity__status",children:f[e.status]}),Number.isFinite(_)&&_>=0?s.jsxs("span",{className:"pc-tool-activity__duration",children:[(_/1e3).toFixed(1),"s"]}):null,s.jsx("span",{className:"pc-tool-activity__chevron","aria-hidden":"true",children:s.jsx(Qe,{name:"chevronRight",size:13})}),e.error?s.jsx("span",{className:"pc-tool-activity__error",title:e.error,children:c}):null]}),s.jsxs("div",{className:"pc-tool-activity__detail",children:[e.error?s.jsxs(s.Fragment,{children:[s.jsx("h4",{children:"Error"}),s.jsx("pre",{className:"pc-tool-activity__output",children:e.error})]}):null,s.jsxs("div",{className:"pc-tool-activity__detail-heading",children:[s.jsx("h4",{children:"Parameters"}),t?s.jsxs("button",{type:"button",onClick:async()=>i(await ic(JSON.stringify(e,null,2))),children:[s.jsx(Qe,{name:"copy",size:13}),n?"Copied":"Copy details"]}):null]}),p?s.jsx("dl",{className:"pc-tool-activity__parameters",children:p.map(([y,w])=>s.jsxs(ve.Fragment,{children:[s.jsx("dt",{children:y}),s.jsx("dd",{children:w&&typeof w=="object"?s.jsx(fr,{value:w}):s.jsx("code",{children:typeof w=="string"?w:JSON.stringify(w)})})]},y))}):e.arguments===void 0?s.jsx("p",{children:"Arguments are unavailable in this ledger."}):s.jsx(fr,{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(fr,{value:e.output})})]}):null]})]})}function yx({tools:e,showCopy:t}){const n=i=>e.filter(o=>o.status===i).length;return s.jsxs("section",{className:"pc-tool-group","aria-label":"Tool activity",children:[s.jsxs("div",{className:"pc-tool-group__heading",children:[s.jsx(Qe,{name:"terminal",size:14}),s.jsx("strong",{children:"Tools"}),s.jsxs("span",{children:[e.length," ",e.length===1?"call":"calls"]}),s.jsx("div",{}),n("running")?s.jsxs("span",{className:"pc-tool-group__running",children:[n("running")," running"]}):null,n("waiting")?s.jsxs("span",{className:"pc-tool-group__waiting",children:[n("waiting")," need approval"]}):null,n("failed")?s.jsxs("span",{className:"pc-tool-group__failed",children:[n("failed")," failed"]}):null,n("completed")?s.jsxs("span",{className:"pc-tool-group__completed",children:[n("completed")," done"]}):null]}),e.map(i=>s.jsx(gx,{tool:i,showCopy:t},i.id))]})}const Ks="not reported",Sr=e=>e===void 0?Ks:Math.round(e).toLocaleString(),Kr=e=>{if(e===void 0)return Ks;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`},wx=e=>e===void 0?Ks:`${Math.round(e).toLocaleString()} tok/s`,$k=(e,t)=>t>0?`${Math.round(e/t*100)}%`:"",tc=(e,t,n=`${t}s`)=>`${e.toLocaleString()} ${e===1?t:n}`,Ak=e=>{const t=e.split("#")[0].replace(/\/+$/,"");return t.slice(t.lastIndexOf("/")+1)||e};function Tk(e){const t=new Map;for(const n of e)n&&t.set(n,(t.get(n)||0)+1);return[...t].map(([n,i])=>i>1?`${n} ×${i}`:n).join(" · ")}function xm(e){const t=[],n=(e.models||[]).map(Ak),i=e.providers||[];return(n.length||i.length)&&t.push([n.join(", ")||"model not reported",i.join(", ")].filter(Boolean).join(" · ")),t.push("From the run ledger; summed across this turn and its child runs."),t}function Mk(e){const t=e.modelCalls||[],n=[],i=[{label:"Input",value:Sr(e.inputTokens)},{label:"Output",value:Sr(e.outputTokens)}];if(e.reasoningTokens!==void 0&&i.push({label:"Reasoning",value:Sr(e.reasoningTokens),hint:"part of output"}),i.push({label:"Total",value:Sr(e.totalTokens)}),n.push({heading:`Usage · ${tc(e.llmCalls,"model call")}`,rows:i}),e.measuredCacheCalls){const l=e.cachedTokens||0,u=e.fedTokens||0,c=[{label:"Reused from cache",value:`${Sr(l)}${l+u?` (${$k(l,l+u)})`:""}`},{label:"Newly processed",value:Sr(e.fedTokens)},{label:"Outcome",value:Tk(t.map(f=>f.cacheOutcome))||(e.cacheOutcomes||[]).join(" · ")||Ks},{label:"Backend",value:(e.cacheBackends||[]).join(", ")||Ks}];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:Ks}]});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?Ks:`${e.totalTokens.toLocaleString()} total`,sections:n,footer:xm(e)}}function zh(e,t,n,i){if(e===void 0)return Ks;const o=[Kr(e)];return t!==void 0&&o.push(`${t.toLocaleString()} ${i}${n!==void 0?` at ${wx(n)}`:""}`),o.join(" · ")}function Rk(e){var _,p,y;const t=e.modelCalls||[],n=[],i=e.durationMs,o=[{label:"Wall clock",value:Kr(i)}];if(o.push({label:"Model",value:e.genTimeMs===void 0?Ks:`${Kr(e.genTimeMs)} · ${tc(e.timedCalls||0,"call")}${e.timedCalls!==e.llmCalls?` (of ${e.llmCalls})`:""}`}),o.push({label:"Tools",value:e.toolTimeMs!==void 0?`${Kr(e.toolTimeMs)} · ${tc(e.toolBatches||0,"batch","batches")}`:e.toolCalls?Ks:"none",hint:e.toolTimeIncludesApproval?"includes approval wait":void 0}),i!==void 0&&e.genTimeMs!==void 0){const w=i-e.genTimeMs-(e.toolTimeMs||0);o.push({label:"Orchestration",value:w>=0?Kr(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:zh(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:zh(e.prefillMs,e.prefillNewTokens,e.prefillNewTokensPerSecond,"new tok"),hint:"derived: prompt ÷ provider rate"}):e.prefillMs!==void 0?l.push({label:"Prefill",value:`${Kr(e.prefillMs)}${e.promptTokensPerSecond!==void 0?` at ${wx(e.promptTokensPerSecond)}`:""}`,hint:"provider rate over all prompt tokens, restored included"}):l.push({label:"Prefill",value:Ks}),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?zh(e.generationPhaseMs,e.generationPhaseTokens,e.generationPhaseTokensPerSecond,"tok"):zh(e.decodeMs,e.outputTokens,e.generationTokensPerSecond,"tok")}),e.measuredSpeedCalls&&e.measuredSpeedCalls!==e.llmCalls&&l.push({label:"Speeds from",value:`${e.measuredSpeedCalls} of ${e.llmCalls} calls`}),n.push({heading:"Model",rows:l});const f=e.speculation;if(f){const w=(f.draftKinds||[]).map(S=>S.toUpperCase()).join(", "),x=[{label:"Mode",value:`${f.used?"on":"off"}${w?` · ${w}`:""}${(_=f.modes)!=null&&_.length?` (${f.modes.join(", ")})`:""}`,hint:f.calls!==e.llmCalls||f.used!==f.calls?`used on ${f.used} of ${e.llmCalls} calls`:void 0},{label:"Acceptance",value:f.acceptanceRate===void 0?Ks:`${Math.round(f.acceptanceRate*100)}% · ${Sr(f.acceptedTokens)} of ${Sr(f.draftedTokens)} drafted`}];((p=f.draftLengths)!=null&&p.length||f.rounds!==void 0)&&x.push({label:"Draft length",value:`${(y=f.draftLengths)!=null&&y.length?`${f.draftLengths.join("/")} tok/round`:Ks}${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:`${Kr(e.toolTimeMs)} · ${tc(e.toolBatches||0,"batch","batches")}`},{label:"Slowest",value:`${Kr(e.slowestToolBatch.ms)} · ${vx(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?"—":`${Kr(w.promptMs)}${w.promptSource==="rate"?"*":""}`,w.promptNewTokensPerSecond===void 0?"—":Math.round(w.promptNewTokensPerSecond).toLocaleString(),w.generationMs===void 0?"—":Kr(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:i===void 0?Ks:`${Kr(i)} wall clock`,sections:n,footer:xm(e)}}function vx(e){return e.tools.length===1?`${e.tools[0]} ×${e.calls}`:`${tc(e.calls,"call")} (${e.tools.join(", ")})`}function Lk(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:xm(e)};const i=[{label:"Succeeded",value:(e.toolCalls-(e.toolsFailed||0)).toLocaleString()},{label:"Failed",value:(e.toolsFailed||0).toLocaleString()}];e.toolsRunning&&i.push({label:"Running",value:e.toolsRunning.toLocaleString()}),e.toolsWaiting&&i.push({label:"Awaiting approval",value:e.toolsWaiting.toLocaleString(),hint:"not run yet — not a failure"}),t.push({heading:"Outcome",rows:i});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?`${Kr(f.ms)}${f.sharedBatches?" +shared":""}`:f.sharedBatches?"shared":Ks])},note:o.some(([,c])=>c.sharedBatches)?"A batch that mixed tools ran them together; its time is not split between them.":void 0});const l=o.filter(([,c])=>c.errors&&Object.keys(c.errors).length);l.length&&t.push({heading:"Failures",rows:l.map(([c,f])=>({label:c,value:Object.entries(f.errors).sort((_,p)=>p[1]-_[1]).map(([_,p])=>p>1?`${_} ×${p}`:_).join(" · ")}))});const u=[{label:"Tool time",value:e.toolTimeMs===void 0?Ks:`${Kr(e.toolTimeMs)} · ${tc(e.toolBatches||0,"batch","batches")}`}];return e.slowestToolBatch&&u.push({label:"Slowest batch",value:`${Kr(e.slowestToolBatch.ms)} · ${vx(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:`${tc(e.toolCalls,"call")}${e.toolsFailed?` · ${e.toolsFailed} failed`:""}`,sections:t,footer:xm(e)}}function P_(e,t){return e==="tokens"?Mk(t):e==="time"?Rk(t):Lk(t)}function Ik(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 i;return s.jsxs("div",{className:"pc-stat-detail-section",children:[s.jsx("div",{className:"pc-stat-detail-heading",children:n.heading}),(i=n.rows)!=null&&i.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===Ks?"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 va=8;function Ok(e){const[t,n]=m.useState(!!e.defaultOpen),[i,o]=m.useState(null),l=m.useRef(null),u=m.useRef(null),c=m.useRef(null),f=`pc-stat-${m.useId().replace(/[^a-zA-Z0-9_-]/g,"")}`,_=m.useCallback(()=>{c.current!==null&&window.clearTimeout(c.current),c.current=null},[]),p=m.useCallback(()=>{_(),n(!0)},[_]),y=m.useCallback(()=>{_(),c.current=window.setTimeout(()=>n(!1),120)},[_]);m.useEffect(()=>_,[_]),m.useLayoutEffect(()=>{if(!t){o(null);return}const j=()=>{const E=l.current,A=u.current;if(!E||!A)return;const L=E.getBoundingClientRect(),O=A.offsetWidth,M=A.offsetHeight,H=window.innerWidth,X=window.innerHeight,Y=L.top-va-M,Z=L.bottom+va,re=Y>=va?Y:Z+M<=X-va?Z:Math.max(va,X-va-M),ie=Math.min(Math.max(va,L.left),Math.max(va,H-va-O));o({top:re,left:ie})};return j(),window.addEventListener("resize",j),window.addEventListener("scroll",j,!0),()=>{window.removeEventListener("resize",j),window.removeEventListener("scroll",j,!0)}},[t]),m.useEffect(()=>{if(!t)return;const j=E=>{E.key==="Escape"&&n(!1)};return document.addEventListener("keydown",j),()=>document.removeEventListener("keydown",j)},[t]);const w=typeof e.onClick=="function",x=w?"button":"span",S=t?s.jsx(Ik,{detail:e.detail,id:f,panelRef:u,onMouseEnter:_,onMouseLeave:y,style:{position:"fixed",top:(i==null?void 0:i.top)??0,left:(i==null?void 0:i.left)??0,visibility:i?"visible":"hidden"}}):null;return s.jsxs(s.Fragment,{children:[s.jsxs(x,{ref:l,...w?{type:"button"}:{tabIndex:0},className:["pc-chat-stat","pc-chat-stat--detail",w?"pc-chat-stat--clickable":"",e.className].filter(Boolean).join(" "),"aria-label":`${e.label} — ${e.detail.title.toLowerCase()} details`,"aria-describedby":t?f:void 0,"data-stat-kind":e.detail.kind,onMouseEnter:p,onMouseLeave:y,onFocus:p,onBlur:()=>n(!1),onKeyDown:j=>{j.key==="Escape"&&n(!1)},onClick:w?()=>{var j;return(j=e.onClick)==null?void 0:j.call(e)}:void 0,children:[e.icon?s.jsx("span",{className:"pc-chat-stat-icon","aria-hidden":"true",children:e.icon}):null,s.jsx("span",{className:"pc-chat-stat-label",children:e.label})]}),S&&typeof document<"u"?Vv.createPortal(S,document.body):S]})}function Pk(e){const t=e.totalTokens!==void 0?P_("tokens",e):null,n=P_("tools",e),i=e.durationMs!==void 0?P_("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(`
|
|
68
|
+
`)}]:[],...i?[{label:`${(e.durationMs/1e3).toFixed(e.durationMs<1e4?1:0)}s`,detail:i}]:[]]}function Dk(e){const t=String(e.role||"").trim().toLowerCase()||"system",n=String(e.kind||"").trim().toLowerCase(),i=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()||(i==="error"?"Error":i==="warn"?"Warning":"System"),icon:i==="error"?"error":i==="warn"?"warning":"info",variant:i==="error"?"error":i==="warn"?"warn":"status"}}function vg(e){var A;const t=e.message,n=m.useMemo(()=>Dk(t),[t.kind,t.level,t.role,t.title]),i=String(t.ts||"").trim(),o=m.useMemo(()=>{if(!i)return"";const L=new Date(i);return Number.isFinite(L.getTime())?L.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):""},[i]),[l,u]=m.useState("idle"),c=m.useRef(null);m.useEffect(()=>()=>{c.current!==null&&window.clearTimeout(c.current)},[]);const f=t.live,_=!f&&typeof e.onSpeakToggle=="function"&&n.variant==="assistant"&&!!String(t.content||"").trim(),p=_&&((A=e.getSpeakState)==null?void 0:A.call(e,t))||"idle",y=p==="loading"?"loader":p==="playing"?"pause":"speaker",w=p==="loading"?"Generating audio…":p==="playing"?"Pause":p==="paused"?"Resume":"Speak (TTS)",x=e.showCopy!==!1,S=Array.isArray(e.attachments)?e.attachments:[],j=t.statistics,E=m.useMemo(()=>Array.isArray(e.stats)?e.stats:j?Pk(j):[],[e.stats,j]);return t.toolActivity?s.jsx(gx,{tool:t.toolActivity,showCopy:e.showCopy}):s.jsxs("div",{className:["pc-chat-item",`pc-chat-item--${n.variant}`,f?"pc-chat-item--live":"",e.className].filter(Boolean).join(" "),...f?{"aria-busy":!0}:{},children:[s.jsxs("div",{className:"pc-chat-header",children:[s.jsx("div",{className:"pc-chat-avatar","aria-hidden":"true",children:s.jsx(Qe,{name:n.icon,size:14})}),s.jsx("span",{className:"pc-chat-role",children:n.label}),f?s.jsxs("span",{className:"pc-chat-live-indicator",title:"The reply is still being written",children:[s.jsx("span",{className:"pc-chat-live-dot","aria-hidden":"true"}),"streaming"]}):null,f!=null&&f.caption?s.jsx("span",{className:"pc-chat-live-caption",children:f.caption}):null,s.jsx("span",{className:"pc-chat-header-spacer"}),o?s.jsx("span",{className:"pc-chat-time",children:o}):null,s.jsxs("div",{className:"pc-chat-header-actions",children:[_?s.jsx("button",{className:"pc-chat-icon-btn",type:"button","aria-label":w,title:w,onClick:()=>{var L;return(L=e.onSpeakToggle)==null?void 0:L.call(e,t)},children:s.jsx(Qe,{name:y,size:22})}):null,x?s.jsx("button",{className:`pc-chat-icon-btn ${l!=="idle"?`pc-chat-icon-btn--${l}`:""}`.trim(),type:"button","aria-label":"Copy message",title:l==="idle"?"Copy":l==="copied"?"Copied":"Copy failed",onClick:async()=>{const L=await ic(String(t.content||""));u(L?"copied":"failed"),c.current!==null&&window.clearTimeout(c.current),c.current=window.setTimeout(()=>u("idle"),900)},children:s.jsx(Qe,{name:"copy",size:22})}):null]})]}),f!=null&&f.reasoning?s.jsxs("details",{className:"pc-chat-thinking",children:[s.jsx("summary",{children:"Thinking"}),s.jsx("div",{className:"pc-chat-thinking-body",children:f.reasoning})]}):null,!f||String(t.content||"").trim()?s.jsx("div",{className:"pc-chat-body",children:s.jsx(qv,{text:String(t.content||""),renderMarkdown:e.renderMarkdown,jsonCollapseAfterDepth:e.jsonCollapseAfterDepth,images:e.images||(n.variant==="user"?"inline":"link"),inlineImage:e.inlineImage})}):null,S.length?s.jsx("div",{className:"pc-chat-attachments","aria-label":"Attachments",children:S.slice(0,24).map((L,O)=>{const M=String(L.label||"").trim()||"attachment",H=String(L.target||"").trim(),X=String(L.title||"").trim(),Y=!!L.disabled||typeof L.onClick!="function";return s.jsxs("button",{type:"button",className:"pc-chat-attachment-chip",title:X||M,onClick:Y?void 0:L.onClick,disabled:Y,children:[s.jsx(Qe,{name:"paperclip",size:14}),H?s.jsx("span",{className:`pc-chat-attachment-target pc-chat-attachment-target--${H}`,children:H}):null,s.jsx("span",{className:"pc-chat-attachment-name",children:M})]},L.id||`${M}:${O}`)})}):null,E.length?s.jsx("div",{className:"pc-chat-stats","aria-label":"Stats",children:E.slice(0,12).map((L,O)=>{const M=String(L.label||"").trim();if(!M)return null;if(L.detail)return s.jsx(Ok,{label:M,detail:L.detail,icon:L.icon,onClick:L.onClick},L.id||`${M}:${O}`);const H=String(L.title||"").trim(),X=typeof L.onClick=="function",Y=X?"button":"span";return s.jsxs(Y,{...X?{type:"button"}:{},className:["pc-chat-stat",X?"pc-chat-stat--clickable":""].filter(Boolean).join(" "),title:H||void 0,onClick:X?()=>{var Z;return(Z=L.onClick)==null?void 0:Z.call(L)}:void 0,children:[L.icon?s.jsx("span",{className:"pc-chat-stat-icon","aria-hidden":"true",children:L.icon}):null,s.jsx("span",{className:"pc-chat-stat-label",children:M})]},L.id||`${M}:${O}`)})}):null]})}function Fk(e,t){const n=Math.max(0,Math.trunc(t));return e.scrollHeight-e.scrollTop-e.clientHeight<=n}function xg(e){const t=typeof e.autoScrollThresholdPx=="number"&&Number.isFinite(e.autoScrollThresholdPx)?e.autoScrollThresholdPx:120,n=e.autoScroll!==!1,i=m.useRef(null),o=m.useRef(null),[l,u]=m.useState(!0),c=m.useMemo(()=>Array.isArray(e.messages)?e.messages:[],[e.messages]),f=m.useMemo(()=>{var y;const p=[];for(const w of c){const x=p[p.length-1];w.toolActivity&&((y=x==null?void 0:x[0])!=null&&y.toolActivity)&&x[0].runId===w.runId?x.push(w):p.push([w])}return p},[c]);m.useEffect(()=>{if(!n)return;const p=i.current;if(!p)return;const y=()=>{u(Fk(p,t))};return p.addEventListener("scroll",y,{passive:!0}),y(),()=>p.removeEventListener("scroll",y)},[n,t]);const _=m.useMemo(()=>{let p=0;for(const y of c)p+=String(y.content??"").length;return`${c.length}:${p}:${String(e.afterKey??"")}`},[c,e.afterKey]);return m.useEffect(()=>{if(!n||!l)return;const p=i.current;p&&(p.scrollTop=p.scrollHeight)},[n,l,_]),s.jsxs("div",{ref:i,className:["pc-chat-thread",e.className].filter(Boolean).join(" "),children:[c.length?null:e.empty||null,f.map((p,y)=>{var S;const w=p[0],x=String(w.id||"")||String(w.ts||"")+":"+String(w.role||"")+":"+y;return w.toolActivity?s.jsx(yx,{tools:p.map(j=>j.toolActivity),showCopy:(S=e.messageProps)==null?void 0:S.showCopy},x):s.jsx(vg,{message:w,...e.messageProps||{}},x)}),e.after,s.jsx("div",{ref:o})]})}const bg=ve.forwardRef(function(t,n){const i=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:i,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 zk(e){return!!(e&&typeof e[Symbol.asyncIterator]=="function")}function Bk(e){const[t,n]=m.useState([]),i=e.messages??t,o=j=>{e.onMessagesChange&&e.onMessagesChange(j),e.messages===void 0&&n(j)},l=m.useRef(i);l.current=i;const[u,c]=m.useState(""),[f,_]=m.useState(!1),p=m.useRef(null),y=e.assistantName||"Assistant",w=!!e.blockedNotice,x=async j=>{const E=String(j||"").trim();if(!E||f||w)return;c("");const A=l.current,L=[...A,{role:"user",content:E,ts:new Date().toISOString()}];o(L),_(!0);const O=new AbortController;p.current=O;try{const M=e.ask(E,{signal:O.signal,history:A});if(zk(M)){let H="";const X=[...L,{role:"assistant",title:y,content:"",ts:new Date().toISOString()}];o(X);for await(const Y of M){if(O.signal.aborted)break;H+=String(Y??""),o([...L,{role:"assistant",title:y,content:H,ts:new Date().toISOString()}])}!H.trim()&&!O.signal.aborted&&o([...L,{role:"assistant",title:y,content:"#FALLBACK the assistant returned no answer.",level:"warn",ts:new Date().toISOString()}])}else{const H=String(await M??"").trim();o([...L,H?{role:"assistant",title:y,content:H,ts:new Date().toISOString()}:{role:"assistant",title:y,content:"#FALLBACK the assistant returned no answer.",level:"warn",ts:new Date().toISOString()}])}}catch(M){O.signal.aborted||o([...l.current,{role:"assistant",title:y,content:`#FALLBACK assistant request failed: ${String((M==null?void 0:M.message)||M||"unknown error")}`,level:"error",ts:new Date().toISOString()}])}finally{p.current===O&&(p.current=null),_(!1)}},S=m.useMemo(()=>i.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]}),[i.length,e.emptyState,e.suggestions,f,w]);return s.jsxs("div",{className:`pc-assistant${e.className?` ${e.className}`:""}`,children:[s.jsxs("div",{className:"pc-assistant__thread",children:[S,s.jsx(xg,{messages:i,autoScroll:!0}),w?s.jsx("div",{className:"pc-assistant__blocked",children:e.blockedNotice}):null]}),s.jsx("div",{className:"pc-assistant__composer",children:s.jsx(bg,{value:u,onChange:c,onSubmit:()=>void x(u),placeholder:e.placeholder||"Ask about this app…",disabled:w,busy:f,rows:2,actions:f?s.jsx("button",{type:"button",className:"pc-btn",onClick:()=>{var j;(j=p.current)==null||j.abort()},children:"Stop"}):null})})]})}const xn=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},um=e=>Array.isArray(e)?e.map(xn):[],en=e=>typeof e=="string"?e:"",ef=e=>en(e.runtime_call_id||e.call_uid),tf=e=>en(e.call_id||e.id);function xx(e,t){const n=t.record,i=xn(n.effect);if(i.type!=="tool_calls")return[];const o=xn(n.result),l=um(xn(i.payload).tool_calls),u=l.length||n.status!=="waiting"?l:um(xn(xn(o.wait).details).tool_calls),c=um(o.results),f=u.length?u:c,_=[];return f.forEach((p,y)=>{let w=ef(p)?c.filter(X=>ef(X)===ef(p)):[];!w.length&&tf(p)&&u.filter(X=>tf(X)===tf(p)).length===1&&(w=c.filter(X=>tf(X)===tf(p)));const x=u.length?w.length===1?w[0]:u.length===c.length?c[y]:{}:p,S=ef(p)||ef(x)||`${en(n.idempotency_key)||en(n.step_id)||t.cursor}:${y}`,j=`${t.runId}:${S}`,E=e.get(j),A=en(p.name||x.name)||(E==null?void 0:E.name);if(!A)return;const L=n.status==="completed"||n.status==="failed",O=n.status==="failed"||x.success===!1||!!x.error,M=p.arguments??x.arguments??(E==null?void 0:E.arguments),H={...E,id:j,runId:t.runId,name:A,arguments:M,status:L?O?"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:(E==null?void 0:E.startedAt)||en(n.started_at)||void 0,endedAt:L&&en(n.ended_at)||(E==null?void 0:E.endedAt)};E&&["completed","failed"].includes(E.status)&&!L||(e.set(j,H),_.push(H))}),_}function ku(e){if(e==null||e===""||typeof e=="boolean")return;const t=Number(e);return Number.isFinite(t)&&t>=0?t:void 0}function zo(e,t){for(const n of t){const i=e==null?void 0:e[n];if(i==null||i===""||typeof i=="boolean")continue;const o=Number(i);if(Number.isFinite(o)&&o>=0)return Math.trunc(o)}}function bx(e){if(typeof e=="string")try{return xn(JSON.parse(e))}catch{return{}}return xn(e)}function yu(e,t){if(t===void 0||t==="")return e;const n=e||[];return n.includes(t)||n.push(t),n}function Uk(e){return zo(e,["reasoning_tokens","thinking_tokens"])??zo(xn(e.completion_tokens_details),["reasoning_tokens"])??zo(xn(e.output_tokens_details),["reasoning_tokens"])}function Wk(e){const t=xn(typeof e=="string"&&e.trim().startsWith("{")?bx(e):e);return en(t.error_class)}function qk(e){const t=new Map;for(const n of e){const i=n.record;if(xn(i.effect).type!=="emit_event")continue;const o=xn(i.result);if(en(o.name)!=="abstract.progress")continue;const l=xn(o.payload);if(en(l.kind)!=="llm"||!en(l.step_id))continue;const u=`${en(l.run_id)||n.runId}:${en(l.step_id)}`,c=t.get(u)||{},f=ku(l.ttft_s);f!==void 0&&(c.ttftS=f),c.provider=c.provider||en(l.provider)||void 0,c.model=c.model||en(l.model)||void 0,t.set(u,c)}return t}function D_(e){var j,E,A,L;const t=new Map,n=new Set,i=new Set,o={llmCalls:0,toolCalls:0,changedFiles:[]};let l=1/0,u=-1/0,c=!1,f=0,_=0,p=0;const y=qk(e),w=[],x=new Set;for(const O of e){const M=O.record,H=`${O.runId}:${M.step_id||O.cursor}:${M.status}`;if(n.has(H))continue;n.add(H);for(const we of[M.started_at,M.ended_at]){const Ae=Date.parse(en(we));Number.isFinite(Ae)&&(l=Math.min(l,Ae),u=Math.max(u,Ae))}for(const we of xx(t,O))we.status==="waiting"&&x.add(we.id);if(xn(M.effect).type!=="llm_call"||M.status!=="completed")continue;o.llmCalls+=1;const X=xn(M.result),Y=xn(X.output),Z=xn(X.usage||X.token_usage||X.tokens||Y.usage||Y.token_usage||Y.tokens),re=zo(Z,["input_tokens","prompt_tokens","prompt","input","in"]),ie=zo(Z,["output_tokens","completion_tokens","completion","output","out"]),ue=zo(Z,["total_tokens","total"])??(re!==void 0||ie!==void 0?(re||0)+(ie||0):void 0);ue!==void 0&&(re===void 0||ie===void 0||re+ie!==ue)&&(c=!0),re!==void 0&&(o.inputTokens=(o.inputTokens||0)+re),ie!==void 0&&(o.outputTokens=(o.outputTokens||0)+ie),ue!==void 0&&(o.totalTokens=(o.totalTokens||0)+ue);const F=ku(X.gen_time??Y.gen_time);F!==void 0&&(o.genTimeMs=(o.genTimeMs||0)+F,o.timedCalls=(o.timedCalls||0)+1);const C=xn(X.metadata||Y.metadata),N=xn(C.performance),P=ku(N.prompt_tokens_per_second),D=ku(N.generation_tokens_per_second),ne=xn(C.prompt_cache),B=ku(ne.cached_tokens),z=ku(ne.fed_tokens);if(P!==void 0||D!==void 0){if(o.measuredSpeedCalls=(o.measuredSpeedCalls||0)+1,P!==void 0&&P>0&&(o.promptTokensPerSecond=(o.promptTokensPerSecond||0)+P,re!==void 0)){const we=re/P*1e3;o.prefillMs=(o.prefillMs||0)+we,z!==void 0&&(f+=z,_+=we)}D!==void 0&&D>0&&(o.generationTokensPerSecond=(o.generationTokensPerSecond||0)+D,ie!==void 0&&(o.decodeMs=(o.decodeMs||0)+ie/D*1e3))}if(B!==void 0||z!==void 0){o.measuredCacheCalls=(o.measuredCacheCalls||0)+1,o.cachedTokens=(o.cachedTokens||0)+(B||0),o.fedTokens=(o.fedTokens||0)+(z||0);const we=en(ne.outcome);if(we){const Ae=o.cacheOutcomes||[];Ae.includes(we)||Ae.push(we),o.cacheOutcomes=Ae}}const G=en(M.step_id)||void 0,T=G&&y.get(`${O.runId}:${G}`)||{},Q=xn(X.route),K={runId:O.runId};G&&(K.stepId=G),en(M.started_at)&&(K.startedAt=en(M.started_at));const J=en(X.model||Y.model)||en(Q.model)||T.model,oe=en(Q.provider)||en(xn(C._provider_request).provider)||T.provider||en(X.provider);J&&(K.model=J),oe&&(K.provider=oe),J&&(o.models=yu(o.models,J)),oe&&(o.providers=yu(o.providers,oe)),(ue===void 0||re!==void 0&&ie!==void 0&&re+ie===ue)&&(re!==void 0&&(K.inputTokens=re),ie!==void 0&&(K.outputTokens=ie)),ue!==void 0&&(K.totalTokens=ue);const fe=Uk(Z);fe!==void 0&&(K.reasoningTokens=fe,o.reasoningTokens=(o.reasoningTokens||0)+fe),B!==void 0&&(K.cachedTokens=B),z!==void 0&&(K.fedTokens=z),en(ne.outcome)&&(K.cacheOutcome=en(ne.outcome)),en(ne.backend)&&(K.cacheBackend=en(ne.backend),o.cacheBackends=yu(o.cacheBackends,K.cacheBackend)),F!==void 0&&(K.genTimeMs=F),P!==void 0&&P>0&&(K.promptTokensPerSecond=P),D!==void 0&&D>0&&(K.generationTokensPerSecond=D),T.ttftS!==void 0?(K.ttftMs=T.ttftS*1e3,K.promptMs=K.ttftMs,K.promptSource="ttft",o.ttftMs=(o.ttftMs||0)+K.ttftMs,o.ttftCalls=(o.ttftCalls||0)+1):K.promptTokensPerSecond!==void 0&&re!==void 0&&(K.promptMs=re/K.promptTokensPerSecond*1e3,K.promptSource="rate"),K.promptMs!==void 0&&(o.promptPhaseMs=(o.promptPhaseMs||0)+K.promptMs,o.promptPhaseCalls=(o.promptPhaseCalls||0)+1,z!==void 0&&K.promptMs>0&&(K.promptNewTokensPerSecond=z/(K.promptMs/1e3),o.promptPhaseNewTokens=(o.promptPhaseNewTokens||0)+z,p+=K.promptMs)),K.ttftMs!==void 0&&F!==void 0&&F>=K.ttftMs?K.generationMs=F-K.ttftMs:K.generationTokensPerSecond!==void 0&&ie!==void 0&&(K.generationMs=ie/K.generationTokensPerSecond*1e3),K.generationMs!==void 0&&ie!==void 0&&(o.generationPhaseMs=(o.generationPhaseMs||0)+K.generationMs,o.generationPhaseTokens=(o.generationPhaseTokens||0)+ie);const _e=xn(C.speculation);if(Object.keys(_e).length){const we={};en(_e.mode)&&(we.mode=en(_e.mode)),typeof _e.used=="boolean"&&(we.used=_e.used),en(_e.draft_kind)&&(we.draftKind=en(_e.draft_kind));const Ae=zo(_e,["accepted_tokens"]),Be=zo(_e,["drafted_tokens"]),We=zo(_e,["rounds"]),_t=zo(_e,["num_draft_tokens"]);Ae!==void 0&&(we.acceptedTokens=Ae),Be!==void 0&&(we.draftedTokens=Be),Ae!==void 0&&Be&&(we.acceptanceRate=Ae/Be),We!==void 0&&(we.rounds=We),_t!==void 0&&(we.draftLength=_t),K.speculation=we;const Pe=o.speculation||(o.speculation={calls:0,used:0});Pe.calls+=1,we.used&&(Pe.used+=1),we.mode&&(Pe.modes=yu(Pe.modes,we.mode)),we.draftKind&&(Pe.draftKinds=yu(Pe.draftKinds,we.draftKind)),Ae!==void 0&&Be!==void 0&&(Pe.acceptedTokens=(Pe.acceptedTokens||0)+Ae,Pe.draftedTokens=(Pe.draftedTokens||0)+Be),We!==void 0&&(Pe.rounds=(Pe.rounds||0)+We),_t!==void 0&&(Pe.draftLengths=yu(Pe.draftLengths,_t))}w.push(K)}w.length&&(w.every(O=>O.startedAt)&&w.sort((O,M)=>Date.parse(O.startedAt)-Date.parse(M.startedAt)),o.modelCalls=w),p>0&&o.promptPhaseNewTokens!==void 0&&(o.promptPhaseTokensPerSecond=o.promptPhaseNewTokens/(p/1e3)),o.generationPhaseMs&&o.generationPhaseTokens!==void 0&&(o.generationPhaseTokensPerSecond=o.generationPhaseTokens/(o.generationPhaseMs/1e3)),(j=o.speculation)!=null&&j.draftedTokens&&(o.speculation.acceptanceRate=(o.speculation.acceptedTokens||0)/o.speculation.draftedTokens),o.measuredSpeedCalls&&(o.promptTokensPerSecond!==void 0&&(o.promptTokensPerSecond/=o.measuredSpeedCalls),o.generationTokensPerSecond!==void 0&&(o.generationTokensPerSecond/=o.measuredSpeedCalls)),_>0&&(o.prefillNewTokens=f,o.prefillNewTokensPerSecond=f/(_/1e3));const S=new Map;for(const O of t.values()){if(O.status==="waiting"){o.toolsWaiting=(o.toolsWaiting||0)+1;continue}if(O.status==="running"){o.toolsRunning=(o.toolsRunning||0)+1;continue}if(!["completed","failed"].includes(O.status))continue;o.toolCalls+=1;const M=O.status==="failed";M&&(o.toolsFailed=(o.toolsFailed||0)+1);const H=o.toolBreakdown||(o.toolBreakdown={}),X=H[O.name]||(H[O.name]={calls:0,failed:0});if(X.calls+=1,M){X.failed+=1;const ue=Wk(O.output);ue&&((X.errors||(X.errors={}))[ue]=(((E=X.errors)==null?void 0:E[ue])||0)+1)}const Y=Date.parse(en(O.startedAt)),Z=Date.parse(en(O.endedAt));if(Number.isFinite(Y)&&Number.isFinite(Z)&&Z>=Y){const ue=`${O.runId}|${O.startedAt}|${O.endedAt}`,F=S.get(ue)||{ms:Z-Y,calls:0,names:new Map,waited:!1};F.calls+=1,F.names.set(O.name,(F.names.get(O.name)||0)+1),x.has(O.id)&&(F.waited=!0),S.set(ue,F)}if(O.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(O.name))continue;const re=bx(O.arguments),ie=en(re.destination||re.destination_path||re.file_path||re.path||re.filename);ie&&i.add(ie)}for(const O of S.values()){o.toolBatches=(o.toolBatches||0)+1,o.toolTimeMs=(o.toolTimeMs||0)+O.ms,O.waited&&(o.toolTimeIncludesApproval=!0);const M=[...O.names.keys()].sort();(!o.slowestToolBatch||O.ms>o.slowestToolBatch.ms)&&(o.slowestToolBatch={ms:O.ms,calls:O.calls,tools:M});const H=(A=o.toolBreakdown)==null?void 0:A[M[0]];if(M.length===1&&H)H.ms=(H.ms||0)+O.ms;else for(const X of M){const Y=(L=o.toolBreakdown)==null?void 0:L[X];Y&&(Y.sharedBatches=(Y.sharedBatches||0)+1)}}return o.changedFiles=[...i],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 Hk(e){const t=xn(xn(e).ledgers);return Object.entries(t).flatMap(([n,i])=>um(xn(i).items).map((o,l)=>({runId:n,cursor:Number(o.cursor)||l+1,record:Object.keys(xn(o.record)).length?xn(o.record):o})))}function Bh(e){if(!e)return!1;for(let t=0;t<e.length;t+=1)if(e[t]==="Files")return!0;return!1}function My(e){var i;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)((i=t[o])==null?void 0:i.kind)==="file"&&(n+=1);return n>0?n:null}function Ry(e){return e===1?"Drop file to attach":typeof e=="number"&&e>1?`Drop ${e} files to attach`:"Drop files to attach"}function jx(e){const t=[],n=[],i=e==null?void 0:e.items;if(i&&i.length){for(let l=0;l<i.length;l+=1){const u=i[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 Vk(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 Gk={"image/png":"png","image/jpeg":"jpg","image/gif":"gif","image/webp":"webp","image/heic":"heic","image/tiff":"tiff","image/bmp":"bmp"};function nf(e){return String(e).padStart(2,"0")}function Kk(e,t,n){const i=String(e||"").trim();if(i&&!/^image\.(png|jpe?g|gif|webp|heic|tiff?|bmp)$/i.test(i))return i;const o=Gk[String(t||"").toLowerCase()]||i.split(".").pop()||"bin",l=`${n.getFullYear()}-${nf(n.getMonth()+1)}-${nf(n.getDate())} at ${nf(n.getHours())}.${nf(n.getMinutes())}.${nf(n.getSeconds())}`;return`${String(t||"").startsWith("image/")||!i?"Pasted image":"Pasted file"} ${l}.${o}`}function Yk(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:i}=jx(e);return i.map(o=>{const l=Kk(o.name,o.type,t);return l===o.name?o:new File([o],l,{type:o.type,lastModified:o.lastModified})})}class Jk{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 Xk(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 Zk(e){return(e instanceof Error?e.message:String(e||"Unknown error")).trim()||"Unknown error"}function Qk(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 eN(e){var Y;const t=e.interaction,[n,i]=m.useState(""),[o,l]=m.useState(()=>t.kind==="event-wait"&&t.initialPayload||""),[u,c]=m.useState(null),[f,_]=m.useState(!1),[p,y]=m.useState(""),[w,x]=m.useState(null),S=`${t.kind}:${t.id}`,j=m.useRef(S),E=m.useRef(!1),A=m.useRef(!1),L=m.useRef(!0),O=m.useRef(0);j.current!==S&&(j.current=S,E.current=!1,A.current=!1,O.current+=1);const M=!!e.disabled||u!==null||f||E.current||A.current,H=async(Z,re)=>{var F;if(e.disabled||E.current||A.current)return;const ie=S,ue=++O.current;E.current=!0,x(null),y(""),c(Z);try{if(await re(),!L.current||j.current!==ie||O.current!==ue)return;A.current=!0,_(!0),y("Response sent. Waiting for the workflow to continue.")}catch(C){if(!L.current||j.current!==ie||O.current!==ue)return;x({submission:Z,message:Zk(C)}),y("The action failed. You can try again."),(F=e.onError)==null||F.call(e,C)}finally{if(!L.current||j.current!==ie||O.current!==ue)return;E.current=!1,c(null)}};m.useEffect(()=>{i(""),l(t.kind==="event-wait"&&t.initialPayload||""),x(null),c(null),_(!1),y("")},[S]),m.useEffect(()=>(L.current=!0,()=>{L.current=!1,O.current+=1,E.current=!1}),[]);const X=()=>{w&&H(w.submission,()=>Xk(t,w.submission))};return s.jsxs("section",{className:"pc-workflow-interaction","aria-labelledby":`pc-workflow-interaction-${S}`,children:[s.jsxs("div",{className:"pc-workflow-interaction__heading",children:[s.jsx(Qe,{name:t.kind==="tool-approval"?"warning":t.kind==="event-wait"?"history":"info",size:16}),s.jsxs("div",{children:[s.jsx("h3",{tabIndex:-1,id:`pc-workflow-interaction-${S}`,children:t.title||(t.kind==="tool-approval"?"Tool approval required":"Input required")}),t.description?s.jsx("div",{className:"pc-workflow-interaction__description",children:t.description}):null]})]}),t.kind==="ask-user"?s.jsxs("div",{className:"pc-workflow-interaction__body",children:[s.jsx("div",{className:"pc-workflow-interaction__prompt",children:t.prompt}),(Y=t.choices)!=null&&Y.length?s.jsx("div",{className:"pc-workflow-interaction__choices","aria-label":"Choices",children:t.choices.map(Z=>s.jsxs("button",{type:"button",className:"pc-workflow-interaction__choice",disabled:M||Z.disabled,onClick:()=>void H({kind:"choice",answer:Z.id},()=>t.onSubmit(Z.id)),children:[s.jsx("span",{children:Z.label}),Z.description?s.jsx("small",{children:Z.description}):null]},Z.id))}):null,t.allowFreeText!==!1?s.jsxs("div",{className:"pc-workflow-interaction__entry",children:[s.jsx("textarea",{"aria-label":"Response",value:n,onChange:Z=>i(Z.target.value),placeholder:t.freeTextPlaceholder||"Type a response",rows:2,disabled:M,onKeyDown:Z=>{Z.key!=="Enter"||Z.shiftKey||Z.nativeEvent.isComposing||Z.keyCode===229||(Z.preventDefault(),n.trim()&&H({kind:"free-text",answer:n},()=>t.onSubmit(n)))}},`${S}:text`),s.jsx("button",{type:"button",className:"pc-btn",disabled:M||!n.trim(),onClick:()=>void H({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:M,onClick:()=>void H({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:M,onClick:()=>void H({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:M,onClick:()=>void H({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:Z=>l(Z.target.value),placeholder:t.payloadPlaceholder||"Enter payload",rows:2,"aria-label":t.payloadLabel||(t.eventName?`Payload for ${t.eventName}`:"Event payload"),disabled:M},`${S}:payload`)]}),s.jsx("div",{className:"pc-workflow-interaction__buttons",children:s.jsx("button",{type:"button",className:"pc-btn",disabled:M,onClick:()=>void H({kind:"event",payload:o},()=>t.onSend(o)),children:(u==null?void 0:u.kind)==="event"?"Sending…":t.sendLabel||"Send event"})})]}),w?s.jsx(Qk,{message:w.message,onRetry:X,disabled:M}):null,s.jsx("div",{className:"pc-workflow-interaction__outcome","aria-live":"polite",children:p})]})}function Uh(e){return(e instanceof Error?e.message:String(e||"Unknown error")).trim()||"Unknown error"}function tN(e){const[t,n]=m.useState(!1),[i,o]=m.useState(!1),[l,u]=m.useState(!1),[c,f]=m.useState(null),_=m.useRef(!0),p=m.useRef(!1),y=m.useRef(!1),w=m.useRef(!1),x=m.useRef(0),S=m.useRef(0),j=m.useRef(0);m.useEffect(()=>(_.current=!0,()=>{_.current=!1,x.current+=1,S.current+=1,j.current+=1,p.current=!1,y.current=!1,w.current=!1}),[]);const E=!!e.blockedNotice,A=!!e.disabled||E,L=!!e.busy||t,O=t||!!e.busy&&!e.sendWhileBusy,M=e.stopState||null,H=(M==null?void 0:M.phase)==="stopping",X=typeof e.onFiles=="function",Y=m.useRef(null),[Z,re]=m.useState(null),[ie,ue]=m.useState(""),F=m.useRef(e.onFiles);F.current=e.onFiles;const C=m.useRef(A);C.current=A;const N=async(K,J)=>{const oe=F.current;if(oe){if(C.current){f({action:"attach",message:"attachments are unavailable right now."});return}if(J.length)f({action:"attach",message:Vk(J)});else if(K.length)f(null);else{f({action:"attach",message:"the drop contained no files."});return}if(K.length){ue(`Attaching ${K.length} ${K.length===1?"file":"files"}…`);try{await oe(K)}catch(fe){_.current&&f({action:"attach",message:Uh(fe)})}}}},P=m.useRef(N);P.current=N,m.useEffect(()=>{if(!X||typeof window>"u")return;const K=new Jk;let J=0;const oe=Pe=>!!(Y.current&&Pe instanceof Node&&Y.current.contains(Pe)),fe=()=>{K.reset(),J&&window.clearInterval(J),J=0,re(null)},_e=()=>{J||(J=window.setInterval(()=>{K.active(Date.now())||fe()},250))},we=Pe=>{var Ye;if(!Bh((Ye=Pe.dataTransfer)==null?void 0:Ye.types))return;K.enter(Date.now());const et=oe(Pe.target),lt=My(Pe.dataTransfer);re(Se=>Se&&Se.over===et&&Se.count===(lt??Se.count)?Se:{count:lt??(Se==null?void 0:Se.count)??null,over:et}),_e()},Ae=Pe=>{var lt;if(!Bh((lt=Pe.dataTransfer)==null?void 0:lt.types))return;Pe.preventDefault(),K.over(Date.now());const et=oe(Pe.target);Pe.dataTransfer&&(Pe.dataTransfer.dropEffect=et&&!C.current?"copy":"none"),re(Ye=>Ye&&Ye.over===et?Ye:{count:(Ye==null?void 0:Ye.count)??My(Pe.dataTransfer),over:et}),_e()},Be=Pe=>{var et;Bh((et=Pe.dataTransfer)==null?void 0:et.types)&&(K.leave(Date.now())||fe())},We=Pe=>{var Le;if(!Bh((Le=Pe.dataTransfer)==null?void 0:Le.types))return;const et=oe(Pe.target),lt=Pe.defaultPrevented&&!et;if(Pe.preventDefault(),fe(),lt)return;if(!et){f({action:"attach",message:"drop files on the conversation to attach them."});return}const{files:Ye,folders:Se}=jx(Pe.dataTransfer);P.current(Ye,Se)},_t=Pe=>{Pe.key==="Escape"&&K.depth>0&&fe()};return window.addEventListener("dragenter",we),window.addEventListener("dragover",Ae),window.addEventListener("dragleave",Be),window.addEventListener("drop",We),window.addEventListener("dragend",fe),window.addEventListener("blur",fe),window.addEventListener("keydown",_t),()=>{window.removeEventListener("dragenter",we),window.removeEventListener("dragover",Ae),window.removeEventListener("dragleave",Be),window.removeEventListener("drop",We),window.removeEventListener("dragend",fe),window.removeEventListener("blur",fe),window.removeEventListener("keydown",_t),J&&window.clearInterval(J)}},[X]);const D=K=>{if(!X||A)return;const J=Yk(K.clipboardData);J.length&&(K.preventDefault(),N(J,[]))},ne=Z?s.jsxs("div",{className:["pc-workflow-chat__dropzone",Z.over?"is-over":"",A?"is-disabled":""].filter(Boolean).join(" "),"aria-hidden":"true",children:[s.jsx("span",{className:"pc-workflow-chat__dropzone-icon",children:s.jsx(Qe,{name:"paperclip",size:18})}),s.jsxs("span",{className:"pc-workflow-chat__dropzone-text",children:[s.jsx("strong",{children:A?"Attachments are unavailable right now":Ry(Z.count)}),A?null:s.jsx("span",{children:Z.over?"Release to upload to this conversation":"Drop anywhere on the conversation"})]})]}):null,B=Z?A?"Attachments are unavailable right now":Ry(Z.count):ie,z=async()=>{const K=String(e.draft||"");if(A||p.current||!e.sendWhileBusy&&e.busy||!K.trim())return;const J=++x.current;p.current=!0,f(null),n(!0);try{await e.onSend(K)}catch(oe){_.current&&x.current===J&&f({action:"send",message:Uh(oe)})}finally{_.current&&x.current===J&&(p.current=!1,n(!1))}},G=async()=>{if(A||y.current||!e.onCancel)return;const K=++S.current;y.current=!0,f(null),o(!0);try{await e.onCancel()}catch(J){_.current&&S.current===K&&f({action:"cancel",message:Uh(J)})}finally{_.current&&S.current===K&&(y.current=!1,o(!1))}},T=async()=>{if(A||w.current||!e.onAttach)return;const K=++j.current;w.current=!0,f(null),u(!0);try{await e.onAttach()}catch(J){_.current&&j.current===K&&f({action:"attach",message:Uh(J)})}finally{_.current&&j.current===K&&(w.current=!1,u(!1))}},Q=()=>{c&&(c.action==="send"&&z(),c.action==="cancel"&&G(),c.action==="attach"&&T())};return s.jsxs("section",{ref:Y,className:["pc-workflow-chat",Z?"pc-workflow-chat--dragging":"",Z!=null&&Z.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(xg,{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(eN,{interaction:e.interaction,disabled:A}):null,E?s.jsx("div",{className:"pc-workflow-chat__blocked",role:"status",children:e.blockedNotice}):null]}),afterKey:`${e.interaction?`${e.interaction.kind}:${e.interaction.id}`:""}:${E?"blocked":""}`})}),c?s.jsxs("div",{className:"pc-workflow-chat__error",role:"alert",children:[s.jsxs("span",{children:["Could not ",c.action==="send"?"send this message":c.action==="attach"?"attach a file":"stop the run",": ",c.message]}),s.jsx("button",{type:"button",onClick:Q,disabled:A,children:"Try again"})]}):null,s.jsxs("div",{className:"pc-workflow-chat__composer",children:[s.jsx(bg,{value:e.draft,onChange:e.onDraftChange,onSubmit:()=>void z(),placeholder:e.placeholder||"Send a message",ariaLabel:"Message",disabled:A,busy:O,sendLabel:e.sendLabel,busyLabel:e.busyLabel,rows:2,leading:e.attachments?s.jsx("div",{className:"pc-workflow-chat__attachments",children:e.attachments}):null,overlay:ne,onPaste:X?D: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:A||l,onClick:()=>void T(),children:[s.jsx(Qe,{name:"paperclip",size:16}),s.jsx("span",{children:l?"Attaching…":"Attach"})]}):null,e.composerExtras,L&&e.onCancel?s.jsxs("button",{type:"button",className:"pc-workflow-chat__stop",disabled:A||i||H,onClick:()=>void G(),children:[s.jsx(Qe,{name:"x",size:14}),s.jsx("span",{children:i||H?"Stopping…":"Stop"})]}):M?s.jsx("span",{className:`pc-workflow-chat__stop-state pc-workflow-chat__stop-state--${M.phase}`,role:"status","aria-live":"polite",children:M.label}):null]})}),X?s.jsx("div",{className:"pc-sr-only",role:"status","aria-live":"polite",children:B}):null]}),e.footer?s.jsx("footer",{className:"pc-workflow-chat__footer",children:e.footer}):null]})}const F_="llm.delta",Wh="llm.delta_end";function nN(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Vl(e){return typeof e=="string"&&e.trim()!==""}function sN(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0}function rN(e){return"reason"in e}function iN(e,t){const n=nN(e),i=n==null?void 0:n.kind,o=typeof i=="string"&&i?i:n&&"reason"in n?Wh:F_,l=f=>{throw new Error(`Malformed ${o} event from the gateway: ${f}`)};if(!n)return l("the payload is not an object");i!==void 0&&i!==F_&&i!==Wh&&l(`unknown kind ${JSON.stringify(i)}`),Vl(n.run_id)||l("run_id is missing"),Vl(n.call_id)||l("call_id is missing"),sN(n.seq)||l("seq is not a non-negative integer");const u=i?i===Wh:"reason"in n;n.root_run_id!==void 0&&!Vl(n.root_run_id)&&l("root_run_id is not a run id"),n.parent_run_id!==void 0&&n.parent_run_id!==null&&!Vl(n.parent_run_id)&&l("parent_run_id is neither a run id nor null");const c={run_id:n.run_id,...Vl(n.root_run_id)?{root_run_id:n.root_run_id}:{},...n.parent_run_id!==void 0?{parent_run_id:n.parent_run_id}:{},...Vl(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:Wh,...c,reason:n.reason,...Vl(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:F_,...c,text:n.text,channel:n.channel,snapshot:n.snapshot})}const oN={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 aN(e){return`This reply is not streamed: ${e?oN[e]||`the gateway reported "${e}"`:"the gateway gave no reason"}. It appears when it is complete.`}function lN(e){return e.toolApprovalGranted?null:e.interaction}const Ly={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 pf(e){return Array.isArray(e)?e:[]}function Gr(e){return vt(e==null?void 0:e.status).toLowerCase()||"unknown"}function Ss(e){return["completed","failed","cancelled"].includes(e.toLowerCase())}function rl(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 cN(e){const t=St(e);return Number((t==null?void 0:t.status)??(t==null?void 0:t.statusCode))}function z_(e){const t=n=>{if(Array.isArray(n))return n.map(t);const i=St(n);if(!i)return n;const o={};for(const l of Object.keys(i).sort())o[l]=t(i[l]);return o};try{return JSON.stringify(t(e))}catch{return"[unserializable]"}}function Pp(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 i=t[n];if(typeof i=="string"&&i.trim())return i.trim()}return""}function wu(e){const t=Pp(e);if(t)return t;if(!St(e)&&!Array.isArray(e))return"";try{return JSON.stringify(e,null,2)}catch{return""}}function Iy(e){if(!e)return"";for(const i of["prompt","request","task","message","query","input"]){const o=vt(e[i]);if(o)return o}const t=St(e.context);for(const i of["task","message"]){const o=vt(t==null?void 0:t[i]);if(o)return o}const n=pf(t==null?void 0:t.messages);for(let i=n.length-1;i>=0;i-=1){const o=St(n[i]);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 Sx(e){const t=St(e.result);return St(t==null?void 0:t.wait)}function B_(e){return e?vt(e.reason)==="subworkflow"||vt(e.wait_key).startsWith("subworkflow:"):!1}function Oy(e,t){return!!(e&&e.runId===t.runId&&vt(e.wait.wait_key)===vt(t.wait.wait_key))}function Dp(e){return St(e.effect)||{}}function uN(e,t){return vt(e.run_id)||t}function Py(e){return vt(e.ended_at)||vt(e.started_at)||void 0}function Dy(e){const t=new Set,n=_=>{const p=vt(_);p&&t.add(p)},i=St(e.result);n(i==null?void 0:i.sub_run_id),n(i==null?void 0:i.subRunId),n(i==null?void 0:i.child_run_id);const o=Dp(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=Sx(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 dN{constructor(t,n={}){this.transport=t,this.options=n,this.snapshot={...Ly},this.subscribers=new Set,this.controller=null,this.generation=0,this.rootRunId="",this.cursors=new Map,this.seenRecords=new Set,this.seenMessages=new Set,this.watchedRuns=new Set,this.childCatchUpAttempts=new Map,this.runStates=new Map,this.historicalRuns=new Map,this.historicalRunFailures=new Map,this.commandIds=new Map,this.toolActivities=new Map,this.historicalEvidence=new Map,this.approvedWaits=new Set,this.grantedToolWaits=new Set,this.resolvedWaits=new Set,this.approvalEpoch=0,this.toolApprovalPolicy=null,this.toolApprovalSuspended=!1,this.toolApprovalStopped=!1,this.displayStatusAt=-1/0,this.stopRequested=!1,this.stopFollowing=!1,this.openLlmSteps=new Set,this.forcedStop=null,this.liveReplies=new Map,this.closedLiveCalls=new Set,this.shownLiveCalls=new Set,this.liveDirty=new Set,this.liveRenderTimer=null,this.lastLiveRender=-1/0;const i=n.liveRenderIntervalMs??60;if(typeof i!="number"||!Number.isFinite(i)||i<0)throw new Error(`liveRenderIntervalMs must be a non-negative number of milliseconds, got ${JSON.stringify(n.liveRenderIntervalMs)}`);this.liveRenderIntervalMs=i}subscribe(t){return this.subscribers.add(t),()=>this.subscribers.delete(t)}getSnapshot(){return this.snapshot}reset(){var t;this.toolApprovalSuspended=!1,this.toolApprovalStopped=!1,this.approvalEpoch+=1,this.displayStatusAt=-1/0,this.stopRequested=!1,this.stopFollowing=!1,this.openLlmSteps.clear(),this.forcedStop=null,this.generation+=1,(t=this.controller)==null||t.abort(),this.controller=null,this.rootRunId="",this.cursors.clear(),this.seenRecords.clear(),this.seenMessages.clear(),this.watchedRuns.clear(),this.childCatchUpAttempts.clear(),this.runStates.clear(),this.historicalRuns.clear(),this.historicalRunFailures.clear(),this.commandIds.clear(),this.toolActivities.clear(),this.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({...Ly})}dispose(){this.reset(),this.subscribers.clear()}async load(t){const n=vt(t);if(this.reset(),!n)return;const i=++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(i))return;const c=St(l),f=St(c==null?void 0:c.waiting),_=Gr(c);if(await this.ingestHistory(u,n,i),!this.live(i))return;if(this.set({...this.snapshot,run:c,status:_,loading:!1,...f&&!Ss(_)?{interaction:this.interactionWith({runId:n,wait:f})}:{}}),c&&this.updateRunState(n,c),f)for(const p of Dy({result:{wait:f}}))p!==n&&this.catchUpAndWatch(p,i);await this.catchUpAndWatch(n,i),this.pollRootLifecycle(n,i)}catch(l){!o.signal.aborted&&this.live(i)&&this.fail(l)}}async sendCommand(t,n={}){var p,y;t==="cancel"&&(this.toolApprovalStopped=!0,this.revokeToolApproval(),this.stopRequested=!0,this.recomputeStop());const i=vt(n.wait_key),o=t==="resume"?i?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"&&i&&((p=this.snapshot.interaction)==null?void 0:p.stepId)||"",u=`${o}\0${t}\0${l}\0${z_(n)}`;let c=this.commandIds.get(u);c||(c=this.newCommandId(),this.commandIds.set(u,c));const f=this.generation,_=(y=this.controller)==null?void 0:y.signal;try{const w=await this.transport.submitCommand({command_id:c,run_id:o,type:t,payload:n,...this.options.clientId?{client_id:this.options.clientId}:{}},_);if(!this.live(f))return w;const x=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 i=this.requireInteraction();if(Ss(this.snapshot.status))throw new Error("This run has already ended.");if(n&&(i.runId!==n.runId||vt(i.wait.wait_key)!==n.waitKey||n.stepId!==void 0&&i.stepId!==n.stepId))throw new Error("This approval request has changed. Review the current request before deciding.");if(t&&this.toolApprovalPolicy&&!this.toolCallsMatch(i,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(i.wait.wait_key),payload:{approved:!!t}}).then(l=>{if(!this.live(o))return l;const u=this.occurrenceKey(i);return this.approvedWaits.add(u),t&&this.isToolApproval(i)&&!this.grantedToolWaits.has(u)&&(this.grantedToolWaits.add(u),this.set({...this.snapshot})),l})}async approveWithPolicyChange(t,n){const i=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(i)||o!==this.approvalEpoch||this.toolApprovalStopped||Ss(this.snapshot.status))&&n()}async allowAllToolsForRun(t){const n=this.generation,i=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)||i!==this.approvalEpoch||Ss(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){z_(t)!==z_(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&&B_(t.wait)&&!B_(n.wait)?n:n&&Oy(n,t)&&t.stepId===void 0&&n.stepId!==void 0?{...t,stepId:n.stepId}:t}adoptDurableWait(t,n){const i=St(n.waiting);if(!i||Gr(n)!=="waiting"||B_(i)||Ss(this.snapshot.status)||this.resolvedWaits.has(`${t}:${vt(i.wait_key)}`))return;const o=this.interactionWith({runId:t,wait:i}),l=this.snapshot.interaction;l&&Oy(l,o)&&l.stepId===o.stepId||this.set({...this.snapshot,interaction:o})}coveredByStandingPermission(t,n){var i;return t.loading||this.toolApprovalStopped||this.toolApprovalSuspended||!this.toolApprovalPolicy&&!t.autoApproveTools||Ss(t.status)||((i=t.run)==null?void 0:i.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,i=n?this.occurrenceKey(n):"",o=!!(n&&this.isToolApproval(n)&&(this.grantedToolWaits.has(i)||!this.approvedWaits.has(i)&&this.coveredByStandingPermission({...t,loading:!1},n)));if(!o&&!this.snapshot.toolApprovalGranted&&!t.toolApprovalGranted)return t.toolApprovalGranted===!1?t:{...t,toolApprovalGranted:!1};let l=!1;const u=t.messages.map(c=>{var p;const f=c.toolActivity;if(!f||((p=this.toolActivities.get(f.id))==null?void 0:p.status)!=="waiting")return c;const _=o&&f.runId===(n==null?void 0:n.runId)?"running":"waiting";return f.status===_?c:(l=!0,this.toolMessage({...f,status:_}))});return{...t,toolApprovalGranted:o,...l?{messages:u}:{}}}toolCallsMatch(t,n){var o;const i=pf((o=St(t.wait.details))==null?void 0:o.tool_calls);return i.length>0&&i.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},i=this.occurrenceKey(t);if(this.approvedWaits.has(i))return;this.approvedWaits.add(i),this.grantedToolWaits.add(i);const o=this.generation,l=this.approvalEpoch;this.approve(!0,n).catch(u=>{if(this.live(o)){if(this.grantedToolWaits.delete(i),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 i;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,(i=this.controller)==null?void 0:i.signal));if(!this.live(n))return;o&&this.updateRunState(t,o)}catch(o){if(!this.live(n))return;if(rl(o))throw o;this.fail(o,!1)}if(await this.catchUp(t,n),!this.live(n)||Ss(Gr(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(rl(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 i;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,(i=this.controller)==null?void 0:i.signal);if(!this.live(n))return;const c=St(u),f=Array.isArray(u)?u:pf(c==null?void 0:c.items);for(const p of f)this.ingestItem(t,p);const _=Number(c==null?void 0:c.next_after);if(!f.length||!Number.isFinite(_)||_<=l)break;this.cursors.set(t,_)}}async watch(t,n){try{await this.followStream(t,n)}finally{this.live(n)&&this.closeLiveRepliesVia(t)}}async followStream(t,n){var o;let i=0;for(;this.live(n)&&!Ss(Gr(this.runStates.get(t)||null));){const l=this.cursors.get(t)||0;this.set({...this.snapshot,connection:i?"reconnecting":"connecting"});try{let u=!1;const c=()=>{!this.live(n)||u||(u=!0,this.set({...this.snapshot,connection:"connected",error:null}))};if(this.dropLiveRepliesVia(t),await this.transport.streamLedger(t,l,_=>{this.live(n)&&(c(),this.ingestItem(t,_))},this.controller.signal,c,_=>{this.live(n)&&(c(),this.ingestDelta(t,_))}),!this.live(n)||(await this.catchUp(t,n),!this.live(n)))return;const f=St(await this.transport.getRun(t,(o=this.controller)==null?void 0:o.signal));if(!this.live(n))return;f&&this.updateRunState(t,f),i+=1}catch(u){if(!this.live(n))return;if(i+=1,this.fail(u,!1),rl(u)){this.set({...this.snapshot,connection:"disconnected"});return}}if(i>=5||!this.live(n))break;await this.waitForRetry(Math.min(2e3,150*2**(i-1)))}if(this.live(n)){if(Ss(Gr(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,i){const o=St(t);if(!o)return;const l=St(o.session),u=pf(l==null?void 0:l.turns).map(St).filter(_=>!!_);if(await this.hydrateHistoricalSessionRuns(u,n,i),!this.live(i))return;for(const _ of u){const p=vt(_==null?void 0:_.run_id)||n;this.ingestSessionTurn(_,n,p!==n&&this.historicalRuns.get(p)||null)}const c=`turn:${n}:user`;if(!this.seenMessages.has(c)){const _=Iy(St(o.input_data));_&&this.addMessage({id:c,role:"user",content:_})}const f=St(o.ledgers);if(f)for(const[_,p]of Object.entries(f)){const y=St(p);for(const w of pf(y==null?void 0:y.items))this.ingestItem(_,w)}}ingestSessionTurn(t,n,i){if(!t)return;const o=vt(t.run_id)||n,l=St(t.input_data)||St(t.input)||{},u=vt(t.prompt)||Iy(l);u&&this.addMessage({id:`turn:${o}:user`,role:"user",content:u,ts:vt(t.created_at)||void 0});const c=this.historicalRunFailures.get(o);if(c){const y=vt(t.answer)||Pp(t.output),w=c.missing?"is unavailable because the run no longer exists":"could not be restored",x=y?` Saved reply (not verified as the final result): ${y}`:"";this.addMessage({id:`history:${o}:unavailable`,role:"system",level:"warn",title:"History",content:`The final output for an earlier turn ${w}.${x}`});return}const _=(i&&Ss(Gr(i))?wu(i.output):"")||(i?vt(t.answer)||Pp(t.output):""),p=this.historicalEvidence.get(o);for(const y of(p==null?void 0:p.tools)||[])this.upsertTool(y);_&&this.addRunAssistantMessage(o,{id:`final:${o}`,role:"assistant",content:_,runId:o,statistics:p==null?void 0:p.statistics,ts:vt(t.updated_at)||void 0})}async hydrateHistoricalSessionRuns(t,n,i){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(i))return;let l=0,u=!1;const c=async()=>{var f,_,p;for(;!u&&this.live(i);){const y=o[l++];if(!y)return;try{const w=St(await this.transport.getRun(y,(f=this.controller)==null?void 0:f.signal));if(!this.live(i))return;if(w){this.historicalRuns.set(y,w);try{const x=await this.transport.getHistory(y,(_=this.controller)==null?void 0:_.signal);if(!this.live(i))return;this.historicalEvidence.set(y,D_(Hk(x)))}catch(x){if(!this.live(i))return;if(rl(x))throw x;this.fail(new Error(`Earlier turn activity could not be restored: ${x instanceof Error?x.message:String(x)}`),!1)}}else this.historicalRuns.set(y,null),this.historicalRunFailures.set(y,{missing:!1,detail:"gateway returned an invalid historical run snapshot"})}catch(w){if(!this.live(i))return;const x=cN(w)===404;this.historicalRuns.set(y,null),this.historicalRunFailures.set(y,{missing:x,detail:w instanceof Error?w.message:vt((p=St(w))==null?void 0:p.detail)||"request failed"}),rl(w)&&(u=!0,this.fail(w))}}};if(await Promise.all(Array.from({length:Math.min(4,o.length)},()=>c())),u&&this.live(i))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 i=St(n),o=St(i==null?void 0:i.record)||i;if(!o)return;const l=uN(o,t),u=Number(i==null?void 0:i.cursor),c=Number.isFinite(u)&&u>0?u:(this.cursors.get(l)||0)+1,f=`${l}:${c}`;if(!this.seenRecords.has(f)){if(this.seenRecords.add(f),this.cursors.set(l,Math.max(this.cursors.get(l)||0,c)),this.set({...this.snapshot,records:[...this.snapshot.records,{cursor:c,record:o,runId:l}]}),this.foldRecord(l,o,f),this.snapshot.messages.some(_=>_.id===`final:${this.rootRunId}`)){const _=D_(this.snapshot.records).statistics;this.set({...this.snapshot,messages:this.snapshot.messages.map(p=>p.id===`final:${this.rootRunId}`?{...p,statistics:_}:p)})}for(const _ of Dy(o))_!==l&&this.catchUpAndWatch(_,this.generation)}}foldRecord(t,n,i){var p,y,w;const o=Dp(n),l=vt(o.type).toLowerCase(),u=St(n.result),c=vt(n.status).toLowerCase(),f=Py(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=wu(u)||wu(St(o.payload));x&&this.addRunAssistantMessage(t,{id:`answer:${t}:${i}`,role:"assistant",content:x,ts:f})}if(l==="emit_event"&&c==="completed"){const x=St(o.payload)||{},S=St(u),j=vt(x.name)||vt(S==null?void 0:S.name),E=x.payload!==void 0?x.payload:S==null?void 0:S.payload;if(["abstract.message","abstractcode.message"].includes(j)){const A=wu(E);if(A){const L=vt((p=St(E))==null?void 0:p.level).toLowerCase(),O=L==="error"?"error":["warn","warning"].includes(L)?"warn":"info";this.addMessage({id:`event:${t}:${i}`,role:"system",title:"Workflow",content:A,level:O,ts:f})}}if(["abstract.status","abstractcode.status"].includes(j)){const A=St(E),L=A?A.status??A.text??A.value:E,O=Date.parse(f||"");!Ss(this.snapshot.status)&&typeof L=="string"&&(!Number.isFinite(O)||O>=this.displayStatusAt)&&(Number.isFinite(O)&&(this.displayStatusAt=O),this.set({...this.snapshot,displayStatus:L.trim()}))}if(["abstract.tool_execution","abstractcode.tool_execution","abstract.tool_result","abstractcode.tool_result"].includes(j)){const A=wu(E);A&&this.addMessage({id:`event:${t}:${i}`,role:"system",title:"Tool activity",content:A,ts:f})}}const _=Sx(n);if(c==="waiting"&&_&&!Ss(this.snapshot.status)&&!Ss(Gr(this.runStates.get(t)||null))&&(this.resolvedWaits.delete(`${t}:${vt(_.wait_key)}`),this.set({...this.snapshot,interaction:this.interactionWith({runId:t,wait:_,...vt(n.step_id)?{stepId:vt(n.step_id)}:{}})})),l==="tool_calls")for(const x of xx(this.toolActivities,{runId:t,cursor:this.cursors.get(t)||0,record:n}))this.upsertTool(x);if(l==="resume"&&(u==null?void 0:u.resumed)===!0){const x=vt((y=St(o.payload))==null?void 0:y.wait_key);x&&this.resolvedWaits.add(`${t}:${x}`),((w=this.snapshot.interaction)==null?void 0:w.runId)===t&&(this.set({...this.snapshot,interaction:null}),this.refreshRunState(t,this.generation))}}foldStopEvidence(t,n,i,o){let l=!1;if(i==="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(i==="emit_event"&&o==="completed"){const u=St(Dp(n).payload)||{},c=St(n.result),f=vt(u.name)||vt(c==null?void 0:c.name),_=St(u.payload!==void 0?u.payload:c==null?void 0:c.payload);f==="abstract.status"&&vt(_==null?void 0:_.killed_by)==="kill_switch"&&(this.forcedStop=_,l=!0)}l&&this.recomputeStop()}recomputeStop(){let t=null;this.forcedStop?t={phase:"forced",label:vt(this.forcedStop.text)||"Stop forced: inference killed",record:this.forcedStop}:this.stopRequested&&(t=this.snapshot.status==="cancelled"&&this.openLlmSteps.size===0?{phase:"stopped",label:"Stopped"}:{phase:"stopping",label:"Stopping…"});const n=this.snapshot.stop||null;((n==null?void 0:n.phase)!==(t==null?void 0:t.phase)||(n==null?void 0:n.label)!==(t==null?void 0:t.label))&&this.set({...this.snapshot,stop:t}),(t==null?void 0:t.phase)==="stopping"&&this.snapshot.status==="cancelled"&&this.followStop(this.generation)}async followStop(t){var n;if(!this.stopFollowing){this.stopFollowing=!0;try{let i=500,o=null;for(;this.live(t)&&((n=this.snapshot.stop)==null?void 0:n.phase)==="stopping";){if(await this.waitForRetry(i),!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),i=Math.min(5e3,i*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),i=this.snapshot.messages.findIndex(l=>l.id===n.id);if(i<0){this.addMessage(n);return}const o=[...this.snapshot.messages];o[i]=n,this.set({...this.snapshot,messages:o})}addRunAssistantMessage(t,n){this.closeLiveRepliesOfRun(t);const i=`answer:${t}:`,o=`final:${t}`;this.snapshot.messages.some(l=>l.role==="assistant"&&l.content===n.content&&(l.id===o||String(l.id||"").startsWith(i)))||this.addMessage(n)}ingestDelta(t,n){let i;try{i=iN(n)}catch(f){this.fail(f,!1);return}const o=`${i.run_id}:${i.call_id}`;if(rN(i)){if(i.reason==="unavailable"){this.noteStreamUnavailable(i);return}if(i.reason==="cancelled"&&i.detail==="reinvoked"){this.closeLiveReply(o,"restarted");return}this.closeLiveReply(o,i.reason==="completed"?void 0:i.reason);return}if(this.closedLiveCalls.has(o)||this.runEnded(i.run_id)||this.runEnded(this.rootRunId))return;const l=this.liveReplies.get(o)||{runId:i.run_id,callId:i.call_id,nodeId:i.node_id||"",via:t,text:"",reasoning:"",seq:{content:-1,reasoning:-1}},u=i.channel==="reasoning"?"reasoning":"text",c=l.seq[i.channel];if(i.snapshot){if(i.seq<c)return;l[u]=i.text}else{if(i.seq<=c)return;l[u]+=i.text}l.seq[i.channel]=i.seq,l.via=t,this.liveReplies.set(o,l),this.liveDirty.add(o),this.scheduleLiveRender()}runEnded(t){return Ss(Gr(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 i=this.liveReplies.get(n);if(!i)continue;const o=this.liveMessage(i),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 i=this.liveReplies.get(t);if(!i){n==="restarted"&&this.shownLiveCalls.has(t)&&this.addMessage(this.restartNote(t));return}this.liveReplies.delete(t),this.liveDirty.delete(t);const o=`live:${i.runId}:${i.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:${i.runId}:${i.callId}`;this.seenMessages.add(c),u[l]={id:c,role:"system",level:"warn",title:"Reply",runId:i.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:aN(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 i of[...this.liveReplies.values()])(i.via===t||i.runId===t)&&this.closeLiveReply(`${i.runId}:${i.callId}`,n)}endLiveRepliesOfRun(t,n){const i=n==="failed"||n==="cancelled"?n:void 0;if(t===this.rootRunId){for(const o of[...this.liveReplies.values()])this.closeLiveReply(`${o.runId}:${o.callId}`,i);this.closedLiveCalls.clear(),this.shownLiveCalls.clear();return}this.closeLiveRepliesVia(t,i);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[i,o]of this.liveReplies)o.via===t&&(this.liveReplies.delete(i),this.liveDirty.delete(i),n.add(`live:${o.runId}:${o.callId}`));n.size&&this.set({...this.snapshot,messages:this.snapshot.messages.filter(i=>!n.has(String(i.id)))})}fail(t,n=!0){var i,o,l;rl(t)&&(this.approvalEpoch+=1,this.toolApprovalStopped=!0,this.toolApprovalSuspended=!0,(o=(i=this.options).onAuthError)==null||o.call(i,t)),this.set({...this.snapshot,error:t instanceof Error?t.message:vt((l=St(t))==null?void 0:l.detail)||String(t),...rl(t)?{autoApproveTools:!1}:{},...n?{connection:"disconnected"}:{}})}newCommandId(){const t=globalThis.crypto;return t&&typeof t.randomUUID=="function"?t.randomUUID():`workflow-${Date.now()}-${Math.random().toString(36).slice(2)}`}updateRunState(t,n){var l;if(this.runStates.set(t,n),Ss(Gr(n))&&this.endLiveRepliesOfRun(t,Gr(n)),t!==this.rootRunId){Ss(Gr(n))&&((l=this.snapshot.interaction)==null?void 0:l.runId)===t?this.set({...this.snapshot,interaction:null}):this.adoptDurableWait(t,n);return}const i=Gr(n),o=Ss(i);if(o){const u=wu(n.output);u&&this.upsertFinal(t,u,Py(n))}this.set({...this.snapshot,run:n,status:i,...o?{interaction:null,autoApproveTools:!1,displayStatus:""}:{}}),o||this.adoptDurableWait(t,n),(this.stopRequested||this.forcedStop)&&this.recomputeStop()}upsertFinal(t,n,i){this.closeLiveRepliesOfRun(t);const o=`final:${t}`;this.seenMessages.add(o);const l={id:o,role:"assistant",content:n,ts:i,runId:t,statistics:D_(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 i;try{const o=St(await this.transport.getRun(t,(i=this.controller)==null?void 0:i.signal));o&&this.live(n)&&this.updateRunState(t,o)}catch(o){this.live(n)&&this.fail(o,!1)}}async pollRootLifecycle(t,n){var i;for(;this.live(n)&&this.rootRunId===t&&!Ss(Gr(this.runStates.get(t)||null));){if(await this.waitForRetry(2e3),!this.live(n)||this.rootRunId!==t||Ss(Gr(this.runStates.get(t)||null)))return;try{const o=St(await this.transport.getRun(t,(i=this.controller)==null?void 0:i.signal));o&&this.live(n)&&this.rootRunId===t&&this.updateRunState(t,o)}catch(o){if(!this.live(n))return;if(rl(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 i=n;return new Promise(l=>{const u=setTimeout(f,t),c=()=>{clearTimeout(u),f()};function f(){i.removeEventListener("abort",c),l()}i.addEventListener("abort",c,{once:!0})})}}function fN(e){const t=m.useMemo(()=>new dN(e.transport,{onAuthError:e.onAuthError,clientId:e.clientId,...e.liveRenderIntervalMs!==void 0?{liveRenderIntervalMs:e.liveRenderIntervalMs}:{}}),[e.transport,e.onAuthError,e.clientId,e.authScopeKey,e.liveRenderIntervalMs]),n=m.useSyncExternalStore(o=>t.subscribe(o),()=>t.getSnapshot(),()=>t.getSnapshot()),i=String(e.runId||"").trim();return m.useEffect(()=>{t.setToolApprovalPolicy(e.enabled===!1?{enabledTools:[],autoApproveTools:[]}:e.toolApprovalPolicy??null)},[t,e.toolApprovalPolicy,e.enabled]),m.useEffect(()=>{if(e.enabled===!1||!i){t.reset();return}return t.load(i),()=>t.reset()},[t,i,e.enabled]),{controller:t,snapshot:n}}function Gl(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function ur(e){return typeof e=="string"?e.trim():e==null?"":typeof e=="number"||typeof e=="boolean"?String(e):""}function Fy(e){return["session","workflow","run","global"].includes(e)?e:null}function ol(e){return{scope:ur(e==null?void 0:e.scope).toLowerCase(),name:ur(e==null?void 0:e.name)||ur(e==null?void 0:e.event_name),scopeId:ur(e==null?void 0:e.scope_id)||ur(e==null?void 0:e.scopeId),sessionId:ur(e==null?void 0:e.session_id)||ur(e==null?void 0:e.sessionId),workflowId:ur(e==null?void 0:e.workflow_id)||ur(e==null?void 0:e.workflowId),runId:ur(e==null?void 0:e.run_id)||ur(e==null?void 0:e.runId)}}function hN(e,t){const n=e.wait,i=ur(n.wait_key),o=[ol(n),ol(Gl(n.details))];for(const l of t){if(l.runId!==e.runId)continue;const u=l.record,c=Gl(u.result),f=Gl(c==null?void 0:c.wait),_=Gl(u.effect),p=Gl(_==null?void 0:_.payload);ur(f==null?void 0:f.wait_key)!==i&&ur(p==null?void 0:p.wait_key)!==i||o.push(ol(u),ol(p),ol(Gl(p==null?void 0:p.details)),ol(f),ol(Gl(f==null?void 0:f.details)))}return o}function U_(e,t){return t.scopeId?t.scopeId:e==="session"?t.sessionId:e==="workflow"?t.workflowId:e==="run"?t.runId:"global"}function kx(e,t,n){return{scope:e,scopeId:t,name:n,...e==="session"?{sessionId:t}:{},...e==="workflow"?{workflowId:t}:{},...e==="run"?{runId:t}:{}}}function mN(e,t,n){if(!n)return null;const i=`evt:${t}:${n}:`;if(!e.startsWith(i))return null;const o=e.slice(i.length);return o?kx(t,n,o):null}function _N(e,t=[],n){if(!e)return{target:null,error:"No event wait is available."};const i=ur(e.wait.wait_key),o=/^evt:(session|workflow|run|global):/.exec(i);if(!o)return{target:null,error:"The gateway did not provide a canonical event wait key."};const l=Fy(o[1]);if(!l)return{target:null,error:"The event wait uses an unsupported scope."};const u=hN(e,Array.isArray(t)?t:[]),c=new Map;for(const w of u){const x=Fy(w.scope);if(!x||!w.name)continue;if(x!==l)return{target:null,error:"Event metadata conflicts with the canonical wait scope."};const S=`evt:${x}:`,j=`:${w.name}`;if(!i.startsWith(S)||!i.endsWith(j)||i.length<=S.length+j.length)return{target:null,error:"Event metadata does not exactly match the canonical wait key."};const E=i.slice(S.length,-j.length),A=U_(x,w);if(A&&A!==E)return{target:null,error:"Event metadata conflicts with the canonical wait target."};const L=kx(x,E,w.name);c.set(`${L.scope}\0${L.scopeId}\0${L.name}`,L)}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=U_(l,w);x&&f.add(x)}if(ur(n==null?void 0:n.run_id)===e.runId){const w=ol(n||null),x=U_(l,w);x&&f.add(x)}const p=[...f].map(w=>mN(i,l,w)).filter(w=>!!w),y=new Map(p.map(w=>[`${w.scope}\0${w.scopeId}\0${w.name}`,w]));return y.size===1?{target:[...y.values()][0]}:y.size>1?{target:null,error:"The event key is ambiguous for the available scope metadata."}:{target:null,error:"The gateway did not provide enough canonical event routing metadata."}}const jg=e=>bt(`runs/${encodeURIComponent(e)}/workspace`);function pN(e){return jg(e)}function gN(e,t){return`${jg(e)}/files?${new URLSearchParams({path:t,recursive:"false"})}`}function yN(e,t){return`${jg(e)}/content?${new URLSearchParams({path:t})}`}async function Vm(e,t){let n="";try{const i=await e.text();try{const o=JSON.parse(i),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:i}catch{n=i}}catch{n=""}return new Error(`${t} (HTTP ${e.status}): ${n.trim()||e.statusText||"no reason given"}`)}function wN(e,t){const n=e&&typeof e=="object"&&!Array.isArray(e)?e:null,i=u=>{throw new Error(`Unexpected /workspace/files response from the gateway: ${u}.`)};if(!n)return i("not an object");Array.isArray(n.entries)||i("no `entries` list"),typeof n.truncated!="boolean"&&i("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")&&i(`entry ${c+1} lacks a name, path or file/dir type`),f}),l=n.hidden&&typeof n.hidden=="object"&&!Array.isArray(n.hidden)?n.hidden:void 0;return{path:typeof n.path=="string"?n.path:t,entries:o,truncated:n.truncated,...l?{hidden:l}:{}}}async function vN(e,t,n){const i=await e(pN(t),{signal:n});if(!i.ok)throw await Vm(i,"The workspace is not available");const o=await i.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 xN(e,t,n,i){const o=await e(gN(t,n),{signal:i});if(!o.ok)throw await Vm(o,"The folder could not be listed");return wN(await o.json(),n)}async function bN(e,t,n,i){const o=await e(yN(t,n),{signal:i});if(!o.ok)throw await Vm(o,"The file could not be read");return await o.blob()}async function jN(e,t,n,i){const o=await vN(e,t,i);return{where:o,listing:o.exists?await xN(e,t,n,i):null}}function SN(e){const t=String(e||"").split("/").filter(Boolean),n=[{label:"Workspace",path:""}];return t.forEach((i,o)=>n.push({label:i,path:t.slice(0,o+1).join("/")})),n}function kN(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,i=0;for(;n>=1024&&i<t.length-1;)n/=1024,i+=1;return`${n<10?n.toFixed(1):Math.round(n)} ${t[i]}`}function NN(e){return[...e].sort((t,n)=>t.type===n.type?t.name.localeCompare(n.name):t.type==="dir"?-1:1)}function CN(e){const t=e.hidden||{},n=Number(t.blocked||0)+Number(t.outside_links||0)+Number(t.other||0),i=[];return n>0&&i.push(`${n} ${n===1?"entry":"entries"} hidden by the gateway's workspace rules`),e.truncated&&i.push("the list is truncated"),i.join("; ")}const EN=new Set(["image/png","image/jpeg","image/gif","image/webp","image/avif","image/bmp","application/pdf","text/plain","application/json"]);function $N(e){const t=String(e||"").split(";",1)[0].trim().toLowerCase();return EN.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 Nx(e,t,n){const i=n==="open"?$N(e.type):{mode:"download"},o=i.mode==="open"&&i.type!==e.type?new Blob([e],{type:i.type}):e,l=URL.createObjectURL(o);if(i.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 AN(e,t,n){const i=await e(Xj(t),{signal:n.signal});if(!i.ok)throw await Vm(i,`${n.name} could not be read`);Nx(await i.blob(),n.name,n.mode??"open")}function Cx(e){const{fetchGateway:t,runId:n}=e,[i,o]=m.useState({runId:n,path:""}),l=i.runId===n?i.path:"",[u,c]=m.useState(null),[f,_]=m.useState(""),[p,y]=m.useState(!!n),[w,x]=m.useState(""),[S,j]=m.useState(0);m.useEffect(()=>{if(!n)return;const L=new AbortController;return y(!0),_(""),(async()=>{try{const O=await jN(t,n,l,L.signal);L.signal.aborted||c({runId:n,...O})}catch(O){L.signal.aborted||_(String((O==null?void 0:O.message)||O))}finally{L.signal.aborted||y(!1)}})(),()=>L.abort()},[t,n,l,S,e.refreshKey]);const E=u&&u.runId===n?u:null,A=m.useCallback(async(L,O)=>{x(L.path),_("");try{Nx(await bN(t,n,L.path),L.name,O)}catch(M){_(String((M==null?void 0:M.message)||M))}finally{x("")}},[t,n]);return s.jsx(TN,{title:e.title,note:e.note,where:(E==null?void 0:E.where)??null,path:l,listing:(E==null?void 0:E.listing)??null,error:f,loading:p,fileBusy:w,selectedPath:e.selectedPath,className:e.className,onNavigate:L=>o({runId:n,path:L}),onRefresh:()=>j(L=>L+1),onFile:e.onSelectFile?void 0:(L,O)=>void A(L,O),onSelectFile:e.onSelectFile,onClose:e.onClose})}function TN(e){var i,o,l,u;const t=e.listing?CN(e.listing):"",n=(o=(i=e.where)==null?void 0:i.host)==null?void 0:o.hostname;return s.jsxs("section",{className:`pc-ws${e.className?` ${e.className}`:""}`,"aria-label":e.title,"data-workspace-root":((l=e.where)==null?void 0:l.workspace_root)||void 0,children:[s.jsxs("header",{className:"pc-ws__head",children:[s.jsxs("span",{className:"pc-ws__title",children:[s.jsx(Qe,{name:"folder",size:15})," ",e.title]}),s.jsx("span",{className:"pc-ws__spacer"}),s.jsx("button",{type:"button",className:"pc-ws__icon-btn","data-action":"refresh-folder",onClick:e.onRefresh,disabled:e.loading,title:"Refresh","aria-label":"Refresh the folder",children:s.jsx(Qe,{name:"refresh",size:14})}),e.onClose?s.jsx("button",{type:"button",className:"pc-ws__icon-btn","data-action":"close-folder",onClick:e.onClose,title:"Close","aria-label":"Close the file browser",children:s.jsx(Qe,{name:"x",size:14})}):null]}),e.where?s.jsxs("div",{className:"pc-ws__root",children:[s.jsx("code",{children:e.where.workspace_root}),n&&((u=e.where.host)==null?void 0:u.caller_is_this_machine)!==!0?s.jsxs("span",{className:"pc-ws__muted",children:[" on the gateway host ",n]}):null]}):null,e.note?s.jsx("div",{className:"pc-ws__muted",children:e.note}):null,s.jsx("nav",{className:"pc-ws__crumbs","aria-label":"Folder",children:SN(e.path).map((c,f,_)=>f===_.length-1?s.jsx("span",{"aria-current":"page",children:c.label},c.path):s.jsxs(ve.Fragment,{children:[s.jsx("button",{type:"button",className:"pc-ws__crumb",onClick:()=>e.onNavigate(c.path),children:c.label}),s.jsx("span",{className:"pc-ws__muted",children:" / "})]},c.path))}),e.error?s.jsx("div",{className:"pc-ws__error",role:"alert",children:e.error}):null,e.loading&&!e.listing?s.jsx("div",{className:"pc-ws__muted",role:"status",children:"Loading…"}):null,e.where&&!e.where.exists?s.jsx("div",{className:"pc-ws__muted",children:"The folder does not exist yet: nothing has been written."}):null,e.listing?e.listing.entries.length?s.jsx("ul",{className:"pc-ws__entries",children:NN(e.listing.entries).map(c=>s.jsx("li",{className:`pc-ws__entry${e.selectedPath===c.path?" is-selected":""}`,"data-type":c.type,"data-path":c.path,children:c.type==="dir"?s.jsxs("button",{type:"button",className:"pc-ws__name","data-action":"open-dir",onClick:()=>e.onNavigate(c.path),children:[s.jsx(Qe,{name:"folder",size:14})," ",c.name,"/"]}):s.jsxs(s.Fragment,{children:[e.onSelectFile?s.jsxs("button",{type:"button",className:"pc-ws__name","data-action":"select-file","aria-pressed":e.selectedPath===c.path,onClick:()=>{var f;return(f=e.onSelectFile)==null?void 0:f.call(e,c)},children:[s.jsx(Qe,{name:"file",size:14})," ",c.name]}):s.jsxs("span",{className:"pc-ws__name",children:[s.jsx(Qe,{name:"file",size:14})," ",c.name]}),s.jsx("span",{className:"pc-ws__size",children:kN(c.size_bytes)}),e.onFile?s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"pc-ws__btn","data-action":"open-file",disabled:e.fileBusy===c.path,onClick:()=>{var f;return(f=e.onFile)==null?void 0:f.call(e,c,"open")},children:"Open"}),s.jsx("button",{type:"button",className:"pc-ws__icon-btn","data-action":"download-file",disabled:e.fileBusy===c.path,onClick:()=>{var f;return(f=e.onFile)==null?void 0:f.call(e,c,"download")},title:`Download ${c.name}`,"aria-label":`Download ${c.name}`,children:s.jsx(Qe,{name:"download",size:14})})]}):null]})},c.path))}):s.jsx("div",{className:"pc-ws__muted",children:"This folder is empty."}):null,t?s.jsx("div",{className:"pc-ws__muted","data-hidden-note":"true",children:t}):null]})}function Ex(e){return s.jsx(qv,{text:e,images:"link"})}const MN={trigger:"Trigger",answer:"Automation"};function RN(e){return s.jsx(vg,{message:{id:`${e.runId}:${e.kind}`,role:e.role,content:e.text,title:MN[e.kind],runId:e.runId},images:"link"})}const LN={renderText:Ex,renderTurn:RN};function IN(e){const{fetchGateway:t,...n}=e,i=n.onOpenResource??(t?o=>AN(t,o.url,{name:o.name}):void 0);return s.jsx(Ck,{...n,onOpenResource:i,...LN})}function ON(e,t,n={}){if(!e)return null;const i=e.wait,o=`${e.runId}:${i.wait_key}:${e.stepId||""}`,l=i.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(i.wait_key||""),stepId:e.stepId},_=[...new Set(c.map(y=>String((y==null?void 0:y.name)||"tool")))],p=n.onPermissionsAll;return{id:o,kind:"tool-approval",title:`${c.length||"Requested"} ${c.length===1?"action needs":"actions need"} permission`,toolName:_.join(", ")||"the requested tools",description:"Review the targets below. Allow once approves this batch only.",detail:s.jsxs("div",{className:"pc-approval-summary",children:[s.jsx(yx,{tools:c.map((y,w)=>({id:String((y==null?void 0:y.call_id)||(y==null?void 0:y.id)||w),runId:e.runId,name:(y==null?void 0:y.name)||"Tool",arguments:y==null?void 0:y.arguments,status:"waiting"}))}),s.jsxs("details",{children:[s.jsx("summary",{children:"Review full tool arguments (JSON)"}),s.jsx(fr,{value:c.length?c:l})]})]}),approveLabel:"Allow once",denyLabel:"Deny",approveAllLabel:p?"Allow all enabled tools":void 0,approveAllDescription:p?"Sets permissions: all for this Gateway account, including future turns. Unchecked tools stay unavailable; explicit Ask overrides and Gateway restrictions remain enforced. Questions still need your answer.":void 0,onApproveAll:p?async()=>{await t.approveWithPolicyChange(f,()=>{p()})}:void 0,onApprove:async()=>{await t.approve(!0,f)},onDeny:async()=>{await t.approve(!1,f)}}}if(i.reason==="user"||i.reason==="ask_user")return{id:o,kind:"ask-user",title:"A question for you",prompt:String(i.prompt||l.prompt||"How would you like to continue?"),allowFreeText:i.allow_free_text!==!1,choices:(Array.isArray(i.choices)?i.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(i.wait_key||"");if(i.reason==="event"||u.startsWith("evt:")){const c=_N(e,n.records||[],n.currentRun??null),f=c.target,_=(f==null?void 0:f.name)||"";return{id:o,kind:"event-wait",title:f?"Waiting for an event":"Event routing unavailable",eventName:_,prompt:String(i.prompt||`This workflow will continue when “${_||"its trigger"}” arrives.`),description:f?"You can also send the expected event here.":`This event cannot be sent safely. ${c.error}`,initialPayload:"{}",payloadLabel:"Event data (JSON)",sendLabel:"Send event",onSend:async p=>{if(!f)throw new Error(c.error);const y=JSON.parse(p||"{}"),w={name:f.name,scope:f.scope,payload:y};f.scope==="session"?w.session_id=f.scopeId:f.scope==="workflow"?w.workflow_id=f.scopeId:f.scope==="run"&&(w.run_id=f.scopeId),await t.emitEvent(w)}}}return null}const PN="# 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- Dev/build uses Vite aliases to sibling workspace packages under `../abstractuic/*/src` (see `vite.config.ts` and `docs/development.md`).\n- `llms.txt` format reference: https://llmstxt.org/\n\n## Documentation (start here)\n- [README](README.md): Install and quickstart\n- [Getting started](docs/getting-started.md): Run the UI and connect to a gateway; Ask about a run (whole conversation, History note when the 50k-token window drops older messages, error cards never sent back) vs the top-bar Assistant (one gateway session per conversation, New conversation, no tools)\n- [FAQ](docs/faq.md): Common questions (grounded in code), including the CLI `/api` session proxy, the About dialog, chat history windows and the tool-less Assistant\n- [Docs index](docs/README.md): What to read next\n- [Architecture](docs/architecture.md): Components, data flow, diagrams\n- [Configuration](docs/configuration.md): launch flags, serving under the gateway at /apps/observer/, UI settings, deployment patterns\n- [API](docs/api.md): Gateway endpoints used by the UI, including Runtime Activity run pages and canonical artifact envelope search/stats for Runtime Artifact Explorer\n- [Automations](docs/automations.md): Launch → Automate (what, when in UTC intervals, independent/growing context, tool approval), the Automations page (icon controls, Edit: the row's Edit opens the form — title, task, interval, context, tools —, 409 conflicts), runs as a conversation, answering waits by kind, the automation's files (browse, open, download through the gateway), Discuss as an in-page chat with a fork, automation tags on Board/Observe/System, legacy schedules and Recreate, the stub gateway\n- [Development](docs/development.md): Local dev, workspace deps, tests, build\n- [Security](docs/security.md): Trust boundaries and operational guidance\n- [Troubleshooting](docs/troubleshooting.md): Common issues and fixes (CORS, mixed content, 401 under `/api`, About shows the gateway unavailable, stale service worker, automations)\n\n## Key entrypoints (code)\n- [CLI](bin/cli.js) and [app server](bin/server.js): launch flags (`--gateway-url`, `--port`, `--host`, `--monitor-gpu`, `--entity-app-url`, `--gateway-dir`), mount-capable handler, session proxy, folder reveal (browsers on this machine only)\n- [App shell + pages](src/ui/app.tsx): settings, page routing, observe/launch flows, durable commands\n- [Gateway client](src/lib/gateway_client.ts): HTTP client + SSE ledger streaming (API source of truth)\n- [Automations rules + controller](src/ui/automations.ts): workflow choice (`@default`), create body, run tags, capability gate, legacy prefill, typed wait answers, page controller\n- [Automations page](src/ui/automations_page.tsx) and [Automate fields](src/ui/automate_form.tsx): the page, rows and the ui-kit `AutomationPanel` wiring; the When/Context/Tools fields\n- [Discussion chat](src/ui/automation_discussion.tsx): panel-chat `WorkflowChat` + `presentInteraction` over the gateway client; folders through panel-chat `WorkspaceBrowser` (`/runs/{id}/workspace*`)\n- [Automations stub gateway](scripts/automations_stub_server.mjs): dev/test stub serving the ui-kit fixtures\n- [Vite config](vite.config.ts): workspace aliases + dev session proxy and `/api` fallback proxy\n- [Package metadata](package.json): npm name/version, scripts, Node engine\n- [llms-full generator](scripts/generate-llms-full.mjs): defines which files are embedded into `llms-full.txt`\n\n## Ecosystem context\n- [AbstractFramework](https://github.com/lpalbou/AbstractFramework): ecosystem entrypoint and component map\n- [AbstractRuntime](https://github.com/lpalbou/abstractruntime): durable workflow runtime behind the gateway ledger\n- [AbstractCore](https://github.com/lpalbou/abstractcore): unified LLM + tools layer commonly used by workflows\n\n## Common tasks\n- Add/change a gateway capability: update `src/lib/gateway_client.ts` (source of truth) → update `docs/api.md` → run `npm test` + `npm run build`.\n- Change CLI behavior/config: update `bin/cli.js` / `bin/server.js` → update `docs/configuration.md` → run `npm run build`.\n- Update docs for agents: edit docs → regenerate `llms-full.txt` with `npm run llms:full`.\n\n## Optional (project meta)\n- [Changelog](CHANGELOG.md): Release notes\n- [Contributing](CONTRIBUTING.md): How to develop and submit changes\n- [Security policy](SECURITY.md): Responsible vulnerability reporting\n- [Acknowledgments](ACKNOWLEDGMENTS.md): Credits\n- [Code of conduct](CODE_OF_CONDUCT.md): Conduct expectations and reporting\n- [License](LICENSE): MIT license\n";function zs(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`id_${Date.now()}_${Math.random().toString(16).slice(2)}`}function DN(e,t){return[...e.filter(n=>!n.local_error),t].map(n=>({role:n.role,content:n.content}))}function qh(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?Math.trunc(e):0}function FN(e){const t=qh(e==null?void 0:e.dropped_messages);if(!e||t<=0)return null;const n=qh(e.replayed_messages),i=qh(e.dropped_tokens),o=qh(e.max_tokens),l=[`Earlier messages not replayed: ${t.toLocaleString("en-US")}${i?` (~${i.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 $x(e){const t=FN(e.history);return t?s.jsx(vg,{message:{role:"system",level:"info",title:"History",content:t}}):null}const zN=1500,BN=12e4;function UN(e,t){return new Promise((n,i)=>{const o=setTimeout(n,e);t.addEventListener("abort",()=>{clearTimeout(o),i(new DOMException("aborted","AbortError"))},{once:!0})})}const WN=["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) ===",PN,"=== END DOCUMENTATION ==="].join(`
|
|
69
|
+
`),qN="observer-docs-assistant";function zy(){return`${qN}:${zs()}`}function HN(e){return{prompt:e,system:WN,tools:[],use_session_history:!0,use_context:!0}}function VN(e){var t,n;for(let i=e.length-1;i>=0;i--){const o=e[i],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 GN(e,t,n=()=>{}){return async(i,o)=>{var f;const l=e(),u=await l.start_run(null,HN(i),{bundle_id:"basic-agent",session_id:t()}),c=Date.now();for(;;){if(await UN(zN,o.signal),Date.now()-c>BN)throw new Error("The assistant run timed out (120s). The run is still visible on the Observe page.");const _=await l.get_run(u),p=String((_==null?void 0:_.status)||"").trim().toLowerCase();if(p==="failed"||p==="cancelled"){const y=String(((f=_==null?void 0:_.error)==null?void 0:f.message)||(_==null?void 0:_.error)||"run "+p).slice(0,400);throw new Error(`The assistant run ${p}: ${y}`)}if(p==="completed"){n((_==null?void 0:_.session_history)??null);const y=await l.get_ledger(u,{after:0,limit:500,signal:o.signal});return VN(y.items)||"(the run completed but produced no readable answer — inspect it on the Observe page)"}}}}function KN(e){const t=m.useRef(e.gateway);t.current=e.gateway;const n=m.useRef(zy()),[i,o]=m.useState([]),[l,u]=m.useState(null),c=m.useMemo(()=>GN(()=>t.current,()=>n.current,u),[]),[f]=m.useState(void 0),_=()=>{n.current=zy(),o([]),u(null)};return s.jsxs(oS,{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:!i.length,onClick:_,title:"Start a new conversation (nothing earlier is replayed)",children:"New conversation"}),children:[s.jsx($x,{history:l}),s.jsx(Bk,{ask:c,messages:i,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."})})]})}const YN="api/local/reveal",JN="sw.js";function XN(e){const t=l=>/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(l),n=l=>{const u=l.split("/").filter(Boolean);return u.length?u[u.length-1].trim():""},i=n(String(e.hash||"").replace(/^#/,""));if(t(i))return i;const o=n(String(e.pathname||""));return t(o)?o:""}const bm="@default:",jm="abstractcode.agent.v1";function ZN(e){const t=String(e||"").trim();if(t.startsWith(bm)){const i=t.slice(bm.length).trim();return i?{kind:"default",interface:i}:null}const n=t.indexOf(":");return n<=0||n>=t.length-1?null:{kind:"bundle",bundle_id:t.slice(0,n),flow_id:t.slice(n+1)}}function QN(e){return e?e.kind==="default"?`${bm}${e.interface}`:`${e.bundle_id}:${e.flow_id}`:""}function e1(e){const t={};for(const i of e)for(const o of i.agent_default_interfaces||[])o&&!t[o]&&(t[o]=i.label);return[jm,...Object.keys(t).filter(i=>i!==jm).sort()].map(i=>({interface:i,value:`${bm}${i}`,label:`Gateway default agent · ${i}${t[i]?` (now: ${t[i]})`:""}`}))}function t1(e,t,n){if(!e)return null;if(e.kind==="default")return{flow_id:"@default",interface:e.interface,input_data:n};const i=String(t(e.bundle_id)||"").trim();if(!i)throw new Error(`The gateway listed no bundle_ref for bundle "${e.bundle_id}". Reload bundles, then try again.`);return{bundle_ref:i,flow_id:e.flow_id,input_data:n}}function n1(e){const t={};for(const[n,i]of Object.entries(e||{}))if(typeof i=="string"){const o=i.trim();o&&(t[n]=o)}else i!==void 0&&(t[n]=i);return t}const s1={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 r1(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 i1="#launch/automate";function o1(e){const t=String(e||"").replace(/^#\/?/,"");if(t==="automations")return{page:"automations"};const n=/^launch(?:\/(once|automate))?$/.exec(t);return n?{page:"launch",mode:n[1]||"once"}:null}const Fp={when:"every",email:rx,notify_email:!1,email_recipients:yg,amount:"24",unit:"h",once_at:"",context:"independent",tool_approval:"auto",title:"",start_at:"",count:"",until:""},By={independent:"Each run starts fresh in its own session. Runs never see each other.",growing:"Each run is a new turn of one conversation and sees the previous runs. The history is bounded: the most recent 50,000 tokens of whole turns are replayed; older runs drop out."},Ax=["use_context"],a1="This choice also sets the workflow's Use Context input: the workflow always reads the history the automation gives it.";function zp(e,t,n=!1){const i=e.when==="every";return{prompt:t,when:e.when==="once"?{kind:"once",at:e.once_at}:{kind:"every",amount:Number(e.amount),unit:e.unit},...n&&e.when==="email"?{trigger:"email",email:e.email}:{},...n&&e.notify_email?{notifyEmail:!0}:{},...n&&e.email_recipients.mode==="list"?{emailRecipients:e.email_recipients}:{},context:e.context,toolApproval:e.tool_approval,title:e.title,...i&&e.start_at?{startAt:e.start_at}:{},...i&&e.count.trim()?{count:Number(e.count)}:{},...i&&e.until?{until:e.until}:{}}}function l1(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:[qt.not_set_up]};const n=n1(t.input_data),i=typeof n.prompt=="string"?n.prompt:"";delete n.prompt;for(const l of Ax)delete n[l];let o;try{o=t1(t.choice,t.bundle_ref_for,n)}catch(l){return{ok:!1,errors:[String((l==null?void 0:l.message)||l)]}}return Mp(zp(e,i,t.email_usable===!0),{target:o,requestId:t.request_id})}function c1(e,t=!1){if(e.when==="email"){if(!t)return"";const l=Mp(zp(e,"preview",!0),{target:{flow_id:"@default",interface:jm},requestId:"preview"});return l.ok?`Runs ${ox(l.body.trigger.config)}.`:""}const n=Mp(zp(e,"preview"),{target:{flow_id:"@default",interface:jm},requestId:"preview"});if(!n.ok)return"";const i=n.body.trigger.config,o=Zv(i);return e.when==="once"?`Runs ${o}.`:`Runs ${o}, first run ${i.start_at?`at ${Na(i.start_at)}`:"now"}.`}class u1{constructor(t){Gs(this,"key","");Gs(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 d1(e,t,n){const i=l1(e,{...t,request_id:""});if(!i.ok)return i;const{request_id:o,...l}=i.body,u=n.id_for(JSON.stringify(l));return{ok:!0,body:{...i.body,request_id:u}}}function xa(e){return typeof e=="string"?e:e??null}function f1(e){var t,n,i,o,l,u;return{run_id:String((e==null?void 0:e.run_id)||"").trim(),workflow_id:xa(e==null?void 0:e.workflow_id),status:typeof(e==null?void 0:e.status)=="string"?String(e.status):"",created_at:xa(e==null?void 0:e.created_at),updated_at:xa(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:xa(e==null?void 0:e.parent_run_id),session_id:xa(e==null?void 0:e.session_id),actor_id:xa(e==null?void 0:e.actor_id),session_kind:xa(e==null?void 0:e.session_kind),automation_id:xa(e==null?void 0:e.automation_id),role:xa(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((i=e==null?void 0:e.schedule)==null?void 0:i.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 xf(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 Tx(e){const t=xf(e);return t==="occurrence"?typeof e.occurrence_index=="number"?`occurrence #${e.occurrence_index}`:"occurrence":t==="legacy"?"legacy schedule":t||""}function Uy(e){return String((e==null?void 0:e.role)||"").trim()==="controller"}function h1(e){var n,i,o;const t=(o=(i=(n=e==null?void 0:e.capabilities)==null?void 0:n.contracts)==null?void 0:i.common)==null?void 0:o.automations;return t&&typeof t=="object"&&t.available===!0?{available:!0,reason:""}:t&&typeof t=="object"&&t.available===!1?{available:!1,reason:"This gateway has the Automations API turned off."}:{available:!1,reason:"This gateway does not advertise the Automations API (capabilities.contracts.common.automations). Update AbstractGateway to use automations; legacy schedules stay manageable from their run view."}}function nc(e){return e.legacy===!0||e.capabilities.includes("legacy")}function Mx(e,t=Date.now()){const n=nc(e),i=e.last_occurrence,o=i&&i.attempts>1?` after ${i.attempts} attempts`:"",l=e.attention.unread||e.attention.pending_waits>0;return{id:e.automation_id,title:e.title,cadence:_g(e.trigger),next_run:e.next_fire_at?`${Na(e.next_fire_at)} (${ux(e.next_fire_at,t)})`:e.status==="paused"?"none while paused":"none scheduled",current:cx(e),state:e.status,last:i?i.excerpt:"",last_status:i?`#${i.index} ${i.status}${o}`:"no runs yet",attention:l?dx(e):null,legacy:n}}function Rx(e){const t=e.last_occurrence;if(!t)return null;const i=["completed","failed","cancelled"].includes(String(t.status))?t.index:t.index-1;return i>=1?i:null}function m1(e,t){const n=wm(e,[],t),i=Rx(e),o=t?{enabled:!1,reason:"Working…"}:nc(e)?{enabled:!1,reason:"Legacy schedule: managed with its existing controls."}:e.capabilities.includes("discuss")?i===null?{enabled:!1,reason:e.last_occurrence?"Available once the first run finishes.":"No occurrence to discuss yet."}:{enabled:!0,reason:`Discuss run #${i} in a new chat (a fork of this automation).`}:{enabled:!1,reason:"Not permitted for this automation."};return{pause:n.pause,resume:n.resume,run_now:n.run_now,edit:n.revise,archive:n.archive,discuss:o}}function _1(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 i=e.status==="paused",o=e.status==="active"||e.status==="paused";return{legacy_pause:i?n("Already suspended."):o?{enabled:!0}:n("The schedule has ended."),legacy_resume:i?{enabled:!0}:n(o?"Already running on schedule.":"The schedule has ended."),legacy_run_now:e.status==="active"?{enabled:!0}:n(i?"Resume the schedule first.":"The schedule has ended."),open_run:{enabled:!0},recreate:{enabled:!0}}}function p1(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 g1=/^([1-9][0-9]*)([smhd])$/;function y1(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 w1(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 i=String(n.target_bundle_ref||"").trim(),o=String(n.target_host_bundle_id||n.target_bundle_id||(i.includes("@")?i.slice(0,i.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={...Fp},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=g1.exec(f);let x=w?Number(w[1]):0,S=w?w[2]:"";S==="s"&&x%60===0&&(x=x/60,S="m"),S==="m"||S==="h"||S==="d"?(c.amount=String(x),c.unit=S):u.push(`The legacy interval "${f}" is not a whole number of minutes, hours or days; choose an interval.`)}typeof n.repeat_count=="number"&&n.repeat_count>=1&&(c.count=String(n.repeat_count));const _=y1(n.repeat_until);_&&(c.until=_),c.context=n.share_context===!1?"independent":"growing";const p=t&&typeof t.input_data=="object"&&t.input_data&&!Array.isArray(t.input_data)?t.input_data:{},y={};for(const[w,x]of Object.entries(p))w==="workflow_selection"||w.startsWith("_")||(y[w]=x);return{choice:{kind:"bundle",bundle_id:o,flow_id:l},input_data:y,form:c,notes:u}}const v1={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 x1(e,t,n){return{answer_wait:async(i,o,l)=>{await e.submit_command({command_id:t(),run_id:i,type:"resume",payload:{wait_key:o,payload:l},client_id:"web_pwa"})},legacy_command:async(i,o,l)=>{await e.submit_command({command_id:t(),run_id:i,type:o,payload:l,client_id:"web_pwa"})},now_iso:n}}function b1(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(i=>typeof i=="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 Wy(e){return e.show_archived||e.status_filter==="archived"?e.items:e.items.filter(t=>t.status!=="archived")}function qy(e){return e.items.filter(t=>t.status==="archived").length}function Sg(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 j1=3e4,Hh=50;function eo(e){return wg(e)?e:{status:0,code:"client_error",message:e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}}function W_(e,t){const n=new Map;for(const i of e)n.set(i.run_id,i);for(const i of t)n.set(i.run_id,i);return Array.from(n.values()).sort((i,o)=>o.index-i.index)}class S1{constructor(t,n,i=[1500,4e3]){Gs(this,"state",{...v1});Gs(this,"listeners",new Set);Gs(this,"list_seq",0);Gs(this,"detail_seq",0);Gs(this,"sources_loaded",!1);this.client=t,this.host=n,this.followups_ms=i}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 i=0;i<200;i+=1){const o=await this.client.listAutomations({...this.state.status_filter?{status:this.state.status_filter}:{},...n?{cursor:n}:{},limit:Hh});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 qm(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 i=this.state.detail,o=i?n.find(l=>l.automation_id===i.automation_id):void 0;this.set({items:n,loaded:!0,loading:!1,list_error:null,refreshed_at:Date.now(),...i&&o?{detail:{...i,summary:o}}:{}}),i&&await this.reload_occurrences(i.automation_id)}catch(n){if(t!==this.list_seq)return;this.set({loading:!1,loaded:!0,list_error:eo(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(),i=++this.detail_seq;if(!n){this.set({selected_id:"",detail:null});return}this.set({selected_id:n,notice:"",...((o=this.state.detail)==null?void 0:o.automation_id)!==n?{detail:null}:{}});try{const l=this.state.items.find(f=>f.automation_id===n);if(l&&nc(l)){this.set({detail:{automation_id:n,summary:l,definition:null,occurrences:[],next_cursor:null,error:null}});return}const[u,c]=await Promise.all([this.client.getAutomation(n),this.client.listOccurrences(n,{limit:Hh})]);if(i!==this.detail_seq)return;this.set({detail:{automation_id:n,summary:l??u.summary,definition:u.definition,occurrences:W_([],c.items),next_cursor:c.next_cursor,error:null}}),await this.load_trigger_sources()}catch(l){if(i!==this.detail_seq)return;this.set({error:eo(l)})}}async reload_occurrences(t){const n=this.state.detail;if(!n||n.automation_id!==t||nc(n.summary))return;const[i,o]=await Promise.all([this.client.getAutomation(t),this.client.listOccurrences(t,{limit:Hh})]),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??i.summary,definition:i.definition,occurrences:W_(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:Hh}),i=this.state.detail;if(!i||i.automation_id!==t.automation_id)return;this.set({detail:{...i,occurrences:W_(i.occurrences,n.items),next_cursor:n.next_cursor}})}catch(n){this.set({error:eo(n)})}}async after_change(t){await this.refresh();for(const n of this.followups_ms)setTimeout(()=>void this.refresh(),n)}async command(t,n,i,o){this.set({busy:!0});try{const l=await this.client.sendAutomationCommand(t,{type:n,...i?{payload:i}:{},...o?{command_id:o}:{}});return await this.after_change(t),l}catch(l){throw eo(l)}finally{this.set({busy:!1})}}async revise(t,n,i,o){this.set({busy:!0});try{const l=await this.client.reviseAutomation(t,{changes:n,...i!==null?{expected_revision:i}:{},...o?{command_id:o}:{}});return await this.after_change(t),l}catch(l){throw eo(l)}finally{this.set({busy:!1})}}async discuss(t,n,i,o){this.set({busy:!0});try{const l=await this.client.discuss(t,{occurrence_index:n,prompt:i,...o?{request_id:o}:{}});return this.set({notice:Sg(n,l)}),l}catch(l){throw eo(l)}finally{this.set({busy:!1})}}async seen(t,n){try{await this.client.markSeen(t,n)}catch(i){throw eo(i)}}async answer_wait(t,n,i,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===i);if(!u)throw new Error(`No loaded wait ${i} on run ${n}; reload the automation.`);await this.host.answer_wait(n,i,b1(u.kind,o)),await this.after_change(t)}catch(u){throw eo(u)}finally{this.set({busy:!1})}}async row_action(t,n){const i=`automation.${n}`;this.set({error:null,notice:""});try{await this.command(t.automation_id,i),this.set({notice:n==="run_now"&&t.status==="paused"?`Run now sent to “${t.title}”; it stays paused.`:`${k1[n]} sent to “${t.title}”.`,confirm_archive_id:""})}catch(o){this.set({error:eo(o)})}}set_show_archived(t){this.set({show_archived:t})}ask_archive(t){this.set({confirm_archive_id:t})}async legacy_action(t,n){if(!nc(t))throw new Error("legacy_action on a non-legacy automation");const i=p1(n,this.host.now_iso());this.set({busy:!0,error:null,notice:""});try{await this.host.legacy_command(t.automation_id,i.type,i.payload),this.set({notice:`${i.type==="pause"?"Suspend":n==="legacy_run_now"?"Run now":"Resume"} sent to “${t.title}”.`}),await this.refresh()}catch(o){this.set({error:eo(o)})}finally{this.set({busy:!1})}}report_error(t){this.set({error:eo(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})}}const k1={pause:"Pause",resume:"Resume",run_now:"Run now",archive:"Archive"};function N1(e){const t=(n,i,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:i});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:s1[e.mode]})]})}function C1(e){const t=e.form,n=qm(e.email_status),i=t.when==="email"&&!n?"every":t.when,o=c1(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:i==="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:i==="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:i==="email",disabled:e.disabled||!n,onChange:()=>e.on_change({when:"email"})})," ",qt.trigger_label]})]}),n?null:s.jsx(Rp,{status:e.email_status,onOpenMyEmail:e.on_open_my_email}),i==="email"?s.jsx(uk,{value:t.email,onChange:l=>e.on_change({email:l}),disabled:e.disabled,idBase:"automate"}):i==="every"?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"automate_row",role:"group","aria-label":"Presets",children:ek.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||(i==="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) — ",By.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"})," — ",By.growing]}),s.jsx("p",{className:"help_text muted","data-context-owns":"use_context",children:a1})]}),s.jsxs("fieldset",{"data-section":"tools",children:[s.jsx("legend",{children:"Tools"}),i==="email"?s.jsx("p",{className:"help_text muted","data-email-rule":"untrusted",children:qt.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"})})," ",sk,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(Rp,{status:e.email_status,onOpenMyEmail:e.on_open_my_email}),s.jsx(dk,{notifyEmail:n&&t.notify_email,onNotifyEmailChange:l=>e.on_change({notify_email:l}),recipients:n?t.email_recipients:yg,onRecipientsChange:l=>e.on_change({email_recipients:l}),disabled:e.disabled||!n,idBase:"automate"})]})]})}function E1(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 $1="abstractobserver";function A1(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,i)=>e.get_ledger(t,{after:n,limit:200,signal:i}),streamLedger:(t,n,i,o,l)=>e.stream_ledger(t,{after:n,on_step:i,signal:o,on_open:l}),submitCommand:t=>e.submit_command(t)}}function T1(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 M1=new Set(["completed","failed","cancelled"]);function R1(e){var O;const{gateway:t,discussion:n}=e,i=m.useMemo(()=>A1(t),[t]),[o,l]=m.useState(((O=n.session)==null?void 0:O.run_id)||""),[u,c]=m.useState(""),[f,_]=m.useState(!1),[p,y]=m.useState(""),{controller:w,snapshot:x}=fN({transport:i,runId:o,enabled:e.connected,clientId:$1}),S=n.session,j=!!o&&!M1.has(x.status)&&x.status!=="idle",E=lN(x),A=async M=>{var X;const H=M.trim();if(H){_(!0);try{if(S){const Y=String(((X=x.run)==null?void 0:X.workflow_id)||""),Z=T1(Y),re=await t.start_run(Z.flow_id,{prompt:H},{bundle_id:Z.bundle_id,session_id:S.session_id});l(re)}else{const Y=await e.on_fork(n.automation_id,n.occurrence_index,H);l(Y.run_id)}c("")}finally{_(!1)}}},L=s.jsxs("div",{className:"discussion_head",children:[s.jsxs("button",{type:"button",className:"btn btn_sm","data-action":"discussion-back",onClick:e.on_close,title:`Back to ${n.automation_title}`,children:[s.jsx(Qe,{name:"chevronRight",size:13,className:"flip_x"})," ",n.automation_title]}),s.jsxs("span",{className:"discussion_title",children:[s.jsx(Qe,{name:"chat",size:15})," Discussion — fork at #",n.occurrence_index]}),s.jsx("span",{className:"pane_spacer"}),S?s.jsxs(s.Fragment,{children:[s.jsxs("button",{type:"button",className:`btn btn_sm${p==="own"?" active":""}`,"data-action":"discussion-files",onClick:()=>y(p==="own"?"":"own"),title:S.workspace_root,children:[s.jsx(Qe,{name:"folder",size:14})," Its files"]}),s.jsxs("button",{type:"button",className:`btn btn_sm${p==="mounted"?" active":""}`,"data-action":"automation-files",onClick:()=>y(p==="mounted"?"":"mounted"),title:S.mounted_workspace,children:[s.jsx(Qe,{name:"folder",size:14})," Automation files"]})]}):null]});return s.jsxs("section",{className:"pane auto_detail auto_discussion","data-discussion-session":(S==null?void 0:S.session_id)||void 0,children:[p&&S?s.jsx(Cx,{fetchGateway:t.fetch_gateway,runId:p==="own"?S.run_id:n.automation_id,title:p==="own"?"Discussion files":"Automation files",note:p==="own"?"The discussion's own writable folder.":"Mounted read-only for the discussion's file tools; nothing is written back.",onClose:()=>y(""),refreshKey:x.status}):null,s.jsx(tN,{header:L,messages:x.messages,draft:u,onDraftChange:c,onSend:A,busy:j||f,busyLabel:f?S?"Starting…":"Forking the automation…":E?"Waiting for you":"Working…",onCancel:j?()=>w.cancel():void 0,stopState:x.stop??null,disabled:!e.connected,interaction:ON(E,w,{records:x.records,currentRun:x.run}),placeholder:S?"Ask a follow-up…":`Ask about run #${n.occurrence_index}…`,emptyState:s.jsxs("div",{className:"help_text muted discussion_intro",children:["A new session that forks this automation at #",n.occurrence_index," with its history (runs 1–",n.occurrence_index,"). It works in its own writable workspace; the automation's files are mounted read-only for the file tools (shell commands are not sandboxed), and nothing is written back into the automation."]}),footer:x.error?s.jsx("div",{className:"observe_context_card error",role:"alert",children:x.error}):null})]})}const L1=5e3,I1=[["","All"],["active","Active"],["paused","Paused"],["completed","Completed"],["failed","Failed"],["archived","Archived"]],O1={pause:cl.pause,resume:cl.resume,run_now:cl.run_now,edit:cl.revise,archive:`${cl.archive}…`,discuss:cl.discuss},P1={pause:so.pause,resume:so.resume,run_now:so.run_now,edit:so.revise,archive:so.archive,discuss:so.discuss},D1={pause:"pause",resume:"resume",run_now:"run_now",edit:"revise",archive:"archive",discuss:"discuss"},F1={legacy_pause:so.pause,legacy_resume:so.resume,legacy_run_now:so.run_now,open_run:"list",recreate:"refresh"};function z1(e){return s.jsx("span",{className:"auto_state","data-field":"state",children:s.jsx(mx,{status:e.status})})}function Vh(e){return s.jsxs("span",{className:`auto_fact${e.className?` ${e.className}`:""}`,"data-field":e.field,title:e.label,children:[s.jsx(Qe,{name:e.icon,size:12}),s.jsx("span",{children:e.children})]})}const B1={legacy_pause:"Suspend",legacy_resume:"Resume",legacy_run_now:"Run now",open_run:"Open run",recreate:"Recreate as automation"};function U1(e){const t=e.summary,n=Mx(t),i=e.state.selected_id===t.automation_id,o=e.state.busy,l=(f,_,p,y,w,x,S,j)=>s.jsxs("button",{type:"button",className:`btn btn_sm auto_action${S?" auto_action_icon":""}${w?` ${w}`:""}`,"data-action":f,disabled:!p.enabled,title:[S?_:null,p.enabled?null:p.reason,j].filter(Boolean).join(`
|
|
70
|
+
`)||void 0,"aria-label":S?_:void 0,"aria-description":j,onClick:y,children:[x?s.jsx(Qe,{name:x,size:13}):null,S?null:s.jsx("span",{children:_})]},f);let u;if(n.legacy){const f=_1(t,o);u=[t.status==="paused"?"legacy_resume":"legacy_pause","legacy_run_now","open_run","recreate"].map(p=>l(p,B1[p],f[p],()=>e.h.on_legacy_action(t,p),void 0,F1[p]))}else{const f=m1(t,o);u=[t.status==="paused"?"resume":"pause","run_now","edit","discuss","archive"].map(p=>l(p,O1[p],f[p],()=>e.h.on_row_action(t,p),p==="archive"?"danger auto_action_end":void 0,P1[p],p==="archive",_x(D1[p],t)))}const c=e.state.confirm_archive_id===t.automation_id;return s.jsxs("li",{className:`auto_row${i?" 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":i?"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(z1,{status:n.state}),n.attention?s.jsxs("span",{className:"chip warn auto_row_attention","data-field":"attention",children:[s.jsx(Qe,{name:"warning",size:12})," ",n.attention]}):null]}),s.jsxs("span",{className:"auto_row_facts",children:[s.jsx(Vh,{icon:"refresh",field:"cadence",label:"When it runs",children:n.cadence}),n.current?s.jsx(Vh,{icon:"loader",field:"current",label:"Running now",className:"auto_row_current",children:n.current}):null,s.jsxs(Vh,{icon:"clock",field:"next",label:"Next run",children:["next: ",n.next_run]}),s.jsx(Vh,{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:Ex(n.last)}):null]}),s.jsx("div",{className:"auto_row_actions",role:"toolbar","aria-label":`Controls for ${n.title}`,children:u}),c?s.jsxs("div",{className:"auto_row_confirm",role:"group","aria-label":"Confirm archive",children:[s.jsxs("span",{children:["Archive “",n.title,"”? Its history stays readable; it will not run again."]}),s.jsxs("button",{type:"button",className:"btn btn_sm danger auto_action","data-action":"archive-confirm",disabled:o,onClick:()=>e.h.on_confirm_archive(t),children:[s.jsx(Qe,{name:"archive",size:13}),s.jsx("span",{children:"Archive"})]}),s.jsxs("button",{type:"button",className:"btn btn_sm auto_action","data-action":"archive-cancel",onClick:e.h.on_cancel_archive,children:[s.jsx(Qe,{name:"x",size:13}),s.jsx("span",{children:"Keep it"})]})]}):null]})}function W1(e){const t=e.state,n=t.error??t.list_error,i=n?vm(n):null;return s.jsxs("section",{className:"pane auto_list","aria-label":"Automations",children:[s.jsxs("div",{className:"pane_header",children:[s.jsx("span",{className:"pane_title",children:"Automations"}),s.jsx("span",{className:"pane_count",children:Wy(t).length}),s.jsx("span",{className:"pane_spacer"}),s.jsx("select",{className:"seg_select",value:t.status_filter,onChange:o=>e.h.on_status_filter(o.target.value),"aria-label":"Filter by status",children:I1.map(([o,l])=>s.jsx("option",{value:o,children:l},o||"all"))}),s.jsx("button",{type:"button",className:"btn btn_sm auto_icon_btn","data-action":"refresh",onClick:e.h.on_refresh,disabled:t.loading||!e.available.available,title:"Refresh","aria-label":"Refresh",children:s.jsx(Qe,{name:t.loading?"loader":"refresh",size:14})}),s.jsxs("a",{className:`btn btn_sm auto_new${e.available.available?"":" disabled"}`,"data-action":"new",href:i1,"aria-disabled":!e.available.available,title:"New automation: opens Launch in Automate mode","aria-label":"New automation",onClick:o=>{o.preventDefault(),e.available.available&&e.h.on_new()},children:[s.jsx(Qe,{name:"plus",size:14}),s.jsx("span",{className:"auto_new_label",children:"New automation"})]})]}),s.jsxs("div",{className:"pane_body scroll",children:[e.available.available?null:s.jsx("div",{className:"warn_callout",role:"note","data-unavailable":"true",children:e.available.reason}),i?s.jsxs("div",{className:"observe_context_card error auto_list_error",role:"alert","data-code":n==null?void 0:n.code,children:[s.jsx(Qe,{name:"error",size:14}),s.jsxs("span",{className:"auto_list_msg",children:[s.jsx("strong",{children:i.title})," ",s.jsx("span",{children:i.detail})]}),t.error&&e.h.on_dismiss_error?s.jsx("button",{type:"button",className:"auto_dismiss","data-action":"dismiss-error","aria-label":"Dismiss",title:"Dismiss",onClick:e.h.on_dismiss_error,children:s.jsx(Qe,{name:"x",size:12})}):null]}):null,s.jsx("div",{className:`auto_notice${t.notice?" on":""}`,role:"status",children:t.notice?s.jsxs(s.Fragment,{children:[s.jsx(Qe,{name:"check",size:13}),s.jsx("span",{className:"auto_list_msg",children:t.notice}),e.h.on_dismiss_notice?s.jsx("button",{type:"button",className:"auto_dismiss","data-action":"dismiss-notice","aria-label":"Dismiss",title:"Dismiss",onClick:e.h.on_dismiss_notice,children:s.jsx(Qe,{name:"x",size:12})}):null]}):null}),e.available.available&&t.loaded&&!t.items.length?s.jsx("div",{className:"help_text muted",children:"No automations yet. Create one from Launch → Automate."}):null,qy(t)>0&&t.status_filter!=="archived"?s.jsxs("label",{className:"auto_show_archived help_text muted",children:[s.jsx("input",{type:"checkbox","data-action":"show-archived",checked:t.show_archived,onChange:o=>e.h.on_show_archived(o.target.checked)})," Show archived (",qy(t),")"]}):null,s.jsx("ul",{className:"auto_rows",children:Wy(t).map(o=>s.jsx(U1,{summary:o,state:t,h:e.h},o.automation_id))})]})]})}function q1(e,t,n){const i=e.state,o=i.detail;if(!o||nc(o.summary))return null;const l=o.automation_id;return{summary:o.summary,...o.definition?{definition:o.definition}:{},occurrences:o.occurrences,triggerSources:i.trigger_sources,busy:i.busy,...o.error?{error:o.error}:{},onRevise:(u,c,f)=>e.revise(l,u,c,f==null?void 0:f.command_id),onCommand:(u,c,f)=>e.command(l,u,c,f==null?void 0:f.command_id),onDiscuss:async(u,c,f)=>{const _=await e.discuss(l,u,c,f==null?void 0:f.request_id);return t.on_open_session(_,Sg(u,_),u),_},onSeen:u=>e.seen(l,u),onLoadMore:()=>void e.load_more(),onOpenRun:u=>t.on_open_run(u),...t.on_open_workspace?{onOpenWorkspace:t.on_open_workspace}:{},...t.fetch_gateway?{fetchGateway:t.fetch_gateway}:{},onAnswerWait:(u,c,f)=>e.answer_wait(l,u,c,f),...n?{editOpen:n.open,onEditOpenChange:n.on_change}:{},emailStatus:i.email_status,...t.on_open_my_email?{onOpenMyEmail:()=>{var u;return(u=t.on_open_my_email)==null?void 0:u.call(t)}}:{}}}function H1(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 (",Lp.toLowerCase(),")."]})});if(nc(t.summary)){const i=Mx(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:i.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 (",i.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=q1(e.ctl,e.host,e.edit);return s.jsxs("section",{className:"pane auto_detail",children:[e.browser??null,n?s.jsx(IN,{...n}):null]})}function V1(e,t){if(t==="edit")return{kind:"edit"};if(t!=="discuss")return{kind:"forward"};const n=Rx(e);return n===null?{kind:"none"}:{kind:"discuss",index:n}}function G1(e){const t=e.ctl,[n,i]=m.useState(null),o=j=>i(E=>({...j,opened:((E==null?void 0:E.opened)||0)+1})),[l,u]=m.useState(""),[c,f]=m.useState("");m.useSyncExternalStore(j=>t.subscribe(j),()=>t.state,()=>t.state);const[_,p]=m.useState(()=>typeof document>"u"||document.visibilityState!=="hidden");m.useEffect(()=>{const j=()=>p(document.visibilityState!=="hidden");return document.addEventListener("visibilitychange",j),()=>document.removeEventListener("visibilitychange",j)},[]),m.useEffect(()=>{if(!e.active||!_||!e.available.available)return;t.refresh();const j=window.setInterval(()=>void t.refresh(),j1);return()=>window.clearInterval(j)},[t,e.active,_,e.available.available]);const y=t.state.detail,w=t.state.notice;m.useEffect(()=>{if(!w)return;const j=window.setTimeout(()=>t.dismiss_notice(),L1);return()=>window.clearTimeout(j)},[t,w]);const x={...e.host,on_open_workspace:j=>u(E=>E===j?"":j),fetch_gateway:e.gateway.fetch_gateway,on_open_session:(j,E,A)=>{e.host.on_open_session(j,E,A),y&&o({automation_id:y.automation_id,automation_title:y.summary.title,occurrence_index:A,session:j})}},S={...e.h,on_select:j=>{i(null),u(""),j!==c&&f(""),e.h.on_select(j)},on_dismiss_notice:()=>t.dismiss_notice(),on_dismiss_error:()=>t.dismiss_error(),on_row_action:(j,E)=>{const A=V1(j,E);A.kind==="forward"?e.h.on_row_action(j,E):A.kind==="edit"?(i(null),u(""),f(j.automation_id),e.h.on_select(j.automation_id)):A.kind==="discuss"&&(e.h.on_select(j.automation_id),o({automation_id:j.automation_id,automation_title:j.title,occurrence_index:A.index}))}};return s.jsxs("div",{className:"page auto_page",children:[s.jsx(W1,{state:t.state,available:e.available,h:S}),n?s.jsx(R1,{gateway:e.gateway,discussion:n,connected:e.active,on_fork:async(j,E,A)=>{const L=await t.discuss(j,E,A);return e.host.on_open_session(L,Sg(E,L),E),i(O=>O&&{...O,session:L}),L},on_close:()=>i(null)},n.opened):s.jsx(H1,{ctl:t,host:x,h:S,edit:{open:!!y&&c===y.automation_id,on_change:j=>f(j&&y?y.automation_id:"")},browser:l?s.jsx(Cx,{fetchGateway:e.gateway.fetch_gateway,runId:l,title:l===(y==null?void 0:y.automation_id)?"Automation files":"Run files",onClose:()=>u("")}):void 0})]})}function K1(){const e="0.3.0".trim();if(!e)throw new Error("AbstractObserver: __APP_VERSION__ is not defined; the vite/vitest config must inject it from package.json");return e}function Y1(){return dS("abstractobserver",K1())}async function J1(e){let t;try{t=await e.gateway_about()}catch(n){return jy(null,n instanceof Error?n.message||n.name:String(n))}return jy(t)}class Sm{constructor(t){this._maxSize=Sm._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=Sm._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),i=Number.isFinite(n)?n:null;this._values.push(i),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 X1(e){try{return new URL(String(e)),!0}catch{return!1}}function Z1({baseUrl:e,endpoint:t}){const n=String(t||"api/gateway/host/metrics/gpu");return X1(n)?n:e&&String(e).trim()?new URL(n,String(e)).toString():n}async function Q1({token:e,getToken:t}){if(typeof t=="function"){const n=await t();return n==null?"":String(n)}return e==null?"":String(e)}function eC({token:e}){const t=String(e||"").trim();return t?{Authorization:`Bearer ${t}`}:{}}function tC(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 i=n.map(l=>Number(l&&l.utilization_gpu_pct)).filter(l=>Number.isFinite(l));return i.length?i.reduce((l,u)=>l+u,0)/i.length:null}return null}async function nC({baseUrl:e,endpoint:t,token:n,getToken:i,signal:o,fetchImpl:l}={}){const u=Z1({baseUrl:e,endpoint:t}),c=await Q1({token:n,getToken:i}),f=l||globalThis.fetch;if(typeof f!="function")return{ok:!1,status:0,error:"fetch_unavailable",payload:null};let _;try{_=await f(u,{method:"GET",headers:{Accept:"application/json",...eC({token:c})},signal:o})}catch(y){return{ok:!1,status:0,error:"network_error",detail:y instanceof Error?y.message:String(y),payload:null}}let p=null;try{p=await _.json()}catch{p=null}return{ok:_.ok,status:_.status,error:_.ok?null:"http_error",payload:p}}const sf=Object.freeze({tickMs:1500,historySize:20,endpoint:"api/gateway/host/metrics/gpu",baseUrl:"",mode:"full"});function sC(e){return Number.isFinite(e)?Math.min(1,Math.max(0,e)):0}function Hy(e,t,n){return Number.isFinite(e)?Math.min(n,Math.max(t,e)):t}function Vy(e,t){const n=Number(e);return Number.isFinite(n)?Math.floor(n):t}function q_(e,t=1){const n=Hy(Number(e)/100,0,1),i=Math.round(140-140*n),o=Hy(Number(t),0,1);return o>=1?`hsl(${i} 85% 55%)`:`hsl(${i} 85% 55% / ${o})`}function Gy(e){const t={...sf,...e||{}};return t.tickMs=Math.max(250,Vy(t.tickMs,sf.tickMs)),t.historySize=Math.max(1,Math.min(200,Vy(t.historySize,sf.historySize))),t.endpoint=String(t.endpoint||sf.endpoint),t.baseUrl=String(t.baseUrl||""),t.mode=String(t.mode||sf.mode).trim().toLowerCase(),t.mode!=="icon"&&(t.mode="full"),t}function rC(){return`
|
|
71
|
+
: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}
|
|
72
|
+
.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)}
|
|
73
|
+
.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))}
|
|
74
|
+
.wrap.icon .top{display:none}
|
|
75
|
+
.wrap.icon .bars{height:var(--monitor-gpu-bars-height,18px)}
|
|
76
|
+
.top{display:flex;align-items:baseline;justify-content:space-between;gap:10px}
|
|
77
|
+
.label{font-size:var(--monitor-gpu-font-size,var(--font-size-sm,12px));opacity:.9}
|
|
78
|
+
.value{font-variant-numeric:tabular-nums;font-size:var(--monitor-gpu-font-size,var(--font-size-sm,12px));opacity:.95}
|
|
79
|
+
.bars{display:flex;align-items:flex-end;gap:2px;height:var(--monitor-gpu-bars-height,34px);overflow:hidden}
|
|
80
|
+
.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}
|
|
81
|
+
.bar.missing{background:var(--monitor-gpu-bar-missing,#62708a);opacity:.35}
|
|
82
|
+
.bar.error{background:var(--monitor-gpu-bar-error,#ff6b6b);opacity:.7}
|
|
83
|
+
.muted{opacity:.6}
|
|
84
|
+
`}class iC{constructor(t,n={}){if(!t||typeof t!="object")throw new TypeError("target element is required");this._target=t,this._opts=Gy(n),this._buffer=new Sm(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=rC();const i=document.createElement("div");i.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",i.appendChild(o),i.appendChild(c),t.appendChild(n),t.appendChild(i),this._els={wrap:i,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=Gy({...this._opts,...t||{}}),i=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"),i&&(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 i=document.createElement("div");i.className="bar missing",i.style.height="2px",t.appendChild(i)}}_render({error:t=!1}={}){if(!this._els)return;const{wrap:n,value:i,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?(i.textContent=t?"N/A":"—",i.classList.add("muted")):(i.textContent=`${c.toFixed(0)}%`,i.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",q_(c,.95)),n.style.setProperty("--monitor-gpu-accent-glow",q_(c,.35))));const f=Array.from(o.children),_=Math.max(0,f.length-l.length),p=Math.max(2,o&&typeof o.clientHeight=="number"&&o.clientHeight>0?o.clientHeight:34);for(let y=0;y<f.length;y+=1){const w=f[y],x=y-_,S=x>=0?l[x]:null,j=Number.isFinite(S)?S:null,E=j==null?0:sC(j/100),A=Math.max(2,Math.min(p,Math.round(E*p)));w.style.height=`${A}px`,w.style.background=j==null?"":q_(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,i=!!t||typeof n=="function";this._abort&&this._abort.abort(),this._abort=new AbortController;const o=await nC({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=tC(l);if(!o.ok){if(this._buffer.push(null),this._render({error:!0}),o.status===401||o.status===403){const f=String(this._token||"").trim(),_=typeof this._getToken=="function";if(!i&&(!!f||_))return;this._stoppedForAuth=!0,this.stop()}else o.status===429&&(this.stop(),this._resumeTimer=setTimeout(()=>{this._resumeTimer=null,this._mounted&&this.start()},3e4));return}if(!u||c==null){this._buffer.push(null),this._render();return}this._buffer.push(c),this._render()}async _poll_loop(t){!this._running||t!==this._timer_gen||(await this._tick(),!(!this._running||t!==this._timer_gen)&&(this._timer=setTimeout(()=>{this._timer=null,this._poll_loop(t)},this._opts.tickMs)))}}function oC(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 iC(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 jt(){return new Date().toISOString()}function aC(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}function Bs(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 ht(e,t){const n=typeof(t==null?void 0:t.max_chars)=="number"?t.max_chars:360,i=typeof(t==null?void 0:t.max_lines)=="number"?t.max_lines:2,l=String(e||"").replace(/\r\n/g,`
|
|
85
|
+
`).replace(/\r/g,`
|
|
86
|
+
`).split(`
|
|
87
|
+
`),u=l.slice(0,Math.max(1,i)).join(`
|
|
88
|
+
`),c=l.length>i,f=u.length>n?`${u.slice(0,Math.max(0,n-1))}…`:u;return c&&f===u?`${u}…`:f}function Lt(e,t){const n=String(e||"");return n.length<=t?n:`${n.slice(0,Math.max(0,t-1))}…`}function H_(e){const t=String(e||"").trim();return t&&t.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")||"untitled"}function Cn(e){const t=typeof e=="string"?e.trim():"";if(!t)return null;const n=t.replace(/(\.\d{3})\d+/,"$1"),i=Date.parse(n);return Number.isFinite(i)?i:null}function lC(e){const t=Date.now()-e,n=Math.floor(t/1e3),i=Math.floor(n/60),o=Math.floor(i/60),l=Math.floor(o/24);return n<60?"just now":i<60?`${i}m ago`:o<24?`${o}h ago`:l<=3?`${l}d ago`:new Date(e).toLocaleDateString(void 0,{month:"short",day:"numeric"})}function Sa(e){const t=Cn(e);return t===null?"—":lC(t)}function Ky(e){if(!Number.isFinite(e))return"";const t=Math.floor(e/1e3);if(t<=0)return"now";const n=Math.floor(t/60),i=Math.floor(n/60),o=Math.floor(i/24),l=t%60,u=n%60,c=i%24;return o>0?`${o}d ${c}h`:i>0?`${i}h ${u}m`:n>0?`${n}m ${l}s`:`${t}s`}function kg(e){if(typeof e!="number"||!Number.isFinite(e)||e<0)return"—";const t=Math.floor(e/1e3),n=t%60,i=Math.floor(t/60),o=i%60,l=Math.floor(i/60),u=l%24,c=Math.floor(l/24);return c>0?`${c}d ${u}h`:l>0?`${l}h ${o}m`:i>0?`${i}m ${n}s`:`${Math.max(0,t)}s`}function Ca(e){const t=Cn(e);return t===null?"—":new Date(t).toLocaleString()}function hn(...e){for(const t of e){const n=String(t??"").trim();if(n)return n}return""}function cC(...e){for(const t of e){const n=Number(t);if(Number.isFinite(n))return n}return null}function Ci(e){const t=String(e||"").trim().toLowerCase();return t==="completed"||t==="failed"||t==="cancelled"}function Pu(e){const t=String(e||"").trim().toLowerCase();return t==="running"||t==="waiting"}function Jl(e){return String((e==null?void 0:e.started_at)||(e==null?void 0:e.created_at)||"").trim()}function Lx(e){const t=String((e==null?void 0:e.status)||"").trim();return Ci(t)?String((e==null?void 0:e.finished_at)||(e==null?void 0:e.updated_at)||"").trim():""}function Ng(e,t=Date.now()){const n=Cn(Jl(e));if(n===null)return-1;const i=Cn(Lx(e));return Math.max(0,(i!==null?i:t)-n)}function oc(e,t=Date.now()){return kg(Ng(e,t))}function uC(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 Du(e){return String(e||"").trim().toLowerCase()}function Gm(e){return`${(e==null?void 0:e.filename)||""} ${(e==null?void 0:e.source_path)||""}`.trim().toLowerCase()}function wf(e,t){return t.some(n=>e.endsWith(n))}function dC(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 fC(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 hC(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 Ix(e,t){var u,c,f,_,p;const n=Du(e==null?void 0:e.content_type),i=Gm(e),o=[e==null?void 0:e.semantic_kind,e==null?void 0:e.render_kind,e==null?void 0:e.task,(u=e==null?void 0:e.tags)==null?void 0:u.semantic_kind,(c=e==null?void 0:e.tags)==null?void 0:c.render_kind,(f=e==null?void 0:e.tags)==null?void 0:f.task,(_=e==null?void 0:e.tags)==null?void 0:_.kind,(p=e==null?void 0:e.tags)==null?void 0:p.type].map(y=>String(y||"").trim().toLowerCase()).filter(Boolean).join(" ");if(/(^|[^a-z0-9])(code|source_code|script|program|executable)([^a-z0-9]|$)/i.test(o)||n.includes("javascript")||n.includes("typescript")||n.includes("x-python")||n.includes("x-shellscript")||n.includes("x-rust")||n.includes("x-go")||n.includes("x-java")||n.includes("x-csrc")||n.includes("x-c++src")||wf(i,[".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,`
|
|
89
|
+
`).replace(/\r/g,`
|
|
90
|
+
`).split(`
|
|
91
|
+
`);return Ox(l)}function mC(e){const n=String(e||"").replace(/\r\n/g,`
|
|
92
|
+
`).replace(/\r/g,`
|
|
93
|
+
`).split(`
|
|
94
|
+
`),i=n.findIndex(u=>/^Markdown Content:\s*$/i.test(u.trim()));if(i===-1)return null;const o=[];for(const u of n.slice(0,i)){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(i+1).join(`
|
|
95
|
+
`).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 i=t.map(o=>o.split(n).length);if(i[0]>=3&&i.every(o=>Math.abs(o-i[0])<=1))return!0}return!1}function pC(e){const t=e.map(i=>i.trimEnd()).filter(Boolean).slice(0,20);if(!t.length)return!1;const n=t.filter(i=>/^(\[[^\]]+\]|\d{4}-\d{2}-\d{2}[t\s]|\w+:\s|traceback\b|error\b|warn\b|info\b)/i.test(i.trim())).length;return t.length>=4&&n/t.length>=.55?!0:Ox(e)}function Ox(e){const t=e.map(i=>i.trimEnd()).filter(Boolean).slice(0,20);if(!t.length)return!1;const n=t.filter(i=>/[{};]\s*$/.test(i)||/^\s*(import|export|const|let|var|function|class|def|if|for|while|return)\b/.test(i)).length;return t.length>=4&&n/t.length>=.55}function gC(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,`
|
|
96
|
+
`).replace(/\r/g,`
|
|
97
|
+
`).split(`
|
|
98
|
+
`).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 yC(e,t){var _;const n=String(t||""),i=dC(e);if(/(^|[^a-z0-9])(markdown|mdown)([^a-z0-9]|$)/i.test(i))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,`
|
|
99
|
+
`).replace(/\r/g,`
|
|
100
|
+
`).split(`
|
|
101
|
+
`),l=o.map(p=>p.trim()).filter(Boolean);if(l.length<2||gC(n)||_C(o)||pC(o))return!1;const u=((_=n.match(/[A-Za-z][A-Za-z'-]+/g))==null?void 0:_.length)||0,c=o.filter(p=>!p.trim()).length,f=l.filter(p=>/[A-Za-z]{3,}/.test(p)&&p.length>=12).length;return u>=24&&f>=2&&(c>=1||l[0].length<=140)}function vf(e){const t=Du(e==null?void 0:e.modality),n=Du(e==null?void 0:e.content_type),i=Gm(e),o=fC(e);return t==="image"||n.startsWith("image/")||wf(i,[".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)||wf(i,[".wav",".mp3",".m4a",".aac",".flac",".ogg",".opus",".aiff",".mid",".midi"])?"audio":t==="video"||n.startsWith("video/")||wf(i,[".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")||Ix(e,"")?"text":"binary"}function km(e,t){const n=Du(e==null?void 0:e.content_type),i=Gm(e),o=String(t||"").trim();return n.includes("html")||i.endsWith(".html")||i.endsWith(".htm")||hC(t)?"html":Ix(e,t)?"code":n.includes("markdown")||i.endsWith(".md")||i.endsWith(".markdown")?"markdown":n.includes("json")||i.endsWith(".json")||i.endsWith(".jsonl")||(o.startsWith("{")||o.startsWith("["))&&Um(o)!==null?"json":yC(e,t)?"markdown":"text"}function Cg(e,t=""){const n=vf(e);if(n==="image"||n==="video")return n;if(n==="audio"){const i=(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,i.semantic_kind,i.modality,i.kind,i.task,i.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 i=Du(e==null?void 0:e.modality),o=Du(e==null?void 0:e.content_type),l=Gm(e);return i==="document"||o.includes("pdf")||wf(l,[".pdf",".doc",".docx",".ppt",".pptx",".xls",".xlsx"])?"document":"other"}return km(e,t)}function V_(e){var _,p;const t=String(e||"").replace(/\r\n/g,`
|
|
102
|
+
`).replace(/\r/g,`
|
|
103
|
+
`).trim();if(!t)return"";const n=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]),i=t.match(/<!--[\s\S]*?-->|<!doctype\b[^>]*>|<!\[CDATA\[[\s\S]*?\]\]>|<\/?[A-Za-z][^>]*>|[^<]+/gi)||[t],o=[];let l=0,u="";const c=y=>" ".repeat(Math.max(0,y)),f=(y,w)=>{const x=y.match(/^(<\/?|<!)([^\s/>]+)([\s\S]*?)(\/?>)$/);if(!x||y.length<=120||y.startsWith("</")||y.startsWith("<!"))return[`${c(w)}${y.trim()}`];const S=(x[3]||"").trim();if(!S)return[`${c(w)}${y.trim()}`];const j=S.match(/[^\s="'<>`]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'<>`]+))?/g)||[S];return[`${c(w)}${x[1]}${x[2]}`,...j.map(E=>`${c(w+1)}${E.trim()}`),`${c(w)}${x[4]}`]};for(const y of i){const w=String(y||"");if(!w.trim())continue;const x=w.trim().toLowerCase();if(x.startsWith("</")){const j=((_=x.match(/^<\/\s*([a-z0-9:-]+)/))==null?void 0:_[1])||"";u&&j===u&&(u=""),l=Math.max(0,l-1),o.push(`${c(l)}${w.trim()}`);continue}if(w.trimStart().startsWith("<")){o.push(...f(w,l));const j=((p=x.match(/^<\s*([a-z0-9:-]+)/))==null?void 0:p[1])||"";/\/>\s*$/.test(w)||x.startsWith("<!")||n.has(j)||(l+=1,(j==="script"||j==="style")&&(u=j));continue}if(u){const j=w.trim();j&&o.push(...j.split(`
|
|
104
|
+
`).map(E=>`${c(l)}${E.trimEnd()}`));continue}const S=w.replace(/\s+/g," ").trim();S&&o.push(`${c(l)}${S}`)}return o.join(`
|
|
105
|
+
`)}function wC(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 Nm(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 pl(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 vC=/^\s*<runtime_metadata>\s*([\s\S]*?)\s*<\/runtime_metadata>\s*/i;function Eg(e){const t=typeof e=="string"?e:String(e??""),n=vC.exec(t);if(!n)return{text:t.trim(),metadata:null,stripped:!1};let i=null;try{const o=JSON.parse(String(n[1]||"").trim());o&&typeof o=="object"&&!Array.isArray(o)&&(i=o)}catch{i=null}return{text:t.slice(n[0].length).trim(),metadata:i,stripped:!0}}function Px(...e){const t={};for(const n of e)if(!(!n||typeof n!="object"||Array.isArray(n)))for(const[i,o]of Object.entries(n))o==null||String(o).trim()===""||(t[i]=o);return Object.keys(t).length?t:null}function Bp(e){if(e==null)return"";if(typeof e=="string")return e.trim();if(Array.isArray(e))return e.map(t=>Bp(t)).filter(Boolean).join(`
|
|
106
|
+
`).trim();if(typeof e=="object"){const t=e.text??e.content??e.message??e.value;if(t!==e){const n=Bp(t);if(n)return n}}return""}function Dx(e){const t=Eg(Bp(e));return{text:t.text,runtime_metadata:t.metadata}}function xC(e){var i,o;if(!e)return{text:"",runtime_metadata:null};const t=typeof e.prompt=="string"?String(e.prompt).trim():"";if(t){const l=Eg(t);return{text:l.text,runtime_metadata:l.metadata}}const n=[(i=e.context)==null?void 0:i.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 _=Dx((c==null?void 0:c.content)??(c==null?void 0:c.text)??c);if(_.text)return{text:_.text,runtime_metadata:Px(_.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 bC(e,t=6){var l,u;if(!e)return[];const i=[(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 i){const f=String((c==null?void 0:c.role)||(c==null?void 0:c.speaker)||(c==null?void 0:c.author)||"").trim().toLowerCase()||"message",_=Dx((c==null?void 0:c.content)??(c==null?void 0:c.text)??(c==null?void 0:c.message)??c),p=_.text;if(!p)continue;const y=String((c==null?void 0:c.ts)||(c==null?void 0:c.timestamp)||(c==null?void 0:c.created_at)||(c==null?void 0:c.time)||"").trim(),w=Px(_.runtime_metadata,c!=null&&c.runtime_metadata&&typeof c.runtime_metadata=="object"?c.runtime_metadata:null,(u=c==null?void 0:c.metadata)!=null&&u.runtime_metadata&&typeof c.metadata.runtime_metadata=="object"?c.metadata.runtime_metadata:null);o.push({role:f,text:p,ts:y,runtime_metadata:w})}return o.slice(Math.max(0,o.length-Math.max(1,t)))}function Fx(e){const t=String(e||"").trim().toLowerCase().replace(/\s+/g," ");return t==="please respond:"||t==="please respond"||t==="type response..."||t==="type response"}function jC(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 zx="inferred from the call's arguments (regex heuristic) — not a declared risk tier; declared tiers replace this when the grant API ships";function Bx(e){const t=String((e==null?void 0:e.name)||"").trim().toLowerCase(),n=e!=null&&e.arguments&&typeof e.arguments=="object"?e.arguments:{},i=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")||i)&&o.push("Shell"),/[;&|]?\s*(rm|rmdir|mv|chmod|chown|sudo)\b/.test(i)&&o.push("Destructive risk"),/(^|\s)(curl|wget|scp|ssh|nc|ncat|ftp)\b/.test(i)&&o.push("Network"),/(^|\s)(cat|sed|rg|grep|ls|find|pwd)\b/.test(i)&&!/[>|]\s*\S/.test(i)&&o.push("Read path"),/[>|]\s*\S|(^|\s)(tee|touch|mkdir|cp)\b/.test(i)&&o.push("Filesystem write"),o.length||o.push("Tool call"),Array.from(new Set(o)).slice(0,4)}function $g(e,t){const n=String((e==null?void 0:e.reason)||"").trim().toLowerCase(),i=jC(t);return t.length?`Approval required: ${i||"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 Ux(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 Wx(e,t){const n=String((e==null?void 0:e.prompt)||"").trim(),i=Eg(n),o=xC(t);return i.text&&!Fx(i.text)?{text:i.text,runtime_metadata:i.metadata}:o.text?o:{text:i.text||n,runtime_metadata:i.metadata}}function SC(e,t){return Wx(e,t).text}function kC(e,t){return e||String(t||"").trim()||{}}function ji(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 gl(e){const t=String(e.status||"unknown").trim()||"unknown";return s.jsx("span",{className:`run_status_pill ${pl(t)}`,children:t})}function NC(e){var l;const t=String((e==null?void 0:e.status)||"").trim().toLowerCase();if(Ci(t))return"";const n=e!=null&&e.waiting&&typeof e.waiting=="object"?e.waiting:null,i=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?$g(n,o):i==="user"?"Waiting for your answer":i==="event"?"Waiting for a response event":i==="subworkflow"?"Waiting for subworkflow":i==="until"?"Scheduled wait":i?`Waiting: ${i}`:t==="waiting"?"Waiting, reason unknown":""}function Cm(e){const t=e==null?void 0:e.error;return t?typeof t=="string"?ht(t,{max_chars:220,max_lines:2}):ht(Bs(t,400),{max_chars:220,max_lines:2}):""}function CC(e){const t=NC(e);if(t)return t;const n=Cm(e);if(n)return n;const i=String((e==null?void 0:e.current_node)||"").trim();if(i)return`Current node: ${i}`;const o=String((e==null?void 0:e.status)||"").trim().toLowerCase();return o==="running"?"Running":Ci(o)?"Terminal":"No current activity reported"}function qx(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 Yy(e){const t=qx(e),n=e!=null&&e.metadata&&typeof e.metadata=="object"?e.metadata:e!=null&&e.meta&&typeof e.meta=="object"?e.meta:{},i=e!=null&&e.tags&&typeof e.tags=="object"?e.tags:{},o=hn(e==null?void 0:e.modality,t==null?void 0:t.modality,n==null?void 0:n.modality,i.modality).toLowerCase();if(o)return o;const l=hn(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,i.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 EC(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 $C(e,t){if(!e||typeof e!="object")return null;const n=EC(e),i=qx(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=hn(n.artifact_id,e.artifact_id,e.$artifact,e.id,i.artifact_id,i.$artifact,i.id,o.artifact_id,o.$artifact);if(!u)return null;const c={...i.tags&&typeof i.tags=="object"?i.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[M,H]of Object.entries(c)){const X=String(M||"").trim();X&&(f[X]=String(H??""))}const _=hn(n.filename,e.filename,i.filename,o.filename,f.filename,f.name,e.name,i.name),p=hn(n.source_path,e.source_path,i.source_path,o.source_path,e.path,i.path,f.path,f.source_path,f.file_path),y=hn(n.content_type,e.content_type,e.mime_type,e.mime,i.content_type,i.mime_type,i.mime,o.content_type,f.content_type),w=hn(n.render_kind,l.render_kind,e.render_kind,f.render_kind),x=hn(n.semantic_kind,l.semantic_kind,e.semantic_kind,f.semantic_kind,f.artifact_type),S=n.access&&typeof n.access=="object"?n.access:e.access&&typeof e.access=="object"?e.access:{},j=n.producer&&typeof n.producer=="object"?n.producer:e.producer&&typeof e.producer=="object"?e.producer:l.producer&&typeof l.producer=="object"?l.producer:{},E=n.provenance&&typeof n.provenance=="object"?n.provenance:e.provenance&&typeof e.provenance=="object"?e.provenance:l.provenance&&typeof l.provenance=="object"?l.provenance:{},A=n.generation&&typeof n.generation=="object"?n.generation:e.generation&&typeof e.generation=="object"?e.generation:l.generation&&typeof l.generation=="object"?l.generation:{},L=n.media&&typeof n.media=="object"?n.media:e.media&&typeof e.media=="object"?e.media:l.media&&typeof l.media=="object"?l.media:{},O=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:hn(n.run_id,e.run_id,i.run_id,o.run_id,f.run_id,E.run_id),content_type:y,modality:hn(n.modality,e.modality,l.modality,f.modality)||Yy({...e,ref:i,metadata:o,tags:f}),semantic_kind:x||Yy({...e,ref:i,metadata:o,tags:f}),render_kind:w||Cg({content_type:y,filename:_,source_path:p,modality:hn(n.modality,e.modality,f.modality),tags:f}),task:hn(n.task,l.task,e.task,f.task,f.provider_task),classification_source:hn(n.classification_source,l.classification_source,e.classification_source),session_id:hn(n.session_id,l.session_id,e.session_id,f.session_id),workflow_id:hn(n.workflow_id,l.workflow_id,e.workflow_id,f.workflow_id,f.workflow),node_id:hn(n.node_id,l.node_id,e.node_id,f.node_id,f.node),step_id:hn(n.step_id,l.step_id,e.step_id,f.step_id),effect_id:hn(n.effect_id,l.effect_id,e.effect_id,f.effect_id,f.effect_idempotency_key),turn_id:hn(n.turn_id,l.turn_id,e.turn_id,f.turn_id,f.turn),ledger_cursor:hn(n.ledger_cursor,l.ledger_cursor,e.ledger_cursor,f.ledger_cursor,f.step_cursor),parent_run_id:hn(n.parent_run_id,l.parent_run_id,e.parent_run_id,f.parent_run_id),actor_id:hn(n.actor_id,l.actor_id,e.actor_id,f.actor_id),title:hn(n.title,e.title,f.title,f.label,f.name),created_at:hn(n.created_at,e.created_at,i.created_at,o.created_at,f.created_at),size_bytes:cC(n.size_bytes,e.size_bytes,i.size_bytes,o.size_bytes,f.size_bytes),filename:_,source_path:p,sha256:hn(n.sha256,e.sha256,i.sha256,o.sha256,f.sha256),tags:f,producer:j,provenance:E,generation:A,media:L,source_refs:Array.isArray(n.source_refs)?n.source_refs:Array.isArray(e.source_refs)?e.source_refs:[],access:S,links:O,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(hn(n.classification_source,l.classification_source,e.classification_source))),descriptor:l,source:t,raw:e}}function Up(e){return e.filename||e.title||(e.source_path?e.source_path.split("/").filter(Boolean).slice(-1)[0]:"")||Lt(e.artifact_id,16)}function AC(e,t){if(t==="type")return Mu(e);if(t==="run")return e.run_id||"(no run)";if(t==="turn")return Wp(e);if(t==="node")return Tu(e)||"(node unknown)";if(t==="workflow")return Ag(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 bf(e)||e.source||"artifact";const n=Cn(e.created_at);return n===null?"(unknown time)":new Date(n).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}function Ag(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 Tu(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 Wp(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 i=Tu(e),o=Cn(e==null?void 0:e.created_at),l=o===null?"unknown time":new Date(o).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}),u=e!=null&&e.run_id?Lt(String(e.run_id),10):"unknown run";return i?`${u} · ${i} · ${l}`:`${u} · ${l}`}function Jy(e){if(!e)return"provenance unavailable";const t=[],n=Ag(e),i=Tu(e),o=bf(e),l=Hx(e);return n&&t.push(n),i&&t.push(i),o&&t.push(o),l&&t.push(l),t.length?t.join(" · "):"provenance unavailable"}function Xl(e){if(typeof e!="number"||!Number.isFinite(e)||e<0)return"—";const t=["B","KB","MB","GB","TB"];let n=e,i=0;for(;n>=1024&&i<t.length-1;)n/=1024,i+=1;const o=i===0?0:n>=10?1:2;return`${n.toFixed(o)} ${t[i]}`}function Mu(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(),i=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"}[i]||i.replace(/[_-]+/g," ").replace(/\b\w/g,l=>l.toUpperCase())}function TC(e){return e==="html"?"HTML":e==="json"?"JSON":e==="audio"?"Unclassified audio":e==="code"?"Code":e.slice(0,1).toUpperCase()+e.slice(1)}function MC(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 RC(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 Xy(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 LC(e){const t=Ca(e.created_at),n=Sa(e.created_at);return t==="—"?"Created —":`${t}${n&&n!=="—"?` (${n})`:""}`}function Zy(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(),i=Ca(n);return i==="—"?"—":i}function Qy(e){const t=e.tags||{},n=String(e.title||t.title||t.name||t.label||e.filename||"").trim();if(n)return n;const i=String(e.source_path||t.path||"").trim();if(i)return i.split("/").filter(Boolean).slice(-1)[0]||i;const o=bf(e),l=Mu(e);return o?`${l} ${o}`:`${l} artifact`}function bf(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 Hx(e){var i,o,l,u,c,f,_,p;if(!e)return"";const t=hn((i=e.producer)==null?void 0:i.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=hn((c=e.producer)==null?void 0:c.model,(f=e.producer)==null?void 0:f.model_id,(_=e.provenance)==null?void 0:_.model,(p=e.generation)==null?void 0:p.model);return t&&n?`${t} / ${n}`:t||n}function IC(e){var t,n,i,o;return e?hn((t=e.generation)==null?void 0:t.prompt,(n=e.generation)==null?void 0:n.input,(i=e.generation)==null?void 0:i.text,(o=e.provenance)==null?void 0:o.prompt):""}function ew(e){if(!e)return"";const t=e.media||{},n=Number(t.duration_s??t.duration_seconds??t.duration),i=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(i)&&Number.isFinite(o)&&i>0&&o>0)return`${Math.round(i)} x ${Math.round(o)}`;const c=Number(t.page_count??t.pages);return Number.isFinite(c)&&c>0?`${Math.round(c)} pages`:""}function tw(e){return e.source_path||e.filename||""}function Em(e,t,n){const i=e.run_id&&t[e.run_id]||null;if(!i)return e;const o=ji(i,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 qp(e,t,n,i=""){const o=Em(e,t,n),l=Cg(o,i);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]||Mu(o)}function to(e){var i;const t=e,n=(i=t==null?void 0:t.result)==null?void 0:i.wait;return!n||typeof n!="object"?null:n}function Gh(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 i=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(!i)return null;const o=(c=n==null?void 0:n.payload)==null?void 0:c.payload;return{name:i,payload:o}}function Uu(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 i=n==null?void 0:n.tool_calls;return Array.isArray(i)?i:[]}function OC(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(),i=(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"&&i?i:n||t||"record"}function Vx(e){if(!e||typeof e!="object")return"Ledger record";const t=String(e.node_id||"").trim(),n=String(e.status||"").trim(),i=OC(e),o=to(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 ${i}`:n==="running"?`${t||"node"} started ${i}`:n==="waiting"?`${t||"node"} is waiting`:[t,n,i].filter(Boolean).join(" · ")||"Ledger record"}function vu(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):Bs(e,320),n=typeof e.duration=="number"?Number(e.duration):-1;return{text:t,duration:n}}return{text:Bs(e,320),duration:-1}}function Df(e){var u,c,f,_,p,y,w,x,S;if(!e||typeof e!="object")return"";const t=String(((u=e==null?void 0:e.effect)==null?void 0:u.type)||"").trim(),n=e==null?void 0:e.result,i=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 E=j,A=[E.response,E.answer,E.message,E.text,E.content];for(const L of A){const O=i(L);if(O)return O}return""};if(t==="answer_user"){const j=i(n==null?void 0:n.message)||i((c=n==null?void 0:n.output)==null?void 0:c.message)||i((f=n==null?void 0:n.output)==null?void 0:f.response)||i((p=(_=e==null?void 0:e.effect)==null?void 0:_.payload)==null?void 0:p.message)||i((w=(y=e==null?void 0:e.effect)==null?void 0:y.payload)==null?void 0:w.text)||i((S=(x=e==null?void 0:e.effect)==null?void 0:x.payload)==null?void 0:S.content);if(j)return j}if(t==="llm_call"){const j=o(n)||i(n==null?void 0:n.output)||o(n==null?void 0:n.output)||i(n==null?void 0:n.response);if(j)return j}return i(n==null?void 0:n.output)||o(n==null?void 0:n.output)||o(n)||i(n==null?void 0:n.response)}function dm(e){var o;const t=String((e==null?void 0:e.node_id)||""),n=String((e==null?void 0:e.status)||""),i=String(((o=e==null?void 0:e.effect)==null?void 0:o.type)||"");return`${t||"(node?)"} • ${n||"(status?)"} • ${i||"(effect?)"}`}function PC(e){return!!(e&&String(e.status||"")==="waiting")}function Gx(e){var n,i;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=(i=l==null?void 0:l.effect)!=null&&i.payload&&typeof l.effect.payload=="object"?l.effect.payload:{},f=l!=null&&l.result&&typeof l.result=="object"?l.result:{},_=(f==null?void 0:f.usage)||(f==null?void 0:f.token_usage)||{},p=typeof c.prompt=="string"?c.prompt:Array.isArray(c.messages)?Bs(c.messages,1800):"",y=typeof f.content=="string"?f.content:typeof f.response=="string"?f.response:typeof l.result=="string"?String(l.result):"",w=Cn(l.started_at),x=Cn(l.ended_at),S=Number(_.prompt_tokens??_.input_tokens??0)||0,j=Number(_.completion_tokens??_.output_tokens??0)||0;t.push({id:`${String(o.run_id||l.run_id||"")}:${o.cursor}`,cursor:Number(o.cursor||0),ts:String(l.ended_at||l.started_at||""),run_id:String(o.run_id||l.run_id||"").trim(),node_id:String(l.node_id||"").trim(),provider:String(c.provider||f.provider||f.runtime_provider||"").trim(),model:String(c.model||f.model||f.runtime_model||"").trim(),prompt_preview:ht(p,{max_chars:1200,max_lines:10}),response_preview:ht(y,{max_chars:1200,max_lines:10}),missing_response:!String(y||"").trim(),tokens:{prompt:S,completion:j,total:Number(_.total_tokens??S+j)||0},duration_ms:w!==null&&x!==null?Math.max(0,x-w):typeof f.gen_time=="number"?Number(f.gen_time)*1e3:null,status:String(l.status||"").trim(),error:l.error?Bs(l.error,500):"",raw:l})}return t.sort((o,l)=>(Cn(l.ts)??0)-(Cn(o.ts)??0))}function nw(e){const t=e.size||18,n=vf(e.artifact),i=Cg(e.artifact,""),o=`artifact_glyph ${i==="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"})]})}):i==="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 DC=2,FC=Number.MAX_SAFE_INTEGER;function zC(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 BC(e){const t=String(e||"");if(typeof DOMParser>"u")return[{kind:"text",text:V_(t)||t}];try{const n=new DOMParser().parseFromString(t,"text/html"),i=[];n.doctype&&i.push({kind:"doctype",name:n.doctype.name||"html"});const o=l=>{if(l.nodeType===Node.TEXT_NODE){const u=String(l.textContent||"").trim();return u?{kind:"text",text:u}:null}if(l.nodeType===Node.COMMENT_NODE)return{kind:"comment",text:String(l.textContent||"")};if(l.nodeType===Node.ELEMENT_NODE){const u=l,c=Array.from(u.attributes||[]).map(_=>({name:_.name,value:_.value})),f=Array.from(u.childNodes||[]).map(o).filter(Boolean);return{kind:"element",tag:u.tagName.toLowerCase(),attrs:c,children:f}}return null};if(n.documentElement){const l=o(n.documentElement);l&&i.push(l)}return i.length?i:[{kind:"text",text:V_(t)||t}]}catch{return[{kind:"text",text:V_(t)||t}]}}function G_(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 Kx(e){const t=e.node,n=e.depth*14,i=e.depth<e.collapseAfterDepth,[o,l]=m.useState(i);if(m.useEffect(()=>{l(i)},[i,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(G_,{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(G_,{tag:t.tag,attrs:t.attrs}),!o&&u?s.jsxs("span",{className:"html-tree__summary_text",children:[" ",zC(u.text)]}):null]}),o?s.jsxs("div",{className:"html-tree__children",children:[t.children.map((c,f)=>s.jsx(Kx,{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(G_,{tag:t.tag,attrs:[],closing:!0})})]}):null]})}function UC(e){const t=m.useMemo(()=>BC(e.text),[e.text]),[n,i]=m.useState({mode:"folded",version:0}),o=n.mode==="unfolded"?FC:DC;m.useEffect(()=>{i(u=>({mode:"folded",version:u.version+1}))},[e.text]);const l=()=>{i(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(Kx,{node:u,depth:0,collapseAfterDepth:o,expansionMode:n.mode,expansionVersion:n.version},`root:${c}`))})]})}function WC(e){var i;const t=mC(e.text);if(!t)return s.jsx("div",{className:`${e.className} structured markdown_preview`,children:s.jsx(Ni,{text:e.text})});const n=((i=t.metadata.find(o=>o.label.toLowerCase()==="title"))==null?void 0:i.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(Ni,{text:t.body||e.text})]})}function Yx(e){const t=String(e.text||""),n=km(e.artifact,t);if(n==="json"){const i=Um(t);if(i!==null)return s.jsx("div",{className:`${e.className} structured`,children:s.jsx(fr,{value:i,collapseAfterDepth:4,showCopy:!1})})}return n==="markdown"?s.jsx(WC,{text:t,className:e.className}):n==="html"?s.jsx(UC,{text:t,className:e.className}):s.jsx("pre",{className:`mono ${e.className}`,children:t})}function qC(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:Up(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(Yx,{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 Tg(e){const t=e==null?void 0:e.waiting;return t&&typeof t=="object"?t:null}function Jx(e){const t=Tg(e);return String((t==null?void 0:t.reason)||(e==null?void 0:e.waiting_reason)||"").trim().toLowerCase()}function sw(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 HC(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 Wu(e){const t=String((e==null?void 0:e.status)||"").trim().toLowerCase();if(Ci(t)||t!=="waiting")return"none";const n=Tg(e),i=Jx(e);return Uu(n).length?"tool_approval":i==="until"||String((e==null?void 0:e.role)||"").trim()==="controller"?"scheduled":i==="subworkflow"?"subworkflow":i==="event"?sw(n)?"user_response":"external_event":i==="user"||sw(n)?"user_response":"unknown_wait"}function Xx(e){const t=Tg(e),n=Uu(t),i=Wu(e);return i==="tool_approval"?`Tool approval: ${HC(n)||"tool call"}`:i==="user_response"?Array.isArray(t==null?void 0:t.choices)&&t.choices.length>0?"Choice required":"User response needed":i==="scheduled"?String((e==null?void 0:e.role)||"").trim()==="controller"?"Automation waiting for its next run":"Scheduled wait":i==="subworkflow"?"Waiting for subworkflow":i==="external_event"?"Waiting for external event":i==="unknown_wait"?"Waiting, context unclear":""}function VC(e){const t=Wu(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.":Ci(n)?"Open the ledger and artifacts for the final outcome.":"Open the run to inspect current activity."}function rw(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 GC(e,t={}){const n=t.now_ms??Date.now(),i=t.workflow_label??"",o=String(e.status||"unknown").trim().toLowerCase()||"unknown",l=Wu(e),u=Ci(o),c=Ng(e,n),f=Cn(e.updated_at||e.created_at)??0,_=o==="running"&&c>=14400*1e3,p=Xx(e)||rw(e)||(e.current_node?`Current node: ${e.current_node}`:o==="running"?"Running":u?"Terminal":"No current activity reported");let y="all";l==="tool_approval"?y="tool_approval":l==="user_response"?y="user_wait":l==="scheduled"?y="scheduled":l==="subworkflow"||l==="external_event"?y="subflows":o==="failed"?y="failed":o==="running"?y="running":u&&(y="finished");const w=l==="tool_approval"?0:l==="user_response"?1:l==="unknown_wait"?2:o==="failed"?3:_?4:o==="running"?5:l!=="none"?6:u?8:7,x=l==="tool_approval"||l==="user_response",S=l==="tool_approval"?"Open approval":l==="user_response"?"Open wait":"Open Observe",j=[e.run_id,e.workflow_id,i,e.session_id,e.parent_run_id,e.status,e.current_node,Jx(e),p,rw(e)].join(" ").toLowerCase();return{run:e,run_id:String(e.run_id||"").trim(),status:o,wait_kind:l,queue:y,attention_rank:w,reason:p,expected_action:VC(e),action_label:S,search_text:j,is_terminal:u,needs_user_action:x,is_stale:_,duration_ms:c,updated_ms:f}}function KC(e,t={}){const n=t.now_ms??Date.now(),i=t.workflow_label_by_id??{};return e.map(o=>GC(o,{now_ms:n,workflow_label:i[String(o.workflow_id||"")]||String(o.workflow_id||"")}))}function YC(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 JC(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 XC(e,t){const n=[...e];return n.sort((i,o)=>{if(t==="recent")return o.updated_ms-i.updated_ms;if(t==="oldest")return i.updated_ms-o.updated_ms;if(t==="duration")return o.duration_ms-i.duration_ms;if(t==="tokens")return(Number(o.run.tokens_total||0)||0)-(Number(i.run.tokens_total||0)||0);if(t==="workflow")return String(i.run.workflow_id||"").localeCompare(String(o.run.workflow_id||""));const l=i.attention_rank-o.attention_rank;return l!==0?l:o.updated_ms-i.updated_ms}),n}function ZC(e){const[t,n]=m.useState("attention"),[i,o]=m.useState(""),[l,u]=m.useState("attention"),[c,f]=m.useState(""),_=m.useMemo(()=>{const F={};for(const C of e.artifacts){const N=String(C.run_id||"").trim();N&&(F[N]=(F[N]||0)+1)}return F},[e.artifacts]),p=m.useMemo(()=>KC(e.runs,{workflow_label_by_id:e.workflow_label_by_id}),[e.runs,e.workflow_label_by_id]),y=m.useMemo(()=>YC(p),[p]),w=m.useMemo(()=>{const F=JC(p,{queue:t,query:i});return XC(F,l)},[p,t,i,l]),x=w.find(F=>String(F.run_id||"")===c)||w.find(F=>String(F.run_id||"")===e.selected_run_id)||w[0]||null,S=(x==null?void 0:x.run)||null,j=String((S==null?void 0:S.run_id)||"").trim(),E=String((S==null?void 0:S.session_id)||"").trim(),A=m.useMemo(()=>E?new Set(e.runs.filter(F=>String(F.session_id||"").trim()===E).map(F=>String(F.run_id||"").trim()).filter(Boolean)):new Set,[e.runs,E]),L=E?A.size:0,O=m.useMemo(()=>E?e.artifacts.filter(F=>String(F.session_id||"").trim()===E||A.has(String(F.run_id||"").trim())).length:0,[e.artifacts,E,A]),M=S!=null&&S.waiting&&typeof S.waiting=="object"?S.waiting:null,H=M?Uu(M):[],X=(x==null?void 0:x.reason)||(M?$g(M,H):""),Y=(x==null?void 0:x.expected_action)||(M?Ux(M,H):""),Z=M?SC(M,null):"",re=j&&_[j]||0,ie=Ci(S==null?void 0:S.status),ue=[{key:"attention",label:"Needs attention",count:y.attention},{key:"user_wait",label:"Needs my response",count:y.user_wait},{key:"tool_approval",label:"Tool approvals",count:y.tool_approval},{key:"running",label:"Running",count:y.running},{key:"failed",label:"Failed",count:y.failed},{key:"scheduled",label:"Scheduled",count:y.scheduled},{key:"subflows",label:"Subflows / external events",count:y.subflows},{key:"finished",label:"Finished",count:y.finished},{key:"all",label:"All loaded",count:y.all}];return s.jsxs("div",{className:"runtime_ops_layout",children:[s.jsxs("aside",{className:"pane runtime_ops_filters",children:[s.jsxs("div",{className:"pane_header runtime_ops_filter_header",children:[s.jsx("span",{className:"pane_title",children:"Queues"}),s.jsx("div",{className:"pane_spacer"}),s.jsxs("button",{className:"btn btn_icon",onClick:e.gateway_connected?e.on_refresh_runs:e.on_reconnect,children:[s.jsx(Qe,{name:"refresh",size:14}),e.gateway_connected?"Refresh":"Reconnect"]})]}),s.jsxs("div",{className:"pane_body scroll runtime_ops_queue_list",children:[ue.map(F=>s.jsxs("button",{className:`runtime_ops_filter ${t===F.key?"selected":""}`,"aria-pressed":t===F.key,onClick:()=>n(F.key),children:[s.jsx("span",{children:F.label}),s.jsx("strong",{children:F.count.toLocaleString()})]},F.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",children:[s.jsxs("div",{className:"pane_header runtime_ops_list_header",children:[s.jsx("span",{className:"pane_title",children:"Runs"}),s.jsx("span",{className:"pane_count",children:w.length.toLocaleString()}),s.jsx("div",{className:"pane_spacer"}),s.jsx("input",{value:i,onChange:F=>o(F.target.value),placeholder:"Search workflow, run, node, status, error"}),s.jsxs("select",{className:"seg_select",value:l,onChange:F=>u(F.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",children:[w.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."}),w.map(F=>{const C=F.run,N=String(C.run_id||"").trim(),P=_[N]||0;return s.jsxs("div",{className:`raised runtime_ops_row ${N===j?"selected":""}`,"aria-current":N===j?"true":void 0,tabIndex:0,onClick:()=>{f(N),e.on_select_run(N)},onKeyDown:D=>{(D.key==="Enter"||D.key===" ")&&(D.preventDefault(),f(N),e.on_select_run(N))},children:[s.jsxs("div",{className:"runtime_ops_row_top",children:[s.jsx("strong",{className:"runtime_ops_row_name",children:ji(C,e.workflow_label_by_id)}),F.is_stale?s.jsx("span",{className:"chip warn",children:"stale"}):null,s.jsx(gl,{status:C.status})]}),s.jsxs("div",{className:"runtime_ops_row_sub",children:[s.jsx("span",{className:"mono",children:Lt(N,18)}),s.jsx("span",{children:Sa(C.updated_at||C.created_at)}),s.jsx("span",{children:oc(C)}),s.jsx("span",{className:"runtime_ops_row_reason",title:F.reason,children:F.reason})]}),s.jsxs("div",{className:"runtime_ops_row_foot",children:[s.jsxs("span",{className:"runtime_ops_row_facts",children:[s.jsxs("span",{children:[Number(C.llm_calls||0).toLocaleString()," llm"]}),s.jsxs("span",{children:[Number(C.tool_calls||0).toLocaleString()," tools"]}),s.jsxs("span",{children:[Number(C.tokens_total||0).toLocaleString()," tok"]}),s.jsxs("span",{children:[P.toLocaleString()," artifacts"]})]}),s.jsxs("div",{className:"runtime_ops_actions",children:[F.needs_user_action?s.jsx("button",{className:"btn primary",onClick:D=>{D.stopPropagation(),e.on_open_run(N)},children:F.action_label}):s.jsx("button",{className:"btn",onClick:D=>{D.stopPropagation(),e.on_open_run(N)},children:"Open"}),s.jsx("button",{className:"btn",onClick:D=>{D.stopPropagation(),e.on_open_ledger(N)},children:"Ledger"}),s.jsx("button",{className:"btn",onClick:D=>{D.stopPropagation(),e.on_select_run(N),e.on_open_logs()},children:"Logs"}),s.jsx("button",{className:"btn",onClick:D=>{D.stopPropagation(),e.on_filter_artifacts(N)},children:"Artifacts"})]})]})]},N)})]})]}),s.jsxs("aside",{className:"pane runtime_ops_inspector",children:[s.jsxs("div",{className:"pane_header",children:[s.jsx("span",{className:"pane_title",children:"Run inspector"}),S?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"pane_spacer"}),s.jsx(gl,{status:S.status})]}):null]}),s.jsx("div",{className:"pane_body scroll runtime_ops_inspector_body",children:S?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"runtime_ops_inspector_head",children:[s.jsx("h3",{children:ji(S,e.workflow_label_by_id)}),s.jsx("span",{className:"mono",children:Lt(j,28)})]}),s.jsxs("div",{className:"runtime_ops_decision",children:[s.jsx("strong",{children:(x==null?void 0:x.reason)||CC(S)}),s.jsx("span",{children:(x==null?void 0:x.expected_action)||(String(S.status||"").toLowerCase()==="waiting"?"This run is paused until the pending wait is resolved or the run is cancelled.":ie?"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:Ca(Jl(S))})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Elapsed"}),s.jsx("strong",{children:oc(S)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Last event"}),s.jsx("strong",{children:Ca(S.updated_at||S.created_at)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Session"}),s.jsx("strong",{className:"mono",children:S.session_id?Lt(String(S.session_id),18):"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Node"}),s.jsx("strong",{className:"mono",children:S.current_node||"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Visible artifacts"}),s.jsx("strong",{children:re.toLocaleString()})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Provider calls"}),s.jsx("strong",{children:Number(S.llm_calls||0).toLocaleString()})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Tokens"}),s.jsx("strong",{children:Number(S.tokens_total||0).toLocaleString()})]})]}),E?s.jsxs("section",{className:"runtime_ops_session_context",children:[s.jsxs("div",{children:[s.jsx("span",{className:"run_hero_eyebrow",children:"Session context"}),s.jsx("strong",{className:"mono",children:Lt(E,30)})]}),s.jsxs("div",{className:"runtime_ops_session_facts",children:[s.jsxs("span",{children:[L.toLocaleString()," loaded run",L===1?"":"s"]}),s.jsxs("span",{children:[O.toLocaleString()," visible artifact",O===1?"":"s"]})]}),s.jsxs("div",{className:"runtime_detail_actions compact",children:[s.jsx("button",{className:"btn",onClick:()=>e.on_filter_session_artifacts(E),children:"Open session artifacts"}),s.jsx("button",{className:"btn",onClick:()=>void ic(E),children:"Copy session id"})]})]}):null,M?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:X})]}),s.jsx("p",{children:Y}),Z?s.jsxs("div",{className:"runtime_ops_wait_request",children:[s.jsx("span",{children:"Request"}),s.jsx(Ni,{text:Z})]}):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."}),H.length?s.jsx("div",{className:"runtime_ops_wait_tools",children:H.map((F,C)=>s.jsxs(ve.Fragment,{children:[s.jsx("span",{className:"chip mono warn",children:String((F==null?void 0:F.name)||"tool")}),Bx(F).map(N=>s.jsxs("span",{className:"chip muted",title:zx,children:[N,"~"]},`${C}:${N}`))]},`${String((F==null?void 0:F.name)||"tool")}:${C}`))}):null,s.jsxs("details",{className:"runtime_raw_details",children:[s.jsx("summary",{className:"muted",children:"Raw wait payload"}),s.jsx(fr,{value:M,collapseAfterDepth:3,showCopy:!0})]})]}):null,Cm(S)?s.jsx("div",{className:"warn_callout",children:Cm(S)}):null,s.jsxs("div",{className:"runtime_detail_actions",children:[s.jsx("button",{className:"btn primary",onClick:()=>e.on_open_run(j),children:"Open Observe"}),s.jsx("button",{className:"btn",onClick:()=>e.on_open_ledger(j),children:"Open ledger"}),s.jsx("button",{className:"btn",onClick:()=>e.on_filter_artifacts(j),children:"Open artifacts"}),s.jsx("button",{className:"btn",onClick:e.on_open_logs,children:"Open logs"}),s.jsx("button",{className:"btn",onClick:()=>void ic(j),children:"Copy run id"})]})]}):s.jsx("div",{className:"empty_state_inline",children:"Select a run to inspect why it is active or blocked."})})]})]})}function QC(e){const t=e.selected_artifact,n=["voice","music","sound","recording","audio","image","video","markdown","html","json","document","code","text","other"],i=[{value:"all",label:"Any time"},{value:"hour",label:"Last hour"},{value:"today",label:"Today"},{value:"week",label:"7 days"},{value:"month",label:"30 days"}],o=m.useMemo(()=>new Set(e.type_filters),[e.type_filters]),l=Math.max(0,Number(e.artifact_total_count||0)),u=!!e.query.trim()||e.type_filters.length>0||e.date_filter!=="all"||e.scope!=="all"||!!e.artifact_run_filter.trim(),c=Math.max(1,Number(e.artifact_page_size||500)),f=Math.max(1,Math.ceil(l/c)),_=Math.min(Math.max(0,Number(e.artifact_page||0)),f-1),p=l?_*c+1:0,y=Math.min(l,_*c+e.artifacts.length),w=m.useMemo(()=>{const C={},N=e.artifact_type_facets&&Object.keys(e.artifact_type_facets).length?e.artifact_type_facets:e.artifact_facets,P=(N==null?void 0:N.semantic_kind)||{},D=(N==null?void 0:N.render_kind)||{};for(const ne of n)C[ne]=Number(P[ne]||D[ne]||0);return C.audio=Number(P.audio||0),C.other=Number(P.other||0)+Number(P.artifact||0)+Number(P.binary||0)+Number(P["(none)"]||0),C},[e.artifact_facets,e.artifact_type_facets]),x=C=>{const N=new Set(o);N.has(C)?N.delete(C):N.add(C),e.on_type_filters_change(Array.from(N.values()))},S=m.useMemo(()=>{const C={waiting:[],running:[],failed:[],cancelled:[],completed:[],other:[]};for(const N of e.runs){const P=String(N.status||"").trim().toLowerCase();P==="waiting"?C.waiting.push(N):P==="running"?C.running.push(N):P==="failed"?C.failed.push(N):P==="cancelled"?C.cancelled.push(N):P==="completed"?C.completed.push(N):C.other.push(N)}return C},[e.runs]),j=t!=null&&t.run_id&&e.run_by_id[t.run_id]||null,E=e.artifact_run_filter?ji(e.run_by_id[e.artifact_run_filter],e.workflow_label_by_id):"",A=m.useMemo(()=>{var P;const C=new Set,N=((P=e.artifact_facets)==null?void 0:P.run_id)||{};for(const D of Object.keys(N))D&&D!=="(none)"&&C.add(D);for(const D of e.artifacts)D.run_id&&C.add(D.run_id);for(const D of e.active_runs)D.run_id&&C.add(String(D.run_id));return Array.from(C).map(D=>e.run_by_id[D]||{run_id:D,workflow_id:null,status:"",created_at:null,updated_at:null}).sort((D,ne)=>{const B=Pu(D.status)?0:1,z=Pu(ne.status)?0:1;if(B!==z)return B-z;const G=Cn(D.updated_at||D.created_at)??0;return(Cn(ne.updated_at||ne.created_at)??0)-G}).slice(0,160)},[e.artifacts,e.active_runs,e.run_by_id,e.artifact_facets]),L=C=>{e.on_artifact_run_filter_change(C),e.on_session_filter_change(""),e.on_scope_change(C?"run":"all")},O=C=>e.gateway_connected?Math.max(0,Number(C||0)).toLocaleString():"—",M=e.selected_run_id&&e.run_by_id[e.selected_run_id]||null,H=m.useMemo(()=>{const C=e.runtime_log_query.trim().toLowerCase(),N=e.runtime_ledger_log_items||[];return C?N.filter(P=>{var B,z;const D=P.record||{};return[P.cursor,D.run_id,D.node_id,D.status,(B=D.effect)==null?void 0:B.type,D.started_at,D.ended_at,Bs(((z=D.effect)==null?void 0:z.payload)??{},900),Bs(D.result??{},900)].join(" ").toLowerCase().includes(C)}):N},[e.runtime_ledger_log_items,e.runtime_log_query]),X=m.useMemo(()=>{const C=e.runtime_log_query.trim().toLowerCase(),N=Gx(e.runtime_ledger_log_items);return C?N.filter(P=>[P.provider,P.model,P.run_id,P.node_id,P.status,P.error,P.prompt_preview,P.response_preview,P.tokens.prompt,P.tokens.completion,P.tokens.total].join(" ").toLowerCase().includes(C)):N},[e.runtime_ledger_log_items,e.runtime_log_query]),Y=X.reduce((C,N)=>C+(Number(N.tokens.total)||0),0),Z=X.filter(C=>C.missing_response||C.error).length,re=m.useMemo(()=>{const C=e.runtime_log_query.trim().toLowerCase(),N=String(e.audit_log_text||"").replace(/\r\n/g,`
|
|
107
|
+
`).replace(/\r/g,`
|
|
108
|
+
`).split(`
|
|
109
|
+
`).filter(Boolean);return C?N.filter(P=>P.toLowerCase().includes(C)):N},[e.audit_log_text,e.runtime_log_query]),ie=e.runtime_log_source==="run_ledger"||e.runtime_log_source==="provider_calls",ue=e.runtime_log_source==="run_ledger"?"Selected Run Ledger":e.runtime_log_source==="provider_calls"?"Provider Calls":"Gateway HTTP Audit",F=e.runtime_log_source==="run_ledger"?"Runtime execution records for the selected workflow run.":e.runtime_log_source==="provider_calls"?"Model/provider call records extracted from the selected run ledger.":"Global Gateway HTTP/audit tail. This is system activity, not artifact provenance.";return s.jsxs("div",{className:"page runtime_page",children:[s.jsxs("section",{className:"runtime_header",children:[s.jsxs("div",{children:[s.jsx("div",{className:"run_hero_eyebrow",children:"System"}),s.jsx("h2",{children:e.tab==="activity"?"Activity monitor":e.tab==="artifacts"?"Artifact explorer":e.tab==="memory"?"Active memory":"Logs"}),s.jsxs("div",{className:"run_hero_meta",children:[s.jsx("span",{className:`status_pill ${e.gateway_connected?"ok":"warn"}`,children:e.gateway_connected?"gateway connected":"gateway offline"}),e.tab==="artifacts"&&e.artifact_run_filter?s.jsxs("span",{className:"chip muted",children:["filtered run ",s.jsx("span",{className:"mono",children:Lt(e.artifact_run_filter,18)})]}):null,e.session_id?s.jsxs("span",{className:"chip muted",children:["session ",s.jsx("span",{className:"mono",children:Lt(e.session_id,18)})]}):null]})]}),s.jsxs("div",{className:"metric_grid compact runtime_header_metrics",children:[s.jsxs("div",{className:"metric_tile",children:[s.jsx("span",{children:"Waiting"}),s.jsx("strong",{children:O(S.waiting.length)})]}),s.jsxs("div",{className:"metric_tile",children:[s.jsx("span",{children:"Running"}),s.jsx("strong",{children:O(S.running.length)})]}),s.jsxs("div",{className:"metric_tile",children:[s.jsx("span",{children:"Failed"}),s.jsx("strong",{children:O(S.failed.length)})]}),s.jsxs("div",{className:"metric_tile",children:[s.jsxs("span",{children:["Artifacts",u?" (filtered)":""]}),s.jsx("strong",{children:O(l)})]})]})]}),s.jsx("nav",{className:"runtime_mode_tabs",role:"tablist","aria-label":"System sections",children:["activity","artifacts","memory","logs"].map(C=>s.jsxs("button",{role:"tab","aria-selected":e.tab===C,className:`runtime_mode_tab ${e.tab===C?"active":""}`,onClick:()=>e.on_tab_change(C),children:[s.jsx(Qe,{name:C==="activity"?"history":C==="artifacts"?"download":C==="memory"?"agent":"terminal",size:14}),s.jsx("span",{children:C==="activity"?"Activity":C==="artifacts"?"Artifacts":C==="memory"?"Memory":"Logs"})]},C))}),e.gateway_connected?null:s.jsxs("div",{className:"runtime_offline_banner",role:"status",children:[s.jsxs("div",{children:[s.jsx("strong",{children:"Gateway offline"}),s.jsx("span",{children:"Activity, artifacts, memory, and logs are unavailable until the gateway reconnects."})]}),s.jsxs("div",{children:[s.jsx("button",{className:"btn primary",onClick:e.on_reconnect,children:"Reconnect"}),s.jsx("button",{className:"btn",onClick:e.on_open_settings,children:"Settings"})]})]}),e.error?s.jsx("div",{className:"warn_callout",children:e.error}):null,e.tab==="activity"?s.jsx(ZC,{gateway_connected:e.gateway_connected,runs:e.runs,artifacts:e.artifacts,selected_run_id:e.selected_run_id,workflow_label_by_id:e.workflow_label_by_id,on_select_run:e.on_select_run,on_open_run:e.on_open_run,on_open_ledger:e.on_open_ledger,on_refresh_runs:e.on_refresh_runs,on_reconnect:e.on_reconnect,on_open_logs:()=>e.on_tab_change("logs"),on_filter_artifacts:C=>{L(C),e.on_select_run(C),e.on_tab_change("artifacts")},on_filter_session_artifacts:C=>{C&&(e.on_artifact_run_filter_change(""),e.on_session_filter_change(C),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:C=>e.on_query_change(C.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:C=>{const N=C.target.value;N!=="run"&&e.on_artifact_run_filter_change(""),N==="session"?e.on_session_filter_change(e.session_id):e.on_session_filter_change(""),e.on_scope_change(N)},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:C=>e.on_group_by_change(C.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:C=>e.on_sort_by_change(C.target.value),children:[s.jsx("option",{value:"newest",children:"Newest"}),s.jsx("option",{value:"oldest",children:"Oldest"}),s.jsx("option",{value:"last_access",children:"Last accessed"}),s.jsx("option",{value:"turn",children:"Turn order"}),s.jsx("option",{value:"type",children:"Type"}),s.jsx("option",{value:"size_desc",children:"Largest"}),s.jsx("option",{value:"size_asc",children:"Smallest"})]})]}),s.jsxs("button",{className:"btn btn_icon",onClick:e.on_refresh_artifacts,disabled:!e.gateway_connected||e.loading,children:[s.jsx(Qe,{name:"refresh",size:14}),e.loading?"Loading…":"Refresh"]})]}),s.jsxs("div",{className:"artifact_filter_section",children:[s.jsxs("div",{className:"artifact_filter_label",children:["Type ",s.jsx("span",{className:"muted",children:"OR"})]}),s.jsxs("div",{className:"artifact_filter_chips",role:"group","aria-label":"Artifact type filters combine with OR",children:[n.map(C=>{const N=o.has(C),P=w[C]||0,D=TC(C);return s.jsxs("button",{type:"button","aria-pressed":N,"aria-label":`${N?"Remove":"Add"} ${D} artifact type filter. Type filters combine with OR.`,title:`${N?"Remove":"Add"} ${D}. Type filters combine with OR.`,className:`artifact_filter_chip ${N?"active":""}`,onClick:()=>x(C),children:[s.jsx("span",{children:D}),s.jsx("span",{className:"artifact_chip_count",children:e.gateway_connected?P.toLocaleString():"—"})]},C)}),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:i.map(C=>s.jsx("button",{type:"button","aria-pressed":e.date_filter===C.value,className:`artifact_filter_chip ${e.date_filter===C.value?"active":""}`,onClick:()=>e.on_date_filter_change(C.value),children:C.label},C.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:E||Lt(e.artifact_run_filter,18)}),".",s.jsx("button",{className:"btn",onClick:()=>L(""),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 ",Xl(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:A.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:()=>L(""),children:[s.jsx("strong",{children:"All artifacts"}),s.jsx("span",{children:e.gateway_connected?`${l.toLocaleString()} match${l===1?"":"es"}`:"counts unavailable"})]}),A.map(C=>{const N=String(C.run_id||"").trim(),P=N===e.artifact_run_filter||N===(t==null?void 0:t.run_id);return s.jsxs("button",{className:`artifact_filter_run ${P?"selected":""}`,onClick:()=>L(N),title:N,children:[s.jsx("strong",{children:ji(C,e.workflow_label_by_id)}),s.jsx("span",{className:"mono",children:Lt(N,15)}),s.jsx("span",{children:oc(C)})]},N)})]})]}),s.jsxs("section",{className:"pane runtime_artifact_browser",children:[s.jsxs("div",{className:"pane_header artifact_browser_header",children:[s.jsx("span",{className:"pane_title",children:"Artifacts"}),s.jsx("span",{className:"pane_count",children:l?`${p.toLocaleString()}-${y.toLocaleString()} of ${l.toLocaleString()}`:"0 items"}),s.jsx("div",{className:"pane_spacer"}),f>1?s.jsxs("div",{className:"artifact_pagination","aria-label":"Artifact pages",children:[s.jsx("button",{className:"btn",onClick:()=>e.on_artifact_page_change(0),disabled:_<=0,children:"First"}),s.jsx("button",{className:"btn",onClick:()=>e.on_artifact_page_change(_-1),disabled:_<=0,children:"Prev"}),s.jsxs("span",{className:"muted artifact_page_label",children:["Page ",(_+1).toLocaleString()," / ",f.toLocaleString()]}),s.jsx("button",{className:"btn",onClick:()=>e.on_artifact_page_change(_+1),disabled:_>=f-1,children:"Next"}),s.jsx("button",{className:"btn",onClick:()=>e.on_artifact_page_change(f-1),disabled:_>=f-1,children:"Last"})]}):null]}),s.jsxs("div",{className:"pane_body scroll artifact_browser_body",children:[e.artifact_groups.length?null:s.jsx("div",{className:"empty_state_inline",children:e.gateway_connected?"No artifacts match the current filters.":"Gateway offline. Artifact inventory cannot be loaded until the connection is restored."}),s.jsx("div",{className:"artifact_group_list",children:e.artifact_groups.map(C=>s.jsxs("section",{className:"artifact_group",children:[s.jsxs("div",{className:"artifact_group_header",children:[s.jsx("span",{children:C.key}),s.jsx("span",{className:"artifact_group_count",children:C.items.length})]}),C.items.map(N=>{var z;const P=N.run_id&&e.run_by_id[N.run_id]||null,D=P?ji(P,e.workflow_label_by_id):Ag(N),ne=ew(N),B=Number(((z=N.access)==null?void 0:z.access_count)||0)||0;return s.jsxs("button",{className:`artifact_row ${(t==null?void 0:t.artifact_id)===N.artifact_id?"selected":""}`,onClick:()=>{e.on_select_artifact(N.artifact_id),N.run_id&&e.on_select_run(N.run_id)},title:N.artifact_id,children:[s.jsx(nw,{artifact:N,size:18}),s.jsxs("div",{className:"artifact_row_main",children:[s.jsxs("div",{className:"artifact_row_title",children:[s.jsx("strong",{children:Qy(Em(N,e.run_by_id,e.workflow_label_by_id))}),s.jsx("span",{className:"artifact_type_badge",children:Mu(N)}),N.render_kind&&N.render_kind!==N.semantic_kind?s.jsx("span",{className:"artifact_type_badge muted",children:N.render_kind}):null,N.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"})," ",LC(N)]}),s.jsxs("span",{children:[s.jsx("b",{children:"Size"})," ",Xl(N.size_bytes)]}),s.jsxs("span",{children:[s.jsx("b",{children:"Last seen"})," ",Zy(N)]}),B?s.jsxs("span",{children:[s.jsx("b",{children:"Accesses"})," ",B.toLocaleString()]}):null,ne?s.jsxs("span",{children:[s.jsx("b",{children:"Media"})," ",ne]}):null,N.content_type?s.jsxs("span",{children:[s.jsx("b",{children:"MIME"})," ",N.content_type]}):null]}),s.jsxs("div",{className:"artifact_row_facts secondary",children:[D?s.jsxs("span",{children:[s.jsx("b",{children:"Workflow"})," ",D]}):null,N.run_id?s.jsxs("span",{className:"mono",children:[s.jsx("b",{children:"Run"})," ",Lt(N.run_id,13)]}):null,s.jsxs("span",{children:[s.jsx("b",{children:"Turn"})," ",Wp(N)]}),Tu(N)?s.jsxs("span",{className:"mono",children:[s.jsx("b",{children:"Node"})," ",Tu(N)]}):null,bf(N)?s.jsxs("span",{children:[s.jsx("b",{children:"Source"})," ",bf(N)]}):null]}),s.jsxs("div",{className:"artifact_row_facts tertiary",children:[s.jsxs("span",{className:"mono",children:[s.jsx("b",{children:"ID"})," ",Lt(N.artifact_id,22)]}),s.jsxs("span",{children:[s.jsx("b",{children:"Provenance"})," ",Jy(N)]})]}),tw(N)?s.jsx("div",{className:"artifact_row_path mono",children:tw(N)}):null]})]},N.artifact_id)})]},C.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?qp(t,e.run_by_id,e.workflow_label_by_id,e.embedded_preview.text):qp(t,e.run_by_id,e.workflow_label_by_id)}):null]}),t?s.jsxs(s.Fragment,{children:[(()=>{var z,G,T,Q,K,J,oe;const C=IC(t),N=Hx(t),P=ew(t),D=Number(((z=t.access)==null?void 0:z.access_count)||0)||0,ne=hn((G=t.links)==null?void 0:G.provider_trace,(T=t.links)==null?void 0:T.provider_trace_url,(Q=t.links)==null?void 0:Q.provider_trace_id),B=hn((K=t.links)==null?void 0:K.audit,(J=t.links)==null?void 0:J.audit_tail,(oe=t.links)==null?void 0:oe.audit_url);return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"artifact_detail_header",children:[s.jsx(nw,{artifact:t,size:22}),s.jsxs("div",{children:[s.jsx("div",{className:"artifact_detail_title",children:Qy(Em(t,e.run_by_id,e.workflow_label_by_id))}),s.jsxs("div",{className:"artifact_detail_subtitle",children:[Mu(t)," • ",t.render_kind||e.embedded_preview.render_kind||t.modality||"artifact"," • ",t.content_type||"unknown MIME"," • ",Xl(t.size_bytes),t.legacy_inferred?" • legacy inferred":""]})]})]}),s.jsx(qC,{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:Mu(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:Ca(t.created_at)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Size"}),s.jsx("strong",{children:Xl(t.size_bytes)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Last seen"}),s.jsx("strong",{children:Zy(t)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Accesses"}),s.jsx("strong",{children:D?D.toLocaleString():"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Run"}),s.jsx("strong",{className:"mono",children:t.run_id?Lt(t.run_id,24):"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Workflow"}),s.jsx("strong",{children:j?ji(j,e.workflow_label_by_id):"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Turn"}),s.jsx("strong",{children:Wp(t)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Node"}),s.jsx("strong",{className:"mono",children:Tu(t)||"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Provider/model"}),s.jsx("strong",{children:N||"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Media facts"}),s.jsx("strong",{children:P||"—"})]}),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:Jy(t)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Artifact id"}),s.jsx("strong",{className:"mono",children:Lt(t.artifact_id,30)})]}),t.sha256?s.jsxs("div",{children:[s.jsx("span",{children:"sha256"}),s.jsx("strong",{className:"mono",children:Lt(t.sha256,30)})]}):null]}),C?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:C})]}):s.jsxs("div",{className:"artifact_provenance_panel muted",children:[s.jsx("div",{className:"artifact_filter_label",children:"Generation prompt / input"}),s.jsx("div",{className:"artifact_prompt_text",children:"Generation prompt not recorded by the runtime artifact descriptor."})]}),Object.keys(t.generation||{}).length||Object.keys(t.producer||{}).length?s.jsxs("details",{className:"runtime_raw_details",children:[s.jsx("summary",{className:"mono muted",children:"Generation and producer metadata"}),s.jsx(fr,{value:{generation:t.generation,producer:t.producer,source_refs:t.source_refs},collapseAfterDepth:3,showCopy:!0})]}):null,t.source_path?s.jsx("div",{className:"artifact_detail_path mono",children:t.source_path}):null,s.jsxs("div",{className:"runtime_detail_actions",children:[s.jsx("button",{className:"btn primary",onClick:()=>e.on_preview_artifact(t),disabled:!t.run_id,children:e.embedded_preview.render_kind==="html"?"Open as web page":"Open full preview"}),s.jsx("button",{className:"btn",onClick:()=>e.on_download_artifact(t),disabled:!t.run_id,children:"Download"}),s.jsx("button",{className:"btn",onClick:()=>L(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:()=>{ne&&window.open(ne,"_blank","noopener,noreferrer")},disabled:!ne,children:"Open provider trace"}),s.jsx("button",{className:"btn",onClick:()=>{B?window.open(B,"_blank","noopener,noreferrer"):e.on_tab_change("logs")},disabled:!B&&!t.audit_available,children:"Open audit trail"}),s.jsx("button",{className:"btn",onClick:()=>void ic(t.artifact_id),disabled:!t.artifact_id,children:"Copy artifact id"})]})]})})(),s.jsxs("details",{className:"runtime_raw_details",children:[s.jsx("summary",{className:"mono muted",children:"Raw metadata"}),s.jsx(fr,{value:t.raw,collapseAfterDepth:3,showCopy:!0})]})]}):s.jsx("div",{className:"empty_state_inline",children:"Select an artifact to inspect metadata, preview, or download content."})]})})]})]}):null,e.tab==="logs"?s.jsxs("section",{className:"overview_panel runtime_logs_panel",children:[s.jsxs("div",{className:"overview_panel_header",children:[s.jsxs("div",{children:[s.jsx("h3",{children:ue}),s.jsx("div",{className:"mono muted",children:F})]}),s.jsxs("div",{className:"actions",style:{marginTop:0},children:[ie&&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:()=>{ie?e.on_refresh_runtime_ledger(e.selected_run_id):e.on_refresh_audit()},disabled:ie?e.runtime_ledger_log_loading:e.audit_log_loading,children:[s.jsx(Qe,{name:"refresh",size:14}),ie?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:C=>e.on_runtime_log_query_change(C.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:M?ji(M,e.workflow_label_by_id):e.selected_run_id?Lt(e.selected_run_id,24):"No run selected"}),e.selected_run_id?s.jsx("em",{className:"mono",children:Lt(e.selected_run_id,34)}):null]}),s.jsxs("div",{children:[s.jsx("span",{children:"Session"}),s.jsx("strong",{className:"mono",children:M!=null&&M.session_id?Lt(String(M.session_id),28):e.session_id?Lt(e.session_id,28):"—"})]}),s.jsxs("div",{className:"runtime_log_context_actions",children:[s.jsx("button",{className:"btn",onClick:()=>e.on_open_run(e.selected_run_id),disabled:!e.selected_run_id,children:"Open Observe"}),s.jsx("button",{className:"btn",onClick:()=>L(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&&!H.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:H.map(C=>{var K,J;const N=C.record||{},P=String(((K=N==null?void 0:N.effect)==null?void 0:K.type)||"").trim(),D=String((N==null?void 0:N.status)||"").trim(),ne=String((N==null?void 0:N.node_id)||"").trim(),B=hn(N==null?void 0:N.ended_at,N==null?void 0:N.started_at,N==null?void 0:N.ts),z=to(N),G=Vx(N),T=P?ht(Bs(((J=N==null?void 0:N.effect)==null?void 0:J.payload)??{},1200),{max_chars:1200,max_lines:6}):"",Q=Df(N)||(z?`Waiting for ${String(z.reason||"input")}`:"")||((N==null?void 0:N.result)!==void 0?Bs(N.result,700):"");return s.jsxs("article",{className:`runtime_log_event ${pl(D)}`,children:[s.jsxs("div",{className:"runtime_log_event_header",children:[s.jsxs("span",{className:"mono",children:["#",C.cursor]}),s.jsx(gl,{status:D||"record"}),P?s.jsx("span",{className:"chip mono muted",children:P}):null,ne?s.jsx("strong",{className:"mono",children:ne}):null,B?s.jsx("span",{className:"mono muted",children:Ca(B)}):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||dm(N),T&&T!=="{}"?T:""].filter(Boolean).join(`
|
|
110
|
+
`)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Outcome"}),s.jsx("p",{children:ht(Q||"—",{max_chars:1200,max_lines:6})})]})]}),s.jsxs("details",{className:"runtime_raw_details",children:[s.jsx("summary",{className:"mono muted",children:"Raw ledger record"}),s.jsx(fr,{value:N,collapseAfterDepth:3,showCopy:!0})]})]},`${e.selected_run_id}:${C.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:M?ji(M,e.workflow_label_by_id):e.selected_run_id?Lt(e.selected_run_id,24):"No run selected"}),e.selected_run_id?s.jsx("em",{className:"mono",children:Lt(e.selected_run_id,34)}):null]}),s.jsxs("div",{children:[s.jsx("span",{children:"Provider calls"}),s.jsx("strong",{children:X.length.toLocaleString()}),s.jsx("em",{className:"mono",children:Y?`${Y.toLocaleString()} tokens`:"tokens not recorded"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Issues"}),s.jsx("strong",{children:Z.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&&!X.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:X.map(C=>s.jsxs("article",{className:`provider_activity ${C.error||C.missing_response?"danger":""}`,children:[s.jsxs("div",{className:"provider_activity_header",children:[s.jsxs("div",{children:[s.jsx("h4",{children:[C.provider||"provider unknown",C.model||"model unknown"].join(" / ")}),s.jsxs("div",{className:"timeline_subtitle",children:[C.node_id?s.jsx("span",{className:"mono",children:C.node_id}):null,C.run_id?s.jsx("span",{className:"mono",children:Lt(C.run_id,16)}):null,s.jsx("span",{children:kg(C.duration_ms)}),C.status?s.jsx(gl,{status:C.status}):null]})]}),s.jsxs("div",{className:"provider_tokens mono",children:[C.tokens.total?C.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:C.prompt_preview||"No prompt payload captured"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Response / error"}),s.jsx("p",{children:C.response_preview||C.error||"No response captured"})]})]}),s.jsxs("details",{className:"runtime_raw_details",children:[s.jsx("summary",{className:"mono muted",children:"Raw provider ledger record"}),s.jsx(fr,{value:C.raw,collapseAfterDepth:3,showCopy:!0})]})]},C.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(`
|
|
111
|
+
`):"(audit tail not loaded or no lines match search)"})]})]}):null]})}const Kh=30;function e2(e){const[t,n]=m.useState(""),i=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:[i.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)"}),i.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:i.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 iw(e,t,n){if(xf(e)==="automation"){const i=String(e.automation_id||e.run_id||"").trim();return n[i]||"Automation"}return ji(e,t)}function ow(e){const t=xf(e.run);return t?s.jsx("span",{className:"chip scheduled run_tree_tag","data-tag":t,children:Tx(e.run)}):null}function t2(e){const t=e.selected_run_id.trim(),n=e.root_run_id.trim()||t,i=e.sections.reduce((o,l)=>o+l.rows.reduce((u,c)=>{const f=[c.run,...c.children];return u+f.filter(_=>Pu(_.status)).length},0),0);return s.jsxs("aside",{className:"observatory_sidebar pane",children:[s.jsxs("div",{className:"run_nav_header pane_header",children:[s.jsx("span",{className:"pane_title",children:"Runs"}),s.jsxs("span",{className:"pane_count",children:[e.total_runs.toLocaleString()," runs • ",i.toLocaleString()," active"]}),s.jsx("span",{className:"pane_spacer"}),s.jsxs("button",{className:"btn btn_icon",onClick:e.on_refresh,disabled:e.loading,title:"Refresh workflow runs",children:[s.jsx(Qe,{name:"refresh",size:14}),e.loading?"…":""]})]}),s.jsxs("div",{className:"run_nav_controls",children:[s.jsx("input",{value:e.search,onChange:o=>e.on_search(o.target.value),placeholder:"Search runs, sessions, workflows"}),s.jsxs("div",{className:"run_nav_filter_row",children:[s.jsx("div",{className:"seg_toggle run_nav_segments",children:["active","waiting","terminal","failed","all"].map(o=>s.jsx("button",{className:`seg_btn ${e.filter===o?"active":""}`,onClick:()=>e.on_filter(o),children:o},o))}),s.jsxs("select",{className:"seg_select",value:e.group_by,onChange:o=>e.on_group_by(o.target.value),title:"Group workflow runs",children:[s.jsx("option",{value:"status",children:"Group by status"}),s.jsx("option",{value:"workflow",children:"Group by workflow"}),s.jsx("option",{value:"session",children:"Group by session"})]})]})]}),s.jsxs("div",{className:"run_tree",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(o=>s.jsxs("section",{className:"run_tree_section",children:[s.jsxs("div",{className:"run_tree_section_header",children:[s.jsx("span",{children:o.label}),s.jsx("span",{className:"mono",children:o.rows.length})]}),o.rows.map(l=>{const u=l.run,c=String(u.run_id||"").trim(),f=c===t;return s.jsxs("div",{className:"run_tree_group",children:[s.jsxs("button",{className:`run_tree_item ${f?"selected":""} ${c===n?"root_context":""}`,onClick:()=>e.on_select(c,c),title:c,children:[s.jsxs("div",{className:"run_tree_item_top",children:[s.jsx("span",{className:"run_tree_label",children:iw(u,e.workflow_label_by_id,e.automation_titles)}),s.jsx(ow,{run:u}),u.status?s.jsx(gl,{status:Nm(u)}):null]}),s.jsxs("div",{className:"run_tree_meta",children:[s.jsx("span",{className:"mono",children:Lt(c,13)}),s.jsx("span",{children:Jl(u)?Sa(Jl(u)):"no start"}),s.jsx("span",{children:oc(u)})]})]}),l.children.length?s.jsx("div",{className:"run_tree_children",children:l.children.map(_=>{const p=String(_.run_id||"").trim();return s.jsxs("button",{className:`run_tree_item run_tree_child ${p===t?"selected":""}`,onClick:()=>e.on_select(p,c),title:p,children:[s.jsxs("div",{className:"run_tree_item_top",children:[s.jsx("span",{className:"run_tree_label",children:iw(_,e.workflow_label_by_id,e.automation_titles)}),s.jsx(ow,{run:_}),s.jsx(gl,{status:Nm(_)})]}),s.jsxs("div",{className:"run_tree_meta",children:[s.jsx("span",{className:"mono",children:Lt(p,13)}),s.jsx("span",{children:Jl(_)?Sa(Jl(_)):"child"}),s.jsx("span",{children:oc(_)})]})]},p)})}):null]},c)})]},o.key))]})]})}function aw(){return s.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:s.jsx("path",{d:"M4 20h16a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.7-.9L9.2 3.9A2 2 0 0 0 7.5 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z"})})}function n2(e){var E,A,L,O,M,H,X;const t=e.run_id.trim(),[n,i]=m.useState(!1);if(!t)return s.jsx("div",{className:"run_overview",children:s.jsx("div",{className:"empty_state_inline",style:{padding:"48px 24px",textAlign:"center"},children:"Select a run on the left to inspect it — or start one from Launch."})});const o=ji(e.run,e.workflow_label_by_id),l=Jl(e.run)||String(((E=e.run_state)==null?void 0:E.started_at)||((A=e.run_state)==null?void 0:A.created_at)||"").trim(),u=Lx(e.run)||(Ci(e.status_label)?String(((L=e.run_state)==null?void 0:L.updated_at)||"").trim():""),c=e.run?oc(e.run):l?kg((Cn(u)??Date.now())-(Cn(l)??Date.now())):"—",f=e.provider_activities.length,_=e.provider_activities.reduce((Y,Z)=>Y+(Number(Z.tokens.total)||0),0),p=e.provider_activities.filter(Y=>Y.missing_response||Y.error).length,y=String(((O=e.latest_summary)==null?void 0:O.text)||"").trim(),w=e.wait_state,x=Ci(e.status_label),S=Cm(e.run)||String(((M=e.run_state)==null?void 0:M.error)||"").trim();let j="";for(let Y=e.records.length-1;Y>=0;Y--){const Z=Df((H=e.records[Y])==null?void 0:H.record);if(Z){j=Z;break}}return s.jsxs("div",{className:"run_overview",children:[s.jsxs("section",{className:"run_hero run_hero_line",children:[s.jsx("h2",{className:"run_hero_title",title:o,children:o}),s.jsx(gl,{status:e.status_label}),t?s.jsx("span",{className:"chip mono muted",title:t,children:Lt(t,18)}):null,e.root_run_id&&e.root_run_id!==t?s.jsxs("span",{className:"chip mono muted",title:e.root_run_id,children:["root ",Lt(e.root_run_id,12)]}):null,s.jsx("span",{className:"run_hero_spacer"}),e.workspace_root?s.jsxs("button",{className:"btn btn_icon",onClick:e.on_reveal_workspace,title:`Open the run's workspace folder
|
|
112
|
+
${e.workspace_root}`,children:[s.jsx(aw,{}),"Folder"]}):null,s.jsx("button",{className:"btn",onClick:e.on_generate_summary,disabled:!t||e.summary_generating,children:e.summary_generating?"Summarizing…":y?"Refresh summary":"Summarize"}),s.jsx("button",{className:"btn",onClick:e.on_open_runtime,title:"Open this run's artifacts in the System explorer",children:"Run artifacts"})]}),x?s.jsxs("section",{className:"overview_panel",children:[s.jsxs("div",{className:"overview_panel_header",children:[s.jsx("h3",{children:"Outcome"}),s.jsx("span",{className:`chip mono ${pl(e.status_label)}`,children:e.status_label||(S?"failed":"completed")})]}),S?s.jsx("div",{className:"error_callout",children:S}):null,j?s.jsx(Ni,{text:ht(j,{max_chars:4e3,max_lines:60})}):null,!S&&!j?s.jsx("div",{className:"empty_state_inline",children:"No final text output was recorded for this run — produced files, if any, live under Run artifacts (above)."}):null]}):null,(()=>{const Y=Array.isArray(e.run_artifacts)?e.run_artifacts:[],Z=C=>{const N=String((C!=null&&C.tags&&typeof C.tags=="object"?C.tags.source:"")||"").trim();return N==="run_store_offload"||N==="node_trace_offload"},re=C=>{const N=C!=null&&C.tags&&typeof C.tags=="object"?C.tags:{},P=String((C==null?void 0:C.filename)||N.filename||"").trim();if(P)return P;const D=String(N.path||(C==null?void 0:C.source_path)||"").trim();return D?D.split("/").pop()||D:String((C==null?void 0:C.title)||"").trim()||String((C==null?void 0:C.artifact_id)||"").slice(0,14)},ie=C=>{var N;return s.jsxs("div",{className:"run_artifact_row",children:[s.jsx("span",{className:"run_artifact_name",title:String(((N=C==null?void 0:C.tags)==null?void 0:N.path)||(C==null?void 0:C.source_path)||(C==null?void 0:C.artifact_id)||""),children:re(C)}),s.jsx("span",{className:"chip mono muted",children:String((C==null?void 0:C.content_type)||"?").replace(/^application\//,"").replace(/^text\//,"")}),s.jsx("span",{className:"run_artifact_size",children:typeof(C==null?void 0:C.size_bytes)=="number"?`${(C.size_bytes/1024).toFixed(C.size_bytes>1e5?0:1)} kB`:""}),s.jsxs("span",{className:"run_artifact_actions",children:[s.jsx("button",{className:"btn",onClick:()=>e.on_preview_run_artifact(C),children:"Preview"}),s.jsx("button",{className:"btn",onClick:()=>e.on_download_run_artifact(C),children:"Download"})]})]},String((C==null?void 0:C.artifact_id)||Math.random()))},ue=Y.filter(C=>!Z(C)),F=Y.filter(Z);return s.jsxs("section",{className:"overview_panel",children:[s.jsxs("div",{className:"overview_panel_header",children:[s.jsx("h3",{children:"Artifacts"}),s.jsx("span",{className:"mono muted",children:Y.length?Y.length.toLocaleString():""}),e.workspace_root?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"pane_spacer"}),s.jsxs("button",{className:"btn btn_icon",onClick:e.on_reveal_workspace,title:`Open the run's workspace folder
|
|
113
|
+
${e.workspace_root}`,children:[s.jsx(aw,{}),"Workspace"]})]}):null]}),e.run_artifacts_error?s.jsx("div",{className:"warn_callout",children:e.run_artifacts_error}):null,e.run_artifacts_loading&&!Y.length?s.jsx("div",{className:"empty_state_inline",children:"Loading artifacts…"}):null,!e.run_artifacts_loading&&!Y.length&&!e.run_artifacts_error?s.jsxs("div",{className:"empty_state_inline",children:["The runtime recorded no durable artifacts for this run.",e.workspace_root?" Files written to the workspace folder (if any) are reachable via the Folder button.":""]}):null,ue.length?s.jsx("div",{className:"run_artifact_list",children:ue.map(ie)}):null,!ue.length&&Y.length?s.jsxs("div",{className:"empty_state_inline",children:["No file products — this run's durable artifacts are internal state offloads (below).",e.workspace_root?" Report files written to the workspace are reachable via the Folder button.":""]}):null,F.length?s.jsxs("details",{className:"runtime_raw_details",children:[s.jsxs("summary",{className:"muted",children:["Internal state offloads (",F.length,")"]}),s.jsx("div",{className:"run_artifact_list",children:F.map(ie)})]}):null]})})(),s.jsxs("div",{className:"metric_grid",children:[s.jsxs("div",{className:"metric_tile",children:[s.jsx("span",{children:"Started"}),s.jsx("strong",{children:Ca(l)})]}),s.jsxs("div",{className:"metric_tile",children:[s.jsx("span",{children:u?"Finished":"Running for"}),s.jsx("strong",{children:u?Ca(u):c})]}),s.jsxs("div",{className:"metric_tile",children:[s.jsx("span",{children:"Total duration"}),s.jsx("strong",{children:c})]}),s.jsxs("div",{className:"metric_tile",children:[s.jsx("span",{children:"Ledger"}),s.jsx("strong",{children:(e.records_count+e.child_records_count).toLocaleString()})]}),s.jsxs("div",{className:"metric_tile",children:[s.jsx("span",{children:"Subworkflows"}),s.jsx("strong",{children:e.subrun_ids.length.toLocaleString()})]}),s.jsxs("div",{className:"metric_tile",children:[s.jsx("span",{children:"Provider calls"}),s.jsx("strong",{children:f.toLocaleString()})]}),s.jsxs("div",{className:"metric_tile",children:[s.jsx("span",{children:"Tokens"}),s.jsx("strong",{children:_?_.toLocaleString():"—"})]}),s.jsxs("div",{className:"metric_tile",children:[s.jsx("span",{children:"Assets"}),s.jsx("strong",{children:e.attachments_count.toLocaleString()})]})]}),s.jsxs("div",{className:"overview_columns",children:[s.jsxs("section",{className:"overview_panel",children:[s.jsxs("div",{className:"overview_panel_header",children:[s.jsx("h3",{children:x?"What happened":"What is happening"}),w?s.jsx("span",{className:"chip mono info",children:"waiting"}):null]}),w?s.jsxs("div",{className:"overview_fact_list",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Reason"}),s.jsx("strong",{children:String(w.reason||"unknown")})]}),w.wait_key?s.jsxs("div",{children:[s.jsx("span",{children:"Wait key"}),s.jsx("strong",{className:"mono",children:Lt(String(w.wait_key),34)})]}):null,(X=w==null?void 0:w.details)!=null&&X.sub_run_id?s.jsxs("div",{children:[s.jsx("span",{children:"Subworkflow"}),s.jsx("strong",{className:"mono",children:Lt(String(w.details.sub_run_id),24)})]}):null,w.prompt?s.jsxs("div",{children:[s.jsx("span",{children:"Prompt"}),s.jsx("strong",{children:ht(String(w.prompt),{max_chars:260,max_lines:3})})]}):null,e.on_answer_wait&&w.wait_key&&String(w.reason||"")==="user"?s.jsx("div",{className:"overview_fact_actions",children:s.jsx("button",{className:"btn primary",onClick:e.on_answer_wait,children:"Review & answer…"})}):null]}):(()=>{var C;const Y=e.timeline_items.length?e.timeline_items[e.timeline_items.length-1]:null,Z=(Y==null?void 0:Y.record)||null,re=String((Z==null?void 0:Z.node_id)||"").trim(),ie=re&&e.node_index?e.node_index[re]:null,ue=String((ie==null?void 0:ie.label)||re||"").trim(),F=String(((C=Z==null?void 0:Z.effect)==null?void 0:C.type)||"").trim();return ue||F?s.jsxs("div",{className:"overview_fact_list",children:[ue?s.jsxs("div",{children:[s.jsx("span",{children:x?"Ended at":"Last step"}),s.jsx("strong",{children:ue})]}):null,F?s.jsxs("div",{children:[s.jsx("span",{children:"Effect"}),s.jsx("strong",{className:"mono",children:F})]}):null]}):s.jsx("div",{className:"empty_state_inline",children:x?"Nothing in flight — the run is finished.":"No active wait is reported for this run."})})(),p?s.jsxs("div",{className:"warn_callout",children:[p," provider call(s) have missing responses or errors."]}):null]}),s.jsxs("section",{className:"overview_panel",children:[s.jsxs("div",{className:"overview_panel_header",children:[s.jsx("h3",{children:"Summary"}),e.latest_summary?s.jsx("span",{className:"chip mono ok",children:"saved"}):s.jsx("span",{className:"chip mono muted",children:"none"})]}),e.summary_error?s.jsx("div",{className:"warn_callout",children:e.summary_error}):null,y?s.jsx(Ni,{text:y}):s.jsx("div",{className:"empty_state_inline",children:"Generate a grounded summary from the root run and its subflows."})]})]}),e.subrun_ids.length?s.jsxs("section",{className:"overview_panel",children:[s.jsxs("div",{className:"overview_panel_header",children:[s.jsx("h3",{children:"Subworkflows"}),s.jsx("span",{className:"mono muted",children:e.subrun_ids.length})]}),s.jsx("div",{className:"subrun_chip_list",children:e.subrun_ids.map(Y=>s.jsx("button",{className:"subrun_chip mono",onClick:()=>e.on_open_subrun(Y),title:Y,children:Lt(Y,22)},Y))})]}):null,e.attachments.length||e.session_id?s.jsxs("section",{className:"overview_panel",children:[s.jsxs("div",{className:"overview_panel_header",children:[s.jsx("h3",{children:"Session files"}),s.jsx("span",{className:"mono muted",children:e.attachments.length?`${e.attachments.length} file${e.attachments.length===1?"":"s"}`:""}),s.jsx("button",{className:"btn btn_sm",onClick:e.on_refresh_attachments,disabled:e.attachments_loading||!e.session_id,children:e.attachments_loading?"Refreshing…":"Refresh"})]}),e.attachments_error?s.jsx("div",{className:"warn_callout",children:e.attachments_error}):null,e.attachments.length?s.jsx("div",{className:"produced_list",children:e.attachments.map(Y=>{const Z=String((Y==null?void 0:Y.artifact_id)||"").trim();if(!Z)return null;const re=Y!=null&&Y.tags&&typeof Y.tags=="object"?Y.tags:{},ie=String((re==null?void 0:re.path)||"").trim()?`@${String(re.path).trim()}`:String((re==null?void 0:re.filename)||"").trim()||Z,ue=typeof(Y==null?void 0:Y.size_bytes)=="number"?Number(Y.size_bytes):null,F=e.attachments_loading||!e.attachments_ready;return s.jsxs("div",{className:"produced_row",children:[s.jsx("span",{className:"produced_name mono",title:Z,children:ie}),s.jsx("span",{className:"mono muted",children:ue!==null?`${ue.toLocaleString()} B`:""}),s.jsxs("span",{className:"produced_actions",children:[s.jsx("button",{className:"btn btn_sm",onClick:()=>e.on_preview_attachment(Y),disabled:F,children:"Preview"}),s.jsx("button",{className:"btn btn_sm",onClick:()=>e.on_download_attachment(Y),disabled:F,children:"Download"})]})]},Z)})}):s.jsx("div",{className:"empty_state_inline",children:x?"No files were attached to this run's session.":"No files in this run's session yet."})]}):null,e.timeline_items.length?s.jsxs("section",{className:"overview_panel",children:[s.jsxs("div",{className:"overview_panel_header",children:[s.jsx("h3",{children:"Chronology"}),s.jsx("span",{className:"mono muted",children:n||e.timeline_items.length<=Kh?`${e.timeline_items.length} steps`:`last ${Kh} of ${e.timeline_items.length} steps`}),e.timeline_items.length>Kh?s.jsx("button",{className:"btn btn_sm",onClick:()=>i(Y=>!Y),children:n?"Show fewer":"Show all"}):null]}),s.jsx(s2,{items:n?e.timeline_items:e.timeline_items.slice(-Kh),node_index:e.node_index,workflow_label_by_id:e.workflow_label_by_id,on_copy:e.on_copy})]}):null]})}function s2(e){const t=n=>{var A,L;const i=n,o=n.record||{},l=String(((A=o==null?void 0:o.effect)==null?void 0:A.type)||i.effect_type||"").trim(),u=String((o==null?void 0:o.status)||i.status||"").trim(),c=String((o==null?void 0:o.node_id)||i.node_id||"").trim(),f=c&&e.node_index?e.node_index[c]:null,_=String((f==null?void 0:f.label)||c||i.title||"Step").trim(),p=to(o),y=(L=o==null?void 0:o.effect)==null?void 0:L.payload,w=o==null?void 0:o.result,x=Df(o),S=l?Bs(y??{},900):ht(String(i.preview||""),{max_chars:900,max_lines:8}),j=x||(p?`Waiting for ${String(p.reason||"input")}${p.wait_key?` (${Lt(String(p.wait_key),18)})`:""}`:"")||(w!==void 0?Bs(w,900):"");return{title:l==="llm_call"?"Model call":l==="tool_calls"?"Tool execution":l==="answer_user"?"User-facing response":l==="start_subworkflow"?"Subworkflow launched":l==="ask_user"?"User input requested":l||i.title||"Ledger event",subtitle:_,request:ht(S,{max_chars:900,max_lines:7}),outcome:ht(j,{max_chars:1100,max_lines:9}),cls:pl(u)}};return s.jsxs("div",{className:"human_timeline",children:[e.items.length?null:s.jsx("div",{className:"empty_state_inline",children:"No ledger records yet."}),e.items.map(n=>{const i=n.record||{},o=t(n),l=String(i.ended_at||i.started_at||n.ts||"").trim();return s.jsxs("article",{className:`timeline_event ${o.cls}`,children:[s.jsx("div",{className:"timeline_marker"}),s.jsxs("div",{className:"timeline_event_body",children:[s.jsxs("div",{className:"timeline_event_header",children:[s.jsxs("div",{children:[s.jsx("h3",{children:o.title}),s.jsxs("div",{className:"timeline_subtitle",children:[s.jsx("span",{children:o.subtitle}),n.run_id?s.jsx("span",{className:"mono",children:Lt(String(n.run_id),13)}):null]})]}),s.jsxs("div",{className:"timeline_time",children:[s.jsx("span",{children:Sa(l)}),s.jsx("span",{className:"mono",title:l,children:Ca(l)})]})]}),s.jsxs("div",{className:"timeline_payload_grid",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Requested"}),s.jsx("p",{className:"mono",children:o.request||"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Outcome"}),s.jsx("p",{children:o.outcome||"—"})]})]}),s.jsx("div",{className:"timeline_actions",children:s.jsxs("button",{className:"btn btn_icon",onClick:()=>e.on_copy(JSON.stringify(i,null,2)),children:[s.jsx(Qe,{name:"copy",size:14}),"JSON"]})})]})]},`${String(n.run_id||i.run_id||"")}:${n.cursor}`)})]})}function r2(e){const t=e.item,n=String(t.node_id||"").trim(),i=n&&e.node_index&&typeof e.node_index=="object"?e.node_index[n]:null,o=typeof(i==null?void 0:i.label)=="string"&&i.label.trim()?i.label.trim():n||t.title,l=typeof(i==null?void 0:i.type)=="string"&&i.type.trim()?i.type.trim():"",u=typeof(i==null?void 0:i.headerColor)=="string"&&i.headerColor.trim()?i.headerColor.trim():"",c=t.kind==="step"?o:t.title,f=u||(t.kind==="error"?"rgba(239, 68, 68, 0.85)":t.kind==="message"?"rgba(167, 139, 250, 0.85)":t.kind==="event"?"rgba(96, 165, 250, 0.85)":t.status==="waiting"?"rgba(96, 165, 250, 0.65)":t.status==="completed"?"rgba(34, 197, 94, 0.65)":"rgba(255, 255, 255, 0.14)"),_=String(t.status||"").trim(),p=_.toLowerCase(),y=pl(p),w=Df(t.data),x=!!(w&&w.trim()),S=Sa(t.ts);return s.jsxs("div",{className:`lc ${y}`,style:{"--lc-accent":f},children:[s.jsxs("div",{className:"lc_header",children:[s.jsx("span",{className:"lc_title",children:c}),s.jsxs("div",{className:"lc_header_right",children:[_?s.jsx("span",{className:`lc_status ${y}`,children:_}):null,s.jsx("span",{className:"lc_time",title:t.ts,children:S})]})]}),s.jsxs("div",{className:"lc_meta",children:[l?s.jsx("span",{className:"lc_chip",children:l}):null,t.effect_type?s.jsx("span",{className:"lc_chip",children:String(t.effect_type)}):null,t.cursor?s.jsxs("span",{className:"lc_chip",children:["#",t.cursor]}):null,t.run_id?s.jsx("span",{className:"lc_chip",children:Lt(String(t.run_id),10)}):null,t.kind!=="step"&&n?s.jsx("span",{className:"lc_chip",children:n}):null]}),t.preview?s.jsx("div",{className:"lc_preview",children:t.preview}):null,t.data?s.jsxs("div",{className:"lc_actions",children:[x?s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"lc_btn",onClick:e.on_toggle_response,children:e.response_open?"Fold Response":"Unfold Response"}),s.jsx("button",{className:"lc_btn",onClick:()=>e.on_copy(String(w||"")),children:"Copy Response"})]}):null,s.jsx("button",{className:"lc_btn",onClick:e.on_toggle,children:e.open?"Fold JSON":"Unfold JSON"}),s.jsx("button",{className:"lc_btn",onClick:()=>{try{e.on_copy(JSON.stringify(t.data,null,2))}catch{e.on_copy(String(t.data))}},children:"Copy JSON"})]}):null,e.response_open&&x?s.jsx("div",{className:"lc_body",children:s.jsx(Ni,{text:String(w||"")})}):null,e.open&&t.data?s.jsx("div",{className:"lc_body lc_body_json mono",children:s.jsx(fr,{value:t.data,collapseAfterDepth:3,showCopy:!1})}):null]})}class i2{constructor(){Gs(this,"_buffer","");Gs(this,"_current",{data_lines:[]})}push(t,n){for(this._buffer+=t;;){const i=this._buffer.indexOf(`
|
|
114
|
+
`);if(i===-1)return;const o=this._buffer.slice(0,i);this._buffer=this._buffer.slice(i+1);const l=o.endsWith("\r")?o.slice(0,-1):o;if(l.startsWith(":"))continue;if(l===""){if(this._current.data_lines.length>0||this._current.event||this._current.id){const _={id:this._current.id,event:this._current.event,data:this._current.data_lines.join(`
|
|
115
|
+
`)};n(_)}this._current={data_lines:[]};continue}const u=l.indexOf(":"),c=u===-1?l:l.slice(0,u),f=u===-1?"":l.slice(u+1).trimStart();if(c==="id"){this._current.id=f;continue}if(c==="event"){this._current.event=f;continue}if(c==="data"){this._current.data_lines.push(f);continue}}}}const Bt=Gv;function bi(e,t=3e4){const n=AbortSignal.timeout(t);if(!e)return n;const i=AbortSignal.any;return typeof i=="function"?i([e,n]):e}function Zx(){var t;const e={};try{const n=(t=document.cookie.split(";").map(i=>i.trim()).find(i=>i.startsWith("abstractobserver_gateway_csrf=")))==null?void 0:t.slice(30);n&&(e["X-AbstractObserver-CSRF"]=decodeURIComponent(n))}catch{}return e}function Pt(e){const t=(e||"").trim(),n={};return t&&(n.Authorization=`Bearer ${t}`),{...n,...Zx()}}async function Vn(e){try{const t=await e.text();return t!=null&&t.trim()?t.trim():`${e.status}`}catch{return`${e.status}`}}class o2 extends Error{constructor(n,i){super(i);Gs(this,"status");this.name="GatewayRequestError",this.status=n}}async function K_(e,t){let n="";try{n=(await e.text()).trim()}catch{n=""}let i=n;try{const o=JSON.parse(n),l=o&&typeof o=="object"?o.detail:void 0;typeof l=="string"&&l.trim()?i=l.trim():l&&typeof l=="object"&&typeof l.message=="string"&&l.message.trim()&&(i=l.message.trim())}catch{}return new o2(e.status,`${t} (HTTP ${e.status}): ${i||e.statusText||"no reason given"}`)}class Y_{constructor(t){Gs(this,"_cfg");Gs(this,"fetch_gateway",(t,n)=>fetch(Bt(this._cfg.base_url,t),{...n,headers:{...n==null?void 0:n.headers,...Pt(this._cfg.auth_token)}}));this._cfg={...t,base_url:(t.base_url||"").trim()}}async start_run(t,n,i){const o=String((i==null?void 0:i.bundle_id)||"").trim(),l=(i==null?void 0:i.session_id)===null||(i==null?void 0:i.session_id)===void 0?"":String(i.session_id||"").trim(),u=String(t||"").trim(),c=String((i==null?void 0:i.interface)||"").trim();if(u==="@default"&&(!c||o))throw new Error("start_run: flow_id '@default' needs `interface` and no bundle_id");const f={input_data:n||{}};o&&(f.bundle_id=o),u&&(f.flow_id=u),u==="@default"&&(f.interface=c),l&&(f.session_id=l);const _=await fetch(Bt(this._cfg.base_url,bt("runs/start")),{method:"POST",headers:{"Content-Type":"application/json",...Pt(this._cfg.auth_token)},body:JSON.stringify(f)});if(!_.ok)throw new Error(`start_run failed: ${_.status}`);const p=await _.json(),y=p==null?void 0:p.run_id;if(typeof y!="string"||!y)throw new Error("start_run: missing run_id");return y}async list_mcp_servers(){for(const t of[bt("mcp/servers"),bt("mcp"),bt("discovery/mcp")])try{const n=await fetch(Bt(this._cfg.base_url,t),{headers:{...Pt(this._cfg.auth_token)},signal:bi()});if(n.status===404||!n.ok)continue;const i=await n.json(),o=Array.isArray(i)?i:Array.isArray(i==null?void 0:i.servers)?i.servers:Array.isArray(i==null?void 0:i.items)?i.items:null;if(!o)continue;return o.map(l=>({name:String((l==null?void 0:l.name)||(l==null?void 0:l.id)||"").trim(),url:typeof(l==null?void 0:l.url)=="string"?l.url:void 0,description:typeof(l==null?void 0:l.description)=="string"?l.description:void 0,auth_required:typeof(l==null?void 0:l.auth_required)=="boolean"?l.auth_required:void 0})).filter(l=>l.name)}catch{return null}return null}async list_skills(){for(const t of[bt("skills"),bt("skills/registry")])try{const n=await fetch(Bt(this._cfg.base_url,t),{headers:{...Pt(this._cfg.auth_token)},signal:bi()});if(n.status===404||!n.ok)continue;const i=await n.json(),o=Array.isArray(i)?i:Array.isArray(i==null?void 0:i.skills)?i.skills:Array.isArray(i==null?void 0:i.items)?i.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(Bt(this._cfg.base_url,bt(`runs/${encodeURIComponent(t)}`)),{headers:{...Pt(this._cfg.auth_token)}});if(!n.ok)throw new Error(`get_run failed: ${await Vn(n)}`);return await n.json()}async get_run_history_bundle(t,n){const i=String(t||"").trim();if(!i)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=Bt(this._cfg.base_url,bt(`runs/${encodeURIComponent(i)}/history_bundle?${o.toString()}`)),u=await fetch(l,{headers:{...Pt(this._cfg.auth_token)}});if(!u.ok)throw new Error(`get_run_history_bundle failed: ${await Vn(u)}`);return await u.json()}async list_runs(t){const n=typeof(t==null?void 0:t.limit)=="number"?t.limit:50,i=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)),i&&c.set("status",i),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=Bt(this._cfg.base_url,bt(`runs?${c.toString()}`)),_=await fetch(f,{headers:{...Pt(this._cfg.auth_token)},signal:AbortSignal.timeout(3e4)});if(!_.ok)throw new Error(`list_runs failed: ${await Vn(_)}`);return await _.json()}async audit_log_tail(t){const n=typeof(t==null?void 0:t.max_bytes)=="number"?Math.max(1024,Math.min(4e5,Math.floor(t.max_bytes))):8e4,i=Bt(this._cfg.base_url,bt(`audit/tail?max_bytes=${encodeURIComponent(String(n))}`)),o=await fetch(i,{headers:{...Pt(this._cfg.auth_token)}});if(!o.ok)throw new Error(`audit_log_tail failed: ${await Vn(o)}`);return await o.json()}async gateway_about(){const t=await fetch(Bt(this._cfg.base_url,bt("about")),{headers:{...Pt(this._cfg.auth_token)},signal:bi(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 i=await fetch(Bt(this._cfg.base_url,bt(`runs/${encodeURIComponent(n)}/input_data`)),{headers:{...Pt(this._cfg.auth_token)}});if(!i.ok)throw new Error(`get_run_input_data failed: ${await Vn(i)}`);return await i.json()}async list_run_artifacts(t,n){const i=String(t||"").trim();if(!i)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=Bt(this._cfg.base_url,bt(`runs/${encodeURIComponent(i)}/artifacts?limit=${encodeURIComponent(String(o))}&offset=${encodeURIComponent(String(l))}`)),c=await fetch(u,{headers:{...Pt(this._cfg.auth_token)}});if(!c.ok)throw new Error(`list_run_artifacts failed: ${await Vn(c)}`);return await c.json()}async list_session_artifacts(t,n){const i=String(t||"").trim();if(!i)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=Bt(this._cfg.base_url,bt(`sessions/${encodeURIComponent(i)}/artifacts?limit=${encodeURIComponent(String(o))}&offset=${encodeURIComponent(String(l))}`)),c=await fetch(u,{headers:{...Pt(this._cfg.auth_token)}});if(!c.ok)throw new Error(`list_session_artifacts failed: ${await Vn(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 i=String((t==null?void 0:t.session_id)||"").trim(),o=String((t==null?void 0:t.run_id)||"").trim(),l=String((t==null?void 0:t.modality)||"").trim(),u=String((t==null?void 0:t.artifact_kind)||"").trim(),c=String((t==null?void 0:t.semantic_kind)||"").trim(),f=String((t==null?void 0:t.render_kind)||"").trim(),_=String((t==null?void 0:t.workflow_id)||"").trim(),p=String((t==null?void 0:t.node_id)||"").trim(),y=String((t==null?void 0:t.content_type)||"").trim(),w=String((t==null?void 0:t.query)||"").trim(),x=String((t==null?void 0:t.tags)||"").trim(),S=String((t==null?void 0:t.cursor)||"").trim(),j=String((t==null?void 0:t.order_by)||"").trim(),E=String((t==null?void 0:t.order)||"").trim(),A=String((t==null?void 0:t.created_after)||"").trim(),L=String((t==null?void 0:t.created_before)||"").trim(),O=typeof(t==null?void 0:t.limit)=="number"?t.limit:500,M=typeof(t==null?void 0:t.offset)=="number"?Math.max(0,Math.floor(t.offset)):0;i&&n.set("session_id",i),o&&n.set("run_id",o),l&&n.set("modality",l),u&&n.set("artifact_kind",u),c&&n.set("semantic_kind",c),f&&n.set("render_kind",f),_&&n.set("workflow_id",_),p&&n.set("node_id",p),y&&n.set("content_type",y),w&&n.set("query",w),x&&n.set("tags",x),S&&n.set("cursor",S),j&&n.set("order_by",j),E&&n.set("order",E),A&&n.set("created_after",A),L&&n.set("created_before",L),t!=null&&t.include_stats&&n.set("include_stats","true"),n.set("limit",String(O)),n.set("offset",String(M));const H=await fetch(Bt(this._cfg.base_url,bt(`artifacts/search?${n.toString()}`)),{headers:{...Pt(this._cfg.auth_token)}});if(!H.ok)throw new Error(`search_artifacts failed: ${await Vn(H)}`);return await H.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 i=await fetch(Bt(this._cfg.base_url,bt(`artifacts/stats?${n.toString()}`)),{headers:{...Pt(this._cfg.auth_token)}});if(!i.ok)throw new Error(`artifact_stats failed: ${await Vn(i)}`);return await i.json()}async download_run_artifact_content(t,n,i){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((i==null?void 0:i.access)||"").trim(),c=u?`?access=${encodeURIComponent(u)}`:"",f=Bt(this._cfg.base_url,bt(`runs/${encodeURIComponent(o)}/artifacts/${encodeURIComponent(l)}/content${c}`)),_=await fetch(f,{headers:{...Pt(this._cfg.auth_token)}});if(!_.ok)throw new Error(`download_run_artifact_content failed: ${await Vn(_)}`);return await _.blob()}async list_entities(){const t=await fetch(Bt(this._cfg.base_url,bt("entities")),{headers:{...Pt(this._cfg.auth_token)},signal:bi()});if(!t.ok)throw new Error(`list_entities failed: ${await Vn(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(Bt(this._cfg.base_url,bt("entities/spec/phases")),{headers:{...Pt(this._cfg.auth_token)},signal:bi()});if(!t.ok)throw new Error(`get_entity_phases_spec failed: ${await Vn(t)}`);return await t.json()}async get_entity_cognition(t){const n=await fetch(Bt(this._cfg.base_url,bt(`entities/${encodeURIComponent(t)}/cognition`)),{headers:{...Pt(this._cfg.auth_token)},signal:bi()});if(!n.ok)throw new Error(`get_entity_cognition failed: ${await Vn(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 i=await fetch(Bt(this._cfg.base_url,bt(`entities/${encodeURIComponent(n)}/card`)),{headers:{...Pt(this._cfg.auth_token)},signal:bi()});if(!i.ok)throw new Error(`get_entity_card failed: ${await Vn(i)}`);return await i.json()}async read_entity_diary_entry(t,n){const i=String(t||"").trim(),o=String(n||"").trim();if(!i||!o)throw new Error("read_entity_diary_entry: name and entry_id are required");const l=Bt(this._cfg.base_url,bt(`entities/${encodeURIComponent(i)}/diary/${encodeURIComponent(o)}?reason=${encodeURIComponent("observer board hint chip")}`)),u=await fetch(l,{headers:{...Pt(this._cfg.auth_token)},signal:bi()});if(!u.ok)throw new Error(`read_entity_diary_entry failed: ${await Vn(u)}`);return await u.json()}async get_ledger(t,n){const i=Number((n==null?void 0:n.after)||0),o=Number((n==null?void 0:n.limit)||0),l=Bt(this._cfg.base_url,bt(`runs/${encodeURIComponent(t)}/ledger?after=${encodeURIComponent(String(i))}&limit=${encodeURIComponent(String(o))}`)),u=await fetch(l,{headers:{...Pt(this._cfg.auth_token)},signal:bi(n==null?void 0:n.signal)});if(!u.ok)throw new Error(`get_ledger failed: ${u.status}`);const c=await u.json(),f=Array.isArray(c==null?void 0:c.items)?c.items:[],_=typeof(c==null?void 0:c.next_after)=="number"?c.next_after:i;return{items:f,next_after:_}}async get_ledger_batch(t){const n=Array.isArray(t==null?void 0:t.runs)?t.runs:[],i=Number((t==null?void 0:t.limit)||0),o=await fetch(Bt(this._cfg.base_url,bt("runs/ledger/batch")),{method:"POST",headers:{"Content-Type":"application/json",...Pt(this._cfg.auth_token)},body:JSON.stringify({runs:n,limit:i}),signal:bi()});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 i=String(t||"").trim();if(!i)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(Bt(this._cfg.base_url,bt(`runs/${encodeURIComponent(i)}/summary`)),{method:"POST",headers:{"Content-Type":"application/json",...Pt(this._cfg.auth_token)},body:JSON.stringify(o)});if(!c.ok)throw await K_(c,"The gateway could not summarize this run");return await c.json()}async run_chat(t,n){const i=String(t||"").trim();if(!i)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(Bt(this._cfg.base_url,bt(`runs/${encodeURIComponent(i)}/chat`)),{method:"POST",headers:{"Content-Type":"application/json",...Pt(this._cfg.auth_token)},body:JSON.stringify(o)});if(!c.ok)throw await K_(c,"The gateway could not answer");return await c.json()}async audio_transcribe(t,n){const i=String(t||"").trim();if(!i)throw new Error("audio_transcribe: run_id is required");const o=n==null?void 0:n.audio_artifact;if(!o||typeof o!="object")throw new Error("audio_transcribe: audio_artifact is required");if(!String(o.$artifact||"").trim())throw new Error("audio_transcribe: audio_artifact.$artifact is required");const u={audio_artifact:o},c=String((n==null?void 0:n.language)||"").trim();c&&(u.language=c);const f=String((n==null?void 0:n.request_id)||"").trim();f&&(u.request_id=f);const _=await fetch(Bt(this._cfg.base_url,bt(`runs/${encodeURIComponent(i)}/audio/transcribe`)),{method:"POST",headers:{"Content-Type":"application/json",...Pt(this._cfg.auth_token)},body:JSON.stringify(u)});if(!_.ok)throw new Error(`audio_transcribe failed: ${await Vn(_)}`);const p=await _.json(),y=String((p==null?void 0:p.text)||"");return{ok:!!(p!=null&&p.ok),run_id:String((p==null?void 0:p.run_id)||""),request_id:String((p==null?void 0:p.request_id)||""),text:y,transcript_artifact:p==null?void 0:p.transcript_artifact}}async voice_tts(t,n){const i=String(t||"").trim();if(!i)throw new Error("voice_tts: run_id is required");const o=String((n==null?void 0:n.text)||"").trim();if(!o)throw new Error("voice_tts: text is required");const l={text:o},u=String((n==null?void 0:n.voice)||"").trim();u&&(l.voice=u);const c=String((n==null?void 0:n.format)||"").trim();c&&(l.format=c);const f=String((n==null?void 0:n.request_id)||"").trim();f&&(l.request_id=f);const _=await fetch(Bt(this._cfg.base_url,bt(`runs/${encodeURIComponent(i)}/voice/tts`)),{method:"POST",headers:{"Content-Type":"application/json",...Pt(this._cfg.auth_token)},body:JSON.stringify(l)});if(!_.ok)throw new Error(`voice_tts failed: ${await Vn(_)}`);const p=await _.json();return{ok:!!(p!=null&&p.ok),run_id:String((p==null?void 0:p.run_id)||""),request_id:String((p==null?void 0:p.request_id)||""),audio_artifact:p==null?void 0:p.audio_artifact}}async save_chat_thread(t,n){const i=String(t||"").trim();if(!i)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(Bt(this._cfg.base_url,bt(`runs/${encodeURIComponent(i)}/chat_threads`)),{method:"POST",headers:{"Content-Type":"application/json",...Pt(this._cfg.auth_token)},body:JSON.stringify(o)});if(!f.ok)throw new Error(`save_chat_thread failed: ${await Vn(f)}`);return await f.json()}async list_bundles(){const t=await fetch(Bt(this._cfg.base_url,bt("bundles")),{headers:{...Pt(this._cfg.auth_token)},signal:bi()});if(!t.ok)throw new Error(`list_bundles failed: ${t.status}`);return await t.json()}async reload_bundles(){const t=await fetch(Bt(this._cfg.base_url,bt("bundles/reload")),{method:"POST",headers:{...Pt(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 i=(n==null?void 0:n.overwrite)===!0,o=(n==null?void 0:n.reload)!==!1,l=new FormData;l.set("overwrite",i?"true":"false"),l.set("reload",o?"true":"false"),l.set("file",t,t.name||"upload.flow");const u=await fetch(Bt(this._cfg.base_url,bt("bundles/upload")),{method:"POST",headers:{...Pt(this._cfg.auth_token)},body:l});if(!u.ok)throw new Error(`upload_bundle failed: ${await Vn(u)}`);return await u.json()}async attachments_upload(t,n,i){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((i==null?void 0:i.filename)||"").trim()||String((n==null?void 0:n.name)||"").trim()||"upload.bin",u=String((i==null?void 0:i.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(Bt(this._cfg.base_url,bt("attachments/upload")),{method:"POST",headers:{...Pt(this._cfg.auth_token)},body:c});if(!f.ok)throw new Error(`attachments_upload failed: ${await Vn(f)}`);const _=await f.json(),p=_==null?void 0:_.attachment;if(!p||typeof p!="object")throw new Error("attachments_upload: missing attachment");if(!String(p.$artifact||"").trim())throw new Error("attachments_upload: missing attachment.$artifact");return p}async remove_bundle(t,n){const i=String(t||"").trim();if(!i)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=Bt(this._cfg.base_url,bt(`bundles/${encodeURIComponent(i)}?${o.toString()}`)),c=await fetch(u,{method:"DELETE",headers:{...Pt(this._cfg.auth_token)}});if(!c.ok)throw new Error(`remove_bundle failed: ${await Vn(c)}`);return await c.json()}async discovery_tools(){const t=await fetch(Bt(this._cfg.base_url,bt("discovery/tools")),{headers:{...Pt(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,i=Bt(this._cfg.base_url,bt(`discovery/providers?include_models=${encodeURIComponent(String(n))}`)),o=await fetch(i,{headers:{...Pt(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 i=await fetch(Bt(this._cfg.base_url,bt(`discovery/providers/${encodeURIComponent(n)}/models`)),{headers:{...Pt(this._cfg.auth_token)}});if(!i.ok)throw new Error(`discovery_provider_models failed: ${i.status}`);return await i.json()}async get_bundle(t){const n=String(t||"").trim();if(!n)throw new Error("get_bundle: bundle_id is required");const i=await fetch(Bt(this._cfg.base_url,bt(`bundles/${encodeURIComponent(n)}`)),{headers:{...Pt(this._cfg.auth_token)}});if(!i.ok)throw new Error(`get_bundle failed: ${i.status}`);return await i.json()}async get_bundle_flow(t,n){const i=String(t||"").trim(),o=String(n||"").trim();if(!i)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(Bt(this._cfg.base_url,bt(`bundles/${encodeURIComponent(i)}/flows/${encodeURIComponent(o)}`)),{headers:{...Pt(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 i=await fetch(Bt(this._cfg.base_url,bt(`workflows/${encodeURIComponent(n)}/flow`)),{headers:{...Pt(this._cfg.auth_token)}});if(!i.ok)throw new Error(`get_workflow_flow failed: ${i.status}`);return await i.json()}async discovery_capabilities(){const t=await fetch(Bt(this._cfg.base_url,bt("discovery/capabilities")),{headers:{...Pt(this._cfg.auth_token)},signal:bi()});if(!t.ok)throw new Error(`discovery_capabilities failed: ${await Vn(t)}`);return await t.json()}automations_client(){const t=this._cfg.auth_token;return $S({fetch:(n,i)=>fetch(n,i),baseUrl:this._cfg.base_url,headers:()=>Pt(t)})}async submit_command(t){const n=await fetch(Bt(this._cfg.base_url,bt("commands")),{method:"POST",headers:{"Content-Type":"application/json",...Pt(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(),i=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:i,limit:o},u=String((t==null?void 0:t.run_id)||"").trim();u&&(l.run_id=u);const c=String((t==null?void 0:t.session_id)||"").trim();c&&(l.session_id=c);const f=String((t==null?void 0:t.owner_id)||"").trim();f&&(l.owner_id=f),t!=null&&t.all_owners&&(l.all_owners=!0);const _=String((t==null?void 0:t.subject)||"").trim();_&&(l.subject=_);const p=String((t==null?void 0:t.predicate)||"").trim();p&&(l.predicate=p);const y=String((t==null?void 0:t.object)||"").trim();y&&(l.object=y);const w=String((t==null?void 0:t.since)||"").trim();w&&(l.since=w);const x=String((t==null?void 0:t.until)||"").trim();x&&(l.until=x);const S=String((t==null?void 0:t.active_at)||"").trim();S&&(l.active_at=S);const j=String((t==null?void 0:t.query_text)||"").trim();j&&(l.query_text=j),typeof(t==null?void 0:t.min_score)=="number"&&Number.isFinite(t.min_score)&&(l.min_score=Number(t.min_score));const E=await fetch(Bt(this._cfg.base_url,bt("kg/query")),{method:"POST",headers:{"Content-Type":"application/json",...Pt(this._cfg.auth_token)},body:JSON.stringify(l)});if(!E.ok)throw new Error(`kg_query failed: ${await Vn(E)}`);return await E.json()}async stream_ledger(t,n){var y;const i=Number((n==null?void 0:n.after)||0),o=n.on_step,l=n.signal,u=Bt(this._cfg.base_url,bt(`runs/${encodeURIComponent(t)}/ledger/stream?after=${encodeURIComponent(String(i))}`)),c=await fetch(u,{headers:{Accept:"text/event-stream",...Pt(this._cfg.auth_token)},signal:l});if(!c.ok)throw await K_(c,"The ledger stream was refused");if(!c.body)throw new Error("stream_ledger: response body is missing");(y=n.on_open)==null||y.call(n);const f=c.body.getReader(),_=new TextDecoder("utf-8"),p=new i2;for(;;){const{value:w,done:x}=await f.read();if(x)return;const S=_.decode(w,{stream:!0});p.push(S,j=>{if(!(j.event!=="step"||!j.data))try{const E=JSON.parse(j.data);E&&typeof E.cursor=="number"&&E.record&&o(E)}catch{}})}}}function a2(e){const t=(e||"").trim();return t?{Authorization:`Bearer ${t}`}:{}}class l2{constructor(t){Gs(this,"_cfg");this._cfg={...t,url:(t.url||"").trim()}}async call_tool(t){const n=String((t==null?void 0:t.name)||"").trim(),i=String((t==null?void 0:t.call_id)||(t==null?void 0:t.id)||zs()),o=t!=null&&t.arguments&&typeof t.arguments=="object"?t.arguments:{};if(!n)return{call_id:i,name:"",success:!1,output:null,error:"Missing tool name"};const l={jsonrpc:"2.0",id:zs(),method:"tools/call",params:{name:n,arguments:o}},u=await fetch(this._cfg.url,{method:"POST",headers:{"Content-Type":"application/json",...a2(this._cfg.auth_token)},body:JSON.stringify(l)});if(!u.ok)return{call_id:i,name:n,success:!1,output:null,error:`Worker HTTP ${u.status}`};const c=await u.json().catch(()=>null),f=c==null?void 0:c.result,_=!!(f!=null&&f.isError),y=(Array.isArray(f==null?void 0:f.content)?f.content:[]).find(x=>x&&x.type==="text"&&typeof x.text=="string"),w=(y==null?void 0:y.text)??"";return _?{call_id:i,name:n,success:!1,output:null,error:w||"Tool failed"}:{call_id:i,name:n,success:!0,output:w,error:null}}}class lw{constructor(t,n){Gs(this,"pending",[]);Gs(this,"scheduled",!1);Gs(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 i=this.pending;this.pending=[],i.length&&this.on_flush(i)})}reset(){this.generation+=1,this.pending=[],this.scheduled=!1}pending_count(){return this.pending.length}}function cw(e,t=""){const n=String(e.role||"").trim(),i=String(e.automation_id||"").trim();return n==="occurrence"&&i&&i!==e.run_id?i:String(e.parent_run_id||t||"").trim()}function c2(e,t){const n=Cn(e.updated_at||e.created_at)??0;return(Cn(t.updated_at||t.created_at)??0)-n}function u2(e,t){const n=t.query.trim().toLowerCase(),i=[...e],o={};for(const w of i){const x=String(w.run_id||"").trim();x&&(o[x]=w)}for(const w of e){const x=cw(w);if(String(w.role||"")==="occurrence"&&x&&!o[x]){const S={run_id:x,workflow_id:null,status:"",role:"controller",session_kind:"automation",automation_id:x,updated_at:w.updated_at??null,created_at:w.created_at??null};o[x]=S,i.push(S)}}const l={},u={};for(const w of i){const x=String(w.run_id||"").trim();if(!x)continue;const S=cw(w,t.parent_hint?t.parent_hint(x):"");u[x]=S,S&&(l[S]||(l[S]=[])).push(w)}const c=w=>{const x=String(w.status||"").trim().toLowerCase();return t.filter==="all"?!0:t.filter==="active"?Pu(x):t.filter==="waiting"?x==="waiting":t.filter==="terminal"?Ci(x):t.filter==="failed"?x==="failed":!0},f=w=>{if(!n)return!0;const x=String(w.workflow_id||w.schedule_target_workflow_id||"").trim(),S=x?t.workflow_label_by_id[x]||x:"";return[w.run_id,x,S,w.session_id,w.status,w.session_kind,w.automation_id].join(" ").toLowerCase().includes(n)},_=[];for(const w of i){const x=String(w.run_id||"").trim();if(!x)continue;const S=u[x];(!S||!o[S])&&_.push(x)}const p={},y=w=>{if(t.group_by==="workflow"){const S=String(w.schedule_target_workflow_id||w.workflow_id||"").trim()||"(unknown workflow)";return{key:S,label:t.workflow_label_by_id[S]||S}}if(t.group_by==="session"){const S=String(w.session_id||"").trim()||"(no session)";return{key:S,label:S}}const x=String(w.status||"").trim().toLowerCase()||"unknown";return Pu(x)?{key:"active",label:"Active"}:x==="failed"?{key:"failed",label:"Failed"}:Ci(x)?{key:"finished",label:"Finished"}:{key:x,label:x}};for(const w of _){const x=o[w];if(!x)continue;const S=[...l[w]||[]].sort(c2),j=S.some(A=>c(A)&&f(A));if(!(c(x)&&f(x))&&!j)continue;const E=y(x);p[E.key]||(p[E.key]={key:E.key,label:E.label,rows:[]}),p[E.key].rows.push({run:x,children:S})}return Object.values(p).sort((w,x)=>{const S={active:0,waiting:1,failed:2,finished:3},j=S[w.key]??10,E=S[x.key]??10;return j!==E?j-E:w.label.localeCompare(x.label)})}const d2={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"},f2=[{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 h2(){const[e,t]=m.useState(!0);return s.jsxs("div",{className:"pin-legend",children:[s.jsxs("button",{className:"pin-legend-toggle mono",type:"button",onClick:()=>t(n=>!n),title:"Pin Type Legend",children:[e?"?":"×"," Pin Types"]}),e?null:s.jsxs("div",{className:"pin-legend-content",children:[f2.map(n=>s.jsxs("div",{className:"pin-legend-row",children:[s.jsx("span",{className:"pin-legend-shape",style:{color:d2[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 un(e){return typeof e=="string"?e:e==null?"":String(e)}function uw(e,t){const n=un(e).trim();return n.length<=t?n:`${n.slice(0,Math.max(0,t-1))}…`}function Qx(e){const t=un(e==null?void 0:e.targetHandle),n=un(e==null?void 0:e.sourceHandle);return!!(t==="exec-in"||n==="exec-out"||t.includes("exec")||n.includes("exec"))}function eb(e){if(!e||typeof e!="object")return"";const t=e!=null&&e.data&&typeof e.data=="object"?e.data:{};return un((t==null?void 0:t.nodeType)||(e==null?void 0:e.type)||"").trim()}function tb(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),i=un(n).trim();if(!i)return"";if(i.includes(":")){const o=i.split(":",2);if(o.length===2&&o[1])return o[1].trim()}return i}function m2(e){const t=un(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 i of n)if(eb(i)==="on_flow_start"){const o=un(i==null?void 0:i.id).trim();if(o)return o}return""}function J_(e){const t=e!=null&&e.position&&typeof e.position=="object"?e.position:{},n=typeof t.x=="number"?t.x:0,i=typeof t.y=="number"?t.y:0;return{x:n,y:i}}function rf(e,t){const n=un(e).trim(),i=un(t).trim();return i?n?`${n}::${i}`:i:""}function _2(e){const t=e.root&&typeof e.root=="object"?e.root:{};if(!e.expand_subflows)return t;const n=[],i=[],o=new Set,l=(u,c,f,_)=>{if(!u||typeof u!="object"||n.length>=e.max_nodes||i.length>=e.max_edges)return;const p=Array.isArray(u.nodes)?u.nodes:[],y=Array.isArray(u.edges)?u.edges:[];for(const w of p){const x=un(w==null?void 0:w.id).trim();if(!x)continue;const S=rf(c,x);if(!S||o.has(S))continue;const j=J_(w),E={...w,id:S,position:{x:j.x+f.x,y:j.y+f.y}};if(n.push(E),o.add(S),n.length>=e.max_nodes)break}for(const w of y){if(!Qx(w))continue;const x=un(w==null?void 0:w.source).trim(),S=un(w==null?void 0:w.target).trim();if(!x||!S)continue;const j=rf(c,x),E=rf(c,S);if(!j||!E)continue;const A=un(w==null?void 0:w.id).trim(),L=A?`${j}->${E}::${A}`:`${j}->${E}`;if(i.push({...w,id:L,source:j,target:E}),i.length>=e.max_edges)break}if(!(_>=e.max_depth))for(const w of p){if(n.length>=e.max_nodes||i.length>=e.max_edges)return;if(eb(w)!=="subflow")continue;const x=tb(w);if(!x)continue;const S=e.flow_by_id[x];if(!S||typeof S!="object")continue;const j=rf(c,un(w==null?void 0:w.id));if(!j)continue;const E=m2(S);if(!E)continue;const L=(Array.isArray(S.nodes)?S.nodes:[]).find(re=>un(re==null?void 0:re.id).trim()===E)||null;if(!L)continue;const O=J_(w),M=J_(L),Y={x:O.x+f.x+240-M.x,y:O.y+f.y+0-M.y},Z=rf(j,E);i.push({id:`${j}=>${Z}`,source:j,target:Z,sourceHandle:"exec-out",targetHandle:"exec-in"}),l(S,j,Y,_+1)}};return l(t,"",{x:0,y:0},0),{...t,id:un(t.id),nodes:n,edges:i}}function p2(e){const t=un(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 g2(e){const t=e.nodes.filter(l=>e.keep_id(l.id)),n=new Set(t.map(l=>l.id)),i={};for(const l of e.edges)i[l.source]||(i[l.source]=[]),i[l.source].push(l.target);const o=new Map;for(const l of t){const u=new Set,c=(i[l.id]||[]).slice();for(;c.length;){const f=c.pop();if(!f||u.has(f))continue;if(u.add(f),n.has(f)){const p=`${l.id}->${f}`;o.has(p)||o.set(p,{id:p,source:l.id,target:f});continue}const _=i[f]||[];for(const p of _)u.has(p)||c.push(p);if(o.size>=e.max_edges)break}if(o.size>=e.max_edges)break}return{nodes:t,edges:Array.from(o.values())}}function dw(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 y2(e){const t=typeof e.now_ms=="number"?e.now_ms:Date.now(),n=e.flow,i=un(e.active_node_id),o=e.recent_nodes||{},l=e.visited_nodes||{},u=e.highlight_path===!0,c=typeof e.vertical_compact=="number"?Math.max(.4,Math.min(1,e.vertical_compact)):.78,{nodes:f,edges:_,bounds:p}=m.useMemo(()=>{const B=_2({root:n||{},flow_by_id:e.flow_by_id||{},expand_subflows:e.expand_subflows===!0,max_depth:3,max_nodes:700,max_edges:900}),z=Array.isArray(B.nodes)?B.nodes:[],G=Array.isArray(B.edges)?B.edges:[];let T=[];for(const Se of z){const Le=un(Se==null?void 0:Se.id).trim();if(!Le)continue;const ct=Se!=null&&Se.position&&typeof Se.position=="object"?Se.position:{},ge=typeof ct.x=="number"?ct.x:0,De=typeof ct.y=="number"?ct.y:0,Ke=Se!=null&&Se.data&&typeof Se.data=="object"?Se.data:{},Dt=un((Ke==null?void 0:Ke.label)||(Se==null?void 0:Se.label)||Le)||Le,tn=un((Ke==null?void 0:Ke.nodeType)||(Se==null?void 0:Se.type)||"unknown")||"unknown",pn=un((Ke==null?void 0:Ke.headerColor)||(Se==null?void 0:Se.headerColor)||"")||"",Wt=Ke!=null&&Ke.eventConfig&&typeof Ke.eventConfig=="object"?Ke.eventConfig:null,It=Wt&&typeof Wt.schedule=="string"?un(Wt.schedule).trim():"",dn=Wt&&typeof Wt.recurrent=="boolean"?!!Wt.recurrent:void 0,Wn=tn==="subflow"?tb(Se):"",Tt=It||dn!==void 0||Wn?{schedule:It||void 0,recurrent:dn,subflow_id:Wn||void 0}:void 0;T.push({id:Le,x:ge,y:De,label:Dt,type:tn,color:pn,meta:Tt})}const Q={};for(const Se of T)Q[Se.id]=Se;let K=[];for(const Se of G){if(!Qx(Se))continue;const Le=un(Se==null?void 0:Se.source).trim(),ct=un(Se==null?void 0:Se.target).trim();!Le||!ct||K.push({id:un((Se==null?void 0:Se.id)||`${Le}->${ct}`),source:Le,target:ct})}const J=new Set(T.map(Se=>Se.id));if(K=K.filter(Se=>J.has(Se.source)&&J.has(Se.target)),e.simplify===!0){const Le=g2({nodes:T,edges:K,keep_id:ct=>{if(i&&ct===i)return!0;const ge=Q[ct];if(!ge)return!1;const De=un(ge.type).trim().toLowerCase();return De==="on_flow_start"||De==="on_flow_end"||De==="subflow"?!0:!p2(De)},max_edges:900});T=Le.nodes,K=Le.edges}if(e.prefer_vertical===!0&&T.length>=2){const Se=T.map(Ke=>Ke.x),Le=T.map(Ke=>Ke.y),ct=Math.max(...Se)-Math.min(...Se),ge=Math.max(...Le)-Math.min(...Le);ct>=ge&&(T=T.map(Ke=>({...Ke,x:Ke.y,y:Ke.x})));const De=Math.min(...T.map(Ke=>Ke.y));T=T.map(Ke=>({...Ke,y:De+(Ke.y-De)*c}))}const oe={};for(const Se of T)oe[Se.id]=Se;const fe=160,_e=56,we=fe/2,Ae=_e/2;let Be=0,We=0,_t=0,Pe=0;T.length&&(Be=Math.min(...T.map(Se=>Se.x)),We=Math.min(...T.map(Se=>Se.y)),_t=Math.max(...T.map(Se=>Se.x+fe)),Pe=Math.max(...T.map(Se=>Se.y+_e)));let et=0;if(K.length){const Se=new Set(K.map(Le=>`${Le.source}->${Le.target}`));for(const Le of K){if(!Se.has(`${Le.target}->${Le.source}`))continue;const ct=oe[Le.source],ge=oe[Le.target];if(!ct||!ge)continue;const De=ct.x+we,Ke=ct.y+Ae,Dt=ge.x+we,tn=ge.y+Ae,pn=Math.max(1,Math.hypot(Dt-De,tn-Ke)),Wt=Math.max(28,Math.min(72,pn*.14)),It=Math.min(200,Wt*3.5);It>et&&(et=It)}}const lt=60+et,Ye={x:Be-lt,y:We-lt,w:_t-Be+lt*2,h:Pe-We+lt*2,node_w:fe,node_h:_e};return{nodes:T,edges:K,bounds:Ye}},[n,e.flow_by_id,e.expand_subflows,e.simplify,e.prefer_vertical,i,c]);if(!n)return s.jsx("div",{className:"graph_empty mono",children:"(no graph loaded)"});const y=m.useRef(null),[w,x]=m.useState(()=>({x:p.x,y:p.y,w:p.w,h:p.h})),S=m.useRef(w);S.current=w,m.useEffect(()=>{x({x:p.x,y:p.y,w:p.w,h:p.h})},[p.x,p.y,p.w,p.h]);const j=m.useRef(new Map),E=m.useRef(null),A=`${w.x} ${w.y} ${w.w} ${w.h}`,L={};for(const B of f)L[B.id]=B;const O=B=>{let z=un(B).trim();if(!z)return"";if(L[z])return z;for(;z.includes("::");)if(z=z.slice(0,Math.max(0,z.lastIndexOf("::"))),L[z])return z;return""},M=O(i),H={};for(const[B,z]of Object.entries(o)){if(typeof z!="number")continue;const G=O(B);G&&(H[G]=Math.max(H[G]||0,z))}const X={};if(u)for(const[B,z]of Object.entries(l)){if(typeof z!="number")continue;const G=O(B);G&&(X[G]=typeof X[G]=="number"?Math.min(X[G],z):z)}const Y=un(e.schedule_next_in).trim(),Z=un(e.schedule_interval).trim(),re=e.node_last_ms&&typeof e.node_last_ms=="object"?e.node_last_ms:{},ie=B=>{try{const z=new Date(B),G=String(z.getHours()).padStart(2,"0"),T=String(z.getMinutes()).padStart(2,"0");return`${G}:${T}`}catch{return""}},ue=(B,z)=>{var K,J;const G=un((K=B.meta)==null?void 0:K.schedule).trim();if(!(((J=B.meta)==null?void 0:J.recurrent)===!0))return z&&Y?`next ${Y}`:G&&G.length<=12&&!G.includes("T")?`in ${G}`:"scheduled";const Q=G||Z;return Q?z&&Y?`${Q} • next ${Y}`:`every ${Q}`:z&&Y?`next ${Y}`:"scheduled"},F=B=>{var fe;const z=un((fe=B.meta)==null?void 0:fe.subflow_id).trim(),G=z&&e.flow_by_id?e.flow_by_id[z]:null,Q=un(G==null?void 0:G.name).trim()||z||B.label||B.id,K=typeof re[B.id]=="number"?Number(re[B.id]):null,J=K!==null?ie(K):"",oe=J?`last ${J}`:"subflow";return{label:Q,sub:oe}},C=(B,z,G)=>{const T=G||S.current,Q=y.current;if(!Q)return{x:B,y:z};const K=Q.getBoundingClientRect(),J=K.width>0?(B-K.left)/K.width:0,oe=K.height>0?(z-K.top)/K.height:0;return{x:T.x+J*T.w,y:T.y+oe*T.h}},N=(B,z,G)=>{const T=G||S.current,Q=Math.max(.12,Math.min(8,z)),K=T.w*Q,J=T.h*Q,oe=T.w>0?(B.x-T.x)/T.w:.5,fe=T.h>0?(B.y-T.y)/T.h:.5,_e=B.x-oe*K,we=B.y-fe*J;x(dw({x:_e,y:we,w:K,h:J},p))},P=(B,z,G)=>{const T=G||S.current,Q=y.current;if(!Q)return;const K=Q.getBoundingClientRect(),J=.88,oe=K.width>0?B/K.width*T.w*J:0,fe=K.height>0?z/K.height*T.h*J:0;x(_e=>dw({x:(G||_e).x-oe,y:(G||_e).y-fe,w:(G||_e).w,h:(G||_e).h},p))},D=m.useMemo(()=>{const B=new Set;for(const z of _)B.add(`${z.source}->${z.target}`);return B},[_]),ne=(B,z,G,T)=>{const Q=p.node_w,K=p.node_h,J=Math.abs(G),oe=Math.abs(T);if(J<1e-6&&oe<1e-6)return{x:B,y:z};const fe=J>1e-6?Q/2/J:Number.POSITIVE_INFINITY,_e=oe>1e-6?K/2/oe:Number.POSITIVE_INFINITY,we=Math.min(fe,_e);return{x:B+G*we,y:z+T*we}};return s.jsxs("div",{className:"graph_wrap",children:[s.jsxs("div",{className:"graph_corner",children:[s.jsxs("div",{className:"graph_corner_buttons",children:[s.jsx("button",{className:"btn graph_corner_btn",type:"button",onClick:()=>x({x:p.x,y:p.y,w:p.w,h:p.h}),title:"Recenter",children:"⤢"}),s.jsx("button",{className:"btn graph_corner_btn",type:"button",onClick:()=>{const B=y.current;if(!B)return;const z=B.getBoundingClientRect(),G=C(z.left+z.width/2,z.top+z.height/2);N(G,.84)},title:"Zoom in",children:"+"}),s.jsx("button",{className:"btn graph_corner_btn",type:"button",onClick:()=>{const B=y.current;if(!B)return;const z=B.getBoundingClientRect(),G=C(z.left+z.width/2,z.top+z.height/2);N(G,1.18)},title:"Zoom out",children:"−"})]}),s.jsx(h2,{})]}),s.jsxs("svg",{ref:y,className:"graph_svg",viewBox:A,role:"img","aria-label":"Workflow execution graph",onWheel:B=>{B.preventDefault();const z=C(B.clientX,B.clientY),G=typeof B.deltaY=="number"?B.deltaY:0,T=typeof B.deltaMode=="number"?Number(B.deltaMode):0,Q=T===1?G*24:T===2?G*800:G,K=45e-5*1.15*1.1;let J=Math.exp(Q*K);J=Math.max(.86,Math.min(1.16,J)),N(z,J)},onPointerDown:B=>{var G,T;(T=(G=B.currentTarget).setPointerCapture)==null||T.call(G,B.pointerId),j.current.set(B.pointerId,{x:B.clientX,y:B.clientY});const z=Array.from(j.current.values());if(z.length===1)E.current={mode:"pan",start_view:S.current,start_client:{x:B.clientX,y:B.clientY},start_dist:0,anchor_svg:{x:0,y:0}};else if(z.length>=2){const Q=z[0],K=z[1],J=Q.x-K.x,oe=Q.y-K.y,fe=Math.max(1,Math.hypot(J,oe)),_e={x:(Q.x+K.x)/2,y:(Q.y+K.y)/2},we=S.current;E.current={mode:"pinch",start_view:we,start_client:_e,start_dist:fe,anchor_svg:C(_e.x,_e.y,we)}}},onPointerMove:B=>{if(!j.current.has(B.pointerId))return;j.current.set(B.pointerId,{x:B.clientX,y:B.clientY});const z=E.current;if(!z)return;const G=Array.from(j.current.values());if(z.mode==="pan"&&G.length===1){const T=B.clientX-z.start_client.x,Q=B.clientY-z.start_client.y;P(T,Q,z.start_view)}else if(z.mode==="pinch"&&G.length>=2){const T=G[0],Q=G[1],K=T.x-Q.x,J=T.y-Q.y,oe=Math.max(1,Math.hypot(K,J)),fe=z.start_dist/oe;N(z.anchor_svg,fe,z.start_view)}},onPointerUp:B=>{j.current.delete(B.pointerId),j.current.size===0&&(E.current=null)},onPointerCancel:B=>{j.current.delete(B.pointerId),j.current.size===0&&(E.current=null)},children:[s.jsxs("defs",{children:[s.jsx("marker",{id:"arrow",viewBox:"0 0 10 10",refX:"9",refY:"5",markerWidth:"8",markerHeight:"8",orient:"auto-start-reverse",children:s.jsx("path",{d:"M 0 0 L 10 5 L 0 10 z",fill:"rgba(148,163,184,0.55)"})}),s.jsxs("filter",{id:"glow",children:[s.jsx("feGaussianBlur",{stdDeviation:"3",result:"coloredBlur"}),s.jsxs("feMerge",{children:[s.jsx("feMergeNode",{in:"coloredBlur"}),s.jsx("feMergeNode",{in:"SourceGraphic"})]})]})]}),_.map(B=>{const z=L[B.source],G=L[B.target];if(!z||!G)return null;const T=z.x+p.node_w/2,Q=z.y+p.node_h/2,K=G.x+p.node_w/2,J=G.y+p.node_h/2,oe=K-T,fe=J-Q,_e=ne(T,Q,oe,fe),we=ne(K,J,-oe,-fe),Ae=B.source!==B.target&&D.has(`${B.target}->${B.source}`),Be=Math.max(1,Math.hypot(oe,fe)),We=-fe/Be,_t=oe/Be,Pe=String(B.source)<String(B.target)?1:-1,lt=Math.abs(oe)>=Math.abs(fe)?oe>=0:fe>=0,Ye=!Ae||lt,Se=Math.max(28,Math.min(72,Be*.14)),Le=Math.min(200,Se*3.5),ct=Ae&&!Ye?Le*Pe:0,ge=(_e.x+we.x)/2+We*ct,De=(_e.y+we.y)/2+_t*ct,Ke=Ae&&!Ye?`M ${_e.x} ${_e.y} Q ${ge} ${De} ${we.x} ${we.y}`:`M ${_e.x} ${_e.y} L ${we.x} ${we.y}`,Dt=u&&X&&X[B.source]!==void 0&&X[B.target]!==void 0;return s.jsx("path",{d:Ke,className:`graph_edge ${Dt?"visited":""}`,markerEnd:"url(#arrow)",fill:"none"},B.id)}),f.map(B=>{const G=(typeof H[B.id]=="number"?H[B.id]:0)>t,T=M&&B.id===M,Q=u&&X&&X[B.id]!==void 0,K=`graph_node ${T?"active":G?"recent":""} ${Q?"visited":""}`,J=B.color||"rgba(255,255,255,0.16)";let oe=B.label||B.id,fe=B.type;if(B.type==="on_schedule")fe=ue(B,!!T);else if(B.type==="subflow"){const Ae=F(B);oe=Ae.label,fe=Ae.sub}const _e=uw(oe,22),we=uw(fe,22);return s.jsxs("g",{className:K,transform:`translate(${B.x}, ${B.y})`,children:[s.jsx("rect",{className:"graph_node_bg",width:p.node_w,height:p.node_h,rx:12,ry:12}),s.jsx("rect",{className:"graph_node_bar",width:p.node_w,height:6,rx:12,ry:12,fill:J}),s.jsx("text",{className:"graph_node_label",x:12,y:28,children:_e}),s.jsx("text",{className:"graph_node_type",x:12,y:46,children:we}),B.type==="on_schedule"?s.jsx("text",{className:"graph_node_icon",x:p.node_w-18,y:18,children:"⏰"}):null]},B.id)})]})]})}function Ys(e){if(typeof e=="string"||typeof e=="number")return""+e;let t="";if(Array.isArray(e))for(let n=0,i;n<e.length;n++)(i=Ys(e[n]))!==""&&(t+=(t&&" ")+i);else for(let n in e)e[n]&&(t+=(t&&" ")+n);return t}var X_={exports:{}},Z_={},Q_={exports:{}},ep={};/**
|
|
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 fw;function w2(){if(fw)return ep;fw=1;var e=Lf();function t(y,w){return y===w&&(y!==0||1/y===1/w)||y!==y&&w!==w}var n=typeof Object.is=="function"?Object.is:t,i=e.useState,o=e.useEffect,l=e.useLayoutEffect,u=e.useDebugValue;function c(y,w){var x=w(),S=i({inst:{value:x,getSnapshot:w}}),j=S[0].inst,E=S[1];return l(function(){j.value=x,j.getSnapshot=w,f(j)&&E({inst:j})},[y,x,w]),o(function(){return f(j)&&E({inst:j}),y(function(){f(j)&&E({inst:j})})},[y]),u(x),x}function f(y){var w=y.getSnapshot;y=y.value;try{var x=w();return!n(y,x)}catch{return!0}}function _(y,w){return w()}var p=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?_:c;return ep.useSyncExternalStore=e.useSyncExternalStore!==void 0?e.useSyncExternalStore:p,ep}var hw;function v2(){return hw||(hw=1,Q_.exports=w2()),Q_.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 mw;function x2(){if(mw)return Z_;mw=1;var e=Lf(),t=v2();function n(_,p){return _===p&&(_!==0||1/_===1/p)||_!==_&&p!==p}var i=typeof Object.is=="function"?Object.is:n,o=t.useSyncExternalStore,l=e.useRef,u=e.useEffect,c=e.useMemo,f=e.useDebugValue;return Z_.useSyncExternalStoreWithSelector=function(_,p,y,w,x){var S=l(null);if(S.current===null){var j={hasValue:!1,value:null};S.current=j}else j=S.current;S=c(function(){function A(X){if(!L){if(L=!0,O=X,X=w(X),x!==void 0&&j.hasValue){var Y=j.value;if(x(Y,X))return M=Y}return M=X}if(Y=M,i(O,X))return Y;var Z=w(X);return x!==void 0&&x(Y,Z)?(O=X,Y):(O=X,M=Z)}var L=!1,O,M,H=y===void 0?null:y;return[function(){return A(p())},H===null?void 0:function(){return A(H())}]},[p,y,w,x]);var E=o(_,S[0],S[1]);return u(function(){j.hasValue=!0,j.value=E},[E]),f(E),E},Z_}var _w;function b2(){return _w||(_w=1,X_.exports=x2()),X_.exports}var j2=b2();const S2=hg(j2),k2={},pw=e=>{let t;const n=new Set,i=(p,y)=>{const w=typeof p=="function"?p(t):p;if(!Object.is(w,t)){const x=t;t=y??(typeof w!="object"||w===null)?w:Object.assign({},t,w),n.forEach(S=>S(t,x))}},o=()=>t,f={setState:i,getState:o,getInitialState:()=>_,subscribe:p=>(n.add(p),()=>n.delete(p)),destroy:()=>{(k2?"production":void 0)!=="production"&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),n.clear()}},_=t=e(i,o,f);return f},N2=e=>e?pw(e):pw,{useDebugValue:C2}=ve,{useSyncExternalStoreWithSelector:E2}=S2,$2=e=>e;function nb(e,t=$2,n){const i=E2(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return C2(i),i}const gw=(e,t)=>{const n=N2(e),i=(o,l=t)=>nb(n,o,l);return Object.assign(i,n),i},A2=(e,t)=>e?gw(e,t):gw;function Us(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[i,o]of e)if(!Object.is(o,t.get(i)))return!1;return!0}if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(const i of e)if(!t.has(i))return!1;return!0}const n=Object.keys(e);if(n.length!==Object.keys(t).length)return!1;for(const i of n)if(!Object.prototype.hasOwnProperty.call(t,i)||!Object.is(e[i],t[i]))return!1;return!0}var T2={value:()=>{}};function Km(){for(var e=0,t=arguments.length,n={},i;e<t;++e){if(!(i=arguments[e]+"")||i in n||/[\s.]/.test(i))throw new Error("illegal type: "+i);n[i]=[]}return new fm(n)}function fm(e){this._=e}function M2(e,t){return e.trim().split(/^|\s+/).map(function(n){var i="",o=n.indexOf(".");if(o>=0&&(i=n.slice(o+1),n=n.slice(0,o)),n&&!t.hasOwnProperty(n))throw new Error("unknown type: "+n);return{type:n,name:i}})}fm.prototype=Km.prototype={constructor:fm,on:function(e,t){var n=this._,i=M2(e+"",n),o,l=-1,u=i.length;if(arguments.length<2){for(;++l<u;)if((o=(e=i[l]).type)&&(o=R2(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=i[l]).type)n[o]=yw(n[o],e.name,t);else if(t==null)for(o in n)n[o]=yw(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 fm(e)},call:function(e,t){if((o=arguments.length-2)>0)for(var n=new Array(o),i=0,o,l;i<o;++i)n[i]=arguments[i+2];if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(l=this._[e],i=0,o=l.length;i<o;++i)l[i].value.apply(t,n)},apply:function(e,t,n){if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(var i=this._[e],o=0,l=i.length;o<l;++o)i[o].value.apply(t,n)}};function R2(e,t){for(var n=0,i=e.length,o;n<i;++n)if((o=e[n]).name===t)return o.value}function yw(e,t,n){for(var i=0,o=e.length;i<o;++i)if(e[i].name===t){e[i]=T2,e=e.slice(0,i).concat(e.slice(i+1));break}return n!=null&&e.push({name:t,value:n}),e}var Hp="http://www.w3.org/1999/xhtml";const ww={svg:"http://www.w3.org/2000/svg",xhtml:Hp,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function Ym(e){var t=e+="",n=t.indexOf(":");return n>=0&&(t=e.slice(0,n))!=="xmlns"&&(e=e.slice(n+1)),ww.hasOwnProperty(t)?{space:ww[t],local:e}:e}function L2(e){return function(){var t=this.ownerDocument,n=this.namespaceURI;return n===Hp&&t.documentElement.namespaceURI===Hp?t.createElement(e):t.createElementNS(n,e)}}function I2(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function sb(e){var t=Ym(e);return(t.local?I2:L2)(t)}function O2(){}function Mg(e){return e==null?O2:function(){return this.querySelector(e)}}function P2(e){typeof e!="function"&&(e=Mg(e));for(var t=this._groups,n=t.length,i=new Array(n),o=0;o<n;++o)for(var l=t[o],u=l.length,c=i[o]=new Array(u),f,_,p=0;p<u;++p)(f=l[p])&&(_=e.call(f,f.__data__,p,l))&&("__data__"in f&&(_.__data__=f.__data__),c[p]=_);return new oi(i,this._parents)}function D2(e){return e==null?[]:Array.isArray(e)?e:Array.from(e)}function F2(){return[]}function rb(e){return e==null?F2:function(){return this.querySelectorAll(e)}}function z2(e){return function(){return D2(e.apply(this,arguments))}}function B2(e){typeof e=="function"?e=z2(e):e=rb(e);for(var t=this._groups,n=t.length,i=[],o=[],l=0;l<n;++l)for(var u=t[l],c=u.length,f,_=0;_<c;++_)(f=u[_])&&(i.push(e.call(f,f.__data__,_,u)),o.push(f));return new oi(i,o)}function ib(e){return function(){return this.matches(e)}}function ob(e){return function(t){return t.matches(e)}}var U2=Array.prototype.find;function W2(e){return function(){return U2.call(this.children,e)}}function q2(){return this.firstElementChild}function H2(e){return this.select(e==null?q2:W2(typeof e=="function"?e:ob(e)))}var V2=Array.prototype.filter;function G2(){return Array.from(this.children)}function K2(e){return function(){return V2.call(this.children,e)}}function Y2(e){return this.selectAll(e==null?G2:K2(typeof e=="function"?e:ob(e)))}function J2(e){typeof e!="function"&&(e=ib(e));for(var t=this._groups,n=t.length,i=new Array(n),o=0;o<n;++o)for(var l=t[o],u=l.length,c=i[o]=[],f,_=0;_<u;++_)(f=l[_])&&e.call(f,f.__data__,_,l)&&c.push(f);return new oi(i,this._parents)}function ab(e){return new Array(e.length)}function X2(){return new oi(this._enter||this._groups.map(ab),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 Z2(e){return function(){return e}}function Q2(e,t,n,i,o,l){for(var u=0,c,f=t.length,_=l.length;u<_;++u)(c=t[u])?(c.__data__=l[u],i[u]=c):n[u]=new $m(e,l[u]);for(;u<f;++u)(c=t[u])&&(o[u]=c)}function eE(e,t,n,i,o,l,u){var c,f,_=new Map,p=t.length,y=l.length,w=new Array(p),x;for(c=0;c<p;++c)(f=t[c])&&(w[c]=x=u.call(f,f.__data__,c,t)+"",_.has(x)?o[c]=f:_.set(x,f));for(c=0;c<y;++c)x=u.call(e,l[c],c,l)+"",(f=_.get(x))?(i[c]=f,f.__data__=l[c],_.delete(x)):n[c]=new $m(e,l[c]);for(c=0;c<p;++c)(f=t[c])&&_.get(w[c])===f&&(o[c]=f)}function tE(e){return e.__data__}function nE(e,t){if(!arguments.length)return Array.from(this,tE);var n=t?eE:Q2,i=this._parents,o=this._groups;typeof e!="function"&&(e=Z2(e));for(var l=o.length,u=new Array(l),c=new Array(l),f=new Array(l),_=0;_<l;++_){var p=i[_],y=o[_],w=y.length,x=sE(e.call(p,p&&p.__data__,_,i)),S=x.length,j=c[_]=new Array(S),E=u[_]=new Array(S),A=f[_]=new Array(w);n(p,y,j,E,A,x,t);for(var L=0,O=0,M,H;L<S;++L)if(M=j[L]){for(L>=O&&(O=L+1);!(H=E[O])&&++O<S;);M._next=H||null}}return u=new oi(u,i),u._enter=c,u._exit=f,u}function sE(e){return typeof e=="object"&&"length"in e?e:Array.from(e)}function rE(){return new oi(this._exit||this._groups.map(ab),this._parents)}function iE(e,t,n){var i=this.enter(),o=this,l=this.exit();return typeof e=="function"?(i=e(i),i&&(i=i.selection())):i=i.append(e+""),t!=null&&(o=t(o),o&&(o=o.selection())),n==null?l.remove():n(l),i&&o?i.merge(o).order():o}function oE(e){for(var t=e.selection?e.selection():e,n=this._groups,i=t._groups,o=n.length,l=i.length,u=Math.min(o,l),c=new Array(o),f=0;f<u;++f)for(var _=n[f],p=i[f],y=_.length,w=c[f]=new Array(y),x,S=0;S<y;++S)(x=_[S]||p[S])&&(w[S]=x);for(;f<o;++f)c[f]=n[f];return new oi(c,this._parents)}function aE(){for(var e=this._groups,t=-1,n=e.length;++t<n;)for(var i=e[t],o=i.length-1,l=i[o],u;--o>=0;)(u=i[o])&&(l&&u.compareDocumentPosition(l)^4&&l.parentNode.insertBefore(u,l),l=u);return this}function lE(e){e||(e=cE);function t(y,w){return y&&w?e(y.__data__,w.__data__):!y-!w}for(var n=this._groups,i=n.length,o=new Array(i),l=0;l<i;++l){for(var u=n[l],c=u.length,f=o[l]=new Array(c),_,p=0;p<c;++p)(_=u[p])&&(f[p]=_);f.sort(t)}return new oi(o,this._parents).order()}function cE(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}function uE(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this}function dE(){return Array.from(this)}function fE(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var i=e[t],o=0,l=i.length;o<l;++o){var u=i[o];if(u)return u}return null}function hE(){let e=0;for(const t of this)++e;return e}function mE(){return!this.node()}function _E(e){for(var t=this._groups,n=0,i=t.length;n<i;++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 pE(e){return function(){this.removeAttribute(e)}}function gE(e){return function(){this.removeAttributeNS(e.space,e.local)}}function yE(e,t){return function(){this.setAttribute(e,t)}}function wE(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function vE(e,t){return function(){var n=t.apply(this,arguments);n==null?this.removeAttribute(e):this.setAttribute(e,n)}}function xE(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 bE(e,t){var n=Ym(e);if(arguments.length<2){var i=this.node();return n.local?i.getAttributeNS(n.space,n.local):i.getAttribute(n)}return this.each((t==null?n.local?gE:pE:typeof t=="function"?n.local?xE:vE:n.local?wE:yE)(n,t))}function lb(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function jE(e){return function(){this.style.removeProperty(e)}}function SE(e,t,n){return function(){this.style.setProperty(e,t,n)}}function kE(e,t,n){return function(){var i=t.apply(this,arguments);i==null?this.style.removeProperty(e):this.style.setProperty(e,i,n)}}function NE(e,t,n){return arguments.length>1?this.each((t==null?jE:typeof t=="function"?kE:SE)(e,t,n??"")):Fu(this.node(),e)}function Fu(e,t){return e.style.getPropertyValue(t)||lb(e).getComputedStyle(e,null).getPropertyValue(t)}function CE(e){return function(){delete this[e]}}function EE(e,t){return function(){this[e]=t}}function $E(e,t){return function(){var n=t.apply(this,arguments);n==null?delete this[e]:this[e]=n}}function AE(e,t){return arguments.length>1?this.each((t==null?CE:typeof t=="function"?$E:EE)(e,t)):this.node()[e]}function cb(e){return e.trim().split(/^|\s+/)}function Rg(e){return e.classList||new ub(e)}function ub(e){this._node=e,this._names=cb(e.getAttribute("class")||"")}ub.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 db(e,t){for(var n=Rg(e),i=-1,o=t.length;++i<o;)n.add(t[i])}function fb(e,t){for(var n=Rg(e),i=-1,o=t.length;++i<o;)n.remove(t[i])}function TE(e){return function(){db(this,e)}}function ME(e){return function(){fb(this,e)}}function RE(e,t){return function(){(t.apply(this,arguments)?db:fb)(this,e)}}function LE(e,t){var n=cb(e+"");if(arguments.length<2){for(var i=Rg(this.node()),o=-1,l=n.length;++o<l;)if(!i.contains(n[o]))return!1;return!0}return this.each((typeof t=="function"?RE:t?TE:ME)(n,t))}function IE(){this.textContent=""}function OE(e){return function(){this.textContent=e}}function PE(e){return function(){var t=e.apply(this,arguments);this.textContent=t??""}}function DE(e){return arguments.length?this.each(e==null?IE:(typeof e=="function"?PE:OE)(e)):this.node().textContent}function FE(){this.innerHTML=""}function zE(e){return function(){this.innerHTML=e}}function BE(e){return function(){var t=e.apply(this,arguments);this.innerHTML=t??""}}function UE(e){return arguments.length?this.each(e==null?FE:(typeof e=="function"?BE:zE)(e)):this.node().innerHTML}function WE(){this.nextSibling&&this.parentNode.appendChild(this)}function qE(){return this.each(WE)}function HE(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function VE(){return this.each(HE)}function GE(e){var t=typeof e=="function"?e:sb(e);return this.select(function(){return this.appendChild(t.apply(this,arguments))})}function KE(){return null}function YE(e,t){var n=typeof e=="function"?e:sb(e),i=t==null?KE:typeof t=="function"?t:Mg(t);return this.select(function(){return this.insertBefore(n.apply(this,arguments),i.apply(this,arguments)||null)})}function JE(){var e=this.parentNode;e&&e.removeChild(this)}function XE(){return this.each(JE)}function ZE(){var e=this.cloneNode(!1),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function QE(){var e=this.cloneNode(!0),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function e$(e){return this.select(e?QE:ZE)}function t$(e){return arguments.length?this.property("__data__",e):this.node().__data__}function n$(e){return function(t){e.call(this,t,this.__data__)}}function s$(e){return e.trim().split(/^|\s+/).map(function(t){var n="",i=t.indexOf(".");return i>=0&&(n=t.slice(i+1),t=t.slice(0,i)),{type:t,name:n}})}function r$(e){return function(){var t=this.__on;if(t){for(var n=0,i=-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[++i]=l;++i?t.length=i:delete this.__on}}}function i$(e,t,n){return function(){var i=this.__on,o,l=n$(t);if(i){for(var u=0,c=i.length;u<c;++u)if((o=i[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},i?i.push(o):this.__on=[o]}}function o$(e,t,n){var i=s$(e+""),o,l=i.length,u;if(arguments.length<2){var c=this.node().__on;if(c){for(var f=0,_=c.length,p;f<_;++f)for(o=0,p=c[f];o<l;++o)if((u=i[o]).type===p.type&&u.name===p.name)return p.value}return}for(c=t?i$:r$,o=0;o<l;++o)this.each(c(i[o],t,n));return this}function hb(e,t,n){var i=lb(e),o=i.CustomEvent;typeof o=="function"?o=new o(t,n):(o=i.document.createEvent("Event"),n?(o.initEvent(t,n.bubbles,n.cancelable),o.detail=n.detail):o.initEvent(t,!1,!1)),e.dispatchEvent(o)}function a$(e,t){return function(){return hb(this,e,t)}}function l$(e,t){return function(){return hb(this,e,t.apply(this,arguments))}}function c$(e,t){return this.each((typeof t=="function"?l$:a$)(e,t))}function*u$(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var i=e[t],o=0,l=i.length,u;o<l;++o)(u=i[o])&&(yield u)}var mb=[null];function oi(e,t){this._groups=e,this._parents=t}function Ff(){return new oi([[document.documentElement]],mb)}function d$(){return this}oi.prototype=Ff.prototype={constructor:oi,select:P2,selectAll:B2,selectChild:H2,selectChildren:Y2,filter:J2,data:nE,enter:X2,exit:rE,join:iE,merge:oE,selection:d$,order:aE,sort:lE,call:uE,nodes:dE,node:fE,size:hE,empty:mE,each:_E,attr:bE,style:NE,property:AE,classed:LE,text:DE,html:UE,raise:qE,lower:VE,append:GE,insert:YE,remove:XE,clone:e$,datum:t$,on:o$,dispatch:c$,[Symbol.iterator]:u$};function Si(e){return typeof e=="string"?new oi([[document.querySelector(e)]],[document.documentElement]):new oi([[e]],mb)}function f$(e){let t;for(;t=e.sourceEvent;)e=t;return e}function no(e,t){if(e=f$(e),t===void 0&&(t=e.currentTarget),t){var n=t.ownerSVGElement||t;if(n.createSVGPoint){var i=n.createSVGPoint();return i.x=e.clientX,i.y=e.clientY,i=i.matrixTransform(t.getScreenCTM().inverse()),[i.x,i.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 h$={passive:!1},jf={capture:!0,passive:!1};function tp(e){e.stopImmediatePropagation()}function Ru(e){e.preventDefault(),e.stopImmediatePropagation()}function _b(e){var t=e.document.documentElement,n=Si(e).on("dragstart.drag",Ru,jf);"onselectstart"in t?n.on("selectstart.drag",Ru,jf):(t.__noselect=t.style.MozUserSelect,t.style.MozUserSelect="none")}function pb(e,t){var n=e.document.documentElement,i=Si(e).on("dragstart.drag",null);t&&(i.on("click.drag",Ru,jf),setTimeout(function(){i.on("click.drag",null)},0)),"onselectstart"in n?i.on("selectstart.drag",null):(n.style.MozUserSelect=n.__noselect,delete n.__noselect)}const Yh=e=>()=>e;function Vp(e,{sourceEvent:t,subject:n,target:i,identifier:o,active:l,x:u,y:c,dx:f,dy:_,dispatch:p}){Object.defineProperties(this,{type:{value:e,enumerable:!0,configurable:!0},sourceEvent:{value:t,enumerable:!0,configurable:!0},subject:{value:n,enumerable:!0,configurable:!0},target:{value:i,enumerable:!0,configurable:!0},identifier:{value:o,enumerable:!0,configurable:!0},active:{value:l,enumerable:!0,configurable:!0},x:{value:u,enumerable:!0,configurable:!0},y:{value:c,enumerable:!0,configurable:!0},dx:{value:f,enumerable:!0,configurable:!0},dy:{value:_,enumerable:!0,configurable:!0},_:{value:p}})}Vp.prototype.on=function(){var e=this._.on.apply(this._,arguments);return e===this._?this:e};function m$(e){return!e.ctrlKey&&!e.button}function _$(){return this.parentNode}function p$(e,t){return t??{x:e.x,y:e.y}}function g$(){return navigator.maxTouchPoints||"ontouchstart"in this}function y$(){var e=m$,t=_$,n=p$,i=g$,o={},l=Km("start","drag","end"),u=0,c,f,_,p,y=0;function w(M){M.on("mousedown.drag",x).filter(i).on("touchstart.drag",E).on("touchmove.drag",A,h$).on("touchend.drag touchcancel.drag",L).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function x(M,H){if(!(p||!e.call(this,M,H))){var X=O(this,t.call(this,M,H),M,H,"mouse");X&&(Si(M.view).on("mousemove.drag",S,jf).on("mouseup.drag",j,jf),_b(M.view),tp(M),_=!1,c=M.clientX,f=M.clientY,X("start",M))}}function S(M){if(Ru(M),!_){var H=M.clientX-c,X=M.clientY-f;_=H*H+X*X>y}o.mouse("drag",M)}function j(M){Si(M.view).on("mousemove.drag mouseup.drag",null),pb(M.view,_),Ru(M),o.mouse("end",M)}function E(M,H){if(e.call(this,M,H)){var X=M.changedTouches,Y=t.call(this,M,H),Z=X.length,re,ie;for(re=0;re<Z;++re)(ie=O(this,Y,M,H,X[re].identifier,X[re]))&&(tp(M),ie("start",M,X[re]))}}function A(M){var H=M.changedTouches,X=H.length,Y,Z;for(Y=0;Y<X;++Y)(Z=o[H[Y].identifier])&&(Ru(M),Z("drag",M,H[Y]))}function L(M){var H=M.changedTouches,X=H.length,Y,Z;for(p&&clearTimeout(p),p=setTimeout(function(){p=null},500),Y=0;Y<X;++Y)(Z=o[H[Y].identifier])&&(tp(M),Z("end",M,H[Y]))}function O(M,H,X,Y,Z,re){var ie=l.copy(),ue=no(re||X,H),F,C,N;if((N=n.call(M,new Vp("beforestart",{sourceEvent:X,target:w,identifier:Z,active:u,x:ue[0],y:ue[1],dx:0,dy:0,dispatch:ie}),Y))!=null)return F=N.x-ue[0]||0,C=N.y-ue[1]||0,function P(D,ne,B){var z=ue,G;switch(D){case"start":o[Z]=P,G=u++;break;case"end":delete o[Z],--u;case"drag":ue=no(B||ne,H),G=u;break}ie.call(D,M,new Vp(D,{sourceEvent:ne,subject:N,target:w,identifier:Z,active:G,x:ue[0]+F,y:ue[1]+C,dx:ue[0]-z[0],dy:ue[1]-z[1],dispatch:ie}),Y)}}return w.filter=function(M){return arguments.length?(e=typeof M=="function"?M:Yh(!!M),w):e},w.container=function(M){return arguments.length?(t=typeof M=="function"?M:Yh(M),w):t},w.subject=function(M){return arguments.length?(n=typeof M=="function"?M:Yh(M),w):n},w.touchable=function(M){return arguments.length?(i=typeof M=="function"?M:Yh(!!M),w):i},w.on=function(){var M=l.on.apply(l,arguments);return M===l?w:M},w.clickDistance=function(M){return arguments.length?(y=(M=+M)*M,w):Math.sqrt(y)},w}function Lg(e,t,n){e.prototype=t.prototype=n,n.constructor=e}function gb(e,t){var n=Object.create(e.prototype);for(var i in t)n[i]=t[i];return n}function zf(){}var Sf=.7,Am=1/Sf,Lu="\\s*([+-]?\\d+)\\s*",kf="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",Uo="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",w$=/^#([0-9a-f]{3,8})$/,v$=new RegExp(`^rgb\\(${Lu},${Lu},${Lu}\\)$`),x$=new RegExp(`^rgb\\(${Uo},${Uo},${Uo}\\)$`),b$=new RegExp(`^rgba\\(${Lu},${Lu},${Lu},${kf}\\)$`),j$=new RegExp(`^rgba\\(${Uo},${Uo},${Uo},${kf}\\)$`),S$=new RegExp(`^hsl\\(${kf},${Uo},${Uo}\\)$`),k$=new RegExp(`^hsla\\(${kf},${Uo},${Uo},${kf}\\)$`),vw={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};Lg(zf,Nf,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:xw,formatHex:xw,formatHex8:N$,formatHsl:C$,formatRgb:bw,toString:bw});function xw(){return this.rgb().formatHex()}function N$(){return this.rgb().formatHex8()}function C$(){return yb(this).formatHsl()}function bw(){return this.rgb().formatRgb()}function Nf(e){var t,n;return e=(e+"").trim().toLowerCase(),(t=w$.exec(e))?(n=t[1].length,t=parseInt(t[1],16),n===6?jw(t):n===3?new Yr(t>>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):n===8?Jh(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?Jh(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=v$.exec(e))?new Yr(t[1],t[2],t[3],1):(t=x$.exec(e))?new Yr(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=b$.exec(e))?Jh(t[1],t[2],t[3],t[4]):(t=j$.exec(e))?Jh(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=S$.exec(e))?Nw(t[1],t[2]/100,t[3]/100,1):(t=k$.exec(e))?Nw(t[1],t[2]/100,t[3]/100,t[4]):vw.hasOwnProperty(e)?jw(vw[e]):e==="transparent"?new Yr(NaN,NaN,NaN,0):null}function jw(e){return new Yr(e>>16&255,e>>8&255,e&255,1)}function Jh(e,t,n,i){return i<=0&&(e=t=n=NaN),new Yr(e,t,n,i)}function E$(e){return e instanceof zf||(e=Nf(e)),e?(e=e.rgb(),new Yr(e.r,e.g,e.b,e.opacity)):new Yr}function Gp(e,t,n,i){return arguments.length===1?E$(e):new Yr(e,t,n,i??1)}function Yr(e,t,n,i){this.r=+e,this.g=+t,this.b=+n,this.opacity=+i}Lg(Yr,Gp,gb(zf,{brighter(e){return e=e==null?Am:Math.pow(Am,e),new Yr(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=e==null?Sf:Math.pow(Sf,e),new Yr(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new Yr(sc(this.r),sc(this.g),sc(this.b),Tm(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:Sw,formatHex:Sw,formatHex8:$$,formatRgb:kw,toString:kw}));function Sw(){return`#${Zl(this.r)}${Zl(this.g)}${Zl(this.b)}`}function $$(){return`#${Zl(this.r)}${Zl(this.g)}${Zl(this.b)}${Zl((isNaN(this.opacity)?1:this.opacity)*255)}`}function kw(){const e=Tm(this.opacity);return`${e===1?"rgb(":"rgba("}${sc(this.r)}, ${sc(this.g)}, ${sc(this.b)}${e===1?")":`, ${e})`}`}function Tm(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function sc(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function Zl(e){return e=sc(e),(e<16?"0":"")+e.toString(16)}function Nw(e,t,n,i){return i<=0?e=t=n=NaN:n<=0||n>=1?e=t=NaN:t<=0&&(e=NaN),new ro(e,t,n,i)}function yb(e){if(e instanceof ro)return new ro(e.h,e.s,e.l,e.opacity);if(e instanceof zf||(e=Nf(e)),!e)return new ro;if(e instanceof ro)return e;e=e.rgb();var t=e.r/255,n=e.g/255,i=e.b/255,o=Math.min(t,n,i),l=Math.max(t,n,i),u=NaN,c=l-o,f=(l+o)/2;return c?(t===l?u=(n-i)/c+(n<i)*6:n===l?u=(i-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 ro(u,c,f,e.opacity)}function A$(e,t,n,i){return arguments.length===1?yb(e):new ro(e,t,n,i??1)}function ro(e,t,n,i){this.h=+e,this.s=+t,this.l=+n,this.opacity=+i}Lg(ro,A$,gb(zf,{brighter(e){return e=e==null?Am:Math.pow(Am,e),new ro(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?Sf:Math.pow(Sf,e),new ro(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,i=n+(n<.5?n:1-n)*t,o=2*n-i;return new Yr(np(e>=240?e-240:e+120,o,i),np(e,o,i),np(e<120?e+240:e-120,o,i),this.opacity)},clamp(){return new ro(Cw(this.h),Xh(this.s),Xh(this.l),Tm(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=Tm(this.opacity);return`${e===1?"hsl(":"hsla("}${Cw(this.h)}, ${Xh(this.s)*100}%, ${Xh(this.l)*100}%${e===1?")":`, ${e})`}`}}));function Cw(e){return e=(e||0)%360,e<0?e+360:e}function Xh(e){return Math.max(0,Math.min(1,e||0))}function np(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 wb=e=>()=>e;function T$(e,t){return function(n){return e+n*t}}function M$(e,t,n){return e=Math.pow(e,n),t=Math.pow(t,n)-e,n=1/n,function(i){return Math.pow(e+i*t,n)}}function R$(e){return(e=+e)==1?vb:function(t,n){return n-t?M$(t,n,e):wb(isNaN(t)?n:t)}}function vb(e,t){var n=t-e;return n?T$(e,n):wb(isNaN(e)?t:e)}const Ew=(function e(t){var n=R$(t);function i(o,l){var u=n((o=Gp(o)).r,(l=Gp(l)).r),c=n(o.g,l.g),f=n(o.b,l.b),_=vb(o.opacity,l.opacity);return function(p){return o.r=u(p),o.g=c(p),o.b=f(p),o.opacity=_(p),o+""}}return i.gamma=e,i})(1);function ul(e,t){return e=+e,t=+t,function(n){return e*(1-n)+t*n}}var Kp=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,sp=new RegExp(Kp.source,"g");function L$(e){return function(){return e}}function I$(e){return function(t){return e(t)+""}}function O$(e,t){var n=Kp.lastIndex=sp.lastIndex=0,i,o,l,u=-1,c=[],f=[];for(e=e+"",t=t+"";(i=Kp.exec(e))&&(o=sp.exec(t));)(l=o.index)>n&&(l=t.slice(n,l),c[u]?c[u]+=l:c[++u]=l),(i=i[0])===(o=o[0])?c[u]?c[u]+=o:c[++u]=o:(c[++u]=null,f.push({i:u,x:ul(i,o)})),n=sp.lastIndex;return n<t.length&&(l=t.slice(n),c[u]?c[u]+=l:c[++u]=l),c.length<2?f[0]?I$(f[0].x):L$(t):(t=f.length,function(_){for(var p=0,y;p<t;++p)c[(y=f[p]).i]=y.x(_);return c.join("")})}var $w=180/Math.PI,Yp={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function xb(e,t,n,i,o,l){var u,c,f;return(u=Math.sqrt(e*e+t*t))&&(e/=u,t/=u),(f=e*n+t*i)&&(n-=e*f,i-=t*f),(c=Math.sqrt(n*n+i*i))&&(n/=c,i/=c,f/=c),e*i<t*n&&(e=-e,t=-t,f=-f,u=-u),{translateX:o,translateY:l,rotate:Math.atan2(t,e)*$w,skewX:Math.atan(f)*$w,scaleX:u,scaleY:c}}var Zh;function P$(e){const t=new(typeof DOMMatrix=="function"?DOMMatrix:WebKitCSSMatrix)(e+"");return t.isIdentity?Yp:xb(t.a,t.b,t.c,t.d,t.e,t.f)}function D$(e){return e==null||(Zh||(Zh=document.createElementNS("http://www.w3.org/2000/svg","g")),Zh.setAttribute("transform",e),!(e=Zh.transform.baseVal.consolidate()))?Yp:(e=e.matrix,xb(e.a,e.b,e.c,e.d,e.e,e.f))}function bb(e,t,n,i){function o(_){return _.length?_.pop()+" ":""}function l(_,p,y,w,x,S){if(_!==y||p!==w){var j=x.push("translate(",null,t,null,n);S.push({i:j-4,x:ul(_,y)},{i:j-2,x:ul(p,w)})}else(y||w)&&x.push("translate("+y+t+w+n)}function u(_,p,y,w){_!==p?(_-p>180?p+=360:p-_>180&&(_+=360),w.push({i:y.push(o(y)+"rotate(",null,i)-2,x:ul(_,p)})):p&&y.push(o(y)+"rotate("+p+i)}function c(_,p,y,w){_!==p?w.push({i:y.push(o(y)+"skewX(",null,i)-2,x:ul(_,p)}):p&&y.push(o(y)+"skewX("+p+i)}function f(_,p,y,w,x,S){if(_!==y||p!==w){var j=x.push(o(x)+"scale(",null,",",null,")");S.push({i:j-4,x:ul(_,y)},{i:j-2,x:ul(p,w)})}else(y!==1||w!==1)&&x.push(o(x)+"scale("+y+","+w+")")}return function(_,p){var y=[],w=[];return _=e(_),p=e(p),l(_.translateX,_.translateY,p.translateX,p.translateY,y,w),u(_.rotate,p.rotate,y,w),c(_.skewX,p.skewX,y,w),f(_.scaleX,_.scaleY,p.scaleX,p.scaleY,y,w),_=p=null,function(x){for(var S=-1,j=w.length,E;++S<j;)y[(E=w[S]).i]=E.x(x);return y.join("")}}}var F$=bb(P$,"px, ","px)","deg)"),z$=bb(D$,", ",")",")"),B$=1e-12;function Aw(e){return((e=Math.exp(e))+1/e)/2}function U$(e){return((e=Math.exp(e))-1/e)/2}function W$(e){return((e=Math.exp(2*e))-1)/(e+1)}const q$=(function e(t,n,i){function o(l,u){var c=l[0],f=l[1],_=l[2],p=u[0],y=u[1],w=u[2],x=p-c,S=y-f,j=x*x+S*S,E,A;if(j<B$)A=Math.log(w/_)/t,E=function(Y){return[c+Y*x,f+Y*S,_*Math.exp(t*Y*A)]};else{var L=Math.sqrt(j),O=(w*w-_*_+i*j)/(2*_*n*L),M=(w*w-_*_-i*j)/(2*w*n*L),H=Math.log(Math.sqrt(O*O+1)-O),X=Math.log(Math.sqrt(M*M+1)-M);A=(X-H)/t,E=function(Y){var Z=Y*A,re=Aw(H),ie=_/(n*L)*(re*W$(t*Z+H)-U$(H));return[c+ie*x,f+ie*S,_*re/Aw(t*Z+H)]}}return E.duration=A*1e3*t/Math.SQRT2,E}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 zu=0,gf=0,of=0,jb=1e3,Mm,yf,Rm=0,ac=0,Jm=0,Cf=typeof performance=="object"&&performance.now?performance:Date,Sb=typeof window=="object"&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(e){setTimeout(e,17)};function Ig(){return ac||(Sb(H$),ac=Cf.now()+Jm)}function H$(){ac=0}function Lm(){this._call=this._time=this._next=null}Lm.prototype=kb.prototype={constructor:Lm,restart:function(e,t,n){if(typeof e!="function")throw new TypeError("callback is not a function");n=(n==null?Ig():+n)+(t==null?0:+t),!this._next&&yf!==this&&(yf?yf._next=this:Mm=this,yf=this),this._call=e,this._time=n,Jp()},stop:function(){this._call&&(this._call=null,this._time=1/0,Jp())}};function kb(e,t,n){var i=new Lm;return i.restart(e,t,n),i}function V$(){Ig(),++zu;for(var e=Mm,t;e;)(t=ac-e._time)>=0&&e._call.call(void 0,t),e=e._next;--zu}function Tw(){ac=(Rm=Cf.now())+Jm,zu=gf=0;try{V$()}finally{zu=0,K$(),ac=0}}function G$(){var e=Cf.now(),t=e-Rm;t>jb&&(Jm-=t,Rm=e)}function K$(){for(var e,t=Mm,n,i=1/0;t;)t._call?(i>t._time&&(i=t._time),e=t,t=t._next):(n=t._next,t._next=null,t=e?e._next=n:Mm=n);yf=e,Jp(i)}function Jp(e){if(!zu){gf&&(gf=clearTimeout(gf));var t=e-ac;t>24?(e<1/0&&(gf=setTimeout(Tw,e-Cf.now()-Jm)),of&&(of=clearInterval(of))):(of||(Rm=Cf.now(),of=setInterval(G$,jb)),zu=1,Sb(Tw))}}function Mw(e,t,n){var i=new Lm;return t=t==null?0:+t,i.restart(o=>{i.stop(),e(o+t)},t,n),i}var Y$=Km("start","end","cancel","interrupt"),J$=[],Nb=0,Rw=1,Xp=2,hm=3,Lw=4,Zp=5,mm=6;function Xm(e,t,n,i,o,l){var u=e.__transition;if(!u)e.__transition={};else if(n in u)return;X$(e,n,{name:t,index:i,group:o,on:Y$,tween:J$,time:l.time,delay:l.delay,duration:l.duration,ease:l.ease,timer:null,state:Nb})}function Og(e,t){var n=ao(e,t);if(n.state>Nb)throw new Error("too late; already scheduled");return n}function Wo(e,t){var n=ao(e,t);if(n.state>hm)throw new Error("too late; already running");return n}function ao(e,t){var n=e.__transition;if(!n||!(n=n[t]))throw new Error("transition not found");return n}function X$(e,t,n){var i=e.__transition,o;i[t]=n,n.timer=kb(l,0,n.time);function l(_){n.state=Rw,n.timer.restart(u,n.delay,n.time),n.delay<=_&&u(_-n.delay)}function u(_){var p,y,w,x;if(n.state!==Rw)return f();for(p in i)if(x=i[p],x.name===n.name){if(x.state===hm)return Mw(u);x.state===Lw?(x.state=mm,x.timer.stop(),x.on.call("interrupt",e,e.__data__,x.index,x.group),delete i[p]):+p<t&&(x.state=mm,x.timer.stop(),x.on.call("cancel",e,e.__data__,x.index,x.group),delete i[p])}if(Mw(function(){n.state===hm&&(n.state=Lw,n.timer.restart(c,n.delay,n.time),c(_))}),n.state=Xp,n.on.call("start",e,e.__data__,n.index,n.group),n.state===Xp){for(n.state=hm,o=new Array(w=n.tween.length),p=0,y=-1;p<w;++p)(x=n.tween[p].value.call(e,e.__data__,n.index,n.group))&&(o[++y]=x);o.length=y+1}}function c(_){for(var p=_<n.duration?n.ease.call(null,_/n.duration):(n.timer.restart(f),n.state=Zp,1),y=-1,w=o.length;++y<w;)o[y].call(e,p);n.state===Zp&&(n.on.call("end",e,e.__data__,n.index,n.group),f())}function f(){n.state=mm,n.timer.stop(),delete i[t];for(var _ in i)return;delete e.__transition}}function _m(e,t){var n=e.__transition,i,o,l=!0,u;if(n){t=t==null?null:t+"";for(u in n){if((i=n[u]).name!==t){l=!1;continue}o=i.state>Xp&&i.state<Zp,i.state=mm,i.timer.stop(),i.on.call(o?"interrupt":"cancel",e,e.__data__,i.index,i.group),delete n[u]}l&&delete e.__transition}}function Z$(e){return this.each(function(){_m(this,e)})}function Q$(e,t){var n,i;return function(){var o=Wo(this,e),l=o.tween;if(l!==n){i=n=l;for(var u=0,c=i.length;u<c;++u)if(i[u].name===t){i=i.slice(),i.splice(u,1);break}}o.tween=i}}function eA(e,t,n){var i,o;if(typeof n!="function")throw new Error;return function(){var l=Wo(this,e),u=l.tween;if(u!==i){o=(i=u).slice();for(var c={name:t,value:n},f=0,_=o.length;f<_;++f)if(o[f].name===t){o[f]=c;break}f===_&&o.push(c)}l.tween=o}}function tA(e,t){var n=this._id;if(e+="",arguments.length<2){for(var i=ao(this.node(),n).tween,o=0,l=i.length,u;o<l;++o)if((u=i[o]).name===e)return u.value;return null}return this.each((t==null?Q$:eA)(n,e,t))}function Pg(e,t,n){var i=e._id;return e.each(function(){var o=Wo(this,i);(o.value||(o.value={}))[t]=n.apply(this,arguments)}),function(o){return ao(o,i).value[t]}}function Cb(e,t){var n;return(typeof t=="number"?ul:t instanceof Nf?Ew:(n=Nf(t))?(t=n,Ew):O$)(e,t)}function nA(e){return function(){this.removeAttribute(e)}}function sA(e){return function(){this.removeAttributeNS(e.space,e.local)}}function rA(e,t,n){var i,o=n+"",l;return function(){var u=this.getAttribute(e);return u===o?null:u===i?l:l=t(i=u,n)}}function iA(e,t,n){var i,o=n+"",l;return function(){var u=this.getAttributeNS(e.space,e.local);return u===o?null:u===i?l:l=t(i=u,n)}}function oA(e,t,n){var i,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===i&&f===o?l:(o=f,l=t(i=u,c)))}}function aA(e,t,n){var i,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===i&&f===o?l:(o=f,l=t(i=u,c)))}}function lA(e,t){var n=Ym(e),i=n==="transform"?z$:Cb;return this.attrTween(e,typeof t=="function"?(n.local?aA:oA)(n,i,Pg(this,"attr."+e,t)):t==null?(n.local?sA:nA)(n):(n.local?iA:rA)(n,i,t))}function cA(e,t){return function(n){this.setAttribute(e,t.call(this,n))}}function uA(e,t){return function(n){this.setAttributeNS(e.space,e.local,t.call(this,n))}}function dA(e,t){var n,i;function o(){var l=t.apply(this,arguments);return l!==i&&(n=(i=l)&&uA(e,l)),n}return o._value=t,o}function fA(e,t){var n,i;function o(){var l=t.apply(this,arguments);return l!==i&&(n=(i=l)&&cA(e,l)),n}return o._value=t,o}function hA(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 i=Ym(e);return this.tween(n,(i.local?dA:fA)(i,t))}function mA(e,t){return function(){Og(this,e).delay=+t.apply(this,arguments)}}function _A(e,t){return t=+t,function(){Og(this,e).delay=t}}function pA(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?mA:_A)(t,e)):ao(this.node(),t).delay}function gA(e,t){return function(){Wo(this,e).duration=+t.apply(this,arguments)}}function yA(e,t){return t=+t,function(){Wo(this,e).duration=t}}function wA(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?gA:yA)(t,e)):ao(this.node(),t).duration}function vA(e,t){if(typeof t!="function")throw new Error;return function(){Wo(this,e).ease=t}}function xA(e){var t=this._id;return arguments.length?this.each(vA(t,e)):ao(this.node(),t).ease}function bA(e,t){return function(){var n=t.apply(this,arguments);if(typeof n!="function")throw new Error;Wo(this,e).ease=n}}function jA(e){if(typeof e!="function")throw new Error;return this.each(bA(this._id,e))}function SA(e){typeof e!="function"&&(e=ib(e));for(var t=this._groups,n=t.length,i=new Array(n),o=0;o<n;++o)for(var l=t[o],u=l.length,c=i[o]=[],f,_=0;_<u;++_)(f=l[_])&&e.call(f,f.__data__,_,l)&&c.push(f);return new Ea(i,this._parents,this._name,this._id)}function kA(e){if(e._id!==this._id)throw new Error;for(var t=this._groups,n=e._groups,i=t.length,o=n.length,l=Math.min(i,o),u=new Array(i),c=0;c<l;++c)for(var f=t[c],_=n[c],p=f.length,y=u[c]=new Array(p),w,x=0;x<p;++x)(w=f[x]||_[x])&&(y[x]=w);for(;c<i;++c)u[c]=t[c];return new Ea(u,this._parents,this._name,this._id)}function NA(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 CA(e,t,n){var i,o,l=NA(t)?Og:Wo;return function(){var u=l(this,e),c=u.on;c!==i&&(o=(i=c).copy()).on(t,n),u.on=o}}function EA(e,t){var n=this._id;return arguments.length<2?ao(this.node(),n).on.on(e):this.each(CA(n,e,t))}function $A(e){return function(){var t=this.parentNode;for(var n in this.__transition)if(+n!==e)return;t&&t.removeChild(this)}}function AA(){return this.on("end.remove",$A(this._id))}function TA(e){var t=this._name,n=this._id;typeof e!="function"&&(e=Mg(e));for(var i=this._groups,o=i.length,l=new Array(o),u=0;u<o;++u)for(var c=i[u],f=c.length,_=l[u]=new Array(f),p,y,w=0;w<f;++w)(p=c[w])&&(y=e.call(p,p.__data__,w,c))&&("__data__"in p&&(y.__data__=p.__data__),_[w]=y,Xm(_[w],t,n,w,_,ao(p,n)));return new Ea(l,this._parents,t,n)}function MA(e){var t=this._name,n=this._id;typeof e!="function"&&(e=rb(e));for(var i=this._groups,o=i.length,l=[],u=[],c=0;c<o;++c)for(var f=i[c],_=f.length,p,y=0;y<_;++y)if(p=f[y]){for(var w=e.call(p,p.__data__,y,f),x,S=ao(p,n),j=0,E=w.length;j<E;++j)(x=w[j])&&Xm(x,t,n,j,w,S);l.push(w),u.push(p)}return new Ea(l,u,t,n)}var RA=Ff.prototype.constructor;function LA(){return new RA(this._groups,this._parents)}function IA(e,t){var n,i,o;return function(){var l=Fu(this,e),u=(this.style.removeProperty(e),Fu(this,e));return l===u?null:l===n&&u===i?o:o=t(n=l,i=u)}}function Eb(e){return function(){this.style.removeProperty(e)}}function OA(e,t,n){var i,o=n+"",l;return function(){var u=Fu(this,e);return u===o?null:u===i?l:l=t(i=u,n)}}function PA(e,t,n){var i,o,l;return function(){var u=Fu(this,e),c=n(this),f=c+"";return c==null&&(f=c=(this.style.removeProperty(e),Fu(this,e))),u===f?null:u===i&&f===o?l:(o=f,l=t(i=u,c))}}function DA(e,t){var n,i,o,l="style."+t,u="end."+l,c;return function(){var f=Wo(this,e),_=f.on,p=f.value[l]==null?c||(c=Eb(t)):void 0;(_!==n||o!==p)&&(i=(n=_).copy()).on(u,o=p),f.on=i}}function FA(e,t,n){var i=(e+="")=="transform"?F$:Cb;return t==null?this.styleTween(e,IA(e,i)).on("end.style."+e,Eb(e)):typeof t=="function"?this.styleTween(e,PA(e,i,Pg(this,"style."+e,t))).each(DA(this._id,e)):this.styleTween(e,OA(e,i,t),n).on("end.style."+e,null)}function zA(e,t,n){return function(i){this.style.setProperty(e,t.call(this,i),n)}}function BA(e,t,n){var i,o;function l(){var u=t.apply(this,arguments);return u!==o&&(i=(o=u)&&zA(e,u,n)),i}return l._value=t,l}function UA(e,t,n){var i="style."+(e+="");if(arguments.length<2)return(i=this.tween(i))&&i._value;if(t==null)return this.tween(i,null);if(typeof t!="function")throw new Error;return this.tween(i,BA(e,t,n??""))}function WA(e){return function(){this.textContent=e}}function qA(e){return function(){var t=e(this);this.textContent=t??""}}function HA(e){return this.tween("text",typeof e=="function"?qA(Pg(this,"text",e)):WA(e==null?"":e+""))}function VA(e){return function(t){this.textContent=e.call(this,t)}}function GA(e){var t,n;function i(){var o=e.apply(this,arguments);return o!==n&&(t=(n=o)&&VA(o)),t}return i._value=e,i}function KA(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,GA(e))}function YA(){for(var e=this._name,t=this._id,n=$b(),i=this._groups,o=i.length,l=0;l<o;++l)for(var u=i[l],c=u.length,f,_=0;_<c;++_)if(f=u[_]){var p=ao(f,t);Xm(f,e,n,_,u,{time:p.time+p.delay+p.duration,delay:0,duration:p.duration,ease:p.ease})}return new Ea(i,this._parents,e,n)}function JA(){var e,t,n=this,i=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 _=Wo(this,i),p=_.on;p!==e&&(t=(e=p).copy(),t._.cancel.push(c),t._.interrupt.push(c),t._.end.push(f)),_.on=t}),o===0&&l()})}var XA=0;function Ea(e,t,n,i){this._groups=e,this._parents=t,this._name=n,this._id=i}function $b(){return++XA}var ba=Ff.prototype;Ea.prototype={constructor:Ea,select:TA,selectAll:MA,selectChild:ba.selectChild,selectChildren:ba.selectChildren,filter:SA,merge:kA,selection:LA,transition:YA,call:ba.call,nodes:ba.nodes,node:ba.node,size:ba.size,empty:ba.empty,each:ba.each,on:EA,attr:lA,attrTween:hA,style:FA,styleTween:UA,text:HA,textTween:KA,remove:AA,tween:tA,delay:pA,duration:wA,ease:xA,easeVarying:jA,end:JA,[Symbol.iterator]:ba[Symbol.iterator]};function ZA(e){return((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2}var QA={time:null,delay:0,duration:250,ease:ZA};function eT(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 tT(e){var t,n;e instanceof Ea?(t=e._id,e=e._name):(t=$b(),(n=QA).time=Ig(),e=e==null?null:e+"");for(var i=this._groups,o=i.length,l=0;l<o;++l)for(var u=i[l],c=u.length,f,_=0;_<c;++_)(f=u[_])&&Xm(f,e,t,_,u,n||eT(f,t));return new Ea(i,this._parents,e,t)}Ff.prototype.interrupt=Z$;Ff.prototype.transition=tT;const Qh=e=>()=>e;function nT(e,{sourceEvent:t,target:n,transform:i,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:i,enumerable:!0,configurable:!0},_:{value:o}})}function ja(e,t,n){this.k=e,this.x=t,this.y=n}ja.prototype={constructor:ja,scale:function(e){return e===1?this:new ja(this.k*e,this.x,this.y)},translate:function(e,t){return e===0&t===0?this:new ja(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 ka=new ja(1,0,0);ja.prototype;function rp(e){e.stopImmediatePropagation()}function af(e){e.preventDefault(),e.stopImmediatePropagation()}function sT(e){return(!e.ctrlKey||e.type==="wheel")&&!e.button}function rT(){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 Iw(){return this.__zoom||ka}function iT(e){return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*(e.ctrlKey?10:1)}function oT(){return navigator.maxTouchPoints||"ontouchstart"in this}function aT(e,t,n){var i=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>i?(i+o)/2:Math.min(0,i)||Math.max(0,o),u>l?(l+u)/2:Math.min(0,l)||Math.max(0,u))}function Ab(){var e=sT,t=rT,n=aT,i=iT,o=oT,l=[0,1/0],u=[[-1/0,-1/0],[1/0,1/0]],c=250,f=q$,_=Km("start","zoom","end"),p,y,w,x=500,S=150,j=0,E=10;function A(N){N.property("__zoom",Iw).on("wheel.zoom",Z,{passive:!1}).on("mousedown.zoom",re).on("dblclick.zoom",ie).filter(o).on("touchstart.zoom",ue).on("touchmove.zoom",F).on("touchend.zoom touchcancel.zoom",C).style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}A.transform=function(N,P,D,ne){var B=N.selection?N.selection():N;B.property("__zoom",Iw),N!==B?H(N,P,D,ne):B.interrupt().each(function(){X(this,arguments).event(ne).start().zoom(null,typeof P=="function"?P.apply(this,arguments):P).end()})},A.scaleBy=function(N,P,D,ne){A.scaleTo(N,function(){var B=this.__zoom.k,z=typeof P=="function"?P.apply(this,arguments):P;return B*z},D,ne)},A.scaleTo=function(N,P,D,ne){A.transform(N,function(){var B=t.apply(this,arguments),z=this.__zoom,G=D==null?M(B):typeof D=="function"?D.apply(this,arguments):D,T=z.invert(G),Q=typeof P=="function"?P.apply(this,arguments):P;return n(O(L(z,Q),G,T),B,u)},D,ne)},A.translateBy=function(N,P,D,ne){A.transform(N,function(){return n(this.__zoom.translate(typeof P=="function"?P.apply(this,arguments):P,typeof D=="function"?D.apply(this,arguments):D),t.apply(this,arguments),u)},null,ne)},A.translateTo=function(N,P,D,ne,B){A.transform(N,function(){var z=t.apply(this,arguments),G=this.__zoom,T=ne==null?M(z):typeof ne=="function"?ne.apply(this,arguments):ne;return n(ka.translate(T[0],T[1]).scale(G.k).translate(typeof P=="function"?-P.apply(this,arguments):-P,typeof D=="function"?-D.apply(this,arguments):-D),z,u)},ne,B)};function L(N,P){return P=Math.max(l[0],Math.min(l[1],P)),P===N.k?N:new ja(P,N.x,N.y)}function O(N,P,D){var ne=P[0]-D[0]*N.k,B=P[1]-D[1]*N.k;return ne===N.x&&B===N.y?N:new ja(N.k,ne,B)}function M(N){return[(+N[0][0]+ +N[1][0])/2,(+N[0][1]+ +N[1][1])/2]}function H(N,P,D,ne){N.on("start.zoom",function(){X(this,arguments).event(ne).start()}).on("interrupt.zoom end.zoom",function(){X(this,arguments).event(ne).end()}).tween("zoom",function(){var B=this,z=arguments,G=X(B,z).event(ne),T=t.apply(B,z),Q=D==null?M(T):typeof D=="function"?D.apply(B,z):D,K=Math.max(T[1][0]-T[0][0],T[1][1]-T[0][1]),J=B.__zoom,oe=typeof P=="function"?P.apply(B,z):P,fe=f(J.invert(Q).concat(K/J.k),oe.invert(Q).concat(K/oe.k));return function(_e){if(_e===1)_e=oe;else{var we=fe(_e),Ae=K/we[2];_e=new ja(Ae,Q[0]-we[0]*Ae,Q[1]-we[1]*Ae)}G.zoom(null,_e)}})}function X(N,P,D){return!D&&N.__zooming||new Y(N,P)}function Y(N,P){this.that=N,this.args=P,this.active=0,this.sourceEvent=null,this.extent=t.apply(N,P),this.taps=0}Y.prototype={event:function(N){return N&&(this.sourceEvent=N),this},start:function(){return++this.active===1&&(this.that.__zooming=this,this.emit("start")),this},zoom:function(N,P){return this.mouse&&N!=="mouse"&&(this.mouse[1]=P.invert(this.mouse[0])),this.touch0&&N!=="touch"&&(this.touch0[1]=P.invert(this.touch0[0])),this.touch1&&N!=="touch"&&(this.touch1[1]=P.invert(this.touch1[0])),this.that.__zoom=P,this.emit("zoom"),this},end:function(){return--this.active===0&&(delete this.that.__zooming,this.emit("end")),this},emit:function(N){var P=Si(this.that).datum();_.call(N,this.that,new nT(N,{sourceEvent:this.sourceEvent,target:A,transform:this.that.__zoom,dispatch:_}),P)}};function Z(N,...P){if(!e.apply(this,arguments))return;var D=X(this,P).event(N),ne=this.__zoom,B=Math.max(l[0],Math.min(l[1],ne.k*Math.pow(2,i.apply(this,arguments)))),z=no(N);if(D.wheel)(D.mouse[0][0]!==z[0]||D.mouse[0][1]!==z[1])&&(D.mouse[1]=ne.invert(D.mouse[0]=z)),clearTimeout(D.wheel);else{if(ne.k===B)return;D.mouse=[z,ne.invert(z)],_m(this),D.start()}af(N),D.wheel=setTimeout(G,S),D.zoom("mouse",n(O(L(ne,B),D.mouse[0],D.mouse[1]),D.extent,u));function G(){D.wheel=null,D.end()}}function re(N,...P){if(w||!e.apply(this,arguments))return;var D=N.currentTarget,ne=X(this,P,!0).event(N),B=Si(N.view).on("mousemove.zoom",Q,!0).on("mouseup.zoom",K,!0),z=no(N,D),G=N.clientX,T=N.clientY;_b(N.view),rp(N),ne.mouse=[z,this.__zoom.invert(z)],_m(this),ne.start();function Q(J){if(af(J),!ne.moved){var oe=J.clientX-G,fe=J.clientY-T;ne.moved=oe*oe+fe*fe>j}ne.event(J).zoom("mouse",n(O(ne.that.__zoom,ne.mouse[0]=no(J,D),ne.mouse[1]),ne.extent,u))}function K(J){B.on("mousemove.zoom mouseup.zoom",null),pb(J.view,ne.moved),af(J),ne.event(J).end()}}function ie(N,...P){if(e.apply(this,arguments)){var D=this.__zoom,ne=no(N.changedTouches?N.changedTouches[0]:N,this),B=D.invert(ne),z=D.k*(N.shiftKey?.5:2),G=n(O(L(D,z),ne,B),t.apply(this,P),u);af(N),c>0?Si(this).transition().duration(c).call(H,G,ne,N):Si(this).call(A.transform,G,ne,N)}}function ue(N,...P){if(e.apply(this,arguments)){var D=N.touches,ne=D.length,B=X(this,P,N.changedTouches.length===ne).event(N),z,G,T,Q;for(rp(N),G=0;G<ne;++G)T=D[G],Q=no(T,this),Q=[Q,this.__zoom.invert(Q),T.identifier],B.touch0?!B.touch1&&B.touch0[2]!==Q[2]&&(B.touch1=Q,B.taps=0):(B.touch0=Q,z=!0,B.taps=1+!!p);p&&(p=clearTimeout(p)),z&&(B.taps<2&&(y=Q[0],p=setTimeout(function(){p=null},x)),_m(this),B.start())}}function F(N,...P){if(this.__zooming){var D=X(this,P).event(N),ne=N.changedTouches,B=ne.length,z,G,T,Q;for(af(N),z=0;z<B;++z)G=ne[z],T=no(G,this),D.touch0&&D.touch0[2]===G.identifier?D.touch0[0]=T:D.touch1&&D.touch1[2]===G.identifier&&(D.touch1[0]=T);if(G=D.that.__zoom,D.touch1){var K=D.touch0[0],J=D.touch0[1],oe=D.touch1[0],fe=D.touch1[1],_e=(_e=oe[0]-K[0])*_e+(_e=oe[1]-K[1])*_e,we=(we=fe[0]-J[0])*we+(we=fe[1]-J[1])*we;G=L(G,Math.sqrt(_e/we)),T=[(K[0]+oe[0])/2,(K[1]+oe[1])/2],Q=[(J[0]+fe[0])/2,(J[1]+fe[1])/2]}else if(D.touch0)T=D.touch0[0],Q=D.touch0[1];else return;D.zoom("touch",n(O(G,T,Q),D.extent,u))}}function C(N,...P){if(this.__zooming){var D=X(this,P).event(N),ne=N.changedTouches,B=ne.length,z,G;for(rp(N),w&&clearTimeout(w),w=setTimeout(function(){w=null},x),z=0;z<B;++z)G=ne[z],D.touch0&&D.touch0[2]===G.identifier?delete D.touch0:D.touch1&&D.touch1[2]===G.identifier&&delete D.touch1;if(D.touch1&&!D.touch0&&(D.touch0=D.touch1,delete D.touch1),D.touch0)D.touch0[1]=this.__zoom.invert(D.touch0[0]);else if(D.end(),D.taps===2&&(G=no(G,this),Math.hypot(y[0]-G[0],y[1]-G[1])<E)){var T=Si(this).on("dblclick.zoom");T&&T.apply(this,arguments)}}}return A.wheelDelta=function(N){return arguments.length?(i=typeof N=="function"?N:Qh(+N),A):i},A.filter=function(N){return arguments.length?(e=typeof N=="function"?N:Qh(!!N),A):e},A.touchable=function(N){return arguments.length?(o=typeof N=="function"?N:Qh(!!N),A):o},A.extent=function(N){return arguments.length?(t=typeof N=="function"?N:Qh([[+N[0][0],+N[0][1]],[+N[1][0],+N[1][1]]]),A):t},A.scaleExtent=function(N){return arguments.length?(l[0]=+N[0],l[1]=+N[1],A):[l[0],l[1]]},A.translateExtent=function(N){return arguments.length?(u[0][0]=+N[0][0],u[1][0]=+N[1][0],u[0][1]=+N[0][1],u[1][1]=+N[1][1],A):[[u[0][0],u[0][1]],[u[1][0],u[1][1]]]},A.constrain=function(N){return arguments.length?(n=N,A):n},A.duration=function(N){return arguments.length?(c=+N,A):c},A.interpolate=function(N){return arguments.length?(f=N,A):f},A.on=function(){var N=_.on.apply(_,arguments);return N===_?A:N},A.clickDistance=function(N){return arguments.length?(j=(N=+N)*N,A):Math.sqrt(j)},A.tapDistance=function(N){return arguments.length?(E=+N,A):E},A}const Zm=m.createContext(null),lT=Zm.Provider,$a={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.`},Tb=$a.error001();function Rn(e,t){const n=m.useContext(Zm);if(n===null)throw new Error(Tb);return nb(n,e,t)}const ks=()=>{const e=m.useContext(Zm);if(e===null)throw new Error(Tb);return m.useMemo(()=>({getState:e.getState,setState:e.setState,subscribe:e.subscribe,destroy:e.destroy}),[e])},cT=e=>e.userSelectionActive?"none":"all";function Ef({position:e,children:t,className:n,style:i,...o}){const l=Rn(cT),u=`${e}`.split("-");return ve.createElement("div",{className:Ys(["react-flow__panel",n,...u]),style:{...i,pointerEvents:l},...o},t)}function uT({proOptions:e,position:t="bottom-right"}){return e!=null&&e.hideAttribution?null:ve.createElement(Ef,{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 dT=({x:e,y:t,label:n,labelStyle:i={},labelShowBg:o=!0,labelBgStyle:l={},labelBgPadding:u=[2,4],labelBgBorderRadius:c=2,children:f,className:_,...p})=>{const y=m.useRef(null),[w,x]=m.useState({x:0,y:0,width:0,height:0}),S=Ys(["react-flow__edge-textwrapper",_]);return m.useEffect(()=>{if(y.current){const j=y.current.getBBox();x({x:j.x,y:j.y,width:j.width,height:j.height})}},[n]),typeof n>"u"||!n?null:ve.createElement("g",{transform:`translate(${e-w.width/2} ${t-w.height/2})`,className:S,visibility:w.width?"visible":"hidden",...p},o&&ve.createElement("rect",{width:w.width+2*u[0],x:-u[0],y:-u[1],height:w.height+2*u[1],className:"react-flow__edge-textbg",style:l,rx:c,ry:c}),ve.createElement("text",{className:"react-flow__edge-text",y:w.height/2,dy:"0.3em",ref:y,style:i},n),f)};var fT=m.memo(dT);const Dg=e=>({width:e.offsetWidth,height:e.offsetHeight}),Bu=(e,t=0,n=1)=>Math.min(Math.max(e,t),n),Fg=(e={x:0,y:0},t)=>({x:Bu(e.x,t[0][0],t[1][0]),y:Bu(e.y,t[0][1],t[1][1])}),Ow=(e,t,n)=>e<t?Bu(Math.abs(e-t),1,50)/50:e>n?-Bu(Math.abs(e-n),1,50)/50:0,Mb=(e,t)=>{const n=Ow(e.x,35,t.width-35)*20,i=Ow(e.y,35,t.height-35)*20;return[n,i]},Rb=e=>{var t;return((t=e.getRootNode)==null?void 0:t.call(e))||(window==null?void 0:window.document)},Lb=(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)}),$f=({x:e,y:t,width:n,height:i})=>({x:e,y:t,x2:e+n,y2:t+i}),Ib=({x:e,y:t,x2:n,y2:i})=>({x:e,y:t,width:n-e,height:i-t}),Pw=e=>({...e.positionAbsolute||{x:0,y:0},width:e.width||0,height:e.height||0}),hT=(e,t)=>Ib(Lb($f(e),$f(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)),i=Math.max(0,Math.min(e.y+e.height,t.y+t.height)-Math.max(e.y,t.y));return Math.ceil(n*i)},mT=e=>ki(e.width)&&ki(e.height)&&ki(e.x)&&ki(e.y),ki=e=>!isNaN(e)&&isFinite(e),hs=Symbol.for("internals"),Ob=["Enter"," ","Escape"],_T=(e,t)=>{},pT=e=>"nativeEvent"in e;function eg(e){var o,l;const t=pT(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 Pb=e=>"clientX"in e,ml=(e,t)=>{var l,u;const n=Pb(e),i=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:i-((t==null?void 0:t.left)??0),y:o-((t==null?void 0:t.top)??0)}},Im=()=>{var e;return typeof navigator<"u"&&((e=navigator==null?void 0:navigator.userAgent)==null?void 0:e.indexOf("Mac"))>=0},Bf=({id:e,path:t,labelX:n,labelY:i,label:o,labelStyle:l,labelShowBg:u,labelBgStyle:c,labelBgPadding:f,labelBgBorderRadius:_,style:p,markerEnd:y,markerStart:w,interactionWidth:x=20})=>ve.createElement(ve.Fragment,null,ve.createElement("path",{id:e,style:p,d:t,fill:"none",className:"react-flow__edge-path",markerEnd:y,markerStart:w}),x&&ve.createElement("path",{d:t,fill:"none",strokeOpacity:0,strokeWidth:x,className:"react-flow__edge-interaction"}),o&&ki(n)&&ki(i)?ve.createElement(fT,{x:n,y:i,label:o,labelStyle:l,labelShowBg:u,labelBgStyle:c,labelBgPadding:f,labelBgBorderRadius:_}):null);Bf.displayName="BaseEdge";function lf(e,t,n){return n===void 0?n:i=>{const o=t().edges.find(l=>l.id===e);o&&n(i,{...o})}}function Db({sourceX:e,sourceY:t,targetX:n,targetY:i}){const o=Math.abs(n-e)/2,l=n<e?n+o:n-o,u=Math.abs(i-t)/2,c=i<t?i+u:i-u;return[l,c,o,u]}function Fb({sourceX:e,sourceY:t,targetX:n,targetY:i,sourceControlX:o,sourceControlY:l,targetControlX:u,targetControlY:c}){const f=e*.125+o*.375+u*.375+n*.125,_=t*.125+l*.375+c*.375+i*.125,p=Math.abs(f-e),y=Math.abs(_-t);return[f,_,p,y]}var lc;(function(e){e.Strict="strict",e.Loose="loose"})(lc||(lc={}));var Ql;(function(e){e.Free="free",e.Vertical="vertical",e.Horizontal="horizontal"})(Ql||(Ql={}));var Af;(function(e){e.Partial="partial",e.Full="full"})(Af||(Af={}));var hl;(function(e){e.Bezier="default",e.Straight="straight",e.Step="step",e.SmoothStep="smoothstep",e.SimpleBezier="simplebezier"})(hl||(hl={}));var Tf;(function(e){e.Arrow="arrow",e.ArrowClosed="arrowclosed"})(Tf||(Tf={}));var mt;(function(e){e.Left="left",e.Top="top",e.Right="right",e.Bottom="bottom"})(mt||(mt={}));function Dw({pos:e,x1:t,y1:n,x2:i,y2:o}){return e===mt.Left||e===mt.Right?[.5*(t+i),n]:[t,.5*(n+o)]}function zb({sourceX:e,sourceY:t,sourcePosition:n=mt.Bottom,targetX:i,targetY:o,targetPosition:l=mt.Top}){const[u,c]=Dw({pos:n,x1:e,y1:t,x2:i,y2:o}),[f,_]=Dw({pos:l,x1:i,y1:o,x2:e,y2:t}),[p,y,w,x]=Fb({sourceX:e,sourceY:t,targetX:i,targetY:o,sourceControlX:u,sourceControlY:c,targetControlX:f,targetControlY:_});return[`M${e},${t} C${u},${c} ${f},${_} ${i},${o}`,p,y,w,x]}const zg=m.memo(({sourceX:e,sourceY:t,targetX:n,targetY:i,sourcePosition:o=mt.Bottom,targetPosition:l=mt.Top,label:u,labelStyle:c,labelShowBg:f,labelBgStyle:_,labelBgPadding:p,labelBgBorderRadius:y,style:w,markerEnd:x,markerStart:S,interactionWidth:j})=>{const[E,A,L]=zb({sourceX:e,sourceY:t,sourcePosition:o,targetX:n,targetY:i,targetPosition:l});return ve.createElement(Bf,{path:E,labelX:A,labelY:L,label:u,labelStyle:c,labelShowBg:f,labelBgStyle:_,labelBgPadding:p,labelBgBorderRadius:y,style:w,markerEnd:x,markerStart:S,interactionWidth:j})});zg.displayName="SimpleBezierEdge";const Fw={[mt.Left]:{x:-1,y:0},[mt.Right]:{x:1,y:0},[mt.Top]:{x:0,y:-1},[mt.Bottom]:{x:0,y:1}},gT=({source:e,sourcePosition:t=mt.Bottom,target:n})=>t===mt.Left||t===mt.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},zw=(e,t)=>Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2));function yT({source:e,sourcePosition:t=mt.Bottom,target:n,targetPosition:i=mt.Top,center:o,offset:l}){const u=Fw[t],c=Fw[i],f={x:e.x+u.x*l,y:e.y+u.y*l},_={x:n.x+c.x*l,y:n.y+c.y*l},p=gT({source:f,sourcePosition:t,target:_}),y=p.x!==0?"x":"y",w=p[y];let x=[],S,j;const E={x:0,y:0},A={x:0,y:0},[L,O,M,H]=Db({sourceX:e.x,sourceY:e.y,targetX:n.x,targetY:n.y});if(u[y]*c[y]===-1){S=o.x||L,j=o.y||O;const Y=[{x:S,y:f.y},{x:S,y:_.y}],Z=[{x:f.x,y:j},{x:_.x,y:j}];u[y]===w?x=y==="x"?Y:Z:x=y==="x"?Z:Y}else{const Y=[{x:f.x,y:_.y}],Z=[{x:_.x,y:f.y}];if(y==="x"?x=u.x===w?Z:Y:x=u.y===w?Y:Z,t===i){const C=Math.abs(e[y]-n[y]);if(C<=l){const N=Math.min(l-1,l-C);u[y]===w?E[y]=(f[y]>e[y]?-1:1)*N:A[y]=(_[y]>n[y]?-1:1)*N}}if(t!==i){const C=y==="x"?"y":"x",N=u[y]===c[C],P=f[C]>_[C],D=f[C]<_[C];(u[y]===1&&(!N&&P||N&&D)||u[y]!==1&&(!N&&D||N&&P))&&(x=y==="x"?Y:Z)}const re={x:f.x+E.x,y:f.y+E.y},ie={x:_.x+A.x,y:_.y+A.y},ue=Math.max(Math.abs(re.x-x[0].x),Math.abs(ie.x-x[0].x)),F=Math.max(Math.abs(re.y-x[0].y),Math.abs(ie.y-x[0].y));ue>=F?(S=(re.x+ie.x)/2,j=x[0].y):(S=x[0].x,j=(re.y+ie.y)/2)}return[[e,{x:f.x+E.x,y:f.y+E.y},...x,{x:_.x+A.x,y:_.y+A.y},n],S,j,M,H]}function wT(e,t,n,i){const o=Math.min(zw(e,t)/2,zw(t,n)/2,i),{x:l,y:u}=t;if(e.x===l&&l===n.x||e.y===u&&u===n.y)return`L${l} ${u}`;if(e.y===u){const _=e.x<n.x?-1:1,p=e.y<n.y?1:-1;return`L ${l+o*_},${u}Q ${l},${u} ${l},${u+o*p}`}const c=e.x<n.x?1:-1,f=e.y<n.y?-1:1;return`L ${l},${u+o*f}Q ${l},${u} ${l+o*c},${u}`}function tg({sourceX:e,sourceY:t,sourcePosition:n=mt.Bottom,targetX:i,targetY:o,targetPosition:l=mt.Top,borderRadius:u=5,centerX:c,centerY:f,offset:_=20}){const[p,y,w,x,S]=yT({source:{x:e,y:t},sourcePosition:n,target:{x:i,y:o},targetPosition:l,center:{x:c,y:f},offset:_});return[p.reduce((E,A,L)=>{let O="";return L>0&&L<p.length-1?O=wT(p[L-1],A,p[L+1],u):O=`${L===0?"M":"L"}${A.x} ${A.y}`,E+=O,E},""),y,w,x,S]}const Qm=m.memo(({sourceX:e,sourceY:t,targetX:n,targetY:i,label:o,labelStyle:l,labelShowBg:u,labelBgStyle:c,labelBgPadding:f,labelBgBorderRadius:_,style:p,sourcePosition:y=mt.Bottom,targetPosition:w=mt.Top,markerEnd:x,markerStart:S,pathOptions:j,interactionWidth:E})=>{const[A,L,O]=tg({sourceX:e,sourceY:t,sourcePosition:y,targetX:n,targetY:i,targetPosition:w,borderRadius:j==null?void 0:j.borderRadius,offset:j==null?void 0:j.offset});return ve.createElement(Bf,{path:A,labelX:L,labelY:O,label:o,labelStyle:l,labelShowBg:u,labelBgStyle:c,labelBgPadding:f,labelBgBorderRadius:_,style:p,markerEnd:x,markerStart:S,interactionWidth:E})});Qm.displayName="SmoothStepEdge";const Bg=m.memo(e=>{var t;return ve.createElement(Qm,{...e,pathOptions:m.useMemo(()=>{var n;return{borderRadius:0,offset:(n=e.pathOptions)==null?void 0:n.offset}},[(t=e.pathOptions)==null?void 0:t.offset])})});Bg.displayName="StepEdge";function vT({sourceX:e,sourceY:t,targetX:n,targetY:i}){const[o,l,u,c]=Db({sourceX:e,sourceY:t,targetX:n,targetY:i});return[`M ${e},${t}L ${n},${i}`,o,l,u,c]}const Ug=m.memo(({sourceX:e,sourceY:t,targetX:n,targetY:i,label:o,labelStyle:l,labelShowBg:u,labelBgStyle:c,labelBgPadding:f,labelBgBorderRadius:_,style:p,markerEnd:y,markerStart:w,interactionWidth:x})=>{const[S,j,E]=vT({sourceX:e,sourceY:t,targetX:n,targetY:i});return ve.createElement(Bf,{path:S,labelX:j,labelY:E,label:o,labelStyle:l,labelShowBg:u,labelBgStyle:c,labelBgPadding:f,labelBgBorderRadius:_,style:p,markerEnd:y,markerStart:w,interactionWidth:x})});Ug.displayName="StraightEdge";function em(e,t){return e>=0?.5*e:t*25*Math.sqrt(-e)}function Bw({pos:e,x1:t,y1:n,x2:i,y2:o,c:l}){switch(e){case mt.Left:return[t-em(t-i,l),n];case mt.Right:return[t+em(i-t,l),n];case mt.Top:return[t,n-em(n-o,l)];case mt.Bottom:return[t,n+em(o-n,l)]}}function Bb({sourceX:e,sourceY:t,sourcePosition:n=mt.Bottom,targetX:i,targetY:o,targetPosition:l=mt.Top,curvature:u=.25}){const[c,f]=Bw({pos:n,x1:e,y1:t,x2:i,y2:o,c:u}),[_,p]=Bw({pos:l,x1:i,y1:o,x2:e,y2:t,c:u}),[y,w,x,S]=Fb({sourceX:e,sourceY:t,targetX:i,targetY:o,sourceControlX:c,sourceControlY:f,targetControlX:_,targetControlY:p});return[`M${e},${t} C${c},${f} ${_},${p} ${i},${o}`,y,w,x,S]}const Om=m.memo(({sourceX:e,sourceY:t,targetX:n,targetY:i,sourcePosition:o=mt.Bottom,targetPosition:l=mt.Top,label:u,labelStyle:c,labelShowBg:f,labelBgStyle:_,labelBgPadding:p,labelBgBorderRadius:y,style:w,markerEnd:x,markerStart:S,pathOptions:j,interactionWidth:E})=>{const[A,L,O]=Bb({sourceX:e,sourceY:t,sourcePosition:o,targetX:n,targetY:i,targetPosition:l,curvature:j==null?void 0:j.curvature});return ve.createElement(Bf,{path:A,labelX:L,labelY:O,label:u,labelStyle:c,labelShowBg:f,labelBgStyle:_,labelBgPadding:p,labelBgBorderRadius:y,style:w,markerEnd:x,markerStart:S,interactionWidth:E})});Om.displayName="BezierEdge";const Wg=m.createContext(null),xT=Wg.Provider;Wg.Consumer;const bT=()=>m.useContext(Wg),jT=e=>"id"in e&&"source"in e&&"target"in e,ST=({source:e,sourceHandle:t,target:n,targetHandle:i})=>`reactflow__edge-${e}${t||""}-${n}${i||""}`,ng=(e,t)=>typeof e>"u"?"":typeof e=="string"?e:`${t?`${t}__`:""}${Object.keys(e).sort().map(i=>`${i}=${e[i]}`).join("&")}`,kT=(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)),NT=(e,t)=>{if(!e.source||!e.target)return t;let n;return jT(e)?n={...e}:n={...e,id:ST(e)},kT(n,t)?t:t.concat(n)},sg=({x:e,y:t},[n,i,o],l,[u,c])=>{const f={x:(e-n)/o,y:(t-i)/o};return l?{x:u*Math.round(f.x/u),y:c*Math.round(f.y/c)}:f},Ub=({x:e,y:t},[n,i,o])=>({x:e*o+n,y:t*o+i}),rc=(e,t=[0,0])=>{if(!e)return{x:0,y:0,positionAbsolute:{x:0,y:0}};const n=(e.width??0)*t[0],i=(e.height??0)*t[1],o={x:e.position.x-n,y:e.position.y-i};return{...o,positionAbsolute:e.positionAbsolute?{x:e.positionAbsolute.x-n,y:e.positionAbsolute.y-i}:o}},e_=(e,t=[0,0])=>{if(e.length===0)return{x:0,y:0,width:0,height:0};const n=e.reduce((i,o)=>{const{x:l,y:u}=rc(o,t).positionAbsolute;return Lb(i,$f({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 Ib(n)},Wb=(e,t,[n,i,o]=[0,0,1],l=!1,u=!1,c=[0,0])=>{const f={x:(t.x-n)/o,y:(t.y-i)/o,width:t.width/o,height:t.height/o},_=[];return e.forEach(p=>{const{width:y,height:w,selectable:x=!0,hidden:S=!1}=p;if(u&&!x||S)return!1;const{positionAbsolute:j}=rc(p,c),E={x:j.x,y:j.y,width:y||0,height:w||0},A=Qp(f,E),L=typeof y>"u"||typeof w>"u"||y===null||w===null,O=l&&A>0,M=(y||0)*(w||0);(L||O||A>=M||p.dragging)&&_.push(p)}),_},qb=(e,t)=>{const n=e.map(i=>i.id);return t.filter(i=>n.includes(i.source)||n.includes(i.target))},Hb=(e,t,n,i,o,l=.1)=>{const u=t/(e.width*(1+l)),c=n/(e.height*(1+l)),f=Math.min(u,c),_=Bu(f,i,o),p=e.x+e.width/2,y=e.y+e.height/2,w=t/2-p*_,x=n/2-y*_;return{x:w,y:x,zoom:_}},Kl=(e,t=0)=>e.transition().duration(t);function Uw(e,t,n,i){return(t[n]||[]).reduce((o,l)=>{var u,c;return`${e.id}-${l.id}-${n}`!==i&&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 CT(e,t,n,i,o,l){const{x:u,y:c}=ml(e),_=t.elementsFromPoint(u,c).find(S=>S.classList.contains("react-flow__handle"));if(_){const S=_.getAttribute("data-nodeid");if(S){const j=qg(void 0,_),E=_.getAttribute("data-handleid"),A=l({nodeId:S,id:E,type:j});if(A){const L=o.find(O=>O.nodeId===S&&O.type===j&&O.id===E);return{handle:{id:E,type:j,nodeId:S,x:(L==null?void 0:L.x)||n.x,y:(L==null?void 0:L.y)||n.y},validHandleResult:A}}}}let p=[],y=1/0;if(o.forEach(S=>{const j=Math.sqrt((S.x-n.x)**2+(S.y-n.y)**2);if(j<=i){const E=l(S);j<=y&&(j<y?p=[{handle:S,validHandleResult:E}]:j===y&&p.push({handle:S,validHandleResult:E}),y=j)}}),!p.length)return{handle:null,validHandleResult:Vb()};if(p.length===1)return p[0];const w=p.some(({validHandleResult:S})=>S.isValid),x=p.some(({handle:S})=>S.type==="target");return p.find(({handle:S,validHandleResult:j})=>x?S.type==="target":w?j.isValid:!0)||p[0]}const ET={source:null,target:null,sourceHandle:null,targetHandle:null},Vb=()=>({handleDomNode:null,isValid:!1,connection:ET,endHandle:null});function Gb(e,t,n,i,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}"]`),_={...Vb(),handleDomNode:f};if(f){const p=qg(void 0,f),y=f.getAttribute("data-nodeid"),w=f.getAttribute("data-handleid"),x=f.classList.contains("connectable"),S=f.classList.contains("connectableend"),j={source:c?y:n,sourceHandle:c?w:i,target:c?n:y,targetHandle:c?i:w};_.connection=j,x&&S&&(t===lc.Strict?c&&p==="source"||!c&&p==="target":y!==n||w!==i)&&(_.endHandle={nodeId:y,handleId:w,type:p},_.isValid=l(j))}return _}function $T({nodes:e,nodeId:t,handleId:n,handleType:i}){return e.reduce((o,l)=>{if(l[hs]){const{handleBounds:u}=l[hs];let c=[],f=[];u&&(c=Uw(l,u,"source",`${t}-${n}-${i}`),f=Uw(l,u,"target",`${t}-${n}-${i}`)),o.push(...c,...f)}return o},[])}function qg(e,t){return e||(t!=null&&t.classList.contains("target")?"target":t!=null&&t.classList.contains("source")?"source":null)}function ip(e){e==null||e.classList.remove("valid","connecting","react-flow__handle-valid","react-flow__handle-connecting")}function AT(e,t){let n=null;return t?n="valid":e&&!t&&(n="invalid"),n}function Kb({event:e,handleId:t,nodeId:n,onConnect:i,isTarget:o,getState:l,setState:u,isValidConnection:c,edgeUpdaterType:f,onEdgeUpdateEnd:_}){const p=Rb(e.target),{connectionMode:y,domNode:w,autoPanOnConnect:x,connectionRadius:S,onConnectStart:j,panBy:E,getNodes:A,cancelConnection:L}=l();let O=0,M;const{x:H,y:X}=ml(e),Y=p==null?void 0:p.elementFromPoint(H,X),Z=qg(f,Y),re=w==null?void 0:w.getBoundingClientRect();if(!re||!Z)return;let ie,ue=ml(e,re),F=!1,C=null,N=!1,P=null;const D=$T({nodes:A(),nodeId:n,handleId:t,handleType:Z}),ne=()=>{if(!x)return;const[G,T]=Mb(ue,re);E({x:G,y:T}),O=requestAnimationFrame(ne)};u({connectionPosition:ue,connectionStatus:null,connectionNodeId:n,connectionHandleId:t,connectionHandleType:Z,connectionStartHandle:{nodeId:n,handleId:t,type:Z},connectionEndHandle:null}),j==null||j(e,{nodeId:n,handleId:t,handleType:Z});function B(G){const{transform:T}=l();ue=ml(G,re);const{handle:Q,validHandleResult:K}=CT(G,p,sg(ue,T,!1,[1,1]),S,D,J=>Gb(J,y,n,t,o?"target":"source",c,p));if(M=Q,F||(ne(),F=!0),P=K.handleDomNode,C=K.connection,N=K.isValid,u({connectionPosition:M&&N?Ub({x:M.x,y:M.y},T):ue,connectionStatus:AT(!!M,N),connectionEndHandle:K.endHandle}),!M&&!N&&!P)return ip(ie);C.source!==C.target&&P&&(ip(ie),ie=P,P.classList.add("connecting","react-flow__handle-connecting"),P.classList.toggle("valid",N),P.classList.toggle("react-flow__handle-valid",N))}function z(G){var T,Q;(M||P)&&C&&N&&(i==null||i(C)),(Q=(T=l()).onConnectEnd)==null||Q.call(T,G),f&&(_==null||_(G)),ip(ie),L(),cancelAnimationFrame(O),F=!1,N=!1,C=null,P=null,p.removeEventListener("mousemove",B),p.removeEventListener("mouseup",z),p.removeEventListener("touchmove",B),p.removeEventListener("touchend",z)}p.addEventListener("mousemove",B),p.addEventListener("mouseup",z),p.addEventListener("touchmove",B),p.addEventListener("touchend",z)}const Ww=()=>!0,TT=e=>({connectionStartHandle:e.connectionStartHandle,connectOnClick:e.connectOnClick,noPanClassName:e.noPanClassName}),MT=(e,t,n)=>i=>{const{connectionStartHandle:o,connectionEndHandle:l,connectionClickStartHandle:u}=i;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}},Yb=m.forwardRef(({type:e="source",position:t=mt.Top,isValidConnection:n,isConnectable:i=!0,isConnectableStart:o=!0,isConnectableEnd:l=!0,id:u,onConnect:c,children:f,className:_,onMouseDown:p,onTouchStart:y,...w},x)=>{var re,ie;const S=u||null,j=e==="target",E=ks(),A=bT(),{connectOnClick:L,noPanClassName:O}=Rn(TT,Us),{connecting:M,clickConnecting:H}=Rn(MT(A,S,e),Us);A||(ie=(re=E.getState()).onError)==null||ie.call(re,"010",$a.error010());const X=ue=>{const{defaultEdgeOptions:F,onConnect:C,hasDefaultEdges:N}=E.getState(),P={...F,...ue};if(N){const{edges:D,setEdges:ne}=E.getState();ne(NT(P,D))}C==null||C(P),c==null||c(P)},Y=ue=>{if(!A)return;const F=Pb(ue);o&&(F&&ue.button===0||!F)&&Kb({event:ue,handleId:S,nodeId:A,onConnect:X,isTarget:j,getState:E.getState,setState:E.setState,isValidConnection:n||E.getState().isValidConnection||Ww}),F?p==null||p(ue):y==null||y(ue)},Z=ue=>{const{onClickConnectStart:F,onClickConnectEnd:C,connectionClickStartHandle:N,connectionMode:P,isValidConnection:D}=E.getState();if(!A||!N&&!o)return;if(!N){F==null||F(ue,{nodeId:A,handleId:S,handleType:e}),E.setState({connectionClickStartHandle:{nodeId:A,type:e,handleId:S}});return}const ne=Rb(ue.target),B=n||D||Ww,{connection:z,isValid:G}=Gb({nodeId:A,id:S,type:e},P,N.nodeId,N.handleId||null,N.type,B,ne);G&&X(z),C==null||C(ue),E.setState({connectionClickStartHandle:null})};return ve.createElement("div",{"data-handleid":S,"data-nodeid":A,"data-handlepos":t,"data-id":`${A}-${S}-${e}`,className:Ys(["react-flow__handle",`react-flow__handle-${t}`,"nodrag",O,_,{source:!j,target:j,connectable:i,connectablestart:o,connectableend:l,connecting:H,connectionindicator:i&&(o&&!M||l&&M)}]),onMouseDown:Y,onTouchStart:Y,onClick:L?Z:void 0,ref:x,...w},f)});Yb.displayName="Handle";var Pm=m.memo(Yb);const Jb=({data:e,isConnectable:t,targetPosition:n=mt.Top,sourcePosition:i=mt.Bottom})=>ve.createElement(ve.Fragment,null,ve.createElement(Pm,{type:"target",position:n,isConnectable:t}),e==null?void 0:e.label,ve.createElement(Pm,{type:"source",position:i,isConnectable:t}));Jb.displayName="DefaultNode";var rg=m.memo(Jb);const Xb=({data:e,isConnectable:t,sourcePosition:n=mt.Bottom})=>ve.createElement(ve.Fragment,null,e==null?void 0:e.label,ve.createElement(Pm,{type:"source",position:n,isConnectable:t}));Xb.displayName="InputNode";var Zb=m.memo(Xb);const Qb=({data:e,isConnectable:t,targetPosition:n=mt.Top})=>ve.createElement(ve.Fragment,null,ve.createElement(Pm,{type:"target",position:n,isConnectable:t}),e==null?void 0:e.label);Qb.displayName="OutputNode";var e0=m.memo(Qb);const Hg=()=>null;Hg.displayName="GroupNode";const RT=e=>({selectedNodes:e.getNodes().filter(t=>t.selected),selectedEdges:e.edges.filter(t=>t.selected)}),tm=e=>e.id;function LT(e,t){return Us(e.selectedNodes.map(tm),t.selectedNodes.map(tm))&&Us(e.selectedEdges.map(tm),t.selectedEdges.map(tm))}const t0=m.memo(({onSelectionChange:e})=>{const t=ks(),{selectedNodes:n,selectedEdges:i}=Rn(RT,LT);return m.useEffect(()=>{const o={nodes:n,edges:i};e==null||e(o),t.getState().onSelectionChange.forEach(l=>l(o))},[n,i,e]),null});t0.displayName="SelectionListener";const IT=e=>!!e.onSelectionChange;function OT({onSelectionChange:e}){const t=Rn(IT);return e||t?ve.createElement(t0,{onSelectionChange:e}):null}const PT=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 xu(e,t){m.useEffect(()=>{typeof e<"u"&&t(e)},[e])}function Jt(e,t,n){m.useEffect(()=>{typeof t<"u"&&n({[e]:t})},[t])}const DT=({nodes:e,edges:t,defaultNodes:n,defaultEdges:i,onConnect:o,onConnectStart:l,onConnectEnd:u,onClickConnectStart:c,onClickConnectEnd:f,nodesDraggable:_,nodesConnectable:p,nodesFocusable:y,edgesFocusable:w,edgesUpdatable:x,elevateNodesOnSelect:S,minZoom:j,maxZoom:E,nodeExtent:A,onNodesChange:L,onEdgesChange:O,elementsSelectable:M,connectionMode:H,snapGrid:X,snapToGrid:Y,translateExtent:Z,connectOnClick:re,defaultEdgeOptions:ie,fitView:ue,fitViewOptions:F,onNodesDelete:C,onEdgesDelete:N,onNodeDrag:P,onNodeDragStart:D,onNodeDragStop:ne,onSelectionDrag:B,onSelectionDragStart:z,onSelectionDragStop:G,noPanClassName:T,nodeOrigin:Q,rfId:K,autoPanOnConnect:J,autoPanOnNodeDrag:oe,onError:fe,connectionRadius:_e,isValidConnection:we,nodeDragThreshold:Ae})=>{const{setNodes:Be,setEdges:We,setDefaultNodesAndEdges:_t,setMinZoom:Pe,setMaxZoom:et,setTranslateExtent:lt,setNodeExtent:Ye,reset:Se}=Rn(PT,Us),Le=ks();return m.useEffect(()=>{const ct=i==null?void 0:i.map(ge=>({...ge,...ie}));return _t(n,ct),()=>{Se()}},[]),Jt("defaultEdgeOptions",ie,Le.setState),Jt("connectionMode",H,Le.setState),Jt("onConnect",o,Le.setState),Jt("onConnectStart",l,Le.setState),Jt("onConnectEnd",u,Le.setState),Jt("onClickConnectStart",c,Le.setState),Jt("onClickConnectEnd",f,Le.setState),Jt("nodesDraggable",_,Le.setState),Jt("nodesConnectable",p,Le.setState),Jt("nodesFocusable",y,Le.setState),Jt("edgesFocusable",w,Le.setState),Jt("edgesUpdatable",x,Le.setState),Jt("elementsSelectable",M,Le.setState),Jt("elevateNodesOnSelect",S,Le.setState),Jt("snapToGrid",Y,Le.setState),Jt("snapGrid",X,Le.setState),Jt("onNodesChange",L,Le.setState),Jt("onEdgesChange",O,Le.setState),Jt("connectOnClick",re,Le.setState),Jt("fitViewOnInit",ue,Le.setState),Jt("fitViewOnInitOptions",F,Le.setState),Jt("onNodesDelete",C,Le.setState),Jt("onEdgesDelete",N,Le.setState),Jt("onNodeDrag",P,Le.setState),Jt("onNodeDragStart",D,Le.setState),Jt("onNodeDragStop",ne,Le.setState),Jt("onSelectionDrag",B,Le.setState),Jt("onSelectionDragStart",z,Le.setState),Jt("onSelectionDragStop",G,Le.setState),Jt("noPanClassName",T,Le.setState),Jt("nodeOrigin",Q,Le.setState),Jt("rfId",K,Le.setState),Jt("autoPanOnConnect",J,Le.setState),Jt("autoPanOnNodeDrag",oe,Le.setState),Jt("onError",fe,Le.setState),Jt("connectionRadius",_e,Le.setState),Jt("isValidConnection",we,Le.setState),Jt("nodeDragThreshold",Ae,Le.setState),xu(e,Be),xu(t,We),xu(j,Pe),xu(E,et),xu(Z,lt),xu(A,Ye),null},qw={display:"none"},FT={position:"absolute",width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0px, 0px, 0px, 0px)",clipPath:"inset(100%)"},n0="react-flow__node-desc",s0="react-flow__edge-desc",zT="react-flow__aria-live",BT=e=>e.ariaLiveMessage;function UT({rfId:e}){const t=Rn(BT);return ve.createElement("div",{id:`${zT}-${e}`,"aria-live":"assertive","aria-atomic":"true",style:FT},t)}function WT({rfId:e,disableKeyboardA11y:t}){return ve.createElement(ve.Fragment,null,ve.createElement("div",{id:`${n0}-${e}`,style:qw},"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:`${s0}-${e}`,style:qw},"Press enter or space to select an edge. You can then press delete to remove it or escape to cancel."),!t&&ve.createElement(UT,{rfId:e}))}var Mf=(e=null,t={actInsideInputWithModifier:!0})=>{const[n,i]=m.useState(!1),o=m.useRef(!1),l=m.useRef(new Set([])),[u,c]=m.useMemo(()=>{if(e!==null){const _=(Array.isArray(e)?e:[e]).filter(y=>typeof y=="string").map(y=>y.split("+")),p=_.reduce((y,w)=>y.concat(...w),[]);return[_,p]}return[[],[]]},[e]);return m.useEffect(()=>{const f=typeof document<"u"?document:null,_=(t==null?void 0:t.target)||f;if(e!==null){const p=x=>{if(o.current=x.ctrlKey||x.metaKey||x.shiftKey,(!o.current||o.current&&!t.actInsideInputWithModifier)&&eg(x))return!1;const j=Vw(x.code,c);l.current.add(x[j]),Hw(u,l.current,!1)&&(x.preventDefault(),i(!0))},y=x=>{if((!o.current||o.current&&!t.actInsideInputWithModifier)&&eg(x))return!1;const j=Vw(x.code,c);Hw(u,l.current,!0)?(i(!1),l.current.clear()):l.current.delete(x[j]),x.key==="Meta"&&l.current.clear(),o.current=!1},w=()=>{l.current.clear(),i(!1)};return _==null||_.addEventListener("keydown",p),_==null||_.addEventListener("keyup",y),window.addEventListener("blur",w),()=>{_==null||_.removeEventListener("keydown",p),_==null||_.removeEventListener("keyup",y),window.removeEventListener("blur",w)}}},[e,i]),n};function Hw(e,t,n){return e.filter(i=>n||i.length===t.size).some(i=>i.every(o=>t.has(o)))}function Vw(e,t){return t.includes(e)?"code":"key"}function r0(e,t,n,i){var u,c;if(!e.parentNode)return n;const o=t.get(e.parentNode),l=rc(o,i);return r0(o,t,{x:(n.x??0)+l.x,y:(n.y??0)+l.y,z:(((u=o[hs])==null?void 0:u.z)??0)>(n.z??0)?((c=o[hs])==null?void 0:c.z)??0:n.z??0},i)}function i0(e,t,n){e.forEach(i=>{var o;if(i.parentNode&&!e.has(i.parentNode))throw new Error(`Parent node ${i.parentNode} not found`);if(i.parentNode||n!=null&&n[i.id]){const{x:l,y:u,z:c}=r0(i,e,{...i.position,z:((o=i[hs])==null?void 0:o.z)??0},t);i.positionAbsolute={x:l,y:u},i[hs].z=c,n!=null&&n[i.id]&&(i[hs].isParent=!0)}})}function op(e,t,n,i){const o=new Map,l={},u=i?1e3:0;return e.forEach(c=>{var w;const f=(ki(c.zIndex)?c.zIndex:0)+(c.selected?u:0),_=t.get(c.id),p={...c,positionAbsolute:{x:c.position.x,y:c.position.y}};c.parentNode&&(l[c.parentNode]=!0);const y=(_==null?void 0:_.type)&&(_==null?void 0:_.type)!==c.type;Object.defineProperty(p,hs,{enumerable:!1,value:{handleBounds:y||(w=_==null?void 0:_[hs])==null?void 0:w.handleBounds,z:f}}),o.set(c.id,p)}),i0(o,n,l),o}function o0(e,t={}){const{getNodes:n,width:i,height:o,minZoom:l,maxZoom:u,d3Zoom:c,d3Selection:f,fitViewOnInitDone:_,fitViewOnInit:p,nodeOrigin:y}=e(),w=t.initial&&!_&&p;if(c&&f&&(w||!t.initial)){const S=n().filter(E=>{var L;const A=t.includeHiddenNodes?E.width&&E.height:!E.hidden;return(L=t.nodes)!=null&&L.length?A&&t.nodes.some(O=>O.id===E.id):A}),j=S.every(E=>E.width&&E.height);if(S.length>0&&j){const E=e_(S,y),{x:A,y:L,zoom:O}=Hb(E,i,o,t.minZoom??l,t.maxZoom??u,t.padding??.1),M=ka.translate(A,L).scale(O);return typeof t.duration=="number"&&t.duration>0?c.transform(Kl(f,t.duration),M):c.transform(f,M),!0}}return!1}function qT(e,t){return e.forEach(n=>{const i=t.get(n.id);i&&t.set(i.id,{...i,[hs]:i[hs],selected:n.selected})}),new Map(t)}function HT(e,t){return t.map(n=>{const i=e.find(o=>o.id===n.id);return i&&(n.selected=i.selected),n})}function nm({changedNodes:e,changedEdges:t,get:n,set:i}){const{nodeInternals:o,edges:l,onNodesChange:u,onEdgesChange:c,hasDefaultNodes:f,hasDefaultEdges:_}=n();e!=null&&e.length&&(f&&i({nodeInternals:qT(e,o)}),u==null||u(e)),t!=null&&t.length&&(_&&i({edges:HT(t,l)}),c==null||c(t))}const bu=()=>{},VT={zoomIn:bu,zoomOut:bu,zoomTo:bu,getZoom:()=>1,setViewport:bu,getViewport:()=>({x:0,y:0,zoom:1}),fitView:()=>!1,setCenter:bu,fitBounds:bu,project:e=>e,screenToFlowPosition:e=>e,flowToScreenPosition:e=>e,viewportInitialized:!1},GT=e=>({d3Zoom:e.d3Zoom,d3Selection:e.d3Selection}),KT=()=>{const e=ks(),{d3Zoom:t,d3Selection:n}=Rn(GT,Us);return m.useMemo(()=>n&&t?{zoomIn:o=>t.scaleBy(Kl(n,o==null?void 0:o.duration),1.2),zoomOut:o=>t.scaleBy(Kl(n,o==null?void 0:o.duration),1/1.2),zoomTo:(o,l)=>t.scaleTo(Kl(n,l==null?void 0:l.duration),o),getZoom:()=>e.getState().transform[2],setViewport:(o,l)=>{const[u,c,f]=e.getState().transform,_=ka.translate(o.x??u,o.y??c).scale(o.zoom??f);t.transform(Kl(n,l==null?void 0:l.duration),_)},getViewport:()=>{const[o,l,u]=e.getState().transform;return{x:o,y:l,zoom:u}},fitView:o=>o0(e.getState,o),setCenter:(o,l,u)=>{const{width:c,height:f,maxZoom:_}=e.getState(),p=typeof(u==null?void 0:u.zoom)<"u"?u.zoom:_,y=c/2-o*p,w=f/2-l*p,x=ka.translate(y,w).scale(p);t.transform(Kl(n,u==null?void 0:u.duration),x)},fitBounds:(o,l)=>{const{width:u,height:c,minZoom:f,maxZoom:_}=e.getState(),{x:p,y,zoom:w}=Hb(o,u,c,f,_,(l==null?void 0:l.padding)??.1),x=ka.translate(p,y).scale(w);t.transform(Kl(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"),sg(o,l,u,c)},screenToFlowPosition:o=>{const{transform:l,snapToGrid:u,snapGrid:c,domNode:f}=e.getState();if(!f)return o;const{x:_,y:p}=f.getBoundingClientRect(),y={x:o.x-_,y:o.y-p};return sg(y,l,u,c)},flowToScreenPosition:o=>{const{transform:l,domNode:u}=e.getState();if(!u)return o;const{x:c,y:f}=u.getBoundingClientRect(),_=Ub(o,l);return{x:_.x+c,y:_.y+f}},viewportInitialized:!0}:VT,[t,n])};function Vg(){const e=KT(),t=ks(),n=m.useCallback(()=>t.getState().getNodes().map(j=>({...j})),[]),i=m.useCallback(j=>t.getState().nodeInternals.get(j),[]),o=m.useCallback(()=>{const{edges:j=[]}=t.getState();return j.map(E=>({...E}))},[]),l=m.useCallback(j=>{const{edges:E=[]}=t.getState();return E.find(A=>A.id===j)},[]),u=m.useCallback(j=>{const{getNodes:E,setNodes:A,hasDefaultNodes:L,onNodesChange:O}=t.getState(),M=E(),H=typeof j=="function"?j(M):j;if(L)A(H);else if(O){const X=H.length===0?M.map(Y=>({type:"remove",id:Y.id})):H.map(Y=>({item:Y,type:"reset"}));O(X)}},[]),c=m.useCallback(j=>{const{edges:E=[],setEdges:A,hasDefaultEdges:L,onEdgesChange:O}=t.getState(),M=typeof j=="function"?j(E):j;if(L)A(M);else if(O){const H=M.length===0?E.map(X=>({type:"remove",id:X.id})):M.map(X=>({item:X,type:"reset"}));O(H)}},[]),f=m.useCallback(j=>{const E=Array.isArray(j)?j:[j],{getNodes:A,setNodes:L,hasDefaultNodes:O,onNodesChange:M}=t.getState();if(O){const X=[...A(),...E];L(X)}else if(M){const H=E.map(X=>({item:X,type:"add"}));M(H)}},[]),_=m.useCallback(j=>{const E=Array.isArray(j)?j:[j],{edges:A=[],setEdges:L,hasDefaultEdges:O,onEdgesChange:M}=t.getState();if(O)L([...A,...E]);else if(M){const H=E.map(X=>({item:X,type:"add"}));M(H)}},[]),p=m.useCallback(()=>{const{getNodes:j,edges:E=[],transform:A}=t.getState(),[L,O,M]=A;return{nodes:j().map(H=>({...H})),edges:E.map(H=>({...H})),viewport:{x:L,y:O,zoom:M}}},[]),y=m.useCallback(({nodes:j,edges:E})=>{const{nodeInternals:A,getNodes:L,edges:O,hasDefaultNodes:M,hasDefaultEdges:H,onNodesDelete:X,onEdgesDelete:Y,onNodesChange:Z,onEdgesChange:re}=t.getState(),ie=(j||[]).map(P=>P.id),ue=(E||[]).map(P=>P.id),F=L().reduce((P,D)=>{const ne=!ie.includes(D.id)&&D.parentNode&&P.find(z=>z.id===D.parentNode);return(typeof D.deletable=="boolean"?D.deletable:!0)&&(ie.includes(D.id)||ne)&&P.push(D),P},[]),C=O.filter(P=>typeof P.deletable=="boolean"?P.deletable:!0),N=C.filter(P=>ue.includes(P.id));if(F||N){const P=qb(F,C),D=[...N,...P],ne=D.reduce((B,z)=>(B.includes(z.id)||B.push(z.id),B),[]);if((H||M)&&(H&&t.setState({edges:O.filter(B=>!ne.includes(B.id))}),M&&(F.forEach(B=>{A.delete(B.id)}),t.setState({nodeInternals:new Map(A)}))),ne.length>0&&(Y==null||Y(D),re&&re(ne.map(B=>({id:B,type:"remove"})))),F.length>0&&(X==null||X(F),Z)){const B=F.map(z=>({id:z.id,type:"remove"}));Z(B)}}},[]),w=m.useCallback(j=>{const E=mT(j),A=E?null:t.getState().nodeInternals.get(j.id);return!E&&!A?[null,null,E]:[E?j:Pw(A),A,E]},[]),x=m.useCallback((j,E=!0,A)=>{const[L,O,M]=w(j);return L?(A||t.getState().getNodes()).filter(H=>{if(!M&&(H.id===O.id||!H.positionAbsolute))return!1;const X=Pw(H),Y=Qp(X,L);return E&&Y>0||Y>=L.width*L.height}):[]},[]),S=m.useCallback((j,E,A=!0)=>{const[L]=w(j);if(!L)return!1;const O=Qp(L,E);return A&&O>0||O>=L.width*L.height},[]);return m.useMemo(()=>({...e,getNodes:n,getNode:i,getEdges:o,getEdge:l,setNodes:u,setEdges:c,addNodes:f,addEdges:_,toObject:p,deleteElements:y,getIntersectingNodes:x,isNodeIntersecting:S}),[e,n,i,o,l,u,c,f,_,p,y,x,S])}const YT={actInsideInputWithModifier:!1};var JT=({deleteKeyCode:e,multiSelectionKeyCode:t})=>{const n=ks(),{deleteElements:i}=Vg(),o=Mf(e,YT),l=Mf(t);m.useEffect(()=>{if(o){const{edges:u,getNodes:c}=n.getState(),f=c().filter(p=>p.selected),_=u.filter(p=>p.selected);i({nodes:f,edges:_}),n.setState({nodesSelectionActive:!1})}},[o]),m.useEffect(()=>{n.setState({multiSelectionActive:l})},[l])};function XT(e){const t=ks();m.useEffect(()=>{let n;const i=()=>{var l,u;if(!e.current)return;const o=Dg(e.current);(o.height===0||o.width===0)&&((u=(l=t.getState()).onError)==null||u.call(l,"004",$a.error004())),t.setState({width:o.width||500,height:o.height||500})};return i(),window.addEventListener("resize",i),e.current&&(n=new ResizeObserver(()=>i()),n.observe(e.current)),()=>{window.removeEventListener("resize",i),n&&e.current&&n.unobserve(e.current)}},[])}const Gg={position:"absolute",width:"100%",height:"100%",top:0,left:0},ZT=(e,t)=>e.x!==t.x||e.y!==t.y||e.zoom!==t.k,sm=e=>({x:e.x,y:e.y,zoom:e.k}),ju=(e,t)=>e.target.closest(`.${t}`),Gw=(e,t)=>t===2&&Array.isArray(e)&&e.includes(2),Kw=e=>{const t=e.ctrlKey&&Im()?10:1;return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*t},QT=e=>({d3Zoom:e.d3Zoom,d3Selection:e.d3Selection,d3ZoomHandler:e.d3ZoomHandler,userSelectionActive:e.userSelectionActive}),eM=({onMove:e,onMoveStart:t,onMoveEnd:n,onPaneContextMenu:i,zoomOnScroll:o=!0,zoomOnPinch:l=!0,panOnScroll:u=!1,panOnScrollSpeed:c=.5,panOnScrollMode:f=Ql.Free,zoomOnDoubleClick:_=!0,elementsSelectable:p,panOnDrag:y=!0,defaultViewport:w,translateExtent:x,minZoom:S,maxZoom:j,zoomActivationKeyCode:E,preventScrolling:A=!0,children:L,noWheelClassName:O,noPanClassName:M})=>{const H=m.useRef(),X=ks(),Y=m.useRef(!1),Z=m.useRef(!1),re=m.useRef(null),ie=m.useRef({x:0,y:0,zoom:0}),{d3Zoom:ue,d3Selection:F,d3ZoomHandler:C,userSelectionActive:N}=Rn(QT,Us),P=Mf(E),D=m.useRef(0),ne=m.useRef(!1),B=m.useRef();return XT(re),m.useEffect(()=>{if(re.current){const z=re.current.getBoundingClientRect(),G=Ab().scaleExtent([S,j]).translateExtent(x),T=Si(re.current).call(G),Q=ka.translate(w.x,w.y).scale(Bu(w.zoom,S,j)),K=[[0,0],[z.width,z.height]],J=G.constrain()(Q,K,x);G.transform(T,J),G.wheelDelta(Kw),X.setState({d3Zoom:G,d3Selection:T,d3ZoomHandler:T.on("wheel.zoom"),transform:[J.x,J.y,J.k],domNode:re.current.closest(".react-flow")})}},[]),m.useEffect(()=>{F&&ue&&(u&&!P&&!N?F.on("wheel.zoom",z=>{if(ju(z,O))return!1;z.preventDefault(),z.stopImmediatePropagation();const G=F.property("__zoom").k||1,T=Im();if(z.ctrlKey&&l&&T){const Ae=no(z),Be=Kw(z),We=G*Math.pow(2,Be);ue.scaleTo(F,We,Ae,z);return}const Q=z.deltaMode===1?20:1;let K=f===Ql.Vertical?0:z.deltaX*Q,J=f===Ql.Horizontal?0:z.deltaY*Q;!T&&z.shiftKey&&f!==Ql.Vertical&&(K=z.deltaY*Q,J=0),ue.translateBy(F,-(K/G)*c,-(J/G)*c,{internal:!0});const oe=sm(F.property("__zoom")),{onViewportChangeStart:fe,onViewportChange:_e,onViewportChangeEnd:we}=X.getState();clearTimeout(B.current),ne.current||(ne.current=!0,t==null||t(z,oe),fe==null||fe(oe)),ne.current&&(e==null||e(z,oe),_e==null||_e(oe),B.current=setTimeout(()=>{n==null||n(z,oe),we==null||we(oe),ne.current=!1},150))},{passive:!1}):typeof C<"u"&&F.on("wheel.zoom",function(z,G){if(!A||ju(z,O))return null;z.preventDefault(),C.call(this,z,G)},{passive:!1}))},[N,u,f,F,ue,C,P,l,A,O,t,e,n]),m.useEffect(()=>{ue&&ue.on("start",z=>{var Q,K;if(!z.sourceEvent||z.sourceEvent.internal)return null;D.current=(Q=z.sourceEvent)==null?void 0:Q.button;const{onViewportChangeStart:G}=X.getState(),T=sm(z.transform);Y.current=!0,ie.current=T,((K=z.sourceEvent)==null?void 0:K.type)==="mousedown"&&X.setState({paneDragging:!0}),G==null||G(T),t==null||t(z.sourceEvent,T)})},[ue,t]),m.useEffect(()=>{ue&&(N&&!Y.current?ue.on("zoom",null):N||ue.on("zoom",z=>{var T;const{onViewportChange:G}=X.getState();if(X.setState({transform:[z.transform.x,z.transform.y,z.transform.k]}),Z.current=!!(i&&Gw(y,D.current??0)),(e||G)&&!((T=z.sourceEvent)!=null&&T.internal)){const Q=sm(z.transform);G==null||G(Q),e==null||e(z.sourceEvent,Q)}}))},[N,ue,e,y,i]),m.useEffect(()=>{ue&&ue.on("end",z=>{if(!z.sourceEvent||z.sourceEvent.internal)return null;const{onViewportChangeEnd:G}=X.getState();if(Y.current=!1,X.setState({paneDragging:!1}),i&&Gw(y,D.current??0)&&!Z.current&&i(z.sourceEvent),Z.current=!1,(n||G)&&ZT(ie.current,z.transform)){const T=sm(z.transform);ie.current=T,clearTimeout(H.current),H.current=setTimeout(()=>{G==null||G(T),n==null||n(z.sourceEvent,T)},u?150:0)}})},[ue,u,y,n,i]),m.useEffect(()=>{ue&&ue.filter(z=>{const G=P||o,T=l&&z.ctrlKey;if((y===!0||Array.isArray(y)&&y.includes(1))&&z.button===1&&z.type==="mousedown"&&(ju(z,"react-flow__node")||ju(z,"react-flow__edge")))return!0;if(!y&&!G&&!u&&!_&&!l||N||!_&&z.type==="dblclick"||ju(z,O)&&z.type==="wheel"||ju(z,M)&&(z.type!=="wheel"||u&&z.type==="wheel"&&!P)||!l&&z.ctrlKey&&z.type==="wheel"||!G&&!u&&!T&&z.type==="wheel"||!y&&(z.type==="mousedown"||z.type==="touchstart")||Array.isArray(y)&&!y.includes(z.button)&&(z.type==="mousedown"||z.type==="touchstart"))return!1;const Q=Array.isArray(y)&&y.includes(z.button)||!z.button||z.button<=1;return(!z.ctrlKey||z.type==="wheel")&&Q})},[N,ue,o,l,u,_,y,p,P]),ve.createElement("div",{className:"react-flow__renderer",ref:re,style:Gg},L)},tM=e=>({userSelectionActive:e.userSelectionActive,userSelectionRect:e.userSelectionRect});function nM(){const{userSelectionActive:e,userSelectionRect:t}=Rn(tM,Us);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 Yw(e,t){const n=e.find(i=>i.id===t.parentNode);if(n){const i=t.position.x+t.width-n.width,o=t.position.y+t.height-n.height;if(i>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,i>0&&(n.style.width+=i),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 sM(e,t){if(e.some(i=>i.type==="reset"))return e.filter(i=>i.type==="reset").map(i=>i.item);const n=e.filter(i=>i.type==="add").map(i=>i.item);return t.reduce((i,o)=>{const l=e.filter(c=>c.id===o.id);if(l.length===0)return i.push(o),i;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&&Yw(i,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&&Yw(i,u);break}case"remove":return i}return i.push(u),i},n)}function rM(e,t){return sM(e,t)}const dl=(e,t)=>({id:e,type:"select",selected:t});function $u(e,t){return e.reduce((n,i)=>{const o=t.includes(i.id);return!i.selected&&o?(i.selected=!0,n.push(dl(i.id,!0))):i.selected&&!o&&(i.selected=!1,n.push(dl(i.id,!1))),n},[])}const ap=(e,t)=>n=>{n.target===t.current&&(e==null||e(n))},iM=e=>({userSelectionActive:e.userSelectionActive,elementsSelectable:e.elementsSelectable,dragging:e.paneDragging}),a0=m.memo(({isSelecting:e,selectionMode:t=Af.Full,panOnDrag:n,onSelectionStart:i,onSelectionEnd:o,onPaneClick:l,onPaneContextMenu:u,onPaneScroll:c,onPaneMouseEnter:f,onPaneMouseMove:_,onPaneMouseLeave:p,children:y})=>{const w=m.useRef(null),x=ks(),S=m.useRef(0),j=m.useRef(0),E=m.useRef(),{userSelectionActive:A,elementsSelectable:L,dragging:O}=Rn(iM,Us),M=()=>{x.setState({userSelectionActive:!1,userSelectionRect:null}),S.current=0,j.current=0},H=C=>{l==null||l(C),x.getState().resetSelectedElements(),x.setState({nodesSelectionActive:!1})},X=C=>{if(Array.isArray(n)&&(n!=null&&n.includes(2))){C.preventDefault();return}u==null||u(C)},Y=c?C=>c(C):void 0,Z=C=>{const{resetSelectedElements:N,domNode:P}=x.getState();if(E.current=P==null?void 0:P.getBoundingClientRect(),!L||!e||C.button!==0||C.target!==w.current||!E.current)return;const{x:D,y:ne}=ml(C,E.current);N(),x.setState({userSelectionRect:{width:0,height:0,startX:D,startY:ne,x:D,y:ne}}),i==null||i(C)},re=C=>{const{userSelectionRect:N,nodeInternals:P,edges:D,transform:ne,onNodesChange:B,onEdgesChange:z,nodeOrigin:G,getNodes:T}=x.getState();if(!e||!E.current||!N)return;x.setState({userSelectionActive:!0,nodesSelectionActive:!1});const Q=ml(C,E.current),K=N.startX??0,J=N.startY??0,oe={...N,x:Q.x<K?Q.x:K,y:Q.y<J?Q.y:J,width:Math.abs(Q.x-K),height:Math.abs(Q.y-J)},fe=T(),_e=Wb(P,oe,ne,t===Af.Partial,!0,G),we=qb(_e,D).map(Be=>Be.id),Ae=_e.map(Be=>Be.id);if(S.current!==Ae.length){S.current=Ae.length;const Be=$u(fe,Ae);Be.length&&(B==null||B(Be))}if(j.current!==we.length){j.current=we.length;const Be=$u(D,we);Be.length&&(z==null||z(Be))}x.setState({userSelectionRect:oe})},ie=C=>{if(C.button!==0)return;const{userSelectionRect:N}=x.getState();!A&&N&&C.target===w.current&&(H==null||H(C)),x.setState({nodesSelectionActive:S.current>0}),M(),o==null||o(C)},ue=C=>{A&&(x.setState({nodesSelectionActive:S.current>0}),o==null||o(C)),M()},F=L&&(e||A);return ve.createElement("div",{className:Ys(["react-flow__pane",{dragging:O,selection:e}]),onClick:F?void 0:ap(H,w),onContextMenu:ap(X,w),onWheel:ap(Y,w),onMouseEnter:F?void 0:f,onMouseDown:F?Z:void 0,onMouseMove:F?re:_,onMouseUp:F?ie:void 0,onMouseLeave:F?ue:p,ref:w,style:Gg},y,ve.createElement(nM,null))});a0.displayName="Pane";function l0(e,t){if(!e.parentNode)return!1;const n=t.get(e.parentNode);return n?n.selected?!0:l0(n,t):!1}function Jw(e,t,n){let i=e;do{if(i!=null&&i.matches(t))return!0;if(i===n.current)return!1;i=i.parentElement}while(i);return!1}function oM(e,t,n,i){return Array.from(e.values()).filter(o=>(o.selected||o.id===i)&&(!o.parentNode||!l0(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 aM(e,t){return!t||t==="parent"?t:[t[0],[t[1][0]-(e.width||0),t[1][1]-(e.height||0)]]}function c0(e,t,n,i,o=[0,0],l){const u=aM(e,e.extent||i);let c=u;if(e.extent==="parent"&&!e.expandParent)if(e.parentNode&&e.width&&e.height){const p=n.get(e.parentNode),{x:y,y:w}=rc(p,o).positionAbsolute;c=p&&ki(y)&&ki(w)&&ki(p.width)&&ki(p.height)?[[y+e.width*o[0],w+e.height*o[1]],[y+p.width-e.width+e.width*o[0],w+p.height-e.height+e.height*o[1]]]:c}else l==null||l("005",$a.error005()),c=u;else if(e.extent&&e.parentNode&&e.extent!=="parent"){const p=n.get(e.parentNode),{x:y,y:w}=rc(p,o).positionAbsolute;c=[[e.extent[0][0]+y,e.extent[0][1]+w],[e.extent[1][0]+y,e.extent[1][1]+w]]}let f={x:0,y:0};if(e.parentNode){const p=n.get(e.parentNode);f=rc(p,o).positionAbsolute}const _=c&&c!=="parent"?Fg(t,c):t;return{position:{x:_.x-f.x,y:_.y-f.y},positionAbsolute:_}}function lp({nodeId:e,dragItems:t,nodeInternals:n}){const i=t.map(o=>({...n.get(o.id),position:o.position,positionAbsolute:o.positionAbsolute}));return[e?i.find(o=>o.id===e):i[0],i]}const Xw=(e,t,n,i)=>{const o=t.querySelectorAll(e);if(!o||!o.length)return null;const l=Array.from(o),u=t.getBoundingClientRect(),c={x:u.width*i[0],y:u.height*i[1]};return l.map(f=>{const _=f.getBoundingClientRect();return{id:f.getAttribute("data-handleid"),position:f.getAttribute("data-handlepos"),x:(_.left-u.left-c.x)/n,y:(_.top-u.top-c.y)/n,...Dg(f)}})};function cf(e,t,n){return n===void 0?n:i=>{const o=t().nodeInternals.get(e);o&&n(i,{...o})}}function ig({id:e,store:t,unselect:n=!1,nodeRef:i}){const{addSelectedNodes:o,unselectNodesAndEdges:l,multiSelectionActive:u,nodeInternals:c,onError:f}=t.getState(),_=c.get(e);if(!_){f==null||f("012",$a.error012(e));return}t.setState({nodesSelectionActive:!1}),_.selected?(n||_.selected&&u)&&(l({nodes:[_],edges:[]}),requestAnimationFrame(()=>{var p;return(p=i==null?void 0:i.current)==null?void 0:p.blur()})):o([e])}function lM(){const e=ks();return m.useCallback(({sourceEvent:n})=>{const{transform:i,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-i[0])/i[2],y:(c-i[1])/i[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 cp(e){return(t,n,i)=>e==null?void 0:e(t,i)}function u0({nodeRef:e,disabled:t=!1,noDragClassName:n,handleSelector:i,nodeId:o,isSelectable:l,selectNodesOnDrag:u}){const c=ks(),[f,_]=m.useState(!1),p=m.useRef([]),y=m.useRef({x:null,y:null}),w=m.useRef(0),x=m.useRef(null),S=m.useRef({x:0,y:0}),j=m.useRef(null),E=m.useRef(!1),A=m.useRef(!1),L=lM();return m.useEffect(()=>{if(e!=null&&e.current){const O=Si(e.current),M=({x:Y,y:Z})=>{const{nodeInternals:re,onNodeDrag:ie,onSelectionDrag:ue,updateNodePositions:F,nodeExtent:C,snapGrid:N,snapToGrid:P,nodeOrigin:D,onError:ne}=c.getState();y.current={x:Y,y:Z};let B=!1,z={x:0,y:0,x2:0,y2:0};if(p.current.length>1&&C){const T=e_(p.current,D);z=$f(T)}if(p.current=p.current.map(T=>{const Q={x:Y-T.distance.x,y:Z-T.distance.y};P&&(Q.x=N[0]*Math.round(Q.x/N[0]),Q.y=N[1]*Math.round(Q.y/N[1]));const K=[[C[0][0],C[0][1]],[C[1][0],C[1][1]]];p.current.length>1&&C&&!T.extent&&(K[0][0]=T.positionAbsolute.x-z.x+C[0][0],K[1][0]=T.positionAbsolute.x+(T.width??0)-z.x2+C[1][0],K[0][1]=T.positionAbsolute.y-z.y+C[0][1],K[1][1]=T.positionAbsolute.y+(T.height??0)-z.y2+C[1][1]);const J=c0(T,Q,re,K,D,ne);return B=B||T.position.x!==J.position.x||T.position.y!==J.position.y,T.position=J.position,T.positionAbsolute=J.positionAbsolute,T}),!B)return;F(p.current,!0,!0),_(!0);const G=o?ie:cp(ue);if(G&&j.current){const[T,Q]=lp({nodeId:o,dragItems:p.current,nodeInternals:re});G(j.current,T,Q)}},H=()=>{if(!x.current)return;const[Y,Z]=Mb(S.current,x.current);if(Y!==0||Z!==0){const{transform:re,panBy:ie}=c.getState();y.current.x=(y.current.x??0)-Y/re[2],y.current.y=(y.current.y??0)-Z/re[2],ie({x:Y,y:Z})&&M(y.current)}w.current=requestAnimationFrame(H)},X=Y=>{var D;const{nodeInternals:Z,multiSelectionActive:re,nodesDraggable:ie,unselectNodesAndEdges:ue,onNodeDragStart:F,onSelectionDragStart:C}=c.getState();A.current=!0;const N=o?F:cp(C);(!u||!l)&&!re&&o&&((D=Z.get(o))!=null&&D.selected||ue()),o&&l&&u&&ig({id:o,store:c,nodeRef:e});const P=L(Y);if(y.current=P,p.current=oM(Z,ie,P,o),N&&p.current){const[ne,B]=lp({nodeId:o,dragItems:p.current,nodeInternals:Z});N(Y.sourceEvent,ne,B)}};if(t)O.on(".drag",null);else{const Y=y$().on("start",Z=>{const{domNode:re,nodeDragThreshold:ie}=c.getState();ie===0&&X(Z);const ue=L(Z);y.current=ue,x.current=(re==null?void 0:re.getBoundingClientRect())||null,S.current=ml(Z.sourceEvent,x.current)}).on("drag",Z=>{var F,C;const re=L(Z),{autoPanOnNodeDrag:ie,nodeDragThreshold:ue}=c.getState();if(!E.current&&A.current&&ie&&(E.current=!0,H()),!A.current){const N=re.xSnapped-(((F=y==null?void 0:y.current)==null?void 0:F.x)??0),P=re.ySnapped-(((C=y==null?void 0:y.current)==null?void 0:C.y)??0);Math.sqrt(N*N+P*P)>ue&&X(Z)}(y.current.x!==re.xSnapped||y.current.y!==re.ySnapped)&&p.current&&A.current&&(j.current=Z.sourceEvent,S.current=ml(Z.sourceEvent,x.current),M(re))}).on("end",Z=>{if(A.current&&(_(!1),E.current=!1,A.current=!1,cancelAnimationFrame(w.current),p.current)){const{updateNodePositions:re,nodeInternals:ie,onNodeDragStop:ue,onSelectionDragStop:F}=c.getState(),C=o?ue:cp(F);if(re(p.current,!1,!1),C){const[N,P]=lp({nodeId:o,dragItems:p.current,nodeInternals:ie});C(Z.sourceEvent,N,P)}}}).filter(Z=>{const re=Z.target;return!Z.button&&(!n||!Jw(re,`.${n}`,e))&&(!i||Jw(re,i,e))});return O.call(Y),()=>{O.on(".drag",null)}}}},[e,t,n,i,l,c,o,u,L]),f}function d0(){const e=ks();return m.useCallback(n=>{const{nodeInternals:i,nodeExtent:o,updateNodePositions:l,getNodes:u,snapToGrid:c,snapGrid:f,onError:_,nodesDraggable:p}=e.getState(),y=u().filter(L=>L.selected&&(L.draggable||p&&typeof L.draggable>"u")),w=c?f[0]:5,x=c?f[1]:5,S=n.isShiftPressed?4:1,j=n.x*w*S,E=n.y*x*S,A=y.map(L=>{if(L.positionAbsolute){const O={x:L.positionAbsolute.x+j,y:L.positionAbsolute.y+E};c&&(O.x=f[0]*Math.round(O.x/f[0]),O.y=f[1]*Math.round(O.y/f[1]));const{positionAbsolute:M,position:H}=c0(L,O,i,o,void 0,_);L.position=H,L.positionAbsolute=M}return L});l(A,!0,!1)},[])}const Iu={ArrowUp:{x:0,y:-1},ArrowDown:{x:0,y:1},ArrowLeft:{x:-1,y:0},ArrowRight:{x:1,y:0}};var uf=e=>{const t=({id:n,type:i,data:o,xPos:l,yPos:u,xPosOrigin:c,yPosOrigin:f,selected:_,onClick:p,onMouseEnter:y,onMouseMove:w,onMouseLeave:x,onContextMenu:S,onDoubleClick:j,style:E,className:A,isDraggable:L,isSelectable:O,isConnectable:M,isFocusable:H,selectNodesOnDrag:X,sourcePosition:Y,targetPosition:Z,hidden:re,resizeObserver:ie,dragHandle:ue,zIndex:F,isParent:C,noDragClassName:N,noPanClassName:P,initialized:D,disableKeyboardA11y:ne,ariaLabel:B,rfId:z,hasHandleBounds:G})=>{const T=ks(),Q=m.useRef(null),K=m.useRef(Y),J=m.useRef(Z),oe=m.useRef(i),fe=O||L||p||y||w||x,_e=d0(),we=cf(n,T.getState,y),Ae=cf(n,T.getState,w),Be=cf(n,T.getState,x),We=cf(n,T.getState,S),_t=cf(n,T.getState,j),Pe=Ye=>{const{nodeDragThreshold:Se}=T.getState();if(O&&(!X||!L||Se>0)&&ig({id:n,store:T,nodeRef:Q}),p){const Le=T.getState().nodeInternals.get(n);Le&&p(Ye,{...Le})}},et=Ye=>{if(!eg(Ye))if(Ob.includes(Ye.key)&&O){const Se=Ye.key==="Escape";ig({id:n,store:T,unselect:Se,nodeRef:Q})}else!ne&&L&&_&&Object.prototype.hasOwnProperty.call(Iu,Ye.key)&&(T.setState({ariaLiveMessage:`Moved selected node ${Ye.key.replace("Arrow","").toLowerCase()}. New position, x: ${~~l}, y: ${~~u}`}),_e({x:Iu[Ye.key].x,y:Iu[Ye.key].y,isShiftPressed:Ye.shiftKey}))};m.useEffect(()=>()=>{Q.current&&(ie==null||ie.unobserve(Q.current))},[]),m.useEffect(()=>{if(Q.current&&!re){const Ye=Q.current;(!D||!G)&&(ie==null||ie.unobserve(Ye),ie==null||ie.observe(Ye))}},[re,D,G]),m.useEffect(()=>{const Ye=oe.current!==i,Se=K.current!==Y,Le=J.current!==Z;Q.current&&(Ye||Se||Le)&&(Ye&&(oe.current=i),Se&&(K.current=Y),Le&&(J.current=Z),T.getState().updateNodeDimensions([{id:n,nodeElement:Q.current,forceUpdate:!0}]))},[n,i,Y,Z]);const lt=u0({nodeRef:Q,disabled:re||!L,noDragClassName:N,handleSelector:ue,nodeId:n,isSelectable:O,selectNodesOnDrag:X});return re?null:ve.createElement("div",{className:Ys(["react-flow__node",`react-flow__node-${i}`,{[P]:L},A,{selected:_,selectable:O,parent:C,dragging:lt}]),ref:Q,style:{zIndex:F,transform:`translate(${c}px,${f}px)`,pointerEvents:fe?"all":"none",visibility:D?"visible":"hidden",...E},"data-id":n,"data-testid":`rf__node-${n}`,onMouseEnter:we,onMouseMove:Ae,onMouseLeave:Be,onContextMenu:We,onClick:Pe,onDoubleClick:_t,onKeyDown:H?et:void 0,tabIndex:H?0:void 0,role:H?"button":void 0,"aria-describedby":ne?void 0:`${n0}-${z}`,"aria-label":B},ve.createElement(xT,{value:n},ve.createElement(e,{id:n,data:o,type:i,xPos:l,yPos:u,selected:_,isConnectable:M,sourcePosition:Y,targetPosition:Z,dragging:lt,dragHandle:ue,zIndex:F})))};return t.displayName="NodeWrapper",m.memo(t)};const cM=e=>{const t=e.getNodes().filter(n=>n.selected);return{...e_(t,e.nodeOrigin),transformString:`translate(${e.transform[0]}px,${e.transform[1]}px) scale(${e.transform[2]})`,userSelectionActive:e.userSelectionActive}};function uM({onSelectionContextMenu:e,noPanClassName:t,disableKeyboardA11y:n}){const i=ks(),{width:o,height:l,x:u,y:c,transformString:f,userSelectionActive:_}=Rn(cM,Us),p=d0(),y=m.useRef(null);if(m.useEffect(()=>{var S;n||(S=y.current)==null||S.focus({preventScroll:!0})},[n]),u0({nodeRef:y}),_||!o||!l)return null;const w=e?S=>{const j=i.getState().getNodes().filter(E=>E.selected);e(S,j)}:void 0,x=S=>{Object.prototype.hasOwnProperty.call(Iu,S.key)&&p({x:Iu[S.key].x,y:Iu[S.key].y,isShiftPressed:S.shiftKey})};return ve.createElement("div",{className:Ys(["react-flow__nodesselection","react-flow__container",t]),style:{transform:f}},ve.createElement("div",{ref:y,className:"react-flow__nodesselection-rect",onContextMenu:w,tabIndex:n?void 0:-1,onKeyDown:n?void 0:x,style:{width:o,height:l,top:c,left:u}}))}var dM=m.memo(uM);const fM=e=>e.nodesSelectionActive,f0=({children:e,onPaneClick:t,onPaneMouseEnter:n,onPaneMouseMove:i,onPaneMouseLeave:o,onPaneContextMenu:l,onPaneScroll:u,deleteKeyCode:c,onMove:f,onMoveStart:_,onMoveEnd:p,selectionKeyCode:y,selectionOnDrag:w,selectionMode:x,onSelectionStart:S,onSelectionEnd:j,multiSelectionKeyCode:E,panActivationKeyCode:A,zoomActivationKeyCode:L,elementsSelectable:O,zoomOnScroll:M,zoomOnPinch:H,panOnScroll:X,panOnScrollSpeed:Y,panOnScrollMode:Z,zoomOnDoubleClick:re,panOnDrag:ie,defaultViewport:ue,translateExtent:F,minZoom:C,maxZoom:N,preventScrolling:P,onSelectionContextMenu:D,noWheelClassName:ne,noPanClassName:B,disableKeyboardA11y:z})=>{const G=Rn(fM),T=Mf(y),Q=Mf(A),K=Q||ie,J=Q||X,oe=T||w&&K!==!0;return JT({deleteKeyCode:c,multiSelectionKeyCode:E}),ve.createElement(eM,{onMove:f,onMoveStart:_,onMoveEnd:p,onPaneContextMenu:l,elementsSelectable:O,zoomOnScroll:M,zoomOnPinch:H,panOnScroll:J,panOnScrollSpeed:Y,panOnScrollMode:Z,zoomOnDoubleClick:re,panOnDrag:!T&&K,defaultViewport:ue,translateExtent:F,minZoom:C,maxZoom:N,zoomActivationKeyCode:L,preventScrolling:P,noWheelClassName:ne,noPanClassName:B},ve.createElement(a0,{onSelectionStart:S,onSelectionEnd:j,onPaneClick:t,onPaneMouseEnter:n,onPaneMouseMove:i,onPaneMouseLeave:o,onPaneContextMenu:l,onPaneScroll:u,panOnDrag:K,isSelecting:!!oe,selectionMode:x},e,G&&ve.createElement(dM,{onSelectionContextMenu:D,noPanClassName:B,disableKeyboardA11y:z})))};f0.displayName="FlowRenderer";var hM=m.memo(f0);function mM(e){return Rn(m.useCallback(n=>e?Wb(n.nodeInternals,{x:0,y:0,width:n.width,height:n.height},n.transform,!0):n.getNodes(),[e]))}function _M(e){const t={input:uf(e.input||Zb),default:uf(e.default||rg),output:uf(e.output||e0),group:uf(e.group||Hg)},n={},i=Object.keys(e).filter(o=>!["input","default","output","group"].includes(o)).reduce((o,l)=>(o[l]=uf(e[l]||rg),o),n);return{...t,...i}}const pM=({x:e,y:t,width:n,height:i,origin:o})=>!n||!i?{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-i*o[1]},gM=e=>({nodesDraggable:e.nodesDraggable,nodesConnectable:e.nodesConnectable,nodesFocusable:e.nodesFocusable,elementsSelectable:e.elementsSelectable,updateNodeDimensions:e.updateNodeDimensions,onError:e.onError}),h0=e=>{const{nodesDraggable:t,nodesConnectable:n,nodesFocusable:i,elementsSelectable:o,updateNodeDimensions:l,onError:u}=Rn(gM,Us),c=mM(e.onlyRenderVisibleElements),f=m.useRef(),_=m.useMemo(()=>{if(typeof ResizeObserver>"u")return null;const p=new ResizeObserver(y=>{const w=y.map(x=>({id:x.target.getAttribute("data-id"),nodeElement:x.target,forceUpdate:!0}));l(w)});return f.current=p,p},[]);return m.useEffect(()=>()=>{var p;(p=f==null?void 0:f.current)==null||p.disconnect()},[]),ve.createElement("div",{className:"react-flow__nodes",style:Gg},c.map(p=>{var H,X,Y;let y=p.type||"default";e.nodeTypes[y]||(u==null||u("003",$a.error003(y)),y="default");const w=e.nodeTypes[y]||e.nodeTypes.default,x=!!(p.draggable||t&&typeof p.draggable>"u"),S=!!(p.selectable||o&&typeof p.selectable>"u"),j=!!(p.connectable||n&&typeof p.connectable>"u"),E=!!(p.focusable||i&&typeof p.focusable>"u"),A=e.nodeExtent?Fg(p.positionAbsolute,e.nodeExtent):p.positionAbsolute,L=(A==null?void 0:A.x)??0,O=(A==null?void 0:A.y)??0,M=pM({x:L,y:O,width:p.width??0,height:p.height??0,origin:e.nodeOrigin});return ve.createElement(w,{key:p.id,id:p.id,className:p.className,style:p.style,type:y,data:p.data,sourcePosition:p.sourcePosition||mt.Bottom,targetPosition:p.targetPosition||mt.Top,hidden:p.hidden,xPos:L,yPos:O,xPosOrigin:M.x,yPosOrigin:M.y,selectNodesOnDrag:e.selectNodesOnDrag,onClick:e.onNodeClick,onMouseEnter:e.onNodeMouseEnter,onMouseMove:e.onNodeMouseMove,onMouseLeave:e.onNodeMouseLeave,onContextMenu:e.onNodeContextMenu,onDoubleClick:e.onNodeDoubleClick,selected:!!p.selected,isDraggable:x,isSelectable:S,isConnectable:j,isFocusable:E,resizeObserver:_,dragHandle:p.dragHandle,zIndex:((H=p[hs])==null?void 0:H.z)??0,isParent:!!((X=p[hs])!=null&&X.isParent),noDragClassName:e.noDragClassName,noPanClassName:e.noPanClassName,initialized:!!p.width&&!!p.height,rfId:e.rfId,disableKeyboardA11y:e.disableKeyboardA11y,ariaLabel:p.ariaLabel,hasHandleBounds:!!((Y=p[hs])!=null&&Y.handleBounds)})}))};h0.displayName="NodeRenderer";var yM=m.memo(h0);const wM=(e,t,n)=>n===mt.Left?e-t:n===mt.Right?e+t:e,vM=(e,t,n)=>n===mt.Top?e-t:n===mt.Bottom?e+t:e,Zw="react-flow__edgeupdater",Qw=({position:e,centerX:t,centerY:n,radius:i=10,onMouseDown:o,onMouseEnter:l,onMouseOut:u,type:c})=>ve.createElement("circle",{onMouseDown:o,onMouseEnter:l,onMouseOut:u,className:Ys([Zw,`${Zw}-${c}`]),cx:wM(t,i,e),cy:vM(n,i,e),r:i,stroke:"transparent",fill:"transparent"}),xM=()=>!0;var Su=e=>{const t=({id:n,className:i,type:o,data:l,onClick:u,onEdgeDoubleClick:c,selected:f,animated:_,label:p,labelStyle:y,labelShowBg:w,labelBgStyle:x,labelBgPadding:S,labelBgBorderRadius:j,style:E,source:A,target:L,sourceX:O,sourceY:M,targetX:H,targetY:X,sourcePosition:Y,targetPosition:Z,elementsSelectable:re,hidden:ie,sourceHandleId:ue,targetHandleId:F,onContextMenu:C,onMouseEnter:N,onMouseMove:P,onMouseLeave:D,edgeUpdaterRadius:ne,onEdgeUpdate:B,onEdgeUpdateStart:z,onEdgeUpdateEnd:G,markerEnd:T,markerStart:Q,rfId:K,ariaLabel:J,isFocusable:oe,isUpdatable:fe,pathOptions:_e,interactionWidth:we})=>{const Ae=m.useRef(null),[Be,We]=m.useState(!1),[_t,Pe]=m.useState(!1),et=ks(),lt=m.useMemo(()=>`url('#${ng(Q,K)}')`,[Q,K]),Ye=m.useMemo(()=>`url('#${ng(T,K)}')`,[T,K]);if(ie)return null;const Se=Tt=>{var yn;const{edges:bn,addSelectedEdges:Fn,unselectNodesAndEdges:An,multiSelectionActive:jn}=et.getState(),Ln=bn.find(Ns=>Ns.id===n);Ln&&(re&&(et.setState({nodesSelectionActive:!1}),Ln.selected&&jn?(An({nodes:[],edges:[Ln]}),(yn=Ae.current)==null||yn.blur()):Fn([n])),u&&u(Tt,Ln))},Le=lf(n,et.getState,c),ct=lf(n,et.getState,C),ge=lf(n,et.getState,N),De=lf(n,et.getState,P),Ke=lf(n,et.getState,D),Dt=(Tt,bn)=>{if(Tt.button!==0)return;const{edges:Fn,isValidConnection:An}=et.getState(),jn=bn?L:A,Ln=(bn?F:ue)||null,yn=bn?"target":"source",Ns=An||xM,Gn=bn,rs=Fn.find(ce=>ce.id===n);Pe(!0),z==null||z(Tt,rs,yn);const Nr=ce=>{Pe(!1),G==null||G(ce,rs,yn)};Kb({event:Tt,handleId:Ln,nodeId:jn,onConnect:ce=>B==null?void 0:B(rs,ce),isTarget:Gn,getState:et.getState,setState:et.setState,isValidConnection:Ns,edgeUpdaterType:yn,onEdgeUpdateEnd:Nr})},tn=Tt=>Dt(Tt,!0),pn=Tt=>Dt(Tt,!1),Wt=()=>We(!0),It=()=>We(!1),dn=!re&&!u,Wn=Tt=>{var bn;if(Ob.includes(Tt.key)&&re){const{unselectNodesAndEdges:Fn,addSelectedEdges:An,edges:jn}=et.getState();Tt.key==="Escape"?((bn=Ae.current)==null||bn.blur(),Fn({edges:[jn.find(yn=>yn.id===n)]})):An([n])}};return ve.createElement("g",{className:Ys(["react-flow__edge",`react-flow__edge-${o}`,i,{selected:f,animated:_,inactive:dn,updating:Be}]),onClick:Se,onDoubleClick:Le,onContextMenu:ct,onMouseEnter:ge,onMouseMove:De,onMouseLeave:Ke,onKeyDown:oe?Wn:void 0,tabIndex:oe?0:void 0,role:oe?"button":"img","data-testid":`rf__edge-${n}`,"aria-label":J===null?void 0:J||`Edge from ${A} to ${L}`,"aria-describedby":oe?`${s0}-${K}`:void 0,ref:Ae},!_t&&ve.createElement(e,{id:n,source:A,target:L,selected:f,animated:_,label:p,labelStyle:y,labelShowBg:w,labelBgStyle:x,labelBgPadding:S,labelBgBorderRadius:j,data:l,style:E,sourceX:O,sourceY:M,targetX:H,targetY:X,sourcePosition:Y,targetPosition:Z,sourceHandleId:ue,targetHandleId:F,markerStart:lt,markerEnd:Ye,pathOptions:_e,interactionWidth:we}),fe&&ve.createElement(ve.Fragment,null,(fe==="source"||fe===!0)&&ve.createElement(Qw,{position:Y,centerX:O,centerY:M,radius:ne,onMouseDown:tn,onMouseEnter:Wt,onMouseOut:It,type:"source"}),(fe==="target"||fe===!0)&&ve.createElement(Qw,{position:Z,centerX:H,centerY:X,radius:ne,onMouseDown:pn,onMouseEnter:Wt,onMouseOut:It,type:"target"})))};return t.displayName="EdgeWrapper",m.memo(t)};function bM(e){const t={default:Su(e.default||Om),straight:Su(e.bezier||Ug),step:Su(e.step||Bg),smoothstep:Su(e.step||Qm),simplebezier:Su(e.simplebezier||zg)},n={},i=Object.keys(e).filter(o=>!["default","bezier"].includes(o)).reduce((o,l)=>(o[l]=Su(e[l]||Om),o),n);return{...t,...i}}function ev(e,t,n=null){const i=((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 mt.Top:return{x:i+l/2,y:o};case mt.Right:return{x:i+l,y:o+u/2};case mt.Bottom:return{x:i+l/2,y:o+u};case mt.Left:return{x:i,y:o+u/2}}}function tv(e,t){return e?e.length===1||!t?e[0]:t&&e.find(n=>n.id===t)||null:null}const jM=(e,t,n,i,o,l)=>{const u=ev(n,e,t),c=ev(l,i,o);return{sourceX:u.x,sourceY:u.y,targetX:c.x,targetY:c.y}};function SM({sourcePos:e,targetPos:t,sourceWidth:n,sourceHeight:i,targetWidth:o,targetHeight:l,width:u,height:c,transform:f}){const _={x:Math.min(e.x,t.x),y:Math.min(e.y,t.y),x2:Math.max(e.x+n,t.x+o),y2:Math.max(e.y+i,t.y+l)};_.x===_.x2&&(_.x2+=1),_.y===_.y2&&(_.y2+=1);const p=$f({x:(0-f[0])/f[2],y:(0-f[1])/f[2],width:u/f[2],height:c/f[2]}),y=Math.max(0,Math.min(p.x2,_.x2)-Math.max(p.x,_.x)),w=Math.max(0,Math.min(p.y2,_.y2)-Math.max(p.y,_.y));return Math.ceil(y*w)>0}function nv(e){var i,o,l,u,c;const t=((i=e==null?void 0:e[hs])==null?void 0:i.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 kM=[{level:0,isMaxLevel:!0,edges:[]}];function NM(e,t,n=!1){let i=-1;const o=e.reduce((u,c)=>{var p,y;const f=ki(c.zIndex);let _=f?c.zIndex:0;if(n){const w=t.get(c.target),x=t.get(c.source),S=c.selected||(w==null?void 0:w.selected)||(x==null?void 0:x.selected),j=Math.max(((p=x==null?void 0:x[hs])==null?void 0:p.z)||0,((y=w==null?void 0:w[hs])==null?void 0:y.z)||0,1e3);_=(f?c.zIndex:0)+(S?j:0)}return u[_]?u[_].push(c):u[_]=[c],i=_>i?_:i,u},{}),l=Object.entries(o).map(([u,c])=>{const f=+u;return{edges:c,level:f,isMaxLevel:f===i}});return l.length===0?kM:l}function CM(e,t,n){const i=Rn(m.useCallback(o=>e?o.edges.filter(l=>{const u=t.get(l.source),c=t.get(l.target);return(u==null?void 0:u.width)&&(u==null?void 0:u.height)&&(c==null?void 0:c.width)&&(c==null?void 0:c.height)&&SM({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 NM(i,t,n)}const EM=({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"}),$M=({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"}),sv={[Tf.Arrow]:EM,[Tf.ArrowClosed]:$M};function AM(e){const t=ks();return m.useMemo(()=>{var o,l;return Object.prototype.hasOwnProperty.call(sv,e)?sv[e]:((l=(o=t.getState()).onError)==null||l.call(o,"009",$a.error009(e)),null)},[e])}const TM=({id:e,type:t,color:n,width:i=12.5,height:o=12.5,markerUnits:l="strokeWidth",strokeWidth:u,orient:c="auto-start-reverse"})=>{const f=AM(t);return f?ve.createElement("marker",{className:"react-flow__arrowhead",id:e,markerWidth:`${i}`,markerHeight:`${o}`,viewBox:"-10 -10 20 20",markerUnits:l,orient:c,refX:"0",refY:"0"},ve.createElement(f,{color:n,strokeWidth:u})):null},MM=({defaultColor:e,rfId:t})=>n=>{const i=[];return n.edges.reduce((o,l)=>([l.markerStart,l.markerEnd].forEach(u=>{if(u&&typeof u=="object"){const c=ng(u,t);i.includes(c)||(o.push({id:c,color:u.color||e,...u}),i.push(c))}}),o),[]).sort((o,l)=>o.id.localeCompare(l.id))},m0=({defaultColor:e,rfId:t})=>{const n=Rn(m.useCallback(MM({defaultColor:e,rfId:t}),[e,t]),(i,o)=>!(i.length!==o.length||i.some((l,u)=>l.id!==o[u].id)));return ve.createElement("defs",null,n.map(i=>ve.createElement(TM,{id:i.id,key:i.id,type:i.type,color:i.color,width:i.width,height:i.height,markerUnits:i.markerUnits,strokeWidth:i.strokeWidth,orient:i.orient})))};m0.displayName="MarkerDefinitions";var RM=m.memo(m0);const LM=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}),_0=({defaultMarkerColor:e,onlyRenderVisibleElements:t,elevateEdgesOnSelect:n,rfId:i,edgeTypes:o,noPanClassName:l,onEdgeUpdate:u,onEdgeContextMenu:c,onEdgeMouseEnter:f,onEdgeMouseMove:_,onEdgeMouseLeave:p,onEdgeClick:y,edgeUpdaterRadius:w,onEdgeDoubleClick:x,onEdgeUpdateStart:S,onEdgeUpdateEnd:j,children:E})=>{const{edgesFocusable:A,edgesUpdatable:L,elementsSelectable:O,width:M,height:H,connectionMode:X,nodeInternals:Y,onError:Z}=Rn(LM,Us),re=CM(t,Y,n);return M?ve.createElement(ve.Fragment,null,re.map(({level:ie,edges:ue,isMaxLevel:F})=>ve.createElement("svg",{key:ie,style:{zIndex:ie},width:M,height:H,className:"react-flow__edges react-flow__container"},F&&ve.createElement(RM,{defaultColor:e,rfId:i}),ve.createElement("g",null,ue.map(C=>{const[N,P,D]=nv(Y.get(C.source)),[ne,B,z]=nv(Y.get(C.target));if(!D||!z)return null;let G=C.type||"default";o[G]||(Z==null||Z("011",$a.error011(G)),G="default");const T=o[G]||o.default,Q=X===lc.Strict?B.target:(B.target??[]).concat(B.source??[]),K=tv(P.source,C.sourceHandle),J=tv(Q,C.targetHandle),oe=(K==null?void 0:K.position)||mt.Bottom,fe=(J==null?void 0:J.position)||mt.Top,_e=!!(C.focusable||A&&typeof C.focusable>"u"),we=typeof u<"u"&&(C.updatable||L&&typeof C.updatable>"u");if(!K||!J)return Z==null||Z("008",$a.error008(K,C)),null;const{sourceX:Ae,sourceY:Be,targetX:We,targetY:_t}=jM(N,K,oe,ne,J,fe);return ve.createElement(T,{key:C.id,id:C.id,className:Ys([C.className,l]),type:G,data:C.data,selected:!!C.selected,animated:!!C.animated,hidden:!!C.hidden,label:C.label,labelStyle:C.labelStyle,labelShowBg:C.labelShowBg,labelBgStyle:C.labelBgStyle,labelBgPadding:C.labelBgPadding,labelBgBorderRadius:C.labelBgBorderRadius,style:C.style,source:C.source,target:C.target,sourceHandleId:C.sourceHandle,targetHandleId:C.targetHandle,markerEnd:C.markerEnd,markerStart:C.markerStart,sourceX:Ae,sourceY:Be,targetX:We,targetY:_t,sourcePosition:oe,targetPosition:fe,elementsSelectable:O,onEdgeUpdate:u,onContextMenu:c,onMouseEnter:f,onMouseMove:_,onMouseLeave:p,onClick:y,edgeUpdaterRadius:w,onEdgeDoubleClick:x,onEdgeUpdateStart:S,onEdgeUpdateEnd:j,rfId:i,ariaLabel:C.ariaLabel,isFocusable:_e,isUpdatable:we,pathOptions:"pathOptions"in C?C.pathOptions:void 0,interactionWidth:C.interactionWidth})})))),E):null};_0.displayName="EdgeRenderer";var IM=m.memo(_0);const OM=e=>`translate(${e.transform[0]}px,${e.transform[1]}px) scale(${e.transform[2]})`;function PM({children:e}){const t=Rn(OM);return ve.createElement("div",{className:"react-flow__viewport react-flow__container",style:{transform:t}},e)}function DM(e){const t=Vg(),n=m.useRef(!1);m.useEffect(()=>{!n.current&&t.viewportInitialized&&e&&(setTimeout(()=>e(t),1),n.current=!0)},[e,t.viewportInitialized])}const FM={[mt.Left]:mt.Right,[mt.Right]:mt.Left,[mt.Top]:mt.Bottom,[mt.Bottom]:mt.Top},p0=({nodeId:e,handleType:t,style:n,type:i=hl.Bezier,CustomComponent:o,connectionStatus:l})=>{var X,Y,Z;const{fromNode:u,handleId:c,toX:f,toY:_,connectionMode:p}=Rn(m.useCallback(re=>({fromNode:re.nodeInternals.get(e),handleId:re.connectionHandleId,toX:(re.connectionPosition.x-re.transform[0])/re.transform[2],toY:(re.connectionPosition.y-re.transform[1])/re.transform[2],connectionMode:re.connectionMode}),[e]),Us),y=(X=u==null?void 0:u[hs])==null?void 0:X.handleBounds;let w=y==null?void 0:y[t];if(p===lc.Loose&&(w=w||(y==null?void 0:y[t==="source"?"target":"source"])),!u||!w)return null;const x=c?w.find(re=>re.id===c):w[0],S=x?x.x+x.width/2:(u.width??0)/2,j=x?x.y+x.height/2:u.height??0,E=(((Y=u.positionAbsolute)==null?void 0:Y.x)??0)+S,A=(((Z=u.positionAbsolute)==null?void 0:Z.y)??0)+j,L=x==null?void 0:x.position,O=L?FM[L]:null;if(!L||!O)return null;if(o)return ve.createElement(o,{connectionLineType:i,connectionLineStyle:n,fromNode:u,fromHandle:x,fromX:E,fromY:A,toX:f,toY:_,fromPosition:L,toPosition:O,connectionStatus:l});let M="";const H={sourceX:E,sourceY:A,sourcePosition:L,targetX:f,targetY:_,targetPosition:O};return i===hl.Bezier?[M]=Bb(H):i===hl.Step?[M]=tg({...H,borderRadius:0}):i===hl.SmoothStep?[M]=tg(H):i===hl.SimpleBezier?[M]=zb(H):M=`M${E},${A} ${f},${_}`,ve.createElement("path",{d:M,fill:"none",className:"react-flow__connection-path",style:n})};p0.displayName="ConnectionLine";const zM=e=>({nodeId:e.connectionNodeId,handleType:e.connectionHandleType,nodesConnectable:e.nodesConnectable,connectionStatus:e.connectionStatus,width:e.width,height:e.height});function BM({containerStyle:e,style:t,type:n,component:i}){const{nodeId:o,handleType:l,nodesConnectable:u,width:c,height:f,connectionStatus:_}=Rn(zM,Us);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:Ys(["react-flow__connection",_])},ve.createElement(p0,{nodeId:o,handleType:l,style:t,type:n,CustomComponent:i,connectionStatus:_})))}function rv(e,t){return m.useRef(null),ks(),m.useMemo(()=>t(e),[e])}const g0=({nodeTypes:e,edgeTypes:t,onMove:n,onMoveStart:i,onMoveEnd:o,onInit:l,onNodeClick:u,onEdgeClick:c,onNodeDoubleClick:f,onEdgeDoubleClick:_,onNodeMouseEnter:p,onNodeMouseMove:y,onNodeMouseLeave:w,onNodeContextMenu:x,onSelectionContextMenu:S,onSelectionStart:j,onSelectionEnd:E,connectionLineType:A,connectionLineStyle:L,connectionLineComponent:O,connectionLineContainerStyle:M,selectionKeyCode:H,selectionOnDrag:X,selectionMode:Y,multiSelectionKeyCode:Z,panActivationKeyCode:re,zoomActivationKeyCode:ie,deleteKeyCode:ue,onlyRenderVisibleElements:F,elementsSelectable:C,selectNodesOnDrag:N,defaultViewport:P,translateExtent:D,minZoom:ne,maxZoom:B,preventScrolling:z,defaultMarkerColor:G,zoomOnScroll:T,zoomOnPinch:Q,panOnScroll:K,panOnScrollSpeed:J,panOnScrollMode:oe,zoomOnDoubleClick:fe,panOnDrag:_e,onPaneClick:we,onPaneMouseEnter:Ae,onPaneMouseMove:Be,onPaneMouseLeave:We,onPaneScroll:_t,onPaneContextMenu:Pe,onEdgeUpdate:et,onEdgeContextMenu:lt,onEdgeMouseEnter:Ye,onEdgeMouseMove:Se,onEdgeMouseLeave:Le,edgeUpdaterRadius:ct,onEdgeUpdateStart:ge,onEdgeUpdateEnd:De,noDragClassName:Ke,noWheelClassName:Dt,noPanClassName:tn,elevateEdgesOnSelect:pn,disableKeyboardA11y:Wt,nodeOrigin:It,nodeExtent:dn,rfId:Wn})=>{const Tt=rv(e,_M),bn=rv(t,bM);return DM(l),ve.createElement(hM,{onPaneClick:we,onPaneMouseEnter:Ae,onPaneMouseMove:Be,onPaneMouseLeave:We,onPaneContextMenu:Pe,onPaneScroll:_t,deleteKeyCode:ue,selectionKeyCode:H,selectionOnDrag:X,selectionMode:Y,onSelectionStart:j,onSelectionEnd:E,multiSelectionKeyCode:Z,panActivationKeyCode:re,zoomActivationKeyCode:ie,elementsSelectable:C,onMove:n,onMoveStart:i,onMoveEnd:o,zoomOnScroll:T,zoomOnPinch:Q,zoomOnDoubleClick:fe,panOnScroll:K,panOnScrollSpeed:J,panOnScrollMode:oe,panOnDrag:_e,defaultViewport:P,translateExtent:D,minZoom:ne,maxZoom:B,onSelectionContextMenu:S,preventScrolling:z,noDragClassName:Ke,noWheelClassName:Dt,noPanClassName:tn,disableKeyboardA11y:Wt},ve.createElement(PM,null,ve.createElement(IM,{edgeTypes:bn,onEdgeClick:c,onEdgeDoubleClick:_,onEdgeUpdate:et,onlyRenderVisibleElements:F,onEdgeContextMenu:lt,onEdgeMouseEnter:Ye,onEdgeMouseMove:Se,onEdgeMouseLeave:Le,onEdgeUpdateStart:ge,onEdgeUpdateEnd:De,edgeUpdaterRadius:ct,defaultMarkerColor:G,noPanClassName:tn,elevateEdgesOnSelect:!!pn,disableKeyboardA11y:Wt,rfId:Wn},ve.createElement(BM,{style:L,type:A,component:O,containerStyle:M})),ve.createElement("div",{className:"react-flow__edgelabel-renderer"}),ve.createElement(yM,{nodeTypes:Tt,onNodeClick:u,onNodeDoubleClick:f,onNodeMouseEnter:p,onNodeMouseMove:y,onNodeMouseLeave:w,onNodeContextMenu:x,selectNodesOnDrag:N,onlyRenderVisibleElements:F,noPanClassName:tn,noDragClassName:Ke,disableKeyboardA11y:Wt,nodeOrigin:It,nodeExtent:dn,rfId:Wn})))};g0.displayName="GraphView";var UM=m.memo(g0);const og=[[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY],[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY]],il={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:og,nodeExtent:og,nodesSelectionActive:!1,userSelectionActive:!1,userSelectionRect:null,connectionNodeId:null,connectionHandleId:null,connectionHandleType:"source",connectionPosition:{x:0,y:0},connectionStatus:null,connectionMode:lc.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:_T,isValidConnection:void 0},WM=()=>A2((e,t)=>({...il,setNodes:n=>{const{nodeInternals:i,nodeOrigin:o,elevateNodesOnSelect:l}=t();e({nodeInternals:op(n,i,o,l)})},getNodes:()=>Array.from(t().nodeInternals.values()),setEdges:n=>{const{defaultEdgeOptions:i={}}=t();e({edges:n.map(o=>({...i,...o}))})},setDefaultNodesAndEdges:(n,i)=>{const o=typeof n<"u",l=typeof i<"u",u=o?op(n,new Map,t().nodeOrigin,t().elevateNodesOnSelect):new Map;e({nodeInternals:u,edges:l?i:[],hasDefaultNodes:o,hasDefaultEdges:l})},updateNodeDimensions:n=>{const{onNodesChange:i,nodeInternals:o,fitViewOnInit:l,fitViewOnInitDone:u,fitViewOnInitOptions:c,domNode:f,nodeOrigin:_}=t(),p=f==null?void 0:f.querySelector(".react-flow__viewport");if(!p)return;const y=window.getComputedStyle(p),{m22:w}=new window.DOMMatrixReadOnly(y.transform),x=n.reduce((j,E)=>{const A=o.get(E.id);if(A){const L=Dg(E.nodeElement);!!(L.width&&L.height&&(A.width!==L.width||A.height!==L.height||E.forceUpdate))&&(o.set(A.id,{...A,[hs]:{...A[hs],handleBounds:{source:Xw(".source",E.nodeElement,w,_),target:Xw(".target",E.nodeElement,w,_)}},...L}),j.push({id:A.id,type:"dimensions",dimensions:L}))}return j},[]);i0(o,_);const S=u||l&&!u&&o0(t,{initial:!0,...c});e({nodeInternals:new Map(o),fitViewOnInitDone:S}),(x==null?void 0:x.length)>0&&(i==null||i(x))},updateNodePositions:(n,i=!0,o=!1)=>{const{triggerNodeChanges:l}=t(),u=n.map(c=>{const f={id:c.id,type:"position",dragging:o};return i&&(f.positionAbsolute=c.positionAbsolute,f.position=c.position),f});l(u)},triggerNodeChanges:n=>{const{onNodesChange:i,nodeInternals:o,hasDefaultNodes:l,nodeOrigin:u,getNodes:c,elevateNodesOnSelect:f}=t();if(n!=null&&n.length){if(l){const _=rM(n,c()),p=op(_,o,u,f);e({nodeInternals:p})}i==null||i(n)}},addSelectedNodes:n=>{const{multiSelectionActive:i,edges:o,getNodes:l}=t();let u,c=null;i?u=n.map(f=>dl(f,!0)):(u=$u(l(),n),c=$u(o,[])),nm({changedNodes:u,changedEdges:c,get:t,set:e})},addSelectedEdges:n=>{const{multiSelectionActive:i,edges:o,getNodes:l}=t();let u,c=null;i?u=n.map(f=>dl(f,!0)):(u=$u(o,n),c=$u(l(),[])),nm({changedNodes:c,changedEdges:u,get:t,set:e})},unselectNodesAndEdges:({nodes:n,edges:i}={})=>{const{edges:o,getNodes:l}=t(),u=n||l(),c=i||o,f=u.map(p=>(p.selected=!1,dl(p.id,!1))),_=c.map(p=>dl(p.id,!1));nm({changedNodes:f,changedEdges:_,get:t,set:e})},setMinZoom:n=>{const{d3Zoom:i,maxZoom:o}=t();i==null||i.scaleExtent([n,o]),e({minZoom:n})},setMaxZoom:n=>{const{d3Zoom:i,minZoom:o}=t();i==null||i.scaleExtent([o,n]),e({maxZoom:n})},setTranslateExtent:n=>{var i;(i=t().d3Zoom)==null||i.translateExtent(n),e({translateExtent:n})},resetSelectedElements:()=>{const{edges:n,getNodes:i}=t(),l=i().filter(c=>c.selected).map(c=>dl(c.id,!1)),u=n.filter(c=>c.selected).map(c=>dl(c.id,!1));nm({changedNodes:l,changedEdges:u,get:t,set:e})},setNodeExtent:n=>{const{nodeInternals:i}=t();i.forEach(o=>{o.positionAbsolute=Fg(o.position,n)}),e({nodeExtent:n,nodeInternals:new Map(i)})},panBy:n=>{const{transform:i,width:o,height:l,d3Zoom:u,d3Selection:c,translateExtent:f}=t();if(!u||!c||!n.x&&!n.y)return!1;const _=ka.translate(i[0]+n.x,i[1]+n.y).scale(i[2]),p=[[0,0],[o,l]],y=u==null?void 0:u.constrain()(_,p,f);return u.transform(c,y),i[0]!==y.x||i[1]!==y.y||i[2]!==y.k},cancelConnection:()=>e({connectionNodeId:il.connectionNodeId,connectionHandleId:il.connectionHandleId,connectionHandleType:il.connectionHandleType,connectionStatus:il.connectionStatus,connectionStartHandle:il.connectionStartHandle,connectionEndHandle:il.connectionEndHandle}),reset:()=>e({...il})}),Object.is),Kg=({children:e})=>{const t=m.useRef(null);return t.current||(t.current=WM()),ve.createElement(lT,{value:t.current},e)};Kg.displayName="ReactFlowProvider";const y0=({children:e})=>m.useContext(Zm)?ve.createElement(ve.Fragment,null,e):ve.createElement(Kg,null,e);y0.displayName="ReactFlowWrapper";const qM={input:Zb,default:rg,output:e0,group:Hg},HM={default:Om,straight:Ug,step:Bg,smoothstep:Qm,simplebezier:zg},VM=[0,0],GM=[15,15],KM={x:0,y:0,zoom:1},YM={width:"100%",height:"100%",overflow:"hidden",position:"relative",zIndex:0},w0=m.forwardRef(({nodes:e,edges:t,defaultNodes:n,defaultEdges:i,className:o,nodeTypes:l=qM,edgeTypes:u=HM,onNodeClick:c,onEdgeClick:f,onInit:_,onMove:p,onMoveStart:y,onMoveEnd:w,onConnect:x,onConnectStart:S,onConnectEnd:j,onClickConnectStart:E,onClickConnectEnd:A,onNodeMouseEnter:L,onNodeMouseMove:O,onNodeMouseLeave:M,onNodeContextMenu:H,onNodeDoubleClick:X,onNodeDragStart:Y,onNodeDrag:Z,onNodeDragStop:re,onNodesDelete:ie,onEdgesDelete:ue,onSelectionChange:F,onSelectionDragStart:C,onSelectionDrag:N,onSelectionDragStop:P,onSelectionContextMenu:D,onSelectionStart:ne,onSelectionEnd:B,connectionMode:z=lc.Strict,connectionLineType:G=hl.Bezier,connectionLineStyle:T,connectionLineComponent:Q,connectionLineContainerStyle:K,deleteKeyCode:J="Backspace",selectionKeyCode:oe="Shift",selectionOnDrag:fe=!1,selectionMode:_e=Af.Full,panActivationKeyCode:we="Space",multiSelectionKeyCode:Ae=Im()?"Meta":"Control",zoomActivationKeyCode:Be=Im()?"Meta":"Control",snapToGrid:We=!1,snapGrid:_t=GM,onlyRenderVisibleElements:Pe=!1,selectNodesOnDrag:et=!0,nodesDraggable:lt,nodesConnectable:Ye,nodesFocusable:Se,nodeOrigin:Le=VM,edgesFocusable:ct,edgesUpdatable:ge,elementsSelectable:De,defaultViewport:Ke=KM,minZoom:Dt=.5,maxZoom:tn=2,translateExtent:pn=og,preventScrolling:Wt=!0,nodeExtent:It,defaultMarkerColor:dn="#b1b1b7",zoomOnScroll:Wn=!0,zoomOnPinch:Tt=!0,panOnScroll:bn=!1,panOnScrollSpeed:Fn=.5,panOnScrollMode:An=Ql.Free,zoomOnDoubleClick:jn=!0,panOnDrag:Ln=!0,onPaneClick:yn,onPaneMouseEnter:Ns,onPaneMouseMove:Gn,onPaneMouseLeave:rs,onPaneScroll:Nr,onPaneContextMenu:Kn,children:ce,onEdgeUpdate:be,onEdgeContextMenu:Ve,onEdgeDoubleClick:He,onEdgeMouseEnter:st,onEdgeMouseMove:ut,onEdgeMouseLeave:At,onEdgeUpdateStart:kt,onEdgeUpdateEnd:Vt,edgeUpdaterRadius:dt=10,onNodesChange:Xt,onEdgesChange:Ut,noDragClassName:Ct="nodrag",noWheelClassName:pt="nowheel",noPanClassName:Ot="nopan",fitView:Ee=!1,fitViewOptions:Ht,connectOnClick:Et=!0,attributionPosition:an,proOptions:$t,defaultEdgeOptions:is,elevateNodesOnSelect:os=!0,elevateEdgesOnSelect:Js=!1,disableKeyboardA11y:Cs=!1,autoPanOnConnect:hr=!0,autoPanOnNodeDrag:Xs=!0,connectionRadius:lo=20,isValidConnection:xe,onError:Yn,style:mn,id:co,nodeDragThreshold:Ei,...Cr},mr)=>{const Jr=co||"1";return ve.createElement("div",{...Cr,style:{...mn,...YM},ref:mr,className:Ys(["react-flow",o]),"data-testid":"rf__wrapper",id:co},ve.createElement(y0,null,ve.createElement(UM,{onInit:_,onMove:p,onMoveStart:y,onMoveEnd:w,onNodeClick:c,onEdgeClick:f,onNodeMouseEnter:L,onNodeMouseMove:O,onNodeMouseLeave:M,onNodeContextMenu:H,onNodeDoubleClick:X,nodeTypes:l,edgeTypes:u,connectionLineType:G,connectionLineStyle:T,connectionLineComponent:Q,connectionLineContainerStyle:K,selectionKeyCode:oe,selectionOnDrag:fe,selectionMode:_e,deleteKeyCode:J,multiSelectionKeyCode:Ae,panActivationKeyCode:we,zoomActivationKeyCode:Be,onlyRenderVisibleElements:Pe,selectNodesOnDrag:et,defaultViewport:Ke,translateExtent:pn,minZoom:Dt,maxZoom:tn,preventScrolling:Wt,zoomOnScroll:Wn,zoomOnPinch:Tt,zoomOnDoubleClick:jn,panOnScroll:bn,panOnScrollSpeed:Fn,panOnScrollMode:An,panOnDrag:Ln,onPaneClick:yn,onPaneMouseEnter:Ns,onPaneMouseMove:Gn,onPaneMouseLeave:rs,onPaneScroll:Nr,onPaneContextMenu:Kn,onSelectionContextMenu:D,onSelectionStart:ne,onSelectionEnd:B,onEdgeUpdate:be,onEdgeContextMenu:Ve,onEdgeDoubleClick:He,onEdgeMouseEnter:st,onEdgeMouseMove:ut,onEdgeMouseLeave:At,onEdgeUpdateStart:kt,onEdgeUpdateEnd:Vt,edgeUpdaterRadius:dt,defaultMarkerColor:dn,noDragClassName:Ct,noWheelClassName:pt,noPanClassName:Ot,elevateEdgesOnSelect:Js,rfId:Jr,disableKeyboardA11y:Cs,nodeOrigin:Le,nodeExtent:It}),ve.createElement(DT,{nodes:e,edges:t,defaultNodes:n,defaultEdges:i,onConnect:x,onConnectStart:S,onConnectEnd:j,onClickConnectStart:E,onClickConnectEnd:A,nodesDraggable:lt,nodesConnectable:Ye,nodesFocusable:Se,edgesFocusable:ct,edgesUpdatable:ge,elementsSelectable:De,elevateNodesOnSelect:os,minZoom:Dt,maxZoom:tn,nodeExtent:It,onNodesChange:Xt,onEdgesChange:Ut,snapToGrid:We,snapGrid:_t,connectionMode:z,translateExtent:pn,connectOnClick:Et,defaultEdgeOptions:is,fitView:Ee,fitViewOptions:Ht,onNodesDelete:ie,onEdgesDelete:ue,onNodeDragStart:Y,onNodeDrag:Z,onNodeDragStop:re,onSelectionDrag:N,onSelectionDragStart:C,onSelectionDragStop:P,noPanClassName:Ot,nodeOrigin:Le,rfId:Jr,autoPanOnConnect:hr,autoPanOnNodeDrag:Xs,onError:Yn,connectionRadius:lo,isValidConnection:xe,nodeDragThreshold:Ei}),ve.createElement(OT,{onSelectionChange:F}),ce,ve.createElement(uT,{proOptions:$t,position:an}),ve.createElement(WT,{rfId:Jr,disableKeyboardA11y:Cs})))});w0.displayName="ReactFlow";const v0=({id:e,x:t,y:n,width:i,height:o,style:l,color:u,strokeColor:c,strokeWidth:f,className:_,borderRadius:p,shapeRendering:y,onClick:w,selected:x})=>{const{background:S,backgroundColor:j}=l||{},E=u||S||j;return ve.createElement("rect",{className:Ys(["react-flow__minimap-node",{selected:x},_]),x:t,y:n,rx:p,ry:p,width:i,height:o,fill:E,stroke:c,strokeWidth:f,shapeRendering:y,onClick:w?A=>w(A,e):void 0})};v0.displayName="MiniMapNode";var JM=m.memo(v0);const XM=e=>e.nodeOrigin,ZM=e=>e.getNodes().filter(t=>!t.hidden&&t.width&&t.height),up=e=>e instanceof Function?e:()=>e;function QM({nodeStrokeColor:e="transparent",nodeColor:t="#e2e2e2",nodeClassName:n="",nodeBorderRadius:i=5,nodeStrokeWidth:o=2,nodeComponent:l=JM,onClick:u}){const c=Rn(ZM,Us),f=Rn(XM),_=up(t),p=up(e),y=up(n),w=typeof window>"u"||window.chrome?"crispEdges":"geometricPrecision";return ve.createElement(ve.Fragment,null,c.map(x=>{const{x:S,y:j}=rc(x,f).positionAbsolute;return ve.createElement(l,{key:x.id,x:S,y:j,width:x.width,height:x.height,style:x.style,selected:x.selected,className:y(x),color:_(x),borderRadius:i,strokeColor:p(x),strokeWidth:o,shapeRendering:w,onClick:u,id:x.id})}))}var eR=m.memo(QM);const tR=200,nR=150,sR=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?hT(e_(t,e.nodeOrigin),n):n,rfId:e.rfId}},rR="react-flow__minimap-desc";function x0({style:e,className:t,nodeStrokeColor:n="transparent",nodeColor:i="#e2e2e2",nodeClassName:o="",nodeBorderRadius:l=5,nodeStrokeWidth:u=2,nodeComponent:c,maskColor:f="rgb(240, 240, 240, 0.6)",maskStrokeColor:_="none",maskStrokeWidth:p=1,position:y="bottom-right",onClick:w,onNodeClick:x,pannable:S=!1,zoomable:j=!1,ariaLabel:E="React Flow mini map",inversePan:A=!1,zoomStep:L=10,offsetScale:O=5}){const M=ks(),H=m.useRef(null),{boundingRect:X,viewBB:Y,rfId:Z}=Rn(sR,Us),re=(e==null?void 0:e.width)??tR,ie=(e==null?void 0:e.height)??nR,ue=X.width/re,F=X.height/ie,C=Math.max(ue,F),N=C*re,P=C*ie,D=O*C,ne=X.x-(N-X.width)/2-D,B=X.y-(P-X.height)/2-D,z=N+D*2,G=P+D*2,T=`${rR}-${Z}`,Q=m.useRef(0);Q.current=C,m.useEffect(()=>{if(H.current){const oe=Si(H.current),fe=Ae=>{const{transform:Be,d3Selection:We,d3Zoom:_t}=M.getState();if(Ae.sourceEvent.type!=="wheel"||!We||!_t)return;const Pe=-Ae.sourceEvent.deltaY*(Ae.sourceEvent.deltaMode===1?.05:Ae.sourceEvent.deltaMode?1:.002)*L,et=Be[2]*Math.pow(2,Pe);_t.scaleTo(We,et)},_e=Ae=>{const{transform:Be,d3Selection:We,d3Zoom:_t,translateExtent:Pe,width:et,height:lt}=M.getState();if(Ae.sourceEvent.type!=="mousemove"||!We||!_t)return;const Ye=Q.current*Math.max(1,Be[2])*(A?-1:1),Se={x:Be[0]-Ae.sourceEvent.movementX*Ye,y:Be[1]-Ae.sourceEvent.movementY*Ye},Le=[[0,0],[et,lt]],ct=ka.translate(Se.x,Se.y).scale(Be[2]),ge=_t.constrain()(ct,Le,Pe);_t.transform(We,ge)},we=Ab().on("zoom",S?_e:null).on("zoom.wheel",j?fe:null);return oe.call(we),()=>{oe.on("zoom",null)}}},[S,j,A,L]);const K=w?oe=>{const fe=no(oe);w(oe,{x:fe[0],y:fe[1]})}:void 0,J=x?(oe,fe)=>{const _e=M.getState().nodeInternals.get(fe);x(oe,_e)}:void 0;return ve.createElement(Ef,{position:y,style:e,className:Ys(["react-flow__minimap",t]),"data-testid":"rf__minimap"},ve.createElement("svg",{width:re,height:ie,viewBox:`${ne} ${B} ${z} ${G}`,role:"img","aria-labelledby":T,ref:H,onClick:K},E&&ve.createElement("title",{id:T},E),ve.createElement(eR,{onClick:J,nodeColor:i,nodeStrokeColor:n,nodeBorderRadius:l,nodeClassName:o,nodeStrokeWidth:u,nodeComponent:c}),ve.createElement("path",{className:"react-flow__minimap-mask",d:`M${ne-D},${B-D}h${z+D*2}v${G+D*2}h${-z-D*2}z
|
|
132
|
+
M${Y.x},${Y.y}h${Y.width}v${Y.height}h${-Y.width}z`,fill:f,fillRule:"evenodd",stroke:_,strokeWidth:p,pointerEvents:"none"})))}x0.displayName="MiniMap";var iR=m.memo(x0);function oR(){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 aR(){return ve.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 5"},ve.createElement("path",{d:"M0 0h32v4.2H0z"}))}function lR(){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 cR(){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 uR(){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 Au=({children:e,className:t,...n})=>ve.createElement("button",{type:"button",className:Ys(["react-flow__controls-button",t]),...n},e);Au.displayName="ControlButton";const dR=e=>({isInteractive:e.nodesDraggable||e.nodesConnectable||e.elementsSelectable,minZoomReached:e.transform[2]<=e.minZoom,maxZoomReached:e.transform[2]>=e.maxZoom}),b0=({style:e,showZoom:t=!0,showFitView:n=!0,showInteractive:i=!0,fitViewOptions:o,onZoomIn:l,onZoomOut:u,onFitView:c,onInteractiveChange:f,className:_,children:p,position:y="bottom-left"})=>{const w=ks(),[x,S]=m.useState(!1),{isInteractive:j,minZoomReached:E,maxZoomReached:A}=Rn(dR,Us),{zoomIn:L,zoomOut:O,fitView:M}=Vg();if(m.useEffect(()=>{S(!0)},[]),!x)return null;const H=()=>{L(),l==null||l()},X=()=>{O(),u==null||u()},Y=()=>{M(o),c==null||c()},Z=()=>{w.setState({nodesDraggable:!j,nodesConnectable:!j,elementsSelectable:!j}),f==null||f(!j)};return ve.createElement(Ef,{className:Ys(["react-flow__controls",_]),position:y,style:e,"data-testid":"rf__controls"},t&&ve.createElement(ve.Fragment,null,ve.createElement(Au,{onClick:H,className:"react-flow__controls-zoomin",title:"zoom in","aria-label":"zoom in",disabled:A},ve.createElement(oR,null)),ve.createElement(Au,{onClick:X,className:"react-flow__controls-zoomout",title:"zoom out","aria-label":"zoom out",disabled:E},ve.createElement(aR,null))),n&&ve.createElement(Au,{className:"react-flow__controls-fitview",onClick:Y,title:"fit view","aria-label":"fit view"},ve.createElement(lR,null)),i&&ve.createElement(Au,{className:"react-flow__controls-interactive",onClick:Z,title:"toggle interactivity","aria-label":"toggle interactivity"},j?ve.createElement(uR,null):ve.createElement(cR,null)),p)};b0.displayName="Controls";var fR=m.memo(b0),io;(function(e){e.Lines="lines",e.Dots="dots",e.Cross="cross"})(io||(io={}));function hR({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 mR({color:e,radius:t}){return ve.createElement("circle",{cx:t,cy:t,r:t,fill:e})}const _R={[io.Dots]:"#91919a",[io.Lines]:"#eee",[io.Cross]:"#e2e2e2"},pR={[io.Dots]:1,[io.Lines]:1,[io.Cross]:6},gR=e=>({transform:e.transform,patternId:`pattern-${e.rfId}`});function j0({id:e,variant:t=io.Dots,gap:n=20,size:i,lineWidth:o=1,offset:l=2,color:u,style:c,className:f}){const _=m.useRef(null),{transform:p,patternId:y}=Rn(gR,Us),w=u||_R[t],x=i||pR[t],S=t===io.Dots,j=t===io.Cross,E=Array.isArray(n)?n:[n,n],A=[E[0]*p[2]||1,E[1]*p[2]||1],L=x*p[2],O=j?[L,L]:A,M=S?[L/l,L/l]:[O[0]/l,O[1]/l];return ve.createElement("svg",{className:Ys(["react-flow__background",f]),style:{...c,position:"absolute",width:"100%",height:"100%",top:0,left:0},ref:_,"data-testid":"rf__background"},ve.createElement("pattern",{id:y+e,x:p[0]%A[0],y:p[1]%A[1],width:A[0],height:A[1],patternUnits:"userSpaceOnUse",patternTransform:`translate(-${M[0]},-${M[1]})`},S?ve.createElement(mR,{color:w,radius:L/l}):ve.createElement(hR,{dimensions:O,color:w,lineWidth:o})),ve.createElement("rect",{x:"0",y:"0",width:"100%",height:"100%",fill:`url(#${y+e})`}))}j0.displayName="Background";var yR=m.memo(j0);function S0(e,t={}){const n=e&&typeof e=="object"&&!Array.isArray(e)?e:null;if(!n)return null;const i=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(i===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(i)>u||Math.abs(o)>u)return null;const c=typeof t.minZoom=="number"&&Number.isFinite(t.minZoom)?t.minZoom:.025,f=typeof t.maxZoom=="number"&&Number.isFinite(t.maxZoom)?t.maxZoom:6,_=Math.min(c,f),p=Math.max(c,f);return{x:i,y:o,zoom:Math.min(p,Math.max(_,l))}}function Dm(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 wR(e){const t=String(e||"").trim();if(!t)return"entity";const n=t.indexOf(":");if(n<=0||n>=t.length-1)return"entity";const i=t.slice(0,n).toLowerCase(),o=t.slice(n+1).toLowerCase();if(i==="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 i==="schema"||i==="skos"||i==="dcterms"||i==="rdf"||i==="cito"?"vocab":"entity"}function vR(e){const t=String(e||"").trim();if(!t)return"";const n=t.indexOf(":");if(n<=0||n>=t.length-1)return Dm(t);const i=t.slice(0,n).toLowerCase(),o=t.slice(n+1);if(i==="ex"){const l=o.indexOf("-");if(l>0&&l<o.length-1)return o.slice(l+1)}return Dm(t)}function ag(e){const i=Math.max(1,Math.ceil(Math.sqrt(e.length))),o={};for(let l=0;l<e.length;l++){const u=Math.floor(l/i),c=l%i;o[e[l]]={x:c*240,y:u*120}}return o}function lg(e){const t=String(e??"");let n=2166136261;for(let i=0;i<t.length;i++)n^=t.charCodeAt(i),n=Math.imul(n,16777619);return n>>>0}function k0(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 xR(e,t){const n={},i=e.length;if(!i)return n;const o=Math.max(260,Math.sqrt(i)*150),l=t%360*Math.PI/180;for(let u=0;u<i;u++){const c=l+2*Math.PI*u/i;n[e[u]]={x:o*Math.cos(c),y:o*Math.sin(c)}}return n}function iv(e,t,n){var S;const i={};if(!e.length)return i;const o=new Map;for(const j of e)o.set(j,new Set);for(const j of t){const E=String((j==null?void 0:j.source)||"").trim(),A=String((j==null?void 0:j.target)||"").trim();if(!E||!A||E===A)continue;const L=o.get(E),O=o.get(A);L&&L.add(A),O&&O.add(E)}let l=e[0],u=-1;for(const j of e){const E=((S=o.get(j))==null?void 0:S.size)??0;(E>u||E===u&&j.localeCompare(l)<0)&&(l=j,u=E)}const c=new Map,f=[];for(c.set(l,0),f.push(l);f.length;){const j=f.shift(),E=c.get(j)??0,A=Array.from(o.get(j)??[]);A.sort((L,O)=>L.localeCompare(O));for(const L of A)c.has(L)||(c.set(L,E+1),f.push(L))}let _=0;for(const j of c.values())_=Math.max(_,j);for(const j of e)c.has(j)||c.set(j,_+1);const p=new Map;for(const j of e){const E=c.get(j)??0,A=p.get(E);A?A.push(j):p.set(E,[j])}const y=Array.from(p.keys()).sort((j,E)=>j-E),w=260,x=n%360*Math.PI/180;for(const j of y){const E=p.get(j)||[];if(E.sort((M,H)=>M.localeCompare(H)),j===0){if(E.length===1)i[E[0]]={x:0,y:0};else for(let H=0;H<E.length;H++){const X=x+2*Math.PI*H/E.length;i[E[H]]={x:80*Math.cos(X),y:80*Math.sin(X)}}continue}const A=w*j,L=E.length;if(L===1){i[E[0]]={x:A,y:0};continue}const O=x+j*.35;for(let M=0;M<L;M++){const H=O+2*Math.PI*M/L;i[E[M]]={x:A*Math.cos(H),y:A*Math.sin(H)}}}return i}function Nu(e,t={}){const n=t.kind??"grid",i=typeof t.seed=="number"&&Number.isFinite(t.seed)?Math.trunc(t.seed):0,o=e.nodes.map(l=>l.id);if(n==="grid")return ag(o);if(n==="circle")return xR(o,i);if(n==="radial")return iv(o,e.edges,i);if(n==="force"){const l=iv(o,e.edges,i),u=k0(i||1),c=Math.max(10,Math.min(42,Math.sqrt(o.length)*2.75)),f={};for(const _ of o){const p=l[_]||{x:0,y:0};f[_]={x:p.x+(u()-.5)*c,y:p.y+(u()-.5)*c}}return f}return ag(o)}function bR(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 jR(e,t={}){const n=!!(t.groupEdges??!0),i=Math.max(1,t.maxEdgeLabelPredicates??3),o=bR(e),l=new Set;for(const w of o){const x=String(w.subject||"").trim(),S=String(w.object||"").trim();x&&l.add(x),S&&l.add(S)}const u=Array.from(l);u.sort((w,x)=>w.localeCompare(x));const c=ag(u),f=u.map(w=>({id:w,type:"default",data:{label:vR(w),kind:wR(w)},position:c[w]||{x:0,y:0}})),_=new Map,p=(w,x)=>{const S=String(w.subject||"").trim(),j=String(w.object||"").trim(),E=String(w.predicate||"").trim();return n?`edge:${S}:${j}`:`edge:${x}:${S}:${E}:${j}`};for(let w=0;w<o.length;w++){const x=o[w],S=p(x,w),j=_.get(S);j?j.push(x):_.set(S,[x])}const y=[];for(const[w,x]of _.entries()){const S=x[0],j=String(S.subject||"").trim(),E=String(S.object||"").trim();if(!j||!E)continue;const A=new Map;for(const Y of x){const Z=String(Y.predicate||"").trim();Z&&A.set(Z,(A.get(Z)||0)+1)}const L=Array.from(A.entries());L.sort((Y,Z)=>Z[1]-Y[1]||Y[0].localeCompare(Z[0]));const M=L.slice(0,i).map(([Y,Z])=>Z>1?`${Dm(Y)}×${Z}`:Dm(Y)).join(" | "),H=L.length>i?` +${L.length-i}`:"",X=`${M}${H}`.trim();y.push({id:w,source:j,target:E,label:X,animated:!1,data:{assertions:x,predicateSummary:X}})}return{nodes:f,edges:y}}function SR(e,t,n,i={}){const o=i.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,E,A)=>{const L=c.get(j);L?L.push({to:E,edgeId:A}):c.set(j,[{to:E,edgeId:A}])};for(const j of e.edges)f(j.source,j.target,j.id),o||f(j.target,j.source,j.id);const _=[l],p=new Map,y=new Map;for(p.set(l,null),y.set(l,null);_.length;){const j=_.shift(),E=c.get(j)||[];for(const A of E)if(!p.has(A.to)){if(p.set(A.to,j),y.set(A.to,A.edgeId),A.to===u){_.length=0;break}_.push(A.to)}}if(!p.has(u))return null;const w=[],x=[];let S=u;for(;S;){w.push(S);const j=y.get(S);j&&x.push(j),S=p.get(S)||null}return w.reverse(),x.reverse(),{nodeIds:w,edgeIds:x}}const ov={seed:1,dt:1,springLength:240,springStrength:.03,repulsionStrength:9e3,centeringStrength:.003,damping:.85,maxSpeed:90,maxRepulsionNodes:320};function rm(e,t={}){const n={...ov,...t,seed:typeof t.seed=="number"&&Number.isFinite(t.seed)?Math.trunc(t.seed):ov.seed},i=e.nodes.map(x=>x.id),o=i.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(i[x],x);const _=t.positions??Nu(e,{kind:"force",seed:n.seed}),p=k0(n.seed||1),y=Math.max(8,Math.min(38,Math.sqrt(o)*2.25));for(let x=0;x<o;x++){const S=i[x],j=_[S],E=typeof(j==null?void 0:j.x)=="number"&&Number.isFinite(j.x)?j.x:(p()-.5)*500,A=typeof(j==null?void 0:j.y)=="number"&&Number.isFinite(j.y)?j.y:(p()-.5)*500;l[2*x]=E+(p()-.5)*y,l[2*x+1]=A+(p()-.5)*y,u[2*x]=0,u[2*x+1]=0}const w=[];for(const x of e.edges){const S=f.get(String((x==null?void 0:x.source)||"").trim()),j=f.get(String((x==null?void 0:x.target)||"").trim());typeof S!="number"||typeof j!="number"||S===j||w.push(S,j)}return{nodeIds:i,pos:l,vel:u,acc:c,edges:new Uint32Array(w),options:n,tick:0}}function kR(e,t=1){const n=e.nodeIds.length;if(!n)return;const i=e.options,o=i.dt;for(let l=0;l<Math.max(1,Math.trunc(t));l++){if(e.acc.fill(0),n<=i.maxRepulsionNodes){const x=i.repulsionStrength;for(let S=0;S<n;S++){const j=e.pos[2*S],E=e.pos[2*S+1];for(let A=S+1;A<n;A++){const L=e.pos[2*A]-j,O=e.pos[2*A+1]-E,M=L*L+O*O+1e-6,H=1/Math.sqrt(M),X=x/M,Y=X*L*H,Z=X*O*H;e.acc[2*S]-=Y,e.acc[2*S+1]-=Z,e.acc[2*A]+=Y,e.acc[2*A+1]+=Z}}}const c=i.springLength,f=i.springStrength,_=e.edges;for(let x=0;x<_.length;x+=2){const S=_[x],j=_[x+1],E=e.pos[2*S],A=e.pos[2*S+1],L=e.pos[2*j],O=e.pos[2*j+1],M=L-E,H=O-A,X=M*M+H*H+1e-6,Y=Math.sqrt(X),Z=f*(Y-c),re=Z*M/Y,ie=Z*H/Y;e.acc[2*S]+=re,e.acc[2*S+1]+=ie,e.acc[2*j]-=re,e.acc[2*j+1]-=ie}const p=i.centeringStrength;for(let x=0;x<n;x++)e.acc[2*x]+=-p*e.pos[2*x],e.acc[2*x+1]+=-p*e.pos[2*x+1];const y=i.damping,w=i.maxSpeed;for(let x=0;x<n;x++){let S=(e.vel[2*x]+e.acc[2*x]*o)*y,j=(e.vel[2*x+1]+e.acc[2*x+1]*o)*y;const E=Math.sqrt(S*S+j*j);if(E>w){const A=w/E;S*=A,j*=A}e.vel[2*x]=S,e.vel[2*x+1]=j,e.pos[2*x]+=S*o,e.pos[2*x+1]+=j*o}e.tick+=1}}function NR(e){const t=e.nodeIds.length;if(!t)return 0;let n=0;for(let i=0;i<t;i++){const o=e.vel[2*i],l=e.vel[2*i+1];n+=Math.sqrt(o*o+l*l)}return n/t}function CR(e){const t={},n=e.nodeIds.length;for(let i=0;i<n;i++)t[e.nodeIds[i]]={x:e.pos[2*i],y:e.pos[2*i+1]};return t}function av(e,t="session"){const n=String(e??"").trim().toLowerCase();return n==="run"||n==="session"||n==="global"||n==="all"?n:t}function ER(){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 $R(){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 N0(e,t,n,i){const o=typeof e=="number"&&Number.isFinite(e)?e:i;return Math.min(n,Math.max(t,o))}function df(e){const t=N0(e,.6,2.4,1),n=240*t,i=9e3*t*t;return{springLength:n,repulsionStrength:i}}const Rf="abstractuic_amx_saved_layouts_v1",cg=.025,ug=6,C0=1e6;function Yg(){if(typeof window>"u")return null;try{return window.localStorage}catch{return null}}function dg(e,t="grid"){const n=String(e??"").trim().toLowerCase();return n==="grid"||n==="circle"||n==="radial"||n==="force"?n:t}function AR(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,i=typeof t.y=="number"&&Number.isFinite(t.y)?t.y:null;return n===null||i===null?null:{x:n,y:i}}function lv(e){const t=Yg();if(!t)return null;const n=String(e??"").trim();if(!n)return null;try{const i=t.getItem(Rf);if(!i)return null;const o=JSON.parse(i),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 _=dg(c.kind,"grid"),p=typeof c.seed=="number"&&Number.isFinite(c.seed)?Math.trunc(c.seed):lg(n),y=c.positions&&typeof c.positions=="object"&&!Array.isArray(c.positions)?c.positions:null,w={};if(y)for(const[j,E]of Object.entries(y)){const A=AR(E);A&&(w[String(j)]=A)}const x=S0(c.viewport,{minZoom:cg,maxZoom:ug,maxAbsTranslate:C0})??void 0,S=typeof c.saved_at=="string"&&c.saved_at.trim()?c.saved_at.trim():"";return{version:f,kind:_,seed:p,positions:w,viewport:x,saved_at:S}}catch{return null}}function TR(e,t){const n=Yg();if(!n)return;const i=String(e??"").trim();if(i)try{const o=n.getItem(Rf),l=o?JSON.parse(o):null,u=l&&typeof l=="object"&&!Array.isArray(l)?{...l}:{};u[i]=t,n.setItem(Rf,JSON.stringify(u))}catch{}}function MR(e){const t=Yg();if(!t)return;const n=String(e??"").trim();if(n)try{const i=t.getItem(Rf);if(!i)return;const o=JSON.parse(i),l=o&&typeof o=="object"&&!Array.isArray(o)?{...o}:null;if(!l||!(n in l))return;delete l[n],t.setItem(Rf,JSON.stringify(l))}catch{}}function RR(e){const t=String(e??"").trim();if(!t)return;const n=Number(t);if(Number.isFinite(n))return n}function dp(e,t){const n=!!(t!=null&&t.allowZero),i=!!(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(i&&u===-1)return-1;if(!(!n&&u<=0)&&!(n&&u<0))return u}function LR(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e,n=typeof t.recall_level=="string"?t.recall_level:"",i=t.applied&&typeof t.applied=="object"&&!Array.isArray(t.applied)?t.applied:null,o=[];return n&&o.push(`recall_level=${n}`),i&&(typeof i.limit=="number"&&o.push(`limit=${i.limit}`),typeof i.min_score=="number"&&o.push(`min_score=${i.min_score}`),typeof i.max_input_tokens=="number"&&o.push(`max_input_tokens=${i.max_input_tokens}`)),o.length?o.join(" · "):null}function IR(e){if(!e||typeof e!="object")return null;const t=[],n=typeof e.scope=="string"?e.scope.trim():"",i=typeof e.owner_id=="string"?e.owner_id.trim():"";n&&t.push(`scope=${n}`),i&&t.push(`owner_id=${i}`);const o=typeof e.confidence=="number"&&Number.isFinite(e.confidence)?e.confidence:null;o!==null&&t.push(`confidence=${o.toFixed(3)}`);const l=e.provenance&&typeof e.provenance=="object"&&!Array.isArray(e.provenance)?e.provenance:null;if(l){const _=typeof l.writer_run_id=="string"?l.writer_run_id.trim():"",p=typeof l.writer_workflow_id=="string"?l.writer_workflow_id.trim():"";_&&t.push(`writer_run_id=${_}`),p&&t.push(`writer_workflow_id=${p}`)}const u=e.attributes&&typeof e.attributes=="object"&&!Array.isArray(e.attributes)?e.attributes:null,c=u&&u._retrieval&&typeof u._retrieval=="object"&&!Array.isArray(u._retrieval)?u._retrieval:null,f=c&&typeof c.score=="number"&&Number.isFinite(c.score)?c.score:null;return f!==null&&t.push(`score=${f.toFixed(3)}`),t.length?t.join(" · "):null}function OR(e,t){const n=String(e??""),i=String(t??"").trim();if(!i)return n;const o=n.toLowerCase().indexOf(i.toLowerCase());if(o<0)return n;const l=n.slice(0,o),u=n.slice(o,o+i.length),c=n.slice(o+i.length);return s.jsxs(s.Fragment,{children:[l,s.jsx("span",{className:"amx-hl",children:u}),c]})}function ff(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 PR(e){const t=typeof e=="string"?e.trim():"";if(!t)return null;const n=t.replace(/(\.\d{3})\d+/,"$1"),i=Date.parse(n);return Number.isFinite(i)?i:null}function hf(e){const t=PR(e);if(t===null)return"";const n=new Date(t),i=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`${i}/${o}/${l} ${u}:${c}`}function E0(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 fp(e,t){const n=String(e??"").trim().toLowerCase();return!!(n&&t.has(n))}function DR(e,t={}){const n=Math.max(1,t.maxPredicates??3),i=new Map;for(const f of e){const _=String((f==null?void 0:f.predicate)||"").trim();_&&i.set(_,(i.get(_)||0)+1)}const o=Array.from(i.entries());o.sort((f,_)=>_[1]-f[1]||f[0].localeCompare(_[0]));const u=o.slice(0,n).map(([f,_])=>{const p=E0(f);return _>1?`${p}×${_}`:p}).join(" | "),c=o.length>n?` +${o.length-n}`:"";return`${u}${c}`.trim()}function FR({resetKey:e,queryMode:t,items:n,activeMemoryText:i,packets:o,packetsVersion:l,packedCount:u,dropped:c,estimatedTokens:f,effort:_,warnings:p,onQuery:y,onItemsReplace:w,onOpenSpan:x,onOpenTranscript:S}){var po;const j=m.useRef(null),E=m.useMemo(()=>{const U=n==null?void 0:n[0],ae=n==null?void 0:n[n.length-1],je=U?`${U.subject}|${U.predicate}|${U.object}`:"",Ne=ae?`${ae.subject}|${ae.predicate}|${ae.object}`:"";return`${(n==null?void 0:n.length)||0}:${je}:${Ne}`},[n]),A=String(e??E),L=t==="replace"?"replace":"override",[O,M]=m.useState(null),[H,X]=m.useState(null),[Y,Z]=m.useState(!1),[re,ie]=m.useState(""),[ue,F]=m.useState(!1),[C,N]=m.useState("");m.useEffect(()=>{M(null),X(null),ie(""),Z(!1),N(""),F(!1)},[A]);const[P,D]=m.useState(""),[ne,B]=m.useState(!0),[z,G]=m.useState(!1),[T,Q]=m.useState(!0),[K]=m.useState(()=>({compact:ER(),show:!1})),J=K.compact,[oe,fe]=m.useState(K.show),[_e,we]=m.useState(!1),Ae=A,Be=m.useMemo(()=>lg(Ae),[Ae]),[We,_t]=m.useState("grid"),[Pe,et]=m.useState(Be),[lt,Ye]=m.useState(!1),[Se,Le]=m.useState(1),ct=m.useRef(null),ge=m.useRef(null),De=m.useRef(!1),[Ke,Dt]=m.useState(0),tn=m.useRef(null),pn=m.useRef(0),Wt=m.useRef(0),It=m.useRef(0),dn=m.useRef(0),[Wn,Tt]=m.useState(!1),[bn,Fn]=m.useState(""),[An,jn]=m.useState({}),Ln=m.useRef({});m.useEffect(()=>{Ln.current=An},[An]);const[yn,Ns]=m.useState(""),[Gn,rs]=m.useState(""),Nr=m.useMemo(()=>{var ae;const U=(ae=n==null?void 0:n[0])==null?void 0:ae.scope;return av(U,"session")},[n]),[Kn,ce]=m.useState(Nr),[be,Ve]=m.useState("standard"),[He,st]=m.useState(""),[ut,At]=m.useState(""),[kt,Vt]=m.useState(""),[dt,Xt]=m.useState(""),[Ut,Ct]=m.useState(""),[pt,Ot]=m.useState(""),[Ee,Ht]=m.useState(""),[Et,an]=m.useState("qwen/qwen3-next-80b");m.useEffect(()=>{ce(Nr)},[A]);const $t=Array.isArray(n)?n:[],is=typeof i=="string"?i:"",os=Array.isArray(o)?o:[],Js=typeof l=="number"?l:void 0,Cs=typeof u=="number"?u:void 0,hr=typeof c=="number"?c:void 0,Xs=typeof f=="number"?f:void 0,lo=_,xe=p,Yn=L==="override"&&(O!=null&&O.items)&&Array.isArray(O.items)?O.items:$t,mn=typeof(O==null?void 0:O.active_memory_text)=="string"&&O.active_memory_text.trim()?O.active_memory_text:is,co=(O==null?void 0:O.effort)??lo,Ei=(O==null?void 0:O.warnings)??xe,Cr=m.useMemo(()=>new Set(["rdf:type","schema:name","skos:preflabel","skos:altlabel","dcterms:title","dcterms:identifier"]),[]),mr=m.useMemo(()=>T?Yn:(Yn||[]).filter(U=>!fp(U==null?void 0:U.predicate,Cr)),[Yn,T,Cr]),Jr=m.useMemo(()=>jR(Yn,{groupEdges:ne}),[Yn,ne]),ot=m.useMemo(()=>{if(T)return Jr;const U=[];for(const ae of Jr.edges){const Ne=(ae&&ae.data&&Array.isArray(ae.data.assertions)?ae.data.assertions:[]).filter(Ue=>!fp(Ue==null?void 0:Ue.predicate,Cr));if(!Ne.length)continue;const ke=DR(Ne);U.push({...ae,label:ke,data:{...ae.data,assertions:Ne,predicateSummary:ke}})}return{nodes:Jr.nodes,edges:U}},[Jr,T,Cr]),sn=m.useMemo(()=>ot.nodes.map(U=>U.id),[ot.nodes]),ms=m.useMemo(()=>{const U=sn[0]||"",ae=sn[sn.length-1]||"";return`${sn.length}:${U}:${ae}`},[sn]),ai=m.useMemo(()=>{var ae;const U=new Map;for(const je of ot.nodes)U.set(je.id,String(((ae=je.data)==null?void 0:ae.label)||je.id));return U},[ot.nodes]),as=m.useMemo(()=>{var ae;const U=new Map;for(const je of ot.nodes)U.set(je.id,String(((ae=je.data)==null?void 0:ae.kind)||""));return U},[ot.nodes]),uo=P.trim().toLowerCase(),fo=m.useMemo(()=>{var ae;if(!uo)return new Set;const U=new Set;for(const je of ot.nodes){const Ne=String(je.id||"").toLowerCase(),ke=String(((ae=je.data)==null?void 0:ae.label)||"").toLowerCase();(Ne.includes(uo)||ke.includes(uo))&&U.add(je.id)}return U},[ot.nodes,uo]),Aa=m.useCallback((U,ae)=>{const je={};for(const Ne of sn){const ke=U[Ne]||ae[Ne];je[Ne]=ke?{x:ke.x,y:ke.y}:{x:0,y:0}}return je},[sn]);m.useEffect(()=>{jn(U=>{const ae=Nu(ot,{kind:We,seed:Pe}),je={};for(const Ne of sn){const ke=U[Ne]||ae[Ne];je[Ne]=ke?{x:ke.x,y:ke.y}:{x:0,y:0}}return je})},[ot,We,Pe,sn,ms]),m.useEffect(()=>{if(!De.current)return;const U=j.current;if(!(!U||typeof U.fitView!="function")&&sn.length){De.current=!1;try{U.fitView({padding:.2,duration:0})}catch{try{U.fitView({padding:.2})}catch{}}}},[sn.length,ms,An]),m.useEffect(()=>{Ye(!1),ct.current=null,ge.current=null,De.current=!1,pn.current=0,Wt.current=0,It.current=0;const U=lv(Ae);if(U&&Object.keys(U.positions||{}).length){if(_t(U.kind),et(U.seed),Tt(!0),Fn(U.saved_at||""),U.viewport){ge.current=U.viewport;const ke=j.current;if(ke&&typeof ke.setViewport=="function"){try{ke.setViewport(U.viewport,{duration:0})}catch{try{ke.setViewport(U.viewport)}catch{}}ge.current=null}}else De.current=!0;const Ne=Nu(ot,{kind:U.kind,seed:U.seed});jn(Aa(U.positions,Ne));return}Tt(!1),Fn("");const ae=lg(Ae);et(ae);const je=Nu(ot,{kind:We,seed:ae});jn(je),We==="force"&&ot.nodes.length>0&&ot.nodes.length<=320&&(ct.current=rm(ot,{seed:ae,positions:je,...df(Se)}),Ye(!0))},[Ae]);const zn=m.useMemo(()=>{const U=String(yn||"").trim(),ae=String(Gn||"").trim();return!U||!ae?null:SR(ot,U,ae,{directed:z})},[ot,yn,Gn,z]),_r=!!(zn&&String(yn||"").trim()&&String(Gn||"").trim()),Tn=m.useMemo(()=>{const U=String(yn||"").trim(),ae=String(Gn||"").trim();if(!U||!ae)return null;const je=z,Ne=new Map,ke=(at,gt)=>{const Ft=Ne.get(at);Ft?Ft.push(gt):Ne.set(at,[gt])};for(const at of ot.edges)ke(at.source,at.target),je||ke(at.target,at.source);const Ue=new Set,ft=[];for(Ue.add(U),ft.push(U);ft.length;){const at=ft.shift(),gt=Ne.get(at)||[];for(const Ft of gt)Ue.has(Ft)||(Ue.add(Ft),ft.push(Ft))}return{reachableFromStart:Ue.size,endReachable:Ue.has(ae),nodes:ot.nodes.length,edges:ot.edges.length,assertions:mr.length}},[z,ot.edges,ot.nodes.length,Gn,yn,mr.length]),pr=m.useMemo(()=>new Set((zn==null?void 0:zn.nodeIds)||[]),[zn]),ho=m.useMemo(()=>new Set((zn==null?void 0:zn.edgeIds)||[]),[zn]),[Xn,Zs]=m.useState(""),[ls,Xr]=m.useState(""),_s=!!(String(Xn||"").trim()||String(ls||"").trim()),Ta=m.useMemo(()=>{const U=new Set,ae=new Set,je=String(Xn||"").trim(),Ne=String(ls||"").trim();if(je){U.add(je);for(const ke of ot.edges)(ke.source===je||ke.target===je)&&(ae.add(ke.id),U.add(ke.source),U.add(ke.target));return{nodes:U,edges:ae}}if(Ne){const ke=ot.edges.find(Ue=>Ue.id===Ne);ke&&(ae.add(ke.id),U.add(ke.source),U.add(ke.target))}return{nodes:U,edges:ae}},[ot.edges,ls,Xn]);m.useEffect(()=>{Zs(""),Xr(""),Ns(""),rs("")},[A]);const[mo,rn]=m.useState(!1);m.useEffect(()=>{rn(!1)},[A]),m.useEffect(()=>{lt||(ct.current=null)},[lt]),m.useEffect(()=>{if(We!=="force")return;const U=ct.current;if(!U)return;const ae=df(Se);U.options.springLength=ae.springLength,U.options.repulsionStrength=ae.repulsionStrength},[We,Se]),m.useEffect(()=>{We!=="force"&<&&Ye(!1)},[We,lt]),m.useEffect(()=>{if(!lt||We!=="force"||ot.nodes.length===0||typeof window>"u"||typeof window.requestAnimationFrame!="function")return;ct.current||(ct.current=rm(ot,{seed:Pe,positions:Ln.current,...df(Se)}));let U=0,ae=0,je=0;const Ne=ot.nodes.length<=140?2:1,ke=1600,Ue=.08,ft=at=>{if(U=window.requestAnimationFrame(ft),at-ae<33)return;ae=at;const gt=ct.current;if(!gt){Ye(!1);return}kR(gt,Ne),je+=Ne,jn(CR(gt)),(NR(gt)<=Ue||je>=ke)&&Ye(!1)};return U=window.requestAnimationFrame(ft),()=>{window.cancelAnimationFrame(U)}},[ot,We,lt,Pe]);const yl=m.useMemo(()=>ot.nodes.map(U=>{var on;const ae=pr.has(U.id),je=fo.has(U.id),Ne=Xn===U.id,ke=_s&&Ta.nodes.has(U.id),Ue=ff((on=U.data)==null?void 0:on.kind),ft="rgba(34, 211, 238, 0.88)",at=je?"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)":"",gt=ae?"rgba(168, 85, 247, 0.9)":je?ft:Ue.stroke,Ft=Ne?"0 0 0 2px rgba(255,255,255,0.20), 0 18px 46px rgba(0,0,0,0.55)":ke?"0 0 0 1px rgba(96, 165, 250, 0.28), 0 12px 34px rgba(0,0,0,0.45)":void 0,Gt=at&&Ft?`${at}, ${Ft}`:Ft||at||void 0,gs=ae?"rgba(168, 85, 247, 0.10)":je?"rgba(34, 211, 238, 0.08)":Ue.bg,Mt=_r?ae||Ne?1:.16:_s?ke||Ne?1:.1:1;return{...U,position:An[U.id]?{x:An[U.id].x,y:An[U.id].y}:U.position,style:{...U.style||{},border:`1px solid ${gt}`,borderRadius:10,background:gs,color:"rgba(255,255,255,0.92)",opacity:Mt,padding:8,fontSize:12,boxShadow:Gt,width:180,cursor:"pointer"}}}),[ot.nodes,_r,fo,An,Xn,pr,_s,Ta.nodes]),$i=m.useMemo(()=>ot.edges.map(U=>{const ae=ho.has(U.id),je=ls===U.id,Ne=_s&&Ta.edges.has(U.id),ke=ae?"rgba(168, 85, 247, 0.9)":_s?Ne||je?"rgba(96, 165, 250, 0.55)":"rgba(255,255,255,0.14)":"rgba(255,255,255,0.18)",Ue=ae?2.75:_s?Ne||je?2.25:1.25:1.5,ft=je?"drop-shadow(0 0 10px rgba(168, 85, 247, 0.25))":void 0,at=ae?"rgba(168, 85, 247, 0.9)":_r?"rgba(255,255,255,0.10)":"rgba(255,255,255,0.28)",gt=_r?ae||je?1:.1:_s?Ne||je?1:.08:1,Ft=_r?ae||je?1:0:_s?Ne||je?1:0:1,Gt=_r?ae||je?String(U.label||""):"":String(U.label||"");return{...U,label:Gt,style:{...U.style||{},stroke:ke,strokeWidth:Ue,filter:ft,opacity:gt},animated:!1,markerEnd:{type:Tf.ArrowClosed,color:at,width:20,height:20},labelShowBg:!0,labelBgPadding:[6,3],labelBgBorderRadius:10,labelBgStyle:{fill:`rgba(0, 0, 0, ${.38*Ft})`,stroke:`rgba(255, 255, 255, ${.14*Ft})`,strokeWidth:1},labelStyle:{fill:`rgba(255, 255, 255, ${.92*Ft})`,fontSize:10,fontWeight:600,letterSpacing:.2,textTransform:"lowercase"}}}),[ot.edges,_r,ls,ho,_s,Ta.edges]),gr=m.useMemo(()=>{if(!ls)return[];const U=ot.edges.find(je=>je.id===ls),ae=U&&U.data&&Array.isArray(U.data.assertions)?U.data.assertions:[];return Array.isArray(ae)?ae:[]},[ot.edges,ls]),Es=m.useMemo(()=>ls&&ot.edges.find(U=>U.id===ls)||null,[ot.edges,ls]),Ma=m.useMemo(()=>{const U=String(Xn||"").trim();return U?Yn.filter(ae=>!ae||typeof ae!="object"||!(ae.subject===U||ae.object===U)?!1:T?!0:!fp(ae.predicate,Cr)):[]},[Yn,Xn,T,Cr]),Er=m.useMemo(()=>ls?gr:Ma,[gr,ls,Ma]),li=m.useMemo(()=>{const U=new Map;for(const ae of Er){if(!ae||typeof ae!="object")continue;const je=ae.provenance&&typeof ae.provenance=="object"&&!Array.isArray(ae.provenance)?ae.provenance:null,Ne=je&&typeof je.span_id=="string"?je.span_id.trim():"",ke=je&&typeof je.writer_run_id=="string"?je.writer_run_id.trim():"",Ue=typeof ae.owner_id=="string"?ae.owner_id.trim():"",ft=ke||Ue;if(!ft||!Ne)continue;const at=`${ft}|${Ne}`,gt=U.get(at),Ft=typeof ae.observed_at=="string"?ae.observed_at.trim():"";gt?(gt.count+=1,Ft&&(!gt.last_observed_at||Ft>gt.last_observed_at)&&(gt.last_observed_at=Ft,gt.last_observed_at_fmt=hf(Ft),gt.assertion=ae)):U.set(at,{span_run_id:ft,span_id:Ne,writer_run_id:ke,count:1,last_observed_at:Ft,last_observed_at_fmt:hf(Ft),assertion:ae})}return Array.from(U.values()).sort((ae,je)=>String(je.last_observed_at||"").localeCompare(String(ae.last_observed_at||"")))},[Er]),Ai=m.useMemo(()=>{const U=new Map;for(const ae of Er){if(!ae||typeof ae!="object")continue;const je=ae.provenance&&typeof ae.provenance=="object"&&!Array.isArray(ae.provenance)?ae.provenance:null,Ne=je&&typeof je.span_id=="string"?je.span_id.trim():"",ke=je&&typeof je.writer_run_id=="string"?je.writer_run_id.trim():"";if(!ke||Ne)continue;const Ue=U.get(ke),ft=typeof ae.observed_at=="string"?ae.observed_at.trim():"";Ue?(Ue.count+=1,ft&&(!Ue.last_observed_at||ft>Ue.last_observed_at)&&(Ue.last_observed_at=ft,Ue.last_observed_at_fmt=hf(ft),Ue.assertion=ae)):U.set(ke,{run_id:ke,count:1,last_observed_at:ft,last_observed_at_fmt:hf(ft),assertion:ae})}return Array.from(U.values()).sort((ae,je)=>String(je.last_observed_at||"").localeCompare(String(ae.last_observed_at||"")))},[Er]),Qs=m.useCallback(U=>{const ae=String(U.run_id||"").trim(),je=typeof U.span_id=="string"?String(U.span_id).trim():"";if(ae){if(S){try{S({run_id:ae,span_id:je||void 0,assertion:U.assertion})}catch{}return}if(x&&je)try{x({run_id:ae,span_id:je,assertion:U.assertion})}catch{}}},[x,S]),$s=m.useCallback(async U=>{const ae=String(U??"");if(ae)try{await navigator.clipboard.writeText(ae)}catch{}},[]),$r=m.useCallback(()=>{const U=j.current;if(!(!U||typeof U.fitView!="function")){if(Xn&&typeof U.getNode=="function"){const ae=U.getNode(Xn);if(ae){U.fitView({nodes:[ae],padding:.55,duration:350});return}}U.fitView({padding:.2,duration:350})}},[Xn]),er=m.useCallback(U=>{const ae=U.kind,je=Math.trunc(U.seed);Ye(!1),ct.current=null,ge.current=null,_t(ae),et(je);const Ne=Nu(ot,{kind:ae,seed:je});jn(Ne),ae==="force"&&(U.autoPlay??!0)&&ot.nodes.length>0&&ot.nodes.length<=320&&(ct.current=rm(ot,{seed:je,positions:Ne,...df(Se)}),Ye(!0))},[ot,Se]),Ti=m.useCallback(()=>{if(We==="force"){if(lt){Ye(!1);return}ct.current=rm(ot,{seed:Pe,positions:Ln.current,...df(Se)}),Ye(!0)}},[ot,We,lt,Pe,Se]);m.useEffect(()=>()=>{typeof window>"u"||typeof window.cancelAnimationFrame=="function"&&dn.current&&window.cancelAnimationFrame(dn.current)},[]);const yr=m.useCallback(()=>{const U=j.current;if(!U||typeof U.getViewport!="function"||!sn.length)return null;const ae=tn.current;if(!ae)return null;const je=ae.getBoundingClientRect();if(!Number.isFinite(je.width)||!Number.isFinite(je.height)||je.width<64||je.height<64)return null;const Ne=U.getViewport(),ke=typeof(Ne==null?void 0:Ne.zoom)=="number"&&Number.isFinite(Ne.zoom)?Ne.zoom:null,Ue=typeof(Ne==null?void 0:Ne.x)=="number"&&Number.isFinite(Ne.x)?Ne.x:null,ft=typeof(Ne==null?void 0:Ne.y)=="number"&&Number.isFinite(Ne.y)?Ne.y:null;if(ke===null||Ue===null||ft===null||ke<=0)return null;const at=140,gt=Math.min(sn.length,180),Ft=Ln.current;let Gt=0,gs=0;for(const Mt of sn){const on=Ft[Mt];if(!on||!Number.isFinite(on.x)||!Number.isFinite(on.y))continue;gs+=1;const En=[{x:on.x,y:on.y},{x:on.x+90,y:on.y+24}];for(const _n of En){const Zn=_n.x*ke+Ue,nr=_n.y*ke+ft;if(Zn>-at&&Zn<je.width+at&&nr>-at&&nr<je.height+at)return!1}if(Gt++,Gt>=gt)break}return gs?!0:null},[sn]),ps=m.useCallback(U=>{typeof window>"u"||typeof window.requestAnimationFrame!="function"||dn.current||(dn.current=window.requestAnimationFrame(()=>{dn.current=0;const ae=yr();if(ae===null){if(It.current>=12)return;It.current+=1,window.setTimeout(()=>ps(`${U}:probe`),120);return}if(ae!==!0){It.current=0,Wt.current=0;return}It.current=0;const je=j.current;if(je&&typeof je.fitView=="function")try{je.fitView({padding:.2,duration:0})}catch{try{je.fitView({padding:.2})}catch{}}if(Wt.current+=1,Wt.current>=4&&pn.current<1){Wt.current=0,pn.current+=1,Dt(Ne=>Ne+1);return}Wt.current<8&&window.setTimeout(()=>ps(`${U}:retry`),220)}))},[yr]);m.useEffect(()=>{Wt.current=0,pn.current=0,It.current=0,ps("mount")},[A,ps]),m.useEffect(()=>{ps("graph change")},[ms,ps]),m.useEffect(()=>{const U=tn.current;if(!U||typeof window>"u"||typeof ResizeObserver!="function")return;const ae=new ResizeObserver(()=>ps("resize"));return ae.observe(U),()=>ae.disconnect()},[ps]);const Mi=m.useCallback(()=>{const U=new Date().toISOString(),ae={};for(const ft of sn){const at=Ln.current[ft];at&&typeof at.x=="number"&&typeof at.y=="number"&&(ae[ft]={x:at.x,y:at.y})}const je=j.current,Ne=je&&typeof je.toObject=="function"?je.toObject():null,ke=Ne&&Ne.viewport?Ne.viewport:je&&typeof je.getViewport=="function"?je.getViewport():null,Ue=S0(ke,{minZoom:cg,maxZoom:ug,maxAbsTranslate:C0})??void 0;TR(Ae,{version:1,kind:We,seed:Pe,positions:ae,viewport:Ue,saved_at:U}),Tt(!0),Fn(U),Ye(!1)},[Ae,We,Pe,sn]),qo=m.useCallback(()=>{const U=lv(Ae);if(!U)return;Ye(!1),ct.current=null,_t(U.kind),et(U.seed),Tt(!0),Fn(U.saved_at||""),ge.current=U.viewport||null,De.current=!U.viewport;const ae=Nu(ot,{kind:U.kind,seed:U.seed});if(jn(Aa(U.positions,ae)),U.viewport){const je=j.current;if(je&&typeof je.setViewport=="function"){try{je.setViewport(U.viewport,{duration:0})}catch{try{je.setViewport(U.viewport)}catch{}}ge.current=null}}},[Aa,ot,Ae]),wl=m.useCallback(()=>{MR(Ae),Tt(!1),Fn("")},[Ae]),tr=m.useCallback(U=>{if(!Array.isArray(U)||U.length===0)return;let ae=!1;jn(je=>{let Ne=je,ke=!1;for(const Ue of U){const ft=Ue&&typeof Ue=="object"&&"id"in Ue&&typeof Ue.id=="string"?String(Ue.id):"",at=(Ue==null?void 0:Ue.type)==="position"?Ue==null?void 0:Ue.position:null;ft&&at&&typeof at.x=="number"&&typeof at.y=="number"&&(ke||(Ne={...je},ke=!0),Ne[ft]={x:at.x,y:at.y},Ue!=null&&Ue.dragging&&(ae=!0))}return ke?Ne:je}),ae&<&&Ye(!1)},[lt]),Ho=m.useMemo(()=>{const U=new Map;for(const ae of ot.edges)U.set(ae.id,ae);return U},[ot.edges]),Zr=m.useMemo(()=>{var Ne;if(!zn)return[];const U=zn.nodeIds||[],ae=zn.edgeIds||[],je=[];for(let ke=0;ke<Math.min(U.length-1,ae.length);ke++){const Ue=U[ke],ft=U[ke+1],at=ae[ke],gt=Ho.get(at),Ft=String(((Ne=gt==null?void 0:gt.data)==null?void 0:Ne.predicateSummary)||(gt==null?void 0:gt.label)||"").trim(),Gt=gt&>.source===Ue&>.target===ft?"forward":gt&>.source===ft&>.target===Ue?"reverse":"unknown";je.push({from:Ue,to:ft,edgeId:at,predicate:Ft,dir:Gt})}return je},[Ho,zn]),cc=m.useCallback(async()=>{if(y){ie(""),N(""),Z(!0);try{const U=RR(Ut),ae=dp(pt,{allowZero:!0,allowNegativeOne:!0}),je=dp(Ee,{allowZero:!0}),Ne=await y({scope:Kn,owner_id:void 0,recall_level:be,query_text:He||void 0,subject:ut||void 0,predicate:kt||void 0,object:dt||void 0,min_score:U,limit:ae,max_input_tokens:je,model:Et||void 0});M(Ne),X("live query"),L==="replace"&&w&&Ne&&Array.isArray(Ne.items)&&w(Ne.items,{kind:"live query",result:Ne})}catch(U){const ae=U instanceof Error?U.message:String(U);ie(ae||"Query failed")}finally{Z(!1)}}},[pt,Ee,Ut,Et,dt,w,y,kt,L,He,be,Kn,ut]),wr=m.useCallback(async()=>{if(!y)return;const U=String(yn||"").trim(),ae=String(Gn||"").trim();if(!U||!ae)return;const je=Math.max(200,dp(pt)??80),Ne=60;N(""),ie(""),F(!0);try{const ke=[],Ue=new Set,ft=Mt=>{if(!Mt||typeof Mt!="object"||typeof Mt.subject!="string"||typeof Mt.predicate!="string"||typeof Mt.object!="string")return;const on=`${Mt.subject}|${Mt.predicate}|${Mt.object}|${String(Mt.observed_at||"")}|${String(Mt.scope||"")}|${String(Mt.owner_id||"")}`;Ue.has(on)||(Ue.add(on),ke.push(Mt))};for(const Mt of Yn)ft(Mt);const at=z,gt=new Set,Ft=[U],Gt=new Set([U]),gs=async Mt=>{const on=await y({scope:Kn,recall_level:be,min_score:0,limit:je,subject:Mt,query_text:void 0,max_input_tokens:0,model:void 0});if(on&&Array.isArray(on.items)){for(const En of on.items)if(ft(En),typeof En.subject=="string"&&En.subject.trim()===Mt&&typeof En.object=="string"){const _n=En.object.trim();_n&&!Gt.has(_n)&&(Gt.add(_n),Ft.push(_n))}}if(!at){const En=await y({scope:Kn,recall_level:be,min_score:0,limit:je,object:Mt,query_text:void 0,max_input_tokens:0,model:void 0});if(En&&Array.isArray(En.items)){for(const _n of En.items)if(ft(_n),typeof _n.object=="string"&&_n.object.trim()===Mt&&typeof _n.subject=="string"){const Zn=_n.subject.trim();Zn&&!Gt.has(Zn)&&(Gt.add(Zn),Ft.push(Zn))}}}};for(;Ft.length&>.size<Ne&&!Gt.has(ae);){const Mt=Ft.shift();!Mt||gt.has(Mt)||(gt.add(Mt),await gs(Mt))}M({ok:!0,count:ke.length,items:ke,active_memory_text:mn,raw:{expanded_for_path:!0,expanded_nodes:gt.size,discovered_nodes:Gt.size,merged:ke.length,directed:at}}),X("expanded neighborhood"),L==="replace"&&w&&w(ke,{kind:"expanded neighborhood",result:{ok:!0,count:ke.length,items:ke,active_memory_text:mn,raw:{expanded_for_path:!0,expanded_nodes:gt.size,discovered_nodes:Gt.size,merged:ke.length,directed:at}}})}catch(ke){const Ue=ke instanceof Error?ke.message:String(ke);N(Ue||"Expand neighborhood failed")}finally{F(!1)}},[z,mn,Yn,pt,w,y,Gn,yn,L,be,Kn]),_o=m.useCallback(()=>{M(null),X(null),ie(""),Z(!1),N(""),F(!1),Ns(""),rs(""),Zs(""),Xr("")},[]),Ws="Search KG",Vo=ot.nodes.length,Go=ot.edges.length,Ko=mr.length;return 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:U=>_t(dg(U.target.value,We)),disabled:!sn.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:Se,onChange:U=>Le(N0(Number(U.target.value),.7,2.2,1))}),s.jsxs("span",{className:"amx-small",children:[Se.toFixed(1),"×"]})]}):null,s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>er({kind:We,seed:Pe}),disabled:!sn.length,children:"Apply"}),s.jsx("button",{type:"button",className:"amx-btn",onClick:Ti,disabled:!sn.length||We!=="force",children:lt?"Pause simulation":"Play simulation"})]})}),s.jsxs("div",{className:"amx-graph","aria-label":"Knowledge graph",ref:tn,children:[s.jsx(Kg,{children:s.jsxs(w0,{nodes:yl,edges:$i,defaultViewport:{x:0,y:0,zoom:1},minZoom:cg,maxZoom:ug,onInit:U=>{j.current=U;const ae=ge.current;if(ae&&typeof U.setViewport=="function")try{U.setViewport(ae,{duration:0})}catch{try{U.setViewport(ae)}catch{}}if(De.current&&typeof U.fitView=="function")try{U.fitView({padding:.2,duration:0})}catch{try{U.fitView({padding:.2})}catch{}}ge.current=null,De.current=!1,ps("init")},nodesDraggable:!0,nodesConnectable:!1,elementsSelectable:!0,onNodesChange:tr,onNodeClick:(U,ae)=>{Xr(""),Zs(ae.id)},onEdgeClick:(U,ae)=>{Zs(""),Xr(ae.id)},onPaneClick:()=>{Zs(""),Xr("")},children:[s.jsx(fR,{className:"amx-flow-controls",children:s.jsx(Au,{type:"button",className:`amx-control-legend ${_e?"amx-control-legend-active":""}`,onClick:()=>we(U=>!U),title:_e?"Hide node color legend":"Show node color legend","aria-label":_e?"Hide node color legend":"Show node color legend",children:s.jsx($R,{})})}),s.jsx(Ef,{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:()=>fe(U=>!U),title:oe?"Hide minimap preview":"Show minimap preview","aria-label":oe?"Hide minimap preview":"Show minimap preview",children:oe?"minimap on":"minimap off"})})}),oe?s.jsx(iR,{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:J?120:160,height:J?80:110,marginBottom:56},nodeColor:U=>{var ae;return ff((ae=U.data)==null?void 0:ae.kind).minimap}}):null,_e?s.jsxs(Ef,{position:"bottom-left",className:"amx-legend-panel",children:[s.jsx("div",{className:"amx-legend-title",children:"node colors"}),s.jsx("div",{className:"amx-legend",children:[{k:"person",label:"person"},{k:"org",label:"org"},{k:"concept",label:"concept"},{k:"claim",label:"claim"},{k:"event",label:"event"},{k:"doc",label:"doc"},{k:"vocab",label:"vocab"}].map(({k:U,label:ae})=>s.jsx("span",{className:"amx-legend-item",style:{borderColor:ff(U).stroke},children:ae},U))})]}):null,s.jsx(yR,{gap:20,size:1,color:"rgba(255,255,255,0.06)"})]})},Ke),s.jsxs("details",{className:"amx-panel amx-controls",children:[s.jsxs("summary",{children:[s.jsx("span",{className:"amx-controls-title",children:Ws}),s.jsxs("span",{className:"amx-small",children:[Ko," assertions · ",Vo," nodes · ",Go," 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:P,onChange:U=>D(U.target.value),placeholder:"filter nodes by id/label"})]}),s.jsxs("label",{children:["group edges",s.jsxs("select",{value:String(ne),onChange:U=>B(U.target.value==="true"),children:[s.jsx("option",{value:"true",children:"group (subject→object)"}),s.jsx("option",{value:"false",children:"no grouping"})]})]}),s.jsxs("label",{children:["view",s.jsxs("select",{value:String(T),onChange:U=>Q(U.target.value==="true"),children:[s.jsx("option",{value:"true",children:"all assertions"}),s.jsx("option",{value:"false",children:"hide rdf:type / labels"})]})]}),s.jsxs("label",{children:["path mode",s.jsxs("select",{value:String(z),onChange:U=>G(U.target.value==="true"),children:[s.jsx("option",{value:"false",children:"undirected"}),s.jsx("option",{value:"true",children:"directed"})]})]})]}),s.jsxs("details",{className:"amx-details",children:[s.jsx("summary",{children:"layout"}),s.jsxs("div",{className:"amx-toolbar-grid",style:{marginTop:10},children:[s.jsxs("label",{children:["layout",s.jsxs("select",{value:We,onChange:U=>_t(dg(U.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:Pe,onChange:U=>et(Math.trunc(Number(U.target.value||0)||0))})]})]}),s.jsxs("div",{className:"amx-actions",style:{marginTop:10},children:[s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>er({kind:We,seed:Pe}),disabled:!sn.length,children:"Apply layout"}),We==="force"?s.jsx("button",{type:"button",className:"amx-btn",onClick:Ti,disabled:!sn.length,children:lt?"Pause simulation":"Play simulation"}):null,s.jsx("button",{type:"button",className:"amx-btn",onClick:Mi,disabled:!sn.length,children:"Save layout"}),Wn?s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"amx-btn",onClick:qo,children:"Load saved"}),s.jsx("button",{type:"button",className:"amx-btn",onClick:wl,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.",Wn?s.jsxs("span",{children:[" ","(saved",bn?`: ${bn}`:"",")"]}):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:yn,onChange:U=>Ns(U.target.value),children:[s.jsx("option",{value:"",children:"(none)"}),sn.map(U=>s.jsx("option",{value:U,children:(()=>{const ae=ai.get(U)||U;return ae===U?ae:`${ae} (${U})`})()},U))]})]}),s.jsxs("label",{children:["path end",s.jsxs("select",{value:Gn,onChange:U=>rs(U.target.value),children:[s.jsx("option",{value:"",children:"(none)"}),sn.map(U=>s.jsx("option",{value:U,children:(()=>{const ae=ai.get(U)||U;return ae===U?ae:`${ae} (${U})`})()},U))]})]})]}),zn?s.jsx("div",{className:"amx-small",style:{marginTop:10},children:Zr.map((U,ae)=>{const je=ai.get(U.from)||U.from,Ne=ai.get(U.to)||U.to,ke=U.dir==="reverse"?" ← ":" → ",Ue=U.predicate?` (${U.predicate})`:"";return s.jsxs("div",{children:[ae===0?s.jsx("span",{children:je}):null,ke,s.jsxs("span",{children:[Ne,Ue]})]},`${U.edgeId}:${ae}`)})}):yn&&Gn?s.jsxs("div",{className:"amx-small",style:{marginTop:10,opacity:.9},children:["No path found in the current subgraph (",(Tn==null?void 0:Tn.assertions)??Ko," assertions · ",(Tn==null?void 0:Tn.nodes)??ot.nodes.length," nodes ·"," ",(Tn==null?void 0:Tn.edges)??ot.edges.length," edges). Start reaches ",(Tn==null?void 0:Tn.reachableFromStart)??0," nodes.",y?s.jsx("div",{style:{marginTop:10},children:s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>void wr(),disabled:ue,children:ue?"Expanding…":"Expand neighborhood"})}):null]}):s.jsx("div",{className:"amx-small",style:{marginTop:10},children:"(no path)"})]}),s.jsxs("details",{className:"amx-details",children:[s.jsx("summary",{children:"query"}),s.jsxs("div",{className:"amx-toolbar-grid",style:{marginTop:10},children:[s.jsxs("label",{children:["query_text (semantic)",s.jsx("input",{value:He,onChange:U=>st(U.target.value),placeholder:"e.g. emotion chip"})]}),s.jsxs("label",{children:["subject (exact)",s.jsx("input",{value:ut,onChange:U=>At(U.target.value),placeholder:"e.g. ex:person-data"})]}),s.jsxs("label",{children:["predicate (exact)",s.jsx("input",{value:kt,onChange:U=>Vt(U.target.value),placeholder:"e.g. schema:about"})]}),s.jsxs("label",{children:["object (exact)",s.jsx("input",{value:dt,onChange:U=>Xt(U.target.value),placeholder:"e.g. ex:concept-emotion-chip"})]}),s.jsxs("label",{children:["min_score",s.jsx("input",{type:"number",step:"any",value:Ut,onChange:U=>Ct(U.target.value),placeholder:"(auto)"})]}),s.jsxs("label",{children:["limit",s.jsx("input",{type:"number",min:"-1",step:"1",value:pt,onChange:U=>Ot(U.target.value),placeholder:"0/-1 = unlimited (if supported)"})]})]})]}),s.jsxs("details",{className:"amx-details",children:[s.jsx("summary",{children:"advanced"}),s.jsxs("div",{className:"amx-toolbar-grid",style:{marginTop:10},children:[s.jsxs("label",{children:["scope",s.jsxs("select",{value:Kn,onChange:U=>ce(av(U.target.value,Kn)),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:be,onChange:U=>Ve(U.target.value||"standard"),children:[s.jsx("option",{value:"urgent",children:"urgent"}),s.jsx("option",{value:"standard",children:"standard"}),s.jsx("option",{value:"deep",children:"deep"})]})]}),s.jsxs("label",{children:["max_input_tokens",s.jsx("input",{type:"number",min:"0",step:"1",value:Ee,onChange:U=>Ht(U.target.value),placeholder:"(auto)"})]}),s.jsxs("label",{children:["model (budgeting)",s.jsx("input",{value:Et,onChange:U=>an(U.target.value),placeholder:"qwen/qwen3-next-80b"})]})]})]}),s.jsxs("div",{className:"amx-actions",children:[s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>void cc(),disabled:!y||Y,children:Y?"Querying…":"Query store"}),s.jsx("button",{type:"button",className:"amx-btn",onClick:_o,disabled:!O&&!re&&!Y,children:"Reset to step output"}),O?s.jsxs("span",{className:"amx-small",children:["showing: ",H||"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,C?s.jsx("span",{className:"amx-small",style:{color:"var(--error, rgba(255, 80, 80, 0.95))"},children:C}):null]})]})]})]})]}),s.jsxs("div",{className:"amx-right",children:[s.jsxs("div",{className:"amx-panel",children:[s.jsx("h3",{children:"Details"}),s.jsx("div",{className:"amx-small",style:{marginBottom:8},children:"Derived from `memory_kg_query` packetization (max_input_tokens); safe to inject into an LLM system prompt."}),(()=>{const U=LR(co);return U?s.jsx("div",{className:"amx-small",style:{marginBottom:8,opacity:.9},children:U}):null})(),(()=>{const U=Ei;if(!U)return null;const ae=typeof U=="string"?U:Array.isArray(U)?U.map(je=>String(je)).join(" · "):JSON.stringify(U);return!ae||!ae.trim()?null:s.jsx("div",{className:"amx-small",style:{marginBottom:8,color:"var(--warning, rgba(255, 180, 90, 0.95))"},children:ae})})(),s.jsx("div",{className:"amx-small",style:{marginBottom:8,opacity:.9},children:(()=>{const U=(O==null?void 0:O.packets_version)??Js,ae=(O==null?void 0:O.packed_count)??Cs,je=(O==null?void 0:O.dropped)??hr,Ne=(O==null?void 0:O.estimated_tokens)??Xs,ke=[];return typeof U=="number"&&ke.push(`packets_v${U}`),typeof ae=="number"&&ke.push(`packed=${ae}`),typeof je=="number"&&ke.push(`dropped=${je}`),typeof Ne=="number"&&ke.push(`est_tokens=${Ne}`),ke.length?ke.join(" · "):"No packetization stats (set max_input_tokens > 0)."})()}),s.jsx("div",{className:"amx-active-memory",children:OR(mn||"(empty)",P)}),(()=>{const U=O!=null&&O.packets&&Array.isArray(O.packets)?O.packets:os;return!Array.isArray(U)||U.length===0?null:s.jsxs("div",{style:{marginTop:10},children:[s.jsxs("button",{type:"button",className:"amx-btn",onClick:()=>rn(ae=>!ae),children:[mo?"Hide":"Show"," packets (",U.length,")"]}),mo?s.jsx("div",{className:"amx-list",style:{marginTop:10},children:U.slice(0,120).map((ae,je)=>{const Ne=ae&&typeof ae=="object"&&!Array.isArray(ae)?ae:null,ke=Ne&&typeof Ne.statement=="string"?Ne.statement:typeof ae=="string"?ae:"",Ue=Ne&&(typeof Ne.retrieval_score=="number"||typeof Ne.retrieval_score=="string")?Ne.retrieval_score:null,ft=Ne&&typeof Ne.observed_at=="string"?Ne.observed_at:null;return s.jsxs("div",{className:"amx-item",children:[s.jsx("div",{className:"amx-mono",children:ke||"(packet)"}),ft||Ue!==null?s.jsxs("div",{className:"amx-small",children:[ft?`[${ft}]`:null,ft&&Ue!==null?" ":null,Ue!==null?`score:${Ue}`:null]}):null]},je)})}):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."}),Xn?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:ai.get(Xn)||Xn}),s.jsxs("div",{className:"amx-small",children:["kind=",as.get(Xn)||"entity"," · id=",Xn]})]}),s.jsxs("div",{className:"amx-actions",children:[s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>void $s(Xn),children:"Copy id"}),s.jsx("button",{type:"button",className:"amx-btn",onClick:$r,children:"Focus"})]})]}):Es&&Es.source&&Es.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:[Es.source," —",String(Es.label||((po=Es.data)==null?void 0:po.predicateSummary)||"").trim()||"?","→ ",Es.target]}),s.jsxs("div",{className:"amx-small",children:["edge_id=",Es.id]})]}),s.jsxs("div",{className:"amx-actions",children:[s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>void $s(Es.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:Er.slice(0,80).map((U,ae)=>{const je=String(U.subject||"").trim(),Ne=String(U.predicate||"").trim(),ke=String(U.object||"").trim(),Ue=ai.get(je)||je,ft=ai.get(ke)||ke,at=as.get(je)||"entity",gt=as.get(ke)||"entity",Ft=ff(at),Gt=ff(gt),gs=hf(U.observed_at),Mt=IR(U),on=U.provenance&&typeof U.provenance=="object"&&!Array.isArray(U.provenance)?U.provenance:null,En=on&&typeof on.span_id=="string"?on.span_id.trim():"",_n=on&&typeof on.writer_run_id=="string"?on.writer_run_id.trim():"",Zn=typeof U.owner_id=="string"?U.owner_id.trim():"",nr=_n||Zn,Qr=!!((S||x)&&En&&nr),Ri=!!(S&&_n&&!En),Ra=Qr||Ri;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:Ft.stroke,background:Ft.bg},title:je,onClick:()=>{je&&(Xr(""),Zs(je))},children:Ue||je||"(subject)"}),s.jsx("span",{className:"amx-arrow",children:"—"}),s.jsx("span",{className:"amx-predicate",title:Ne,children:E0(Ne)||"(predicate)"}),s.jsx("span",{className:"amx-arrow",children:"→"}),s.jsx("button",{type:"button",className:"amx-term",style:{borderColor:Gt.stroke,background:Gt.bg},title:ke,onClick:()=>{ke&&(Xr(""),Zs(ke))},children:ft||ke||"(object)"})]}),s.jsxs("div",{className:"amx-triple-meta",children:[gs?s.jsxs("span",{className:"amx-small",title:String(U.observed_at||""),children:["[",gs,"]"]}):null,Mt?s.jsx("span",{className:"amx-small",children:Mt}):null]}),En||_n?s.jsxs("div",{className:"amx-triple-actions",children:[En?s.jsxs("span",{className:"amx-small",children:["span:",En]}):null,_n?s.jsxs("span",{className:"amx-small",children:["run:",_n]}):null,Ra?s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>{if(Qr&&En&&nr){Qs({run_id:nr,span_id:En,assertion:U});return}Ri&&_n&&Qs({run_id:_n,assertion:U})},children:"Open transcript"}):null]}):null]},ae)})})]}),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)."}),li.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:li.slice(0,60).map(U=>s.jsxs("div",{className:"amx-item",style:{display:"flex",justifyContent:"space-between",gap:10,alignItems:"center"},children:[s.jsxs("div",{style:{minWidth:0},children:[s.jsxs("div",{className:"amx-mono",style:{fontSize:11,opacity:.95},children:["span:",U.span_id]}),s.jsxs("div",{className:"amx-small",children:["run_id=",U.span_run_id," · assertions=",U.count,U.last_observed_at_fmt?` · last=[${U.last_observed_at_fmt}]`:""]})]}),x||S?s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>Qs({run_id:U.span_run_id,span_id:U.span_id,assertion:U.assertion}),children:"Open transcript"}):null]},`${U.span_run_id}|${U.span_id}`))})]}):null,S&&Ai.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:Ai.slice(0,40).map(U=>s.jsxs("div",{className:"amx-item",style:{display:"flex",justifyContent:"space-between",gap:10,alignItems:"center"},children:[s.jsxs("div",{style:{minWidth:0},children:[s.jsxs("div",{className:"amx-mono",style:{fontSize:11,opacity:.95},children:["run:",U.run_id]}),s.jsxs("div",{className:"amx-small",children:["assertions=",U.count,U.last_observed_at_fmt?` · last=[${U.last_observed_at_fmt}]`:""]})]}),s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>Qs({run_id:U.run_id,assertion:U.assertion}),children:"Open transcript"})]},U.run_id))})]}):null,!li.length&&!(S&&Ai.length)?s.jsx("div",{className:"amx-small",children:"(no provenance)"}):null]})]})]})}function fl({open:e,title:t,children:n,actions:i,variant:o="default",onClose:l}){if(m.useEffect(()=>{if(!e)return;const c=f=>{f.key==="Escape"&&l()};return window.addEventListener("keydown",c),()=>window.removeEventListener("keydown",c)},[e,l]),!e)return null;const u=o==="fullscreen";return s.jsx("div",{className:`modal_backdrop${u?" fullscreen":""}`,onMouseDown:c=>{c.target===c.currentTarget&&l()},children:s.jsxs("div",{className:`modal_panel${u?" fullscreen":""}`,children:[s.jsxs("div",{className:"modal_header",children:[s.jsx("div",{className:"modal_title",children:t}),s.jsx("button",{className:"btn",onClick:l,children:"Close"})]}),s.jsx("div",{className:"modal_body",children:n}),i?s.jsx("div",{className:"modal_footer",children:i}):null]})})}function hp(e,t="session"){const n=String(e||"").trim().toLowerCase();return n==="run"||n==="session"||n==="global"||n==="all"?n:t}function al(e){const t=typeof e=="string"?e.trim():"";if(!t)return null;const n=t.replace(/(\.\d{3})\d+/,"$1"),i=Date.parse(n);return Number.isFinite(i)?i:null}function Yl(e){if(typeof e!="number"||!Number.isFinite(e))return"—";const t=new Date(e),n=t.getUTCFullYear(),i=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}/${i}/${o} ${l}:${u}`}function zR(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=al(t);return n!==null?Yl(n):t}function Jg(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 $0(e){return String(e??"").replace(/[*_`~]/g,"")}function im(e,t){const n=!!(t!=null&&t.strip_punct),i=Jg(e);let o=$0(i).replace(/\s+/g," ").trim().toLowerCase();return n&&(o=o.replace(/[^\p{L}\p{N}\s]+/gu,"").replace(/\s+/g," ").trim()),o}function om(e,t){const n=String(t??"").trim();if(!n)return!1;const i=im(n,{strip_punct:!1});if(!i)return!1;if(im(String(e??""),{strip_punct:!1}).includes(i))return!0;const l=im(n,{strip_punct:!0});return l?im(String(e??""),{strip_punct:!0}).includes(l):!1}function cv(e){const t=Jg(e).trim();if(!t)return[];const n=[],i=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&&i(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&&i(f)}}return i($0(t)),n}function BR(e){const t=String(e??"").replace(/\r\n/g,`
|
|
135
|
+
`).replace(/\r/g,`
|
|
136
|
+
`);if(!t)return null;const n=t.split(`
|
|
137
|
+
`);let i;const o=[],l=[];let u=null,c=[],f=!1;const _=()=>{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=i?null:w.match(/^\s*created_at\s*=\s*(.+)\s*$/i);if(x&&x[1]){i=x[1].trim();continue}const S=w.match(/^\s*(USER|ASSISTANT|SYSTEM)\s*:\s*(.*)$/i);if(S){f=!0,_();const j=String(S[1]||"").trim().toLowerCase();u=j==="user"?"user":j==="assistant"?"assistant":"system";const E=String(S[2]??"");c=E?[E]:[];continue}u?c.push(w):o.push(w)}if(_(),!f||!l.length)return null;const p=o.join(`
|
|
139
|
+
`).trim(),y={messages:[]};i&&(y.created_at=i),p&&y.messages.push({role:"system",content:p});for(const w of l)y.messages.push({role:w.role,content:w.lines.join(`
|
|
140
|
+
`)});return y.messages.length?y:null}function uv(e,t){const n=String(e||""),i=String(t||"");return i>n?i:n}function dv(e){const t=String((e==null?void 0:e.subject)||"").trim(),n=String((e==null?void 0:e.predicate)||"").trim(),i=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}|${i}|${o}|${l}|${u}`}function UR(e){const t=String((e==null?void 0:e.observed_at)||"").trim(),n=String((e==null?void 0:e.subject)||"").trim(),i=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} --${i}--> ${o}${f}`}function WR({gateway:e,selected_run_id:t,selected_session_id:n}){const[i,o]=m.useState(String(t||"").trim()),[l,u]=m.useState(String(n||"").trim()),[c,f]=m.useState("all"),_=c==="all",[p,y]=m.useState(!0),[w,x]=m.useState(750),[S,j]=m.useState(5e3),[E,A]=m.useState([]),[L,O]=m.useState(void 0),[M,H]=m.useState(""),[X,Y]=m.useState(!1),[Z,re]=m.useState([]),[ie,ue]=m.useState(!1),[F,C]=m.useState(!1),[N,P]=m.useState(""),[D,ne]=m.useState(""),[B,z]=m.useState(""),[G,T]=m.useState(""),[Q,K]=m.useState("artifact"),[J,oe]=m.useState(null),[fe,_e]=m.useState(""),[we,Ae]=m.useState(null),Be=m.useRef(!1),We=m.useMemo(()=>{const ce=we,be=ce!=null&&ce.attributes&&typeof ce.attributes=="object"&&!Array.isArray(ce.attributes)?ce.attributes:null;return(be&&typeof be.evidence_quote=="string"?String(be.evidence_quote):"").trim()},[we]),_t=m.useMemo(()=>{const ce=J,be=ce&&typeof ce=="object"&&!Array.isArray(ce)?ce:null,Ve=be&&typeof be.note=="string"?String(be.note):"";return Jg(Ve).trim()},[J]),Pe=m.useMemo(()=>{const ce=J&&typeof J=="object"&&!Array.isArray(J)?J:null,be=ce&&Array.isArray(ce.messages)?ce.messages:null;return Array.isArray(be)?be:null},[J]),et=m.useMemo(()=>{const ce=_t,be=We;return!ce||!be?!1:om(ce,be)},[We,_t]),lt=m.useMemo(()=>{const ce=Pe,be=We;if(!ce||!be)return[];const Ve=[];for(let He=0;He<Math.min(ce.length,500);He++){const st=ce[He],ut=(st==null?void 0:st.content)==null?"":String(st.content);om(ut,be)&&Ve.push(He)}return Ve},[We,Pe]),Ye=m.useMemo(()=>new Set(lt),[lt]),Se=lt.length?lt[0]:null,Le=m.useCallback(ce=>{const be=document.getElementById(`source_msg_${ce}`);be&&typeof be.scrollIntoView=="function"&&be.scrollIntoView({block:"center",behavior:"smooth"})},[]),ct=m.useCallback(()=>{const ce=document.getElementById("source_note_hit_0")||document.getElementById("source_note_msg_hit_0");ce&&typeof ce.scrollIntoView=="function"&&ce.scrollIntoView({block:"center",behavior:"smooth"})},[]);m.useEffect(()=>{if(ie&&!(F||N)&&!Be.current){if(Se!==null){Be.current=!0,window.setTimeout(()=>Le(Se),0);return}if(et){Be.current=!0,window.setTimeout(()=>ct(),0);return}}},[Le,ct,N,Se,F,et,ie]);const ge=m.useRef(new Set),De=m.useRef(""),Ke=m.useRef(null),Dt=m.useRef(null);m.useEffect(()=>{o(String(t||"").trim())},[t]),m.useEffect(()=>{u(String(n||"").trim())},[n]);const tn=m.useMemo(()=>{const ce=String(i||"").trim(),be=String(l||"").trim();return`mindmap:${c}:${ce}:${be}`},[i,l,c]),pn=m.useMemo(()=>{let ce=null,be=null;for(const Ve of E){const He=al(Ve==null?void 0:Ve.observed_at);He!==null&&(ce=ce===null?He:Math.min(ce,He),be=be===null?He:Math.max(be,He))}return{min_ms:ce,max_ms:be}},[E]),Wt=1e3,It=m.useMemo(()=>{const ce=pn.min_ms,be=pn.max_ms;if(typeof ce!="number"||typeof be!="number"||!Number.isFinite(ce)||!Number.isFinite(be))return null;if(be<=ce)return{min_ms:ce,max_ms:ce,real_max_ms:be};const Ve=ce+Math.ceil((be-ce)/Wt)*Wt;return{min_ms:ce,max_ms:Ve,real_max_ms:be}},[pn.max_ms,pn.min_ms]),[dn,Wn]=m.useState(!0),[Tt,bn]=m.useState(null);m.useEffect(()=>{dn&&It&&bn(It.max_ms)},[dn,It]);const Fn=m.useMemo(()=>{const ce=typeof Tt=="number"?Tt:null;return ce===null?E:E.filter(be=>{const Ve=al(be==null?void 0:be.observed_at);return Ve===null?!0:Ve<=ce})},[E,Tt]),An=m.useCallback((ce,be)=>{const Ve=Array.isArray(ce)?ce:[],He=String(De.current||"").trim(),st=new Set,ut=[];let At="";for(const kt of Ve){if(!kt||typeof kt!="object"||typeof kt.subject!="string"||typeof kt.predicate!="string"||typeof kt.object!="string")continue;const Vt=dv(kt);if(st.has(Vt))continue;st.add(Vt),ut.push(kt);const dt=String(kt.observed_at||"").trim();dt&&(At=uv(At,dt))}A(ut),O(be==null?void 0:be.warnings),ge.current=st,De.current=At||He},[]),jn=m.useCallback(async ce=>{const be=hp(ce.scope,"session"),Ve=String(ce.subject||"").trim(),He=String(ce.predicate||"").trim(),st=String(ce.object||"").trim(),ut=String(ce.since||"").trim(),At=String(ce.until||"").trim(),kt=String(ce.active_at||"").trim(),Vt=String(ce.query_text||"").trim(),dt=typeof ce.min_score=="number"&&Number.isFinite(ce.min_score)?Number(ce.min_score):void 0,Xt=ce.order==="asc"?"asc":"desc",Ut=typeof ce.limit=="number"&&Number.isFinite(ce.limit)?Number(ce.limit):0,Ct=String(i||"").trim(),pt=String(l||"").trim(),Ot={scope:be,all_owners:_,limit:Ut,order:Xt};Ve&&(Ot.subject=Ve),He&&(Ot.predicate=He),st&&(Ot.object=st),ut&&(Ot.since=ut),At&&(Ot.until=At),kt&&(Ot.active_at=kt),Vt&&(Ot.query_text=Vt),typeof dt=="number"&&(Ot.min_score=dt),_||(be==="run"?Ct&&(Ot.run_id=Ct):be==="session"?pt?Ot.session_id=pt:Ct&&(Ot.run_id=Ct):be==="all"&&(Ct?Ot.run_id=Ct:pt&&(Ot.session_id=pt)));try{const Ee=await e.kg_query(Ot),Ht=Array.isArray(Ee==null?void 0:Ee.items)?Ee.items:[],Et=Ee==null?void 0:Ee.warnings;return{ok:(Ee==null?void 0:Ee.ok)!==!1,count:Number((Ee==null?void 0:Ee.count)||Ht.length),items:Ht,warnings:Et,raw:Ee}}catch(Ee){const Ht=Ee instanceof Error?Ee.message:String(Ee);if(Ht.includes("Run '")&&Ht.includes("not found")&&!pt&&(be==="session"||be==="all")&&Ct){const an=await e.kg_query({...Ot,run_id:void 0,session_id:Ct}),$t=Array.isArray(an==null?void 0:an.items)?an.items:[],is=an==null?void 0:an.warnings;return{ok:(an==null?void 0:an.ok)!==!1,count:Number((an==null?void 0:an.count)||$t.length),items:$t,warnings:is,raw:an}}throw new Error(Ht||"KG query failed")}},[_,e,i,l]),Ln=m.useCallback(async ce=>{var He;const be=String(ce.run_id||"").trim(),Ve=String(ce.span_id||"").trim();if(!(!be||!Ve)){ue(!0),C(!0),P(""),z(be),T(Ve),K("artifact"),ne(`source span:${Ve}`),oe(null),_e(""),Ae(ce.assertion&&typeof ce.assertion=="object"?ce.assertion:null),Be.current=!1;try{const st=[be],ut=typeof((He=ce.assertion)==null?void 0:He.owner_id)=="string"?String(ce.assertion.owner_id).trim():"";ut&&ut!==be&&st.push(ut);let At=null,kt=null;for(const Vt of st)try{kt=await(await e.download_run_artifact_content(Vt,Ve)).text(),Vt!==be&&z(Vt);break}catch(dt){At=dt instanceof Error?dt.message:String(dt)}if(kt==null)throw new Error(At||"Failed to load source span");_e(kt);try{const Vt=JSON.parse(kt);oe(Vt)}catch{oe(null)}}catch(st){const ut=st instanceof Error?st.message:String(st);P(ut||"Failed to load source span")}finally{C(!1)}}},[e]),yn=m.useCallback(async ce=>{const be=String(ce.run_id||"").trim();if(!be)return null;try{const Ve=await e.list_run_artifacts(be,{limit:200}),st=(Array.isArray(Ve==null?void 0:Ve.items)?Ve.items:[]).map(dt=>{const Xt=typeof(dt==null?void 0:dt.artifact_id)=="string"?String(dt.artifact_id).trim():"",Ut=dt!=null&&dt.tags&&typeof dt.tags=="object"&&!Array.isArray(dt.tags)?dt.tags:null,Ct=Ut&&typeof Ut.kind=="string"?String(Ut.kind).trim():"";return{artifact_id:Xt,kind:Ct}}).filter(dt=>!!(dt.artifact_id&&(dt.kind==="conversation_span"||dt.kind==="memory_note")));if(!st.length)return null;if(st.length===1)return st[0].artifact_id;const ut=ce.assertion,At=ut!=null&&ut.attributes&&typeof ut.attributes=="object"&&!Array.isArray(ut.attributes)?ut.attributes:null,Vt=(At&&typeof At.evidence_quote=="string"?String(At.evidence_quote):"").trim();if(!Vt)return null;for(const dt of st.slice(0,10))try{const Ut=await(await e.download_run_artifact_content(be,dt.artifact_id)).text(),Ct=JSON.parse(Ut);if(Ct&&typeof Ct=="object"){const pt=typeof Ct.note=="string"?String(Ct.note):"";if(pt&&pt.includes(Vt))return dt.artifact_id;const Ot=Array.isArray(Ct.messages)?Ct.messages:null;if(Ot){for(const Ee of Ot.slice(0,200))if(((Ee==null?void 0:Ee.content)==null?"":String(Ee.content)).includes(Vt))return dt.artifact_id}}}catch{}}catch{}return null},[e]),Ns=m.useCallback(async ce=>{const be=String(ce.run_id||"").trim();if(be){ue(!0),C(!0),P(""),z(be),T(""),K("run_input"),ne(`transcript run:${be}`),oe(null),_e(""),Ae(ce.assertion&&typeof ce.assertion=="object"?ce.assertion:null),Be.current=!1;try{const Ve=await yn({run_id:be,assertion:ce.assertion});if(Ve){await Ln({run_id:be,span_id:Ve,assertion:ce.assertion});return}const He=await e.get_run_input_data(be),st=He&&typeof He=="object"&&!Array.isArray(He)?He.input_data:null,ut={kind:"run_input_data",run_id:be};if(He&&typeof(He==null?void 0:He.workflow_id)=="string"&&(ut.workflow_id=String(He.workflow_id)),st&&typeof st=="object"&&!Array.isArray(st)){const At=st.context,Vt=(At&&typeof At=="object"&&Array.isArray(At.messages)?At.messages:null)||(Array.isArray(st.messages)?st.messages:null);Array.isArray(Vt)&&(ut.messages=Vt);const dt=["text","prompt","task","message"];for(const Xt of dt){const Ut=st[Xt];if(typeof Ut=="string"&&Ut.trim()){ut.note=Ut.trim();break}}ut.input_data=st}!ut.messages&&!ut.note&&(ut.note=JSON.stringify(st??He??{},null,2));try{const At=await e.get_run(be),kt=At&&typeof(At==null?void 0:At.created_at)=="string"?String(At.created_at):"";kt&&(ut.created_at=kt)}catch{}oe(ut),_e(JSON.stringify(He,null,2))}catch(Ve){const He=Ve instanceof Error?Ve.message:String(Ve);P(He||"Failed to load run input transcript")}finally{C(!1)}}},[e,Ln,yn]),Gn=m.useCallback(async()=>{H(""),Y(!0);try{const ce=c==="all"?"all":c,be=await jn({scope:ce,limit:0,order:"desc"});An(be.items||[],{warnings:be.warnings}),Ke.current={scope:ce}}catch(ce){const be=ce instanceof Error?ce.message:String(ce);H(be||"Load failed")}finally{Y(!1)}},[jn,An,c]);m.useEffect(()=>{E.length||Gn()},[]);const rs=m.useCallback(async ce=>{const be=hp(ce.scope,"session");return Dt.current=ce,await jn({scope:be,subject:ce.subject,predicate:ce.predicate,object:ce.object,query_text:ce.query_text,min_score:ce.min_score,since:ce.since,until:ce.until,active_at:ce.active_at,limit:typeof ce.limit=="number"?ce.limit:0,order:"desc"})},[jn]),Nr=m.useCallback((ce,be)=>{var Ve;if((be==null?void 0:be.kind)==="live query"){const He=Dt.current;He&&(Ke.current={scope:hp(He.scope,"session"),subject:typeof He.subject=="string"?He.subject:void 0,predicate:typeof He.predicate=="string"?He.predicate:void 0,object:typeof He.object=="string"?He.object:void 0})}An(ce,{warnings:(Ve=be==null?void 0:be.result)==null?void 0:Ve.warnings})},[An]),Kn=m.useCallback(async()=>{const ce=Ke.current;if(!ce)return;const be=String(De.current||"").trim(),Ve=await jn({scope:ce.scope,subject:ce.subject,predicate:ce.predicate,object:ce.object,since:be||void 0,order:"asc",limit:0}),He=Array.isArray(Ve.items)?Ve.items:[];if(!He.length)return;const ut=Date.now()+Math.max(250,Math.min(2e4,S)),At=ge.current,kt=[],Vt=[];let dt=String(De.current||"").trim();for(const Xt of He){if(!Xt||typeof Xt!="object"||typeof Xt.subject!="string"||typeof Xt.predicate!="string"||typeof Xt.object!="string")continue;const Ut=dv(Xt);if(At.has(Ut))continue;At.add(Ut),kt.push(Xt),Vt.push({id:Ut,assertion:Xt,expires_at_ms:ut});const Ct=String(Xt.observed_at||"").trim();Ct&&(dt=uv(dt,Ct))}kt.length&&(De.current=dt,A(Xt=>{const Ut=Xt.concat(kt);return Ut.sort((Ct,pt)=>String((pt==null?void 0:pt.observed_at)||"").localeCompare(String((Ct==null?void 0:Ct.observed_at)||""))),Ut}),re(Xt=>{const Ut=Xt.concat(Vt);return Ut.sort((Ct,pt)=>pt.expires_at_ms-Ct.expires_at_ms),Ut.slice(0,30)}))},[S,jn]);return m.useEffect(()=>{if(!p)return;let ce=!1,be=null;const Ve=async()=>{if(!ce){try{await Kn()}catch{}ce||(be=window.setTimeout(()=>void Ve(),Math.max(250,Math.min(6e4,w))))}};return Ve(),()=>{ce=!0,be!==null&&window.clearTimeout(be)}},[p,w,Kn]),m.useEffect(()=>{if(!Z.length)return;const ce=window.setInterval(()=>{const be=Date.now();re(Ve=>Ve.filter(He=>He.expires_at_ms>be))},250);return()=>window.clearInterval(ce)},[Z.length]),s.jsxs("div",{className:"mindmap_root",children:[s.jsxs("div",{className:"mindmap_bar",children:[s.jsx("button",{className:"btn",onClick:()=>void Gn(),disabled:X,children:X?"Loading…":"Load snapshot"}),s.jsxs("label",{className:"field_inline",children:[s.jsx("span",{className:"mono muted",children:"source"}),s.jsxs("select",{value:c,onChange:ce=>{const be=String(ce.target.value||"").trim();(be==="all"||be==="global"||be==="session"||be==="run")&&f(be)},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.jsxs("label",{className:"field_inline",children:[s.jsx("span",{className:"mono muted",children:"live"}),s.jsx("input",{type:"checkbox",checked:p,onChange:ce=>y(!!ce.target.checked)})]}),c==="session"?s.jsxs("label",{className:"field_inline",children:[s.jsx("span",{className:"mono muted",children:"session_id"}),s.jsx("input",{className:"mono",value:l,onChange:ce=>u(String(ce.target.value||"")),placeholder:"(required)"})]}):null,c==="run"?s.jsxs("label",{className:"field_inline",children:[s.jsx("span",{className:"mono muted",children:"run_id"}),s.jsx("input",{className:"mono",value:i,onChange:ce=>o(String(ce.target.value||"")),placeholder:"(required)"})]}):null,s.jsxs("details",{className:"mindmap_details",children:[s.jsx("summary",{className:"mono muted",children:"advanced"}),s.jsx("div",{className:"mindmap_advanced",children:s.jsxs("div",{className:"field_inline",children:[s.jsx("span",{className:"mono muted",style:{width:84},children:"poll_ms"}),s.jsx("input",{type:"number",min:250,max:6e4,step:50,value:w,onChange:ce=>x(Math.max(250,Number(ce.target.value||0)||750))}),s.jsx("span",{className:"mono muted",children:"highlight_ms"}),s.jsx("input",{type:"number",min:250,max:2e4,step:250,value:S,onChange:ce=>j(Math.max(250,Number(ce.target.value||0)||5e3))})]})})]})]}),M?s.jsx("div",{className:"mindmap_error mono",children:M}):null,s.jsxs("div",{className:"mindmap_explorer",children:[s.jsx(FR,{title:"mindmap",resetKey:tn,queryMode:"replace",items:Fn,warnings:L,onQuery:rs,onItemsReplace:Nr,onOpenSpan:({run_id:ce,span_id:be,assertion:Ve})=>{Ln({run_id:ce,span_id:be,assertion:Ve})},onOpenTranscript:({run_id:ce,span_id:be,assertion:Ve})=>{const He=String(ce||"").trim(),st=typeof be=="string"?String(be).trim():"";He&&(st?Ln({run_id:He,span_id:st,assertion:Ve}):Ns({run_id:He,assertion:Ve}))}},tn),Z.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:Z.slice().sort((ce,be)=>be.expires_at_ms-ce.expires_at_ms).slice(0,12).map(ce=>s.jsx("div",{className:"mindmap_recent_item mono",children:UR(ce.assertion)},ce.id))})]}):null,It?s.jsx("div",{className:"mindmap_timeline mindmap_overlay mindmap_overlay_timeline",children:s.jsxs("div",{className:"mindmap_timeline_row",children:[s.jsx("div",{className:"mindmap_timeline_label mono muted",children:Yl(Math.min(typeof Tt=="number"?Tt: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 Tt=="number"?Tt:It.max_ms,onChange:ce=>{const be=Number(ce.target.value||0);bn(be),Wn(be>=It.max_ms)}}),s.jsxs("div",{className:"mindmap_timeline_counts mono muted",children:[Fn.length.toLocaleString(),"/",E.length.toLocaleString()]})]})}):null]}),s.jsxs(fl,{open:ie,title:D||"source",onClose:()=>{ue(!1)},children:[F?s.jsx("div",{className:"mono muted",children:"Loading…"}):null,N?s.jsx("div",{className:"mindmap_error mono",children:N}):null,!F&&!N?s.jsxs("div",{className:"source_span",children:[(()=>{const ce=we;if(!ce)return null;const be=String(ce.subject||"").trim(),Ve=String(ce.predicate||"").trim(),He=String(ce.object||"").trim(),st=Yl(al(ce.observed_at)),ut=ce.attributes&&typeof ce.attributes=="object"&&!Array.isArray(ce.attributes)?ce.attributes:null,At=ut&&typeof ut.evidence_quote=="string"?String(ut.evidence_quote):"",kt=ut&&typeof ut.original_context=="string"?String(ut.original_context):"";return s.jsxs("div",{className:"source_header",children:[s.jsxs("div",{className:"mono source_triple",title:`${be} --${Ve}--> ${He}`,children:[be," ",s.jsxs("span",{className:"muted",children:["—",Ve,"→"]})," ",He," ",st?s.jsxs("span",{className:"muted",children:["[",st,"]"]}):null]}),At?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:At}),kt?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:kt})]}):null]}):null]})})(),s.jsxs("div",{className:"mono muted",style:{marginBottom:10},children:["run_id=",B," · ",Q==="artifact"?`span_id=${G}`:"source=input_data"]}),s.jsxs("div",{className:"source_actions",children:[Se!==null?s.jsx("button",{className:"btn",onClick:()=>Le(Se),children:"Jump to evidence"}):null,Se===null&&et?s.jsx("button",{className:"btn",onClick:()=>ct(),children:"Jump to evidence"}):null]}),(()=>{const ce=J,be=ce&&typeof ce=="object"&&!Array.isArray(ce)?ce:null,Ve=Pe,He=_t,st=be&&typeof be.created_at=="string"?String(be.created_at):"",ut=st?al(st):null,At=ut!==null?Yl(ut):st,kt=be&&be.span&&typeof be.span=="object"&&!Array.isArray(be.span)?be.span:null,Vt=kt&&typeof kt.from_timestamp=="string"?String(kt.from_timestamp):"",dt=kt&&typeof kt.to_timestamp=="string"?String(kt.to_timestamp):"",Xt=Vt?al(Vt):null,Ut=dt?al(dt):null,Ct=Xt!==null&&Ut!==null?`${Yl(Xt)} → ${Yl(Ut)}`:"";if(He){const pt=BR(He);if(pt){const Ot=We,Ee=Ot?pt.messages.findIndex($t=>om($t.content,Ot)):-1,Ht=Ot?cv(Ot):[],Et=pt.created_at||st,an=Et?zR(Et):st?At:"";return s.jsx("div",{className:"source_chat",children:pt.messages.map(($t,is)=>{const os=$t.role,Js=!!(Ot&&om($t.content,Ot)),Cs=os==="user"?"USER":os==="assistant"?"ASSISTANT":"SYSTEM";return s.jsxs("div",{id:is===Ee?"source_note_msg_hit_0":void 0,className:`source_msg source_${os} ${Js?"source_match":""}`,children:[s.jsxs("div",{className:"source_msg_meta mono muted",children:[s.jsxs("span",{children:["#",is+1," · ",Cs,Js?s.jsx("span",{className:"source_match_badge",children:"evidence"}):null]}),an?s.jsx("span",{title:Et||"",children:an}):null]}),s.jsx("div",{className:"source_msg_body",children:s.jsx(Ni,{text:$t.content,highlights:Js&&Ht.length?Ht:void 0,highlightClassName:"source_note_hit",highlightId:is===Ee?"source_note_hit_0":void 0})})]},`note_msg:${is}`)})})}return s.jsxs("div",{className:"source_note",children:[st?s.jsx("div",{className:"mono muted",style:{marginBottom:10},children:s.jsxs("span",{title:st,children:["created_at=",At]})}):null,s.jsx(Ni,{text:He,highlights:We?cv(We):void 0,highlightClassName:"source_note_hit",highlightId:"source_note_hit_0"})]})}if(Ve){const pt=new Map;for(const Ee of Ve){const Ht=typeof(Ee==null?void 0:Ee.role)=="string"?String(Ee.role):"unknown";pt.set(Ht,(pt.get(Ht)||0)+1)}const Ot=Array.from(pt.entries()).sort((Ee,Ht)=>Ht[1]-Ee[1]||Ee[0].localeCompare(Ht[0])).map(([Ee,Ht])=>`${Ee}×${Ht}`).join(" · ");return s.jsxs("div",{className:"source_chat",children:[st?s.jsxs("div",{className:"mono muted",style:{marginBottom:10},children:[s.jsxs("span",{title:st,children:["created_at=",At]})," · messages=",Ve.length]}):null,Ct?s.jsxs("div",{className:"mono muted",style:{marginBottom:10},children:["span=",Ct]}):null,Ot?s.jsxs("div",{className:"mono muted",style:{marginBottom:10},children:["participants: ",Ot]}):null,Ve.slice(0,200).map((Ee,Ht)=>{var hr,Xs;const Et=typeof(Ee==null?void 0:Ee.role)=="string"?String(Ee.role):"unknown",an=(Ee==null?void 0:Ee.content)==null?"":String(Ee.content),$t=typeof(Ee==null?void 0:Ee.timestamp)=="string"?String(Ee.timestamp):"",is=$t?al($t):null,os=is!==null?Yl(is):$t,Js=typeof(Ee==null?void 0:Ee.message_id)=="string"?String(Ee.message_id):typeof((hr=Ee==null?void 0:Ee.metadata)==null?void 0:hr.message_id)=="string"?String(Ee.metadata.message_id):typeof((Xs=Ee==null?void 0:Ee.metadata)==null?void 0:Xs.id)=="string"?String(Ee.metadata.id):"",Cs=Ye.has(Ht);return s.jsxs("div",{id:`source_msg_${Ht}`,className:`source_msg source_${Et} ${Cs?"source_match":""}`,children:[s.jsxs("div",{className:"source_msg_meta mono muted",children:[s.jsxs("span",{children:["#",Ht+1," · ",Et,Cs?s.jsx("span",{className:"source_match_badge",children:"evidence"}):null,Js?s.jsx("span",{className:"source_msg_id",children:Js}):null]}),$t?s.jsx("span",{title:$t,children:os}):null]}),s.jsx("div",{className:"source_msg_body",children:s.jsx(Ni,{text:an})})]},Ht)})]})}return s.jsx("pre",{className:"mono source_raw",style:{whiteSpace:"pre-wrap",wordBreak:"break-word"},children:(typeof ce=="string"?ce:fe)||"(empty)"})})()]}):null]})]})}const mp=4;function qR(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 i=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:i(t.kinds),felt_tones:i(t.felt_tones),dreams:o}}function fv(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 i=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:i}}function HR(e){var c,f;const t=_=>{var y;const p=(y=e==null?void 0:e[_])==null?void 0:y.open;return Array.isArray(p)?p.map(fv).filter(w=>w!==null):[]},n=t("questions"),i=t("problems"),o=(c=e==null?void 0:e.lessons)==null?void 0:c.lessons,l=Array.isArray(o)?o.map(fv).filter(_=>_!==null):[],u=typeof((f=e==null?void 0:e.lessons)==null?void 0:f.total)=="number"?e.lessons.total:l.length;return{questions:n.slice(0,mp),questions_total:n.length,problems:i.slice(0,mp),problems_total:i.length,lessons:l.slice(0,mp),lessons_total:u}}function _p(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 hv={review:"Review",working:"Working",pending:"Pending",done:"Done"},VR={review:"nothing needs you",working:"idle",pending:"nothing scheduled",done:"no recent runs"},GR={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 KR(e){const t=String((e==null?void 0:e.status)||"").trim().toLowerCase();if(Ci(t))return"done";const n=Wu(e);return n==="tool_approval"||n==="user_response"?"review":n==="scheduled"||t==="pending"||t==="queued"||t==="created"?"pending":"working"}function YR(e){const t=Wu(e);return t==="tool_approval"||t==="user_response"}function mv(e,t=Date.now()){const n=KR(e),i=e!=null&&e.waiting&&typeof e.waiting=="object"?e.waiting:null,o=Uu(i),l=Cn((i==null?void 0:i.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:Wu(e),reason:Xx(e),tool_names:o.map(u=>String((u==null?void 0:u.name)||"tool")).filter(Boolean),wait_key:String((i==null?void 0:i.wait_key)||"").trim(),allow_free_text:(i==null?void 0:i.allow_free_text)!==!1,prompt:String((i==null?void 0:i.prompt)||"").trim(),since_ms:l,duration_ms:Ng(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:xf(e),tag_label:Tx(e),automation_id:xf(e)==="occurrence"?String((e==null?void 0:e.automation_id)||"").trim():""}}function JR(e,t,n=Date.now()){const i={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)||Uy(u)||YR(u)&&(l.add(c),i.review.push(mv(u,n)))}for(const u of e||[]){const c=String((u==null?void 0:u.run_id)||"").trim();if(!u||!c||l.has(c)||Uy(u))continue;const f=mv(u,n);i[f.column].push(f)}return i.review.sort((u,c)=>(u.since_ms??0)-(c.since_ms??0)),i.working.sort((u,c)=>(c.since_ms??0)-(u.since_ms??0)),i.pending.sort((u,c)=>(c.since_ms??0)-(u.since_ms??0)),i.done.sort((u,c)=>Number(c.failed)-Number(u.failed)||(c.since_ms??0)-(u.since_ms??0)),i}const fg={"12h":12*36e5,"24h":24*36e5,"48h":48*36e5,"72h":72*36e5,"7d":7*864e5,"14d":14*864e5,"1m":30*864e5,all:null},pp={"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"},_v="48h";function XR(e,t,n=Date.now()){const i=fg[t]??null;if(i===null)return{visible:e,hidden_count:0};const o=n-i,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 ZR(e,t=Date.now()){const n=String(e||"").trim();if(!n)return null;const i=Date.parse(n);return Number.isFinite(i)?Math.max(0,t-i):null}const QR=6e4;function mf(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 eL(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 tL(e){const t=String(e||"");return t.length>14?`${t.slice(0,6)}…${t.slice(-6)}`:t}function gp(e){const t=String(e||"").trim();return t.length>72?`${t.slice(0,70)}…`:t}function nL(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 i=t.slice(0,t.lastIndexOf(":"));/[a-z]/i.test(i)&&!/^[0-9a-f]+$/i.test(i.replace(/[@.\-_]/g,""))&&(n=i)}return n.length>34?`${n.slice(0,32)}…`:n}function pm(e){return e.toLowerCase().replace(/[_-]+/g," ")}function sL(e){var _,p;const t=e!=null&&e.spec&&typeof e.spec=="object"?e.spec:null,n=t!=null&&t.phases&&typeof t.phases=="object"&&!Array.isArray(t.phases)?t.phases:null;if(!n)return null;const i=Object.keys(n).filter(y=>y&&typeof y=="string");if(!i.length)return null;const o=[];for(const y of i){o.push({needle:pm(y),phase:y});const w=(_=n[y])==null?void 0:_.spoken_synonyms;if(Array.isArray(w))for(const x of w){const S=pm(String(x||"").trim());S&&o.push({needle:S,phase:y})}}const u=(typeof t.initial_phase=="string"&&i.includes(t.initial_phase)?t.initial_phase:null)??(i.includes("sleep")?"sleep":null);if(!u)return null;const c=[],f=(p=t==null?void 0:t.state_mode_axis)==null?void 0:p.words;if(f&&typeof f=="object"&&!Array.isArray(f))for(const[y,w]of Object.entries(f)){const x=String((w==null?void 0:w.phase)||"").trim(),S=pm(String(y||"").trim());S&&i.includes(x)&&c.push({needle:S,phase:x})}return{phases:i,synonyms:o,modes:c,initial:u,version:typeof t.version=="number"?t.version:null,sha256:String((e==null?void 0:e.sha256)||"").trim()}}const rL=["asleep","sleep","dream"],iL=["rest"],oL=["awake","idle"];function aL(e,t){const n=String(e||"").trim().toLowerCase();if(!n)return"unknown";if(t){const i=pm(n),o=t.synonyms.filter(u=>i.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=>i.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":rL.some(u=>n.includes(u))?t.initial:iL.some(u=>n.includes(u))&&t.phases.includes("personal")?"personal":oL.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 lL=new Set(["visit","work","personal","sleep","paused","resting","stopped","unknown"]),cL=new Set(["visit","work","personal","sleep","paused","resting","stopped","unknown"]);function uL(e){if(!e)return lL;const t=e.phases.filter(n=>cL.has(n));return new Set([...t,"paused","stopped","unknown"])}function dL(e){var X,Y,Z,re,ie,ue;const t=Date.now(),n=m.useMemo(()=>JR(e.runs,e.all_runs,Date.now()),[e.runs,e.all_runs]),[i,o]=m.useState(""),[l,u]=m.useState(""),[c,f]=m.useState(!1),[_,p]=m.useState(()=>{try{const F=localStorage.getItem("abstractobserver_done_window_v1");return F&&F in fg?F:_v}catch{return _v}}),y=m.useMemo(()=>XR(n.done,_,t),[n.done,_]),w=mf(e.runs_refreshed_at,t),x=n.review.length,S=y.visible.filter(F=>F.failed).length,[j,E]=m.useState(""),[A,L]=m.useState(null),O=F=>`${F.run_id}:${F.wait_key}:${F.since_ms??""}`;m.useEffect(()=>{i&&(n.review.some(F=>O(F)===i)||o(""))},[n,i]);async function M(F,C){o(O(F)),u("");try{await e.on_resume_wait(F.run_id,F.wait_key,C)}catch(N){u(`${F.run_id}: ${String((N==null?void 0:N.message)||N||"resume failed")}`),o("")}}function H(F){const C=i===O(F),N=F.column==="review",P=N&&!F.wait_key;return s.jsxs("div",{className:`mc_card ${N?"mc_card_review":""} ${F.failed?"mc_card_failed":""}`,onClick:()=>e.on_open_run(F.run_id),role:"button",tabIndex:0,onKeyDown:D=>{D.key==="Enter"&&D.target===D.currentTarget&&e.on_open_run(F.run_id)},children:[s.jsxs("div",{className:"mc_card_head",children:[s.jsx("span",{className:"mc_card_title",title:F.workflow,children:nL(F.workflow)}),(()=>{const D=F.failed?"failed":Nm({status:F.status,paused:F.paused});return s.jsx("span",{className:`mc_status ${pl(D)}`,children:D==="unknown"?"?":D})})()]}),s.jsxs("div",{className:"mc_card_meta",children:[s.jsx("span",{className:"mono",title:F.run_id,children:tL(F.run_id)}),F.is_subrun?s.jsx("span",{title:"This wait lives in a child run of an agent workflow",children:"subrun"}):null,F.tag?s.jsx("span",{className:"mc_pill","data-tag":F.tag,children:F.tag_label}):null,F.automation_id?s.jsx("button",{type:"button",className:"btn btn_sm",title:"Open this occurrence's automation",onClick:D=>{D.stopPropagation(),e.on_open_automation(F.automation_id)},onKeyDown:D=>D.stopPropagation(),children:"Automation"}):null,F.duration_ms>=0?s.jsx("span",{children:eL(F.duration_ms)}):null,F.tokens_total!==null?s.jsxs("span",{children:[F.tokens_total.toLocaleString()," tk"]}):null,F.tool_calls!==null&&F.tool_calls>0?s.jsxs("span",{children:[F.tool_calls," tools"]}):null]}),F.is_scheduled&&F.schedule_interval?s.jsxs("div",{className:"mc_card_line",children:["every ",F.schedule_interval]}):null,F.failed&&F.error?s.jsx("div",{className:"mc_card_error",title:F.error,children:F.error.length>120?`${F.error.slice(0,118)}…`:F.error}):null,N?s.jsxs("div",{className:"mc_card_review_body",onClick:D=>D.stopPropagation(),onKeyDown:D=>D.stopPropagation(),children:[s.jsx("div",{className:"mc_card_reason",children:F.reason||"Needs a decision"}),F.prompt?s.jsx("div",{className:"mc_card_prompt",title:F.prompt,children:F.prompt.length>240?`${F.prompt.slice(0,238)}…`:F.prompt}):null,F.tool_names.length?s.jsxs("div",{className:"mc_card_tools",title:"Tool calls awaiting your approval",children:[F.tool_names.slice(0,4).map((D,ne)=>s.jsx("span",{className:"mc_tool_chip mono",children:D},`${D}_${ne}`)),F.tool_names.length>4?s.jsxs("span",{className:"mc_tool_chip",children:["+",F.tool_names.length-4," more"]}):null]}):null,F.since_ms!==null?s.jsxs("div",{className:"mc_card_waiting",children:["waiting ",mf(F.since_ms,t)]}):null,P?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,P?s.jsx("div",{className:"mc_card_actions",children:s.jsx("button",{className:"btn",onClick:()=>e.on_open_run(F.run_id),children:"Open the run →"})}):F.wait_kind==="tool_approval"?s.jsxs("div",{className:"mc_card_actions",children:[s.jsx("button",{className:"btn success",disabled:C,onClick:()=>void M(F,{approved:!0}),children:C?"Resuming…":"Approve"}),s.jsx("button",{className:"btn danger",disabled:C,onClick:()=>void M(F,{approved:!1}),children:"Reject"})]}):s.jsx("div",{className:"mc_card_actions",children:s.jsx("button",{className:"btn primary",onClick:()=>e.on_open_run(F.run_id),children:"Review & answer →"})})]}):null]},F.run_id)}return s.jsxs("div",{className:"page page_scroll mc_page",children:[s.jsxs("div",{className:"mc_health",children:[s.jsx("span",{className:`mc_led ${e.gateway_connected?"ok":"bad"}`,title:e.gateway_connected?"Gateway connected":"Gateway unreachable"}),e.gateway_connected?null:s.jsx("span",{className:"mc_health_text",children:"gateway unreachable"}),e.runs_refreshed_at===null?s.jsx("span",{className:"mc_health_text muted mc_loading",children:"loading runs…"}):s.jsxs("div",{className:"mc_stats",children:[s.jsxs("div",{className:`mc_stat ${x?"is_hot":""}`,title:"runs blocked on a human decision (Review column)",children:[s.jsx("span",{className:"mc_stat_value",children:x}),s.jsx("span",{className:"mc_stat_label",children:"need you"})]}),s.jsxs("div",{className:`mc_stat ${S?"is_bad":""}`,title:"failed runs in the Done column",children:[s.jsx("span",{className:"mc_stat_value",children:S}),s.jsx("span",{className:"mc_stat_label",children:"failed"})]}),s.jsxs("div",{className:"mc_stat",title:"runs executing or parked listening",children:[s.jsx("span",{className:"mc_stat_value",children:n.working.length}),s.jsx("span",{className:"mc_stat_label",children:"working"})]})]}),s.jsx("span",{className:"mc_spacer"}),s.jsxs("div",{className:"mc_health_side",children:[w?s.jsxs("span",{className:"mc_health_text muted",title:"age of the last runs poll — the board is only as live as this",children:["data ",w," old"]}):null,s.jsx("button",{className:"btn",onClick:e.on_refresh,disabled:e.refreshing,children:e.refreshing?"Refreshing…":"Refresh"})]})]}),l?s.jsx("div",{className:"mc_error",children:l}):null,e.entities.length||e.entities_error?s.jsxs("div",{className:"mc_entities",children:[s.jsxs("div",{className:"mc_entities_head",children:[s.jsxs("span",{children:["Entities",e.entities_total>e.entities.length?` (${e.entities.length} of ${e.entities_total} — open the entity app for all)`:""]}),s.jsx("a",{className:"mc_entity_link",href:e.entity_app_href,target:"_blank",rel:"noreferrer",children:"open the entity app →"})]}),e.entities_error?s.jsx("div",{className:"muted",children:e.entities_error}):null,s.jsx("div",{className:"mc_entities_row",children:e.entities.map(F=>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(F.name)}&live=1`,target:"_blank",rel:"noreferrer",title:[F.error,F.age_days!==null?`${F.age_days.toFixed(0)} days old`:"",F.last_moment].filter(Boolean).join(" — ")||F.name,children:[s.jsx("span",{className:"mc_entity_name",children:F.name}),(()=>{var z;const C=String(F.live_phase||F.state||"").trim(),N=aL(C,e.phase_graph),P=uL(e.phase_graph).has(N)?N:"other",D=((z=e.phase_graph)==null?void 0:z.initial)??"sleep",ne=/awake|idle/i.test(C)&&N===D,B=C&&C.toLowerCase()!==N?` — wire word: ${C}${ne?" (settling)":""}`:"";return s.jsx("span",{className:`mc_entity_phase mc_phase_${P}`,title:(F.live_phase?"phase (cognition wire)":"phase from card state — cognition wire unavailable")+B,children:N})})(),F.last_moment?s.jsx("span",{className:"mc_entity_moment",title:F.last_moment,children:F.last_moment.replace(/_/g," ")}):null,(()=>{if(F.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 C=ZR(F.last_moment_at,t);return F.working===!1?s.jsxs("span",{className:"mc_entity_live muted",title:"idle (cognition wire)",children:["idle",C!==null?` · ${mf(t-C,t)} ago`:""]}):C===null?null:C<=QR?s.jsx("span",{className:"mc_entity_live",title:`last moment ${mf(t-C,t)} ago`,children:"● active"}):s.jsxs("span",{className:"mc_entity_live muted",title:"time since the last recorded moment",children:[mf(t-C,t)," ago"]})})(),F.tokens_total!==null?s.jsxs("span",{className:"muted mc_entity_spend",title:`lifetime billed tokens (home run ledger)${F.live_visit_tokens!==null?`; open visit: ${_p(F.live_visit_tokens)} tk`:""}${F.spend_warning?`; ${F.spend_warning}`:""}`,children:[_p(F.tokens_total)," tk",F.live_visit_tokens!==null?` (+${_p(F.live_visit_tokens)})`:"",F.spend_warning?"*":""]}):null]}),F.open_questions_total||F.open_problems_total||F.lessons_total||F.dreams_brief?s.jsx("button",{type:"button",className:"mc_entity_hints_btn","aria-expanded":j===F.name,title:"open questions / problems + distilled lessons + night signals from the entity card — click to expand",onClick:()=>E(j===F.name?"":F.name),children:[F.open_questions_total?`${F.open_questions_total} question${F.open_questions_total>1?"s":""}`:"",F.open_problems_total?`${F.open_problems_total} problem${F.open_problems_total>1?"s":""}`:"",F.lessons_total?`${F.lessons_total} lesson${F.lessons_total>1?"s":""}`:"",F.dreams_brief?`night: ${F.dreams_brief.count} signal${F.dreams_brief.count>1?"s":""}`:""].filter(Boolean).join(" · ")}):null]},F.name))}),(()=>{if(!j)return null;const F=e.entities.find(P=>P.name===j);if(!F||!F.open_questions.length&&!F.open_problems.length&&!F.lessons.length&&!F.dreams_brief)return null;const C=e.on_read_diary?async P=>{const D=await e.on_read_diary(F.name,P);L({entity:F.name,entry:(D==null?void 0:D.entry)??D,seq:typeof(D==null?void 0:D.read_recorded_at_seq)=="number"?D.read_recorded_at_seq:null})}:void 0,N=F.open_questions_total-F.open_questions.length+(F.open_problems_total-F.open_problems.length)+(F.lessons_total-F.lessons.length);return s.jsxs("div",{className:"mc_entity_hints_panel",children:[F.open_questions.map((P,D)=>s.jsx(M_,{kind:"question",label:P.title||gp(P.statement),entryId:P.entry_id,onOpen:C,title:P.statement||P.title},`q_${P.record_id||D}`)),F.open_problems.map((P,D)=>s.jsx(M_,{kind:"problem",label:P.title||gp(P.statement),entryId:P.entry_id,onOpen:C,title:P.statement||P.title},`p_${P.record_id||D}`)),F.lessons.map((P,D)=>s.jsx(M_,{kind:"lesson",label:P.title||gp(P.statement),entryId:P.entry_id,onOpen:C,title:P.statement||P.title},`l_${P.record_id||D}`)),F.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: ",F.dreams_brief.count,F.dreams_brief.dreams?` across ${F.dreams_brief.dreams} dream${F.dreams_brief.dreams>1?"s":""}`:"",F.dreams_brief.kinds.length?` — ${F.dreams_brief.kinds.slice(0,6).join(", ")}${F.dreams_brief.kinds.length>6?` +${F.dreams_brief.kinds.length-6} more`:""}`:"",F.dreams_brief.felt_tones.length?` · felt: ${F.dreams_brief.felt_tones.slice(0,6).join(", ")}`:""]}):null,N>0?s.jsxs("span",{className:"muted mc_entity_hints_more",children:["+",N," more — open the entity app"]}):null]})})()]}):null,A?s.jsx(fl,{open:!0,title:`${A.entity} — diary entry`,onClose:()=>L(null),children:s.jsxs("div",{className:"mc_diary_entry",children:[s.jsx("div",{className:"mc_diary_meta muted",children:[(X=A.entry)!=null&&X.kind?`kind: ${A.entry.kind}`:"",(Y=A.entry)!=null&&Y.visibility?`visibility: ${A.entry.visibility}`:"",(Z=A.entry)!=null&&Z.written_at?`written: ${A.entry.written_at}`:"",(re=A.entry)!=null&&re.entry_id?`id: ${A.entry.entry_id}`:""].filter(Boolean).join(" · ")}),s.jsxs("div",{className:"mc_diary_recorded muted",children:["this read was recorded in ",A.entity,"’s stream",A.seq!==null?` (seq ${A.seq})`:""]}),(ie=A.entry)!=null&&ie.gist?s.jsx("div",{className:"mc_diary_gist",children:String(A.entry.gist)}):null,s.jsx("pre",{className:"mc_diary_text",children:String(((ue=A.entry)==null?void 0:ue.text)||"(entry carries no text)")})]})}):null,s.jsx("div",{className:"mc_board",children:Object.keys(hv).map(F=>{const C=F==="done"?y.visible:n[F],N=F==="done"&&!c?C.slice(0,8):C;return s.jsxs("div",{className:`mc_column mc_column_${F}`,children:[s.jsxs("div",{className:"mc_column_head",children:[s.jsx("span",{className:"mc_column_title",children:hv[F]}),F==="done"?s.jsx("select",{className:"mc_window_select",value:_,title:"Show terminal runs from this time window",onClick:P=>P.stopPropagation(),onChange:P=>{const D=P.target.value;p(D),f(!1);try{localStorage.setItem("abstractobserver_done_window_v1",D)}catch{}},children:Object.keys(fg).map(P=>s.jsx("option",{value:P,children:pp[P]},P))}):null,s.jsx("span",{className:"mc_column_count",title:F==="done"&&y.hidden_count?`${y.hidden_count} older run(s) outside this window`:void 0,children:C.length})]}),s.jsx("div",{className:"mc_column_hint muted",children:GR[F]}),s.jsxs("div",{className:"mc_column_cards",children:[N.map(P=>H(P)),C.length?null:s.jsx("div",{className:"mc_empty muted",children:e.runs_refreshed_at===null?"loading…":F==="done"&&y.hidden_count?`none in the ${pp[_]} — ${y.hidden_count} older`:VR[F]}),F==="done"&&C.length>8&&!c?s.jsxs("button",{className:"btn mc_more",onClick:()=>f(!0),children:["show all ",C.length]}):null,F==="done"&&y.hidden_count&&C.length?s.jsxs("div",{className:"mc_window_note muted",title:"Widen the window above to see older terminal runs",children:["+",y.hidden_count," older outside ",pp[_]]}):null]})]},F)})})]})}function pv(e){const t=Array.from(new Set(e.map(n=>String(n||"").trim()).filter(Boolean)));return t.sort((n,i)=>n.localeCompare(i)),t}function gv(e){const t=e.disabled===!0,n=m.useMemo(()=>pv(e.options||[]),[e.options]),i=m.useMemo(()=>pv(e.value||[]),[e.value]),[o,l]=m.useState(!1),[u,c]=m.useState(""),f=m.useMemo(()=>{const y=u.trim().toLowerCase();return y?n.filter(w=>w.toLowerCase().includes(y)):n},[n,u]),_=m.useMemo(()=>new Set(i),[i]),p=typeof e.max_list_height_px=="number"?e.max_list_height_px:220;return s.jsxs("div",{className:"multi_select",children:[s.jsxs("div",{className:"multi_select_row",children:[s.jsxs("button",{className:"btn",type:"button",onClick:()=>l(y=>!y),disabled:t||!n.length,"aria-expanded":o,children:[o?"Hide":"Select"," • ",i.length>0?`${i.length} of ${n.length}`:e.placeholder||"(none)"]}),s.jsx("button",{className:"btn",type:"button",onClick:()=>e.onChange(n.slice()),disabled:t||!n.length||i.length===n.length,title:"Select all",children:"All"}),s.jsx("button",{className:"btn",type:"button",onClick:()=>e.onChange([]),disabled:t||i.length===0,title:"Clear selection",children:"Clear"})]}),i.length>0?s.jsx("div",{className:"multi_select_chips",children:i.map(y=>s.jsxs("span",{className:"multi_select_chip",title:y,onClick:()=>{if(t)return;const w=new Set(_);w.delete(y),e.onChange(Array.from(w.values()))},children:[y,t?null:s.jsx("span",{className:"multi_select_chip_x",children:"×"})]},y))}):null,o?s.jsxs("div",{className:"multi_select_panel",children:[s.jsx("input",{className:"mono",value:u,onChange:y=>c(String(y.target.value||"")),placeholder:"filter…",disabled:t}),s.jsxs("div",{className:"multi_select_list",style:{maxHeight:`${p}px`},children:[f.map(y=>{const w=_.has(y);return s.jsxs("label",{className:`multi_select_item mono ${w?"checked":""}`,children:[s.jsx("input",{type:"checkbox",checked:w,disabled:t,onChange:x=>{const S=new Set(_);x.target.checked?S.add(y):S.delete(y),e.onChange(Array.from(S.values()))}}),s.jsx("span",{children:y})]},y)}),f.length?null:s.jsx("div",{className:"mono muted",children:"(no matches)"})]})]}):null]})}function fL(){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 hL(){if(typeof window>"u")return!1;const e=window;return!!(e!=null&&e.AudioContext||e!=null&&e.webkitAudioContext)}function mL(){const e=window.MediaRecorder,t=i=>{var o;try{return!!((o=e==null?void 0:e.isTypeSupported)!=null&&o.call(e,i))}catch{return!1}},n=["audio/webm;codecs=opus","audio/webm","audio/mp4","audio/ogg;codecs=opus","audio/ogg"];for(const i of n)if(t(i))return i;return""}async function _L(e,t){var o;const n=t.slice(0),i=(o=e.decodeAudioData)==null?void 0:o.bind(e);if(typeof i!="function")throw new Error("decodeAudioData not available");try{const l=i(n);if(l&&typeof l.then=="function")return await l}catch{}return await new Promise((l,u)=>{try{i(n,l,u)}catch(c){u(c)}})}function pL(e){const t=P=>{var D;return(D=e.on_error)==null?void 0:D.call(e,P)},n=m.useMemo(()=>hL(),[]),i=m.useMemo(()=>fL(),[]),[o,l]=m.useState({key:"",status:"idle"}),u=m.useRef(""),c=m.useRef(""),f=m.useRef(null),_=m.useRef(null),p=m.useRef(null),y=m.useRef(null),w=m.useRef(0),x=m.useRef(0),S=()=>{try{const P=globalThis,D=(P==null?void 0:P.AudioContext)||(P==null?void 0:P.webkitAudioContext);if(!D)return null;if(!f.current){const z=new D,G=z.createGain();G.gain.value=1,G.connect(z.destination),f.current=z,_.current=G}const ne=f.current,B=_.current;if(!ne||!B)return null;try{ne.state==="suspended"&&ne.resume()}catch{}return{ctx:ne,gain:B}}catch{return null}},j=()=>{const P=p.current;if(p.current=null,!!P){try{P.onended=null}catch{}try{P.stop()}catch{}try{P.disconnect()}catch{}}},E=()=>{j(),c.current="",u.current="",y.current=null,w.current=0,x.current=0,l({key:"",status:"idle"})};m.useEffect(()=>()=>{var P,D;E();try{(P=_.current)==null||P.disconnect()}catch{}try{(D=f.current)==null||D.close()}catch{}f.current=null,_.current=null,y.current=null},[]);const A=async(P,D,ne)=>{const B=S();if(!B)throw new Error("TTS playback is not supported in this browser");const{ctx:z,gain:G}=B;try{z.state==="suspended"&&await z.resume()}catch{}j();const T=z.createBufferSource();T.buffer=D,T.connect(G);const Q=Number.isFinite(Number(D.duration))?Number(D.duration):0,K=Math.max(0,Math.min(Number(ne||0),Q>0?Math.max(0,Q-.01):0));x.current=z.currentTime-K,w.current=K,p.current=T,u.current=P,T.onended=()=>{p.current===T&&(p.current=null,w.current=0,x.current=0,u.current="",l({key:"",status:"idle"}))},T.start(0,K),l({key:P,status:"playing"})},L=async(P,D)=>{const ne=String(P||"").trim(),B=String(D||"").trim();if(!ne||!B)return;const z=e.gateway,G=String(e.run_id||"").trim();if(!z){t==null||t("Connect to the gateway first.");return}if(!G){t==null||t("Voice store not available (missing run_id).");return}const T=S();if(!T){t==null||t("TTS playback is not supported in this browser.");return}const Q=o.key===ne;if(Q&&o.status==="playing"){const K=Math.max(0,T.ctx.currentTime-Number(x.current||0));w.current=K,j(),l({key:ne,status:"paused"});return}if(Q&&o.status==="paused"){const K=y.current;if(K){t==null||t("");try{await A(ne,K,w.current)}catch(J){t==null||t(String((J==null?void 0:J.message)||J||"TTS play failed")),l({key:"",status:"idle"})}return}}if(!(Q&&o.status==="loading")){j(),y.current=null,w.current=0,x.current=0,u.current=ne,c.current=ne,l({key:ne,status:"loading"}),t==null||t("");try{const K=await z.voice_tts(G,{text:B,request_id:zs()}),J=K==null?void 0:K.audio_artifact,oe=J&&typeof J=="object"&&!Array.isArray(J)?String(J.$artifact||"").trim():"";if(!oe)throw new Error("TTS failed: missing audio artifact");const _e=await(await z.download_run_artifact_content(G,oe)).arrayBuffer();if(c.current!==ne)return;const we=await _L(T.ctx,_e);if(c.current!==ne)return;y.current=we,w.current=0,await A(ne,we,0)}catch(K){c.current===ne&&(c.current="",u.current="",l({key:"",status:"idle"})),t==null||t(String((K==null?void 0:K.message)||K||"TTS failed"))}}},[O,M]=m.useState(!1),[H,X]=m.useState(!1),Y=m.useRef(null),Z=m.useRef(null),re=m.useRef([]),ie=m.useRef("");function ue(){var P,D;try{(D=(P=Y.current)==null?void 0:P.getTracks)==null||D.call(P).forEach(ne=>{try{ne.stop()}catch{}})}catch{}Y.current=null}m.useEffect(()=>()=>{var P,D;try{(D=(P=Z.current)==null?void 0:P.stop)==null||D.call(P)}catch{}Z.current=null,ue()},[]);async function F(P,D){var G;if(t==null||t(""),!P||!P.size||H)return;const ne=e.gateway,B=String(e.session_id||"").trim(),z=String(e.run_id||"").trim();if(!ne){t==null||t("Connect to the gateway first.");return}if(!B){t==null||t("Voice input unavailable (missing session_id).");return}if(!z){t==null||t("Voice input unavailable (missing run_id).");return}X(!0);try{const T=String(D||P.type||"").toLowerCase(),Q=T.includes("mp4")?"m4a":T.includes("ogg")?"ogg":T.includes("wav")?"wav":"webm",K=new File([P],`recording.${Q}`,{type:T||"audio/webm"}),J=await ne.attachments_upload(B,K,{filename:K.name,content_type:K.type}),oe=await ne.audio_transcribe(z,{audio_artifact:J,request_id:zs()}),fe=String((oe==null?void 0:oe.text)||"").trim();fe&&((G=e.on_transcript)==null||G.call(e,fe))}catch(T){t==null||t(String((T==null?void 0:T.message)||T||"Transcription failed"))}finally{X(!1)}}async function C(){if(t==null||t(""),!i){t==null||t("Voice recording is not supported in this browser (MediaRecorder/getUserMedia unavailable).");return}if(!H&&!(O||Z.current)){re.current=[];try{const P=await navigator.mediaDevices.getUserMedia({audio:!0});Y.current=P;const D=mL();ie.current=D;const ne=D?new MediaRecorder(P,{mimeType:D}):new MediaRecorder(P);Z.current=ne,ne.ondataavailable=B=>{try{B!=null&&B.data&&re.current.push(B.data)}catch{}},ne.onerror=()=>{t==null||t("Recording failed.")},ne.onstop=()=>{M(!1),ue(),Z.current=null;try{const B=new Blob(re.current,{type:ie.current||""});F(B,ie.current)}catch(B){t==null||t(String((B==null?void 0:B.message)||B||"Failed to build recording"))}},ne.start(),M(!0)}catch(P){ue(),Z.current=null,M(!1);const D=String((P==null?void 0:P.message)||P||"Failed to access microphone");t==null||t(D.toLowerCase().includes("permission")?`Microphone permission denied: ${D}`:D)}}}function N(){const P=Z.current;if(!(!O||!P)){Z.current=null,M(!1);try{P.stop()}catch(D){t==null||t(String((D==null?void 0:D.message)||D||"Failed to stop recording"))}}}return m.useEffect(()=>{if(!O)return;const P=()=>N();return window.addEventListener("pointerup",P),window.addEventListener("pointercancel",P),()=>{window.removeEventListener("pointerup",P),window.removeEventListener("pointercancel",P)}},[O]),{tts_supported:n,tts_playback:o,toggle_tts:L,stop_tts:E,voice_ptt_supported:i,voice_ptt_recording:O,voice_ptt_busy:H,start_voice_ptt_recording:C,stop_voice_ptt_recording:N}}const am=500,Fm="http://127.0.0.1:8080";function yv(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 _f(e){const t=String(e||"").trim();return t.startsWith("abstractcode.")?`abstract.${t.slice(13)}`:t}function yp(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,i=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${i} — the loop sees it at this boundary`}function wp(e){const t=String(e||"").trim();return t.startsWith("abstract.")||t.startsWith("abstractcode.")}function gL(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 yL(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 i=n.data&&typeof n.data=="object"?n.data:{},o=Array.isArray(i.outputs)?i.outputs:[],l=i.pinDefaults&&typeof i.pinDefaults=="object"?i.pinDefaults:{},u=[];for(const c of o){if(!c||typeof c!="object")continue;const f=String(c.id||"").trim();if(!f)continue;const _=String(c.type||"").trim();if(_==="execution"||f==="exec-out"||f==="exec")continue;const p=String(c.label||f).trim()||f,y={id:f,label:p,type:_||"unknown"};l&&Object.prototype.hasOwnProperty.call(l,f)&&(y.default=l[f]),u.push(y)}return u}function vp(e,t){const n=String((e==null?void 0:e.message)||e||"Discovery failed");if(/\b401\b/.test(n)){const i=String(t.gateway_user||"").trim();return i?`Gateway authentication failed for user '${i}'. 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 wL=/^[a-zA-Z0-9_-]+$/;function wv(e){return wL.test(String(e||"").trim())}async function vL(e){const t=String(e||""),n=new TextEncoder().encode(t),i=globalThis.crypto;if(!i||!i.subtle||typeof i.subtle.digest!="function")throw new Error("crypto.subtle.digest not available");const o=await i.subtle.digest("SHA-256",n);return Array.from(new Uint8Array(o)).map(l=>l.toString(16).padStart(2,"0")).join("")}async function vv(e){const t=String(e||"").trim();if(!t)throw new Error("session_id is required");if(wv(t)){const i=`session_memory_${t}`;if(wv(i))return i}return`session_memory_sha_${(await vL(t)).slice(0,32)}`}const xv=new Set(["abstract.status","abstract.summary","abstract.chat"]);function xL(e){if(!e)return!1;if(e.kind==="error")return!0;if(e.kind==="info")return!1;const t=String(e.emit_name||"").trim();if((e.kind==="event"||e.kind==="message")&&t)return!xv.has(t);const n=String(e.effect_type||"").trim();if(n){if(n==="tool_calls"||n==="llm_call"||n==="ask_user"||n==="answer_user"||n==="memory_compact"||n==="start_subworkflow")return!0;if(n==="emit_event")return!(t&&xv.has(t))}if(String(e.status||"").trim()==="waiting"){const l=to(e.data),u=String((l==null?void 0:l.reason)||"").trim();return!!(u==="user"||u==="event"||Uu(l).length)}return!!Df(e.data)}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)||Fm),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:Fm,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 jL(e){localStorage.setItem("abstractobserver_settings",JSON.stringify({...e,auth_token:""}))}function SL(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}))},i=String(e.display??"").trim().replace(/^\[/,"").replace(/\]$/,"");return n("time",i||e.local_datetime),n("tz",e.timezone),n("country",e.country),n("user",e.user),t}function bv(e){const t=SL(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 kL(){return typeof window>"u"?"":XN(window.location)}function NL(){try{const e="abstractobserver_session_id_v1",t=window.sessionStorage.getItem(e);if(t&&t.trim())return t.trim();const n=globalThis.crypto,o=`obs_${n&&typeof n.randomUUID=="function"?n.randomUUID():`${Math.random().toString(16).slice(2)}_${Date.now().toString(16)}`}`;return window.sessionStorage.setItem(e,o),o}catch{return""}}function CL(){var Ps,Zi,qr,Vs,Yd,hu,mu,Th,Qi,Jd,_u,Do,pu;const[e,t]=m.useState("board"),[n,i]=m.useState(()=>bL()),o=typeof window<"u"&&((Ps=window.__ABSTRACT_UI_CONFIG__)==null?void 0:Ps.monitor_gpu)===!0,l=typeof window<"u"&&(((Zi=window.__ABSTRACT_UI_CONFIG__)==null?void 0:Zi.entity_app_url)||"").trim().replace(/\/+$/,"")||"http://127.0.0.1:3007",u=m.useRef(null),[c,f]=m.useState(""),[_,p]=m.useState(""),[y,w]=m.useState(()=>kL()),[x,S]=m.useState(""),[j,E]=m.useState(""),[A,L]=m.useState("{}"),[O]=m.useState(()=>NL()),[M,H]=m.useState(null),[X,Y]=m.useState(!1),[Z,re]=m.useState(""),[ie,ue]=m.useState(!1),[F,C]=m.useState(""),[N,P]=m.useState(!1),D=tS({appName:"AbstractObserver",variant:"dismissable",defaultGatewayUrl:typeof window<"u"&&((qr=window.__ABSTRACT_UI_CONFIG__)==null?void 0:qr.gateway_url)||Fm,onStatusChange:g=>bd(g)}),[ne,B]=m.useState(null),[z,G]=m.useState(null),[T,Q]=m.useState(!1),[K,J]=m.useState(null),[oe,fe]=m.useState("once"),[_e,we]=m.useState(""),[Ae,Be]=m.useState(Fp),[We,_t]=m.useState([]),[Pe,et]=m.useState(null),[lt,Ye]=m.useState(!1),[Se,Le]=m.useState([]),ct=m.useRef(new u1(zs)),[ge,De]=m.useState({available:!1,reason:"Sign in to a gateway to use automations."}),[Ke,Dt]=bS("abstractobserver",{legacyKey:"abstractobserver_settings"}),[tn,pn]=m.useState(!1),[Wt,It]=m.useState(!1),[dn,Wn]=m.useState([]),[Tt,bn]=m.useState([]),[Fn,An]=m.useState([]),[jn,Ln]=m.useState(!1),[yn,Ns]=m.useState(null),[Gn,rs]=m.useState([]),[Nr,Kn]=m.useState(0),[ce,be]=m.useState(""),Ve=m.useRef(!1),He=m.useRef(0),st=m.useRef(0),[ut,At]=m.useState(!1),[kt,Vt]=m.useState([]),[dt,Xt]=m.useState([]),[Ut,Ct]=m.useState({}),[pt,Ot]=m.useState(!1),[Ee,Ht]=m.useState(!1),[Et,an]=m.useState(!1),[$t,is]=m.useState([]),[os,Js]=m.useState([]),Cs=m.useRef(0),hr=m.useRef(null);hr.current||(hr.current=new lw(g=>window.setTimeout(g,40),g=>is(k=>k.concat(g))));const Xs=m.useRef(null);Xs.current||(Xs.current=new lw(g=>window.setTimeout(g,40),g=>Js(k=>k.concat(g))));const lo=m.useRef({scanned:0,found:null}),[xe,Yn]=m.useState(null),[mn,co]=m.useState(""),[Ei,Cr]=m.useState(!1),mr=m.useRef(null),[Jr,ot]=m.useState({}),[sn,ms]=m.useState({}),[ai,as]=m.useState(!1),[uo,fo]=m.useState(""),[Aa,zn]=m.useState(!0),[_r,Tn]=m.useState(""),[pr,ho]=m.useState(!1),[Xn,Zs]=m.useState(!1),[ls,Xr]=m.useState(6),[_s,Ta]=m.useState("standard"),[mo,rn]=m.useState(""),[yl,$i]=m.useState(""),[gr,Es]=m.useState(!1),[Ma,Er]=m.useState(!1),[li,Ai]=m.useState("pause"),[Qs,$s]=m.useState(""),[$r,er]=m.useState(""),[Ti,yr]=m.useState(""),ps=m.useRef(null),Mi=m.useRef(null),[qo,wl]=m.useState(!1),tr=m.useRef(null),[Ho,Zr]=m.useState(""),[cc,wr]=m.useState(""),[_o,Ws]=m.useState(""),[Vo,Go]=m.useState(""),[Ko,po]=m.useState(""),[U,ae]=m.useState(!1),[je,Ne]=m.useState("idle"),[ke,Ue]=m.useState([]),[ft,at]=m.useState(null),gt=m.useRef(null),[Ft,Gt]=m.useState(!1),[gs,Mt]=m.useState(""),[on,En]=m.useState(""),[_n,Zn]=m.useState(""),[nr,Qr]=m.useState([]),[Ri,Ra]=m.useState(!1),[Uf,uc]=m.useState(""),[vl,dc]=m.useState(""),[fc,hc]=m.useState(!1),[Wf,Yo]=m.useState(""),qu=m.useMemo(()=>{if(!ke.length)return"";try{return JSON.stringify(ke.map(g=>({role:g.role,content:g.content,ts:g.ts})))}catch{return"1"}},[ke]),Hu=m.useMemo(()=>ke.length?_n?qu!==_n:!0:!1,[qu,ke.length,_n]),Vu=m.useMemo(()=>nr.map(g=>{const k=String(g.title||"").trim()||`Chat ${String(g.thread_id||"").slice(0,8)}`,$=String(g.created_at||"").trim(),I=$?$.replace("T"," ").slice(0,19):"",q=String(g.run_id||"").trim()?String(g.run_id).slice(0,8):"",W=[k,I&&`(${I})`,q&&`run ${q}`].filter(Boolean).join(" • ");return{value:String(g.thread_id||""),label:W}}),[nr]);m.useEffect(()=>{o&&oC()},[o]),m.useEffect(()=>{if(!o)return;const g=u.current;g&&(g.token=n.gateway_auth_mode==="direct"&&n.auth_token||"")},[o,n.auth_token,n.gateway_auth_mode]);const[Gu,Ku]=m.useState([]),[Yu,Ju]=m.useState({}),[t_,qf]=m.useState({}),[mc,nn]=m.useState(""),[Xu,n_]=m.useState(""),[Zu,s_]=m.useState("all"),[Qu,r_]=m.useState("status"),[Qn,qs]=m.useState("overview"),[xl,Hf]=m.useState(!0),[La,_c]=m.useState("steps"),[Vf,ed]=m.useState(""),[go,td]=m.useState(""),[Gf,pc]=m.useState([]),[nd,sd]=m.useState(!1),[bl,yo]=m.useState(""),[Kf,Ia]=m.useState(""),[i_,gc]=m.useState([]),[rd,yc]=m.useState(!1),[Yf,wc]=m.useState(""),[Jf,id]=m.useState(!1),[o_,a_]=m.useState(""),[l_,Oa]=m.useState(""),[Ar,wo]=m.useState(""),[Xf,jl]=m.useState(!1),[Jo,Pa]=m.useState(""),[vo,Sl]=m.useState(null),[vc,xo]=m.useState({}),[xc,Li]=m.useState(!1),[bc,Da]=m.useState(""),[Xo,Fa]=m.useState(!1),[jc,Zf]=m.useState(!1),[Sc,kl]=m.useState(()=>Date.now()),[ci,Zo]=m.useState(""),[Qf,Nl]=m.useState({}),[eh,ui]=m.useState({}),Qo=m.useRef([]),sr=m.useRef(null),bo=m.useRef(""),kc=m.useRef({}),di=m.useRef({}),od=m.useRef({}),za=m.useRef(new Set),[fi,gn]=m.useState([]),ea=m.useRef(""),Ii=m.useRef({}),Tr=m.useRef(null),Hs=m.useRef(null),Oi=m.useRef(0),hi=m.useRef({}),ta=m.useRef(!1),Mr=m.useRef(new Set),[Nc,Cc]=m.useState(""),[mi,Pi]=m.useState(""),vr=m.useRef(""),[Cl,El]=m.useState(!1),[ad,Ba]=m.useState(""),Ec=()=>({artifact_id:"",kind:"binary",render_kind:"",text:"",url:"",loading:!1,error:""}),[$l,ld]=m.useState("activity"),[cd,th]=m.useState([]),[$c,Di]=m.useState(0),[nh,na]=m.useState(0),[_i,Ua]=m.useState({}),[Fi,Ac]=m.useState({}),[c_,sh]=m.useState(!1),[sa,Wa]=m.useState(""),[pi,Tc]=m.useState(""),[ra,jo]=m.useState("all"),[ei,Sn]=m.useState(""),[ln,So]=m.useState([]),[es,rr]=m.useState("all"),[Rr,qa]=m.useState("type"),[ys,Mc]=m.useState("newest"),[zi,ud]=m.useState(""),[ko,Ha]=m.useState(""),[gi,Va]=m.useState(""),[ia,Rc]=m.useState(0),[Ga,yi]=m.useState(()=>Ec()),[Ka,No]=m.useState(!1),[Al,Lc]=m.useState(""),[Lr,ws]=m.useState(""),[qn,Ir]=m.useState(""),[ti,oa]=m.useState("text"),[rh,Tl]=m.useState(null),[dd,As]=m.useState(!1),[ir,wn]=m.useState(""),[Or,fd]=m.useState(""),[ih,Ic]=m.useState(""),[Oc,hd]=m.useState(!1),[Pc,md]=m.useState(""),[Bi,_d]=m.useState("run_ledger"),[u_,Ml]=m.useState(""),[Dc,Fc]=m.useState([]),[oh,Co]=m.useState(""),[ah,Rl]=m.useState(!1),[zc,Eo]=m.useState(""),Oe=m.useMemo(()=>new Y_({base_url:n.gateway_auth_mode==="session"?"":n.gateway_url,auth_token:n.gateway_auth_mode==="session"?"":n.auth_token}),[n.gateway_auth_mode,n.gateway_url,n.auth_token]),Bn=m.useMemo(()=>new S1(Oe.automations_client(),x1(Oe,zs,jt)),[Oe]),Ll=m.useSyncExternalStore(g=>Bn.subscribe(g),()=>Bn.state),Bc=r1(n.gateway_url),$o=Bc?()=>{window.open(Bc,"_blank","noopener,noreferrer")}:void 0;m.useEffect(()=>{e==="launch"&&oe==="automate"&&N&&Bn.load_email_status()},[e,oe,N,Bn]),m.useEffect(()=>{const g=()=>{const k=o1(window.location.hash);k&&(k.page==="launch"&&fe(k.mode),t(k.page))};return g(),window.addEventListener("hashchange",g),()=>window.removeEventListener("hashchange",g)},[]);const Pr=m.useMemo(()=>{const g={};for(const k of Ll.items)g[k.automation_id]=k.title;return g},[Ll.items]),aa=m.useMemo(()=>Y1(),[]),[pd,gd]=m.useState([]),wi=m.useRef(0);function Ao(){const g=++wi.current;gd([["Gateway","checking…"]]),J1(Oe).then(k=>{g===wi.current&&gd(k)})}const Ya=m.useMemo(()=>n.worker_url.trim()?new l2({url:n.worker_url.trim(),auth_token:n.worker_token}):null,[n.worker_url,n.worker_token]),Ts=$t.length?$t[$t.length-1].record:null,zt=m.useMemo(()=>to(Ts),[Ts]),In=m.useMemo(()=>{const g=j.trim();if(!M||!g||String(M.bundle_id||"").trim()&&String(M.bundle_id||"").trim()!==g)return null;const k=Array.isArray(M.entrypoints)?M.entrypoints:[];if(!k.length)return null;const $=x.trim();if($)return k.find(q=>String(q.flow_id||"").trim()===$)||null;if(k.length===1)return k[0];const I=String(M.default_entrypoint||"").trim();return I&&k.find(q=>String(q.flow_id||"").trim()===I)||null},[M,j,x]),Ja=m.useMemo(()=>{const g=In==null?void 0:In.inputs;return Array.isArray(g)?g:[]},[In]),yd=m.useMemo(()=>yL(vo),[vo]),To=m.useMemo(()=>Ja.length?Ja:yd,[Ja,yd]),wd=m.useMemo(()=>{const g=typeof(xe==null?void 0:xe.workflow_id)=="string"?String(xe.workflow_id):"",k=yv(g);if(k&&M&&String(M.bundle_id||"").trim()===k.bundle_id){const q=(Array.isArray(M.entrypoints)?M.entrypoints:[]).find(W=>String((W==null?void 0:W.flow_id)||"").trim()===k.flow_id);if(q&&q.node_index&&typeof q.node_index=="object")return q.node_index}const $=In==null?void 0:In.node_index;return $&&typeof $=="object"?$:{}},[xe,M,In]);m.useEffect(()=>{jL(n)},[n]),m.useEffect(()=>()=>{Tr.current&&Tr.current.abort(),Hs.current&&Hs.current.abort(),ps.current&&window.clearTimeout(ps.current),Mi.current&&window.clearTimeout(Mi.current),sr.current&&window.clearTimeout(sr.current),tr.current&&window.clearTimeout(tr.current)},[]);const it=m.useMemo(()=>{const g=A.trim();if(!g)return{};try{const k=JSON.parse(g);return typeof k!="object"||k===null||Array.isArray(k)?null:k}catch{return null}},[A]),vi=typeof(it==null?void 0:it.prompt)=="string"?String(it.prompt):"",la=typeof(it==null?void 0:it.provider)=="string"?String(it.provider):"",Il=typeof(it==null?void 0:it.model)=="string"?String(it.model):"",ca=typeof(it==null?void 0:it.workspace_root)=="string"?String(it.workspace_root):"",Uc=typeof(it==null?void 0:it.workspace_access_mode)=="string"?String(it.workspace_access_mode):"",Xa=m.useMemo(()=>{const g=it==null?void 0:it.workspace_allowed_paths;return Array.isArray(g)?g.map(k=>String(k||"").trim()).filter(Boolean).join(`
|
|
141
|
+
`):typeof g=="string"?String(g):""},[it]),lh=m.useMemo(()=>{const g=it==null?void 0:it.workspace_ignored_paths;return Array.isArray(g)?g.map(k=>String(k||"").trim()).filter(Boolean).join(`
|
|
142
|
+
`):typeof g=="string"?String(g):""},[it]),vd=To.length>0&&!!j.trim(),$n=g=>{const k=String(g||"").trim().toLowerCase();return k==="object"||k==="memory"||k==="assertion"||k==="assertions"||k==="any"};m.useEffect(()=>{ms({})},[j,x]),m.useEffect(()=>{it!==null&&ot(g=>{const k={};for(const $ of To){if(!$||typeof $!="object")continue;const I=String($.id||"").trim();if(!I)continue;const q=String($.type||"").trim();if(!$n(q))continue;if(String(sn[I]||"").trim()){k[I]=typeof g[I]=="string"?g[I]:"";continue}const V=it==null?void 0:it[I];V===void 0?k[I]="":k[I]=aC(V)}return k})},[To,it,sn]);const Ui=_e?{kind:"default",interface:_e}:j.trim()&&x.trim()?{kind:"bundle",bundle_id:j.trim(),flow_id:x.trim()}:null,xd=QN(Ui),Dr=Array.isArray(it==null?void 0:it.skills)?it.skills.map(g=>String(g||"").trim()).filter(Boolean):[],or=m.useMemo(()=>{const g={};for(const k of dn){const $=String(k.workflow_id||"").trim(),I=String(k.label||"").trim();$&&I&&(g[$]=I)}return g},[dn]),Wc=m.useMemo(()=>dn.filter(g=>g.has_interface),[dn]),ua=m.useMemo(()=>{const g=new Set;for(const k of Array.isArray(dt)?dt:[]){const $=String((k==null?void 0:k.name)||"").trim();$&&g.add($)}return Array.from(g).sort()},[dt]),On=m.useMemo(()=>{const g=[];for(const k of Array.isArray(dt)?dt:[]){const $=String((k==null?void 0:k.name)||"").trim();if(!$)continue;const I=String((k==null?void 0:k.display_name)||"").trim();g.push({name:$,display_name:I||void 0})}return g},[dt]),ts=m.useMemo(()=>{const g=new Set;for(const k of kt||[]){if(!k||typeof k!="object")continue;const $=String(k.name||"").trim();$&&g.add($)}return Array.from(g).sort()},[kt]),ns=m.useMemo(()=>{const g=n.maintenance_ai_provider.trim();if(!g)return{models:[],error:""};const k=Ut[g];return k?{models:(Array.isArray(k.models)?k.models:[]).map(I=>String(I||"").trim()).filter(Boolean),error:String(k.error||"")}:{models:[],error:""}},[Ut,n.maintenance_ai_provider]),Za=n.maintenance_ai_provider.trim(),Ol=!!(Za&&N&&!Object.prototype.hasOwnProperty.call(Ut,Za));m.useEffect(()=>{const g=la.trim();if(!g||Ut[g]||Ii.current[g])return;Ii.current[g]=!0;let k=!1;return(async()=>{try{const I=await Oe.discovery_provider_models(g);if(k)return;const q=Array.isArray(I==null?void 0:I.models)?I.models:[],W=typeof(I==null?void 0:I.error)=="string"?String(I.error):"";Ct(V=>({...V,[g]:{models:q,error:W||void 0}}))}catch(I){if(k)return;Ct(q=>({...q,[g]:{models:[],error:String((I==null?void 0:I.message)||I||"Failed to load models")}}))}finally{delete Ii.current[g]}})(),()=>{k=!0}},[la,Ut,Oe]),m.useEffect(()=>{const g=n.maintenance_ai_provider.trim();if(!g||!N||Ut[g]||Ii.current[g])return;Ii.current[g]=!0;let k=!1;return(async()=>{try{const I=await Oe.discovery_provider_models(g);if(k)return;const q=Array.isArray(I==null?void 0:I.models)?I.models:[],W=typeof(I==null?void 0:I.error)=="string"?String(I.error):"";Ct(V=>({...V,[g]:{models:q,error:W||void 0}}))}catch(I){if(k)return;Ct(q=>({...q,[g]:{models:[],error:String((I==null?void 0:I.message)||I||"Failed to load models")}}))}finally{delete Ii.current[g]}})(),()=>{k=!0}},[n.maintenance_ai_provider,Ut,Oe,N]);function vn(g,k){const $=String(g||"").trim();if(!$)return;let I={};try{const q=JSON.parse(A||"{}");typeof q=="object"&&q!==null&&!Array.isArray(q)&&(I=q)}catch{I={}}if(k==null){delete I[$],L(JSON.stringify(I,null,2));return}if(typeof k=="string")k?I[$]=k:delete I[$];else if(Array.isArray(k)){const q=k.map(W=>W).filter(W=>W!=null);q.length?I[$]=q:delete I[$]}else I[$]=k;L(JSON.stringify(I,null,2))}async function ch(g){const k=String(g||"").trim();if(!k)return re("Missing bundle_id"),null;re(""),Y(!0);try{const $=await Oe.get_bundle(k);return H($),Kt({ts:jt(),kind:"info",title:`Loaded bundle ${k}`}),$}catch($){return H(null),re(String(($==null?void 0:$.message)||$||"Failed to load bundle")),null}finally{Y(!1)}}function cs(g){const k=[],$=Array.isArray(g==null?void 0:g.items)?g.items:[];for(const I of $){const q=String((I==null?void 0:I.bundle_id)||"").trim();if(!q)continue;const W=Array.isArray(I==null?void 0:I.entrypoints)?I.entrypoints:[];if(W.length)for(const V of W){const te=String((V==null?void 0:V.flow_id)||"").trim();if(!te||(V==null?void 0:V.deprecated)===!0)continue;const $e=`${q}:${te}`,he=String((V==null?void 0:V.name)||"").trim(),pe=he?`${q} · ${he}`:`${q} · ${te}`,Ce=String((V==null?void 0:V.description)||"").trim(),Ie=(Array.isArray(V==null?void 0:V.interfaces)?V.interfaces:[]).some(Ge=>String(Ge||"").trim().length>0),Ze=Array.isArray(V==null?void 0:V.agent_default_interfaces)?V.agent_default_interfaces.map(Ge=>String(Ge||"").trim()).filter(Boolean):[];k.push({workflow_id:$e,bundle_id:q,bundle_ref:String((I==null?void 0:I.bundle_ref)||"").trim(),flow_id:te,label:pe,description:Ce||void 0,has_interface:Ie,agent_default_interfaces:Ze})}}return k.sort((I,q)=>I.label.localeCompare(q.label)),k}async function Ms(g=Oe,k){if(Ve.current&&!(k!=null&&k.force))return;Ve.current=!0;const $=Rs.current;Ln(!0);try{const I=he=>he.map(f1).filter(pe=>!!pe.run_id),[q,W]=await Promise.all([g.list_runs({limit:200,root_only:!0,include_metrics:!0}),g.list_runs({limit:500,root_only:!1,include_metrics:!0})]);if($!==Rs.current)return;const V=Array.isArray(q==null?void 0:q.items)?q.items:[],te=Array.isArray(W==null?void 0:W.items)?W.items:[],$e=I(V).filter(he=>!String(he.parent_run_id||"").trim()||he.role==="occurrence");bn($e),An(I(te).filter(he=>!!he.run_id)),Ns(Date.now()),st.current=0,He.current=0}catch(I){const q=String((I==null?void 0:I.message)||I||"");if(Kt({ts:jt(),kind:"error",title:"Refresh runs failed",preview:ht(q)}),(/\b40[13]\b/.test(q)||/unauthorized|forbidden/i.test(q))&&D.refresh().catch(()=>{}),/\b429\b/.test(q)||/too many requests/i.test(q)){const W=Math.min(12e4,Math.max(15e3,st.current*2||15e3));st.current=W,He.current=Date.now()+W,Kt({ts:jt(),kind:"info",title:`Gateway rate-limited — pausing polls ${Math.round(W/1e3)}s`})}}finally{Ve.current=!1,Ln(!1)}}async function qc(g){var te,$e,he;const k=Rs.current;P(!0),Ct({});const[$,,I,q,W]=await Promise.allSettled([g.list_bundles(),Ms(g),g.discovery_tools(),g.discovery_providers({include_models:!1}),g.discovery_capabilities()]);if(k!==Rs.current)return;if($.status==="rejected"&&I.status==="rejected"&&q.status==="rejected"){P(!1),C(vp($.reason,n)),Kt({ts:jt(),kind:"error",title:"Discovery failed",preview:ht(String($.reason||""))});return}De(W.status==="fulfilled"?h1(W.value):{available:!1,reason:`Could not read the gateway capabilities: ${String(((te=W.reason)==null?void 0:te.message)||W.reason)}`});let V=0;if($.status==="fulfilled"){const pe=cs($.value);V=pe.length,Wn(pe)}else Wn([]),Kt({ts:jt(),kind:"error",title:"Discovery bundles failed",preview:ht(String($.reason||""))});if(I.status==="fulfilled"){const pe=Array.isArray(($e=I.value)==null?void 0:$e.items)?I.value.items:[];Vt(pe)}else Vt([]),Kt({ts:jt(),kind:"error",title:"Discovery tools failed",preview:ht(String(I.reason||""))});if(q.status==="fulfilled"){const pe=Array.isArray((he=q.value)==null?void 0:he.items)?q.value.items:[];Xt(pe)}else Xt([]),Kt({ts:jt(),kind:"error",title:"Discovery providers failed",preview:ht(String(q.reason||""))});Kt({ts:jt(),kind:"info",title:"Gateway discovery loaded",preview:ht(`workflows: ${V}`)})}async function da(g){var k,$;C(""),P(!1),ue(!0);try{if(!(g!=null&&g.prefer_direct)&&(await D.refresh(),Fr.current))return;const I=String(n.auth_token||"").trim();if(!I){g!=null&&g.open_modal_if_needed&&D.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(((k=window==null?void 0:window.location)==null?void 0:k.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 $e=new URL(q),he=String((($=window==null?void 0:window.location)==null?void 0:$.hostname)||"").trim().toLowerCase(),pe=String($e.hostname||"").trim().toLowerCase(),Ce=ze=>ze==="localhost"||ze==="127.0.0.1"||ze==="::1";if(Ce(pe)&&he&&!Ce(he))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(te){throw new Error(String((te==null?void 0:te.message)||te||"Invalid Gateway URL"))}}const W=new Y_({base_url:q,auth_token:I});await W.list_bundles(),i(V=>({...V,gateway_auth_mode:"direct"})),await qc(W)}catch(I){C(vp(I,n))}finally{ue(!1)}}const Fr=m.useRef(!1),Rs=m.useRef(0),fa=m.useRef(!1);function bd(g){var $,I,q;B(g);const k=!!(g&&g.has_session&&(($=g.gateway)!=null&&$.ok));if(Fr.current=k,k){if(fa.current=!1,N&&n.gateway_auth_mode==="direct")return;const W=String(((q=(I=g==null?void 0:g.gateway)==null?void 0:I.principal)==null?void 0:q.user_id)||"").trim();if(i(V=>({...V,gateway_auth_mode:"session",auth_token:"",gateway_user:W||V.gateway_user})),N&&n.gateway_auth_mode==="session")return;C(""),ue(!0),qc(new Y_({base_url:"",auth_token:""})).catch(V=>C(vp(V,n))).finally(()=>ue(!1));return}g&&!g.has_session&&(n.gateway_auth_mode==="session"&&Hc({keep_session:!0}),String(n.auth_token||"").trim()&&!N&&!fa.current&&(fa.current=!0,da({prefer_direct:!0})))}async function jd(){if(!(ut||ie)){At(!0);try{await Oe.reload_bundles();const g=await Oe.list_bundles(),k=cs(g);Wn(k),Kt({ts:jt(),kind:"info",title:"Bundles reloaded",preview:ht(`workflows: ${k.length}`)})}catch(g){const k=String((g==null?void 0:g.message)||g||"Bundle reload failed");Kt({ts:jt(),kind:"error",title:"Bundle reload failed",preview:ht(k),data:{error:k}})}finally{At(!1)}}}async function uh(g){if(Ei||ie||!N)return;const k=g;if(k){Cr(!0),nn("");try{const $=await Oe.upload_bundle(k,{overwrite:!1,reload:!0});Kt({ts:jt(),kind:"info",title:"Bundle uploaded",preview:ht(String(($==null?void 0:$.bundle_ref)||""))});const I=await Oe.list_bundles(),q=cs(I);Wn(q)}catch($){const I=String(($==null?void 0:$.message)||$||"Upload failed");nn(I),Kt({ts:jt(),kind:"error",title:"Upload .flow failed",preview:ht(I),data:{error:I}})}finally{Cr(!1);try{mr.current&&(mr.current.value="")}catch{}}}}function Hc(g){Rs.current+=1,g!=null&&g.keep_session||(D.signOut().catch(()=>{}),Fr.current=!1),Zc(),E(""),S(""),Pa(""),H(null),re(""),Y(!1),Wn([]),bn([]),An([]),Ns(null),rs([]),Vt([]),Xt([]),Ct({}),C(""),P(!1),B(null),i(k=>({...k,auth_token:""})),Kt({ts:jt(),kind:"info",title:"Gateway disconnected"})}async function Vc(g){const k=String(g??"");if(k){try{await navigator.clipboard.writeText(k),Pn("Copied to clipboard",2);return}catch{}try{const $=document.createElement("textarea");$.value=k,$.style.position="fixed",$.style.left="-9999px",$.style.top="0",$.style.opacity="0",document.body.appendChild($),$.focus(),$.select(),document.execCommand("copy"),document.body.removeChild($),Pn("Copied to clipboard",2)}catch{Pn("Copy failed",2)}}}m.useEffect(()=>{const g=c.trim();if(!pt||!g)return;let k=!1;const $=async()=>{if(!(He.current>Date.now()))try{const q=await Oe.get_run(g);k||Yn(q)}catch{}};$();const I=window.setInterval($,2e3);return()=>{k=!0,window.clearInterval(I)}},[pt,c,Oe]),m.useEffect(()=>{if(!N)return;let g=null,k=!1,$=!1;const I=V=>{k||(g!==null&&window.clearTimeout(g),g=window.setTimeout(()=>void q(),V))},q=async()=>{if($)return;const V=He.current-Date.now();if(V>0){I(V+500);return}$=!0;const te=Date.now();try{await Ms(Oe)}finally{$=!1;const $e=Date.now()-te,he=document.visibilityState==="hidden"?3e4:5e3;I(Math.max(he,$e*3))}},W=()=>{document.visibilityState==="visible"&&q()};return q(),document.addEventListener("visibilitychange",W),()=>{k=!0,g!==null&&window.clearTimeout(g),document.removeEventListener("visibilitychange",W)}},[N,Oe]);const[dh,Gc]=m.useState(null);m.useEffect(()=>{if(!N){Gc(null);return}let g=!1;return(async()=>{try{const k=await Oe.get_entity_phases_spec();if(g)return;const $=sL(k);if(Gc($),$)try{const I=localStorage.getItem("abstractobserver_phase_graph_id_v1"),q=I?JSON.parse(I):null;q&&q.sha256&&$.sha256&&q.sha256!==$.sha256&&q.version===$.version&&Kt({ts:jt(),kind:"error",title:"Phase-graph drift: served bytes changed without a version bump",preview:ht(`v${$.version}: ${String(q.sha256).slice(0,12)}… -> ${String($.sha256).slice(0,12)}…`),data:{prev:q,now:{sha256:$.sha256,version:$.version}}}),localStorage.setItem("abstractobserver_phase_graph_id_v1",JSON.stringify({sha256:$.sha256,version:$.version}))}catch{}}catch(k){if(!g){Gc(null);const $=String((k==null?void 0:k.message)||k||"");/404|not found/i.test($)||Kt({ts:jt(),kind:"info",title:"Phase-graph fetch failed — pre-wire fallback vocabulary in use (#FALLBACK)",preview:ht($),data:{error:$}})}}})(),()=>{g=!0}},[N]),m.useEffect(()=>{if(!N){rs([]),be("");return}let g=!1,k=null;const $=async()=>{if(!(He.current>Date.now())){try{const I=await Oe.list_entities(),q=I.entities.map(V=>String((V==null?void 0:V.name)||(V==null?void 0:V.slug)||"").trim()).filter(Boolean).slice(0,12),W=await Promise.all(q.map(async V=>{var te,$e;try{const[he,pe]=await Promise.all([Oe.get_entity_card(V),Oe.get_entity_cognition(V).catch(()=>null)]),Ce=he!=null&&he.state&&typeof he.state=="object"?he.state:null,ze=Array.isArray(he==null?void 0:he.moments)?he.moments:[],Ie=ze.length?ze[ze.length-1]:null,Ze=(te=pe==null?void 0:pe.spend)==null?void 0:te.lifetime,Ge=($e=pe==null?void 0:pe.spend)==null?void 0:$e.live_visit,cn=Array.isArray(pe==null?void 0:pe.warnings)?pe.warnings.map(qe=>String(qe||"")).filter(Boolean):[],Rt=HR(he);return{name:V,state:String((Ce==null?void 0:Ce.state)??(typeof(he==null?void 0:he.state)=="string"?he.state:"")).trim(),age_days:typeof(he==null?void 0:he.age_days)=="number"?he.age_days:null,last_moment:String((Ie==null?void 0:Ie.kind)||"").trim(),last_moment_at:String((Ie==null?void 0:Ie.at)||"").trim(),working:typeof(pe==null?void 0:pe.working)=="boolean"?pe.working:null,tokens_total:typeof(Ze==null?void 0:Ze.tokens_total)=="number"?Ze.tokens_total:null,live_visit_tokens:typeof(Ge==null?void 0:Ge.tokens_total)=="number"?Ge.tokens_total:null,spend_warning:cn.join(" | "),live_phase:typeof(pe==null?void 0:pe.phase)=="string"?pe.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:qR(he),error:""}}catch(he){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((he==null?void 0:he.message)||he||"card failed")}}}));g||(rs(W),Kn(I.entities.length),be(""))}catch(I){if(!g){rs([]);const q=String((I==null?void 0:I.message)||I||"");be(/404|not found/i.test(q)?"":q)}}g||(k=window.setTimeout(()=>void $(),3e4))}};return $(),()=>{g=!0,k!==null&&window.clearTimeout(k)}},[N,Oe]);async function fh(g,k,$){const I=String(k||"").trim();if(!g||!I)throw new Error("This wait has no wait_key yet — open the run to inspect.");await Oe.submit_command({command_id:zs(),run_id:g,type:"resume",payload:{wait_key:I,payload:$||{}},client_id:"web_pwa"}),Kt({ts:jt(),kind:"info",title:"Board resume submitted",preview:ht(`run ${g} · wait ${I}`),data:{run_id:g,wait_key:I}}),Ms(Oe,{force:!0}),window.setTimeout(()=>void Ms(Oe,{force:!0}),1200)}const zr=m.useMemo(()=>{const g=xe==null?void 0:xe.session_id;return typeof g=="string"?g.trim():g==null?"":String(g||"").trim()},[xe]),ha=m.useMemo(()=>{const g=String(zr||"").trim();return g||String(O||"").trim()},[zr,O]);m.useEffect(()=>{if(!N||!ha){po(""),Go("");return}(async()=>{try{const g=await vv(ha);po(g)}catch{po("")}})()},[N,ha]);const Mn=pL({gateway:N?Oe:null,session_id:ha,run_id:Ko,on_error:Go,on_transcript:g=>{const k=String(g||"").trim();k&&(wr($=>{const I=String($||"");return I.trim()?`${I.trimEnd()}
|
|
143
|
+
${k}`:k}),window.setTimeout(()=>{var $;return($=gt.current)==null?void 0:$.focus()},0))}});function Sd(g,k){try{const $=URL.createObjectURL(g),I=document.createElement("a");I.href=$,I.download=k||"download",I.rel="noreferrer",document.body.appendChild(I),I.click(),document.body.removeChild(I),window.setTimeout(()=>URL.revokeObjectURL($),5e3)}catch{}}async function Pl(){if(!nd){if(!N||!zr){td(""),pc([]),yo("");return}sd(!0),yo("");try{const g=await vv(zr);td(g);const k=await Oe.list_run_artifacts(g,{limit:800}),I=(Array.isArray(k==null?void 0:k.items)?k.items:[]).filter(q=>{const W=q==null?void 0:q.tags;return W&&typeof W=="object"&&String(W.kind||"").trim()==="attachment"});pc(I)}catch(g){const k=String((g==null?void 0:g.message)||g||"Failed to load session attachments"),$=k.toLowerCase();k.includes("404")||$.includes("session_memory_")&&$.includes("not found")||$.includes('"detail"')&&$.includes("not found")&&$.includes("session_memory_")?(pc([]),yo("")):(pc([]),yo(k)),td("")}finally{sd(!1)}}}async function Kc(){const g=Kf.trim();if(!g){Pn("This run recorded no workspace folder",2);return}try{const k=await fetch(YN,{method:"POST",headers:{"Content-Type":"application/json",...Zx()},body:JSON.stringify({path:g})}),$=await k.json().catch(()=>({}));k.ok&&($!=null&&$.ok)?Pn(`Opened ${String($.path||g)}`,2):Pn(String(($==null?void 0:$.error)||`Folder reveal failed (${k.status})`),3)}catch(k){Pn(String((k==null?void 0:k.message)||k||"Folder reveal failed"),3)}}async function hh(g){const k=String(go||"").trim();if(!k){Pn("No session attachment store yet",2);return}const $=String((g==null?void 0:g.artifact_id)||"").trim();if(!$)return;const I=g!=null&&g.tags&&typeof g.tags=="object"?g.tags:{},q=String(I.filename||"").trim(),W=String(I.path||"").trim(),V=q||(W?W.split("/").pop():"")||$,te=H_(V);try{const $e=await Oe.download_run_artifact_content(k,$,{access:"download"});Sd($e,te),Pn("Downloaded attachment",2)}catch($e){Pn(String(($e==null?void 0:$e.message)||$e||"Download failed"),3)}}async function kd(g){const k=String(go||"").trim(),$=String((g==null?void 0:g.artifact_id)||"").trim();if(!k||!$)return;const I=g!=null&&g.tags&&typeof g.tags=="object"?g.tags:{},q=String(I.filename||"").trim(),W=String(I.path||"").trim(),V=W?`@${W}`:q||$,te=typeof(g==null?void 0:g.size_bytes)=="number"?Number(g.size_bytes):null,$e=String((g==null?void 0:g.content_type)||I.content_type||"").trim().toLowerCase();if(a_(V),Oa(""),wo(""),id(!0),typeof te=="number"&&te>1e6){Oa(`(Attachment is ${te.toLocaleString()} bytes; download to view.)`);return}if(!(!$e||$e.startsWith("text/")||$e.includes("json")||$e.includes("yaml")||$e.includes("toml")||$e.includes("xml"))){Oa(`(Binary attachment: ${$e||"unknown"}; download to view.)`);return}jl(!0);try{const Ce=await(await Oe.download_run_artifact_content(k,$,{access:"download"})).text(),ze=14e3,Ie=Ce.length>ze?`${Ce.slice(0,Math.max(0,ze-1))}…`:Ce;Oa(Ie)}catch(pe){wo(String((pe==null?void 0:pe.message)||pe||"Preview failed"))}finally{jl(!1)}}async function Nd(g){const k=String((g==null?void 0:g.run_id)||"").trim(),$=String((g==null?void 0:g.artifact_id)||"").trim();if(!k||!$){Pn("Artifact download needs a run id",3);return}const I=Up(g)||$;try{const q=await Oe.download_run_artifact_content(k,$,{access:"preview"});Sd(q,H_(I)),Pn("Downloaded artifact",2)}catch(q){Pn(String((q==null?void 0:q.message)||q||"Download failed"),3)}}async function Cd(g){const k=String((g==null?void 0:g.run_id)||"").trim(),$=String((g==null?void 0:g.artifact_id)||"").trim();if(!k||!$){Pn("Artifact preview needs a run id",3);return}const I=Up(g),q=String((g==null?void 0:g.content_type)||"").trim().toLowerCase(),W=vf(g);if(Lc(I||$),ws(""),wn(""),oa(W),Tl(g),No(!0),qn&&(URL.revokeObjectURL(qn),Ir("")),W==="binary"){ws(`(Binary artifact: ${q||"unknown"}; download to view.)`);return}if(W==="text"&&typeof g.size_bytes=="number"&&g.size_bytes>15e5){ws(`(Text artifact is ${g.size_bytes.toLocaleString()} bytes; download to view.)`);return}As(!0);try{const V=await Oe.download_run_artifact_content(k,$,{access:"preview"});if(W==="text"){const te=await V.text(),$e=km(g,te),he=$e==="json"?15e5:$e==="markdown"?25e4:$e==="html"?3e5:22e3;ws(te.length>he&&$e!=="text"?`${Xl(g.size_bytes??te.length)} ${$e.toUpperCase()} artifact. Download to inspect it.`:te.length>he?`${te.slice(0,Math.max(0,he-1))}…`:te)}else Ir(URL.createObjectURL(V))}catch(V){wn(String((V==null?void 0:V.message)||V||"Preview failed"))}finally{As(!1)}}m.useEffect(()=>()=>{qn&&URL.revokeObjectURL(qn)},[qn]);async function mh(g){const k=String(g.artifact_id||"").trim(),$=String(g.run_id||"").trim(),I=vf(g);if(!$||!k)return{artifact_id:k,kind:I,render_kind:"",text:"Preview needs artifact run metadata.",url:"",loading:!1,error:""};if(I==="binary")return{artifact_id:k,kind:I,render_kind:"",text:`Preview unavailable for ${g.content_type||g.modality||"this artifact"}. Download to inspect it.`,url:"",loading:!1,error:""};if(I==="text"&&typeof g.size_bytes=="number"&&g.size_bytes>5e5)return{artifact_id:k,kind:I,render_kind:"",text:`${Xl(g.size_bytes)} text artifact. Use Preview for a larger view or Download to inspect locally.`,url:"",loading:!1,error:""};try{const q=await Oe.download_run_artifact_content($,k,{access:"preview"});if(I==="text"){const W=await q.text(),V=km(g,W),te=V==="json"?5e5:V==="markdown"?12e4:V==="html"?3e5:8e3;return{artifact_id:k,kind:I,render_kind:V,text:W.length>te&&V!=="text"?`${Xl(g.size_bytes??W.length)} ${V.toUpperCase()} artifact. Use Larger preview or Download to inspect it.`:W.length>te?`${W.slice(0,Math.max(0,te-1))}…`:W,url:"",loading:!1,error:""}}return{artifact_id:k,kind:I,render_kind:"",text:"",url:URL.createObjectURL(q),loading:!1,error:""}}catch(q){return{artifact_id:k,kind:I,render_kind:"",text:"",url:"",loading:!1,error:String((q==null?void 0:q.message)||q||"Preview failed")}}}async function _h(g){if(Ga.url&&URL.revokeObjectURL(Ga.url),!g){yi(Ec());return}const k=String(g.artifact_id||"").trim(),$=vf(g);yi({artifact_id:k,kind:$,render_kind:"",text:"",url:"",loading:!0,error:""}),yi(await mh(g))}m.useEffect(()=>{Pl()},[Oe,N,zr]);function Kt(g){const k=String(g.id||"").trim()||zs();Ku($=>[{...g,id:k},...$].slice(0,800))}function Pn(g,k){yr(g),Mi.current&&window.clearTimeout(Mi.current),wl(!1),window.requestAnimationFrame(()=>wl(!0)),Mi.current=window.setTimeout(()=>{wl(!1),Mi.current=null},1500),ps.current&&(window.clearTimeout(ps.current),ps.current=null),k>0&&(ps.current=window.setTimeout(()=>{yr(""),ps.current=null},Math.max(1,k)*1e3))}function ar(g,k){const $=String(g||"").trim(),I=String(k||"").trim();if(!I)return"";const q=$?String(kc.current[$]||"").trim():"";return q?`${q}::${I}`:I}function Yc(g,k,$){const I=String(g||"").trim(),q=String(k||"").trim(),W=String($||"").trim();if(!I||!q||!W)return;const V=ar(I,q);V&&(kc.current[W]=V,di.current[W]=I,od.current[W]={parent_run_id:I,parent_node_id:q},za.current.has(W)||(za.current.add(W),gn(te=>te.includes(W)?te:[...te,W])))}function Jc(g){const k=String(g||"").trim();if(!k)return;const $=Date.now(),I=bo.current;bo.current=k,kl($),Nl(q=>{const W={};for(const[he,pe]of Object.entries(q))typeof pe=="number"&&pe>$&&(W[he]=pe);W[k]=Math.max(W[k]||0,$+2e3),I&&I!==k&&(W[I]=Math.max(W[I]||0,$+2e3));const V=Object.keys(W);if(V.length<=200)return W;const te=V.sort((he,pe)=>(W[pe]||0)-(W[he]||0)).slice(0,200),$e={};for(const he of te)$e[he]=W[he]||0;return $e}),ui(q=>{if(typeof q[k]=="number")return q;const W={...q,[k]:$};if(Qo.current.push(k),Qo.current.length>8e3){const V=Qo.current.splice(0,1500);for(const te of V)delete W[te]}return W}),sr.current&&window.clearTimeout(sr.current),sr.current=window.setTimeout(()=>{const q=Date.now();Nl(W=>{const V={};for(const[te,$e]of Object.entries(W))typeof $e=="number"&&$e>q&&(V[te]=$e);return V}),kl(q),sr.current=null},2200)}function Ed(g,k){var Ge,cn,Rt;const $=String(k||"").trim()||c.trim();Cs.current=g.cursor,(Ge=hr.current)==null||Ge.push({cursor:g.cursor,record:g.record}),$&&Mr.current.add(`${$}:${g.cursor}`);const I=Gh(g.record),q=I&&I.name?_f(I.name):"",W=g.record,V=typeof(W==null?void 0:W.node_id)=="string"?W.node_id:"",te=typeof(W==null?void 0:W.status)=="string"?W.status:"",$e=typeof((cn=W==null?void 0:W.effect)==null?void 0:cn.type)=="string"?W.effect.type:"",he=typeof(W==null?void 0:W.run_id)=="string"?W.run_id:"",pe=he||$;if(q==="abstract.status"&&pe===$){const{text:qe,duration:xt}=vu(I==null?void 0:I.payload);Pn(qe,xt)}const Ce=V?ar(pe,V):"";if(te==="waiting"){const qe=to(W);if(String((qe==null?void 0:qe.reason)||"").trim()==="subworkflow"){const Nn=typeof((Rt=qe==null?void 0:qe.details)==null?void 0:Rt.sub_run_id)=="string"?String(qe.details.sub_run_id):"";Nn&&V&&Yc(pe,V,Nn)}}if(V&&(Jc(ar(pe,V)),te==="waiting"||te==="running")){const qe=ar(pe,V);qe&&(bo.current=qe,Zo(qe))}let ze="step",Ie=Ce||V||"(node?)",Ze="";if(I&&I.name&&wp(I.name))ze=q==="abstract.message"?"message":"event",Ie=q||I.name,Ze=ht(q==="abstract.steer_seen"?yp(I==null?void 0:I.payload):vu(I==null?void 0:I.payload).text);else if(W!=null&&W.error)ze="error",Ie="error",Ze=ht(Bs(W.error,360));else if(te==="waiting"){const qe=to(W),xt=String((qe==null?void 0:qe.reason)||"").trim();Ze=ht(xt?`waiting • ${xt}`:"waiting")}else W!=null&&W.result?Ze=ht(Bs(W.result,360)):$e?Ze=ht($e):Ze=ht(dm(W));Kt({id:`step:${he||$||"?"}:${g.cursor}`,ts:String((W==null?void 0:W.ended_at)||(W==null?void 0:W.started_at)||jt()),kind:ze,title:Ie,preview:Ze,data:W,cursor:g.cursor,run_id:he||$||void 0,node_id:Ce||V,status:te,effect_type:$e,emit_name:q||(I==null?void 0:I.name)||void 0})}function d_(g,k){var Ze,Ge,cn;Oi.current=Math.max(Oi.current,k.cursor);const $=`${g}:${k.cursor}`;if(!!Mr.current.has($))return;Mr.current.add($),(Ze=Xs.current)==null||Ze.push({run_id:g,cursor:k.cursor,record:k.record});const q=Gh(k.record),W=q&&q.name?_f(q.name):"",V=k.record,te=typeof(V==null?void 0:V.node_id)=="string"?V.node_id:"",$e=te?ar(g,te):"",he=typeof(V==null?void 0:V.status)=="string"?V.status:"",pe=typeof((Ge=V==null?void 0:V.effect)==null?void 0:Ge.type)=="string"?V.effect.type:"";if(he==="waiting"){const Rt=to(V);if(String((Rt==null?void 0:Rt.reason)||"").trim()==="subworkflow"){const xt=typeof((cn=Rt==null?void 0:Rt.details)==null?void 0:cn.sub_run_id)=="string"?String(Rt.details.sub_run_id):"";xt&&te&&Yc(g,te,xt),xt&&vr.current.trim()===String(g||"").trim()&&(vr.current=xt,Pi(xt))}}if(te&&(Jc(ar(g,te)),he==="waiting"||he==="running")){const Rt=ar(g,te);Rt&&(bo.current=Rt,Zo(Rt))}if((he==="completed"||he==="failed")&&vr.current.trim()===String(g||"").trim()){const Rt=String(di.current[String(g||"").trim()]||"").trim();Rt&&Rt!==c.trim()?(vr.current=Rt,Pi(Rt)):(vr.current="",Pi(""))}if(W==="abstract.status"&&g===c.trim()){const{text:Rt,duration:qe}=vu(q==null?void 0:q.payload);Pn(Rt,qe)}let Ce="step",ze=$e||te||"(node?)",Ie="";if(q&&q.name&&wp(q.name))Ce=W==="abstract.message"?"message":"event",ze=`subrun • ${W||q.name}`,Ie=ht(W==="abstract.steer_seen"?yp(q==null?void 0:q.payload):vu(q==null?void 0:q.payload).text);else if(V!=null&&V.error)Ce="error",ze="error",Ie=ht(Bs(V.error,360));else if(he==="waiting"){const Rt=to(V),qe=String((Rt==null?void 0:Rt.reason)||"").trim();Ie=ht(qe?`waiting • ${qe}`:"waiting")}else V!=null&&V.result?Ie=ht(Bs(V.result,360)):pe?Ie=ht(pe):Ie=ht(dm(V));Kt({id:`step:${g}:${k.cursor}`,ts:String((V==null?void 0:V.ended_at)||(V==null?void 0:V.started_at)||jt()),kind:Ce,title:ze,preview:Ie,data:V,cursor:k.cursor,run_id:g,node_id:$e||te,status:he,effect_type:pe,emit_name:W||(q==null?void 0:q.name)||""})}function f_(g,k){var Ge,cn,Rt;const $=String(g||"").trim();if(!$)return;const I=`${$}:${k.cursor}`;if(!!Mr.current.has(I))return;Mr.current.add(I),(Ge=Xs.current)==null||Ge.push({run_id:$,cursor:k.cursor,record:k.record});const W=Gh(k.record),V=W&&W.name?_f(W.name):"",te=k.record,$e=typeof(te==null?void 0:te.node_id)=="string"?te.node_id:"",he=$e?ar($,$e):"",pe=typeof(te==null?void 0:te.status)=="string"?te.status:"",Ce=typeof((cn=te==null?void 0:te.effect)==null?void 0:cn.type)=="string"?te.effect.type:"";if(pe==="waiting"){const qe=to(te);if(String((qe==null?void 0:qe.reason)||"").trim()==="subworkflow"){const Nn=typeof((Rt=qe==null?void 0:qe.details)==null?void 0:Rt.sub_run_id)=="string"?String(qe.details.sub_run_id):"";Nn&&$e&&Yc($,$e,Nn)}}if($e&&(Jc(ar($,$e)),pe==="waiting"||pe==="running")){const qe=ar($,$e);qe&&(bo.current=qe,Zo(qe))}if(V==="abstract.status"&&$===c.trim()){const{text:qe,duration:xt}=vu(W==null?void 0:W.payload);Pn(qe,xt)}let ze="step",Ie=he||$e||"(node?)",Ze="";if(W&&W.name&&wp(W.name))ze=V==="abstract.message"?"message":"event",Ie=`subrun • ${V||W.name}`,Ze=ht(V==="abstract.steer_seen"?yp(W==null?void 0:W.payload):vu(W==null?void 0:W.payload).text);else if(te!=null&&te.error)ze="error",Ie="error",Ze=ht(Bs(te.error,360));else if(pe==="waiting"){const qe=to(te),xt=String((qe==null?void 0:qe.reason)||"").trim();Ze=ht(xt?`waiting • ${xt}`:"waiting")}else te!=null&&te.result?Ze=ht(Bs(te.result,360)):Ce?Ze=ht(Ce):Ze=ht(dm(te));Kt({id:`step:${$}:${k.cursor}`,ts:String((te==null?void 0:te.ended_at)||(te==null?void 0:te.started_at)||jt()),kind:ze,title:Ie,preview:Ze,data:te,cursor:k.cursor,run_id:$,node_id:he||$e,status:pe,effect_type:Ce,emit_name:V||(W==null?void 0:W.name)||""})}async function $d(g,k){var I,q;let $=k.after;for(;;){if((I=k.signal)!=null&&I.aborted)return $;const W=await Oe.get_ledger(g,{after:$,limit:200,signal:k.signal});if((q=k.signal)!=null&&q.aborted)return $;const V=Array.isArray(W.items)?W.items:[];if(!V.length)return Cs.current=$,$;const te=$;for(let $e=0;$e<V.length;$e++){const he=V[$e];Ed({cursor:te+$e+1,record:he},g)}$=typeof W.next_after=="number"?W.next_after:$}}async function Qa(g){var W,V,te,$e;const k=String(g||"").trim();nn(""),Ht(!0),Ot(!1),(W=hr.current)==null||W.reset(),(V=Xs.current)==null||V.reset(),lo.current={scanned:0,found:null},is([]),Cs.current=0,Js([]),Mr.current=new Set,Ku([]),Ju({}),qf({}),_c("steps"),ed(""),yr(""),Yn(null),Zr(""),Ia(""),gc([]),wc(""),Zo(""),bo.current="",Nl({}),ui({}),Qo.current=[],kl(Date.now()),kc.current=k?{[k]:""}:{},di.current={},od.current={},za.current=new Set,gn([]),ea.current="",vr.current="",Pi(""),hi.current={},sr.current&&window.clearTimeout(sr.current),sr.current=null,tr.current&&window.clearTimeout(tr.current),tr.current=null,Tr.current&&Tr.current.abort(),Hs.current&&Hs.current.abort(),Hs.current=null,Oi.current=0,Cc("");const $=new AbortController;Tr.current=$;let I=!1;try{let he="",pe="";try{const Ce=await Oe.get_run(k);Yn(Ce);const ze=typeof(Ce==null?void 0:Ce.workflow_id)=="string"?String(Ce.workflow_id):"",Ie=yv(ze);Ie&&(he=Ie.bundle_id,pe=Ie.flow_id)}catch{}try{const Ce=await Oe.get_run_input_data(k);typeof(Ce==null?void 0:Ce.bundle_id)=="string"&&(he=String(Ce.bundle_id||"").trim()||he),typeof(Ce==null?void 0:Ce.flow_id)=="string"&&(pe=String(Ce.flow_id||"").trim()||pe);const ze=Ce&&typeof Ce.input_data=="object"&&Ce.input_data&&!Array.isArray(Ce.input_data)?Ce.input_data:null;ze&&L(JSON.stringify(ze,null,2));const Ie=Ce==null?void 0:Ce.workspace,Ze=typeof(Ie==null?void 0:Ie.workspace_root)=="string"?String(Ie.workspace_root).trim():"";Ia(Ze)}catch{Ia("")}(async()=>{yc(!0),wc("");try{const Ce=await Oe.list_run_artifacts(k,{limit:200}),ze=Array.isArray(Ce==null?void 0:Ce.items)?Ce.items:[];$.signal.aborted||gc(ze)}catch(Ce){$.signal.aborted||(gc([]),wc(String((Ce==null?void 0:Ce.message)||Ce||"artifact listing failed")))}finally{$.signal.aborted||yc(!1)}})(),he&&pe&&(E(he),S(pe),Pa(pe),await ch(he)),await $d(k,{after:0,signal:$.signal});try{const Ce=await Oe.get_run_history_bundle(k,{include_subruns:!0,include_session:!1,ledger_mode:"tail",ledger_max_items:1}),ze=Ce&&typeof Ce=="object"?Ce.ledgers:null,Ze=(ze&&typeof ze=="object"?Object.keys(ze):[]).map(Ge=>String(Ge||"").trim()).filter(Boolean).filter(Ge=>Ge!==k);if(Ze.length){for(const Ge of Ze)za.current.add(Ge);gn(Ge=>Array.from(new Set([...Ge,...Ze])));try{const Ge=typeof((te=ze==null?void 0:ze[k])==null?void 0:te.total)=="number"?Number(ze[k].total):0;let cn="",Rt=-1;for(const qe of Ze){const xt=typeof(($e=ze==null?void 0:ze[qe])==null?void 0:$e.total)=="number"?Number(ze[qe].total):0;xt>Rt&&(cn=qe,Rt=xt)}cn&&Rt>Math.max(Ge*3,Ge+20)&&(vr.current=cn,Pi(cn))}catch{}}}catch{}Ot(!0),Kt({ts:jt(),kind:"info",title:`Attached to run ${k}`,data:{run_id:k}}),I=!0}catch(he){const pe=String((he==null?void 0:he.message)||he||"unknown error");nn(pe),Kt({ts:jt(),kind:"error",title:"Connection error",preview:ht(pe),data:{error:pe}}),Ot(!1)}finally{Ht(!1)}if(!I||$.signal.aborted)return;(async()=>{let he=250;for(;!$.signal.aborted;){try{const pe=await $d(k,{after:Cs.current,signal:$.signal});await Oe.stream_ledger(k,{after:pe,on_step:Ce=>Ed(Ce,k),signal:$.signal})}catch(pe){if($.signal.aborted)break;const Ce=String((pe==null?void 0:pe.message)||pe||"stream error");Kt({ts:jt(),kind:"error",title:"Ledger stream error (will retry)",preview:ht(Ce),data:{error:Ce}})}if($.signal.aborted)break;await new Promise(pe=>setTimeout(pe,he)),he=Math.min(5e3,Math.floor(he*1.6))}})()}async function ph(){const g=Ui,k=(g==null?void 0:g.kind)==="bundle"?g.flow_id:(g==null?void 0:g.kind)==="default"?"@default":"",$=(g==null?void 0:g.kind)==="bundle"?g.bundle_id:"";if(!g){const I="Select a workflow first (Launch → pick a workflow).";return nn(I),I}nn(""),Ht(!0);try{let I={};const q=A.trim();if(q)try{if(I=JSON.parse(q),typeof I!="object"||I===null||Array.isArray(I))throw new Error("input_data must be a JSON object")}catch(pe){const Ce=`Invalid input_data JSON: ${String((pe==null?void 0:pe.message)||pe)}`;return nn(Ce),Ce}for(const[pe,Ce]of Object.entries(I)){if(typeof Ce!="string")continue;const ze=Ce.trim();ze?I[pe]=ze:delete I[pe]}const W=(To||[]).find(pe=>pe&&typeof pe=="object"&&pe.id==="prompt"),V=W&&typeof W=="object"&&Object.prototype.hasOwnProperty.call(W,"default"),te=I==null?void 0:I.prompt,$e=typeof te=="string"?te.trim():"";if(W&&!V&&!$e){const pe="Missing required input_data.prompt";return nn(pe),pe}const he=await Oe.start_run(k,I,{...$?{bundle_id:$}:{},...g.kind==="default"?{interface:g.interface}:{},session_id:String(O||"").trim()||null});return p(he),f(he),co(""),await Qa(he),Ms(),null}catch(I){const q=String((I==null?void 0:I.message)||I||"start failed");return nn(q),q}finally{Ht(!1)}}async function Xc(){if(_t([]),et(null),!ge.available){_t([ge.reason]);return}const g=d1(Ae,{choice:Ui,bundle_ref_for:k=>{var $;return(($=dn.find(I=>I.bundle_id===k))==null?void 0:$.bundle_ref)||""},input_data:it,email_usable:Bn.email_usable},ct.current);if(!g.ok){_t(g.errors);return}Ye(!0);try{const k=await Oe.automations_client().createAutomation(g.body);ct.current.reset(),Le([]),Be(Fp),Kt({ts:jt(),kind:"info",title:"Automation created",preview:ht(`${g.body.title} · ${k.automation_id}`)}),t("automations"),await Bn.refresh(),await Bn.select(k.automation_id)}catch(k){const $=(k&&typeof k=="object"&&typeof k.code=="string"?k:null)||{status:0,code:"client_error",message:String((k==null?void 0:k.message)||k||"Create failed")};et($)}finally{Ye(!1)}}async function h_(){if(co(""),oe==="automate"){await Xc();return}const g=await ph();if(g){co(g);return}qs("overview"),t("observe")}async function gh(g){if(vn("skills",void 0),!!g){if(g.kind==="default"){we(g.interface),E(""),S(""),H(null);return}we(""),E(g.bundle_id),S(g.flow_id),Pa(g.flow_id),await ch(g.bundle_id)}}async function yh(g){const[k,$]=await Promise.all([Oe.get_run(g),Oe.get_run_input_data(g)]),I=w1(k,$);await gh(I.choice),L(JSON.stringify(I.input_data,null,2)),Be(I.form),Le([`Recreating the legacy schedule ${Lt(g,14)} as an automation. The legacy schedule keeps running until you suspend it.`,...I.notes]),ct.current.reset(),fe("automate"),t("launch")}async function vs(g,k){const $=String(g||"").trim();if(!$)return;if(Ee){Pn(`Still attaching — retry in a moment (${Lt($,14)})`,2500);return}nn("");const I=String((k==null?void 0:k.root_run_id)||$).trim()||$;p(I),f($),await Qa($)}m.useEffect(()=>{const g=String(y||"").trim();if(!g)return;let k=!1;return(async()=>{try{if(N||await da({open_modal_if_needed:!0}),k)return;qs("overview"),t("observe"),await vs(g)}catch($){k||nn(String(($==null?void 0:$.message)||$||"Failed to attach run from URL"))}finally{k||w("")}})(),()=>{k=!0}},[y]);function Zc(){var g,k;Tr.current&&Tr.current.abort(),Tr.current=null,Hs.current&&Hs.current.abort(),Hs.current=null,Oi.current=0,Cc(""),f(""),p(""),kc.current={},di.current={},od.current={},za.current=new Set,gn([]),ea.current="",vr.current="",Pi(""),hi.current={},Zr(""),sr.current&&window.clearTimeout(sr.current),sr.current=null,tr.current&&window.clearTimeout(tr.current),tr.current=null,Ot(!1),Ht(!1),an(!1),Cs.current=0,(g=hr.current)==null||g.reset(),(k=Xs.current)==null||k.reset(),lo.current={scanned:0,found:null},is([]),Js([]),Mr.current=new Set,Yn(null),Ku([]),Ju({}),Zo(""),bo.current="",Nl({}),ui({}),Qo.current=[],kl(Date.now()),Pn("",-1),nn(""),El(!1),Ba(""),Ue([]),at(null),wr(""),Ws(""),ae(!1),Gt(!1),Mt(""),En(""),Zn(""),Qr([]),Ra(!1),uc(""),dc(""),hc(!1),Yo("")}m.useEffect(()=>{Ue([]),at(null),wr(""),Ws(""),ae(!1),Gt(!1),Mt(""),En(""),Zn(""),Qr([]),Ra(!1),uc(""),dc(""),hc(!1),Yo("")},[c]),m.useEffect(()=>{Qn==="chat"&&c.trim()&&N&&Qc()},[Qn,c,N,xe==null?void 0:xe.workflow_id]);async function Dl(g,k,$){const I=String(g||"").trim();if(!I)return nn("Missing run_id"),"Missing run_id";nn("");try{const q={},W=String(($==null?void 0:$.reason)||"").trim();W&&(q.reason=W),await Oe.submit_command({command_id:zs(),run_id:I,type:k,payload:q,client_id:"web_pwa"}),Kt({ts:jt(),kind:"info",title:`${k} submitted`,preview:W?`reason: ${W}`:"",data:{run_id:I,type:k,reason:W}});try{if(I===c.trim()){const V=await Oe.get_run(I);Yn(V)}}catch{}return Ms(Oe,{force:!0}),window.setTimeout(()=>void Ms(Oe,{force:!0}),900),window.setTimeout(()=>void Ms(Oe,{force:!0}),2400),null}catch(q){const W=String((q==null?void 0:q.message)||q||`${k} failed`);return nn(W),W}}async function Ad(g,k){return Dl(c.trim(),g,k)}async function Td(g,k="Stopped from AbstractObserver"){const $=String(g||"").trim();if(!$||!window.confirm(`Cancel run ${Lt($,24)}?`))return;await Dl($,"cancel",{reason:k})||Pn("Cancel submitted",2)}async function wh(){var $;const g=c.trim();if(!g){nn("Select a run first.");return}if(!N){nn("Connect to the gateway first.");return}if(Et)return;const k=String((($=xe==null?void 0:xe.waiting)==null?void 0:$.reason)||"").trim().toLowerCase()||String(us||"").trim().toLowerCase();if(!br||Br||qi||Wi.toLowerCase()!=="waiting"||k!=="until"){nn("This run is not a scheduled wait that can be triggered now.");return}nn(""),an(!0);try{const I={payload:{mode:"run_now",requested_at:jt()}},q=String(Ls||"").trim();q&&(I.wait_key=q),await Oe.submit_command({command_id:zs(),run_id:g,type:"resume",payload:I,client_id:"web_pwa"}),Kt({ts:jt(),kind:"info",title:"Scheduled run triggered",preview:ht(`run ${g}`),data:{run_id:g,until:ni||null}});try{const W=await Oe.get_run(g);Yn(W)}catch{}}catch(I){nn(String((I==null?void 0:I.message)||I||"Failed to trigger scheduled run"))}finally{an(!1)}}async function Md(g){const k=c.trim();if(!k)return nn("Missing run_id"),"Missing run_id";if(pr)return"Schedule update already in progress";const $=String(g.interval||"").trim();if(!/^\s*(\d+(?:\.\d+)?)\s*(ms|s|m|h|d)\s*$/i.test($)){const q="Invalid interval (expected like '20m', '1h', '0.5s', '250ms')";return Tn(q),q}Tn(""),nn(""),ho(!0),Ht(!0);try{await Oe.submit_command({command_id:zs(),run_id:k,type:"update_schedule",payload:{interval:$,apply_immediately:g.apply_immediately!==!1},client_id:"web_pwa"}),Kt({ts:jt(),kind:"info",title:"Schedule updated",preview:ht(`interval: ${$}`),data:{interval:$},run_id:k});try{const q=await Oe.get_run(k);Yn(q)}catch{}return null}catch(q){const W=String((q==null?void 0:q.message)||q||"update_schedule failed");return Tn(W),nn(W),W}finally{Ht(!1),ho(!1)}}async function el(g){const k=c.trim();if(!k)return nn("Missing run_id"),"Missing run_id";if(gr)return"Compaction already in progress";const $=typeof(g==null?void 0:g.preserve_recent)=="number"?g.preserve_recent:ls,I=Math.max(0,Math.min(500,Math.floor(Number.isFinite($)?$:6))),q=(g==null?void 0:g.compression_mode)||_s,W=String((g==null?void 0:g.focus)??mo??"").trim();$i(""),nn(""),Es(!0),Ht(!0);try{const V={preserve_recent:I,compression_mode:q};return W&&(V.focus=W),await Oe.submit_command({command_id:zs(),run_id:k,type:"compact_memory",payload:V,client_id:"web_pwa"}),Kt({ts:jt(),kind:"info",title:"Compaction requested",preview:ht(`mode: ${q} • preserve_recent: ${I}`),data:V,run_id:k}),null}catch(V){const te=String((V==null?void 0:V.message)||V||"compact_memory failed");return $i(te),nn(te),te}finally{Ht(!1),Es(!1)}}async function Rd(){const g=c.trim();if(!g){Ba("Missing run_id");return}if(!Cl){Ba(""),El(!0);try{const k=n.maintenance_ai_provider.trim(),$=n.maintenance_ai_model.trim();await Oe.generate_run_summary(g,{provider:k||void 0,model:$||void 0,include_subruns:!0}),Kt({ts:jt(),kind:"info",title:"Summary generation requested",preview:ht(`run ${g}`)})}catch(k){Ba(String((k==null?void 0:k.message)||k||"Failed to generate summary"))}finally{El(!1)}}}async function Ld(){const g=c.trim();if(!g){Ws("Select a run first.");return}if(!N){Ws("Connect to the gateway first.");return}const k=cc.trim();if(!k||U)return;if(Mn.voice_ptt_busy){Go("Wait for transcription to finish.");return}Ws(""),Go(""),ae(!0);const I={id:`local:${zs()}`,role:"user",content:k,ts:jt()};Ue(q=>[...q,I]),wr("");try{const q=DN(ke,I),W=n.maintenance_ai_provider.trim(),V=n.maintenance_ai_model.trim(),te=await Oe.run_chat(g,{provider:W||void 0,model:V||void 0,include_subruns:!0,messages:q}),$e=String((te==null?void 0:te.answer)||"").trim()||"(empty response)",he=String((te==null?void 0:te.generated_at)||"").trim()||jt();at((te==null?void 0:te.history)??null),Ue(pe=>[...pe,{id:`local:${zs()}`,role:"assistant",content:$e,ts:he}])}catch(q){const W=uC(q);Ws(W),Ue(V=>[...V,{id:`local:${zs()}`,role:"assistant",content:`(error: ${W})`,ts:jt(),local_error:!0}])}finally{ae(!1)}}function m_(g){const k=String(g.id||g.ts||"").trim(),$=String(g.content||"").trim();!k||!$||(Go(""),Mn.toggle_tts(k,$))}function vh(g){const k=String(g.id||g.ts||"").trim(),$=Mn.tts_playback;return!k||!$.key||$.key!==k?"idle":$.status}function Id(g){if(!ke.length)return;const k=c.trim(),$=k?`Run ${k}`:"Chat",I=jj(ke.map(q=>({role:q.role,content:q.content,ts:q.ts})),{heading:$});if(g==="download"){const q=new Date().toISOString().slice(0,19).replace(/[:T]/g,"-"),W=`abstractobserver-chat-${H_(k||"run")}-${q}.md`;Sj({filename:W,text:I,mime:"text/markdown;charset=utf-8"});return}(async()=>{const q=await ic(I);Ne(q?"copied":"failed"),window.setTimeout(()=>Ne("idle"),900)})()}async function Qc(){const g=typeof(xe==null?void 0:xe.workflow_id)=="string"?String(xe.workflow_id).trim():"";if(!g){Qr([]);return}if(N&&!Ri){uc(""),Ra(!0);try{const k=await Oe.list_runs({limit:200,workflow_id:g,root_only:!0}),$=Array.isArray(k==null?void 0:k.items)?k.items:[],I=[];for(const he of $){const pe=typeof(he==null?void 0:he.run_id)=="string"?String(he.run_id).trim():"";if(!pe)continue;const Ce=typeof(he==null?void 0:he.ledger_len)=="number"?Number(he.ledger_len):0;I.push({run_id:pe,ledger_len:Number.isFinite(Ce)?Ce:0})}if(!I.length){Qr([]);return}const q=400,W=I.map(he=>({run_id:he.run_id,after:Math.max(0,(he.ledger_len||0)-q)})),V=await Oe.get_ledger_batch({runs:W,limit:q}),te=[],$e=new Set;for(const he of I){const pe=V!=null&&V.runs&&typeof V.runs=="object"?V.runs[he.run_id]:null,Ce=Array.isArray(pe==null?void 0:pe.items)?pe.items:[];for(const ze of Ce){const Ie=ze==null?void 0:ze.effect;if(!Ie||typeof Ie!="object"||String(Ie.type||"")!=="emit_event")continue;const Ze=Ie.payload;if(!Ze||typeof Ze!="object"||String(Ze.name||"")!=="abstract.chat.thread")continue;const Ge=Ze.payload;if(!Ge||typeof Ge!="object")continue;const cn=typeof Ge.thread_id=="string"?String(Ge.thread_id).trim():"";if(!cn||$e.has(cn))continue;$e.add(cn);const Rt=typeof Ge.created_at=="string"?String(Ge.created_at):"",qe=typeof Ge.title=="string"?String(Ge.title):"",xt=typeof Ge.workflow_id=="string"?String(Ge.workflow_id):g,Nn=typeof Ge.run_id=="string"?String(Ge.run_id):he.run_id,Qt=typeof Ge.provider=="string"?String(Ge.provider):"",Ds=typeof Ge.model=="string"?String(Ge.model):"",Hr=typeof Ge.message_count=="number"?Number(Ge.message_count):null,fs=Ge.chat_artifact,Fo=fs&&typeof fs=="object"&&typeof fs.$artifact=="string"?String(fs.$artifact):"";Fo&&te.push({thread_id:cn,created_at:Rt,title:qe||`Chat ${cn.slice(0,8)}`,run_id:Nn,workflow_id:xt,message_count:Hr,provider:Qt,model:Ds,artifact_id:Fo})}}te.sort((he,pe)=>String(pe.created_at||"").localeCompare(String(he.created_at||""))),Qr(te)}catch(k){uc(String((k==null?void 0:k.message)||k||"Failed to load saved discussions"))}finally{Ra(!1)}}}async function xh(){const g=c.trim();if(!g){Mt("Select a run first.");return}if(!N){Mt("Connect to the gateway first.");return}if(ke.length&&!Ft){Mt(""),Gt(!0);try{const k=n.maintenance_ai_provider.trim(),$=n.maintenance_ai_model.trim(),I=await Oe.save_chat_thread(g,{provider:k||void 0,model:$||void 0,include_subruns:!0,messages:ke.map(V=>({role:V.role,content:V.content,ts:V.ts}))}),q=typeof(I==null?void 0:I.created_at)=="string"?String(I.created_at):jt();En(q);try{const V=JSON.stringify(ke.map(te=>({role:te.role,content:te.content,ts:te.ts})));Zn(V)}catch{Zn("1")}typeof(I==null?void 0:I.thread_id)=="string"&&String(I.thread_id).trim()&&dc(String(I.thread_id).trim());const W=!!(I!=null&&I.duplicate);Pn(W?"Already saved":"Saved discussion",2),await Qc()}catch(k){Mt(String((k==null?void 0:k.message)||k||"Failed to save discussion"))}finally{Gt(!1)}}}async function bh(){const g=String(vl||"").trim();if(!g)return;const k=nr.find(q=>String(q.thread_id||"").trim()===g)||null;if(!k){Yo("Saved discussion not found (refresh list).");return}if(!N){Yo("Connect to the gateway first.");return}if(fc)return;const $=ke.length>0,I=(()=>{if(!$)return!1;if(!_n)return!0;try{return JSON.stringify(ke.map(W=>({role:W.role,content:W.content,ts:W.ts})))!==_n}catch{return!0}})();if(!($&&I&&!window.confirm("Replace the current chat with the selected saved discussion? Unsaved changes will be lost."))){Yo(""),hc(!0);try{const W=await(await Oe.download_run_artifact_content(k.run_id,k.artifact_id)).text(),V=JSON.parse(W),te=Array.isArray(V==null?void 0:V.messages)?V.messages:[],$e=typeof(V==null?void 0:V.created_at)=="string"?String(V.created_at):String(k.created_at||""),he=[];for(let pe=0;pe<te.length;pe++){const Ce=te[pe];if(!Ce||typeof Ce!="object")continue;const ze=String(Ce.role||"").trim()==="assistant"?"assistant":"user",Ie=typeof Ce.content=="string"?String(Ce.content):"";if(!Ie.trim())continue;const Ze=typeof Ce.ts=="string"?String(Ce.ts):$e||jt();he.push({id:`thread:${g}:${pe}`,role:ze,content:Ie.trim(),ts:Ze})}Ue(he),at(null),wr(""),Ws(""),Mt(""),En($e||"");try{const pe=JSON.stringify(he.map(Ce=>({role:Ce.role,content:Ce.content,ts:Ce.ts})));Zn(pe)}catch{Zn("1")}Pn("Loaded discussion",2)}catch(q){Yo(String((q==null?void 0:q.message)||q||"Failed to load saved discussion"))}finally{hc(!1)}}}async function eu(g){const k=c.trim(),$=String((zt==null?void 0:zt.wait_key)||"").trim();if(!k||!$){nn("No active wait to resume");return}if(String((zt==null?void 0:zt.reason)||"").trim()==="subworkflow"){nn("This run is waiting on a subworkflow; attach to the child run instead of resuming manually.");return}nn(""),an(!0);try{await Oe.submit_command({command_id:zs(),run_id:k,type:"resume",payload:{wait_key:$,payload:g||{}},client_id:"web_pwa"}),Kt({ts:jt(),kind:"info",title:"Resume submitted",preview:ht(`wait_key: ${$}`),data:{wait_key:$,payload:g||{}}}),Zr($);try{const I=await Oe.get_run(k);Yn(I)}catch{}Ms(Oe,{force:!0}),window.setTimeout(()=>void Ms(Oe,{force:!0}),900),window.setTimeout(()=>void Ms(Oe,{force:!0}),2400),tr.current&&window.clearTimeout(tr.current),tr.current=window.setTimeout(()=>{Zr(I=>I===$?"":I)},2e3)}catch(I){nn(String((I==null?void 0:I.message)||I||"resume failed"))}finally{an(!1)}}async function lr(g){if(!Ya){nn("No worker configured");return}if(!Et){nn(""),an(!0);try{const k=[];for(const $ of g){const I=await Ya.call_tool($);k.push(I)}await eu({mode:"executed",results:k})}finally{an(!1)}}}const Hn=m.useMemo(()=>Uu(zt),[zt]),Ls=String((zt==null?void 0:zt.wait_key)||"").trim(),us=String((zt==null?void 0:zt.reason)||"").trim(),ni=typeof(zt==null?void 0:zt.until)=="string"?String(zt.until):"",Wi=typeof(xe==null?void 0:xe.status)=="string"?String(xe.status):"",qi=!!(xe!=null&&xe.paused),Br=Wi==="completed"||Wi==="failed"||Wi==="cancelled",jh=us==="until"&&!!ni,tl=!Br&&PC(Ts)&&(!!Ls||jh),Sh=us==="user",tu=us==="event"?_f(gL(Ls)):"",Od=us==="event"&&tu==="abstract.ask",Pd=Hn.length>0,Dd=tl&&Ls&&(Sh||Od||Pd)&&Ho!==Ls&&e!=="board",Hi=typeof((Vs=zt==null?void 0:zt.details)==null?void 0:Vs.sub_run_id)=="string"?String(zt.details.sub_run_id):"",Mo={run_id:c.trim(),workflow_id:typeof(xe==null?void 0:xe.workflow_id)=="string"?String(xe.workflow_id):null,status:Wi,created_at:typeof(xe==null?void 0:xe.created_at)=="string"?String(xe.created_at):null,updated_at:typeof(xe==null?void 0:xe.updated_at)=="string"?String(xe.updated_at):null,session_id:typeof(xe==null?void 0:xe.session_id)=="string"?String(xe.session_id):null,current_node:typeof(xe==null?void 0:xe.current_node)=="string"?String(xe.current_node):null},kh=$t.slice(-10).map(g=>{var k,$,I,q,W,V;return{cursor:g.cursor,node_id:String(((k=g.record)==null?void 0:k.node_id)||"").trim(),status:String((($=g.record)==null?void 0:$.status)||"").trim(),effect_type:String(((q=(I=g.record)==null?void 0:I.effect)==null?void 0:q.type)||"").trim(),ts:String(((W=g.record)==null?void 0:W.ended_at)||((V=g.record)==null?void 0:V.started_at)||"").trim(),summary:Vx(g.record)}}),Fd=$g(zt,Hn),zd=Ux(zt,Hn),Bd=Wx(zt,it),Vi=Bd.text,Gi=Bd.runtime_metadata,nu=String((zt==null?void 0:zt.prompt)||"").trim(),Ud=bC(it,6),Wd=!!(nu&&Fx(nu)),su=!!(nu&&!Wd),Nh=su?"Question from workflow":Vi&&Vi!==nu?"Closest prior user request":"Request context",Fl=kC(it,A),Is=!!A.trim(),xr=xe!=null&&xe.schedule&&typeof xe.schedule=="object"?xe.schedule:null,nl=typeof(xr==null?void 0:xr.interval)=="string"?String(xr.interval).trim():"",ru=typeof(xr==null?void 0:xr.share_context)=="boolean"?!!xr.share_context:null,xs=typeof(xr==null?void 0:xr.repeat_count)=="number"?Number(xr.repeat_count):null,br=!!(xe!=null&&xe.is_scheduled)||!!xr,Je=br&&!!nl,ma=br?qi?"Resume schedule":"Suspend schedule":Wi==="running"&&!qi?"Pause":"Resume",iu=br?qi?"resume":"pause":ma==="Pause"?"pause":"resume",Ch=br?!c.trim()||Ee||Et||Br:!c.trim()||Ee||Et||Br||iu==="resume"&&!qi,__=br&&!qi&&!Br&&!Ee&&!Et&&Wi.toLowerCase()==="waiting"&&(String(((Yd=xe==null?void 0:xe.waiting)==null?void 0:Yd.reason)||"").trim().toLowerCase()==="until"||us==="until")&&!!String(ni||"").trim(),bs=(hu=xe==null?void 0:xe.limits)==null?void 0:hu.tokens,Ro=typeof(bs==null?void 0:bs.pct)=="number"?Number(bs.pct):null,ou=bs==null?void 0:bs.estimated_used,qd=(bs==null?void 0:bs.max_input_tokens)??(bs==null?void 0:bs.max_tokens),Eh=m.useMemo(()=>{const g=lo.current;$t.length<g.scanned&&(g.scanned=0,g.found=null);for(let k=g.scanned;k<$t.length;k++){const $=$t[k],I=$==null?void 0:$.record;if(!I)continue;const q=Gh(I);if((q&&q.name?_f(q.name):"")!=="abstract.summary")continue;const V=q!=null&&q.payload&&typeof q.payload=="object"?q.payload:{},te=typeof(V==null?void 0:V.text)=="string"?String(V.text):"";te.trim()&&(g.found={cursor:$.cursor,ts:String((I==null?void 0:I.ended_at)||(I==null?void 0:I.started_at)||""),text:te,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 g.scanned=$t.length,g.found},[$t]);m.useEffect(()=>{vr.current=mi.trim()},[mi]),m.useEffect(()=>{const g=c.trim(),k=Hi.trim();if(!(pt&&us==="subworkflow"&&!!k&&k!==g)){ea.current="",mi.trim()&&Pi("");return}ea.current!==k&&(ea.current=k,vr.current=k,Pi(k))},[pt,c,us,Hi,mi]),m.useEffect(()=>{xo({})},[j]);const Hd=m.useMemo(()=>((Array.isArray(M==null?void 0:M.entrypoints)?M==null?void 0:M.entrypoints:[])||[]).map(k=>String((k==null?void 0:k.flow_id)||"").trim()).filter(Boolean),[M]),si=m.useMemo(()=>{const g=String((xe==null?void 0:xe.workflow_id)||"").trim();return pt&&br?g:""},[pt,br,xe==null?void 0:xe.workflow_id]),Vd=m.useMemo(()=>{var V;if(!pt||!c.trim()||!si.trim())return ci;const g=String((xe==null?void 0:xe.status)||"").trim().toLowerCase(),k=String((xe==null?void 0:xe.current_node)||"").trim();if(g!=="waiting"&&g!=="running"||!k)return ci;const $=ar(c.trim(),k);if(!$)return ci;const I=String(us||((V=xe==null?void 0:xe.waiting)==null?void 0:V.reason)||"").trim().toLowerCase(),q=typeof(Ts==null?void 0:Ts.node_id)=="string"?String(Ts.node_id).trim():"",W=typeof(Ts==null?void 0:Ts.status)=="string"?String(Ts.status).trim().toLowerCase():"";return g==="waiting"&&I==="until"||!ci.trim()||(W==="waiting"||W==="running")&&!q?$:ci},[pt,c,si,xe==null?void 0:xe.status,xe==null?void 0:xe.current_node,(mu=xe==null?void 0:xe.waiting)==null?void 0:mu.reason,us,ci,Ts]),js=m.useMemo(()=>{const g={},k=c.trim(),$=(I,q)=>{if(!q)return;const W=typeof(q==null?void 0:q.node_id)=="string"?String(q.node_id).trim():"";if(!W)return;const V=ar(I,W);if(!V)return;const te=String((q==null?void 0:q.ended_at)||(q==null?void 0:q.started_at)||"").trim(),$e=Cn(te);$e!==null&&(g[V]=Math.max(g[V]||0,$e))};for(const I of $t)I&&I.record&&$(k,I.record);for(const I of os)I&&I.record&&$(String(I.run_id||"").trim(),I.record);return g},[$t,os,c,fi]);m.useEffect(()=>{var $;if(!pt||!c.trim()||!si.trim())return;const g=String((xe==null?void 0:xe.current_node)||"").trim();!g||String((($=xe==null?void 0:xe.waiting)==null?void 0:$.reason)||"").trim()==="subworkflow"||Jc(ar(c.trim(),g))},[pt,c,si,xe==null?void 0:xe.current_node,(Th=xe==null?void 0:xe.waiting)==null?void 0:Th.reason]),m.useEffect(()=>{const g=String((In==null?void 0:In.flow_id)||"").trim();g&&(Jo.trim()||Pa(g))},[In,Jo]),m.useEffect(()=>{const g=si.trim(),k=j.trim(),$=Jo.trim();if(g){let q=!1;return Li(!0),Da(""),Oe.get_workflow_flow(g).then(W=>{if(q)return;const V=W==null?void 0:W.flow;Sl(V&&typeof V=="object"?V:null)}).catch(W=>{q||(Sl(null),Da(String((W==null?void 0:W.message)||W||"Failed to load workflow flow")))}).finally(()=>{q||Li(!1)}),()=>{q=!0}}if(!k||!$){Sl(null),Da(""),Li(!1);return}let I=!1;return Li(!0),Da(""),Oe.get_bundle_flow(k,$).then(q=>{if(I)return;const W=q==null?void 0:q.flow,V=W&&typeof W=="object"?W:null;Sl(V),V&&xo(te=>({...te,[$]:V}))}).catch(q=>{I||(Sl(null),Da(String((q==null?void 0:q.message)||q||"Failed to load flow")))}).finally(()=>{I||Li(!1)}),()=>{I=!0}},[si,j,Jo,Oe]),m.useEffect(()=>{const g=j.trim();if(!Xo||!g||!vo)return;let k=!1;const $=3,I=he=>{const pe=Array.isArray(he==null?void 0:he.nodes)?he.nodes:[],Ce=[];for(const ze of pe){const Ie=ze!=null&&ze.data&&typeof ze.data=="object"?ze.data:{};if(String((Ie==null?void 0:Ie.nodeType)||(ze==null?void 0:ze.type)||"").trim()!=="subflow")continue;const Ge=(Ie==null?void 0:Ie.subflowId)||(Ie==null?void 0:Ie.flowId),cn=typeof Ge=="string"?Ge.trim():"";cn&&Ce.push(cn.includes(":")?cn.split(":",2)[1]:cn)}return Ce},q=new Set,W=new Set,V=(he,pe)=>{if(!(!he||pe>=$))for(const Ce of I(he)){const ze=String(Ce||"").trim();if(!ze||q.has(ze))continue;q.add(ze),W.add(ze);const Ie=vc[ze];Ie&&V(Ie,pe+1)}};V(vo,0);const te=Array.from(W).filter(he=>!vc[he]).slice(0,20);return te.length?((async()=>{for(const he of te){if(k)return;try{const pe=await Oe.get_bundle_flow(g,he),Ce=pe==null?void 0:pe.flow,ze=Ce&&typeof Ce=="object"?Ce:null;if(!ze)continue;xo(Ie=>Ie[he]?Ie:{...Ie,[he]:ze})}catch{}}})(),()=>{k=!0}):void 0},[Xo,j,vo,vc,Oe]);const Ur=m.useMemo(()=>{const k=(Array.isArray(M==null?void 0:M.flows)?M==null?void 0:M.flows:[]).map($=>String($||"").trim()).filter(Boolean);return k.length?Array.from(new Set(k)).sort():Array.from(new Set(Hd)).sort()},[M,Hd]);m.useEffect(()=>{Br&&ci.trim()&&(Zo(""),bo.current="")},[Br,c,ci]),m.useEffect(()=>{const g=mi.trim(),k=c.trim();if(!(pt&&!!g&&g!==k)){Hs.current&&Hs.current.abort(),Hs.current=null,Oi.current=0,Nc&&Cc("");return}if(Nc===g)return;Hs.current&&Hs.current.abort();const I=new AbortController;Hs.current=I,Oi.current=0,Cc(g),Kt({ts:jt(),kind:"info",title:`Following run ${g} (status/events)`});let q=250;return(async()=>{for(;!I.signal.aborted;){try{await Oe.stream_ledger(g,{after:Oi.current,on_step:V=>d_(g,V),signal:I.signal});return}catch(V){if(I.signal.aborted)break;const te=String((V==null?void 0:V.message)||V||"stream error");Kt({ts:jt(),kind:"error",title:"Child ledger stream error (will retry)",preview:ht(te),data:{child_run_id:g,error:te}})}if(I.signal.aborted)break;await new Promise(V=>setTimeout(V,q)),q=Math.min(5e3,Math.floor(q*1.6))}})(),()=>{I.abort()}},[pt,mi,c,Oe,Nc]),m.useEffect(()=>{if(!pt||!c.trim())return;let g=!1;const k=async()=>{if(!g&&!ta.current&&fi.length&&!(He.current>Date.now())){ta.current=!0;try{const I=fi.map(te=>String(te||"").trim()).filter(Boolean);if(!I.length)return;const q=I.map(te=>({run_id:te,after:Number(hi.current[te]||0)})),W=await Oe.get_ledger_batch({runs:q,limit:200}),V=W&&typeof W=="object"?W.runs:{};for(const te of I){if(g)return;const $e=V&&typeof V=="object"?V[te]:null,he=Array.isArray($e==null?void 0:$e.items)?$e.items:[],pe=typeof($e==null?void 0:$e.next_after)=="number"?$e.next_after:Number(hi.current[te]||0),Ce=Number(hi.current[te]||0);for(let ze=0;ze<he.length;ze++){const Ie=he[ze];f_(te,{cursor:Ce+ze+1,record:Ie})}hi.current[te]=pe}}catch(I){if(g)return;Kt({ts:jt(),kind:"error",title:"Subrun digest poll failed",preview:ht(String((I==null?void 0:I.message)||I||""))})}finally{ta.current=!1}}};k();const $=window.setInterval(()=>void k(),2e3);return()=>{g=!0,window.clearInterval($),ta.current=!1}},[pt,c,fi,Oe]);const xi=m.useMemo(()=>xl?Gu.filter(xL):Gu,[xl,Gu]),ri=m.useMemo(()=>{const g=c.trim(),k=[];for(const $ of $t)!$||!$.record||k.push({run_id:g,cursor:$.cursor,record:$.record});for(const $ of os)!$||!$.record||k.push({run_id:String($.run_id||"").trim(),cursor:$.cursor,record:$.record});return k},[$t,os,c]),zl=m.useMemo(()=>{var k,$,I;const g={};for(const q of ri){const W=String(q.run_id||((k=q.record)==null?void 0:k.run_id)||"").trim();!W||String(((I=($=q.record)==null?void 0:$.effect)==null?void 0:I.type)||"").trim()!=="llm_call"||(g[W]=(g[W]||0)+1)}return g},[ri]),ii=m.useMemo(()=>{const g=mi.trim();if(g)return g;let k="",$=-1;for(const[I,q]of Object.entries(zl))q>$&&(k=I,$=q);return k||c.trim()},[zl,mi,c]),Ki=(Vf.trim()||ii).trim(),Wr=m.useMemo(()=>{var q;const g=new Set,k=c.trim(),$=mi.trim();k&&g.add(k),$&&g.add($);for(const W of fi){const V=String(W||"").trim();V&&g.add(V)}for(const W of ri){const V=String(W.run_id||((q=W.record)==null?void 0:q.run_id)||"").trim();V&&g.add(V)}const I=Array.from(g);return I.sort((W,V)=>k&&W===k&&V!==k?-1:k&&V===k&&W!==k?1:$&&W===$&&V!==$?-1:$&&V===$&&W!==$?1:W<V?-1:W>V?1:0),I},[c,mi,fi,ri]),Gd=m.useMemo(()=>yj(ri,{run_id:Ki}),[ri,Ki]),Jn=m.useMemo(()=>{const g=c.trim();return g&&(Fn.find(k=>String(k.run_id||"").trim()===g)||Tt.find(k=>String(k.run_id||"").trim()===g))||null},[Fn,Tt,c]),_a=String((xe==null?void 0:xe.status)||(Jn==null?void 0:Jn.status)||"").trim(),$h=String(us||((Qi=xe==null?void 0:xe.waiting)==null?void 0:Qi.reason)||(Jn==null?void 0:Jn.waiting_reason)||"").trim().toLowerCase(),Kd=!!(xe!=null&&xe.is_scheduled||Jn!=null&&Jn.is_scheduled),Ah=!!(xe!=null&&xe.paused||Jn!=null&&Jn.paused),Bl=Kd&&_a.toLowerCase()==="waiting",au=Bl&&$h==="until",jr=Cn(ni),Zt=au&&jr!==null?Ky(jr-Date.now()):"",Un=wC(xe),Dn=Kd&&Ah?"Suspended":Bl?"Scheduled":Nm({status:_a,paused:Ah,stop_reason:Un});async function ds(){if(N){sh(!0),Wa("");try{const g=ra,k=g==="session"?String(ei||zr||O||"").trim():"",$=g==="run"?String(zi||c||"").trim():"",I=MC(es),q=ln.length?ln.join(","):"",W=RC(ys),V=Math.max(0,ia)*am,te=await Oe.search_artifacts({scope:g,session_id:k||void 0,run_id:$||void 0,query:pi||void 0,artifact_kind:q||void 0,created_after:I||void 0,include_stats:!0,limit:am,offset:V,order_by:W.order_by,order:W.order}),$e=[],he=new Set;for(const Ze of Array.isArray(te==null?void 0:te.items)?te.items:[]){const Ge=$C(Ze,"search");!Ge||he.has(Ge.artifact_id)||(he.add(Ge.artifact_id),$e.push(Ge))}const pe=te!=null&&te.stats&&typeof te.stats=="object"?te.stats:{},Ce=Number((pe==null?void 0:pe.total)??(te==null?void 0:te.total)??$e.length),ze=Xy(te);let Ie=ze;if(ln.length)try{const Ze=await Oe.search_artifacts({scope:g,session_id:k||void 0,run_id:$||void 0,query:pi||void 0,created_after:I||void 0,include_stats:!0,limit:1,offset:0,order_by:W.order_by,order:W.order});Ie=Xy(Ze)}catch{Ie=ze}Di(Number.isFinite(Ce)?Math.max(0,Ce):$e.length),na(Number((pe==null?void 0:pe.total_bytes)??(pe==null?void 0:pe.byte_total)??0)||0),Ua(ze),Ac(Ie),th($e),Va(Ze=>{var Ge;return Ze&&$e.some(cn=>cn.artifact_id===Ze)?Ze:((Ge=$e[0])==null?void 0:Ge.artifact_id)||""})}catch(g){Wa(String((g==null?void 0:g.message)||g||"Failed to load artifacts")),th([]),Di(0),na(0),Ua({}),Ac({}),Va("")}finally{sh(!1)}}}async function cr(){if(N){hd(!0),md("");try{const g=await Oe.audit_log_tail({max_bytes:16e4}),k=typeof(g==null?void 0:g.bytes)=="number"?Number(g.bytes):0,$=!!(g!=null&&g.truncated);fd(String((g==null?void 0:g.content)||"")),Ic(`${k.toLocaleString()} bytes${$?" (tail)":""}`)}catch(g){md(String((g==null?void 0:g.message)||g||"Failed to load audit log")),fd(""),Ic("")}finally{hd(!1)}}}async function pa(g){if(!N)return;const k=String(g||ko||zi||c||"").trim();if(!k){Fc([]),Co(""),Eo("Select a run in Activity or Artifacts to load its runtime ledger.");return}Rl(!0),Eo("");try{const $=await Oe.get_ledger(k,{after:0,limit:2e3}),I=Array.isArray($.items)?$.items:[];Fc(I.map((W,V)=>({cursor:V+1,record:W})));const q=typeof $.next_after=="number"?Number($.next_after):I.length;Co(`${I.length.toLocaleString()} record${I.length===1?"":"s"}${q>=2e3?" (first 2,000)":""}`)}catch($){Eo(String(($==null?void 0:$.message)||$||"Failed to load run ledger")),Fc([]),Co("")}finally{Rl(!1)}}m.useEffect(()=>{N&&e==="runtime"&&ds()},[N,e,ra,ei,zi,pi,ln,es,ys,ia]),m.useEffect(()=>{N&&(Oc||Or||e==="runtime"&&cr())},[N,e,Qn]),m.useEffect(()=>{if(!N||e!=="runtime"||$l!=="logs"||Bi!=="run_ledger"&&Bi!=="provider_calls")return;const g=String(ko||zi||c||"").trim();g&&pa(g)},[N,e,$l,Bi,ko,zi,c]);const kn=m.useMemo(()=>{const g=new Map;for(const k of[...Tt,...Fn]){const $=String(k.run_id||"").trim();$&&g.set($,k)}for(const k of fi){const $=String(k||"").trim();!$||g.has($)||g.set($,{run_id:$,workflow_id:null,status:"",created_at:null,updated_at:null,ledger_len:null,parent_run_id:di.current[$]||null,session_id:zr||null})}return c.trim()&&!g.has(c.trim())&&g.set(c.trim(),{run_id:c.trim(),workflow_id:typeof(xe==null?void 0:xe.workflow_id)=="string"?String(xe.workflow_id):null,status:typeof(xe==null?void 0:xe.status)=="string"?String(xe.status):"",created_at:typeof(xe==null?void 0:xe.created_at)=="string"?String(xe.created_at):null,updated_at:typeof(xe==null?void 0:xe.updated_at)=="string"?String(xe.updated_at):null,ledger_len:$t.length||null,parent_run_id:typeof(xe==null?void 0:xe.parent_run_id)=="string"?String(xe.parent_run_id):null,session_id:typeof(xe==null?void 0:xe.session_id)=="string"?String(xe.session_id):zr||null}),Array.from(g.values()).sort((k,$)=>{const I=Cn(k.updated_at||k.created_at)??0;return(Cn($.updated_at||$.created_at)??0)-I})},[Fn,Tt,c,xe,$t.length,fi,zr]),Ul=m.useMemo(()=>u2(kn,{query:Xu,filter:Zu,group_by:Qu,workflow_label_by_id:or,parent_hint:g=>di.current[g]||""}),[kn,Xu,Zu,Qu,or]),ga=m.useMemo(()=>Gx(ri),[ri]),lu=m.useMemo(()=>{const g=[...ri];return g.sort((k,$)=>{var W,V,te,$e;const I=Cn(((W=k.record)==null?void 0:W.ended_at)||((V=k.record)==null?void 0:V.started_at))??0,q=Cn(((te=$.record)==null?void 0:te.ended_at)||(($e=$.record)==null?void 0:$e.started_at))??0;return I-q}),g.slice(-240)},[ri]),Yi=m.useMemo(()=>{const g={};for(const k of kn){const $=String(k.run_id||"").trim();$&&(g[$]=k)}return g},[kn]),ya=String(ko||zi||c||"").trim(),Os=ya&&Yi[ya]||null,cu=String(ei||(Os==null?void 0:Os.session_id)||zr||O||"").trim(),wa=m.useMemo(()=>cd.map(g=>Em(g,Yi,or)),[cd,Yi,or]);m.useEffect(()=>{Rc(0)},[pi,ln,es,zi,ys,Rr,ra,ei]);const Ji=Math.max(1,Math.ceil($c/am)),Lo=Math.min(Math.max(0,ia),Ji-1);m.useEffect(()=>{ia!==Lo&&Rc(Lo)},[ia,Lo]);const Xi=m.useMemo(()=>wa,[wa,Lo]),Io=m.useMemo(()=>{const g={};for(const k of Xi){const $=Rr==="type"?qp(k,Yi,or):AC(k,Rr);g[$]||(g[$]=[]),g[$].push(k)}return Object.entries(g).map(([k,$])=>({key:k,items:$})).sort((k,$)=>{var I,q;if(Rr==="time"){const W=Cn((I=k.items[0])==null?void 0:I.created_at)??0,V=Cn((q=$.items[0])==null?void 0:q.created_at)??0;if(W!==V)return V-W}return k.key.localeCompare($.key)})},[Xi,Rr,Yi,or]),Oo=m.useMemo(()=>{const g=gi.trim();return g?Xi.find(k=>k.artifact_id===g)||Xi[0]||null:Xi[0]||null},[Xi,gi]);m.useEffect(()=>{e!=="runtime"||$l!=="artifacts"||_h(Oo)},[e,$l,Oo==null?void 0:Oo.artifact_id]),m.useEffect(()=>()=>{Ga.url&&URL.revokeObjectURL(Ga.url)},[Ga.url]);const Po=m.useMemo(()=>kn.filter(g=>Pu(g.status)),[kn]);m.useEffect(()=>{if(e!=="settings"&&e!=="launch"||!N||T)return;let g=!1;return(async()=>{const[k,$]=await Promise.all([Oe.list_skills(),Oe.list_mcp_servers()]);g||(G(k),J($),Q(!0))})(),()=>{g=!0}},[e,N,T]);const uu=[{id:"board",label:"Board",icon:s.jsx(Qe,{name:"board",size:16})},{id:"observe",label:"Observe",icon:s.jsx(Qe,{name:"history",size:16})},{id:"runtime",label:"System",icon:s.jsx(Qe,{name:"server",size:16})},{id:"launch",label:"Launch",icon:s.jsx(Qe,{name:"send",size:16})},{id:"automations",label:"Automations",icon:s.jsx(Qe,{name:"refresh",size:16})}],Wl={board:"Board",observe:"Observe",runtime:"System",launch:"Launch",automations:"Automations",settings:"Settings"},du=s.jsxs(s.Fragment,{children:[Ui?s.jsxs("details",{className:"launch_capabilities",style:{marginTop:"10px"},children:[s.jsxs("summary",{className:"help_text muted",style:{cursor:"pointer"},children:["Capabilities",Dr.length?` · ${Dr.length} skill${Dr.length===1?"":"s"}`:""]}),s.jsx("div",{className:"help_text muted",style:{fontSize:"var(--font-size-sm)",marginTop:"8px"},children:"Skills attach knowledge procedures to this run. The gateway resolves selections through the trust gate at start: validated skills activate, unverified ones are held for review, blocked ones never ride."}),z===null?s.jsx("div",{className:"help_text muted",style:{marginTop:"8px"},children:"This gateway does not serve a skills inventory yet — the shelf lights up here when it ships."}):z.length?s.jsx("div",{className:"launch_skill_list",children:z.map(g=>{var q;const k=Dr.includes(g.name),$=g.blocked===!0,I=g.requires_review===!0&&!$;return s.jsxs("label",{className:`launch_skill_row ${$?"is_blocked":""} ${k?"is_on":""}`,title:[g.description||"",g.tree_hash?`tree ${g.tree_hash.slice(0,16)}…`:"",$&&((q=g.reasons)!=null&&q.length)?`blocked: ${g.reasons.join("; ")}`:""].filter(Boolean).join(`
|
|
144
|
+
`),children:[s.jsx("input",{type:"checkbox",checked:k,disabled:$||Ee||Et||lt,onChange:W=>{const V=W.target.checked?Array.from(new Set([...Dr,g.name])):Dr.filter(te=>te!==g.name);vn("skills",V.length?V:void 0)}}),s.jsx("span",{className:"launch_skill_name",children:g.name}),g.trust_level?s.jsx("span",{className:`chip ${$?"danger":I?"warn":"muted"}`,children:$?"blocked":I?"review":g.trust_level}):null,g.description?s.jsx("span",{className:"launch_skill_desc",children:g.description}):null]},g.name)})}):s.jsx("div",{className:"help_text muted",style:{marginTop:"8px"},children:"The gateway's skills shelf is empty."}),Dr.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:{fontSize:"var(--font-size-sm)",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:ca,onChange:g=>vn("workspace_root",g.target.value),placeholder:"/path/to/workspace",disabled:Ee||Et}),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:(Uc||"workspace_only").trim()||"workspace_only",onChange:g=>vn("workspace_access_mode",g.target.value),disabled:Ee||Et,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."})]})]}),(Uc||"").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:Xa,onChange:g=>vn("workspace_allowed_paths",g.target.value),placeholder:`/path/to/project
|
|
145
|
+
/path/to/workspace`,disabled:Ee||Et,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:lh,onChange:g=>vn("workspace_ignored_paths",g.target.value),placeholder:`node_modules
|
|
146
|
+
runtime
|
|
147
|
+
secret`,disabled:Ee||Et,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:mr,type:"file",accept:".flow",style:{display:"none"},onChange:g=>{const k=g.target.files&&g.target.files.length?g.target.files[0]:null;k&&uh(k)}}),s.jsx("button",{type:"button",className:"btn launch_btn_upload",onClick:()=>{var g;return(g=mr.current)==null?void 0:g.click()},disabled:!N||ie||Ei||Ee||Et,title:"Upload a .flow bundle",children:Ei?"…":"Upload .flow"}),s.jsxs("button",{type:"button",className:"btn launch_btn_reload",onClick:()=>void jd(),disabled:!N||ie||ut||Ee||Et,title:"Reload picks up server-side edits",children:[s.jsx(Qe,{name:"refresh",size:14}),ut?"…":"Reload bundles"]})]})]})]});function ql(g){t("observe"),qs("overview"),vs(g)}const fu={on_select:g=>void Bn.select(g),on_row_action:(g,k)=>{if(k==="discuss"||k==="edit")throw new Error(`${k} is routed by AutomationsPage (route_row_action), not the app handlers.`);if(k==="archive"){Bn.ask_archive(g.automation_id);return}Bn.row_action(g,k)},on_legacy_action:(g,k)=>{if(k==="open_run"){ql(g.automation_id);return}if(k==="recreate"){yh(g.automation_id).catch($=>Bn.report_error($));return}Bn.legacy_action(g,k)},on_confirm_archive:g=>void Bn.row_action(g,"archive"),on_cancel_archive:()=>Bn.ask_archive(""),on_status_filter:g=>void Bn.set_status_filter(g),on_refresh:()=>void Bn.refresh(),on_new:()=>{fe("automate"),t("launch")},on_show_archived:g=>Bn.set_show_archived(g)};return s.jsxs("div",{className:"app-shell shell",children:[s.jsxs("aside",{className:"shell_sidebar",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.jsxs("nav",{className:"shell_nav",children:[uu.map(g=>s.jsxs("button",{className:`shell_nav_item ${e===g.id?"active":""}`,onClick:()=>t(g.id),type:"button",children:[s.jsx("span",{className:"shell_nav_icon",children:g.icon}),s.jsx("span",{className:"shell_nav_label",children:g.label})]},g.id)),s.jsxs("a",{className:"shell_nav_item",href:l,target:"_blank",rel:"noreferrer",title:"Open the entity app (memory graph + visits)",children:[s.jsx("span",{className:"shell_nav_icon",children:s.jsx(Qe,{name:"bot",size:16})}),s.jsx("span",{className:"shell_nav_label",children:"Entities ↗"})]}),s.jsxs("button",{className:`shell_nav_item ${e==="settings"?"active":""}`,onClick:()=>t("settings"),type:"button",children:[s.jsx("span",{className:"shell_nav_icon",children:s.jsx(Qe,{name:"settings",size:16})}),s.jsx("span",{className:"shell_nav_label",children:"Settings"})]})]}),s.jsx("div",{className:"shell_sidebar_footer",children:s.jsxs("div",{className:"shell_connection shell_connection_passive",title:N?"Gateway connected":ie?"Gateway: connecting…":"Gateway: signed out",children:[s.jsx("span",{className:`gateway_led ${N?"ok":ie?"warn":"err"}`,"aria-hidden":"true"}),s.jsx("span",{className:`shell_connection_label ${N&&((_u=(Jd=ne==null?void 0:ne.gateway)==null?void 0:Jd.principal)!=null&&_u.user_id)?"mono":""}`,children:N?((pu=(Do=ne==null?void 0:ne.gateway)==null?void 0:Do.principal)==null?void 0:pu.user_id)||(n.gateway_auth_mode==="direct"?"direct dev":"connected"):ie?"connecting…":"signed out"})]})})]}),s.jsxs("div",{className:"shell_main",children:[s.jsxs("header",{className:"shell_header",children:[s.jsx("div",{className:"shell_header_title",children:Wl[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(wS,{assistant:{open:Wt,onToggle:()=>It(g=>!g),label:"Observer assistant (docs-grounded)"},appearance:{onOpen:()=>pn(!0)},about:{identity:aa,extraRows:pd,onOpen:Ao},connection:{phase:D.phase,signingOut:D.signingOut,onConnect:()=>D.openModal(),onDisconnect:()=>Hc()}})]})]}),s.jsx(Qj,{...D.modalProps}),s.jsx(jS,{open:tn,onClose:()=>pn(!1),value:Ke,onChange:Dt}),s.jsx(KN,{open:Wt,onClose:()=>It(!1),connected:N,topOffset:44,gateway:Oe}),s.jsxs("div",{className:"app-body shell_content",children:[e==="board"?N?s.jsx(dL,{gateway_connected:N,runs:Tt,all_runs:Fn,runs_refreshed_at:yn,entities:Gn,entities_total:Nr,entities_error:ce,refreshing:jn,on_refresh:()=>void Ms(Oe,{force:!0}),on_open_run:g=>{t("observe"),qs("overview"),vs(g)},on_resume_wait:fh,on_open_automation:g=>{t("automations"),Bn.refresh().then(()=>Bn.select(g))},entity_app_href:l,on_read_diary:(g,k)=>Oe.read_entity_diary_entry(g,k),phase_graph:dh}):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.",F?` Last attempt: ${F}`:""]}),s.jsxs("div",{className:"row",style:{gap:"8px",alignItems:"center"},children:[s.jsx("button",{className:"btn primary",onClick:()=>D.openModal(),disabled:ie,children:ie?"Connecting…":"Sign in"}),s.jsx("button",{className:"btn",onClick:()=>void da({open_modal_if_needed:!0}),disabled:ie,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 ${N?"ok":"warn"}`,children:Yv(ne).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:()=>D.openModal(),children:"Manage connection…"}),N?s.jsx("button",{className:"btn",onClick:()=>Hc(),title:"Sign this browser out of the gateway (this app's session only)",children:"Sign out"}):null]})]}),F?s.jsx("div",{className:"warn_callout",children:F}):null,s.jsxs("div",{className:"settings_row",children:[s.jsxs("div",{className:"settings_row_main",children:[s.jsx("div",{className:"settings_row_title",children:"Auto-connect on load"}),s.jsx("div",{className:"settings_row_help",children:"Reuse the browser session automatically when the app opens."})]}),s.jsx("div",{className:"settings_row_actions",children:s.jsxs("select",{value:n.auto_connect_gateway?"on":"off",onChange:g=>i(k=>({...k,auto_connect_gateway:g.target.value==="on"})),children:[s.jsx("option",{value:"on",children:"On"}),s.jsx("option",{value:"off",children:"Off"})]})})]}),s.jsxs("details",{className:"settings_advanced",children:[s.jsx("summary",{children:"Advanced: direct dev connection (bearer token, cross-origin)"}),s.jsxs("div",{className:"field",style:{marginTop:"8px"},children:[s.jsx("label",{children:"Gateway URL"}),s.jsx("input",{value:n.gateway_url,onChange:g=>i(k=>({...k,gateway_url:g.target.value})),placeholder:Fm})]}),s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Dev bearer token"}),s.jsx("input",{type:"password",value:n.auth_token,onChange:g=>i(k=>({...k,auth_token:g.target.value,gateway_auth_mode:"direct"})),placeholder:"development only — prefer the sign-in dialog"})]}),s.jsx("button",{className:"btn",onClick:()=>void da({prefer_direct:!0}),disabled:ie,children:ie?"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(Wj,{className:"field",providerLabel:"Provider",modelLabel:"Model",providerPlaceholder:"(gateway default)",modelPlaceholder:"(gateway default)",provider:n.maintenance_ai_provider,model:n.maintenance_ai_model,providers:On,models:ns.models,loadingProviders:ie,loadingModels:Ol,modelError:Za?ns.error:"",allowCustomProvider:!0,allowCustomModel:!0,allowGatewayDefault:!0,gatewayDefaultLabel:"(gateway default)",onChange:g=>i(k=>({...k,maintenance_ai_provider:g.provider,maintenance_ai_model:g.model}))}),s.jsx("div",{className:"settings_subhead",children:"Skills"}),z===null?s.jsx("div",{className:"settings_row_help",children:N?T?"The gateway does not serve a skills inventory yet — the abstractskill shelf list lights up here the day it ships.":"Probing the gateway for the skills inventory…":"Connect to the gateway to list installable skills (abstractskill shelf)."}):z.length?s.jsx("div",{className:"settings_choice_list",children:z.map(g=>{const k=n.assistant_skill_names.includes(g.name);return s.jsxs("label",{className:`settings_choice ${k?"on":""}`,title:g.description||g.name,children:[s.jsx("input",{type:"checkbox",checked:k,onChange:$=>i(I=>({...I,assistant_skill_names:$.target.checked?Array.from(new Set([...I.assistant_skill_names,g.name])):I.assistant_skill_names.filter(q=>q!==g.name)}))}),s.jsxs("span",{className:"settings_choice_name",children:[g.name,g.version?s.jsxs("em",{children:[" v",g.version]}):null]}),g.description?s.jsx("span",{className:"settings_choice_desc",children:g.description}):null]},g.name)})}):s.jsx("div",{className:"settings_row_help",children:"The gateway serves an empty skills inventory."}),s.jsx("div",{className:"settings_row_help",children:"Selected skills ride the assistant's runs once the gateway's skills-attachment lane serves them; the selection persists here meanwhile."}),s.jsx("div",{className:"settings_subhead",children:"MCP servers"}),s.jsx("div",{className:"settings_row_help",style:{marginTop:0},children:"Remote tool endpoints the assistant may call. The gateway does not serve an MCP inventory yet — one manual endpoint is supported (advanced / potentially dangerous: it executes tool waits from this browser)."}),s.jsxs("div",{className:"settings_mcp_row",children:[s.jsx("input",{className:"mono",value:n.worker_url,onChange:g=>i(k=>({...k,worker_url:g.target.value})),placeholder:"https://your-mcp-worker-endpoint"}),s.jsx("input",{className:"mono",type:"password",value:n.worker_token,onChange:g=>i(k=>({...k,worker_token:g.target.value})),placeholder:"Bearer token (optional)"}),s.jsx("span",{className:`chip ${n.worker_url.trim()?"ok":"muted"}`,children:n.worker_url.trim()?"configured":"none"})]})]})]})]})}):null,e==="launch"?s.jsx("div",{className:"page page_scroll",children:s.jsx("div",{className:"page_inner constrained",children:s.jsxs("div",{className:"card",children:[s.jsx(N1,{mode:oe,automate_available:ge.available,automate_reason:ge.reason,on_change:fe}),oe==="automate"&&!ge.available&&N?s.jsx("div",{className:"warn_callout",role:"note",children:ge.reason}):null,oe==="automate"&&Se.length?s.jsx("div",{className:"help_text",role:"note",children:Se.map(g=>s.jsx("div",{children:g},g))}):null,N?null:s.jsxs("div",{className:"warn_callout",children:["Not connected."," ",s.jsx("button",{className:"btn primary",onClick:()=>D.openModal(),children:"Sign in"})," ","to launch workflows on this gateway."]}),oe==="automate"?s.jsx("div",{className:"section_title",children:"What"}):null,s.jsx("div",{className:"launch_workflow_bar",children:s.jsxs("select",{className:"launch_workflow_select","aria-label":"Workflow",value:xd,onChange:async g=>{const k=ZN(String(g.target.value||""));k&&await gh(k)},disabled:ie||!N,children:[s.jsx("option",{value:"",children:Wc.length?"(select workflow)":pt?ie?"(loading workflows…)":"(no executable workflows published on this gateway)":"(sign in to load workflows)"}),s.jsx("optgroup",{label:"Gateway default",children:e1(dn).map(g=>s.jsx("option",{value:g.value,children:g.label},g.value))}),s.jsx("optgroup",{label:"Workflows",children:Wc.map(g=>s.jsx("option",{value:g.workflow_id,children:g.label},g.workflow_id))})]})}),s.jsxs("div",{className:"field",children:[In!=null&&In.description?s.jsx("div",{className:"help_text muted",style:{fontSize:"var(--font-size-sm)",marginTop:"6px"},children:String(In.description)}):null,X?s.jsx("div",{className:"help_text muted",style:{fontSize:"var(--font-size-sm)"},children:"Loading workflow…"}):null,Z?s.jsx("div",{className:"mono",style:{color:"rgba(239, 68, 68, 0.9)",fontSize:"var(--font-size-sm)"},children:Z}):null]}),s.jsx("div",{className:"section_divider"}),s.jsx("div",{className:"section_title",children:"Inputs"}),Ui?it===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:jt()})]}),s.jsx("div",{className:"body mono",children:"Invalid input JSON — reselect the workflow to reset its inputs."})]}):vd?s.jsx("div",{className:"launch_inputs",children:(()=>{const g=Ee||Et,k=[],$=[];for(const W of To){if(!W||typeof W!="object")continue;const V=String(W.id||"").trim();if(!V||oe==="automate"&&Ax.includes(V))continue;const te=String(W.type||"").trim().toLowerCase();te==="tools"||te==="skills"||te==="mcp"||te==="mcp_servers"||V==="skills"||V==="mcp"||V==="mcp_servers"||te==="array"||$n(te)||V==="prompt"||V==="system"?k.push(W):$.push(W)}const I=W=>String(W||"").trim().replace(/_/g," ").replace(/\b\w/g,V=>V.toUpperCase()),q=(W,V)=>{const te=String(W.id||"").trim();if(!te)return null;const $e=String(W.label||te).trim()||te,he=$e===te?I(te):$e,pe=String(W.type||"").trim().toLowerCase(),Ce=Object.prototype.hasOwnProperty.call(W,"default"),ze=Ce?W.default:void 0,Ie=Ce?typeof ze=="string"?ze:Bs(ze,80):"",Ze=it==null?void 0:it[te],Ge=Ce?`${Ie}`:"";if(pe==="tools"){const qe=Array.isArray(Ze)?Ze.map(Qt=>String(Qt||"").trim()).filter(Boolean):[],xt=Array.isArray(ze)?ze.map(Qt=>String(Qt||"").trim()).filter(Boolean):[],Nn=Array.from(new Set([...ts,...qe,...xt])).sort();return s.jsxs("div",{className:"launch_field_wide",children:[s.jsx("label",{className:"launch_label",children:he}),s.jsx(gv,{options:Nn,value:qe,disabled:g,placeholder:"(no tools selected)",onChange:Qt=>vn(te,Qt)})]},te)}if(pe==="skills"||te==="skills")return null;if(pe==="mcp"||pe==="mcp_servers"||te==="mcp"||te==="mcp_servers"){const qe=Array.isArray(Ze)?Ze.map(Qt=>String(Qt||"").trim()).filter(Boolean):[];if(K===null&&!qe.length)return s.jsxs("div",{className:"launch_field_wide",children:[s.jsx("label",{className:"launch_label",children:he}),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."})]},te);const xt=(K||[]).map(Qt=>Qt.name),Nn=Array.from(new Set([...xt,...qe])).sort();return s.jsxs("div",{className:"launch_field_wide",children:[s.jsx("label",{className:"launch_label",children:he}),s.jsx(gv,{options:Nn,value:qe,disabled:g,placeholder:"(no MCP servers selected)",onChange:Qt=>vn(te,Qt)})]},te)}if(pe==="provider"||pe==="provider_text"){const qe=typeof Ze=="string"?String(Ze):"";return s.jsxs("div",{className:V||"launch_field",children:[s.jsx("label",{className:"launch_label",children:he}),s.jsxs("select",{value:qe,onChange:xt=>vn(te,xt.target.value),disabled:g,children:[s.jsx("option",{value:"",children:Ge||"(select)"}),ua.map(xt=>s.jsx("option",{value:xt,children:xt},xt))]})]},te)}if(pe==="model"||pe==="model_text"){const qe=typeof Ze=="string"?String(Ze):"",xt=String((it==null?void 0:it.provider)||"").trim(),Nn=xt?Ut[xt]:void 0,Qt=Nn&&Array.isArray(Nn.models)?Nn.models.map(Ds=>String(Ds||"").trim()).filter(Boolean):[];return s.jsxs("div",{className:V||"launch_field",children:[s.jsx("label",{className:"launch_label",children:he}),Qt.length?s.jsxs("select",{value:qe,onChange:Ds=>vn(te,Ds.target.value),disabled:g,children:[s.jsx("option",{value:"",children:Ge||"(select)"}),Qt.map(Ds=>s.jsx("option",{value:Ds,children:Ds},Ds))]}):s.jsx("input",{value:qe,onChange:Ds=>vn(te,Ds.target.value),placeholder:Ge||"model id",disabled:g})]},te)}if(pe==="boolean"){const qe=typeof Ze=="boolean"?Ze?"true":"false":"";return s.jsxs("div",{className:V||"launch_field",children:[s.jsx("label",{className:"launch_label",children:he}),s.jsxs("select",{value:qe,onChange:xt=>{const Nn=String(xt.target.value||"").trim();Nn?vn(te,Nn==="true"):vn(te,void 0)},disabled:g,children:[s.jsx("option",{value:"",children:Ge||"(default)"}),s.jsx("option",{value:"true",children:"Yes"}),s.jsx("option",{value:"false",children:"No"})]})]},te)}if(pe==="number"){const qe=typeof Ze=="number"&&Number.isFinite(Ze)?String(Ze):"";return s.jsxs("div",{className:V||"launch_field",children:[s.jsx("label",{className:"launch_label",children:he}),s.jsx("input",{type:"number",value:qe,onChange:xt=>{const Nn=String(xt.target.value||"").trim();if(!Nn){vn(te,void 0);return}const Qt=Number(Nn);Number.isFinite(Qt)&&vn(te,Qt)},placeholder:Ge,disabled:g})]},te)}if(pe==="array"){const qe=Array.isArray(Ze)?Ze.map(xt=>String(xt||"").trim()).filter(Boolean).join(`
|
|
148
|
+
`):"";return s.jsxs("div",{className:"launch_field_wide",children:[s.jsx("label",{className:"launch_label",children:he}),s.jsx("textarea",{className:"mono",value:qe,onChange:xt=>{const Nn=String(xt.target.value||"").split(/\r?\n/g).map(Qt=>String(Qt||"").trim()).filter(Boolean);vn(te,Nn.length?Nn:void 0)},placeholder:Ge||"(one item per line)",rows:2,disabled:g})]},te)}if($n(pe)){const qe=typeof Jr[te]=="string"?Jr[te]:"",xt=String(sn[te]||"").trim();return s.jsxs("div",{className:"launch_field_wide",children:[s.jsxs("label",{className:"launch_label",children:[he," ",s.jsx("span",{className:"launch_label_type",children:pe})]}),s.jsx("textarea",{className:"mono",value:qe,onChange:Nn=>{const Qt=String(Nn.target.value??"");ot(Hr=>({...Hr,[te]:Qt}));const Ds=Qt.trim();if(!Ds){ms(Hr=>{const fs={...Hr};return delete fs[te],fs}),vn(te,void 0);return}try{const Hr=JSON.parse(Ds);ms(fs=>{const Fo={...fs};return delete Fo[te],Fo}),vn(te,Hr)}catch(Hr){ms(fs=>({...fs,[te]:String((Hr==null?void 0:Hr.message)||Hr||"Invalid JSON")}))}},placeholder:Ge||"{...}",rows:3,disabled:g}),xt?s.jsx("div",{className:"launch_field_error",children:xt}):null]},te)}const cn=typeof Ze=="string"?String(Ze):"";return te==="prompt"||te==="system"?s.jsxs("div",{className:"launch_field_wide",children:[s.jsx("label",{className:"launch_label",children:he}),s.jsx("textarea",{value:cn,onChange:qe=>vn(te,qe.target.value),placeholder:Ge||(te==="prompt"?"What should the agent do?":"System instructions (optional)"),rows:3,disabled:g})]},te):s.jsxs("div",{className:V||"launch_field",children:[s.jsx("label",{className:"launch_label",children:he}),s.jsx("input",{value:cn,onChange:qe=>vn(te,qe.target.value),placeholder:Ge,disabled:g})]},te)};return k.sort((W,V)=>{const te={system:0,prompt:1,tools:2};return(te[String(W.id||"")]??10)-(te[String(V.id||"")]??10)}),s.jsxs(s.Fragment,{children:[k.map(W=>q(W)),$.length>0?s.jsx("div",{className:"launch_grid",children:$.map(W=>q(W,"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:vi,onChange:g=>vn("prompt",g.target.value),placeholder:"What do you want the workflow/agent to do?",rows:3,disabled:Ee||Et})]}),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:la,onChange:g=>vn("provider",g.target.value),placeholder:"lmstudio / ollama / openai / ...",disabled:Ee||Et})]})}),s.jsx("div",{className:"col",children:s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Model (common)"}),s.jsx("input",{value:Il,onChange:g=>vn("model",g.target.value),placeholder:"qwen/qwen3-next-80b / gpt-4.1 / ...",disabled:Ee||Et})]})})]})]}):s.jsx("div",{className:"help_text muted",style:{fontSize:"var(--font-size-sm)",marginTop:"8px"},children:"Select a workflow above to configure inputs."}),oe==="automate"?s.jsxs(s.Fragment,{children:[s.jsx(C1,{form:Ae,email_status:Ll.email_status,on_open_my_email:$o,tools:Array.isArray(it==null?void 0:it.tools)?it.tools.map(g=>String(g)):void 0,disabled:lt,on_change:g=>Be(k=>({...k,...g}))}),s.jsxs("details",{className:"launch_advanced",style:{marginTop:"10px"},children:[s.jsxs("summary",{className:"help_text muted",style:{cursor:"pointer"},children:["Advanced",Dr.length?` · ${Dr.length} skill${Dr.length===1?"":"s"}`:""]}),s.jsx(E1,{form:Ae,disabled:lt,on_change:g=>Be(k=>({...k,...g}))}),du]})]}):du,s.jsx("div",{className:"section_divider"}),mn?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:mn})]}):null,oe==="automate"&&We.length?s.jsx("ul",{className:"automate_errors",role:"alert",children:We.map(g=>s.jsx("li",{children:g},g))}):null,oe==="automate"&&Pe?s.jsxs("div",{className:"observe_context_card error",role:"alert","data-code":Pe.code,style:{marginBottom:"10px"},children:[s.jsx("span",{className:"chip mono danger",children:Pe.code}),s.jsxs("span",{children:[s.jsx("strong",{children:vm(Pe).title})," ",vm(Pe).detail,Pe.field?s.jsxs("span",{className:"mono",children:[" (",Pe.field,")"]}):null]})]}):null,s.jsx("div",{className:"launch_actions_bar launch_actions_stack",children:(()=>{const g=oe==="automate",k=N?Ui?it===null?"Inputs contain invalid JSON":g&&!ge.available?"Automations unavailable on this gateway":Ee||Et?"Attaching to a run…":ie||X?"Loading…":lt?"Submitting…":"":"Select a workflow":"Sign in first";return s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"launch_submit_btn",onClick:()=>void h_(),disabled:!!k,title:k,children:g?lt?"Creating…":"Create automation":Ee?"Launching…":"Launch now"}),k&&!lt&&!Ee?s.jsx("span",{className:"mono muted launch_disabled_reason",children:k}):null]})})()})]})})}):null,e==="automations"?s.jsx(G1,{ctl:Bn,gateway:Oe,active:e==="automations"&&N,available:ge,h:fu,host:{on_open_run:g=>ql(g),...$o?{on_open_my_email:$o}:{},on_open_session:(g,k)=>{Kt({ts:jt(),kind:"info",title:"Discussion started",preview:ht(k),data:g})}}}):null,e==="runtime"?s.jsx(QC,{gateway_connected:N,tab:$l,runs:kn,active_runs:Po,all_artifacts:cd,artifacts:Xi,artifact_total_count:$c,artifact_total_bytes:nh,artifact_facets:_i,artifact_type_facets:Fi,artifact_page:Lo,artifact_page_size:am,artifact_groups:Io,selected_artifact:Oo,embedded_preview:Ga,loading:c_,error:sa,query:pi,scope:ra,type_filters:ln,date_filter:es,group_by:Rr,sort_by:ys,artifact_run_filter:zi,audit_log_text:Or,audit_log_meta:ih,audit_log_loading:Oc,audit_log_error:Pc,workflow_label_by_id:or,run_by_id:Yi,selected_run_id:ya,session_id:cu,runtime_log_source:Bi,runtime_log_query:u_,runtime_ledger_log_items:Dc,runtime_ledger_log_meta:oh,runtime_ledger_log_loading:ah,runtime_ledger_log_error:zc,on_tab_change:ld,on_query_change:Tc,on_scope_change:jo,on_session_filter_change:Sn,on_type_filters_change:So,on_date_filter_change:rr,on_group_by_change:qa,on_sort_by_change:Mc,on_artifact_page_change:Rc,on_artifact_run_filter_change:g=>{const k=String(g||"").trim();ud(k),k&&Ha(k),k&&ra!=="run"&&jo("run")},on_refresh_artifacts:()=>void ds(),on_refresh_audit:()=>void cr(),on_refresh_runtime_ledger:g=>void pa(g),on_runtime_log_source_change:_d,on_runtime_log_query_change:Ml,on_select_run:g=>{const k=String(g||"").trim();Ha(k);const $=k&&Yi[k]||null,I=String(($==null?void 0:$.session_id)||"").trim();I&&Sn(I)},on_select_artifact:Va,on_preview_artifact:g=>void Cd(g),on_download_artifact:g=>void Nd(g),on_open_run:g=>{Ha(String(g||"").trim()),t("observe"),qs("overview"),vs(g)},on_open_ledger:g=>{Ha(String(g||"").trim()),t("observe"),qs("ledger"),vs(g)},on_refresh_runs:()=>void Ms(Oe,{force:!0}),on_reconnect:()=>void da({open_modal_if_needed:!0}),on_open_settings:()=>t("settings"),memory_panel:N?s.jsx(WR,{gateway:Oe,selected_run_id:ko,selected_session_id:cu}):null}):null,e==="observe"?s.jsx("div",{className:"page observe_page",children:s.jsxs("div",{className:"observatory_layout",children:[s.jsx(t2,{sections:Ul,selected_run_id:c,root_run_id:_,search:Xu,filter:Zu,group_by:Qu,loading:jn,connected:N,on_sign_in:()=>D.openModal(),total_runs:kn.length,workflow_label_by_id:or,automation_titles:Pr,on_search:n_,on_filter:s_,on_group_by:r_,on_refresh:()=>void Ms(),on_select:(g,k)=>void vs(g,{root_run_id:k||g})}),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:or[String((Jn==null?void 0:Jn.workflow_id)||"")]||String((Jn==null?void 0:Jn.workflow_id)||"").trim()||Lt(c.trim(),22)}),s.jsx("span",{className:"chip mono muted",children:Lt(c.trim(),14)}),s.jsx("span",{className:`chip ${pl(Dn||_a,Un)}`,title:String((Un==null?void 0:Un.headline)||""),children:Dn||_a||"unknown"})]}):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:[s.jsx("button",{className:"btn",onClick:()=>{if(iu==="pause"){Ai("pause"),$s(""),er(""),Er(!0);return}Ad("resume")},disabled:Ch,children:ma}),__?s.jsx("button",{className:"btn primary",onClick:()=>void wh(),disabled:Ee||Et||Br||qi,children:"Run now"}):null,s.jsx("button",{className:"btn danger",onClick:()=>{Ai("cancel"),$s(""),er(""),Er(!0)},disabled:Ee||Et||Br,children:"Cancel"}),s.jsx("button",{className:"btn btn_icon",onClick:Zc,title:"Clear the run view",children:s.jsx(Qe,{name:"x",size:14})})]}):null]}),c.trim()&&!Br?s.jsx("div",{className:"observe_steer_row",children:s.jsx(iS,{runId:c.trim(),parked:tl,submit:(g,k)=>Oe.submit_command({command_id:`steer-${zs()}`,run_id:g,type:"inject_guidance",payload:{guidance:k},client_id:"web_pwa"}).then($=>({accepted:!!($!=null&&$.accepted),duplicate:!!($!=null&&$.duplicate),seq:Number(($==null?void 0:$.seq)??0)})),onSent:()=>Kt({ts:jt(),kind:"info",title:"Steer queued",preview:"inject_guidance submitted — delivery shows as abstract.steer_seen in the ledger"})})}):null,tl||br||mc?s.jsxs("div",{className:"observe_toolbar_context",children:[tl?s.jsxs("div",{className:"observe_context_card info",children:[s.jsxs("div",{className:"observe_context_label",children:[(()=>{const g=br?qi?"suspended":"scheduled":"waiting";return s.jsx("span",{className:`chip ${pl(g)}`,children:g})})(),s.jsx("span",{className:"muted",children:us||"unknown"})]}),s.jsxs("div",{className:"observe_context_body",children:[Ls?s.jsxs("span",{className:"mono",title:Ls,children:[s.jsx("span",{className:"muted",children:"wait_key"}),": ",Lt(Ls,46)]}):null,us==="event"&&tu?s.jsxs("span",{className:"mono",children:[s.jsx("span",{className:"muted",children:"event"}),": ",tu]}):null,us==="subworkflow"&&Hi?s.jsxs("span",{className:"mono",children:[s.jsx("span",{className:"muted",children:"child"}),": ",Lt(Hi,18)]}):null,us==="until"&&ni?s.jsxs("span",{className:"mono",title:ni,children:[s.jsx("span",{className:"muted",children:"until"}),": ",Lt(ni,46)]}):null,us==="until"&&ni?s.jsx("span",{className:"mono muted",children:(()=>{const g=Cn(ni),k=g!==null?new Date(g).toLocaleString():ni,$=g!==null?Ky(g-Date.now()):"";return`Next at ${k}${$?` (in ${$})`:""}`})()}):null]}),us==="subworkflow"&&Hi?s.jsxs("div",{className:"observe_context_actions",children:[s.jsx("button",{className:"btn primary",onClick:async()=>{f(Hi),await Qa(Hi)},disabled:Ee,children:"Attach to child"}),_.trim()&&_.trim()!==c.trim()?s.jsx("button",{className:"btn",onClick:async()=>{f(_.trim()),await Qa(_.trim())},disabled:Ee,children:"Back to root"}):null]}):null]}):null,br?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:Je?`every ${nl}`:"once"})]}),s.jsxs("div",{className:"observe_context_body",children:[nl?s.jsxs("span",{className:"mono",children:[s.jsx("span",{className:"muted",children:"interval"}),": ",nl]}):null,s.jsxs("span",{className:"mono",children:[s.jsx("span",{className:"muted",children:"share ctx"}),": ",ru?"yes":"no"]}),typeof xs=="number"?s.jsxs("span",{className:"mono",children:[s.jsx("span",{className:"muted",children:"repeats"}),": ",xs]}):null]}),Ro!==null?s.jsxs("div",{className:"observe_context_budget",children:[s.jsxs("span",{className:"mono muted",children:[typeof ou=="number"&&typeof qd=="number"?`${ou.toLocaleString()} / ${qd.toLocaleString()}`:"",` • ${Math.round(Math.max(0,Math.min(1,Ro))*100)}%`]}),s.jsx("div",{className:"observe_budget_bar",children:s.jsx("div",{className:`observe_budget_fill ${Ro>=.9?"danger":Ro>=.75?"warn":"ok"}`,style:{width:`${Math.round(Math.max(0,Math.min(1,Ro))*100)}%`}})})]}):null,s.jsxs("div",{className:"observe_context_actions",children:[Je?s.jsx("button",{className:"btn",onClick:()=>{fo(nl||""),zn(!0),Tn(""),as(!0)},disabled:Ee||pr,children:"Edit schedule"}):null,Je?s.jsx("button",{className:"btn",onClick:()=>{$i(""),Zs(!0)},disabled:Ee||gr,children:"Compact context"}):null,s.jsx("button",{className:"btn",onClick:()=>void yh(c.trim()).catch(g=>nn(String((g==null?void 0:g.message)||g))),disabled:Ee||!c.trim(),title:"Open Launch → Automate prefilled from this schedule (this schedule is not changed)",children:"Recreate as automation"})]})]}):null,mc?s.jsxs("div",{className:"observe_context_card error",children:[s.jsx("span",{className:"chip danger",children:"error"}),s.jsx("span",{className:"mono",children:mc})]}):null]}):null]}),s.jsxs("div",{className:"card panel_card card_scroll observe_viewer observe_viewer_full",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":Qn==="overview",className:`tab ${Qn==="overview"?"active":""}`,onClick:()=>qs("overview"),children:"Story"}),s.jsx("button",{role:"tab","aria-selected":Qn==="ledger",className:`tab ${Qn==="ledger"?"active":""}`,onClick:()=>qs("ledger"),children:"Ledger"}),s.jsx("button",{role:"tab","aria-selected":Qn==="graph",className:`tab ${Qn==="graph"?"active":""}`,onClick:()=>qs("graph"),children:"Flow"}),s.jsx("button",{role:"tab","aria-selected":Qn==="chat",className:`tab ${Qn==="chat"?"active":""}`,onClick:()=>qs("chat"),children:"Ask"})]}),Qn==="ledger"&&(xi.length>0||La==="cycles")?s.jsxs("div",{className:"tab_bar_controls",children:[s.jsxs("div",{className:"seg_toggle",children:[s.jsx("button",{className:`seg_btn ${La==="steps"?"active":""}`,onClick:()=>_c("steps"),children:"Steps"}),s.jsx("button",{className:`seg_btn ${La==="cycles"?"active":""}`,onClick:()=>_c("cycles"),children:"Cycles"})]}),La==="steps"?s.jsx("button",{className:`seg_action ${xl?"active":""}`,onClick:()=>Hf(g=>!g),title:xl?"Showing condensed view":"Showing all steps",children:xl?"Condensed":"All"}):s.jsxs("select",{className:"mono seg_select",value:Ki,onChange:g=>ed(String(g.target.value||"")),disabled:!Wr.length,title:"Select run for cycles view",children:[Wr.length?null:s.jsx("option",{value:"",children:"(no runs)"}),Wr.map(g=>{const k=typeof zl[g]=="number"?Number(zl[g]):0,$=`${Lt(g,18)}${k?` • ${k} llm`:""}`;return s.jsx("option",{value:g,children:$},g)})]}),s.jsx("button",{className:"seg_action",disabled:!$t.length&&!os.length,title:"Copy full ledger as JSONL",onClick:()=>{const $=[...$t.map(W=>({run_id:c.trim()||W.record.run_id||"",cursor:W.cursor,record:W.record})),...os.map(W=>({run_id:W.run_id,cursor:W.cursor,record:W.record}))].map(W=>{var $e,he;const V=String((($e=W.record)==null?void 0:$e.ended_at)||((he=W.record)==null?void 0:he.started_at)||"").trim(),te=Cn(V);return{...W,_ms:te??0}});$.sort((W,V)=>(W._ms||0)-(V._ms||0));const q=($.length>5e3?$.slice($.length-5e3):$).map(({_ms:W,...V})=>JSON.stringify(V)).join(`
|
|
149
|
+
`);Vc(q)},children:"Copy JSONL"})]}):null,Qn==="graph"?s.jsxs("div",{className:"tab_bar_controls",children:[s.jsx("button",{className:`seg_action ${Xo?"active":""}`,onClick:()=>Fa(g=>!g),children:"Subflows"}),s.jsx("button",{className:`seg_action ${jc?"active":""}`,onClick:()=>Zf(g=>!g),children:"Path"}),Ur.length?s.jsx("select",{className:"mono seg_select",value:Jo,onChange:g=>Pa(String(g.target.value||"")),disabled:!!si.trim()||!j.trim()||xc,children:Ur.map(g=>s.jsx("option",{value:g,children:g},g))}):null]}):null]}),Qn==="overview"?s.jsx(n2,{run_id:c,run:Jn,run_state:xe,status_label:Dn||_a||"unknown",workflow_label_by_id:or,root_run_id:_,subrun_ids:fi,session_id:zr,records_count:$t.length,records:$t,child_records_count:os.length,provider_activities:ga,attachments_count:Gf.length,latest_summary:Eh,wait_state:zt,summary_generating:Cl,summary_error:ad,on_generate_summary:()=>void Rd(),on_open_runtime:()=>{const g=String(c||"").trim();g&&(Ha(g),ud(g),jo("run")),ld("artifacts"),t("runtime")},on_open_subrun:g=>void vs(g,{root_run_id:_||c||g}),on_answer_wait:()=>Zr(""),workspace_root:Kf,on_reveal_workspace:()=>void Kc(),run_artifacts:i_,run_artifacts_loading:rd,run_artifacts_error:Yf,on_preview_run_artifact:g=>void Cd(g),on_download_run_artifact:g=>void Nd(g),timeline_items:lu,node_index:wd,attachments:Gf,attachments_loading:nd,attachments_error:bl,attachments_ready:!!go.trim(),on_refresh_attachments:()=>void Pl(),on_preview_attachment:g=>void kd(g),on_download_attachment:g=>void hh(g),on_copy:g=>void Vc(g)}):null,Qn==="ledger"?s.jsx(s.Fragment,{children:La==="steps"?s.jsxs("div",{className:"log log_scroll",children:[xi.map(g=>s.jsx(r2,{item:g,open:Yu[g.id]===!0,on_toggle:()=>Ju(k=>({...k,[g.id]:!k[g.id]})),response_open:t_[g.id]===!0,on_toggle_response:()=>qf(k=>({...k,[g.id]:!k[g.id]})),node_index:wd,on_copy:k=>void Vc(k)},g.id)),xi.length?null:s.jsx("div",{className:"empty_state_inline",children:"(no ledger items)"})]}):s.jsx("div",{className:"log log_scroll",children:s.jsx(fj,{items:Gd.items,title:"Agent",subtitle:Gd.node_id?`node_id: ${Gd.node_id}`:"Live per-effect trace (LLM/tool calls).",subRunId:Ki,onOpenSubRun:Ki&&Ki!==c.trim()?()=>{f(Ki),Qa(Ki)}:void 0})})}):null,Qn==="graph"?s.jsxs(s.Fragment,{children:[bc?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:jt()})]}),s.jsx("div",{className:"body mono",children:bc})]}):null,xc?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:si.trim()?si.trim():Jo})]}),s.jsx("div",{className:"body mono",children:"Loading graph…"})]}):null,s.jsx("div",{className:"graph_panel",children:s.jsx(y2,{flow:vo,flow_by_id:vc,expand_subflows:Xo,simplify:!0,prefer_vertical:!0,vertical_compact:.78,schedule_next_in:Zt,schedule_interval:nl,node_last_ms:js,active_node_id:Vd,recent_nodes:Qf,visited_nodes:eh,highlight_path:jc,now_ms:Sc})})]}):null,s.jsxs(fl,{open:Jf,title:o_||"Attachment",onClose:()=>{id(!1),Oa(""),wo(""),jl(!1)},actions:s.jsx(s.Fragment,{children:s.jsx("button",{className:"btn",onClick:()=>{id(!1),Oa(""),wo(""),jl(!1)},children:"Close"})}),children:[Xf?s.jsx("div",{className:"mono muted",style:{fontSize:"var(--font-size-sm)",marginBottom:"8px"},children:"Loading…"}):null,Ar?s.jsx("div",{className:"mono",style:{color:"rgba(239, 68, 68, 0.9)",fontSize:"var(--font-size-sm)",marginBottom:"8px"},children:Ar}):null,s.jsx("pre",{className:"mono",style:{whiteSpace:"pre-wrap",maxHeight:"62vh",overflow:"auto",margin:0},children:l_||"(empty)"})]}),Qn==="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(Ou,{value:vl,options:Vu,placeholder:Ri?"Loading…":Vu.length?"Select a saved discussion…":"(none saved)",disabled:!c.trim()||!N||!Vu.length,loading:Ri,searchable:!0,clearable:!0,onChange:g=>{dc(g),Yo("")}})}),s.jsxs("div",{className:"actions",style:{justifyContent:"flex-end",marginTop:0},children:[s.jsx("button",{className:"btn",type:"button",disabled:!vl.trim()||!N||fc,onClick:()=>void bh(),children:fc?"Loading…":"Load"}),s.jsx("button",{className:"btn",type:"button",disabled:!ke.length||U||Ft||fc,onClick:()=>{Ue([]),at(null),wr(""),Ws(""),Mt(""),En(""),Zn("")},children:"Clear"}),s.jsx("button",{className:"btn",type:"button",onClick:()=>void Qc(),disabled:!c.trim()||!N||Ri,children:Ri?"Refreshing…":"Refresh"})]})]}),s.jsxs("div",{className:"actions",style:{justifyContent:"flex-end",marginTop:"8px",flexWrap:"wrap"},children:[s.jsx("button",{className:"btn",type:"button",disabled:!ke.length||!c.trim()||!N||Ft||!Hu,onClick:()=>void xh(),title:Hu?"":"No changes since last save",children:Ft?"Saving…":!Hu&&on?"Saved":"Save discussion"}),s.jsx("button",{className:"btn",type:"button",disabled:!ke.length,onClick:()=>Id("download"),children:"Export Markdown"}),s.jsx("button",{className:"btn",type:"button",disabled:!ke.length,onClick:()=>Id("copy"),children:je==="copied"?"Copied":je==="failed"?"Copy failed":"Copy Markdown"})]}),on?s.jsxs("div",{className:"chat_hint",children:["Last saved: ",Sa(on)]}):null,gs?s.jsx("div",{className:"chat_hint chat_hint_danger",children:gs}):null,Wf?s.jsx("div",{className:"chat_hint chat_hint_danger",children:Wf}):null,Uf?s.jsx("div",{className:"chat_hint chat_hint_danger",children:Uf}):null]})]}),_o?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:jt()})]}),s.jsx("div",{className:"body mono",children:_o})]}):null,Vo?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:jt()})]}),s.jsx("div",{className:"body mono",children:Vo})]}):null,s.jsx("div",{className:"chat_messages",style:{marginTop:"10px"},children:s.jsx(xg,{messages:ke,className:"log_scroll",after:s.jsx($x,{history:ft}),afterKey:ft?`${ft.replayed_messages}:${ft.dropped_messages}`:null,messageProps:Mn.tts_supported&&N&&Ko.trim()?{onSpeakToggle:m_,getSpeakState:vh,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.jsx("div",{className:"chat_composer",style:{marginTop:"10px"},children:s.jsx(bg,{ref:gt,value:cc,onChange:wr,onSubmit:()=>void Ld(),placeholder:"Ask about this run…",disabled:!c.trim()||!N||U,busy:U||Mn.voice_ptt_busy,busyLabel:Mn.voice_ptt_busy?"Transcribing…":"Thinking…",rows:3,sendButtonClassName:"btn primary",actions:s.jsxs("button",{className:`btn btn_icon voice_btn${Mn.voice_ptt_recording?" danger":""}`,type:"button",disabled:!N||!ha.trim()||!Ko.trim()||U||Mn.voice_ptt_busy||!Mn.voice_ptt_supported,title:Mn.voice_ptt_supported?Mn.voice_ptt_busy?"Transcribing…":Mn.voice_ptt_recording?"Recording… release to transcribe":"Hold to talk (record + transcribe)":"Voice recording is not supported in this browser","aria-label":"Voice input",onPointerDown:g=>{var k,$;if(!(!N||!ha.trim()||!Ko.trim()||U||Mn.voice_ptt_busy||!Mn.voice_ptt_supported)){g.preventDefault();try{($=(k=g.currentTarget)==null?void 0:k.setPointerCapture)==null||$.call(k,g.pointerId)}catch{}Mn.start_voice_ptt_recording()}},onPointerUp:g=>{g.preventDefault(),Mn.stop_voice_ptt_recording()},onPointerCancel:g=>{g.preventDefault(),Mn.stop_voice_ptt_recording()},children:[s.jsx(Qe,{name:Mn.voice_ptt_recording?"x":"mic",size:16}),Mn.voice_ptt_busy?"Transcribing…":Mn.voice_ptt_recording?"Recording…":"Voice"]})})})]}):null,c.trim()?s.jsxs("div",{className:`status_bar ${qo?"pulse":""}`,children:[s.jsx("strong",{children:"Run"}),":"," ",s.jsx("span",{className:"mono",children:Dn||_a||"unknown"}),au&&Zt?s.jsxs("span",{className:"mono muted",children:[" • next in ",Zt]}):null,Ti?s.jsxs("span",{className:"mono muted",children:[" • ",Ti]}):null]}):null]})]})]})}):null,s.jsxs(fl,{open:Ka,title:Al||"Artifact",onClose:()=>{No(!1),ws(""),wn(""),As(!1),Tl(null),qn&&(URL.revokeObjectURL(qn),Ir(""))},actions:s.jsx("button",{className:"btn",onClick:()=>{No(!1),ws(""),wn(""),As(!1),Tl(null),qn&&(URL.revokeObjectURL(qn),Ir(""))},children:"Close"}),children:[dd?s.jsx("div",{className:"mono muted",style:{fontSize:"var(--font-size-sm)",marginBottom:"8px"},children:"Loading…"}):null,ir?s.jsx("div",{className:"mono",style:{color:"rgba(239, 68, 68, 0.9)",fontSize:"var(--font-size-sm)",marginBottom:"8px"},children:ir}):null,ti==="image"&&qn?s.jsx("img",{className:"runtime_preview_media",src:qn,alt:Al||"Artifact preview"}):ti==="audio"&&qn?s.jsx("audio",{className:"runtime_preview_media",controls:!0,src:qn}):ti==="video"&&qn?s.jsx("video",{className:"runtime_preview_media",controls:!0,src:qn}):s.jsx(Yx,{artifact:rh,text:Lr||"(empty)",className:"runtime_preview_text"})]}),ai?s.jsxs(fl,{open:ai,title:"Edit schedule",onClose:()=>{as(!1),fo(""),zn(!0),Tn(""),ho(!1)},actions:s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"btn",onClick:()=>{as(!1),fo(""),zn(!0),Tn(""),ho(!1)},disabled:Ee||pr,children:"Back"}),s.jsx("button",{className:"btn primary",onClick:async()=>{await Md({interval:uo,apply_immediately:Aa})||(as(!1),Tn(""),ho(!1))},disabled:Ee||pr||!uo.trim(),children:"Save"})]}),children:[_r?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:jt()})]}),s.jsx("div",{className:"body mono",children:_r})]}):null,s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Interval"}),s.jsx("input",{className:"mono",value:uo,onChange:g=>fo(String(g.target.value||"")),placeholder:"20m / 1h / 0.5s / 250ms",disabled:Ee||pr}),s.jsxs("div",{className:"mono muted",style:{fontSize:"var(--font-size-sm)"},children:["Accepted units: ",s.jsx("span",{className:"mono",children:"ms"}),", ",s.jsx("span",{className:"mono",children:"s"}),", ",s.jsx("span",{className:"mono",children:"m"}),","," ",s.jsx("span",{className:"mono",children:"h"}),", ",s.jsx("span",{className:"mono",children:"d"}),". This updates the existing scheduled run in place (no context loss)."]})]}),s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Quick picks"}),s.jsx("div",{className:"actions",style:{gap:"8px",flexWrap:"wrap"},children:["15m","30m","1h","2h","6h","1d"].map(g=>s.jsx("button",{className:"btn",onClick:()=>fo(g),disabled:Ee||pr,children:g},g))})]}),s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Apply"}),s.jsxs("label",{style:{display:"flex",gap:"10px",alignItems:"center"},children:[s.jsx("input",{type:"checkbox",checked:Aa,onChange:g=>zn(!!g.target.checked),disabled:Ee||pr}),"Apply immediately (recompute next run from now if waiting)"]})]})]}):null,Xn?s.jsxs(fl,{open:Xn,title:"Compact scheduled context",onClose:()=>{Zs(!1),$i(""),Es(!1)},actions:s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"btn",onClick:()=>{Zs(!1),$i(""),Es(!1)},disabled:Ee||gr,children:"Cancel"}),s.jsx("button",{className:"btn primary",onClick:async()=>{await el({preserve_recent:ls,compression_mode:_s,focus:mo})||(Zs(!1),$i(""),Es(!1))},disabled:Ee||gr,children:gr?"Compacting…":"Compact"})]}),children:[yl?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:jt()})]}),s.jsx("div",{className:"body mono",children:yl})]}):null,s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Preserve recent turns"}),s.jsx("input",{type:"number",min:1,value:String(ls),onChange:g=>Xr(Math.max(1,parseInt(g.target.value||"6",10)||6)),disabled:Ee||gr})]}),s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Mode"}),s.jsxs("select",{value:_s,onChange:g=>Ta(g.target.value),disabled:Ee||gr,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:mo,onChange:g=>rn(String(g.target.value||"")),placeholder:"e.g. important decisions, next steps…",disabled:Ee||gr})]})]}):null,Ma?s.jsxs(fl,{open:Ma,title:li==="cancel"?"Cancel run":br?"Suspend schedule":"Pause run",onClose:()=>{Er(!1),$s(""),er("")},actions:s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"btn",onClick:()=>{Er(!1),$s(""),er("")},disabled:Ee||Et,children:"Back"}),s.jsx("button",{className:`btn ${li==="cancel"?"danger":"primary"}`,onClick:async()=>{er("");const g=await Ad(li,{reason:Qs});if(g){er(g);return}Er(!1),$s(""),er("")},disabled:Ee||Et,children:li==="pause"?br?"Suspend":"Pause":"Cancel"})]}),children:[$r?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:jt()})]}),s.jsx("div",{className:"body mono",children:$r})]}):null,s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Reason (optional)"}),s.jsx("input",{className:"mono",value:Qs,onChange:g=>$s(g.target.value),placeholder:"reason…"})]})]}):null,Dd?s.jsxs(fl,{open:Dd,title:Fd,onClose:()=>{Ls&&Zr(Ls)},actions:s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"btn",onClick:()=>{qs("ledger"),t("observe"),Ls&&Zr(Ls)},disabled:!c.trim(),children:"Open ledger"}),s.jsx("button",{className:"btn",onClick:()=>Ls&&Zr(Ls),disabled:Et,children:"Dismiss"}),Hn.length?s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"btn danger",disabled:Et,onClick:()=>eu({approved:!1}),children:"Reject"}),s.jsx("button",{className:"btn",disabled:Et,onClick:()=>eu({approved:!0}),children:"Approve only"}),s.jsx("button",{className:"btn primary",disabled:!Ya||Et,onClick:()=>lr(Hn),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:Fd}),s.jsx("p",{children:zd})]}),s.jsx(gl,{status:Wi||"waiting"})]}),Vi?s.jsxs("div",{className:`wait_request_card ${su?"":"inferred"}`,children:[s.jsx("span",{children:Nh}),s.jsx(bv,{metadata:Gi}),s.jsx(Ni,{text:Vi}),su?null:s.jsx("p",{className:"wait_context_note",children:"The runtime did not attach a specific question to this wait. This is inferred from the run input; verify the session turns and workflow steps before answering."})]}):s.jsx("div",{className:"warn_callout",children:"This wait did not provide a clear prompt or recoverable prior user request. Review the full run input and recent workflow steps before submitting a response."}),Ud.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:Ud.map((g,k)=>s.jsxs("div",{className:`wait_turn_row role_${g.role.replace(/[^a-z0-9_-]+/g,"_")}`,children:[s.jsxs("div",{className:"wait_turn_meta",children:[s.jsx("strong",{children:g.role==="assistant"?"Assistant":g.role==="user"||g.role==="human"?"User":g.role}),g.ts?s.jsx("span",{className:"mono muted",children:Sa(g.ts)}):null]}),s.jsx(bv,{metadata:g.runtime_metadata}),s.jsx(Ni,{text:ht(g.text,{max_chars:1200,max_lines:10})})]},`${g.role}:${k}`))})]}):null,s.jsxs("div",{className:"artifact_detail_grid",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Workflow"}),s.jsx("strong",{children:ji(Mo,or)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Run"}),s.jsx("strong",{className:"mono",children:Lt(c.trim(),24)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Node"}),s.jsx("strong",{className:"mono",children:Mo.current_node||String((Ts==null?void 0:Ts.node_id)||"—")})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Elapsed"}),s.jsx("strong",{children:oc(Mo)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Session"}),s.jsx("strong",{className:"mono",children:Mo.session_id?Lt(String(Mo.session_id),18):"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Wait key"}),s.jsx("strong",{className:"mono",children:Lt(Ls,28)})]})]}),Is?s.jsxs("details",{className:"runtime_raw_details wait_full_input_details",open:!Vi,children:[s.jsx("summary",{className:"mono muted",children:"Full run input JSON"}),s.jsx("div",{className:"wait_shared_json",children:s.jsx(fr,{value:Fl,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:[kh.map(g=>s.jsxs("div",{className:"wait_event_row",children:[s.jsxs("span",{className:"mono",children:["#",g.cursor]}),s.jsx("strong",{children:g.summary||g.effect_type||g.status||"event"}),s.jsx("span",{className:"mono muted",children:[g.node_id,g.status,Sa(g.ts)].filter(Boolean).join(" · ")})]},`${g.cursor}:${g.node_id}:${g.status}`)),kh.length?null:s.jsx("div",{className:"empty_state_inline",children:"No ledger context is loaded. Open the ledger before deciding."})]})]})]}),Hn.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:Hn.map((g,k)=>s.jsxs("div",{className:"wait_tool_card",children:[s.jsxs("div",{className:"wait_tool_header",children:[s.jsx("strong",{children:String((g==null?void 0:g.name)||"tool")}),s.jsxs("div",{className:"wait_tool_badges",children:[s.jsx("span",{className:"chip mono warn",children:"approval"}),Bx(g).map($=>s.jsxs("span",{className:"chip mono muted",title:zx,children:[$,"~"]},$))]})]}),s.jsx("div",{className:"wait_tool_args",children:s.jsx(fr,{value:(g==null?void 0:g.arguments)||{},collapseAfterDepth:3,showCopy:!0})})]},`${String((g==null?void 0:g.name)||"tool")}:${k}`))}),Ya?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 Td(c.trim(),"Cancelled from wait prompt"),disabled:!c.trim()||Et,children:"Cancel whole run"})}),s.jsxs("details",{className:"runtime_raw_details",children:[s.jsx("summary",{className:"mono muted",children:"Diagnostics"}),s.jsx("div",{className:"wait_shared_json",children:s.jsx(fr,{value:zt||{},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:Vi||"No explicit prompt was provided. Open the ledger for context before responding."}),s.jsx(e2,{wait:zt,disabled:Et,on_submit:g=>eu({response:g})}),s.jsx("div",{className:"actions",children:s.jsx("button",{className:"btn danger",onClick:()=>void Td(c.trim(),"Cancelled from wait prompt"),disabled:!c.trim()||Et,children:"Cancel whole run"})}),s.jsxs("details",{className:"runtime_raw_details",children:[s.jsx("summary",{className:"mono muted",children:"Diagnostics"}),s.jsx("div",{className:"wait_shared_json",children:s.jsx(fr,{value:zt||{},collapseAfterDepth:3,showCopy:!0})})]})]})]}):null]})]})]})}if("serviceWorker"in navigator){window.addEventListener("load",()=>{navigator.serviceWorker.register(JN).then(t=>t.update()).catch(()=>{})});let e=!1;navigator.serviceWorker.addEventListener("controllerchange",()=>{e||(e=!0,window.location.reload())})}G0.createRoot(document.getElementById("root")).render(s.jsx(ve.StrictMode,{children:s.jsx(CL,{})}));
|
|
150
|
+
//# sourceMappingURL=index-qNhYHB2C.js.map
|