@abstractframework/observer 0.2.1 → 0.4.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.
@@ -1,150 +0,0 @@
1
- var u0=Object.defineProperty;var d0=(e,t,n)=>t in e?u0(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 tg(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var p_={exports:{}},zd={},g_={exports:{}},Gt={};/**
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 Ug;function f0(){if(Ug)return Gt;Ug=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"),w=Symbol.iterator;function y(T){return T===null||typeof T!="object"?null:(T=w&&T[w]||T["@@iterator"],typeof T=="function"?T:null)}var x={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},S=Object.assign,b={};function $(T,Q,K){this.props=T,this.context=Q,this.refs=b,this.updater=K||x}$.prototype.isReactComponent={},$.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")},$.prototype.forceUpdate=function(T){this.updater.enqueueForceUpdate(this,T,"forceUpdate")};function E(){}E.prototype=$.prototype;function L(T,Q,K){this.props=T,this.context=Q,this.refs=b,this.updater=K||x}var D=L.prototype=new E;D.constructor=L,S(D,$.prototype),D.isPureReactComponent=!0;var M=Array.isArray,H=Object.prototype.hasOwnProperty,Z={current:null},Y={key:!0,ref:!0,__self:!0,__source:!0};function X(T,Q,K){var J,oe={},fe=null,me=null;if(Q!=null)for(J in Q.ref!==void 0&&(me=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:me,props:oe,_owner:Z.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 me=!1;if(T===null)me=!0;else switch(fe){case"string":case"number":me=!0;break;case"object":switch(T.$$typeof){case e:case t:me=!0}}if(me)return me=T,oe=oe(me),T=J===""?"."+C(me,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||me&&me.key===oe.key?"":(""+oe.key).replace(F,"$&/")+"/")+T)),Q.push(oe)),1;if(me=0,J=J===""?".":J+":",M(T))for(var we=0;we<T.length;we++){fe=T[we];var Ae=J+C(fe,we);me+=N(fe,Q,K,Ae,oe)}else if(Ae=y(T),typeof Ae=="function")for(T=Ae.call(T),we=0;!(fe=T.next()).done;)fe=fe.value,Ae=J+C(fe,we++),me+=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 me}function O(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 P(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:Z};function G(){throw Error("act(...) is not supported in production builds of React.")}return Gt.Children={map:O,forEach:function(T,Q,K){O(T,function(){Q.apply(this,arguments)},K)},count:function(T){var Q=0;return O(T,function(){Q++}),Q},toArray:function(T){return O(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}},Gt.Component=$,Gt.Fragment=n,Gt.Profiler=o,Gt.PureComponent=L,Gt.StrictMode=i,Gt.Suspense=f,Gt.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=z,Gt.act=G,Gt.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,me=T._owner;if(Q!=null){if(Q.ref!==void 0&&(fe=Q.ref,me=Z.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:me}},Gt.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},Gt.createElement=X,Gt.createFactory=function(T){var Q=X.bind(null,T);return Q.type=T,Q},Gt.createRef=function(){return{current:null}},Gt.forwardRef=function(T){return{$$typeof:c,render:T}},Gt.isValidElement=ie,Gt.lazy=function(T){return{$$typeof:p,_payload:{_status:-1,_result:T},_init:P}},Gt.memo=function(T,Q){return{$$typeof:_,type:T,compare:Q===void 0?null:Q}},Gt.startTransition=function(T){var Q=B.transition;B.transition={};try{T()}finally{B.transition=Q}},Gt.unstable_act=G,Gt.useCallback=function(T,Q){return ne.current.useCallback(T,Q)},Gt.useContext=function(T){return ne.current.useContext(T)},Gt.useDebugValue=function(){},Gt.useDeferredValue=function(T){return ne.current.useDeferredValue(T)},Gt.useEffect=function(T,Q){return ne.current.useEffect(T,Q)},Gt.useId=function(){return ne.current.useId()},Gt.useImperativeHandle=function(T,Q,K){return ne.current.useImperativeHandle(T,Q,K)},Gt.useInsertionEffect=function(T,Q){return ne.current.useInsertionEffect(T,Q)},Gt.useLayoutEffect=function(T,Q){return ne.current.useLayoutEffect(T,Q)},Gt.useMemo=function(T,Q){return ne.current.useMemo(T,Q)},Gt.useReducer=function(T,Q,K){return ne.current.useReducer(T,Q,K)},Gt.useRef=function(T){return ne.current.useRef(T)},Gt.useState=function(T){return ne.current.useState(T)},Gt.useSyncExternalStore=function(T,Q,K){return ne.current.useSyncExternalStore(T,Q,K)},Gt.useTransition=function(){return ne.current.useTransition()},Gt.version="18.3.1",Gt}var Wg;function bf(){return Wg||(Wg=1,g_.exports=f0()),g_.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 qg;function h0(){if(qg)return zd;qg=1;var e=bf(),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,w={},y=null,x=null;_!==void 0&&(y=""+_),f.key!==void 0&&(y=""+f.key),f.ref!==void 0&&(x=f.ref);for(p in f)i.call(f,p)&&!l.hasOwnProperty(p)&&(w[p]=f[p]);if(c&&c.defaultProps)for(p in f=c.defaultProps,f)w[p]===void 0&&(w[p]=f[p]);return{$$typeof:t,type:c,key:y,ref:x,props:w,_owner:o.current}}return zd.Fragment=n,zd.jsx=u,zd.jsxs=u,zd}var Hg;function m0(){return Hg||(Hg=1,p_.exports=h0()),p_.exports}var s=m0(),m=bf();const ve=tg(m);var Dh={},y_={exports:{}},Hr={},w_={exports:{}},v_={};/**
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 Vg;function _0(){return Vg||(Vg=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,me=B[fe];if(0>o(oe,G))fe<Q&&0>o(me,oe)?(B[T]=me,B[fe]=G,T=fe):(B[T]=oe,B[J]=G,T=J);else if(fe<Q&&0>o(me,G))B[T]=me,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,w=null,y=3,x=!1,S=!1,b=!1,$=typeof setTimeout=="function"?setTimeout:null,E=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 D(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(b=!1,D(B),!S)if(n(f)!==null)S=!0,P(H);else{var z=n(_);z!==null&&ne(M,z.startTime-B)}}function H(B,z){S=!1,b&&(b=!1,E(X),X=-1),x=!0;var G=y;try{for(D(z),w=n(f);w!==null&&(!(w.expirationTime>z)||B&&!ue());){var T=w.callback;if(typeof T=="function"){w.callback=null,y=w.priorityLevel;var Q=T(w.expirationTime<=z);z=e.unstable_now(),typeof Q=="function"?w.callback=Q:w===n(f)&&i(f),D(z)}else i(f);w=n(f)}if(w!==null)var K=!0;else{var J=n(_);J!==null&&ne(M,J.startTime-z),K=!1}return K}finally{w=null,y=G,x=!1}}var Z=!1,Y=null,X=-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():(Z=!1,Y=null)}}else Z=!1}var C;if(typeof L=="function")C=function(){L(F)};else if(typeof MessageChannel<"u"){var N=new MessageChannel,O=N.port2;N.port1.onmessage=F,C=function(){O.postMessage(null)}}else C=function(){$(F,0)};function P(B){Y=B,Z||(Z=!0,C())}function ne(B,z){X=$(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,P(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 y},e.unstable_getFirstCallbackNode=function(){return n(f)},e.unstable_next=function(B){switch(y){case 1:case 2:case 3:var z=3;break;default:z=y}var G=y;y=z;try{return B()}finally{y=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=y;y=B;try{return z()}finally{y=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(_)&&(b?(E(X),X=-1):b=!0,ne(M,G-T))):(B.sortIndex=Q,t(f,B),S||x||(S=!0,P(H))),B},e.unstable_shouldYield=ue,e.unstable_wrapCallback=function(B){var z=y;return function(){var G=y;y=z;try{return B.apply(this,arguments)}finally{y=G}}}})(v_)),v_}var Gg;function p0(){return Gg||(Gg=1,w_.exports=_0()),w_.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 Kg;function g0(){if(Kg)return Hr;Kg=1;var e=bf(),t=p0();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={},w={};function y(r){return f.call(w,r)?!0:f.call(p,r)?!1:_.test(r)?w[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 b(r,a,d,h,v,j,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=j,this.removeEmptyString=R}var $={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(r){$[r]=new b(r,0,!1,r,null,!1,!1)}),[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(r){var a=r[0];$[a]=new b(a,1,!1,r[1],null,!1,!1)}),["contentEditable","draggable","spellCheck","value"].forEach(function(r){$[r]=new b(r,2,!1,r.toLowerCase(),null,!1,!1)}),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(r){$[r]=new b(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){$[r]=new b(r,3,!1,r.toLowerCase(),null,!1,!1)}),["checked","multiple","muted","selected"].forEach(function(r){$[r]=new b(r,3,!0,r,null,!1,!1)}),["capture","download"].forEach(function(r){$[r]=new b(r,4,!1,r,null,!1,!1)}),["cols","rows","size","span"].forEach(function(r){$[r]=new b(r,6,!1,r,null,!1,!1)}),["rowSpan","start"].forEach(function(r){$[r]=new b(r,5,!1,r.toLowerCase(),null,!1,!1)});var E=/[\-:]([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(E,L);$[a]=new b(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(E,L);$[a]=new b(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(E,L);$[a]=new b(a,1,!1,r,"http://www.w3.org/XML/1998/namespace",!1,!1)}),["tabIndex","crossOrigin"].forEach(function(r){$[r]=new b(r,1,!1,r.toLowerCase(),null,!1,!1)}),$.xlinkHref=new b("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1),["src","href","action","formAction"].forEach(function(r){$[r]=new b(r,1,!1,r.toLowerCase(),null,!0,!0)});function D(r,a,d,h){var v=$.hasOwnProperty(a)?$[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?y(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"),Z=Symbol.for("react.portal"),Y=Symbol.for("react.fragment"),X=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"),O=Symbol.for("react.memo"),P=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
- `),j=h.stack.split(`
36
- `),R=v.length-1,ee=j.length-1;1<=R&&0<=ee&&v[R]!==j[ee];)ee--;for(;1<=R&&0<=ee;R--,ee--)if(v[R]!==j[ee]){if(R!==1||ee!==1)do if(R--,ee--,0>ee||v[R]!==j[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 Z:return"Portal";case re:return"Profiler";case X: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 O:return a=r.displayName||null,a!==null?a:fe(r.type)||"Memo";case P:a=r._payload,r=r._init;try{return fe(r(a))}catch{}}return null}function me(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===X?"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,j=d.set;return Object.defineProperty(r,a,{configurable:!0,get:function(){return v.call(this)},set:function(R){h=""+R,j.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&&D(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 Qt(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 _n(r){var a=r.textContent;a===r._wrapperState.initialValue&&a!==""&&a!==null&&(r.value=a)}function Ut(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"?Ut(a):r==="http://www.w3.org/2000/svg"&&a==="foreignObject"?"http://www.w3.org/1999/xhtml":r}var un,Bn=(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(un=un||document.createElement("div"),un.innerHTML="<svg>"+a.valueOf().toString()+"</svg>",a=un.firstChild;r.firstChild;)r.removeChild(r.firstChild);for(;a.firstChild;)r.appendChild(a.firstChild)}});function Mt(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},Dn=["Webkit","ms","Moz","O"];Object.keys(bn).forEach(function(r){Dn.forEach(function(a){a=a+r.charAt(0).toUpperCase()+r.substring(1),bn[a]=bn[r]})});function En(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=En(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 wn(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 Cs(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 Kn=null;function ls(r){return r=r.target||r.srcElement||window,r.correspondingUseElement&&(r=r.correspondingUseElement),r.nodeType===3?r.parentNode:r}var Cr=null,Yn=null,ce=null;function be(r){if(r=Ta(r)){if(typeof Cr!="function")throw Error(n(280));var a=r.stateNode;a&&(a=Pc(a),Cr(r.stateNode,r.type,a))}}function Ge(r){Yn?ce?ce.push(r):ce=[r]:Yn=r}function Ve(){if(Yn){var r=Yn,a=ce;if(ce=Yn=null,be(r),a)for(r=0;r<a.length;r++)be(a[r])}}function st(r,a){return r(a)}function ut(){}var Et=!1;function jt(r,a,d){if(Et)return r(a,d);Et=!0;try{return st(r,a,d)}finally{Et=!1,(Yn!==null||ce!==null)&&(ut(),Ve())}}function qt(r,a){var d=r.stateNode;if(d===null)return null;var h=Pc(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 Yt={};Object.defineProperty(Yt,"passive",{get:function(){dt=!0}}),window.addEventListener("test",Yt,Yt),window.removeEventListener("test",Yt,Yt)}catch{dt=!1}function Bt(r,a,d,h,v,j,R,ee,se){var ye=Array.prototype.slice.call(arguments,3);try{a.apply(d,ye)}catch(Me){this.onError(Me)}}var Nt=!1,pt=null,Ot=!1,$e=null,Wt={onError:function(r){Nt=!0,pt=r}};function Ct(r,a,d,h,v,j,R,ee,se){Nt=!1,pt=null,Bt.apply(Wt,arguments)}function rn(r,a,d,h,v,j,R,ee,se){if(Ct.apply(this,arguments),Nt){if(Nt){var ye=pt;Nt=!1,pt=null}else throw Error(n(198));Ot||(Ot=!0,$e=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 cs(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 us(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 j=v.alternate;if(j===null){if(h=v.return,h!==null){d=h;continue}break}if(v.child===j.child){for(j=v.child;j;){if(j===d)return us(v),r;if(j===h)return us(v),a;j=j.sibling}throw Error(n(188))}if(d.return!==h.return)d=v,h=j;else{for(var R=!1,ee=v.child;ee;){if(ee===d){R=!0,d=v,h=j;break}if(ee===h){R=!0,h=v,d=j;break}ee=ee.sibling}if(!R){for(ee=j.child;ee;){if(ee===d){R=!0,d=j,h=v;break}if(ee===h){R=!0,h=j,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 $s(r){return r=Js(r),r!==null?fr(r):null}function fr(r){if(r.tag===5||r.tag===6)return r;for(r=r.child;r!==null;){var a=fr(r);if(a!==null)return a;r=r.sibling}return null}var Xs=t.unstable_scheduleCallback,so=t.unstable_cancelCallback,xe=t.unstable_shouldYield,Jn=t.unstable_requestPaint,hn=t.unstable_now,ro=t.unstable_getCurrentPriorityLevel,$i=t.unstable_ImmediatePriority,$r=t.unstable_UserBlockingPriority,hr=t.unstable_NormalPriority,Kr=t.unstable_LowPriority,it=t.unstable_IdlePriority,tn=null,gs=null;function oi(r){if(gs&&typeof gs.onCommitFiberRoot=="function")try{gs.onCommitFiberRoot(tn,r,void 0,(r.current.flags&128)===128)}catch{}}var ds=Math.clz32?Math.clz32:ya,io=Math.log,oo=Math.LN2;function ya(r){return r>>>=0,r===0?32:31-(io(r)/oo|0)|0}var Fn=64,mr=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 _r(r,a){var d=r.pendingLanes;if(d===0)return 0;var h=0,v=r.suspendedLanes,j=r.pingedLanes,R=d&268435455;if(R!==0){var ee=R&~v;ee!==0?h=Tn(ee):(j&=R,j!==0&&(h=Tn(j)))}else R=d&~v,R!==0?h=Tn(R):j!==0&&(h=Tn(j));if(h===0)return 0;if(a!==0&&a!==h&&(a&v)===0&&(v=h&-h,j=a&-a,v>=j||v===16&&(j&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-ds(a),v=1<<d,h|=r[d],a&=~v;return h}function ao(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 Qn(r,a){for(var d=r.suspendedLanes,h=r.pingedLanes,v=r.expirationTimes,j=r.pendingLanes;0<j;){var R=31-ds(j),ee=1<<R,se=v[R];se===-1?((ee&d)===0||(ee&h)!==0)&&(v[R]=ao(ee,a)):se<=a&&(r.expiredLanes|=ee),j&=~ee}}function Zs(r){return r=r.pendingLanes&-1073741825,r!==0?r:r&1073741824?1073741824:0}function fs(){var r=Fn;return Fn<<=1,(Fn&4194240)===0&&(Fn=64),r}function Yr(r){for(var a=[],d=0;31>d;d++)a.push(r);return a}function ys(r,a,d){r.pendingLanes|=a,a!==536870912&&(r.suspendedLanes=0,r.pingedLanes=0),r=r.eventTimes,a=31-ds(a),r[a]=d}function wa(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-ds(d),j=1<<v;a[v]=0,h[v]=-1,r[v]=-1,d&=~j}}function lo(r,a){var d=r.entangledLanes|=a;for(r=r.entanglements;d;){var h=31-ds(d),v=1<<h;v&a|r[h]&a&&(r[h]|=a),d&=~v}}var nn=0;function ml(r){return r&=-r,1<r?4<r?(r&268435455)!==0?16:536870912:4:1}var Ai,pr,As,va,Ar,ai=!1,Ei=[],Qs=null,Es=null,Er=null,er=new Map,Ti=new Map,gr=[],ws="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":Es=null;break;case"mouseover":case"mouseout":Er=null;break;case"pointerover":case"pointerout":er.delete(a.pointerId);break;case"gotpointercapture":case"lostpointercapture":Ti.delete(a.pointerId)}}function Lo(r,a,d,h,v,j){return r===null||r.nativeEvent!==j?(r={blockedOn:a,domEventName:d,eventSystemFlags:h,nativeEvent:j,targetContainers:[v]},a!==null&&(a=Ta(a),a!==null&&pr(a)),r):(r.eventSystemFlags|=h,a=r.targetContainers,v!==null&&a.indexOf(v)===-1&&a.push(v),r)}function _l(r,a,d,h,v){switch(a){case"focusin":return Qs=Lo(Qs,r,a,d,h,v),!0;case"dragenter":return Es=Lo(Es,r,a,d,h,v),!0;case"mouseover":return Er=Lo(Er,r,a,d,h,v),!0;case"pointerover":var j=v.pointerId;return er.set(j,Lo(er.get(j)||null,r,a,d,h,v)),!0;case"gotpointercapture":return j=v.pointerId,Ti.set(j,Lo(Ti.get(j)||null,r,a,d,h,v)),!0}return!1}function tr(r){var a=Go(r.target);if(a!==null){var d=$t(a);if(d!==null){if(a=d.tag,a===13){if(a=cs(d),a!==null){r.blockedOn=a,Ar(r.priority,function(){As(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 Io(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);Kn=h,d.target.dispatchEvent(h),Kn=null}else return a=Ta(d),a!==null&&pr(a),r.blockedOn=d,!1;a.shift()}return!0}function Jr(r,a,d){Io(r)&&d.delete(a)}function _c(){ai=!1,Qs!==null&&Io(Qs)&&(Qs=null),Es!==null&&Io(Es)&&(Es=null),Er!==null&&Io(Er)&&(Er=null),er.forEach(Jr),Ti.forEach(Jr)}function yr(r,a){r.blockedOn===a&&(r.blockedOn=null,ai||(ai=!0,t.unstable_scheduleCallback(t.unstable_NormalPriority,_c)))}function co(r){function a(v){return yr(v,r)}if(0<Ei.length){yr(Ei[0],r);for(var d=1;d<Ei.length;d++){var h=Ei[d];h.blockedOn===r&&(h.blockedOn=null)}}for(Qs!==null&&yr(Qs,r),Es!==null&&yr(Es,r),Er!==null&&yr(Er,r),er.forEach(a),Ti.forEach(a),d=0;d<gr.length;d++)h=gr[d],h.blockedOn===r&&(h.blockedOn=null);for(;0<gr.length&&(d=gr[0],d.blockedOn===null);)tr(d),d.blockedOn===null&&gr.shift()}var zs=M.ReactCurrentBatchConfig,Oo=!0;function Po(r,a,d,h){var v=nn,j=zs.transition;zs.transition=null;try{nn=1,uo(r,a,d,h)}finally{nn=v,zs.transition=j}}function Do(r,a,d,h){var v=nn,j=zs.transition;zs.transition=null;try{nn=4,uo(r,a,d,h)}finally{nn=v,zs.transition=j}}function uo(r,a,d,h){if(Oo){var v=ae(r,a,d,h);if(v===null)Oi(r,a,h,U,d),Mi(r,h);else if(_l(v,r,a,d,h))h.stopPropagation();else if(Mi(r,h),a&4&&-1<ws.indexOf(r)){for(;v!==null;){var j=Ta(v);if(j!==null&&Ai(j),j=ae(r,a,d,h),j===null&&Oi(r,a,h,U,d),j===v)break;v=j}v!==null&&h.stopPropagation()}else Oi(r,a,h,null,d)}}var U=null;function ae(r,a,d,h){if(U=null,r=ls(h),r=Go(r),r!==null)if(a=$t(r),a===null)r=null;else if(d=a.tag,d===13){if(r=cs(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(ro()){case $i:return 1;case $r:return 4;case hr:case Kr:return 16;case it:return 536870912;default:return 16}default:return 16}}var Ce=null,ke=null,Ue=null;function ft(){if(Ue)return Ue;var r,a=ke,d=a.length,h,v="value"in Ce?Ce.value:Ce.textContent,j=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[j-h];h++);return Ue=v.slice(r,1<h?1-h:void 0)}function ot(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 Ht(r){function a(d,h,v,j,R){this._reactName=d,this._targetInst=v,this.type=h,this.nativeEvent=j,this.target=R,this.currentTarget=null;for(var ee in r)r.hasOwnProperty(ee)&&(d=r[ee],this[ee]=d?d(j):j[ee]);return this.isDefaultPrevented=(j.defaultPrevented!=null?j.defaultPrevented:j.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 vs={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(r){return r.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},Rt=Ht(vs),sn=G({},vs,{view:0,detail:0}),Cn=Ht(sn),mn,es,nr,Xr=G({},sn,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:Ku,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"?(mn=r.screenX-nr.screenX,es=r.screenY-nr.screenY):es=mn=0,nr=r),mn)},movementY:function(r){return"movementY"in r?r.movementY:es}}),Ri=Ht(Xr),xa=G({},Xr,{dataTransfer:0}),Af=Ht(xa),pc=G({},sn,{relatedTarget:0}),pl=Ht(pc),gc=G({},vs,{animationName:0,elapsedTime:0,pseudoElement:0}),yc=Ht(gc),wc=G({},vs,{clipboardData:function(r){return"clipboardData"in r?r.clipboardData:window.clipboardData}}),Ef=Ht(wc),Fo=G({},vs,{data:0}),Wu=Ht(Fo),qu={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},Hu={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"},Vu={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function Gu(r){var a=this.nativeEvent;return a.getModifierState?a.getModifierState(r):(r=Vu[r])?!!a[r]:!1}function Ku(){return Gu}var Yu=G({},sn,{key:function(r){if(r.key){var a=qu[r.key]||r.key;if(a!=="Unidentified")return a}return r.type==="keypress"?(r=ot(r),r===13?"Enter":String.fromCharCode(r)):r.type==="keydown"||r.type==="keyup"?Hu[r.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:Ku,charCode:function(r){return r.type==="keypress"?ot(r):0},keyCode:function(r){return r.type==="keydown"||r.type==="keyup"?r.keyCode:0},which:function(r){return r.type==="keypress"?ot(r):r.type==="keydown"||r.type==="keyup"?r.keyCode:0}}),Jm=Ht(Yu),Tf=G({},Xr,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),vc=Ht(Tf),en=G({},sn,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:Ku}),Ju=Ht(en),Xm=G({},vs,{propertyName:0,elapsedTime:0,pseudoElement:0}),Xu=Ht(Xm),Zm=G({},Xr,{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}),Zu=Ht(Zm),Qm=[9,13,27,32],ts=c&&"CompositionEvent"in window,Bs=null;c&&"documentMode"in document&&(Bs=document.documentMode);var gl=c&&"TextEvent"in window&&!Bs,Mf=c&&(!ts||Bs&&8<Bs&&11>=Bs),ba=" ",xc=!1;function Rf(r,a){switch(r){case"keyup":return Qm.indexOf(a.keyCode)!==-1;case"keydown":return a.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Qu(r){return r=r.detail,typeof r=="object"&&"data"in r?r.data:null}var fo=!1;function ed(r,a){switch(r){case"compositionend":return Qu(a);case"keypress":return a.which!==32?null:(xc=!0,ba);case"textInput":return r=a.data,r===ba&&xc?null:r;default:return null}}function Lf(r,a){if(fo)return r==="compositionend"||!ts&&Rf(r,a)?(r=ft(),Ue=ke=Ce=null,fo=!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 Mf&&a.locale!=="ko"?null:a.data;default:return null}}var bc={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 td(r){var a=r&&r.nodeName&&r.nodeName.toLowerCase();return a==="input"?!!bc[r.type]:a==="textarea"}function nd(r,a,d,h){Ge(h),a=Ho(a,"onChange"),0<a.length&&(d=new Rt("onChange","change",null,d,h),r.push({event:d,listeners:a}))}var yl=null,ho=null;function If(r){di(r,0)}function ja(r){var a=_i(r);if(_t(a))return r}function e_(r,a){if(r==="change")return a}var jc=!1;if(c){var sd;if(c){var Sc="oninput"in document;if(!Sc){var Of=document.createElement("div");Of.setAttribute("oninput","return;"),Sc=typeof Of.oninput=="function"}sd=Sc}else sd=!1;jc=sd&&(!document.documentMode||9<document.documentMode)}function kc(){yl&&(yl.detachEvent("onpropertychange",Pf),ho=yl=null)}function Pf(r){if(r.propertyName==="value"&&ja(ho)){var a=[];nd(a,ho,r,ls(r)),jt(If,a)}}function rd(r,a,d){r==="focusin"?(kc(),yl=a,ho=d,yl.attachEvent("onpropertychange",Pf)):r==="focusout"&&kc()}function t_(r){if(r==="selectionchange"||r==="keyup"||r==="keydown")return ja(ho)}function n_(r,a){if(r==="click")return ja(a)}function s_(r,a){if(r==="input"||r==="change")return ja(a)}function Sa(r,a){return r===a&&(r!==0||1/r===1/a)||r!==r&&a!==a}var Tr=typeof Object.is=="function"?Object.is:Sa;function mo(r,a){if(Tr(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)||!Tr(r[v],a[v]))return!1}return!0}function Df(r){for(;r&&r.firstChild;)r=r.firstChild;return r}function wl(r,a){var d=Df(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=Df(d)}}function zo(r,a){return r&&a?r===a?!0:r&&r.nodeType===3?!1:a&&a.nodeType===3?zo(r,a.parentNode):"contains"in r?r.contains(a):r.compareDocumentPosition?!!(r.compareDocumentPosition(a)&16):!1:!1}function ka(){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 _o(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 vl(r){var a=ka(),d=r.focusedElem,h=r.selectionRange;if(a!==d&&d&&d.ownerDocument&&zo(d.ownerDocument.documentElement,d)){if(h!==null&&_o(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,j=Math.min(h.start,v);h=h.end===void 0?j:Math.min(h.end,v),!r.extend&&j>h&&(v=h,h=j,j=v),v=wl(d,j);var R=wl(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(),j>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 Nc=c&&"documentMode"in document&&11>=document.documentMode,po=null,Cc=null,Li=null,$c=!1;function Na(r,a,d){var h=d.window===d?d.document:d.nodeType===9?d:d.ownerDocument;$c||po==null||po!==Pe(h)||(h=po,"selectionStart"in h&&_o(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&&mo(Li,h)||(Li=h,h=Ho(Cc,"onSelect"),0<h.length&&(a=new Rt("onSelect","select",null,a,d),r.push({event:a,listeners:h}),a.target=po)))}function Bo(r,a){var d={};return d[r.toLowerCase()]=a.toLowerCase(),d["Webkit"+r]="webkit"+a,d["Moz"+r]="moz"+a,d}var Ca={animationend:Bo("Animation","AnimationEnd"),animationiteration:Bo("Animation","AnimationIteration"),animationstart:Bo("Animation","AnimationStart"),transitionend:Bo("Transition","TransitionEnd")},Ac={},Ff={};c&&(Ff=document.createElement("div").style,"AnimationEvent"in window||(delete Ca.animationend.animation,delete Ca.animationiteration.animation,delete Ca.animationstart.animation),"TransitionEvent"in window||delete Ca.transitionend.transition);function Ec(r){if(Ac[r])return Ac[r];if(!Ca[r])return r;var a=Ca[r],d;for(d in a)if(a.hasOwnProperty(d)&&d in Ff)return Ac[r]=a[d];return r}var xl=Ec("animationend"),li=Ec("animationiteration"),Uo=Ec("animationstart"),zf=Ec("transitionend"),bl=new Map,Bf="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 ci(r,a){bl.set(r,a),l(a,[r])}for(var Wo=0;Wo<Bf.length;Wo++){var sr=Bf[Wo],go=sr.toLowerCase(),Tc=sr[0].toUpperCase()+sr.slice(1);ci(go,"on"+Tc)}ci(xl,"onAnimationEnd"),ci(li,"onAnimationIteration"),ci(Uo,"onAnimationStart"),ci("dblclick","onDoubleClick"),ci("focusin","onFocus"),ci("focusout","onBlur"),ci(zf,"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 ui="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(" "),id=new Set("cancel close invalid load scroll toggle".split(" ").concat(ui));function $a(r,a,d){var h=r.type||"unknown-event";r.currentTarget=d,rn(h,a,void 0,r),r.currentTarget=null}function di(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 j=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!==j&&v.isPropagationStopped())break e;$a(v,ee,ye),j=se}else for(R=0;R<h.length;R++){if(ee=h[R],se=ee.instance,ye=ee.currentTarget,ee=ee.listener,se!==j&&v.isPropagationStopped())break e;$a(v,ee,ye),j=se}}}if(Ot)throw r=$e,Ot=!1,$e=null,r}function pn(r,a){var d=a[Oc];d===void 0&&(d=a[Oc]=new Set);var h=r+"__bubble";d.has(h)||(Us(a,r,2,!1),d.add(h))}function qo(r,a,d){var h=0;a&&(h|=4),Us(d,r,h,a)}var Ii="_reactListening"+Math.random().toString(36).slice(2);function Mr(r){if(!r[Ii]){r[Ii]=!0,i.forEach(function(d){d!=="selectionchange"&&(id.has(d)||qo(d,!1,r),qo(d,!0,r))});var a=r.nodeType===9?r:r.ownerDocument;a===null||a[Ii]||(a[Ii]=!0,qo("selectionchange",!1,a))}}function Us(r,a,d,h){switch(je(a)){case 1:var v=Po;break;case 4:v=Do;break;default:v=uo}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 j=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=Go(ee),R===null)return;if(se=R.tag,se===5||se===6){h=j=R;continue e}ee=ee.parentNode}}h=h.return}jt(function(){var ye=j,Me=ls(d),Re=[];e:{var Te=bl.get(r);if(Te!==void 0){var Je=Rt,tt=r;switch(r){case"keypress":if(ot(d)===0)break e;case"keydown":case"keyup":Je=Jm;break;case"focusin":tt="focus",Je=pl;break;case"focusout":tt="blur",Je=pl;break;case"beforeblur":case"afterblur":Je=pl;break;case"click":if(d.button===2)break e;case"auxclick":case"dblclick":case"mousedown":case"mousemove":case"mouseup":case"mouseout":case"mouseover":case"contextmenu":Je=Ri;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":Je=Af;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":Je=Ju;break;case xl:case li:case Uo:Je=yc;break;case zf:Je=Xu;break;case"scroll":Je=Cn;break;case"wheel":Je=Zu;break;case"copy":case"cut":case"paste":Je=Ef;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":Je=vc}var nt=(a&4)!==0,as=!nt&&r==="scroll",de=nt?Te!==null?Te+"Capture":null:Te;nt=[];for(var le=ye,he;le!==null;){he=le;var Fe=he.stateNode;if(he.tag===5&&Fe!==null&&(he=Fe,de!==null&&(Fe=qt(le,de),Fe!=null&&nt.push(fi(le,Fe,he)))),as)break;le=le.return}0<nt.length&&(Te=new Je(Te,tt,null,d,Me),Re.push({event:Te,listeners:nt}))}}if((a&7)===0){e:{if(Te=r==="mouseover"||r==="pointerover",Je=r==="mouseout"||r==="pointerout",Te&&d!==Kn&&(tt=d.relatedTarget||d.fromElement)&&(Go(tt)||tt[Fi]))break e;if((Je||Te)&&(Te=Me.window===Me?Me:(Te=Me.ownerDocument)?Te.defaultView||Te.parentWindow:window,Je?(tt=d.relatedTarget||d.toElement,Je=ye,tt=tt?Go(tt):null,tt!==null&&(as=$t(tt),tt!==as||tt.tag!==5&&tt.tag!==6)&&(tt=null)):(Je=null,tt=ye),Je!==tt)){if(nt=Ri,Fe="onMouseLeave",de="onMouseEnter",le="mouse",(r==="pointerout"||r==="pointerover")&&(nt=vc,Fe="onPointerLeave",de="onPointerEnter",le="pointer"),as=Je==null?Te:_i(Je),he=tt==null?Te:_i(tt),Te=new nt(Fe,le+"leave",Je,d,Me),Te.target=as,Te.relatedTarget=he,Fe=null,Go(Me)===ye&&(nt=new nt(de,le+"enter",tt,d,Me),nt.target=he,nt.relatedTarget=as,Fe=nt),as=Fe,Je&&tt)t:{for(nt=Je,de=tt,le=0,he=nt;he;he=Rr(he))le++;for(he=0,Fe=de;Fe;Fe=Rr(Fe))he++;for(;0<le-he;)nt=Rr(nt),le--;for(;0<he-le;)de=Rr(de),he--;for(;le--;){if(nt===de||de!==null&&nt===de.alternate)break t;nt=Rr(nt),de=Rr(de)}nt=null}else nt=null;Je!==null&&Mc(Re,Te,Je,nt,!1),tt!==null&&as!==null&&Mc(Re,as,tt,nt,!0)}}e:{if(Te=ye?_i(ye):window,Je=Te.nodeName&&Te.nodeName.toLowerCase(),Je==="select"||Je==="input"&&Te.type==="file")var rt=e_;else if(td(Te))if(jc)rt=s_;else{rt=t_;var yt=rd}else(Je=Te.nodeName)&&Je.toLowerCase()==="input"&&(Te.type==="checkbox"||Te.type==="radio")&&(rt=n_);if(rt&&(rt=rt(r,ye))){nd(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?_i(ye):window,r){case"focusin":(td(yt)||yt.contentEditable==="true")&&(po=yt,Cc=ye,Li=null);break;case"focusout":Li=Cc=po=null;break;case"mousedown":$c=!0;break;case"contextmenu":case"mouseup":case"dragend":$c=!1,Na(Re,d,Me);break;case"selectionchange":if(Nc)break;case"keydown":case"keyup":Na(Re,d,Me)}var wt;if(ts)e:{switch(r){case"compositionstart":var St="onCompositionStart";break e;case"compositionend":St="onCompositionEnd";break e;case"compositionupdate":St="onCompositionUpdate";break e}St=void 0}else fo?Rf(r,d)&&(St="onCompositionEnd"):r==="keydown"&&d.keyCode===229&&(St="onCompositionStart");St&&(Mf&&d.locale!=="ko"&&(fo||St!=="onCompositionStart"?St==="onCompositionEnd"&&fo&&(wt=ft()):(Ce=Me,ke="value"in Ce?Ce.value:Ce.textContent,fo=!0)),yt=Ho(ye,St),0<yt.length&&(St=new Wu(St,r,null,d,Me),Re.push({event:St,listeners:yt}),wt?St.data=wt:(wt=Qu(d),wt!==null&&(St.data=wt)))),(wt=gl?ed(r,d):Lf(r,d))&&(ye=Ho(ye,"onBeforeInput"),0<ye.length&&(Me=new Wu("onBeforeInput","beforeinput",null,d,Me),Re.push({event:Me,listeners:ye}),Me.data=wt))}di(Re,a)})}function fi(r,a,d){return{instance:r,listener:a,currentTarget:d}}function Ho(r,a){for(var d=a+"Capture",h=[];r!==null;){var v=r,j=v.stateNode;v.tag===5&&j!==null&&(v=j,j=qt(r,d),j!=null&&h.unshift(fi(r,j,v)),j=qt(r,a),j!=null&&h.push(fi(r,j,v))),r=r.return}return h}function Rr(r){if(r===null)return null;do r=r.return;while(r&&r.tag!==5);return r||null}function Mc(r,a,d,h,v){for(var j=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=qt(d,j),se!=null&&R.unshift(fi(d,se,ee))):v||(se=qt(d,j),se!=null&&R.push(fi(d,se,ee)))),d=d.return}R.length!==0&&r.push({event:a,listeners:R})}var Rc=/\r\n?/g,hi=/\u0000|\uFFFD/g;function Pi(r){return(typeof r=="string"?r:""+r).replace(Rc,`
38
- `).replace(hi,"")}function wr(r,a,d){if(a=Pi(a),Pi(r)!==a&&d)throw Error(n(425))}function jl(){}var Sl=null,od=null;function Aa(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 Lc=typeof setTimeout=="function"?setTimeout:void 0,kl=typeof clearTimeout=="function"?clearTimeout:void 0,ad=typeof Promise=="function"?Promise:void 0,ld=typeof queueMicrotask=="function"?queueMicrotask:typeof ad<"u"?function(r){return ad.resolve(null).then(r).catch(Uf)}:Lc;function Uf(r){setTimeout(function(){throw r})}function Ic(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),co(a);return}h--}else d!=="$"&&d!=="$?"&&d!=="$!"||h++;d=v}while(d);co(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 Wf(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 Vo=Math.random().toString(36).slice(2),mi="__reactFiber$"+Vo,Ea="__reactProps$"+Vo,Fi="__reactContainer$"+Vo,Oc="__reactEvents$"+Vo,r_="__reactListeners$"+Vo,qf="__reactHandles$"+Vo;function Go(r){var a=r[mi];if(a)return a;for(var d=r.parentNode;d;){if(a=d[Fi]||d[mi]){if(d=a.alternate,a.child!==null||d!==null&&d.child!==null)for(r=Wf(r);r!==null;){if(d=r[mi])return d;r=Wf(r)}return a}r=d,d=r.parentNode}return null}function Ta(r){return r=r[mi]||r[Fi],!r||r.tag!==5&&r.tag!==6&&r.tag!==13&&r.tag!==3?null:r}function _i(r){if(r.tag===5||r.tag===6)return r.stateNode;throw Error(n(33))}function Pc(r){return r[Ea]||null}var Ko=[],yo=-1;function Zr(r){return{current:r}}function Sn(r){0>yo||(r.current=Ko[yo],Ko[yo]=null,yo--)}function on(r,a){yo++,Ko[yo]=r.current,r.current=a}var wo={},ns=Zr(wo),rr=Zr(!1),Lr=wo;function Ma(r,a){var d=r.type.contextTypes;if(!d)return wo;var h=r.stateNode;if(h&&h.__reactInternalMemoizedUnmaskedChildContext===a)return h.__reactInternalMemoizedMaskedChildContext;var v={},j;for(j in d)v[j]=a[j];return h&&(r=r.stateNode,r.__reactInternalMemoizedUnmaskedChildContext=a,r.__reactInternalMemoizedMaskedChildContext=v),v}function xs(r){return r=r.childContextTypes,r!=null}function Dc(){Sn(rr),Sn(ns)}function zi(r,a,d){if(ns.current!==wo)throw Error(n(168));on(ns,a),on(rr,d)}function cd(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,me(r)||"Unknown",v));return G({},d,h)}function vo(r){return r=(r=r.stateNode)&&r.__reactInternalMemoizedMergedChildContext||wo,Lr=ns.current,on(ns,r),on(rr,rr.current),!0}function Ra(r,a,d){var h=r.stateNode;if(!h)throw Error(n(169));d?(r=cd(r,a,Lr),h.__reactInternalMemoizedMergedChildContext=r,Sn(rr),Sn(ns),on(ns,r)):Sn(rr),on(rr,d)}var pi=null,La=!1,Yo=!1;function Fc(r){pi===null?pi=[r]:pi.push(r)}function Ia(r){La=!0,Fc(r)}function gi(){if(!Yo&&pi!==null){Yo=!0;var r=0,a=nn;try{var d=pi;for(nn=1;r<d.length;r++){var h=d[r];do h=h(!0);while(h!==null)}pi=null,La=!1}catch(v){throw pi!==null&&(pi=pi.slice(r+1)),Xs($i,gi),v}finally{nn=a,Yo=!1}}return null}var Oa=[],xo=0,Nl=null,zc=0,Ir=[],bs=0,Un=null,Or=1,Qr="";function Jo(r,a){Oa[xo++]=zc,Oa[xo++]=Nl,Nl=r,zc=a}function Hf(r,a,d){Ir[bs++]=Or,Ir[bs++]=Qr,Ir[bs++]=Un,Un=r;var h=Or;r=Qr;var v=32-ds(h)-1;h&=~(1<<v),d+=1;var j=32-ds(a)+v;if(30<j){var R=v-v%5;j=(h&(1<<R)-1).toString(32),h>>=R,v-=R,Or=1<<32-ds(a)+v|d<<v|h,Qr=j+r}else Or=1<<j|d<<v|h,Qr=r}function Cl(r){r.return!==null&&(Jo(r,1),Hf(r,1,0))}function ud(r){for(;r===Nl;)Nl=Oa[--xo],Oa[xo]=null,zc=Oa[--xo],Oa[xo]=null;for(;r===Un;)Un=Ir[--bs],Ir[bs]=null,Qr=Ir[--bs],Ir[bs]=null,Or=Ir[--bs],Ir[bs]=null}var Ts=null,ir=null,vn=!1,Pr=null;function dd(r,a){var d=Pn(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 Vf(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,Ts=r,ir=Di(a.firstChild),!0):!1;case 6:return a=r.pendingProps===""||a.nodeType!==3?null:a,a!==null?(r.stateNode=a,Ts=r,ir=null,!0):!1;case 13:return a=a.nodeType!==8?null:a,a!==null?(d=Un!==null?{id:Or,overflow:Qr}:null,r.memoizedState={dehydrated:a,treeContext:d,retryLane:1073741824},d=Pn(18,null,null,0),d.stateNode=a,d.return=r,r.child=d,Ts=r,ir=null,!0):!1;default:return!1}}function Bc(r){return(r.mode&1)!==0&&(r.flags&128)===0}function Uc(r){if(vn){var a=ir;if(a){var d=a;if(!Vf(r,a)){if(Bc(r))throw Error(n(418));a=Di(d.nextSibling);var h=Ts;a&&Vf(r,a)?dd(h,d):(r.flags=r.flags&-4097|2,vn=!1,Ts=r)}}else{if(Bc(r))throw Error(n(418));r.flags=r.flags&-4097|2,vn=!1,Ts=r}}}function fd(r){for(r=r.return;r!==null&&r.tag!==5&&r.tag!==3&&r.tag!==13;)r=r.return;Ts=r}function Wc(r){if(r!==Ts)return!1;if(!vn)return fd(r),vn=!0,!1;var a;if((a=r.tag!==3)&&!(a=r.tag!==5)&&(a=r.type,a=a!=="head"&&a!=="body"&&!Aa(r.type,r.memoizedProps)),a&&(a=ir)){if(Bc(r))throw hd(),Error(n(418));for(;a;)dd(r,a),a=Di(a.nextSibling)}if(fd(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=Ts?Di(r.stateNode.nextSibling):null;return!0}function hd(){for(var r=ir;r;)r=Di(r.nextSibling)}function Bi(){ir=Ts=null,vn=!1}function md(r){Pr===null?Pr=[r]:Pr.push(r)}var i_=M.ReactCurrentBatchConfig;function $l(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,j=""+r;return a!==null&&a.ref!==null&&typeof a.ref=="function"&&a.ref._stringRef===j?a.ref:(a=function(R){var ee=v.refs;R===null?delete ee[j]:ee[j]=R},a._stringRef=j,a)}if(typeof r!="string")throw Error(n(284));if(!d._owner)throw Error(n(290,r))}return r}function qc(r,a){throw r=Object.prototype.toString.call(a),Error(n(31,r==="[object Object]"?"object with keys {"+Object.keys(a).join(", ")+"}":r))}function Hc(r){var a=r._init;return a(r._payload)}function Gf(r){function a(de,le){if(r){var he=de.deletions;he===null?(de.deletions=[le],de.flags|=16):he.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=Za(de,le),de.index=0,de.sibling=null,de}function j(de,le,he){return de.index=he,r?(he=de.alternate,he!==null?(he=he.index,he<le?(de.flags|=2,le):he):(de.flags|=2,le)):(de.flags|=1048576,le)}function R(de){return r&&de.alternate===null&&(de.flags|=2),de}function ee(de,le,he,Fe){return le===null||le.tag!==6?(le=u_(he,de.mode,Fe),le.return=de,le):(le=v(le,he),le.return=de,le)}function se(de,le,he,Fe){var rt=he.type;return rt===Y?Me(de,le,he.props.children,Fe,he.key):le!==null&&(le.elementType===rt||typeof rt=="object"&&rt!==null&&rt.$$typeof===P&&Hc(rt)===le.type)?(Fe=v(le,he.props),Fe.ref=$l(de,le,he),Fe.return=de,Fe):(Fe=Eh(he.type,he.key,he.props,null,de.mode,Fe),Fe.ref=$l(de,le,he),Fe.return=de,Fe)}function ye(de,le,he,Fe){return le===null||le.tag!==4||le.stateNode.containerInfo!==he.containerInfo||le.stateNode.implementation!==he.implementation?(le=d_(he,de.mode,Fe),le.return=de,le):(le=v(le,he.children||[]),le.return=de,le)}function Me(de,le,he,Fe,rt){return le===null||le.tag!==7?(le=Xl(he,de.mode,Fe,rt),le.return=de,le):(le=v(le,he),le.return=de,le)}function Re(de,le,he){if(typeof le=="string"&&le!==""||typeof le=="number")return le=u_(""+le,de.mode,he),le.return=de,le;if(typeof le=="object"&&le!==null){switch(le.$$typeof){case H:return he=Eh(le.type,le.key,le.props,null,de.mode,he),he.ref=$l(de,null,le),he.return=de,he;case Z:return le=d_(le,de.mode,he),le.return=de,le;case P:var Fe=le._init;return Re(de,Fe(le._payload),he)}if(ge(le)||z(le))return le=Xl(le,de.mode,he,null),le.return=de,le;qc(de,le)}return null}function Te(de,le,he,Fe){var rt=le!==null?le.key:null;if(typeof he=="string"&&he!==""||typeof he=="number")return rt!==null?null:ee(de,le,""+he,Fe);if(typeof he=="object"&&he!==null){switch(he.$$typeof){case H:return he.key===rt?se(de,le,he,Fe):null;case Z:return he.key===rt?ye(de,le,he,Fe):null;case P:return rt=he._init,Te(de,le,rt(he._payload),Fe)}if(ge(he)||z(he))return rt!==null?null:Me(de,le,he,Fe,null);qc(de,he)}return null}function Je(de,le,he,Fe,rt){if(typeof Fe=="string"&&Fe!==""||typeof Fe=="number")return de=de.get(he)||null,ee(le,de,""+Fe,rt);if(typeof Fe=="object"&&Fe!==null){switch(Fe.$$typeof){case H:return de=de.get(Fe.key===null?he:Fe.key)||null,se(le,de,Fe,rt);case Z:return de=de.get(Fe.key===null?he:Fe.key)||null,ye(le,de,Fe,rt);case P:var yt=Fe._init;return Je(de,le,he,yt(Fe._payload),rt)}if(ge(Fe)||z(Fe))return de=de.get(he)||null,Me(le,de,Fe,rt,null);qc(le,Fe)}return null}function tt(de,le,he,Fe){for(var rt=null,yt=null,wt=le,St=le=0,Is=null;wt!==null&&St<he.length;St++){wt.index>St?(Is=wt,wt=null):Is=wt.sibling;var dn=Te(de,wt,he[St],Fe);if(dn===null){wt===null&&(wt=Is);break}r&&wt&&dn.alternate===null&&a(de,wt),le=j(dn,le,St),yt===null?rt=dn:yt.sibling=dn,yt=dn,wt=Is}if(St===he.length)return d(de,wt),vn&&Jo(de,St),rt;if(wt===null){for(;St<he.length;St++)wt=Re(de,he[St],Fe),wt!==null&&(le=j(wt,le,St),yt===null?rt=wt:yt.sibling=wt,yt=wt);return vn&&Jo(de,St),rt}for(wt=h(de,wt);St<he.length;St++)Is=Je(wt,de,St,he[St],Fe),Is!==null&&(r&&Is.alternate!==null&&wt.delete(Is.key===null?St:Is.key),le=j(Is,le,St),yt===null?rt=Is:yt.sibling=Is,yt=Is);return r&&wt.forEach(function(Qa){return a(de,Qa)}),vn&&Jo(de,St),rt}function nt(de,le,he,Fe){var rt=z(he);if(typeof rt!="function")throw Error(n(150));if(he=rt.call(he),he==null)throw Error(n(151));for(var yt=rt=null,wt=le,St=le=0,Is=null,dn=he.next();wt!==null&&!dn.done;St++,dn=he.next()){wt.index>St?(Is=wt,wt=null):Is=wt.sibling;var Qa=Te(de,wt,dn.value,Fe);if(Qa===null){wt===null&&(wt=Is);break}r&&wt&&Qa.alternate===null&&a(de,wt),le=j(Qa,le,St),yt===null?rt=Qa:yt.sibling=Qa,yt=Qa,wt=Is}if(dn.done)return d(de,wt),vn&&Jo(de,St),rt;if(wt===null){for(;!dn.done;St++,dn=he.next())dn=Re(de,dn.value,Fe),dn!==null&&(le=j(dn,le,St),yt===null?rt=dn:yt.sibling=dn,yt=dn);return vn&&Jo(de,St),rt}for(wt=h(de,wt);!dn.done;St++,dn=he.next())dn=Je(wt,de,St,dn.value,Fe),dn!==null&&(r&&dn.alternate!==null&&wt.delete(dn.key===null?St:dn.key),le=j(dn,le,St),yt===null?rt=dn:yt.sibling=dn,yt=dn);return r&&wt.forEach(function(c0){return a(de,c0)}),vn&&Jo(de,St),rt}function as(de,le,he,Fe){if(typeof he=="object"&&he!==null&&he.type===Y&&he.key===null&&(he=he.props.children),typeof he=="object"&&he!==null){switch(he.$$typeof){case H:e:{for(var rt=he.key,yt=le;yt!==null;){if(yt.key===rt){if(rt=he.type,rt===Y){if(yt.tag===7){d(de,yt.sibling),le=v(yt,he.props.children),le.return=de,de=le;break e}}else if(yt.elementType===rt||typeof rt=="object"&&rt!==null&&rt.$$typeof===P&&Hc(rt)===yt.type){d(de,yt.sibling),le=v(yt,he.props),le.ref=$l(de,yt,he),le.return=de,de=le;break e}d(de,yt);break}else a(de,yt);yt=yt.sibling}he.type===Y?(le=Xl(he.props.children,de.mode,Fe,he.key),le.return=de,de=le):(Fe=Eh(he.type,he.key,he.props,null,de.mode,Fe),Fe.ref=$l(de,le,he),Fe.return=de,de=Fe)}return R(de);case Z:e:{for(yt=he.key;le!==null;){if(le.key===yt)if(le.tag===4&&le.stateNode.containerInfo===he.containerInfo&&le.stateNode.implementation===he.implementation){d(de,le.sibling),le=v(le,he.children||[]),le.return=de,de=le;break e}else{d(de,le);break}else a(de,le);le=le.sibling}le=d_(he,de.mode,Fe),le.return=de,de=le}return R(de);case P:return yt=he._init,as(de,le,yt(he._payload),Fe)}if(ge(he))return tt(de,le,he,Fe);if(z(he))return nt(de,le,he,Fe);qc(de,he)}return typeof he=="string"&&he!==""||typeof he=="number"?(he=""+he,le!==null&&le.tag===6?(d(de,le.sibling),le=v(le,he),le.return=de,de=le):(d(de,le),le=u_(he,de.mode,Fe),le.return=de,de=le),R(de)):d(de,le)}return as}var bo=Gf(!0),Kf=Gf(!1),Al=Zr(null),Vc=null,jo=null,Oe=null;function ss(){Oe=jo=Vc=null}function Gc(r){var a=Al.current;Sn(Al),r._currentValue=a}function _d(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 Pa(r,a){Vc=r,Oe=jo=null,r=r.dependencies,r!==null&&r.firstContext!==null&&((r.lanes&a)!==0&&(gn=!0),r.firstContext=null)}function Dr(r){var a=r._currentValue;if(Oe!==r)if(r={context:r,memoizedValue:a,next:null},jo===null){if(Vc===null)throw Error(n(308));jo=r,Vc.dependencies={lanes:0,firstContext:r}}else jo=jo.next=r;return a}var So=null;function Kc(r){So===null?So=[r]:So.push(r)}function Yf(r,a,d,h){var v=a.interleaved;return v===null?(d.next=d,Kc(a)):(d.next=v.next,v.next=d),a.interleaved=d,Fr(r,h)}function Fr(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 zn=!1;function Xt(r){r.updateQueue={baseState:r.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function js(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 ei(r,a){return{eventTime:r,lane:a,tag:0,payload:null,callback:null,next:null}}function Ui(r,a,d){var h=r.updateQueue;if(h===null)return null;if(h=h.shared,(Vt&2)!==0){var v=h.pending;return v===null?a.next=a:(a.next=v.next,v.next=a),h.pending=a,Fr(r,d)}return v=h.interleaved,v===null?(a.next=a,Kc(h)):(a.next=v.next,v.next=a),h.interleaved=a,Fr(r,d)}function ko(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,lo(r,d)}}function pd(r,a){var d=r.updateQueue,h=r.alternate;if(h!==null&&(h=h.updateQueue,d===h)){var v=null,j=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};j===null?v=j=R:j=j.next=R,d=d.next}while(d!==null);j===null?v=j=a:j=j.next=a}else v=j=a;d={baseState:h.baseState,firstBaseUpdate:v,lastBaseUpdate:j,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 at(r,a,d,h){var v=r.updateQueue;zn=!1;var j=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?j=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(j!==null){var Re=v.baseState;R=0,Me=ye=se=null,ee=j;do{var Te=ee.lane,Je=ee.eventTime;if((h&Te)===Te){Me!==null&&(Me=Me.next={eventTime:Je,lane:0,tag:ee.tag,payload:ee.payload,callback:ee.callback,next:null});e:{var tt=r,nt=ee;switch(Te=a,Je=d,nt.tag){case 1:if(tt=nt.payload,typeof tt=="function"){Re=tt.call(Je,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(Je,Re,Te):tt,Te==null)break e;Re=G({},Re,Te);break e;case 2:zn=!0}}ee.callback!==null&&ee.lane!==0&&(r.flags|=64,Te=v.effects,Te===null?v.effects=[ee]:Te.push(ee))}else Je={eventTime:Je,lane:Te,tag:ee.tag,payload:ee.payload,callback:ee.callback,next:null},Me===null?(ye=Me=Je,se=Re):Me=Me.next=Je,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 j===null&&(v.shared.lanes=0);jr|=R,r.lanes=R,r.memoizedState=Re}}function Jf(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 Xo={},yi=Zr(Xo),El=Zr(Xo),Da=Zr(Xo);function Zo(r){if(r===Xo)throw Error(n(174));return r}function gd(r,a){switch(on(Da,a),on(El,r),on(yi,Xo),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(yi),on(yi,a)}function Fa(){Sn(yi),Sn(El),Sn(Da)}function Yc(r){Zo(Da.current);var a=Zo(yi.current),d=It(a,r.type);a!==d&&(on(El,r),on(yi,d))}function No(r){El.current===r&&(Sn(yi),Sn(El))}var In=Zr(0);function vr(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 xr=[];function Jc(){for(var r=0;r<xr.length;r++)xr[r]._workInProgressVersionPrimary=null;xr.length=0}var Xc=M.ReactCurrentDispatcher,yd=M.ReactCurrentBatchConfig,Qo=0,Mn=null,Wn=null,hs=null,kn=!1,za=!1,ea=0,or=0;function Ss(){throw Error(n(321))}function ta(r,a){if(a===null)return!1;for(var d=0;d<a.length&&d<r.length;d++)if(!Tr(r[d],a[d]))return!1;return!0}function Tl(r,a,d,h,v,j){if(Qo=j,Mn=a,a.memoizedState=null,a.updateQueue=null,a.lanes=0,Xc.current=r===null||r.memoizedState===null?ah:ra,r=d(h,v),za){j=0;do{if(za=!1,ea=0,25<=j)throw Error(n(301));j+=1,hs=Wn=null,a.updateQueue=null,Xc.current=lh,r=d(h,v)}while(za)}if(Xc.current=Ol,a=Wn!==null&&Wn.next!==null,Qo=0,hs=Wn=Mn=null,kn=!1,a)throw Error(n(300));return r}function na(){var r=ea!==0;return ea=0,r}function zr(){var r={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return hs===null?Mn.memoizedState=hs=r:hs=hs.next=r,hs}function Br(){if(Wn===null){var r=Mn.alternate;r=r!==null?r.memoizedState:null}else r=Wn.next;var a=hs===null?Mn.memoizedState:hs.next;if(a!==null)hs=a,Wn=r;else{if(r===null)throw Error(n(310));Wn=r,r={memoizedState:Wn.memoizedState,baseState:Wn.baseState,baseQueue:Wn.baseQueue,queue:Wn.queue,next:null},hs===null?Mn.memoizedState=hs=r:hs=hs.next=r}return hs}function Ml(r,a){return typeof a=="function"?a(r):a}function wd(r){var a=Br(),d=a.queue;if(d===null)throw Error(n(311));d.lastRenderedReducer=r;var h=Wn,v=h.baseQueue,j=d.pending;if(j!==null){if(v!==null){var R=v.next;v.next=j.next,j.next=R}h.baseQueue=v=j,d.pending=null}if(v!==null){j=v.next,h=h.baseState;var ee=R=null,se=null,ye=j;do{var Me=ye.lane;if((Qo&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,Mn.lanes|=Me,jr|=Me}ye=ye.next}while(ye!==null&&ye!==j);se===null?R=h:se.next=ee,Tr(h,a.memoizedState)||(gn=!0),a.memoizedState=h,a.baseState=R,a.baseQueue=se,d.lastRenderedState=h}if(r=d.interleaved,r!==null){v=r;do j=v.lane,Mn.lanes|=j,jr|=j,v=v.next;while(v!==r)}else v===null&&(d.lanes=0);return[a.memoizedState,d.dispatch]}function Rl(r){var a=Br(),d=a.queue;if(d===null)throw Error(n(311));d.lastRenderedReducer=r;var h=d.dispatch,v=d.pending,j=a.memoizedState;if(v!==null){d.pending=null;var R=v=v.next;do j=r(j,R.action),R=R.next;while(R!==v);Tr(j,a.memoizedState)||(gn=!0),a.memoizedState=j,a.baseQueue===null&&(a.baseState=j),d.lastRenderedState=j}return[j,h]}function Zc(){}function Xf(r,a){var d=Mn,h=Br(),v=a(),j=!Tr(h.memoizedState,v);if(j&&(h.memoizedState=v,gn=!0),h=h.queue,nu(Ur.bind(null,d,h,r),[r]),h.getSnapshot!==a||j||hs!==null&&hs.memoizedState.tag&1){if(d.flags|=2048,Ba(9,Zf.bind(null,d,h,v,a),void 0,null),is===null)throw Error(n(349));(Qo&30)!==0||Qc(d,a,v)}return v}function Qc(r,a,d){r.flags|=16384,r={getSnapshot:a,value:d},a=Mn.updateQueue,a===null?(a={lastEffect:null,stores:null},Mn.updateQueue=a,a.stores=[r]):(d=a.stores,d===null?a.stores=[r]:d.push(r))}function Zf(r,a,d,h){a.value=d,a.getSnapshot=h,sa(a)&&qn(r)}function Ur(r,a,d){return d(function(){sa(a)&&qn(r)})}function sa(r){var a=r.getSnapshot;r=r.value;try{var d=a();return!Tr(r,d)}catch{return!0}}function qn(r){var a=Fr(r,1);a!==null&&qr(a,r,1,-1)}function vd(r){var a=zr();return typeof r=="function"&&(r=r()),a.memoizedState=a.baseState=r,r={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:Ml,lastRenderedState:r},a.queue=r,r=r.dispatch=Il.bind(null,Mn,r),[a.memoizedState,r]}function Ba(r,a,d,h){return r={tag:r,create:a,destroy:d,deps:h,next:null},a=Mn.updateQueue,a===null?(a={lastEffect:null,stores:null},Mn.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 Qf(){return Br().memoizedState}function eu(r,a,d,h){var v=zr();Mn.flags|=r,v.memoizedState=Ba(1|a,d,void 0,h===void 0?null:h)}function tu(r,a,d,h){var v=Br();h=h===void 0?null:h;var j=void 0;if(Wn!==null){var R=Wn.memoizedState;if(j=R.destroy,h!==null&&ta(h,R.deps)){v.memoizedState=Ba(a,d,j,h);return}}Mn.flags|=r,v.memoizedState=Ba(1|a,d,j,h)}function xd(r,a){return eu(8390656,8,r,a)}function nu(r,a){return tu(2048,8,r,a)}function eh(r,a){return tu(4,2,r,a)}function th(r,a){return tu(4,4,r,a)}function Jt(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 On(r,a,d){return d=d!=null?d.concat([r]):null,tu(4,4,Jt.bind(null,a,r),d)}function Ws(){}function su(r,a){var d=Br();a=a===void 0?null:a;var h=d.memoizedState;return h!==null&&a!==null&&ta(a,h[1])?h[0]:(d.memoizedState=[r,a],r)}function Ll(r,a){var d=Br();a=a===void 0?null:a;var h=d.memoizedState;return h!==null&&a!==null&&ta(a,h[1])?h[0]:(r=r(),d.memoizedState=[r,a],r)}function bd(r,a,d){return(Qo&21)===0?(r.baseState&&(r.baseState=!1,gn=!0),r.memoizedState=d):(Tr(d,a)||(d=fs(),Mn.lanes|=d,jr|=d,r.baseState=!0),a)}function o_(r,a){var d=nn;nn=d!==0&&4>d?d:4,r(!0);var h=yd.transition;yd.transition={};try{r(!1),a()}finally{nn=d,yd.transition=h}}function nh(){return Br().memoizedState}function sh(r,a,d){var h=Gi(r);if(d={lane:h,action:d,hasEagerState:!1,eagerState:null,next:null},rh(r))ih(a,d);else if(d=Yf(r,a,d,h),d!==null){var v=Ls();qr(d,r,h,v),oh(d,a,h)}}function Il(r,a,d){var h=Gi(r),v={lane:h,action:d,hasEagerState:!1,eagerState:null,next:null};if(rh(r))ih(a,v);else{var j=r.alternate;if(r.lanes===0&&(j===null||j.lanes===0)&&(j=a.lastRenderedReducer,j!==null))try{var R=a.lastRenderedState,ee=j(R,d);if(v.hasEagerState=!0,v.eagerState=ee,Tr(ee,R)){var se=a.interleaved;se===null?(v.next=v,Kc(a)):(v.next=se.next,se.next=v),a.interleaved=v;return}}catch{}finally{}d=Yf(r,a,v,h),d!==null&&(v=Ls(),qr(d,r,h,v),oh(d,a,h))}}function rh(r){var a=r.alternate;return r===Mn||a!==null&&a===Mn}function ih(r,a){za=kn=!0;var d=r.pending;d===null?a.next=a:(a.next=d.next,d.next=a),r.pending=a}function oh(r,a,d){if((d&4194240)!==0){var h=a.lanes;h&=r.pendingLanes,d|=h,a.lanes=d,lo(r,d)}}var Ol={readContext:Dr,useCallback:Ss,useContext:Ss,useEffect:Ss,useImperativeHandle:Ss,useInsertionEffect:Ss,useLayoutEffect:Ss,useMemo:Ss,useReducer:Ss,useRef:Ss,useState:Ss,useDebugValue:Ss,useDeferredValue:Ss,useTransition:Ss,useMutableSource:Ss,useSyncExternalStore:Ss,useId:Ss,unstable_isNewReconciler:!1},ah={readContext:Dr,useCallback:function(r,a){return zr().memoizedState=[r,a===void 0?null:a],r},useContext:Dr,useEffect:xd,useImperativeHandle:function(r,a,d){return d=d!=null?d.concat([r]):null,eu(4194308,4,Jt.bind(null,a,r),d)},useLayoutEffect:function(r,a){return eu(4194308,4,r,a)},useInsertionEffect:function(r,a){return eu(4,2,r,a)},useMemo:function(r,a){var d=zr();return a=a===void 0?null:a,r=r(),d.memoizedState=[r,a],r},useReducer:function(r,a,d){var h=zr();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=sh.bind(null,Mn,r),[h.memoizedState,r]},useRef:function(r){var a=zr();return r={current:r},a.memoizedState=r},useState:vd,useDebugValue:Ws,useDeferredValue:function(r){return zr().memoizedState=r},useTransition:function(){var r=vd(!1),a=r[0];return r=o_.bind(null,r[1]),zr().memoizedState=r,[a,r]},useMutableSource:function(){},useSyncExternalStore:function(r,a,d){var h=Mn,v=zr();if(vn){if(d===void 0)throw Error(n(407));d=d()}else{if(d=a(),is===null)throw Error(n(349));(Qo&30)!==0||Qc(h,a,d)}v.memoizedState=d;var j={value:d,getSnapshot:a};return v.queue=j,xd(Ur.bind(null,h,j,r),[r]),h.flags|=2048,Ba(9,Zf.bind(null,h,j,d,a),void 0,null),d},useId:function(){var r=zr(),a=is.identifierPrefix;if(vn){var d=Qr,h=Or;d=(h&~(1<<32-ds(h)-1)).toString(32)+d,a=":"+a+"R"+d,d=ea++,0<d&&(a+="H"+d.toString(32)),a+=":"}else d=or++,a=":"+a+"r"+d.toString(32)+":";return r.memoizedState=a},unstable_isNewReconciler:!1},ra={readContext:Dr,useCallback:su,useContext:Dr,useEffect:nu,useImperativeHandle:On,useInsertionEffect:eh,useLayoutEffect:th,useMemo:Ll,useReducer:wd,useRef:Qf,useState:function(){return wd(Ml)},useDebugValue:Ws,useDeferredValue:function(r){var a=Br();return bd(a,Wn.memoizedState,r)},useTransition:function(){var r=wd(Ml)[0],a=Br().memoizedState;return[r,a]},useMutableSource:Zc,useSyncExternalStore:Xf,useId:nh,unstable_isNewReconciler:!1},lh={readContext:Dr,useCallback:su,useContext:Dr,useEffect:nu,useImperativeHandle:On,useInsertionEffect:eh,useLayoutEffect:th,useMemo:Ll,useReducer:Rl,useRef:Qf,useState:function(){return Rl(Ml)},useDebugValue:Ws,useDeferredValue:function(r){var a=Br();return Wn===null?a.memoizedState=r:bd(a,Wn.memoizedState,r)},useTransition:function(){var r=Rl(Ml)[0],a=Br().memoizedState;return[r,a]},useMutableSource:Zc,useSyncExternalStore:Xf,useId:nh,unstable_isNewReconciler:!1};function Wr(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 ru(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 Pl={isMounted:function(r){return(r=r._reactInternals)?$t(r)===r:!1},enqueueSetState:function(r,a,d){r=r._reactInternals;var h=Ls(),v=Gi(r),j=ei(h,v);j.payload=a,d!=null&&(j.callback=d),a=Ui(r,j,v),a!==null&&(qr(a,r,v,h),ko(a,r,v))},enqueueReplaceState:function(r,a,d){r=r._reactInternals;var h=Ls(),v=Gi(r),j=ei(h,v);j.tag=1,j.payload=a,d!=null&&(j.callback=d),a=Ui(r,j,v),a!==null&&(qr(a,r,v,h),ko(a,r,v))},enqueueForceUpdate:function(r,a){r=r._reactInternals;var d=Ls(),h=Gi(r),v=ei(d,h);v.tag=2,a!=null&&(v.callback=a),a=Ui(r,v,h),a!==null&&(qr(a,r,h,d),ko(a,r,h))}};function ch(r,a,d,h,v,j,R){return r=r.stateNode,typeof r.shouldComponentUpdate=="function"?r.shouldComponentUpdate(h,j,R):a.prototype&&a.prototype.isPureReactComponent?!mo(d,h)||!mo(v,j):!0}function uh(r,a,d){var h=!1,v=wo,j=a.contextType;return typeof j=="object"&&j!==null?j=Dr(j):(v=xs(a)?Lr:ns.current,h=a.contextTypes,j=(h=h!=null)?Ma(r,v):wo),a=new a(d,j),r.memoizedState=a.state!==null&&a.state!==void 0?a.state:null,a.updater=Pl,r.stateNode=a,a._reactInternals=r,h&&(r=r.stateNode,r.__reactInternalMemoizedUnmaskedChildContext=v,r.__reactInternalMemoizedMaskedChildContext=j),a}function dh(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&&Pl.enqueueReplaceState(a,a.state,null)}function jd(r,a,d,h){var v=r.stateNode;v.props=d,v.state=r.memoizedState,v.refs={},Xt(r);var j=a.contextType;typeof j=="object"&&j!==null?v.context=Dr(j):(j=xs(a)?Lr:ns.current,v.context=Ma(r,j)),v.state=r.memoizedState,j=a.getDerivedStateFromProps,typeof j=="function"&&(ru(r,a,j,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&&Pl.enqueueReplaceState(v,v.state,null),at(r,d,v,h),v.state=r.memoizedState),typeof v.componentDidMount=="function"&&(r.flags|=4194308)}function Ua(r,a){try{var d="",h=a;do d+=oe(h),h=h.return;while(h);var v=d}catch(j){v=`
39
- Error generating stack: `+j.message+`
40
- `+j.stack}return{value:r,source:a,stack:v,digest:null}}function Sd(r,a,d){return{value:r,source:null,stack:d??null,digest:a??null}}function kd(r,a){try{console.error(a.value)}catch(d){setTimeout(function(){throw d})}}var fh=typeof WeakMap=="function"?WeakMap:Map;function iu(r,a,d){d=ei(-1,d),d.tag=3,d.payload={element:null};var h=a.value;return d.callback=function(){du||(du=!0,aa=h),kd(r,a)},d}function hh(r,a,d){d=ei(-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(){kd(r,a)}}var j=r.stateNode;return j!==null&&typeof j.componentDidCatch=="function"&&(d.callback=function(){kd(r,a),typeof h!="function"&&($o===null?$o=new Set([this]):$o.add(this));var R=a.stack;this.componentDidCatch(a.value,{componentStack:R!==null?R:""})}),d}function mh(r,a,d){var h=r.pingCache;if(h===null){h=r.pingCache=new fh;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=ln.bind(null,r,a,d),a.then(r,r))}function Dl(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 _h(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=ei(-1,1),a.tag=2,Ui(d,a,1))),d.lanes|=1),r):(r.flags|=65536,r.lanes=v,r)}var ia=M.ReactCurrentOwner,gn=!1;function an(r,a,d,h){a.child=r===null?Kf(a,null,d,h):bo(a,r.child,d,h)}function ti(r,a,d,h,v){d=d.render;var j=a.ref;return Pa(a,v),h=Tl(r,a,d,h,j,v),d=na(),r!==null&&!gn?(a.updateQueue=r.updateQueue,a.flags&=-2053,r.lanes&=~v,wi(r,a,v)):(vn&&d&&Cl(a),a.flags|=1,an(r,a,h,v),a.child)}function Wi(r,a,d,h,v){if(r===null){var j=d.type;return typeof j=="function"&&!Sr(j)&&j.defaultProps===void 0&&d.compare===null&&d.defaultProps===void 0?(a.tag=15,a.type=j,qi(r,a,j,h,v)):(r=Eh(d.type,null,h,a,a.mode,v),r.ref=a.ref,r.return=a,a.child=r)}if(j=r.child,(r.lanes&v)===0){var R=j.memoizedProps;if(d=d.compare,d=d!==null?d:mo,d(R,h)&&r.ref===a.ref)return wi(r,a,v)}return a.flags|=1,r=Za(j,h),r.ref=a.ref,r.return=a,a.child=r}function qi(r,a,d,h,v){if(r!==null){var j=r.memoizedProps;if(mo(j,h)&&r.ref===a.ref)if(gn=!1,a.pendingProps=h=j,(r.lanes&v)!==0)(r.flags&131072)!==0&&(gn=!0);else return a.lanes=r.lanes,wi(r,a,v)}return Wa(r,a,d,h,v)}function ni(r,a,d){var h=a.pendingProps,v=h.children,j=r!==null?r.memoizedState:null;if(h.mode==="hidden")if((a.mode&1)===0)a.memoizedState={baseLanes:0,cachePool:null,transitions:null},on(Ka,Zn),Zn|=d;else{if((d&1073741824)===0)return r=j!==null?j.baseLanes|d:d,a.lanes=a.childLanes=1073741824,a.memoizedState={baseLanes:r,cachePool:null,transitions:null},a.updateQueue=null,on(Ka,Zn),Zn|=r,null;a.memoizedState={baseLanes:0,cachePool:null,transitions:null},h=j!==null?j.baseLanes:d,on(Ka,Zn),Zn|=h}else j!==null?(h=j.baseLanes|d,a.memoizedState=null):h=d,on(Ka,Zn),Zn|=h;return an(r,a,v,d),a.child}function ph(r,a){var d=a.ref;(r===null&&d!==null||r!==null&&r.ref!==d)&&(a.flags|=512,a.flags|=2097152)}function Wa(r,a,d,h,v){var j=xs(d)?Lr:ns.current;return j=Ma(a,j),Pa(a,v),d=Tl(r,a,d,h,j,v),h=na(),r!==null&&!gn?(a.updateQueue=r.updateQueue,a.flags&=-2053,r.lanes&=~v,wi(r,a,v)):(vn&&h&&Cl(a),a.flags|=1,an(r,a,d,v),a.child)}function gh(r,a,d,h,v){if(xs(d)){var j=!0;vo(a)}else j=!1;if(Pa(a,v),a.stateNode===null)oa(r,a),uh(a,d,h),jd(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=Dr(ye):(ye=xs(d)?Lr:ns.current,ye=Ma(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)&&dh(a,R,h,ye),zn=!1;var Te=a.memoizedState;R.state=Te,at(a,h,R,v),se=a.memoizedState,ee!==h||Te!==se||rr.current||zn?(typeof Me=="function"&&(ru(a,d,Me,h),se=a.memoizedState),(ee=zn||ch(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,js(r,a),ee=a.memoizedProps,ye=a.type===a.elementType?ee:Wr(a.type,ee),R.props=ye,Re=a.pendingProps,Te=R.context,se=d.contextType,typeof se=="object"&&se!==null?se=Dr(se):(se=xs(d)?Lr:ns.current,se=Ma(a,se));var Je=d.getDerivedStateFromProps;(Me=typeof Je=="function"||typeof R.getSnapshotBeforeUpdate=="function")||typeof R.UNSAFE_componentWillReceiveProps!="function"&&typeof R.componentWillReceiveProps!="function"||(ee!==Re||Te!==se)&&dh(a,R,h,se),zn=!1,Te=a.memoizedState,R.state=Te,at(a,h,R,v);var tt=a.memoizedState;ee!==Re||Te!==tt||rr.current||zn?(typeof Je=="function"&&(ru(a,d,Je,h),tt=a.memoizedState),(ye=zn||ch(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 Fl(r,a,d,h,j,v)}function Fl(r,a,d,h,v,j){ph(r,a);var R=(a.flags&128)!==0;if(!h&&!R)return v&&Ra(a,d,!1),wi(r,a,j);h=a.stateNode,ia.current=a;var ee=R&&typeof d.getDerivedStateFromError!="function"?null:h.render();return a.flags|=1,r!==null&&R?(a.child=bo(a,r.child,null,j),a.child=bo(a,null,ee,j)):an(r,a,ee,j),a.memoizedState=h.state,v&&Ra(a,d,!0),a.child}function yh(r){var a=r.stateNode;a.pendingContext?zi(r,a.pendingContext,a.pendingContext!==a.context):a.context&&zi(r,a.context,!1),gd(r,a.containerInfo)}function wh(r,a,d,h,v){return Bi(),md(v),a.flags|=256,an(r,a,d,h),a.child}var ou={dehydrated:null,treeContext:null,retryLane:0};function Hi(r){return{baseLanes:r,cachePool:null,transitions:null}}function qa(r,a,d){var h=a.pendingProps,v=In.current,j=!1,R=(a.flags&128)!==0,ee;if((ee=R)||(ee=r!==null&&r.memoizedState===null?!1:(v&2)!==0),ee?(j=!0,a.flags&=-129):(r===null||r.memoizedState!==null)&&(v|=1),on(In,v&1),r===null)return Uc(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,j?(h=a.mode,j=a.child,R={mode:"hidden",children:R},(h&1)===0&&j!==null?(j.childLanes=0,j.pendingProps=R):j=Th(R,h,0,null),r=Xl(r,h,d,null),j.return=a,r.return=a,j.sibling=r,a.child=j,a.child.memoizedState=Hi(d),a.memoizedState=ou,r):au(a,R));if(v=r.memoizedState,v!==null&&(ee=v.dehydrated,ee!==null))return a_(r,a,R,h,ee,v,d);if(j){j=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=Za(v,se),h.subtreeFlags=v.subtreeFlags&14680064),ee!==null?j=Za(ee,j):(j=Xl(j,R,d,null),j.flags|=2),j.return=a,h.return=a,h.sibling=j,a.child=h,h=j,j=a.child,R=r.child.memoizedState,R=R===null?Hi(d):{baseLanes:R.baseLanes|d,cachePool:null,transitions:R.transitions},j.memoizedState=R,j.childLanes=r.childLanes&~d,a.memoizedState=ou,h}return j=r.child,r=j.sibling,h=Za(j,{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 au(r,a){return a=Th({mode:"visible",children:a},r.mode,0,null),a.return=r,r.child=a}function zl(r,a,d,h){return h!==null&&md(h),bo(a,r.child,null,d),r=au(a,a.pendingProps.children),r.flags|=2,a.memoizedState=null,r}function a_(r,a,d,h,v,j,R){if(d)return a.flags&256?(a.flags&=-257,h=Sd(Error(n(422))),zl(r,a,R,h)):a.memoizedState!==null?(a.child=r.child,a.flags|=128,null):(j=h.fallback,v=a.mode,h=Th({mode:"visible",children:h.children},v,0,null),j=Xl(j,v,R,null),j.flags|=2,h.return=a,j.return=a,h.sibling=j,a.child=h,(a.mode&1)!==0&&bo(a,r.child,null,R),a.child.memoizedState=Hi(R),a.memoizedState=ou,j);if((a.mode&1)===0)return zl(r,a,R,null);if(v.data==="$!"){if(h=v.nextSibling&&v.nextSibling.dataset,h)var ee=h.dgst;return h=ee,j=Error(n(419)),h=Sd(j,h,void 0),zl(r,a,R,h)}if(ee=(R&r.childLanes)!==0,gn||ee){if(h=is,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!==j.retryLane&&(j.retryLane=v,Fr(r,v),qr(h,r,v,-1))}return W(),h=Sd(Error(n(421))),zl(r,a,R,h)}return v.data==="$?"?(a.flags|=128,a.child=r.child,a=He.bind(null,r),v._reactRetry=a,null):(r=j.treeContext,ir=Di(v.nextSibling),Ts=a,vn=!0,Pr=null,r!==null&&(Ir[bs++]=Or,Ir[bs++]=Qr,Ir[bs++]=Un,Or=r.id,Qr=r.overflow,Un=a),a=au(a,h.children),a.flags|=4096,a)}function Nd(r,a,d){r.lanes|=a;var h=r.alternate;h!==null&&(h.lanes|=a),_d(r.return,a,d)}function Co(r,a,d,h,v){var j=r.memoizedState;j===null?r.memoizedState={isBackwards:a,rendering:null,renderingStartTime:0,last:h,tail:d,tailMode:v}:(j.isBackwards=a,j.rendering=null,j.renderingStartTime=0,j.last=h,j.tail=d,j.tailMode=v)}function vh(r,a,d){var h=a.pendingProps,v=h.revealOrder,j=h.tail;if(an(r,a,h.children,d),h=In.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&&Nd(r,d,a);else if(r.tag===19)Nd(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(on(In,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&&vr(r)===null&&(v=d),d=d.sibling;d=v,d===null?(v=a.child,a.child=null):(v=d.sibling,d.sibling=null),Co(a,!1,v,d,j);break;case"backwards":for(d=null,v=a.child,a.child=null;v!==null;){if(r=v.alternate,r!==null&&vr(r)===null){a.child=v;break}r=v.sibling,v.sibling=d,d=v,v=r}Co(a,!0,d,null,j);break;case"together":Co(a,!1,null,null,void 0);break;default:a.memoizedState=null}return a.child}function oa(r,a){(a.mode&1)===0&&r!==null&&(r.alternate=null,a.alternate=null,a.flags|=2)}function wi(r,a,d){if(r!==null&&(a.dependencies=r.dependencies),jr|=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=Za(r,r.pendingProps),a.child=d,d.return=a;r.sibling!==null;)r=r.sibling,d=d.sibling=Za(r,r.pendingProps),d.return=a;d.sibling=null}return a.child}function l_(r,a,d){switch(a.tag){case 3:yh(a),Bi();break;case 5:Yc(a);break;case 1:xs(a.type)&&vo(a);break;case 4:gd(a,a.stateNode.containerInfo);break;case 10:var h=a.type._context,v=a.memoizedProps.value;on(Al,h._currentValue),h._currentValue=v;break;case 13:if(h=a.memoizedState,h!==null)return h.dehydrated!==null?(on(In,In.current&1),a.flags|=128,null):(d&a.child.childLanes)!==0?qa(r,a,d):(on(In,In.current&1),r=wi(r,a,d),r!==null?r.sibling:null);on(In,In.current&1);break;case 19:if(h=(d&a.childLanes)!==0,(r.flags&128)!==0){if(h)return vh(r,a,d);a.flags|=128}if(v=a.memoizedState,v!==null&&(v.rendering=null,v.tail=null,v.lastEffect=null),on(In,In.current),h)break;return null;case 22:case 23:return a.lanes=0,ni(r,a,d)}return wi(r,a,d)}var lu,Cd,xh,bh;lu=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}},Cd=function(){},xh=function(r,a,d,h){var v=r.memoizedProps;if(v!==h){r=a.stateNode,Zo(yi.current);var j=null;switch(d){case"input":v=et(r,v),h=et(r,h),j=[];break;case"select":v=G({},v,{value:void 0}),h=G({},h,{value:void 0}),j=[];break;case"textarea":v=Ke(r,v),h=Ke(r,h),j=[];break;default:typeof v.onClick!="function"&&typeof h.onClick=="function"&&(r.onclick=jl)}wn(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)?j||(j=[]):(j=j||[]).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||(j||(j=[]),j.push(ye,d)),d=se;else ye==="dangerouslySetInnerHTML"?(se=se?se.__html:void 0,ee=ee?ee.__html:void 0,se!=null&&ee!==se&&(j=j||[]).push(ye,se)):ye==="children"?typeof se!="string"&&typeof se!="number"||(j=j||[]).push(ye,""+se):ye!=="suppressContentEditableWarning"&&ye!=="suppressHydrationWarning"&&(o.hasOwnProperty(ye)?(se!=null&&ye==="onScroll"&&pn("scroll",r),j||ee===se||(j=[])):(j=j||[]).push(ye,se))}d&&(j=j||[]).push("style",d);var ye=j;(a.updateQueue=ye)&&(a.flags|=4)}},bh=function(r,a,d,h){d!==h&&(a.flags|=4)};function ks(r,a){if(!vn)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 Hn(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 c_(r,a,d){var h=a.pendingProps;switch(ud(a),a.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return Hn(a),null;case 1:return xs(a.type)&&Dc(),Hn(a),null;case 3:return h=a.stateNode,Fa(),Sn(rr),Sn(ns),Jc(),h.pendingContext&&(h.context=h.pendingContext,h.pendingContext=null),(r===null||r.child===null)&&(Wc(a)?a.flags|=4:r===null||r.memoizedState.isDehydrated&&(a.flags&256)===0||(a.flags|=1024,Pr!==null&&(mu(Pr),Pr=null))),Cd(r,a),Hn(a),null;case 5:No(a);var v=Zo(Da.current);if(d=a.type,r!==null&&a.stateNode!=null)xh(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 Hn(a),null}if(r=Zo(yi.current),Wc(a)){h=a.stateNode,d=a.type;var j=a.memoizedProps;switch(h[mi]=a,h[Ea]=j,r=(a.mode&1)!==0,d){case"dialog":pn("cancel",h),pn("close",h);break;case"iframe":case"object":case"embed":pn("load",h);break;case"video":case"audio":for(v=0;v<ui.length;v++)pn(ui[v],h);break;case"source":pn("error",h);break;case"img":case"image":case"link":pn("error",h),pn("load",h);break;case"details":pn("toggle",h);break;case"input":lt(h,j),pn("invalid",h);break;case"select":h._wrapperState={wasMultiple:!!j.multiple},pn("invalid",h);break;case"textarea":Dt(h,j),pn("invalid",h)}wn(d,j),v=null;for(var R in j)if(j.hasOwnProperty(R)){var ee=j[R];R==="children"?typeof ee=="string"?h.textContent!==ee&&(j.suppressHydrationWarning!==!0&&wr(h.textContent,ee,r),v=["children",ee]):typeof ee=="number"&&h.textContent!==""+ee&&(j.suppressHydrationWarning!==!0&&wr(h.textContent,ee,r),v=["children",""+ee]):o.hasOwnProperty(R)&&ee!=null&&R==="onScroll"&&pn("scroll",h)}switch(d){case"input":We(h),Le(h,j,!0);break;case"textarea":We(h),_n(h);break;case"select":case"option":break;default:typeof j.onClick=="function"&&(h.onclick=jl)}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=Ut(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[mi]=a,r[Ea]=h,lu(r,a,!1,!1),a.stateNode=r;e:{switch(R=Cs(d,h),d){case"dialog":pn("cancel",r),pn("close",r),v=h;break;case"iframe":case"object":case"embed":pn("load",r),v=h;break;case"video":case"audio":for(v=0;v<ui.length;v++)pn(ui[v],r);v=h;break;case"source":pn("error",r),v=h;break;case"img":case"image":case"link":pn("error",r),pn("load",r),v=h;break;case"details":pn("toggle",r),v=h;break;case"input":lt(r,h),v=et(r,h),pn("invalid",r);break;case"option":v=h;break;case"select":r._wrapperState={wasMultiple:!!h.multiple},v=G({},h,{value:void 0}),pn("invalid",r);break;case"textarea":Dt(r,h),v=Ke(r,h),pn("invalid",r);break;default:v=h}wn(d,v),ee=v;for(j in ee)if(ee.hasOwnProperty(j)){var se=ee[j];j==="style"?jn(r,se):j==="dangerouslySetInnerHTML"?(se=se?se.__html:void 0,se!=null&&Bn(r,se)):j==="children"?typeof se=="string"?(d!=="textarea"||se!=="")&&Mt(r,se):typeof se=="number"&&Mt(r,""+se):j!=="suppressContentEditableWarning"&&j!=="suppressHydrationWarning"&&j!=="autoFocus"&&(o.hasOwnProperty(j)?se!=null&&j==="onScroll"&&pn("scroll",r):se!=null&&D(r,j,se,R))}switch(d){case"input":We(r),Le(r,h,!1);break;case"textarea":We(r),_n(r);break;case"option":h.value!=null&&r.setAttribute("value",""+we(h.value));break;case"select":r.multiple=!!h.multiple,j=h.value,j!=null?De(r,!!h.multiple,j,!1):h.defaultValue!=null&&De(r,!!h.multiple,h.defaultValue,!0);break;default:typeof v.onClick=="function"&&(r.onclick=jl)}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 Hn(a),null;case 6:if(r&&a.stateNode!=null)bh(r,a,r.memoizedProps,h);else{if(typeof h!="string"&&a.stateNode===null)throw Error(n(166));if(d=Zo(Da.current),Zo(yi.current),Wc(a)){if(h=a.stateNode,d=a.memoizedProps,h[mi]=a,(j=h.nodeValue!==d)&&(r=Ts,r!==null))switch(r.tag){case 3:wr(h.nodeValue,d,(r.mode&1)!==0);break;case 5:r.memoizedProps.suppressHydrationWarning!==!0&&wr(h.nodeValue,d,(r.mode&1)!==0)}j&&(a.flags|=4)}else h=(d.nodeType===9?d:d.ownerDocument).createTextNode(h),h[mi]=a,a.stateNode=h}return Hn(a),null;case 13:if(Sn(In),h=a.memoizedState,r===null||r.memoizedState!==null&&r.memoizedState.dehydrated!==null){if(vn&&ir!==null&&(a.mode&1)!==0&&(a.flags&128)===0)hd(),Bi(),a.flags|=98560,j=!1;else if(j=Wc(a),h!==null&&h.dehydrated!==null){if(r===null){if(!j)throw Error(n(318));if(j=a.memoizedState,j=j!==null?j.dehydrated:null,!j)throw Error(n(317));j[mi]=a}else Bi(),(a.flags&128)===0&&(a.memoizedState=null),a.flags|=4;Hn(a),j=!1}else Pr!==null&&(mu(Pr),Pr=null),j=!0;if(!j)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||(In.current&1)!==0?os===0&&(os=3):W())),a.updateQueue!==null&&(a.flags|=4),Hn(a),null);case 4:return Fa(),Cd(r,a),r===null&&Mr(a.stateNode.containerInfo),Hn(a),null;case 10:return Gc(a.type._context),Hn(a),null;case 17:return xs(a.type)&&Dc(),Hn(a),null;case 19:if(Sn(In),j=a.memoizedState,j===null)return Hn(a),null;if(h=(a.flags&128)!==0,R=j.rendering,R===null)if(h)ks(j,!1);else{if(os!==0||r!==null&&(r.flags&128)!==0)for(r=a.child;r!==null;){if(R=vr(r),R!==null){for(a.flags|=128,ks(j,!1),h=R.updateQueue,h!==null&&(a.updateQueue=h,a.flags|=4),a.subtreeFlags=0,h=d,d=a.child;d!==null;)j=d,r=h,j.flags&=14680066,R=j.alternate,R===null?(j.childLanes=0,j.lanes=r,j.child=null,j.subtreeFlags=0,j.memoizedProps=null,j.memoizedState=null,j.updateQueue=null,j.dependencies=null,j.stateNode=null):(j.childLanes=R.childLanes,j.lanes=R.lanes,j.child=R.child,j.subtreeFlags=0,j.deletions=null,j.memoizedProps=R.memoizedProps,j.memoizedState=R.memoizedState,j.updateQueue=R.updateQueue,j.type=R.type,r=R.dependencies,j.dependencies=r===null?null:{lanes:r.lanes,firstContext:r.firstContext}),d=d.sibling;return on(In,In.current&1|2),a.child}r=r.sibling}j.tail!==null&&hn()>xi&&(a.flags|=128,h=!0,ks(j,!1),a.lanes=4194304)}else{if(!h)if(r=vr(R),r!==null){if(a.flags|=128,h=!0,d=r.updateQueue,d!==null&&(a.updateQueue=d,a.flags|=4),ks(j,!0),j.tail===null&&j.tailMode==="hidden"&&!R.alternate&&!vn)return Hn(a),null}else 2*hn()-j.renderingStartTime>xi&&d!==1073741824&&(a.flags|=128,h=!0,ks(j,!1),a.lanes=4194304);j.isBackwards?(R.sibling=a.child,a.child=R):(d=j.last,d!==null?d.sibling=R:a.child=R,j.last=R)}return j.tail!==null?(a=j.tail,j.rendering=a,j.tail=a.sibling,j.renderingStartTime=hn(),a.sibling=null,d=In.current,on(In,h?d&1|2:d&1),a):(Hn(a),null);case 22:case 23:return k(),h=a.memoizedState!==null,r!==null&&r.memoizedState!==null!==h&&(a.flags|=8192),h&&(a.mode&1)!==0?(Zn&1073741824)!==0&&(Hn(a),a.subtreeFlags&6&&(a.flags|=8192)):Hn(a),null;case 24:return null;case 25:return null}throw Error(n(156,a.tag))}function jh(r,a){switch(ud(a),a.tag){case 1:return xs(a.type)&&Dc(),r=a.flags,r&65536?(a.flags=r&-65537|128,a):null;case 3:return Fa(),Sn(rr),Sn(ns),Jc(),r=a.flags,(r&65536)!==0&&(r&128)===0?(a.flags=r&-65537|128,a):null;case 5:return No(a),null;case 13:if(Sn(In),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(In),null;case 4:return Fa(),null;case 10:return Gc(a.type._context),null;case 22:case 23:return k(),null;case 24:return null;default:return null}}var Ms=!1,ms=!1,Sh=typeof WeakSet=="function"?WeakSet:Set,Xe=null;function Ha(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 $d(r,a,d){try{d()}catch(h){Ie(r,a,h)}}var ar=!1;function Bl(r,a){if(Sl=Oo,r=ka(),_o(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,j=h.focusNode;h=h.focusOffset;try{d.nodeType,j.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 Je;Re!==d||v!==0&&Re.nodeType!==3||(ee=R+v),Re!==j||h!==0&&Re.nodeType!==3||(se=R+h),Re.nodeType===3&&(R+=Re.nodeValue.length),(Je=Re.firstChild)!==null;)Te=Re,Re=Je;for(;;){if(Re===r)break t;if(Te===d&&++ye===v&&(ee=R),Te===j&&++Me===h&&(se=R),(Je=Re.nextSibling)!==null)break;Re=Te,Te=Re.parentNode}Re=Je}d=ee===-1||se===-1?null:{start:ee,end:se}}else d=null}d=d||{start:0,end:0}}else d=null;for(od={focusedElem:r,selectionRange:d},Oo=!1,Xe=a;Xe!==null;)if(a=Xe,r=a.child,(a.subtreeFlags&1028)!==0&&r!==null)r.return=a,Xe=r;else for(;Xe!==null;){a=Xe;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,as=tt.memoizedState,de=a.stateNode,le=de.getSnapshotBeforeUpdate(a.elementType===a.type?nt:Wr(a.type,nt),as);de.__reactInternalSnapshotBeforeUpdate=le}break;case 3:var he=a.stateNode.containerInfo;he.nodeType===1?he.textContent="":he.nodeType===9&&he.documentElement&&he.removeChild(he.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,Xe=r;break}Xe=a.return}return tt=ar,ar=!1,tt}function Va(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 j=v.destroy;v.destroy=void 0,j!==void 0&&$d(a,d,j)}v=v.next}while(v!==h)}}function Ul(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 Ad(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 Ed(r){var a=r.alternate;a!==null&&(r.alternate=null,Ed(a)),r.child=null,r.deletions=null,r.sibling=null,r.tag===5&&(a=r.stateNode,a!==null&&(delete a[mi],delete a[Ea],delete a[Oc],delete a[r_],delete a[qf])),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 vi(r){return r.tag===5||r.tag===3||r.tag===4}function kh(r){e:for(;;){for(;r.sibling===null;){if(r.return===null||vi(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 Td(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=jl));else if(h!==4&&(r=r.child,r!==null))for(Td(r,a,d),r=r.sibling;r!==null;)Td(r,a,d),r=r.sibling}function cu(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(cu(r,a,d),r=r.sibling;r!==null;)cu(r,a,d),r=r.sibling}var rs=null,Xn=!1;function si(r,a,d){for(d=d.child;d!==null;)Nh(r,a,d),d=d.sibling}function Nh(r,a,d){if(gs&&typeof gs.onCommitFiberUnmount=="function")try{gs.onCommitFiberUnmount(tn,d)}catch{}switch(d.tag){case 5:ms||Ha(d,a);case 6:var h=rs,v=Xn;rs=null,si(r,a,d),rs=h,Xn=v,rs!==null&&(Xn?(r=rs,d=d.stateNode,r.nodeType===8?r.parentNode.removeChild(d):r.removeChild(d)):rs.removeChild(d.stateNode));break;case 18:rs!==null&&(Xn?(r=rs,d=d.stateNode,r.nodeType===8?Ic(r.parentNode,d):r.nodeType===1&&Ic(r,d),co(r)):Ic(rs,d.stateNode));break;case 4:h=rs,v=Xn,rs=d.stateNode.containerInfo,Xn=!0,si(r,a,d),rs=h,Xn=v;break;case 0:case 11:case 14:case 15:if(!ms&&(h=d.updateQueue,h!==null&&(h=h.lastEffect,h!==null))){v=h=h.next;do{var j=v,R=j.destroy;j=j.tag,R!==void 0&&((j&2)!==0||(j&4)!==0)&&$d(d,a,R),v=v.next}while(v!==h)}si(r,a,d);break;case 1:if(!ms&&(Ha(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)}si(r,a,d);break;case 21:si(r,a,d);break;case 22:d.mode&1?(ms=(h=ms)||d.memoizedState!==null,si(r,a,d),ms=h):si(r,a,d);break;default:si(r,a,d)}}function Vi(r){var a=r.updateQueue;if(a!==null){r.updateQueue=null;var d=r.stateNode;d===null&&(d=r.stateNode=new Sh),a.forEach(function(h){var v=vt.bind(null,r,h);d.has(h)||(d.add(h),h.then(v,v))})}}function br(r,a){var d=a.deletions;if(d!==null)for(var h=0;h<d.length;h++){var v=d[h];try{var j=r,R=a,ee=R;e:for(;ee!==null;){switch(ee.tag){case 5:rs=ee.stateNode,Xn=!1;break e;case 3:rs=ee.stateNode.containerInfo,Xn=!0;break e;case 4:rs=ee.stateNode.containerInfo,Xn=!0;break e}ee=ee.return}if(rs===null)throw Error(n(160));Nh(j,R,v),rs=null,Xn=!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;)uu(a,r),a=a.sibling}function uu(r,a){var d=r.alternate,h=r.flags;switch(r.tag){case 0:case 11:case 14:case 15:if(br(a,r),yn(r),h&4){try{Va(3,r,r.return),Ul(3,r)}catch(nt){Ie(r,r.return,nt)}try{Va(5,r,r.return)}catch(nt){Ie(r,r.return,nt)}}break;case 1:br(a,r),yn(r),h&512&&d!==null&&Ha(d,d.return);break;case 5:if(br(a,r),yn(r),h&512&&d!==null&&Ha(d,d.return),r.flags&32){var v=r.stateNode;try{Mt(v,"")}catch(nt){Ie(r,r.return,nt)}}if(h&4&&(v=r.stateNode,v!=null)){var j=r.memoizedProps,R=d!==null?d.memoizedProps:j,ee=r.type,se=r.updateQueue;if(r.updateQueue=null,se!==null)try{ee==="input"&&j.type==="radio"&&j.name!=null&&Ye(v,j),Cs(ee,R);var ye=Cs(ee,j);for(R=0;R<se.length;R+=2){var Me=se[R],Re=se[R+1];Me==="style"?jn(v,Re):Me==="dangerouslySetInnerHTML"?Bn(v,Re):Me==="children"?Mt(v,Re):D(v,Me,Re,ye)}switch(ee){case"input":Se(v,j);break;case"textarea":Qt(v,j);break;case"select":var Te=v._wrapperState.wasMultiple;v._wrapperState.wasMultiple=!!j.multiple;var Je=j.value;Je!=null?De(v,!!j.multiple,Je,!1):Te!==!!j.multiple&&(j.defaultValue!=null?De(v,!!j.multiple,j.defaultValue,!0):De(v,!!j.multiple,j.multiple?[]:"",!1))}v[Ea]=j}catch(nt){Ie(r,r.return,nt)}}break;case 6:if(br(a,r),yn(r),h&4){if(r.stateNode===null)throw Error(n(162));v=r.stateNode,j=r.memoizedProps;try{v.nodeValue=j}catch(nt){Ie(r,r.return,nt)}}break;case 3:if(br(a,r),yn(r),h&4&&d!==null&&d.memoizedState.isDehydrated)try{co(a.containerInfo)}catch(nt){Ie(r,r.return,nt)}break;case 4:br(a,r),yn(r);break;case 13:br(a,r),yn(r),v=r.child,v.flags&8192&&(j=v.memoizedState!==null,v.stateNode.isHidden=j,!j||v.alternate!==null&&v.alternate.memoizedState!==null||(Id=hn())),h&4&&Vi(r);break;case 22:if(Me=d!==null&&d.memoizedState!==null,r.mode&1?(ms=(ye=ms)||Me,br(a,r),ms=ye):br(a,r),yn(r),h&8192){if(ye=r.memoizedState!==null,(r.stateNode.isHidden=ye)&&!Me&&(r.mode&1)!==0)for(Xe=r,Me=r.child;Me!==null;){for(Re=Xe=Me;Xe!==null;){switch(Te=Xe,Je=Te.child,Te.tag){case 0:case 11:case 14:case 15:Va(4,Te,Te.return);break;case 1:Ha(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:Ha(Te,Te.return);break;case 22:if(Te.memoizedState!==null){Rd(Re);continue}}Je!==null?(Je.return=Te,Xe=Je):Rd(Re)}Me=Me.sibling}e:for(Me=null,Re=r;;){if(Re.tag===5){if(Me===null){Me=Re;try{v=Re.stateNode,ye?(j=v.style,typeof j.setProperty=="function"?j.setProperty("display","none","important"):j.display="none"):(ee=Re.stateNode,se=Re.memoizedProps.style,R=se!=null&&se.hasOwnProperty("display")?se.display:null,ee.style.display=En("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:br(a,r),yn(r),h&4&&Vi(r);break;case 21:break;default:br(a,r),yn(r)}}function yn(r){var a=r.flags;if(a&2){try{e:{for(var d=r.return;d!==null;){if(vi(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&&(Mt(v,""),h.flags&=-33);var j=kh(r);cu(r,j,v);break;case 3:case 4:var R=h.stateNode.containerInfo,ee=kh(r);Td(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 Ga(r,a,d){Xe=r,Ch(r)}function Ch(r,a,d){for(var h=(r.mode&1)!==0;Xe!==null;){var v=Xe,j=v.child;if(v.tag===22&&h){var R=v.memoizedState!==null||Ms;if(!R){var ee=v.alternate,se=ee!==null&&ee.memoizedState!==null||ms;ee=Ms;var ye=ms;if(Ms=R,(ms=se)&&!ye)for(Xe=v;Xe!==null;)R=Xe,se=R.child,R.tag===22&&R.memoizedState!==null?Ld(v):se!==null?(se.return=R,Xe=se):Ld(v);for(;j!==null;)Xe=j,Ch(j),j=j.sibling;Xe=v,Ms=ee,ms=ye}Md(r)}else(v.subtreeFlags&8772)!==0&&j!==null?(j.return=v,Xe=j):Md(r)}}function Md(r){for(;Xe!==null;){var a=Xe;if((a.flags&8772)!==0){var d=a.alternate;try{if((a.flags&8772)!==0)switch(a.tag){case 0:case 11:case 15:ms||Ul(5,a);break;case 1:var h=a.stateNode;if(a.flags&4&&!ms)if(d===null)h.componentDidMount();else{var v=a.elementType===a.type?d.memoizedProps:Wr(a.type,d.memoizedProps);h.componentDidUpdate(v,d.memoizedState,h.__reactInternalSnapshotBeforeUpdate)}var j=a.updateQueue;j!==null&&Jf(a,j,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}Jf(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&&co(Re)}}}break;case 19:case 17:case 21:case 22:case 23:case 25:break;default:throw Error(n(163))}ms||a.flags&512&&Ad(a)}catch(Te){Ie(a,a.return,Te)}}if(a===r){Xe=null;break}if(d=a.sibling,d!==null){d.return=a.return,Xe=d;break}Xe=a.return}}function Rd(r){for(;Xe!==null;){var a=Xe;if(a===r){Xe=null;break}var d=a.sibling;if(d!==null){d.return=a.return,Xe=d;break}Xe=a.return}}function Ld(r){for(;Xe!==null;){var a=Xe;try{switch(a.tag){case 0:case 11:case 15:var d=a.return;try{Ul(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 j=a.return;try{Ad(a)}catch(se){Ie(a,j,se)}break;case 5:var R=a.return;try{Ad(a)}catch(se){Ie(a,R,se)}}}catch(se){Ie(a,a.return,se)}if(a===r){Xe=null;break}var ee=a.sibling;if(ee!==null){ee.return=a.return,Xe=ee;break}Xe=a.return}}var $h=Math.ceil,Wl=M.ReactCurrentDispatcher,ql=M.ReactCurrentOwner,Rs=M.ReactCurrentBatchConfig,Vt=0,is=null,Vn=null,_s=0,Zn=0,Ka=Zr(0),os=0,Hl=null,jr=0,Ya=0,Vl=0,Ja=null,qs=null,Id=0,xi=1/0,Hs=null,du=!1,aa=null,$o=null,fu=!1,Ao=null,Gl=0,Xa=0,Od=null,Kl=-1,Yl=0;function Ls(){return(Vt&6)!==0?hn():Kl!==-1?Kl:Kl=hn()}function Gi(r){return(r.mode&1)===0?1:(Vt&2)!==0&&_s!==0?_s&-_s:i_.transition!==null?(Yl===0&&(Yl=fs()),Yl):(r=nn,r!==0||(r=window.event,r=r===void 0?16:je(r.type)),r)}function qr(r,a,d,h){if(50<Xa)throw Xa=0,Od=null,Error(n(185));ys(r,d,h),((Vt&2)===0||r!==is)&&(r===is&&((Vt&2)===0&&(Ya|=d),os===4&&Ki(r,_s)),Vs(r,h),d===1&&Vt===0&&(a.mode&1)===0&&(xi=hn()+500,La&&gi()))}function Vs(r,a){var d=r.callbackNode;Qn(r,a);var h=_r(r,r===is?_s:0);if(h===0)d!==null&&so(d),r.callbackNode=null,r.callbackPriority=0;else if(a=h&-h,r.callbackPriority!==a){if(d!=null&&so(d),a===1)r.tag===0?Ia(Dd.bind(null,r)):Fc(Dd.bind(null,r)),ld(function(){(Vt&6)===0&&gi()}),d=null;else{switch(ml(h)){case 1:d=$i;break;case 4:d=$r;break;case 16:d=hr;break;case 536870912:d=it;break;default:d=hr}d=$n(d,Pd.bind(null,r))}r.callbackPriority=a,r.callbackNode=d}}function Pd(r,a){if(Kl=-1,Yl=0,(Vt&6)!==0)throw Error(n(327));var d=r.callbackNode;if(qe()&&r.callbackNode!==d)return null;var h=_r(r,r===is?_s:0);if(h===0)return null;if((h&30)!==0||(h&r.expiredLanes)!==0||a)a=V(r,h);else{a=h;var v=Vt;Vt|=2;var j=q();(is!==r||_s!==a)&&(Hs=null,xi=hn()+500,A(r,a));do try{Ee();break}catch(ee){I(r,ee)}while(!0);ss(),Wl.current=j,Vt=v,Vn!==null?a=0:(is=null,_s=0,a=os)}if(a!==0){if(a===2&&(v=Zs(r),v!==0&&(h=v,a=hu(r,v))),a===1)throw d=Hl,A(r,0),Ki(r,h),Vs(r,hn()),d;if(a===6)Ki(r,h);else{if(v=r.current.alternate,(h&30)===0&&!Ah(v)&&(a=V(r,h),a===2&&(j=Zs(r),j!==0&&(h=j,a=hu(r,j))),a===1))throw d=Hl,A(r,0),Ki(r,h),Vs(r,hn()),d;switch(r.finishedWork=v,r.finishedLanes=h,a){case 0:case 1:throw Error(n(345));case 2:Ne(r,qs,Hs);break;case 3:if(Ki(r,h),(h&130023424)===h&&(a=Id+500-hn(),10<a)){if(_r(r,0)!==0)break;if(v=r.suspendedLanes,(v&h)!==h){Ls(),r.pingedLanes|=r.suspendedLanes&v;break}r.timeoutHandle=Lc(Ne.bind(null,r,qs,Hs),a);break}Ne(r,qs,Hs);break;case 4:if(Ki(r,h),(h&4194240)===h)break;for(a=r.eventTimes,v=-1;0<h;){var R=31-ds(h);j=1<<R,R=a[R],R>v&&(v=R),h&=~j}if(h=v,h=hn()-h,h=(120>h?120:480>h?480:1080>h?1080:1920>h?1920:3e3>h?3e3:4320>h?4320:1960*$h(h/1960))-h,10<h){r.timeoutHandle=Lc(Ne.bind(null,r,qs,Hs),h);break}Ne(r,qs,Hs);break;case 5:Ne(r,qs,Hs);break;default:throw Error(n(329))}}}return Vs(r,hn()),r.callbackNode===d?Pd.bind(null,r):null}function hu(r,a){var d=Ja;return r.current.memoizedState.isDehydrated&&(A(r,a).flags|=256),r=V(r,a),r!==2&&(a=qs,qs=d,a!==null&&mu(a)),r}function mu(r){qs===null?qs=r:qs.push.apply(qs,r)}function Ah(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],j=v.getSnapshot;v=v.value;try{if(!Tr(j(),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 Ki(r,a){for(a&=~Vl,a&=~Ya,r.suspendedLanes|=a,r.pingedLanes&=~a,r=r.expirationTimes;0<a;){var d=31-ds(a),h=1<<d;r[d]=-1,a&=~h}}function Dd(r){if((Vt&6)!==0)throw Error(n(327));qe();var a=_r(r,0);if((a&1)===0)return Vs(r,hn()),null;var d=V(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=Hl,A(r,0),Ki(r,a),Vs(r,hn()),d;if(d===6)throw Error(n(345));return r.finishedWork=r.current.alternate,r.finishedLanes=a,Ne(r,qs,Hs),Vs(r,hn()),null}function _u(r,a){var d=Vt;Vt|=1;try{return r(a)}finally{Vt=d,Vt===0&&(xi=hn()+500,La&&gi())}}function g(r){Ao!==null&&Ao.tag===0&&(Vt&6)===0&&qe();var a=Vt;Vt|=1;var d=Rs.transition,h=nn;try{if(Rs.transition=null,nn=1,r)return r()}finally{nn=h,Rs.transition=d,Vt=a,(Vt&6)===0&&gi()}}function k(){Zn=Ka.current,Sn(Ka)}function A(r,a){r.finishedWork=null,r.finishedLanes=0;var d=r.timeoutHandle;if(d!==-1&&(r.timeoutHandle=-1,kl(d)),Vn!==null)for(d=Vn.return;d!==null;){var h=d;switch(ud(h),h.tag){case 1:h=h.type.childContextTypes,h!=null&&Dc();break;case 3:Fa(),Sn(rr),Sn(ns),Jc();break;case 5:No(h);break;case 4:Fa();break;case 13:Sn(In);break;case 19:Sn(In);break;case 10:Gc(h.type._context);break;case 22:case 23:k()}d=d.return}if(is=r,Vn=r=Za(r.current,null),_s=Zn=a,os=0,Hl=null,Vl=Ya=jr=0,qs=Ja=null,So!==null){for(a=0;a<So.length;a++)if(d=So[a],h=d.interleaved,h!==null){d.interleaved=null;var v=h.next,j=d.pending;if(j!==null){var R=j.next;j.next=v,h.next=R}d.pending=h}So=null}return r}function I(r,a){do{var d=Vn;try{if(ss(),Xc.current=Ol,kn){for(var h=Mn.memoizedState;h!==null;){var v=h.queue;v!==null&&(v.pending=null),h=h.next}kn=!1}if(Qo=0,hs=Wn=Mn=null,za=!1,ea=0,ql.current=null,d===null||d.return===null){os=1,Hl=a,Vn=null;break}e:{var j=r,R=d.return,ee=d,se=a;if(a=_s,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 Je=Dl(R);if(Je!==null){Je.flags&=-257,_h(Je,R,ee,j,a),Je.mode&1&&mh(j,ye,a),a=Je,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){mh(j,ye,a),W();break e}se=Error(n(426))}}else if(vn&&ee.mode&1){var as=Dl(R);if(as!==null){(as.flags&65536)===0&&(as.flags|=256),_h(as,R,ee,j,a),md(Ua(se,ee));break e}}j=se=Ua(se,ee),os!==4&&(os=2),Ja===null?Ja=[j]:Ja.push(j),j=R;do{switch(j.tag){case 3:j.flags|=65536,a&=-a,j.lanes|=a;var de=iu(j,se,a);pd(j,de);break e;case 1:ee=se;var le=j.type,he=j.stateNode;if((j.flags&128)===0&&(typeof le.getDerivedStateFromError=="function"||he!==null&&typeof he.componentDidCatch=="function"&&($o===null||!$o.has(he)))){j.flags|=65536,a&=-a,j.lanes|=a;var Fe=hh(j,ee,a);pd(j,Fe);break e}}j=j.return}while(j!==null)}pe(d)}catch(rt){a=rt,Vn===d&&d!==null&&(Vn=d=d.return);continue}break}while(!0)}function q(){var r=Wl.current;return Wl.current=Ol,r===null?Ol:r}function W(){(os===0||os===3||os===2)&&(os=4),is===null||(jr&268435455)===0&&(Ya&268435455)===0||Ki(is,_s)}function V(r,a){var d=Vt;Vt|=2;var h=q();(is!==r||_s!==a)&&(Hs=null,A(r,a));do try{te();break}catch(v){I(r,v)}while(!0);if(ss(),Vt=d,Wl.current=h,Vn!==null)throw Error(n(261));return is=null,_s=0,os}function te(){for(;Vn!==null;)_e(Vn)}function Ee(){for(;Vn!==null&&!xe();)_e(Vn)}function _e(r){var a=xn(r.alternate,r,Zn);r.memoizedProps=r.pendingProps,a===null?pe(r):Vn=a,ql.current=null}function pe(r){var a=r;do{var d=a.alternate;if(r=a.return,(a.flags&32768)===0){if(d=c_(d,a,Zn),d!==null){Vn=d;return}}else{if(d=jh(d,a),d!==null){d.flags&=32767,Vn=d;return}if(r!==null)r.flags|=32768,r.subtreeFlags=0,r.deletions=null;else{os=6,Vn=null;return}}if(a=a.sibling,a!==null){Vn=a;return}Vn=a=r}while(a!==null);os===0&&(os=5)}function Ne(r,a,d){var h=nn,v=Rs.transition;try{Rs.transition=null,nn=1,ze(r,a,d,h)}finally{Rs.transition=v,nn=h}return null}function ze(r,a,d,h){do qe();while(Ao!==null);if((Vt&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 j=d.lanes|d.childLanes;if(wa(r,j),r===is&&(Vn=is=null,_s=0),(d.subtreeFlags&2064)===0&&(d.flags&2064)===0||fu||(fu=!0,$n(hr,function(){return qe(),null})),j=(d.flags&15990)!==0,(d.subtreeFlags&15990)!==0||j){j=Rs.transition,Rs.transition=null;var R=nn;nn=1;var ee=Vt;Vt|=4,ql.current=null,Bl(r,d),uu(d,r),vl(od),Oo=!!Sl,od=Sl=null,r.current=d,Ga(d),Jn(),Vt=ee,nn=R,Rs.transition=j}else r.current=d;if(fu&&(fu=!1,Ao=r,Gl=v),j=r.pendingLanes,j===0&&($o=null),oi(d.stateNode),Vs(r,hn()),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(du)throw du=!1,r=aa,aa=null,r;return(Gl&1)!==0&&r.tag!==0&&qe(),j=r.pendingLanes,(j&1)!==0?r===Od?Xa++:(Xa=0,Od=r):Xa=0,gi(),null}function qe(){if(Ao!==null){var r=ml(Gl),a=Rs.transition,d=nn;try{if(Rs.transition=null,nn=16>r?16:r,Ao===null)var h=!1;else{if(r=Ao,Ao=null,Gl=0,(Vt&6)!==0)throw Error(n(331));var v=Vt;for(Vt|=4,Xe=r.current;Xe!==null;){var j=Xe,R=j.child;if((Xe.flags&16)!==0){var ee=j.deletions;if(ee!==null){for(var se=0;se<ee.length;se++){var ye=ee[se];for(Xe=ye;Xe!==null;){var Me=Xe;switch(Me.tag){case 0:case 11:case 15:Va(8,Me,j)}var Re=Me.child;if(Re!==null)Re.return=Me,Xe=Re;else for(;Xe!==null;){Me=Xe;var Te=Me.sibling,Je=Me.return;if(Ed(Me),Me===ye){Xe=null;break}if(Te!==null){Te.return=Je,Xe=Te;break}Xe=Je}}}var tt=j.alternate;if(tt!==null){var nt=tt.child;if(nt!==null){tt.child=null;do{var as=nt.sibling;nt.sibling=null,nt=as}while(nt!==null)}}Xe=j}}if((j.subtreeFlags&2064)!==0&&R!==null)R.return=j,Xe=R;else e:for(;Xe!==null;){if(j=Xe,(j.flags&2048)!==0)switch(j.tag){case 0:case 11:case 15:Va(9,j,j.return)}var de=j.sibling;if(de!==null){de.return=j.return,Xe=de;break e}Xe=j.return}}var le=r.current;for(Xe=le;Xe!==null;){R=Xe;var he=R.child;if((R.subtreeFlags&2064)!==0&&he!==null)he.return=R,Xe=he;else e:for(R=le;Xe!==null;){if(ee=Xe,(ee.flags&2048)!==0)try{switch(ee.tag){case 0:case 11:case 15:Ul(9,ee)}}catch(rt){Ie(ee,ee.return,rt)}if(ee===R){Xe=null;break e}var Fe=ee.sibling;if(Fe!==null){Fe.return=ee.return,Xe=Fe;break e}Xe=ee.return}}if(Vt=v,gi(),gs&&typeof gs.onPostCommitFiberRoot=="function")try{gs.onPostCommitFiberRoot(tn,r)}catch{}h=!0}return h}finally{nn=d,Rs.transition=a}}return!1}function Ze(r,a,d){a=Ua(d,a),a=iu(r,a,1),r=Ui(r,a,1),a=Ls(),r!==null&&(ys(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"&&($o===null||!$o.has(h))){r=Ua(d,r),r=hh(a,r,1),a=Ui(a,r,1),r=Ls(),a!==null&&(ys(a,1,r),Vs(a,r));break}}a=a.return}}function ln(r,a,d){var h=r.pingCache;h!==null&&h.delete(a),a=Ls(),r.pingedLanes|=r.suspendedLanes&d,is===r&&(_s&d)===d&&(os===4||os===3&&(_s&130023424)===_s&&500>hn()-Id?A(r,0):Vl|=d),Vs(r,a)}function Tt(r,a){a===0&&((r.mode&1)===0?a=1:(a=mr,mr<<=1,(mr&130023424)===0&&(mr=4194304)));var d=Ls();r=Fr(r,a),r!==null&&(ys(r,a,d),Vs(r,d))}function He(r){var a=r.memoizedState,d=0;a!==null&&(d=a.retryLane),Tt(r,d)}function vt(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),Tt(r,d)}var xn;xn=function(r,a,d){if(r!==null)if(r.memoizedProps!==a.pendingProps||rr.current)gn=!0;else{if((r.lanes&d)===0&&(a.flags&128)===0)return gn=!1,l_(r,a,d);gn=(r.flags&131072)!==0}else gn=!1,vn&&(a.flags&1048576)!==0&&Hf(a,zc,a.index);switch(a.lanes=0,a.tag){case 2:var h=a.type;oa(r,a),r=a.pendingProps;var v=Ma(a,ns.current);Pa(a,d),v=Tl(null,a,h,r,v,d);var j=na();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,xs(h)?(j=!0,vo(a)):j=!1,a.memoizedState=v.state!==null&&v.state!==void 0?v.state:null,Xt(a),v.updater=Pl,a.stateNode=v,v._reactInternals=a,jd(a,h,r,d),a=Fl(null,a,h,!0,j,d)):(a.tag=0,vn&&j&&Cl(a),an(null,a,v,d),a=a.child),a;case 16:h=a.elementType;e:{switch(oa(r,a),r=a.pendingProps,v=h._init,h=v(h._payload),a.type=h,v=a.tag=Jl(h),r=Wr(h,r),v){case 0:a=Wa(null,a,h,r,d);break e;case 1:a=gh(null,a,h,r,d);break e;case 11:a=ti(null,a,h,r,d);break e;case 14:a=Wi(null,a,h,Wr(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:Wr(h,v),Wa(r,a,h,v,d);case 1:return h=a.type,v=a.pendingProps,v=a.elementType===h?v:Wr(h,v),gh(r,a,h,v,d);case 3:e:{if(yh(a),r===null)throw Error(n(387));h=a.pendingProps,j=a.memoizedState,v=j.element,js(r,a),at(a,h,null,d);var R=a.memoizedState;if(h=R.element,j.isDehydrated)if(j={element:h,isDehydrated:!1,cache:R.cache,pendingSuspenseBoundaries:R.pendingSuspenseBoundaries,transitions:R.transitions},a.updateQueue.baseState=j,a.memoizedState=j,a.flags&256){v=Ua(Error(n(423)),a),a=wh(r,a,h,d,v);break e}else if(h!==v){v=Ua(Error(n(424)),a),a=wh(r,a,h,d,v);break e}else for(ir=Di(a.stateNode.containerInfo.firstChild),Ts=a,vn=!0,Pr=null,d=Kf(a,null,h,d),a.child=d;d;)d.flags=d.flags&-3|4096,d=d.sibling;else{if(Bi(),h===v){a=wi(r,a,d);break e}an(r,a,h,d)}a=a.child}return a;case 5:return Yc(a),r===null&&Uc(a),h=a.type,v=a.pendingProps,j=r!==null?r.memoizedProps:null,R=v.children,Aa(h,v)?R=null:j!==null&&Aa(h,j)&&(a.flags|=32),ph(r,a),an(r,a,R,d),a.child;case 6:return r===null&&Uc(a),null;case 13:return qa(r,a,d);case 4:return gd(a,a.stateNode.containerInfo),h=a.pendingProps,r===null?a.child=bo(a,null,h,d):an(r,a,h,d),a.child;case 11:return h=a.type,v=a.pendingProps,v=a.elementType===h?v:Wr(h,v),ti(r,a,h,v,d);case 7:return an(r,a,a.pendingProps,d),a.child;case 8:return an(r,a,a.pendingProps.children,d),a.child;case 12:return an(r,a,a.pendingProps.children,d),a.child;case 10:e:{if(h=a.type._context,v=a.pendingProps,j=a.memoizedProps,R=v.value,on(Al,h._currentValue),h._currentValue=R,j!==null)if(Tr(j.value,R)){if(j.children===v.children&&!rr.current){a=wi(r,a,d);break e}}else for(j=a.child,j!==null&&(j.return=a);j!==null;){var ee=j.dependencies;if(ee!==null){R=j.child;for(var se=ee.firstContext;se!==null;){if(se.context===h){if(j.tag===1){se=ei(-1,d&-d),se.tag=2;var ye=j.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}}j.lanes|=d,se=j.alternate,se!==null&&(se.lanes|=d),_d(j.return,d,a),ee.lanes|=d;break}se=se.next}}else if(j.tag===10)R=j.type===a.type?null:j.child;else if(j.tag===18){if(R=j.return,R===null)throw Error(n(341));R.lanes|=d,ee=R.alternate,ee!==null&&(ee.lanes|=d),_d(R,d,a),R=j.sibling}else R=j.child;if(R!==null)R.return=j;else for(R=j;R!==null;){if(R===a){R=null;break}if(j=R.sibling,j!==null){j.return=R.return,R=j;break}R=R.return}j=R}an(r,a,v.children,d),a=a.child}return a;case 9:return v=a.type,h=a.pendingProps.children,Pa(a,d),v=Dr(v),h=h(v),a.flags|=1,an(r,a,h,d),a.child;case 14:return h=a.type,v=Wr(h,a.pendingProps),v=Wr(h.type,v),Wi(r,a,h,v,d);case 15:return qi(r,a,a.type,a.pendingProps,d);case 17:return h=a.type,v=a.pendingProps,v=a.elementType===h?v:Wr(h,v),oa(r,a),a.tag=1,xs(h)?(r=!0,vo(a)):r=!1,Pa(a,d),uh(a,h,v),jd(a,h,v,d),Fl(null,a,h,!0,r,d);case 19:return vh(r,a,d);case 22:return ni(r,a,d)}throw Error(n(156,a.tag))};function $n(r,a){return Xs(r,a)}function lr(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 Pn(r,a,d,h){return new lr(r,a,d,h)}function Sr(r){return r=r.prototype,!(!r||!r.isReactComponent)}function Jl(r){if(typeof r=="function")return Sr(r)?1:0;if(r!=null){if(r=r.$$typeof,r===F)return 11;if(r===O)return 14}return 2}function Za(r,a){var d=r.alternate;return d===null?(d=Pn(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 Eh(r,a,d,h,v,j){var R=2;if(h=r,typeof r=="function")Sr(r)&&(R=1);else if(typeof r=="string")R=5;else e:switch(r){case Y:return Xl(d.children,v,j,a);case X:R=8,v|=8;break;case re:return r=Pn(12,d,a,v|2),r.elementType=re,r.lanes=j,r;case C:return r=Pn(13,d,a,v),r.elementType=C,r.lanes=j,r;case N:return r=Pn(19,d,a,v),r.elementType=N,r.lanes=j,r;case ne:return Th(d,v,j,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 O:R=14;break e;case P:R=16,h=null;break e}throw Error(n(130,r==null?r:typeof r,""))}return a=Pn(R,d,a,v),a.elementType=r,a.type=h,a.lanes=j,a}function Xl(r,a,d,h){return r=Pn(7,r,h,a),r.lanes=d,r}function Th(r,a,d,h){return r=Pn(22,r,h,a),r.elementType=ne,r.lanes=d,r.stateNode={isHidden:!1},r}function u_(r,a,d){return r=Pn(6,r,null,a),r.lanes=d,r}function d_(r,a,d){return a=Pn(4,r.children!==null?r.children:[],r.key,a),a.lanes=d,a.stateNode={containerInfo:r.containerInfo,pendingChildren:null,implementation:r.implementation},a}function s0(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=Yr(0),this.expirationTimes=Yr(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Yr(0),this.identifierPrefix=h,this.onRecoverableError=v,this.mutableSourceEagerHydrationData=null}function f_(r,a,d,h,v,j,R,ee,se){return r=new s0(r,a,d,ee,se),a===1?(a=1,j===!0&&(a|=8)):a=0,j=Pn(3,null,null,a),r.current=j,j.stateNode=r,j.memoizedState={element:h,isDehydrated:d,cache:null,transitions:null,pendingSuspenseBoundaries:null},Xt(j),r}function r0(r,a,d){var h=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:Z,key:h==null?null:""+h,children:r,containerInfo:a,implementation:d}}function Pg(r){if(!r)return wo;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(xs(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(xs(d))return cd(r,d,a)}return a}function Dg(r,a,d,h,v,j,R,ee,se){return r=f_(d,h,!0,r,v,j,R,ee,se),r.context=Pg(null),d=r.current,h=Ls(),v=Gi(d),j=ei(h,v),j.callback=a??null,Ui(d,j,v),r.current.lanes=v,ys(r,v,h),Vs(r,h),r}function Mh(r,a,d,h){var v=a.current,j=Ls(),R=Gi(v);return d=Pg(d),a.context===null?a.context=d:a.pendingContext=d,a=ei(j,R),a.payload={element:r},h=h===void 0?null:h,h!==null&&(a.callback=h),r=Ui(v,a,R),r!==null&&(qr(r,v,R,j),ko(r,v,R)),R}function Rh(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 Fg(r,a){if(r=r.memoizedState,r!==null&&r.dehydrated!==null){var d=r.retryLane;r.retryLane=d!==0&&d<a?d:a}}function h_(r,a){Fg(r,a),(r=r.alternate)&&Fg(r,a)}function i0(){return null}var zg=typeof reportError=="function"?reportError:function(r){console.error(r)};function m_(r){this._internalRoot=r}Lh.prototype.render=m_.prototype.render=function(r){var a=this._internalRoot;if(a===null)throw Error(n(409));Mh(r,a,null,null)},Lh.prototype.unmount=m_.prototype.unmount=function(){var r=this._internalRoot;if(r!==null){this._internalRoot=null;var a=r.containerInfo;g(function(){Mh(null,r,null,null)}),a[Fi]=null}};function Lh(r){this._internalRoot=r}Lh.prototype.unstable_scheduleHydration=function(r){if(r){var a=va();r={blockedOn:null,target:r,priority:a};for(var d=0;d<gr.length&&a!==0&&a<gr[d].priority;d++);gr.splice(d,0,r),d===0&&tr(r)}};function __(r){return!(!r||r.nodeType!==1&&r.nodeType!==9&&r.nodeType!==11)}function Ih(r){return!(!r||r.nodeType!==1&&r.nodeType!==9&&r.nodeType!==11&&(r.nodeType!==8||r.nodeValue!==" react-mount-point-unstable "))}function Bg(){}function o0(r,a,d,h,v){if(v){if(typeof h=="function"){var j=h;h=function(){var ye=Rh(R);j.call(ye)}}var R=Dg(a,h,r,0,null,!1,!1,"",Bg);return r._reactRootContainer=R,r[Fi]=R.current,Mr(r.nodeType===8?r.parentNode:r),g(),R}for(;v=r.lastChild;)r.removeChild(v);if(typeof h=="function"){var ee=h;h=function(){var ye=Rh(se);ee.call(ye)}}var se=f_(r,0,!1,null,null,!1,!1,"",Bg);return r._reactRootContainer=se,r[Fi]=se.current,Mr(r.nodeType===8?r.parentNode:r),g(function(){Mh(a,se,d,h)}),se}function Oh(r,a,d,h,v){var j=d._reactRootContainer;if(j){var R=j;if(typeof v=="function"){var ee=v;v=function(){var se=Rh(R);ee.call(se)}}Mh(a,R,r,v)}else R=o0(d,a,r,v,h);return Rh(R)}Ai=function(r){switch(r.tag){case 3:var a=r.stateNode;if(a.current.memoizedState.isDehydrated){var d=Tn(a.pendingLanes);d!==0&&(lo(a,d|1),Vs(a,hn()),(Vt&6)===0&&(xi=hn()+500,gi()))}break;case 13:g(function(){var h=Fr(r,1);if(h!==null){var v=Ls();qr(h,r,1,v)}}),h_(r,1)}},pr=function(r){if(r.tag===13){var a=Fr(r,134217728);if(a!==null){var d=Ls();qr(a,r,134217728,d)}h_(r,134217728)}},As=function(r){if(r.tag===13){var a=Gi(r),d=Fr(r,a);if(d!==null){var h=Ls();qr(d,r,a,h)}h_(r,a)}},va=function(){return nn},Ar=function(r,a){var d=nn;try{return nn=r,a()}finally{nn=d}},Cr=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=Pc(h);if(!v)throw Error(n(90));_t(h),Se(h,v)}}}break;case"textarea":Qt(r,d);break;case"select":a=d.value,a!=null&&De(r,!!d.multiple,a,!1)}},st=_u,ut=g;var a0={usingClientEntryPoint:!1,Events:[Ta,_i,Pc,Ge,Ve,_u]},Fd={findFiberByHostInstance:Go,bundleType:0,version:"18.3.1",rendererPackageName:"react-dom"},l0={bundleType:Fd.bundleType,version:Fd.version,rendererPackageName:Fd.rendererPackageName,rendererConfig:Fd.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:M.ReactCurrentDispatcher,findHostInstanceByFiber:function(r){return r=$s(r),r===null?null:r.stateNode},findFiberByHostInstance:Fd.findFiberByHostInstance||i0,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 Ph=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!Ph.isDisabled&&Ph.supportsFiber)try{tn=Ph.inject(l0),gs=Ph}catch{}}return Hr.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=a0,Hr.createPortal=function(r,a){var d=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!__(a))throw Error(n(200));return r0(r,a,null,d)},Hr.createRoot=function(r,a){if(!__(r))throw Error(n(299));var d=!1,h="",v=zg;return a!=null&&(a.unstable_strictMode===!0&&(d=!0),a.identifierPrefix!==void 0&&(h=a.identifierPrefix),a.onRecoverableError!==void 0&&(v=a.onRecoverableError)),a=f_(r,1,!1,null,null,d,!1,h,v),r[Fi]=a.current,Mr(r.nodeType===8?r.parentNode:r),new m_(a)},Hr.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=$s(a),r=r===null?null:r.stateNode,r},Hr.flushSync=function(r){return g(r)},Hr.hydrate=function(r,a,d){if(!Ih(a))throw Error(n(200));return Oh(null,r,a,!0,d)},Hr.hydrateRoot=function(r,a,d){if(!__(r))throw Error(n(405));var h=d!=null&&d.hydratedSources||null,v=!1,j="",R=zg;if(d!=null&&(d.unstable_strictMode===!0&&(v=!0),d.identifierPrefix!==void 0&&(j=d.identifierPrefix),d.onRecoverableError!==void 0&&(R=d.onRecoverableError)),a=Dg(a,null,r,1,d??null,v,!1,j,R),r[Fi]=a.current,Mr(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 Lh(a)},Hr.render=function(r,a,d){if(!Ih(a))throw Error(n(200));return Oh(null,r,a,!1,d)},Hr.unmountComponentAtNode=function(r){if(!Ih(r))throw Error(n(40));return r._reactRootContainer?(g(function(){Oh(null,null,r,!1,function(){r._reactRootContainer=null,r[Fi]=null})}),!0):!1},Hr.unstable_batchedUpdates=_u,Hr.unstable_renderSubtreeIntoContainer=function(r,a,d,h){if(!Ih(d))throw Error(n(200));if(r==null||r._reactInternals===void 0)throw Error(n(38));return Oh(r,a,d,!1,h)},Hr.version="18.3.1-next-f1338f8080-20240426",Hr}var Yg;function iv(){if(Yg)return y_.exports;Yg=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(),y_.exports=g0(),y_.exports}var Jg;function y0(){if(Jg)return Dh;Jg=1;var e=iv();return Dh.createRoot=e.createRoot,Dh.hydrateRoot=e.hydrateRoot,Dh}var w0=y0();const v0=tg(w0);async function ov(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 x0=3,b0=Number.MAX_SAFE_INTEGER;function av(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function lv(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 S0(e){if(e==null)return"";if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}}function Nu({kind:e,children:t}){return s.jsx("span",{className:`json-token ${e}`,children:t})}function k0(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(Nu,{kind:"string",children:t})}function N0(e,t,n){return e===null?s.jsx(Nu,{kind:"null",children:"null"}):typeof e=="string"?s.jsx(k0,{value:e,expansion_mode:t,expansion_version:n}):typeof e=="number"?s.jsx(Nu,{kind:"number",children:String(e)}):typeof e=="boolean"?s.jsx(Nu,{kind:"boolean",children:e?"true":"false"}):s.jsx(Nu,{kind:"string",children:JSON.stringify(String(e))})}function C0(e){return lv(e)?e.length===1?"1 item":`${e.length} items`:av(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,_=av(n),p=lv(n),w=_||p,y=i<o,[x,S]=m.useState(y);m.useEffect(()=>{S(y)},[y,u]);const b=t?s.jsxs(s.Fragment,{children:[s.jsx(Nu,{kind:"key",children:JSON.stringify(t)}),": "]}):null;if(!w)return s.jsxs("div",{className:"json-viewer__line",style:{paddingLeft:f},children:[b,N0(n,l,u),c?",":""]});const $=p?"[":"{",E=p?"]":"}",L=C0(n),D=x?`${$}`:`${$}…${E}${L?` (${L})`:""}`,M=p?n.map((H,Z)=>({key:String(Z),label:void 0,value:H})):Object.entries(n).map(([H,Z])=>({key:H,label:H,value:Z}));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:[b,s.jsx("span",{className:"json-viewer__caret","aria-hidden":"true",children:x?"▾":"▸"}),s.jsx("span",{className:"json-viewer__punct",children:D}),!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:E}),c?",":""]}):s.jsxs(s.Fragment,{children:[M.map((H,Z)=>{const Y=Z===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:E}),c?",":""]})]})}):null]})}function uv(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):x0,c=o.mode==="unfolded"?b0:u,f=m.useMemo(()=>typeof t=="string"?j0(t):t,[t]),_=m.useMemo(()=>S0(t),[t]),p=["json-viewer",n].filter(Boolean).join(" ");m.useEffect(()=>{l(y=>({mode:"folded",version:y.version+1}))},[f]);const w=()=>{l(y=>({mode:y.mode==="unfolded"?"folded":"unfolded",version:y.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:w,"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 ov(_),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 x_(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 $0(e){return String(e??"").replace(/\r\n/g,`
41
- `).replace(/\r/g,`
42
- `).split(`
43
- `)}function A0({text:e,className:t}){const n=$0(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 y=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:y?`language-${y}`:void 0,children:S})},`pre:${o}`));continue}const f=c.match(/^(#{1,3})\s+(.*)$/);if(f){const w=f[1].length,y=f[2]||"",x=x_(y);w===1?i.push(s.jsx("h1",{children:x},`h1:${o}`)):w===2?i.push(s.jsx("h2",{children:x},`h2:${o}`)):i.push(s.jsx("h3",{children:x},`h3:${o}`)),o+=1;continue}const _=w=>{const y=w.trimStart();return y.startsWith("- ")||y.startsWith("* ")};if(_(c)){const w=[];for(;o<n.length&&_(String(n[o]??""));){const y=String(n[o]??"").trimStart();w.push(y.slice(2)),o+=1}i.push(s.jsx("ul",{className:"mf-md_ul",children:w.map((y,x)=>s.jsx("li",{children:x_(y)},`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((w,y)=>s.jsxs(ve.Fragment,{children:[x_(w),y<p.length-1?s.jsx("br",{}):null]},`pl:${o}:${y}`))},`p:${o}`))}const l=["mf-md",t].filter(Boolean).join(" ");return s.jsx("div",{className:l,children:i})}const Xg="observe";function Nr(e){return!e||typeof e!="object"?null:e}function hp(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 Zg(e){const t=Nr(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 E0(e){if(Array.isArray(e)){if(e.length===0)return null;const n=[];for(const i of e){const o=Zg(i);if(!o)return null;n.push(o)}return n}const t=Zg(e);return t?[t]:null}function T0(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 M0(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 Qg({text:e}){const t=String(e||""),n=T0(t);if(n!==null)return s.jsx(uv,{value:n});const i=t.trim();return i.startsWith("{")||i.startsWith("[")?s.jsx("pre",{className:"run-details-output",children:t||"(none)"}):t.includes(`
45
- `)||M0(t)?s.jsx("div",{className:"run-details-output",children:s.jsx(A0,{text:t})}):s.jsx("pre",{className:"run-details-output",children:t||"(none)"})}function dv({value:e}){if(e==null)return s.jsx("pre",{className:"run-details-output",children:"(none)"});const t=E0(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(Qg,{text:n.content})})]},`${n.role}:${i}`))}):typeof e=="string"?s.jsx(Qg,{text:e}):s.jsx(uv,{value:e})}function fv(e){const t=e.effect;return!t||typeof t!="object"?null:t}function dl(e){const t=fv(e);return(t&&typeof t.type=="string"?t.type:"")||"effect"}function Pm(e){const t=fv(e),n=t==null?void 0:t.payload;return!n||typeof n!="object"?null:n}function ng(e){const t=e.result;return!t||typeof t!="object"?null:t}function hv(e){if(dl(e)!=="tool_calls")return[];const n=ng(e),i=n&&Array.isArray(n.results)?n.results:null;if(!i)return[];const o=[];for(const l of i){const u=Nr(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(dl(e)!=="tool_calls")return[];const n=Pm(e),i=n&&Array.isArray(n.tool_calls)?n.tool_calls:null;if(!i)return[];const o=[];for(const l of i){const u=Nr(l);if(!u)continue;const c=typeof u.name=="string"?u.name.trim():"";if(!c)continue;const f=Nr(u.args)||Nr(u.arguments)||{};o.push({call_id:typeof u.call_id=="string"?u.call_id:void 0,name:c,args:f})}return o}function Dm(e){const t=e.error;if(typeof t=="string")return t.trim();const n=Nr(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 _v(e){if(!e)return"";const t=e.reasoning;if(typeof t=="string")return t.trim();const n=Nr(t);return n&&typeof n.text=="string"?n.text.trim():""}function pv(e){const t=dl(e),n=Pm(e),i=ng(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=_v(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=Nr(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 _m(e){const t=typeof e.status=="string"?e.status:"unknown";return t==="failed"||Dm(e.step)?"failed":t}function R0(e){const t=e.map(n=>_m(n));return t.some(n=>n==="failed")?"failed":t.some(n=>n==="waiting")?"waiting":t.some(n=>n==="running")?"running":"completed"}function b_(e){return e.filter(t=>!t.hidden)}function L0(e){const t=dl(e),n=Dm(e);return b_(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 I0(e){const t=dl(e);return t==="llm_call"?"user":t==="tool_calls"?"tools":Dm(e)?"errors":"raw"}function O0(e){const t=new Map,n=Pm(e),i=n&&Array.isArray(n.tools)?n.tools:null;if(!i)return t;for(const o of i){const l=Nr(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=Nr(_);return(p&&typeof p.id=="string"?p.id.trim():"")||""}).filter(Boolean);t.set(u,f)}return t}function gv(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(hp(_,42))}`:typeof _=="number"||typeof _=="boolean"?`${f}=${String(_)}`:_==null?`${f}=null`:`${f}=${hp(JSON.stringify(_),42)}`});return`${e}(${c.join(", ")}${u.length>5?", …":""})`}function P0(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 j_({item:e,label:t,toolDefs:n,defaultOpen:i=!1}){const o=e.step,l=dl(o),u=L0(o),c=I0(o),[f,_]=m.useState(c),[p,w]=m.useState(!!i),y=Pm(o),x=ng(o),S=Dm(o),b=P0(e),$=e.nodeId?String(e.nodeId):"",E=e.runId?String(e.runId):"",L=l==="tool_calls"?mv(o):[],D=l==="tool_calls"?hv(o):[],M=L.map(ie=>gv(ie.name,ie.args,n.get(ie.name)||null)),Z=(()=>{if(f==="raw")return o;if(f==="errors")return S||null;if(l==="llm_call"){const ie=y||{},ue=typeof ie.system_prompt=="string"?String(ie.system_prompt):"",F=typeof ie.prompt=="string"?String(ie.prompt):"",C=Nr(x==null?void 0:x.metadata),N=C?Nr(C._runtime_observability):null,O=N?Nr(N.llm_generate_kwargs):null,P=O&&Array.isArray(O.messages)?O.messages:null,ne=C?Nr(C._provider_request):null,B=ne?Nr(ne.payload):null,z=B&&Array.isArray(B.messages)?B.messages:null,G=Array.isArray(ie.messages)?ie.messages:[],T=P||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(me=>typeof(me==null?void 0:me.content)=="string"&&String(me.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(me=>typeof(me==null?void 0:me.content)=="string"&&String(me.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 _v(x)||null}return l==="tool_calls"&&f==="tools"?{tool_calls:L,tool_signatures:M,results:D}:o})(),Y=pv(o),X=_m(e),re=X==="completed"?"OK":X==="failed"?"ERROR":X==="waiting"?"WAITING":X.toUpperCase();return s.jsxs("details",{className:`agent-trace-entry ${X}`,open:p,onToggle:ie=>w(ie.currentTarget.open),children:[s.jsxs("summary",{className:"agent-trace-summary",children:[s.jsx("span",{className:`agent-trace-status ${X}`,children:re}),s.jsx("span",{className:"agent-cycle-stage","data-stage":t,children:t}),s.jsx("span",{className:"agent-trace-kind",children:l}),b?s.jsx("span",{className:"agent-trace-node",children:b}):null,$?s.jsx("span",{className:"agent-trace-node",children:$}):null,E?s.jsx("span",{className:"agent-trace-run",children:E}):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(dv,{value:Z})]})]})}function D0({acts:e}){const t=e.flatMap(l=>hv(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":Xg,children:Xg}),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(dv,{value:_})]},`${l.name}:${l.call_id||""}:${u}`)})})})]})}function F0({items:e,subRunId:t,title:n,subtitle:i,onOpenSubRun:o,defaultOpenLatest:l=!0}){const u=m.useMemo(()=>{const w=Array.isArray(e)?e.slice():[];return w.sort((y,x)=>{const S=y.ts?new Date(y.ts).getTime():NaN,b=x.ts?new Date(x.ts).getTime():NaN;return Number.isFinite(S)&&Number.isFinite(b)?S-b:0}),w},[e]),c=m.useMemo(()=>{const w=[];let y=null,x=0;for(const S of u){const b=dl(S.step);if(b==="llm_call"){x+=1,y={id:`cycle:${S.runId}:${x}:${S.ts||""}`,index:x,items:[S],think:S,acts:[],others:[],status:_m(S),ts:S.ts},w.push(y);continue}y||(x+=1,y={id:`cycle:${S.runId}:${x}:${S.ts||""}`,index:x,items:[],think:null,acts:[],others:[],status:_m(S),ts:S.ts},w.push(y)),y.items.push(S),b==="tool_calls"?y.acts.push(S):y.others.push(S),y.status=R0(y.items)}return w},[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:w=>{w.stopPropagation(),ov(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:w=>{w.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(w=>{const y=w.status,x=y==="completed"?"OK":y==="failed"?"ERROR":y==="waiting"?"WAITING":y.toUpperCase(),S=y==="completed"?"✓":y==="failed"?"✗":"",b=S?`${S} ${x}`:x,$=w.think?pv(w.think.step):"",E=w.think?O0(w.think.step):new Map,D=w.acts.flatMap(H=>mv(H.step)).map(H=>gv(H.name,H.args,E.get(H.name)||null)),M=l&&w.index===c.length;return s.jsxs("details",{className:`agent-cycle ${y}`,open:M,children:[s.jsxs("summary",{className:"agent-cycle-summary",children:[s.jsx("span",{className:`agent-trace-status ${y}`,children:b}),s.jsx("span",{className:"agent-cycle-label",children:"cycle"}),s.jsxs("span",{className:"agent-cycle-index",children:["#",w.index]}),D.length?s.jsxs("span",{className:"agent-trace-badges",children:[D.slice(0,3).map(H=>s.jsx("span",{className:"run-metric-badge metric-tool",title:H,children:hp(H,62)},H)),D.length>3?s.jsxs("span",{className:"run-metric-badge metric-tool",children:["+",D.length-3]}):null]}):null,s.jsx("span",{className:"agent-cycle-spacer"}),$?s.jsx("span",{className:"agent-cycle-preview",children:$}):null]}),s.jsxs("div",{className:"agent-cycle-body",children:[w.think?s.jsx(j_,{item:w.think,label:"think",toolDefs:E,defaultOpen:M}):null,w.acts.map(H=>s.jsx(j_,{item:H,label:"act",toolDefs:E},H.id)),s.jsx(D0,{acts:w.acts}),w.others.length?s.jsxs("div",{className:"agent-cycle-others",children:[s.jsx("div",{className:"agent-cycle-others-title",children:"other"}),w.others.map(H=>{const Z=M&&dl(H.step)==="answer_user";return s.jsx(j_,{item:H,label:"other",toolDefs:E,defaultOpen:Z},H.id)})]}):null]})]},w.id)})]})]})}function to(e){return typeof e=="string"?e.trim():""}function z0(e){var t;return to(e.run_id)||to((t=e.record)==null?void 0:t.run_id)}function mp(e){return to(e==null?void 0:e.node_id)}const B0=new Set(["reason","act","observe","thought","think"]);function _p(e){const t=to(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 B0.has(i)?n.slice(0,-1).join("::"):t}function yv(e){var t;return to((t=e==null?void 0:e.effect)==null?void 0:t.type)}function U0(e){return to(e==null?void 0:e.status)||"unknown"}function ey(e){return to(e==null?void 0:e.step_id)}function W0(e){return to(e==null?void 0:e.ended_at)||to(e==null?void 0:e.started_at)}function q0(e){const t=new Map,n=new Map;for(const o of e){const l=_p(mp(o));if(!l)continue;const u=yv(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 H0(e,t){const n=to(t.run_id);if(!n)return{run_id:"",node_id:"",items:[]};const i=(Array.isArray(e)?e:[]).filter(x=>x&&x.record&&z0(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=_p(to(t.node_id)),u=l||q0(o),c=new Set(["llm_call","tool_calls","ask_user","answer_user"]);let f=i.filter(x=>c.has(yv(x.record)));l&&(f=f.filter(x=>_p(mp(x.record))===l));const _=new Map,p=[];for(const x of f){const S=ey(x.record);if(!S){p.push(x);continue}const b=_.get(S);(!b||(x.cursor||0)>(b.cursor||0))&&_.set(S,x)}const y=[...p,...Array.from(_.values())].sort((x,S)=>(x.cursor||0)-(S.cursor||0)).map(x=>{const S=x.record,b=mp(S)||"(node?)",$=W0(S),E=ey(S);return{id:`ledger:${n}:${x.cursor}:${E||""}`,runId:n,nodeId:b,ts:$||void 0,status:U0(S),step:S}});return{run_id:n,node_id:u,items:y}}function Fm(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 V0(e){if(e==null)return"";if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}}function G0(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 K0(e){return e.endsWith(`
46
- `)?e:`${e}
47
- `}function Y0(e){return String(e||"").trimStart().startsWith("```")}function J0(e,t){const i=[`# ${String((t==null?void 0:t.heading)||"Chat").trim()||"Chat"}`,""];for(const o of e){const l=G0(o);i.push(`## ${l}`,"");const u=String(o.content||""),c=Fm(u);c!==null&&!Y0(u)?i.push("```json",V0(c).trimEnd(),"```",""):i.push(K0(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 dc(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 X0(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 Z0=3,Q0=Number.MAX_SAFE_INTEGER;function wv(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function vv(e){return Array.isArray(e)}function ej(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:`pc-json-token ${e}`,children:t})}function tj(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(Cu,{kind:"string",children:t})}function nj(e,t,n){return e===null?s.jsx(Cu,{kind:"null",children:"null"}):typeof e=="string"?s.jsx(tj,{value:e,expansionMode:t,expansionVersion: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 sj(e){return vv(e)?e.length===1?"1 item":`${e.length} items`:wv(e)?Object.keys(e).length===1?"1 key":`${Object.keys(e).length} keys`:""}function xv(e){const{label:t,value:n,depth:i,collapseAfterDepth:o,expansionMode:l,expansionVersion:u,trailingComma:c}=e,f=i*14,_=wv(n),p=vv(n),w=_||p,y=i<o,[x,S]=m.useState(y);m.useEffect(()=>{S(y)},[y,u]);const b=t?s.jsxs(s.Fragment,{children:[s.jsx(Cu,{kind:"key",children:JSON.stringify(t)}),": "]}):null;if(!w)return s.jsxs("div",{className:"pc-json-viewer__line",style:{paddingLeft:f},children:[b,nj(n,l,u),c?",":""]});const $=p?"[":"{",E=p?"]":"}",L=sj(n),D=x?`${$}`:`${$}…${E}${L?` (${L})`:""}`,M=p?n.map((H,Z)=>({key:String(Z),label:void 0,value:H})):Object.entries(n).map(([H,Z])=>({key:H,label:H,value:Z}));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:[b,s.jsx("span",{className:"pc-json-viewer__caret","aria-hidden":"true",children:x?"▾":"▸"}),s.jsx("span",{className:"pc-json-viewer__punct",children:D}),!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:E}),c?",":""]}):s.jsxs(s.Fragment,{children:[M.map((H,Z)=>{const Y=Z===M.length-1;return s.jsx(xv,{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:E}),c?",":""]})]})}):null]})}function rj(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 dr(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):Z0,c=o.mode==="unfolded"?Q0:u,f=m.useMemo(()=>typeof t=="string"?rj(t):t,[t]),_=m.useMemo(()=>ej(t),[t]),p=["pc-json-viewer",n].filter(Boolean).join(" ");m.useEffect(()=>{l(y=>({mode:"folded",version:y.version+1}))},[f]);const w=()=>{l(y=>({mode:y.mode==="unfolded"?"folded":"unfolded",version:y.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:w,"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 dc(_),children:"Copy JSON"}):null]}),s.jsx("div",{className:"pc-json-viewer__tree",role:"tree","aria-label":"JSON viewer",children:s.jsx(xv,{value:f,depth:0,collapseAfterDepth:c,expansionMode:o.mode,expansionVersion:o.version,trailingComma:!1})})]})}function Bd(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 w=t.needlesLower[p];if(!w)continue;const y=o.indexOf(w,l);if(y===-1)continue;const x=t.needles[p]||"";x&&(u===-1||y<u||y===u&&x.length>c.length)&&(u=y,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 bv(e){const t=String(e||"").trim();if(t&&/^(https?:|mailto:|tel:|#|\/)/i.test(t))return t}const pp="http://same-origin.invalid/";function ij(e){try{const t=new URL(e,pp);return t.protocol==="http:"&&t.origin===new URL(pp).origin}catch{return!1}}function jv(e){const t=String(e||"").trim();return bv(t)??(t&&ij(t)?t:void 0)}let oc=null;function oj(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??pp;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 Sv(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 rl(e,t){const n=[],i=String(e??"");let o=0,l="";const u=()=>{if(l){for(const c of Bd(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),w=jv(i.slice(f+2,_));if(w&&oc&&!oc(w)){u(),n.push(Sv(`img:${o}`,w,p)),o=_+1;continue}if(w){u(),n.push(s.jsxs("span",{className:"pc-md_image_inline",children:[s.jsx("img",{className:"pc-md_img",src:w,alt:p,loading:"lazy"}),p?s.jsx("span",{className:"pc-md_img_caption",children:t?Bd(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),w=bv(i.slice(f+2,_));if(w){u(),n.push(s.jsx("a",{className:"pc-md_link",href:w,target:w.startsWith("#")?void 0:"_blank",rel:"noreferrer",children:rl(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?Bd(_,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?Bd(_,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?Bd(_,t):_},`em:${o}`)),o=f+1;continue}}l+=c,o+=1}return u(),n}function aj(e){return String(e??"").replace(/\r\n/g,`
50
- `).replace(/\r/g,`
51
- `).split(`
52
- `)}function am(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 lj(e){const t=[];for(const o of e){const l=am(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 kv(e,t,n){const i=e.items.map((o,l)=>s.jsxs("li",{children:[rl(o.content,t),o.children.map((u,c)=>kv(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 cj(e,t,n){return lj(e).map((i,o)=>kv(i,t,`${n}:${o}`))}function ty(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 ny(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 sy=/^(#{1,5})\s+(.*)$/;function ry(e){return e.trim().startsWith("```")}function iy(e){return e.trimStart().startsWith(">")}function Ni(e){const t=oc;oc=e.images==="link"?e.inlineImage||oj:null;try{return uj(e)}finally{oc=t}}function uj({text:e,className:t,highlight:n,highlights:i,highlightClassName:o,highlightId:l}){const u=aj(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 w=0;for(;w<u.length;){const x=String(u[w]??"");if(!x.trim()){w+=1;continue}const S=x.trim();if(/^([-_*])(\s*\1){2,}$/.test(S)){c.push(s.jsx("hr",{className:"pc-md_hr"},`hr:${w}`)),w+=1;continue}const b=x.match(/^\s*!\[([^\]]*)\]\(([^)]+)\)\s*$/);if(b){const L=jv(b[2]||"");if(L&&oc&&!oc(L)){c.push(s.jsx("p",{className:"pc-md_p",children:Sv(`img:${w}`,L,b[1]||"")},`p:${w}`)),w+=1;continue}if(L){const D=b[1]||"";c.push(s.jsxs("figure",{className:"pc-md_figure",children:[s.jsx("img",{className:"pc-md_img",src:L,alt:D,loading:"lazy"}),D?s.jsx("figcaption",{children:rl(D,p)}):null]},`figure:${w}`)),w+=1;continue}}if(ry(x)){const D=x.trim().replace(/```/g,"").trim(),M=[];for(w+=1;w<u.length&&!String(u[w]??"").trim().startsWith("```");)M.push(String(u[w]??"")),w+=1;w<u.length&&(w+=1);const H=M.join(`
53
- `);c.push(s.jsx("pre",{className:"pc-md_pre",children:s.jsx("code",{className:D?`language-${D}`:void 0,children:H})},`pre:${w}`));continue}const $=x.match(sy);if($){const L=$[1].length,D=$[2]||"",M=rl(D,p);L===1?c.push(s.jsx("h1",{children:M},`h1:${w}`)):L===2?c.push(s.jsx("h2",{children:M},`h2:${w}`)):L===3?c.push(s.jsx("h3",{children:M},`h3:${w}`)):L===4?c.push(s.jsx("h4",{children:M},`h4:${w}`)):c.push(s.jsx("h5",{children:M},`h5:${w}`)),w+=1;continue}if(iy(x)){const L=[];for(;w<u.length&&String(u[w]??"").trimStart().startsWith(">");){const M=String(u[w]??"").trimStart();L.push(M.replace(/^>\s?/,"")),w+=1}c.push(s.jsx("blockquote",{className:"pc-md_quote",children:L.map((D,M)=>s.jsxs(ve.Fragment,{children:[rl(D,p),M<L.length-1?s.jsx("br",{}):null]},`q:${w}:${M}`))},`quote:${w}`));continue}if(x.includes("|")&&w+1<u.length&&ny(String(u[w+1]??""))){const L=ty(x),D=Math.max(1,L.length),M=[];for(w+=2;w<u.length;){const H=String(u[w]??"");if(!H.trim()||!H.includes("|"))break;const Z=ty(H),Y=[];for(let X=0;X<D;X++)Y.push(Z[X]??"");M.push(Y),w+=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,D).map((H,Z)=>s.jsx("th",{children:rl(H,p)},`th:${w}:${Z}`))})}),s.jsx("tbody",{children:M.map((H,Z)=>s.jsx("tr",{children:H.map((Y,X)=>s.jsx("td",{children:rl(Y,p)},`td:${w}:${Z}:${X}`))},`tr:${w}:${Z}`))})]})},`table:${w}`));continue}if(am(x)){const L=[];for(;w<u.length;){const D=String(u[w]??"");if(!D.trim()||D.trimStart().startsWith("```"))break;if(am(D)||/^\s{2,}\S/.test(D)){L.push(D),w+=1;continue}break}c.push(s.jsx(ve.Fragment,{children:cj(L,p,`list:${w}`)},`list:${w}`));continue}const E=[];for(;w<u.length&&String(u[w]??"").trim()&&!(E.length>0&&am(String(u[w]??"")));){const L=String(u[w]??"");if(E.length>0&&(sy.test(L)||ry(L)||iy(L))||E.length>0&&L.includes("|")&&w+1<u.length&&ny(String(u[w+1]??"")))break;E.push(L),w+=1}c.push(s.jsx("p",{className:"pc-md_p",children:E.map((L,D)=>s.jsxs(ve.Fragment,{children:[rl(L,p),D<E.length-1?s.jsx("br",{}):null]},`pl:${w}:${D}`))},`p:${w}`))}const y=["pc-md",t].filter(Boolean).join(" ");return s.jsx("div",{className:y,children:c})}function Nv(e){const t=String(e.text??""),n=m.useMemo(()=>Fm(t),[t]),i=["pc-chat-content",e.className].filter(Boolean).join(" ");return n!==null?s.jsx("div",{className:i,children:s.jsx(dr,{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 Cv=[{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"]}];Cv.map(e=>({id:e.id,label:e.label}));function dj(e){return`theme-${String(e||"").trim()||"dark"}`}function oy(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 gp=[{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}],yp=[{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 gp.find(n=>n.id===t)||gp[1]}function hj(e){const t=String(e).trim();return yp.find(n=>n.id===t)||yp[1]}function ay(e){try{const t=document.documentElement,n=fj(e.font_scale||"md"),i=hj(e.header_density||"standard");t.style.setProperty("--font-scale",String(n.scale)),t.style.setProperty("--header-density",String(i.density))}catch{}}var $v=iv();function pu(...e){return e.filter(Boolean).join(" ")}function Iu({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:w,triggerClassName:y,ariaLabel:x,id:S,includeValueOption:b=!1,onOpen:$,customOptionLabel:E,validateCustomValue:L,onChange:D,renderOption:M,renderValue:H}){const Z=m.useRef(null),Y=m.useRef(null),X=m.useRef(null),re=m.useRef($),ie=m.useId(),ue=S||`af-select-${ie.replace(/[^a-zA-Z0-9_-]/g,"")}`,F=`${ue}-listbox`,[C,N]=m.useState(!1),[O,P]=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=$},[$]);const K=m.useMemo(()=>{if(!b)return t;const ge=String(e??"").trim();return!ge||t.some(De=>De.value===ge)?t:[...t,{value:ge,label:ge}]},[b,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=O.trim().toLowerCase();return ge?K.filter(De=>De.label.toLowerCase().includes(ge)||De.value.toLowerCase().includes(ge)):K},[K,O]),me=m.useMemo(()=>{if(!c)return null;const ge=O.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:E?E(ge):`Use "${ge}"`,disabled:!!Ke,reason:Ke}},[c,E,K,O,L]),we=m.useMemo(()=>{const ge=me?[me,...fe]:fe;if(ge.length>0)return ge;const De=String(e??"").trim();return o&&De?[{value:De,label:oe||De}]:ge},[me,fe,o,oe,e]),Ae=m.useCallback(()=>{const ge=Z.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)),Qt=window.innerHeight-De.bottom,_n=De.top,Ut=Qt>=220||Qt>=_n?"bottom":"top";G(Ut);const It=Ut==="bottom"?De.bottom+6:De.top-6;Q({left:Dt,top:It,width:Ke})},[_]),Be=m.useCallback(()=>{N(!1),P("")},[]);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,Qt;const Ke=De.target;Ke&&((Dt=Z.current)!=null&&Dt.contains(Ke)||(Qt=Y.current)!=null&&Qt.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=X.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||(D(ge),Be(),(Ke=Z.current)==null||Ke.focus())},_t=ge=>{var De,Ke;if(ge.key==="Escape")return ge.preventDefault(),Be(),(De=Z.current)==null||De.focus(),!0;if(ge.key==="Tab")return Be(),(Ke=Z.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=me!=null&&me.disabled?me.reason||"Unavailable":"",Se=C&&we.length>0?`${ue}-opt-${ne}`:void 0,Le=s.jsx("span",{className:pu("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:pu("af-select",p==="pin"?"af-select--pin":"af-select--panel",w),children:[s.jsxs("button",{ref:Z,id:ue,type:"button",className:pu("af-select-trigger",f&&et&&"af-select-trigger--clearable",y),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:pu("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(),D(""),Be(),(De=Z.current)==null||De.focus()},title:"Clear",children:"×"}):null,C?$v.createPortal(s.jsxs("div",{ref:Y,className:pu("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:X,className:"af-select-search-input",value:O,onChange:ge=>P(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,Qt=String(ge.group||"").trim(),_n=De>0?String(((It=we[De-1])==null?void 0:It.group)||"").trim():"",Ut=!!Qt&&Qt!==_n;return s.jsxs(ve.Fragment,{children:[Ut?s.jsx("div",{className:"af-select-group",role:"presentation",children:Qt}):null,s.jsx("div",{id:`${ue}-opt-${De}`,role:"option","aria-selected":Ke,className:pu("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:un=>{un.preventDefault(),un.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 mj(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 _j(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 pj(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(),w=mj(e.providers),y=_j(e.models),x=t||!!e.loadingProviders,S=t||!!e.loadingModels,b=[...i?[{value:"",label:o}]:[],...w.map(E=>({value:E.name,label:E.display_name?`${E.display_name} (${E.name})`:E.name}))],$=[...i?[{value:"",label:o}]:[],...y.map(E=>({value:E,label:E}))];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(Iu,{value:_,options:b,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:E=>e.onChange({provider:String(E||"").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(Iu,{value:p,options:$,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:E=>e.onChange({provider:_,model:String(E||"").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 ly(...e){return e.filter(Boolean).join(" ")}function gj({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:w="admin",onUserIdChange:y,token:x,tokenPlaceholder:S="Paste Gateway user token",showToken:b=!1,onTokenChange:$,onShowTokenChange:E,remember:L=!1,rememberLabel:D="Remember this browser",onRememberChange:M,loading:H=!1,submitting:Z=!1,submitDisabled:Y=!1,submitLabel:X="Sign in",submittingLabel:re="Signing in...",closeLabel:ie="Close",signOutLabel:ue="Sign out",showClose:F=!1,showSignOut:C=!1,error:N,message:O,className:P,onSubmit:ne,onClose:B,onSignOut:z}){const G=H||Z,T=G||Y||!String(p||"").trim()||!String(x||"").trim(),Q=K=>{K.preventDefault(),!T&&ne()};return s.jsxs("form",{className:ly("af-gateway-signin",P),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:ly("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=>y(K.target.value),placeholder:w,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:b?"text":"password",value:x,onChange:K=>$(K.target.value),placeholder:S,autoComplete:"current-password",disabled:G}),s.jsx("button",{className:"af-gateway-signin__secondary",type:"button",onClick:()=>E==null?void 0:E(!b),disabled:G,children:b?"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}),D]})]}),N?s.jsx("div",{className:"af-gateway-signin__message af-gateway-signin__message--error",children:N}):null,!N&&O?s.jsx("div",{className:"af-gateway-signin__message af-gateway-signin__message--ok",children:O}):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:Z?re:X})]})]})}function yj(e){return e==="light"?"Light":"Dark"}function wj(e){const t=e.themes&&e.themes.length?e.themes:Cv,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:yj(u.group)})),[t]);return s.jsx(Iu,{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…",w=(_==null?void 0:_.swatches)||null,y=!f;return s.jsxs("span",{className:"af-theme-value",children:[s.jsx("span",{className:`af-theme-label ${y?"af-theme-label--placeholder":""}`.trim(),children:p}),n&&w?s.jsx("span",{className:"af-theme-swatches","aria-hidden":"true",children:w.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((w,y)=>s.jsx("span",{className:"af-theme-swatch",style:{background:w}},`${f}:${y}`))}):null,c.selected?s.jsx("span",{className:"af-select-check",children:"✓"}):null]})]})}})}function vj(e){const t=e.scales&&e.scales.length?e.scales:gp,n=e.variant||"panel",i=m.useMemo(()=>t.map(o=>({value:o.id,label:o.label})),[t]);return s.jsx(Iu,{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 xj(e){const t=e.densities&&e.densities.length?e.densities:yp,n=e.variant||"panel",i=m.useMemo(()=>t.map(o=>({value:o.id,label:o.label})),[t]);return s.jsx(Iu,{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 bj=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=bj.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 wp="api/gateway",jf="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?`${wp}/${t}`:wp}function Av(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 Sj(e){const t=String(e||""),n=`/${wp}/`;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 vp(e=jf){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 kj(e,t=jf){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 Ev(e=jf){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 S_(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 Tv(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 Nj(e){const t=e.connectionPath||jf,[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,w]=m.useState(e.defaultGatewayUrl||"http://127.0.0.1:8080"),[y,x]=m.useState("admin"),[S,b]=m.useState(""),[$,E]=m.useState(!1),[L,D]=m.useState(!0),[M,H]=m.useState(""),[Z,Y]=m.useState(""),X=m.useMemo(()=>Tv(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 O=e.initialStatus;re(O),typeof O.gateway_url=="string"&&O.gateway_url.trim()&&w(S_(O.gateway_url));const P=(N=O.gateway)==null?void 0:N.principal;P!=null&&P.user_id&&x(P.user_id);return}i(!0),H(""),vp(t).then(O=>{var ne;re(O),typeof O.gateway_url=="string"&&O.gateway_url.trim()&&w(S_(O.gateway_url));const P=(ne=O.gateway)==null?void 0:ne.principal;P!=null&&P.user_id&&x(P.user_id)}).catch(O=>H(`Failed to load connection status: ${String((O==null?void 0:O.message)||O)}`)).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=S_(p);w(C);const N=await kj({gateway_url:C,gateway_user_id:y,gateway_token:S,persist:L},t);re(N),b(""),_(!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 Ev(t),b("");const C=await vp(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(gj,{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:X.label,statusTone:X.tone,tokenSourceLabel:u!=null&&u.has_session?"token: browser session":"token: missing",showGatewayUrl:!0,gatewayUrl:p,onGatewayUrlChange:C=>w(C),userId:y,onUserIdChange:x,token:S,tokenPlaceholder:u!=null&&u.has_session?"(browser session already signed in)":"Paste Gateway user token",showToken:$,onTokenChange:b,onShowTokenChange:E,remember:L,rememberLabel:"Keep this browser signed in",onRememberChange:D,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:Z,onSubmit:ue})})})}function Cj(e){return!!(e&&e.ok===!0&&e.has_session===!0)}function $j(e){const t=e||{},n=t.connectionPath||jf,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"),[w,y]=m.useState(!1),x=m.useRef(!1),S=m.useRef(!1),b=m.useRef("loading"),$=m.useRef("none"),E=m.useRef(!1),L=m.useRef(0),D=m.useCallback(N=>{var P;L.current+=1,f(N),(P=o.current)==null||P.call(o,N);const O=Cj(N);if(O)p("connected"),b.current="connected",x.current=!1,$.current="none",S.current||y(!1);else if(N!==null){const ne=b.current;p("disconnected"),b.current="disconnected",ne!=="disconnected"&&($.current=E.current?"signout":ne==="connected"?"mid":"boot");const B=l.current==="blocking"||$.current!=="mid"||u.current;!x.current&&B&&y(!0)}N!==null&&(S.current=O)},[]),M=m.useCallback(async()=>{const N=L.current;try{const O=await vp(n);if(L.current!==N)return;D(O)}catch{if(L.current!==N)return;D(null)}},[n,D]),[H,Z]=m.useState(!1),[Y,X]=m.useState(null),re=m.useCallback(async()=>{Z(!0),X(null),L.current+=1;let N=null;try{await Ev(n)}catch(O){N=String((O==null?void 0:O.message)||O||"Sign-out request failed")}E.current=!0;try{await M()}finally{E.current=!1}X(N),Z(!1)},[n,M]),ie=m.useRef(!1);m.useEffect(()=>{ie.current||(ie.current=!0,M())},[M]);const ue=m.useCallback(()=>{y(!0)},[]),F=m.useCallback(()=>{const N=b.current;i==="blocking"&&N==="disconnected"||(N==="disconnected"&&(x.current=!0),y(!1))},[i]),C=m.useMemo(()=>({isOpen:w,onClose:F,blocking:i==="blocking"&&_!=="connected",appName:t.appName,connectionPath:n,defaultGatewayUrl:t.defaultGatewayUrl,initialStatus:c,onStatusChange:D}),[w,F,i,_,t.appName,n,t.defaultGatewayUrl,c,D]);return{status:c,phase:_,connected:_==="connected",modalOpen:w,signingOut:H,signOutError:Y,openModal:ue,refresh:M,signOut:re,modalProps:C}}function Aj(){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 Ej(){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 Tj(e){const t=e.commandsPath||bt("commands"),n=Aj(),i=JSON.stringify({command_id:n,run_id:e.runId,type:"inject_guidance",payload:{guidance:e.guidance}}),o=e.csrfToken!==void 0?[e.csrfToken]:Ej();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 Mj(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 w=t.trim();if(!w||l.current||e.disabled)return;l.current=!0;const y=u.current;o({kind:"sending"});try{const S=e.submit?await e.submit(e.runId,w):await Tj({runId:e.runId,guidance:w,commandsPath:e.commandsPath});if(u.current!==y)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:w})}catch(S){u.current===y&&o({kind:"error",detail:String((S==null?void 0:S.message)||S)})}finally{l.current=!1}},p=w=>{w.key==="Enter"&&(w.metaKey||w.ctrlKey)&&(w.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:w=>{n(w.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 Rj(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 Lj={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"},Ij={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"}},Oj={framework:Lj,apps:Ij},pm=Oj;function Pj(){return Object.keys(pm.apps).sort()}function Dj(e,t){const n=Object.prototype.hasOwnProperty.call(pm.apps,e)?pm.apps[e]:void 0;if(!n)throw new Error(`appIdentity: unknown application id "${e}" (known: ${Pj().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 Fj(e,t){const n=pm.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 k_(e){return typeof e=="string"?e.trim():""}function cy(e,t){if(t!=null)return[["Gateway",`unavailable (${String(t).trim()||"unknown error"})`]];const n=e&&typeof e=="object"&&!Array.isArray(e)?e:{},i=k_(n.abstractgateway);if(!i)return[["Gateway","unavailable (the gateway did not report its version)"]];const o=k_(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 _=k_(u[f]);_&&l.push([`Gateway package ${f}`,_])}return l}const zj='a[href], button:not(:disabled), input:not(:disabled), select:not(:disabled), textarea:not(:disabled), [tabindex]:not([tabindex="-1"])';function Bj(e,t,n){if(e.key!=="Tab"||!t)return;const i=Array.from(t.querySelectorAll(zj));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 Uj=/https?:\/\/[^\s<>"]+/g;function Wj(e,t){if(e==="Contact")return[{text:t,href:`mailto:${t}`}];const n=[];let i=0;for(const o of t.matchAll(Uj)){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 qj({label:e,value:t}){return s.jsx("span",{children:Wj(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 Hj(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}Bj(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=Fj(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(qj,{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 Vj(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(Hj,{open:o,onClose:()=>l(!1),identity:u.identity,extraRows:u.extraRows}):null]})}const lm={theme:"dark",font_scale:"md",header_density:"standard"};function Gj(e){const t=e&&typeof e=="object"?e:{};return{theme:typeof t.theme=="string"&&t.theme?t.theme:lm.theme,font_scale:typeof t.font_scale=="string"&&t.font_scale?t.font_scale:lm.font_scale,header_density:typeof t.header_density=="string"&&t.header_density?t.header_density:lm.header_density}}function Kj(e){return`af_appearance_${e}_v1`}function Yj(e,t){const n=Kj(e),i=m.useMemo(()=>({...lm,...(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=Gj({...i,...JSON.parse(c)}))}catch{}try{oy(u.theme),ay({font_scale:u.font_scale,header_density:u.header_density})}catch{}return u});return m.useEffect(()=>{oy(o.theme),ay({font_scale:o.font_scale,header_density:o.header_density});try{localStorage.setItem(n,JSON.stringify(o))}catch{}},[n,o]),[o,l]}function Jj(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(wj,{value:e.value.theme,onChange:t=>e.onChange({...e.value,theme:t})}),s.jsx("label",{className:"af-appearance__label",children:"Font size"}),s.jsx(vj,{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(xj,{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 Xj={diary:"var(--accent)",question:"#e7b45a",dream:"#c084dd",interest:"#7bd88a",lesson:"#6ea8d8",world_model:"#5eead4"};function uy(e){const t=String(e||"");return t.length>14?`${t.slice(0,10)}…${t.slice(-4)}`:t}function N_(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&&Xj[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:uy(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:uy(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 C_=bt("automations"),Zj=bt("trigger-sources");class dy 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 Qj(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 $_(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 tS(e){const t=e.newId??eS,n=o=>`${C_}/${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(Av(e.baseUrl,l),f),p=await _.text();let w,y=!1;if(p)try{w=JSON.parse(p),y=!0}catch{y=!1}if(!_.ok)throw new dy(Qj(_.status,w));if(!y||w===null||typeof w!="object")throw new dy({status:_.status,code:"invalid_response",message:`The gateway answered ${o} ${l} with a body that is not a JSON object.`});return w}return{listAutomations:(o={})=>i("GET",`${C_}${$_({status:o.status,cursor:o.cursor,limit:o.limit})}`),getAutomation:o=>i("GET",n(o)),createAutomation:o=>i("POST",C_,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${$_({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${$_({cursor:l.cursor,limit:l.limit})}`),listTriggerSources:()=>i("GET",Zj)}}const nS=/^([1-9][0-9]*)([smhd])$/,sS={s:["second","seconds"],m:["minute","minutes"],h:["hour","hours"],d:["day","days"]};function sg(e){if(typeof e!="string")return null;const t=nS.exec(e);return t?{amount:Number(t[1]),unit:t[2]}:null}function rS(e){const t=sg(e);if(!t)return`every ${e}`;const[n,i]=sS[t.unit];return t.amount===1?`every ${n}`:`every ${t.amount} ${i}`}function ma(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 Mv(e){const t=e;if(typeof t.every!="string")return t.start_at?`once at ${ma(t.start_at)}`:"once, now";const n=[`${rS(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 ${ma(t.until)}`),n.join(" · ")}function rg(e){return e.source_id==="schedule"&&e.source_version===1?Mv(e.config):e.source_id==="manual"&&e.source_version===1?"manual runs only":`${e.source_id}@${e.source_version}`}function Rv(e){return e==="growing"?"Growing — each run sees the previous runs":"Independent — each run starts fresh"}const iS={active:"Active",paused:"Paused",completed:"Completed",failed:"Failed",archived:"Archived"},To={pause:"automation.pause",resume:"automation.resume",run_now:"automation.run_now",stop_current:"automation.stop_current",archive:"automation.archive"},oS=new Set(["running","waiting","backoff"]);function aS(e,t=[]){return e.current_occurrence!=null}function Lv(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 Iv(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 gm(e,t=[],n=!1){const i=new Set(e.capabilities),o=e.status,l=aS(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 lS(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 cS(e){return[...e].sort((t,n)=>t.index-n.index).map(t=>{const n=lS(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:!oS.has(t.status)}})}function uS(e){const t=e.attention.items;return t.length?t[t.length-1].cursor:null}function Ov(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 dS={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 ym(e){return{title:dS[e.code]??`The gateway refused the request (${e.code}).`,detail:e.message}}function ig(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.status=="number"&&typeof t.code=="string"&&typeof t.message=="string"}function Pv(e,t){const n=e.trigger.source_id==="schedule"?e.trigger.config.every:void 0,i=t?t.target.input_data.prompt:void 0;return{title:e.title,every:typeof n=="string"?n:null,context:e.context_mode,prompt:typeof i=="string"?i:null,toolApproval:t?t.policy.tool_approval:null}}function fS(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=Pv(e,n);if(t.every!==u.every&&t.every!==null&&(sg(t.every)?o.trigger={source_id:e.trigger.source_id,source_version:e.trigger.source_version,config:{...e.trigger.config,every:t.every}}:i.push("Interval must be a whole number of minutes, hours or days.")),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.")}return n&&t.toolApproval&&t.toolApproval!==u.toolApproval&&(o.policy={tool_approval:t.toolApproval}),i.length?{errors:i}:Object.keys(o).length?o:null}const hS=[{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 A_(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 mS(e){const t=e.trim().split(`
54
- `)[0].trim();return t.length>120?`${t.slice(0,119)}…`:t}function _S(e){const t=[],n={};if(e.when.kind==="once"){const o=A_(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=A_(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=A_(e.until);o?n.until=o:t.push("Stop at must be a date and time (UTC).")}return{config:n,errors:t}}function Dv(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()||mS(i);o.length>120&&n.push("Title is at most 120 characters.");const{config:l,errors:u}=_S(e);if(n.push(...u),n.length||!t.target)return{ok:!1,errors:n};const c={...t.target,input_data:{...t.target.input_data??{},prompt:i}};return{ok:!0,body:{request_id:t.requestId,title:o,target:c,trigger:{source_id:"schedule",source_version:1,config:l},context:{mode:e.context},policy:{tool_approval:e.toolApproval??"auto"}}}}const pS="Tools run without asking (you approve them now by creating this automation)";function gS(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 yS(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 Fv={ask_user:"Question for you",tool_approval:"Approval needed",event:"Waiting for an event"};class wS{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||vS(n.error))&&this.open.delete(t)}}function vS(e){return ig(e)&&e.status>0&&e.code!=="invalid_response"}function xS(){const e=globalThis.crypto;if(!e||typeof e.randomUUID!="function")throw new Error("crypto.randomUUID is unavailable; pass newId");return e.randomUUID()}class bS{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 fy(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}const jS={pause:"Pause",resume:"Resume",run_now:"Run now",stop_current:"Stop current",revise:"Edit",archive:"Archive",discuss:"Discuss"},SS={pause:`Stop scheduled runs until you resume.
55
- A run in progress, with its retries, finishes. Run now still works.`,resume:`Restart the schedule at its next time after now.
56
- Times missed while paused are skipped; resuming does not run it now.`,run_now:`Run it once now, without waiting for the schedule.
57
- The schedule does not move: the next scheduled run keeps its time, or starts right after this run if its time comes first.
58
- Does not count toward a run limit. Works while paused; it stays paused.
59
- Not available while a run is in progress.`,stop_current:`Cancel the run in progress, or its pending retry.
60
- It ends as cancelled, with no failure notice. The schedule continues.`,revise:`Change the task, schedule or settings.
61
- 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.
62
- 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.
63
- It has its own workspace (the automation's files are read-only) and never changes the automation.`},kS="Next scheduled run: {time}.",NS="Growing context: later runs see this run in their history.",CS={run_now:{name:"playCircle"}},$S={labels:jS,hints:SS,run_now_next_run_line:kS,run_now_growing_line:NS,icons:CS},AS={active:"play",paused:"pause",completed:"check",failed:"error",archived:"archive"};function zv(e){const t=String(e.status),n=AS[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:iS[t]??t}),n?s.jsx(Qe,{name:n,size:e.iconSize??11,className:"af-auto__status-icon"}):null]})}const xp="Discuss — fork at this occurrence (own workspace, automation files read-only)",zm=e=>s.jsx("div",{className:"af-auto-text","data-unformatted":"true",children:e});function ES(e){return ig(e)?e:{status:0,code:"client_error",message:e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}}function hy(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 TS(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 MS(e){const t=e.summary,n=Lv(t),i=TS(t,e.triggerSources),o=t.next_fire_at?`${ma(t.next_fire_at)} (${Iv(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(zv,{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:[rg(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:Rv(t.context_mode)}),n?s.jsxs(s.Fragment,{children:[s.jsx("dt",{children:"Now"}),s.jsx("dd",{"data-fact":"current",className:"is-notable",children:n})]}):null,s.jsx("dt",{children:"Next run"}),s.jsx("dd",{"data-fact":"next",children:o}),s.jsx("dt",{children:"Runs"}),s.jsx("dd",{"data-fact":"count",children:t.occurrence_count}),t.workspace_root?s.jsxs(s.Fragment,{children:[s.jsx("dt",{children:"Workspace"}),s.jsx("dd",{"data-fact":"workspace",className:"af-auto__workspace",children:e.onOpenWorkspace?s.jsxs("button",{type:"button",className:"af-auto__path","data-action":"open-workspace",title:`Browse the automation's folder
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(hy,{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(hy,{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:Ov(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 RS(e){const t=e.definition,n=e.renderText??zm,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," · ",rg(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:Rv(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:"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 Sf=$S,il=Sf.labels,Zi={pause:"pause",resume:"play",run_now:Sf.icons.run_now.name,stop_current:"stop",revise:"edit",archive:"archive",discuss:"chat"},bp=Sf.hints,LS=Sf.run_now_next_run_line,IS=Sf.run_now_growing_line;function Bv(e,t){const n=[bp[e]];return e==="run_now"&&t&&(t.next_fire_at&&n.push(LS.replace("{time}",ma(t.next_fire_at))),t.context_mode==="growing"&&n.push(IS)),n.join(`
65
- `)}function OS(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=>il[p]).join(", ")}: ${u}`});for(const p of c)l[p]=_}),{lines:o,describedBy:l}}function ur(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 PS(e){const t=gm(e.summary,e.occurrences,e.busy),n=[e.summary.status==="paused"?"resume":"pause","run_now","stop_current","revise","archive"],i=OS(t,n,e.idBase??`af-auto-${e.summary.automation_id}`),o=(l,u,c)=>{const f=Bv(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(ur,{icon:Zi[l],label:(c==null?void 0:c.label)??il[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(To.resume)):o("pause",()=>e.onCommand(To.pause)),o("run_now",()=>e.onCommand(To.run_now)),o("stop_current",()=>e.onCommand(To.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(To.archive),children:s.jsx(ur,{icon:"archive",label:"Archive"})}),s.jsx("button",{type:"button",className:"af-auto__btn","data-action":"archive-cancel",onClick:e.onCancelArchive,children:s.jsx(ur,{icon:"x",label:"Keep it"})})]})]}):null]})}const my=[["m","minutes"],["h","hours"],["d","days"]];function DS(e,t){const n=w=>{const y=e.elements.namedItem(w);return y&&typeof y.value=="string"?y.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;return{title:n("title")??t.title,every:l,context:c,prompt:f??t.prompt??null,toolApproval:p}}function FS(e){const t=Pv(e.summary,e.definition),n=t.every?sg(t.every):null,i=n&&n.unit==="s"?[["s","seconds"],...my]:my,o=`af-auto-revise-${e.summary.automation_id}`;return s.jsxs("form",{className:"af-auto__revise","aria-labelledby":`${o}-heading`,onSubmit:l=>{l.preventDefault(),e.onSubmit(DS(l.currentTarget,t))},onKeyDown:l=>{l.key==="Escape"&&(l.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:"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(([l,u])=>s.jsx("option",{value:l,children:u},l))})]})]}):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,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(l=>s.jsx("li",{children:l},l))}):null,s.jsxs("div",{className:"af-auto__row",children:[s.jsx("button",{type:"submit",className:"af-auto__btn af-auto__btn--primary","data-action":"edit-save",disabled:e.busy,children:s.jsx(ur,{icon:"check",label:"Save changes"})}),s.jsx("button",{type:"button",className:"af-auto__btn","data-action":"edit-cancel",onClick:e.onCancel,children:s.jsx(ur,{icon:"x",label:"Cancel"})})]})]})}function jp(e,t){const n=e.elements.namedItem(t);return n&&typeof n.value=="string"?n.value.trim():""}function zS(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??zm,l=u=>s.jsxs("div",{className:"af-auto-wait__prompt",id:n,children:[s.jsx("span",{className:"af-auto-wait__kind",children:Fv[t.kind]??"Waiting"}),t.prompt?o(t.prompt):s.jsxs("span",{children:[" ",u]})]});if(t.kind==="tool_approval"){const u=gS(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(ur,{icon:"check",label:"Approve"})}),s.jsx("button",{type:"button",className:"af-auto__btn af-auto__btn--danger","data-action":"wait-deny",disabled:e.busy,onClick:()=>i({approved:!1}),children:s.jsx(ur,{icon:"x",label:"Deny"})})]})]})}return t.kind==="event"?s.jsxs("form",{className:"af-auto-wait af-auto-wait--event","data-wait-key":t.wait_key,"data-wait-kind":t.kind,"aria-labelledby":n,onSubmit:u=>{var f;u.preventDefault();const c=yS(jp(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(ur,{icon:"send",label:"Send event"})})})]}):t.kind==="ask_user"?s.jsxs("form",{className:"af-auto-wait af-auto-wait--ask_user","data-wait-key":t.wait_key,"data-wait-kind":t.kind,"aria-labelledby":n,onSubmit:u=>{u.preventDefault();const c=jp(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(ur,{icon:"send",label:"Answer"})})]})]}):s.jsxs("div",{className:"af-auto-wait",role:"group","data-wait-key":t.wait_key,"data-wait-kind":String(t.kind),"aria-labelledby":n,children:[l("The run is waiting."),s.jsxs("p",{className:"af-auto__hint",children:["This kind of wait (",String(t.kind),") cannot be answered here; open the run."]})]})}function BS(e){const{row:t,tone:n,badge:i,statusText:o}=e.view,l=`af-auto-occ-${t.run_id}`,u=e.renderText??zm,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.",_=(y,x)=>e.renderTurn?e.renderTurn({kind:y,role:y==="trigger"?"user":"assistant",text:x,index:t.index,runId:t.run_id}):u(x),p=e.renderTurn?" af-auto-turn--card":"",w=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 ",ma(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:[" · ",ma(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:w}),t.artifacts.length?s.jsx("ul",{className:"af-auto-artifacts","aria-label":"Artifacts",children:t.artifacts.map(y=>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:y.url,name:y.name,mimeType:y.mime_type,runId:t.run_id})},children:[s.jsx(Qe,{name:"file",size:13,className:"af-auto__btn-icon"})," ",y.name]}):s.jsx("span",{className:"af-auto-artifact__name",children:y.name})," ",s.jsx("span",{className:"af-auto-turn__muted",children:y.mime_type})]},y.artifact_id))}):null,t.waits.map(y=>s.jsx(zS,{wait:y,busy:e.busy,idBase:l,onAnswerWait:e.onAnswerWait,onWaitError:e.onWaitError,renderText:e.renderText},`${y.run_id}:${y.wait_key}`))]}),s.jsxs("div",{className:"af-auto-occ__foot",children:[s.jsxs("details",{className:"af-auto-occ__details",children:[s.jsx("summary",{children:"Run details"}),s.jsxs("dl",{className:"af-auto__facts",children:[s.jsx("dt",{children:"Run"}),s.jsx("dd",{children:s.jsx("code",{children:t.run_id})}),s.jsx("dt",{children:"Attempts"}),s.jsx("dd",{children:t.attempts})]}),s.jsxs("div",{className:"af-auto__row",children:[s.jsx("button",{type:"button",className:"af-auto__btn","data-action":"open-run",onClick:()=>e.onOpenRun(t.run_id),children:s.jsx(ur,{icon:"list",label:"Open run ledger"})}),e.onOpenResource?s.jsx("button",{type:"button",className:"af-auto__btn","data-action":"open-ledger-json",onClick:()=>{var y;return(y=e.onOpenResource)==null?void 0:y.call(e,{kind:"ledger",url:t.ledger_url,name:`run-${t.run_id}-ledger.json`,runId:t.run_id})},children:s.jsx(ur,{icon:"file",label:"Ledger (JSON)"})}):null,t.workspace_url&&e.onOpenWorkspace?s.jsx("button",{type:"button",className:"af-auto__btn","data-action":"open-workspace",title:"Browse this run's folder",onClick:()=>{var y;return(y=e.onOpenWorkspace)==null?void 0:y.call(e,t.run_id)},children:s.jsx(ur,{icon:"folder",label:"Workspace"})}):null]})]}),e.discussOpen?s.jsxs("form",{className:"af-auto-discuss","aria-label":`${xp}, from occurrence ${t.index}`,onSubmit:y=>{y.preventDefault();const x=jp(y.currentTarget,"prompt");x&&e.onDiscussSubmit(t.index,x)},children:[s.jsxs("p",{className:"af-auto__hint",children:["Starts a new session that forks this automation at #",t.index," with its full history (runs 1–",t.index,"). It works in its own writable workspace; the automation's files are mounted read-only for the file tools (shell commands are not sandboxed), and nothing is written back into the automation's session."]}),s.jsx("textarea",{name:"prompt",rows:3,"aria-label":"Your message",placeholder:"Ask about this result…",required:!0}),s.jsxs("div",{className:"af-auto__row",children:[s.jsx("button",{type:"submit",className:"af-auto__btn af-auto__btn--primary","data-action":"discuss-submit",disabled:e.busy,children:s.jsx(ur,{icon:"send",label:"Start discussion"})}),s.jsx("button",{type:"button",className:"af-auto__btn","data-action":"discuss-cancel",onClick:e.onDiscussCancel,children:s.jsx(ur,{icon:"x",label:"Cancel"})})]})]}):s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"af-auto__btn af-auto__btn--quiet","data-action":"discuss",disabled:!c,title:bp.discuss,"aria-description":bp.discuss,"aria-describedby":f?`${l}-discuss-why`:void 0,onClick:()=>e.onDiscussOpen(t.index),children:s.jsx(ur,{icon:Zi.discuss,label:xp})}),f?s.jsx("span",{className:"af-auto__reasons",id:`${l}-discuss-why`,children:f}):null]})]})]})}const US=5e3,WS={[To.pause]:"Pause sent.",[To.resume]:"Resume sent.",[To.run_now]:"Run requested.",[To.stop_current]:"Stop sent."};function qS(e){const{summary:t,busy:n}=e,i=e.renderText??zm,o=m.useId(),l=m.useRef(null),[u,c]=m.useState(!1),f=e.editOpen!==void 0,p=gm(t,e.occurrences,!1).revise.enabled&&(f?e.editOpen===!0:u),w=m.useRef(null);p?(!w.current||w.current.summary.automation_id!==t.automation_id)&&(w.current={summary:t,definition:e.definition}):w.current=null;const y=w.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)},[b,$]=m.useState([]),[E,L]=m.useState(!1),[D,M]=m.useState(null),[H,Z]=m.useState(null),[Y,X]=m.useState(null);m.useEffect(()=>{if(!Y)return;const J=setTimeout(()=>X(null),US);return()=>clearTimeout(J)},[Y]),m.useEffect(()=>{var oe;if(!p)return;$([]);const J=fy(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=fy(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 wS(e.newId??xS));const F=ue.current,C=J=>Z(ES(J)),N=(J,oe,fe)=>{Z(null),X(null),oe(F.idFor(J)).then(me=>{F.settle(J,{ok:!0}),fe(me)},me=>{F.settle(J,{ok:!1,error:me}),C(me)})},O=uS(t),P=m.useRef(e.onSeen);P.current=e.onSeen;const ne=m.useRef(null);ne.current||(ne.current=new bS),m.useEffect(()=>{const J=ne.current,oe=O?`${t.automation_id}|${O}`:null;if(!O||!J.next(oe,t))return;const fe=t;P.current(O).then(()=>J.succeeded(oe),me=>{J.failed(oe,fe),C(me)})});const B=gm(t,e.occurrences,n),z=cS(e.occurrences),G=t.occurrence_count-e.occurrences.length,T=H??e.error??null,Q=T?ym(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(MS,{summary:t,triggerSources:e.triggerSources,titleId:o,nowMs:e.nowMs,onOpenWorkspace:e.onOpenWorkspace}),s.jsx(PS,{summary:t,occurrences:e.occurrences,busy:n,confirmingArchive:E,reviseOpen:p,notice:Y,onDismissNotice:()=>X(null),idBase:`${o}-ctl`,onCommand:J=>N(`command:${J}`,oe=>e.onCommand(J,void 0,{command_id:oe}),()=>{J===To.archive?(L(!1),X("Archive requested."),ie(['[data-action="archive"]'])):X(WS[J]??"Command sent.")}),onToggleRevise:()=>{$([]),S(!p)},onAskArchive:()=>L(!0),onCancelArchive:()=>{L(!1),ie(['[data-action="archive"]'])}}),p&&y?s.jsx(FS,{summary:y.summary,definition:y.definition,busy:n,errors:b,onCancel:()=>{S(!1),ie(['[data-action="edit"]'])},onSubmit:J=>{const oe=y.summary,fe=fS(oe,J,y.definition);if(fe===null){$(["Nothing changed."]);return}if("errors"in fe){$(fe.errors);return}$([]),N(`revise:${oe.revision}:${JSON.stringify(fe)}`,me=>e.onRevise(fe,oe.revision,{command_id:me}),()=>{X("Saved; applies from the next run."),S(!1),ie(['[data-action="edit"]'])})}}):e.definition?s.jsx(RS,{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:()=>Z(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," · ",ma(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:Fv[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(ur,{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(BS,{view:J,busy:n,discuss:B.discuss,renderText:i,renderTurn:e.renderTurn,onOpenWorkspace:e.onOpenWorkspace,onOpenResource:e.onOpenResource?fe=>{var me;Z(null);try{Promise.resolve((me=e.onOpenResource)==null?void 0:me.call(e,fe)).catch(C)}catch(we){C(we)}}:void 0,discussOpen:D===J.row.index,onOpenRun:e.onOpenRun,onAnswerWait:(fe,me,we)=>{Z(null),e.onAnswerWait(fe,me,we).then(()=>X("Answer sent."),C)},onWaitError:fe=>Z({status:0,code:"invalid_payload",message:fe}),onDiscussOpen:M,onDiscussCancel:()=>{M(null),ie([`${oe} [data-action="discuss"]`])},onDiscussSubmit:(fe,me)=>N(`discuss:${fe}:${me}`,we=>e.onDiscuss(fe,me,{request_id:we}),we=>{M(null),X(`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 Uv(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}}function HS(e){const t=Uv(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 Wv({tool:e,showCopy:t=!0}){const[n,i]=m.useState(!1),o=Uv(e.arguments),l=HS(e.arguments),u=["file path","path"].includes(l.label)&&l.value.length>60?`${l.value.split(/[\\/]/).pop()} · ${l.value.slice(0,24)}…`:l.value,c=e.error&&/^File ['"].+['"] does not exist\.?$/.test(e.error)?"File not found. Expand for the exact path.":e.error&&e.error.length>180?`${e.error.slice(0,100)}…${e.error.slice(-70)}`:e.error,f={running:"Running",waiting:"Approval needed",completed:"Done",failed:"Failed"},_=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 dc(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(([w,y])=>s.jsxs(ve.Fragment,{children:[s.jsx("dt",{children:w}),s.jsx("dd",{children:y&&typeof y=="object"?s.jsx(dr,{value:y}):s.jsx("code",{children:typeof y=="string"?y:JSON.stringify(y)})})]},w))}):e.arguments===void 0?s.jsx("p",{children:"Arguments are unavailable in this ledger."}):s.jsx(dr,{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(dr,{value:e.output})})]}):null]})]})}function qv({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(Wv,{tool:i,showCopy:t},i.id))]})}const Ks="not reported",kr=e=>e===void 0?Ks:Math.round(e).toLocaleString(),Vr=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`},Hv=e=>e===void 0?Ks:`${Math.round(e).toLocaleString()} tok/s`,VS=(e,t)=>t>0?`${Math.round(e/t*100)}%`:"",ac=(e,t,n=`${t}s`)=>`${e.toLocaleString()} ${e===1?t:n}`,GS=e=>{const t=e.split("#")[0].replace(/\/+$/,"");return t.slice(t.lastIndexOf("/")+1)||e};function KS(e){const t=new Map;for(const n of e)n&&t.set(n,(t.get(n)||0)+1);return[...t].map(([n,i])=>i>1?`${n} ×${i}`:n).join(" · ")}function wm(e){const t=[],n=(e.models||[]).map(GS),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 YS(e){const t=e.modelCalls||[],n=[],i=[{label:"Input",value:kr(e.inputTokens)},{label:"Output",value:kr(e.outputTokens)}];if(e.reasoningTokens!==void 0&&i.push({label:"Reasoning",value:kr(e.reasoningTokens),hint:"part of output"}),i.push({label:"Total",value:kr(e.totalTokens)}),n.push({heading:`Usage · ${ac(e.llmCalls,"model call")}`,rows:i}),e.measuredCacheCalls){const l=e.cachedTokens||0,u=e.fedTokens||0,c=[{label:"Reused from cache",value:`${kr(l)}${l+u?` (${VS(l,l+u)})`:""}`},{label:"Newly processed",value:kr(e.fedTokens)},{label:"Outcome",value:KS(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:`${kr(o[0].inputTokens)} tokens`}]}):o.length>1&&n.push({heading:"Context",rows:[{label:"First → last call",value:`${kr(o[0].inputTokens)} → ${kr(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),kr(l.inputTokens),l.cachedTokens===void 0?"—":kr(l.cachedTokens),l.fedTokens===void 0?"—":kr(l.fedTokens),kr(l.outputTokens),l.cacheOutcome||"—"])}}),{kind:"tokens",title:"Tokens",headline:e.totalTokens===void 0?Ks:`${e.totalTokens.toLocaleString()} total`,sections:n,footer:wm(e)}}function Fh(e,t,n,i){if(e===void 0)return Ks;const o=[Vr(e)];return t!==void 0&&o.push(`${t.toLocaleString()} ${i}${n!==void 0?` at ${Hv(n)}`:""}`),o.join(" · ")}function JS(e){var _,p,w;const t=e.modelCalls||[],n=[],i=e.durationMs,o=[{label:"Wall clock",value:Vr(i)}];if(o.push({label:"Model",value:e.genTimeMs===void 0?Ks:`${Vr(e.genTimeMs)} · ${ac(e.timedCalls||0,"call")}${e.timedCalls!==e.llmCalls?` (of ${e.llmCalls})`:""}`}),o.push({label:"Tools",value:e.toolTimeMs!==void 0?`${Vr(e.toolTimeMs)} · ${ac(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 y=i-e.genTimeMs-(e.toolTimeMs||0);o.push({label:"Orchestration",value:y>=0?Vr(y):"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:Fh(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:Fh(e.prefillMs,e.prefillNewTokens,e.prefillNewTokensPerSecond,"new tok"),hint:"derived: prompt ÷ provider rate"}):e.prefillMs!==void 0?l.push({label:"Prefill",value:`${Vr(e.prefillMs)}${e.promptTokensPerSecond!==void 0?` at ${Hv(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?Fh(e.generationPhaseMs,e.generationPhaseTokens,e.generationPhaseTokensPerSecond,"tok"):Fh(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 y=(f.draftKinds||[]).map(S=>S.toUpperCase()).join(", "),x=[{label:"Mode",value:`${f.used?"on":"off"}${y?` · ${y}`:""}${(_=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)}% · ${kr(f.acceptedTokens)} of ${kr(f.draftedTokens)} drafted`}];((p=f.draftLengths)!=null&&p.length||f.rounds!==void 0)&&x.push({label:"Draft length",value:`${(w=f.draftLengths)!=null&&w.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:`${Vr(e.toolTimeMs)} · ${ac(e.toolBatches||0,"batch","batches")}`},{label:"Slowest",value:`${Vr(e.slowestToolBatch.ms)} · ${Vv(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((y,x)=>[String(x+1),y.promptMs===void 0?"—":`${Vr(y.promptMs)}${y.promptSource==="rate"?"*":""}`,y.promptNewTokensPerSecond===void 0?"—":Math.round(y.promptNewTokensPerSecond).toLocaleString(),y.generationMs===void 0?"—":Vr(y.generationMs),y.generationTokensPerSecond===void 0?"—":Math.round(y.generationTokensPerSecond).toLocaleString(),y.cacheOutcome||"—"])},note:t.some(y=>y.promptSource==="rate")?"* derived from the provider's prompt rate (no TTFT event).":void 0}),{kind:"time",title:"Time",headline:i===void 0?Ks:`${Vr(i)} wall clock`,sections:n,footer:wm(e)}}function Vv(e){return e.tools.length===1?`${e.tools[0]} ×${e.calls}`:`${ac(e.calls,"call")} (${e.tools.join(", ")})`}function XS(e){const t=[],n=(e.toolsWaiting||0)+(e.toolsRunning||0);if(!e.toolCalls&&!n)return t.push({heading:"Outcome",rows:[{label:"Tools called",value:"none"}]}),{kind:"tools",title:"Tools",headline:"none",sections:t,footer:wm(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?`${Vr(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:`${Vr(e.toolTimeMs)} · ${ac(e.toolBatches||0,"batch","batches")}`}];return e.slowestToolBatch&&u.push({label:"Slowest batch",value:`${Vr(e.slowestToolBatch.ms)} · ${Vv(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:`${ac(e.toolCalls,"call")}${e.toolsFailed?` · ${e.toolsFailed} failed`:""}`,sections:t,footer:wm(e)}}function E_(e,t){return e==="tokens"?YS(t):e==="time"?JS(t):XS(t)}function ZS(e){const t=e.detail;return s.jsxs("div",{ref:e.panelRef,id:e.id,role:"tooltip",className:`pc-stat-detail pc-stat-detail--${t.kind}`,style:e.style,onMouseEnter:e.onMouseEnter,onMouseLeave:e.onMouseLeave,children:[s.jsxs("div",{className:"pc-stat-detail-head",children:[s.jsx("span",{className:"pc-stat-detail-title",children:t.title}),s.jsx("span",{className:"pc-stat-detail-headline",children:t.headline})]}),t.sections.map(n=>{var 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 la=8;function QS(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)},[_]),w=m.useCallback(()=>{_(),c.current=window.setTimeout(()=>n(!1),120)},[_]);m.useEffect(()=>_,[_]),m.useLayoutEffect(()=>{if(!t){o(null);return}const b=()=>{const $=l.current,E=u.current;if(!$||!E)return;const L=$.getBoundingClientRect(),D=E.offsetWidth,M=E.offsetHeight,H=window.innerWidth,Z=window.innerHeight,Y=L.top-la-M,X=L.bottom+la,re=Y>=la?Y:X+M<=Z-la?X:Math.max(la,Z-la-M),ie=Math.min(Math.max(la,L.left),Math.max(la,H-la-D));o({top:re,left:ie})};return b(),window.addEventListener("resize",b),window.addEventListener("scroll",b,!0),()=>{window.removeEventListener("resize",b),window.removeEventListener("scroll",b,!0)}},[t]),m.useEffect(()=>{if(!t)return;const b=$=>{$.key==="Escape"&&n(!1)};return document.addEventListener("keydown",b),()=>document.removeEventListener("keydown",b)},[t]);const y=typeof e.onClick=="function",x=y?"button":"span",S=t?s.jsx(ZS,{detail:e.detail,id:f,panelRef:u,onMouseEnter:_,onMouseLeave:w,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,...y?{type:"button"}:{tabIndex:0},className:["pc-chat-stat","pc-chat-stat--detail",y?"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:w,onFocus:p,onBlur:()=>n(!1),onKeyDown:b=>{b.key==="Escape"&&n(!1)},onClick:y?()=>{var b;return(b=e.onClick)==null?void 0:b.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"?$v.createPortal(S,document.body):S]})}function ek(e){const t=e.totalTokens!==void 0?E_("tokens",e):null,n=E_("tools",e),i=e.durationMs!==void 0?E_("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 tk(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 og(e){var E;const t=e.message,n=m.useMemo(()=>tk(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=_&&((E=e.getSpeakState)==null?void 0:E.call(e,t))||"idle",w=p==="loading"?"loader":p==="playing"?"pause":"speaker",y=p==="loading"?"Generating audio…":p==="playing"?"Pause":p==="paused"?"Resume":"Speak (TTS)",x=e.showCopy!==!1,S=Array.isArray(e.attachments)?e.attachments:[],b=t.statistics,$=m.useMemo(()=>Array.isArray(e.stats)?e.stats:b?ek(b):[],[e.stats,b]);return t.toolActivity?s.jsx(Wv,{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":y,title:y,onClick:()=>{var L;return(L=e.onSpeakToggle)==null?void 0:L.call(e,t)},children:s.jsx(Qe,{name:w,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 dc(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(Nv,{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,D)=>{const M=String(L.label||"").trim()||"attachment",H=String(L.target||"").trim(),Z=String(L.title||"").trim(),Y=!!L.disabled||typeof L.onClick!="function";return s.jsxs("button",{type:"button",className:"pc-chat-attachment-chip",title:Z||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}:${D}`)})}):null,$.length?s.jsx("div",{className:"pc-chat-stats","aria-label":"Stats",children:$.slice(0,12).map((L,D)=>{const M=String(L.label||"").trim();if(!M)return null;if(L.detail)return s.jsx(QS,{label:M,detail:L.detail,icon:L.icon,onClick:L.onClick},L.id||`${M}:${D}`);const H=String(L.title||"").trim(),Z=typeof L.onClick=="function",Y=Z?"button":"span";return s.jsxs(Y,{...Z?{type:"button"}:{},className:["pc-chat-stat",Z?"pc-chat-stat--clickable":""].filter(Boolean).join(" "),title:H||void 0,onClick:Z?()=>{var X;return(X=L.onClick)==null?void 0:X.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}:${D}`)})}):null]})}function nk(e,t){const n=Math.max(0,Math.trunc(t));return e.scrollHeight-e.scrollTop-e.clientHeight<=n}function ag(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 w;const p=[];for(const y of c){const x=p[p.length-1];y.toolActivity&&((w=x==null?void 0:x[0])!=null&&w.toolActivity)&&x[0].runId===y.runId?x.push(y):p.push([y])}return p},[c]);m.useEffect(()=>{if(!n)return;const p=i.current;if(!p)return;const w=()=>{u(nk(p,t))};return p.addEventListener("scroll",w,{passive:!0}),w(),()=>p.removeEventListener("scroll",w)},[n,t]);const _=m.useMemo(()=>{let p=0;for(const w of c)p+=String(w.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,w)=>{var S;const y=p[0],x=String(y.id||"")||String(y.ts||"")+":"+String(y.role||"")+":"+w;return y.toolActivity?s.jsx(qv,{tools:p.map(b=>b.toolActivity),showCopy:(S=e.messageProps)==null?void 0:S.showCopy},x):s.jsx(og,{message:y,...e.messageProps||{}},x)}),e.after,s.jsx("div",{ref:o})]})}const lg=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 sk(e){return!!(e&&typeof e[Symbol.asyncIterator]=="function")}function rk(e){const[t,n]=m.useState([]),i=e.messages??t,o=b=>{e.onMessagesChange&&e.onMessagesChange(b),e.messages===void 0&&n(b)},l=m.useRef(i);l.current=i;const[u,c]=m.useState(""),[f,_]=m.useState(!1),p=m.useRef(null),w=e.assistantName||"Assistant",y=!!e.blockedNotice,x=async b=>{const $=String(b||"").trim();if(!$||f||y)return;c("");const E=l.current,L=[...E,{role:"user",content:$,ts:new Date().toISOString()}];o(L),_(!0);const D=new AbortController;p.current=D;try{const M=e.ask($,{signal:D.signal,history:E});if(sk(M)){let H="";const Z=[...L,{role:"assistant",title:w,content:"",ts:new Date().toISOString()}];o(Z);for await(const Y of M){if(D.signal.aborted)break;H+=String(Y??""),o([...L,{role:"assistant",title:w,content:H,ts:new Date().toISOString()}])}!H.trim()&&!D.signal.aborted&&o([...L,{role:"assistant",title:w,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:w,content:H,ts:new Date().toISOString()}:{role:"assistant",title:w,content:"#FALLBACK the assistant returned no answer.",level:"warn",ts:new Date().toISOString()}])}}catch(M){D.signal.aborted||o([...l.current,{role:"assistant",title:w,content:`#FALLBACK assistant request failed: ${String((M==null?void 0:M.message)||M||"unknown error")}`,level:"error",ts:new Date().toISOString()}])}finally{p.current===D&&(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(b=>s.jsx("button",{type:"button",className:"pc-assistant__suggestion",onClick:()=>void x(b),disabled:f||y,children:b},b))}):null]}),[i.length,e.emptyState,e.suggestions,f,y]);return s.jsxs("div",{className:`pc-assistant${e.className?` ${e.className}`:""}`,children:[s.jsxs("div",{className:"pc-assistant__thread",children:[S,s.jsx(ag,{messages:i,autoScroll:!0}),y?s.jsx("div",{className:"pc-assistant__blocked",children:e.blockedNotice}):null]}),s.jsx("div",{className:"pc-assistant__composer",children:s.jsx(lg,{value:u,onChange:c,onSubmit:()=>void x(u),placeholder:e.placeholder||"Ask about this app…",disabled:y,busy:f,rows:2,actions:f?s.jsx("button",{type:"button",className:"pc-btn",onClick:()=>{var b;(b=p.current)==null||b.abort()},children:"Stop"}):null})})]})}const An=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},Sp=e=>Array.isArray(e)?e.map(An):[],Zt=e=>typeof e=="string"?e:"",Ud=e=>Zt(e.runtime_call_id||e.call_uid),Wd=e=>Zt(e.call_id||e.id);function Gv(e,t){const n=t.record,i=An(n.effect);if(i.type!=="tool_calls")return[];const o=An(n.result),l=Sp(An(i.payload).tool_calls),u=Sp(o.results),c=l.length?l:u,f=[];return c.forEach((_,p)=>{let w=Ud(_)?u.filter(H=>Ud(H)===Ud(_)):[];!w.length&&Wd(_)&&l.filter(H=>Wd(H)===Wd(_)).length===1&&(w=u.filter(H=>Wd(H)===Wd(_)));const y=l.length?w.length===1?w[0]:l.length===u.length?u[p]:{}:_,x=Ud(_)||Ud(y)||`${Zt(n.idempotency_key)||Zt(n.step_id)||t.cursor}:${p}`,S=`${t.runId}:${x}`,b=e.get(S),$=Zt(_.name||y.name)||(b==null?void 0:b.name);if(!$)return;const E=n.status==="completed"||n.status==="failed",L=n.status==="failed"||y.success===!1||!!y.error,D=_.arguments??y.arguments??(b==null?void 0:b.arguments),M={...b,id:S,runId:t.runId,name:$,arguments:D,status:E?L?"failed":"completed":n.status==="waiting"?"waiting":"running",...typeof y.success=="boolean"?{success:y.success}:{},...y.output!==void 0||y.result!==void 0?{output:y.output??y.result}:{},...y.error?{error:String(y.error)}:{},startedAt:(b==null?void 0:b.startedAt)||Zt(n.started_at)||void 0,endedAt:E&&Zt(n.ended_at)||(b==null?void 0:b.endedAt)};b&&["completed","failed"].includes(b.status)&&!E||(e.set(S,M),f.push(M))}),f}function Su(e){if(e==null||e===""||typeof e=="boolean")return;const t=Number(e);return Number.isFinite(t)&&t>=0?t:void 0}function Eo(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 Kv(e){if(typeof e=="string")try{return An(JSON.parse(e))}catch{return{}}return An(e)}function gu(e,t){if(t===void 0||t==="")return e;const n=e||[];return n.includes(t)||n.push(t),n}function ik(e){return Eo(e,["reasoning_tokens","thinking_tokens"])??Eo(An(e.completion_tokens_details),["reasoning_tokens"])??Eo(An(e.output_tokens_details),["reasoning_tokens"])}function ok(e){const t=An(typeof e=="string"&&e.trim().startsWith("{")?Kv(e):e);return Zt(t.error_class)}function ak(e){const t=new Map;for(const n of e){const i=n.record;if(An(i.effect).type!=="emit_event")continue;const o=An(i.result);if(Zt(o.name)!=="abstract.progress")continue;const l=An(o.payload);if(Zt(l.kind)!=="llm"||!Zt(l.step_id))continue;const u=`${Zt(l.run_id)||n.runId}:${Zt(l.step_id)}`,c=t.get(u)||{},f=Su(l.ttft_s);f!==void 0&&(c.ttftS=f),c.provider=c.provider||Zt(l.provider)||void 0,c.model=c.model||Zt(l.model)||void 0,t.set(u,c)}return t}function T_(e){var b,$,E,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 w=ak(e),y=[],x=new Set;for(const D of e){const M=D.record,H=`${D.runId}:${M.step_id||D.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(Zt(we));Number.isFinite(Ae)&&(l=Math.min(l,Ae),u=Math.max(u,Ae))}for(const we of Gv(t,D))we.status==="waiting"&&x.add(we.id);if(An(M.effect).type!=="llm_call"||M.status!=="completed")continue;o.llmCalls+=1;const Z=An(M.result),Y=An(Z.output),X=An(Z.usage||Z.token_usage||Z.tokens||Y.usage||Y.token_usage||Y.tokens),re=Eo(X,["input_tokens","prompt_tokens","prompt","input","in"]),ie=Eo(X,["output_tokens","completion_tokens","completion","output","out"]),ue=Eo(X,["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=Su(Z.gen_time??Y.gen_time);F!==void 0&&(o.genTimeMs=(o.genTimeMs||0)+F,o.timedCalls=(o.timedCalls||0)+1);const C=An(Z.metadata||Y.metadata),N=An(C.performance),O=Su(N.prompt_tokens_per_second),P=Su(N.generation_tokens_per_second),ne=An(C.prompt_cache),B=Su(ne.cached_tokens),z=Su(ne.fed_tokens);if(O!==void 0||P!==void 0){if(o.measuredSpeedCalls=(o.measuredSpeedCalls||0)+1,O!==void 0&&O>0&&(o.promptTokensPerSecond=(o.promptTokensPerSecond||0)+O,re!==void 0)){const we=re/O*1e3;o.prefillMs=(o.prefillMs||0)+we,z!==void 0&&(f+=z,_+=we)}P!==void 0&&P>0&&(o.generationTokensPerSecond=(o.generationTokensPerSecond||0)+P,ie!==void 0&&(o.decodeMs=(o.decodeMs||0)+ie/P*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=Zt(ne.outcome);if(we){const Ae=o.cacheOutcomes||[];Ae.includes(we)||Ae.push(we),o.cacheOutcomes=Ae}}const G=Zt(M.step_id)||void 0,T=G&&w.get(`${D.runId}:${G}`)||{},Q=An(Z.route),K={runId:D.runId};G&&(K.stepId=G),Zt(M.started_at)&&(K.startedAt=Zt(M.started_at));const J=Zt(Z.model||Y.model)||Zt(Q.model)||T.model,oe=Zt(Q.provider)||Zt(An(C._provider_request).provider)||T.provider||Zt(Z.provider);J&&(K.model=J),oe&&(K.provider=oe),J&&(o.models=gu(o.models,J)),oe&&(o.providers=gu(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=ik(X);fe!==void 0&&(K.reasoningTokens=fe,o.reasoningTokens=(o.reasoningTokens||0)+fe),B!==void 0&&(K.cachedTokens=B),z!==void 0&&(K.fedTokens=z),Zt(ne.outcome)&&(K.cacheOutcome=Zt(ne.outcome)),Zt(ne.backend)&&(K.cacheBackend=Zt(ne.backend),o.cacheBackends=gu(o.cacheBackends,K.cacheBackend)),F!==void 0&&(K.genTimeMs=F),O!==void 0&&O>0&&(K.promptTokensPerSecond=O),P!==void 0&&P>0&&(K.generationTokensPerSecond=P),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 me=An(C.speculation);if(Object.keys(me).length){const we={};Zt(me.mode)&&(we.mode=Zt(me.mode)),typeof me.used=="boolean"&&(we.used=me.used),Zt(me.draft_kind)&&(we.draftKind=Zt(me.draft_kind));const Ae=Eo(me,["accepted_tokens"]),Be=Eo(me,["drafted_tokens"]),We=Eo(me,["rounds"]),_t=Eo(me,["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=gu(Pe.modes,we.mode)),we.draftKind&&(Pe.draftKinds=gu(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=gu(Pe.draftLengths,_t))}y.push(K)}y.length&&(y.every(D=>D.startedAt)&&y.sort((D,M)=>Date.parse(D.startedAt)-Date.parse(M.startedAt)),o.modelCalls=y),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)),(b=o.speculation)!=null&&b.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 D of t.values()){if(D.status==="waiting"){o.toolsWaiting=(o.toolsWaiting||0)+1;continue}if(D.status==="running"){o.toolsRunning=(o.toolsRunning||0)+1;continue}if(!["completed","failed"].includes(D.status))continue;o.toolCalls+=1;const M=D.status==="failed";M&&(o.toolsFailed=(o.toolsFailed||0)+1);const H=o.toolBreakdown||(o.toolBreakdown={}),Z=H[D.name]||(H[D.name]={calls:0,failed:0});if(Z.calls+=1,M){Z.failed+=1;const ue=ok(D.output);ue&&((Z.errors||(Z.errors={}))[ue]=((($=Z.errors)==null?void 0:$[ue])||0)+1)}const Y=Date.parse(Zt(D.startedAt)),X=Date.parse(Zt(D.endedAt));if(Number.isFinite(Y)&&Number.isFinite(X)&&X>=Y){const ue=`${D.runId}|${D.startedAt}|${D.endedAt}`,F=S.get(ue)||{ms:X-Y,calls:0,names:new Map,waited:!1};F.calls+=1,F.names.set(D.name,(F.names.get(D.name)||0)+1),x.has(D.id)&&(F.waited=!0),S.set(ue,F)}if(D.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(D.name))continue;const re=Kv(D.arguments),ie=Zt(re.destination||re.destination_path||re.file_path||re.path||re.filename);ie&&i.add(ie)}for(const D of S.values()){o.toolBatches=(o.toolBatches||0)+1,o.toolTimeMs=(o.toolTimeMs||0)+D.ms,D.waited&&(o.toolTimeIncludesApproval=!0);const M=[...D.names.keys()].sort();(!o.slowestToolBatch||D.ms>o.slowestToolBatch.ms)&&(o.slowestToolBatch={ms:D.ms,calls:D.calls,tools:M});const H=(E=o.toolBreakdown)==null?void 0:E[M[0]];if(M.length===1&&H)H.ms=(H.ms||0)+D.ms;else for(const Z of M){const Y=(L=o.toolBreakdown)==null?void 0:L[Z];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 lk(e){const t=An(An(e).ledgers);return Object.entries(t).flatMap(([n,i])=>Sp(An(i).items).map((o,l)=>({runId:n,cursor:Number(o.cursor)||l+1,record:Object.keys(An(o.record)).length?An(o.record):o})))}function zh(e){if(!e)return!1;for(let t=0;t<e.length;t+=1)if(e[t]==="Files")return!0;return!1}function _y(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 py(e){return e===1?"Drop file to attach":typeof e=="number"&&e>1?`Drop ${e} files to attach`:"Drop files to attach"}function Yv(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 ck(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 uk={"image/png":"png","image/jpeg":"jpg","image/gif":"gif","image/webp":"webp","image/heic":"heic","image/tiff":"tiff","image/bmp":"bmp"};function qd(e){return String(e).padStart(2,"0")}function dk(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=uk[String(t||"").toLowerCase()]||i.split(".").pop()||"bin",l=`${n.getFullYear()}-${qd(n.getMonth()+1)}-${qd(n.getDate())} at ${qd(n.getHours())}.${qd(n.getMinutes())}.${qd(n.getSeconds())}`;return`${String(t||"").startsWith("image/")||!i?"Pasted image":"Pasted file"} ${l}.${o}`}function fk(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}=Yv(e);return i.map(o=>{const l=dk(o.name,o.type,t);return l===o.name?o:new File([o],l,{type:o.type,lastModified:o.lastModified})})}class hk{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 mk(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 _k(e){return(e instanceof Error?e.message:String(e||"Unknown error")).trim()||"Unknown error"}function pk(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 gk(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,w]=m.useState(""),[y,x]=m.useState(null),S=`${t.kind}:${t.id}`,b=m.useRef(S),$=m.useRef(!1),E=m.useRef(!1),L=m.useRef(!0),D=m.useRef(0);b.current!==S&&(b.current=S,$.current=!1,E.current=!1,D.current+=1);const M=!!e.disabled||u!==null||f||$.current||E.current,H=async(X,re)=>{var F;if(e.disabled||$.current||E.current)return;const ie=S,ue=++D.current;$.current=!0,x(null),w(""),c(X);try{if(await re(),!L.current||b.current!==ie||D.current!==ue)return;E.current=!0,_(!0),w("Response sent. Waiting for the workflow to continue.")}catch(C){if(!L.current||b.current!==ie||D.current!==ue)return;x({submission:X,message:_k(C)}),w("The action failed. You can try again."),(F=e.onError)==null||F.call(e,C)}finally{if(!L.current||b.current!==ie||D.current!==ue)return;$.current=!1,c(null)}};m.useEffect(()=>{i(""),l(t.kind==="event-wait"&&t.initialPayload||""),x(null),c(null),_(!1),w("")},[S]),m.useEffect(()=>(L.current=!0,()=>{L.current=!1,D.current+=1,$.current=!1}),[]);const Z=()=>{y&&H(y.submission,()=>mk(t,y.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(X=>s.jsxs("button",{type:"button",className:"pc-workflow-interaction__choice",disabled:M||X.disabled,onClick:()=>void H({kind:"choice",answer:X.id},()=>t.onSubmit(X.id)),children:[s.jsx("span",{children:X.label}),X.description?s.jsx("small",{children:X.description}):null]},X.id))}):null,t.allowFreeText!==!1?s.jsxs("div",{className:"pc-workflow-interaction__entry",children:[s.jsx("textarea",{"aria-label":"Response",value:n,onChange:X=>i(X.target.value),placeholder:t.freeTextPlaceholder||"Type a response",rows:2,disabled:M,onKeyDown:X=>{X.key!=="Enter"||X.shiftKey||X.nativeEvent.isComposing||X.keyCode===229||(X.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:X=>l(X.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"})})]}),y?s.jsx(pk,{message:y.message,onRetry:Z,disabled:M}):null,s.jsx("div",{className:"pc-workflow-interaction__outcome","aria-live":"polite",children:p})]})}function Bh(e){return(e instanceof Error?e.message:String(e||"Unknown error")).trim()||"Unknown error"}function yk(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),w=m.useRef(!1),y=m.useRef(!1),x=m.useRef(0),S=m.useRef(0),b=m.useRef(0);m.useEffect(()=>(_.current=!0,()=>{_.current=!1,x.current+=1,S.current+=1,b.current+=1,p.current=!1,w.current=!1,y.current=!1}),[]);const $=!!e.blockedNotice,E=!!e.disabled||$,L=!!e.busy||t,D=t||!!e.busy&&!e.sendWhileBusy,M=e.stopState||null,H=(M==null?void 0:M.phase)==="stopping",Z=typeof e.onFiles=="function",Y=m.useRef(null),[X,re]=m.useState(null),[ie,ue]=m.useState(""),F=m.useRef(e.onFiles);F.current=e.onFiles;const C=m.useRef(E);C.current=E;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:ck(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:Bh(fe)})}}}},O=m.useRef(N);O.current=N,m.useEffect(()=>{if(!Z||typeof window>"u")return;const K=new hk;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)},me=()=>{J||(J=window.setInterval(()=>{K.active(Date.now())||fe()},250))},we=Pe=>{var Ye;if(!zh((Ye=Pe.dataTransfer)==null?void 0:Ye.types))return;K.enter(Date.now());const et=oe(Pe.target),lt=_y(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}),me()},Ae=Pe=>{var lt;if(!zh((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)??_y(Pe.dataTransfer),over:et}),me()},Be=Pe=>{var et;zh((et=Pe.dataTransfer)==null?void 0:et.types)&&(K.leave(Date.now())||fe())},We=Pe=>{var Le;if(!zh((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}=Yv(Pe.dataTransfer);O.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)}},[Z]);const P=K=>{if(!Z||E)return;const J=fk(K.clipboardData);J.length&&(K.preventDefault(),N(J,[]))},ne=X?s.jsxs("div",{className:["pc-workflow-chat__dropzone",X.over?"is-over":"",E?"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:E?"Attachments are unavailable right now":py(X.count)}),E?null:s.jsx("span",{children:X.over?"Release to upload to this conversation":"Drop anywhere on the conversation"})]})]}):null,B=X?E?"Attachments are unavailable right now":py(X.count):ie,z=async()=>{const K=String(e.draft||"");if(E||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:Bh(oe)})}finally{_.current&&x.current===J&&(p.current=!1,n(!1))}},G=async()=>{if(E||w.current||!e.onCancel)return;const K=++S.current;w.current=!0,f(null),o(!0);try{await e.onCancel()}catch(J){_.current&&S.current===K&&f({action:"cancel",message:Bh(J)})}finally{_.current&&S.current===K&&(w.current=!1,o(!1))}},T=async()=>{if(E||y.current||!e.onAttach)return;const K=++b.current;y.current=!0,f(null),u(!0);try{await e.onAttach()}catch(J){_.current&&b.current===K&&f({action:"attach",message:Bh(J)})}finally{_.current&&b.current===K&&(y.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",X?"pc-workflow-chat--dragging":"",X!=null&&X.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(ag,{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(gk,{interaction:e.interaction,disabled:E}):null,$?s.jsx("div",{className:"pc-workflow-chat__blocked",role:"status",children:e.blockedNotice}):null]}),afterKey:`${e.interaction?`${e.interaction.kind}:${e.interaction.id}`:""}:${$?"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:E,children:"Try again"})]}):null,s.jsxs("div",{className:"pc-workflow-chat__composer",children:[s.jsx(lg,{value:e.draft,onChange:e.onDraftChange,onSubmit:()=>void z(),placeholder:e.placeholder||"Send a message",ariaLabel:"Message",disabled:E,busy:D,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:Z?P: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:E||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:E||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]})}),Z?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 M_="llm.delta",Uh="llm.delta_end";function wk(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Zl(e){return typeof e=="string"&&e.trim()!==""}function vk(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0}function xk(e){return"reason"in e}function bk(e,t){const n=wk(e),i=n==null?void 0:n.kind,o=typeof i=="string"&&i?i:n&&"reason"in n?Uh:M_,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!==M_&&i!==Uh&&l(`unknown kind ${JSON.stringify(i)}`),Zl(n.run_id)||l("run_id is missing"),Zl(n.call_id)||l("call_id is missing"),vk(n.seq)||l("seq is not a non-negative integer");const u=i?i===Uh:"reason"in n;n.root_run_id!==void 0&&!Zl(n.root_run_id)&&l("root_run_id is not a run id"),n.parent_run_id!==void 0&&n.parent_run_id!==null&&!Zl(n.parent_run_id)&&l("parent_run_id is neither a run id nor null");const c={run_id:n.run_id,...Zl(n.root_run_id)?{root_run_id:n.root_run_id}:{},...n.parent_run_id!==void 0?{parent_run_id:n.parent_run_id}:{},...Zl(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:Uh,...c,reason:n.reason,...Zl(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:M_,...c,text:n.text,channel:n.channel,snapshot:n.snapshot})}const jk={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 Sk(e){return`This reply is not streamed: ${e?jk[e]||`the gateway reported "${e}"`:"the gateway gave no reason"}. It appears when it is complete.`}function kk(e){return e.toolApprovalGranted?null:e.interaction}const gy={messages:[],records:[],run:null,interaction:null,status:"idle",displayStatus:"",loading:!1,error:null,connection:"idle",toolApprovalGranted:!1,stop:null};function At(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function kt(e){return typeof e=="string"?e.trim():e==null?"":typeof e=="number"||typeof e=="boolean"?String(e):""}function sf(e){return Array.isArray(e)?e:[]}function ri(e){return kt(e==null?void 0:e.status).toLowerCase()||"unknown"}function Os(e){return["completed","failed","cancelled"].includes(e.toLowerCase())}function el(e){const t=At(e),n=Number((t==null?void 0:t.status)??(t==null?void 0:t.statusCode));return n===401||n===403}function Nk(e){const t=At(e);return Number((t==null?void 0:t.status)??(t==null?void 0:t.statusCode))}function R_(e){const t=n=>{if(Array.isArray(n))return n.map(t);const i=At(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 kp(e){if(typeof e=="string")return e.trim();const t=At(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 yu(e){const t=kp(e);if(t)return t;if(!At(e)&&!Array.isArray(e))return"";try{return JSON.stringify(e,null,2)}catch{return""}}function yy(e){if(!e)return"";for(const i of["prompt","request","task","message","query","input"]){const o=kt(e[i]);if(o)return o}const t=At(e.context);for(const i of["task","message"]){const o=kt(t==null?void 0:t[i]);if(o)return o}const n=sf(t==null?void 0:t.messages);for(let i=n.length-1;i>=0;i-=1){const o=At(n[i]);if(kt(o==null?void 0:o.role).toLowerCase()!=="user")continue;const l=kt(o==null?void 0:o.content);if(l)return l}return""}function Jv(e){const t=At(e.result);return At(t==null?void 0:t.wait)}function Np(e){return At(e.effect)||{}}function Ck(e,t){return kt(e.run_id)||t}function wy(e){return kt(e.ended_at)||kt(e.started_at)||void 0}function vy(e){const t=new Set,n=_=>{const p=kt(_);p&&t.add(p)},i=At(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=Np(e),l=At(o.payload);kt(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=Jv(e),c=At(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=kt(u==null?void 0:u.wait_key);return f.startsWith("subworkflow:")&&n(f.slice(12)),[...t]}class $k{constructor(t,n={}){this.transport=t,this.options=n,this.snapshot={...gy},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.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.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({...gy})}dispose(){this.reset(),this.subscribers.clear()}async load(t){var l;const n=kt(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[u,c]=await Promise.all([this.transport.getRun(n,o.signal),this.transport.getHistory(n,o.signal)]);if(!this.live(i))return;const f=At(u),_=At(f==null?void 0:f.waiting),p=ri(f);if(await this.ingestHistory(c,n,i),!this.live(i))return;if(this.set({...this.snapshot,run:f,status:p,loading:!1,..._&&!Os(p)?{interaction:{runId:n,wait:_,...((l=this.snapshot.interaction)==null?void 0:l.runId)===n&&kt(this.snapshot.interaction.wait.wait_key)===kt(_.wait_key)?{stepId:this.snapshot.interaction.stepId}:{}}}:{}}),f&&this.updateRunState(n,f),_)for(const w of vy({result:{wait:_}}))w!==n&&this.catchUpAndWatch(w,i);await this.catchUpAndWatch(n,i),this.pollRootLifecycle(n,i)}catch(u){!o.signal.aborted&&this.live(i)&&this.fail(u)}}async sendCommand(t,n={}){var p,w;t==="cancel"&&(this.toolApprovalStopped=!0,this.revokeToolApproval(),this.stopRequested=!0,this.recomputeStop());const i=kt(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${R_(n)}`;let c=this.commandIds.get(u);c||(c=this.newCommandId(),this.commandIds.set(u,c));const f=this.generation,_=(w=this.controller)==null?void 0:w.signal;try{const y=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 y;const x=At(y);if(x&&x.accepted===!1)throw t==="cancel"&&(this.stopRequested=!1,this.recomputeStop()),new Error(kt(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),y}catch(y){throw this.live(f)&&this.fail(y,!1),y}}resume(t){const n=this.requireInteraction();return this.sendCommand("resume",{wait_key:kt(n.wait.wait_key),payload:{response:t}})}approve(t,n){const i=this.requireInteraction();if(Os(this.snapshot.status))throw new Error("This run has already ended.");if(n&&(i.runId!==n.runId||kt(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:kt(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||Os(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||Os(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){R_(t)!==R_(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}:${kt(t.wait.wait_key)}${t.stepId?`:${t.stepId}`:""}`}coveredByStandingPermission(t,n){var i;return t.loading||this.toolApprovalStopped||this.toolApprovalSuspended||!this.toolApprovalPolicy&&!t.autoApproveTools||Os(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:!!kt(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=sf((o=At(t.wait.details))==null?void 0:o.tool_calls);return i.length>0&&i.every(l=>{var c;const u=kt((c=At(l))==null?void 0:c.name);return!!u&&n.includes(u)})}isToolApproval(t){const n=At(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:kt(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(!kt(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=At(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(el(o))throw o;this.fail(o,!1)}if(await this.catchUp(t,n),!this.live(n)||Os(ri(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(el(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=At(u),f=Array.isArray(u)?u:sf(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)&&!Os(ri(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=At(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),el(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(Os(ri(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=At(t);if(!o)return;const l=At(o.session),u=sf(l==null?void 0:l.turns).map(At).filter(_=>!!_);if(await this.hydrateHistoricalSessionRuns(u,n,i),!this.live(i))return;for(const _ of u){const p=kt(_==null?void 0:_.run_id)||n;this.ingestSessionTurn(_,n,p!==n&&this.historicalRuns.get(p)||null)}const c=`turn:${n}:user`;if(!this.seenMessages.has(c)){const _=yy(At(o.input_data));_&&this.addMessage({id:c,role:"user",content:_})}const f=At(o.ledgers);if(f)for(const[_,p]of Object.entries(f)){const w=At(p);for(const y of sf(w==null?void 0:w.items))this.ingestItem(_,y)}}ingestSessionTurn(t,n,i){if(!t)return;const o=kt(t.run_id)||n,l=At(t.input_data)||At(t.input)||{},u=kt(t.prompt)||yy(l);u&&this.addMessage({id:`turn:${o}:user`,role:"user",content:u,ts:kt(t.created_at)||void 0});const c=this.historicalRunFailures.get(o);if(c){const w=kt(t.answer)||kp(t.output),y=c.missing?"is unavailable because the run no longer exists":"could not be restored",x=w?` Saved reply (not verified as the final result): ${w}`:"";this.addMessage({id:`history:${o}:unavailable`,role:"system",level:"warn",title:"History",content:`The final output for an earlier turn ${y}.${x}`});return}const _=(i&&Os(ri(i))?yu(i.output):"")||(i?kt(t.answer)||kp(t.output):""),p=this.historicalEvidence.get(o);for(const w of(p==null?void 0:p.tools)||[])this.upsertTool(w);_&&this.addRunAssistantMessage(o,{id:`final:${o}`,role:"assistant",content:_,runId:o,statistics:p==null?void 0:p.statistics,ts:kt(t.updated_at)||void 0})}async hydrateHistoricalSessionRuns(t,n,i){const o=[...new Set(t.map(f=>kt(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 w=o[l++];if(!w)return;try{const y=At(await this.transport.getRun(w,(f=this.controller)==null?void 0:f.signal));if(!this.live(i))return;if(y){this.historicalRuns.set(w,y);try{const x=await this.transport.getHistory(w,(_=this.controller)==null?void 0:_.signal);if(!this.live(i))return;this.historicalEvidence.set(w,T_(lk(x)))}catch(x){if(!this.live(i))return;if(el(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(w,null),this.historicalRunFailures.set(w,{missing:!1,detail:"gateway returned an invalid historical run snapshot"})}catch(y){if(!this.live(i))return;const x=Nk(y)===404;this.historicalRuns.set(w,null),this.historicalRunFailures.set(w,{missing:x,detail:y instanceof Error?y.message:kt((p=At(y))==null?void 0:p.detail)||"request failed"}),el(y)&&(u=!0,this.fail(y))}}};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=At(n),o=At(i==null?void 0:i.record)||i;if(!o)return;const l=Ck(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 _=T_(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 vy(o))_!==l&&this.catchUpAndWatch(_,this.generation)}}foldRecord(t,n,i){var p,w;const o=Np(n),l=kt(o.type).toLowerCase(),u=At(n.result),c=kt(n.status).toLowerCase(),f=wy(n);if(this.foldStopEvidence(t,n,l,c),["llm_call","tool_calls"].includes(l)&&["started","running"].includes(c)){const y=Date.parse(f||"");(!Number.isFinite(y)||y>=this.displayStatusAt)&&(Number.isFinite(y)&&(this.displayStatusAt=y),this.snapshot.displayStatus&&this.set({...this.snapshot,displayStatus:""}))}if(l==="answer_user"&&c==="completed"){const y=yu(u)||yu(At(o.payload));y&&this.addRunAssistantMessage(t,{id:`answer:${t}:${i}`,role:"assistant",content:y,ts:f})}if(l==="emit_event"&&c==="completed"){const y=At(o.payload)||{},x=At(u),S=kt(y.name)||kt(x==null?void 0:x.name),b=y.payload!==void 0?y.payload:x==null?void 0:x.payload;if(["abstract.message","abstractcode.message"].includes(S)){const $=yu(b);if($){const E=kt((p=At(b))==null?void 0:p.level).toLowerCase(),L=E==="error"?"error":["warn","warning"].includes(E)?"warn":"info";this.addMessage({id:`event:${t}:${i}`,role:"system",title:"Workflow",content:$,level:L,ts:f})}}if(["abstract.status","abstractcode.status"].includes(S)){const $=At(b),E=$?$.status??$.text??$.value:b,L=Date.parse(f||"");!Os(this.snapshot.status)&&typeof E=="string"&&(!Number.isFinite(L)||L>=this.displayStatusAt)&&(Number.isFinite(L)&&(this.displayStatusAt=L),this.set({...this.snapshot,displayStatus:E.trim()}))}if(["abstract.tool_execution","abstractcode.tool_execution","abstract.tool_result","abstractcode.tool_result"].includes(S)){const $=yu(b);$&&this.addMessage({id:`event:${t}:${i}`,role:"system",title:"Tool activity",content:$,ts:f})}}const _=Jv(n);if(c==="waiting"&&_&&!Os(this.snapshot.status)&&!Os(ri(this.runStates.get(t)||null))&&this.set({...this.snapshot,interaction:{runId:t,wait:_,...kt(n.step_id)?{stepId:kt(n.step_id)}:{}}}),l==="tool_calls")for(const y of Gv(this.toolActivities,{runId:t,cursor:this.cursors.get(t)||0,record:n}))this.upsertTool(y);l==="resume"&&(u==null?void 0:u.resumed)===!0&&((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=kt(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=At(Np(n).payload)||{},c=At(n.result),f=kt(u.name)||kt(c==null?void 0:c.name),_=At(u.payload!==void 0?u.payload:c==null?void 0:c.payload);f==="abstract.status"&&kt(_==null?void 0:_.killed_by)==="kill_switch"&&(this.forcedStop=_,l=!0)}l&&this.recomputeStop()}recomputeStop(){let t=null;this.forcedStop?t={phase:"forced",label:kt(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=kt(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=bk(n)}catch(f){this.fail(f,!1);return}const o=`${i.run_id}:${i.call_id}`;if(xk(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 Os(ri(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:Sk(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;el(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:kt((l=At(t))==null?void 0:l.detail)||String(t),...el(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),Os(ri(n))&&this.endLiveRepliesOfRun(t,ri(n)),t!==this.rootRunId){Os(ri(n))&&((l=this.snapshot.interaction)==null?void 0:l.runId)===t&&this.set({...this.snapshot,interaction:null});return}const i=ri(n),o=Os(i);if(o){const u=yu(n.output);u&&this.upsertFinal(t,u,wy(n))}this.set({...this.snapshot,run:n,status:i,...o?{interaction:null,autoApproveTools:!1,displayStatus:""}:{}}),(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:T_(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=At(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&&!Os(ri(this.runStates.get(t)||null));){if(await this.waitForRetry(2e3),!this.live(n)||this.rootRunId!==t||Os(ri(this.runStates.get(t)||null)))return;try{const o=At(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(el(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 Ak(e){const t=m.useMemo(()=>new $k(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 Ql(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function cr(e){return typeof e=="string"?e.trim():e==null?"":typeof e=="number"||typeof e=="boolean"?String(e):""}function xy(e){return["session","workflow","run","global"].includes(e)?e:null}function nl(e){return{scope:cr(e==null?void 0:e.scope).toLowerCase(),name:cr(e==null?void 0:e.name)||cr(e==null?void 0:e.event_name),scopeId:cr(e==null?void 0:e.scope_id)||cr(e==null?void 0:e.scopeId),sessionId:cr(e==null?void 0:e.session_id)||cr(e==null?void 0:e.sessionId),workflowId:cr(e==null?void 0:e.workflow_id)||cr(e==null?void 0:e.workflowId),runId:cr(e==null?void 0:e.run_id)||cr(e==null?void 0:e.runId)}}function Ek(e,t){const n=e.wait,i=cr(n.wait_key),o=[nl(n),nl(Ql(n.details))];for(const l of t){if(l.runId!==e.runId)continue;const u=l.record,c=Ql(u.result),f=Ql(c==null?void 0:c.wait),_=Ql(u.effect),p=Ql(_==null?void 0:_.payload);cr(f==null?void 0:f.wait_key)!==i&&cr(p==null?void 0:p.wait_key)!==i||o.push(nl(u),nl(p),nl(Ql(p==null?void 0:p.details)),nl(f),nl(Ql(f==null?void 0:f.details)))}return o}function L_(e,t){return t.scopeId?t.scopeId:e==="session"?t.sessionId:e==="workflow"?t.workflowId:e==="run"?t.runId:"global"}function Xv(e,t,n){return{scope:e,scopeId:t,name:n,...e==="session"?{sessionId:t}:{},...e==="workflow"?{workflowId:t}:{},...e==="run"?{runId:t}:{}}}function Tk(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?Xv(t,n,o):null}function Mk(e,t=[],n){if(!e)return{target:null,error:"No event wait is available."};const i=cr(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=xy(o[1]);if(!l)return{target:null,error:"The event wait uses an unsupported scope."};const u=Ek(e,Array.isArray(t)?t:[]),c=new Map;for(const y of u){const x=xy(y.scope);if(!x||!y.name)continue;if(x!==l)return{target:null,error:"Event metadata conflicts with the canonical wait scope."};const S=`evt:${x}:`,b=`:${y.name}`;if(!i.startsWith(S)||!i.endsWith(b)||i.length<=S.length+b.length)return{target:null,error:"Event metadata does not exactly match the canonical wait key."};const $=i.slice(S.length,-b.length),E=L_(x,y);if(E&&E!==$)return{target:null,error:"Event metadata conflicts with the canonical wait target."};const L=Xv(x,$,y.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 y of u){const x=L_(l,y);x&&f.add(x)}if(cr(n==null?void 0:n.run_id)===e.runId){const y=nl(n||null),x=L_(l,y);x&&f.add(x)}const p=[...f].map(y=>Tk(i,l,y)).filter(y=>!!y),w=new Map(p.map(y=>[`${y.scope}\0${y.scopeId}\0${y.name}`,y]));return w.size===1?{target:[...w.values()][0]}:w.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 cg=e=>bt(`runs/${encodeURIComponent(e)}/workspace`);function Rk(e){return cg(e)}function Lk(e,t){return`${cg(e)}/files?${new URLSearchParams({path:t,recursive:"false"})}`}function Ik(e,t){return`${cg(e)}/content?${new URLSearchParams({path:t})}`}async function Bm(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 Ok(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 Pk(e,t,n){const i=await e(Rk(t),{signal:n});if(!i.ok)throw await Bm(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 Dk(e,t,n,i){const o=await e(Lk(t,n),{signal:i});if(!o.ok)throw await Bm(o,"The folder could not be listed");return Ok(await o.json(),n)}async function Fk(e,t,n,i){const o=await e(Ik(t,n),{signal:i});if(!o.ok)throw await Bm(o,"The file could not be read");return await o.blob()}async function zk(e,t,n,i){const o=await Pk(e,t,i);return{where:o,listing:o.exists?await Dk(e,t,n,i):null}}function Bk(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 Uk(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 Wk(e){return[...e].sort((t,n)=>t.type===n.type?t.name.localeCompare(n.name):t.type==="dir"?-1:1)}function qk(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 Hk=new Set(["image/png","image/jpeg","image/gif","image/webp","image/avif","image/bmp","application/pdf","text/plain","application/json"]);function Vk(e){const t=String(e||"").split(";",1)[0].trim().toLowerCase();return Hk.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 Zv(e,t,n){const i=n==="open"?Vk(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 Gk(e,t,n){const i=await e(Sj(t),{signal:n.signal});if(!i.ok)throw await Bm(i,`${n.name} could not be read`);Zv(await i.blob(),n.name,n.mode??"open")}function Qv(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,w]=m.useState(!!n),[y,x]=m.useState(""),[S,b]=m.useState(0);m.useEffect(()=>{if(!n)return;const L=new AbortController;return w(!0),_(""),(async()=>{try{const D=await zk(t,n,l,L.signal);L.signal.aborted||c({runId:n,...D})}catch(D){L.signal.aborted||_(String((D==null?void 0:D.message)||D))}finally{L.signal.aborted||w(!1)}})(),()=>L.abort()},[t,n,l,S,e.refreshKey]);const $=u&&u.runId===n?u:null,E=m.useCallback(async(L,D)=>{x(L.path),_("");try{Zv(await Fk(t,n,L.path),L.name,D)}catch(M){_(String((M==null?void 0:M.message)||M))}finally{x("")}},[t,n]);return s.jsx(Kk,{title:e.title,note:e.note,where:($==null?void 0:$.where)??null,path:l,listing:($==null?void 0:$.listing)??null,error:f,loading:p,fileBusy:y,selectedPath:e.selectedPath,className:e.className,onNavigate:L=>o({runId:n,path:L}),onRefresh:()=>b(L=>L+1),onFile:e.onSelectFile?void 0:(L,D)=>void E(L,D),onSelectFile:e.onSelectFile,onClose:e.onClose})}function Kk(e){var i,o,l,u;const t=e.listing?qk(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:Bk(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:Wk(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:Uk(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(Nv,{text:e,images:"link"})}const Yk={trigger:"Trigger",answer:"Automation"};function Jk(e){return s.jsx(og,{message:{id:`${e.runId}:${e.kind}`,role:e.role,content:e.text,title:Yk[e.kind],runId:e.runId},images:"link"})}const Xk={renderText:ex,renderTurn:Jk};function Zk(e){const{fetchGateway:t,...n}=e,i=n.onOpenResource??(t?o=>Gk(t,o.url,{name:o.name}):void 0);return s.jsx(qS,{...n,onOpenResource:i,...Xk})}function Qk(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(w=>String((w==null?void 0:w.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(qv,{tools:c.map((w,y)=>({id:String((w==null?void 0:w.call_id)||(w==null?void 0:w.id)||y),runId:e.runId,name:(w==null?void 0:w.name)||"Tool",arguments:w==null?void 0:w.arguments,status:"waiting"}))}),s.jsxs("details",{children:[s.jsx("summary",{children:"Review full tool arguments (JSON)"}),s.jsx(dr,{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=Mk(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 w=JSON.parse(p||"{}"),y={name:f.name,scope:f.scope,payload:w};f.scope==="session"?y.session_id=f.scopeId:f.scope==="workflow"?y.workflow_id=f.scopeId:f.scope==="run"&&(y.run_id=f.scopeId),await t.emitEvent(y)}}}return null}const eN="# 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 Ps(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`id_${Date.now()}_${Math.random().toString(16).slice(2)}`}function tN(e,t){return[...e.filter(n=>!n.local_error),t].map(n=>({role:n.role,content:n.content}))}function Wh(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?Math.trunc(e):0}function nN(e){const t=Wh(e==null?void 0:e.dropped_messages);if(!e||t<=0)return null;const n=Wh(e.replayed_messages),i=Wh(e.dropped_tokens),o=Wh(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 tx(e){const t=nN(e.history);return t?s.jsx(og,{message:{role:"system",level:"info",title:"History",content:t}}):null}const sN=1500,rN=12e4;function iN(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 oN=["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) ===",eN,"=== END DOCUMENTATION ==="].join(`
69
- `),aN="observer-docs-assistant";function by(){return`${aN}:${Ps()}`}function lN(e){return{prompt:e,system:oN,tools:[],use_session_history:!0,use_context:!0}}function cN(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 uN(e,t,n=()=>{}){return async(i,o)=>{var f;const l=e(),u=await l.start_run(null,lN(i),{bundle_id:"basic-agent",session_id:t()}),c=Date.now();for(;;){if(await iN(sN,o.signal),Date.now()-c>rN)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 w=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}: ${w}`)}if(p==="completed"){n((_==null?void 0:_.session_history)??null);const w=await l.get_ledger(u,{after:0,limit:500,signal:o.signal});return cN(w.items)||"(the run completed but produced no readable answer — inspect it on the Observe page)"}}}}function dN(e){const t=m.useRef(e.gateway);t.current=e.gateway;const n=m.useRef(by()),[i,o]=m.useState([]),[l,u]=m.useState(null),c=m.useMemo(()=>uN(()=>t.current,()=>n.current,u),[]),[f]=m.useState(void 0),_=()=>{n.current=by(),o([]),u(null)};return s.jsxs(Rj,{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(tx,{history:l}),s.jsx(rk,{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 fN="api/local/reveal",hN="sw.js";function mN(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 vm="@default:",Cp="abstractcode.agent.v1";function _N(e){const t=String(e||"").trim();if(t.startsWith(vm)){const i=t.slice(vm.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 pN(e){return e?e.kind==="default"?`${vm}${e.interface}`:`${e.bundle_id}:${e.flow_id}`:""}function gN(e){const t={};for(const i of e)for(const o of i.agent_default_interfaces||[])o&&!t[o]&&(t[o]=i.label);return[Cp,...Object.keys(t).filter(i=>i!==Cp).sort()].map(i=>({interface:i,value:`${vm}${i}`,label:`Gateway default agent · ${i}${t[i]?` (now: ${t[i]})`:""}`}))}function yN(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 wN(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 vN={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) or when you ask; manage it on the Automations page."},xN="#launch/automate";function bN(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 $p={when:"every",amount:"24",unit:"h",once_at:"",context:"independent",tool_approval:"auto",title:"",start_at:"",count:"",until:""},jy={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."},nx=["use_context"],jN="This choice also sets the workflow's Use Context input: the workflow always reads the history the automation gives it.";function sx(e,t){const n=e.when==="every";return{prompt:t,when:n?{kind:"every",amount:Number(e.amount),unit:e.unit}:{kind:"once",at:e.once_at},context:e.context,toolApproval:e.tool_approval,title:e.title,...n&&e.start_at?{startAt:e.start_at}:{},...n&&e.count.trim()?{count:Number(e.count)}:{},...n&&e.until?{until:e.until}:{}}}function SN(e,t){if(t.input_data===null)return{ok:!1,errors:["The inputs are not valid JSON."]};const n=wN(t.input_data),i=typeof n.prompt=="string"?n.prompt:"";delete n.prompt;for(const l of nx)delete n[l];let o;try{o=yN(t.choice,t.bundle_ref_for,n)}catch(l){return{ok:!1,errors:[String((l==null?void 0:l.message)||l)]}}return Dv(sx(e,i),{target:o,requestId:t.request_id})}function kN(e){const t=Dv(sx(e,"preview"),{target:{flow_id:"@default",interface:Cp},requestId:"preview"});if(!t.ok)return"";const n=t.body.trigger.config,i=Mv(n);return e.when==="once"?`Runs ${i}.`:`Runs ${i}, first run ${n.start_at?`at ${ma(n.start_at)}`:"now"}.`}class NN{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 CN(e,t,n){const i=SN(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 ca(e){return typeof e=="string"?e:e??null}function $N(e){var t,n,i,o,l,u;return{run_id:String((e==null?void 0:e.run_id)||"").trim(),workflow_id:ca(e==null?void 0:e.workflow_id),status:typeof(e==null?void 0:e.status)=="string"?String(e.status):"",created_at:ca(e==null?void 0:e.created_at),updated_at:ca(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:ca(e==null?void 0:e.parent_run_id),session_id:ca(e==null?void 0:e.session_id),actor_id:ca(e==null?void 0:e.actor_id),session_kind:ca(e==null?void 0:e.session_kind),automation_id:ca(e==null?void 0:e.automation_id),role:ca(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 cf(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 rx(e){const t=cf(e);return t==="occurrence"?typeof e.occurrence_index=="number"?`occurrence #${e.occurrence_index}`:"occurrence":t==="legacy"?"legacy schedule":t||""}function Sy(e){return String((e==null?void 0:e.role)||"").trim()==="controller"}function AN(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 lc(e){return e.legacy===!0||e.capabilities.includes("legacy")}function ix(e,t=Date.now()){const n=lc(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:rg(e.trigger),next_run:e.next_fire_at?`${ma(e.next_fire_at)} (${Iv(e.next_fire_at,t)})`:e.status==="paused"?"none while paused":"none scheduled",current:Lv(e),state:e.status,last:i?i.excerpt:"",last_status:i?`#${i.index} ${i.status}${o}`:"no runs yet",attention:l?Ov(e):null,legacy:n}}function ox(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 EN(e,t){const n=gm(e,[],t),i=ox(e),o=t?{enabled:!1,reason:"Working…"}:lc(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 TN(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 MN(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 RN=/^([1-9][0-9]*)([smhd])$/;function LN(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 IN(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={...$p},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 y=RN.exec(f);let x=y?Number(y[1]):0,S=y?y[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 _=LN(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:{},w={};for(const[y,x]of Object.entries(p))y==="workflow_selection"||y.startsWith("_")||(w[y]=x);return{choice:{kind:"bundle",bundle_id:o,flow_id:l},input_data:w,form:c,notes:u}}const ON={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:""};function PN(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 DN(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 ky(e){return e.show_archived||e.status_filter==="archived"?e.items:e.items.filter(t=>t.status!=="archived")}function Ny(e){return e.items.filter(t=>t.status==="archived").length}function ug(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 FN=3e4,qh=50;function Yi(e){return ig(e)?e:{status:0,code:"client_error",message:e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}}function I_(e,t){const n=new Map;for(const 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 zN{constructor(t,n,i=[1500,4e3]){Gs(this,"state",{...ON});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:qh});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 refresh(){const t=++this.list_seq;this.set({loading:!0});try{const n=await this.list_all();if(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:Yi(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&&lc(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:qh})]);if(i!==this.detail_seq)return;this.set({detail:{automation_id:n,summary:l??u.summary,definition:u.definition,occurrences:I_([],c.items),next_cursor:c.next_cursor,error:null}}),await this.load_trigger_sources()}catch(l){if(i!==this.detail_seq)return;this.set({error:Yi(l)})}}async reload_occurrences(t){const n=this.state.detail;if(!n||n.automation_id!==t||lc(n.summary))return;const[i,o]=await Promise.all([this.client.getAutomation(t),this.client.listOccurrences(t,{limit:qh})]),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:I_(l.occurrences,o.items),next_cursor:l.occurrences.length>o.items.length?l.next_cursor:o.next_cursor}})}async load_more(){const t=this.state.detail;if(!(!t||!t.next_cursor))try{const n=await this.client.listOccurrences(t.automation_id,{cursor:t.next_cursor,limit:qh}),i=this.state.detail;if(!i||i.automation_id!==t.automation_id)return;this.set({detail:{...i,occurrences:I_(i.occurrences,n.items),next_cursor:n.next_cursor}})}catch(n){this.set({error:Yi(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 Yi(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 Yi(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:ug(n,l)}),l}catch(l){throw Yi(l)}finally{this.set({busy:!1})}}async seen(t,n){try{await this.client.markSeen(t,n)}catch(i){throw Yi(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,DN(u.kind,o)),await this.after_change(t)}catch(u){throw Yi(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.`:`${BN[n]} sent to “${t.title}”.`,confirm_archive_id:""})}catch(o){this.set({error:Yi(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(!lc(t))throw new Error("legacy_action on a non-legacy automation");const i=MN(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:Yi(o)})}finally{this.set({busy:!1})}}report_error(t){this.set({error:Yi(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 BN={pause:"Pause",resume:"Resume",run_now:"Run now",archive:"Archive"};function UN(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:vN[e.mode]})]})}function WN(e){const t=e.form,n=kN(t);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:t.when==="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:t.when==="once",disabled:e.disabled,onChange:()=>e.on_change({when:"once"})})," Once at…"]})]}),t.when==="every"?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"automate_row",role:"group","aria-label":"Presets",children:hS.map(i=>i.when.kind==="every"?s.jsx("button",{type:"button",className:"btn btn_sm","data-preset":i.label,"aria-pressed":Number(t.amount)===i.when.amount&&t.unit===i.when.unit,disabled:e.disabled,onClick:()=>{i.when.kind==="every"&&e.on_change({amount:String(i.when.amount),unit:i.when.unit})},children:i.label},i.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:i=>e.on_change({amount:i.target.value})}),s.jsxs("select",{value:t.unit,disabled:e.disabled,"aria-label":"Interval unit",onChange:i=>e.on_change({unit:i.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:i=>e.on_change({once_at:i.target.value})})]}),s.jsx("div",{className:"automate_preview","aria-live":"polite","data-preview":"true",children:n||"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) — ",jy.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"})," — ",jy.growing]}),s.jsx("p",{className:"help_text muted","data-context-owns":"use_context",children:jN})]}),s.jsxs("fieldset",{"data-section":"tools",children:[s.jsx("legend",{children:"Tools"}),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"})})," ",pS,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"]})]})]})}function qN(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 HN="abstractobserver";function VN(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 GN(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 KN=new Set(["completed","failed","cancelled"]);function YN(e){var D;const{gateway:t,discussion:n}=e,i=m.useMemo(()=>VN(t),[t]),[o,l]=m.useState(((D=n.session)==null?void 0:D.run_id)||""),[u,c]=m.useState(""),[f,_]=m.useState(!1),[p,w]=m.useState(""),{controller:y,snapshot:x}=Ak({transport:i,runId:o,enabled:e.connected,clientId:HN}),S=n.session,b=!!o&&!KN.has(x.status)&&x.status!=="idle",$=kk(x),E=async M=>{var Z;const H=M.trim();if(H){_(!0);try{if(S){const Y=String(((Z=x.run)==null?void 0:Z.workflow_id)||""),X=GN(Y),re=await t.start_run(X.flow_id,{prompt:H},{bundle_id:X.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:()=>w(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:()=>w(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(Qv,{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:()=>w(""),refreshKey:x.status}):null,s.jsx(yk,{header:L,messages:x.messages,draft:u,onDraftChange:c,onSend:E,busy:b||f,busyLabel:f?S?"Starting…":"Forking the automation…":$?"Waiting for you":"Working…",onCancel:b?()=>y.cancel():void 0,stopState:x.stop??null,disabled:!e.connected,interaction:Qk($,y,{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 JN=5e3,XN=[["","All"],["active","Active"],["paused","Paused"],["completed","Completed"],["failed","Failed"],["archived","Archived"]],ZN={pause:il.pause,resume:il.resume,run_now:il.run_now,edit:il.revise,archive:`${il.archive}…`,discuss:il.discuss},QN={pause:Zi.pause,resume:Zi.resume,run_now:Zi.run_now,edit:Zi.revise,archive:Zi.archive,discuss:Zi.discuss},e1={pause:"pause",resume:"resume",run_now:"run_now",edit:"revise",archive:"archive",discuss:"discuss"},t1={legacy_pause:Zi.pause,legacy_resume:Zi.resume,legacy_run_now:Zi.run_now,open_run:"list",recreate:"refresh"};function n1(e){return s.jsx("span",{className:"auto_state","data-field":"state",children:s.jsx(zv,{status:e.status})})}function Hh(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 s1={legacy_pause:"Suspend",legacy_resume:"Resume",legacy_run_now:"Run now",open_run:"Open run",recreate:"Recreate as automation"};function r1(e){const t=e.summary,n=ix(t),i=e.state.selected_id===t.automation_id,o=e.state.busy,l=(f,_,p,w,y,x,S,b)=>s.jsxs("button",{type:"button",className:`btn btn_sm auto_action${S?" auto_action_icon":""}${y?` ${y}`:""}`,"data-action":f,disabled:!p.enabled,title:[S?_:null,p.enabled?null:p.reason,b].filter(Boolean).join(`
70
- `)||void 0,"aria-label":S?_:void 0,"aria-description":b,onClick:w,children:[x?s.jsx(Qe,{name:x,size:13}):null,S?null:s.jsx("span",{children:_})]},f);let u;if(n.legacy){const f=TN(t,o);u=[t.status==="paused"?"legacy_resume":"legacy_pause","legacy_run_now","open_run","recreate"].map(p=>l(p,s1[p],f[p],()=>e.h.on_legacy_action(t,p),void 0,t1[p]))}else{const f=EN(t,o);u=[t.status==="paused"?"resume":"pause","run_now","edit","discuss","archive"].map(p=>l(p,ZN[p],f[p],()=>e.h.on_row_action(t,p),p==="archive"?"danger auto_action_end":void 0,QN[p],p==="archive",Bv(e1[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(n1,{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(Hh,{icon:"refresh",field:"cadence",label:"When it runs",children:n.cadence}),n.current?s.jsx(Hh,{icon:"loader",field:"current",label:"Running now",className:"auto_row_current",children:n.current}):null,s.jsxs(Hh,{icon:"clock",field:"next",label:"Next run",children:["next: ",n.next_run]}),s.jsx(Hh,{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 i1(e){const t=e.state,n=t.error??t.list_error,i=n?ym(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:ky(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:XN.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:xN,"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,Ny(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 (",Ny(t),")"]}):null,s.jsx("ul",{className:"auto_rows",children:ky(t).map(o=>s.jsx(r1,{summary:o,state:t,h:e.h},o.automation_id))})]})]})}function o1(e,t,n){const i=e.state,o=i.detail;if(!o||lc(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(_,ug(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}:{}}}function a1(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 (",xp.toLowerCase(),")."]})});if(lc(t.summary)){const i=ix(t.summary);return s.jsxs("section",{className:"pane auto_detail","data-legacy":"true",children:[s.jsxs("div",{className:"pane_header",children:[s.jsx("span",{className:"pane_title",children: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=o1(e.ctl,e.host,e.edit);return s.jsxs("section",{className:"pane auto_detail",children:[e.browser??null,n?s.jsx(Zk,{...n}):null]})}function l1(e,t){if(t==="edit")return{kind:"edit"};if(t!=="discuss")return{kind:"forward"};const n=ox(e);return n===null?{kind:"none"}:{kind:"discuss",index:n}}function c1(e){const t=e.ctl,[n,i]=m.useState(null),o=b=>i($=>({...b,opened:(($==null?void 0:$.opened)||0)+1})),[l,u]=m.useState(""),[c,f]=m.useState("");m.useSyncExternalStore(b=>t.subscribe(b),()=>t.state,()=>t.state);const[_,p]=m.useState(()=>typeof document>"u"||document.visibilityState!=="hidden");m.useEffect(()=>{const b=()=>p(document.visibilityState!=="hidden");return document.addEventListener("visibilitychange",b),()=>document.removeEventListener("visibilitychange",b)},[]),m.useEffect(()=>{if(!e.active||!_||!e.available.available)return;t.refresh();const b=window.setInterval(()=>void t.refresh(),FN);return()=>window.clearInterval(b)},[t,e.active,_,e.available.available]);const w=t.state.detail,y=t.state.notice;m.useEffect(()=>{if(!y)return;const b=window.setTimeout(()=>t.dismiss_notice(),JN);return()=>window.clearTimeout(b)},[t,y]);const x={...e.host,on_open_workspace:b=>u($=>$===b?"":b),fetch_gateway:e.gateway.fetch_gateway,on_open_session:(b,$,E)=>{e.host.on_open_session(b,$,E),w&&o({automation_id:w.automation_id,automation_title:w.summary.title,occurrence_index:E,session:b})}},S={...e.h,on_select:b=>{i(null),u(""),b!==c&&f(""),e.h.on_select(b)},on_dismiss_notice:()=>t.dismiss_notice(),on_dismiss_error:()=>t.dismiss_error(),on_row_action:(b,$)=>{const E=l1(b,$);E.kind==="forward"?e.h.on_row_action(b,$):E.kind==="edit"?(i(null),u(""),f(b.automation_id),e.h.on_select(b.automation_id)):E.kind==="discuss"&&(e.h.on_select(b.automation_id),o({automation_id:b.automation_id,automation_title:b.title,occurrence_index:E.index}))}};return s.jsxs("div",{className:"page auto_page",children:[s.jsx(i1,{state:t.state,available:e.available,h:S}),n?s.jsx(YN,{gateway:e.gateway,discussion:n,connected:e.active,on_fork:async(b,$,E)=>{const L=await t.discuss(b,$,E);return e.host.on_open_session(L,ug($,L),$),i(D=>D&&{...D,session:L}),L},on_close:()=>i(null)},n.opened):s.jsx(a1,{ctl:t,host:x,h:S,edit:{open:!!w&&c===w.automation_id,on_change:b=>f(b&&w?w.automation_id:"")},browser:l?s.jsx(Qv,{fetchGateway:e.gateway.fetch_gateway,runId:l,title:l===(w==null?void 0:w.automation_id)?"Automation files":"Run files",onClose:()=>u("")}):void 0})]})}function u1(){const e="0.2.1".trim();if(!e)throw new Error("AbstractObserver: __APP_VERSION__ is not defined; the vite/vitest config must inject it from package.json");return e}function d1(){return Dj("abstractobserver",u1())}async function f1(e){let t;try{t=await e.gateway_about()}catch(n){return cy(null,n instanceof Error?n.message||n.name:String(n))}return cy(t)}class xm{constructor(t){this._maxSize=xm._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=xm._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 h1(e){try{return new URL(String(e)),!0}catch{return!1}}function m1({baseUrl:e,endpoint:t}){const n=String(t||"api/gateway/host/metrics/gpu");return h1(n)?n:e&&String(e).trim()?new URL(n,String(e)).toString():n}async function _1({token:e,getToken:t}){if(typeof t=="function"){const n=await t();return n==null?"":String(n)}return e==null?"":String(e)}function p1({token:e}){const t=String(e||"").trim();return t?{Authorization:`Bearer ${t}`}:{}}function g1(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 y1({baseUrl:e,endpoint:t,token:n,getToken:i,signal:o,fetchImpl:l}={}){const u=m1({baseUrl:e,endpoint:t}),c=await _1({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",...p1({token:c})},signal:o})}catch(w){return{ok:!1,status:0,error:"network_error",detail:w instanceof Error?w.message:String(w),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 Hd=Object.freeze({tickMs:1500,historySize:20,endpoint:"api/gateway/host/metrics/gpu",baseUrl:"",mode:"full"});function w1(e){return Number.isFinite(e)?Math.min(1,Math.max(0,e)):0}function Cy(e,t,n){return Number.isFinite(e)?Math.min(n,Math.max(t,e)):t}function $y(e,t){const n=Number(e);return Number.isFinite(n)?Math.floor(n):t}function O_(e,t=1){const n=Cy(Number(e)/100,0,1),i=Math.round(140-140*n),o=Cy(Number(t),0,1);return o>=1?`hsl(${i} 85% 55%)`:`hsl(${i} 85% 55% / ${o})`}function Ay(e){const t={...Hd,...e||{}};return t.tickMs=Math.max(250,$y(t.tickMs,Hd.tickMs)),t.historySize=Math.max(1,Math.min(200,$y(t.historySize,Hd.historySize))),t.endpoint=String(t.endpoint||Hd.endpoint),t.baseUrl=String(t.baseUrl||""),t.mode=String(t.mode||Hd.mode).trim().toLowerCase(),t.mode!=="icon"&&(t.mode="full"),t}function v1(){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 x1{constructor(t,n={}){if(!t||typeof t!="object")throw new TypeError("target element is required");this._target=t,this._opts=Ay(n),this._buffer=new xm(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=v1();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=Ay({...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",O_(c,.95)),n.style.setProperty("--monitor-gpu-accent-glow",O_(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 w=0;w<f.length;w+=1){const y=f[w],x=w-_,S=x>=0?l[x]:null,b=Number.isFinite(S)?S:null,$=b==null?0:w1(b/100),E=Math.max(2,Math.min(p,Math.round($*p)));y.style.height=`${E}px`,y.style.background=b==null?"":O_(b),y.className="bar",b==null&&y.classList.add("missing"),t&&y.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 y1({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=g1(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 b1(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 x1(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 xt(){return new Date().toISOString()}function j1(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}function Ds(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 P_(e){const t=String(e||"").trim();return t&&t.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")||"untitled"}function Nn(e){const t=typeof e=="string"?e.trim():"";if(!t)return null;const n=t.replace(/(\.\d{3})\d+/,"$1"),i=Date.parse(n);return Number.isFinite(i)?i:null}function S1(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 fa(e){const t=Nn(e);return t===null?"—":S1(t)}function Ey(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 dg(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 _a(e){const t=Nn(e);return t===null?"—":new Date(t).toLocaleString()}function fn(...e){for(const t of e){const n=String(t??"").trim();if(n)return n}return""}function k1(...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 Ou(e){const t=String(e||"").trim().toLowerCase();return t==="running"||t==="waiting"}function nc(e){return String((e==null?void 0:e.started_at)||(e==null?void 0:e.created_at)||"").trim()}function ax(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 fg(e,t=Date.now()){const n=Nn(nc(e));if(n===null)return-1;const i=Nn(ax(e));return Math.max(0,(i!==null?i:t)-n)}function fc(e,t=Date.now()){return dg(fg(e,t))}function N1(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 Pu(e){return String(e||"").trim().toLowerCase()}function Um(e){return`${(e==null?void 0:e.filename)||""} ${(e==null?void 0:e.source_path)||""}`.trim().toLowerCase()}function af(e,t){return t.some(n=>e.endsWith(n))}function C1(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 $1(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 A1(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 lx(e,t){var u,c,f,_,p;const n=Pu(e==null?void 0:e.content_type),i=Um(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(w=>String(w||"").trim().toLowerCase()).filter(Boolean).join(" ");if(/(^|[^a-z0-9])(code|source_code|script|program|executable)([^a-z0-9]|$)/i.test(o)||n.includes("javascript")||n.includes("typescript")||n.includes("x-python")||n.includes("x-shellscript")||n.includes("x-rust")||n.includes("x-go")||n.includes("x-java")||n.includes("x-csrc")||n.includes("x-c++src")||af(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 cx(l)}function E1(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 T1(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 M1(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:cx(e)}function cx(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 R1(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 L1(e,t){var _;const n=String(t||""),i=C1(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||R1(n)||T1(o)||M1(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 lf(e){const t=Pu(e==null?void 0:e.modality),n=Pu(e==null?void 0:e.content_type),i=Um(e),o=$1(e);return t==="image"||n.startsWith("image/")||af(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)||af(i,[".wav",".mp3",".m4a",".aac",".flac",".ogg",".opus",".aiff",".mid",".midi"])?"audio":t==="video"||n.startsWith("video/")||af(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")||lx(e,"")?"text":"binary"}function bm(e,t){const n=Pu(e==null?void 0:e.content_type),i=Um(e),o=String(t||"").trim();return n.includes("html")||i.endsWith(".html")||i.endsWith(".htm")||A1(t)?"html":lx(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("["))&&Fm(o)!==null?"json":L1(e,t)?"markdown":"text"}function hg(e,t=""){const n=lf(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=Pu(e==null?void 0:e.modality),o=Pu(e==null?void 0:e.content_type),l=Um(e);return i==="document"||o.includes("pdf")||af(l,[".pdf",".doc",".docx",".ppt",".pptx",".xls",".xlsx"])?"document":"other"}return bm(e,t)}function D_(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=w=>" ".repeat(Math.max(0,w)),f=(w,y)=>{const x=w.match(/^(<\/?|<!)([^\s/>]+)([\s\S]*?)(\/?>)$/);if(!x||w.length<=120||w.startsWith("</")||w.startsWith("<!"))return[`${c(y)}${w.trim()}`];const S=(x[3]||"").trim();if(!S)return[`${c(y)}${w.trim()}`];const b=S.match(/[^\s="'<>`]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'<>`]+))?/g)||[S];return[`${c(y)}${x[1]}${x[2]}`,...b.map($=>`${c(y+1)}${$.trim()}`),`${c(y)}${x[4]}`]};for(const w of i){const y=String(w||"");if(!y.trim())continue;const x=y.trim().toLowerCase();if(x.startsWith("</")){const b=((_=x.match(/^<\/\s*([a-z0-9:-]+)/))==null?void 0:_[1])||"";u&&b===u&&(u=""),l=Math.max(0,l-1),o.push(`${c(l)}${y.trim()}`);continue}if(y.trimStart().startsWith("<")){o.push(...f(y,l));const b=((p=x.match(/^<\s*([a-z0-9:-]+)/))==null?void 0:p[1])||"";/\/>\s*$/.test(y)||x.startsWith("<!")||n.has(b)||(l+=1,(b==="script"||b==="style")&&(u=b));continue}if(u){const b=y.trim();b&&o.push(...b.split(`
104
- `).map($=>`${c(l)}${$.trimEnd()}`));continue}const S=y.replace(/\s+/g," ").trim();S&&o.push(`${c(l)}${S}`)}return o.join(`
105
- `)}function I1(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 jm(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 fl(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 O1=/^\s*<runtime_metadata>\s*([\s\S]*?)\s*<\/runtime_metadata>\s*/i;function mg(e){const t=typeof e=="string"?e:String(e??""),n=O1.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 ux(...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 Ap(e){if(e==null)return"";if(typeof e=="string")return e.trim();if(Array.isArray(e))return e.map(t=>Ap(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=Ap(t);if(n)return n}}return""}function dx(e){const t=mg(Ap(e));return{text:t.text,runtime_metadata:t.metadata}}function P1(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=mg(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:ux(_.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 D1(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 w=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(),y=ux(_.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:w,runtime_metadata:y})}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 F1(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 hx="inferred from the call's arguments (regex heuristic) — not a declared risk tier; declared tiers replace this when the grant API ships";function mx(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=F1(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 _x(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 px(e,t){const n=String((e==null?void 0:e.prompt)||"").trim(),i=mg(n),o=P1(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 z1(e,t){return px(e,t).text}function B1(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 hl(e){const t=String(e.status||"unknown").trim()||"unknown";return s.jsx("span",{className:`run_status_pill ${fl(t)}`,children:t})}function U1(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 Sm(e){const t=e==null?void 0:e.error;return t?typeof t=="string"?ht(t,{max_chars:220,max_lines:2}):ht(Ds(t,400),{max_chars:220,max_lines:2}):""}function W1(e){const t=U1(e);if(t)return t;const n=Sm(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 gx(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 Ty(e){const t=gx(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=fn(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=fn(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 q1(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 H1(e,t){if(!e||typeof e!="object")return null;const n=q1(e),i=gx(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=fn(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 Z=String(M||"").trim();Z&&(f[Z]=String(H??""))}const _=fn(n.filename,e.filename,i.filename,o.filename,f.filename,f.name,e.name,i.name),p=fn(n.source_path,e.source_path,i.source_path,o.source_path,e.path,i.path,f.path,f.source_path,f.file_path),w=fn(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),y=fn(n.render_kind,l.render_kind,e.render_kind,f.render_kind),x=fn(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:{},b=n.producer&&typeof n.producer=="object"?n.producer:e.producer&&typeof e.producer=="object"?e.producer:l.producer&&typeof l.producer=="object"?l.producer:{},$=n.provenance&&typeof n.provenance=="object"?n.provenance:e.provenance&&typeof e.provenance=="object"?e.provenance:l.provenance&&typeof l.provenance=="object"?l.provenance:{},E=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:{},D=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:fn(n.run_id,e.run_id,i.run_id,o.run_id,f.run_id,$.run_id),content_type:w,modality:fn(n.modality,e.modality,l.modality,f.modality)||Ty({...e,ref:i,metadata:o,tags:f}),semantic_kind:x||Ty({...e,ref:i,metadata:o,tags:f}),render_kind:y||hg({content_type:w,filename:_,source_path:p,modality:fn(n.modality,e.modality,f.modality),tags:f}),task:fn(n.task,l.task,e.task,f.task,f.provider_task),classification_source:fn(n.classification_source,l.classification_source,e.classification_source),session_id:fn(n.session_id,l.session_id,e.session_id,f.session_id),workflow_id:fn(n.workflow_id,l.workflow_id,e.workflow_id,f.workflow_id,f.workflow),node_id:fn(n.node_id,l.node_id,e.node_id,f.node_id,f.node),step_id:fn(n.step_id,l.step_id,e.step_id,f.step_id),effect_id:fn(n.effect_id,l.effect_id,e.effect_id,f.effect_id,f.effect_idempotency_key),turn_id:fn(n.turn_id,l.turn_id,e.turn_id,f.turn_id,f.turn),ledger_cursor:fn(n.ledger_cursor,l.ledger_cursor,e.ledger_cursor,f.ledger_cursor,f.step_cursor),parent_run_id:fn(n.parent_run_id,l.parent_run_id,e.parent_run_id,f.parent_run_id),actor_id:fn(n.actor_id,l.actor_id,e.actor_id,f.actor_id),title:fn(n.title,e.title,f.title,f.label,f.name),created_at:fn(n.created_at,e.created_at,i.created_at,o.created_at,f.created_at),size_bytes:k1(n.size_bytes,e.size_bytes,i.size_bytes,o.size_bytes,f.size_bytes),filename:_,source_path:p,sha256:fn(n.sha256,e.sha256,i.sha256,o.sha256,f.sha256),tags:f,producer:b,provenance:$,generation:E,media:L,source_refs:Array.isArray(n.source_refs)?n.source_refs:Array.isArray(e.source_refs)?e.source_refs:[],access:S,links:D,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(fn(n.classification_source,l.classification_source,e.classification_source))),descriptor:l,source:t,raw:e}}function Ep(e){return e.filename||e.title||(e.source_path?e.source_path.split("/").filter(Boolean).slice(-1)[0]:"")||Lt(e.artifact_id,16)}function V1(e,t){if(t==="type")return Tu(e);if(t==="run")return e.run_id||"(no run)";if(t==="turn")return Tp(e);if(t==="node")return Eu(e)||"(node unknown)";if(t==="workflow")return pg(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 uf(e)||e.source||"artifact";const n=Nn(e.created_at);return n===null?"(unknown time)":new Date(n).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}function pg(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 Eu(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 Tp(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=Eu(e),o=Nn(e==null?void 0:e.created_at),l=o===null?"unknown time":new Date(o).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}),u=e!=null&&e.run_id?Lt(String(e.run_id),10):"unknown run";return i?`${u} · ${i} · ${l}`:`${u} · ${l}`}function My(e){if(!e)return"provenance unavailable";const t=[],n=pg(e),i=Eu(e),o=uf(e),l=yx(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 sc(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 Tu(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 G1(e){return e==="html"?"HTML":e==="json"?"JSON":e==="audio"?"Unclassified audio":e==="code"?"Code":e.slice(0,1).toUpperCase()+e.slice(1)}function K1(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 Y1(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 Ry(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 J1(e){const t=_a(e.created_at),n=fa(e.created_at);return t==="—"?"Created —":`${t}${n&&n!=="—"?` (${n})`:""}`}function Ly(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=_a(n);return i==="—"?"—":i}function Iy(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=uf(e),l=Tu(e);return o?`${l} ${o}`:`${l} artifact`}function uf(e){var n;const t=e.tags||{};return String(e.task||((n=e.provenance)==null?void 0:n.source)||t.task||t.kind||t.source||e.source||"").trim()}function yx(e){var i,o,l,u,c,f,_,p;if(!e)return"";const t=fn((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=fn((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 X1(e){var t,n,i,o;return e?fn((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 Oy(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 Py(e){return e.source_path||e.filename||""}function km(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 Mp(e,t,n,i=""){const o=km(e,t,n),l=hg(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]||Tu(o)}function Ji(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 Vh(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 Bu(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 Z1(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 wx(e){if(!e||typeof e!="object")return"Ledger record";const t=String(e.node_id||"").trim(),n=String(e.status||"").trim(),i=Z1(e),o=Ji(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 wu(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):Ds(e,320),n=typeof e.duration=="number"?Number(e.duration):-1;return{text:t,duration:n}}return{text:Ds(e,320),duration:-1}}function kf(e){var u,c,f,_,p,w,y,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=b=>typeof b=="string"?b.trim():b==null?"":typeof b=="number"||typeof b=="boolean"?String(b):"",o=b=>{if(!b||typeof b!="object")return"";const $=b,E=[$.response,$.answer,$.message,$.text,$.content];for(const L of E){const D=i(L);if(D)return D}return""};if(t==="answer_user"){const b=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((y=(w=e==null?void 0:e.effect)==null?void 0:w.payload)==null?void 0:y.text)||i((S=(x=e==null?void 0:e.effect)==null?void 0:x.payload)==null?void 0:S.content);if(b)return b}if(t==="llm_call"){const b=o(n)||i(n==null?void 0:n.output)||o(n==null?void 0:n.output)||i(n==null?void 0:n.response);if(b)return b}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 cm(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 Q1(e){return!!(e&&String(e.status||"")==="waiting")}function vx(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)?Ds(c.messages,1800):"",w=typeof f.content=="string"?f.content:typeof f.response=="string"?f.response:typeof l.result=="string"?String(l.result):"",y=Nn(l.started_at),x=Nn(l.ended_at),S=Number(_.prompt_tokens??_.input_tokens??0)||0,b=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(w,{max_chars:1200,max_lines:10}),missing_response:!String(w||"").trim(),tokens:{prompt:S,completion:b,total:Number(_.total_tokens??S+b)||0},duration_ms:y!==null&&x!==null?Math.max(0,x-y):typeof f.gen_time=="number"?Number(f.gen_time)*1e3:null,status:String(l.status||"").trim(),error:l.error?Ds(l.error,500):"",raw:l})}return t.sort((o,l)=>(Nn(l.ts)??0)-(Nn(o.ts)??0))}function Dy(e){const t=e.size||18,n=lf(e.artifact),i=hg(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 eC=2,tC=Number.MAX_SAFE_INTEGER;function nC(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 sC(e){const t=String(e||"");if(typeof DOMParser>"u")return[{kind:"text",text:D_(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:D_(t)||t}]}catch{return[{kind:"text",text:D_(t)||t}]}}function F_(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 xx(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(F_,{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(F_,{tag:t.tag,attrs:t.attrs}),!o&&u?s.jsxs("span",{className:"html-tree__summary_text",children:[" ",nC(u.text)]}):null]}),o?s.jsxs("div",{className:"html-tree__children",children:[t.children.map((c,f)=>s.jsx(xx,{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(F_,{tag:t.tag,attrs:[],closing:!0})})]}):null]})}function rC(e){const t=m.useMemo(()=>sC(e.text),[e.text]),[n,i]=m.useState({mode:"folded",version:0}),o=n.mode==="unfolded"?tC:eC;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(xx,{node:u,depth:0,collapseAfterDepth:o,expansionMode:n.mode,expansionVersion:n.version},`root:${c}`))})]})}function iC(e){var i;const t=E1(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 bx(e){const t=String(e.text||""),n=bm(e.artifact,t);if(n==="json"){const i=Fm(t);if(i!==null)return s.jsx("div",{className:`${e.className} structured`,children:s.jsx(dr,{value:i,collapseAfterDepth:4,showCopy:!1})})}return n==="markdown"?s.jsx(iC,{text:t,className:e.className}):n==="html"?s.jsx(rC,{text:t,className:e.className}):s.jsx("pre",{className:`mono ${e.className}`,children:t})}function oC(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:Ep(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(bx,{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 gg(e){const t=e==null?void 0:e.waiting;return t&&typeof t=="object"?t:null}function jx(e){const t=gg(e);return String((t==null?void 0:t.reason)||(e==null?void 0:e.waiting_reason)||"").trim().toLowerCase()}function Fy(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 aC(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 Uu(e){const t=String((e==null?void 0:e.status)||"").trim().toLowerCase();if(Ci(t)||t!=="waiting")return"none";const n=gg(e),i=jx(e);return Bu(n).length?"tool_approval":i==="until"||String((e==null?void 0:e.role)||"").trim()==="controller"?"scheduled":i==="subworkflow"?"subworkflow":i==="event"?Fy(n)?"user_response":"external_event":i==="user"||Fy(n)?"user_response":"unknown_wait"}function Sx(e){const t=gg(e),n=Bu(t),i=Uu(e);return i==="tool_approval"?`Tool approval: ${aC(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 lC(e){const t=Uu(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 zy(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 cC(e,t={}){const n=t.now_ms??Date.now(),i=t.workflow_label??"",o=String(e.status||"unknown").trim().toLowerCase()||"unknown",l=Uu(e),u=Ci(o),c=fg(e,n),f=Nn(e.updated_at||e.created_at)??0,_=o==="running"&&c>=14400*1e3,p=Sx(e)||zy(e)||(e.current_node?`Current node: ${e.current_node}`:o==="running"?"Running":u?"Terminal":"No current activity reported");let w="all";l==="tool_approval"?w="tool_approval":l==="user_response"?w="user_wait":l==="scheduled"?w="scheduled":l==="subworkflow"||l==="external_event"?w="subflows":o==="failed"?w="failed":o==="running"?w="running":u&&(w="finished");const y=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",b=[e.run_id,e.workflow_id,i,e.session_id,e.parent_run_id,e.status,e.current_node,jx(e),p,zy(e)].join(" ").toLowerCase();return{run:e,run_id:String(e.run_id||"").trim(),status:o,wait_kind:l,queue:w,attention_rank:y,reason:p,expected_action:lC(e),action_label:S,search_text:b,is_terminal:u,needs_user_action:x,is_stale:_,duration_ms:c,updated_ms:f}}function uC(e,t={}){const n=t.now_ms??Date.now(),i=t.workflow_label_by_id??{};return e.map(o=>cC(o,{now_ms:n,workflow_label:i[String(o.workflow_id||"")]||String(o.workflow_id||"")}))}function dC(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 fC(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 hC(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 mC(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(()=>uC(e.runs,{workflow_label_by_id:e.workflow_label_by_id}),[e.runs,e.workflow_label_by_id]),w=m.useMemo(()=>dC(p),[p]),y=m.useMemo(()=>{const F=fC(p,{queue:t,query:i});return hC(F,l)},[p,t,i,l]),x=y.find(F=>String(F.run_id||"")===c)||y.find(F=>String(F.run_id||"")===e.selected_run_id)||y[0]||null,S=(x==null?void 0:x.run)||null,b=String((S==null?void 0:S.run_id)||"").trim(),$=String((S==null?void 0:S.session_id)||"").trim(),E=m.useMemo(()=>$?new Set(e.runs.filter(F=>String(F.session_id||"").trim()===$).map(F=>String(F.run_id||"").trim()).filter(Boolean)):new Set,[e.runs,$]),L=$?E.size:0,D=m.useMemo(()=>$?e.artifacts.filter(F=>String(F.session_id||"").trim()===$||E.has(String(F.run_id||"").trim())).length:0,[e.artifacts,$,E]),M=S!=null&&S.waiting&&typeof S.waiting=="object"?S.waiting:null,H=M?Bu(M):[],Z=(x==null?void 0:x.reason)||(M?_g(M,H):""),Y=(x==null?void 0:x.expected_action)||(M?_x(M,H):""),X=M?z1(M,null):"",re=b&&_[b]||0,ie=Ci(S==null?void 0:S.status),ue=[{key:"attention",label:"Needs attention",count:w.attention},{key:"user_wait",label:"Needs my response",count:w.user_wait},{key:"tool_approval",label:"Tool approvals",count:w.tool_approval},{key:"running",label:"Running",count:w.running},{key:"failed",label:"Failed",count:w.failed},{key:"scheduled",label:"Scheduled",count:w.scheduled},{key:"subflows",label:"Subflows / external events",count:w.subflows},{key:"finished",label:"Finished",count:w.finished},{key:"all",label:"All loaded",count:w.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:y.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:[y.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."}),y.map(F=>{const C=F.run,N=String(C.run_id||"").trim(),O=_[N]||0;return s.jsxs("div",{className:`raised runtime_ops_row ${N===b?"selected":""}`,"aria-current":N===b?"true":void 0,tabIndex:0,onClick:()=>{f(N),e.on_select_run(N)},onKeyDown:P=>{(P.key==="Enter"||P.key===" ")&&(P.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(hl,{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:fa(C.updated_at||C.created_at)}),s.jsx("span",{children:fc(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:[O.toLocaleString()," artifacts"]})]}),s.jsxs("div",{className:"runtime_ops_actions",children:[F.needs_user_action?s.jsx("button",{className:"btn primary",onClick:P=>{P.stopPropagation(),e.on_open_run(N)},children:F.action_label}):s.jsx("button",{className:"btn",onClick:P=>{P.stopPropagation(),e.on_open_run(N)},children:"Open"}),s.jsx("button",{className:"btn",onClick:P=>{P.stopPropagation(),e.on_open_ledger(N)},children:"Ledger"}),s.jsx("button",{className:"btn",onClick:P=>{P.stopPropagation(),e.on_select_run(N),e.on_open_logs()},children:"Logs"}),s.jsx("button",{className:"btn",onClick:P=>{P.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(hl,{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(b,28)})]}),s.jsxs("div",{className:"runtime_ops_decision",children:[s.jsx("strong",{children:(x==null?void 0:x.reason)||W1(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:_a(nc(S))})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Elapsed"}),s.jsx("strong",{children:fc(S)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Last event"}),s.jsx("strong",{children:_a(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()})]})]}),$?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($,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:[D.toLocaleString()," visible artifact",D===1?"":"s"]})]}),s.jsxs("div",{className:"runtime_detail_actions compact",children:[s.jsx("button",{className:"btn",onClick:()=>e.on_filter_session_artifacts($),children:"Open session artifacts"}),s.jsx("button",{className:"btn",onClick:()=>void dc($),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:Z})]}),s.jsx("p",{children:Y}),X?s.jsxs("div",{className:"runtime_ops_wait_request",children:[s.jsx("span",{children:"Request"}),s.jsx(Ni,{text:X})]}):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")}),mx(F).map(N=>s.jsxs("span",{className:"chip muted",title:hx,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(dr,{value:M,collapseAfterDepth:3,showCopy:!0})]})]}):null,Sm(S)?s.jsx("div",{className:"warn_callout",children:Sm(S)}):null,s.jsxs("div",{className:"runtime_detail_actions",children:[s.jsx("button",{className:"btn primary",onClick:()=>e.on_open_run(b),children:"Open Observe"}),s.jsx("button",{className:"btn",onClick:()=>e.on_open_ledger(b),children:"Open ledger"}),s.jsx("button",{className:"btn",onClick:()=>e.on_filter_artifacts(b),children:"Open artifacts"}),s.jsx("button",{className:"btn",onClick:e.on_open_logs,children:"Open logs"}),s.jsx("button",{className:"btn",onClick:()=>void dc(b),children:"Copy run id"})]})]}):s.jsx("div",{className:"empty_state_inline",children:"Select a run to inspect why it is active or blocked."})})]})]})}function _C(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,w=Math.min(l,_*c+e.artifacts.length),y=m.useMemo(()=>{const C={},N=e.artifact_type_facets&&Object.keys(e.artifact_type_facets).length?e.artifact_type_facets:e.artifact_facets,O=(N==null?void 0:N.semantic_kind)||{},P=(N==null?void 0:N.render_kind)||{};for(const ne of n)C[ne]=Number(O[ne]||P[ne]||0);return C.audio=Number(O.audio||0),C.other=Number(O.other||0)+Number(O.artifact||0)+Number(O.binary||0)+Number(O["(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 O=String(N.status||"").trim().toLowerCase();O==="waiting"?C.waiting.push(N):O==="running"?C.running.push(N):O==="failed"?C.failed.push(N):O==="cancelled"?C.cancelled.push(N):O==="completed"?C.completed.push(N):C.other.push(N)}return C},[e.runs]),b=t!=null&&t.run_id&&e.run_by_id[t.run_id]||null,$=e.artifact_run_filter?ji(e.run_by_id[e.artifact_run_filter],e.workflow_label_by_id):"",E=m.useMemo(()=>{var O;const C=new Set,N=((O=e.artifact_facets)==null?void 0:O.run_id)||{};for(const P of Object.keys(N))P&&P!=="(none)"&&C.add(P);for(const P of e.artifacts)P.run_id&&C.add(P.run_id);for(const P of e.active_runs)P.run_id&&C.add(String(P.run_id));return Array.from(C).map(P=>e.run_by_id[P]||{run_id:P,workflow_id:null,status:"",created_at:null,updated_at:null}).sort((P,ne)=>{const B=Ou(P.status)?0:1,z=Ou(ne.status)?0:1;if(B!==z)return B-z;const G=Nn(P.updated_at||P.created_at)??0;return(Nn(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")},D=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(O=>{var B,z;const P=O.record||{};return[O.cursor,P.run_id,P.node_id,P.status,(B=P.effect)==null?void 0:B.type,P.started_at,P.ended_at,Ds(((z=P.effect)==null?void 0:z.payload)??{},900),Ds(P.result??{},900)].join(" ").toLowerCase().includes(C)}):N},[e.runtime_ledger_log_items,e.runtime_log_query]),Z=m.useMemo(()=>{const C=e.runtime_log_query.trim().toLowerCase(),N=vx(e.runtime_ledger_log_items);return C?N.filter(O=>[O.provider,O.model,O.run_id,O.node_id,O.status,O.error,O.prompt_preview,O.response_preview,O.tokens.prompt,O.tokens.completion,O.tokens.total].join(" ").toLowerCase().includes(C)):N},[e.runtime_ledger_log_items,e.runtime_log_query]),Y=Z.reduce((C,N)=>C+(Number(N.tokens.total)||0),0),X=Z.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(O=>O.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:D(S.waiting.length)})]}),s.jsxs("div",{className:"metric_tile",children:[s.jsx("span",{children:"Running"}),s.jsx("strong",{children:D(S.running.length)})]}),s.jsxs("div",{className:"metric_tile",children:[s.jsx("span",{children:"Failed"}),s.jsx("strong",{children:D(S.failed.length)})]}),s.jsxs("div",{className:"metric_tile",children:[s.jsxs("span",{children:["Artifacts",u?" (filtered)":""]}),s.jsx("strong",{children:D(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(mC,{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),O=y[C]||0,P=G1(C);return s.jsxs("button",{type:"button","aria-pressed":N,"aria-label":`${N?"Remove":"Add"} ${P} artifact type filter. Type filters combine with OR.`,title:`${N?"Remove":"Add"} ${P}. Type filters combine with OR.`,className:`artifact_filter_chip ${N?"active":""}`,onClick:()=>x(C),children:[s.jsx("span",{children:P}),s.jsx("span",{className:"artifact_chip_count",children:e.gateway_connected?O.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:$||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 ",sc(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:E.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"})]}),E.map(C=>{const N=String(C.run_id||"").trim(),O=N===e.artifact_run_filter||N===(t==null?void 0:t.run_id);return s.jsxs("button",{className:`artifact_filter_run ${O?"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:fc(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()}-${w.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 O=N.run_id&&e.run_by_id[N.run_id]||null,P=O?ji(O,e.workflow_label_by_id):pg(N),ne=Oy(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(Dy,{artifact:N,size:18}),s.jsxs("div",{className:"artifact_row_main",children:[s.jsxs("div",{className:"artifact_row_title",children:[s.jsx("strong",{children:Iy(km(N,e.run_by_id,e.workflow_label_by_id))}),s.jsx("span",{className:"artifact_type_badge",children:Tu(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"})," ",J1(N)]}),s.jsxs("span",{children:[s.jsx("b",{children:"Size"})," ",sc(N.size_bytes)]}),s.jsxs("span",{children:[s.jsx("b",{children:"Last seen"})," ",Ly(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:[P?s.jsxs("span",{children:[s.jsx("b",{children:"Workflow"})," ",P]}):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"})," ",Tp(N)]}),Eu(N)?s.jsxs("span",{className:"mono",children:[s.jsx("b",{children:"Node"})," ",Eu(N)]}):null,uf(N)?s.jsxs("span",{children:[s.jsx("b",{children:"Source"})," ",uf(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"})," ",My(N)]})]}),Py(N)?s.jsx("div",{className:"artifact_row_path mono",children:Py(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?Mp(t,e.run_by_id,e.workflow_label_by_id,e.embedded_preview.text):Mp(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=X1(t),N=yx(t),O=Oy(t),P=Number(((z=t.access)==null?void 0:z.access_count)||0)||0,ne=fn((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=fn((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(Dy,{artifact:t,size:22}),s.jsxs("div",{children:[s.jsx("div",{className:"artifact_detail_title",children:Iy(km(t,e.run_by_id,e.workflow_label_by_id))}),s.jsxs("div",{className:"artifact_detail_subtitle",children:[Tu(t)," • ",t.render_kind||e.embedded_preview.render_kind||t.modality||"artifact"," • ",t.content_type||"unknown MIME"," • ",sc(t.size_bytes),t.legacy_inferred?" • legacy inferred":""]})]})]}),s.jsx(oC,{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:Tu(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:_a(t.created_at)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Size"}),s.jsx("strong",{children:sc(t.size_bytes)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Last seen"}),s.jsx("strong",{children:Ly(t)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Accesses"}),s.jsx("strong",{children:P?P.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:b?ji(b,e.workflow_label_by_id):"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Turn"}),s.jsx("strong",{children:Tp(t)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Node"}),s.jsx("strong",{className:"mono",children:Eu(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:O||"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Trace"}),s.jsx("strong",{children:t.provider_trace_available?"available":"not recorded"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Provenance"}),s.jsx("strong",{children:My(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(dr,{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 dc(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(dr,{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||{},O=String(((K=N==null?void 0:N.effect)==null?void 0:K.type)||"").trim(),P=String((N==null?void 0:N.status)||"").trim(),ne=String((N==null?void 0:N.node_id)||"").trim(),B=fn(N==null?void 0:N.ended_at,N==null?void 0:N.started_at,N==null?void 0:N.ts),z=Ji(N),G=wx(N),T=O?ht(Ds(((J=N==null?void 0:N.effect)==null?void 0:J.payload)??{},1200),{max_chars:1200,max_lines:6}):"",Q=kf(N)||(z?`Waiting for ${String(z.reason||"input")}`:"")||((N==null?void 0:N.result)!==void 0?Ds(N.result,700):"");return s.jsxs("article",{className:`runtime_log_event ${fl(P)}`,children:[s.jsxs("div",{className:"runtime_log_event_header",children:[s.jsxs("span",{className:"mono",children:["#",C.cursor]}),s.jsx(hl,{status:P||"record"}),O?s.jsx("span",{className:"chip mono muted",children:O}):null,ne?s.jsx("strong",{className:"mono",children:ne}):null,B?s.jsx("span",{className:"mono muted",children:_a(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||cm(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(dr,{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:Z.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:X.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&&!Z.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:Z.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:dg(C.duration_ms)}),C.status?s.jsx(hl,{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(dr,{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 Gh=30;function pC(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 By(e,t,n){if(cf(e)==="automation"){const i=String(e.automation_id||e.run_id||"").trim();return n[i]||"Automation"}return ji(e,t)}function Uy(e){const t=cf(e.run);return t?s.jsx("span",{className:"chip scheduled run_tree_tag","data-tag":t,children:rx(e.run)}):null}function gC(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(_=>Ou(_.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:By(u,e.workflow_label_by_id,e.automation_titles)}),s.jsx(Uy,{run:u}),u.status?s.jsx(hl,{status:jm(u)}):null]}),s.jsxs("div",{className:"run_tree_meta",children:[s.jsx("span",{className:"mono",children:Lt(c,13)}),s.jsx("span",{children:nc(u)?fa(nc(u)):"no start"}),s.jsx("span",{children:fc(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:By(_,e.workflow_label_by_id,e.automation_titles)}),s.jsx(Uy,{run:_}),s.jsx(hl,{status:jm(_)})]}),s.jsxs("div",{className:"run_tree_meta",children:[s.jsx("span",{className:"mono",children:Lt(p,13)}),s.jsx("span",{children:nc(_)?fa(nc(_)):"child"}),s.jsx("span",{children:fc(_)})]})]},p)})}):null]},c)})]},o.key))]})]})}function Wy(){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 yC(e){var $,E,L,D,M,H,Z;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=nc(e.run)||String((($=e.run_state)==null?void 0:$.started_at)||((E=e.run_state)==null?void 0:E.created_at)||"").trim(),u=ax(e.run)||(Ci(e.status_label)?String(((L=e.run_state)==null?void 0:L.updated_at)||"").trim():""),c=e.run?fc(e.run):l?dg((Nn(u)??Date.now())-(Nn(l)??Date.now())):"—",f=e.provider_activities.length,_=e.provider_activities.reduce((Y,X)=>Y+(Number(X.tokens.total)||0),0),p=e.provider_activities.filter(Y=>Y.missing_response||Y.error).length,w=String(((D=e.latest_summary)==null?void 0:D.text)||"").trim(),y=e.wait_state,x=Ci(e.status_label),S=Sm(e.run)||String(((M=e.run_state)==null?void 0:M.error)||"").trim();let b="";for(let Y=e.records.length-1;Y>=0;Y--){const X=kf((H=e.records[Y])==null?void 0:H.record);if(X){b=X;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(hl,{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(Wy,{}),"Folder"]}):null,s.jsx("button",{className:"btn",onClick:e.on_generate_summary,disabled:!t||e.summary_generating,children:e.summary_generating?"Summarizing…":w?"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 ${fl(e.status_label)}`,children:e.status_label||(S?"failed":"completed")})]}),S?s.jsx("div",{className:"error_callout",children:S}):null,b?s.jsx(Ni,{text:ht(b,{max_chars:4e3,max_lines:60})}):null,!S&&!b?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:[],X=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:{},O=String((C==null?void 0:C.filename)||N.filename||"").trim();if(O)return O;const P=String(N.path||(C==null?void 0:C.source_path)||"").trim();return P?P.split("/").pop()||P: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=>!X(C)),F=Y.filter(X);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(Wy,{}),"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:_a(l)})]}),s.jsxs("div",{className:"metric_tile",children:[s.jsx("span",{children:u?"Finished":"Running for"}),s.jsx("strong",{children:u?_a(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"}),y?s.jsx("span",{className:"chip mono info",children:"waiting"}):null]}),y?s.jsxs("div",{className:"overview_fact_list",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Reason"}),s.jsx("strong",{children:String(y.reason||"unknown")})]}),y.wait_key?s.jsxs("div",{children:[s.jsx("span",{children:"Wait key"}),s.jsx("strong",{className:"mono",children:Lt(String(y.wait_key),34)})]}):null,(Z=y==null?void 0:y.details)!=null&&Z.sub_run_id?s.jsxs("div",{children:[s.jsx("span",{children:"Subworkflow"}),s.jsx("strong",{className:"mono",children:Lt(String(y.details.sub_run_id),24)})]}):null,y.prompt?s.jsxs("div",{children:[s.jsx("span",{children:"Prompt"}),s.jsx("strong",{children:ht(String(y.prompt),{max_chars:260,max_lines:3})})]}):null,e.on_answer_wait&&y.wait_key&&String(y.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,X=(Y==null?void 0:Y.record)||null,re=String((X==null?void 0:X.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=X==null?void 0:X.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,w?s.jsx(Ni,{text:w}):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 X=String((Y==null?void 0:Y.artifact_id)||"").trim();if(!X)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()||X,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:X,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"})]})]},X)})}):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<=Gh?`${e.timeline_items.length} steps`:`last ${Gh} of ${e.timeline_items.length} steps`}),e.timeline_items.length>Gh?s.jsx("button",{className:"btn btn_sm",onClick:()=>i(Y=>!Y),children:n?"Show fewer":"Show all"}):null]}),s.jsx(wC,{items:n?e.timeline_items:e.timeline_items.slice(-Gh),node_index:e.node_index,workflow_label_by_id:e.workflow_label_by_id,on_copy:e.on_copy})]}):null]})}function wC(e){const t=n=>{var E,L;const i=n,o=n.record||{},l=String(((E=o==null?void 0:o.effect)==null?void 0:E.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=Ji(o),w=(L=o==null?void 0:o.effect)==null?void 0:L.payload,y=o==null?void 0:o.result,x=kf(o),S=l?Ds(w??{},900):ht(String(i.preview||""),{max_chars:900,max_lines:8}),b=x||(p?`Waiting for ${String(p.reason||"input")}${p.wait_key?` (${Lt(String(p.wait_key),18)})`:""}`:"")||(y!==void 0?Ds(y,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(b,{max_chars:1100,max_lines:9}),cls:fl(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:fa(l)}),s.jsx("span",{className:"mono",title:l,children:_a(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 vC(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(),w=fl(p),y=kf(t.data),x=!!(y&&y.trim()),S=fa(t.ts);return s.jsxs("div",{className:`lc ${w}`,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 ${w}`,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(y||"")),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(y||"")})}):null,e.open&&t.data?s.jsx("div",{className:"lc_body lc_body_json mono",children:s.jsx(dr,{value:t.data,collapseAfterDepth:3,showCopy:!1})}):null]})}class xC{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 zt=Av;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 kx(){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,...kx()}}async function Gn(e){try{const t=await e.text();return t!=null&&t.trim()?t.trim():`${e.status}`}catch{return`${e.status}`}}class bC extends Error{constructor(n,i){super(i);Gs(this,"status");this.name="GatewayRequestError",this.status=n}}async function z_(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 bC(e.status,`${t} (HTTP ${e.status}): ${i||e.statusText||"no reason given"}`)}class B_{constructor(t){Gs(this,"_cfg");Gs(this,"fetch_gateway",(t,n)=>fetch(zt(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(zt(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(),w=p==null?void 0:p.run_id;if(typeof w!="string"||!w)throw new Error("start_run: missing run_id");return w}async list_mcp_servers(){for(const t of[bt("mcp/servers"),bt("mcp"),bt("discovery/mcp")])try{const n=await fetch(zt(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(zt(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(zt(this._cfg.base_url,bt(`runs/${encodeURIComponent(t)}`)),{headers:{...Pt(this._cfg.auth_token)}});if(!n.ok)throw new Error(`get_run failed: ${await Gn(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=zt(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 Gn(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=zt(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 Gn(_)}`);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=zt(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 Gn(o)}`);return await o.json()}async gateway_about(){const t=await fetch(zt(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(zt(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 Gn(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=zt(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 Gn(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=zt(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 Gn(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(),w=String((t==null?void 0:t.content_type)||"").trim(),y=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(),b=String((t==null?void 0:t.order_by)||"").trim(),$=String((t==null?void 0:t.order)||"").trim(),E=String((t==null?void 0:t.created_after)||"").trim(),L=String((t==null?void 0:t.created_before)||"").trim(),D=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),w&&n.set("content_type",w),y&&n.set("query",y),x&&n.set("tags",x),S&&n.set("cursor",S),b&&n.set("order_by",b),$&&n.set("order",$),E&&n.set("created_after",E),L&&n.set("created_before",L),t!=null&&t.include_stats&&n.set("include_stats","true"),n.set("limit",String(D)),n.set("offset",String(M));const H=await fetch(zt(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 Gn(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(zt(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 Gn(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=zt(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 Gn(_)}`);return await _.blob()}async list_entities(){const t=await fetch(zt(this._cfg.base_url,bt("entities")),{headers:{...Pt(this._cfg.auth_token)},signal:bi()});if(!t.ok)throw new Error(`list_entities failed: ${await Gn(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(zt(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 Gn(t)}`);return await t.json()}async get_entity_cognition(t){const n=await fetch(zt(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 Gn(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(zt(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 Gn(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=zt(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 Gn(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=zt(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(zt(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(zt(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 z_(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(zt(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 z_(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(zt(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 Gn(_)}`);const p=await _.json(),w=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:w,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(zt(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 Gn(_)}`);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(zt(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 Gn(f)}`);return await f.json()}async list_bundles(){const t=await fetch(zt(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(zt(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(zt(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 Gn(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(zt(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 Gn(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=zt(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 Gn(c)}`);return await c.json()}async discovery_tools(){const t=await fetch(zt(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=zt(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(zt(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(zt(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(zt(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(zt(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(zt(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 Gn(t)}`);return await t.json()}automations_client(){const t=this._cfg.auth_token;return tS({fetch:(n,i)=>fetch(n,i),baseUrl:this._cfg.base_url,headers:()=>Pt(t)})}async submit_command(t){const n=await fetch(zt(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 w=String((t==null?void 0:t.object)||"").trim();w&&(l.object=w);const y=String((t==null?void 0:t.since)||"").trim();y&&(l.since=y);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 b=String((t==null?void 0:t.query_text)||"").trim();b&&(l.query_text=b),typeof(t==null?void 0:t.min_score)=="number"&&Number.isFinite(t.min_score)&&(l.min_score=Number(t.min_score));const $=await fetch(zt(this._cfg.base_url,bt("kg/query")),{method:"POST",headers:{"Content-Type":"application/json",...Pt(this._cfg.auth_token)},body:JSON.stringify(l)});if(!$.ok)throw new Error(`kg_query failed: ${await Gn($)}`);return await $.json()}async stream_ledger(t,n){var w;const i=Number((n==null?void 0:n.after)||0),o=n.on_step,l=n.signal,u=zt(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 z_(c,"The ledger stream was refused");if(!c.body)throw new Error("stream_ledger: response body is missing");(w=n.on_open)==null||w.call(n);const f=c.body.getReader(),_=new TextDecoder("utf-8"),p=new xC;for(;;){const{value:y,done:x}=await f.read();if(x)return;const S=_.decode(y,{stream:!0});p.push(S,b=>{if(!(b.event!=="step"||!b.data))try{const $=JSON.parse(b.data);$&&typeof $.cursor=="number"&&$.record&&o($)}catch{}})}}}function jC(e){const t=(e||"").trim();return t?{Authorization:`Bearer ${t}`}:{}}class SC{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)||Ps()),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:Ps(),method:"tools/call",params:{name:n,arguments:o}},u=await fetch(this._cfg.url,{method:"POST",headers:{"Content-Type":"application/json",...jC(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),w=(Array.isArray(f==null?void 0:f.content)?f.content:[]).find(x=>x&&x.type==="text"&&typeof x.text=="string"),y=(w==null?void 0:w.text)??"";return _?{call_id:i,name:n,success:!1,output:null,error:y||"Tool failed"}:{call_id:i,name:n,success:!0,output:y,error:null}}}class qy{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 Hy(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 kC(e,t){const n=Nn(e.updated_at||e.created_at)??0;return(Nn(t.updated_at||t.created_at)??0)-n}function NC(e,t){const n=t.query.trim().toLowerCase(),i=[...e],o={};for(const y of i){const x=String(y.run_id||"").trim();x&&(o[x]=y)}for(const y of e){const x=Hy(y);if(String(y.role||"")==="occurrence"&&x&&!o[x]){const S={run_id:x,workflow_id:null,status:"",role:"controller",session_kind:"automation",automation_id:x,updated_at:y.updated_at??null,created_at:y.created_at??null};o[x]=S,i.push(S)}}const l={},u={};for(const y of i){const x=String(y.run_id||"").trim();if(!x)continue;const S=Hy(y,t.parent_hint?t.parent_hint(x):"");u[x]=S,S&&(l[S]||(l[S]=[])).push(y)}const c=y=>{const x=String(y.status||"").trim().toLowerCase();return t.filter==="all"?!0:t.filter==="active"?Ou(x):t.filter==="waiting"?x==="waiting":t.filter==="terminal"?Ci(x):t.filter==="failed"?x==="failed":!0},f=y=>{if(!n)return!0;const x=String(y.workflow_id||y.schedule_target_workflow_id||"").trim(),S=x?t.workflow_label_by_id[x]||x:"";return[y.run_id,x,S,y.session_id,y.status,y.session_kind,y.automation_id].join(" ").toLowerCase().includes(n)},_=[];for(const y of i){const x=String(y.run_id||"").trim();if(!x)continue;const S=u[x];(!S||!o[S])&&_.push(x)}const p={},w=y=>{if(t.group_by==="workflow"){const S=String(y.schedule_target_workflow_id||y.workflow_id||"").trim()||"(unknown workflow)";return{key:S,label:t.workflow_label_by_id[S]||S}}if(t.group_by==="session"){const S=String(y.session_id||"").trim()||"(no session)";return{key:S,label:S}}const x=String(y.status||"").trim().toLowerCase()||"unknown";return Ou(x)?{key:"active",label:"Active"}:x==="failed"?{key:"failed",label:"Failed"}:Ci(x)?{key:"finished",label:"Finished"}:{key:x,label:x}};for(const y of _){const x=o[y];if(!x)continue;const S=[...l[y]||[]].sort(kC),b=S.some(E=>c(E)&&f(E));if(!(c(x)&&f(x))&&!b)continue;const $=w(x);p[$.key]||(p[$.key]={key:$.key,label:$.label,rows:[]}),p[$.key].rows.push({run:x,children:S})}return Object.values(p).sort((y,x)=>{const S={active:0,waiting:1,failed:2,finished:3},b=S[y.key]??10,$=S[x.key]??10;return b!==$?b-$:y.label.localeCompare(x.label)})}const CC={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"},$C=[{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 AC(){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:[$C.map(n=>s.jsxs("div",{className:"pin-legend-row",children:[s.jsx("span",{className:"pin-legend-shape",style:{color:CC[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 cn(e){return typeof e=="string"?e:e==null?"":String(e)}function Vy(e,t){const n=cn(e).trim();return n.length<=t?n:`${n.slice(0,Math.max(0,t-1))}…`}function Nx(e){const t=cn(e==null?void 0:e.targetHandle),n=cn(e==null?void 0:e.sourceHandle);return!!(t==="exec-in"||n==="exec-out"||t.includes("exec")||n.includes("exec"))}function Cx(e){if(!e||typeof e!="object")return"";const t=e!=null&&e.data&&typeof e.data=="object"?e.data:{};return cn((t==null?void 0:t.nodeType)||(e==null?void 0:e.type)||"").trim()}function $x(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=cn(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 EC(e){const t=cn(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(Cx(i)==="on_flow_start"){const o=cn(i==null?void 0:i.id).trim();if(o)return o}return""}function U_(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 Vd(e,t){const n=cn(e).trim(),i=cn(t).trim();return i?n?`${n}::${i}`:i:""}function TC(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:[],w=Array.isArray(u.edges)?u.edges:[];for(const y of p){const x=cn(y==null?void 0:y.id).trim();if(!x)continue;const S=Vd(c,x);if(!S||o.has(S))continue;const b=U_(y),$={...y,id:S,position:{x:b.x+f.x,y:b.y+f.y}};if(n.push($),o.add(S),n.length>=e.max_nodes)break}for(const y of w){if(!Nx(y))continue;const x=cn(y==null?void 0:y.source).trim(),S=cn(y==null?void 0:y.target).trim();if(!x||!S)continue;const b=Vd(c,x),$=Vd(c,S);if(!b||!$)continue;const E=cn(y==null?void 0:y.id).trim(),L=E?`${b}->${$}::${E}`:`${b}->${$}`;if(i.push({...y,id:L,source:b,target:$}),i.length>=e.max_edges)break}if(!(_>=e.max_depth))for(const y of p){if(n.length>=e.max_nodes||i.length>=e.max_edges)return;if(Cx(y)!=="subflow")continue;const x=$x(y);if(!x)continue;const S=e.flow_by_id[x];if(!S||typeof S!="object")continue;const b=Vd(c,cn(y==null?void 0:y.id));if(!b)continue;const $=EC(S);if(!$)continue;const L=(Array.isArray(S.nodes)?S.nodes:[]).find(re=>cn(re==null?void 0:re.id).trim()===$)||null;if(!L)continue;const D=U_(y),M=U_(L),Y={x:D.x+f.x+240-M.x,y:D.y+f.y+0-M.y},X=Vd(b,$);i.push({id:`${b}=>${X}`,source:b,target:X,sourceHandle:"exec-out",targetHandle:"exec-in"}),l(S,b,Y,_+1)}};return l(t,"",{x:0,y:0},0),{...t,id:cn(t.id),nodes:n,edges:i}}function MC(e){const t=cn(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 RC(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 Gy(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 LC(e){const t=typeof e.now_ms=="number"?e.now_ms:Date.now(),n=e.flow,i=cn(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=TC({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=cn(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=cn((Ke==null?void 0:Ke.label)||(Se==null?void 0:Se.label)||Le)||Le,Qt=cn((Ke==null?void 0:Ke.nodeType)||(Se==null?void 0:Se.type)||"unknown")||"unknown",_n=cn((Ke==null?void 0:Ke.headerColor)||(Se==null?void 0:Se.headerColor)||"")||"",Ut=Ke!=null&&Ke.eventConfig&&typeof Ke.eventConfig=="object"?Ke.eventConfig:null,It=Ut&&typeof Ut.schedule=="string"?cn(Ut.schedule).trim():"",un=Ut&&typeof Ut.recurrent=="boolean"?!!Ut.recurrent:void 0,Bn=Qt==="subflow"?$x(Se):"",Mt=It||un!==void 0||Bn?{schedule:It||void 0,recurrent:un,subflow_id:Bn||void 0}:void 0;T.push({id:Le,x:ge,y:De,label:Dt,type:Qt,color:_n,meta:Mt})}const Q={};for(const Se of T)Q[Se.id]=Se;let K=[];for(const Se of G){if(!Nx(Se))continue;const Le=cn(Se==null?void 0:Se.source).trim(),ct=cn(Se==null?void 0:Se.target).trim();!Le||!ct||K.push({id:cn((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=RC({nodes:T,edges:K,keep_id:ct=>{if(i&&ct===i)return!0;const ge=Q[ct];if(!ge)return!1;const De=cn(ge.type).trim().toLowerCase();return De==="on_flow_start"||De==="on_flow_end"||De==="subflow"?!0:!MC(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,me=56,we=fe/2,Ae=me/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+me)));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,Qt=ge.y+Ae,_n=Math.max(1,Math.hypot(Dt-De,Qt-Ke)),Ut=Math.max(28,Math.min(72,_n*.14)),It=Math.min(200,Ut*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:me};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 w=m.useRef(null),[y,x]=m.useState(()=>({x:p.x,y:p.y,w:p.w,h:p.h})),S=m.useRef(y);S.current=y,m.useEffect(()=>{x({x:p.x,y:p.y,w:p.w,h:p.h})},[p.x,p.y,p.w,p.h]);const b=m.useRef(new Map),$=m.useRef(null),E=`${y.x} ${y.y} ${y.w} ${y.h}`,L={};for(const B of f)L[B.id]=B;const D=B=>{let z=cn(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=D(i),H={};for(const[B,z]of Object.entries(o)){if(typeof z!="number")continue;const G=D(B);G&&(H[G]=Math.max(H[G]||0,z))}const Z={};if(u)for(const[B,z]of Object.entries(l)){if(typeof z!="number")continue;const G=D(B);G&&(Z[G]=typeof Z[G]=="number"?Math.min(Z[G],z):z)}const Y=cn(e.schedule_next_in).trim(),X=cn(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=cn((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||X;return Q?z&&Y?`${Q} • next ${Y}`:`every ${Q}`:z&&Y?`next ${Y}`:"scheduled"},F=B=>{var fe;const z=cn((fe=B.meta)==null?void 0:fe.subflow_id).trim(),G=z&&e.flow_by_id?e.flow_by_id[z]:null,Q=cn(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=w.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,me=B.x-oe*K,we=B.y-fe*J;x(Gy({x:me,y:we,w:K,h:J},p))},O=(B,z,G)=>{const T=G||S.current,Q=w.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(me=>Gy({x:(G||me).x-oe,y:(G||me).y-fe,w:(G||me).w,h:(G||me).h},p))},P=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,me=oe>1e-6?K/2/oe:Number.POSITIVE_INFINITY,we=Math.min(fe,me);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=w.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=w.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(AC,{})]}),s.jsxs("svg",{ref:w,className:"graph_svg",viewBox:E,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),b.current.set(B.pointerId,{x:B.clientX,y:B.clientY});const z=Array.from(b.current.values());if(z.length===1)$.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)),me={x:(Q.x+K.x)/2,y:(Q.y+K.y)/2},we=S.current;$.current={mode:"pinch",start_view:we,start_client:me,start_dist:fe,anchor_svg:C(me.x,me.y,we)}}},onPointerMove:B=>{if(!b.current.has(B.pointerId))return;b.current.set(B.pointerId,{x:B.clientX,y:B.clientY});const z=$.current;if(!z)return;const G=Array.from(b.current.values());if(z.mode==="pan"&&G.length===1){const T=B.clientX-z.start_client.x,Q=B.clientY-z.start_client.y;O(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=>{b.current.delete(B.pointerId),b.current.size===0&&($.current=null)},onPointerCancel:B=>{b.current.delete(B.pointerId),b.current.size===0&&($.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,me=ne(T,Q,oe,fe),we=ne(K,J,-oe,-fe),Ae=B.source!==B.target&&P.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=(me.x+we.x)/2+We*ct,De=(me.y+we.y)/2+_t*ct,Ke=Ae&&!Ye?`M ${me.x} ${me.y} Q ${ge} ${De} ${we.x} ${we.y}`:`M ${me.x} ${me.y} L ${we.x} ${we.y}`,Dt=u&&Z&&Z[B.source]!==void 0&&Z[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&&Z&&Z[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 me=Vy(oe,22),we=Vy(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:me}),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 W_={exports:{}},q_={},H_={exports:{}},V_={};/**
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 Ky;function IC(){if(Ky)return V_;Ky=1;var e=bf();function t(w,y){return w===y&&(w!==0||1/w===1/y)||w!==w&&y!==y}var n=typeof Object.is=="function"?Object.is:t,i=e.useState,o=e.useEffect,l=e.useLayoutEffect,u=e.useDebugValue;function c(w,y){var x=y(),S=i({inst:{value:x,getSnapshot:y}}),b=S[0].inst,$=S[1];return l(function(){b.value=x,b.getSnapshot=y,f(b)&&$({inst:b})},[w,x,y]),o(function(){return f(b)&&$({inst:b}),w(function(){f(b)&&$({inst:b})})},[w]),u(x),x}function f(w){var y=w.getSnapshot;w=w.value;try{var x=y();return!n(w,x)}catch{return!0}}function _(w,y){return y()}var p=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?_:c;return V_.useSyncExternalStore=e.useSyncExternalStore!==void 0?e.useSyncExternalStore:p,V_}var Yy;function OC(){return Yy||(Yy=1,H_.exports=IC()),H_.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 Jy;function PC(){if(Jy)return q_;Jy=1;var e=bf(),t=OC();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 q_.useSyncExternalStoreWithSelector=function(_,p,w,y,x){var S=l(null);if(S.current===null){var b={hasValue:!1,value:null};S.current=b}else b=S.current;S=c(function(){function E(Z){if(!L){if(L=!0,D=Z,Z=y(Z),x!==void 0&&b.hasValue){var Y=b.value;if(x(Y,Z))return M=Y}return M=Z}if(Y=M,i(D,Z))return Y;var X=y(Z);return x!==void 0&&x(Y,X)?(D=Z,Y):(D=Z,M=X)}var L=!1,D,M,H=w===void 0?null:w;return[function(){return E(p())},H===null?void 0:function(){return E(H())}]},[p,w,y,x]);var $=o(_,S[0],S[1]);return u(function(){b.hasValue=!0,b.value=$},[$]),f($),$},q_}var Xy;function DC(){return Xy||(Xy=1,W_.exports=PC()),W_.exports}var FC=DC();const zC=tg(FC),BC={},Zy=e=>{let t;const n=new Set,i=(p,w)=>{const y=typeof p=="function"?p(t):p;if(!Object.is(y,t)){const x=t;t=w??(typeof y!="object"||y===null)?y:Object.assign({},t,y),n.forEach(S=>S(t,x))}},o=()=>t,f={setState:i,getState:o,getInitialState:()=>_,subscribe:p=>(n.add(p),()=>n.delete(p)),destroy:()=>{(BC?"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},UC=e=>e?Zy(e):Zy,{useDebugValue:WC}=ve,{useSyncExternalStoreWithSelector:qC}=zC,HC=e=>e;function Ax(e,t=HC,n){const i=qC(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return WC(i),i}const Qy=(e,t)=>{const n=UC(e),i=(o,l=t)=>Ax(n,o,l);return Object.assign(i,n),i},VC=(e,t)=>e?Qy(e,t):Qy;function Fs(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 GC={value:()=>{}};function Wm(){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 um(n)}function um(e){this._=e}function KC(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}})}um.prototype=Wm.prototype={constructor:um,on:function(e,t){var n=this._,i=KC(e+"",n),o,l=-1,u=i.length;if(arguments.length<2){for(;++l<u;)if((o=(e=i[l]).type)&&(o=YC(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]=ew(n[o],e.name,t);else if(t==null)for(o in n)n[o]=ew(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 um(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 YC(e,t){for(var n=0,i=e.length,o;n<i;++n)if((o=e[n]).name===t)return o.value}function ew(e,t,n){for(var i=0,o=e.length;i<o;++i)if(e[i].name===t){e[i]=GC,e=e.slice(0,i).concat(e.slice(i+1));break}return n!=null&&e.push({name:t,value:n}),e}var Rp="http://www.w3.org/1999/xhtml";const tw={svg:"http://www.w3.org/2000/svg",xhtml:Rp,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function qm(e){var t=e+="",n=t.indexOf(":");return n>=0&&(t=e.slice(0,n))!=="xmlns"&&(e=e.slice(n+1)),tw.hasOwnProperty(t)?{space:tw[t],local:e}:e}function JC(e){return function(){var t=this.ownerDocument,n=this.namespaceURI;return n===Rp&&t.documentElement.namespaceURI===Rp?t.createElement(e):t.createElementNS(n,e)}}function XC(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function Ex(e){var t=qm(e);return(t.local?XC:JC)(t)}function ZC(){}function yg(e){return e==null?ZC:function(){return this.querySelector(e)}}function QC(e){typeof e!="function"&&(e=yg(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 ii(i,this._parents)}function e2(e){return e==null?[]:Array.isArray(e)?e:Array.from(e)}function t2(){return[]}function Tx(e){return e==null?t2:function(){return this.querySelectorAll(e)}}function n2(e){return function(){return e2(e.apply(this,arguments))}}function s2(e){typeof e=="function"?e=n2(e):e=Tx(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 ii(i,o)}function Mx(e){return function(){return this.matches(e)}}function Rx(e){return function(t){return t.matches(e)}}var r2=Array.prototype.find;function i2(e){return function(){return r2.call(this.children,e)}}function o2(){return this.firstElementChild}function a2(e){return this.select(e==null?o2:i2(typeof e=="function"?e:Rx(e)))}var l2=Array.prototype.filter;function c2(){return Array.from(this.children)}function u2(e){return function(){return l2.call(this.children,e)}}function d2(e){return this.selectAll(e==null?c2:u2(typeof e=="function"?e:Rx(e)))}function f2(e){typeof e!="function"&&(e=Mx(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 ii(i,this._parents)}function Lx(e){return new Array(e.length)}function h2(){return new ii(this._enter||this._groups.map(Lx),this._parents)}function Nm(e,t){this.ownerDocument=e.ownerDocument,this.namespaceURI=e.namespaceURI,this._next=null,this._parent=e,this.__data__=t}Nm.prototype={constructor:Nm,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 m2(e){return function(){return e}}function _2(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 Nm(e,l[u]);for(;u<f;++u)(c=t[u])&&(o[u]=c)}function p2(e,t,n,i,o,l,u){var c,f,_=new Map,p=t.length,w=l.length,y=new Array(p),x;for(c=0;c<p;++c)(f=t[c])&&(y[c]=x=u.call(f,f.__data__,c,t)+"",_.has(x)?o[c]=f:_.set(x,f));for(c=0;c<w;++c)x=u.call(e,l[c],c,l)+"",(f=_.get(x))?(i[c]=f,f.__data__=l[c],_.delete(x)):n[c]=new Nm(e,l[c]);for(c=0;c<p;++c)(f=t[c])&&_.get(y[c])===f&&(o[c]=f)}function g2(e){return e.__data__}function y2(e,t){if(!arguments.length)return Array.from(this,g2);var n=t?p2:_2,i=this._parents,o=this._groups;typeof e!="function"&&(e=m2(e));for(var l=o.length,u=new Array(l),c=new Array(l),f=new Array(l),_=0;_<l;++_){var p=i[_],w=o[_],y=w.length,x=w2(e.call(p,p&&p.__data__,_,i)),S=x.length,b=c[_]=new Array(S),$=u[_]=new Array(S),E=f[_]=new Array(y);n(p,w,b,$,E,x,t);for(var L=0,D=0,M,H;L<S;++L)if(M=b[L]){for(L>=D&&(D=L+1);!(H=$[D])&&++D<S;);M._next=H||null}}return u=new ii(u,i),u._enter=c,u._exit=f,u}function w2(e){return typeof e=="object"&&"length"in e?e:Array.from(e)}function v2(){return new ii(this._exit||this._groups.map(Lx),this._parents)}function x2(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 b2(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],w=_.length,y=c[f]=new Array(w),x,S=0;S<w;++S)(x=_[S]||p[S])&&(y[S]=x);for(;f<o;++f)c[f]=n[f];return new ii(c,this._parents)}function j2(){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 S2(e){e||(e=k2);function t(w,y){return w&&y?e(w.__data__,y.__data__):!w-!y}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 ii(o,this._parents).order()}function k2(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}function N2(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this}function C2(){return Array.from(this)}function $2(){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 A2(){let e=0;for(const t of this)++e;return e}function E2(){return!this.node()}function T2(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 M2(e){return function(){this.removeAttribute(e)}}function R2(e){return function(){this.removeAttributeNS(e.space,e.local)}}function L2(e,t){return function(){this.setAttribute(e,t)}}function I2(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function O2(e,t){return function(){var n=t.apply(this,arguments);n==null?this.removeAttribute(e):this.setAttribute(e,n)}}function P2(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 D2(e,t){var n=qm(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?R2:M2:typeof t=="function"?n.local?P2:O2:n.local?I2:L2)(n,t))}function Ix(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function F2(e){return function(){this.style.removeProperty(e)}}function z2(e,t,n){return function(){this.style.setProperty(e,t,n)}}function B2(e,t,n){return function(){var i=t.apply(this,arguments);i==null?this.style.removeProperty(e):this.style.setProperty(e,i,n)}}function U2(e,t,n){return arguments.length>1?this.each((t==null?F2:typeof t=="function"?B2:z2)(e,t,n??"")):Du(this.node(),e)}function Du(e,t){return e.style.getPropertyValue(t)||Ix(e).getComputedStyle(e,null).getPropertyValue(t)}function W2(e){return function(){delete this[e]}}function q2(e,t){return function(){this[e]=t}}function H2(e,t){return function(){var n=t.apply(this,arguments);n==null?delete this[e]:this[e]=n}}function V2(e,t){return arguments.length>1?this.each((t==null?W2:typeof t=="function"?H2:q2)(e,t)):this.node()[e]}function Ox(e){return e.trim().split(/^|\s+/)}function wg(e){return e.classList||new Px(e)}function Px(e){this._node=e,this._names=Ox(e.getAttribute("class")||"")}Px.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 Dx(e,t){for(var n=wg(e),i=-1,o=t.length;++i<o;)n.add(t[i])}function Fx(e,t){for(var n=wg(e),i=-1,o=t.length;++i<o;)n.remove(t[i])}function G2(e){return function(){Dx(this,e)}}function K2(e){return function(){Fx(this,e)}}function Y2(e,t){return function(){(t.apply(this,arguments)?Dx:Fx)(this,e)}}function J2(e,t){var n=Ox(e+"");if(arguments.length<2){for(var i=wg(this.node()),o=-1,l=n.length;++o<l;)if(!i.contains(n[o]))return!1;return!0}return this.each((typeof t=="function"?Y2:t?G2:K2)(n,t))}function X2(){this.textContent=""}function Z2(e){return function(){this.textContent=e}}function Q2(e){return function(){var t=e.apply(this,arguments);this.textContent=t??""}}function e$(e){return arguments.length?this.each(e==null?X2:(typeof e=="function"?Q2:Z2)(e)):this.node().textContent}function t$(){this.innerHTML=""}function n$(e){return function(){this.innerHTML=e}}function s$(e){return function(){var t=e.apply(this,arguments);this.innerHTML=t??""}}function r$(e){return arguments.length?this.each(e==null?t$:(typeof e=="function"?s$:n$)(e)):this.node().innerHTML}function i$(){this.nextSibling&&this.parentNode.appendChild(this)}function o$(){return this.each(i$)}function a$(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function l$(){return this.each(a$)}function c$(e){var t=typeof e=="function"?e:Ex(e);return this.select(function(){return this.appendChild(t.apply(this,arguments))})}function u$(){return null}function d$(e,t){var n=typeof e=="function"?e:Ex(e),i=t==null?u$:typeof t=="function"?t:yg(t);return this.select(function(){return this.insertBefore(n.apply(this,arguments),i.apply(this,arguments)||null)})}function f$(){var e=this.parentNode;e&&e.removeChild(this)}function h$(){return this.each(f$)}function m$(){var e=this.cloneNode(!1),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function _$(){var e=this.cloneNode(!0),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function p$(e){return this.select(e?_$:m$)}function g$(e){return arguments.length?this.property("__data__",e):this.node().__data__}function y$(e){return function(t){e.call(this,t,this.__data__)}}function w$(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 v$(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 x$(e,t,n){return function(){var i=this.__on,o,l=y$(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 b$(e,t,n){var i=w$(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?x$:v$,o=0;o<l;++o)this.each(c(i[o],t,n));return this}function zx(e,t,n){var i=Ix(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 j$(e,t){return function(){return zx(this,e,t)}}function S$(e,t){return function(){return zx(this,e,t.apply(this,arguments))}}function k$(e,t){return this.each((typeof t=="function"?S$:j$)(e,t))}function*N$(){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 Bx=[null];function ii(e,t){this._groups=e,this._parents=t}function Nf(){return new ii([[document.documentElement]],Bx)}function C$(){return this}ii.prototype=Nf.prototype={constructor:ii,select:QC,selectAll:s2,selectChild:a2,selectChildren:d2,filter:f2,data:y2,enter:h2,exit:v2,join:x2,merge:b2,selection:C$,order:j2,sort:S2,call:N2,nodes:C2,node:$2,size:A2,empty:E2,each:T2,attr:D2,style:U2,property:V2,classed:J2,text:e$,html:r$,raise:o$,lower:l$,append:c$,insert:d$,remove:h$,clone:p$,datum:g$,on:b$,dispatch:k$,[Symbol.iterator]:N$};function Si(e){return typeof e=="string"?new ii([[document.querySelector(e)]],[document.documentElement]):new ii([[e]],Bx)}function $$(e){let t;for(;t=e.sourceEvent;)e=t;return e}function Xi(e,t){if(e=$$(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 A$={passive:!1},df={capture:!0,passive:!1};function G_(e){e.stopImmediatePropagation()}function Mu(e){e.preventDefault(),e.stopImmediatePropagation()}function Ux(e){var t=e.document.documentElement,n=Si(e).on("dragstart.drag",Mu,df);"onselectstart"in t?n.on("selectstart.drag",Mu,df):(t.__noselect=t.style.MozUserSelect,t.style.MozUserSelect="none")}function Wx(e,t){var n=e.document.documentElement,i=Si(e).on("dragstart.drag",null);t&&(i.on("click.drag",Mu,df),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 Kh=e=>()=>e;function Lp(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}})}Lp.prototype.on=function(){var e=this._.on.apply(this._,arguments);return e===this._?this:e};function E$(e){return!e.ctrlKey&&!e.button}function T$(){return this.parentNode}function M$(e,t){return t??{x:e.x,y:e.y}}function R$(){return navigator.maxTouchPoints||"ontouchstart"in this}function L$(){var e=E$,t=T$,n=M$,i=R$,o={},l=Wm("start","drag","end"),u=0,c,f,_,p,w=0;function y(M){M.on("mousedown.drag",x).filter(i).on("touchstart.drag",$).on("touchmove.drag",E,A$).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 Z=D(this,t.call(this,M,H),M,H,"mouse");Z&&(Si(M.view).on("mousemove.drag",S,df).on("mouseup.drag",b,df),Ux(M.view),G_(M),_=!1,c=M.clientX,f=M.clientY,Z("start",M))}}function S(M){if(Mu(M),!_){var H=M.clientX-c,Z=M.clientY-f;_=H*H+Z*Z>w}o.mouse("drag",M)}function b(M){Si(M.view).on("mousemove.drag mouseup.drag",null),Wx(M.view,_),Mu(M),o.mouse("end",M)}function $(M,H){if(e.call(this,M,H)){var Z=M.changedTouches,Y=t.call(this,M,H),X=Z.length,re,ie;for(re=0;re<X;++re)(ie=D(this,Y,M,H,Z[re].identifier,Z[re]))&&(G_(M),ie("start",M,Z[re]))}}function E(M){var H=M.changedTouches,Z=H.length,Y,X;for(Y=0;Y<Z;++Y)(X=o[H[Y].identifier])&&(Mu(M),X("drag",M,H[Y]))}function L(M){var H=M.changedTouches,Z=H.length,Y,X;for(p&&clearTimeout(p),p=setTimeout(function(){p=null},500),Y=0;Y<Z;++Y)(X=o[H[Y].identifier])&&(G_(M),X("end",M,H[Y]))}function D(M,H,Z,Y,X,re){var ie=l.copy(),ue=Xi(re||Z,H),F,C,N;if((N=n.call(M,new Lp("beforestart",{sourceEvent:Z,target:y,identifier:X,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 O(P,ne,B){var z=ue,G;switch(P){case"start":o[X]=O,G=u++;break;case"end":delete o[X],--u;case"drag":ue=Xi(B||ne,H),G=u;break}ie.call(P,M,new Lp(P,{sourceEvent:ne,subject:N,target:y,identifier:X,active:G,x:ue[0]+F,y:ue[1]+C,dx:ue[0]-z[0],dy:ue[1]-z[1],dispatch:ie}),Y)}}return y.filter=function(M){return arguments.length?(e=typeof M=="function"?M:Kh(!!M),y):e},y.container=function(M){return arguments.length?(t=typeof M=="function"?M:Kh(M),y):t},y.subject=function(M){return arguments.length?(n=typeof M=="function"?M:Kh(M),y):n},y.touchable=function(M){return arguments.length?(i=typeof M=="function"?M:Kh(!!M),y):i},y.on=function(){var M=l.on.apply(l,arguments);return M===l?y:M},y.clickDistance=function(M){return arguments.length?(w=(M=+M)*M,y):Math.sqrt(w)},y}function vg(e,t,n){e.prototype=t.prototype=n,n.constructor=e}function qx(e,t){var n=Object.create(e.prototype);for(var i in t)n[i]=t[i];return n}function Cf(){}var ff=.7,Cm=1/ff,Ru="\\s*([+-]?\\d+)\\s*",hf="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",Mo="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",I$=/^#([0-9a-f]{3,8})$/,O$=new RegExp(`^rgb\\(${Ru},${Ru},${Ru}\\)$`),P$=new RegExp(`^rgb\\(${Mo},${Mo},${Mo}\\)$`),D$=new RegExp(`^rgba\\(${Ru},${Ru},${Ru},${hf}\\)$`),F$=new RegExp(`^rgba\\(${Mo},${Mo},${Mo},${hf}\\)$`),z$=new RegExp(`^hsl\\(${hf},${Mo},${Mo}\\)$`),B$=new RegExp(`^hsla\\(${hf},${Mo},${Mo},${hf}\\)$`),nw={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};vg(Cf,mf,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:sw,formatHex:sw,formatHex8:U$,formatHsl:W$,formatRgb:rw,toString:rw});function sw(){return this.rgb().formatHex()}function U$(){return this.rgb().formatHex8()}function W$(){return Hx(this).formatHsl()}function rw(){return this.rgb().formatRgb()}function mf(e){var t,n;return e=(e+"").trim().toLowerCase(),(t=I$.exec(e))?(n=t[1].length,t=parseInt(t[1],16),n===6?iw(t):n===3?new Gr(t>>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):n===8?Yh(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?Yh(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=O$.exec(e))?new Gr(t[1],t[2],t[3],1):(t=P$.exec(e))?new Gr(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=D$.exec(e))?Yh(t[1],t[2],t[3],t[4]):(t=F$.exec(e))?Yh(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=z$.exec(e))?lw(t[1],t[2]/100,t[3]/100,1):(t=B$.exec(e))?lw(t[1],t[2]/100,t[3]/100,t[4]):nw.hasOwnProperty(e)?iw(nw[e]):e==="transparent"?new Gr(NaN,NaN,NaN,0):null}function iw(e){return new Gr(e>>16&255,e>>8&255,e&255,1)}function Yh(e,t,n,i){return i<=0&&(e=t=n=NaN),new Gr(e,t,n,i)}function q$(e){return e instanceof Cf||(e=mf(e)),e?(e=e.rgb(),new Gr(e.r,e.g,e.b,e.opacity)):new Gr}function Ip(e,t,n,i){return arguments.length===1?q$(e):new Gr(e,t,n,i??1)}function Gr(e,t,n,i){this.r=+e,this.g=+t,this.b=+n,this.opacity=+i}vg(Gr,Ip,qx(Cf,{brighter(e){return e=e==null?Cm:Math.pow(Cm,e),new Gr(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=e==null?ff:Math.pow(ff,e),new Gr(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new Gr(cc(this.r),cc(this.g),cc(this.b),$m(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:ow,formatHex:ow,formatHex8:H$,formatRgb:aw,toString:aw}));function ow(){return`#${rc(this.r)}${rc(this.g)}${rc(this.b)}`}function H$(){return`#${rc(this.r)}${rc(this.g)}${rc(this.b)}${rc((isNaN(this.opacity)?1:this.opacity)*255)}`}function aw(){const e=$m(this.opacity);return`${e===1?"rgb(":"rgba("}${cc(this.r)}, ${cc(this.g)}, ${cc(this.b)}${e===1?")":`, ${e})`}`}function $m(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function cc(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function rc(e){return e=cc(e),(e<16?"0":"")+e.toString(16)}function lw(e,t,n,i){return i<=0?e=t=n=NaN:n<=0||n>=1?e=t=NaN:t<=0&&(e=NaN),new Qi(e,t,n,i)}function Hx(e){if(e instanceof Qi)return new Qi(e.h,e.s,e.l,e.opacity);if(e instanceof Cf||(e=mf(e)),!e)return new Qi;if(e instanceof Qi)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 Qi(u,c,f,e.opacity)}function V$(e,t,n,i){return arguments.length===1?Hx(e):new Qi(e,t,n,i??1)}function Qi(e,t,n,i){this.h=+e,this.s=+t,this.l=+n,this.opacity=+i}vg(Qi,V$,qx(Cf,{brighter(e){return e=e==null?Cm:Math.pow(Cm,e),new Qi(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?ff:Math.pow(ff,e),new Qi(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 Gr(K_(e>=240?e-240:e+120,o,i),K_(e,o,i),K_(e<120?e+240:e-120,o,i),this.opacity)},clamp(){return new Qi(cw(this.h),Jh(this.s),Jh(this.l),$m(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=$m(this.opacity);return`${e===1?"hsl(":"hsla("}${cw(this.h)}, ${Jh(this.s)*100}%, ${Jh(this.l)*100}%${e===1?")":`, ${e})`}`}}));function cw(e){return e=(e||0)%360,e<0?e+360:e}function Jh(e){return Math.max(0,Math.min(1,e||0))}function K_(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 Vx=e=>()=>e;function G$(e,t){return function(n){return e+n*t}}function K$(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 Y$(e){return(e=+e)==1?Gx:function(t,n){return n-t?K$(t,n,e):Vx(isNaN(t)?n:t)}}function Gx(e,t){var n=t-e;return n?G$(e,n):Vx(isNaN(e)?t:e)}const uw=(function e(t){var n=Y$(t);function i(o,l){var u=n((o=Ip(o)).r,(l=Ip(l)).r),c=n(o.g,l.g),f=n(o.b,l.b),_=Gx(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 ol(e,t){return e=+e,t=+t,function(n){return e*(1-n)+t*n}}var Op=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,Y_=new RegExp(Op.source,"g");function J$(e){return function(){return e}}function X$(e){return function(t){return e(t)+""}}function Z$(e,t){var n=Op.lastIndex=Y_.lastIndex=0,i,o,l,u=-1,c=[],f=[];for(e=e+"",t=t+"";(i=Op.exec(e))&&(o=Y_.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:ol(i,o)})),n=Y_.lastIndex;return n<t.length&&(l=t.slice(n),c[u]?c[u]+=l:c[++u]=l),c.length<2?f[0]?X$(f[0].x):J$(t):(t=f.length,function(_){for(var p=0,w;p<t;++p)c[(w=f[p]).i]=w.x(_);return c.join("")})}var dw=180/Math.PI,Pp={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function Kx(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)*dw,skewX:Math.atan(f)*dw,scaleX:u,scaleY:c}}var Xh;function Q$(e){const t=new(typeof DOMMatrix=="function"?DOMMatrix:WebKitCSSMatrix)(e+"");return t.isIdentity?Pp:Kx(t.a,t.b,t.c,t.d,t.e,t.f)}function eA(e){return e==null||(Xh||(Xh=document.createElementNS("http://www.w3.org/2000/svg","g")),Xh.setAttribute("transform",e),!(e=Xh.transform.baseVal.consolidate()))?Pp:(e=e.matrix,Kx(e.a,e.b,e.c,e.d,e.e,e.f))}function Yx(e,t,n,i){function o(_){return _.length?_.pop()+" ":""}function l(_,p,w,y,x,S){if(_!==w||p!==y){var b=x.push("translate(",null,t,null,n);S.push({i:b-4,x:ol(_,w)},{i:b-2,x:ol(p,y)})}else(w||y)&&x.push("translate("+w+t+y+n)}function u(_,p,w,y){_!==p?(_-p>180?p+=360:p-_>180&&(_+=360),y.push({i:w.push(o(w)+"rotate(",null,i)-2,x:ol(_,p)})):p&&w.push(o(w)+"rotate("+p+i)}function c(_,p,w,y){_!==p?y.push({i:w.push(o(w)+"skewX(",null,i)-2,x:ol(_,p)}):p&&w.push(o(w)+"skewX("+p+i)}function f(_,p,w,y,x,S){if(_!==w||p!==y){var b=x.push(o(x)+"scale(",null,",",null,")");S.push({i:b-4,x:ol(_,w)},{i:b-2,x:ol(p,y)})}else(w!==1||y!==1)&&x.push(o(x)+"scale("+w+","+y+")")}return function(_,p){var w=[],y=[];return _=e(_),p=e(p),l(_.translateX,_.translateY,p.translateX,p.translateY,w,y),u(_.rotate,p.rotate,w,y),c(_.skewX,p.skewX,w,y),f(_.scaleX,_.scaleY,p.scaleX,p.scaleY,w,y),_=p=null,function(x){for(var S=-1,b=y.length,$;++S<b;)w[($=y[S]).i]=$.x(x);return w.join("")}}}var tA=Yx(Q$,"px, ","px)","deg)"),nA=Yx(eA,", ",")",")"),sA=1e-12;function fw(e){return((e=Math.exp(e))+1/e)/2}function rA(e){return((e=Math.exp(e))-1/e)/2}function iA(e){return((e=Math.exp(2*e))-1)/(e+1)}const oA=(function e(t,n,i){function o(l,u){var c=l[0],f=l[1],_=l[2],p=u[0],w=u[1],y=u[2],x=p-c,S=w-f,b=x*x+S*S,$,E;if(b<sA)E=Math.log(y/_)/t,$=function(Y){return[c+Y*x,f+Y*S,_*Math.exp(t*Y*E)]};else{var L=Math.sqrt(b),D=(y*y-_*_+i*b)/(2*_*n*L),M=(y*y-_*_-i*b)/(2*y*n*L),H=Math.log(Math.sqrt(D*D+1)-D),Z=Math.log(Math.sqrt(M*M+1)-M);E=(Z-H)/t,$=function(Y){var X=Y*E,re=fw(H),ie=_/(n*L)*(re*iA(t*X+H)-rA(H));return[c+ie*x,f+ie*S,_*re/fw(t*X+H)]}}return $.duration=E*1e3*t/Math.SQRT2,$}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 Fu=0,rf=0,Gd=0,Jx=1e3,Am,of,Em=0,hc=0,Hm=0,_f=typeof performance=="object"&&performance.now?performance:Date,Xx=typeof window=="object"&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(e){setTimeout(e,17)};function xg(){return hc||(Xx(aA),hc=_f.now()+Hm)}function aA(){hc=0}function Tm(){this._call=this._time=this._next=null}Tm.prototype=Zx.prototype={constructor:Tm,restart:function(e,t,n){if(typeof e!="function")throw new TypeError("callback is not a function");n=(n==null?xg():+n)+(t==null?0:+t),!this._next&&of!==this&&(of?of._next=this:Am=this,of=this),this._call=e,this._time=n,Dp()},stop:function(){this._call&&(this._call=null,this._time=1/0,Dp())}};function Zx(e,t,n){var i=new Tm;return i.restart(e,t,n),i}function lA(){xg(),++Fu;for(var e=Am,t;e;)(t=hc-e._time)>=0&&e._call.call(void 0,t),e=e._next;--Fu}function hw(){hc=(Em=_f.now())+Hm,Fu=rf=0;try{lA()}finally{Fu=0,uA(),hc=0}}function cA(){var e=_f.now(),t=e-Em;t>Jx&&(Hm-=t,Em=e)}function uA(){for(var e,t=Am,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:Am=n);of=e,Dp(i)}function Dp(e){if(!Fu){rf&&(rf=clearTimeout(rf));var t=e-hc;t>24?(e<1/0&&(rf=setTimeout(hw,e-_f.now()-Hm)),Gd&&(Gd=clearInterval(Gd))):(Gd||(Em=_f.now(),Gd=setInterval(cA,Jx)),Fu=1,Xx(hw))}}function mw(e,t,n){var i=new Tm;return t=t==null?0:+t,i.restart(o=>{i.stop(),e(o+t)},t,n),i}var dA=Wm("start","end","cancel","interrupt"),fA=[],Qx=0,_w=1,Fp=2,dm=3,pw=4,zp=5,fm=6;function Vm(e,t,n,i,o,l){var u=e.__transition;if(!u)e.__transition={};else if(n in u)return;hA(e,n,{name:t,index:i,group:o,on:dA,tween:fA,time:l.time,delay:l.delay,duration:l.duration,ease:l.ease,timer:null,state:Qx})}function bg(e,t){var n=no(e,t);if(n.state>Qx)throw new Error("too late; already scheduled");return n}function Ro(e,t){var n=no(e,t);if(n.state>dm)throw new Error("too late; already running");return n}function no(e,t){var n=e.__transition;if(!n||!(n=n[t]))throw new Error("transition not found");return n}function hA(e,t,n){var i=e.__transition,o;i[t]=n,n.timer=Zx(l,0,n.time);function l(_){n.state=_w,n.timer.restart(u,n.delay,n.time),n.delay<=_&&u(_-n.delay)}function u(_){var p,w,y,x;if(n.state!==_w)return f();for(p in i)if(x=i[p],x.name===n.name){if(x.state===dm)return mw(u);x.state===pw?(x.state=fm,x.timer.stop(),x.on.call("interrupt",e,e.__data__,x.index,x.group),delete i[p]):+p<t&&(x.state=fm,x.timer.stop(),x.on.call("cancel",e,e.__data__,x.index,x.group),delete i[p])}if(mw(function(){n.state===dm&&(n.state=pw,n.timer.restart(c,n.delay,n.time),c(_))}),n.state=Fp,n.on.call("start",e,e.__data__,n.index,n.group),n.state===Fp){for(n.state=dm,o=new Array(y=n.tween.length),p=0,w=-1;p<y;++p)(x=n.tween[p].value.call(e,e.__data__,n.index,n.group))&&(o[++w]=x);o.length=w+1}}function c(_){for(var p=_<n.duration?n.ease.call(null,_/n.duration):(n.timer.restart(f),n.state=zp,1),w=-1,y=o.length;++w<y;)o[w].call(e,p);n.state===zp&&(n.on.call("end",e,e.__data__,n.index,n.group),f())}function f(){n.state=fm,n.timer.stop(),delete i[t];for(var _ in i)return;delete e.__transition}}function hm(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>Fp&&i.state<zp,i.state=fm,i.timer.stop(),i.on.call(o?"interrupt":"cancel",e,e.__data__,i.index,i.group),delete n[u]}l&&delete e.__transition}}function mA(e){return this.each(function(){hm(this,e)})}function _A(e,t){var n,i;return function(){var o=Ro(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 pA(e,t,n){var i,o;if(typeof n!="function")throw new Error;return function(){var l=Ro(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 gA(e,t){var n=this._id;if(e+="",arguments.length<2){for(var i=no(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?_A:pA)(n,e,t))}function jg(e,t,n){var i=e._id;return e.each(function(){var o=Ro(this,i);(o.value||(o.value={}))[t]=n.apply(this,arguments)}),function(o){return no(o,i).value[t]}}function eb(e,t){var n;return(typeof t=="number"?ol:t instanceof mf?uw:(n=mf(t))?(t=n,uw):Z$)(e,t)}function yA(e){return function(){this.removeAttribute(e)}}function wA(e){return function(){this.removeAttributeNS(e.space,e.local)}}function vA(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 xA(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 bA(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 jA(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 SA(e,t){var n=qm(e),i=n==="transform"?nA:eb;return this.attrTween(e,typeof t=="function"?(n.local?jA:bA)(n,i,jg(this,"attr."+e,t)):t==null?(n.local?wA:yA)(n):(n.local?xA:vA)(n,i,t))}function kA(e,t){return function(n){this.setAttribute(e,t.call(this,n))}}function NA(e,t){return function(n){this.setAttributeNS(e.space,e.local,t.call(this,n))}}function CA(e,t){var n,i;function o(){var l=t.apply(this,arguments);return l!==i&&(n=(i=l)&&NA(e,l)),n}return o._value=t,o}function $A(e,t){var n,i;function o(){var l=t.apply(this,arguments);return l!==i&&(n=(i=l)&&kA(e,l)),n}return o._value=t,o}function AA(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=qm(e);return this.tween(n,(i.local?CA:$A)(i,t))}function EA(e,t){return function(){bg(this,e).delay=+t.apply(this,arguments)}}function TA(e,t){return t=+t,function(){bg(this,e).delay=t}}function MA(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?EA:TA)(t,e)):no(this.node(),t).delay}function RA(e,t){return function(){Ro(this,e).duration=+t.apply(this,arguments)}}function LA(e,t){return t=+t,function(){Ro(this,e).duration=t}}function IA(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?RA:LA)(t,e)):no(this.node(),t).duration}function OA(e,t){if(typeof t!="function")throw new Error;return function(){Ro(this,e).ease=t}}function PA(e){var t=this._id;return arguments.length?this.each(OA(t,e)):no(this.node(),t).ease}function DA(e,t){return function(){var n=t.apply(this,arguments);if(typeof n!="function")throw new Error;Ro(this,e).ease=n}}function FA(e){if(typeof e!="function")throw new Error;return this.each(DA(this._id,e))}function zA(e){typeof e!="function"&&(e=Mx(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 pa(i,this._parents,this._name,this._id)}function BA(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,w=u[c]=new Array(p),y,x=0;x<p;++x)(y=f[x]||_[x])&&(w[x]=y);for(;c<i;++c)u[c]=t[c];return new pa(u,this._parents,this._name,this._id)}function UA(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 WA(e,t,n){var i,o,l=UA(t)?bg:Ro;return function(){var u=l(this,e),c=u.on;c!==i&&(o=(i=c).copy()).on(t,n),u.on=o}}function qA(e,t){var n=this._id;return arguments.length<2?no(this.node(),n).on.on(e):this.each(WA(n,e,t))}function HA(e){return function(){var t=this.parentNode;for(var n in this.__transition)if(+n!==e)return;t&&t.removeChild(this)}}function VA(){return this.on("end.remove",HA(this._id))}function GA(e){var t=this._name,n=this._id;typeof e!="function"&&(e=yg(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,w,y=0;y<f;++y)(p=c[y])&&(w=e.call(p,p.__data__,y,c))&&("__data__"in p&&(w.__data__=p.__data__),_[y]=w,Vm(_[y],t,n,y,_,no(p,n)));return new pa(l,this._parents,t,n)}function KA(e){var t=this._name,n=this._id;typeof e!="function"&&(e=Tx(e));for(var i=this._groups,o=i.length,l=[],u=[],c=0;c<o;++c)for(var f=i[c],_=f.length,p,w=0;w<_;++w)if(p=f[w]){for(var y=e.call(p,p.__data__,w,f),x,S=no(p,n),b=0,$=y.length;b<$;++b)(x=y[b])&&Vm(x,t,n,b,y,S);l.push(y),u.push(p)}return new pa(l,u,t,n)}var YA=Nf.prototype.constructor;function JA(){return new YA(this._groups,this._parents)}function XA(e,t){var n,i,o;return function(){var l=Du(this,e),u=(this.style.removeProperty(e),Du(this,e));return l===u?null:l===n&&u===i?o:o=t(n=l,i=u)}}function tb(e){return function(){this.style.removeProperty(e)}}function ZA(e,t,n){var i,o=n+"",l;return function(){var u=Du(this,e);return u===o?null:u===i?l:l=t(i=u,n)}}function QA(e,t,n){var i,o,l;return function(){var u=Du(this,e),c=n(this),f=c+"";return c==null&&(f=c=(this.style.removeProperty(e),Du(this,e))),u===f?null:u===i&&f===o?l:(o=f,l=t(i=u,c))}}function eE(e,t){var n,i,o,l="style."+t,u="end."+l,c;return function(){var f=Ro(this,e),_=f.on,p=f.value[l]==null?c||(c=tb(t)):void 0;(_!==n||o!==p)&&(i=(n=_).copy()).on(u,o=p),f.on=i}}function tE(e,t,n){var i=(e+="")=="transform"?tA:eb;return t==null?this.styleTween(e,XA(e,i)).on("end.style."+e,tb(e)):typeof t=="function"?this.styleTween(e,QA(e,i,jg(this,"style."+e,t))).each(eE(this._id,e)):this.styleTween(e,ZA(e,i,t),n).on("end.style."+e,null)}function nE(e,t,n){return function(i){this.style.setProperty(e,t.call(this,i),n)}}function sE(e,t,n){var i,o;function l(){var u=t.apply(this,arguments);return u!==o&&(i=(o=u)&&nE(e,u,n)),i}return l._value=t,l}function rE(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,sE(e,t,n??""))}function iE(e){return function(){this.textContent=e}}function oE(e){return function(){var t=e(this);this.textContent=t??""}}function aE(e){return this.tween("text",typeof e=="function"?oE(jg(this,"text",e)):iE(e==null?"":e+""))}function lE(e){return function(t){this.textContent=e.call(this,t)}}function cE(e){var t,n;function i(){var o=e.apply(this,arguments);return o!==n&&(t=(n=o)&&lE(o)),t}return i._value=e,i}function uE(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,cE(e))}function dE(){for(var e=this._name,t=this._id,n=nb(),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=no(f,t);Vm(f,e,n,_,u,{time:p.time+p.delay+p.duration,delay:0,duration:p.duration,ease:p.ease})}return new pa(i,this._parents,e,n)}function fE(){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 _=Ro(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 hE=0;function pa(e,t,n,i){this._groups=e,this._parents=t,this._name=n,this._id=i}function nb(){return++hE}var ua=Nf.prototype;pa.prototype={constructor:pa,select:GA,selectAll:KA,selectChild:ua.selectChild,selectChildren:ua.selectChildren,filter:zA,merge:BA,selection:JA,transition:dE,call:ua.call,nodes:ua.nodes,node:ua.node,size:ua.size,empty:ua.empty,each:ua.each,on:qA,attr:SA,attrTween:AA,style:tE,styleTween:rE,text:aE,textTween:uE,remove:VA,tween:gA,delay:MA,duration:IA,ease:PA,easeVarying:FA,end:fE,[Symbol.iterator]:ua[Symbol.iterator]};function mE(e){return((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2}var _E={time:null,delay:0,duration:250,ease:mE};function pE(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 gE(e){var t,n;e instanceof pa?(t=e._id,e=e._name):(t=nb(),(n=_E).time=xg(),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[_])&&Vm(f,e,t,_,u,n||pE(f,t));return new pa(i,this._parents,e,t)}Nf.prototype.interrupt=mA;Nf.prototype.transition=gE;const Zh=e=>()=>e;function yE(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 da(e,t,n){this.k=e,this.x=t,this.y=n}da.prototype={constructor:da,scale:function(e){return e===1?this:new da(this.k*e,this.x,this.y)},translate:function(e,t){return e===0&t===0?this:new da(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 ha=new da(1,0,0);da.prototype;function J_(e){e.stopImmediatePropagation()}function Kd(e){e.preventDefault(),e.stopImmediatePropagation()}function wE(e){return(!e.ctrlKey||e.type==="wheel")&&!e.button}function vE(){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 gw(){return this.__zoom||ha}function xE(e){return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*(e.ctrlKey?10:1)}function bE(){return navigator.maxTouchPoints||"ontouchstart"in this}function jE(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 sb(){var e=wE,t=vE,n=jE,i=xE,o=bE,l=[0,1/0],u=[[-1/0,-1/0],[1/0,1/0]],c=250,f=oA,_=Wm("start","zoom","end"),p,w,y,x=500,S=150,b=0,$=10;function E(N){N.property("__zoom",gw).on("wheel.zoom",X,{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)")}E.transform=function(N,O,P,ne){var B=N.selection?N.selection():N;B.property("__zoom",gw),N!==B?H(N,O,P,ne):B.interrupt().each(function(){Z(this,arguments).event(ne).start().zoom(null,typeof O=="function"?O.apply(this,arguments):O).end()})},E.scaleBy=function(N,O,P,ne){E.scaleTo(N,function(){var B=this.__zoom.k,z=typeof O=="function"?O.apply(this,arguments):O;return B*z},P,ne)},E.scaleTo=function(N,O,P,ne){E.transform(N,function(){var B=t.apply(this,arguments),z=this.__zoom,G=P==null?M(B):typeof P=="function"?P.apply(this,arguments):P,T=z.invert(G),Q=typeof O=="function"?O.apply(this,arguments):O;return n(D(L(z,Q),G,T),B,u)},P,ne)},E.translateBy=function(N,O,P,ne){E.transform(N,function(){return n(this.__zoom.translate(typeof O=="function"?O.apply(this,arguments):O,typeof P=="function"?P.apply(this,arguments):P),t.apply(this,arguments),u)},null,ne)},E.translateTo=function(N,O,P,ne,B){E.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(ha.translate(T[0],T[1]).scale(G.k).translate(typeof O=="function"?-O.apply(this,arguments):-O,typeof P=="function"?-P.apply(this,arguments):-P),z,u)},ne,B)};function L(N,O){return O=Math.max(l[0],Math.min(l[1],O)),O===N.k?N:new da(O,N.x,N.y)}function D(N,O,P){var ne=O[0]-P[0]*N.k,B=O[1]-P[1]*N.k;return ne===N.x&&B===N.y?N:new da(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,O,P,ne){N.on("start.zoom",function(){Z(this,arguments).event(ne).start()}).on("interrupt.zoom end.zoom",function(){Z(this,arguments).event(ne).end()}).tween("zoom",function(){var B=this,z=arguments,G=Z(B,z).event(ne),T=t.apply(B,z),Q=P==null?M(T):typeof P=="function"?P.apply(B,z):P,K=Math.max(T[1][0]-T[0][0],T[1][1]-T[0][1]),J=B.__zoom,oe=typeof O=="function"?O.apply(B,z):O,fe=f(J.invert(Q).concat(K/J.k),oe.invert(Q).concat(K/oe.k));return function(me){if(me===1)me=oe;else{var we=fe(me),Ae=K/we[2];me=new da(Ae,Q[0]-we[0]*Ae,Q[1]-we[1]*Ae)}G.zoom(null,me)}})}function Z(N,O,P){return!P&&N.__zooming||new Y(N,O)}function Y(N,O){this.that=N,this.args=O,this.active=0,this.sourceEvent=null,this.extent=t.apply(N,O),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,O){return this.mouse&&N!=="mouse"&&(this.mouse[1]=O.invert(this.mouse[0])),this.touch0&&N!=="touch"&&(this.touch0[1]=O.invert(this.touch0[0])),this.touch1&&N!=="touch"&&(this.touch1[1]=O.invert(this.touch1[0])),this.that.__zoom=O,this.emit("zoom"),this},end:function(){return--this.active===0&&(delete this.that.__zooming,this.emit("end")),this},emit:function(N){var O=Si(this.that).datum();_.call(N,this.that,new yE(N,{sourceEvent:this.sourceEvent,target:E,transform:this.that.__zoom,dispatch:_}),O)}};function X(N,...O){if(!e.apply(this,arguments))return;var P=Z(this,O).event(N),ne=this.__zoom,B=Math.max(l[0],Math.min(l[1],ne.k*Math.pow(2,i.apply(this,arguments)))),z=Xi(N);if(P.wheel)(P.mouse[0][0]!==z[0]||P.mouse[0][1]!==z[1])&&(P.mouse[1]=ne.invert(P.mouse[0]=z)),clearTimeout(P.wheel);else{if(ne.k===B)return;P.mouse=[z,ne.invert(z)],hm(this),P.start()}Kd(N),P.wheel=setTimeout(G,S),P.zoom("mouse",n(D(L(ne,B),P.mouse[0],P.mouse[1]),P.extent,u));function G(){P.wheel=null,P.end()}}function re(N,...O){if(y||!e.apply(this,arguments))return;var P=N.currentTarget,ne=Z(this,O,!0).event(N),B=Si(N.view).on("mousemove.zoom",Q,!0).on("mouseup.zoom",K,!0),z=Xi(N,P),G=N.clientX,T=N.clientY;Ux(N.view),J_(N),ne.mouse=[z,this.__zoom.invert(z)],hm(this),ne.start();function Q(J){if(Kd(J),!ne.moved){var oe=J.clientX-G,fe=J.clientY-T;ne.moved=oe*oe+fe*fe>b}ne.event(J).zoom("mouse",n(D(ne.that.__zoom,ne.mouse[0]=Xi(J,P),ne.mouse[1]),ne.extent,u))}function K(J){B.on("mousemove.zoom mouseup.zoom",null),Wx(J.view,ne.moved),Kd(J),ne.event(J).end()}}function ie(N,...O){if(e.apply(this,arguments)){var P=this.__zoom,ne=Xi(N.changedTouches?N.changedTouches[0]:N,this),B=P.invert(ne),z=P.k*(N.shiftKey?.5:2),G=n(D(L(P,z),ne,B),t.apply(this,O),u);Kd(N),c>0?Si(this).transition().duration(c).call(H,G,ne,N):Si(this).call(E.transform,G,ne,N)}}function ue(N,...O){if(e.apply(this,arguments)){var P=N.touches,ne=P.length,B=Z(this,O,N.changedTouches.length===ne).event(N),z,G,T,Q;for(J_(N),G=0;G<ne;++G)T=P[G],Q=Xi(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&&(w=Q[0],p=setTimeout(function(){p=null},x)),hm(this),B.start())}}function F(N,...O){if(this.__zooming){var P=Z(this,O).event(N),ne=N.changedTouches,B=ne.length,z,G,T,Q;for(Kd(N),z=0;z<B;++z)G=ne[z],T=Xi(G,this),P.touch0&&P.touch0[2]===G.identifier?P.touch0[0]=T:P.touch1&&P.touch1[2]===G.identifier&&(P.touch1[0]=T);if(G=P.that.__zoom,P.touch1){var K=P.touch0[0],J=P.touch0[1],oe=P.touch1[0],fe=P.touch1[1],me=(me=oe[0]-K[0])*me+(me=oe[1]-K[1])*me,we=(we=fe[0]-J[0])*we+(we=fe[1]-J[1])*we;G=L(G,Math.sqrt(me/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(P.touch0)T=P.touch0[0],Q=P.touch0[1];else return;P.zoom("touch",n(D(G,T,Q),P.extent,u))}}function C(N,...O){if(this.__zooming){var P=Z(this,O).event(N),ne=N.changedTouches,B=ne.length,z,G;for(J_(N),y&&clearTimeout(y),y=setTimeout(function(){y=null},x),z=0;z<B;++z)G=ne[z],P.touch0&&P.touch0[2]===G.identifier?delete P.touch0:P.touch1&&P.touch1[2]===G.identifier&&delete P.touch1;if(P.touch1&&!P.touch0&&(P.touch0=P.touch1,delete P.touch1),P.touch0)P.touch0[1]=this.__zoom.invert(P.touch0[0]);else if(P.end(),P.taps===2&&(G=Xi(G,this),Math.hypot(w[0]-G[0],w[1]-G[1])<$)){var T=Si(this).on("dblclick.zoom");T&&T.apply(this,arguments)}}}return E.wheelDelta=function(N){return arguments.length?(i=typeof N=="function"?N:Zh(+N),E):i},E.filter=function(N){return arguments.length?(e=typeof N=="function"?N:Zh(!!N),E):e},E.touchable=function(N){return arguments.length?(o=typeof N=="function"?N:Zh(!!N),E):o},E.extent=function(N){return arguments.length?(t=typeof N=="function"?N:Zh([[+N[0][0],+N[0][1]],[+N[1][0],+N[1][1]]]),E):t},E.scaleExtent=function(N){return arguments.length?(l[0]=+N[0],l[1]=+N[1],E):[l[0],l[1]]},E.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],E):[[u[0][0],u[0][1]],[u[1][0],u[1][1]]]},E.constrain=function(N){return arguments.length?(n=N,E):n},E.duration=function(N){return arguments.length?(c=+N,E):c},E.interpolate=function(N){return arguments.length?(f=N,E):f},E.on=function(){var N=_.on.apply(_,arguments);return N===_?E:N},E.clickDistance=function(N){return arguments.length?(b=(N=+N)*N,E):Math.sqrt(b)},E.tapDistance=function(N){return arguments.length?($=+N,E):$},E}const Gm=m.createContext(null),SE=Gm.Provider,ga={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.`},rb=ga.error001();function Rn(e,t){const n=m.useContext(Gm);if(n===null)throw new Error(rb);return Ax(n,e,t)}const Ns=()=>{const e=m.useContext(Gm);if(e===null)throw new Error(rb);return m.useMemo(()=>({getState:e.getState,setState:e.setState,subscribe:e.subscribe,destroy:e.destroy}),[e])},kE=e=>e.userSelectionActive?"none":"all";function pf({position:e,children:t,className:n,style:i,...o}){const l=Rn(kE),u=`${e}`.split("-");return ve.createElement("div",{className:Ys(["react-flow__panel",n,...u]),style:{...i,pointerEvents:l},...o},t)}function NE({proOptions:e,position:t="bottom-right"}){return e!=null&&e.hideAttribution?null:ve.createElement(pf,{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 CE=({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 w=m.useRef(null),[y,x]=m.useState({x:0,y:0,width:0,height:0}),S=Ys(["react-flow__edge-textwrapper",_]);return m.useEffect(()=>{if(w.current){const b=w.current.getBBox();x({x:b.x,y:b.y,width:b.width,height:b.height})}},[n]),typeof n>"u"||!n?null:ve.createElement("g",{transform:`translate(${e-y.width/2} ${t-y.height/2})`,className:S,visibility:y.width?"visible":"hidden",...p},o&&ve.createElement("rect",{width:y.width+2*u[0],x:-u[0],y:-u[1],height:y.height+2*u[1],className:"react-flow__edge-textbg",style:l,rx:c,ry:c}),ve.createElement("text",{className:"react-flow__edge-text",y:y.height/2,dy:"0.3em",ref:w,style:i},n),f)};var $E=m.memo(CE);const Sg=e=>({width:e.offsetWidth,height:e.offsetHeight}),zu=(e,t=0,n=1)=>Math.min(Math.max(e,t),n),kg=(e={x:0,y:0},t)=>({x:zu(e.x,t[0][0],t[1][0]),y:zu(e.y,t[0][1],t[1][1])}),yw=(e,t,n)=>e<t?zu(Math.abs(e-t),1,50)/50:e>n?-zu(Math.abs(e-n),1,50)/50:0,ib=(e,t)=>{const n=yw(e.x,35,t.width-35)*20,i=yw(e.y,35,t.height-35)*20;return[n,i]},ob=e=>{var t;return((t=e.getRootNode)==null?void 0:t.call(e))||(window==null?void 0:window.document)},ab=(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)}),gf=({x:e,y:t,width:n,height:i})=>({x:e,y:t,x2:e+n,y2:t+i}),lb=({x:e,y:t,x2:n,y2:i})=>({x:e,y:t,width:n-e,height:i-t}),ww=e=>({...e.positionAbsolute||{x:0,y:0},width:e.width||0,height:e.height||0}),AE=(e,t)=>lb(ab(gf(e),gf(t))),Bp=(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)},EE=e=>ki(e.width)&&ki(e.height)&&ki(e.x)&&ki(e.y),ki=e=>!isNaN(e)&&isFinite(e),ps=Symbol.for("internals"),cb=["Enter"," ","Escape"],TE=(e,t)=>{},ME=e=>"nativeEvent"in e;function Up(e){var o,l;const t=ME(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 ub=e=>"clientX"in e,ul=(e,t)=>{var l,u;const n=ub(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)}},Mm=()=>{var e;return typeof navigator<"u"&&((e=navigator==null?void 0:navigator.userAgent)==null?void 0:e.indexOf("Mac"))>=0},$f=({id:e,path:t,labelX:n,labelY:i,label:o,labelStyle:l,labelShowBg:u,labelBgStyle:c,labelBgPadding:f,labelBgBorderRadius:_,style:p,markerEnd:w,markerStart:y,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:w,markerStart:y}),x&&ve.createElement("path",{d:t,fill:"none",strokeOpacity:0,strokeWidth:x,className:"react-flow__edge-interaction"}),o&&ki(n)&&ki(i)?ve.createElement($E,{x:n,y:i,label:o,labelStyle:l,labelShowBg:u,labelBgStyle:c,labelBgPadding:f,labelBgBorderRadius:_}):null);$f.displayName="BaseEdge";function Yd(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),w=Math.abs(_-t);return[f,_,p,w]}var mc;(function(e){e.Strict="strict",e.Loose="loose"})(mc||(mc={}));var ic;(function(e){e.Free="free",e.Vertical="vertical",e.Horizontal="horizontal"})(ic||(ic={}));var yf;(function(e){e.Partial="partial",e.Full="full"})(yf||(yf={}));var cl;(function(e){e.Bezier="default",e.Straight="straight",e.Step="step",e.SmoothStep="smoothstep",e.SimpleBezier="simplebezier"})(cl||(cl={}));var wf;(function(e){e.Arrow="arrow",e.ArrowClosed="arrowclosed"})(wf||(wf={}));var mt;(function(e){e.Left="left",e.Top="top",e.Right="right",e.Bottom="bottom"})(mt||(mt={}));function vw({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 hb({sourceX:e,sourceY:t,sourcePosition:n=mt.Bottom,targetX:i,targetY:o,targetPosition:l=mt.Top}){const[u,c]=vw({pos:n,x1:e,y1:t,x2:i,y2:o}),[f,_]=vw({pos:l,x1:i,y1:o,x2:e,y2:t}),[p,w,y,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,w,y,x]}const Ng=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:w,style:y,markerEnd:x,markerStart:S,interactionWidth:b})=>{const[$,E,L]=hb({sourceX:e,sourceY:t,sourcePosition:o,targetX:n,targetY:i,targetPosition:l});return ve.createElement($f,{path:$,labelX:E,labelY:L,label:u,labelStyle:c,labelShowBg:f,labelBgStyle:_,labelBgPadding:p,labelBgBorderRadius:w,style:y,markerEnd:x,markerStart:S,interactionWidth:b})});Ng.displayName="SimpleBezierEdge";const xw={[mt.Left]:{x:-1,y:0},[mt.Right]:{x:1,y:0},[mt.Top]:{x:0,y:-1},[mt.Bottom]:{x:0,y:1}},RE=({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},bw=(e,t)=>Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2));function LE({source:e,sourcePosition:t=mt.Bottom,target:n,targetPosition:i=mt.Top,center:o,offset:l}){const u=xw[t],c=xw[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=RE({source:f,sourcePosition:t,target:_}),w=p.x!==0?"x":"y",y=p[w];let x=[],S,b;const $={x:0,y:0},E={x:0,y:0},[L,D,M,H]=db({sourceX:e.x,sourceY:e.y,targetX:n.x,targetY:n.y});if(u[w]*c[w]===-1){S=o.x||L,b=o.y||D;const Y=[{x:S,y:f.y},{x:S,y:_.y}],X=[{x:f.x,y:b},{x:_.x,y:b}];u[w]===y?x=w==="x"?Y:X:x=w==="x"?X:Y}else{const Y=[{x:f.x,y:_.y}],X=[{x:_.x,y:f.y}];if(w==="x"?x=u.x===y?X:Y:x=u.y===y?Y:X,t===i){const C=Math.abs(e[w]-n[w]);if(C<=l){const N=Math.min(l-1,l-C);u[w]===y?$[w]=(f[w]>e[w]?-1:1)*N:E[w]=(_[w]>n[w]?-1:1)*N}}if(t!==i){const C=w==="x"?"y":"x",N=u[w]===c[C],O=f[C]>_[C],P=f[C]<_[C];(u[w]===1&&(!N&&O||N&&P)||u[w]!==1&&(!N&&P||N&&O))&&(x=w==="x"?Y:X)}const re={x:f.x+$.x,y:f.y+$.y},ie={x:_.x+E.x,y:_.y+E.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,b=x[0].y):(S=x[0].x,b=(re.y+ie.y)/2)}return[[e,{x:f.x+$.x,y:f.y+$.y},...x,{x:_.x+E.x,y:_.y+E.y},n],S,b,M,H]}function IE(e,t,n,i){const o=Math.min(bw(e,t)/2,bw(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 Wp({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,w,y,x,S]=LE({source:{x:e,y:t},sourcePosition:n,target:{x:i,y:o},targetPosition:l,center:{x:c,y:f},offset:_});return[p.reduce(($,E,L)=>{let D="";return L>0&&L<p.length-1?D=IE(p[L-1],E,p[L+1],u):D=`${L===0?"M":"L"}${E.x} ${E.y}`,$+=D,$},""),w,y,x,S]}const Km=m.memo(({sourceX:e,sourceY:t,targetX:n,targetY:i,label:o,labelStyle:l,labelShowBg:u,labelBgStyle:c,labelBgPadding:f,labelBgBorderRadius:_,style:p,sourcePosition:w=mt.Bottom,targetPosition:y=mt.Top,markerEnd:x,markerStart:S,pathOptions:b,interactionWidth:$})=>{const[E,L,D]=Wp({sourceX:e,sourceY:t,sourcePosition:w,targetX:n,targetY:i,targetPosition:y,borderRadius:b==null?void 0:b.borderRadius,offset:b==null?void 0:b.offset});return ve.createElement($f,{path:E,labelX:L,labelY:D,label:o,labelStyle:l,labelShowBg:u,labelBgStyle:c,labelBgPadding:f,labelBgBorderRadius:_,style:p,markerEnd:x,markerStart:S,interactionWidth:$})});Km.displayName="SmoothStepEdge";const Cg=m.memo(e=>{var t;return ve.createElement(Km,{...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])})});Cg.displayName="StepEdge";function OE({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 $g=m.memo(({sourceX:e,sourceY:t,targetX:n,targetY:i,label:o,labelStyle:l,labelShowBg:u,labelBgStyle:c,labelBgPadding:f,labelBgBorderRadius:_,style:p,markerEnd:w,markerStart:y,interactionWidth:x})=>{const[S,b,$]=OE({sourceX:e,sourceY:t,targetX:n,targetY:i});return ve.createElement($f,{path:S,labelX:b,labelY:$,label:o,labelStyle:l,labelShowBg:u,labelBgStyle:c,labelBgPadding:f,labelBgBorderRadius:_,style:p,markerEnd:w,markerStart:y,interactionWidth:x})});$g.displayName="StraightEdge";function Qh(e,t){return e>=0?.5*e:t*25*Math.sqrt(-e)}function jw({pos:e,x1:t,y1:n,x2:i,y2:o,c:l}){switch(e){case mt.Left:return[t-Qh(t-i,l),n];case mt.Right:return[t+Qh(i-t,l),n];case mt.Top:return[t,n-Qh(n-o,l)];case mt.Bottom:return[t,n+Qh(o-n,l)]}}function mb({sourceX:e,sourceY:t,sourcePosition:n=mt.Bottom,targetX:i,targetY:o,targetPosition:l=mt.Top,curvature:u=.25}){const[c,f]=jw({pos:n,x1:e,y1:t,x2:i,y2:o,c:u}),[_,p]=jw({pos:l,x1:i,y1:o,x2:e,y2:t,c:u}),[w,y,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}`,w,y,x,S]}const Rm=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:w,style:y,markerEnd:x,markerStart:S,pathOptions:b,interactionWidth:$})=>{const[E,L,D]=mb({sourceX:e,sourceY:t,sourcePosition:o,targetX:n,targetY:i,targetPosition:l,curvature:b==null?void 0:b.curvature});return ve.createElement($f,{path:E,labelX:L,labelY:D,label:u,labelStyle:c,labelShowBg:f,labelBgStyle:_,labelBgPadding:p,labelBgBorderRadius:w,style:y,markerEnd:x,markerStart:S,interactionWidth:$})});Rm.displayName="BezierEdge";const Ag=m.createContext(null),PE=Ag.Provider;Ag.Consumer;const DE=()=>m.useContext(Ag),FE=e=>"id"in e&&"source"in e&&"target"in e,zE=({source:e,sourceHandle:t,target:n,targetHandle:i})=>`reactflow__edge-${e}${t||""}-${n}${i||""}`,qp=(e,t)=>typeof e>"u"?"":typeof e=="string"?e:`${t?`${t}__`:""}${Object.keys(e).sort().map(i=>`${i}=${e[i]}`).join("&")}`,BE=(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)),UE=(e,t)=>{if(!e.source||!e.target)return t;let n;return FE(e)?n={...e}:n={...e,id:zE(e)},BE(n,t)?t:t.concat(n)},Hp=({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},_b=({x:e,y:t},[n,i,o])=>({x:e*o+n,y:t*o+i}),uc=(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}},Ym=(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}=uc(o,t).positionAbsolute;return ab(i,gf({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 lb(n)},pb=(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:w,height:y,selectable:x=!0,hidden:S=!1}=p;if(u&&!x||S)return!1;const{positionAbsolute:b}=uc(p,c),$={x:b.x,y:b.y,width:w||0,height:y||0},E=Bp(f,$),L=typeof w>"u"||typeof y>"u"||w===null||y===null,D=l&&E>0,M=(w||0)*(y||0);(L||D||E>=M||p.dragging)&&_.push(p)}),_},gb=(e,t)=>{const n=e.map(i=>i.id);return t.filter(i=>n.includes(i.source)||n.includes(i.target))},yb=(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),_=zu(f,i,o),p=e.x+e.width/2,w=e.y+e.height/2,y=t/2-p*_,x=n/2-w*_;return{x:y,y:x,zoom:_}},ec=(e,t=0)=>e.transition().duration(t);function Sw(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 WE(e,t,n,i,o,l){const{x:u,y:c}=ul(e),_=t.elementsFromPoint(u,c).find(S=>S.classList.contains("react-flow__handle"));if(_){const S=_.getAttribute("data-nodeid");if(S){const b=Eg(void 0,_),$=_.getAttribute("data-handleid"),E=l({nodeId:S,id:$,type:b});if(E){const L=o.find(D=>D.nodeId===S&&D.type===b&&D.id===$);return{handle:{id:$,type:b,nodeId:S,x:(L==null?void 0:L.x)||n.x,y:(L==null?void 0:L.y)||n.y},validHandleResult:E}}}}let p=[],w=1/0;if(o.forEach(S=>{const b=Math.sqrt((S.x-n.x)**2+(S.y-n.y)**2);if(b<=i){const $=l(S);b<=w&&(b<w?p=[{handle:S,validHandleResult:$}]:b===w&&p.push({handle:S,validHandleResult:$}),w=b)}}),!p.length)return{handle:null,validHandleResult:wb()};if(p.length===1)return p[0];const y=p.some(({validHandleResult:S})=>S.isValid),x=p.some(({handle:S})=>S.type==="target");return p.find(({handle:S,validHandleResult:b})=>x?S.type==="target":y?b.isValid:!0)||p[0]}const qE={source:null,target:null,sourceHandle:null,targetHandle:null},wb=()=>({handleDomNode:null,isValid:!1,connection:qE,endHandle:null});function vb(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}"]`),_={...wb(),handleDomNode:f};if(f){const p=Eg(void 0,f),w=f.getAttribute("data-nodeid"),y=f.getAttribute("data-handleid"),x=f.classList.contains("connectable"),S=f.classList.contains("connectableend"),b={source:c?w:n,sourceHandle:c?y:i,target:c?n:w,targetHandle:c?i:y};_.connection=b,x&&S&&(t===mc.Strict?c&&p==="source"||!c&&p==="target":w!==n||y!==i)&&(_.endHandle={nodeId:w,handleId:y,type:p},_.isValid=l(b))}return _}function HE({nodes:e,nodeId:t,handleId:n,handleType:i}){return e.reduce((o,l)=>{if(l[ps]){const{handleBounds:u}=l[ps];let c=[],f=[];u&&(c=Sw(l,u,"source",`${t}-${n}-${i}`),f=Sw(l,u,"target",`${t}-${n}-${i}`)),o.push(...c,...f)}return o},[])}function Eg(e,t){return e||(t!=null&&t.classList.contains("target")?"target":t!=null&&t.classList.contains("source")?"source":null)}function X_(e){e==null||e.classList.remove("valid","connecting","react-flow__handle-valid","react-flow__handle-connecting")}function VE(e,t){let n=null;return t?n="valid":e&&!t&&(n="invalid"),n}function xb({event:e,handleId:t,nodeId:n,onConnect:i,isTarget:o,getState:l,setState:u,isValidConnection:c,edgeUpdaterType:f,onEdgeUpdateEnd:_}){const p=ob(e.target),{connectionMode:w,domNode:y,autoPanOnConnect:x,connectionRadius:S,onConnectStart:b,panBy:$,getNodes:E,cancelConnection:L}=l();let D=0,M;const{x:H,y:Z}=ul(e),Y=p==null?void 0:p.elementFromPoint(H,Z),X=Eg(f,Y),re=y==null?void 0:y.getBoundingClientRect();if(!re||!X)return;let ie,ue=ul(e,re),F=!1,C=null,N=!1,O=null;const P=HE({nodes:E(),nodeId:n,handleId:t,handleType:X}),ne=()=>{if(!x)return;const[G,T]=ib(ue,re);$({x:G,y:T}),D=requestAnimationFrame(ne)};u({connectionPosition:ue,connectionStatus:null,connectionNodeId:n,connectionHandleId:t,connectionHandleType:X,connectionStartHandle:{nodeId:n,handleId:t,type:X},connectionEndHandle:null}),b==null||b(e,{nodeId:n,handleId:t,handleType:X});function B(G){const{transform:T}=l();ue=ul(G,re);const{handle:Q,validHandleResult:K}=WE(G,p,Hp(ue,T,!1,[1,1]),S,P,J=>vb(J,w,n,t,o?"target":"source",c,p));if(M=Q,F||(ne(),F=!0),O=K.handleDomNode,C=K.connection,N=K.isValid,u({connectionPosition:M&&N?_b({x:M.x,y:M.y},T):ue,connectionStatus:VE(!!M,N),connectionEndHandle:K.endHandle}),!M&&!N&&!O)return X_(ie);C.source!==C.target&&O&&(X_(ie),ie=O,O.classList.add("connecting","react-flow__handle-connecting"),O.classList.toggle("valid",N),O.classList.toggle("react-flow__handle-valid",N))}function z(G){var T,Q;(M||O)&&C&&N&&(i==null||i(C)),(Q=(T=l()).onConnectEnd)==null||Q.call(T,G),f&&(_==null||_(G)),X_(ie),L(),cancelAnimationFrame(D),F=!1,N=!1,C=null,O=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 kw=()=>!0,GE=e=>({connectionStartHandle:e.connectionStartHandle,connectOnClick:e.connectOnClick,noPanClassName:e.noPanClassName}),KE=(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}},bb=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:w,...y},x)=>{var re,ie;const S=u||null,b=e==="target",$=Ns(),E=DE(),{connectOnClick:L,noPanClassName:D}=Rn(GE,Fs),{connecting:M,clickConnecting:H}=Rn(KE(E,S,e),Fs);E||(ie=(re=$.getState()).onError)==null||ie.call(re,"010",ga.error010());const Z=ue=>{const{defaultEdgeOptions:F,onConnect:C,hasDefaultEdges:N}=$.getState(),O={...F,...ue};if(N){const{edges:P,setEdges:ne}=$.getState();ne(UE(O,P))}C==null||C(O),c==null||c(O)},Y=ue=>{if(!E)return;const F=ub(ue);o&&(F&&ue.button===0||!F)&&xb({event:ue,handleId:S,nodeId:E,onConnect:Z,isTarget:b,getState:$.getState,setState:$.setState,isValidConnection:n||$.getState().isValidConnection||kw}),F?p==null||p(ue):w==null||w(ue)},X=ue=>{const{onClickConnectStart:F,onClickConnectEnd:C,connectionClickStartHandle:N,connectionMode:O,isValidConnection:P}=$.getState();if(!E||!N&&!o)return;if(!N){F==null||F(ue,{nodeId:E,handleId:S,handleType:e}),$.setState({connectionClickStartHandle:{nodeId:E,type:e,handleId:S}});return}const ne=ob(ue.target),B=n||P||kw,{connection:z,isValid:G}=vb({nodeId:E,id:S,type:e},O,N.nodeId,N.handleId||null,N.type,B,ne);G&&Z(z),C==null||C(ue),$.setState({connectionClickStartHandle:null})};return ve.createElement("div",{"data-handleid":S,"data-nodeid":E,"data-handlepos":t,"data-id":`${E}-${S}-${e}`,className:Ys(["react-flow__handle",`react-flow__handle-${t}`,"nodrag",D,_,{source:!b,target:b,connectable:i,connectablestart:o,connectableend:l,connecting:H,connectionindicator:i&&(o&&!M||l&&M)}]),onMouseDown:Y,onTouchStart:Y,onClick:L?X:void 0,ref:x,...y},f)});bb.displayName="Handle";var Lm=m.memo(bb);const jb=({data:e,isConnectable:t,targetPosition:n=mt.Top,sourcePosition:i=mt.Bottom})=>ve.createElement(ve.Fragment,null,ve.createElement(Lm,{type:"target",position:n,isConnectable:t}),e==null?void 0:e.label,ve.createElement(Lm,{type:"source",position:i,isConnectable:t}));jb.displayName="DefaultNode";var Vp=m.memo(jb);const Sb=({data:e,isConnectable:t,sourcePosition:n=mt.Bottom})=>ve.createElement(ve.Fragment,null,e==null?void 0:e.label,ve.createElement(Lm,{type:"source",position:n,isConnectable:t}));Sb.displayName="InputNode";var kb=m.memo(Sb);const Nb=({data:e,isConnectable:t,targetPosition:n=mt.Top})=>ve.createElement(ve.Fragment,null,ve.createElement(Lm,{type:"target",position:n,isConnectable:t}),e==null?void 0:e.label);Nb.displayName="OutputNode";var Cb=m.memo(Nb);const Tg=()=>null;Tg.displayName="GroupNode";const YE=e=>({selectedNodes:e.getNodes().filter(t=>t.selected),selectedEdges:e.edges.filter(t=>t.selected)}),em=e=>e.id;function JE(e,t){return Fs(e.selectedNodes.map(em),t.selectedNodes.map(em))&&Fs(e.selectedEdges.map(em),t.selectedEdges.map(em))}const $b=m.memo(({onSelectionChange:e})=>{const t=Ns(),{selectedNodes:n,selectedEdges:i}=Rn(YE,JE);return m.useEffect(()=>{const o={nodes:n,edges:i};e==null||e(o),t.getState().onSelectionChange.forEach(l=>l(o))},[n,i,e]),null});$b.displayName="SelectionListener";const XE=e=>!!e.onSelectionChange;function ZE({onSelectionChange:e}){const t=Rn(XE);return e||t?ve.createElement($b,{onSelectionChange:e}):null}const QE=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 vu(e,t){m.useEffect(()=>{typeof e<"u"&&t(e)},[e])}function Kt(e,t,n){m.useEffect(()=>{typeof t<"u"&&n({[e]:t})},[t])}const eT=({nodes:e,edges:t,defaultNodes:n,defaultEdges:i,onConnect:o,onConnectStart:l,onConnectEnd:u,onClickConnectStart:c,onClickConnectEnd:f,nodesDraggable:_,nodesConnectable:p,nodesFocusable:w,edgesFocusable:y,edgesUpdatable:x,elevateNodesOnSelect:S,minZoom:b,maxZoom:$,nodeExtent:E,onNodesChange:L,onEdgesChange:D,elementsSelectable:M,connectionMode:H,snapGrid:Z,snapToGrid:Y,translateExtent:X,connectOnClick:re,defaultEdgeOptions:ie,fitView:ue,fitViewOptions:F,onNodesDelete:C,onEdgesDelete:N,onNodeDrag:O,onNodeDragStart:P,onNodeDragStop:ne,onSelectionDrag:B,onSelectionDragStart:z,onSelectionDragStop:G,noPanClassName:T,nodeOrigin:Q,rfId:K,autoPanOnConnect:J,autoPanOnNodeDrag:oe,onError:fe,connectionRadius:me,isValidConnection:we,nodeDragThreshold:Ae})=>{const{setNodes:Be,setEdges:We,setDefaultNodesAndEdges:_t,setMinZoom:Pe,setMaxZoom:et,setTranslateExtent:lt,setNodeExtent:Ye,reset:Se}=Rn(QE,Fs),Le=Ns();return m.useEffect(()=>{const ct=i==null?void 0:i.map(ge=>({...ge,...ie}));return _t(n,ct),()=>{Se()}},[]),Kt("defaultEdgeOptions",ie,Le.setState),Kt("connectionMode",H,Le.setState),Kt("onConnect",o,Le.setState),Kt("onConnectStart",l,Le.setState),Kt("onConnectEnd",u,Le.setState),Kt("onClickConnectStart",c,Le.setState),Kt("onClickConnectEnd",f,Le.setState),Kt("nodesDraggable",_,Le.setState),Kt("nodesConnectable",p,Le.setState),Kt("nodesFocusable",w,Le.setState),Kt("edgesFocusable",y,Le.setState),Kt("edgesUpdatable",x,Le.setState),Kt("elementsSelectable",M,Le.setState),Kt("elevateNodesOnSelect",S,Le.setState),Kt("snapToGrid",Y,Le.setState),Kt("snapGrid",Z,Le.setState),Kt("onNodesChange",L,Le.setState),Kt("onEdgesChange",D,Le.setState),Kt("connectOnClick",re,Le.setState),Kt("fitViewOnInit",ue,Le.setState),Kt("fitViewOnInitOptions",F,Le.setState),Kt("onNodesDelete",C,Le.setState),Kt("onEdgesDelete",N,Le.setState),Kt("onNodeDrag",O,Le.setState),Kt("onNodeDragStart",P,Le.setState),Kt("onNodeDragStop",ne,Le.setState),Kt("onSelectionDrag",B,Le.setState),Kt("onSelectionDragStart",z,Le.setState),Kt("onSelectionDragStop",G,Le.setState),Kt("noPanClassName",T,Le.setState),Kt("nodeOrigin",Q,Le.setState),Kt("rfId",K,Le.setState),Kt("autoPanOnConnect",J,Le.setState),Kt("autoPanOnNodeDrag",oe,Le.setState),Kt("onError",fe,Le.setState),Kt("connectionRadius",me,Le.setState),Kt("isValidConnection",we,Le.setState),Kt("nodeDragThreshold",Ae,Le.setState),vu(e,Be),vu(t,We),vu(b,Pe),vu($,et),vu(X,lt),vu(E,Ye),null},Nw={display:"none"},tT={position:"absolute",width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0px, 0px, 0px, 0px)",clipPath:"inset(100%)"},Ab="react-flow__node-desc",Eb="react-flow__edge-desc",nT="react-flow__aria-live",sT=e=>e.ariaLiveMessage;function rT({rfId:e}){const t=Rn(sT);return ve.createElement("div",{id:`${nT}-${e}`,"aria-live":"assertive","aria-atomic":"true",style:tT},t)}function iT({rfId:e,disableKeyboardA11y:t}){return ve.createElement(ve.Fragment,null,ve.createElement("div",{id:`${Ab}-${e}`,style:Nw},"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:`${Eb}-${e}`,style:Nw},"Press enter or space to select an edge. You can then press delete to remove it or escape to cancel."),!t&&ve.createElement(rT,{rfId:e}))}var vf=(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(w=>typeof w=="string").map(w=>w.split("+")),p=_.reduce((w,y)=>w.concat(...y),[]);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)&&Up(x))return!1;const b=$w(x.code,c);l.current.add(x[b]),Cw(u,l.current,!1)&&(x.preventDefault(),i(!0))},w=x=>{if((!o.current||o.current&&!t.actInsideInputWithModifier)&&Up(x))return!1;const b=$w(x.code,c);Cw(u,l.current,!0)?(i(!1),l.current.clear()):l.current.delete(x[b]),x.key==="Meta"&&l.current.clear(),o.current=!1},y=()=>{l.current.clear(),i(!1)};return _==null||_.addEventListener("keydown",p),_==null||_.addEventListener("keyup",w),window.addEventListener("blur",y),()=>{_==null||_.removeEventListener("keydown",p),_==null||_.removeEventListener("keyup",w),window.removeEventListener("blur",y)}}},[e,i]),n};function Cw(e,t,n){return e.filter(i=>n||i.length===t.size).some(i=>i.every(o=>t.has(o)))}function $w(e,t){return t.includes(e)?"code":"key"}function Tb(e,t,n,i){var u,c;if(!e.parentNode)return n;const o=t.get(e.parentNode),l=uc(o,i);return Tb(o,t,{x:(n.x??0)+l.x,y:(n.y??0)+l.y,z:(((u=o[ps])==null?void 0:u.z)??0)>(n.z??0)?((c=o[ps])==null?void 0:c.z)??0:n.z??0},i)}function Mb(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}=Tb(i,e,{...i.position,z:((o=i[ps])==null?void 0:o.z)??0},t);i.positionAbsolute={x:l,y:u},i[ps].z=c,n!=null&&n[i.id]&&(i[ps].isParent=!0)}})}function Z_(e,t,n,i){const o=new Map,l={},u=i?1e3:0;return e.forEach(c=>{var y;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 w=(_==null?void 0:_.type)&&(_==null?void 0:_.type)!==c.type;Object.defineProperty(p,ps,{enumerable:!1,value:{handleBounds:w||(y=_==null?void 0:_[ps])==null?void 0:y.handleBounds,z:f}}),o.set(c.id,p)}),Mb(o,n,l),o}function Rb(e,t={}){const{getNodes:n,width:i,height:o,minZoom:l,maxZoom:u,d3Zoom:c,d3Selection:f,fitViewOnInitDone:_,fitViewOnInit:p,nodeOrigin:w}=e(),y=t.initial&&!_&&p;if(c&&f&&(y||!t.initial)){const S=n().filter($=>{var L;const E=t.includeHiddenNodes?$.width&&$.height:!$.hidden;return(L=t.nodes)!=null&&L.length?E&&t.nodes.some(D=>D.id===$.id):E}),b=S.every($=>$.width&&$.height);if(S.length>0&&b){const $=Ym(S,w),{x:E,y:L,zoom:D}=yb($,i,o,t.minZoom??l,t.maxZoom??u,t.padding??.1),M=ha.translate(E,L).scale(D);return typeof t.duration=="number"&&t.duration>0?c.transform(ec(f,t.duration),M):c.transform(f,M),!0}}return!1}function oT(e,t){return e.forEach(n=>{const i=t.get(n.id);i&&t.set(i.id,{...i,[ps]:i[ps],selected:n.selected})}),new Map(t)}function aT(e,t){return t.map(n=>{const i=e.find(o=>o.id===n.id);return i&&(n.selected=i.selected),n})}function tm({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:oT(e,o)}),u==null||u(e)),t!=null&&t.length&&(_&&i({edges:aT(t,l)}),c==null||c(t))}const xu=()=>{},lT={zoomIn:xu,zoomOut:xu,zoomTo:xu,getZoom:()=>1,setViewport:xu,getViewport:()=>({x:0,y:0,zoom:1}),fitView:()=>!1,setCenter:xu,fitBounds:xu,project:e=>e,screenToFlowPosition:e=>e,flowToScreenPosition:e=>e,viewportInitialized:!1},cT=e=>({d3Zoom:e.d3Zoom,d3Selection:e.d3Selection}),uT=()=>{const e=Ns(),{d3Zoom:t,d3Selection:n}=Rn(cT,Fs);return m.useMemo(()=>n&&t?{zoomIn:o=>t.scaleBy(ec(n,o==null?void 0:o.duration),1.2),zoomOut:o=>t.scaleBy(ec(n,o==null?void 0:o.duration),1/1.2),zoomTo:(o,l)=>t.scaleTo(ec(n,l==null?void 0:l.duration),o),getZoom:()=>e.getState().transform[2],setViewport:(o,l)=>{const[u,c,f]=e.getState().transform,_=ha.translate(o.x??u,o.y??c).scale(o.zoom??f);t.transform(ec(n,l==null?void 0:l.duration),_)},getViewport:()=>{const[o,l,u]=e.getState().transform;return{x:o,y:l,zoom:u}},fitView:o=>Rb(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:_,w=c/2-o*p,y=f/2-l*p,x=ha.translate(w,y).scale(p);t.transform(ec(n,u==null?void 0:u.duration),x)},fitBounds:(o,l)=>{const{width:u,height:c,minZoom:f,maxZoom:_}=e.getState(),{x:p,y:w,zoom:y}=yb(o,u,c,f,_,(l==null?void 0:l.padding)??.1),x=ha.translate(p,w).scale(y);t.transform(ec(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"),Hp(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(),w={x:o.x-_,y:o.y-p};return Hp(w,l,u,c)},flowToScreenPosition:o=>{const{transform:l,domNode:u}=e.getState();if(!u)return o;const{x:c,y:f}=u.getBoundingClientRect(),_=_b(o,l);return{x:_.x+c,y:_.y+f}},viewportInitialized:!0}:lT,[t,n])};function Mg(){const e=uT(),t=Ns(),n=m.useCallback(()=>t.getState().getNodes().map(b=>({...b})),[]),i=m.useCallback(b=>t.getState().nodeInternals.get(b),[]),o=m.useCallback(()=>{const{edges:b=[]}=t.getState();return b.map($=>({...$}))},[]),l=m.useCallback(b=>{const{edges:$=[]}=t.getState();return $.find(E=>E.id===b)},[]),u=m.useCallback(b=>{const{getNodes:$,setNodes:E,hasDefaultNodes:L,onNodesChange:D}=t.getState(),M=$(),H=typeof b=="function"?b(M):b;if(L)E(H);else if(D){const Z=H.length===0?M.map(Y=>({type:"remove",id:Y.id})):H.map(Y=>({item:Y,type:"reset"}));D(Z)}},[]),c=m.useCallback(b=>{const{edges:$=[],setEdges:E,hasDefaultEdges:L,onEdgesChange:D}=t.getState(),M=typeof b=="function"?b($):b;if(L)E(M);else if(D){const H=M.length===0?$.map(Z=>({type:"remove",id:Z.id})):M.map(Z=>({item:Z,type:"reset"}));D(H)}},[]),f=m.useCallback(b=>{const $=Array.isArray(b)?b:[b],{getNodes:E,setNodes:L,hasDefaultNodes:D,onNodesChange:M}=t.getState();if(D){const Z=[...E(),...$];L(Z)}else if(M){const H=$.map(Z=>({item:Z,type:"add"}));M(H)}},[]),_=m.useCallback(b=>{const $=Array.isArray(b)?b:[b],{edges:E=[],setEdges:L,hasDefaultEdges:D,onEdgesChange:M}=t.getState();if(D)L([...E,...$]);else if(M){const H=$.map(Z=>({item:Z,type:"add"}));M(H)}},[]),p=m.useCallback(()=>{const{getNodes:b,edges:$=[],transform:E}=t.getState(),[L,D,M]=E;return{nodes:b().map(H=>({...H})),edges:$.map(H=>({...H})),viewport:{x:L,y:D,zoom:M}}},[]),w=m.useCallback(({nodes:b,edges:$})=>{const{nodeInternals:E,getNodes:L,edges:D,hasDefaultNodes:M,hasDefaultEdges:H,onNodesDelete:Z,onEdgesDelete:Y,onNodesChange:X,onEdgesChange:re}=t.getState(),ie=(b||[]).map(O=>O.id),ue=($||[]).map(O=>O.id),F=L().reduce((O,P)=>{const ne=!ie.includes(P.id)&&P.parentNode&&O.find(z=>z.id===P.parentNode);return(typeof P.deletable=="boolean"?P.deletable:!0)&&(ie.includes(P.id)||ne)&&O.push(P),O},[]),C=D.filter(O=>typeof O.deletable=="boolean"?O.deletable:!0),N=C.filter(O=>ue.includes(O.id));if(F||N){const O=gb(F,C),P=[...N,...O],ne=P.reduce((B,z)=>(B.includes(z.id)||B.push(z.id),B),[]);if((H||M)&&(H&&t.setState({edges:D.filter(B=>!ne.includes(B.id))}),M&&(F.forEach(B=>{E.delete(B.id)}),t.setState({nodeInternals:new Map(E)}))),ne.length>0&&(Y==null||Y(P),re&&re(ne.map(B=>({id:B,type:"remove"})))),F.length>0&&(Z==null||Z(F),X)){const B=F.map(z=>({id:z.id,type:"remove"}));X(B)}}},[]),y=m.useCallback(b=>{const $=EE(b),E=$?null:t.getState().nodeInternals.get(b.id);return!$&&!E?[null,null,$]:[$?b:ww(E),E,$]},[]),x=m.useCallback((b,$=!0,E)=>{const[L,D,M]=y(b);return L?(E||t.getState().getNodes()).filter(H=>{if(!M&&(H.id===D.id||!H.positionAbsolute))return!1;const Z=ww(H),Y=Bp(Z,L);return $&&Y>0||Y>=L.width*L.height}):[]},[]),S=m.useCallback((b,$,E=!0)=>{const[L]=y(b);if(!L)return!1;const D=Bp(L,$);return E&&D>0||D>=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:w,getIntersectingNodes:x,isNodeIntersecting:S}),[e,n,i,o,l,u,c,f,_,p,w,x,S])}const dT={actInsideInputWithModifier:!1};var fT=({deleteKeyCode:e,multiSelectionKeyCode:t})=>{const n=Ns(),{deleteElements:i}=Mg(),o=vf(e,dT),l=vf(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 hT(e){const t=Ns();m.useEffect(()=>{let n;const i=()=>{var l,u;if(!e.current)return;const o=Sg(e.current);(o.height===0||o.width===0)&&((u=(l=t.getState()).onError)==null||u.call(l,"004",ga.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 Rg={position:"absolute",width:"100%",height:"100%",top:0,left:0},mT=(e,t)=>e.x!==t.x||e.y!==t.y||e.zoom!==t.k,nm=e=>({x:e.x,y:e.y,zoom:e.k}),bu=(e,t)=>e.target.closest(`.${t}`),Aw=(e,t)=>t===2&&Array.isArray(e)&&e.includes(2),Ew=e=>{const t=e.ctrlKey&&Mm()?10:1;return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*t},_T=e=>({d3Zoom:e.d3Zoom,d3Selection:e.d3Selection,d3ZoomHandler:e.d3ZoomHandler,userSelectionActive:e.userSelectionActive}),pT=({onMove:e,onMoveStart:t,onMoveEnd:n,onPaneContextMenu:i,zoomOnScroll:o=!0,zoomOnPinch:l=!0,panOnScroll:u=!1,panOnScrollSpeed:c=.5,panOnScrollMode:f=ic.Free,zoomOnDoubleClick:_=!0,elementsSelectable:p,panOnDrag:w=!0,defaultViewport:y,translateExtent:x,minZoom:S,maxZoom:b,zoomActivationKeyCode:$,preventScrolling:E=!0,children:L,noWheelClassName:D,noPanClassName:M})=>{const H=m.useRef(),Z=Ns(),Y=m.useRef(!1),X=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(_T,Fs),O=vf($),P=m.useRef(0),ne=m.useRef(!1),B=m.useRef();return hT(re),m.useEffect(()=>{if(re.current){const z=re.current.getBoundingClientRect(),G=sb().scaleExtent([S,b]).translateExtent(x),T=Si(re.current).call(G),Q=ha.translate(y.x,y.y).scale(zu(y.zoom,S,b)),K=[[0,0],[z.width,z.height]],J=G.constrain()(Q,K,x);G.transform(T,J),G.wheelDelta(Ew),Z.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&&!O&&!N?F.on("wheel.zoom",z=>{if(bu(z,D))return!1;z.preventDefault(),z.stopImmediatePropagation();const G=F.property("__zoom").k||1,T=Mm();if(z.ctrlKey&&l&&T){const Ae=Xi(z),Be=Ew(z),We=G*Math.pow(2,Be);ue.scaleTo(F,We,Ae,z);return}const Q=z.deltaMode===1?20:1;let K=f===ic.Vertical?0:z.deltaX*Q,J=f===ic.Horizontal?0:z.deltaY*Q;!T&&z.shiftKey&&f!==ic.Vertical&&(K=z.deltaY*Q,J=0),ue.translateBy(F,-(K/G)*c,-(J/G)*c,{internal:!0});const oe=nm(F.property("__zoom")),{onViewportChangeStart:fe,onViewportChange:me,onViewportChangeEnd:we}=Z.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),me==null||me(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(!E||bu(z,D))return null;z.preventDefault(),C.call(this,z,G)},{passive:!1}))},[N,u,f,F,ue,C,O,l,E,D,t,e,n]),m.useEffect(()=>{ue&&ue.on("start",z=>{var Q,K;if(!z.sourceEvent||z.sourceEvent.internal)return null;P.current=(Q=z.sourceEvent)==null?void 0:Q.button;const{onViewportChangeStart:G}=Z.getState(),T=nm(z.transform);Y.current=!0,ie.current=T,((K=z.sourceEvent)==null?void 0:K.type)==="mousedown"&&Z.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}=Z.getState();if(Z.setState({transform:[z.transform.x,z.transform.y,z.transform.k]}),X.current=!!(i&&Aw(w,P.current??0)),(e||G)&&!((T=z.sourceEvent)!=null&&T.internal)){const Q=nm(z.transform);G==null||G(Q),e==null||e(z.sourceEvent,Q)}}))},[N,ue,e,w,i]),m.useEffect(()=>{ue&&ue.on("end",z=>{if(!z.sourceEvent||z.sourceEvent.internal)return null;const{onViewportChangeEnd:G}=Z.getState();if(Y.current=!1,Z.setState({paneDragging:!1}),i&&Aw(w,P.current??0)&&!X.current&&i(z.sourceEvent),X.current=!1,(n||G)&&mT(ie.current,z.transform)){const T=nm(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,w,n,i]),m.useEffect(()=>{ue&&ue.filter(z=>{const G=O||o,T=l&&z.ctrlKey;if((w===!0||Array.isArray(w)&&w.includes(1))&&z.button===1&&z.type==="mousedown"&&(bu(z,"react-flow__node")||bu(z,"react-flow__edge")))return!0;if(!w&&!G&&!u&&!_&&!l||N||!_&&z.type==="dblclick"||bu(z,D)&&z.type==="wheel"||bu(z,M)&&(z.type!=="wheel"||u&&z.type==="wheel"&&!O)||!l&&z.ctrlKey&&z.type==="wheel"||!G&&!u&&!T&&z.type==="wheel"||!w&&(z.type==="mousedown"||z.type==="touchstart")||Array.isArray(w)&&!w.includes(z.button)&&(z.type==="mousedown"||z.type==="touchstart"))return!1;const Q=Array.isArray(w)&&w.includes(z.button)||!z.button||z.button<=1;return(!z.ctrlKey||z.type==="wheel")&&Q})},[N,ue,o,l,u,_,w,p,O]),ve.createElement("div",{className:"react-flow__renderer",ref:re,style:Rg},L)},gT=e=>({userSelectionActive:e.userSelectionActive,userSelectionRect:e.userSelectionRect});function yT(){const{userSelectionActive:e,userSelectionRect:t}=Rn(gT,Fs);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 Tw(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 wT(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&&Tw(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&&Tw(i,u);break}case"remove":return i}return i.push(u),i},n)}function vT(e,t){return wT(e,t)}const al=(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(al(i.id,!0))):i.selected&&!o&&(i.selected=!1,n.push(al(i.id,!1))),n},[])}const Q_=(e,t)=>n=>{n.target===t.current&&(e==null||e(n))},xT=e=>({userSelectionActive:e.userSelectionActive,elementsSelectable:e.elementsSelectable,dragging:e.paneDragging}),Lb=m.memo(({isSelecting:e,selectionMode:t=yf.Full,panOnDrag:n,onSelectionStart:i,onSelectionEnd:o,onPaneClick:l,onPaneContextMenu:u,onPaneScroll:c,onPaneMouseEnter:f,onPaneMouseMove:_,onPaneMouseLeave:p,children:w})=>{const y=m.useRef(null),x=Ns(),S=m.useRef(0),b=m.useRef(0),$=m.useRef(),{userSelectionActive:E,elementsSelectable:L,dragging:D}=Rn(xT,Fs),M=()=>{x.setState({userSelectionActive:!1,userSelectionRect:null}),S.current=0,b.current=0},H=C=>{l==null||l(C),x.getState().resetSelectedElements(),x.setState({nodesSelectionActive:!1})},Z=C=>{if(Array.isArray(n)&&(n!=null&&n.includes(2))){C.preventDefault();return}u==null||u(C)},Y=c?C=>c(C):void 0,X=C=>{const{resetSelectedElements:N,domNode:O}=x.getState();if($.current=O==null?void 0:O.getBoundingClientRect(),!L||!e||C.button!==0||C.target!==y.current||!$.current)return;const{x:P,y:ne}=ul(C,$.current);N(),x.setState({userSelectionRect:{width:0,height:0,startX:P,startY:ne,x:P,y:ne}}),i==null||i(C)},re=C=>{const{userSelectionRect:N,nodeInternals:O,edges:P,transform:ne,onNodesChange:B,onEdgesChange:z,nodeOrigin:G,getNodes:T}=x.getState();if(!e||!$.current||!N)return;x.setState({userSelectionActive:!0,nodesSelectionActive:!1});const Q=ul(C,$.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(),me=pb(O,oe,ne,t===yf.Partial,!0,G),we=gb(me,P).map(Be=>Be.id),Ae=me.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(b.current!==we.length){b.current=we.length;const Be=$u(P,we);Be.length&&(z==null||z(Be))}x.setState({userSelectionRect:oe})},ie=C=>{if(C.button!==0)return;const{userSelectionRect:N}=x.getState();!E&&N&&C.target===y.current&&(H==null||H(C)),x.setState({nodesSelectionActive:S.current>0}),M(),o==null||o(C)},ue=C=>{E&&(x.setState({nodesSelectionActive:S.current>0}),o==null||o(C)),M()},F=L&&(e||E);return ve.createElement("div",{className:Ys(["react-flow__pane",{dragging:D,selection:e}]),onClick:F?void 0:Q_(H,y),onContextMenu:Q_(Z,y),onWheel:Q_(Y,y),onMouseEnter:F?void 0:f,onMouseDown:F?X:void 0,onMouseMove:F?re:_,onMouseUp:F?ie:void 0,onMouseLeave:F?ue:p,ref:y,style:Rg},w,ve.createElement(yT,null))});Lb.displayName="Pane";function Ib(e,t){if(!e.parentNode)return!1;const n=t.get(e.parentNode);return n?n.selected?!0:Ib(n,t):!1}function Mw(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 bT(e,t,n,i){return Array.from(e.values()).filter(o=>(o.selected||o.id===i)&&(!o.parentNode||!Ib(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 jT(e,t){return!t||t==="parent"?t:[t[0],[t[1][0]-(e.width||0),t[1][1]-(e.height||0)]]}function Ob(e,t,n,i,o=[0,0],l){const u=jT(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:w,y}=uc(p,o).positionAbsolute;c=p&&ki(w)&&ki(y)&&ki(p.width)&&ki(p.height)?[[w+e.width*o[0],y+e.height*o[1]],[w+p.width-e.width+e.width*o[0],y+p.height-e.height+e.height*o[1]]]:c}else l==null||l("005",ga.error005()),c=u;else if(e.extent&&e.parentNode&&e.extent!=="parent"){const p=n.get(e.parentNode),{x:w,y}=uc(p,o).positionAbsolute;c=[[e.extent[0][0]+w,e.extent[0][1]+y],[e.extent[1][0]+w,e.extent[1][1]+y]]}let f={x:0,y:0};if(e.parentNode){const p=n.get(e.parentNode);f=uc(p,o).positionAbsolute}const _=c&&c!=="parent"?kg(t,c):t;return{position:{x:_.x-f.x,y:_.y-f.y},positionAbsolute:_}}function ep({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 Rw=(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,...Sg(f)}})};function Jd(e,t,n){return n===void 0?n:i=>{const o=t().nodeInternals.get(e);o&&n(i,{...o})}}function Gp({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",ga.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 ST(){const e=Ns();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 tp(e){return(t,n,i)=>e==null?void 0:e(t,i)}function Pb({nodeRef:e,disabled:t=!1,noDragClassName:n,handleSelector:i,nodeId:o,isSelectable:l,selectNodesOnDrag:u}){const c=Ns(),[f,_]=m.useState(!1),p=m.useRef([]),w=m.useRef({x:null,y:null}),y=m.useRef(0),x=m.useRef(null),S=m.useRef({x:0,y:0}),b=m.useRef(null),$=m.useRef(!1),E=m.useRef(!1),L=ST();return m.useEffect(()=>{if(e!=null&&e.current){const D=Si(e.current),M=({x:Y,y:X})=>{const{nodeInternals:re,onNodeDrag:ie,onSelectionDrag:ue,updateNodePositions:F,nodeExtent:C,snapGrid:N,snapToGrid:O,nodeOrigin:P,onError:ne}=c.getState();w.current={x:Y,y:X};let B=!1,z={x:0,y:0,x2:0,y2:0};if(p.current.length>1&&C){const T=Ym(p.current,P);z=gf(T)}if(p.current=p.current.map(T=>{const Q={x:Y-T.distance.x,y:X-T.distance.y};O&&(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=Ob(T,Q,re,K,P,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:tp(ue);if(G&&b.current){const[T,Q]=ep({nodeId:o,dragItems:p.current,nodeInternals:re});G(b.current,T,Q)}},H=()=>{if(!x.current)return;const[Y,X]=ib(S.current,x.current);if(Y!==0||X!==0){const{transform:re,panBy:ie}=c.getState();w.current.x=(w.current.x??0)-Y/re[2],w.current.y=(w.current.y??0)-X/re[2],ie({x:Y,y:X})&&M(w.current)}y.current=requestAnimationFrame(H)},Z=Y=>{var P;const{nodeInternals:X,multiSelectionActive:re,nodesDraggable:ie,unselectNodesAndEdges:ue,onNodeDragStart:F,onSelectionDragStart:C}=c.getState();E.current=!0;const N=o?F:tp(C);(!u||!l)&&!re&&o&&((P=X.get(o))!=null&&P.selected||ue()),o&&l&&u&&Gp({id:o,store:c,nodeRef:e});const O=L(Y);if(w.current=O,p.current=bT(X,ie,O,o),N&&p.current){const[ne,B]=ep({nodeId:o,dragItems:p.current,nodeInternals:X});N(Y.sourceEvent,ne,B)}};if(t)D.on(".drag",null);else{const Y=L$().on("start",X=>{const{domNode:re,nodeDragThreshold:ie}=c.getState();ie===0&&Z(X);const ue=L(X);w.current=ue,x.current=(re==null?void 0:re.getBoundingClientRect())||null,S.current=ul(X.sourceEvent,x.current)}).on("drag",X=>{var F,C;const re=L(X),{autoPanOnNodeDrag:ie,nodeDragThreshold:ue}=c.getState();if(!$.current&&E.current&&ie&&($.current=!0,H()),!E.current){const N=re.xSnapped-(((F=w==null?void 0:w.current)==null?void 0:F.x)??0),O=re.ySnapped-(((C=w==null?void 0:w.current)==null?void 0:C.y)??0);Math.sqrt(N*N+O*O)>ue&&Z(X)}(w.current.x!==re.xSnapped||w.current.y!==re.ySnapped)&&p.current&&E.current&&(b.current=X.sourceEvent,S.current=ul(X.sourceEvent,x.current),M(re))}).on("end",X=>{if(E.current&&(_(!1),$.current=!1,E.current=!1,cancelAnimationFrame(y.current),p.current)){const{updateNodePositions:re,nodeInternals:ie,onNodeDragStop:ue,onSelectionDragStop:F}=c.getState(),C=o?ue:tp(F);if(re(p.current,!1,!1),C){const[N,O]=ep({nodeId:o,dragItems:p.current,nodeInternals:ie});C(X.sourceEvent,N,O)}}}).filter(X=>{const re=X.target;return!X.button&&(!n||!Mw(re,`.${n}`,e))&&(!i||Mw(re,i,e))});return D.call(Y),()=>{D.on(".drag",null)}}}},[e,t,n,i,l,c,o,u,L]),f}function Db(){const e=Ns();return m.useCallback(n=>{const{nodeInternals:i,nodeExtent:o,updateNodePositions:l,getNodes:u,snapToGrid:c,snapGrid:f,onError:_,nodesDraggable:p}=e.getState(),w=u().filter(L=>L.selected&&(L.draggable||p&&typeof L.draggable>"u")),y=c?f[0]:5,x=c?f[1]:5,S=n.isShiftPressed?4:1,b=n.x*y*S,$=n.y*x*S,E=w.map(L=>{if(L.positionAbsolute){const D={x:L.positionAbsolute.x+b,y:L.positionAbsolute.y+$};c&&(D.x=f[0]*Math.round(D.x/f[0]),D.y=f[1]*Math.round(D.y/f[1]));const{positionAbsolute:M,position:H}=Ob(L,D,i,o,void 0,_);L.position=H,L.positionAbsolute=M}return L});l(E,!0,!1)},[])}const Lu={ArrowUp:{x:0,y:-1},ArrowDown:{x:0,y:1},ArrowLeft:{x:-1,y:0},ArrowRight:{x:1,y:0}};var Xd=e=>{const t=({id:n,type:i,data:o,xPos:l,yPos:u,xPosOrigin:c,yPosOrigin:f,selected:_,onClick:p,onMouseEnter:w,onMouseMove:y,onMouseLeave:x,onContextMenu:S,onDoubleClick:b,style:$,className:E,isDraggable:L,isSelectable:D,isConnectable:M,isFocusable:H,selectNodesOnDrag:Z,sourcePosition:Y,targetPosition:X,hidden:re,resizeObserver:ie,dragHandle:ue,zIndex:F,isParent:C,noDragClassName:N,noPanClassName:O,initialized:P,disableKeyboardA11y:ne,ariaLabel:B,rfId:z,hasHandleBounds:G})=>{const T=Ns(),Q=m.useRef(null),K=m.useRef(Y),J=m.useRef(X),oe=m.useRef(i),fe=D||L||p||w||y||x,me=Db(),we=Jd(n,T.getState,w),Ae=Jd(n,T.getState,y),Be=Jd(n,T.getState,x),We=Jd(n,T.getState,S),_t=Jd(n,T.getState,b),Pe=Ye=>{const{nodeDragThreshold:Se}=T.getState();if(D&&(!Z||!L||Se>0)&&Gp({id:n,store:T,nodeRef:Q}),p){const Le=T.getState().nodeInternals.get(n);Le&&p(Ye,{...Le})}},et=Ye=>{if(!Up(Ye))if(cb.includes(Ye.key)&&D){const Se=Ye.key==="Escape";Gp({id:n,store:T,unselect:Se,nodeRef:Q})}else!ne&&L&&_&&Object.prototype.hasOwnProperty.call(Lu,Ye.key)&&(T.setState({ariaLiveMessage:`Moved selected node ${Ye.key.replace("Arrow","").toLowerCase()}. New position, x: ${~~l}, y: ${~~u}`}),me({x:Lu[Ye.key].x,y:Lu[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;(!P||!G)&&(ie==null||ie.unobserve(Ye),ie==null||ie.observe(Ye))}},[re,P,G]),m.useEffect(()=>{const Ye=oe.current!==i,Se=K.current!==Y,Le=J.current!==X;Q.current&&(Ye||Se||Le)&&(Ye&&(oe.current=i),Se&&(K.current=Y),Le&&(J.current=X),T.getState().updateNodeDimensions([{id:n,nodeElement:Q.current,forceUpdate:!0}]))},[n,i,Y,X]);const lt=Pb({nodeRef:Q,disabled:re||!L,noDragClassName:N,handleSelector:ue,nodeId:n,isSelectable:D,selectNodesOnDrag:Z});return re?null:ve.createElement("div",{className:Ys(["react-flow__node",`react-flow__node-${i}`,{[O]:L},E,{selected:_,selectable:D,parent:C,dragging:lt}]),ref:Q,style:{zIndex:F,transform:`translate(${c}px,${f}px)`,pointerEvents:fe?"all":"none",visibility:P?"visible":"hidden",...$},"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:`${Ab}-${z}`,"aria-label":B},ve.createElement(PE,{value:n},ve.createElement(e,{id:n,data:o,type:i,xPos:l,yPos:u,selected:_,isConnectable:M,sourcePosition:Y,targetPosition:X,dragging:lt,dragHandle:ue,zIndex:F})))};return t.displayName="NodeWrapper",m.memo(t)};const kT=e=>{const t=e.getNodes().filter(n=>n.selected);return{...Ym(t,e.nodeOrigin),transformString:`translate(${e.transform[0]}px,${e.transform[1]}px) scale(${e.transform[2]})`,userSelectionActive:e.userSelectionActive}};function NT({onSelectionContextMenu:e,noPanClassName:t,disableKeyboardA11y:n}){const i=Ns(),{width:o,height:l,x:u,y:c,transformString:f,userSelectionActive:_}=Rn(kT,Fs),p=Db(),w=m.useRef(null);if(m.useEffect(()=>{var S;n||(S=w.current)==null||S.focus({preventScroll:!0})},[n]),Pb({nodeRef:w}),_||!o||!l)return null;const y=e?S=>{const b=i.getState().getNodes().filter($=>$.selected);e(S,b)}:void 0,x=S=>{Object.prototype.hasOwnProperty.call(Lu,S.key)&&p({x:Lu[S.key].x,y:Lu[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:w,className:"react-flow__nodesselection-rect",onContextMenu:y,tabIndex:n?void 0:-1,onKeyDown:n?void 0:x,style:{width:o,height:l,top:c,left:u}}))}var CT=m.memo(NT);const $T=e=>e.nodesSelectionActive,Fb=({children:e,onPaneClick:t,onPaneMouseEnter:n,onPaneMouseMove:i,onPaneMouseLeave:o,onPaneContextMenu:l,onPaneScroll:u,deleteKeyCode:c,onMove:f,onMoveStart:_,onMoveEnd:p,selectionKeyCode:w,selectionOnDrag:y,selectionMode:x,onSelectionStart:S,onSelectionEnd:b,multiSelectionKeyCode:$,panActivationKeyCode:E,zoomActivationKeyCode:L,elementsSelectable:D,zoomOnScroll:M,zoomOnPinch:H,panOnScroll:Z,panOnScrollSpeed:Y,panOnScrollMode:X,zoomOnDoubleClick:re,panOnDrag:ie,defaultViewport:ue,translateExtent:F,minZoom:C,maxZoom:N,preventScrolling:O,onSelectionContextMenu:P,noWheelClassName:ne,noPanClassName:B,disableKeyboardA11y:z})=>{const G=Rn($T),T=vf(w),Q=vf(E),K=Q||ie,J=Q||Z,oe=T||y&&K!==!0;return fT({deleteKeyCode:c,multiSelectionKeyCode:$}),ve.createElement(pT,{onMove:f,onMoveStart:_,onMoveEnd:p,onPaneContextMenu:l,elementsSelectable:D,zoomOnScroll:M,zoomOnPinch:H,panOnScroll:J,panOnScrollSpeed:Y,panOnScrollMode:X,zoomOnDoubleClick:re,panOnDrag:!T&&K,defaultViewport:ue,translateExtent:F,minZoom:C,maxZoom:N,zoomActivationKeyCode:L,preventScrolling:O,noWheelClassName:ne,noPanClassName:B},ve.createElement(Lb,{onSelectionStart:S,onSelectionEnd:b,onPaneClick:t,onPaneMouseEnter:n,onPaneMouseMove:i,onPaneMouseLeave:o,onPaneContextMenu:l,onPaneScroll:u,panOnDrag:K,isSelecting:!!oe,selectionMode:x},e,G&&ve.createElement(CT,{onSelectionContextMenu:P,noPanClassName:B,disableKeyboardA11y:z})))};Fb.displayName="FlowRenderer";var AT=m.memo(Fb);function ET(e){return Rn(m.useCallback(n=>e?pb(n.nodeInternals,{x:0,y:0,width:n.width,height:n.height},n.transform,!0):n.getNodes(),[e]))}function TT(e){const t={input:Xd(e.input||kb),default:Xd(e.default||Vp),output:Xd(e.output||Cb),group:Xd(e.group||Tg)},n={},i=Object.keys(e).filter(o=>!["input","default","output","group"].includes(o)).reduce((o,l)=>(o[l]=Xd(e[l]||Vp),o),n);return{...t,...i}}const MT=({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]},RT=e=>({nodesDraggable:e.nodesDraggable,nodesConnectable:e.nodesConnectable,nodesFocusable:e.nodesFocusable,elementsSelectable:e.elementsSelectable,updateNodeDimensions:e.updateNodeDimensions,onError:e.onError}),zb=e=>{const{nodesDraggable:t,nodesConnectable:n,nodesFocusable:i,elementsSelectable:o,updateNodeDimensions:l,onError:u}=Rn(RT,Fs),c=ET(e.onlyRenderVisibleElements),f=m.useRef(),_=m.useMemo(()=>{if(typeof ResizeObserver>"u")return null;const p=new ResizeObserver(w=>{const y=w.map(x=>({id:x.target.getAttribute("data-id"),nodeElement:x.target,forceUpdate:!0}));l(y)});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:Rg},c.map(p=>{var H,Z,Y;let w=p.type||"default";e.nodeTypes[w]||(u==null||u("003",ga.error003(w)),w="default");const y=e.nodeTypes[w]||e.nodeTypes.default,x=!!(p.draggable||t&&typeof p.draggable>"u"),S=!!(p.selectable||o&&typeof p.selectable>"u"),b=!!(p.connectable||n&&typeof p.connectable>"u"),$=!!(p.focusable||i&&typeof p.focusable>"u"),E=e.nodeExtent?kg(p.positionAbsolute,e.nodeExtent):p.positionAbsolute,L=(E==null?void 0:E.x)??0,D=(E==null?void 0:E.y)??0,M=MT({x:L,y:D,width:p.width??0,height:p.height??0,origin:e.nodeOrigin});return ve.createElement(y,{key:p.id,id:p.id,className:p.className,style:p.style,type:w,data:p.data,sourcePosition:p.sourcePosition||mt.Bottom,targetPosition:p.targetPosition||mt.Top,hidden:p.hidden,xPos:L,yPos:D,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:b,isFocusable:$,resizeObserver:_,dragHandle:p.dragHandle,zIndex:((H=p[ps])==null?void 0:H.z)??0,isParent:!!((Z=p[ps])!=null&&Z.isParent),noDragClassName:e.noDragClassName,noPanClassName:e.noPanClassName,initialized:!!p.width&&!!p.height,rfId:e.rfId,disableKeyboardA11y:e.disableKeyboardA11y,ariaLabel:p.ariaLabel,hasHandleBounds:!!((Y=p[ps])!=null&&Y.handleBounds)})}))};zb.displayName="NodeRenderer";var LT=m.memo(zb);const IT=(e,t,n)=>n===mt.Left?e-t:n===mt.Right?e+t:e,OT=(e,t,n)=>n===mt.Top?e-t:n===mt.Bottom?e+t:e,Lw="react-flow__edgeupdater",Iw=({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([Lw,`${Lw}-${c}`]),cx:IT(t,i,e),cy:OT(n,i,e),r:i,stroke:"transparent",fill:"transparent"}),PT=()=>!0;var ju=e=>{const t=({id:n,className:i,type:o,data:l,onClick:u,onEdgeDoubleClick:c,selected:f,animated:_,label:p,labelStyle:w,labelShowBg:y,labelBgStyle:x,labelBgPadding:S,labelBgBorderRadius:b,style:$,source:E,target:L,sourceX:D,sourceY:M,targetX:H,targetY:Z,sourcePosition:Y,targetPosition:X,elementsSelectable:re,hidden:ie,sourceHandleId:ue,targetHandleId:F,onContextMenu:C,onMouseEnter:N,onMouseMove:O,onMouseLeave:P,edgeUpdaterRadius:ne,onEdgeUpdate:B,onEdgeUpdateStart:z,onEdgeUpdateEnd:G,markerEnd:T,markerStart:Q,rfId:K,ariaLabel:J,isFocusable:oe,isUpdatable:fe,pathOptions:me,interactionWidth:we})=>{const Ae=m.useRef(null),[Be,We]=m.useState(!1),[_t,Pe]=m.useState(!1),et=Ns(),lt=m.useMemo(()=>`url('#${qp(Q,K)}')`,[Q,K]),Ye=m.useMemo(()=>`url('#${qp(T,K)}')`,[T,K]);if(ie)return null;const Se=Mt=>{var wn;const{edges:bn,addSelectedEdges:Dn,unselectNodesAndEdges:En,multiSelectionActive:jn}=et.getState(),Ln=bn.find(Cs=>Cs.id===n);Ln&&(re&&(et.setState({nodesSelectionActive:!1}),Ln.selected&&jn?(En({nodes:[],edges:[Ln]}),(wn=Ae.current)==null||wn.blur()):Dn([n])),u&&u(Mt,Ln))},Le=Yd(n,et.getState,c),ct=Yd(n,et.getState,C),ge=Yd(n,et.getState,N),De=Yd(n,et.getState,O),Ke=Yd(n,et.getState,P),Dt=(Mt,bn)=>{if(Mt.button!==0)return;const{edges:Dn,isValidConnection:En}=et.getState(),jn=bn?L:E,Ln=(bn?F:ue)||null,wn=bn?"target":"source",Cs=En||PT,Kn=bn,ls=Dn.find(ce=>ce.id===n);Pe(!0),z==null||z(Mt,ls,wn);const Cr=ce=>{Pe(!1),G==null||G(ce,ls,wn)};xb({event:Mt,handleId:Ln,nodeId:jn,onConnect:ce=>B==null?void 0:B(ls,ce),isTarget:Kn,getState:et.getState,setState:et.setState,isValidConnection:Cs,edgeUpdaterType:wn,onEdgeUpdateEnd:Cr})},Qt=Mt=>Dt(Mt,!0),_n=Mt=>Dt(Mt,!1),Ut=()=>We(!0),It=()=>We(!1),un=!re&&!u,Bn=Mt=>{var bn;if(cb.includes(Mt.key)&&re){const{unselectNodesAndEdges:Dn,addSelectedEdges:En,edges:jn}=et.getState();Mt.key==="Escape"?((bn=Ae.current)==null||bn.blur(),Dn({edges:[jn.find(wn=>wn.id===n)]})):En([n])}};return ve.createElement("g",{className:Ys(["react-flow__edge",`react-flow__edge-${o}`,i,{selected:f,animated:_,inactive:un,updating:Be}]),onClick:Se,onDoubleClick:Le,onContextMenu:ct,onMouseEnter:ge,onMouseMove:De,onMouseLeave:Ke,onKeyDown:oe?Bn: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 ${E} to ${L}`,"aria-describedby":oe?`${Eb}-${K}`:void 0,ref:Ae},!_t&&ve.createElement(e,{id:n,source:E,target:L,selected:f,animated:_,label:p,labelStyle:w,labelShowBg:y,labelBgStyle:x,labelBgPadding:S,labelBgBorderRadius:b,data:l,style:$,sourceX:D,sourceY:M,targetX:H,targetY:Z,sourcePosition:Y,targetPosition:X,sourceHandleId:ue,targetHandleId:F,markerStart:lt,markerEnd:Ye,pathOptions:me,interactionWidth:we}),fe&&ve.createElement(ve.Fragment,null,(fe==="source"||fe===!0)&&ve.createElement(Iw,{position:Y,centerX:D,centerY:M,radius:ne,onMouseDown:Qt,onMouseEnter:Ut,onMouseOut:It,type:"source"}),(fe==="target"||fe===!0)&&ve.createElement(Iw,{position:X,centerX:H,centerY:Z,radius:ne,onMouseDown:_n,onMouseEnter:Ut,onMouseOut:It,type:"target"})))};return t.displayName="EdgeWrapper",m.memo(t)};function DT(e){const t={default:ju(e.default||Rm),straight:ju(e.bezier||$g),step:ju(e.step||Cg),smoothstep:ju(e.step||Km),simplebezier:ju(e.simplebezier||Ng)},n={},i=Object.keys(e).filter(o=>!["default","bezier"].includes(o)).reduce((o,l)=>(o[l]=ju(e[l]||Rm),o),n);return{...t,...i}}function Ow(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 Pw(e,t){return e?e.length===1||!t?e[0]:t&&e.find(n=>n.id===t)||null:null}const FT=(e,t,n,i,o,l)=>{const u=Ow(n,e,t),c=Ow(l,i,o);return{sourceX:u.x,sourceY:u.y,targetX:c.x,targetY:c.y}};function zT({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=gf({x:(0-f[0])/f[2],y:(0-f[1])/f[2],width:u/f[2],height:c/f[2]}),w=Math.max(0,Math.min(p.x2,_.x2)-Math.max(p.x,_.x)),y=Math.max(0,Math.min(p.y2,_.y2)-Math.max(p.y,_.y));return Math.ceil(w*y)>0}function Dw(e){var i,o,l,u,c;const t=((i=e==null?void 0:e[ps])==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 BT=[{level:0,isMaxLevel:!0,edges:[]}];function UT(e,t,n=!1){let i=-1;const o=e.reduce((u,c)=>{var p,w;const f=ki(c.zIndex);let _=f?c.zIndex:0;if(n){const y=t.get(c.target),x=t.get(c.source),S=c.selected||(y==null?void 0:y.selected)||(x==null?void 0:x.selected),b=Math.max(((p=x==null?void 0:x[ps])==null?void 0:p.z)||0,((w=y==null?void 0:y[ps])==null?void 0:w.z)||0,1e3);_=(f?c.zIndex:0)+(S?b: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?BT:l}function WT(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)&&zT({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 UT(i,t,n)}const qT=({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"}),HT=({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"}),Fw={[wf.Arrow]:qT,[wf.ArrowClosed]:HT};function VT(e){const t=Ns();return m.useMemo(()=>{var o,l;return Object.prototype.hasOwnProperty.call(Fw,e)?Fw[e]:((l=(o=t.getState()).onError)==null||l.call(o,"009",ga.error009(e)),null)},[e])}const GT=({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=VT(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},KT=({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=qp(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))},Bb=({defaultColor:e,rfId:t})=>{const n=Rn(m.useCallback(KT({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(GT,{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})))};Bb.displayName="MarkerDefinitions";var YT=m.memo(Bb);const JT=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}),Ub=({defaultMarkerColor:e,onlyRenderVisibleElements:t,elevateEdgesOnSelect:n,rfId:i,edgeTypes:o,noPanClassName:l,onEdgeUpdate:u,onEdgeContextMenu:c,onEdgeMouseEnter:f,onEdgeMouseMove:_,onEdgeMouseLeave:p,onEdgeClick:w,edgeUpdaterRadius:y,onEdgeDoubleClick:x,onEdgeUpdateStart:S,onEdgeUpdateEnd:b,children:$})=>{const{edgesFocusable:E,edgesUpdatable:L,elementsSelectable:D,width:M,height:H,connectionMode:Z,nodeInternals:Y,onError:X}=Rn(JT,Fs),re=WT(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(YT,{defaultColor:e,rfId:i}),ve.createElement("g",null,ue.map(C=>{const[N,O,P]=Dw(Y.get(C.source)),[ne,B,z]=Dw(Y.get(C.target));if(!P||!z)return null;let G=C.type||"default";o[G]||(X==null||X("011",ga.error011(G)),G="default");const T=o[G]||o.default,Q=Z===mc.Strict?B.target:(B.target??[]).concat(B.source??[]),K=Pw(O.source,C.sourceHandle),J=Pw(Q,C.targetHandle),oe=(K==null?void 0:K.position)||mt.Bottom,fe=(J==null?void 0:J.position)||mt.Top,me=!!(C.focusable||E&&typeof C.focusable>"u"),we=typeof u<"u"&&(C.updatable||L&&typeof C.updatable>"u");if(!K||!J)return X==null||X("008",ga.error008(K,C)),null;const{sourceX:Ae,sourceY:Be,targetX:We,targetY:_t}=FT(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:D,onEdgeUpdate:u,onContextMenu:c,onMouseEnter:f,onMouseMove:_,onMouseLeave:p,onClick:w,edgeUpdaterRadius:y,onEdgeDoubleClick:x,onEdgeUpdateStart:S,onEdgeUpdateEnd:b,rfId:i,ariaLabel:C.ariaLabel,isFocusable:me,isUpdatable:we,pathOptions:"pathOptions"in C?C.pathOptions:void 0,interactionWidth:C.interactionWidth})})))),$):null};Ub.displayName="EdgeRenderer";var XT=m.memo(Ub);const ZT=e=>`translate(${e.transform[0]}px,${e.transform[1]}px) scale(${e.transform[2]})`;function QT({children:e}){const t=Rn(ZT);return ve.createElement("div",{className:"react-flow__viewport react-flow__container",style:{transform:t}},e)}function eM(e){const t=Mg(),n=m.useRef(!1);m.useEffect(()=>{!n.current&&t.viewportInitialized&&e&&(setTimeout(()=>e(t),1),n.current=!0)},[e,t.viewportInitialized])}const tM={[mt.Left]:mt.Right,[mt.Right]:mt.Left,[mt.Top]:mt.Bottom,[mt.Bottom]:mt.Top},Wb=({nodeId:e,handleType:t,style:n,type:i=cl.Bezier,CustomComponent:o,connectionStatus:l})=>{var Z,Y,X;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]),Fs),w=(Z=u==null?void 0:u[ps])==null?void 0:Z.handleBounds;let y=w==null?void 0:w[t];if(p===mc.Loose&&(y=y||(w==null?void 0:w[t==="source"?"target":"source"])),!u||!y)return null;const x=c?y.find(re=>re.id===c):y[0],S=x?x.x+x.width/2:(u.width??0)/2,b=x?x.y+x.height/2:u.height??0,$=(((Y=u.positionAbsolute)==null?void 0:Y.x)??0)+S,E=(((X=u.positionAbsolute)==null?void 0:X.y)??0)+b,L=x==null?void 0:x.position,D=L?tM[L]:null;if(!L||!D)return null;if(o)return ve.createElement(o,{connectionLineType:i,connectionLineStyle:n,fromNode:u,fromHandle:x,fromX:$,fromY:E,toX:f,toY:_,fromPosition:L,toPosition:D,connectionStatus:l});let M="";const H={sourceX:$,sourceY:E,sourcePosition:L,targetX:f,targetY:_,targetPosition:D};return i===cl.Bezier?[M]=mb(H):i===cl.Step?[M]=Wp({...H,borderRadius:0}):i===cl.SmoothStep?[M]=Wp(H):i===cl.SimpleBezier?[M]=hb(H):M=`M${$},${E} ${f},${_}`,ve.createElement("path",{d:M,fill:"none",className:"react-flow__connection-path",style:n})};Wb.displayName="ConnectionLine";const nM=e=>({nodeId:e.connectionNodeId,handleType:e.connectionHandleType,nodesConnectable:e.nodesConnectable,connectionStatus:e.connectionStatus,width:e.width,height:e.height});function sM({containerStyle:e,style:t,type:n,component:i}){const{nodeId:o,handleType:l,nodesConnectable:u,width:c,height:f,connectionStatus:_}=Rn(nM,Fs);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(Wb,{nodeId:o,handleType:l,style:t,type:n,CustomComponent:i,connectionStatus:_})))}function zw(e,t){return m.useRef(null),Ns(),m.useMemo(()=>t(e),[e])}const qb=({nodeTypes:e,edgeTypes:t,onMove:n,onMoveStart:i,onMoveEnd:o,onInit:l,onNodeClick:u,onEdgeClick:c,onNodeDoubleClick:f,onEdgeDoubleClick:_,onNodeMouseEnter:p,onNodeMouseMove:w,onNodeMouseLeave:y,onNodeContextMenu:x,onSelectionContextMenu:S,onSelectionStart:b,onSelectionEnd:$,connectionLineType:E,connectionLineStyle:L,connectionLineComponent:D,connectionLineContainerStyle:M,selectionKeyCode:H,selectionOnDrag:Z,selectionMode:Y,multiSelectionKeyCode:X,panActivationKeyCode:re,zoomActivationKeyCode:ie,deleteKeyCode:ue,onlyRenderVisibleElements:F,elementsSelectable:C,selectNodesOnDrag:N,defaultViewport:O,translateExtent:P,minZoom:ne,maxZoom:B,preventScrolling:z,defaultMarkerColor:G,zoomOnScroll:T,zoomOnPinch:Q,panOnScroll:K,panOnScrollSpeed:J,panOnScrollMode:oe,zoomOnDoubleClick:fe,panOnDrag:me,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:Qt,elevateEdgesOnSelect:_n,disableKeyboardA11y:Ut,nodeOrigin:It,nodeExtent:un,rfId:Bn})=>{const Mt=zw(e,TT),bn=zw(t,DT);return eM(l),ve.createElement(AT,{onPaneClick:we,onPaneMouseEnter:Ae,onPaneMouseMove:Be,onPaneMouseLeave:We,onPaneContextMenu:Pe,onPaneScroll:_t,deleteKeyCode:ue,selectionKeyCode:H,selectionOnDrag:Z,selectionMode:Y,onSelectionStart:b,onSelectionEnd:$,multiSelectionKeyCode:X,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:me,defaultViewport:O,translateExtent:P,minZoom:ne,maxZoom:B,onSelectionContextMenu:S,preventScrolling:z,noDragClassName:Ke,noWheelClassName:Dt,noPanClassName:Qt,disableKeyboardA11y:Ut},ve.createElement(QT,null,ve.createElement(XT,{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:Qt,elevateEdgesOnSelect:!!_n,disableKeyboardA11y:Ut,rfId:Bn},ve.createElement(sM,{style:L,type:E,component:D,containerStyle:M})),ve.createElement("div",{className:"react-flow__edgelabel-renderer"}),ve.createElement(LT,{nodeTypes:Mt,onNodeClick:u,onNodeDoubleClick:f,onNodeMouseEnter:p,onNodeMouseMove:w,onNodeMouseLeave:y,onNodeContextMenu:x,selectNodesOnDrag:N,onlyRenderVisibleElements:F,noPanClassName:Qt,noDragClassName:Ke,disableKeyboardA11y:Ut,nodeOrigin:It,nodeExtent:un,rfId:Bn})))};qb.displayName="GraphView";var rM=m.memo(qb);const Kp=[[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY],[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY]],tl={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:Kp,nodeExtent:Kp,nodesSelectionActive:!1,userSelectionActive:!1,userSelectionRect:null,connectionNodeId:null,connectionHandleId:null,connectionHandleType:"source",connectionPosition:{x:0,y:0},connectionStatus:null,connectionMode:mc.Strict,domNode:null,paneDragging:!1,noPanClassName:"nopan",nodeOrigin:[0,0],nodeDragThreshold:0,snapGrid:[15,15],snapToGrid:!1,nodesDraggable:!0,nodesConnectable:!0,nodesFocusable:!0,edgesFocusable:!0,edgesUpdatable:!0,elementsSelectable:!0,elevateNodesOnSelect:!0,fitViewOnInit:!1,fitViewOnInitDone:!1,fitViewOnInitOptions:void 0,onSelectionChange:[],multiSelectionActive:!1,connectionStartHandle:null,connectionEndHandle:null,connectionClickStartHandle:null,connectOnClick:!0,ariaLiveMessage:"",autoPanOnConnect:!0,autoPanOnNodeDrag:!0,connectionRadius:20,onError:TE,isValidConnection:void 0},iM=()=>VC((e,t)=>({...tl,setNodes:n=>{const{nodeInternals:i,nodeOrigin:o,elevateNodesOnSelect:l}=t();e({nodeInternals:Z_(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?Z_(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 w=window.getComputedStyle(p),{m22:y}=new window.DOMMatrixReadOnly(w.transform),x=n.reduce((b,$)=>{const E=o.get($.id);if(E){const L=Sg($.nodeElement);!!(L.width&&L.height&&(E.width!==L.width||E.height!==L.height||$.forceUpdate))&&(o.set(E.id,{...E,[ps]:{...E[ps],handleBounds:{source:Rw(".source",$.nodeElement,y,_),target:Rw(".target",$.nodeElement,y,_)}},...L}),b.push({id:E.id,type:"dimensions",dimensions:L}))}return b},[]);Mb(o,_);const S=u||l&&!u&&Rb(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 _=vT(n,c()),p=Z_(_,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=>al(f,!0)):(u=$u(l(),n),c=$u(o,[])),tm({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=>al(f,!0)):(u=$u(o,n),c=$u(l(),[])),tm({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,al(p.id,!1))),_=c.map(p=>al(p.id,!1));tm({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=>al(c.id,!1)),u=n.filter(c=>c.selected).map(c=>al(c.id,!1));tm({changedNodes:l,changedEdges:u,get:t,set:e})},setNodeExtent:n=>{const{nodeInternals:i}=t();i.forEach(o=>{o.positionAbsolute=kg(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 _=ha.translate(i[0]+n.x,i[1]+n.y).scale(i[2]),p=[[0,0],[o,l]],w=u==null?void 0:u.constrain()(_,p,f);return u.transform(c,w),i[0]!==w.x||i[1]!==w.y||i[2]!==w.k},cancelConnection:()=>e({connectionNodeId:tl.connectionNodeId,connectionHandleId:tl.connectionHandleId,connectionHandleType:tl.connectionHandleType,connectionStatus:tl.connectionStatus,connectionStartHandle:tl.connectionStartHandle,connectionEndHandle:tl.connectionEndHandle}),reset:()=>e({...tl})}),Object.is),Lg=({children:e})=>{const t=m.useRef(null);return t.current||(t.current=iM()),ve.createElement(SE,{value:t.current},e)};Lg.displayName="ReactFlowProvider";const Hb=({children:e})=>m.useContext(Gm)?ve.createElement(ve.Fragment,null,e):ve.createElement(Lg,null,e);Hb.displayName="ReactFlowWrapper";const oM={input:kb,default:Vp,output:Cb,group:Tg},aM={default:Rm,straight:$g,step:Cg,smoothstep:Km,simplebezier:Ng},lM=[0,0],cM=[15,15],uM={x:0,y:0,zoom:1},dM={width:"100%",height:"100%",overflow:"hidden",position:"relative",zIndex:0},Vb=m.forwardRef(({nodes:e,edges:t,defaultNodes:n,defaultEdges:i,className:o,nodeTypes:l=oM,edgeTypes:u=aM,onNodeClick:c,onEdgeClick:f,onInit:_,onMove:p,onMoveStart:w,onMoveEnd:y,onConnect:x,onConnectStart:S,onConnectEnd:b,onClickConnectStart:$,onClickConnectEnd:E,onNodeMouseEnter:L,onNodeMouseMove:D,onNodeMouseLeave:M,onNodeContextMenu:H,onNodeDoubleClick:Z,onNodeDragStart:Y,onNodeDrag:X,onNodeDragStop:re,onNodesDelete:ie,onEdgesDelete:ue,onSelectionChange:F,onSelectionDragStart:C,onSelectionDrag:N,onSelectionDragStop:O,onSelectionContextMenu:P,onSelectionStart:ne,onSelectionEnd:B,connectionMode:z=mc.Strict,connectionLineType:G=cl.Bezier,connectionLineStyle:T,connectionLineComponent:Q,connectionLineContainerStyle:K,deleteKeyCode:J="Backspace",selectionKeyCode:oe="Shift",selectionOnDrag:fe=!1,selectionMode:me=yf.Full,panActivationKeyCode:we="Space",multiSelectionKeyCode:Ae=Mm()?"Meta":"Control",zoomActivationKeyCode:Be=Mm()?"Meta":"Control",snapToGrid:We=!1,snapGrid:_t=cM,onlyRenderVisibleElements:Pe=!1,selectNodesOnDrag:et=!0,nodesDraggable:lt,nodesConnectable:Ye,nodesFocusable:Se,nodeOrigin:Le=lM,edgesFocusable:ct,edgesUpdatable:ge,elementsSelectable:De,defaultViewport:Ke=uM,minZoom:Dt=.5,maxZoom:Qt=2,translateExtent:_n=Kp,preventScrolling:Ut=!0,nodeExtent:It,defaultMarkerColor:un="#b1b1b7",zoomOnScroll:Bn=!0,zoomOnPinch:Mt=!0,panOnScroll:bn=!1,panOnScrollSpeed:Dn=.5,panOnScrollMode:En=ic.Free,zoomOnDoubleClick:jn=!0,panOnDrag:Ln=!0,onPaneClick:wn,onPaneMouseEnter:Cs,onPaneMouseMove:Kn,onPaneMouseLeave:ls,onPaneScroll:Cr,onPaneContextMenu:Yn,children:ce,onEdgeUpdate:be,onEdgeContextMenu:Ge,onEdgeDoubleClick:Ve,onEdgeMouseEnter:st,onEdgeMouseMove:ut,onEdgeMouseLeave:Et,onEdgeUpdateStart:jt,onEdgeUpdateEnd:qt,edgeUpdaterRadius:dt=10,onNodesChange:Yt,onEdgesChange:Bt,noDragClassName:Nt="nodrag",noWheelClassName:pt="nowheel",noPanClassName:Ot="nopan",fitView:$e=!1,fitViewOptions:Wt,connectOnClick:Ct=!0,attributionPosition:rn,proOptions:$t,defaultEdgeOptions:cs,elevateNodesOnSelect:us=!0,elevateEdgesOnSelect:Js=!1,disableKeyboardA11y:$s=!1,autoPanOnConnect:fr=!0,autoPanOnNodeDrag:Xs=!0,connectionRadius:so=20,isValidConnection:xe,onError:Jn,style:hn,id:ro,nodeDragThreshold:$i,...$r},hr)=>{const Kr=ro||"1";return ve.createElement("div",{...$r,style:{...hn,...dM},ref:hr,className:Ys(["react-flow",o]),"data-testid":"rf__wrapper",id:ro},ve.createElement(Hb,null,ve.createElement(rM,{onInit:_,onMove:p,onMoveStart:w,onMoveEnd:y,onNodeClick:c,onEdgeClick:f,onNodeMouseEnter:L,onNodeMouseMove:D,onNodeMouseLeave:M,onNodeContextMenu:H,onNodeDoubleClick:Z,nodeTypes:l,edgeTypes:u,connectionLineType:G,connectionLineStyle:T,connectionLineComponent:Q,connectionLineContainerStyle:K,selectionKeyCode:oe,selectionOnDrag:fe,selectionMode:me,deleteKeyCode:J,multiSelectionKeyCode:Ae,panActivationKeyCode:we,zoomActivationKeyCode:Be,onlyRenderVisibleElements:Pe,selectNodesOnDrag:et,defaultViewport:Ke,translateExtent:_n,minZoom:Dt,maxZoom:Qt,preventScrolling:Ut,zoomOnScroll:Bn,zoomOnPinch:Mt,zoomOnDoubleClick:jn,panOnScroll:bn,panOnScrollSpeed:Dn,panOnScrollMode:En,panOnDrag:Ln,onPaneClick:wn,onPaneMouseEnter:Cs,onPaneMouseMove:Kn,onPaneMouseLeave:ls,onPaneScroll:Cr,onPaneContextMenu:Yn,onSelectionContextMenu:P,onSelectionStart:ne,onSelectionEnd:B,onEdgeUpdate:be,onEdgeContextMenu:Ge,onEdgeDoubleClick:Ve,onEdgeMouseEnter:st,onEdgeMouseMove:ut,onEdgeMouseLeave:Et,onEdgeUpdateStart:jt,onEdgeUpdateEnd:qt,edgeUpdaterRadius:dt,defaultMarkerColor:un,noDragClassName:Nt,noWheelClassName:pt,noPanClassName:Ot,elevateEdgesOnSelect:Js,rfId:Kr,disableKeyboardA11y:$s,nodeOrigin:Le,nodeExtent:It}),ve.createElement(eT,{nodes:e,edges:t,defaultNodes:n,defaultEdges:i,onConnect:x,onConnectStart:S,onConnectEnd:b,onClickConnectStart:$,onClickConnectEnd:E,nodesDraggable:lt,nodesConnectable:Ye,nodesFocusable:Se,edgesFocusable:ct,edgesUpdatable:ge,elementsSelectable:De,elevateNodesOnSelect:us,minZoom:Dt,maxZoom:Qt,nodeExtent:It,onNodesChange:Yt,onEdgesChange:Bt,snapToGrid:We,snapGrid:_t,connectionMode:z,translateExtent:_n,connectOnClick:Ct,defaultEdgeOptions:cs,fitView:$e,fitViewOptions:Wt,onNodesDelete:ie,onEdgesDelete:ue,onNodeDragStart:Y,onNodeDrag:X,onNodeDragStop:re,onSelectionDrag:N,onSelectionDragStart:C,onSelectionDragStop:O,noPanClassName:Ot,nodeOrigin:Le,rfId:Kr,autoPanOnConnect:fr,autoPanOnNodeDrag:Xs,onError:Jn,connectionRadius:so,isValidConnection:xe,nodeDragThreshold:$i}),ve.createElement(ZE,{onSelectionChange:F}),ce,ve.createElement(NE,{proOptions:$t,position:rn}),ve.createElement(iT,{rfId:Kr,disableKeyboardA11y:$s})))});Vb.displayName="ReactFlow";const Gb=({id:e,x:t,y:n,width:i,height:o,style:l,color:u,strokeColor:c,strokeWidth:f,className:_,borderRadius:p,shapeRendering:w,onClick:y,selected:x})=>{const{background:S,backgroundColor:b}=l||{},$=u||S||b;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:$,stroke:c,strokeWidth:f,shapeRendering:w,onClick:y?E=>y(E,e):void 0})};Gb.displayName="MiniMapNode";var fM=m.memo(Gb);const hM=e=>e.nodeOrigin,mM=e=>e.getNodes().filter(t=>!t.hidden&&t.width&&t.height),np=e=>e instanceof Function?e:()=>e;function _M({nodeStrokeColor:e="transparent",nodeColor:t="#e2e2e2",nodeClassName:n="",nodeBorderRadius:i=5,nodeStrokeWidth:o=2,nodeComponent:l=fM,onClick:u}){const c=Rn(mM,Fs),f=Rn(hM),_=np(t),p=np(e),w=np(n),y=typeof window>"u"||window.chrome?"crispEdges":"geometricPrecision";return ve.createElement(ve.Fragment,null,c.map(x=>{const{x:S,y:b}=uc(x,f).positionAbsolute;return ve.createElement(l,{key:x.id,x:S,y:b,width:x.width,height:x.height,style:x.style,selected:x.selected,className:w(x),color:_(x),borderRadius:i,strokeColor:p(x),strokeWidth:o,shapeRendering:y,onClick:u,id:x.id})}))}var pM=m.memo(_M);const gM=200,yM=150,wM=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?AE(Ym(t,e.nodeOrigin),n):n,rfId:e.rfId}},vM="react-flow__minimap-desc";function Kb({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:w="bottom-right",onClick:y,onNodeClick:x,pannable:S=!1,zoomable:b=!1,ariaLabel:$="React Flow mini map",inversePan:E=!1,zoomStep:L=10,offsetScale:D=5}){const M=Ns(),H=m.useRef(null),{boundingRect:Z,viewBB:Y,rfId:X}=Rn(wM,Fs),re=(e==null?void 0:e.width)??gM,ie=(e==null?void 0:e.height)??yM,ue=Z.width/re,F=Z.height/ie,C=Math.max(ue,F),N=C*re,O=C*ie,P=D*C,ne=Z.x-(N-Z.width)/2-P,B=Z.y-(O-Z.height)/2-P,z=N+P*2,G=O+P*2,T=`${vM}-${X}`,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)},me=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])*(E?-1:1),Se={x:Be[0]-Ae.sourceEvent.movementX*Ye,y:Be[1]-Ae.sourceEvent.movementY*Ye},Le=[[0,0],[et,lt]],ct=ha.translate(Se.x,Se.y).scale(Be[2]),ge=_t.constrain()(ct,Le,Pe);_t.transform(We,ge)},we=sb().on("zoom",S?me:null).on("zoom.wheel",b?fe:null);return oe.call(we),()=>{oe.on("zoom",null)}}},[S,b,E,L]);const K=y?oe=>{const fe=Xi(oe);y(oe,{x:fe[0],y:fe[1]})}:void 0,J=x?(oe,fe)=>{const me=M.getState().nodeInternals.get(fe);x(oe,me)}:void 0;return ve.createElement(pf,{position:w,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},$&&ve.createElement("title",{id:T},$),ve.createElement(pM,{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-P},${B-P}h${z+P*2}v${G+P*2}h${-z-P*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"})))}Kb.displayName="MiniMap";var xM=m.memo(Kb);function bM(){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 jM(){return ve.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 5"},ve.createElement("path",{d:"M0 0h32v4.2H0z"}))}function SM(){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 kM(){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 NM(){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 CM=e=>({isInteractive:e.nodesDraggable||e.nodesConnectable||e.elementsSelectable,minZoomReached:e.transform[2]<=e.minZoom,maxZoomReached:e.transform[2]>=e.maxZoom}),Yb=({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:w="bottom-left"})=>{const y=Ns(),[x,S]=m.useState(!1),{isInteractive:b,minZoomReached:$,maxZoomReached:E}=Rn(CM,Fs),{zoomIn:L,zoomOut:D,fitView:M}=Mg();if(m.useEffect(()=>{S(!0)},[]),!x)return null;const H=()=>{L(),l==null||l()},Z=()=>{D(),u==null||u()},Y=()=>{M(o),c==null||c()},X=()=>{y.setState({nodesDraggable:!b,nodesConnectable:!b,elementsSelectable:!b}),f==null||f(!b)};return ve.createElement(pf,{className:Ys(["react-flow__controls",_]),position:w,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:E},ve.createElement(bM,null)),ve.createElement(Au,{onClick:Z,className:"react-flow__controls-zoomout",title:"zoom out","aria-label":"zoom out",disabled:$},ve.createElement(jM,null))),n&&ve.createElement(Au,{className:"react-flow__controls-fitview",onClick:Y,title:"fit view","aria-label":"fit view"},ve.createElement(SM,null)),i&&ve.createElement(Au,{className:"react-flow__controls-interactive",onClick:X,title:"toggle interactivity","aria-label":"toggle interactivity"},b?ve.createElement(NM,null):ve.createElement(kM,null)),p)};Yb.displayName="Controls";var $M=m.memo(Yb),eo;(function(e){e.Lines="lines",e.Dots="dots",e.Cross="cross"})(eo||(eo={}));function AM({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 EM({color:e,radius:t}){return ve.createElement("circle",{cx:t,cy:t,r:t,fill:e})}const TM={[eo.Dots]:"#91919a",[eo.Lines]:"#eee",[eo.Cross]:"#e2e2e2"},MM={[eo.Dots]:1,[eo.Lines]:1,[eo.Cross]:6},RM=e=>({transform:e.transform,patternId:`pattern-${e.rfId}`});function Jb({id:e,variant:t=eo.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:w}=Rn(RM,Fs),y=u||TM[t],x=i||MM[t],S=t===eo.Dots,b=t===eo.Cross,$=Array.isArray(n)?n:[n,n],E=[$[0]*p[2]||1,$[1]*p[2]||1],L=x*p[2],D=b?[L,L]:E,M=S?[L/l,L/l]:[D[0]/l,D[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:w+e,x:p[0]%E[0],y:p[1]%E[1],width:E[0],height:E[1],patternUnits:"userSpaceOnUse",patternTransform:`translate(-${M[0]},-${M[1]})`},S?ve.createElement(EM,{color:y,radius:L/l}):ve.createElement(AM,{dimensions:D,color:y,lineWidth:o})),ve.createElement("rect",{x:"0",y:"0",width:"100%",height:"100%",fill:`url(#${w+e})`}))}Jb.displayName="Background";var LM=m.memo(Jb);function Xb(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 Im(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 IM(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 OM(e){const t=String(e||"").trim();if(!t)return"";const n=t.indexOf(":");if(n<=0||n>=t.length-1)return Im(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 Im(t)}function Yp(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 Jp(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 Zb(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 PM(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 Bw(e,t,n){var S;const i={};if(!e.length)return i;const o=new Map;for(const b of e)o.set(b,new Set);for(const b of t){const $=String((b==null?void 0:b.source)||"").trim(),E=String((b==null?void 0:b.target)||"").trim();if(!$||!E||$===E)continue;const L=o.get($),D=o.get(E);L&&L.add(E),D&&D.add($)}let l=e[0],u=-1;for(const b of e){const $=((S=o.get(b))==null?void 0:S.size)??0;($>u||$===u&&b.localeCompare(l)<0)&&(l=b,u=$)}const c=new Map,f=[];for(c.set(l,0),f.push(l);f.length;){const b=f.shift(),$=c.get(b)??0,E=Array.from(o.get(b)??[]);E.sort((L,D)=>L.localeCompare(D));for(const L of E)c.has(L)||(c.set(L,$+1),f.push(L))}let _=0;for(const b of c.values())_=Math.max(_,b);for(const b of e)c.has(b)||c.set(b,_+1);const p=new Map;for(const b of e){const $=c.get(b)??0,E=p.get($);E?E.push(b):p.set($,[b])}const w=Array.from(p.keys()).sort((b,$)=>b-$),y=260,x=n%360*Math.PI/180;for(const b of w){const $=p.get(b)||[];if($.sort((M,H)=>M.localeCompare(H)),b===0){if($.length===1)i[$[0]]={x:0,y:0};else for(let H=0;H<$.length;H++){const Z=x+2*Math.PI*H/$.length;i[$[H]]={x:80*Math.cos(Z),y:80*Math.sin(Z)}}continue}const E=y*b,L=$.length;if(L===1){i[$[0]]={x:E,y:0};continue}const D=x+b*.35;for(let M=0;M<L;M++){const H=D+2*Math.PI*M/L;i[$[M]]={x:E*Math.cos(H),y:E*Math.sin(H)}}}return i}function ku(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 Yp(o);if(n==="circle")return PM(o,i);if(n==="radial")return Bw(o,e.edges,i);if(n==="force"){const l=Bw(o,e.edges,i),u=Zb(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 Yp(o)}function DM(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 FM(e,t={}){const n=!!(t.groupEdges??!0),i=Math.max(1,t.maxEdgeLabelPredicates??3),o=DM(e),l=new Set;for(const y of o){const x=String(y.subject||"").trim(),S=String(y.object||"").trim();x&&l.add(x),S&&l.add(S)}const u=Array.from(l);u.sort((y,x)=>y.localeCompare(x));const c=Yp(u),f=u.map(y=>({id:y,type:"default",data:{label:OM(y),kind:IM(y)},position:c[y]||{x:0,y:0}})),_=new Map,p=(y,x)=>{const S=String(y.subject||"").trim(),b=String(y.object||"").trim(),$=String(y.predicate||"").trim();return n?`edge:${S}:${b}`:`edge:${x}:${S}:${$}:${b}`};for(let y=0;y<o.length;y++){const x=o[y],S=p(x,y),b=_.get(S);b?b.push(x):_.set(S,[x])}const w=[];for(const[y,x]of _.entries()){const S=x[0],b=String(S.subject||"").trim(),$=String(S.object||"").trim();if(!b||!$)continue;const E=new Map;for(const Y of x){const X=String(Y.predicate||"").trim();X&&E.set(X,(E.get(X)||0)+1)}const L=Array.from(E.entries());L.sort((Y,X)=>X[1]-Y[1]||Y[0].localeCompare(X[0]));const M=L.slice(0,i).map(([Y,X])=>X>1?`${Im(Y)}×${X}`:Im(Y)).join(" | "),H=L.length>i?` +${L.length-i}`:"",Z=`${M}${H}`.trim();w.push({id:y,source:b,target:$,label:Z,animated:!1,data:{assertions:x,predicateSummary:Z}})}return{nodes:f,edges:w}}function zM(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=(b,$,E)=>{const L=c.get(b);L?L.push({to:$,edgeId:E}):c.set(b,[{to:$,edgeId:E}])};for(const b of e.edges)f(b.source,b.target,b.id),o||f(b.target,b.source,b.id);const _=[l],p=new Map,w=new Map;for(p.set(l,null),w.set(l,null);_.length;){const b=_.shift(),$=c.get(b)||[];for(const E of $)if(!p.has(E.to)){if(p.set(E.to,b),w.set(E.to,E.edgeId),E.to===u){_.length=0;break}_.push(E.to)}}if(!p.has(u))return null;const y=[],x=[];let S=u;for(;S;){y.push(S);const b=w.get(S);b&&x.push(b),S=p.get(S)||null}return y.reverse(),x.reverse(),{nodeIds:y,edgeIds:x}}const Uw={seed:1,dt:1,springLength:240,springStrength:.03,repulsionStrength:9e3,centeringStrength:.003,damping:.85,maxSpeed:90,maxRepulsionNodes:320};function sm(e,t={}){const n={...Uw,...t,seed:typeof t.seed=="number"&&Number.isFinite(t.seed)?Math.trunc(t.seed):Uw.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??ku(e,{kind:"force",seed:n.seed}),p=Zb(n.seed||1),w=Math.max(8,Math.min(38,Math.sqrt(o)*2.25));for(let x=0;x<o;x++){const S=i[x],b=_[S],$=typeof(b==null?void 0:b.x)=="number"&&Number.isFinite(b.x)?b.x:(p()-.5)*500,E=typeof(b==null?void 0:b.y)=="number"&&Number.isFinite(b.y)?b.y:(p()-.5)*500;l[2*x]=$+(p()-.5)*w,l[2*x+1]=E+(p()-.5)*w,u[2*x]=0,u[2*x+1]=0}const y=[];for(const x of e.edges){const S=f.get(String((x==null?void 0:x.source)||"").trim()),b=f.get(String((x==null?void 0:x.target)||"").trim());typeof S!="number"||typeof b!="number"||S===b||y.push(S,b)}return{nodeIds:i,pos:l,vel:u,acc:c,edges:new Uint32Array(y),options:n,tick:0}}function BM(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 b=e.pos[2*S],$=e.pos[2*S+1];for(let E=S+1;E<n;E++){const L=e.pos[2*E]-b,D=e.pos[2*E+1]-$,M=L*L+D*D+1e-6,H=1/Math.sqrt(M),Z=x/M,Y=Z*L*H,X=Z*D*H;e.acc[2*S]-=Y,e.acc[2*S+1]-=X,e.acc[2*E]+=Y,e.acc[2*E+1]+=X}}}const c=i.springLength,f=i.springStrength,_=e.edges;for(let x=0;x<_.length;x+=2){const S=_[x],b=_[x+1],$=e.pos[2*S],E=e.pos[2*S+1],L=e.pos[2*b],D=e.pos[2*b+1],M=L-$,H=D-E,Z=M*M+H*H+1e-6,Y=Math.sqrt(Z),X=f*(Y-c),re=X*M/Y,ie=X*H/Y;e.acc[2*S]+=re,e.acc[2*S+1]+=ie,e.acc[2*b]-=re,e.acc[2*b+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 w=i.damping,y=i.maxSpeed;for(let x=0;x<n;x++){let S=(e.vel[2*x]+e.acc[2*x]*o)*w,b=(e.vel[2*x+1]+e.acc[2*x+1]*o)*w;const $=Math.sqrt(S*S+b*b);if($>y){const E=y/$;S*=E,b*=E}e.vel[2*x]=S,e.vel[2*x+1]=b,e.pos[2*x]+=S*o,e.pos[2*x+1]+=b*o}e.tick+=1}}function UM(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 WM(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 Ww(e,t="session"){const n=String(e??"").trim().toLowerCase();return n==="run"||n==="session"||n==="global"||n==="all"?n:t}function qM(){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 HM(){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 Qb(e,t,n,i){const o=typeof e=="number"&&Number.isFinite(e)?e:i;return Math.min(n,Math.max(t,o))}function Zd(e){const t=Qb(e,.6,2.4,1),n=240*t,i=9e3*t*t;return{springLength:n,repulsionStrength:i}}const xf="abstractuic_amx_saved_layouts_v1",Xp=.025,Zp=6,e0=1e6;function Ig(){if(typeof window>"u")return null;try{return window.localStorage}catch{return null}}function Qp(e,t="grid"){const n=String(e??"").trim().toLowerCase();return n==="grid"||n==="circle"||n==="radial"||n==="force"?n:t}function VM(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 qw(e){const t=Ig();if(!t)return null;const n=String(e??"").trim();if(!n)return null;try{const i=t.getItem(xf);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 _=Qp(c.kind,"grid"),p=typeof c.seed=="number"&&Number.isFinite(c.seed)?Math.trunc(c.seed):Jp(n),w=c.positions&&typeof c.positions=="object"&&!Array.isArray(c.positions)?c.positions:null,y={};if(w)for(const[b,$]of Object.entries(w)){const E=VM($);E&&(y[String(b)]=E)}const x=Xb(c.viewport,{minZoom:Xp,maxZoom:Zp,maxAbsTranslate:e0})??void 0,S=typeof c.saved_at=="string"&&c.saved_at.trim()?c.saved_at.trim():"";return{version:f,kind:_,seed:p,positions:y,viewport:x,saved_at:S}}catch{return null}}function GM(e,t){const n=Ig();if(!n)return;const i=String(e??"").trim();if(i)try{const o=n.getItem(xf),l=o?JSON.parse(o):null,u=l&&typeof l=="object"&&!Array.isArray(l)?{...l}:{};u[i]=t,n.setItem(xf,JSON.stringify(u))}catch{}}function KM(e){const t=Ig();if(!t)return;const n=String(e??"").trim();if(n)try{const i=t.getItem(xf);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(xf,JSON.stringify(l))}catch{}}function YM(e){const t=String(e??"").trim();if(!t)return;const n=Number(t);if(Number.isFinite(n))return n}function sp(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 JM(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 XM(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 ZM(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 Qd(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 QM(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 ef(e){const t=QM(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 t0(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 rp(e,t){const n=String(e??"").trim().toLowerCase();return!!(n&&t.has(n))}function eR(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=t0(f);return _>1?`${p}×${_}`:p}).join(" | "),c=o.length>n?` +${o.length-n}`:"";return`${u}${c}`.trim()}function tR({resetKey:e,queryMode:t,items:n,activeMemoryText:i,packets:o,packetsVersion:l,packedCount:u,dropped:c,estimatedTokens:f,effort:_,warnings:p,onQuery:w,onItemsReplace:y,onOpenSpan:x,onOpenTranscript:S}){var uo;const b=m.useRef(null),$=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}`:"",Ce=ae?`${ae.subject}|${ae.predicate}|${ae.object}`:"";return`${(n==null?void 0:n.length)||0}:${je}:${Ce}`},[n]),E=String(e??$),L=t==="replace"?"replace":"override",[D,M]=m.useState(null),[H,Z]=m.useState(null),[Y,X]=m.useState(!1),[re,ie]=m.useState(""),[ue,F]=m.useState(!1),[C,N]=m.useState("");m.useEffect(()=>{M(null),Z(null),ie(""),X(!1),N(""),F(!1)},[E]);const[O,P]=m.useState(""),[ne,B]=m.useState(!0),[z,G]=m.useState(!1),[T,Q]=m.useState(!0),[K]=m.useState(()=>({compact:qM(),show:!1})),J=K.compact,[oe,fe]=m.useState(K.show),[me,we]=m.useState(!1),Ae=E,Be=m.useMemo(()=>Jp(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),Qt=m.useRef(null),_n=m.useRef(0),Ut=m.useRef(0),It=m.useRef(0),un=m.useRef(0),[Bn,Mt]=m.useState(!1),[bn,Dn]=m.useState(""),[En,jn]=m.useState({}),Ln=m.useRef({});m.useEffect(()=>{Ln.current=En},[En]);const[wn,Cs]=m.useState(""),[Kn,ls]=m.useState(""),Cr=m.useMemo(()=>{var ae;const U=(ae=n==null?void 0:n[0])==null?void 0:ae.scope;return Ww(U,"session")},[n]),[Yn,ce]=m.useState(Cr),[be,Ge]=m.useState("standard"),[Ve,st]=m.useState(""),[ut,Et]=m.useState(""),[jt,qt]=m.useState(""),[dt,Yt]=m.useState(""),[Bt,Nt]=m.useState(""),[pt,Ot]=m.useState(""),[$e,Wt]=m.useState(""),[Ct,rn]=m.useState("qwen/qwen3-next-80b");m.useEffect(()=>{ce(Cr)},[E]);const $t=Array.isArray(n)?n:[],cs=typeof i=="string"?i:"",us=Array.isArray(o)?o:[],Js=typeof l=="number"?l:void 0,$s=typeof u=="number"?u:void 0,fr=typeof c=="number"?c:void 0,Xs=typeof f=="number"?f:void 0,so=_,xe=p,Jn=L==="override"&&(D!=null&&D.items)&&Array.isArray(D.items)?D.items:$t,hn=typeof(D==null?void 0:D.active_memory_text)=="string"&&D.active_memory_text.trim()?D.active_memory_text:cs,ro=(D==null?void 0:D.effort)??so,$i=(D==null?void 0:D.warnings)??xe,$r=m.useMemo(()=>new Set(["rdf:type","schema:name","skos:preflabel","skos:altlabel","dcterms:title","dcterms:identifier"]),[]),hr=m.useMemo(()=>T?Jn:(Jn||[]).filter(U=>!rp(U==null?void 0:U.predicate,$r)),[Jn,T,$r]),Kr=m.useMemo(()=>FM(Jn,{groupEdges:ne}),[Jn,ne]),it=m.useMemo(()=>{if(T)return Kr;const U=[];for(const ae of Kr.edges){const Ce=(ae&&ae.data&&Array.isArray(ae.data.assertions)?ae.data.assertions:[]).filter(Ue=>!rp(Ue==null?void 0:Ue.predicate,$r));if(!Ce.length)continue;const ke=eR(Ce);U.push({...ae,label:ke,data:{...ae.data,assertions:Ce,predicateSummary:ke}})}return{nodes:Kr.nodes,edges:U}},[Kr,T,$r]),tn=m.useMemo(()=>it.nodes.map(U=>U.id),[it.nodes]),gs=m.useMemo(()=>{const U=tn[0]||"",ae=tn[tn.length-1]||"";return`${tn.length}:${U}:${ae}`},[tn]),oi=m.useMemo(()=>{var ae;const U=new Map;for(const je of it.nodes)U.set(je.id,String(((ae=je.data)==null?void 0:ae.label)||je.id));return U},[it.nodes]),ds=m.useMemo(()=>{var ae;const U=new Map;for(const je of it.nodes)U.set(je.id,String(((ae=je.data)==null?void 0:ae.kind)||""));return U},[it.nodes]),io=O.trim().toLowerCase(),oo=m.useMemo(()=>{var ae;if(!io)return new Set;const U=new Set;for(const je of it.nodes){const Ce=String(je.id||"").toLowerCase(),ke=String(((ae=je.data)==null?void 0:ae.label)||"").toLowerCase();(Ce.includes(io)||ke.includes(io))&&U.add(je.id)}return U},[it.nodes,io]),ya=m.useCallback((U,ae)=>{const je={};for(const Ce of tn){const ke=U[Ce]||ae[Ce];je[Ce]=ke?{x:ke.x,y:ke.y}:{x:0,y:0}}return je},[tn]);m.useEffect(()=>{jn(U=>{const ae=ku(it,{kind:We,seed:Pe}),je={};for(const Ce of tn){const ke=U[Ce]||ae[Ce];je[Ce]=ke?{x:ke.x,y:ke.y}:{x:0,y:0}}return je})},[it,We,Pe,tn,gs]),m.useEffect(()=>{if(!De.current)return;const U=b.current;if(!(!U||typeof U.fitView!="function")&&tn.length){De.current=!1;try{U.fitView({padding:.2,duration:0})}catch{try{U.fitView({padding:.2})}catch{}}}},[tn.length,gs,En]),m.useEffect(()=>{Ye(!1),ct.current=null,ge.current=null,De.current=!1,_n.current=0,Ut.current=0,It.current=0;const U=qw(Ae);if(U&&Object.keys(U.positions||{}).length){if(_t(U.kind),et(U.seed),Mt(!0),Dn(U.saved_at||""),U.viewport){ge.current=U.viewport;const ke=b.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 Ce=ku(it,{kind:U.kind,seed:U.seed});jn(ya(U.positions,Ce));return}Mt(!1),Dn("");const ae=Jp(Ae);et(ae);const je=ku(it,{kind:We,seed:ae});jn(je),We==="force"&&it.nodes.length>0&&it.nodes.length<=320&&(ct.current=sm(it,{seed:ae,positions:je,...Zd(Se)}),Ye(!0))},[Ae]);const Fn=m.useMemo(()=>{const U=String(wn||"").trim(),ae=String(Kn||"").trim();return!U||!ae?null:zM(it,U,ae,{directed:z})},[it,wn,Kn,z]),mr=!!(Fn&&String(wn||"").trim()&&String(Kn||"").trim()),Tn=m.useMemo(()=>{const U=String(wn||"").trim(),ae=String(Kn||"").trim();if(!U||!ae)return null;const je=z,Ce=new Map,ke=(ot,gt)=>{const Ft=Ce.get(ot);Ft?Ft.push(gt):Ce.set(ot,[gt])};for(const ot of it.edges)ke(ot.source,ot.target),je||ke(ot.target,ot.source);const Ue=new Set,ft=[];for(Ue.add(U),ft.push(U);ft.length;){const ot=ft.shift(),gt=Ce.get(ot)||[];for(const Ft of gt)Ue.has(Ft)||(Ue.add(Ft),ft.push(Ft))}return{reachableFromStart:Ue.size,endReachable:Ue.has(ae),nodes:it.nodes.length,edges:it.edges.length,assertions:hr.length}},[z,it.edges,it.nodes.length,Kn,wn,hr.length]),_r=m.useMemo(()=>new Set((Fn==null?void 0:Fn.nodeIds)||[]),[Fn]),ao=m.useMemo(()=>new Set((Fn==null?void 0:Fn.edgeIds)||[]),[Fn]),[Qn,Zs]=m.useState(""),[fs,Yr]=m.useState(""),ys=!!(String(Qn||"").trim()||String(fs||"").trim()),wa=m.useMemo(()=>{const U=new Set,ae=new Set,je=String(Qn||"").trim(),Ce=String(fs||"").trim();if(je){U.add(je);for(const ke of it.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(Ce){const ke=it.edges.find(Ue=>Ue.id===Ce);ke&&(ae.add(ke.id),U.add(ke.source),U.add(ke.target))}return{nodes:U,edges:ae}},[it.edges,fs,Qn]);m.useEffect(()=>{Zs(""),Yr(""),Cs(""),ls("")},[E]);const[lo,nn]=m.useState(!1);m.useEffect(()=>{nn(!1)},[E]),m.useEffect(()=>{lt||(ct.current=null)},[lt]),m.useEffect(()=>{if(We!=="force")return;const U=ct.current;if(!U)return;const ae=Zd(Se);U.options.springLength=ae.springLength,U.options.repulsionStrength=ae.repulsionStrength},[We,Se]),m.useEffect(()=>{We!=="force"&&lt&&Ye(!1)},[We,lt]),m.useEffect(()=>{if(!lt||We!=="force"||it.nodes.length===0||typeof window>"u"||typeof window.requestAnimationFrame!="function")return;ct.current||(ct.current=sm(it,{seed:Pe,positions:Ln.current,...Zd(Se)}));let U=0,ae=0,je=0;const Ce=it.nodes.length<=140?2:1,ke=1600,Ue=.08,ft=ot=>{if(U=window.requestAnimationFrame(ft),ot-ae<33)return;ae=ot;const gt=ct.current;if(!gt){Ye(!1);return}BM(gt,Ce),je+=Ce,jn(WM(gt)),(UM(gt)<=Ue||je>=ke)&&Ye(!1)};return U=window.requestAnimationFrame(ft),()=>{window.cancelAnimationFrame(U)}},[it,We,lt,Pe]);const ml=m.useMemo(()=>it.nodes.map(U=>{var sn;const ae=_r.has(U.id),je=oo.has(U.id),Ce=Qn===U.id,ke=ys&&wa.nodes.has(U.id),Ue=Qd((sn=U.data)==null?void 0:sn.kind),ft="rgba(34, 211, 238, 0.88)",ot=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=Ce?"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,Ht=ot&&Ft?`${ot}, ${Ft}`:Ft||ot||void 0,vs=ae?"rgba(168, 85, 247, 0.10)":je?"rgba(34, 211, 238, 0.08)":Ue.bg,Rt=mr?ae||Ce?1:.16:ys?ke||Ce?1:.1:1;return{...U,position:En[U.id]?{x:En[U.id].x,y:En[U.id].y}:U.position,style:{...U.style||{},border:`1px solid ${gt}`,borderRadius:10,background:vs,color:"rgba(255,255,255,0.92)",opacity:Rt,padding:8,fontSize:12,boxShadow:Ht,width:180,cursor:"pointer"}}}),[it.nodes,mr,oo,En,Qn,_r,ys,wa.nodes]),Ai=m.useMemo(()=>it.edges.map(U=>{const ae=ao.has(U.id),je=fs===U.id,Ce=ys&&wa.edges.has(U.id),ke=ae?"rgba(168, 85, 247, 0.9)":ys?Ce||je?"rgba(96, 165, 250, 0.55)":"rgba(255,255,255,0.14)":"rgba(255,255,255,0.18)",Ue=ae?2.75:ys?Ce||je?2.25:1.25:1.5,ft=je?"drop-shadow(0 0 10px rgba(168, 85, 247, 0.25))":void 0,ot=ae?"rgba(168, 85, 247, 0.9)":mr?"rgba(255,255,255,0.10)":"rgba(255,255,255,0.28)",gt=mr?ae||je?1:.1:ys?Ce||je?1:.08:1,Ft=mr?ae||je?1:0:ys?Ce||je?1:0:1,Ht=mr?ae||je?String(U.label||""):"":String(U.label||"");return{...U,label:Ht,style:{...U.style||{},stroke:ke,strokeWidth:Ue,filter:ft,opacity:gt},animated:!1,markerEnd:{type:wf.ArrowClosed,color:ot,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"}}}),[it.edges,mr,fs,ao,ys,wa.edges]),pr=m.useMemo(()=>{if(!fs)return[];const U=it.edges.find(je=>je.id===fs),ae=U&&U.data&&Array.isArray(U.data.assertions)?U.data.assertions:[];return Array.isArray(ae)?ae:[]},[it.edges,fs]),As=m.useMemo(()=>fs&&it.edges.find(U=>U.id===fs)||null,[it.edges,fs]),va=m.useMemo(()=>{const U=String(Qn||"").trim();return U?Jn.filter(ae=>!ae||typeof ae!="object"||!(ae.subject===U||ae.object===U)?!1:T?!0:!rp(ae.predicate,$r)):[]},[Jn,Qn,T,$r]),Ar=m.useMemo(()=>fs?pr:va,[pr,fs,va]),ai=m.useMemo(()=>{const U=new Map;for(const ae of Ar){if(!ae||typeof ae!="object")continue;const je=ae.provenance&&typeof ae.provenance=="object"&&!Array.isArray(ae.provenance)?ae.provenance:null,Ce=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||!Ce)continue;const ot=`${ft}|${Ce}`,gt=U.get(ot),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=ef(Ft),gt.assertion=ae)):U.set(ot,{span_run_id:ft,span_id:Ce,writer_run_id:ke,count:1,last_observed_at:Ft,last_observed_at_fmt:ef(Ft),assertion:ae})}return Array.from(U.values()).sort((ae,je)=>String(je.last_observed_at||"").localeCompare(String(ae.last_observed_at||"")))},[Ar]),Ei=m.useMemo(()=>{const U=new Map;for(const ae of Ar){if(!ae||typeof ae!="object")continue;const je=ae.provenance&&typeof ae.provenance=="object"&&!Array.isArray(ae.provenance)?ae.provenance:null,Ce=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||Ce)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=ef(ft),Ue.assertion=ae)):U.set(ke,{run_id:ke,count:1,last_observed_at:ft,last_observed_at_fmt:ef(ft),assertion:ae})}return Array.from(U.values()).sort((ae,je)=>String(je.last_observed_at||"").localeCompare(String(ae.last_observed_at||"")))},[Ar]),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]),Es=m.useCallback(async U=>{const ae=String(U??"");if(ae)try{await navigator.clipboard.writeText(ae)}catch{}},[]),Er=m.useCallback(()=>{const U=b.current;if(!(!U||typeof U.fitView!="function")){if(Qn&&typeof U.getNode=="function"){const ae=U.getNode(Qn);if(ae){U.fitView({nodes:[ae],padding:.55,duration:350});return}}U.fitView({padding:.2,duration:350})}},[Qn]),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 Ce=ku(it,{kind:ae,seed:je});jn(Ce),ae==="force"&&(U.autoPlay??!0)&&it.nodes.length>0&&it.nodes.length<=320&&(ct.current=sm(it,{seed:je,positions:Ce,...Zd(Se)}),Ye(!0))},[it,Se]),Ti=m.useCallback(()=>{if(We==="force"){if(lt){Ye(!1);return}ct.current=sm(it,{seed:Pe,positions:Ln.current,...Zd(Se)}),Ye(!0)}},[it,We,lt,Pe,Se]);m.useEffect(()=>()=>{typeof window>"u"||typeof window.cancelAnimationFrame=="function"&&un.current&&window.cancelAnimationFrame(un.current)},[]);const gr=m.useCallback(()=>{const U=b.current;if(!U||typeof U.getViewport!="function"||!tn.length)return null;const ae=Qt.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 Ce=U.getViewport(),ke=typeof(Ce==null?void 0:Ce.zoom)=="number"&&Number.isFinite(Ce.zoom)?Ce.zoom:null,Ue=typeof(Ce==null?void 0:Ce.x)=="number"&&Number.isFinite(Ce.x)?Ce.x:null,ft=typeof(Ce==null?void 0:Ce.y)=="number"&&Number.isFinite(Ce.y)?Ce.y:null;if(ke===null||Ue===null||ft===null||ke<=0)return null;const ot=140,gt=Math.min(tn.length,180),Ft=Ln.current;let Ht=0,vs=0;for(const Rt of tn){const sn=Ft[Rt];if(!sn||!Number.isFinite(sn.x)||!Number.isFinite(sn.y))continue;vs+=1;const Cn=[{x:sn.x,y:sn.y},{x:sn.x+90,y:sn.y+24}];for(const mn of Cn){const es=mn.x*ke+Ue,nr=mn.y*ke+ft;if(es>-ot&&es<je.width+ot&&nr>-ot&&nr<je.height+ot)return!1}if(Ht++,Ht>=gt)break}return vs?!0:null},[tn]),ws=m.useCallback(U=>{typeof window>"u"||typeof window.requestAnimationFrame!="function"||un.current||(un.current=window.requestAnimationFrame(()=>{un.current=0;const ae=gr();if(ae===null){if(It.current>=12)return;It.current+=1,window.setTimeout(()=>ws(`${U}:probe`),120);return}if(ae!==!0){It.current=0,Ut.current=0;return}It.current=0;const je=b.current;if(je&&typeof je.fitView=="function")try{je.fitView({padding:.2,duration:0})}catch{try{je.fitView({padding:.2})}catch{}}if(Ut.current+=1,Ut.current>=4&&_n.current<1){Ut.current=0,_n.current+=1,Dt(Ce=>Ce+1);return}Ut.current<8&&window.setTimeout(()=>ws(`${U}:retry`),220)}))},[gr]);m.useEffect(()=>{Ut.current=0,_n.current=0,It.current=0,ws("mount")},[E,ws]),m.useEffect(()=>{ws("graph change")},[gs,ws]),m.useEffect(()=>{const U=Qt.current;if(!U||typeof window>"u"||typeof ResizeObserver!="function")return;const ae=new ResizeObserver(()=>ws("resize"));return ae.observe(U),()=>ae.disconnect()},[ws]);const Mi=m.useCallback(()=>{const U=new Date().toISOString(),ae={};for(const ft of tn){const ot=Ln.current[ft];ot&&typeof ot.x=="number"&&typeof ot.y=="number"&&(ae[ft]={x:ot.x,y:ot.y})}const je=b.current,Ce=je&&typeof je.toObject=="function"?je.toObject():null,ke=Ce&&Ce.viewport?Ce.viewport:je&&typeof je.getViewport=="function"?je.getViewport():null,Ue=Xb(ke,{minZoom:Xp,maxZoom:Zp,maxAbsTranslate:e0})??void 0;GM(Ae,{version:1,kind:We,seed:Pe,positions:ae,viewport:Ue,saved_at:U}),Mt(!0),Dn(U),Ye(!1)},[Ae,We,Pe,tn]),Lo=m.useCallback(()=>{const U=qw(Ae);if(!U)return;Ye(!1),ct.current=null,_t(U.kind),et(U.seed),Mt(!0),Dn(U.saved_at||""),ge.current=U.viewport||null,De.current=!U.viewport;const ae=ku(it,{kind:U.kind,seed:U.seed});if(jn(ya(U.positions,ae)),U.viewport){const je=b.current;if(je&&typeof je.setViewport=="function"){try{je.setViewport(U.viewport,{duration:0})}catch{try{je.setViewport(U.viewport)}catch{}}ge.current=null}}},[ya,it,Ae]),_l=m.useCallback(()=>{KM(Ae),Mt(!1),Dn("")},[Ae]),tr=m.useCallback(U=>{if(!Array.isArray(U)||U.length===0)return;let ae=!1;jn(je=>{let Ce=je,ke=!1;for(const Ue of U){const ft=Ue&&typeof Ue=="object"&&"id"in Ue&&typeof Ue.id=="string"?String(Ue.id):"",ot=(Ue==null?void 0:Ue.type)==="position"?Ue==null?void 0:Ue.position:null;ft&&ot&&typeof ot.x=="number"&&typeof ot.y=="number"&&(ke||(Ce={...je},ke=!0),Ce[ft]={x:ot.x,y:ot.y},Ue!=null&&Ue.dragging&&(ae=!0))}return ke?Ce:je}),ae&&lt&&Ye(!1)},[lt]),Io=m.useMemo(()=>{const U=new Map;for(const ae of it.edges)U.set(ae.id,ae);return U},[it.edges]),Jr=m.useMemo(()=>{var Ce;if(!Fn)return[];const U=Fn.nodeIds||[],ae=Fn.edgeIds||[],je=[];for(let ke=0;ke<Math.min(U.length-1,ae.length);ke++){const Ue=U[ke],ft=U[ke+1],ot=ae[ke],gt=Io.get(ot),Ft=String(((Ce=gt==null?void 0:gt.data)==null?void 0:Ce.predicateSummary)||(gt==null?void 0:gt.label)||"").trim(),Ht=gt&&gt.source===Ue&&gt.target===ft?"forward":gt&&gt.source===ft&&gt.target===Ue?"reverse":"unknown";je.push({from:Ue,to:ft,edgeId:ot,predicate:Ft,dir:Ht})}return je},[Io,Fn]),_c=m.useCallback(async()=>{if(w){ie(""),N(""),X(!0);try{const U=YM(Bt),ae=sp(pt,{allowZero:!0,allowNegativeOne:!0}),je=sp($e,{allowZero:!0}),Ce=await w({scope:Yn,owner_id:void 0,recall_level:be,query_text:Ve||void 0,subject:ut||void 0,predicate:jt||void 0,object:dt||void 0,min_score:U,limit:ae,max_input_tokens:je,model:Ct||void 0});M(Ce),Z("live query"),L==="replace"&&y&&Ce&&Array.isArray(Ce.items)&&y(Ce.items,{kind:"live query",result:Ce})}catch(U){const ae=U instanceof Error?U.message:String(U);ie(ae||"Query failed")}finally{X(!1)}}},[pt,$e,Bt,Ct,dt,y,w,jt,L,Ve,be,Yn,ut]),yr=m.useCallback(async()=>{if(!w)return;const U=String(wn||"").trim(),ae=String(Kn||"").trim();if(!U||!ae)return;const je=Math.max(200,sp(pt)??80),Ce=60;N(""),ie(""),F(!0);try{const ke=[],Ue=new Set,ft=Rt=>{if(!Rt||typeof Rt!="object"||typeof Rt.subject!="string"||typeof Rt.predicate!="string"||typeof Rt.object!="string")return;const sn=`${Rt.subject}|${Rt.predicate}|${Rt.object}|${String(Rt.observed_at||"")}|${String(Rt.scope||"")}|${String(Rt.owner_id||"")}`;Ue.has(sn)||(Ue.add(sn),ke.push(Rt))};for(const Rt of Jn)ft(Rt);const ot=z,gt=new Set,Ft=[U],Ht=new Set([U]),vs=async Rt=>{const sn=await w({scope:Yn,recall_level:be,min_score:0,limit:je,subject:Rt,query_text:void 0,max_input_tokens:0,model:void 0});if(sn&&Array.isArray(sn.items)){for(const Cn of sn.items)if(ft(Cn),typeof Cn.subject=="string"&&Cn.subject.trim()===Rt&&typeof Cn.object=="string"){const mn=Cn.object.trim();mn&&!Ht.has(mn)&&(Ht.add(mn),Ft.push(mn))}}if(!ot){const Cn=await w({scope:Yn,recall_level:be,min_score:0,limit:je,object:Rt,query_text:void 0,max_input_tokens:0,model:void 0});if(Cn&&Array.isArray(Cn.items)){for(const mn of Cn.items)if(ft(mn),typeof mn.object=="string"&&mn.object.trim()===Rt&&typeof mn.subject=="string"){const es=mn.subject.trim();es&&!Ht.has(es)&&(Ht.add(es),Ft.push(es))}}}};for(;Ft.length&&gt.size<Ce&&!Ht.has(ae);){const Rt=Ft.shift();!Rt||gt.has(Rt)||(gt.add(Rt),await vs(Rt))}M({ok:!0,count:ke.length,items:ke,active_memory_text:hn,raw:{expanded_for_path:!0,expanded_nodes:gt.size,discovered_nodes:Ht.size,merged:ke.length,directed:ot}}),Z("expanded neighborhood"),L==="replace"&&y&&y(ke,{kind:"expanded neighborhood",result:{ok:!0,count:ke.length,items:ke,active_memory_text:hn,raw:{expanded_for_path:!0,expanded_nodes:gt.size,discovered_nodes:Ht.size,merged:ke.length,directed:ot}}})}catch(ke){const Ue=ke instanceof Error?ke.message:String(ke);N(Ue||"Expand neighborhood failed")}finally{F(!1)}},[z,hn,Jn,pt,y,w,Kn,wn,L,be,Yn]),co=m.useCallback(()=>{M(null),Z(null),ie(""),X(!1),N(""),F(!1),Cs(""),ls(""),Zs(""),Yr("")},[]),zs="Search KG",Oo=it.nodes.length,Po=it.edges.length,Do=hr.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(Qp(U.target.value,We)),disabled:!tn.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(Qb(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:!tn.length,children:"Apply"}),s.jsx("button",{type:"button",className:"amx-btn",onClick:Ti,disabled:!tn.length||We!=="force",children:lt?"Pause simulation":"Play simulation"})]})}),s.jsxs("div",{className:"amx-graph","aria-label":"Knowledge graph",ref:Qt,children:[s.jsx(Lg,{children:s.jsxs(Vb,{nodes:ml,edges:Ai,defaultViewport:{x:0,y:0,zoom:1},minZoom:Xp,maxZoom:Zp,onInit:U=>{b.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,ws("init")},nodesDraggable:!0,nodesConnectable:!1,elementsSelectable:!0,onNodesChange:tr,onNodeClick:(U,ae)=>{Yr(""),Zs(ae.id)},onEdgeClick:(U,ae)=>{Zs(""),Yr(ae.id)},onPaneClick:()=>{Zs(""),Yr("")},children:[s.jsx($M,{className:"amx-flow-controls",children:s.jsx(Au,{type:"button",className:`amx-control-legend ${me?"amx-control-legend-active":""}`,onClick:()=>we(U=>!U),title:me?"Hide node color legend":"Show node color legend","aria-label":me?"Hide node color legend":"Show node color legend",children:s.jsx(HM,{})})}),s.jsx(pf,{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(xM,{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 Qd((ae=U.data)==null?void 0:ae.kind).minimap}}):null,me?s.jsxs(pf,{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:Qd(U).stroke},children:ae},U))})]}):null,s.jsx(LM,{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:zs}),s.jsxs("span",{className:"amx-small",children:[Do," assertions · ",Oo," nodes · ",Po," edges"]})]}),s.jsxs("div",{className:"amx-toolbar",style:{marginTop:10},children:[s.jsxs("div",{className:"amx-toolbar-grid",children:[s.jsxs("label",{children:["search / highlight",s.jsx("input",{value:O,onChange:U=>P(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(Qp(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:!tn.length,children:"Apply layout"}),We==="force"?s.jsx("button",{type:"button",className:"amx-btn",onClick:Ti,disabled:!tn.length,children:lt?"Pause simulation":"Play simulation"}):null,s.jsx("button",{type:"button",className:"amx-btn",onClick:Mi,disabled:!tn.length,children:"Save layout"}),Bn?s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"amx-btn",onClick:Lo,children:"Load saved"}),s.jsx("button",{type:"button",className:"amx-btn",onClick:_l,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.",Bn?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:wn,onChange:U=>Cs(U.target.value),children:[s.jsx("option",{value:"",children:"(none)"}),tn.map(U=>s.jsx("option",{value:U,children:(()=>{const ae=oi.get(U)||U;return ae===U?ae:`${ae} (${U})`})()},U))]})]}),s.jsxs("label",{children:["path end",s.jsxs("select",{value:Kn,onChange:U=>ls(U.target.value),children:[s.jsx("option",{value:"",children:"(none)"}),tn.map(U=>s.jsx("option",{value:U,children:(()=>{const ae=oi.get(U)||U;return ae===U?ae:`${ae} (${U})`})()},U))]})]})]}),Fn?s.jsx("div",{className:"amx-small",style:{marginTop:10},children:Jr.map((U,ae)=>{const je=oi.get(U.from)||U.from,Ce=oi.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:[Ce,Ue]})]},`${U.edgeId}:${ae}`)})}):wn&&Kn?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)??Do," assertions · ",(Tn==null?void 0:Tn.nodes)??it.nodes.length," nodes ·"," ",(Tn==null?void 0:Tn.edges)??it.edges.length," edges). Start reaches ",(Tn==null?void 0:Tn.reachableFromStart)??0," nodes.",w?s.jsx("div",{style:{marginTop:10},children:s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>void yr(),disabled:ue,children:ue?"Expanding…":"Expand neighborhood"})}):null]}):s.jsx("div",{className:"amx-small",style:{marginTop:10},children:"(no path)"})]}),s.jsxs("details",{className:"amx-details",children:[s.jsx("summary",{children:"query"}),s.jsxs("div",{className:"amx-toolbar-grid",style:{marginTop:10},children:[s.jsxs("label",{children:["query_text (semantic)",s.jsx("input",{value:Ve,onChange:U=>st(U.target.value),placeholder:"e.g. emotion chip"})]}),s.jsxs("label",{children:["subject (exact)",s.jsx("input",{value:ut,onChange:U=>Et(U.target.value),placeholder:"e.g. ex:person-data"})]}),s.jsxs("label",{children:["predicate (exact)",s.jsx("input",{value:jt,onChange:U=>qt(U.target.value),placeholder:"e.g. schema:about"})]}),s.jsxs("label",{children:["object (exact)",s.jsx("input",{value:dt,onChange:U=>Yt(U.target.value),placeholder:"e.g. ex:concept-emotion-chip"})]}),s.jsxs("label",{children:["min_score",s.jsx("input",{type:"number",step:"any",value:Bt,onChange:U=>Nt(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:Yn,onChange:U=>ce(Ww(U.target.value,Yn)),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=>Ge(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:$e,onChange:U=>Wt(U.target.value),placeholder:"(auto)"})]}),s.jsxs("label",{children:["model (budgeting)",s.jsx("input",{value:Ct,onChange:U=>rn(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 _c(),disabled:!w||Y,children:Y?"Querying…":"Query store"}),s.jsx("button",{type:"button",className:"amx-btn",onClick:co,disabled:!D&&!re&&!Y,children:"Reset to step output"}),D?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=JM(ro);return U?s.jsx("div",{className:"amx-small",style:{marginBottom:8,opacity:.9},children:U}):null})(),(()=>{const U=$i;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=(D==null?void 0:D.packets_version)??Js,ae=(D==null?void 0:D.packed_count)??$s,je=(D==null?void 0:D.dropped)??fr,Ce=(D==null?void 0:D.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 Ce=="number"&&ke.push(`est_tokens=${Ce}`),ke.length?ke.join(" · "):"No packetization stats (set max_input_tokens > 0)."})()}),s.jsx("div",{className:"amx-active-memory",children:ZM(hn||"(empty)",O)}),(()=>{const U=D!=null&&D.packets&&Array.isArray(D.packets)?D.packets:us;return!Array.isArray(U)||U.length===0?null:s.jsxs("div",{style:{marginTop:10},children:[s.jsxs("button",{type:"button",className:"amx-btn",onClick:()=>nn(ae=>!ae),children:[lo?"Hide":"Show"," packets (",U.length,")"]}),lo?s.jsx("div",{className:"amx-list",style:{marginTop:10},children:U.slice(0,120).map((ae,je)=>{const Ce=ae&&typeof ae=="object"&&!Array.isArray(ae)?ae:null,ke=Ce&&typeof Ce.statement=="string"?Ce.statement:typeof ae=="string"?ae:"",Ue=Ce&&(typeof Ce.retrieval_score=="number"||typeof Ce.retrieval_score=="string")?Ce.retrieval_score:null,ft=Ce&&typeof Ce.observed_at=="string"?Ce.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."}),Qn?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:oi.get(Qn)||Qn}),s.jsxs("div",{className:"amx-small",children:["kind=",ds.get(Qn)||"entity"," · id=",Qn]})]}),s.jsxs("div",{className:"amx-actions",children:[s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>void Es(Qn),children:"Copy id"}),s.jsx("button",{type:"button",className:"amx-btn",onClick:Er,children:"Focus"})]})]}):As&&As.source&&As.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:[As.source," —",String(As.label||((uo=As.data)==null?void 0:uo.predicateSummary)||"").trim()||"?","→ ",As.target]}),s.jsxs("div",{className:"amx-small",children:["edge_id=",As.id]})]}),s.jsxs("div",{className:"amx-actions",children:[s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>void Es(As.id),children:"Copy id"}),s.jsx("button",{type:"button",className:"amx-btn",onClick:Er,children:"Fit"})]})]}):s.jsx("div",{className:"amx-small",style:{marginBottom:10,opacity:.9},children:"(no selection)"}),s.jsx("div",{className:"amx-list",children:Ar.slice(0,80).map((U,ae)=>{const je=String(U.subject||"").trim(),Ce=String(U.predicate||"").trim(),ke=String(U.object||"").trim(),Ue=oi.get(je)||je,ft=oi.get(ke)||ke,ot=ds.get(je)||"entity",gt=ds.get(ke)||"entity",Ft=Qd(ot),Ht=Qd(gt),vs=ef(U.observed_at),Rt=XM(U),sn=U.provenance&&typeof U.provenance=="object"&&!Array.isArray(U.provenance)?U.provenance:null,Cn=sn&&typeof sn.span_id=="string"?sn.span_id.trim():"",mn=sn&&typeof sn.writer_run_id=="string"?sn.writer_run_id.trim():"",es=typeof U.owner_id=="string"?U.owner_id.trim():"",nr=mn||es,Xr=!!((S||x)&&Cn&&nr),Ri=!!(S&&mn&&!Cn),xa=Xr||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&&(Yr(""),Zs(je))},children:Ue||je||"(subject)"}),s.jsx("span",{className:"amx-arrow",children:"—"}),s.jsx("span",{className:"amx-predicate",title:Ce,children:t0(Ce)||"(predicate)"}),s.jsx("span",{className:"amx-arrow",children:"→"}),s.jsx("button",{type:"button",className:"amx-term",style:{borderColor:Ht.stroke,background:Ht.bg},title:ke,onClick:()=>{ke&&(Yr(""),Zs(ke))},children:ft||ke||"(object)"})]}),s.jsxs("div",{className:"amx-triple-meta",children:[vs?s.jsxs("span",{className:"amx-small",title:String(U.observed_at||""),children:["[",vs,"]"]}):null,Rt?s.jsx("span",{className:"amx-small",children:Rt}):null]}),Cn||mn?s.jsxs("div",{className:"amx-triple-actions",children:[Cn?s.jsxs("span",{className:"amx-small",children:["span:",Cn]}):null,mn?s.jsxs("span",{className:"amx-small",children:["run:",mn]}):null,xa?s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>{if(Xr&&Cn&&nr){Qs({run_id:nr,span_id:Cn,assertion:U});return}Ri&&mn&&Qs({run_id:mn,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)."}),ai.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:ai.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&&Ei.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:Ei.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,!ai.length&&!(S&&Ei.length)?s.jsx("div",{className:"amx-small",children:"(no provenance)"}):null]})]})]})}function ll({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 ip(e,t="session"){const n=String(e||"").trim().toLowerCase();return n==="run"||n==="session"||n==="global"||n==="all"?n:t}function sl(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 tc(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 nR(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=sl(t);return n!==null?tc(n):t}function Og(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 n0(e){return String(e??"").replace(/[*_`~]/g,"")}function rm(e,t){const n=!!(t!=null&&t.strip_punct),i=Og(e);let o=n0(i).replace(/\s+/g," ").trim().toLowerCase();return n&&(o=o.replace(/[^\p{L}\p{N}\s]+/gu,"").replace(/\s+/g," ").trim()),o}function im(e,t){const n=String(t??"").trim();if(!n)return!1;const i=rm(n,{strip_punct:!1});if(!i)return!1;if(rm(String(e??""),{strip_punct:!1}).includes(i))return!0;const l=rm(n,{strip_punct:!0});return l?rm(String(e??""),{strip_punct:!0}).includes(l):!1}function Hw(e){const t=Og(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(n0(t)),n}function sR(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 y=c.join(`
138
- `).trim();y&&l.push({role:u,lines:[y]}),u=null,c=[]};for(const y of n){const x=i?null:y.match(/^\s*created_at\s*=\s*(.+)\s*$/i);if(x&&x[1]){i=x[1].trim();continue}const S=y.match(/^\s*(USER|ASSISTANT|SYSTEM)\s*:\s*(.*)$/i);if(S){f=!0,_();const b=String(S[1]||"").trim().toLowerCase();u=b==="user"?"user":b==="assistant"?"assistant":"system";const $=String(S[2]??"");c=$?[$]:[];continue}u?c.push(y):o.push(y)}if(_(),!f||!l.length)return null;const p=o.join(`
139
- `).trim(),w={messages:[]};i&&(w.created_at=i),p&&w.messages.push({role:"system",content:p});for(const y of l)w.messages.push({role:y.role,content:y.lines.join(`
140
- `)});return w.messages.length?w:null}function Vw(e,t){const n=String(e||""),i=String(t||"");return i>n?i:n}function Gw(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 rR(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 iR({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,w]=m.useState(!0),[y,x]=m.useState(750),[S,b]=m.useState(5e3),[$,E]=m.useState([]),[L,D]=m.useState(void 0),[M,H]=m.useState(""),[Z,Y]=m.useState(!1),[X,re]=m.useState([]),[ie,ue]=m.useState(!1),[F,C]=m.useState(!1),[N,O]=m.useState(""),[P,ne]=m.useState(""),[B,z]=m.useState(""),[G,T]=m.useState(""),[Q,K]=m.useState("artifact"),[J,oe]=m.useState(null),[fe,me]=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,Ge=be&&typeof be.note=="string"?String(be.note):"";return Og(Ge).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:im(ce,be)},[We,_t]),lt=m.useMemo(()=>{const ce=Pe,be=We;if(!ce||!be)return[];const Ge=[];for(let Ve=0;Ve<Math.min(ce.length,500);Ve++){const st=ce[Ve],ut=(st==null?void 0:st.content)==null?"":String(st.content);im(ut,be)&&Ge.push(Ve)}return Ge},[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 Qt=m.useMemo(()=>{const ce=String(i||"").trim(),be=String(l||"").trim();return`mindmap:${c}:${ce}:${be}`},[i,l,c]),_n=m.useMemo(()=>{let ce=null,be=null;for(const Ge of $){const Ve=sl(Ge==null?void 0:Ge.observed_at);Ve!==null&&(ce=ce===null?Ve:Math.min(ce,Ve),be=be===null?Ve:Math.max(be,Ve))}return{min_ms:ce,max_ms:be}},[$]),Ut=1e3,It=m.useMemo(()=>{const ce=_n.min_ms,be=_n.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 Ge=ce+Math.ceil((be-ce)/Ut)*Ut;return{min_ms:ce,max_ms:Ge,real_max_ms:be}},[_n.max_ms,_n.min_ms]),[un,Bn]=m.useState(!0),[Mt,bn]=m.useState(null);m.useEffect(()=>{un&&It&&bn(It.max_ms)},[un,It]);const Dn=m.useMemo(()=>{const ce=typeof Mt=="number"?Mt:null;return ce===null?$:$.filter(be=>{const Ge=sl(be==null?void 0:be.observed_at);return Ge===null?!0:Ge<=ce})},[$,Mt]),En=m.useCallback((ce,be)=>{const Ge=Array.isArray(ce)?ce:[],Ve=String(De.current||"").trim(),st=new Set,ut=[];let Et="";for(const jt of Ge){if(!jt||typeof jt!="object"||typeof jt.subject!="string"||typeof jt.predicate!="string"||typeof jt.object!="string")continue;const qt=Gw(jt);if(st.has(qt))continue;st.add(qt),ut.push(jt);const dt=String(jt.observed_at||"").trim();dt&&(Et=Vw(Et,dt))}E(ut),D(be==null?void 0:be.warnings),ge.current=st,De.current=Et||Ve},[]),jn=m.useCallback(async ce=>{const be=ip(ce.scope,"session"),Ge=String(ce.subject||"").trim(),Ve=String(ce.predicate||"").trim(),st=String(ce.object||"").trim(),ut=String(ce.since||"").trim(),Et=String(ce.until||"").trim(),jt=String(ce.active_at||"").trim(),qt=String(ce.query_text||"").trim(),dt=typeof ce.min_score=="number"&&Number.isFinite(ce.min_score)?Number(ce.min_score):void 0,Yt=ce.order==="asc"?"asc":"desc",Bt=typeof ce.limit=="number"&&Number.isFinite(ce.limit)?Number(ce.limit):0,Nt=String(i||"").trim(),pt=String(l||"").trim(),Ot={scope:be,all_owners:_,limit:Bt,order:Yt};Ge&&(Ot.subject=Ge),Ve&&(Ot.predicate=Ve),st&&(Ot.object=st),ut&&(Ot.since=ut),Et&&(Ot.until=Et),jt&&(Ot.active_at=jt),qt&&(Ot.query_text=qt),typeof dt=="number"&&(Ot.min_score=dt),_||(be==="run"?Nt&&(Ot.run_id=Nt):be==="session"?pt?Ot.session_id=pt:Nt&&(Ot.run_id=Nt):be==="all"&&(Nt?Ot.run_id=Nt:pt&&(Ot.session_id=pt)));try{const $e=await e.kg_query(Ot),Wt=Array.isArray($e==null?void 0:$e.items)?$e.items:[],Ct=$e==null?void 0:$e.warnings;return{ok:($e==null?void 0:$e.ok)!==!1,count:Number(($e==null?void 0:$e.count)||Wt.length),items:Wt,warnings:Ct,raw:$e}}catch($e){const Wt=$e instanceof Error?$e.message:String($e);if(Wt.includes("Run '")&&Wt.includes("not found")&&!pt&&(be==="session"||be==="all")&&Nt){const rn=await e.kg_query({...Ot,run_id:void 0,session_id:Nt}),$t=Array.isArray(rn==null?void 0:rn.items)?rn.items:[],cs=rn==null?void 0:rn.warnings;return{ok:(rn==null?void 0:rn.ok)!==!1,count:Number((rn==null?void 0:rn.count)||$t.length),items:$t,warnings:cs,raw:rn}}throw new Error(Wt||"KG query failed")}},[_,e,i,l]),Ln=m.useCallback(async ce=>{var Ve;const be=String(ce.run_id||"").trim(),Ge=String(ce.span_id||"").trim();if(!(!be||!Ge)){ue(!0),C(!0),O(""),z(be),T(Ge),K("artifact"),ne(`source span:${Ge}`),oe(null),me(""),Ae(ce.assertion&&typeof ce.assertion=="object"?ce.assertion:null),Be.current=!1;try{const st=[be],ut=typeof((Ve=ce.assertion)==null?void 0:Ve.owner_id)=="string"?String(ce.assertion.owner_id).trim():"";ut&&ut!==be&&st.push(ut);let Et=null,jt=null;for(const qt of st)try{jt=await(await e.download_run_artifact_content(qt,Ge)).text(),qt!==be&&z(qt);break}catch(dt){Et=dt instanceof Error?dt.message:String(dt)}if(jt==null)throw new Error(Et||"Failed to load source span");me(jt);try{const qt=JSON.parse(jt);oe(qt)}catch{oe(null)}}catch(st){const ut=st instanceof Error?st.message:String(st);O(ut||"Failed to load source span")}finally{C(!1)}}},[e]),wn=m.useCallback(async ce=>{const be=String(ce.run_id||"").trim();if(!be)return null;try{const Ge=await e.list_run_artifacts(be,{limit:200}),st=(Array.isArray(Ge==null?void 0:Ge.items)?Ge.items:[]).map(dt=>{const Yt=typeof(dt==null?void 0:dt.artifact_id)=="string"?String(dt.artifact_id).trim():"",Bt=dt!=null&&dt.tags&&typeof dt.tags=="object"&&!Array.isArray(dt.tags)?dt.tags:null,Nt=Bt&&typeof Bt.kind=="string"?String(Bt.kind).trim():"";return{artifact_id:Yt,kind:Nt}}).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,Et=ut!=null&&ut.attributes&&typeof ut.attributes=="object"&&!Array.isArray(ut.attributes)?ut.attributes:null,qt=(Et&&typeof Et.evidence_quote=="string"?String(Et.evidence_quote):"").trim();if(!qt)return null;for(const dt of st.slice(0,10))try{const Bt=await(await e.download_run_artifact_content(be,dt.artifact_id)).text(),Nt=JSON.parse(Bt);if(Nt&&typeof Nt=="object"){const pt=typeof Nt.note=="string"?String(Nt.note):"";if(pt&&pt.includes(qt))return dt.artifact_id;const Ot=Array.isArray(Nt.messages)?Nt.messages:null;if(Ot){for(const $e of Ot.slice(0,200))if((($e==null?void 0:$e.content)==null?"":String($e.content)).includes(qt))return dt.artifact_id}}}catch{}}catch{}return null},[e]),Cs=m.useCallback(async ce=>{const be=String(ce.run_id||"").trim();if(be){ue(!0),C(!0),O(""),z(be),T(""),K("run_input"),ne(`transcript run:${be}`),oe(null),me(""),Ae(ce.assertion&&typeof ce.assertion=="object"?ce.assertion:null),Be.current=!1;try{const Ge=await wn({run_id:be,assertion:ce.assertion});if(Ge){await Ln({run_id:be,span_id:Ge,assertion:ce.assertion});return}const Ve=await e.get_run_input_data(be),st=Ve&&typeof Ve=="object"&&!Array.isArray(Ve)?Ve.input_data:null,ut={kind:"run_input_data",run_id:be};if(Ve&&typeof(Ve==null?void 0:Ve.workflow_id)=="string"&&(ut.workflow_id=String(Ve.workflow_id)),st&&typeof st=="object"&&!Array.isArray(st)){const Et=st.context,qt=(Et&&typeof Et=="object"&&Array.isArray(Et.messages)?Et.messages:null)||(Array.isArray(st.messages)?st.messages:null);Array.isArray(qt)&&(ut.messages=qt);const dt=["text","prompt","task","message"];for(const Yt of dt){const Bt=st[Yt];if(typeof Bt=="string"&&Bt.trim()){ut.note=Bt.trim();break}}ut.input_data=st}!ut.messages&&!ut.note&&(ut.note=JSON.stringify(st??Ve??{},null,2));try{const Et=await e.get_run(be),jt=Et&&typeof(Et==null?void 0:Et.created_at)=="string"?String(Et.created_at):"";jt&&(ut.created_at=jt)}catch{}oe(ut),me(JSON.stringify(Ve,null,2))}catch(Ge){const Ve=Ge instanceof Error?Ge.message:String(Ge);O(Ve||"Failed to load run input transcript")}finally{C(!1)}}},[e,Ln,wn]),Kn=m.useCallback(async()=>{H(""),Y(!0);try{const ce=c==="all"?"all":c,be=await jn({scope:ce,limit:0,order:"desc"});En(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,En,c]);m.useEffect(()=>{$.length||Kn()},[]);const ls=m.useCallback(async ce=>{const be=ip(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]),Cr=m.useCallback((ce,be)=>{var Ge;if((be==null?void 0:be.kind)==="live query"){const Ve=Dt.current;Ve&&(Ke.current={scope:ip(Ve.scope,"session"),subject:typeof Ve.subject=="string"?Ve.subject:void 0,predicate:typeof Ve.predicate=="string"?Ve.predicate:void 0,object:typeof Ve.object=="string"?Ve.object:void 0})}En(ce,{warnings:(Ge=be==null?void 0:be.result)==null?void 0:Ge.warnings})},[En]),Yn=m.useCallback(async()=>{const ce=Ke.current;if(!ce)return;const be=String(De.current||"").trim(),Ge=await jn({scope:ce.scope,subject:ce.subject,predicate:ce.predicate,object:ce.object,since:be||void 0,order:"asc",limit:0}),Ve=Array.isArray(Ge.items)?Ge.items:[];if(!Ve.length)return;const ut=Date.now()+Math.max(250,Math.min(2e4,S)),Et=ge.current,jt=[],qt=[];let dt=String(De.current||"").trim();for(const Yt of Ve){if(!Yt||typeof Yt!="object"||typeof Yt.subject!="string"||typeof Yt.predicate!="string"||typeof Yt.object!="string")continue;const Bt=Gw(Yt);if(Et.has(Bt))continue;Et.add(Bt),jt.push(Yt),qt.push({id:Bt,assertion:Yt,expires_at_ms:ut});const Nt=String(Yt.observed_at||"").trim();Nt&&(dt=Vw(dt,Nt))}jt.length&&(De.current=dt,E(Yt=>{const Bt=Yt.concat(jt);return Bt.sort((Nt,pt)=>String((pt==null?void 0:pt.observed_at)||"").localeCompare(String((Nt==null?void 0:Nt.observed_at)||""))),Bt}),re(Yt=>{const Bt=Yt.concat(qt);return Bt.sort((Nt,pt)=>pt.expires_at_ms-Nt.expires_at_ms),Bt.slice(0,30)}))},[S,jn]);return m.useEffect(()=>{if(!p)return;let ce=!1,be=null;const Ge=async()=>{if(!ce){try{await Yn()}catch{}ce||(be=window.setTimeout(()=>void Ge(),Math.max(250,Math.min(6e4,y))))}};return Ge(),()=>{ce=!0,be!==null&&window.clearTimeout(be)}},[p,y,Yn]),m.useEffect(()=>{if(!X.length)return;const ce=window.setInterval(()=>{const be=Date.now();re(Ge=>Ge.filter(Ve=>Ve.expires_at_ms>be))},250);return()=>window.clearInterval(ce)},[X.length]),s.jsxs("div",{className:"mindmap_root",children:[s.jsxs("div",{className:"mindmap_bar",children:[s.jsx("button",{className:"btn",onClick:()=>void Kn(),disabled:Z,children:Z?"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=>w(!!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:y,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=>b(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(tR,{title:"mindmap",resetKey:Qt,queryMode:"replace",items:Dn,warnings:L,onQuery:ls,onItemsReplace:Cr,onOpenSpan:({run_id:ce,span_id:be,assertion:Ge})=>{Ln({run_id:ce,span_id:be,assertion:Ge})},onOpenTranscript:({run_id:ce,span_id:be,assertion:Ge})=>{const Ve=String(ce||"").trim(),st=typeof be=="string"?String(be).trim():"";Ve&&(st?Ln({run_id:Ve,span_id:st,assertion:Ge}):Cs({run_id:Ve,assertion:Ge}))}},Qt),X.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:X.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:rR(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:tc(Math.min(typeof Mt=="number"?Mt:It.max_ms,It.real_max_ms))}),s.jsx("input",{className:"mindmap_slider",type:"range",min:It.min_ms,max:It.max_ms,step:Ut,value:typeof Mt=="number"?Mt:It.max_ms,onChange:ce=>{const be=Number(ce.target.value||0);bn(be),Bn(be>=It.max_ms)}}),s.jsxs("div",{className:"mindmap_timeline_counts mono muted",children:[Dn.length.toLocaleString(),"/",$.length.toLocaleString()]})]})}):null]}),s.jsxs(ll,{open:ie,title:P||"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(),Ge=String(ce.predicate||"").trim(),Ve=String(ce.object||"").trim(),st=tc(sl(ce.observed_at)),ut=ce.attributes&&typeof ce.attributes=="object"&&!Array.isArray(ce.attributes)?ce.attributes:null,Et=ut&&typeof ut.evidence_quote=="string"?String(ut.evidence_quote):"",jt=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} --${Ge}--> ${Ve}`,children:[be," ",s.jsxs("span",{className:"muted",children:["—",Ge,"→"]})," ",Ve," ",st?s.jsxs("span",{className:"muted",children:["[",st,"]"]}):null]}),Et?s.jsxs("div",{className:"source_evidence",children:[s.jsx("div",{className:"mono muted",style:{fontSize:11,marginBottom:6},children:"evidence_quote"}),s.jsx("pre",{className:"mono source_evidence_quote",children:Et}),jt?s.jsxs("details",{className:"source_evidence_more",children:[s.jsx("summary",{className:"mono muted",children:"original_context"}),s.jsx("pre",{className:"mono source_evidence_quote",children:jt})]}):null]}):null]})})(),s.jsxs("div",{className:"mono muted",style:{marginBottom:10},children:["run_id=",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,Ge=Pe,Ve=_t,st=be&&typeof be.created_at=="string"?String(be.created_at):"",ut=st?sl(st):null,Et=ut!==null?tc(ut):st,jt=be&&be.span&&typeof be.span=="object"&&!Array.isArray(be.span)?be.span:null,qt=jt&&typeof jt.from_timestamp=="string"?String(jt.from_timestamp):"",dt=jt&&typeof jt.to_timestamp=="string"?String(jt.to_timestamp):"",Yt=qt?sl(qt):null,Bt=dt?sl(dt):null,Nt=Yt!==null&&Bt!==null?`${tc(Yt)} → ${tc(Bt)}`:"";if(Ve){const pt=sR(Ve);if(pt){const Ot=We,$e=Ot?pt.messages.findIndex($t=>im($t.content,Ot)):-1,Wt=Ot?Hw(Ot):[],Ct=pt.created_at||st,rn=Ct?nR(Ct):st?Et:"";return s.jsx("div",{className:"source_chat",children:pt.messages.map(($t,cs)=>{const us=$t.role,Js=!!(Ot&&im($t.content,Ot)),$s=us==="user"?"USER":us==="assistant"?"ASSISTANT":"SYSTEM";return s.jsxs("div",{id:cs===$e?"source_note_msg_hit_0":void 0,className:`source_msg source_${us} ${Js?"source_match":""}`,children:[s.jsxs("div",{className:"source_msg_meta mono muted",children:[s.jsxs("span",{children:["#",cs+1," · ",$s,Js?s.jsx("span",{className:"source_match_badge",children:"evidence"}):null]}),rn?s.jsx("span",{title:Ct||"",children:rn}):null]}),s.jsx("div",{className:"source_msg_body",children:s.jsx(Ni,{text:$t.content,highlights:Js&&Wt.length?Wt:void 0,highlightClassName:"source_note_hit",highlightId:cs===$e?"source_note_hit_0":void 0})})]},`note_msg:${cs}`)})})}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=",Et]})}):null,s.jsx(Ni,{text:Ve,highlights:We?Hw(We):void 0,highlightClassName:"source_note_hit",highlightId:"source_note_hit_0"})]})}if(Ge){const pt=new Map;for(const $e of Ge){const Wt=typeof($e==null?void 0:$e.role)=="string"?String($e.role):"unknown";pt.set(Wt,(pt.get(Wt)||0)+1)}const Ot=Array.from(pt.entries()).sort(($e,Wt)=>Wt[1]-$e[1]||$e[0].localeCompare(Wt[0])).map(([$e,Wt])=>`${$e}×${Wt}`).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=",Et]})," · messages=",Ge.length]}):null,Nt?s.jsxs("div",{className:"mono muted",style:{marginBottom:10},children:["span=",Nt]}):null,Ot?s.jsxs("div",{className:"mono muted",style:{marginBottom:10},children:["participants: ",Ot]}):null,Ge.slice(0,200).map(($e,Wt)=>{var fr,Xs;const Ct=typeof($e==null?void 0:$e.role)=="string"?String($e.role):"unknown",rn=($e==null?void 0:$e.content)==null?"":String($e.content),$t=typeof($e==null?void 0:$e.timestamp)=="string"?String($e.timestamp):"",cs=$t?sl($t):null,us=cs!==null?tc(cs):$t,Js=typeof($e==null?void 0:$e.message_id)=="string"?String($e.message_id):typeof((fr=$e==null?void 0:$e.metadata)==null?void 0:fr.message_id)=="string"?String($e.metadata.message_id):typeof((Xs=$e==null?void 0:$e.metadata)==null?void 0:Xs.id)=="string"?String($e.metadata.id):"",$s=Ye.has(Wt);return s.jsxs("div",{id:`source_msg_${Wt}`,className:`source_msg source_${Ct} ${$s?"source_match":""}`,children:[s.jsxs("div",{className:"source_msg_meta mono muted",children:[s.jsxs("span",{children:["#",Wt+1," · ",Ct,$s?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:us}):null]}),s.jsx("div",{className:"source_msg_body",children:s.jsx(Ni,{text:rn})})]},Wt)})]})}return s.jsx("pre",{className:"mono source_raw",style:{whiteSpace:"pre-wrap",wordBreak:"break-word"},children:(typeof ce=="string"?ce:fe)||"(empty)"})})()]}):null]})]})}const op=4;function oR(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 Kw(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 aR(e){var c,f;const t=_=>{var w;const p=(w=e==null?void 0:e[_])==null?void 0:w.open;return Array.isArray(p)?p.map(Kw).filter(y=>y!==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(Kw).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,op),questions_total:n.length,problems:i.slice(0,op),problems_total:i.length,lessons:l.slice(0,op),lessons_total:u}}function ap(e){return e===null||!Number.isFinite(e)||e<0?"":e<1e3?String(Math.round(e)):e<1e6?`${(e/1e3).toFixed(e<1e4?1:0)}k`:`${(e/1e6).toFixed(1)}M`}const Yw={review:"Review",working:"Working",pending:"Pending",done:"Done"},lR={review:"nothing needs you",working:"idle",pending:"nothing scheduled",done:"no recent runs"},cR={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 uR(e){const t=String((e==null?void 0:e.status)||"").trim().toLowerCase();if(Ci(t))return"done";const n=Uu(e);return n==="tool_approval"||n==="user_response"?"review":n==="scheduled"||t==="pending"||t==="queued"||t==="created"?"pending":"working"}function dR(e){const t=Uu(e);return t==="tool_approval"||t==="user_response"}function Jw(e,t=Date.now()){const n=uR(e),i=e!=null&&e.waiting&&typeof e.waiting=="object"?e.waiting:null,o=Bu(i),l=Nn((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:Uu(e),reason:Sx(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:fg(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:cf(e),tag_label:rx(e),automation_id:cf(e)==="occurrence"?String((e==null?void 0:e.automation_id)||"").trim():""}}function fR(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)||Sy(u)||dR(u)&&(l.add(c),i.review.push(Jw(u,n)))}for(const u of e||[]){const c=String((u==null?void 0:u.run_id)||"").trim();if(!u||!c||l.has(c)||Sy(u))continue;const f=Jw(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 eg={"12h":12*36e5,"24h":24*36e5,"48h":48*36e5,"72h":72*36e5,"7d":7*864e5,"14d":14*864e5,"1m":30*864e5,all:null},lp={"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"},Xw="48h";function hR(e,t,n=Date.now()){const i=eg[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 mR(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 _R=6e4;function tf(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 pR(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 gR(e){const t=String(e||"");return t.length>14?`${t.slice(0,6)}…${t.slice(-6)}`:t}function cp(e){const t=String(e||"").trim();return t.length>72?`${t.slice(0,70)}…`:t}function yR(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 mm(e){return e.toLowerCase().replace(/[_-]+/g," ")}function wR(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(w=>w&&typeof w=="string");if(!i.length)return null;const o=[];for(const w of i){o.push({needle:mm(w),phase:w});const y=(_=n[w])==null?void 0:_.spoken_synonyms;if(Array.isArray(y))for(const x of y){const S=mm(String(x||"").trim());S&&o.push({needle:S,phase:w})}}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[w,y]of Object.entries(f)){const x=String((y==null?void 0:y.phase)||"").trim(),S=mm(String(w||"").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 vR=["asleep","sleep","dream"],xR=["rest"],bR=["awake","idle"];function jR(e,t){const n=String(e||"").trim().toLowerCase();if(!n)return"unknown";if(t){const i=mm(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":vR.some(u=>n.includes(u))?t.initial:xR.some(u=>n.includes(u))&&t.phases.includes("personal")?"personal":bR.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 SR=new Set(["visit","work","personal","sleep","paused","resting","stopped","unknown"]),kR=new Set(["visit","work","personal","sleep","paused","resting","stopped","unknown"]);function NR(e){if(!e)return SR;const t=e.phases.filter(n=>kR.has(n));return new Set([...t,"paused","stopped","unknown"])}function CR(e){var Z,Y,X,re,ie,ue;const t=Date.now(),n=m.useMemo(()=>fR(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 eg?F:Xw}catch{return Xw}}),w=m.useMemo(()=>hR(n.done,_,t),[n.done,_]),y=tf(e.runs_refreshed_at,t),x=n.review.length,S=w.visible.filter(F=>F.failed).length,[b,$]=m.useState(""),[E,L]=m.useState(null),D=F=>`${F.run_id}:${F.wait_key}:${F.since_ms??""}`;m.useEffect(()=>{i&&(n.review.some(F=>D(F)===i)||o(""))},[n,i]);async function M(F,C){o(D(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===D(F),N=F.column==="review",O=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:P=>{P.key==="Enter"&&P.target===P.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:yR(F.workflow)}),(()=>{const P=F.failed?"failed":jm({status:F.status,paused:F.paused});return s.jsx("span",{className:`mc_status ${fl(P)}`,children:P==="unknown"?"?":P})})()]}),s.jsxs("div",{className:"mc_card_meta",children:[s.jsx("span",{className:"mono",title:F.run_id,children:gR(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:P=>{P.stopPropagation(),e.on_open_automation(F.automation_id)},onKeyDown:P=>P.stopPropagation(),children:"Automation"}):null,F.duration_ms>=0?s.jsx("span",{children:pR(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:P=>P.stopPropagation(),onKeyDown:P=>P.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((P,ne)=>s.jsx("span",{className:"mc_tool_chip mono",children:P},`${P}_${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 ",tf(F.since_ms,t)]}):null,O?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,O?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:[y?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 ",y," 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=jR(C,e.phase_graph),O=NR(e.phase_graph).has(N)?N:"other",P=((z=e.phase_graph)==null?void 0:z.initial)??"sleep",ne=/awake|idle/i.test(C)&&N===P,B=C&&C.toLowerCase()!==N?` — wire word: ${C}${ne?" (settling)":""}`:"";return s.jsx("span",{className:`mc_entity_phase mc_phase_${O}`,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=mR(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?` · ${tf(t-C,t)} ago`:""]}):C===null?null:C<=_R?s.jsx("span",{className:"mc_entity_live",title:`last moment ${tf(t-C,t)} ago`,children:"● active"}):s.jsxs("span",{className:"mc_entity_live muted",title:"time since the last recorded moment",children:[tf(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: ${ap(F.live_visit_tokens)} tk`:""}${F.spend_warning?`; ${F.spend_warning}`:""}`,children:[ap(F.tokens_total)," tk",F.live_visit_tokens!==null?` (+${ap(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":b===F.name,title:"open questions / problems + distilled lessons + night signals from the entity card — click to expand",onClick:()=>$(b===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(!b)return null;const F=e.entities.find(O=>O.name===b);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 O=>{const P=await e.on_read_diary(F.name,O);L({entity:F.name,entry:(P==null?void 0:P.entry)??P,seq:typeof(P==null?void 0:P.read_recorded_at_seq)=="number"?P.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((O,P)=>s.jsx(N_,{kind:"question",label:O.title||cp(O.statement),entryId:O.entry_id,onOpen:C,title:O.statement||O.title},`q_${O.record_id||P}`)),F.open_problems.map((O,P)=>s.jsx(N_,{kind:"problem",label:O.title||cp(O.statement),entryId:O.entry_id,onOpen:C,title:O.statement||O.title},`p_${O.record_id||P}`)),F.lessons.map((O,P)=>s.jsx(N_,{kind:"lesson",label:O.title||cp(O.statement),entryId:O.entry_id,onOpen:C,title:O.statement||O.title},`l_${O.record_id||P}`)),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,E?s.jsx(ll,{open:!0,title:`${E.entity} — diary entry`,onClose:()=>L(null),children:s.jsxs("div",{className:"mc_diary_entry",children:[s.jsx("div",{className:"mc_diary_meta muted",children:[(Z=E.entry)!=null&&Z.kind?`kind: ${E.entry.kind}`:"",(Y=E.entry)!=null&&Y.visibility?`visibility: ${E.entry.visibility}`:"",(X=E.entry)!=null&&X.written_at?`written: ${E.entry.written_at}`:"",(re=E.entry)!=null&&re.entry_id?`id: ${E.entry.entry_id}`:""].filter(Boolean).join(" · ")}),s.jsxs("div",{className:"mc_diary_recorded muted",children:["this read was recorded in ",E.entity,"’s stream",E.seq!==null?` (seq ${E.seq})`:""]}),(ie=E.entry)!=null&&ie.gist?s.jsx("div",{className:"mc_diary_gist",children:String(E.entry.gist)}):null,s.jsx("pre",{className:"mc_diary_text",children:String(((ue=E.entry)==null?void 0:ue.text)||"(entry carries no text)")})]})}):null,s.jsx("div",{className:"mc_board",children:Object.keys(Yw).map(F=>{const C=F==="done"?w.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:Yw[F]}),F==="done"?s.jsx("select",{className:"mc_window_select",value:_,title:"Show terminal runs from this time window",onClick:O=>O.stopPropagation(),onChange:O=>{const P=O.target.value;p(P),f(!1);try{localStorage.setItem("abstractobserver_done_window_v1",P)}catch{}},children:Object.keys(eg).map(O=>s.jsx("option",{value:O,children:lp[O]},O))}):null,s.jsx("span",{className:"mc_column_count",title:F==="done"&&w.hidden_count?`${w.hidden_count} older run(s) outside this window`:void 0,children:C.length})]}),s.jsx("div",{className:"mc_column_hint muted",children:cR[F]}),s.jsxs("div",{className:"mc_column_cards",children:[N.map(O=>H(O)),C.length?null:s.jsx("div",{className:"mc_empty muted",children:e.runs_refreshed_at===null?"loading…":F==="done"&&w.hidden_count?`none in the ${lp[_]} — ${w.hidden_count} older`:lR[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"&&w.hidden_count&&C.length?s.jsxs("div",{className:"mc_window_note muted",title:"Widen the window above to see older terminal runs",children:["+",w.hidden_count," older outside ",lp[_]]}):null]})]},F)})})]})}function Zw(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 Qw(e){const t=e.disabled===!0,n=m.useMemo(()=>Zw(e.options||[]),[e.options]),i=m.useMemo(()=>Zw(e.value||[]),[e.value]),[o,l]=m.useState(!1),[u,c]=m.useState(""),f=m.useMemo(()=>{const w=u.trim().toLowerCase();return w?n.filter(y=>y.toLowerCase().includes(w)):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(w=>!w),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(w=>s.jsxs("span",{className:"multi_select_chip",title:w,onClick:()=>{if(t)return;const y=new Set(_);y.delete(w),e.onChange(Array.from(y.values()))},children:[w,t?null:s.jsx("span",{className:"multi_select_chip_x",children:"×"})]},w))}):null,o?s.jsxs("div",{className:"multi_select_panel",children:[s.jsx("input",{className:"mono",value:u,onChange:w=>c(String(w.target.value||"")),placeholder:"filter…",disabled:t}),s.jsxs("div",{className:"multi_select_list",style:{maxHeight:`${p}px`},children:[f.map(w=>{const y=_.has(w);return s.jsxs("label",{className:`multi_select_item mono ${y?"checked":""}`,children:[s.jsx("input",{type:"checkbox",checked:y,disabled:t,onChange:x=>{const S=new Set(_);x.target.checked?S.add(w):S.delete(w),e.onChange(Array.from(S.values()))}}),s.jsx("span",{children:w})]},w)}),f.length?null:s.jsx("div",{className:"mono muted",children:"(no matches)"})]})]}):null]})}function $R(){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 AR(){if(typeof window>"u")return!1;const e=window;return!!(e!=null&&e.AudioContext||e!=null&&e.webkitAudioContext)}function ER(){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 TR(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 MR(e){const t=O=>{var P;return(P=e.on_error)==null?void 0:P.call(e,O)},n=m.useMemo(()=>AR(),[]),i=m.useMemo(()=>$R(),[]),[o,l]=m.useState({key:"",status:"idle"}),u=m.useRef(""),c=m.useRef(""),f=m.useRef(null),_=m.useRef(null),p=m.useRef(null),w=m.useRef(null),y=m.useRef(0),x=m.useRef(0),S=()=>{try{const O=globalThis,P=(O==null?void 0:O.AudioContext)||(O==null?void 0:O.webkitAudioContext);if(!P)return null;if(!f.current){const z=new P,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}},b=()=>{const O=p.current;if(p.current=null,!!O){try{O.onended=null}catch{}try{O.stop()}catch{}try{O.disconnect()}catch{}}},$=()=>{b(),c.current="",u.current="",w.current=null,y.current=0,x.current=0,l({key:"",status:"idle"})};m.useEffect(()=>()=>{var O,P;$();try{(O=_.current)==null||O.disconnect()}catch{}try{(P=f.current)==null||P.close()}catch{}f.current=null,_.current=null,w.current=null},[]);const E=async(O,P,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{}b();const T=z.createBufferSource();T.buffer=P,T.connect(G);const Q=Number.isFinite(Number(P.duration))?Number(P.duration):0,K=Math.max(0,Math.min(Number(ne||0),Q>0?Math.max(0,Q-.01):0));x.current=z.currentTime-K,y.current=K,p.current=T,u.current=O,T.onended=()=>{p.current===T&&(p.current=null,y.current=0,x.current=0,u.current="",l({key:"",status:"idle"}))},T.start(0,K),l({key:O,status:"playing"})},L=async(O,P)=>{const ne=String(O||"").trim(),B=String(P||"").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));y.current=K,b(),l({key:ne,status:"paused"});return}if(Q&&o.status==="paused"){const K=w.current;if(K){t==null||t("");try{await E(ne,K,y.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")){b(),w.current=null,y.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:Ps()}),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 me=await(await z.download_run_artifact_content(G,oe)).arrayBuffer();if(c.current!==ne)return;const we=await TR(T.ctx,me);if(c.current!==ne)return;w.current=we,y.current=0,await E(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"))}}},[D,M]=m.useState(!1),[H,Z]=m.useState(!1),Y=m.useRef(null),X=m.useRef(null),re=m.useRef([]),ie=m.useRef("");function ue(){var O,P;try{(P=(O=Y.current)==null?void 0:O.getTracks)==null||P.call(O).forEach(ne=>{try{ne.stop()}catch{}})}catch{}Y.current=null}m.useEffect(()=>()=>{var O,P;try{(P=(O=X.current)==null?void 0:O.stop)==null||P.call(O)}catch{}X.current=null,ue()},[]);async function F(O,P){var G;if(t==null||t(""),!O||!O.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}Z(!0);try{const T=String(P||O.type||"").toLowerCase(),Q=T.includes("mp4")?"m4a":T.includes("ogg")?"ogg":T.includes("wav")?"wav":"webm",K=new File([O],`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:Ps()}),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{Z(!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&&!(D||X.current)){re.current=[];try{const O=await navigator.mediaDevices.getUserMedia({audio:!0});Y.current=O;const P=ER();ie.current=P;const ne=P?new MediaRecorder(O,{mimeType:P}):new MediaRecorder(O);X.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(),X.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(O){ue(),X.current=null,M(!1);const P=String((O==null?void 0:O.message)||O||"Failed to access microphone");t==null||t(P.toLowerCase().includes("permission")?`Microphone permission denied: ${P}`:P)}}}function N(){const O=X.current;if(!(!D||!O)){X.current=null,M(!1);try{O.stop()}catch(P){t==null||t(String((P==null?void 0:P.message)||P||"Failed to stop recording"))}}}return m.useEffect(()=>{if(!D)return;const O=()=>N();return window.addEventListener("pointerup",O),window.addEventListener("pointercancel",O),()=>{window.removeEventListener("pointerup",O),window.removeEventListener("pointercancel",O)}},[D]),{tts_supported:n,tts_playback:o,toggle_tts:L,stop_tts:$,voice_ptt_supported:i,voice_ptt_recording:D,voice_ptt_busy:H,start_voice_ptt_recording:C,stop_voice_ptt_recording:N}}const om=500,Om="http://127.0.0.1:8080";function ev(e){const t=String(e||"").trim(),n=t.indexOf(":");return n<=0||n>=t.length-1?null:{bundle_id:t.slice(0,n),flow_id:t.slice(n+1)}}function nf(e){const t=String(e||"").trim();return t.startsWith("abstractcode.")?`abstract.${t.slice(13)}`:t}function up(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 dp(e){const t=String(e||"").trim();return t.startsWith("abstract.")||t.startsWith("abstractcode.")}function RR(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 LR(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,w={id:f,label:p,type:_||"unknown"};l&&Object.prototype.hasOwnProperty.call(l,f)&&(w.default=l[f]),u.push(w)}return u}function fp(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 IR=/^[a-zA-Z0-9_-]+$/;function tv(e){return IR.test(String(e||"").trim())}async function OR(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 nv(e){const t=String(e||"").trim();if(!t)throw new Error("session_id is required");if(tv(t)){const i=`session_memory_${t}`;if(tv(i))return i}return`session_memory_sha_${(await OR(t)).slice(0,32)}`}const sv=new Set(["abstract.status","abstract.summary","abstract.chat"]);function PR(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!sv.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&&sv.has(t))}if(String(e.status||"").trim()==="waiting"){const l=Ji(e.data),u=String((l==null?void 0:l.reason)||"").trim();return!!(u==="user"||u==="event"||Bu(l).length)}return!!kf(e.data)}function DR(){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)||Om),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:Om,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 FR(e){localStorage.setItem("abstractobserver_settings",JSON.stringify({...e,auth_token:""}))}function zR(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 rv(e){const t=zR(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 BR(){return typeof window>"u"?"":mN(window.location)}function UR(){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 WR(){var Kl,Yl,Ls,Gi,qr,Vs,Pd,hu,mu,Ah,Ki,Dd,_u;const[e,t]=m.useState("board"),[n,i]=m.useState(()=>DR()),o=typeof window<"u"&&((Kl=window.__ABSTRACT_UI_CONFIG__)==null?void 0:Kl.monitor_gpu)===!0,l=typeof window<"u"&&(((Yl=window.__ABSTRACT_UI_CONFIG__)==null?void 0:Yl.entity_app_url)||"").trim().replace(/\/+$/,"")||"http://127.0.0.1:3007",u=m.useRef(null),[c,f]=m.useState(""),[_,p]=m.useState(""),[w,y]=m.useState(()=>BR()),[x,S]=m.useState(""),[b,$]=m.useState(""),[E,L]=m.useState("{}"),[D]=m.useState(()=>UR()),[M,H]=m.useState(null),[Z,Y]=m.useState(!1),[X,re]=m.useState(""),[ie,ue]=m.useState(!1),[F,C]=m.useState(""),[N,O]=m.useState(!1),P=$j({appName:"AbstractObserver",variant:"dismissable",defaultGatewayUrl:typeof window<"u"&&((Ls=window.__ABSTRACT_UI_CONFIG__)==null?void 0:Ls.gateway_url)||Om,onStatusChange:g=>Br(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"),[me,we]=m.useState(""),[Ae,Be]=m.useState($p),[We,_t]=m.useState([]),[Pe,et]=m.useState(null),[lt,Ye]=m.useState(!1),[Se,Le]=m.useState([]),ct=m.useRef(new NN(Ps)),[ge,De]=m.useState({available:!1,reason:"Sign in to a gateway to use automations."}),[Ke,Dt]=Yj("abstractobserver",{legacyKey:"abstractobserver_settings"}),[Qt,_n]=m.useState(!1),[Ut,It]=m.useState(!1),[un,Bn]=m.useState([]),[Mt,bn]=m.useState([]),[Dn,En]=m.useState([]),[jn,Ln]=m.useState(!1),[wn,Cs]=m.useState(null),[Kn,ls]=m.useState([]),[Cr,Yn]=m.useState(0),[ce,be]=m.useState(""),Ge=m.useRef(!1),Ve=m.useRef(0),st=m.useRef(0),[ut,Et]=m.useState(!1),[jt,qt]=m.useState([]),[dt,Yt]=m.useState([]),[Bt,Nt]=m.useState({}),[pt,Ot]=m.useState(!1),[$e,Wt]=m.useState(!1),[Ct,rn]=m.useState(!1),[$t,cs]=m.useState([]),[us,Js]=m.useState([]),$s=m.useRef(0),fr=m.useRef(null);fr.current||(fr.current=new qy(g=>window.setTimeout(g,40),g=>cs(k=>k.concat(g))));const Xs=m.useRef(null);Xs.current||(Xs.current=new qy(g=>window.setTimeout(g,40),g=>Js(k=>k.concat(g))));const so=m.useRef({scanned:0,found:null}),[xe,Jn]=m.useState(null),[hn,ro]=m.useState(""),[$i,$r]=m.useState(!1),hr=m.useRef(null),[Kr,it]=m.useState({}),[tn,gs]=m.useState({}),[oi,ds]=m.useState(!1),[io,oo]=m.useState(""),[ya,Fn]=m.useState(!0),[mr,Tn]=m.useState(""),[_r,ao]=m.useState(!1),[Qn,Zs]=m.useState(!1),[fs,Yr]=m.useState(6),[ys,wa]=m.useState("standard"),[lo,nn]=m.useState(""),[ml,Ai]=m.useState(""),[pr,As]=m.useState(!1),[va,Ar]=m.useState(!1),[ai,Ei]=m.useState("pause"),[Qs,Es]=m.useState(""),[Er,er]=m.useState(""),[Ti,gr]=m.useState(""),ws=m.useRef(null),Mi=m.useRef(null),[Lo,_l]=m.useState(!1),tr=m.useRef(null),[Io,Jr]=m.useState(""),[_c,yr]=m.useState(""),[co,zs]=m.useState(""),[Oo,Po]=m.useState(""),[Do,uo]=m.useState(""),[U,ae]=m.useState(!1),[je,Ce]=m.useState("idle"),[ke,Ue]=m.useState([]),[ft,ot]=m.useState(null),gt=m.useRef(null),[Ft,Ht]=m.useState(!1),[vs,Rt]=m.useState(""),[sn,Cn]=m.useState(""),[mn,es]=m.useState(""),[nr,Xr]=m.useState([]),[Ri,xa]=m.useState(!1),[Af,pc]=m.useState(""),[pl,gc]=m.useState(""),[yc,wc]=m.useState(!1),[Ef,Fo]=m.useState(""),Wu=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]),qu=m.useMemo(()=>ke.length?mn?Wu!==mn:!0:!1,[Wu,ke.length,mn]),Hu=m.useMemo(()=>nr.map(g=>{const k=String(g.title||"").trim()||`Chat ${String(g.thread_id||"").slice(0,8)}`,A=String(g.created_at||"").trim(),I=A?A.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&&b1()},[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[Vu,Gu]=m.useState([]),[Ku,Yu]=m.useState({}),[Jm,Tf]=m.useState({}),[vc,en]=m.useState(""),[Ju,Xm]=m.useState(""),[Xu,Zm]=m.useState("all"),[Zu,Qm]=m.useState("status"),[ts,Bs]=m.useState("overview"),[gl,Mf]=m.useState(!0),[ba,xc]=m.useState("steps"),[Rf,Qu]=m.useState(""),[fo,ed]=m.useState(""),[Lf,bc]=m.useState([]),[td,nd]=m.useState(!1),[yl,ho]=m.useState(""),[If,ja]=m.useState(""),[e_,jc]=m.useState([]),[sd,Sc]=m.useState(!1),[Of,kc]=m.useState(""),[Pf,rd]=m.useState(!1),[t_,n_]=m.useState(""),[s_,Sa]=m.useState(""),[Tr,mo]=m.useState(""),[Df,wl]=m.useState(!1),[zo,ka]=m.useState(""),[_o,vl]=m.useState(null),[Nc,po]=m.useState({}),[Cc,Li]=m.useState(!1),[$c,Na]=m.useState(""),[Bo,Ca]=m.useState(!1),[Ac,Ff]=m.useState(!1),[Ec,xl]=m.useState(()=>Date.now()),[li,Uo]=m.useState(""),[zf,bl]=m.useState({}),[Bf,ci]=m.useState({}),Wo=m.useRef([]),sr=m.useRef(null),go=m.useRef(""),Tc=m.useRef({}),ui=m.useRef({}),id=m.useRef({}),$a=m.useRef(new Set),[di,pn]=m.useState([]),qo=m.useRef(""),Ii=m.useRef({}),Mr=m.useRef(null),Us=m.useRef(null),Oi=m.useRef(0),fi=m.useRef({}),Ho=m.useRef(!1),Rr=m.useRef(new Set),[Mc,Rc]=m.useState(""),[hi,Pi]=m.useState(""),wr=m.useRef(""),[jl,Sl]=m.useState(!1),[od,Aa]=m.useState(""),Lc=()=>({artifact_id:"",kind:"binary",render_kind:"",text:"",url:"",loading:!1,error:""}),[kl,ad]=m.useState("activity"),[ld,Uf]=m.useState([]),[Ic,Di]=m.useState(0),[Wf,Vo]=m.useState(0),[mi,Ea]=m.useState({}),[Fi,Oc]=m.useState({}),[r_,qf]=m.useState(!1),[Go,Ta]=m.useState(""),[_i,Pc]=m.useState(""),[Ko,yo]=m.useState("all"),[Zr,Sn]=m.useState(""),[on,wo]=m.useState([]),[ns,rr]=m.useState("all"),[Lr,Ma]=m.useState("type"),[xs,Dc]=m.useState("newest"),[zi,cd]=m.useState(""),[vo,Ra]=m.useState(""),[pi,La]=m.useState(""),[Yo,Fc]=m.useState(0),[Ia,gi]=m.useState(()=>Lc()),[Oa,xo]=m.useState(!1),[Nl,zc]=m.useState(""),[Ir,bs]=m.useState(""),[Un,Or]=m.useState(""),[Qr,Jo]=m.useState("text"),[Hf,Cl]=m.useState(null),[ud,Ts]=m.useState(!1),[ir,vn]=m.useState(""),[Pr,dd]=m.useState(""),[Vf,Bc]=m.useState(""),[Uc,fd]=m.useState(!1),[Wc,hd]=m.useState(""),[Bi,md]=m.useState("run_ledger"),[i_,$l]=m.useState(""),[qc,Hc]=m.useState([]),[Gf,bo]=m.useState(""),[Kf,Al]=m.useState(!1),[Vc,jo]=m.useState(""),Oe=m.useMemo(()=>new B_({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]),ss=m.useMemo(()=>new zN(Oe.automations_client(),PN(Oe,Ps,xt)),[Oe]),Gc=m.useSyncExternalStore(g=>ss.subscribe(g),()=>ss.state);m.useEffect(()=>{const g=()=>{const k=bN(window.location.hash);k&&(k.page==="launch"&&fe(k.mode),t(k.page))};return g(),window.addEventListener("hashchange",g),()=>window.removeEventListener("hashchange",g)},[]);const _d=m.useMemo(()=>{const g={};for(const k of Gc.items)g[k.automation_id]=k.title;return g},[Gc.items]),Pa=m.useMemo(()=>d1(),[]),[Dr,So]=m.useState([]),Kc=m.useRef(0);function Yf(){const g=++Kc.current;So([["Gateway","checking…"]]),f1(Oe).then(k=>{g===Kc.current&&So(k)})}const Fr=m.useMemo(()=>n.worker_url.trim()?new SC({url:n.worker_url.trim(),auth_token:n.worker_token}):null,[n.worker_url,n.worker_token]),zn=$t.length?$t[$t.length-1].record:null,Xt=m.useMemo(()=>Ji(zn),[zn]),js=m.useMemo(()=>{const g=b.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 A=x.trim();if(A)return k.find(q=>String(q.flow_id||"").trim()===A)||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,b,x]),ei=m.useMemo(()=>{const g=js==null?void 0:js.inputs;return Array.isArray(g)?g:[]},[js]),Ui=m.useMemo(()=>LR(_o),[_o]),ko=m.useMemo(()=>ei.length?ei:Ui,[ei,Ui]),pd=m.useMemo(()=>{const g=typeof(xe==null?void 0:xe.workflow_id)=="string"?String(xe.workflow_id):"",k=ev(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 A=js==null?void 0:js.node_index;return A&&typeof A=="object"?A:{}},[xe,M,js]);m.useEffect(()=>{FR(n)},[n]),m.useEffect(()=>()=>{Mr.current&&Mr.current.abort(),Us.current&&Us.current.abort(),ws.current&&window.clearTimeout(ws.current),Mi.current&&window.clearTimeout(Mi.current),sr.current&&window.clearTimeout(sr.current),tr.current&&window.clearTimeout(tr.current)},[]);const at=m.useMemo(()=>{const g=E.trim();if(!g)return{};try{const k=JSON.parse(g);return typeof k!="object"||k===null||Array.isArray(k)?null:k}catch{return null}},[E]),Jf=typeof(at==null?void 0:at.prompt)=="string"?String(at.prompt):"",Xo=typeof(at==null?void 0:at.provider)=="string"?String(at.provider):"",yi=typeof(at==null?void 0:at.model)=="string"?String(at.model):"",El=typeof(at==null?void 0:at.workspace_root)=="string"?String(at.workspace_root):"",Da=typeof(at==null?void 0:at.workspace_access_mode)=="string"?String(at.workspace_access_mode):"",Zo=m.useMemo(()=>{const g=at==null?void 0:at.workspace_allowed_paths;return Array.isArray(g)?g.map(k=>String(k||"").trim()).filter(Boolean).join(`
141
- `):typeof g=="string"?String(g):""},[at]),gd=m.useMemo(()=>{const g=at==null?void 0:at.workspace_ignored_paths;return Array.isArray(g)?g.map(k=>String(k||"").trim()).filter(Boolean).join(`
142
- `):typeof g=="string"?String(g):""},[at]),Fa=ko.length>0&&!!b.trim(),Yc=g=>{const k=String(g||"").trim().toLowerCase();return k==="object"||k==="memory"||k==="assertion"||k==="assertions"||k==="any"};m.useEffect(()=>{gs({})},[b,x]),m.useEffect(()=>{at!==null&&it(g=>{const k={};for(const A of ko){if(!A||typeof A!="object")continue;const I=String(A.id||"").trim();if(!I)continue;const q=String(A.type||"").trim();if(!Yc(q))continue;if(String(tn[I]||"").trim()){k[I]=typeof g[I]=="string"?g[I]:"";continue}const V=at==null?void 0:at[I];V===void 0?k[I]="":k[I]=j1(V)}return k})},[ko,at,tn]);const No=me?{kind:"default",interface:me}:b.trim()&&x.trim()?{kind:"bundle",bundle_id:b.trim(),flow_id:x.trim()}:null,In=pN(No),vr=Array.isArray(at==null?void 0:at.skills)?at.skills.map(g=>String(g||"").trim()).filter(Boolean):[],xr=m.useMemo(()=>{const g={};for(const k of un){const A=String(k.workflow_id||"").trim(),I=String(k.label||"").trim();A&&I&&(g[A]=I)}return g},[un]),Jc=m.useMemo(()=>un.filter(g=>g.has_interface),[un]),Xc=m.useMemo(()=>{const g=new Set;for(const k of Array.isArray(dt)?dt:[]){const A=String((k==null?void 0:k.name)||"").trim();A&&g.add(A)}return Array.from(g).sort()},[dt]),yd=m.useMemo(()=>{const g=[];for(const k of Array.isArray(dt)?dt:[]){const A=String((k==null?void 0:k.name)||"").trim();if(!A)continue;const I=String((k==null?void 0:k.display_name)||"").trim();g.push({name:A,display_name:I||void 0})}return g},[dt]),Qo=m.useMemo(()=>{const g=new Set;for(const k of jt||[]){if(!k||typeof k!="object")continue;const A=String(k.name||"").trim();A&&g.add(A)}return Array.from(g).sort()},[jt]),Mn=m.useMemo(()=>{const g=n.maintenance_ai_provider.trim();if(!g)return{models:[],error:""};const k=Bt[g];return k?{models:(Array.isArray(k.models)?k.models:[]).map(I=>String(I||"").trim()).filter(Boolean),error:String(k.error||"")}:{models:[],error:""}},[Bt,n.maintenance_ai_provider]),Wn=n.maintenance_ai_provider.trim(),hs=!!(Wn&&N&&!Object.prototype.hasOwnProperty.call(Bt,Wn));m.useEffect(()=>{const g=Xo.trim();if(!g||Bt[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):"";Nt(V=>({...V,[g]:{models:q,error:W||void 0}}))}catch(I){if(k)return;Nt(q=>({...q,[g]:{models:[],error:String((I==null?void 0:I.message)||I||"Failed to load models")}}))}finally{delete Ii.current[g]}})(),()=>{k=!0}},[Xo,Bt,Oe]),m.useEffect(()=>{const g=n.maintenance_ai_provider.trim();if(!g||!N||Bt[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):"";Nt(V=>({...V,[g]:{models:q,error:W||void 0}}))}catch(I){if(k)return;Nt(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,Bt,Oe,N]);function kn(g,k){const A=String(g||"").trim();if(!A)return;let I={};try{const q=JSON.parse(E||"{}");typeof q=="object"&&q!==null&&!Array.isArray(q)&&(I=q)}catch{I={}}if(k==null){delete I[A],L(JSON.stringify(I,null,2));return}if(typeof k=="string")k?I[A]=k:delete I[A];else if(Array.isArray(k)){const q=k.map(W=>W).filter(W=>W!=null);q.length?I[A]=q:delete I[A]}else I[A]=k;L(JSON.stringify(I,null,2))}async function za(g){const k=String(g||"").trim();if(!k)return re("Missing bundle_id"),null;re(""),Y(!0);try{const A=await Oe.get_bundle(k);return H(A),Jt({ts:xt(),kind:"info",title:`Loaded bundle ${k}`}),A}catch(A){return H(null),re(String((A==null?void 0:A.message)||A||"Failed to load bundle")),null}finally{Y(!1)}}function ea(g){const k=[],A=Array.isArray(g==null?void 0:g.items)?g.items:[];for(const I of A){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 Ee=`${q}:${te}`,_e=String((V==null?void 0:V.name)||"").trim(),pe=_e?`${q} · ${_e}`:`${q} · ${te}`,Ne=String((V==null?void 0:V.description)||"").trim(),qe=(Array.isArray(V==null?void 0:V.interfaces)?V.interfaces:[]).some(Ie=>String(Ie||"").trim().length>0),Ze=Array.isArray(V==null?void 0:V.agent_default_interfaces)?V.agent_default_interfaces.map(Ie=>String(Ie||"").trim()).filter(Boolean):[];k.push({workflow_id:Ee,bundle_id:q,bundle_ref:String((I==null?void 0:I.bundle_ref)||"").trim(),flow_id:te,label:pe,description:Ne||void 0,has_interface:qe,agent_default_interfaces:Ze})}}return k.sort((I,q)=>I.label.localeCompare(q.label)),k}async function or(g=Oe,k){if(Ge.current&&!(k!=null&&k.force))return;Ge.current=!0;const A=na.current;Ln(!0);try{const I=_e=>_e.map($N).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(A!==na.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:[],Ee=I(V).filter(_e=>!String(_e.parent_run_id||"").trim()||_e.role==="occurrence");bn(Ee),En(I(te).filter(_e=>!!_e.run_id)),Cs(Date.now()),st.current=0,Ve.current=0}catch(I){const q=String((I==null?void 0:I.message)||I||"");if(Jt({ts:xt(),kind:"error",title:"Refresh runs failed",preview:ht(q)}),(/\b40[13]\b/.test(q)||/unauthorized|forbidden/i.test(q))&&P.refresh().catch(()=>{}),/\b429\b/.test(q)||/too many requests/i.test(q)){const W=Math.min(12e4,Math.max(15e3,st.current*2||15e3));st.current=W,Ve.current=Date.now()+W,Jt({ts:xt(),kind:"info",title:`Gateway rate-limited — pausing polls ${Math.round(W/1e3)}s`})}}finally{Ge.current=!1,Ln(!1)}}async function Ss(g){var te,Ee,_e;const k=na.current;O(!0),Nt({});const[A,,I,q,W]=await Promise.allSettled([g.list_bundles(),or(g),g.discovery_tools(),g.discovery_providers({include_models:!1}),g.discovery_capabilities()]);if(k!==na.current)return;if(A.status==="rejected"&&I.status==="rejected"&&q.status==="rejected"){O(!1),C(fp(A.reason,n)),Jt({ts:xt(),kind:"error",title:"Discovery failed",preview:ht(String(A.reason||""))});return}De(W.status==="fulfilled"?AN(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(A.status==="fulfilled"){const pe=ea(A.value);V=pe.length,Bn(pe)}else Bn([]),Jt({ts:xt(),kind:"error",title:"Discovery bundles failed",preview:ht(String(A.reason||""))});if(I.status==="fulfilled"){const pe=Array.isArray((Ee=I.value)==null?void 0:Ee.items)?I.value.items:[];qt(pe)}else qt([]),Jt({ts:xt(),kind:"error",title:"Discovery tools failed",preview:ht(String(I.reason||""))});if(q.status==="fulfilled"){const pe=Array.isArray((_e=q.value)==null?void 0:_e.items)?q.value.items:[];Yt(pe)}else Yt([]),Jt({ts:xt(),kind:"error",title:"Discovery providers failed",preview:ht(String(q.reason||""))});Jt({ts:xt(),kind:"info",title:"Gateway discovery loaded",preview:ht(`workflows: ${V}`)})}async function ta(g){var k,A;C(""),O(!1),ue(!0);try{if(!(g!=null&&g.prefer_direct)&&(await P.refresh(),Tl.current))return;const I=String(n.auth_token||"").trim();if(!I){g!=null&&g.open_modal_if_needed&&P.openModal();return}const q=String(n.gateway_url||"").trim();if(q){const V=q.toLowerCase();if(!V.startsWith("http://")&&!V.startsWith("https://"))throw new Error("Gateway URL must start with http:// or https:// (or leave it blank to use same origin / dev proxy).");try{if(String(((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 Ee=new URL(q),_e=String(((A=window==null?void 0:window.location)==null?void 0:A.hostname)||"").trim().toLowerCase(),pe=String(Ee.hostname||"").trim().toLowerCase(),Ne=ze=>ze==="localhost"||ze==="127.0.0.1"||ze==="::1";if(Ne(pe)&&_e&&!Ne(_e))throw new Error("Gateway URL points to localhost, which from this device is not your machine. Use the gateway's public URL (e.g. an ngrok https URL) or leave Gateway URL blank to use same origin /api proxy.")}catch(te){throw new Error(String((te==null?void 0:te.message)||te||"Invalid Gateway URL"))}}const W=new B_({base_url:q,auth_token:I});await W.list_bundles(),i(V=>({...V,gateway_auth_mode:"direct"})),await Ss(W)}catch(I){C(fp(I,n))}finally{ue(!1)}}const Tl=m.useRef(!1),na=m.useRef(0),zr=m.useRef(!1);function Br(g){var A,I,q;B(g);const k=!!(g&&g.has_session&&((A=g.gateway)!=null&&A.ok));if(Tl.current=k,k){if(zr.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),Ss(new B_({base_url:"",auth_token:""})).catch(V=>C(fp(V,n))).finally(()=>ue(!1));return}g&&!g.has_session&&(n.gateway_auth_mode==="session"&&Rl({keep_session:!0}),String(n.auth_token||"").trim()&&!N&&!zr.current&&(zr.current=!0,ta({prefer_direct:!0})))}async function Ml(){if(!(ut||ie)){Et(!0);try{await Oe.reload_bundles();const g=await Oe.list_bundles(),k=ea(g);Bn(k),Jt({ts:xt(),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");Jt({ts:xt(),kind:"error",title:"Bundle reload failed",preview:ht(k),data:{error:k}})}finally{Et(!1)}}}async function wd(g){if($i||ie||!N)return;const k=g;if(k){$r(!0),en("");try{const A=await Oe.upload_bundle(k,{overwrite:!1,reload:!0});Jt({ts:xt(),kind:"info",title:"Bundle uploaded",preview:ht(String((A==null?void 0:A.bundle_ref)||""))});const I=await Oe.list_bundles(),q=ea(I);Bn(q)}catch(A){const I=String((A==null?void 0:A.message)||A||"Upload failed");en(I),Jt({ts:xt(),kind:"error",title:"Upload .flow failed",preview:ht(I),data:{error:I}})}finally{$r(!1);try{hr.current&&(hr.current.value="")}catch{}}}}function Rl(g){na.current+=1,g!=null&&g.keep_session||(P.signOut().catch(()=>{}),Tl.current=!1),lh(),$(""),S(""),ka(""),H(null),re(""),Y(!1),Bn([]),bn([]),En([]),Cs(null),ls([]),qt([]),Yt([]),Nt({}),C(""),O(!1),B(null),i(k=>({...k,auth_token:""})),Jt({ts:xt(),kind:"info",title:"Gateway disconnected"})}async function Zc(g){const k=String(g??"");if(k){try{await navigator.clipboard.writeText(k),On("Copied to clipboard",2);return}catch{}try{const A=document.createElement("textarea");A.value=k,A.style.position="fixed",A.style.left="-9999px",A.style.top="0",A.style.opacity="0",document.body.appendChild(A),A.focus(),A.select(),document.execCommand("copy"),document.body.removeChild(A),On("Copied to clipboard",2)}catch{On("Copy failed",2)}}}m.useEffect(()=>{const g=c.trim();if(!pt||!g)return;let k=!1;const A=async()=>{if(!(Ve.current>Date.now()))try{const q=await Oe.get_run(g);k||Jn(q)}catch{}};A();const I=window.setInterval(A,2e3);return()=>{k=!0,window.clearInterval(I)}},[pt,c,Oe]),m.useEffect(()=>{if(!N)return;let g=null,k=!1,A=!1;const I=V=>{k||(g!==null&&window.clearTimeout(g),g=window.setTimeout(()=>void q(),V))},q=async()=>{if(A)return;const V=Ve.current-Date.now();if(V>0){I(V+500);return}A=!0;const te=Date.now();try{await or(Oe)}finally{A=!1;const Ee=Date.now()-te,_e=document.visibilityState==="hidden"?3e4:5e3;I(Math.max(_e,Ee*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[Xf,Qc]=m.useState(null);m.useEffect(()=>{if(!N){Qc(null);return}let g=!1;return(async()=>{try{const k=await Oe.get_entity_phases_spec();if(g)return;const A=wR(k);if(Qc(A),A)try{const I=localStorage.getItem("abstractobserver_phase_graph_id_v1"),q=I?JSON.parse(I):null;q&&q.sha256&&A.sha256&&q.sha256!==A.sha256&&q.version===A.version&&Jt({ts:xt(),kind:"error",title:"Phase-graph drift: served bytes changed without a version bump",preview:ht(`v${A.version}: ${String(q.sha256).slice(0,12)}… -> ${String(A.sha256).slice(0,12)}…`),data:{prev:q,now:{sha256:A.sha256,version:A.version}}}),localStorage.setItem("abstractobserver_phase_graph_id_v1",JSON.stringify({sha256:A.sha256,version:A.version}))}catch{}}catch(k){if(!g){Qc(null);const A=String((k==null?void 0:k.message)||k||"");/404|not found/i.test(A)||Jt({ts:xt(),kind:"info",title:"Phase-graph fetch failed — pre-wire fallback vocabulary in use (#FALLBACK)",preview:ht(A),data:{error:A}})}}})(),()=>{g=!0}},[N]),m.useEffect(()=>{if(!N){ls([]),be("");return}let g=!1,k=null;const A=async()=>{if(!(Ve.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,Ee;try{const[_e,pe]=await Promise.all([Oe.get_entity_card(V),Oe.get_entity_cognition(V).catch(()=>null)]),Ne=_e!=null&&_e.state&&typeof _e.state=="object"?_e.state:null,ze=Array.isArray(_e==null?void 0:_e.moments)?_e.moments:[],qe=ze.length?ze[ze.length-1]:null,Ze=(te=pe==null?void 0:pe.spend)==null?void 0:te.lifetime,Ie=(Ee=pe==null?void 0:pe.spend)==null?void 0:Ee.live_visit,ln=Array.isArray(pe==null?void 0:pe.warnings)?pe.warnings.map(He=>String(He||"")).filter(Boolean):[],Tt=aR(_e);return{name:V,state:String((Ne==null?void 0:Ne.state)??(typeof(_e==null?void 0:_e.state)=="string"?_e.state:"")).trim(),age_days:typeof(_e==null?void 0:_e.age_days)=="number"?_e.age_days:null,last_moment:String((qe==null?void 0:qe.kind)||"").trim(),last_moment_at:String((qe==null?void 0:qe.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(Ie==null?void 0:Ie.tokens_total)=="number"?Ie.tokens_total:null,spend_warning:ln.join(" | "),live_phase:typeof(pe==null?void 0:pe.phase)=="string"?pe.phase:"",open_questions:Tt.questions,open_questions_total:Tt.questions_total,open_problems:Tt.problems,open_problems_total:Tt.problems_total,lessons:Tt.lessons,lessons_total:Tt.lessons_total,dreams_brief:oR(_e),error:""}}catch(_e){return{name:V,state:"",age_days:null,last_moment:"",last_moment_at:"",working:null,tokens_total:null,live_visit_tokens:null,spend_warning:"",live_phase:"",open_questions:[],open_questions_total:0,open_problems:[],open_problems_total:0,lessons:[],lessons_total:0,dreams_brief:null,error:String((_e==null?void 0:_e.message)||_e||"card failed")}}}));g||(ls(W),Yn(I.entities.length),be(""))}catch(I){if(!g){ls([]);const q=String((I==null?void 0:I.message)||I||"");be(/404|not found/i.test(q)?"":q)}}g||(k=window.setTimeout(()=>void A(),3e4))}};return A(),()=>{g=!0,k!==null&&window.clearTimeout(k)}},[N,Oe]);async function Zf(g,k,A){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:Ps(),run_id:g,type:"resume",payload:{wait_key:I,payload:A||{}},client_id:"web_pwa"}),Jt({ts:xt(),kind:"info",title:"Board resume submitted",preview:ht(`run ${g} · wait ${I}`),data:{run_id:g,wait_key:I}}),or(Oe,{force:!0}),window.setTimeout(()=>void or(Oe,{force:!0}),1200)}const Ur=m.useMemo(()=>{const g=xe==null?void 0:xe.session_id;return typeof g=="string"?g.trim():g==null?"":String(g||"").trim()},[xe]),sa=m.useMemo(()=>{const g=String(Ur||"").trim();return g||String(D||"").trim()},[Ur,D]);m.useEffect(()=>{if(!N||!sa){uo(""),Po("");return}(async()=>{try{const g=await nv(sa);uo(g)}catch{uo("")}})()},[N,sa]);const qn=MR({gateway:N?Oe:null,session_id:sa,run_id:Do,on_error:Po,on_transcript:g=>{const k=String(g||"").trim();k&&(yr(A=>{const I=String(A||"");return I.trim()?`${I.trimEnd()}
143
- ${k}`:k}),window.setTimeout(()=>{var A;return(A=gt.current)==null?void 0:A.focus()},0))}});function vd(g,k){try{const A=URL.createObjectURL(g),I=document.createElement("a");I.href=A,I.download=k||"download",I.rel="noreferrer",document.body.appendChild(I),I.click(),document.body.removeChild(I),window.setTimeout(()=>URL.revokeObjectURL(A),5e3)}catch{}}async function Ba(){if(!td){if(!N||!Ur){ed(""),bc([]),ho("");return}nd(!0),ho("");try{const g=await nv(Ur);ed(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"});bc(I)}catch(g){const k=String((g==null?void 0:g.message)||g||"Failed to load session attachments"),A=k.toLowerCase();k.includes("404")||A.includes("session_memory_")&&A.includes("not found")||A.includes('"detail"')&&A.includes("not found")&&A.includes("session_memory_")?(bc([]),ho("")):(bc([]),ho(k)),ed("")}finally{nd(!1)}}}async function Qf(){const g=If.trim();if(!g){On("This run recorded no workspace folder",2);return}try{const k=await fetch(fN,{method:"POST",headers:{"Content-Type":"application/json",...kx()},body:JSON.stringify({path:g})}),A=await k.json().catch(()=>({}));k.ok&&(A!=null&&A.ok)?On(`Opened ${String(A.path||g)}`,2):On(String((A==null?void 0:A.error)||`Folder reveal failed (${k.status})`),3)}catch(k){On(String((k==null?void 0:k.message)||k||"Folder reveal failed"),3)}}async function eu(g){const k=String(fo||"").trim();if(!k){On("No session attachment store yet",2);return}const A=String((g==null?void 0:g.artifact_id)||"").trim();if(!A)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():"")||A,te=P_(V);try{const Ee=await Oe.download_run_artifact_content(k,A,{access:"download"});vd(Ee,te),On("Downloaded attachment",2)}catch(Ee){On(String((Ee==null?void 0:Ee.message)||Ee||"Download failed"),3)}}async function tu(g){const k=String(fo||"").trim(),A=String((g==null?void 0:g.artifact_id)||"").trim();if(!k||!A)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||A,te=typeof(g==null?void 0:g.size_bytes)=="number"?Number(g.size_bytes):null,Ee=String((g==null?void 0:g.content_type)||I.content_type||"").trim().toLowerCase();if(n_(V),Sa(""),mo(""),rd(!0),typeof te=="number"&&te>1e6){Sa(`(Attachment is ${te.toLocaleString()} bytes; download to view.)`);return}if(!(!Ee||Ee.startsWith("text/")||Ee.includes("json")||Ee.includes("yaml")||Ee.includes("toml")||Ee.includes("xml"))){Sa(`(Binary attachment: ${Ee||"unknown"}; download to view.)`);return}wl(!0);try{const Ne=await(await Oe.download_run_artifact_content(k,A,{access:"download"})).text(),ze=14e3,qe=Ne.length>ze?`${Ne.slice(0,Math.max(0,ze-1))}…`:Ne;Sa(qe)}catch(pe){mo(String((pe==null?void 0:pe.message)||pe||"Preview failed"))}finally{wl(!1)}}async function xd(g){const k=String((g==null?void 0:g.run_id)||"").trim(),A=String((g==null?void 0:g.artifact_id)||"").trim();if(!k||!A){On("Artifact download needs a run id",3);return}const I=Ep(g)||A;try{const q=await Oe.download_run_artifact_content(k,A,{access:"preview"});vd(q,P_(I)),On("Downloaded artifact",2)}catch(q){On(String((q==null?void 0:q.message)||q||"Download failed"),3)}}async function nu(g){const k=String((g==null?void 0:g.run_id)||"").trim(),A=String((g==null?void 0:g.artifact_id)||"").trim();if(!k||!A){On("Artifact preview needs a run id",3);return}const I=Ep(g),q=String((g==null?void 0:g.content_type)||"").trim().toLowerCase(),W=lf(g);if(zc(I||A),bs(""),vn(""),Jo(W),Cl(g),xo(!0),Un&&(URL.revokeObjectURL(Un),Or("")),W==="binary"){bs(`(Binary artifact: ${q||"unknown"}; download to view.)`);return}if(W==="text"&&typeof g.size_bytes=="number"&&g.size_bytes>15e5){bs(`(Text artifact is ${g.size_bytes.toLocaleString()} bytes; download to view.)`);return}Ts(!0);try{const V=await Oe.download_run_artifact_content(k,A,{access:"preview"});if(W==="text"){const te=await V.text(),Ee=bm(g,te),_e=Ee==="json"?15e5:Ee==="markdown"?25e4:Ee==="html"?3e5:22e3;bs(te.length>_e&&Ee!=="text"?`${sc(g.size_bytes??te.length)} ${Ee.toUpperCase()} artifact. Download to inspect it.`:te.length>_e?`${te.slice(0,Math.max(0,_e-1))}…`:te)}else Or(URL.createObjectURL(V))}catch(V){vn(String((V==null?void 0:V.message)||V||"Preview failed"))}finally{Ts(!1)}}m.useEffect(()=>()=>{Un&&URL.revokeObjectURL(Un)},[Un]);async function eh(g){const k=String(g.artifact_id||"").trim(),A=String(g.run_id||"").trim(),I=lf(g);if(!A||!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:`${sc(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(A,k,{access:"preview"});if(I==="text"){const W=await q.text(),V=bm(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"?`${sc(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 th(g){if(Ia.url&&URL.revokeObjectURL(Ia.url),!g){gi(Lc());return}const k=String(g.artifact_id||"").trim(),A=lf(g);gi({artifact_id:k,kind:A,render_kind:"",text:"",url:"",loading:!0,error:""}),gi(await eh(g))}m.useEffect(()=>{Ba()},[Oe,N,Ur]);function Jt(g){const k=String(g.id||"").trim()||Ps();Gu(A=>[{...g,id:k},...A].slice(0,800))}function On(g,k){gr(g),Mi.current&&window.clearTimeout(Mi.current),_l(!1),window.requestAnimationFrame(()=>_l(!0)),Mi.current=window.setTimeout(()=>{_l(!1),Mi.current=null},1500),ws.current&&(window.clearTimeout(ws.current),ws.current=null),k>0&&(ws.current=window.setTimeout(()=>{gr(""),ws.current=null},Math.max(1,k)*1e3))}function Ws(g,k){const A=String(g||"").trim(),I=String(k||"").trim();if(!I)return"";const q=A?String(Tc.current[A]||"").trim():"";return q?`${q}::${I}`:I}function su(g,k,A){const I=String(g||"").trim(),q=String(k||"").trim(),W=String(A||"").trim();if(!I||!q||!W)return;const V=Ws(I,q);V&&(Tc.current[W]=V,ui.current[W]=I,id.current[W]={parent_run_id:I,parent_node_id:q},$a.current.has(W)||($a.current.add(W),pn(te=>te.includes(W)?te:[...te,W])))}function Ll(g){const k=String(g||"").trim();if(!k)return;const A=Date.now(),I=go.current;go.current=k,xl(A),bl(q=>{const W={};for(const[_e,pe]of Object.entries(q))typeof pe=="number"&&pe>A&&(W[_e]=pe);W[k]=Math.max(W[k]||0,A+2e3),I&&I!==k&&(W[I]=Math.max(W[I]||0,A+2e3));const V=Object.keys(W);if(V.length<=200)return W;const te=V.sort((_e,pe)=>(W[pe]||0)-(W[_e]||0)).slice(0,200),Ee={};for(const _e of te)Ee[_e]=W[_e]||0;return Ee}),ci(q=>{if(typeof q[k]=="number")return q;const W={...q,[k]:A};if(Wo.current.push(k),Wo.current.length>8e3){const V=Wo.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();bl(W=>{const V={};for(const[te,Ee]of Object.entries(W))typeof Ee=="number"&&Ee>q&&(V[te]=Ee);return V}),xl(q),sr.current=null},2200)}function bd(g,k){var Ie,ln,Tt;const A=String(k||"").trim()||c.trim();$s.current=g.cursor,(Ie=fr.current)==null||Ie.push({cursor:g.cursor,record:g.record}),A&&Rr.current.add(`${A}:${g.cursor}`);const I=Vh(g.record),q=I&&I.name?nf(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:"",Ee=typeof((ln=W==null?void 0:W.effect)==null?void 0:ln.type)=="string"?W.effect.type:"",_e=typeof(W==null?void 0:W.run_id)=="string"?W.run_id:"",pe=_e||A;if(q==="abstract.status"&&pe===A){const{text:He,duration:vt}=wu(I==null?void 0:I.payload);On(He,vt)}const Ne=V?Ws(pe,V):"";if(te==="waiting"){const He=Ji(W);if(String((He==null?void 0:He.reason)||"").trim()==="subworkflow"){const xn=typeof((Tt=He==null?void 0:He.details)==null?void 0:Tt.sub_run_id)=="string"?String(He.details.sub_run_id):"";xn&&V&&su(pe,V,xn)}}if(V&&(Ll(Ws(pe,V)),te==="waiting"||te==="running")){const He=Ws(pe,V);He&&(go.current=He,Uo(He))}let ze="step",qe=Ne||V||"(node?)",Ze="";if(I&&I.name&&dp(I.name))ze=q==="abstract.message"?"message":"event",qe=q||I.name,Ze=ht(q==="abstract.steer_seen"?up(I==null?void 0:I.payload):wu(I==null?void 0:I.payload).text);else if(W!=null&&W.error)ze="error",qe="error",Ze=ht(Ds(W.error,360));else if(te==="waiting"){const He=Ji(W),vt=String((He==null?void 0:He.reason)||"").trim();Ze=ht(vt?`waiting • ${vt}`:"waiting")}else W!=null&&W.result?Ze=ht(Ds(W.result,360)):Ee?Ze=ht(Ee):Ze=ht(cm(W));Jt({id:`step:${_e||A||"?"}:${g.cursor}`,ts:String((W==null?void 0:W.ended_at)||(W==null?void 0:W.started_at)||xt()),kind:ze,title:qe,preview:Ze,data:W,cursor:g.cursor,run_id:_e||A||void 0,node_id:Ne||V,status:te,effect_type:Ee,emit_name:q||(I==null?void 0:I.name)||void 0})}function o_(g,k){var Ze,Ie,ln;Oi.current=Math.max(Oi.current,k.cursor);const A=`${g}:${k.cursor}`;if(!!Rr.current.has(A))return;Rr.current.add(A),(Ze=Xs.current)==null||Ze.push({run_id:g,cursor:k.cursor,record:k.record});const q=Vh(k.record),W=q&&q.name?nf(q.name):"",V=k.record,te=typeof(V==null?void 0:V.node_id)=="string"?V.node_id:"",Ee=te?Ws(g,te):"",_e=typeof(V==null?void 0:V.status)=="string"?V.status:"",pe=typeof((Ie=V==null?void 0:V.effect)==null?void 0:Ie.type)=="string"?V.effect.type:"";if(_e==="waiting"){const Tt=Ji(V);if(String((Tt==null?void 0:Tt.reason)||"").trim()==="subworkflow"){const vt=typeof((ln=Tt==null?void 0:Tt.details)==null?void 0:ln.sub_run_id)=="string"?String(Tt.details.sub_run_id):"";vt&&te&&su(g,te,vt),vt&&wr.current.trim()===String(g||"").trim()&&(wr.current=vt,Pi(vt))}}if(te&&(Ll(Ws(g,te)),_e==="waiting"||_e==="running")){const Tt=Ws(g,te);Tt&&(go.current=Tt,Uo(Tt))}if((_e==="completed"||_e==="failed")&&wr.current.trim()===String(g||"").trim()){const Tt=String(ui.current[String(g||"").trim()]||"").trim();Tt&&Tt!==c.trim()?(wr.current=Tt,Pi(Tt)):(wr.current="",Pi(""))}if(W==="abstract.status"&&g===c.trim()){const{text:Tt,duration:He}=wu(q==null?void 0:q.payload);On(Tt,He)}let Ne="step",ze=Ee||te||"(node?)",qe="";if(q&&q.name&&dp(q.name))Ne=W==="abstract.message"?"message":"event",ze=`subrun • ${W||q.name}`,qe=ht(W==="abstract.steer_seen"?up(q==null?void 0:q.payload):wu(q==null?void 0:q.payload).text);else if(V!=null&&V.error)Ne="error",ze="error",qe=ht(Ds(V.error,360));else if(_e==="waiting"){const Tt=Ji(V),He=String((Tt==null?void 0:Tt.reason)||"").trim();qe=ht(He?`waiting • ${He}`:"waiting")}else V!=null&&V.result?qe=ht(Ds(V.result,360)):pe?qe=ht(pe):qe=ht(cm(V));Jt({id:`step:${g}:${k.cursor}`,ts:String((V==null?void 0:V.ended_at)||(V==null?void 0:V.started_at)||xt()),kind:Ne,title:ze,preview:qe,data:V,cursor:k.cursor,run_id:g,node_id:Ee||te,status:_e,effect_type:pe,emit_name:W||(q==null?void 0:q.name)||""})}function nh(g,k){var Ie,ln,Tt;const A=String(g||"").trim();if(!A)return;const I=`${A}:${k.cursor}`;if(!!Rr.current.has(I))return;Rr.current.add(I),(Ie=Xs.current)==null||Ie.push({run_id:A,cursor:k.cursor,record:k.record});const W=Vh(k.record),V=W&&W.name?nf(W.name):"",te=k.record,Ee=typeof(te==null?void 0:te.node_id)=="string"?te.node_id:"",_e=Ee?Ws(A,Ee):"",pe=typeof(te==null?void 0:te.status)=="string"?te.status:"",Ne=typeof((ln=te==null?void 0:te.effect)==null?void 0:ln.type)=="string"?te.effect.type:"";if(pe==="waiting"){const He=Ji(te);if(String((He==null?void 0:He.reason)||"").trim()==="subworkflow"){const xn=typeof((Tt=He==null?void 0:He.details)==null?void 0:Tt.sub_run_id)=="string"?String(He.details.sub_run_id):"";xn&&Ee&&su(A,Ee,xn)}}if(Ee&&(Ll(Ws(A,Ee)),pe==="waiting"||pe==="running")){const He=Ws(A,Ee);He&&(go.current=He,Uo(He))}if(V==="abstract.status"&&A===c.trim()){const{text:He,duration:vt}=wu(W==null?void 0:W.payload);On(He,vt)}let ze="step",qe=_e||Ee||"(node?)",Ze="";if(W&&W.name&&dp(W.name))ze=V==="abstract.message"?"message":"event",qe=`subrun • ${V||W.name}`,Ze=ht(V==="abstract.steer_seen"?up(W==null?void 0:W.payload):wu(W==null?void 0:W.payload).text);else if(te!=null&&te.error)ze="error",qe="error",Ze=ht(Ds(te.error,360));else if(pe==="waiting"){const He=Ji(te),vt=String((He==null?void 0:He.reason)||"").trim();Ze=ht(vt?`waiting • ${vt}`:"waiting")}else te!=null&&te.result?Ze=ht(Ds(te.result,360)):Ne?Ze=ht(Ne):Ze=ht(cm(te));Jt({id:`step:${A}:${k.cursor}`,ts:String((te==null?void 0:te.ended_at)||(te==null?void 0:te.started_at)||xt()),kind:ze,title:qe,preview:Ze,data:te,cursor:k.cursor,run_id:A,node_id:_e||Ee,status:pe,effect_type:Ne,emit_name:V||(W==null?void 0:W.name)||""})}async function sh(g,k){var I,q;let A=k.after;for(;;){if((I=k.signal)!=null&&I.aborted)return A;const W=await Oe.get_ledger(g,{after:A,limit:200,signal:k.signal});if((q=k.signal)!=null&&q.aborted)return A;const V=Array.isArray(W.items)?W.items:[];if(!V.length)return $s.current=A,A;const te=A;for(let Ee=0;Ee<V.length;Ee++){const _e=V[Ee];bd({cursor:te+Ee+1,record:_e},g)}A=typeof W.next_after=="number"?W.next_after:A}}async function Il(g){var W,V,te,Ee;const k=String(g||"").trim();en(""),Wt(!0),Ot(!1),(W=fr.current)==null||W.reset(),(V=Xs.current)==null||V.reset(),so.current={scanned:0,found:null},cs([]),$s.current=0,Js([]),Rr.current=new Set,Gu([]),Yu({}),Tf({}),xc("steps"),Qu(""),gr(""),Jn(null),Jr(""),ja(""),jc([]),kc(""),Uo(""),go.current="",bl({}),ci({}),Wo.current=[],xl(Date.now()),Tc.current=k?{[k]:""}:{},ui.current={},id.current={},$a.current=new Set,pn([]),qo.current="",wr.current="",Pi(""),fi.current={},sr.current&&window.clearTimeout(sr.current),sr.current=null,tr.current&&window.clearTimeout(tr.current),tr.current=null,Mr.current&&Mr.current.abort(),Us.current&&Us.current.abort(),Us.current=null,Oi.current=0,Rc("");const A=new AbortController;Mr.current=A;let I=!1;try{let _e="",pe="";try{const Ne=await Oe.get_run(k);Jn(Ne);const ze=typeof(Ne==null?void 0:Ne.workflow_id)=="string"?String(Ne.workflow_id):"",qe=ev(ze);qe&&(_e=qe.bundle_id,pe=qe.flow_id)}catch{}try{const Ne=await Oe.get_run_input_data(k);typeof(Ne==null?void 0:Ne.bundle_id)=="string"&&(_e=String(Ne.bundle_id||"").trim()||_e),typeof(Ne==null?void 0:Ne.flow_id)=="string"&&(pe=String(Ne.flow_id||"").trim()||pe);const ze=Ne&&typeof Ne.input_data=="object"&&Ne.input_data&&!Array.isArray(Ne.input_data)?Ne.input_data:null;ze&&L(JSON.stringify(ze,null,2));const qe=Ne==null?void 0:Ne.workspace,Ze=typeof(qe==null?void 0:qe.workspace_root)=="string"?String(qe.workspace_root).trim():"";ja(Ze)}catch{ja("")}(async()=>{Sc(!0),kc("");try{const Ne=await Oe.list_run_artifacts(k,{limit:200}),ze=Array.isArray(Ne==null?void 0:Ne.items)?Ne.items:[];A.signal.aborted||jc(ze)}catch(Ne){A.signal.aborted||(jc([]),kc(String((Ne==null?void 0:Ne.message)||Ne||"artifact listing failed")))}finally{A.signal.aborted||Sc(!1)}})(),_e&&pe&&($(_e),S(pe),ka(pe),await za(_e)),await sh(k,{after:0,signal:A.signal});try{const Ne=await Oe.get_run_history_bundle(k,{include_subruns:!0,include_session:!1,ledger_mode:"tail",ledger_max_items:1}),ze=Ne&&typeof Ne=="object"?Ne.ledgers:null,Ze=(ze&&typeof ze=="object"?Object.keys(ze):[]).map(Ie=>String(Ie||"").trim()).filter(Boolean).filter(Ie=>Ie!==k);if(Ze.length){for(const Ie of Ze)$a.current.add(Ie);pn(Ie=>Array.from(new Set([...Ie,...Ze])));try{const Ie=typeof((te=ze==null?void 0:ze[k])==null?void 0:te.total)=="number"?Number(ze[k].total):0;let ln="",Tt=-1;for(const He of Ze){const vt=typeof((Ee=ze==null?void 0:ze[He])==null?void 0:Ee.total)=="number"?Number(ze[He].total):0;vt>Tt&&(ln=He,Tt=vt)}ln&&Tt>Math.max(Ie*3,Ie+20)&&(wr.current=ln,Pi(ln))}catch{}}}catch{}Ot(!0),Jt({ts:xt(),kind:"info",title:`Attached to run ${k}`,data:{run_id:k}}),I=!0}catch(_e){const pe=String((_e==null?void 0:_e.message)||_e||"unknown error");en(pe),Jt({ts:xt(),kind:"error",title:"Connection error",preview:ht(pe),data:{error:pe}}),Ot(!1)}finally{Wt(!1)}if(!I||A.signal.aborted)return;(async()=>{let _e=250;for(;!A.signal.aborted;){try{const pe=await sh(k,{after:$s.current,signal:A.signal});await Oe.stream_ledger(k,{after:pe,on_step:Ne=>bd(Ne,k),signal:A.signal})}catch(pe){if(A.signal.aborted)break;const Ne=String((pe==null?void 0:pe.message)||pe||"stream error");Jt({ts:xt(),kind:"error",title:"Ledger stream error (will retry)",preview:ht(Ne),data:{error:Ne}})}if(A.signal.aborted)break;await new Promise(pe=>setTimeout(pe,_e)),_e=Math.min(5e3,Math.floor(_e*1.6))}})()}async function rh(){const g=No,k=(g==null?void 0:g.kind)==="bundle"?g.flow_id:(g==null?void 0:g.kind)==="default"?"@default":"",A=(g==null?void 0:g.kind)==="bundle"?g.bundle_id:"";if(!g){const I="Select a workflow first (Launch → pick a workflow).";return en(I),I}en(""),Wt(!0);try{let I={};const q=E.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 Ne=`Invalid input_data JSON: ${String((pe==null?void 0:pe.message)||pe)}`;return en(Ne),Ne}for(const[pe,Ne]of Object.entries(I)){if(typeof Ne!="string")continue;const ze=Ne.trim();ze?I[pe]=ze:delete I[pe]}const W=(ko||[]).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,Ee=typeof te=="string"?te.trim():"";if(W&&!V&&!Ee){const pe="Missing required input_data.prompt";return en(pe),pe}const _e=await Oe.start_run(k,I,{...A?{bundle_id:A}:{},...g.kind==="default"?{interface:g.interface}:{},session_id:String(D||"").trim()||null});return p(_e),f(_e),ro(""),await Il(_e),or(),null}catch(I){const q=String((I==null?void 0:I.message)||I||"start failed");return en(q),q}finally{Wt(!1)}}async function ih(){if(_t([]),et(null),!ge.available){_t([ge.reason]);return}const g=CN(Ae,{choice:No,bundle_ref_for:k=>{var A;return((A=un.find(I=>I.bundle_id===k))==null?void 0:A.bundle_ref)||""},input_data:at},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($p),Jt({ts:xt(),kind:"info",title:"Automation created",preview:ht(`${g.body.title} · ${k.automation_id}`)}),t("automations"),await ss.refresh(),await ss.select(k.automation_id)}catch(k){const A=(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(A)}finally{Ye(!1)}}async function oh(){if(ro(""),oe==="automate"){await ih();return}const g=await rh();if(g){ro(g);return}Bs("overview"),t("observe")}async function Ol(g){if(kn("skills",void 0),!!g){if(g.kind==="default"){we(g.interface),$(""),S(""),H(null);return}we(""),$(g.bundle_id),S(g.flow_id),ka(g.flow_id),await za(g.bundle_id)}}async function ah(g){const[k,A]=await Promise.all([Oe.get_run(g),Oe.get_run_input_data(g)]),I=IN(k,A);await Ol(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 ra(g,k){const A=String(g||"").trim();if(!A)return;if($e){On(`Still attaching — retry in a moment (${Lt(A,14)})`,2500);return}en("");const I=String((k==null?void 0:k.root_run_id)||A).trim()||A;p(I),f(A),await Il(A)}m.useEffect(()=>{const g=String(w||"").trim();if(!g)return;let k=!1;return(async()=>{try{if(N||await ta({open_modal_if_needed:!0}),k)return;Bs("overview"),t("observe"),await ra(g)}catch(A){k||en(String((A==null?void 0:A.message)||A||"Failed to attach run from URL"))}finally{k||y("")}})(),()=>{k=!0}},[w]);function lh(){var g,k;Mr.current&&Mr.current.abort(),Mr.current=null,Us.current&&Us.current.abort(),Us.current=null,Oi.current=0,Rc(""),f(""),p(""),Tc.current={},ui.current={},id.current={},$a.current=new Set,pn([]),qo.current="",wr.current="",Pi(""),fi.current={},Jr(""),sr.current&&window.clearTimeout(sr.current),sr.current=null,tr.current&&window.clearTimeout(tr.current),tr.current=null,Ot(!1),Wt(!1),rn(!1),$s.current=0,(g=fr.current)==null||g.reset(),(k=Xs.current)==null||k.reset(),so.current={scanned:0,found:null},cs([]),Js([]),Rr.current=new Set,Jn(null),Gu([]),Yu({}),Uo(""),go.current="",bl({}),ci({}),Wo.current=[],xl(Date.now()),On("",-1),en(""),Sl(!1),Aa(""),Ue([]),ot(null),yr(""),zs(""),ae(!1),Ht(!1),Rt(""),Cn(""),es(""),Xr([]),xa(!1),pc(""),gc(""),wc(!1),Fo("")}m.useEffect(()=>{Ue([]),ot(null),yr(""),zs(""),ae(!1),Ht(!1),Rt(""),Cn(""),es(""),Xr([]),xa(!1),pc(""),gc(""),wc(!1),Fo("")},[c]),m.useEffect(()=>{ts==="chat"&&c.trim()&&N&&iu()},[ts,c,N,xe==null?void 0:xe.workflow_id]);async function Wr(g,k,A){const I=String(g||"").trim();if(!I)return en("Missing run_id"),"Missing run_id";en("");try{const q={},W=String((A==null?void 0:A.reason)||"").trim();W&&(q.reason=W),await Oe.submit_command({command_id:Ps(),run_id:I,type:k,payload:q,client_id:"web_pwa"}),Jt({ts:xt(),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);Jn(V)}}catch{}return or(Oe,{force:!0}),window.setTimeout(()=>void or(Oe,{force:!0}),900),window.setTimeout(()=>void or(Oe,{force:!0}),2400),null}catch(q){const W=String((q==null?void 0:q.message)||q||`${k} failed`);return en(W),W}}async function ru(g,k){return Wr(c.trim(),g,k)}async function Pl(g,k="Stopped from AbstractObserver"){const A=String(g||"").trim();if(!A||!window.confirm(`Cancel run ${Lt(A,24)}?`))return;await Wr(A,"cancel",{reason:k})||On("Cancel submitted",2)}async function ch(){var A;const g=c.trim();if(!g){en("Select a run first.");return}if(!N){en("Connect to the gateway first.");return}if(Ct)return;const k=String(((A=xe==null?void 0:xe.waiting)==null?void 0:A.reason)||"").trim().toLowerCase()||String(an||"").trim().toLowerCase();if(!Ms||ni||qi||Wi.toLowerCase()!=="waiting"||k!=="until"){en("This run is not a scheduled wait that can be triggered now.");return}en(""),rn(!0);try{const I={payload:{mode:"run_now",requested_at:xt()}},q=String(gn||"").trim();q&&(I.wait_key=q),await Oe.submit_command({command_id:Ps(),run_id:g,type:"resume",payload:I,client_id:"web_pwa"}),Jt({ts:xt(),kind:"info",title:"Scheduled run triggered",preview:ht(`run ${g}`),data:{run_id:g,until:ti||null}});try{const W=await Oe.get_run(g);Jn(W)}catch{}}catch(I){en(String((I==null?void 0:I.message)||I||"Failed to trigger scheduled run"))}finally{rn(!1)}}async function uh(g){const k=c.trim();if(!k)return en("Missing run_id"),"Missing run_id";if(_r)return"Schedule update already in progress";const A=String(g.interval||"").trim();if(!/^\s*(\d+(?:\.\d+)?)\s*(ms|s|m|h|d)\s*$/i.test(A)){const q="Invalid interval (expected like '20m', '1h', '0.5s', '250ms')";return Tn(q),q}Tn(""),en(""),ao(!0),Wt(!0);try{await Oe.submit_command({command_id:Ps(),run_id:k,type:"update_schedule",payload:{interval:A,apply_immediately:g.apply_immediately!==!1},client_id:"web_pwa"}),Jt({ts:xt(),kind:"info",title:"Schedule updated",preview:ht(`interval: ${A}`),data:{interval:A},run_id:k});try{const q=await Oe.get_run(k);Jn(q)}catch{}return null}catch(q){const W=String((q==null?void 0:q.message)||q||"update_schedule failed");return Tn(W),en(W),W}finally{Wt(!1),ao(!1)}}async function dh(g){const k=c.trim();if(!k)return en("Missing run_id"),"Missing run_id";if(pr)return"Compaction already in progress";const A=typeof(g==null?void 0:g.preserve_recent)=="number"?g.preserve_recent:fs,I=Math.max(0,Math.min(500,Math.floor(Number.isFinite(A)?A:6))),q=(g==null?void 0:g.compression_mode)||ys,W=String((g==null?void 0:g.focus)??lo??"").trim();Ai(""),en(""),As(!0),Wt(!0);try{const V={preserve_recent:I,compression_mode:q};return W&&(V.focus=W),await Oe.submit_command({command_id:Ps(),run_id:k,type:"compact_memory",payload:V,client_id:"web_pwa"}),Jt({ts:xt(),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 Ai(te),en(te),te}finally{Wt(!1),As(!1)}}async function jd(){const g=c.trim();if(!g){Aa("Missing run_id");return}if(!jl){Aa(""),Sl(!0);try{const k=n.maintenance_ai_provider.trim(),A=n.maintenance_ai_model.trim();await Oe.generate_run_summary(g,{provider:k||void 0,model:A||void 0,include_subruns:!0}),Jt({ts:xt(),kind:"info",title:"Summary generation requested",preview:ht(`run ${g}`)})}catch(k){Aa(String((k==null?void 0:k.message)||k||"Failed to generate summary"))}finally{Sl(!1)}}}async function Ua(){const g=c.trim();if(!g){zs("Select a run first.");return}if(!N){zs("Connect to the gateway first.");return}const k=_c.trim();if(!k||U)return;if(qn.voice_ptt_busy){Po("Wait for transcription to finish.");return}zs(""),Po(""),ae(!0);const I={id:`local:${Ps()}`,role:"user",content:k,ts:xt()};Ue(q=>[...q,I]),yr("");try{const q=tN(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}),Ee=String((te==null?void 0:te.answer)||"").trim()||"(empty response)",_e=String((te==null?void 0:te.generated_at)||"").trim()||xt();ot((te==null?void 0:te.history)??null),Ue(pe=>[...pe,{id:`local:${Ps()}`,role:"assistant",content:Ee,ts:_e}])}catch(q){const W=N1(q);zs(W),Ue(V=>[...V,{id:`local:${Ps()}`,role:"assistant",content:`(error: ${W})`,ts:xt(),local_error:!0}])}finally{ae(!1)}}function Sd(g){const k=String(g.id||g.ts||"").trim(),A=String(g.content||"").trim();!k||!A||(Po(""),qn.toggle_tts(k,A))}function kd(g){const k=String(g.id||g.ts||"").trim(),A=qn.tts_playback;return!k||!A.key||A.key!==k?"idle":A.status}function fh(g){if(!ke.length)return;const k=c.trim(),A=k?`Run ${k}`:"Chat",I=J0(ke.map(q=>({role:q.role,content:q.content,ts:q.ts})),{heading:A});if(g==="download"){const q=new Date().toISOString().slice(0,19).replace(/[:T]/g,"-"),W=`abstractobserver-chat-${P_(k||"run")}-${q}.md`;X0({filename:W,text:I,mime:"text/markdown;charset=utf-8"});return}(async()=>{const q=await dc(I);Ce(q?"copied":"failed"),window.setTimeout(()=>Ce("idle"),900)})()}async function iu(){const g=typeof(xe==null?void 0:xe.workflow_id)=="string"?String(xe.workflow_id).trim():"";if(!g){Xr([]);return}if(N&&!Ri){pc(""),xa(!0);try{const k=await Oe.list_runs({limit:200,workflow_id:g,root_only:!0}),A=Array.isArray(k==null?void 0:k.items)?k.items:[],I=[];for(const _e of A){const pe=typeof(_e==null?void 0:_e.run_id)=="string"?String(_e.run_id).trim():"";if(!pe)continue;const Ne=typeof(_e==null?void 0:_e.ledger_len)=="number"?Number(_e.ledger_len):0;I.push({run_id:pe,ledger_len:Number.isFinite(Ne)?Ne:0})}if(!I.length){Xr([]);return}const q=400,W=I.map(_e=>({run_id:_e.run_id,after:Math.max(0,(_e.ledger_len||0)-q)})),V=await Oe.get_ledger_batch({runs:W,limit:q}),te=[],Ee=new Set;for(const _e of I){const pe=V!=null&&V.runs&&typeof V.runs=="object"?V.runs[_e.run_id]:null,Ne=Array.isArray(pe==null?void 0:pe.items)?pe.items:[];for(const ze of Ne){const qe=ze==null?void 0:ze.effect;if(!qe||typeof qe!="object"||String(qe.type||"")!=="emit_event")continue;const Ze=qe.payload;if(!Ze||typeof Ze!="object"||String(Ze.name||"")!=="abstract.chat.thread")continue;const Ie=Ze.payload;if(!Ie||typeof Ie!="object")continue;const ln=typeof Ie.thread_id=="string"?String(Ie.thread_id).trim():"";if(!ln||Ee.has(ln))continue;Ee.add(ln);const Tt=typeof Ie.created_at=="string"?String(Ie.created_at):"",He=typeof Ie.title=="string"?String(Ie.title):"",vt=typeof Ie.workflow_id=="string"?String(Ie.workflow_id):g,xn=typeof Ie.run_id=="string"?String(Ie.run_id):_e.run_id,$n=typeof Ie.provider=="string"?String(Ie.provider):"",lr=typeof Ie.model=="string"?String(Ie.model):"",Pn=typeof Ie.message_count=="number"?Number(Ie.message_count):null,Sr=Ie.chat_artifact,Jl=Sr&&typeof Sr=="object"&&typeof Sr.$artifact=="string"?String(Sr.$artifact):"";Jl&&te.push({thread_id:ln,created_at:Tt,title:He||`Chat ${ln.slice(0,8)}`,run_id:xn,workflow_id:vt,message_count:Pn,provider:$n,model:lr,artifact_id:Jl})}}te.sort((_e,pe)=>String(pe.created_at||"").localeCompare(String(_e.created_at||""))),Xr(te)}catch(k){pc(String((k==null?void 0:k.message)||k||"Failed to load saved discussions"))}finally{xa(!1)}}}async function hh(){const g=c.trim();if(!g){Rt("Select a run first.");return}if(!N){Rt("Connect to the gateway first.");return}if(ke.length&&!Ft){Rt(""),Ht(!0);try{const k=n.maintenance_ai_provider.trim(),A=n.maintenance_ai_model.trim(),I=await Oe.save_chat_thread(g,{provider:k||void 0,model:A||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):xt();Cn(q);try{const V=JSON.stringify(ke.map(te=>({role:te.role,content:te.content,ts:te.ts})));es(V)}catch{es("1")}typeof(I==null?void 0:I.thread_id)=="string"&&String(I.thread_id).trim()&&gc(String(I.thread_id).trim());const W=!!(I!=null&&I.duplicate);On(W?"Already saved":"Saved discussion",2),await iu()}catch(k){Rt(String((k==null?void 0:k.message)||k||"Failed to save discussion"))}finally{Ht(!1)}}}async function mh(){const g=String(pl||"").trim();if(!g)return;const k=nr.find(q=>String(q.thread_id||"").trim()===g)||null;if(!k){Fo("Saved discussion not found (refresh list).");return}if(!N){Fo("Connect to the gateway first.");return}if(yc)return;const A=ke.length>0,I=(()=>{if(!A)return!1;if(!mn)return!0;try{return JSON.stringify(ke.map(W=>({role:W.role,content:W.content,ts:W.ts})))!==mn}catch{return!0}})();if(!(A&&I&&!window.confirm("Replace the current chat with the selected saved discussion? Unsaved changes will be lost."))){Fo(""),wc(!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:[],Ee=typeof(V==null?void 0:V.created_at)=="string"?String(V.created_at):String(k.created_at||""),_e=[];for(let pe=0;pe<te.length;pe++){const Ne=te[pe];if(!Ne||typeof Ne!="object")continue;const ze=String(Ne.role||"").trim()==="assistant"?"assistant":"user",qe=typeof Ne.content=="string"?String(Ne.content):"";if(!qe.trim())continue;const Ze=typeof Ne.ts=="string"?String(Ne.ts):Ee||xt();_e.push({id:`thread:${g}:${pe}`,role:ze,content:qe.trim(),ts:Ze})}Ue(_e),ot(null),yr(""),zs(""),Rt(""),Cn(Ee||"");try{const pe=JSON.stringify(_e.map(Ne=>({role:Ne.role,content:Ne.content,ts:Ne.ts})));es(pe)}catch{es("1")}On("Loaded discussion",2)}catch(q){Fo(String((q==null?void 0:q.message)||q||"Failed to load saved discussion"))}finally{wc(!1)}}}async function Dl(g){const k=c.trim(),A=String((Xt==null?void 0:Xt.wait_key)||"").trim();if(!k||!A){en("No active wait to resume");return}if(String((Xt==null?void 0:Xt.reason)||"").trim()==="subworkflow"){en("This run is waiting on a subworkflow; attach to the child run instead of resuming manually.");return}en(""),rn(!0);try{await Oe.submit_command({command_id:Ps(),run_id:k,type:"resume",payload:{wait_key:A,payload:g||{}},client_id:"web_pwa"}),Jt({ts:xt(),kind:"info",title:"Resume submitted",preview:ht(`wait_key: ${A}`),data:{wait_key:A,payload:g||{}}}),Jr(A);try{const I=await Oe.get_run(k);Jn(I)}catch{}or(Oe,{force:!0}),window.setTimeout(()=>void or(Oe,{force:!0}),900),window.setTimeout(()=>void or(Oe,{force:!0}),2400),tr.current&&window.clearTimeout(tr.current),tr.current=window.setTimeout(()=>{Jr(I=>I===A?"":I)},2e3)}catch(I){en(String((I==null?void 0:I.message)||I||"resume failed"))}finally{rn(!1)}}async function _h(g){if(!Fr){en("No worker configured");return}if(!Ct){en(""),rn(!0);try{const k=[];for(const A of g){const I=await Fr.call_tool(A);k.push(I)}await Dl({mode:"executed",results:k})}finally{rn(!1)}}}const ia=m.useMemo(()=>Bu(Xt),[Xt]),gn=String((Xt==null?void 0:Xt.wait_key)||"").trim(),an=String((Xt==null?void 0:Xt.reason)||"").trim(),ti=typeof(Xt==null?void 0:Xt.until)=="string"?String(Xt.until):"",Wi=typeof(xe==null?void 0:xe.status)=="string"?String(xe.status):"",qi=!!(xe!=null&&xe.paused),ni=Wi==="completed"||Wi==="failed"||Wi==="cancelled",ph=an==="until"&&!!ti,Wa=!ni&&Q1(zn)&&(!!gn||ph),gh=an==="user",Fl=an==="event"?nf(RR(gn)):"",yh=an==="event"&&Fl==="abstract.ask",wh=ia.length>0,ou=Wa&&gn&&(gh||yh||wh)&&Io!==gn&&e!=="board",Hi=typeof((Gi=Xt==null?void 0:Xt.details)==null?void 0:Gi.sub_run_id)=="string"?String(Xt.details.sub_run_id):"",qa={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},au=$t.slice(-10).map(g=>{var k,A,I,q,W,V;return{cursor:g.cursor,node_id:String(((k=g.record)==null?void 0:k.node_id)||"").trim(),status:String(((A=g.record)==null?void 0:A.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:wx(g.record)}}),zl=_g(Xt,ia),a_=_x(Xt,ia),Nd=px(Xt,at),Co=Nd.text,vh=Nd.runtime_metadata,oa=String((Xt==null?void 0:Xt.prompt)||"").trim(),wi=D1(at,6),l_=!!(oa&&fx(oa)),lu=!!(oa&&!l_),Cd=lu?"Question from workflow":Co&&Co!==oa?"Closest prior user request":"Request context",xh=B1(at,E),bh=!!E.trim(),ks=xe!=null&&xe.schedule&&typeof xe.schedule=="object"?xe.schedule:null,Hn=typeof(ks==null?void 0:ks.interval)=="string"?String(ks.interval).trim():"",c_=typeof(ks==null?void 0:ks.share_context)=="boolean"?!!ks.share_context:null,jh=typeof(ks==null?void 0:ks.repeat_count)=="number"?Number(ks.repeat_count):null,Ms=!!(xe!=null&&xe.is_scheduled)||!!ks,ms=Ms&&!!Hn,Sh=Ms?qi?"Resume schedule":"Suspend schedule":Wi==="running"&&!qi?"Pause":"Resume",Xe=Ms?qi?"resume":"pause":Sh==="Pause"?"pause":"resume",Ha=Ms?!c.trim()||$e||Ct||ni:!c.trim()||$e||Ct||ni||Xe==="resume"&&!qi,$d=Ms&&!qi&&!ni&&!$e&&!Ct&&Wi.toLowerCase()==="waiting"&&(String(((qr=xe==null?void 0:xe.waiting)==null?void 0:qr.reason)||"").trim().toLowerCase()==="until"||an==="until")&&!!String(ti||"").trim(),ar=(Vs=xe==null?void 0:xe.limits)==null?void 0:Vs.tokens,Bl=typeof(ar==null?void 0:ar.pct)=="number"?Number(ar.pct):null,Va=ar==null?void 0:ar.estimated_used,Ul=(ar==null?void 0:ar.max_input_tokens)??(ar==null?void 0:ar.max_tokens),Ad=m.useMemo(()=>{const g=so.current;$t.length<g.scanned&&(g.scanned=0,g.found=null);for(let k=g.scanned;k<$t.length;k++){const A=$t[k],I=A==null?void 0:A.record;if(!I)continue;const q=Vh(I);if((q&&q.name?nf(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:A.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(()=>{wr.current=hi.trim()},[hi]),m.useEffect(()=>{const g=c.trim(),k=Hi.trim();if(!(pt&&an==="subworkflow"&&!!k&&k!==g)){qo.current="",hi.trim()&&Pi("");return}qo.current!==k&&(qo.current=k,wr.current=k,Pi(k))},[pt,c,an,Hi,hi]),m.useEffect(()=>{po({})},[b]);const Ed=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]),vi=m.useMemo(()=>{const g=String((xe==null?void 0:xe.workflow_id)||"").trim();return pt&&Ms?g:""},[pt,Ms,xe==null?void 0:xe.workflow_id]),kh=m.useMemo(()=>{var V;if(!pt||!c.trim()||!vi.trim())return li;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 li;const A=Ws(c.trim(),k);if(!A)return li;const I=String(an||((V=xe==null?void 0:xe.waiting)==null?void 0:V.reason)||"").trim().toLowerCase(),q=typeof(zn==null?void 0:zn.node_id)=="string"?String(zn.node_id).trim():"",W=typeof(zn==null?void 0:zn.status)=="string"?String(zn.status).trim().toLowerCase():"";return g==="waiting"&&I==="until"||!li.trim()||(W==="waiting"||W==="running")&&!q?A:li},[pt,c,vi,xe==null?void 0:xe.status,xe==null?void 0:xe.current_node,(Pd=xe==null?void 0:xe.waiting)==null?void 0:Pd.reason,an,li,zn]),Td=m.useMemo(()=>{const g={},k=c.trim(),A=(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=Ws(I,W);if(!V)return;const te=String((q==null?void 0:q.ended_at)||(q==null?void 0:q.started_at)||"").trim(),Ee=Nn(te);Ee!==null&&(g[V]=Math.max(g[V]||0,Ee))};for(const I of $t)I&&I.record&&A(k,I.record);for(const I of us)I&&I.record&&A(String(I.run_id||"").trim(),I.record);return g},[$t,us,c,di]);m.useEffect(()=>{var A;if(!pt||!c.trim()||!vi.trim())return;const g=String((xe==null?void 0:xe.current_node)||"").trim();!g||String(((A=xe==null?void 0:xe.waiting)==null?void 0:A.reason)||"").trim()==="subworkflow"||Ll(Ws(c.trim(),g))},[pt,c,vi,xe==null?void 0:xe.current_node,(hu=xe==null?void 0:xe.waiting)==null?void 0:hu.reason]),m.useEffect(()=>{const g=String((js==null?void 0:js.flow_id)||"").trim();g&&(zo.trim()||ka(g))},[js,zo]),m.useEffect(()=>{const g=vi.trim(),k=b.trim(),A=zo.trim();if(g){let q=!1;return Li(!0),Na(""),Oe.get_workflow_flow(g).then(W=>{if(q)return;const V=W==null?void 0:W.flow;vl(V&&typeof V=="object"?V:null)}).catch(W=>{q||(vl(null),Na(String((W==null?void 0:W.message)||W||"Failed to load workflow flow")))}).finally(()=>{q||Li(!1)}),()=>{q=!0}}if(!k||!A){vl(null),Na(""),Li(!1);return}let I=!1;return Li(!0),Na(""),Oe.get_bundle_flow(k,A).then(q=>{if(I)return;const W=q==null?void 0:q.flow,V=W&&typeof W=="object"?W:null;vl(V),V&&po(te=>({...te,[A]:V}))}).catch(q=>{I||(vl(null),Na(String((q==null?void 0:q.message)||q||"Failed to load flow")))}).finally(()=>{I||Li(!1)}),()=>{I=!0}},[vi,b,zo,Oe]),m.useEffect(()=>{const g=b.trim();if(!Bo||!g||!_o)return;let k=!1;const A=3,I=_e=>{const pe=Array.isArray(_e==null?void 0:_e.nodes)?_e.nodes:[],Ne=[];for(const ze of pe){const qe=ze!=null&&ze.data&&typeof ze.data=="object"?ze.data:{};if(String((qe==null?void 0:qe.nodeType)||(ze==null?void 0:ze.type)||"").trim()!=="subflow")continue;const Ie=(qe==null?void 0:qe.subflowId)||(qe==null?void 0:qe.flowId),ln=typeof Ie=="string"?Ie.trim():"";ln&&Ne.push(ln.includes(":")?ln.split(":",2)[1]:ln)}return Ne},q=new Set,W=new Set,V=(_e,pe)=>{if(!(!_e||pe>=A))for(const Ne of I(_e)){const ze=String(Ne||"").trim();if(!ze||q.has(ze))continue;q.add(ze),W.add(ze);const qe=Nc[ze];qe&&V(qe,pe+1)}};V(_o,0);const te=Array.from(W).filter(_e=>!Nc[_e]).slice(0,20);return te.length?((async()=>{for(const _e of te){if(k)return;try{const pe=await Oe.get_bundle_flow(g,_e),Ne=pe==null?void 0:pe.flow,ze=Ne&&typeof Ne=="object"?Ne:null;if(!ze)continue;po(qe=>qe[_e]?qe:{...qe,[_e]:ze})}catch{}}})(),()=>{k=!0}):void 0},[Bo,b,_o,Nc,Oe]);const cu=m.useMemo(()=>{const k=(Array.isArray(M==null?void 0:M.flows)?M==null?void 0:M.flows:[]).map(A=>String(A||"").trim()).filter(Boolean);return k.length?Array.from(new Set(k)).sort():Array.from(new Set(Ed)).sort()},[M,Ed]);m.useEffect(()=>{ni&&li.trim()&&(Uo(""),go.current="")},[ni,c,li]),m.useEffect(()=>{const g=hi.trim(),k=c.trim();if(!(pt&&!!g&&g!==k)){Us.current&&Us.current.abort(),Us.current=null,Oi.current=0,Mc&&Rc("");return}if(Mc===g)return;Us.current&&Us.current.abort();const I=new AbortController;Us.current=I,Oi.current=0,Rc(g),Jt({ts:xt(),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=>o_(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");Jt({ts:xt(),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,hi,c,Oe,Mc]),m.useEffect(()=>{if(!pt||!c.trim())return;let g=!1;const k=async()=>{if(!g&&!Ho.current&&di.length&&!(Ve.current>Date.now())){Ho.current=!0;try{const I=di.map(te=>String(te||"").trim()).filter(Boolean);if(!I.length)return;const q=I.map(te=>({run_id:te,after:Number(fi.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 Ee=V&&typeof V=="object"?V[te]:null,_e=Array.isArray(Ee==null?void 0:Ee.items)?Ee.items:[],pe=typeof(Ee==null?void 0:Ee.next_after)=="number"?Ee.next_after:Number(fi.current[te]||0),Ne=Number(fi.current[te]||0);for(let ze=0;ze<_e.length;ze++){const qe=_e[ze];nh(te,{cursor:Ne+ze+1,record:qe})}fi.current[te]=pe}}catch(I){if(g)return;Jt({ts:xt(),kind:"error",title:"Subrun digest poll failed",preview:ht(String((I==null?void 0:I.message)||I||""))})}finally{Ho.current=!1}}};k();const A=window.setInterval(()=>void k(),2e3);return()=>{g=!0,window.clearInterval(A),Ho.current=!1}},[pt,c,di,Oe]);const rs=m.useMemo(()=>gl?Vu.filter(PR):Vu,[gl,Vu]),Xn=m.useMemo(()=>{const g=c.trim(),k=[];for(const A of $t)!A||!A.record||k.push({run_id:g,cursor:A.cursor,record:A.record});for(const A of us)!A||!A.record||k.push({run_id:String(A.run_id||"").trim(),cursor:A.cursor,record:A.record});return k},[$t,us,c]),si=m.useMemo(()=>{var k,A,I;const g={};for(const q of Xn){const W=String(q.run_id||((k=q.record)==null?void 0:k.run_id)||"").trim();!W||String(((I=(A=q.record)==null?void 0:A.effect)==null?void 0:I.type)||"").trim()!=="llm_call"||(g[W]=(g[W]||0)+1)}return g},[Xn]),Nh=m.useMemo(()=>{const g=hi.trim();if(g)return g;let k="",A=-1;for(const[I,q]of Object.entries(si))q>A&&(k=I,A=q);return k||c.trim()},[si,hi,c]),Vi=(Rf.trim()||Nh).trim(),br=m.useMemo(()=>{var q;const g=new Set,k=c.trim(),A=hi.trim();k&&g.add(k),A&&g.add(A);for(const W of di){const V=String(W||"").trim();V&&g.add(V)}for(const W of Xn){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:A&&W===A&&V!==A?-1:A&&V===A&&W!==A?1:W<V?-1:W>V?1:0),I},[c,hi,di,Xn]),uu=m.useMemo(()=>H0(Xn,{run_id:Vi}),[Xn,Vi]),yn=m.useMemo(()=>{const g=c.trim();return g&&(Dn.find(k=>String(k.run_id||"").trim()===g)||Mt.find(k=>String(k.run_id||"").trim()===g))||null},[Dn,Mt,c]),Ga=String((xe==null?void 0:xe.status)||(yn==null?void 0:yn.status)||"").trim(),Ch=String(an||((mu=xe==null?void 0:xe.waiting)==null?void 0:mu.reason)||(yn==null?void 0:yn.waiting_reason)||"").trim().toLowerCase(),Md=!!(xe!=null&&xe.is_scheduled||yn!=null&&yn.is_scheduled),Rd=!!(xe!=null&&xe.paused||yn!=null&&yn.paused),Ld=Md&&Ga.toLowerCase()==="waiting",$h=Ld&&Ch==="until",Wl=Nn(ti),ql=$h&&Wl!==null?Ey(Wl-Date.now()):"",Rs=I1(xe),Vt=Md&&Rd?"Suspended":Ld?"Scheduled":jm({status:Ga,paused:Rd,stop_reason:Rs});async function is(){if(N){qf(!0),Ta("");try{const g=Ko,k=g==="session"?String(Zr||Ur||D||"").trim():"",A=g==="run"?String(zi||c||"").trim():"",I=K1(ns),q=on.length?on.join(","):"",W=Y1(xs),V=Math.max(0,Yo)*om,te=await Oe.search_artifacts({scope:g,session_id:k||void 0,run_id:A||void 0,query:_i||void 0,artifact_kind:q||void 0,created_after:I||void 0,include_stats:!0,limit:om,offset:V,order_by:W.order_by,order:W.order}),Ee=[],_e=new Set;for(const Ze of Array.isArray(te==null?void 0:te.items)?te.items:[]){const Ie=H1(Ze,"search");!Ie||_e.has(Ie.artifact_id)||(_e.add(Ie.artifact_id),Ee.push(Ie))}const pe=te!=null&&te.stats&&typeof te.stats=="object"?te.stats:{},Ne=Number((pe==null?void 0:pe.total)??(te==null?void 0:te.total)??Ee.length),ze=Ry(te);let qe=ze;if(on.length)try{const Ze=await Oe.search_artifacts({scope:g,session_id:k||void 0,run_id:A||void 0,query:_i||void 0,created_after:I||void 0,include_stats:!0,limit:1,offset:0,order_by:W.order_by,order:W.order});qe=Ry(Ze)}catch{qe=ze}Di(Number.isFinite(Ne)?Math.max(0,Ne):Ee.length),Vo(Number((pe==null?void 0:pe.total_bytes)??(pe==null?void 0:pe.byte_total)??0)||0),Ea(ze),Oc(qe),Uf(Ee),La(Ze=>{var Ie;return Ze&&Ee.some(ln=>ln.artifact_id===Ze)?Ze:((Ie=Ee[0])==null?void 0:Ie.artifact_id)||""})}catch(g){Ta(String((g==null?void 0:g.message)||g||"Failed to load artifacts")),Uf([]),Di(0),Vo(0),Ea({}),Oc({}),La("")}finally{qf(!1)}}}async function Vn(){if(N){fd(!0),hd("");try{const g=await Oe.audit_log_tail({max_bytes:16e4}),k=typeof(g==null?void 0:g.bytes)=="number"?Number(g.bytes):0,A=!!(g!=null&&g.truncated);dd(String((g==null?void 0:g.content)||"")),Bc(`${k.toLocaleString()} bytes${A?" (tail)":""}`)}catch(g){hd(String((g==null?void 0:g.message)||g||"Failed to load audit log")),dd(""),Bc("")}finally{fd(!1)}}}async function _s(g){if(!N)return;const k=String(g||vo||zi||c||"").trim();if(!k){Hc([]),bo(""),jo("Select a run in Activity or Artifacts to load its runtime ledger.");return}Al(!0),jo("");try{const A=await Oe.get_ledger(k,{after:0,limit:2e3}),I=Array.isArray(A.items)?A.items:[];Hc(I.map((W,V)=>({cursor:V+1,record:W})));const q=typeof A.next_after=="number"?Number(A.next_after):I.length;bo(`${I.length.toLocaleString()} record${I.length===1?"":"s"}${q>=2e3?" (first 2,000)":""}`)}catch(A){jo(String((A==null?void 0:A.message)||A||"Failed to load run ledger")),Hc([]),bo("")}finally{Al(!1)}}m.useEffect(()=>{N&&e==="runtime"&&is()},[N,e,Ko,Zr,zi,_i,on,ns,xs,Yo]),m.useEffect(()=>{N&&(Uc||Pr||e==="runtime"&&Vn())},[N,e,ts]),m.useEffect(()=>{if(!N||e!=="runtime"||kl!=="logs"||Bi!=="run_ledger"&&Bi!=="provider_calls")return;const g=String(vo||zi||c||"").trim();g&&_s(g)},[N,e,kl,Bi,vo,zi,c]);const Zn=m.useMemo(()=>{const g=new Map;for(const k of[...Mt,...Dn]){const A=String(k.run_id||"").trim();A&&g.set(A,k)}for(const k of di){const A=String(k||"").trim();!A||g.has(A)||g.set(A,{run_id:A,workflow_id:null,status:"",created_at:null,updated_at:null,ledger_len:null,parent_run_id:ui.current[A]||null,session_id:Ur||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):Ur||null}),Array.from(g.values()).sort((k,A)=>{const I=Nn(k.updated_at||k.created_at)??0;return(Nn(A.updated_at||A.created_at)??0)-I})},[Dn,Mt,c,xe,$t.length,di,Ur]),Ka=m.useMemo(()=>NC(Zn,{query:Ju,filter:Xu,group_by:Zu,workflow_label_by_id:xr,parent_hint:g=>ui.current[g]||""}),[Zn,Ju,Xu,Zu,xr]),os=m.useMemo(()=>vx(Xn),[Xn]),Hl=m.useMemo(()=>{const g=[...Xn];return g.sort((k,A)=>{var W,V,te,Ee;const I=Nn(((W=k.record)==null?void 0:W.ended_at)||((V=k.record)==null?void 0:V.started_at))??0,q=Nn(((te=A.record)==null?void 0:te.ended_at)||((Ee=A.record)==null?void 0:Ee.started_at))??0;return I-q}),g.slice(-240)},[Xn]),jr=m.useMemo(()=>{const g={};for(const k of Zn){const A=String(k.run_id||"").trim();A&&(g[A]=k)}return g},[Zn]),Ya=String(vo||zi||c||"").trim(),Vl=Ya&&jr[Ya]||null,Ja=String(Zr||(Vl==null?void 0:Vl.session_id)||Ur||D||"").trim(),qs=m.useMemo(()=>ld.map(g=>km(g,jr,xr)),[ld,jr,xr]);m.useEffect(()=>{Fc(0)},[_i,on,ns,zi,xs,Lr,Ko,Zr]);const Id=Math.max(1,Math.ceil(Ic/om)),xi=Math.min(Math.max(0,Yo),Id-1);m.useEffect(()=>{Yo!==xi&&Fc(xi)},[Yo,xi]);const Hs=m.useMemo(()=>qs,[qs,xi]),du=m.useMemo(()=>{const g={};for(const k of Hs){const A=Lr==="type"?Mp(k,jr,xr):V1(k,Lr);g[A]||(g[A]=[]),g[A].push(k)}return Object.entries(g).map(([k,A])=>({key:k,items:A})).sort((k,A)=>{var I,q;if(Lr==="time"){const W=Nn((I=k.items[0])==null?void 0:I.created_at)??0,V=Nn((q=A.items[0])==null?void 0:q.created_at)??0;if(W!==V)return V-W}return k.key.localeCompare(A.key)})},[Hs,Lr,jr,xr]),aa=m.useMemo(()=>{const g=pi.trim();return g?Hs.find(k=>k.artifact_id===g)||Hs[0]||null:Hs[0]||null},[Hs,pi]);m.useEffect(()=>{e!=="runtime"||kl!=="artifacts"||th(aa)},[e,kl,aa==null?void 0:aa.artifact_id]),m.useEffect(()=>()=>{Ia.url&&URL.revokeObjectURL(Ia.url)},[Ia.url]);const $o=m.useMemo(()=>Zn.filter(g=>Ou(g.status)),[Zn]);m.useEffect(()=>{if(e!=="settings"&&e!=="launch"||!N||T)return;let g=!1;return(async()=>{const[k,A]=await Promise.all([Oe.list_skills(),Oe.list_mcp_servers()]);g||(G(k),J(A),Q(!0))})(),()=>{g=!0}},[e,N,T]);const fu=[{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})}],Ao={board:"Board",observe:"Observe",runtime:"System",launch:"Launch",automations:"Automations",settings:"Settings"},Gl=s.jsxs(s.Fragment,{children:[No?s.jsxs("details",{className:"launch_capabilities",style:{marginTop:"10px"},children:[s.jsxs("summary",{className:"help_text muted",style:{cursor:"pointer"},children:["Capabilities",vr.length?` · ${vr.length} skill${vr.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=vr.includes(g.name),A=g.blocked===!0,I=g.requires_review===!0&&!A;return s.jsxs("label",{className:`launch_skill_row ${A?"is_blocked":""} ${k?"is_on":""}`,title:[g.description||"",g.tree_hash?`tree ${g.tree_hash.slice(0,16)}…`:"",A&&((q=g.reasons)!=null&&q.length)?`blocked: ${g.reasons.join("; ")}`:""].filter(Boolean).join(`
144
- `),children:[s.jsx("input",{type:"checkbox",checked:k,disabled:A||$e||Ct||lt,onChange:W=>{const V=W.target.checked?Array.from(new Set([...vr,g.name])):vr.filter(te=>te!==g.name);kn("skills",V.length?V:void 0)}}),s.jsx("span",{className:"launch_skill_name",children:g.name}),g.trust_level?s.jsx("span",{className:`chip ${A?"danger":I?"warn":"muted"}`,children:A?"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."}),vr.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:El,onChange:g=>kn("workspace_root",g.target.value),placeholder:"/path/to/workspace",disabled:$e||Ct}),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:(Da||"workspace_only").trim()||"workspace_only",onChange:g=>kn("workspace_access_mode",g.target.value),disabled:$e||Ct,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."})]})]}),(Da||"").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:Zo,onChange:g=>kn("workspace_allowed_paths",g.target.value),placeholder:`/path/to/project
145
- /path/to/workspace`,disabled:$e||Ct,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:gd,onChange:g=>kn("workspace_ignored_paths",g.target.value),placeholder:`node_modules
146
- runtime
147
- secret`,disabled:$e||Ct,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:hr,type:"file",accept:".flow",style:{display:"none"},onChange:g=>{const k=g.target.files&&g.target.files.length?g.target.files[0]:null;k&&wd(k)}}),s.jsx("button",{type:"button",className:"btn launch_btn_upload",onClick:()=>{var g;return(g=hr.current)==null?void 0:g.click()},disabled:!N||ie||$i||$e||Ct,title:"Upload a .flow bundle",children:$i?"…":"Upload .flow"}),s.jsxs("button",{type:"button",className:"btn launch_btn_reload",onClick:()=>void Ml(),disabled:!N||ie||ut||$e||Ct,title:"Reload picks up server-side edits",children:[s.jsx(Qe,{name:"refresh",size:14}),ut?"…":"Reload bundles"]})]})]})]});function Xa(g){t("observe"),Bs("overview"),ra(g)}const Od={on_select:g=>void ss.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"){ss.ask_archive(g.automation_id);return}ss.row_action(g,k)},on_legacy_action:(g,k)=>{if(k==="open_run"){Xa(g.automation_id);return}if(k==="recreate"){ah(g.automation_id).catch(A=>ss.report_error(A));return}ss.legacy_action(g,k)},on_confirm_archive:g=>void ss.row_action(g,"archive"),on_cancel_archive:()=>ss.ask_archive(""),on_status_filter:g=>void ss.set_status_filter(g),on_refresh:()=>void ss.refresh(),on_new:()=>{fe("automate"),t("launch")},on_show_archived:g=>ss.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:[fu.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&&((Ki=(Ah=ne==null?void 0:ne.gateway)==null?void 0:Ah.principal)!=null&&Ki.user_id)?"mono":""}`,children:N?((_u=(Dd=ne==null?void 0:ne.gateway)==null?void 0:Dd.principal)==null?void 0:_u.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:Ao[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(Vj,{assistant:{open:Ut,onToggle:()=>It(g=>!g),label:"Observer assistant (docs-grounded)"},appearance:{onOpen:()=>_n(!0)},about:{identity:Pa,extraRows:Dr,onOpen:Yf},connection:{phase:P.phase,signingOut:P.signingOut,onConnect:()=>P.openModal(),onDisconnect:()=>Rl()}})]})]}),s.jsx(Nj,{...P.modalProps}),s.jsx(Jj,{open:Qt,onClose:()=>_n(!1),value:Ke,onChange:Dt}),s.jsx(dN,{open:Ut,onClose:()=>It(!1),connected:N,topOffset:44,gateway:Oe}),s.jsxs("div",{className:"app-body shell_content",children:[e==="board"?N?s.jsx(CR,{gateway_connected:N,runs:Mt,all_runs:Dn,runs_refreshed_at:wn,entities:Kn,entities_total:Cr,entities_error:ce,refreshing:jn,on_refresh:()=>void or(Oe,{force:!0}),on_open_run:g=>{t("observe"),Bs("overview"),ra(g)},on_resume_wait:Zf,on_open_automation:g=>{t("automations"),ss.refresh().then(()=>ss.select(g))},entity_app_href:l,on_read_diary:(g,k)=>Oe.read_entity_diary_entry(g,k),phase_graph:Xf}):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:()=>P.openModal(),disabled:ie,children:ie?"Connecting…":"Sign in"}),s.jsx("button",{className:"btn",onClick:()=>void ta({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:Tv(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:()=>P.openModal(),children:"Manage connection…"}),N?s.jsx("button",{className:"btn",onClick:()=>Rl(),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:Om})]}),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 ta({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(pj,{className:"field",providerLabel:"Provider",modelLabel:"Model",providerPlaceholder:"(gateway default)",modelPlaceholder:"(gateway default)",provider:n.maintenance_ai_provider,model:n.maintenance_ai_model,providers:yd,models:Mn.models,loadingProviders:ie,loadingModels:hs,modelError:Wn?Mn.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:A=>i(I=>({...I,assistant_skill_names:A.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(UN,{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:()=>P.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:In,onChange:async g=>{const k=_N(String(g.target.value||""));k&&await Ol(k)},disabled:ie||!N,children:[s.jsx("option",{value:"",children:Jc.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:gN(un).map(g=>s.jsx("option",{value:g.value,children:g.label},g.value))}),s.jsx("optgroup",{label:"Workflows",children:Jc.map(g=>s.jsx("option",{value:g.workflow_id,children:g.label},g.workflow_id))})]})}),s.jsxs("div",{className:"field",children:[js!=null&&js.description?s.jsx("div",{className:"help_text muted",style:{fontSize:"var(--font-size-sm)",marginTop:"6px"},children:String(js.description)}):null,Z?s.jsx("div",{className:"help_text muted",style:{fontSize:"var(--font-size-sm)"},children:"Loading workflow…"}):null,X?s.jsx("div",{className:"mono",style:{color:"rgba(239, 68, 68, 0.9)",fontSize:"var(--font-size-sm)"},children:X}):null]}),s.jsx("div",{className:"section_divider"}),s.jsx("div",{className:"section_title",children:"Inputs"}),No?at===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:xt()})]}),s.jsx("div",{className:"body mono",children:"Invalid input JSON — reselect the workflow to reset its inputs."})]}):Fa?s.jsx("div",{className:"launch_inputs",children:(()=>{const g=$e||Ct,k=[],A=[];for(const W of ko){if(!W||typeof W!="object")continue;const V=String(W.id||"").trim();if(!V||oe==="automate"&&nx.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"||Yc(te)||V==="prompt"||V==="system"?k.push(W):A.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 Ee=String(W.label||te).trim()||te,_e=Ee===te?I(te):Ee,pe=String(W.type||"").trim().toLowerCase(),Ne=Object.prototype.hasOwnProperty.call(W,"default"),ze=Ne?W.default:void 0,qe=Ne?typeof ze=="string"?ze:Ds(ze,80):"",Ze=at==null?void 0:at[te],Ie=Ne?`${qe}`:"";if(pe==="tools"){const He=Array.isArray(Ze)?Ze.map($n=>String($n||"").trim()).filter(Boolean):[],vt=Array.isArray(ze)?ze.map($n=>String($n||"").trim()).filter(Boolean):[],xn=Array.from(new Set([...Qo,...He,...vt])).sort();return s.jsxs("div",{className:"launch_field_wide",children:[s.jsx("label",{className:"launch_label",children:_e}),s.jsx(Qw,{options:xn,value:He,disabled:g,placeholder:"(no tools selected)",onChange:$n=>kn(te,$n)})]},te)}if(pe==="skills"||te==="skills")return null;if(pe==="mcp"||pe==="mcp_servers"||te==="mcp"||te==="mcp_servers"){const He=Array.isArray(Ze)?Ze.map($n=>String($n||"").trim()).filter(Boolean):[];if(K===null&&!He.length)return s.jsxs("div",{className:"launch_field_wide",children:[s.jsx("label",{className:"launch_label",children:_e}),s.jsx("div",{className:"help_text muted",children:"This gateway does not serve an MCP server inventory yet — MCP selection lights up here when it ships."})]},te);const vt=(K||[]).map($n=>$n.name),xn=Array.from(new Set([...vt,...He])).sort();return s.jsxs("div",{className:"launch_field_wide",children:[s.jsx("label",{className:"launch_label",children:_e}),s.jsx(Qw,{options:xn,value:He,disabled:g,placeholder:"(no MCP servers selected)",onChange:$n=>kn(te,$n)})]},te)}if(pe==="provider"||pe==="provider_text"){const He=typeof Ze=="string"?String(Ze):"";return s.jsxs("div",{className:V||"launch_field",children:[s.jsx("label",{className:"launch_label",children:_e}),s.jsxs("select",{value:He,onChange:vt=>kn(te,vt.target.value),disabled:g,children:[s.jsx("option",{value:"",children:Ie||"(select)"}),Xc.map(vt=>s.jsx("option",{value:vt,children:vt},vt))]})]},te)}if(pe==="model"||pe==="model_text"){const He=typeof Ze=="string"?String(Ze):"",vt=String((at==null?void 0:at.provider)||"").trim(),xn=vt?Bt[vt]:void 0,$n=xn&&Array.isArray(xn.models)?xn.models.map(lr=>String(lr||"").trim()).filter(Boolean):[];return s.jsxs("div",{className:V||"launch_field",children:[s.jsx("label",{className:"launch_label",children:_e}),$n.length?s.jsxs("select",{value:He,onChange:lr=>kn(te,lr.target.value),disabled:g,children:[s.jsx("option",{value:"",children:Ie||"(select)"}),$n.map(lr=>s.jsx("option",{value:lr,children:lr},lr))]}):s.jsx("input",{value:He,onChange:lr=>kn(te,lr.target.value),placeholder:Ie||"model id",disabled:g})]},te)}if(pe==="boolean"){const He=typeof Ze=="boolean"?Ze?"true":"false":"";return s.jsxs("div",{className:V||"launch_field",children:[s.jsx("label",{className:"launch_label",children:_e}),s.jsxs("select",{value:He,onChange:vt=>{const xn=String(vt.target.value||"").trim();xn?kn(te,xn==="true"):kn(te,void 0)},disabled:g,children:[s.jsx("option",{value:"",children:Ie||"(default)"}),s.jsx("option",{value:"true",children:"Yes"}),s.jsx("option",{value:"false",children:"No"})]})]},te)}if(pe==="number"){const He=typeof Ze=="number"&&Number.isFinite(Ze)?String(Ze):"";return s.jsxs("div",{className:V||"launch_field",children:[s.jsx("label",{className:"launch_label",children:_e}),s.jsx("input",{type:"number",value:He,onChange:vt=>{const xn=String(vt.target.value||"").trim();if(!xn){kn(te,void 0);return}const $n=Number(xn);Number.isFinite($n)&&kn(te,$n)},placeholder:Ie,disabled:g})]},te)}if(pe==="array"){const He=Array.isArray(Ze)?Ze.map(vt=>String(vt||"").trim()).filter(Boolean).join(`
148
- `):"";return s.jsxs("div",{className:"launch_field_wide",children:[s.jsx("label",{className:"launch_label",children:_e}),s.jsx("textarea",{className:"mono",value:He,onChange:vt=>{const xn=String(vt.target.value||"").split(/\r?\n/g).map($n=>String($n||"").trim()).filter(Boolean);kn(te,xn.length?xn:void 0)},placeholder:Ie||"(one item per line)",rows:2,disabled:g})]},te)}if(Yc(pe)){const He=typeof Kr[te]=="string"?Kr[te]:"",vt=String(tn[te]||"").trim();return s.jsxs("div",{className:"launch_field_wide",children:[s.jsxs("label",{className:"launch_label",children:[_e," ",s.jsx("span",{className:"launch_label_type",children:pe})]}),s.jsx("textarea",{className:"mono",value:He,onChange:xn=>{const $n=String(xn.target.value??"");it(Pn=>({...Pn,[te]:$n}));const lr=$n.trim();if(!lr){gs(Pn=>{const Sr={...Pn};return delete Sr[te],Sr}),kn(te,void 0);return}try{const Pn=JSON.parse(lr);gs(Sr=>{const Jl={...Sr};return delete Jl[te],Jl}),kn(te,Pn)}catch(Pn){gs(Sr=>({...Sr,[te]:String((Pn==null?void 0:Pn.message)||Pn||"Invalid JSON")}))}},placeholder:Ie||"{...}",rows:3,disabled:g}),vt?s.jsx("div",{className:"launch_field_error",children:vt}):null]},te)}const ln=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:_e}),s.jsx("textarea",{value:ln,onChange:He=>kn(te,He.target.value),placeholder:Ie||(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:_e}),s.jsx("input",{value:ln,onChange:He=>kn(te,He.target.value),placeholder:Ie,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)),A.length>0?s.jsx("div",{className:"launch_grid",children:A.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:Jf,onChange:g=>kn("prompt",g.target.value),placeholder:"What do you want the workflow/agent to do?",rows:3,disabled:$e||Ct})]}),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:Xo,onChange:g=>kn("provider",g.target.value),placeholder:"lmstudio / ollama / openai / ...",disabled:$e||Ct})]})}),s.jsx("div",{className:"col",children:s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Model (common)"}),s.jsx("input",{value:yi,onChange:g=>kn("model",g.target.value),placeholder:"qwen/qwen3-next-80b / gpt-4.1 / ...",disabled:$e||Ct})]})})]})]}):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(WN,{form:Ae,tools:Array.isArray(at==null?void 0:at.tools)?at.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",vr.length?` · ${vr.length} skill${vr.length===1?"":"s"}`:""]}),s.jsx(qN,{form:Ae,disabled:lt,on_change:g=>Be(k=>({...k,...g}))}),Gl]})]}):Gl,s.jsx("div",{className:"section_divider"}),hn?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:hn})]}):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:ym(Pe).title})," ",ym(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?No?at===null?"Inputs contain invalid JSON":g&&!ge.available?"Automations unavailable on this gateway":$e||Ct?"Attaching to a run…":ie||Z?"Loading…":lt?"Submitting…":"":"Select a workflow":"Sign in first";return s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"launch_submit_btn",onClick:()=>void oh(),disabled:!!k,title:k,children:g?lt?"Creating…":"Create automation":$e?"Launching…":"Launch now"}),k&&!lt&&!$e?s.jsx("span",{className:"mono muted launch_disabled_reason",children:k}):null]})})()})]})})}):null,e==="automations"?s.jsx(c1,{ctl:ss,gateway:Oe,active:e==="automations"&&N,available:ge,h:Od,host:{on_open_run:g=>Xa(g),on_open_session:(g,k)=>{Jt({ts:xt(),kind:"info",title:"Discussion started",preview:ht(k),data:g})}}}):null,e==="runtime"?s.jsx(_C,{gateway_connected:N,tab:kl,runs:Zn,active_runs:$o,all_artifacts:ld,artifacts:Hs,artifact_total_count:Ic,artifact_total_bytes:Wf,artifact_facets:mi,artifact_type_facets:Fi,artifact_page:xi,artifact_page_size:om,artifact_groups:du,selected_artifact:aa,embedded_preview:Ia,loading:r_,error:Go,query:_i,scope:Ko,type_filters:on,date_filter:ns,group_by:Lr,sort_by:xs,artifact_run_filter:zi,audit_log_text:Pr,audit_log_meta:Vf,audit_log_loading:Uc,audit_log_error:Wc,workflow_label_by_id:xr,run_by_id:jr,selected_run_id:Ya,session_id:Ja,runtime_log_source:Bi,runtime_log_query:i_,runtime_ledger_log_items:qc,runtime_ledger_log_meta:Gf,runtime_ledger_log_loading:Kf,runtime_ledger_log_error:Vc,on_tab_change:ad,on_query_change:Pc,on_scope_change:yo,on_session_filter_change:Sn,on_type_filters_change:wo,on_date_filter_change:rr,on_group_by_change:Ma,on_sort_by_change:Dc,on_artifact_page_change:Fc,on_artifact_run_filter_change:g=>{const k=String(g||"").trim();cd(k),k&&Ra(k),k&&Ko!=="run"&&yo("run")},on_refresh_artifacts:()=>void is(),on_refresh_audit:()=>void Vn(),on_refresh_runtime_ledger:g=>void _s(g),on_runtime_log_source_change:md,on_runtime_log_query_change:$l,on_select_run:g=>{const k=String(g||"").trim();Ra(k);const A=k&&jr[k]||null,I=String((A==null?void 0:A.session_id)||"").trim();I&&Sn(I)},on_select_artifact:La,on_preview_artifact:g=>void nu(g),on_download_artifact:g=>void xd(g),on_open_run:g=>{Ra(String(g||"").trim()),t("observe"),Bs("overview"),ra(g)},on_open_ledger:g=>{Ra(String(g||"").trim()),t("observe"),Bs("ledger"),ra(g)},on_refresh_runs:()=>void or(Oe,{force:!0}),on_reconnect:()=>void ta({open_modal_if_needed:!0}),on_open_settings:()=>t("settings"),memory_panel:N?s.jsx(iR,{gateway:Oe,selected_run_id:vo,selected_session_id:Ja}):null}):null,e==="observe"?s.jsx("div",{className:"page observe_page",children:s.jsxs("div",{className:"observatory_layout",children:[s.jsx(gC,{sections:Ka,selected_run_id:c,root_run_id:_,search:Ju,filter:Xu,group_by:Zu,loading:jn,connected:N,on_sign_in:()=>P.openModal(),total_runs:Zn.length,workflow_label_by_id:xr,automation_titles:_d,on_search:Xm,on_filter:Zm,on_group_by:Qm,on_refresh:()=>void or(),on_select:(g,k)=>void ra(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:xr[String((yn==null?void 0:yn.workflow_id)||"")]||String((yn==null?void 0:yn.workflow_id)||"").trim()||Lt(c.trim(),22)}),s.jsx("span",{className:"chip mono muted",children:Lt(c.trim(),14)}),s.jsx("span",{className:`chip ${fl(Vt||Ga,Rs)}`,title:String((Rs==null?void 0:Rs.headline)||""),children:Vt||Ga||"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(Xe==="pause"){Ei("pause"),Es(""),er(""),Ar(!0);return}ru("resume")},disabled:Ha,children:Sh}),$d?s.jsx("button",{className:"btn primary",onClick:()=>void ch(),disabled:$e||Ct||ni||qi,children:"Run now"}):null,s.jsx("button",{className:"btn danger",onClick:()=>{Ei("cancel"),Es(""),er(""),Ar(!0)},disabled:$e||Ct||ni,children:"Cancel"}),s.jsx("button",{className:"btn btn_icon",onClick:lh,title:"Clear the run view",children:s.jsx(Qe,{name:"x",size:14})})]}):null]}),c.trim()&&!ni?s.jsx("div",{className:"observe_steer_row",children:s.jsx(Mj,{runId:c.trim(),parked:Wa,submit:(g,k)=>Oe.submit_command({command_id:`steer-${Ps()}`,run_id:g,type:"inject_guidance",payload:{guidance:k},client_id:"web_pwa"}).then(A=>({accepted:!!(A!=null&&A.accepted),duplicate:!!(A!=null&&A.duplicate),seq:Number((A==null?void 0:A.seq)??0)})),onSent:()=>Jt({ts:xt(),kind:"info",title:"Steer queued",preview:"inject_guidance submitted — delivery shows as abstract.steer_seen in the ledger"})})}):null,Wa||Ms||vc?s.jsxs("div",{className:"observe_toolbar_context",children:[Wa?s.jsxs("div",{className:"observe_context_card info",children:[s.jsxs("div",{className:"observe_context_label",children:[(()=>{const g=Ms?qi?"suspended":"scheduled":"waiting";return s.jsx("span",{className:`chip ${fl(g)}`,children:g})})(),s.jsx("span",{className:"muted",children:an||"unknown"})]}),s.jsxs("div",{className:"observe_context_body",children:[gn?s.jsxs("span",{className:"mono",title:gn,children:[s.jsx("span",{className:"muted",children:"wait_key"}),": ",Lt(gn,46)]}):null,an==="event"&&Fl?s.jsxs("span",{className:"mono",children:[s.jsx("span",{className:"muted",children:"event"}),": ",Fl]}):null,an==="subworkflow"&&Hi?s.jsxs("span",{className:"mono",children:[s.jsx("span",{className:"muted",children:"child"}),": ",Lt(Hi,18)]}):null,an==="until"&&ti?s.jsxs("span",{className:"mono",title:ti,children:[s.jsx("span",{className:"muted",children:"until"}),": ",Lt(ti,46)]}):null,an==="until"&&ti?s.jsx("span",{className:"mono muted",children:(()=>{const g=Nn(ti),k=g!==null?new Date(g).toLocaleString():ti,A=g!==null?Ey(g-Date.now()):"";return`Next at ${k}${A?` (in ${A})`:""}`})()}):null]}),an==="subworkflow"&&Hi?s.jsxs("div",{className:"observe_context_actions",children:[s.jsx("button",{className:"btn primary",onClick:async()=>{f(Hi),await Il(Hi)},disabled:$e,children:"Attach to child"}),_.trim()&&_.trim()!==c.trim()?s.jsx("button",{className:"btn",onClick:async()=>{f(_.trim()),await Il(_.trim())},disabled:$e,children:"Back to root"}):null]}):null]}):null,Ms?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:ms?`every ${Hn}`:"once"})]}),s.jsxs("div",{className:"observe_context_body",children:[Hn?s.jsxs("span",{className:"mono",children:[s.jsx("span",{className:"muted",children:"interval"}),": ",Hn]}):null,s.jsxs("span",{className:"mono",children:[s.jsx("span",{className:"muted",children:"share ctx"}),": ",c_?"yes":"no"]}),typeof jh=="number"?s.jsxs("span",{className:"mono",children:[s.jsx("span",{className:"muted",children:"repeats"}),": ",jh]}):null]}),Bl!==null?s.jsxs("div",{className:"observe_context_budget",children:[s.jsxs("span",{className:"mono muted",children:[typeof Va=="number"&&typeof Ul=="number"?`${Va.toLocaleString()} / ${Ul.toLocaleString()}`:"",` • ${Math.round(Math.max(0,Math.min(1,Bl))*100)}%`]}),s.jsx("div",{className:"observe_budget_bar",children:s.jsx("div",{className:`observe_budget_fill ${Bl>=.9?"danger":Bl>=.75?"warn":"ok"}`,style:{width:`${Math.round(Math.max(0,Math.min(1,Bl))*100)}%`}})})]}):null,s.jsxs("div",{className:"observe_context_actions",children:[ms?s.jsx("button",{className:"btn",onClick:()=>{oo(Hn||""),Fn(!0),Tn(""),ds(!0)},disabled:$e||_r,children:"Edit schedule"}):null,ms?s.jsx("button",{className:"btn",onClick:()=>{Ai(""),Zs(!0)},disabled:$e||pr,children:"Compact context"}):null,s.jsx("button",{className:"btn",onClick:()=>void ah(c.trim()).catch(g=>en(String((g==null?void 0:g.message)||g))),disabled:$e||!c.trim(),title:"Open Launch → Automate prefilled from this schedule (this schedule is not changed)",children:"Recreate as automation"})]})]}):null,vc?s.jsxs("div",{className:"observe_context_card error",children:[s.jsx("span",{className:"chip danger",children:"error"}),s.jsx("span",{className:"mono",children:vc})]}):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":ts==="overview",className:`tab ${ts==="overview"?"active":""}`,onClick:()=>Bs("overview"),children:"Story"}),s.jsx("button",{role:"tab","aria-selected":ts==="ledger",className:`tab ${ts==="ledger"?"active":""}`,onClick:()=>Bs("ledger"),children:"Ledger"}),s.jsx("button",{role:"tab","aria-selected":ts==="graph",className:`tab ${ts==="graph"?"active":""}`,onClick:()=>Bs("graph"),children:"Flow"}),s.jsx("button",{role:"tab","aria-selected":ts==="chat",className:`tab ${ts==="chat"?"active":""}`,onClick:()=>Bs("chat"),children:"Ask"})]}),ts==="ledger"&&(rs.length>0||ba==="cycles")?s.jsxs("div",{className:"tab_bar_controls",children:[s.jsxs("div",{className:"seg_toggle",children:[s.jsx("button",{className:`seg_btn ${ba==="steps"?"active":""}`,onClick:()=>xc("steps"),children:"Steps"}),s.jsx("button",{className:`seg_btn ${ba==="cycles"?"active":""}`,onClick:()=>xc("cycles"),children:"Cycles"})]}),ba==="steps"?s.jsx("button",{className:`seg_action ${gl?"active":""}`,onClick:()=>Mf(g=>!g),title:gl?"Showing condensed view":"Showing all steps",children:gl?"Condensed":"All"}):s.jsxs("select",{className:"mono seg_select",value:Vi,onChange:g=>Qu(String(g.target.value||"")),disabled:!br.length,title:"Select run for cycles view",children:[br.length?null:s.jsx("option",{value:"",children:"(no runs)"}),br.map(g=>{const k=typeof si[g]=="number"?Number(si[g]):0,A=`${Lt(g,18)}${k?` • ${k} llm`:""}`;return s.jsx("option",{value:g,children:A},g)})]}),s.jsx("button",{className:"seg_action",disabled:!$t.length&&!us.length,title:"Copy full ledger as JSONL",onClick:()=>{const A=[...$t.map(W=>({run_id:c.trim()||W.record.run_id||"",cursor:W.cursor,record:W.record})),...us.map(W=>({run_id:W.run_id,cursor:W.cursor,record:W.record}))].map(W=>{var Ee,_e;const V=String(((Ee=W.record)==null?void 0:Ee.ended_at)||((_e=W.record)==null?void 0:_e.started_at)||"").trim(),te=Nn(V);return{...W,_ms:te??0}});A.sort((W,V)=>(W._ms||0)-(V._ms||0));const q=(A.length>5e3?A.slice(A.length-5e3):A).map(({_ms:W,...V})=>JSON.stringify(V)).join(`
149
- `);Zc(q)},children:"Copy JSONL"})]}):null,ts==="graph"?s.jsxs("div",{className:"tab_bar_controls",children:[s.jsx("button",{className:`seg_action ${Bo?"active":""}`,onClick:()=>Ca(g=>!g),children:"Subflows"}),s.jsx("button",{className:`seg_action ${Ac?"active":""}`,onClick:()=>Ff(g=>!g),children:"Path"}),cu.length?s.jsx("select",{className:"mono seg_select",value:zo,onChange:g=>ka(String(g.target.value||"")),disabled:!!vi.trim()||!b.trim()||Cc,children:cu.map(g=>s.jsx("option",{value:g,children:g},g))}):null]}):null]}),ts==="overview"?s.jsx(yC,{run_id:c,run:yn,run_state:xe,status_label:Vt||Ga||"unknown",workflow_label_by_id:xr,root_run_id:_,subrun_ids:di,session_id:Ur,records_count:$t.length,records:$t,child_records_count:us.length,provider_activities:os,attachments_count:Lf.length,latest_summary:Ad,wait_state:Xt,summary_generating:jl,summary_error:od,on_generate_summary:()=>void jd(),on_open_runtime:()=>{const g=String(c||"").trim();g&&(Ra(g),cd(g),yo("run")),ad("artifacts"),t("runtime")},on_open_subrun:g=>void ra(g,{root_run_id:_||c||g}),on_answer_wait:()=>Jr(""),workspace_root:If,on_reveal_workspace:()=>void Qf(),run_artifacts:e_,run_artifacts_loading:sd,run_artifacts_error:Of,on_preview_run_artifact:g=>void nu(g),on_download_run_artifact:g=>void xd(g),timeline_items:Hl,node_index:pd,attachments:Lf,attachments_loading:td,attachments_error:yl,attachments_ready:!!fo.trim(),on_refresh_attachments:()=>void Ba(),on_preview_attachment:g=>void tu(g),on_download_attachment:g=>void eu(g),on_copy:g=>void Zc(g)}):null,ts==="ledger"?s.jsx(s.Fragment,{children:ba==="steps"?s.jsxs("div",{className:"log log_scroll",children:[rs.map(g=>s.jsx(vC,{item:g,open:Ku[g.id]===!0,on_toggle:()=>Yu(k=>({...k,[g.id]:!k[g.id]})),response_open:Jm[g.id]===!0,on_toggle_response:()=>Tf(k=>({...k,[g.id]:!k[g.id]})),node_index:pd,on_copy:k=>void Zc(k)},g.id)),rs.length?null:s.jsx("div",{className:"empty_state_inline",children:"(no ledger items)"})]}):s.jsx("div",{className:"log log_scroll",children:s.jsx(F0,{items:uu.items,title:"Agent",subtitle:uu.node_id?`node_id: ${uu.node_id}`:"Live per-effect trace (LLM/tool calls).",subRunId:Vi,onOpenSubRun:Vi&&Vi!==c.trim()?()=>{f(Vi),Il(Vi)}:void 0})})}):null,ts==="graph"?s.jsxs(s.Fragment,{children:[$c?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:xt()})]}),s.jsx("div",{className:"body mono",children:$c})]}):null,Cc?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:vi.trim()?vi.trim():zo})]}),s.jsx("div",{className:"body mono",children:"Loading graph…"})]}):null,s.jsx("div",{className:"graph_panel",children:s.jsx(LC,{flow:_o,flow_by_id:Nc,expand_subflows:Bo,simplify:!0,prefer_vertical:!0,vertical_compact:.78,schedule_next_in:ql,schedule_interval:Hn,node_last_ms:Td,active_node_id:kh,recent_nodes:zf,visited_nodes:Bf,highlight_path:Ac,now_ms:Ec})})]}):null,s.jsxs(ll,{open:Pf,title:t_||"Attachment",onClose:()=>{rd(!1),Sa(""),mo(""),wl(!1)},actions:s.jsx(s.Fragment,{children:s.jsx("button",{className:"btn",onClick:()=>{rd(!1),Sa(""),mo(""),wl(!1)},children:"Close"})}),children:[Df?s.jsx("div",{className:"mono muted",style:{fontSize:"var(--font-size-sm)",marginBottom:"8px"},children:"Loading…"}):null,Tr?s.jsx("div",{className:"mono",style:{color:"rgba(239, 68, 68, 0.9)",fontSize:"var(--font-size-sm)",marginBottom:"8px"},children:Tr}):null,s.jsx("pre",{className:"mono",style:{whiteSpace:"pre-wrap",maxHeight:"62vh",overflow:"auto",margin:0},children:s_||"(empty)"})]}),ts==="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(Iu,{value:pl,options:Hu,placeholder:Ri?"Loading…":Hu.length?"Select a saved discussion…":"(none saved)",disabled:!c.trim()||!N||!Hu.length,loading:Ri,searchable:!0,clearable:!0,onChange:g=>{gc(g),Fo("")}})}),s.jsxs("div",{className:"actions",style:{justifyContent:"flex-end",marginTop:0},children:[s.jsx("button",{className:"btn",type:"button",disabled:!pl.trim()||!N||yc,onClick:()=>void mh(),children:yc?"Loading…":"Load"}),s.jsx("button",{className:"btn",type:"button",disabled:!ke.length||U||Ft||yc,onClick:()=>{Ue([]),ot(null),yr(""),zs(""),Rt(""),Cn(""),es("")},children:"Clear"}),s.jsx("button",{className:"btn",type:"button",onClick:()=>void iu(),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||!qu,onClick:()=>void hh(),title:qu?"":"No changes since last save",children:Ft?"Saving…":!qu&&sn?"Saved":"Save discussion"}),s.jsx("button",{className:"btn",type:"button",disabled:!ke.length,onClick:()=>fh("download"),children:"Export Markdown"}),s.jsx("button",{className:"btn",type:"button",disabled:!ke.length,onClick:()=>fh("copy"),children:je==="copied"?"Copied":je==="failed"?"Copy failed":"Copy Markdown"})]}),sn?s.jsxs("div",{className:"chat_hint",children:["Last saved: ",fa(sn)]}):null,vs?s.jsx("div",{className:"chat_hint chat_hint_danger",children:vs}):null,Ef?s.jsx("div",{className:"chat_hint chat_hint_danger",children:Ef}):null,Af?s.jsx("div",{className:"chat_hint chat_hint_danger",children:Af}):null]})]}),co?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:xt()})]}),s.jsx("div",{className:"body mono",children:co})]}):null,Oo?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:xt()})]}),s.jsx("div",{className:"body mono",children:Oo})]}):null,s.jsx("div",{className:"chat_messages",style:{marginTop:"10px"},children:s.jsx(ag,{messages:ke,className:"log_scroll",after:s.jsx(tx,{history:ft}),afterKey:ft?`${ft.replayed_messages}:${ft.dropped_messages}`:null,messageProps:qn.tts_supported&&N&&Do.trim()?{onSpeakToggle:Sd,getSpeakState:kd,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(lg,{ref:gt,value:_c,onChange:yr,onSubmit:()=>void Ua(),placeholder:"Ask about this run…",disabled:!c.trim()||!N||U,busy:U||qn.voice_ptt_busy,busyLabel:qn.voice_ptt_busy?"Transcribing…":"Thinking…",rows:3,sendButtonClassName:"btn primary",actions:s.jsxs("button",{className:`btn btn_icon voice_btn${qn.voice_ptt_recording?" danger":""}`,type:"button",disabled:!N||!sa.trim()||!Do.trim()||U||qn.voice_ptt_busy||!qn.voice_ptt_supported,title:qn.voice_ptt_supported?qn.voice_ptt_busy?"Transcribing…":qn.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,A;if(!(!N||!sa.trim()||!Do.trim()||U||qn.voice_ptt_busy||!qn.voice_ptt_supported)){g.preventDefault();try{(A=(k=g.currentTarget)==null?void 0:k.setPointerCapture)==null||A.call(k,g.pointerId)}catch{}qn.start_voice_ptt_recording()}},onPointerUp:g=>{g.preventDefault(),qn.stop_voice_ptt_recording()},onPointerCancel:g=>{g.preventDefault(),qn.stop_voice_ptt_recording()},children:[s.jsx(Qe,{name:qn.voice_ptt_recording?"x":"mic",size:16}),qn.voice_ptt_busy?"Transcribing…":qn.voice_ptt_recording?"Recording…":"Voice"]})})})]}):null,c.trim()?s.jsxs("div",{className:`status_bar ${Lo?"pulse":""}`,children:[s.jsx("strong",{children:"Run"}),":"," ",s.jsx("span",{className:"mono",children:Vt||Ga||"unknown"}),$h&&ql?s.jsxs("span",{className:"mono muted",children:[" • next in ",ql]}):null,Ti?s.jsxs("span",{className:"mono muted",children:[" • ",Ti]}):null]}):null]})]})]})}):null,s.jsxs(ll,{open:Oa,title:Nl||"Artifact",onClose:()=>{xo(!1),bs(""),vn(""),Ts(!1),Cl(null),Un&&(URL.revokeObjectURL(Un),Or(""))},actions:s.jsx("button",{className:"btn",onClick:()=>{xo(!1),bs(""),vn(""),Ts(!1),Cl(null),Un&&(URL.revokeObjectURL(Un),Or(""))},children:"Close"}),children:[ud?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,Qr==="image"&&Un?s.jsx("img",{className:"runtime_preview_media",src:Un,alt:Nl||"Artifact preview"}):Qr==="audio"&&Un?s.jsx("audio",{className:"runtime_preview_media",controls:!0,src:Un}):Qr==="video"&&Un?s.jsx("video",{className:"runtime_preview_media",controls:!0,src:Un}):s.jsx(bx,{artifact:Hf,text:Ir||"(empty)",className:"runtime_preview_text"})]}),oi?s.jsxs(ll,{open:oi,title:"Edit schedule",onClose:()=>{ds(!1),oo(""),Fn(!0),Tn(""),ao(!1)},actions:s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"btn",onClick:()=>{ds(!1),oo(""),Fn(!0),Tn(""),ao(!1)},disabled:$e||_r,children:"Back"}),s.jsx("button",{className:"btn primary",onClick:async()=>{await uh({interval:io,apply_immediately:ya})||(ds(!1),Tn(""),ao(!1))},disabled:$e||_r||!io.trim(),children:"Save"})]}),children:[mr?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:xt()})]}),s.jsx("div",{className:"body mono",children:mr})]}):null,s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Interval"}),s.jsx("input",{className:"mono",value:io,onChange:g=>oo(String(g.target.value||"")),placeholder:"20m / 1h / 0.5s / 250ms",disabled:$e||_r}),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:()=>oo(g),disabled:$e||_r,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:ya,onChange:g=>Fn(!!g.target.checked),disabled:$e||_r}),"Apply immediately (recompute next run from now if waiting)"]})]})]}):null,Qn?s.jsxs(ll,{open:Qn,title:"Compact scheduled context",onClose:()=>{Zs(!1),Ai(""),As(!1)},actions:s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"btn",onClick:()=>{Zs(!1),Ai(""),As(!1)},disabled:$e||pr,children:"Cancel"}),s.jsx("button",{className:"btn primary",onClick:async()=>{await dh({preserve_recent:fs,compression_mode:ys,focus:lo})||(Zs(!1),Ai(""),As(!1))},disabled:$e||pr,children:pr?"Compacting…":"Compact"})]}),children:[ml?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:xt()})]}),s.jsx("div",{className:"body mono",children:ml})]}):null,s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Preserve recent turns"}),s.jsx("input",{type:"number",min:1,value:String(fs),onChange:g=>Yr(Math.max(1,parseInt(g.target.value||"6",10)||6)),disabled:$e||pr})]}),s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Mode"}),s.jsxs("select",{value:ys,onChange:g=>wa(g.target.value),disabled:$e||pr,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:lo,onChange:g=>nn(String(g.target.value||"")),placeholder:"e.g. important decisions, next steps…",disabled:$e||pr})]})]}):null,va?s.jsxs(ll,{open:va,title:ai==="cancel"?"Cancel run":Ms?"Suspend schedule":"Pause run",onClose:()=>{Ar(!1),Es(""),er("")},actions:s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"btn",onClick:()=>{Ar(!1),Es(""),er("")},disabled:$e||Ct,children:"Back"}),s.jsx("button",{className:`btn ${ai==="cancel"?"danger":"primary"}`,onClick:async()=>{er("");const g=await ru(ai,{reason:Qs});if(g){er(g);return}Ar(!1),Es(""),er("")},disabled:$e||Ct,children:ai==="pause"?Ms?"Suspend":"Pause":"Cancel"})]}),children:[Er?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:xt()})]}),s.jsx("div",{className:"body mono",children:Er})]}):null,s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Reason (optional)"}),s.jsx("input",{className:"mono",value:Qs,onChange:g=>Es(g.target.value),placeholder:"reason…"})]})]}):null,ou?s.jsxs(ll,{open:ou,title:zl,onClose:()=>{gn&&Jr(gn)},actions:s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"btn",onClick:()=>{Bs("ledger"),t("observe"),gn&&Jr(gn)},disabled:!c.trim(),children:"Open ledger"}),s.jsx("button",{className:"btn",onClick:()=>gn&&Jr(gn),disabled:Ct,children:"Dismiss"}),ia.length?s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"btn danger",disabled:Ct,onClick:()=>Dl({approved:!1}),children:"Reject"}),s.jsx("button",{className:"btn",disabled:Ct,onClick:()=>Dl({approved:!0}),children:"Approve only"}),s.jsx("button",{className:"btn primary",disabled:!Fr||Ct,onClick:()=>_h(ia),children:"Approve and execute"})]}):null]}),children:[s.jsxs("div",{className:"wait_context_panel",children:[s.jsxs("div",{className:"wait_context_header",children:[s.jsxs("div",{children:[s.jsx("div",{className:"run_hero_eyebrow",children:"What you need to do"}),s.jsx("strong",{children:zl}),s.jsx("p",{children:a_})]}),s.jsx(hl,{status:Wi||"waiting"})]}),Co?s.jsxs("div",{className:`wait_request_card ${lu?"":"inferred"}`,children:[s.jsx("span",{children:Cd}),s.jsx(rv,{metadata:vh}),s.jsx(Ni,{text:Co}),lu?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."}),wi.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:wi.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:fa(g.ts)}):null]}),s.jsx(rv,{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(qa,xr)})]}),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:qa.current_node||String((zn==null?void 0:zn.node_id)||"—")})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Elapsed"}),s.jsx("strong",{children:fc(qa)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Session"}),s.jsx("strong",{className:"mono",children:qa.session_id?Lt(String(qa.session_id),18):"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Wait key"}),s.jsx("strong",{className:"mono",children:Lt(gn,28)})]})]}),bh?s.jsxs("details",{className:"runtime_raw_details wait_full_input_details",open:!Co,children:[s.jsx("summary",{className:"mono muted",children:"Full run input JSON"}),s.jsx("div",{className:"wait_shared_json",children:s.jsx(dr,{value:xh,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:[au.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,fa(g.ts)].filter(Boolean).join(" · ")})]},`${g.cursor}:${g.node_id}:${g.status}`)),au.length?null:s.jsx("div",{className:"empty_state_inline",children:"No ledger context is loaded. Open the ledger before deciding."})]})]})]}),ia.length?s.jsxs("div",{className:"wait_action_panel",children:[s.jsx("div",{className:"wait_action_intro",children:"Approve and execute runs the listed tool request through your configured worker. Approve only sends approval without local execution. Reject returns a denial. Cancel run stops the whole workflow run."}),s.jsx("div",{className:"wait_tool_list",children:ia.map((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"}),mx(g).map(A=>s.jsxs("span",{className:"chip mono muted",title:hx,children:[A,"~"]},A))]})]}),s.jsx("div",{className:"wait_tool_args",children:s.jsx(dr,{value:(g==null?void 0:g.arguments)||{},collapseAfterDepth:3,showCopy:!0})})]},`${String((g==null?void 0:g.name)||"tool")}:${k}`))}),Fr?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 Pl(c.trim(),"Cancelled from wait prompt"),disabled:!c.trim()||Ct,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(dr,{value:Xt||{},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:Co||"No explicit prompt was provided. Open the ledger for context before responding."}),s.jsx(pC,{wait:Xt,disabled:Ct,on_submit:g=>Dl({response:g})}),s.jsx("div",{className:"actions",children:s.jsx("button",{className:"btn danger",onClick:()=>void Pl(c.trim(),"Cancelled from wait prompt"),disabled:!c.trim()||Ct,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(dr,{value:Xt||{},collapseAfterDepth:3,showCopy:!0})})]})]})]}):null]})]})]})}if("serviceWorker"in navigator){window.addEventListener("load",()=>{navigator.serviceWorker.register(hN).then(t=>t.update()).catch(()=>{})});let e=!1;navigator.serviceWorker.addEventListener("controllerchange",()=>{e||(e=!0,window.location.reload())})}v0.createRoot(document.getElementById("root")).render(s.jsx(ve.StrictMode,{children:s.jsx(WR,{})}));
150
- //# sourceMappingURL=index-CKmZd-uV.js.map