@abstractframework/observer 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,138 +0,0 @@
1
- var a0=Object.defineProperty;var l0=(e,t,n)=>t in e?a0(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var Gr=(e,t,n)=>l0(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 Qp(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var __={exports:{}},zd={},p_={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 zg;function c0(){if(zg)return Gt;zg=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 se(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=se(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 P(T,Q,K){if(T==null)return T;var J=[],oe=0;return N(T,J,"","",function(fe){return Q.call(K,fe,oe++)}),J}function O(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:P,forEach:function(T,Q,K){P(T,function(){Q.apply(this,arguments)},K)},count:function(T){var Q=0;return P(T,function(){Q++}),Q},toArray:function(T){return P(T,function(Q){return Q})||[]},only:function(T){if(!ie(T))throw Error("React.Children.only expected to receive a single React element child.");return T}},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:O}},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 Bg;function bf(){return Bg||(Bg=1,p_.exports=c0()),p_.exports}/**
10
- * @license React
11
- * react-jsx-runtime.production.min.js
12
- *
13
- * Copyright (c) Facebook, Inc. and its affiliates.
14
- *
15
- * This source code is licensed under the MIT license found in the
16
- * LICENSE file in the root directory of this source tree.
17
- */var Ug;function u0(){if(Ug)return zd;Ug=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 Wg;function d0(){return Wg||(Wg=1,__.exports=u0()),__.exports}var r=d0(),m=bf();const ve=Qp(m);var Oh={},g_={exports:{}},Hs={},y_={exports:{}},w_={};/**
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 qg;function f0(){return qg||(qg=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,O(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,se=5,ie=-1;function ue(){return!(e.unstable_now()-ie<se)}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,P=N.port2;N.port1.onmessage=F,C=function(){P.postMessage(null)}}else C=function(){$(F,0)};function O(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,O(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"):se=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,O(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}}}})(w_)),w_}var Hg;function h0(){return Hg||(Hg=1,y_.exports=f0()),y_.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 Vg;function m0(){if(Vg)return Hs;Vg=1;var e=bf(),t=h0();function n(s){for(var a="https://reactjs.org/docs/error-decoder.html?invariant="+s,d=1;d<arguments.length;d++)a+="&args[]="+encodeURIComponent(arguments[d]);return"Minified React error #"+s+"; 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(s,a){u(s,a),u(s+"Capture",a)}function u(s,a){for(o[s]=a,s=0;s<a.length;s++)i.add(a[s])}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(s){return f.call(w,s)?!0:f.call(p,s)?!1:_.test(s)?w[s]=!0:(p[s]=!0,!1)}function x(s,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:(s=s.toLowerCase().slice(0,5),s!=="data-"&&s!=="aria-");default:return!1}}function S(s,a,d,h){if(a===null||typeof a>"u"||x(s,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(s,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=s,this.type=a,this.sanitizeURL=j,this.removeEmptyString=R}var $={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(s){$[s]=new b(s,0,!1,s,null,!1,!1)}),[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(s){var a=s[0];$[a]=new b(a,1,!1,s[1],null,!1,!1)}),["contentEditable","draggable","spellCheck","value"].forEach(function(s){$[s]=new b(s,2,!1,s.toLowerCase(),null,!1,!1)}),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(s){$[s]=new b(s,2,!1,s,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(s){$[s]=new b(s,3,!1,s.toLowerCase(),null,!1,!1)}),["checked","multiple","muted","selected"].forEach(function(s){$[s]=new b(s,3,!0,s,null,!1,!1)}),["capture","download"].forEach(function(s){$[s]=new b(s,4,!1,s,null,!1,!1)}),["cols","rows","size","span"].forEach(function(s){$[s]=new b(s,6,!1,s,null,!1,!1)}),["rowSpan","start"].forEach(function(s){$[s]=new b(s,5,!1,s.toLowerCase(),null,!1,!1)});var E=/[\-:]([a-z])/g;function L(s){return s[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(s){var a=s.replace(E,L);$[a]=new b(a,1,!1,s,null,!1,!1)}),"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(s){var a=s.replace(E,L);$[a]=new b(a,1,!1,s,"http://www.w3.org/1999/xlink",!1,!1)}),["xml:base","xml:lang","xml:space"].forEach(function(s){var a=s.replace(E,L);$[a]=new b(a,1,!1,s,"http://www.w3.org/XML/1998/namespace",!1,!1)}),["tabIndex","crossOrigin"].forEach(function(s){$[s]=new b(s,1,!1,s.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(s){$[s]=new b(s,1,!1,s.toLowerCase(),null,!0,!0)});function D(s,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?s.removeAttribute(a):s.setAttribute(a,""+d)):v.mustUseProperty?s[v.propertyName]=d===null?v.type===3?!1:"":d:(a=v.attributeName,h=v.attributeNamespace,d===null?s.removeAttribute(a):(v=v.type,d=v===3||v===4&&d===!0?"":""+d,h?s.setAttributeNS(h,a,d):s.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"),se=Symbol.for("react.profiler"),ie=Symbol.for("react.provider"),ue=Symbol.for("react.context"),F=Symbol.for("react.forward_ref"),C=Symbol.for("react.suspense"),N=Symbol.for("react.suspense_list"),P=Symbol.for("react.memo"),O=Symbol.for("react.lazy"),ne=Symbol.for("react.offscreen"),B=Symbol.iterator;function z(s){return s===null||typeof s!="object"?null:(s=B&&s[B]||s["@@iterator"],typeof s=="function"?s:null)}var G=Object.assign,T;function Q(s){if(T===void 0)try{throw Error()}catch(d){var a=d.stack.trim().match(/\n( *(at )?)/);T=a&&a[1]||""}return`
34
- `+T+s}var K=!1;function J(s,a){if(!s||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(s,[],a)}else{try{a.call()}catch(ye){h=ye}s.call(a.prototype)}else{try{throw Error()}catch(ye){h=ye}s()}}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 re=`
37
- `+v[R].replace(" at new "," at ");return s.displayName&&re.includes("<anonymous>")&&(re=re.replace("<anonymous>",s.displayName)),re}while(1<=R&&0<=ee);break}}}finally{K=!1,Error.prepareStackTrace=d}return(s=s?s.displayName||s.name:"")?Q(s):""}function oe(s){switch(s.tag){case 5:return Q(s.type);case 16:return Q("Lazy");case 13:return Q("Suspense");case 19:return Q("SuspenseList");case 0:case 2:case 15:return s=J(s.type,!1),s;case 11:return s=J(s.type.render,!1),s;case 1:return s=J(s.type,!0),s;default:return""}}function fe(s){if(s==null)return null;if(typeof s=="function")return s.displayName||s.name||null;if(typeof s=="string")return s;switch(s){case Y:return"Fragment";case Z:return"Portal";case se:return"Profiler";case X:return"StrictMode";case C:return"Suspense";case N:return"SuspenseList"}if(typeof s=="object")switch(s.$$typeof){case ue:return(s.displayName||"Context")+".Consumer";case ie:return(s._context.displayName||"Context")+".Provider";case F:var a=s.render;return s=s.displayName,s||(s=a.displayName||a.name||"",s=s!==""?"ForwardRef("+s+")":"ForwardRef"),s;case P:return a=s.displayName||null,a!==null?a:fe(s.type)||"Memo";case O:a=s._payload,s=s._init;try{return fe(s(a))}catch{}}return null}function me(s){var a=s.type;switch(s.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 s=a.render,s=s.displayName||s.name||"",a.displayName||(s!==""?"ForwardRef("+s+")":"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(s){switch(typeof s){case"boolean":case"number":case"string":case"undefined":return s;case"object":return s;default:return""}}function Ae(s){var a=s.type;return(s=s.nodeName)&&s.toLowerCase()==="input"&&(a==="checkbox"||a==="radio")}function Be(s){var a=Ae(s)?"checked":"value",d=Object.getOwnPropertyDescriptor(s.constructor.prototype,a),h=""+s[a];if(!s.hasOwnProperty(a)&&typeof d<"u"&&typeof d.get=="function"&&typeof d.set=="function"){var v=d.get,j=d.set;return Object.defineProperty(s,a,{configurable:!0,get:function(){return v.call(this)},set:function(R){h=""+R,j.call(this,R)}}),Object.defineProperty(s,a,{enumerable:d.enumerable}),{getValue:function(){return h},setValue:function(R){h=""+R},stopTracking:function(){s._valueTracker=null,delete s[a]}}}}function We(s){s._valueTracker||(s._valueTracker=Be(s))}function _t(s){if(!s)return!1;var a=s._valueTracker;if(!a)return!0;var d=a.getValue(),h="";return s&&(h=Ae(s)?s.checked?"true":"false":s.value),s=h,s!==d?(a.setValue(s),!0):!1}function Oe(s){if(s=s||(typeof document<"u"?document:void 0),typeof s>"u")return null;try{return s.activeElement||s.body}catch{return s.body}}function et(s,a){var d=a.checked;return G({},a,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:d??s._wrapperState.initialChecked})}function lt(s,a){var d=a.defaultValue==null?"":a.defaultValue,h=a.checked!=null?a.checked:a.defaultChecked;d=we(a.value!=null?a.value:d),s._wrapperState={initialChecked:h,initialValue:d,controlled:a.type==="checkbox"||a.type==="radio"?a.checked!=null:a.value!=null}}function Ye(s,a){a=a.checked,a!=null&&D(s,"checked",a,!1)}function Se(s,a){Ye(s,a);var d=we(a.value),h=a.type;if(d!=null)h==="number"?(d===0&&s.value===""||s.value!=d)&&(s.value=""+d):s.value!==""+d&&(s.value=""+d);else if(h==="submit"||h==="reset"){s.removeAttribute("value");return}a.hasOwnProperty("value")?ct(s,a.type,d):a.hasOwnProperty("defaultValue")&&ct(s,a.type,we(a.defaultValue)),a.checked==null&&a.defaultChecked!=null&&(s.defaultChecked=!!a.defaultChecked)}function Le(s,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=""+s._wrapperState.initialValue,d||a===s.value||(s.value=a),s.defaultValue=a}d=s.name,d!==""&&(s.name=""),s.defaultChecked=!!s._wrapperState.initialChecked,d!==""&&(s.name=d)}function ct(s,a,d){(a!=="number"||Oe(s.ownerDocument)!==s)&&(d==null?s.defaultValue=""+s._wrapperState.initialValue:s.defaultValue!==""+d&&(s.defaultValue=""+d))}var ge=Array.isArray;function De(s,a,d,h){if(s=s.options,a){a={};for(var v=0;v<d.length;v++)a["$"+d[v]]=!0;for(d=0;d<s.length;d++)v=a.hasOwnProperty("$"+s[d].value),s[d].selected!==v&&(s[d].selected=v),v&&h&&(s[d].defaultSelected=!0)}else{for(d=""+we(d),a=null,v=0;v<s.length;v++){if(s[v].value===d){s[v].selected=!0,h&&(s[v].defaultSelected=!0);return}a!==null||s[v].disabled||(a=s[v])}a!==null&&(a.selected=!0)}}function Ke(s,a){if(a.dangerouslySetInnerHTML!=null)throw Error(n(91));return G({},a,{value:void 0,defaultValue:void 0,children:""+s._wrapperState.initialValue})}function Dt(s,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}s._wrapperState={initialValue:we(d)}}function Qt(s,a){var d=we(a.value),h=we(a.defaultValue);d!=null&&(d=""+d,d!==s.value&&(s.value=d),a.defaultValue==null&&s.defaultValue!==d&&(s.defaultValue=d)),h!=null&&(s.defaultValue=""+h)}function _n(s){var a=s.textContent;a===s._wrapperState.initialValue&&a!==""&&a!==null&&(s.value=a)}function Ut(s){switch(s){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(s,a){return s==null||s==="http://www.w3.org/1999/xhtml"?Ut(a):s==="http://www.w3.org/2000/svg"&&a==="foreignObject"?"http://www.w3.org/1999/xhtml":s}var un,Bn=(function(s){return typeof MSApp<"u"&&MSApp.execUnsafeLocalFunction?function(a,d,h,v){MSApp.execUnsafeLocalFunction(function(){return s(a,d,h,v)})}:s})(function(s,a){if(s.namespaceURI!=="http://www.w3.org/2000/svg"||"innerHTML"in s)s.innerHTML=a;else{for(un=un||document.createElement("div"),un.innerHTML="<svg>"+a.valueOf().toString()+"</svg>",a=un.firstChild;s.firstChild;)s.removeChild(s.firstChild);for(;a.firstChild;)s.appendChild(a.firstChild)}});function Mt(s,a){if(a){var d=s.firstChild;if(d&&d===s.lastChild&&d.nodeType===3){d.nodeValue=a;return}}s.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(s){Dn.forEach(function(a){a=a+s.charAt(0).toUpperCase()+s.substring(1),bn[a]=bn[s]})});function En(s,a,d){return a==null||typeof a=="boolean"||a===""?"":d||typeof a!="number"||a===0||bn.hasOwnProperty(s)&&bn[s]?(""+a).trim():a+"px"}function jn(s,a){s=s.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?s.setProperty(d,v):s[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(s,a){if(a){if(Ln[s]&&(a.children!=null||a.dangerouslySetInnerHTML!=null))throw Error(n(137,s));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 Cr(s,a){if(s.indexOf("-")===-1)return typeof a.is=="string";switch(s){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 lr(s){return s=s.target||s.srcElement||window,s.correspondingUseElement&&(s=s.correspondingUseElement),s.nodeType===3?s.parentNode:s}var Cs=null,Yn=null,ce=null;function be(s){if(s=Aa(s)){if(typeof Cs!="function")throw Error(n(280));var a=s.stateNode;a&&(a=Oc(a),Cs(s.stateNode,s.type,a))}}function Ge(s){Yn?ce?ce.push(s):ce=[s]:Yn=s}function Ve(){if(Yn){var s=Yn,a=ce;if(ce=Yn=null,be(s),a)for(s=0;s<a.length;s++)be(a[s])}}function rt(s,a){return s(a)}function ut(){}var Et=!1;function jt(s,a,d){if(Et)return s(a,d);Et=!0;try{return rt(s,a,d)}finally{Et=!1,(Yn!==null||ce!==null)&&(ut(),Ve())}}function qt(s,a){var d=s.stateNode;if(d===null)return null;var h=Oc(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)||(s=s.type,h=!(s==="button"||s==="input"||s==="select"||s==="textarea")),s=!h;break e;default:s=!1}if(s)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(s,a,d,h,v,j,R,ee,re){var ye=Array.prototype.slice.call(arguments,3);try{a.apply(d,ye)}catch(Me){this.onError(Me)}}var Nt=!1,pt=null,Pt=!1,$e=null,Wt={onError:function(s){Nt=!0,pt=s}};function Ct(s,a,d,h,v,j,R,ee,re){Nt=!1,pt=null,Bt.apply(Wt,arguments)}function sn(s,a,d,h,v,j,R,ee,re){if(Ct.apply(this,arguments),Nt){if(Nt){var ye=pt;Nt=!1,pt=null}else throw Error(n(198));Pt||(Pt=!0,$e=ye)}}function $t(s){var a=s,d=s;if(s.alternate)for(;a.return;)a=a.return;else{s=a;do a=s,(a.flags&4098)!==0&&(d=a.return),s=a.return;while(s)}return a.tag===3?d:null}function cr(s){if(s.tag===13){var a=s.memoizedState;if(a===null&&(s=s.alternate,s!==null&&(a=s.memoizedState)),a!==null)return a.dehydrated}return null}function ur(s){if($t(s)!==s)throw Error(n(188))}function Jr(s){var a=s.alternate;if(!a){if(a=$t(s),a===null)throw Error(n(188));return a!==s?null:s}for(var d=s,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 ur(v),s;if(j===h)return ur(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?s:a}function $r(s){return s=Jr(s),s!==null?fs(s):null}function fs(s){if(s.tag===5||s.tag===6)return s;for(s=s.child;s!==null;){var a=fs(s);if(a!==null)return a;s=s.sibling}return null}var Xr=t.unstable_scheduleCallback,no=t.unstable_cancelCallback,xe=t.unstable_shouldYield,Jn=t.unstable_requestPaint,hn=t.unstable_now,ro=t.unstable_getCurrentPriorityLevel,$i=t.unstable_ImmediatePriority,$s=t.unstable_UserBlockingPriority,hs=t.unstable_NormalPriority,Ks=t.unstable_LowPriority,it=t.unstable_IdlePriority,tn=null,gr=null;function oi(s){if(gr&&typeof gr.onCommitFiberRoot=="function")try{gr.onCommitFiberRoot(tn,s,void 0,(s.current.flags&128)===128)}catch{}}var dr=Math.clz32?Math.clz32:pa,so=Math.log,io=Math.LN2;function pa(s){return s>>>=0,s===0?32:31-(so(s)/io|0)|0}var Fn=64,ms=4194304;function Tn(s){switch(s&-s){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 s&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return s&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return s}}function _s(s,a){var d=s.pendingLanes;if(d===0)return 0;var h=0,v=s.suspendedLanes,j=s.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=s.entangledLanes,a!==0)for(s=s.entanglements,a&=h;0<a;)d=31-dr(a),v=1<<d,h|=s[d],a&=~v;return h}function oo(s,a){switch(s){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(s,a){for(var d=s.suspendedLanes,h=s.pingedLanes,v=s.expirationTimes,j=s.pendingLanes;0<j;){var R=31-dr(j),ee=1<<R,re=v[R];re===-1?((ee&d)===0||(ee&h)!==0)&&(v[R]=oo(ee,a)):re<=a&&(s.expiredLanes|=ee),j&=~ee}}function Zr(s){return s=s.pendingLanes&-1073741825,s!==0?s:s&1073741824?1073741824:0}function fr(){var s=Fn;return Fn<<=1,(Fn&4194240)===0&&(Fn=64),s}function Ys(s){for(var a=[],d=0;31>d;d++)a.push(s);return a}function yr(s,a,d){s.pendingLanes|=a,a!==536870912&&(s.suspendedLanes=0,s.pingedLanes=0),s=s.eventTimes,a=31-dr(a),s[a]=d}function ga(s,a){var d=s.pendingLanes&~a;s.pendingLanes=a,s.suspendedLanes=0,s.pingedLanes=0,s.expiredLanes&=a,s.mutableReadLanes&=a,s.entangledLanes&=a,a=s.entanglements;var h=s.eventTimes;for(s=s.expirationTimes;0<d;){var v=31-dr(d),j=1<<v;a[v]=0,h[v]=-1,s[v]=-1,d&=~j}}function ao(s,a){var d=s.entangledLanes|=a;for(s=s.entanglements;d;){var h=31-dr(d),v=1<<h;v&a|s[h]&a&&(s[h]|=a),d&=~v}}var nn=0;function ml(s){return s&=-s,1<s?4<s?(s&268435455)!==0?16:536870912:4:1}var Ai,ps,Ar,ya,As,ai=!1,Ei=[],Qr=null,Er=null,Es=null,es=new Map,Ti=new Map,gs=[],wr="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(s,a){switch(s){case"focusin":case"focusout":Qr=null;break;case"dragenter":case"dragleave":Er=null;break;case"mouseover":case"mouseout":Es=null;break;case"pointerover":case"pointerout":es.delete(a.pointerId);break;case"gotpointercapture":case"lostpointercapture":Ti.delete(a.pointerId)}}function Ro(s,a,d,h,v,j){return s===null||s.nativeEvent!==j?(s={blockedOn:a,domEventName:d,eventSystemFlags:h,nativeEvent:j,targetContainers:[v]},a!==null&&(a=Aa(a),a!==null&&ps(a)),s):(s.eventSystemFlags|=h,a=s.targetContainers,v!==null&&a.indexOf(v)===-1&&a.push(v),s)}function _l(s,a,d,h,v){switch(a){case"focusin":return Qr=Ro(Qr,s,a,d,h,v),!0;case"dragenter":return Er=Ro(Er,s,a,d,h,v),!0;case"mouseover":return Es=Ro(Es,s,a,d,h,v),!0;case"pointerover":var j=v.pointerId;return es.set(j,Ro(es.get(j)||null,s,a,d,h,v)),!0;case"gotpointercapture":return j=v.pointerId,Ti.set(j,Ro(Ti.get(j)||null,s,a,d,h,v)),!0}return!1}function ts(s){var a=Vo(s.target);if(a!==null){var d=$t(a);if(d!==null){if(a=d.tag,a===13){if(a=cr(d),a!==null){s.blockedOn=a,As(s.priority,function(){Ar(d)});return}}else if(a===3&&d.stateNode.current.memoizedState.isDehydrated){s.blockedOn=d.tag===3?d.stateNode.containerInfo:null;return}}}s.blockedOn=null}function Lo(s){if(s.blockedOn!==null)return!1;for(var a=s.targetContainers;0<a.length;){var d=ae(s.domEventName,s.eventSystemFlags,a[0],s.nativeEvent);if(d===null){d=s.nativeEvent;var h=new d.constructor(d.type,d);Kn=h,d.target.dispatchEvent(h),Kn=null}else return a=Aa(d),a!==null&&ps(a),s.blockedOn=d,!1;a.shift()}return!0}function Js(s,a,d){Lo(s)&&d.delete(a)}function _c(){ai=!1,Qr!==null&&Lo(Qr)&&(Qr=null),Er!==null&&Lo(Er)&&(Er=null),Es!==null&&Lo(Es)&&(Es=null),es.forEach(Js),Ti.forEach(Js)}function ys(s,a){s.blockedOn===a&&(s.blockedOn=null,ai||(ai=!0,t.unstable_scheduleCallback(t.unstable_NormalPriority,_c)))}function lo(s){function a(v){return ys(v,s)}if(0<Ei.length){ys(Ei[0],s);for(var d=1;d<Ei.length;d++){var h=Ei[d];h.blockedOn===s&&(h.blockedOn=null)}}for(Qr!==null&&ys(Qr,s),Er!==null&&ys(Er,s),Es!==null&&ys(Es,s),es.forEach(a),Ti.forEach(a),d=0;d<gs.length;d++)h=gs[d],h.blockedOn===s&&(h.blockedOn=null);for(;0<gs.length&&(d=gs[0],d.blockedOn===null);)ts(d),d.blockedOn===null&&gs.shift()}var zr=M.ReactCurrentBatchConfig,Io=!0;function Po(s,a,d,h){var v=nn,j=zr.transition;zr.transition=null;try{nn=1,co(s,a,d,h)}finally{nn=v,zr.transition=j}}function Oo(s,a,d,h){var v=nn,j=zr.transition;zr.transition=null;try{nn=4,co(s,a,d,h)}finally{nn=v,zr.transition=j}}function co(s,a,d,h){if(Io){var v=ae(s,a,d,h);if(v===null)Pi(s,a,h,U,d),Mi(s,h);else if(_l(v,s,a,d,h))h.stopPropagation();else if(Mi(s,h),a&4&&-1<wr.indexOf(s)){for(;v!==null;){var j=Aa(v);if(j!==null&&Ai(j),j=ae(s,a,d,h),j===null&&Pi(s,a,h,U,d),j===v)break;v=j}v!==null&&h.stopPropagation()}else Pi(s,a,h,null,d)}}var U=null;function ae(s,a,d,h){if(U=null,s=lr(h),s=Vo(s),s!==null)if(a=$t(s),a===null)s=null;else if(d=a.tag,d===13){if(s=cr(a),s!==null)return s;s=null}else if(d===3){if(a.stateNode.current.memoizedState.isDehydrated)return a.tag===3?a.stateNode.containerInfo:null;s=null}else a!==s&&(s=null);return U=s,null}function je(s){switch(s){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 $s:return 4;case hs:case Ks: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 s,a=ke,d=a.length,h,v="value"in Ce?Ce.value:Ce.textContent,j=v.length;for(s=0;s<d&&a[s]===v[s];s++);var R=d-s;for(h=1;h<=R&&a[d-h]===v[j-h];h++);return Ue=v.slice(s,1<h?1-h:void 0)}function ot(s){var a=s.keyCode;return"charCode"in s?(s=s.charCode,s===0&&a===13&&(s=13)):s=a,s===10&&(s=13),32<=s||s===13?s:0}function gt(){return!0}function Ft(){return!1}function Ht(s){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 s)s.hasOwnProperty(ee)&&(d=s[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 vr={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(s){return s.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},Rt=Ht(vr),rn=G({},vr,{view:0,detail:0}),Cn=Ht(rn),mn,er,ns,Xs=G({},rn,{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(s){return s.relatedTarget===void 0?s.fromElement===s.srcElement?s.toElement:s.fromElement:s.relatedTarget},movementX:function(s){return"movementX"in s?s.movementX:(s!==ns&&(ns&&s.type==="mousemove"?(mn=s.screenX-ns.screenX,er=s.screenY-ns.screenY):er=mn=0,ns=s),mn)},movementY:function(s){return"movementY"in s?s.movementY:er}}),Ri=Ht(Xs),wa=G({},Xs,{dataTransfer:0}),$f=Ht(wa),pc=G({},rn,{relatedTarget:0}),pl=Ht(pc),gc=G({},vr,{animationName:0,elapsedTime:0,pseudoElement:0}),yc=Ht(gc),wc=G({},vr,{clipboardData:function(s){return"clipboardData"in s?s.clipboardData:window.clipboardData}}),Af=Ht(wc),Do=G({},vr,{data:0}),Wu=Ht(Do),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(s){var a=this.nativeEvent;return a.getModifierState?a.getModifierState(s):(s=Vu[s])?!!a[s]:!1}function Ku(){return Gu}var Yu=G({},rn,{key:function(s){if(s.key){var a=qu[s.key]||s.key;if(a!=="Unidentified")return a}return s.type==="keypress"?(s=ot(s),s===13?"Enter":String.fromCharCode(s)):s.type==="keydown"||s.type==="keyup"?Hu[s.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:Ku,charCode:function(s){return s.type==="keypress"?ot(s):0},keyCode:function(s){return s.type==="keydown"||s.type==="keyup"?s.keyCode:0},which:function(s){return s.type==="keypress"?ot(s):s.type==="keydown"||s.type==="keyup"?s.keyCode:0}}),Ym=Ht(Yu),Ef=G({},Xs,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),vc=Ht(Ef),en=G({},rn,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:Ku}),Ju=Ht(en),Jm=G({},vr,{propertyName:0,elapsedTime:0,pseudoElement:0}),Xu=Ht(Jm),Xm=G({},Xs,{deltaX:function(s){return"deltaX"in s?s.deltaX:"wheelDeltaX"in s?-s.wheelDeltaX:0},deltaY:function(s){return"deltaY"in s?s.deltaY:"wheelDeltaY"in s?-s.wheelDeltaY:"wheelDelta"in s?-s.wheelDelta:0},deltaZ:0,deltaMode:0}),Zu=Ht(Xm),Zm=[9,13,27,32],tr=c&&"CompositionEvent"in window,Br=null;c&&"documentMode"in document&&(Br=document.documentMode);var gl=c&&"TextEvent"in window&&!Br,Tf=c&&(!tr||Br&&8<Br&&11>=Br),va=" ",xc=!1;function Mf(s,a){switch(s){case"keyup":return Zm.indexOf(a.keyCode)!==-1;case"keydown":return a.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Qu(s){return s=s.detail,typeof s=="object"&&"data"in s?s.data:null}var uo=!1;function ed(s,a){switch(s){case"compositionend":return Qu(a);case"keypress":return a.which!==32?null:(xc=!0,va);case"textInput":return s=a.data,s===va&&xc?null:s;default:return null}}function Rf(s,a){if(uo)return s==="compositionend"||!tr&&Mf(s,a)?(s=ft(),Ue=ke=Ce=null,uo=!1,s):null;switch(s){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 Tf&&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(s){var a=s&&s.nodeName&&s.nodeName.toLowerCase();return a==="input"?!!bc[s.type]:a==="textarea"}function nd(s,a,d,h){Ge(h),a=qo(a,"onChange"),0<a.length&&(d=new Rt("onChange","change",null,d,h),s.push({event:d,listeners:a}))}var yl=null,fo=null;function Lf(s){di(s,0)}function xa(s){var a=_i(s);if(_t(a))return s}function Qm(s,a){if(s==="change")return a}var jc=!1;if(c){var rd;if(c){var Sc="oninput"in document;if(!Sc){var If=document.createElement("div");If.setAttribute("oninput","return;"),Sc=typeof If.oninput=="function"}rd=Sc}else rd=!1;jc=rd&&(!document.documentMode||9<document.documentMode)}function kc(){yl&&(yl.detachEvent("onpropertychange",Pf),fo=yl=null)}function Pf(s){if(s.propertyName==="value"&&xa(fo)){var a=[];nd(a,fo,s,lr(s)),jt(Lf,a)}}function sd(s,a,d){s==="focusin"?(kc(),yl=a,fo=d,yl.attachEvent("onpropertychange",Pf)):s==="focusout"&&kc()}function e_(s){if(s==="selectionchange"||s==="keyup"||s==="keydown")return xa(fo)}function t_(s,a){if(s==="click")return xa(a)}function n_(s,a){if(s==="input"||s==="change")return xa(a)}function ba(s,a){return s===a&&(s!==0||1/s===1/a)||s!==s&&a!==a}var Ts=typeof Object.is=="function"?Object.is:ba;function ho(s,a){if(Ts(s,a))return!0;if(typeof s!="object"||s===null||typeof a!="object"||a===null)return!1;var d=Object.keys(s),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)||!Ts(s[v],a[v]))return!1}return!0}function Of(s){for(;s&&s.firstChild;)s=s.firstChild;return s}function wl(s,a){var d=Of(s);s=0;for(var h;d;){if(d.nodeType===3){if(h=s+d.textContent.length,s<=a&&h>=a)return{node:d,offset:a-s};s=h}e:{for(;d;){if(d.nextSibling){d=d.nextSibling;break e}d=d.parentNode}d=void 0}d=Of(d)}}function Fo(s,a){return s&&a?s===a?!0:s&&s.nodeType===3?!1:a&&a.nodeType===3?Fo(s,a.parentNode):"contains"in s?s.contains(a):s.compareDocumentPosition?!!(s.compareDocumentPosition(a)&16):!1:!1}function ja(){for(var s=window,a=Oe();a instanceof s.HTMLIFrameElement;){try{var d=typeof a.contentWindow.location.href=="string"}catch{d=!1}if(d)s=a.contentWindow;else break;a=Oe(s.document)}return a}function mo(s){var a=s&&s.nodeName&&s.nodeName.toLowerCase();return a&&(a==="input"&&(s.type==="text"||s.type==="search"||s.type==="tel"||s.type==="url"||s.type==="password")||a==="textarea"||s.contentEditable==="true")}function vl(s){var a=ja(),d=s.focusedElem,h=s.selectionRange;if(a!==d&&d&&d.ownerDocument&&Fo(d.ownerDocument.documentElement,d)){if(h!==null&&mo(d)){if(a=h.start,s=h.end,s===void 0&&(s=a),"selectionStart"in d)d.selectionStart=a,d.selectionEnd=Math.min(s,d.value.length);else if(s=(a=d.ownerDocument||document)&&a.defaultView||window,s.getSelection){s=s.getSelection();var v=d.textContent.length,j=Math.min(h.start,v);h=h.end===void 0?j:Math.min(h.end,v),!s.extend&&j>h&&(v=h,h=j,j=v),v=wl(d,j);var R=wl(d,h);v&&R&&(s.rangeCount!==1||s.anchorNode!==v.node||s.anchorOffset!==v.offset||s.focusNode!==R.node||s.focusOffset!==R.offset)&&(a=a.createRange(),a.setStart(v.node,v.offset),s.removeAllRanges(),j>h?(s.addRange(a),s.extend(R.node,R.offset)):(a.setEnd(R.node,R.offset),s.addRange(a)))}}for(a=[],s=d;s=s.parentNode;)s.nodeType===1&&a.push({element:s,left:s.scrollLeft,top:s.scrollTop});for(typeof d.focus=="function"&&d.focus(),d=0;d<a.length;d++)s=a[d],s.element.scrollLeft=s.left,s.element.scrollTop=s.top}}var Nc=c&&"documentMode"in document&&11>=document.documentMode,_o=null,Cc=null,Li=null,$c=!1;function Sa(s,a,d){var h=d.window===d?d.document:d.nodeType===9?d:d.ownerDocument;$c||_o==null||_o!==Oe(h)||(h=_o,"selectionStart"in h&&mo(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&&ho(Li,h)||(Li=h,h=qo(Cc,"onSelect"),0<h.length&&(a=new Rt("onSelect","select",null,a,d),s.push({event:a,listeners:h}),a.target=_o)))}function zo(s,a){var d={};return d[s.toLowerCase()]=a.toLowerCase(),d["Webkit"+s]="webkit"+a,d["Moz"+s]="moz"+a,d}var ka={animationend:zo("Animation","AnimationEnd"),animationiteration:zo("Animation","AnimationIteration"),animationstart:zo("Animation","AnimationStart"),transitionend:zo("Transition","TransitionEnd")},Ac={},Df={};c&&(Df=document.createElement("div").style,"AnimationEvent"in window||(delete ka.animationend.animation,delete ka.animationiteration.animation,delete ka.animationstart.animation),"TransitionEvent"in window||delete ka.transitionend.transition);function Ec(s){if(Ac[s])return Ac[s];if(!ka[s])return s;var a=ka[s],d;for(d in a)if(a.hasOwnProperty(d)&&d in Df)return Ac[s]=a[d];return s}var xl=Ec("animationend"),li=Ec("animationiteration"),Bo=Ec("animationstart"),Ff=Ec("transitionend"),bl=new Map,zf="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(s,a){bl.set(s,a),l(a,[s])}for(var Uo=0;Uo<zf.length;Uo++){var rs=zf[Uo],po=rs.toLowerCase(),Tc=rs[0].toUpperCase()+rs.slice(1);ci(po,"on"+Tc)}ci(xl,"onAnimationEnd"),ci(li,"onAnimationIteration"),ci(Bo,"onAnimationStart"),ci("dblclick","onDoubleClick"),ci("focusin","onFocus"),ci("focusout","onBlur"),ci(Ff,"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 Na(s,a,d){var h=s.type||"unknown-event";s.currentTarget=d,sn(h,a,void 0,s),s.currentTarget=null}function di(s,a){a=(a&4)!==0;for(var d=0;d<s.length;d++){var h=s[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],re=ee.instance,ye=ee.currentTarget;if(ee=ee.listener,re!==j&&v.isPropagationStopped())break e;Na(v,ee,ye),j=re}else for(R=0;R<h.length;R++){if(ee=h[R],re=ee.instance,ye=ee.currentTarget,ee=ee.listener,re!==j&&v.isPropagationStopped())break e;Na(v,ee,ye),j=re}}}if(Pt)throw s=$e,Pt=!1,$e=null,s}function pn(s,a){var d=a[Pc];d===void 0&&(d=a[Pc]=new Set);var h=s+"__bubble";d.has(h)||(Ur(a,s,2,!1),d.add(h))}function Wo(s,a,d){var h=0;a&&(h|=4),Ur(d,s,h,a)}var Ii="_reactListening"+Math.random().toString(36).slice(2);function Ms(s){if(!s[Ii]){s[Ii]=!0,i.forEach(function(d){d!=="selectionchange"&&(id.has(d)||Wo(d,!1,s),Wo(d,!0,s))});var a=s.nodeType===9?s:s.ownerDocument;a===null||a[Ii]||(a[Ii]=!0,Wo("selectionchange",!1,a))}}function Ur(s,a,d,h){switch(je(a)){case 1:var v=Po;break;case 4:v=Oo;break;default:v=co}d=v.bind(null,a,d,s),v=void 0,!dt||a!=="touchstart"&&a!=="touchmove"&&a!=="wheel"||(v=!0),h?v!==void 0?s.addEventListener(a,d,{capture:!0,passive:v}):s.addEventListener(a,d,!0):v!==void 0?s.addEventListener(a,d,{passive:v}):s.addEventListener(a,d,!1)}function Pi(s,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 re=R.tag;if((re===3||re===4)&&(re=R.stateNode.containerInfo,re===v||re.nodeType===8&&re.parentNode===v))return;R=R.return}for(;ee!==null;){if(R=Vo(ee),R===null)return;if(re=R.tag,re===5||re===6){h=j=R;continue e}ee=ee.parentNode}}h=h.return}jt(function(){var ye=j,Me=lr(d),Re=[];e:{var Te=bl.get(s);if(Te!==void 0){var Je=Rt,tt=s;switch(s){case"keypress":if(ot(d)===0)break e;case"keydown":case"keyup":Je=Ym;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=$f;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":Je=Ju;break;case xl:case li:case Bo:Je=yc;break;case Ff:Je=Xu;break;case"scroll":Je=Cn;break;case"wheel":Je=Zu;break;case"copy":case"cut":case"paste":Je=Af;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":Je=vc}var nt=(a&4)!==0,ar=!nt&&s==="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)))),ar)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=s==="mouseover"||s==="pointerover",Je=s==="mouseout"||s==="pointerout",Te&&d!==Kn&&(tt=d.relatedTarget||d.fromElement)&&(Vo(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?Vo(tt):null,tt!==null&&(ar=$t(tt),tt!==ar||tt.tag!==5&&tt.tag!==6)&&(tt=null)):(Je=null,tt=ye),Je!==tt)){if(nt=Ri,Fe="onMouseLeave",de="onMouseEnter",le="mouse",(s==="pointerout"||s==="pointerover")&&(nt=vc,Fe="onPointerLeave",de="onPointerEnter",le="pointer"),ar=Je==null?Te:_i(Je),he=tt==null?Te:_i(tt),Te=new nt(Fe,le+"leave",Je,d,Me),Te.target=ar,Te.relatedTarget=he,Fe=null,Vo(Me)===ye&&(nt=new nt(de,le+"enter",tt,d,Me),nt.target=he,nt.relatedTarget=ar,Fe=nt),ar=Fe,Je&&tt)t:{for(nt=Je,de=tt,le=0,he=nt;he;he=Rs(he))le++;for(he=0,Fe=de;Fe;Fe=Rs(Fe))he++;for(;0<le-he;)nt=Rs(nt),le--;for(;0<he-le;)de=Rs(de),he--;for(;le--;){if(nt===de||de!==null&&nt===de.alternate)break t;nt=Rs(nt),de=Rs(de)}nt=null}else nt=null;Je!==null&&Mc(Re,Te,Je,nt,!1),tt!==null&&ar!==null&&Mc(Re,ar,tt,nt,!0)}}e:{if(Te=ye?_i(ye):window,Je=Te.nodeName&&Te.nodeName.toLowerCase(),Je==="select"||Je==="input"&&Te.type==="file")var st=Qm;else if(td(Te))if(jc)st=n_;else{st=e_;var yt=sd}else(Je=Te.nodeName)&&Je.toLowerCase()==="input"&&(Te.type==="checkbox"||Te.type==="radio")&&(st=t_);if(st&&(st=st(s,ye))){nd(Re,st,d,Me);break e}yt&&yt(s,Te,ye),s==="focusout"&&(yt=Te._wrapperState)&&yt.controlled&&Te.type==="number"&&ct(Te,"number",Te.value)}switch(yt=ye?_i(ye):window,s){case"focusin":(td(yt)||yt.contentEditable==="true")&&(_o=yt,Cc=ye,Li=null);break;case"focusout":Li=Cc=_o=null;break;case"mousedown":$c=!0;break;case"contextmenu":case"mouseup":case"dragend":$c=!1,Sa(Re,d,Me);break;case"selectionchange":if(Nc)break;case"keydown":case"keyup":Sa(Re,d,Me)}var wt;if(tr)e:{switch(s){case"compositionstart":var St="onCompositionStart";break e;case"compositionend":St="onCompositionEnd";break e;case"compositionupdate":St="onCompositionUpdate";break e}St=void 0}else uo?Mf(s,d)&&(St="onCompositionEnd"):s==="keydown"&&d.keyCode===229&&(St="onCompositionStart");St&&(Tf&&d.locale!=="ko"&&(uo||St!=="onCompositionStart"?St==="onCompositionEnd"&&uo&&(wt=ft()):(Ce=Me,ke="value"in Ce?Ce.value:Ce.textContent,uo=!0)),yt=qo(ye,St),0<yt.length&&(St=new Wu(St,s,null,d,Me),Re.push({event:St,listeners:yt}),wt?St.data=wt:(wt=Qu(d),wt!==null&&(St.data=wt)))),(wt=gl?ed(s,d):Rf(s,d))&&(ye=qo(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(s,a,d){return{instance:s,listener:a,currentTarget:d}}function qo(s,a){for(var d=a+"Capture",h=[];s!==null;){var v=s,j=v.stateNode;v.tag===5&&j!==null&&(v=j,j=qt(s,d),j!=null&&h.unshift(fi(s,j,v)),j=qt(s,a),j!=null&&h.push(fi(s,j,v))),s=s.return}return h}function Rs(s){if(s===null)return null;do s=s.return;while(s&&s.tag!==5);return s||null}function Mc(s,a,d,h,v){for(var j=a._reactName,R=[];d!==null&&d!==h;){var ee=d,re=ee.alternate,ye=ee.stateNode;if(re!==null&&re===h)break;ee.tag===5&&ye!==null&&(ee=ye,v?(re=qt(d,j),re!=null&&R.unshift(fi(d,re,ee))):v||(re=qt(d,j),re!=null&&R.push(fi(d,re,ee)))),d=d.return}R.length!==0&&s.push({event:a,listeners:R})}var Rc=/\r\n?/g,hi=/\u0000|\uFFFD/g;function Oi(s){return(typeof s=="string"?s:""+s).replace(Rc,`
38
- `).replace(hi,"")}function ws(s,a,d){if(a=Oi(a),Oi(s)!==a&&d)throw Error(n(425))}function jl(){}var Sl=null,od=null;function Ca(s,a){return s==="textarea"||s==="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(s){return ad.resolve(null).then(s).catch(Bf)}:Lc;function Bf(s){setTimeout(function(){throw s})}function Ic(s,a){var d=a,h=0;do{var v=d.nextSibling;if(s.removeChild(d),v&&v.nodeType===8)if(d=v.data,d==="/$"){if(h===0){s.removeChild(v),lo(a);return}h--}else d!=="$"&&d!=="$?"&&d!=="$!"||h++;d=v}while(d);lo(a)}function Di(s){for(;s!=null;s=s.nextSibling){var a=s.nodeType;if(a===1||a===3)break;if(a===8){if(a=s.data,a==="$"||a==="$!"||a==="$?")break;if(a==="/$")return null}}return s}function Uf(s){s=s.previousSibling;for(var a=0;s;){if(s.nodeType===8){var d=s.data;if(d==="$"||d==="$!"||d==="$?"){if(a===0)return s;a--}else d==="/$"&&a++}s=s.previousSibling}return null}var Ho=Math.random().toString(36).slice(2),mi="__reactFiber$"+Ho,$a="__reactProps$"+Ho,Fi="__reactContainer$"+Ho,Pc="__reactEvents$"+Ho,r_="__reactListeners$"+Ho,Wf="__reactHandles$"+Ho;function Vo(s){var a=s[mi];if(a)return a;for(var d=s.parentNode;d;){if(a=d[Fi]||d[mi]){if(d=a.alternate,a.child!==null||d!==null&&d.child!==null)for(s=Uf(s);s!==null;){if(d=s[mi])return d;s=Uf(s)}return a}s=d,d=s.parentNode}return null}function Aa(s){return s=s[mi]||s[Fi],!s||s.tag!==5&&s.tag!==6&&s.tag!==13&&s.tag!==3?null:s}function _i(s){if(s.tag===5||s.tag===6)return s.stateNode;throw Error(n(33))}function Oc(s){return s[$a]||null}var Go=[],go=-1;function Zs(s){return{current:s}}function Sn(s){0>go||(s.current=Go[go],Go[go]=null,go--)}function on(s,a){go++,Go[go]=s.current,s.current=a}var yo={},nr=Zs(yo),ss=Zs(!1),Ls=yo;function Ea(s,a){var d=s.type.contextTypes;if(!d)return yo;var h=s.stateNode;if(h&&h.__reactInternalMemoizedUnmaskedChildContext===a)return h.__reactInternalMemoizedMaskedChildContext;var v={},j;for(j in d)v[j]=a[j];return h&&(s=s.stateNode,s.__reactInternalMemoizedUnmaskedChildContext=a,s.__reactInternalMemoizedMaskedChildContext=v),v}function xr(s){return s=s.childContextTypes,s!=null}function Dc(){Sn(ss),Sn(nr)}function zi(s,a,d){if(nr.current!==yo)throw Error(n(168));on(nr,a),on(ss,d)}function cd(s,a,d){var h=s.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(s)||"Unknown",v));return G({},d,h)}function wo(s){return s=(s=s.stateNode)&&s.__reactInternalMemoizedMergedChildContext||yo,Ls=nr.current,on(nr,s),on(ss,ss.current),!0}function Ta(s,a,d){var h=s.stateNode;if(!h)throw Error(n(169));d?(s=cd(s,a,Ls),h.__reactInternalMemoizedMergedChildContext=s,Sn(ss),Sn(nr),on(nr,s)):Sn(ss),on(ss,d)}var pi=null,Ma=!1,Ko=!1;function Fc(s){pi===null?pi=[s]:pi.push(s)}function Ra(s){Ma=!0,Fc(s)}function gi(){if(!Ko&&pi!==null){Ko=!0;var s=0,a=nn;try{var d=pi;for(nn=1;s<d.length;s++){var h=d[s];do h=h(!0);while(h!==null)}pi=null,Ma=!1}catch(v){throw pi!==null&&(pi=pi.slice(s+1)),Xr($i,gi),v}finally{nn=a,Ko=!1}}return null}var La=[],vo=0,Nl=null,zc=0,Is=[],br=0,Un=null,Ps=1,Qs="";function Yo(s,a){La[vo++]=zc,La[vo++]=Nl,Nl=s,zc=a}function qf(s,a,d){Is[br++]=Ps,Is[br++]=Qs,Is[br++]=Un,Un=s;var h=Ps;s=Qs;var v=32-dr(h)-1;h&=~(1<<v),d+=1;var j=32-dr(a)+v;if(30<j){var R=v-v%5;j=(h&(1<<R)-1).toString(32),h>>=R,v-=R,Ps=1<<32-dr(a)+v|d<<v|h,Qs=j+s}else Ps=1<<j|d<<v|h,Qs=s}function Cl(s){s.return!==null&&(Yo(s,1),qf(s,1,0))}function ud(s){for(;s===Nl;)Nl=La[--vo],La[vo]=null,zc=La[--vo],La[vo]=null;for(;s===Un;)Un=Is[--br],Is[br]=null,Qs=Is[--br],Is[br]=null,Ps=Is[--br],Is[br]=null}var Tr=null,is=null,vn=!1,Os=null;function dd(s,a){var d=On(5,null,null,0);d.elementType="DELETED",d.stateNode=a,d.return=s,a=s.deletions,a===null?(s.deletions=[d],s.flags|=16):a.push(d)}function Hf(s,a){switch(s.tag){case 5:var d=s.type;return a=a.nodeType!==1||d.toLowerCase()!==a.nodeName.toLowerCase()?null:a,a!==null?(s.stateNode=a,Tr=s,is=Di(a.firstChild),!0):!1;case 6:return a=s.pendingProps===""||a.nodeType!==3?null:a,a!==null?(s.stateNode=a,Tr=s,is=null,!0):!1;case 13:return a=a.nodeType!==8?null:a,a!==null?(d=Un!==null?{id:Ps,overflow:Qs}:null,s.memoizedState={dehydrated:a,treeContext:d,retryLane:1073741824},d=On(18,null,null,0),d.stateNode=a,d.return=s,s.child=d,Tr=s,is=null,!0):!1;default:return!1}}function Bc(s){return(s.mode&1)!==0&&(s.flags&128)===0}function Uc(s){if(vn){var a=is;if(a){var d=a;if(!Hf(s,a)){if(Bc(s))throw Error(n(418));a=Di(d.nextSibling);var h=Tr;a&&Hf(s,a)?dd(h,d):(s.flags=s.flags&-4097|2,vn=!1,Tr=s)}}else{if(Bc(s))throw Error(n(418));s.flags=s.flags&-4097|2,vn=!1,Tr=s}}}function fd(s){for(s=s.return;s!==null&&s.tag!==5&&s.tag!==3&&s.tag!==13;)s=s.return;Tr=s}function Wc(s){if(s!==Tr)return!1;if(!vn)return fd(s),vn=!0,!1;var a;if((a=s.tag!==3)&&!(a=s.tag!==5)&&(a=s.type,a=a!=="head"&&a!=="body"&&!Ca(s.type,s.memoizedProps)),a&&(a=is)){if(Bc(s))throw hd(),Error(n(418));for(;a;)dd(s,a),a=Di(a.nextSibling)}if(fd(s),s.tag===13){if(s=s.memoizedState,s=s!==null?s.dehydrated:null,!s)throw Error(n(317));e:{for(s=s.nextSibling,a=0;s;){if(s.nodeType===8){var d=s.data;if(d==="/$"){if(a===0){is=Di(s.nextSibling);break e}a--}else d!=="$"&&d!=="$!"&&d!=="$?"||a++}s=s.nextSibling}is=null}}else is=Tr?Di(s.stateNode.nextSibling):null;return!0}function hd(){for(var s=is;s;)s=Di(s.nextSibling)}function Bi(){is=Tr=null,vn=!1}function md(s){Os===null?Os=[s]:Os.push(s)}var s_=M.ReactCurrentBatchConfig;function $l(s,a,d){if(s=d.ref,s!==null&&typeof s!="function"&&typeof s!="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,s));var v=h,j=""+s;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 s!="string")throw Error(n(284));if(!d._owner)throw Error(n(290,s))}return s}function qc(s,a){throw s=Object.prototype.toString.call(a),Error(n(31,s==="[object Object]"?"object with keys {"+Object.keys(a).join(", ")+"}":s))}function Hc(s){var a=s._init;return a(s._payload)}function Vf(s){function a(de,le){if(s){var he=de.deletions;he===null?(de.deletions=[le],de.flags|=16):he.push(le)}}function d(de,le){if(!s)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=Ja(de,le),de.index=0,de.sibling=null,de}function j(de,le,he){return de.index=he,s?(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 s&&de.alternate===null&&(de.flags|=2),de}function ee(de,le,he,Fe){return le===null||le.tag!==6?(le=c_(he,de.mode,Fe),le.return=de,le):(le=v(le,he),le.return=de,le)}function re(de,le,he,Fe){var st=he.type;return st===Y?Me(de,le,he.props.children,Fe,he.key):le!==null&&(le.elementType===st||typeof st=="object"&&st!==null&&st.$$typeof===O&&Hc(st)===le.type)?(Fe=v(le,he.props),Fe.ref=$l(de,le,he),Fe.return=de,Fe):(Fe=Ah(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=u_(he,de.mode,Fe),le.return=de,le):(le=v(le,he.children||[]),le.return=de,le)}function Me(de,le,he,Fe,st){return le===null||le.tag!==7?(le=Xl(he,de.mode,Fe,st),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=c_(""+le,de.mode,he),le.return=de,le;if(typeof le=="object"&&le!==null){switch(le.$$typeof){case H:return he=Ah(le.type,le.key,le.props,null,de.mode,he),he.ref=$l(de,null,le),he.return=de,he;case Z:return le=u_(le,de.mode,he),le.return=de,le;case O: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 st=le!==null?le.key:null;if(typeof he=="string"&&he!==""||typeof he=="number")return st!==null?null:ee(de,le,""+he,Fe);if(typeof he=="object"&&he!==null){switch(he.$$typeof){case H:return he.key===st?re(de,le,he,Fe):null;case Z:return he.key===st?ye(de,le,he,Fe):null;case O:return st=he._init,Te(de,le,st(he._payload),Fe)}if(ge(he)||z(he))return st!==null?null:Me(de,le,he,Fe,null);qc(de,he)}return null}function Je(de,le,he,Fe,st){if(typeof Fe=="string"&&Fe!==""||typeof Fe=="number")return de=de.get(he)||null,ee(le,de,""+Fe,st);if(typeof Fe=="object"&&Fe!==null){switch(Fe.$$typeof){case H:return de=de.get(Fe.key===null?he:Fe.key)||null,re(le,de,Fe,st);case Z:return de=de.get(Fe.key===null?he:Fe.key)||null,ye(le,de,Fe,st);case O:var yt=Fe._init;return Je(de,le,he,yt(Fe._payload),st)}if(ge(Fe)||z(Fe))return de=de.get(he)||null,Me(le,de,Fe,st,null);qc(le,Fe)}return null}function tt(de,le,he,Fe){for(var st=null,yt=null,wt=le,St=le=0,Ir=null;wt!==null&&St<he.length;St++){wt.index>St?(Ir=wt,wt=null):Ir=wt.sibling;var dn=Te(de,wt,he[St],Fe);if(dn===null){wt===null&&(wt=Ir);break}s&&wt&&dn.alternate===null&&a(de,wt),le=j(dn,le,St),yt===null?st=dn:yt.sibling=dn,yt=dn,wt=Ir}if(St===he.length)return d(de,wt),vn&&Yo(de,St),st;if(wt===null){for(;St<he.length;St++)wt=Re(de,he[St],Fe),wt!==null&&(le=j(wt,le,St),yt===null?st=wt:yt.sibling=wt,yt=wt);return vn&&Yo(de,St),st}for(wt=h(de,wt);St<he.length;St++)Ir=Je(wt,de,St,he[St],Fe),Ir!==null&&(s&&Ir.alternate!==null&&wt.delete(Ir.key===null?St:Ir.key),le=j(Ir,le,St),yt===null?st=Ir:yt.sibling=Ir,yt=Ir);return s&&wt.forEach(function(Xa){return a(de,Xa)}),vn&&Yo(de,St),st}function nt(de,le,he,Fe){var st=z(he);if(typeof st!="function")throw Error(n(150));if(he=st.call(he),he==null)throw Error(n(151));for(var yt=st=null,wt=le,St=le=0,Ir=null,dn=he.next();wt!==null&&!dn.done;St++,dn=he.next()){wt.index>St?(Ir=wt,wt=null):Ir=wt.sibling;var Xa=Te(de,wt,dn.value,Fe);if(Xa===null){wt===null&&(wt=Ir);break}s&&wt&&Xa.alternate===null&&a(de,wt),le=j(Xa,le,St),yt===null?st=Xa:yt.sibling=Xa,yt=Xa,wt=Ir}if(dn.done)return d(de,wt),vn&&Yo(de,St),st;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?st=dn:yt.sibling=dn,yt=dn);return vn&&Yo(de,St),st}for(wt=h(de,wt);!dn.done;St++,dn=he.next())dn=Je(wt,de,St,dn.value,Fe),dn!==null&&(s&&dn.alternate!==null&&wt.delete(dn.key===null?St:dn.key),le=j(dn,le,St),yt===null?st=dn:yt.sibling=dn,yt=dn);return s&&wt.forEach(function(o0){return a(de,o0)}),vn&&Yo(de,St),st}function ar(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 st=he.key,yt=le;yt!==null;){if(yt.key===st){if(st=he.type,st===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===st||typeof st=="object"&&st!==null&&st.$$typeof===O&&Hc(st)===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=Ah(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=u_(he,de.mode,Fe),le.return=de,de=le}return R(de);case O:return yt=he._init,ar(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=c_(he,de.mode,Fe),le.return=de,de=le),R(de)):d(de,le)}return ar}var xo=Vf(!0),Gf=Vf(!1),Al=Zs(null),Vc=null,bo=null,Pe=null;function rr(){Pe=bo=Vc=null}function Gc(s){var a=Al.current;Sn(Al),s._currentValue=a}function _d(s,a,d){for(;s!==null;){var h=s.alternate;if((s.childLanes&a)!==a?(s.childLanes|=a,h!==null&&(h.childLanes|=a)):h!==null&&(h.childLanes&a)!==a&&(h.childLanes|=a),s===d)break;s=s.return}}function Ia(s,a){Vc=s,Pe=bo=null,s=s.dependencies,s!==null&&s.firstContext!==null&&((s.lanes&a)!==0&&(gn=!0),s.firstContext=null)}function Ds(s){var a=s._currentValue;if(Pe!==s)if(s={context:s,memoizedValue:a,next:null},bo===null){if(Vc===null)throw Error(n(308));bo=s,Vc.dependencies={lanes:0,firstContext:s}}else bo=bo.next=s;return a}var jo=null;function Kc(s){jo===null?jo=[s]:jo.push(s)}function Kf(s,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,Fs(s,h)}function Fs(s,a){s.lanes|=a;var d=s.alternate;for(d!==null&&(d.lanes|=a),d=s,s=s.return;s!==null;)s.childLanes|=a,d=s.alternate,d!==null&&(d.childLanes|=a),d=s,s=s.return;return d.tag===3?d.stateNode:null}var zn=!1;function Xt(s){s.updateQueue={baseState:s.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function jr(s,a){s=s.updateQueue,a.updateQueue===s&&(a.updateQueue={baseState:s.baseState,firstBaseUpdate:s.firstBaseUpdate,lastBaseUpdate:s.lastBaseUpdate,shared:s.shared,effects:s.effects})}function ei(s,a){return{eventTime:s,lane:a,tag:0,payload:null,callback:null,next:null}}function Ui(s,a,d){var h=s.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,Fs(s,d)}return v=h.interleaved,v===null?(a.next=a,Kc(h)):(a.next=v.next,v.next=a),h.interleaved=a,Fs(s,d)}function So(s,a,d){if(a=a.updateQueue,a!==null&&(a=a.shared,(d&4194240)!==0)){var h=a.lanes;h&=s.pendingLanes,d|=h,a.lanes=d,ao(s,d)}}function pd(s,a){var d=s.updateQueue,h=s.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},s.updateQueue=d;return}s=d.lastBaseUpdate,s===null?d.firstBaseUpdate=a:s.next=a,d.lastBaseUpdate=a}function at(s,a,d,h){var v=s.updateQueue;zn=!1;var j=v.firstBaseUpdate,R=v.lastBaseUpdate,ee=v.shared.pending;if(ee!==null){v.shared.pending=null;var re=ee,ye=re.next;re.next=null,R===null?j=ye:R.next=ye,R=re;var Me=s.alternate;Me!==null&&(Me=Me.updateQueue,ee=Me.lastBaseUpdate,ee!==R&&(ee===null?Me.firstBaseUpdate=ye:ee.next=ye,Me.lastBaseUpdate=re))}if(j!==null){var Re=v.baseState;R=0,Me=ye=re=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=s,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&&(s.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,re=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&&(re=Re),v.baseState=re,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);js|=R,s.lanes=R,s.memoizedState=Re}}function Yf(s,a,d){if(s=a.effects,a.effects=null,s!==null)for(a=0;a<s.length;a++){var h=s[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 Jo={},yi=Zs(Jo),El=Zs(Jo),Pa=Zs(Jo);function Xo(s){if(s===Jo)throw Error(n(174));return s}function gd(s,a){switch(on(Pa,a),on(El,s),on(yi,Jo),s=a.nodeType,s){case 9:case 11:a=(a=a.documentElement)?a.namespaceURI:It(null,"");break;default:s=s===8?a.parentNode:a,a=s.namespaceURI||null,s=s.tagName,a=It(a,s)}Sn(yi),on(yi,a)}function Oa(){Sn(yi),Sn(El),Sn(Pa)}function Yc(s){Xo(Pa.current);var a=Xo(yi.current),d=It(a,s.type);a!==d&&(on(El,s),on(yi,d))}function ko(s){El.current===s&&(Sn(yi),Sn(El))}var In=Zs(0);function vs(s){for(var a=s;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===s)break;for(;a.sibling===null;){if(a.return===null||a.return===s)return null;a=a.return}a.sibling.return=a.return,a=a.sibling}return null}var xs=[];function Jc(){for(var s=0;s<xs.length;s++)xs[s]._workInProgressVersionPrimary=null;xs.length=0}var Xc=M.ReactCurrentDispatcher,yd=M.ReactCurrentBatchConfig,Zo=0,Mn=null,Wn=null,hr=null,kn=!1,Da=!1,Qo=0,os=0;function Sr(){throw Error(n(321))}function ea(s,a){if(a===null)return!1;for(var d=0;d<a.length&&d<s.length;d++)if(!Ts(s[d],a[d]))return!1;return!0}function Tl(s,a,d,h,v,j){if(Zo=j,Mn=a,a.memoizedState=null,a.updateQueue=null,a.lanes=0,Xc.current=s===null||s.memoizedState===null?oh:ra,s=d(h,v),Da){j=0;do{if(Da=!1,Qo=0,25<=j)throw Error(n(301));j+=1,hr=Wn=null,a.updateQueue=null,Xc.current=ah,s=d(h,v)}while(Da)}if(Xc.current=Pl,a=Wn!==null&&Wn.next!==null,Zo=0,hr=Wn=Mn=null,kn=!1,a)throw Error(n(300));return s}function ta(){var s=Qo!==0;return Qo=0,s}function zs(){var s={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return hr===null?Mn.memoizedState=hr=s:hr=hr.next=s,hr}function Bs(){if(Wn===null){var s=Mn.alternate;s=s!==null?s.memoizedState:null}else s=Wn.next;var a=hr===null?Mn.memoizedState:hr.next;if(a!==null)hr=a,Wn=s;else{if(s===null)throw Error(n(310));Wn=s,s={memoizedState:Wn.memoizedState,baseState:Wn.baseState,baseQueue:Wn.baseQueue,queue:Wn.queue,next:null},hr===null?Mn.memoizedState=hr=s:hr=hr.next=s}return hr}function Ml(s,a){return typeof a=="function"?a(s):a}function wd(s){var a=Bs(),d=a.queue;if(d===null)throw Error(n(311));d.lastRenderedReducer=s;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,re=null,ye=j;do{var Me=ye.lane;if((Zo&Me)===Me)re!==null&&(re=re.next={lane:0,action:ye.action,hasEagerState:ye.hasEagerState,eagerState:ye.eagerState,next:null}),h=ye.hasEagerState?ye.eagerState:s(h,ye.action);else{var Re={lane:Me,action:ye.action,hasEagerState:ye.hasEagerState,eagerState:ye.eagerState,next:null};re===null?(ee=re=Re,R=h):re=re.next=Re,Mn.lanes|=Me,js|=Me}ye=ye.next}while(ye!==null&&ye!==j);re===null?R=h:re.next=ee,Ts(h,a.memoizedState)||(gn=!0),a.memoizedState=h,a.baseState=R,a.baseQueue=re,d.lastRenderedState=h}if(s=d.interleaved,s!==null){v=s;do j=v.lane,Mn.lanes|=j,js|=j,v=v.next;while(v!==s)}else v===null&&(d.lanes=0);return[a.memoizedState,d.dispatch]}function Rl(s){var a=Bs(),d=a.queue;if(d===null)throw Error(n(311));d.lastRenderedReducer=s;var h=d.dispatch,v=d.pending,j=a.memoizedState;if(v!==null){d.pending=null;var R=v=v.next;do j=s(j,R.action),R=R.next;while(R!==v);Ts(j,a.memoizedState)||(gn=!0),a.memoizedState=j,a.baseQueue===null&&(a.baseState=j),d.lastRenderedState=j}return[j,h]}function Zc(){}function Jf(s,a){var d=Mn,h=Bs(),v=a(),j=!Ts(h.memoizedState,v);if(j&&(h.memoizedState=v,gn=!0),h=h.queue,nu(Us.bind(null,d,h,s),[s]),h.getSnapshot!==a||j||hr!==null&&hr.memoizedState.tag&1){if(d.flags|=2048,Fa(9,Xf.bind(null,d,h,v,a),void 0,null),ir===null)throw Error(n(349));(Zo&30)!==0||Qc(d,a,v)}return v}function Qc(s,a,d){s.flags|=16384,s={getSnapshot:a,value:d},a=Mn.updateQueue,a===null?(a={lastEffect:null,stores:null},Mn.updateQueue=a,a.stores=[s]):(d=a.stores,d===null?a.stores=[s]:d.push(s))}function Xf(s,a,d,h){a.value=d,a.getSnapshot=h,na(a)&&qn(s)}function Us(s,a,d){return d(function(){na(a)&&qn(s)})}function na(s){var a=s.getSnapshot;s=s.value;try{var d=a();return!Ts(s,d)}catch{return!0}}function qn(s){var a=Fs(s,1);a!==null&&qs(a,s,1,-1)}function vd(s){var a=zs();return typeof s=="function"&&(s=s()),a.memoizedState=a.baseState=s,s={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:Ml,lastRenderedState:s},a.queue=s,s=s.dispatch=Il.bind(null,Mn,s),[a.memoizedState,s]}function Fa(s,a,d,h){return s={tag:s,create:a,destroy:d,deps:h,next:null},a=Mn.updateQueue,a===null?(a={lastEffect:null,stores:null},Mn.updateQueue=a,a.lastEffect=s.next=s):(d=a.lastEffect,d===null?a.lastEffect=s.next=s:(h=d.next,d.next=s,s.next=h,a.lastEffect=s)),s}function Zf(){return Bs().memoizedState}function eu(s,a,d,h){var v=zs();Mn.flags|=s,v.memoizedState=Fa(1|a,d,void 0,h===void 0?null:h)}function tu(s,a,d,h){var v=Bs();h=h===void 0?null:h;var j=void 0;if(Wn!==null){var R=Wn.memoizedState;if(j=R.destroy,h!==null&&ea(h,R.deps)){v.memoizedState=Fa(a,d,j,h);return}}Mn.flags|=s,v.memoizedState=Fa(1|a,d,j,h)}function xd(s,a){return eu(8390656,8,s,a)}function nu(s,a){return tu(2048,8,s,a)}function Qf(s,a){return tu(4,2,s,a)}function eh(s,a){return tu(4,4,s,a)}function Jt(s,a){if(typeof a=="function")return s=s(),a(s),function(){a(null)};if(a!=null)return s=s(),a.current=s,function(){a.current=null}}function Pn(s,a,d){return d=d!=null?d.concat([s]):null,tu(4,4,Jt.bind(null,a,s),d)}function Wr(){}function ru(s,a){var d=Bs();a=a===void 0?null:a;var h=d.memoizedState;return h!==null&&a!==null&&ea(a,h[1])?h[0]:(d.memoizedState=[s,a],s)}function Ll(s,a){var d=Bs();a=a===void 0?null:a;var h=d.memoizedState;return h!==null&&a!==null&&ea(a,h[1])?h[0]:(s=s(),d.memoizedState=[s,a],s)}function bd(s,a,d){return(Zo&21)===0?(s.baseState&&(s.baseState=!1,gn=!0),s.memoizedState=d):(Ts(d,a)||(d=fr(),Mn.lanes|=d,js|=d,s.baseState=!0),a)}function i_(s,a){var d=nn;nn=d!==0&&4>d?d:4,s(!0);var h=yd.transition;yd.transition={};try{s(!1),a()}finally{nn=d,yd.transition=h}}function th(){return Bs().memoizedState}function nh(s,a,d){var h=Gi(s);if(d={lane:h,action:d,hasEagerState:!1,eagerState:null,next:null},rh(s))sh(a,d);else if(d=Kf(s,a,d,h),d!==null){var v=Lr();qs(d,s,h,v),ih(d,a,h)}}function Il(s,a,d){var h=Gi(s),v={lane:h,action:d,hasEagerState:!1,eagerState:null,next:null};if(rh(s))sh(a,v);else{var j=s.alternate;if(s.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,Ts(ee,R)){var re=a.interleaved;re===null?(v.next=v,Kc(a)):(v.next=re.next,re.next=v),a.interleaved=v;return}}catch{}finally{}d=Kf(s,a,v,h),d!==null&&(v=Lr(),qs(d,s,h,v),ih(d,a,h))}}function rh(s){var a=s.alternate;return s===Mn||a!==null&&a===Mn}function sh(s,a){Da=kn=!0;var d=s.pending;d===null?a.next=a:(a.next=d.next,d.next=a),s.pending=a}function ih(s,a,d){if((d&4194240)!==0){var h=a.lanes;h&=s.pendingLanes,d|=h,a.lanes=d,ao(s,d)}}var Pl={readContext:Ds,useCallback:Sr,useContext:Sr,useEffect:Sr,useImperativeHandle:Sr,useInsertionEffect:Sr,useLayoutEffect:Sr,useMemo:Sr,useReducer:Sr,useRef:Sr,useState:Sr,useDebugValue:Sr,useDeferredValue:Sr,useTransition:Sr,useMutableSource:Sr,useSyncExternalStore:Sr,useId:Sr,unstable_isNewReconciler:!1},oh={readContext:Ds,useCallback:function(s,a){return zs().memoizedState=[s,a===void 0?null:a],s},useContext:Ds,useEffect:xd,useImperativeHandle:function(s,a,d){return d=d!=null?d.concat([s]):null,eu(4194308,4,Jt.bind(null,a,s),d)},useLayoutEffect:function(s,a){return eu(4194308,4,s,a)},useInsertionEffect:function(s,a){return eu(4,2,s,a)},useMemo:function(s,a){var d=zs();return a=a===void 0?null:a,s=s(),d.memoizedState=[s,a],s},useReducer:function(s,a,d){var h=zs();return a=d!==void 0?d(a):a,h.memoizedState=h.baseState=a,s={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:s,lastRenderedState:a},h.queue=s,s=s.dispatch=nh.bind(null,Mn,s),[h.memoizedState,s]},useRef:function(s){var a=zs();return s={current:s},a.memoizedState=s},useState:vd,useDebugValue:Wr,useDeferredValue:function(s){return zs().memoizedState=s},useTransition:function(){var s=vd(!1),a=s[0];return s=i_.bind(null,s[1]),zs().memoizedState=s,[a,s]},useMutableSource:function(){},useSyncExternalStore:function(s,a,d){var h=Mn,v=zs();if(vn){if(d===void 0)throw Error(n(407));d=d()}else{if(d=a(),ir===null)throw Error(n(349));(Zo&30)!==0||Qc(h,a,d)}v.memoizedState=d;var j={value:d,getSnapshot:a};return v.queue=j,xd(Us.bind(null,h,j,s),[s]),h.flags|=2048,Fa(9,Xf.bind(null,h,j,d,a),void 0,null),d},useId:function(){var s=zs(),a=ir.identifierPrefix;if(vn){var d=Qs,h=Ps;d=(h&~(1<<32-dr(h)-1)).toString(32)+d,a=":"+a+"R"+d,d=Qo++,0<d&&(a+="H"+d.toString(32)),a+=":"}else d=os++,a=":"+a+"r"+d.toString(32)+":";return s.memoizedState=a},unstable_isNewReconciler:!1},ra={readContext:Ds,useCallback:ru,useContext:Ds,useEffect:nu,useImperativeHandle:Pn,useInsertionEffect:Qf,useLayoutEffect:eh,useMemo:Ll,useReducer:wd,useRef:Zf,useState:function(){return wd(Ml)},useDebugValue:Wr,useDeferredValue:function(s){var a=Bs();return bd(a,Wn.memoizedState,s)},useTransition:function(){var s=wd(Ml)[0],a=Bs().memoizedState;return[s,a]},useMutableSource:Zc,useSyncExternalStore:Jf,useId:th,unstable_isNewReconciler:!1},ah={readContext:Ds,useCallback:ru,useContext:Ds,useEffect:nu,useImperativeHandle:Pn,useInsertionEffect:Qf,useLayoutEffect:eh,useMemo:Ll,useReducer:Rl,useRef:Zf,useState:function(){return Rl(Ml)},useDebugValue:Wr,useDeferredValue:function(s){var a=Bs();return Wn===null?a.memoizedState=s:bd(a,Wn.memoizedState,s)},useTransition:function(){var s=Rl(Ml)[0],a=Bs().memoizedState;return[s,a]},useMutableSource:Zc,useSyncExternalStore:Jf,useId:th,unstable_isNewReconciler:!1};function Ws(s,a){if(s&&s.defaultProps){a=G({},a),s=s.defaultProps;for(var d in s)a[d]===void 0&&(a[d]=s[d]);return a}return a}function su(s,a,d,h){a=s.memoizedState,d=d(h,a),d=d==null?a:G({},a,d),s.memoizedState=d,s.lanes===0&&(s.updateQueue.baseState=d)}var Ol={isMounted:function(s){return(s=s._reactInternals)?$t(s)===s:!1},enqueueSetState:function(s,a,d){s=s._reactInternals;var h=Lr(),v=Gi(s),j=ei(h,v);j.payload=a,d!=null&&(j.callback=d),a=Ui(s,j,v),a!==null&&(qs(a,s,v,h),So(a,s,v))},enqueueReplaceState:function(s,a,d){s=s._reactInternals;var h=Lr(),v=Gi(s),j=ei(h,v);j.tag=1,j.payload=a,d!=null&&(j.callback=d),a=Ui(s,j,v),a!==null&&(qs(a,s,v,h),So(a,s,v))},enqueueForceUpdate:function(s,a){s=s._reactInternals;var d=Lr(),h=Gi(s),v=ei(d,h);v.tag=2,a!=null&&(v.callback=a),a=Ui(s,v,h),a!==null&&(qs(a,s,h,d),So(a,s,h))}};function lh(s,a,d,h,v,j,R){return s=s.stateNode,typeof s.shouldComponentUpdate=="function"?s.shouldComponentUpdate(h,j,R):a.prototype&&a.prototype.isPureReactComponent?!ho(d,h)||!ho(v,j):!0}function ch(s,a,d){var h=!1,v=yo,j=a.contextType;return typeof j=="object"&&j!==null?j=Ds(j):(v=xr(a)?Ls:nr.current,h=a.contextTypes,j=(h=h!=null)?Ea(s,v):yo),a=new a(d,j),s.memoizedState=a.state!==null&&a.state!==void 0?a.state:null,a.updater=Ol,s.stateNode=a,a._reactInternals=s,h&&(s=s.stateNode,s.__reactInternalMemoizedUnmaskedChildContext=v,s.__reactInternalMemoizedMaskedChildContext=j),a}function uh(s,a,d,h){s=a.state,typeof a.componentWillReceiveProps=="function"&&a.componentWillReceiveProps(d,h),typeof a.UNSAFE_componentWillReceiveProps=="function"&&a.UNSAFE_componentWillReceiveProps(d,h),a.state!==s&&Ol.enqueueReplaceState(a,a.state,null)}function jd(s,a,d,h){var v=s.stateNode;v.props=d,v.state=s.memoizedState,v.refs={},Xt(s);var j=a.contextType;typeof j=="object"&&j!==null?v.context=Ds(j):(j=xr(a)?Ls:nr.current,v.context=Ea(s,j)),v.state=s.memoizedState,j=a.getDerivedStateFromProps,typeof j=="function"&&(su(s,a,j,d),v.state=s.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&&Ol.enqueueReplaceState(v,v.state,null),at(s,d,v,h),v.state=s.memoizedState),typeof v.componentDidMount=="function"&&(s.flags|=4194308)}function za(s,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:s,source:a,stack:v,digest:null}}function Sd(s,a,d){return{value:s,source:null,stack:d??null,digest:a??null}}function kd(s,a){try{console.error(a.value)}catch(d){setTimeout(function(){throw d})}}var dh=typeof WeakMap=="function"?WeakMap:Map;function iu(s,a,d){d=ei(-1,d),d.tag=3,d.payload={element:null};var h=a.value;return d.callback=function(){du||(du=!0,oa=h),kd(s,a)},d}function fh(s,a,d){d=ei(-1,d),d.tag=3;var h=s.type.getDerivedStateFromError;if(typeof h=="function"){var v=a.value;d.payload=function(){return h(v)},d.callback=function(){kd(s,a)}}var j=s.stateNode;return j!==null&&typeof j.componentDidCatch=="function"&&(d.callback=function(){kd(s,a),typeof h!="function"&&(Co===null?Co=new Set([this]):Co.add(this));var R=a.stack;this.componentDidCatch(a.value,{componentStack:R!==null?R:""})}),d}function hh(s,a,d){var h=s.pingCache;if(h===null){h=s.pingCache=new dh;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),s=ln.bind(null,s,a,d),a.then(s,s))}function Dl(s){do{var a;if((a=s.tag===13)&&(a=s.memoizedState,a=a!==null?a.dehydrated!==null:!0),a)return s;s=s.return}while(s!==null);return null}function mh(s,a,d,h,v){return(s.mode&1)===0?(s===a?s.flags|=65536:(s.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),s):(s.flags|=65536,s.lanes=v,s)}var sa=M.ReactCurrentOwner,gn=!1;function an(s,a,d,h){a.child=s===null?Gf(a,null,d,h):xo(a,s.child,d,h)}function ti(s,a,d,h,v){d=d.render;var j=a.ref;return Ia(a,v),h=Tl(s,a,d,h,j,v),d=ta(),s!==null&&!gn?(a.updateQueue=s.updateQueue,a.flags&=-2053,s.lanes&=~v,wi(s,a,v)):(vn&&d&&Cl(a),a.flags|=1,an(s,a,h,v),a.child)}function Wi(s,a,d,h,v){if(s===null){var j=d.type;return typeof j=="function"&&!Ss(j)&&j.defaultProps===void 0&&d.compare===null&&d.defaultProps===void 0?(a.tag=15,a.type=j,qi(s,a,j,h,v)):(s=Ah(d.type,null,h,a,a.mode,v),s.ref=a.ref,s.return=a,a.child=s)}if(j=s.child,(s.lanes&v)===0){var R=j.memoizedProps;if(d=d.compare,d=d!==null?d:ho,d(R,h)&&s.ref===a.ref)return wi(s,a,v)}return a.flags|=1,s=Ja(j,h),s.ref=a.ref,s.return=a,a.child=s}function qi(s,a,d,h,v){if(s!==null){var j=s.memoizedProps;if(ho(j,h)&&s.ref===a.ref)if(gn=!1,a.pendingProps=h=j,(s.lanes&v)!==0)(s.flags&131072)!==0&&(gn=!0);else return a.lanes=s.lanes,wi(s,a,v)}return Ba(s,a,d,h,v)}function ni(s,a,d){var h=a.pendingProps,v=h.children,j=s!==null?s.memoizedState:null;if(h.mode==="hidden")if((a.mode&1)===0)a.memoizedState={baseLanes:0,cachePool:null,transitions:null},on(Va,Zn),Zn|=d;else{if((d&1073741824)===0)return s=j!==null?j.baseLanes|d:d,a.lanes=a.childLanes=1073741824,a.memoizedState={baseLanes:s,cachePool:null,transitions:null},a.updateQueue=null,on(Va,Zn),Zn|=s,null;a.memoizedState={baseLanes:0,cachePool:null,transitions:null},h=j!==null?j.baseLanes:d,on(Va,Zn),Zn|=h}else j!==null?(h=j.baseLanes|d,a.memoizedState=null):h=d,on(Va,Zn),Zn|=h;return an(s,a,v,d),a.child}function _h(s,a){var d=a.ref;(s===null&&d!==null||s!==null&&s.ref!==d)&&(a.flags|=512,a.flags|=2097152)}function Ba(s,a,d,h,v){var j=xr(d)?Ls:nr.current;return j=Ea(a,j),Ia(a,v),d=Tl(s,a,d,h,j,v),h=ta(),s!==null&&!gn?(a.updateQueue=s.updateQueue,a.flags&=-2053,s.lanes&=~v,wi(s,a,v)):(vn&&h&&Cl(a),a.flags|=1,an(s,a,d,v),a.child)}function ph(s,a,d,h,v){if(xr(d)){var j=!0;wo(a)}else j=!1;if(Ia(a,v),a.stateNode===null)ia(s,a),ch(a,d,h),jd(a,d,h,v),h=!0;else if(s===null){var R=a.stateNode,ee=a.memoizedProps;R.props=ee;var re=R.context,ye=d.contextType;typeof ye=="object"&&ye!==null?ye=Ds(ye):(ye=xr(d)?Ls:nr.current,ye=Ea(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||re!==ye)&&uh(a,R,h,ye),zn=!1;var Te=a.memoizedState;R.state=Te,at(a,h,R,v),re=a.memoizedState,ee!==h||Te!==re||ss.current||zn?(typeof Me=="function"&&(su(a,d,Me,h),re=a.memoizedState),(ee=zn||lh(a,d,ee,h,Te,re,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=re),R.props=h,R.state=re,R.context=ye,h=ee):(typeof R.componentDidMount=="function"&&(a.flags|=4194308),h=!1)}else{R=a.stateNode,jr(s,a),ee=a.memoizedProps,ye=a.type===a.elementType?ee:Ws(a.type,ee),R.props=ye,Re=a.pendingProps,Te=R.context,re=d.contextType,typeof re=="object"&&re!==null?re=Ds(re):(re=xr(d)?Ls:nr.current,re=Ea(a,re));var Je=d.getDerivedStateFromProps;(Me=typeof Je=="function"||typeof R.getSnapshotBeforeUpdate=="function")||typeof R.UNSAFE_componentWillReceiveProps!="function"&&typeof R.componentWillReceiveProps!="function"||(ee!==Re||Te!==re)&&uh(a,R,h,re),zn=!1,Te=a.memoizedState,R.state=Te,at(a,h,R,v);var tt=a.memoizedState;ee!==Re||Te!==tt||ss.current||zn?(typeof Je=="function"&&(su(a,d,Je,h),tt=a.memoizedState),(ye=zn||lh(a,d,ye,h,Te,tt,re)||!1)?(Me||typeof R.UNSAFE_componentWillUpdate!="function"&&typeof R.componentWillUpdate!="function"||(typeof R.componentWillUpdate=="function"&&R.componentWillUpdate(h,tt,re),typeof R.UNSAFE_componentWillUpdate=="function"&&R.UNSAFE_componentWillUpdate(h,tt,re)),typeof R.componentDidUpdate=="function"&&(a.flags|=4),typeof R.getSnapshotBeforeUpdate=="function"&&(a.flags|=1024)):(typeof R.componentDidUpdate!="function"||ee===s.memoizedProps&&Te===s.memoizedState||(a.flags|=4),typeof R.getSnapshotBeforeUpdate!="function"||ee===s.memoizedProps&&Te===s.memoizedState||(a.flags|=1024),a.memoizedProps=h,a.memoizedState=tt),R.props=h,R.state=tt,R.context=re,h=ye):(typeof R.componentDidUpdate!="function"||ee===s.memoizedProps&&Te===s.memoizedState||(a.flags|=4),typeof R.getSnapshotBeforeUpdate!="function"||ee===s.memoizedProps&&Te===s.memoizedState||(a.flags|=1024),h=!1)}return Fl(s,a,d,h,j,v)}function Fl(s,a,d,h,v,j){_h(s,a);var R=(a.flags&128)!==0;if(!h&&!R)return v&&Ta(a,d,!1),wi(s,a,j);h=a.stateNode,sa.current=a;var ee=R&&typeof d.getDerivedStateFromError!="function"?null:h.render();return a.flags|=1,s!==null&&R?(a.child=xo(a,s.child,null,j),a.child=xo(a,null,ee,j)):an(s,a,ee,j),a.memoizedState=h.state,v&&Ta(a,d,!0),a.child}function gh(s){var a=s.stateNode;a.pendingContext?zi(s,a.pendingContext,a.pendingContext!==a.context):a.context&&zi(s,a.context,!1),gd(s,a.containerInfo)}function yh(s,a,d,h,v){return Bi(),md(v),a.flags|=256,an(s,a,d,h),a.child}var ou={dehydrated:null,treeContext:null,retryLane:0};function Hi(s){return{baseLanes:s,cachePool:null,transitions:null}}function Ua(s,a,d){var h=a.pendingProps,v=In.current,j=!1,R=(a.flags&128)!==0,ee;if((ee=R)||(ee=s!==null&&s.memoizedState===null?!1:(v&2)!==0),ee?(j=!0,a.flags&=-129):(s===null||s.memoizedState!==null)&&(v|=1),on(In,v&1),s===null)return Uc(a),s=a.memoizedState,s!==null&&(s=s.dehydrated,s!==null)?((a.mode&1)===0?a.lanes=1:s.data==="$!"?a.lanes=8:a.lanes=1073741824,null):(R=h.children,s=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=Eh(R,h,0,null),s=Xl(s,h,d,null),j.return=a,s.return=a,j.sibling=s,a.child=j,a.child.memoizedState=Hi(d),a.memoizedState=ou,s):au(a,R));if(v=s.memoizedState,v!==null&&(ee=v.dehydrated,ee!==null))return o_(s,a,R,h,ee,v,d);if(j){j=h.fallback,R=a.mode,v=s.child,ee=v.sibling;var re={mode:"hidden",children:h.children};return(R&1)===0&&a.child!==v?(h=a.child,h.childLanes=0,h.pendingProps=re,a.deletions=null):(h=Ja(v,re),h.subtreeFlags=v.subtreeFlags&14680064),ee!==null?j=Ja(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=s.child.memoizedState,R=R===null?Hi(d):{baseLanes:R.baseLanes|d,cachePool:null,transitions:R.transitions},j.memoizedState=R,j.childLanes=s.childLanes&~d,a.memoizedState=ou,h}return j=s.child,s=j.sibling,h=Ja(j,{mode:"visible",children:h.children}),(a.mode&1)===0&&(h.lanes=d),h.return=a,h.sibling=null,s!==null&&(d=a.deletions,d===null?(a.deletions=[s],a.flags|=16):d.push(s)),a.child=h,a.memoizedState=null,h}function au(s,a){return a=Eh({mode:"visible",children:a},s.mode,0,null),a.return=s,s.child=a}function zl(s,a,d,h){return h!==null&&md(h),xo(a,s.child,null,d),s=au(a,a.pendingProps.children),s.flags|=2,a.memoizedState=null,s}function o_(s,a,d,h,v,j,R){if(d)return a.flags&256?(a.flags&=-257,h=Sd(Error(n(422))),zl(s,a,R,h)):a.memoizedState!==null?(a.child=s.child,a.flags|=128,null):(j=h.fallback,v=a.mode,h=Eh({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&&xo(a,s.child,null,R),a.child.memoizedState=Hi(R),a.memoizedState=ou,j);if((a.mode&1)===0)return zl(s,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(s,a,R,h)}if(ee=(R&s.childLanes)!==0,gn||ee){if(h=ir,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,Fs(s,v),qs(h,s,v,-1))}return W(),h=Sd(Error(n(421))),zl(s,a,R,h)}return v.data==="$?"?(a.flags|=128,a.child=s.child,a=He.bind(null,s),v._reactRetry=a,null):(s=j.treeContext,is=Di(v.nextSibling),Tr=a,vn=!0,Os=null,s!==null&&(Is[br++]=Ps,Is[br++]=Qs,Is[br++]=Un,Ps=s.id,Qs=s.overflow,Un=a),a=au(a,h.children),a.flags|=4096,a)}function Nd(s,a,d){s.lanes|=a;var h=s.alternate;h!==null&&(h.lanes|=a),_d(s.return,a,d)}function No(s,a,d,h,v){var j=s.memoizedState;j===null?s.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 wh(s,a,d){var h=a.pendingProps,v=h.revealOrder,j=h.tail;if(an(s,a,h.children,d),h=In.current,(h&2)!==0)h=h&1|2,a.flags|=128;else{if(s!==null&&(s.flags&128)!==0)e:for(s=a.child;s!==null;){if(s.tag===13)s.memoizedState!==null&&Nd(s,d,a);else if(s.tag===19)Nd(s,d,a);else if(s.child!==null){s.child.return=s,s=s.child;continue}if(s===a)break e;for(;s.sibling===null;){if(s.return===null||s.return===a)break e;s=s.return}s.sibling.return=s.return,s=s.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;)s=d.alternate,s!==null&&vs(s)===null&&(v=d),d=d.sibling;d=v,d===null?(v=a.child,a.child=null):(v=d.sibling,d.sibling=null),No(a,!1,v,d,j);break;case"backwards":for(d=null,v=a.child,a.child=null;v!==null;){if(s=v.alternate,s!==null&&vs(s)===null){a.child=v;break}s=v.sibling,v.sibling=d,d=v,v=s}No(a,!0,d,null,j);break;case"together":No(a,!1,null,null,void 0);break;default:a.memoizedState=null}return a.child}function ia(s,a){(a.mode&1)===0&&s!==null&&(s.alternate=null,a.alternate=null,a.flags|=2)}function wi(s,a,d){if(s!==null&&(a.dependencies=s.dependencies),js|=a.lanes,(d&a.childLanes)===0)return null;if(s!==null&&a.child!==s.child)throw Error(n(153));if(a.child!==null){for(s=a.child,d=Ja(s,s.pendingProps),a.child=d,d.return=a;s.sibling!==null;)s=s.sibling,d=d.sibling=Ja(s,s.pendingProps),d.return=a;d.sibling=null}return a.child}function a_(s,a,d){switch(a.tag){case 3:gh(a),Bi();break;case 5:Yc(a);break;case 1:xr(a.type)&&wo(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?Ua(s,a,d):(on(In,In.current&1),s=wi(s,a,d),s!==null?s.sibling:null);on(In,In.current&1);break;case 19:if(h=(d&a.childLanes)!==0,(s.flags&128)!==0){if(h)return wh(s,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(s,a,d)}return wi(s,a,d)}var lu,Cd,vh,xh;lu=function(s,a){for(var d=a.child;d!==null;){if(d.tag===5||d.tag===6)s.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(){},vh=function(s,a,d,h){var v=s.memoizedProps;if(v!==h){s=a.stateNode,Xo(yi.current);var j=null;switch(d){case"input":v=et(s,v),h=et(s,h),j=[];break;case"select":v=G({},v,{value:void 0}),h=G({},h,{value:void 0}),j=[];break;case"textarea":v=Ke(s,v),h=Ke(s,h),j=[];break;default:typeof v.onClick!="function"&&typeof h.onClick=="function"&&(s.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 re=h[ye];if(ee=v!=null?v[ye]:void 0,h.hasOwnProperty(ye)&&re!==ee&&(re!=null||ee!=null))if(ye==="style")if(ee){for(R in ee)!ee.hasOwnProperty(R)||re&&re.hasOwnProperty(R)||(d||(d={}),d[R]="");for(R in re)re.hasOwnProperty(R)&&ee[R]!==re[R]&&(d||(d={}),d[R]=re[R])}else d||(j||(j=[]),j.push(ye,d)),d=re;else ye==="dangerouslySetInnerHTML"?(re=re?re.__html:void 0,ee=ee?ee.__html:void 0,re!=null&&ee!==re&&(j=j||[]).push(ye,re)):ye==="children"?typeof re!="string"&&typeof re!="number"||(j=j||[]).push(ye,""+re):ye!=="suppressContentEditableWarning"&&ye!=="suppressHydrationWarning"&&(o.hasOwnProperty(ye)?(re!=null&&ye==="onScroll"&&pn("scroll",s),j||ee===re||(j=[])):(j=j||[]).push(ye,re))}d&&(j=j||[]).push("style",d);var ye=j;(a.updateQueue=ye)&&(a.flags|=4)}},xh=function(s,a,d,h){d!==h&&(a.flags|=4)};function kr(s,a){if(!vn)switch(s.tailMode){case"hidden":a=s.tail;for(var d=null;a!==null;)a.alternate!==null&&(d=a),a=a.sibling;d===null?s.tail=null:d.sibling=null;break;case"collapsed":d=s.tail;for(var h=null;d!==null;)d.alternate!==null&&(h=d),d=d.sibling;h===null?a||s.tail===null?s.tail=null:s.tail.sibling=null:h.sibling=null}}function Hn(s){var a=s.alternate!==null&&s.alternate.child===s.child,d=0,h=0;if(a)for(var v=s.child;v!==null;)d|=v.lanes|v.childLanes,h|=v.subtreeFlags&14680064,h|=v.flags&14680064,v.return=s,v=v.sibling;else for(v=s.child;v!==null;)d|=v.lanes|v.childLanes,h|=v.subtreeFlags,h|=v.flags,v.return=s,v=v.sibling;return s.subtreeFlags|=h,s.childLanes=d,a}function l_(s,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 xr(a.type)&&Dc(),Hn(a),null;case 3:return h=a.stateNode,Oa(),Sn(ss),Sn(nr),Jc(),h.pendingContext&&(h.context=h.pendingContext,h.pendingContext=null),(s===null||s.child===null)&&(Wc(a)?a.flags|=4:s===null||s.memoizedState.isDehydrated&&(a.flags&256)===0||(a.flags|=1024,Os!==null&&(mu(Os),Os=null))),Cd(s,a),Hn(a),null;case 5:ko(a);var v=Xo(Pa.current);if(d=a.type,s!==null&&a.stateNode!=null)vh(s,a,d,h,v),s.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(s=Xo(yi.current),Wc(a)){h=a.stateNode,d=a.type;var j=a.memoizedProps;switch(h[mi]=a,h[$a]=j,s=(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&&ws(h.textContent,ee,s),v=["children",ee]):typeof ee=="number"&&h.textContent!==""+ee&&(j.suppressHydrationWarning!==!0&&ws(h.textContent,ee,s),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,s==="http://www.w3.org/1999/xhtml"&&(s=Ut(d)),s==="http://www.w3.org/1999/xhtml"?d==="script"?(s=R.createElement("div"),s.innerHTML="<script><\/script>",s=s.removeChild(s.firstChild)):typeof h.is=="string"?s=R.createElement(d,{is:h.is}):(s=R.createElement(d),d==="select"&&(R=s,h.multiple?R.multiple=!0:h.size&&(R.size=h.size))):s=R.createElementNS(s,d),s[mi]=a,s[$a]=h,lu(s,a,!1,!1),a.stateNode=s;e:{switch(R=Cr(d,h),d){case"dialog":pn("cancel",s),pn("close",s),v=h;break;case"iframe":case"object":case"embed":pn("load",s),v=h;break;case"video":case"audio":for(v=0;v<ui.length;v++)pn(ui[v],s);v=h;break;case"source":pn("error",s),v=h;break;case"img":case"image":case"link":pn("error",s),pn("load",s),v=h;break;case"details":pn("toggle",s),v=h;break;case"input":lt(s,h),v=et(s,h),pn("invalid",s);break;case"option":v=h;break;case"select":s._wrapperState={wasMultiple:!!h.multiple},v=G({},h,{value:void 0}),pn("invalid",s);break;case"textarea":Dt(s,h),v=Ke(s,h),pn("invalid",s);break;default:v=h}wn(d,v),ee=v;for(j in ee)if(ee.hasOwnProperty(j)){var re=ee[j];j==="style"?jn(s,re):j==="dangerouslySetInnerHTML"?(re=re?re.__html:void 0,re!=null&&Bn(s,re)):j==="children"?typeof re=="string"?(d!=="textarea"||re!=="")&&Mt(s,re):typeof re=="number"&&Mt(s,""+re):j!=="suppressContentEditableWarning"&&j!=="suppressHydrationWarning"&&j!=="autoFocus"&&(o.hasOwnProperty(j)?re!=null&&j==="onScroll"&&pn("scroll",s):re!=null&&D(s,j,re,R))}switch(d){case"input":We(s),Le(s,h,!1);break;case"textarea":We(s),_n(s);break;case"option":h.value!=null&&s.setAttribute("value",""+we(h.value));break;case"select":s.multiple=!!h.multiple,j=h.value,j!=null?De(s,!!h.multiple,j,!1):h.defaultValue!=null&&De(s,!!h.multiple,h.defaultValue,!0);break;default:typeof v.onClick=="function"&&(s.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(s&&a.stateNode!=null)xh(s,a,s.memoizedProps,h);else{if(typeof h!="string"&&a.stateNode===null)throw Error(n(166));if(d=Xo(Pa.current),Xo(yi.current),Wc(a)){if(h=a.stateNode,d=a.memoizedProps,h[mi]=a,(j=h.nodeValue!==d)&&(s=Tr,s!==null))switch(s.tag){case 3:ws(h.nodeValue,d,(s.mode&1)!==0);break;case 5:s.memoizedProps.suppressHydrationWarning!==!0&&ws(h.nodeValue,d,(s.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,s===null||s.memoizedState!==null&&s.memoizedState.dehydrated!==null){if(vn&&is!==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(s===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 Os!==null&&(mu(Os),Os=null),j=!0;if(!j)return a.flags&65536?a:null}return(a.flags&128)!==0?(a.lanes=d,a):(h=h!==null,h!==(s!==null&&s.memoizedState!==null)&&h&&(a.child.flags|=8192,(a.mode&1)!==0&&(s===null||(In.current&1)!==0?or===0&&(or=3):W())),a.updateQueue!==null&&(a.flags|=4),Hn(a),null);case 4:return Oa(),Cd(s,a),s===null&&Ms(a.stateNode.containerInfo),Hn(a),null;case 10:return Gc(a.type._context),Hn(a),null;case 17:return xr(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)kr(j,!1);else{if(or!==0||s!==null&&(s.flags&128)!==0)for(s=a.child;s!==null;){if(R=vs(s),R!==null){for(a.flags|=128,kr(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,s=h,j.flags&=14680066,R=j.alternate,R===null?(j.childLanes=0,j.lanes=s,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,s=R.dependencies,j.dependencies=s===null?null:{lanes:s.lanes,firstContext:s.firstContext}),d=d.sibling;return on(In,In.current&1|2),a.child}s=s.sibling}j.tail!==null&&hn()>xi&&(a.flags|=128,h=!0,kr(j,!1),a.lanes=4194304)}else{if(!h)if(s=vs(R),s!==null){if(a.flags|=128,h=!0,d=s.updateQueue,d!==null&&(a.updateQueue=d,a.flags|=4),kr(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,kr(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,s!==null&&s.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 bh(s,a){switch(ud(a),a.tag){case 1:return xr(a.type)&&Dc(),s=a.flags,s&65536?(a.flags=s&-65537|128,a):null;case 3:return Oa(),Sn(ss),Sn(nr),Jc(),s=a.flags,(s&65536)!==0&&(s&128)===0?(a.flags=s&-65537|128,a):null;case 5:return ko(a),null;case 13:if(Sn(In),s=a.memoizedState,s!==null&&s.dehydrated!==null){if(a.alternate===null)throw Error(n(340));Bi()}return s=a.flags,s&65536?(a.flags=s&-65537|128,a):null;case 19:return Sn(In),null;case 4:return Oa(),null;case 10:return Gc(a.type._context),null;case 22:case 23:return k(),null;case 24:return null;default:return null}}var Mr=!1,mr=!1,jh=typeof WeakSet=="function"?WeakSet:Set,Xe=null;function Wa(s,a){var d=s.ref;if(d!==null)if(typeof d=="function")try{d(null)}catch(h){Ie(s,a,h)}else d.current=null}function $d(s,a,d){try{d()}catch(h){Ie(s,a,h)}}var as=!1;function Bl(s,a){if(Sl=Io,s=ja(),mo(s)){if("selectionStart"in s)var d={start:s.selectionStart,end:s.selectionEnd};else e:{d=(d=s.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,re=-1,ye=0,Me=0,Re=s,Te=null;t:for(;;){for(var Je;Re!==d||v!==0&&Re.nodeType!==3||(ee=R+v),Re!==j||h!==0&&Re.nodeType!==3||(re=R+h),Re.nodeType===3&&(R+=Re.nodeValue.length),(Je=Re.firstChild)!==null;)Te=Re,Re=Je;for(;;){if(Re===s)break t;if(Te===d&&++ye===v&&(ee=R),Te===j&&++Me===h&&(re=R),(Je=Re.nextSibling)!==null)break;Re=Te,Te=Re.parentNode}Re=Je}d=ee===-1||re===-1?null:{start:ee,end:re}}else d=null}d=d||{start:0,end:0}}else d=null;for(od={focusedElem:s,selectionRange:d},Io=!1,Xe=a;Xe!==null;)if(a=Xe,s=a.child,(a.subtreeFlags&1028)!==0&&s!==null)s.return=a,Xe=s;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,ar=tt.memoizedState,de=a.stateNode,le=de.getSnapshotBeforeUpdate(a.elementType===a.type?nt:Ws(a.type,nt),ar);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(s=a.sibling,s!==null){s.return=a.return,Xe=s;break}Xe=a.return}return tt=as,as=!1,tt}function qa(s,a,d){var h=a.updateQueue;if(h=h!==null?h.lastEffect:null,h!==null){var v=h=h.next;do{if((v.tag&s)===s){var j=v.destroy;v.destroy=void 0,j!==void 0&&$d(a,d,j)}v=v.next}while(v!==h)}}function Ul(s,a){if(a=a.updateQueue,a=a!==null?a.lastEffect:null,a!==null){var d=a=a.next;do{if((d.tag&s)===s){var h=d.create;d.destroy=h()}d=d.next}while(d!==a)}}function Ad(s){var a=s.ref;if(a!==null){var d=s.stateNode;switch(s.tag){case 5:s=d;break;default:s=d}typeof a=="function"?a(s):a.current=s}}function Ed(s){var a=s.alternate;a!==null&&(s.alternate=null,Ed(a)),s.child=null,s.deletions=null,s.sibling=null,s.tag===5&&(a=s.stateNode,a!==null&&(delete a[mi],delete a[$a],delete a[Pc],delete a[r_],delete a[Wf])),s.stateNode=null,s.return=null,s.dependencies=null,s.memoizedProps=null,s.memoizedState=null,s.pendingProps=null,s.stateNode=null,s.updateQueue=null}function vi(s){return s.tag===5||s.tag===3||s.tag===4}function Sh(s){e:for(;;){for(;s.sibling===null;){if(s.return===null||vi(s.return))return null;s=s.return}for(s.sibling.return=s.return,s=s.sibling;s.tag!==5&&s.tag!==6&&s.tag!==18;){if(s.flags&2||s.child===null||s.tag===4)continue e;s.child.return=s,s=s.child}if(!(s.flags&2))return s.stateNode}}function Td(s,a,d){var h=s.tag;if(h===5||h===6)s=s.stateNode,a?d.nodeType===8?d.parentNode.insertBefore(s,a):d.insertBefore(s,a):(d.nodeType===8?(a=d.parentNode,a.insertBefore(s,d)):(a=d,a.appendChild(s)),d=d._reactRootContainer,d!=null||a.onclick!==null||(a.onclick=jl));else if(h!==4&&(s=s.child,s!==null))for(Td(s,a,d),s=s.sibling;s!==null;)Td(s,a,d),s=s.sibling}function cu(s,a,d){var h=s.tag;if(h===5||h===6)s=s.stateNode,a?d.insertBefore(s,a):d.appendChild(s);else if(h!==4&&(s=s.child,s!==null))for(cu(s,a,d),s=s.sibling;s!==null;)cu(s,a,d),s=s.sibling}var sr=null,Xn=!1;function ri(s,a,d){for(d=d.child;d!==null;)kh(s,a,d),d=d.sibling}function kh(s,a,d){if(gr&&typeof gr.onCommitFiberUnmount=="function")try{gr.onCommitFiberUnmount(tn,d)}catch{}switch(d.tag){case 5:mr||Wa(d,a);case 6:var h=sr,v=Xn;sr=null,ri(s,a,d),sr=h,Xn=v,sr!==null&&(Xn?(s=sr,d=d.stateNode,s.nodeType===8?s.parentNode.removeChild(d):s.removeChild(d)):sr.removeChild(d.stateNode));break;case 18:sr!==null&&(Xn?(s=sr,d=d.stateNode,s.nodeType===8?Ic(s.parentNode,d):s.nodeType===1&&Ic(s,d),lo(s)):Ic(sr,d.stateNode));break;case 4:h=sr,v=Xn,sr=d.stateNode.containerInfo,Xn=!0,ri(s,a,d),sr=h,Xn=v;break;case 0:case 11:case 14:case 15:if(!mr&&(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)}ri(s,a,d);break;case 1:if(!mr&&(Wa(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)}ri(s,a,d);break;case 21:ri(s,a,d);break;case 22:d.mode&1?(mr=(h=mr)||d.memoizedState!==null,ri(s,a,d),mr=h):ri(s,a,d);break;default:ri(s,a,d)}}function Vi(s){var a=s.updateQueue;if(a!==null){s.updateQueue=null;var d=s.stateNode;d===null&&(d=s.stateNode=new jh),a.forEach(function(h){var v=vt.bind(null,s,h);d.has(h)||(d.add(h),h.then(v,v))})}}function bs(s,a){var d=a.deletions;if(d!==null)for(var h=0;h<d.length;h++){var v=d[h];try{var j=s,R=a,ee=R;e:for(;ee!==null;){switch(ee.tag){case 5:sr=ee.stateNode,Xn=!1;break e;case 3:sr=ee.stateNode.containerInfo,Xn=!0;break e;case 4:sr=ee.stateNode.containerInfo,Xn=!0;break e}ee=ee.return}if(sr===null)throw Error(n(160));kh(j,R,v),sr=null,Xn=!1;var re=v.alternate;re!==null&&(re.return=null),v.return=null}catch(ye){Ie(v,a,ye)}}if(a.subtreeFlags&12854)for(a=a.child;a!==null;)uu(a,s),a=a.sibling}function uu(s,a){var d=s.alternate,h=s.flags;switch(s.tag){case 0:case 11:case 14:case 15:if(bs(a,s),yn(s),h&4){try{qa(3,s,s.return),Ul(3,s)}catch(nt){Ie(s,s.return,nt)}try{qa(5,s,s.return)}catch(nt){Ie(s,s.return,nt)}}break;case 1:bs(a,s),yn(s),h&512&&d!==null&&Wa(d,d.return);break;case 5:if(bs(a,s),yn(s),h&512&&d!==null&&Wa(d,d.return),s.flags&32){var v=s.stateNode;try{Mt(v,"")}catch(nt){Ie(s,s.return,nt)}}if(h&4&&(v=s.stateNode,v!=null)){var j=s.memoizedProps,R=d!==null?d.memoizedProps:j,ee=s.type,re=s.updateQueue;if(s.updateQueue=null,re!==null)try{ee==="input"&&j.type==="radio"&&j.name!=null&&Ye(v,j),Cr(ee,R);var ye=Cr(ee,j);for(R=0;R<re.length;R+=2){var Me=re[R],Re=re[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[$a]=j}catch(nt){Ie(s,s.return,nt)}}break;case 6:if(bs(a,s),yn(s),h&4){if(s.stateNode===null)throw Error(n(162));v=s.stateNode,j=s.memoizedProps;try{v.nodeValue=j}catch(nt){Ie(s,s.return,nt)}}break;case 3:if(bs(a,s),yn(s),h&4&&d!==null&&d.memoizedState.isDehydrated)try{lo(a.containerInfo)}catch(nt){Ie(s,s.return,nt)}break;case 4:bs(a,s),yn(s);break;case 13:bs(a,s),yn(s),v=s.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(s);break;case 22:if(Me=d!==null&&d.memoizedState!==null,s.mode&1?(mr=(ye=mr)||Me,bs(a,s),mr=ye):bs(a,s),yn(s),h&8192){if(ye=s.memoizedState!==null,(s.stateNode.isHidden=ye)&&!Me&&(s.mode&1)!==0)for(Xe=s,Me=s.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:qa(4,Te,Te.return);break;case 1:Wa(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:Wa(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=s;;){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,re=Re.memoizedProps.style,R=re!=null&&re.hasOwnProperty("display")?re.display:null,ee.style.display=En("display",R))}catch(nt){Ie(s,s.return,nt)}}}else if(Re.tag===6){if(Me===null)try{Re.stateNode.nodeValue=ye?"":Re.memoizedProps}catch(nt){Ie(s,s.return,nt)}}else if((Re.tag!==22&&Re.tag!==23||Re.memoizedState===null||Re===s)&&Re.child!==null){Re.child.return=Re,Re=Re.child;continue}if(Re===s)break e;for(;Re.sibling===null;){if(Re.return===null||Re.return===s)break e;Me===Re&&(Me=null),Re=Re.return}Me===Re&&(Me=null),Re.sibling.return=Re.return,Re=Re.sibling}}break;case 19:bs(a,s),yn(s),h&4&&Vi(s);break;case 21:break;default:bs(a,s),yn(s)}}function yn(s){var a=s.flags;if(a&2){try{e:{for(var d=s.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=Sh(s);cu(s,j,v);break;case 3:case 4:var R=h.stateNode.containerInfo,ee=Sh(s);Td(s,ee,R);break;default:throw Error(n(161))}}catch(re){Ie(s,s.return,re)}s.flags&=-3}a&4096&&(s.flags&=-4097)}function Ha(s,a,d){Xe=s,Nh(s)}function Nh(s,a,d){for(var h=(s.mode&1)!==0;Xe!==null;){var v=Xe,j=v.child;if(v.tag===22&&h){var R=v.memoizedState!==null||Mr;if(!R){var ee=v.alternate,re=ee!==null&&ee.memoizedState!==null||mr;ee=Mr;var ye=mr;if(Mr=R,(mr=re)&&!ye)for(Xe=v;Xe!==null;)R=Xe,re=R.child,R.tag===22&&R.memoizedState!==null?Ld(v):re!==null?(re.return=R,Xe=re):Ld(v);for(;j!==null;)Xe=j,Nh(j),j=j.sibling;Xe=v,Mr=ee,mr=ye}Md(s)}else(v.subtreeFlags&8772)!==0&&j!==null?(j.return=v,Xe=j):Md(s)}}function Md(s){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:mr||Ul(5,a);break;case 1:var h=a.stateNode;if(a.flags&4&&!mr)if(d===null)h.componentDidMount();else{var v=a.elementType===a.type?d.memoizedProps:Ws(a.type,d.memoizedProps);h.componentDidUpdate(v,d.memoizedState,h.__reactInternalSnapshotBeforeUpdate)}var j=a.updateQueue;j!==null&&Yf(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}Yf(a,R,d)}break;case 5:var ee=a.stateNode;if(d===null&&a.flags&4){d=ee;var re=a.memoizedProps;switch(a.type){case"button":case"input":case"select":case"textarea":re.autoFocus&&d.focus();break;case"img":re.src&&(d.src=re.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&&lo(Re)}}}break;case 19:case 17:case 21:case 22:case 23:case 25:break;default:throw Error(n(163))}mr||a.flags&512&&Ad(a)}catch(Te){Ie(a,a.return,Te)}}if(a===s){Xe=null;break}if(d=a.sibling,d!==null){d.return=a.return,Xe=d;break}Xe=a.return}}function Rd(s){for(;Xe!==null;){var a=Xe;if(a===s){Xe=null;break}var d=a.sibling;if(d!==null){d.return=a.return,Xe=d;break}Xe=a.return}}function Ld(s){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(re){Ie(a,d,re)}break;case 1:var h=a.stateNode;if(typeof h.componentDidMount=="function"){var v=a.return;try{h.componentDidMount()}catch(re){Ie(a,v,re)}}var j=a.return;try{Ad(a)}catch(re){Ie(a,j,re)}break;case 5:var R=a.return;try{Ad(a)}catch(re){Ie(a,R,re)}}}catch(re){Ie(a,a.return,re)}if(a===s){Xe=null;break}var ee=a.sibling;if(ee!==null){ee.return=a.return,Xe=ee;break}Xe=a.return}}var Ch=Math.ceil,Wl=M.ReactCurrentDispatcher,ql=M.ReactCurrentOwner,Rr=M.ReactCurrentBatchConfig,Vt=0,ir=null,Vn=null,_r=0,Zn=0,Va=Zs(0),or=0,Hl=null,js=0,Ga=0,Vl=0,Ka=null,qr=null,Id=0,xi=1/0,Hr=null,du=!1,oa=null,Co=null,fu=!1,$o=null,Gl=0,Ya=0,Pd=null,Kl=-1,Yl=0;function Lr(){return(Vt&6)!==0?hn():Kl!==-1?Kl:Kl=hn()}function Gi(s){return(s.mode&1)===0?1:(Vt&2)!==0&&_r!==0?_r&-_r:s_.transition!==null?(Yl===0&&(Yl=fr()),Yl):(s=nn,s!==0||(s=window.event,s=s===void 0?16:je(s.type)),s)}function qs(s,a,d,h){if(50<Ya)throw Ya=0,Pd=null,Error(n(185));yr(s,d,h),((Vt&2)===0||s!==ir)&&(s===ir&&((Vt&2)===0&&(Ga|=d),or===4&&Ki(s,_r)),Vr(s,h),d===1&&Vt===0&&(a.mode&1)===0&&(xi=hn()+500,Ma&&gi()))}function Vr(s,a){var d=s.callbackNode;Qn(s,a);var h=_s(s,s===ir?_r:0);if(h===0)d!==null&&no(d),s.callbackNode=null,s.callbackPriority=0;else if(a=h&-h,s.callbackPriority!==a){if(d!=null&&no(d),a===1)s.tag===0?Ra(Dd.bind(null,s)):Fc(Dd.bind(null,s)),ld(function(){(Vt&6)===0&&gi()}),d=null;else{switch(ml(h)){case 1:d=$i;break;case 4:d=$s;break;case 16:d=hs;break;case 536870912:d=it;break;default:d=hs}d=$n(d,Od.bind(null,s))}s.callbackPriority=a,s.callbackNode=d}}function Od(s,a){if(Kl=-1,Yl=0,(Vt&6)!==0)throw Error(n(327));var d=s.callbackNode;if(qe()&&s.callbackNode!==d)return null;var h=_s(s,s===ir?_r:0);if(h===0)return null;if((h&30)!==0||(h&s.expiredLanes)!==0||a)a=V(s,h);else{a=h;var v=Vt;Vt|=2;var j=q();(ir!==s||_r!==a)&&(Hr=null,xi=hn()+500,A(s,a));do try{Ee();break}catch(ee){I(s,ee)}while(!0);rr(),Wl.current=j,Vt=v,Vn!==null?a=0:(ir=null,_r=0,a=or)}if(a!==0){if(a===2&&(v=Zr(s),v!==0&&(h=v,a=hu(s,v))),a===1)throw d=Hl,A(s,0),Ki(s,h),Vr(s,hn()),d;if(a===6)Ki(s,h);else{if(v=s.current.alternate,(h&30)===0&&!$h(v)&&(a=V(s,h),a===2&&(j=Zr(s),j!==0&&(h=j,a=hu(s,j))),a===1))throw d=Hl,A(s,0),Ki(s,h),Vr(s,hn()),d;switch(s.finishedWork=v,s.finishedLanes=h,a){case 0:case 1:throw Error(n(345));case 2:Ne(s,qr,Hr);break;case 3:if(Ki(s,h),(h&130023424)===h&&(a=Id+500-hn(),10<a)){if(_s(s,0)!==0)break;if(v=s.suspendedLanes,(v&h)!==h){Lr(),s.pingedLanes|=s.suspendedLanes&v;break}s.timeoutHandle=Lc(Ne.bind(null,s,qr,Hr),a);break}Ne(s,qr,Hr);break;case 4:if(Ki(s,h),(h&4194240)===h)break;for(a=s.eventTimes,v=-1;0<h;){var R=31-dr(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*Ch(h/1960))-h,10<h){s.timeoutHandle=Lc(Ne.bind(null,s,qr,Hr),h);break}Ne(s,qr,Hr);break;case 5:Ne(s,qr,Hr);break;default:throw Error(n(329))}}}return Vr(s,hn()),s.callbackNode===d?Od.bind(null,s):null}function hu(s,a){var d=Ka;return s.current.memoizedState.isDehydrated&&(A(s,a).flags|=256),s=V(s,a),s!==2&&(a=qr,qr=d,a!==null&&mu(a)),s}function mu(s){qr===null?qr=s:qr.push.apply(qr,s)}function $h(s){for(var a=s;;){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(!Ts(j(),v))return!1}catch{return!1}}}if(d=a.child,a.subtreeFlags&16384&&d!==null)d.return=a,a=d;else{if(a===s)break;for(;a.sibling===null;){if(a.return===null||a.return===s)return!0;a=a.return}a.sibling.return=a.return,a=a.sibling}}return!0}function Ki(s,a){for(a&=~Vl,a&=~Ga,s.suspendedLanes|=a,s.pingedLanes&=~a,s=s.expirationTimes;0<a;){var d=31-dr(a),h=1<<d;s[d]=-1,a&=~h}}function Dd(s){if((Vt&6)!==0)throw Error(n(327));qe();var a=_s(s,0);if((a&1)===0)return Vr(s,hn()),null;var d=V(s,a);if(s.tag!==0&&d===2){var h=Zr(s);h!==0&&(a=h,d=hu(s,h))}if(d===1)throw d=Hl,A(s,0),Ki(s,a),Vr(s,hn()),d;if(d===6)throw Error(n(345));return s.finishedWork=s.current.alternate,s.finishedLanes=a,Ne(s,qr,Hr),Vr(s,hn()),null}function _u(s,a){var d=Vt;Vt|=1;try{return s(a)}finally{Vt=d,Vt===0&&(xi=hn()+500,Ma&&gi())}}function g(s){$o!==null&&$o.tag===0&&(Vt&6)===0&&qe();var a=Vt;Vt|=1;var d=Rr.transition,h=nn;try{if(Rr.transition=null,nn=1,s)return s()}finally{nn=h,Rr.transition=d,Vt=a,(Vt&6)===0&&gi()}}function k(){Zn=Va.current,Sn(Va)}function A(s,a){s.finishedWork=null,s.finishedLanes=0;var d=s.timeoutHandle;if(d!==-1&&(s.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:Oa(),Sn(ss),Sn(nr),Jc();break;case 5:ko(h);break;case 4:Oa();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(ir=s,Vn=s=Ja(s.current,null),_r=Zn=a,or=0,Hl=null,Vl=Ga=js=0,qr=Ka=null,jo!==null){for(a=0;a<jo.length;a++)if(d=jo[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}jo=null}return s}function I(s,a){do{var d=Vn;try{if(rr(),Xc.current=Pl,kn){for(var h=Mn.memoizedState;h!==null;){var v=h.queue;v!==null&&(v.pending=null),h=h.next}kn=!1}if(Zo=0,hr=Wn=Mn=null,Da=!1,Qo=0,ql.current=null,d===null||d.return===null){or=1,Hl=a,Vn=null;break}e:{var j=s,R=d.return,ee=d,re=a;if(a=_r,ee.flags|=32768,re!==null&&typeof re=="object"&&typeof re.then=="function"){var ye=re,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,mh(Je,R,ee,j,a),Je.mode&1&&hh(j,ye,a),a=Je,re=ye;var tt=a.updateQueue;if(tt===null){var nt=new Set;nt.add(re),a.updateQueue=nt}else tt.add(re);break e}else{if((a&1)===0){hh(j,ye,a),W();break e}re=Error(n(426))}}else if(vn&&ee.mode&1){var ar=Dl(R);if(ar!==null){(ar.flags&65536)===0&&(ar.flags|=256),mh(ar,R,ee,j,a),md(za(re,ee));break e}}j=re=za(re,ee),or!==4&&(or=2),Ka===null?Ka=[j]:Ka.push(j),j=R;do{switch(j.tag){case 3:j.flags|=65536,a&=-a,j.lanes|=a;var de=iu(j,re,a);pd(j,de);break e;case 1:ee=re;var le=j.type,he=j.stateNode;if((j.flags&128)===0&&(typeof le.getDerivedStateFromError=="function"||he!==null&&typeof he.componentDidCatch=="function"&&(Co===null||!Co.has(he)))){j.flags|=65536,a&=-a,j.lanes|=a;var Fe=fh(j,ee,a);pd(j,Fe);break e}}j=j.return}while(j!==null)}pe(d)}catch(st){a=st,Vn===d&&d!==null&&(Vn=d=d.return);continue}break}while(!0)}function q(){var s=Wl.current;return Wl.current=Pl,s===null?Pl:s}function W(){(or===0||or===3||or===2)&&(or=4),ir===null||(js&268435455)===0&&(Ga&268435455)===0||Ki(ir,_r)}function V(s,a){var d=Vt;Vt|=2;var h=q();(ir!==s||_r!==a)&&(Hr=null,A(s,a));do try{te();break}catch(v){I(s,v)}while(!0);if(rr(),Vt=d,Wl.current=h,Vn!==null)throw Error(n(261));return ir=null,_r=0,or}function te(){for(;Vn!==null;)_e(Vn)}function Ee(){for(;Vn!==null&&!xe();)_e(Vn)}function _e(s){var a=xn(s.alternate,s,Zn);s.memoizedProps=s.pendingProps,a===null?pe(s):Vn=a,ql.current=null}function pe(s){var a=s;do{var d=a.alternate;if(s=a.return,(a.flags&32768)===0){if(d=l_(d,a,Zn),d!==null){Vn=d;return}}else{if(d=bh(d,a),d!==null){d.flags&=32767,Vn=d;return}if(s!==null)s.flags|=32768,s.subtreeFlags=0,s.deletions=null;else{or=6,Vn=null;return}}if(a=a.sibling,a!==null){Vn=a;return}Vn=a=s}while(a!==null);or===0&&(or=5)}function Ne(s,a,d){var h=nn,v=Rr.transition;try{Rr.transition=null,nn=1,ze(s,a,d,h)}finally{Rr.transition=v,nn=h}return null}function ze(s,a,d,h){do qe();while($o!==null);if((Vt&6)!==0)throw Error(n(327));d=s.finishedWork;var v=s.finishedLanes;if(d===null)return null;if(s.finishedWork=null,s.finishedLanes=0,d===s.current)throw Error(n(177));s.callbackNode=null,s.callbackPriority=0;var j=d.lanes|d.childLanes;if(ga(s,j),s===ir&&(Vn=ir=null,_r=0),(d.subtreeFlags&2064)===0&&(d.flags&2064)===0||fu||(fu=!0,$n(hs,function(){return qe(),null})),j=(d.flags&15990)!==0,(d.subtreeFlags&15990)!==0||j){j=Rr.transition,Rr.transition=null;var R=nn;nn=1;var ee=Vt;Vt|=4,ql.current=null,Bl(s,d),uu(d,s),vl(od),Io=!!Sl,od=Sl=null,s.current=d,Ha(d),Jn(),Vt=ee,nn=R,Rr.transition=j}else s.current=d;if(fu&&(fu=!1,$o=s,Gl=v),j=s.pendingLanes,j===0&&(Co=null),oi(d.stateNode),Vr(s,hn()),a!==null)for(h=s.onRecoverableError,d=0;d<a.length;d++)v=a[d],h(v.value,{componentStack:v.stack,digest:v.digest});if(du)throw du=!1,s=oa,oa=null,s;return(Gl&1)!==0&&s.tag!==0&&qe(),j=s.pendingLanes,(j&1)!==0?s===Pd?Ya++:(Ya=0,Pd=s):Ya=0,gi(),null}function qe(){if($o!==null){var s=ml(Gl),a=Rr.transition,d=nn;try{if(Rr.transition=null,nn=16>s?16:s,$o===null)var h=!1;else{if(s=$o,$o=null,Gl=0,(Vt&6)!==0)throw Error(n(331));var v=Vt;for(Vt|=4,Xe=s.current;Xe!==null;){var j=Xe,R=j.child;if((Xe.flags&16)!==0){var ee=j.deletions;if(ee!==null){for(var re=0;re<ee.length;re++){var ye=ee[re];for(Xe=ye;Xe!==null;){var Me=Xe;switch(Me.tag){case 0:case 11:case 15:qa(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 ar=nt.sibling;nt.sibling=null,nt=ar}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:qa(9,j,j.return)}var de=j.sibling;if(de!==null){de.return=j.return,Xe=de;break e}Xe=j.return}}var le=s.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(st){Ie(ee,ee.return,st)}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(),gr&&typeof gr.onPostCommitFiberRoot=="function")try{gr.onPostCommitFiberRoot(tn,s)}catch{}h=!0}return h}finally{nn=d,Rr.transition=a}}return!1}function Ze(s,a,d){a=za(d,a),a=iu(s,a,1),s=Ui(s,a,1),a=Lr(),s!==null&&(yr(s,1,a),Vr(s,a))}function Ie(s,a,d){if(s.tag===3)Ze(s,s,d);else for(;a!==null;){if(a.tag===3){Ze(a,s,d);break}else if(a.tag===1){var h=a.stateNode;if(typeof a.type.getDerivedStateFromError=="function"||typeof h.componentDidCatch=="function"&&(Co===null||!Co.has(h))){s=za(d,s),s=fh(a,s,1),a=Ui(a,s,1),s=Lr(),a!==null&&(yr(a,1,s),Vr(a,s));break}}a=a.return}}function ln(s,a,d){var h=s.pingCache;h!==null&&h.delete(a),a=Lr(),s.pingedLanes|=s.suspendedLanes&d,ir===s&&(_r&d)===d&&(or===4||or===3&&(_r&130023424)===_r&&500>hn()-Id?A(s,0):Vl|=d),Vr(s,a)}function Tt(s,a){a===0&&((s.mode&1)===0?a=1:(a=ms,ms<<=1,(ms&130023424)===0&&(ms=4194304)));var d=Lr();s=Fs(s,a),s!==null&&(yr(s,a,d),Vr(s,d))}function He(s){var a=s.memoizedState,d=0;a!==null&&(d=a.retryLane),Tt(s,d)}function vt(s,a){var d=0;switch(s.tag){case 13:var h=s.stateNode,v=s.memoizedState;v!==null&&(d=v.retryLane);break;case 19:h=s.stateNode;break;default:throw Error(n(314))}h!==null&&h.delete(a),Tt(s,d)}var xn;xn=function(s,a,d){if(s!==null)if(s.memoizedProps!==a.pendingProps||ss.current)gn=!0;else{if((s.lanes&d)===0&&(a.flags&128)===0)return gn=!1,a_(s,a,d);gn=(s.flags&131072)!==0}else gn=!1,vn&&(a.flags&1048576)!==0&&qf(a,zc,a.index);switch(a.lanes=0,a.tag){case 2:var h=a.type;ia(s,a),s=a.pendingProps;var v=Ea(a,nr.current);Ia(a,d),v=Tl(null,a,h,s,v,d);var j=ta();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,xr(h)?(j=!0,wo(a)):j=!1,a.memoizedState=v.state!==null&&v.state!==void 0?v.state:null,Xt(a),v.updater=Ol,a.stateNode=v,v._reactInternals=a,jd(a,h,s,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(ia(s,a),s=a.pendingProps,v=h._init,h=v(h._payload),a.type=h,v=a.tag=Jl(h),s=Ws(h,s),v){case 0:a=Ba(null,a,h,s,d);break e;case 1:a=ph(null,a,h,s,d);break e;case 11:a=ti(null,a,h,s,d);break e;case 14:a=Wi(null,a,h,Ws(h.type,s),d);break e}throw Error(n(306,h,""))}return a;case 0:return h=a.type,v=a.pendingProps,v=a.elementType===h?v:Ws(h,v),Ba(s,a,h,v,d);case 1:return h=a.type,v=a.pendingProps,v=a.elementType===h?v:Ws(h,v),ph(s,a,h,v,d);case 3:e:{if(gh(a),s===null)throw Error(n(387));h=a.pendingProps,j=a.memoizedState,v=j.element,jr(s,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=za(Error(n(423)),a),a=yh(s,a,h,d,v);break e}else if(h!==v){v=za(Error(n(424)),a),a=yh(s,a,h,d,v);break e}else for(is=Di(a.stateNode.containerInfo.firstChild),Tr=a,vn=!0,Os=null,d=Gf(a,null,h,d),a.child=d;d;)d.flags=d.flags&-3|4096,d=d.sibling;else{if(Bi(),h===v){a=wi(s,a,d);break e}an(s,a,h,d)}a=a.child}return a;case 5:return Yc(a),s===null&&Uc(a),h=a.type,v=a.pendingProps,j=s!==null?s.memoizedProps:null,R=v.children,Ca(h,v)?R=null:j!==null&&Ca(h,j)&&(a.flags|=32),_h(s,a),an(s,a,R,d),a.child;case 6:return s===null&&Uc(a),null;case 13:return Ua(s,a,d);case 4:return gd(a,a.stateNode.containerInfo),h=a.pendingProps,s===null?a.child=xo(a,null,h,d):an(s,a,h,d),a.child;case 11:return h=a.type,v=a.pendingProps,v=a.elementType===h?v:Ws(h,v),ti(s,a,h,v,d);case 7:return an(s,a,a.pendingProps,d),a.child;case 8:return an(s,a,a.pendingProps.children,d),a.child;case 12:return an(s,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(Ts(j.value,R)){if(j.children===v.children&&!ss.current){a=wi(s,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 re=ee.firstContext;re!==null;){if(re.context===h){if(j.tag===1){re=ei(-1,d&-d),re.tag=2;var ye=j.updateQueue;if(ye!==null){ye=ye.shared;var Me=ye.pending;Me===null?re.next=re:(re.next=Me.next,Me.next=re),ye.pending=re}}j.lanes|=d,re=j.alternate,re!==null&&(re.lanes|=d),_d(j.return,d,a),ee.lanes|=d;break}re=re.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(s,a,v.children,d),a=a.child}return a;case 9:return v=a.type,h=a.pendingProps.children,Ia(a,d),v=Ds(v),h=h(v),a.flags|=1,an(s,a,h,d),a.child;case 14:return h=a.type,v=Ws(h,a.pendingProps),v=Ws(h.type,v),Wi(s,a,h,v,d);case 15:return qi(s,a,a.type,a.pendingProps,d);case 17:return h=a.type,v=a.pendingProps,v=a.elementType===h?v:Ws(h,v),ia(s,a),a.tag=1,xr(h)?(s=!0,wo(a)):s=!1,Ia(a,d),ch(a,h,v),jd(a,h,v,d),Fl(null,a,h,!0,s,d);case 19:return wh(s,a,d);case 22:return ni(s,a,d)}throw Error(n(156,a.tag))};function $n(s,a){return Xr(s,a)}function ls(s,a,d,h){this.tag=s,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 On(s,a,d,h){return new ls(s,a,d,h)}function Ss(s){return s=s.prototype,!(!s||!s.isReactComponent)}function Jl(s){if(typeof s=="function")return Ss(s)?1:0;if(s!=null){if(s=s.$$typeof,s===F)return 11;if(s===P)return 14}return 2}function Ja(s,a){var d=s.alternate;return d===null?(d=On(s.tag,a,s.key,s.mode),d.elementType=s.elementType,d.type=s.type,d.stateNode=s.stateNode,d.alternate=s,s.alternate=d):(d.pendingProps=a,d.type=s.type,d.flags=0,d.subtreeFlags=0,d.deletions=null),d.flags=s.flags&14680064,d.childLanes=s.childLanes,d.lanes=s.lanes,d.child=s.child,d.memoizedProps=s.memoizedProps,d.memoizedState=s.memoizedState,d.updateQueue=s.updateQueue,a=s.dependencies,d.dependencies=a===null?null:{lanes:a.lanes,firstContext:a.firstContext},d.sibling=s.sibling,d.index=s.index,d.ref=s.ref,d}function Ah(s,a,d,h,v,j){var R=2;if(h=s,typeof s=="function")Ss(s)&&(R=1);else if(typeof s=="string")R=5;else e:switch(s){case Y:return Xl(d.children,v,j,a);case X:R=8,v|=8;break;case se:return s=On(12,d,a,v|2),s.elementType=se,s.lanes=j,s;case C:return s=On(13,d,a,v),s.elementType=C,s.lanes=j,s;case N:return s=On(19,d,a,v),s.elementType=N,s.lanes=j,s;case ne:return Eh(d,v,j,a);default:if(typeof s=="object"&&s!==null)switch(s.$$typeof){case ie:R=10;break e;case ue:R=9;break e;case F:R=11;break e;case P:R=14;break e;case O:R=16,h=null;break e}throw Error(n(130,s==null?s:typeof s,""))}return a=On(R,d,a,v),a.elementType=s,a.type=h,a.lanes=j,a}function Xl(s,a,d,h){return s=On(7,s,h,a),s.lanes=d,s}function Eh(s,a,d,h){return s=On(22,s,h,a),s.elementType=ne,s.lanes=d,s.stateNode={isHidden:!1},s}function c_(s,a,d){return s=On(6,s,null,a),s.lanes=d,s}function u_(s,a,d){return a=On(4,s.children!==null?s.children:[],s.key,a),a.lanes=d,a.stateNode={containerInfo:s.containerInfo,pendingChildren:null,implementation:s.implementation},a}function e0(s,a,d,h,v){this.tag=a,this.containerInfo=s,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=Ys(0),this.expirationTimes=Ys(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Ys(0),this.identifierPrefix=h,this.onRecoverableError=v,this.mutableSourceEagerHydrationData=null}function d_(s,a,d,h,v,j,R,ee,re){return s=new e0(s,a,d,ee,re),a===1?(a=1,j===!0&&(a|=8)):a=0,j=On(3,null,null,a),s.current=j,j.stateNode=s,j.memoizedState={element:h,isDehydrated:d,cache:null,transitions:null,pendingSuspenseBoundaries:null},Xt(j),s}function t0(s,a,d){var h=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:Z,key:h==null?null:""+h,children:s,containerInfo:a,implementation:d}}function Ig(s){if(!s)return yo;s=s._reactInternals;e:{if($t(s)!==s||s.tag!==1)throw Error(n(170));var a=s;do{switch(a.tag){case 3:a=a.stateNode.context;break e;case 1:if(xr(a.type)){a=a.stateNode.__reactInternalMemoizedMergedChildContext;break e}}a=a.return}while(a!==null);throw Error(n(171))}if(s.tag===1){var d=s.type;if(xr(d))return cd(s,d,a)}return a}function Pg(s,a,d,h,v,j,R,ee,re){return s=d_(d,h,!0,s,v,j,R,ee,re),s.context=Ig(null),d=s.current,h=Lr(),v=Gi(d),j=ei(h,v),j.callback=a??null,Ui(d,j,v),s.current.lanes=v,yr(s,v,h),Vr(s,h),s}function Th(s,a,d,h){var v=a.current,j=Lr(),R=Gi(v);return d=Ig(d),a.context===null?a.context=d:a.pendingContext=d,a=ei(j,R),a.payload={element:s},h=h===void 0?null:h,h!==null&&(a.callback=h),s=Ui(v,a,R),s!==null&&(qs(s,v,R,j),So(s,v,R)),R}function Mh(s){if(s=s.current,!s.child)return null;switch(s.child.tag){case 5:return s.child.stateNode;default:return s.child.stateNode}}function Og(s,a){if(s=s.memoizedState,s!==null&&s.dehydrated!==null){var d=s.retryLane;s.retryLane=d!==0&&d<a?d:a}}function f_(s,a){Og(s,a),(s=s.alternate)&&Og(s,a)}function n0(){return null}var Dg=typeof reportError=="function"?reportError:function(s){console.error(s)};function h_(s){this._internalRoot=s}Rh.prototype.render=h_.prototype.render=function(s){var a=this._internalRoot;if(a===null)throw Error(n(409));Th(s,a,null,null)},Rh.prototype.unmount=h_.prototype.unmount=function(){var s=this._internalRoot;if(s!==null){this._internalRoot=null;var a=s.containerInfo;g(function(){Th(null,s,null,null)}),a[Fi]=null}};function Rh(s){this._internalRoot=s}Rh.prototype.unstable_scheduleHydration=function(s){if(s){var a=ya();s={blockedOn:null,target:s,priority:a};for(var d=0;d<gs.length&&a!==0&&a<gs[d].priority;d++);gs.splice(d,0,s),d===0&&ts(s)}};function m_(s){return!(!s||s.nodeType!==1&&s.nodeType!==9&&s.nodeType!==11)}function Lh(s){return!(!s||s.nodeType!==1&&s.nodeType!==9&&s.nodeType!==11&&(s.nodeType!==8||s.nodeValue!==" react-mount-point-unstable "))}function Fg(){}function r0(s,a,d,h,v){if(v){if(typeof h=="function"){var j=h;h=function(){var ye=Mh(R);j.call(ye)}}var R=Pg(a,h,s,0,null,!1,!1,"",Fg);return s._reactRootContainer=R,s[Fi]=R.current,Ms(s.nodeType===8?s.parentNode:s),g(),R}for(;v=s.lastChild;)s.removeChild(v);if(typeof h=="function"){var ee=h;h=function(){var ye=Mh(re);ee.call(ye)}}var re=d_(s,0,!1,null,null,!1,!1,"",Fg);return s._reactRootContainer=re,s[Fi]=re.current,Ms(s.nodeType===8?s.parentNode:s),g(function(){Th(a,re,d,h)}),re}function Ih(s,a,d,h,v){var j=d._reactRootContainer;if(j){var R=j;if(typeof v=="function"){var ee=v;v=function(){var re=Mh(R);ee.call(re)}}Th(a,R,s,v)}else R=r0(d,a,s,v,h);return Mh(R)}Ai=function(s){switch(s.tag){case 3:var a=s.stateNode;if(a.current.memoizedState.isDehydrated){var d=Tn(a.pendingLanes);d!==0&&(ao(a,d|1),Vr(a,hn()),(Vt&6)===0&&(xi=hn()+500,gi()))}break;case 13:g(function(){var h=Fs(s,1);if(h!==null){var v=Lr();qs(h,s,1,v)}}),f_(s,1)}},ps=function(s){if(s.tag===13){var a=Fs(s,134217728);if(a!==null){var d=Lr();qs(a,s,134217728,d)}f_(s,134217728)}},Ar=function(s){if(s.tag===13){var a=Gi(s),d=Fs(s,a);if(d!==null){var h=Lr();qs(d,s,a,h)}f_(s,a)}},ya=function(){return nn},As=function(s,a){var d=nn;try{return nn=s,a()}finally{nn=d}},Cs=function(s,a,d){switch(a){case"input":if(Se(s,d),a=d.name,d.type==="radio"&&a!=null){for(d=s;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!==s&&h.form===s.form){var v=Oc(h);if(!v)throw Error(n(90));_t(h),Se(h,v)}}}break;case"textarea":Qt(s,d);break;case"select":a=d.value,a!=null&&De(s,!!d.multiple,a,!1)}},rt=_u,ut=g;var s0={usingClientEntryPoint:!1,Events:[Aa,_i,Oc,Ge,Ve,_u]},Fd={findFiberByHostInstance:Vo,bundleType:0,version:"18.3.1",rendererPackageName:"react-dom"},i0={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(s){return s=$r(s),s===null?null:s.stateNode},findFiberByHostInstance:Fd.findFiberByHostInstance||n0,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(i0),gr=Ph}catch{}}return Hs.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=s0,Hs.createPortal=function(s,a){var d=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!m_(a))throw Error(n(200));return t0(s,a,null,d)},Hs.createRoot=function(s,a){if(!m_(s))throw Error(n(299));var d=!1,h="",v=Dg;return a!=null&&(a.unstable_strictMode===!0&&(d=!0),a.identifierPrefix!==void 0&&(h=a.identifierPrefix),a.onRecoverableError!==void 0&&(v=a.onRecoverableError)),a=d_(s,1,!1,null,null,d,!1,h,v),s[Fi]=a.current,Ms(s.nodeType===8?s.parentNode:s),new h_(a)},Hs.findDOMNode=function(s){if(s==null)return null;if(s.nodeType===1)return s;var a=s._reactInternals;if(a===void 0)throw typeof s.render=="function"?Error(n(188)):(s=Object.keys(s).join(","),Error(n(268,s)));return s=$r(a),s=s===null?null:s.stateNode,s},Hs.flushSync=function(s){return g(s)},Hs.hydrate=function(s,a,d){if(!Lh(a))throw Error(n(200));return Ih(null,s,a,!0,d)},Hs.hydrateRoot=function(s,a,d){if(!m_(s))throw Error(n(405));var h=d!=null&&d.hydratedSources||null,v=!1,j="",R=Dg;if(d!=null&&(d.unstable_strictMode===!0&&(v=!0),d.identifierPrefix!==void 0&&(j=d.identifierPrefix),d.onRecoverableError!==void 0&&(R=d.onRecoverableError)),a=Pg(a,null,s,1,d??null,v,!1,j,R),s[Fi]=a.current,Ms(s),h)for(s=0;s<h.length;s++)d=h[s],v=d._getVersion,v=v(d._source),a.mutableSourceEagerHydrationData==null?a.mutableSourceEagerHydrationData=[d,v]:a.mutableSourceEagerHydrationData.push(d,v);return new Rh(a)},Hs.render=function(s,a,d){if(!Lh(a))throw Error(n(200));return Ih(null,s,a,!1,d)},Hs.unmountComponentAtNode=function(s){if(!Lh(s))throw Error(n(40));return s._reactRootContainer?(g(function(){Ih(null,null,s,!1,function(){s._reactRootContainer=null,s[Fi]=null})}),!0):!1},Hs.unstable_batchedUpdates=_u,Hs.unstable_renderSubtreeIntoContainer=function(s,a,d,h){if(!Lh(d))throw Error(n(200));if(s==null||s._reactInternals===void 0)throw Error(n(38));return Ih(s,a,d,!1,h)},Hs.version="18.3.1-next-f1338f8080-20240426",Hs}var Gg;function rv(){if(Gg)return g_.exports;Gg=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(),g_.exports=m0(),g_.exports}var Kg;function _0(){if(Kg)return Oh;Kg=1;var e=rv();return Oh.createRoot=e.createRoot,Oh.hydrateRoot=e.hydrateRoot,Oh}var p0=_0();const g0=Qp(p0);async function sv(e){const t=String(e||"");if(!t)return!1;try{return await navigator.clipboard.writeText(t),!0}catch{try{const n=document.createElement("textarea");return n.value=t,n.style.position="fixed",n.style.left="-9999px",document.body.appendChild(n),n.select(),document.execCommand("copy"),document.body.removeChild(n),!0}catch{return!1}}}const y0=3,w0=Number.MAX_SAFE_INTEGER;function iv(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function ov(e){return Array.isArray(e)}function v0(e){const t=e.trim();if(!t)return e;if(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))try{return JSON.parse(t)}catch{return e}return e}function x0(e){if(e==null)return"";if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}}function Nu({kind:e,children:t}){return r.jsx("span",{className:`json-token ${e}`,children:t})}function b0(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?r.jsxs("span",{className:`json-string ${i?"open":"collapsed"}`,children:[r.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?r.jsx("span",{className:"json-token string json-string__value",children:t}):r.jsxs("button",{type:"button",className:"json-string__preview",onClick:()=>o(!0),"aria-label":"Expand string value",children:[r.jsx("span",{className:"json-token string json-string__preview_text",children:t}),r.jsx("span",{className:"json-string__suffix",children:"(...)"})]})]}):r.jsx(Nu,{kind:"string",children:t})}function j0(e,t,n){return e===null?r.jsx(Nu,{kind:"null",children:"null"}):typeof e=="string"?r.jsx(b0,{value:e,expansion_mode:t,expansion_version:n}):typeof e=="number"?r.jsx(Nu,{kind:"number",children:String(e)}):typeof e=="boolean"?r.jsx(Nu,{kind:"boolean",children:e?"true":"false"}):r.jsx(Nu,{kind:"string",children:JSON.stringify(String(e))})}function S0(e){return ov(e)?e.length===1?"1 item":`${e.length} items`:iv(e)?Object.keys(e).length===1?"1 key":`${Object.keys(e).length} keys`:""}function av(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,_=iv(n),p=ov(n),w=_||p,y=i<o,[x,S]=m.useState(y);m.useEffect(()=>{S(y)},[y,u]);const b=t?r.jsxs(r.Fragment,{children:[r.jsx(Nu,{kind:"key",children:JSON.stringify(t)}),": "]}):null;if(!w)return r.jsxs("div",{className:"json-viewer__line",style:{paddingLeft:f},children:[b,j0(n,l,u),c?",":""]});const $=p?"[":"{",E=p?"]":"}",L=S0(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 r.jsxs("details",{className:"json-viewer__details",open:x,onToggle:H=>S(H.currentTarget.open),children:[r.jsxs("summary",{className:"json-viewer__summary",style:{paddingLeft:f},children:[b,r.jsx("span",{className:"json-viewer__caret","aria-hidden":"true",children:x?"▾":"▸"}),r.jsx("span",{className:"json-viewer__punct",children:D}),!x&&c?r.jsx("span",{className:"json-viewer__punct",children:","}):null]}),x?r.jsx("div",{className:"json-viewer__children",children:M.length===0?r.jsxs("div",{className:"json-viewer__line",style:{paddingLeft:f},children:[r.jsx("span",{className:"json-viewer__punct",children:E}),c?",":""]}):r.jsxs(r.Fragment,{children:[M.map((H,Z)=>{const Y=Z===M.length-1;return r.jsx(av,{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}`)}),r.jsxs("div",{className:"json-viewer__line",style:{paddingLeft:f},children:[r.jsx("span",{className:"json-viewer__punct",children:E}),c?",":""]})]})}):null]})}function lv(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):y0,c=o.mode==="unfolded"?w0:u,f=m.useMemo(()=>typeof t=="string"?v0(t):t,[t]),_=m.useMemo(()=>x0(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 r.jsxs("div",{className:p,children:[r.jsxs("div",{className:"json-viewer__toolbar",children:[r.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?r.jsx("button",{type:"button",className:"json-viewer__btn json-viewer__copy",onClick:()=>void sv(_),children:"Copy"}):null]}),r.jsx("div",{className:"json-viewer__tree",role:"tree","aria-label":"JSON viewer",children:r.jsx(av,{value:f,depth:0,collapse_after_depth:c,expansion_mode:o.mode,expansion_version:o.version,trailing_comma:!1})})]})}function v_(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(r.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(r.jsx("strong",{children:n.slice(i+2,c)},`bold:${i}`)),i=c+2;continue}}o+=u,i+=1}return l(),t}function k0(e){return String(e??"").replace(/\r\n/g,`
41
- `).replace(/\r/g,`
42
- `).split(`
43
- `)}function N0({text:e,className:t}){const n=k0(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(r.jsx("pre",{className:"mf-md_pre",children:r.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=v_(y);w===1?i.push(r.jsx("h1",{children:x},`h1:${o}`)):w===2?i.push(r.jsx("h2",{children:x},`h2:${o}`)):i.push(r.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(r.jsx("ul",{className:"mf-md_ul",children:w.map((y,x)=>r.jsx("li",{children:v_(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(r.jsx("p",{className:"mf-md_p",children:p.map((w,y)=>r.jsxs(ve.Fragment,{children:[v_(w),y<p.length-1?r.jsx("br",{}):null]},`pl:${o}:${y}`))},`p:${o}`))}const l=["mf-md",t].filter(Boolean).join(" ");return r.jsx("div",{className:l,children:i})}const Yg="observe";function Ns(e){return!e||typeof e!="object"?null:e}function fp(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 Jg(e){const t=Ns(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 C0(e){if(Array.isArray(e)){if(e.length===0)return null;const n=[];for(const i of e){const o=Jg(i);if(!o)return null;n.push(o)}return n}const t=Jg(e);return t?[t]:null}function $0(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 A0(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 Xg({text:e}){const t=String(e||""),n=$0(t);if(n!==null)return r.jsx(lv,{value:n});const i=t.trim();return i.startsWith("{")||i.startsWith("[")?r.jsx("pre",{className:"run-details-output",children:t||"(none)"}):t.includes(`
45
- `)||A0(t)?r.jsx("div",{className:"run-details-output",children:r.jsx(N0,{text:t})}):r.jsx("pre",{className:"run-details-output",children:t||"(none)"})}function cv({value:e}){if(e==null)return r.jsx("pre",{className:"run-details-output",children:"(none)"});const t=C0(e);return t?r.jsx("div",{className:"mf-msg-list",children:t.map((n,i)=>r.jsxs("div",{className:"mf-msg",children:[r.jsxs("div",{className:"mf-msg-meta",children:[r.jsx("span",{className:`mf-msg-role ${n.role}`,children:n.role}),n.name?r.jsx("span",{className:"mf-msg-name",children:n.name}):null]}),r.jsx("div",{className:"mf-msg-content",children:r.jsx(Xg,{text:n.content})})]},`${n.role}:${i}`))}):typeof e=="string"?r.jsx(Xg,{text:e}):r.jsx(lv,{value:e})}function uv(e){const t=e.effect;return!t||typeof t!="object"?null:t}function ul(e){const t=uv(e);return(t&&typeof t.type=="string"?t.type:"")||"effect"}function Pm(e){const t=uv(e),n=t==null?void 0:t.payload;return!n||typeof n!="object"?null:n}function eg(e){const t=e.result;return!t||typeof t!="object"?null:t}function dv(e){if(ul(e)!=="tool_calls")return[];const n=eg(e),i=n&&Array.isArray(n.results)?n.results:null;if(!i)return[];const o=[];for(const l of i){const u=Ns(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 fv(e){if(ul(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=Ns(l);if(!u)continue;const c=typeof u.name=="string"?u.name.trim():"";if(!c)continue;const f=Ns(u.args)||Ns(u.arguments)||{};o.push({call_id:typeof u.call_id=="string"?u.call_id:void 0,name:c,args:f})}return o}function Om(e){const t=e.error;if(typeof t=="string")return t.trim();const n=Ns(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 hv(e){if(!e)return"";const t=e.reasoning;if(typeof t=="string")return t.trim();const n=Ns(t);return n&&typeof n.text=="string"?n.text.trim():""}function mv(e){const t=ul(e),n=Pm(e),i=eg(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=hv(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=Ns(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 mm(e){const t=typeof e.status=="string"?e.status:"unknown";return t==="failed"||Om(e.step)?"failed":t}function E0(e){const t=e.map(n=>mm(n));return t.some(n=>n==="failed")?"failed":t.some(n=>n==="waiting")?"waiting":t.some(n=>n==="running")?"running":"completed"}function x_(e){return e.filter(t=>!t.hidden)}function T0(e){const t=ul(e),n=Om(e);return x_(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 M0(e){const t=ul(e);return t==="llm_call"?"user":t==="tool_calls"?"tools":Om(e)?"errors":"raw"}function R0(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=Ns(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=Ns(_);return(p&&typeof p.id=="string"?p.id.trim():"")||""}).filter(Boolean);t.set(u,f)}return t}function _v(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(fp(_,42))}`:typeof _=="number"||typeof _=="boolean"?`${f}=${String(_)}`:_==null?`${f}=null`:`${f}=${fp(JSON.stringify(_),42)}`});return`${e}(${c.join(", ")}${u.length>5?", …":""})`}function L0(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 b_({item:e,label:t,toolDefs:n,defaultOpen:i=!1}){const o=e.step,l=ul(o),u=T0(o),c=M0(o),[f,_]=m.useState(c),[p,w]=m.useState(!!i),y=Pm(o),x=eg(o),S=Om(o),b=L0(e),$=e.nodeId?String(e.nodeId):"",E=e.runId?String(e.runId):"",L=l==="tool_calls"?fv(o):[],D=l==="tool_calls"?dv(o):[],M=L.map(ie=>_v(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=Ns(x==null?void 0:x.metadata),N=C?Ns(C._runtime_observability):null,P=N?Ns(N.llm_generate_kwargs):null,O=P&&Array.isArray(P.messages)?P.messages:null,ne=C?Ns(C._provider_request):null,B=ne?Ns(ne.payload):null,z=B&&Array.isArray(B.messages)?B.messages:null,G=Array.isArray(ie.messages)?ie.messages:[],T=O||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 hv(x)||null}return l==="tool_calls"&&f==="tools"?{tool_calls:L,tool_signatures:M,results:D}:o})(),Y=mv(o),X=mm(e),se=X==="completed"?"OK":X==="failed"?"ERROR":X==="waiting"?"WAITING":X.toUpperCase();return r.jsxs("details",{className:`agent-trace-entry ${X}`,open:p,onToggle:ie=>w(ie.currentTarget.open),children:[r.jsxs("summary",{className:"agent-trace-summary",children:[r.jsx("span",{className:`agent-trace-status ${X}`,children:se}),r.jsx("span",{className:"agent-cycle-stage","data-stage":t,children:t}),r.jsx("span",{className:"agent-trace-kind",children:l}),b?r.jsx("span",{className:"agent-trace-node",children:b}):null,$?r.jsx("span",{className:"agent-trace-node",children:$}):null,E?r.jsx("span",{className:"agent-trace-run",children:E}):null]}),Y?r.jsx("div",{className:"agent-trace-preview",children:Y}):null,r.jsxs("div",{className:"agent-trace-body",children:[r.jsx("div",{className:"agent-trace-tabs",children:u.map(ie=>r.jsx("button",{type:"button",className:`agent-trace-tab ${ie.id===f?"active":""}`,onClick:()=>_(ie.id),children:ie.label},ie.id))}),r.jsx(cv,{value:Z})]})]})}function I0({acts:e}){const t=e.flatMap(l=>dv(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 r.jsxs("details",{className:`agent-trace-entry ${o}`,open:!1,children:[r.jsxs("summary",{className:"agent-trace-summary",children:[r.jsx("span",{className:`agent-trace-status ${o}`,children:n.length?"ERROR":"OK"}),r.jsx("span",{className:"agent-cycle-stage","data-stage":Yg,children:Yg}),r.jsx("span",{className:"agent-trace-kind",children:"OBSERVATIONS"}),r.jsx("span",{className:"agent-trace-preview-inline",children:i})]}),r.jsx("div",{className:"agent-observe-body",children:t.length===0?r.jsx("div",{className:"agent-observe-empty",children:"(no tool results)"}):r.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 r.jsxs("details",{className:`agent-observe-result ${c}`,open:!1,children:[r.jsxs("summary",{className:"agent-observe-summary",children:[r.jsx("span",{className:`agent-trace-status ${c}`,children:f}),r.jsx("span",{className:"agent-observe-name",children:l.name}),l.call_id?r.jsx("span",{className:"agent-observe-callid",children:l.call_id}):null]}),r.jsx(cv,{value:_})]},`${l.name}:${l.call_id||""}:${u}`)})})})]})}function P0({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=ul(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:mm(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:mm(S),ts:S.ts},w.push(y)),y.items.push(S),b==="tool_calls"?y.acts.push(S):y.others.push(S),y.status=E0(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 r.jsxs("div",{className:"agent-trace-panel",children:[r.jsxs("div",{className:"agent-trace-header",children:[r.jsx("div",{className:"agent-trace-title",children:f}),r.jsxs("div",{className:"agent-trace-subtitle",children:[_,p?r.jsxs("span",{className:"agent-trace-subrun",children:[" ","sub_run_id: ",p,r.jsx("button",{type:"button",className:"agent-trace-copy",onClick:w=>{w.stopPropagation(),sv(p)},title:`Copy sub_run_id: ${p}`,"aria-label":"Copy sub run id",children:"⧉"}),o?r.jsx("button",{type:"button",className:"agent-trace-open",onClick:w=>{w.stopPropagation(),o()},title:"Open sub-run",children:"Open"}):null]}):null]})]}),u.length===0?r.jsx("div",{className:"agent-trace-empty",children:"No trace entries yet."}):r.jsxs("div",{className:"agent-cycle-list",children:[r.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?mv(w.think.step):"",E=w.think?R0(w.think.step):new Map,D=w.acts.flatMap(H=>fv(H.step)).map(H=>_v(H.name,H.args,E.get(H.name)||null)),M=l&&w.index===c.length;return r.jsxs("details",{className:`agent-cycle ${y}`,open:M,children:[r.jsxs("summary",{className:"agent-cycle-summary",children:[r.jsx("span",{className:`agent-trace-status ${y}`,children:b}),r.jsx("span",{className:"agent-cycle-label",children:"cycle"}),r.jsxs("span",{className:"agent-cycle-index",children:["#",w.index]}),D.length?r.jsxs("span",{className:"agent-trace-badges",children:[D.slice(0,3).map(H=>r.jsx("span",{className:"run-metric-badge metric-tool",title:H,children:fp(H,62)},H)),D.length>3?r.jsxs("span",{className:"run-metric-badge metric-tool",children:["+",D.length-3]}):null]}):null,r.jsx("span",{className:"agent-cycle-spacer"}),$?r.jsx("span",{className:"agent-cycle-preview",children:$}):null]}),r.jsxs("div",{className:"agent-cycle-body",children:[w.think?r.jsx(b_,{item:w.think,label:"think",toolDefs:E,defaultOpen:M}):null,w.acts.map(H=>r.jsx(b_,{item:H,label:"act",toolDefs:E},H.id)),r.jsx(I0,{acts:w.acts}),w.others.length?r.jsxs("div",{className:"agent-cycle-others",children:[r.jsx("div",{className:"agent-cycle-others-title",children:"other"}),w.others.map(H=>{const Z=M&&ul(H.step)==="answer_user";return r.jsx(b_,{item:H,label:"other",toolDefs:E,defaultOpen:Z},H.id)})]}):null]})]},w.id)})]})]})}function eo(e){return typeof e=="string"?e.trim():""}function O0(e){var t;return eo(e.run_id)||eo((t=e.record)==null?void 0:t.run_id)}function hp(e){return eo(e==null?void 0:e.node_id)}const D0=new Set(["reason","act","observe","thought","think"]);function mp(e){const t=eo(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 D0.has(i)?n.slice(0,-1).join("::"):t}function pv(e){var t;return eo((t=e==null?void 0:e.effect)==null?void 0:t.type)}function F0(e){return eo(e==null?void 0:e.status)||"unknown"}function Zg(e){return eo(e==null?void 0:e.step_id)}function z0(e){return eo(e==null?void 0:e.ended_at)||eo(e==null?void 0:e.started_at)}function B0(e){const t=new Map,n=new Map;for(const o of e){const l=mp(hp(o));if(!l)continue;const u=pv(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 U0(e,t){const n=eo(t.run_id);if(!n)return{run_id:"",node_id:"",items:[]};const i=(Array.isArray(e)?e:[]).filter(x=>x&&x.record&&O0(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=mp(eo(t.node_id)),u=l||B0(o),c=new Set(["llm_call","tool_calls","ask_user","answer_user"]);let f=i.filter(x=>c.has(pv(x.record)));l&&(f=f.filter(x=>mp(hp(x.record))===l));const _=new Map,p=[];for(const x of f){const S=Zg(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=hp(S)||"(node?)",$=z0(S),E=Zg(S);return{id:`ledger:${n}:${x.cursor}:${E||""}`,runId:n,nodeId:b,ts:$||void 0,status:F0(S),step:S}});return{run_id:n,node_id:u,items:y}}function Dm(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 W0(e){if(e==null)return"";if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}}function q0(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 H0(e){return e.endsWith(`
46
- `)?e:`${e}
47
- `}function V0(e){return String(e||"").trimStart().startsWith("```")}function G0(e,t){const i=[`# ${String((t==null?void 0:t.heading)||"Chat").trim()||"Chat"}`,""];for(const o of e){const l=q0(o);i.push(`## ${l}`,"");const u=String(o.content||""),c=Dm(u);c!==null&&!V0(u)?i.push("```json",W0(c).trimEnd(),"```",""):i.push(H0(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 K0(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 Y0=3,J0=Number.MAX_SAFE_INTEGER;function gv(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function yv(e){return Array.isArray(e)}function X0(e){if(e==null)return"";if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}}function Cu({kind:e,children:t}){return r.jsx("span",{className:`pc-json-token ${e}`,children:t})}function Z0(e){const t=JSON.stringify(e.value),n=t.length>96||t.includes("\\n")||t.includes("\\r")||t.includes("\\t"),[i,o]=m.useState(!n||e.expansionMode==="unfolded");return m.useEffect(()=>{n&&o(e.expansionMode==="unfolded")},[n,e.expansionMode,e.expansionVersion]),n?r.jsxs("span",{className:`pc-json-string ${i?"open":"collapsed"}`,children:[r.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?r.jsx("span",{className:"pc-json-token string pc-json-string__value",children:t}):r.jsxs("button",{type:"button",className:"pc-json-string__preview",onClick:()=>o(!0),"aria-label":"Expand string value",children:[r.jsx("span",{className:"pc-json-token string pc-json-string__preview_text",children:t}),r.jsx("span",{className:"pc-json-string__suffix",children:"(...)"})]})]}):r.jsx(Cu,{kind:"string",children:t})}function Q0(e,t,n){return e===null?r.jsx(Cu,{kind:"null",children:"null"}):typeof e=="string"?r.jsx(Z0,{value:e,expansionMode:t,expansionVersion:n}):typeof e=="number"?r.jsx(Cu,{kind:"number",children:String(e)}):typeof e=="boolean"?r.jsx(Cu,{kind:"boolean",children:e?"true":"false"}):r.jsx(Cu,{kind:"string",children:JSON.stringify(String(e))})}function ej(e){return yv(e)?e.length===1?"1 item":`${e.length} items`:gv(e)?Object.keys(e).length===1?"1 key":`${Object.keys(e).length} keys`:""}function wv(e){const{label:t,value:n,depth:i,collapseAfterDepth:o,expansionMode:l,expansionVersion:u,trailingComma:c}=e,f=i*14,_=gv(n),p=yv(n),w=_||p,y=i<o,[x,S]=m.useState(y);m.useEffect(()=>{S(y)},[y,u]);const b=t?r.jsxs(r.Fragment,{children:[r.jsx(Cu,{kind:"key",children:JSON.stringify(t)}),": "]}):null;if(!w)return r.jsxs("div",{className:"pc-json-viewer__line",style:{paddingLeft:f},children:[b,Q0(n,l,u),c?",":""]});const $=p?"[":"{",E=p?"]":"}",L=ej(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 r.jsxs("details",{className:"pc-json-viewer__details",open:x,onToggle:H=>S(H.currentTarget.open),children:[r.jsxs("summary",{className:"pc-json-viewer__summary",style:{paddingLeft:f},children:[b,r.jsx("span",{className:"pc-json-viewer__caret","aria-hidden":"true",children:x?"▾":"▸"}),r.jsx("span",{className:"pc-json-viewer__punct",children:D}),!x&&c?r.jsx("span",{className:"pc-json-viewer__punct",children:","}):null]}),x?r.jsx("div",{className:"pc-json-viewer__children",children:M.length===0?r.jsxs("div",{className:"pc-json-viewer__line",style:{paddingLeft:f},children:[r.jsx("span",{className:"pc-json-viewer__punct",children:E}),c?",":""]}):r.jsxs(r.Fragment,{children:[M.map((H,Z)=>{const Y=Z===M.length-1;return r.jsx(wv,{label:H.label,value:H.value,depth:i+1,collapseAfterDepth:o,expansionMode:l,expansionVersion:u,trailingComma:!Y},`${i}:${t||"root"}:${H.key}`)}),r.jsxs("div",{className:"pc-json-viewer__line",style:{paddingLeft:f},children:[r.jsx("span",{className:"pc-json-viewer__punct",children:E}),c?",":""]})]})}):null]})}function tj(e){const t=e.trim();if(!t)return e;if(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))try{return JSON.parse(t)}catch{return e}return e}function ds(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):Y0,c=o.mode==="unfolded"?J0:u,f=m.useMemo(()=>typeof t=="string"?tj(t):t,[t]),_=m.useMemo(()=>X0(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 r.jsxs("div",{className:p,children:[r.jsxs("div",{className:"pc-json-viewer__toolbar",children:[r.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?r.jsx("button",{type:"button",className:"pc-btn pc-json-viewer__copy",onClick:()=>void dc(_),children:"Copy JSON"}):null]}),r.jsx("div",{className:"pc-json-viewer__tree",role:"tree","aria-label":"JSON viewer",children:r.jsx(wv,{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(r.jsx("span",{id:f,className:t.className,children:_},`hl:${t.hits}`)),t.hits+=1,l=u+c.length}return i}function vv(e){const t=String(e||"").trim();if(t&&/^(https?:|mailto:|tel:|#|\/)/i.test(t))return t}const _p="http://same-origin.invalid/";function nj(e){try{const t=new URL(e,_p);return t.protocol==="http:"&&t.origin===new URL(_p).origin}catch{return!1}}function xv(e){const t=String(e||"").trim();return vv(t)??(t&&nj(t)?t:void 0)}let oc=null;function rj(e){const t=String(e||"").trim();if(!t)return!1;const n=typeof document<"u"&&document.baseURI?document.baseURI:null;if(n===null&&/^[a-z][a-z0-9+.-]*:/i.test(t))return!1;const i=n??_p;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 bv(e,t,n){return r.jsx("a",{className:"pc-md_link pc-md_image_link",href:t,target:"_blank",rel:"noopener noreferrer",children:`image: ${n||t}`},e)}function nl(e,t){const n=[],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=xv(i.slice(f+2,_));if(w&&oc&&!oc(w)){u(),n.push(bv(`img:${o}`,w,p)),o=_+1;continue}if(w){u(),n.push(r.jsxs("span",{className:"pc-md_image_inline",children:[r.jsx("img",{className:"pc-md_img",src:w,alt:p,loading:"lazy"}),p?r.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=vv(i.slice(f+2,_));if(w){u(),n.push(r.jsx("a",{className:"pc-md_link",href:w,target:w.startsWith("#")?void 0:"_blank",rel:"noreferrer",children:nl(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(r.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(r.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(r.jsx("em",{children:t?Bd(_,t):_},`em:${o}`)),o=f+1;continue}}l+=c,o+=1}return u(),n}function sj(e){return String(e??"").replace(/\r\n/g,`
50
- `).replace(/\r/g,`
51
- `).split(`
52
- `)}function om(e){const n=String(e??"").match(/^([ \t]*)(?:([-*+])|(\d{1,9})[.)])\s+(.*)$/);return n?{indent:n[1].replace(/\t/g," ").length,ordered:!!n[3],start:n[3]?Math.max(1,parseInt(n[3],10)||1):1,content:n[4]??""}:null}function ij(e){const t=[];for(const o of e){const l=om(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 jv(e,t,n){const i=e.items.map((o,l)=>r.jsxs("li",{children:[nl(o.content,t),o.children.map((u,c)=>jv(u,t,`${n}:${l}:${c}`))]},`${n}:li:${l}`));return e.ordered?r.jsx("ol",{className:"pc-md_ol",start:e.start!==1?e.start:void 0,children:i},n):r.jsx("ul",{className:"pc-md_ul",children:i},n)}function oj(e,t,n){return ij(e).map((i,o)=>jv(i,t,`${n}:${o}`))}function Qg(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 ey(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 ty=/^(#{1,5})\s+(.*)$/;function ny(e){return e.trim().startsWith("```")}function ry(e){return e.trimStart().startsWith(">")}function Ni(e){const t=oc;oc=e.images==="link"?e.inlineImage||rj:null;try{return aj(e)}finally{oc=t}}function aj({text:e,className:t,highlight:n,highlights:i,highlightClassName:o,highlightId:l}){const u=sj(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(r.jsx("hr",{className:"pc-md_hr"},`hr:${w}`)),w+=1;continue}const b=x.match(/^\s*!\[([^\]]*)\]\(([^)]+)\)\s*$/);if(b){const L=xv(b[2]||"");if(L&&oc&&!oc(L)){c.push(r.jsx("p",{className:"pc-md_p",children:bv(`img:${w}`,L,b[1]||"")},`p:${w}`)),w+=1;continue}if(L){const D=b[1]||"";c.push(r.jsxs("figure",{className:"pc-md_figure",children:[r.jsx("img",{className:"pc-md_img",src:L,alt:D,loading:"lazy"}),D?r.jsx("figcaption",{children:nl(D,p)}):null]},`figure:${w}`)),w+=1;continue}}if(ny(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(r.jsx("pre",{className:"pc-md_pre",children:r.jsx("code",{className:D?`language-${D}`:void 0,children:H})},`pre:${w}`));continue}const $=x.match(ty);if($){const L=$[1].length,D=$[2]||"",M=nl(D,p);L===1?c.push(r.jsx("h1",{children:M},`h1:${w}`)):L===2?c.push(r.jsx("h2",{children:M},`h2:${w}`)):L===3?c.push(r.jsx("h3",{children:M},`h3:${w}`)):L===4?c.push(r.jsx("h4",{children:M},`h4:${w}`)):c.push(r.jsx("h5",{children:M},`h5:${w}`)),w+=1;continue}if(ry(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(r.jsx("blockquote",{className:"pc-md_quote",children:L.map((D,M)=>r.jsxs(ve.Fragment,{children:[nl(D,p),M<L.length-1?r.jsx("br",{}):null]},`q:${w}:${M}`))},`quote:${w}`));continue}if(x.includes("|")&&w+1<u.length&&ey(String(u[w+1]??""))){const L=Qg(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=Qg(H),Y=[];for(let X=0;X<D;X++)Y.push(Z[X]??"");M.push(Y),w+=1}c.push(r.jsx("div",{className:"pc-md_table_wrap",children:r.jsxs("table",{className:"pc-md_table",children:[r.jsx("thead",{children:r.jsx("tr",{children:L.slice(0,D).map((H,Z)=>r.jsx("th",{children:nl(H,p)},`th:${w}:${Z}`))})}),r.jsx("tbody",{children:M.map((H,Z)=>r.jsx("tr",{children:H.map((Y,X)=>r.jsx("td",{children:nl(Y,p)},`td:${w}:${Z}:${X}`))},`tr:${w}:${Z}`))})]})},`table:${w}`));continue}if(om(x)){const L=[];for(;w<u.length;){const D=String(u[w]??"");if(!D.trim()||D.trimStart().startsWith("```"))break;if(om(D)||/^\s{2,}\S/.test(D)){L.push(D),w+=1;continue}break}c.push(r.jsx(ve.Fragment,{children:oj(L,p,`list:${w}`)},`list:${w}`));continue}const E=[];for(;w<u.length&&String(u[w]??"").trim()&&!(E.length>0&&om(String(u[w]??"")));){const L=String(u[w]??"");if(E.length>0&&(ty.test(L)||ny(L)||ry(L))||E.length>0&&L.includes("|")&&w+1<u.length&&ey(String(u[w+1]??"")))break;E.push(L),w+=1}c.push(r.jsx("p",{className:"pc-md_p",children:E.map((L,D)=>r.jsxs(ve.Fragment,{children:[nl(L,p),D<E.length-1?r.jsx("br",{}):null]},`pl:${w}:${D}`))},`p:${w}`))}const y=["pc-md",t].filter(Boolean).join(" ");return r.jsx("div",{className:y,children:c})}function Sv(e){const t=String(e.text??""),n=m.useMemo(()=>Dm(t),[t]),i=["pc-chat-content",e.className].filter(Boolean).join(" ");return n!==null?r.jsx("div",{className:i,children:r.jsx(ds,{value:n,collapseAfterDepth:e.jsonCollapseAfterDepth})}):e.renderMarkdown?r.jsx("div",{className:i,children:e.renderMarkdown(t)}):r.jsx("div",{className:i,children:r.jsx(Ni,{text:t,images:e.images,inlineImage:e.inlineImage})})}const kv=[{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"]}];kv.map(e=>({id:e.id,label:e.label}));function lj(e){return`theme-${String(e||"").trim()||"dark"}`}function sy(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(lj(e))}catch{}}const pp=[{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}],gp=[{id:"compact",label:"Compact",density:.85},{id:"standard",label:"Standard",density:1},{id:"spacious",label:"Spacious",density:1.2}];function cj(e){const t=String(e).trim();return pp.find(n=>n.id===t)||pp[1]}function uj(e){const t=String(e).trim();return gp.find(n=>n.id===t)||gp[1]}function iy(e){try{const t=document.documentElement,n=cj(e.font_scale||"md"),i=uj(e.header_density||"standard");t.style.setProperty("--font-scale",String(n.scale)),t.style.setProperty("--header-density",String(i.density))}catch{}}var Nv=rv();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),se=m.useRef($),ie=m.useId(),ue=S||`af-select-${ie.replace(/[^a-zA-Z0-9_-]/g,"")}`,F=`${ue}-listbox`,[C,N]=m.useState(!1),[P,O]=m.useState(""),[ne,B]=m.useState(0),[z,G]=m.useState("bottom"),[T,Q]=m.useState({left:0,top:0,width:0});m.useEffect(()=>{se.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=P.trim().toLowerCase();return ge?K.filter(De=>De.label.toLowerCase().includes(ge)||De.value.toLowerCase().includes(ge)):K},[K,P]),me=m.useMemo(()=>{if(!c)return null;const ge=P.trim();if(!ge||K.some(Dt=>Dt.value===ge))return null;const Ke=(L==null?void 0:L(ge,{options:K}))||"";return{value:ge,label:E?E(ge):`Use "${ge}"`,disabled:!!Ke,reason:Ke}},[c,E,K,P,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),O("")},[]);m.useEffect(()=>{var ge;C&&((ge=se.current)==null||ge.call(se))},[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},Oe=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=r.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 r.jsxs("span",{className:pu("af-select",p==="pin"?"af-select--pin":"af-select--panel",w),children:[r.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:Oe,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,r.jsx("span",{className:pu("af-select-caret",C&&"af-select-caret--open"),children:"▾"})]}),f&&et?r.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?Nv.createPortal(r.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?r.jsxs("div",{className:"af-select-search",children:[r.jsx("input",{ref:X,className:"af-select-search-input",value:P,onChange:ge=>O(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?r.jsx("div",{id:`${ue}-custom-error`,className:"af-select-custom-error",role:"alert",children:Ye}):null]}):null,r.jsx("div",{className:"af-select-options",role:"listbox",id:F,"aria-label":x,children:o&&we.length===0?r.jsx("div",{className:"af-select-empty",children:"Loading…"}):we.length===0?r.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 r.jsxs(ve.Fragment,{children:[Ut?r.jsx("div",{className:"af-select-group",role:"presentation",children:Qt}):null,r.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}):r.jsxs(r.Fragment,{children:[r.jsxs("span",{className:"af-select-option-label",children:[r.jsx("span",{children:ge.label}),ge.reason?r.jsx("small",{className:"af-select-option-reason",children:ge.reason}):null]}),Ke?r.jsx("span",{className:"af-select-check",children:"✓"}):null]})})]},ge.value)})})]}),document.body):null]})}function dj(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 fj(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 hj(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=dj(e.providers),y=fj(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 r.jsxs("div",{className:e.className,style:n==="row"?{display:"flex",gap:"10px",flexWrap:"wrap",alignItems:"flex-start"}:{display:"flex",flexDirection:"column",gap:"10px"},children:[r.jsxs("div",{style:n==="row"?{flex:"1 1 260px",minWidth:240}:void 0,children:[r.jsx("label",{children:l}),r.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?r.jsx("div",{className:"mono muted",style:{fontSize:"12px",marginTop:"6px"},children:"Loading providers…"}):null,e.providerError?r.jsx("div",{className:"mono",style:{color:"var(--error)",fontSize:"12px",marginTop:"6px"},children:e.providerError}):null]}),r.jsxs("div",{style:n==="row"?{flex:"1 1 260px",minWidth:240}:void 0,children:[r.jsx("label",{children:u}),r.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?r.jsx("div",{className:"mono muted",style:{fontSize:"12px",marginTop:"6px"},children:"Loading models…"}):null,e.modelError?r.jsx("div",{className:"mono",style:{color:"var(--error)",fontSize:"12px",marginTop:"6px"},children:e.modelError}):null]})]})}function oy(...e){return e.filter(Boolean).join(" ")}function mj({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:se="Signing in...",closeLabel:ie="Close",signOutLabel:ue="Sign out",showClose:F=!1,showSignOut:C=!1,error:N,message:P,className:O,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 r.jsxs("form",{className:oy("af-gateway-signin",O),onSubmit:Q,children:[r.jsxs("div",{className:"af-gateway-signin__hero",children:[r.jsxs("div",{children:[r.jsx("div",{className:"af-gateway-signin__kicker",children:e}),r.jsx("h2",{children:t}),n?r.jsx("p",{children:n}):null]}),r.jsx("div",{className:"af-gateway-signin__mark","aria-hidden":"true",children:"↔"})]}),r.jsxs("div",{className:"af-gateway-signin__status-row",children:[r.jsx("span",{className:oy("af-gateway-signin__status",`af-gateway-signin__status--${o}`),children:i}),l?r.jsx("span",{className:"af-gateway-signin__source",children:l}):null]}),r.jsxs("div",{className:"af-gateway-signin__form",children:[u?r.jsxs(r.Fragment,{children:[r.jsx("label",{className:"af-gateway-signin__label",htmlFor:"gateway-session-url",children:"Gateway URL"}),r.jsx("input",{id:"gateway-session-url",value:c,onChange:K=>_==null?void 0:_(K.target.value),placeholder:f,autoComplete:"url",disabled:G})]}):null,r.jsx("label",{className:"af-gateway-signin__label",htmlFor:"gateway-session-user",children:"Gateway user"}),r.jsx("input",{id:"gateway-session-user",value:p,onChange:K=>y(K.target.value),placeholder:w,autoComplete:"username",disabled:G}),r.jsx("label",{className:"af-gateway-signin__label",htmlFor:"gateway-session-token",children:"Gateway token"}),r.jsxs("div",{className:"af-gateway-signin__token-input",children:[r.jsx("input",{id:"gateway-session-token",type:b?"text":"password",value:x,onChange:K=>$(K.target.value),placeholder:S,autoComplete:"current-password",disabled:G}),r.jsx("button",{className:"af-gateway-signin__secondary",type:"button",onClick:()=>E==null?void 0:E(!b),disabled:G,children:b?"Hide":"Show"})]}),r.jsx("label",{className:"af-gateway-signin__label",children:"Browser session"}),r.jsxs("label",{className:"af-gateway-signin__checkbox",children:[r.jsx("input",{type:"checkbox",checked:!!L,onChange:K=>M==null?void 0:M(K.target.checked),disabled:G}),D]})]}),N?r.jsx("div",{className:"af-gateway-signin__message af-gateway-signin__message--error",children:N}):null,!N&&P?r.jsx("div",{className:"af-gateway-signin__message af-gateway-signin__message--ok",children:P}):null,r.jsxs("div",{className:"af-gateway-signin__actions",children:[F?r.jsx("button",{className:"af-gateway-signin__secondary",type:"button",onClick:B,disabled:G,children:ie}):null,C?r.jsx("button",{className:"af-gateway-signin__secondary",type:"button",onClick:()=>void(z==null?void 0:z()),disabled:G,children:ue}):null,r.jsx("button",{className:"af-gateway-signin__primary",type:"submit",disabled:T,children:Z?se:X})]})]})}function _j(e){return e==="light"?"Light":"Dark"}function pj(e){const t=e.themes&&e.themes.length?e.themes:kv,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:_j(u.group)})),[t]);return r.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 r.jsxs("span",{className:"af-theme-value",children:[r.jsx("span",{className:`af-theme-label ${y?"af-theme-label--placeholder":""}`.trim(),children:p}),n&&w?r.jsx("span",{className:"af-theme-swatches","aria-hidden":"true",children:w.map((x,S)=>r.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 r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"af-theme-option-label",children:u.label}),r.jsxs("span",{className:"af-theme-option-right",children:[n&&p?r.jsx("span",{className:"af-theme-swatches","aria-hidden":"true",children:p.map((w,y)=>r.jsx("span",{className:"af-theme-swatch",style:{background:w}},`${f}:${y}`))}):null,c.selected?r.jsx("span",{className:"af-select-check",children:"✓"}):null]})]})}})}function gj(e){const t=e.scales&&e.scales.length?e.scales:pp,n=e.variant||"panel",i=m.useMemo(()=>t.map(o=>({value:o.id,label:o.label})),[t]);return r.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 yj(e){const t=e.densities&&e.densities.length?e.densities:gp,n=e.variant||"panel",i=m.useMemo(()=>t.map(o=>({value:o.id,label:o.label})),[t]);return r.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 wj=new Set(["board","inbox","server","agent","playCircle","list","gear"]);function vj(e){switch(e){case"chat":return r.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 r.jsxs(r.Fragment,{children:[r.jsx("path",{d:"M12 5v14"}),r.jsx("path",{d:"M5 12h14"})]});case"history":return r.jsxs(r.Fragment,{children:[r.jsx("circle",{cx:"12",cy:"12",r:"9"}),r.jsx("path",{d:"M12 7v5l3 3"})]});case"refresh":return r.jsxs(r.Fragment,{children:[r.jsx("path",{d:"M21 12a9 9 0 0 0-15.5-6.4L3 8"}),r.jsx("path",{d:"M3 3v5h5"}),r.jsx("path",{d:"M3 12a9 9 0 0 0 15.5 6.4L21 16"}),r.jsx("path",{d:"M21 21v-5h-5"})]});case"settings":return r.jsxs(r.Fragment,{children:[r.jsx("path",{d:"M4 6h16"}),r.jsx("circle",{cx:"8",cy:"6",r:"2"}),r.jsx("path",{d:"M4 12h16"}),r.jsx("circle",{cx:"16",cy:"12",r:"2"}),r.jsx("path",{d:"M4 18h16"}),r.jsx("circle",{cx:"10",cy:"18",r:"2"})]});case"user":return r.jsxs(r.Fragment,{children:[r.jsx("circle",{cx:"12",cy:"8",r:"4"}),r.jsx("path",{d:"M4 21a8 8 0 0 1 16 0"})]});case"bot":return r.jsxs(r.Fragment,{children:[r.jsx("path",{d:"M12 2v3"}),r.jsx("rect",{x:"5",y:"6",width:"14",height:"14",rx:"3"}),r.jsx("circle",{cx:"9",cy:"13",r:"1",fill:"currentColor",stroke:"none"}),r.jsx("circle",{cx:"15",cy:"13",r:"1",fill:"currentColor",stroke:"none"}),r.jsx("path",{d:"M9 17h6"})]});case"paperclip":return r.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 r.jsxs(r.Fragment,{children:[r.jsx("path",{d:"M12 14a3 3 0 0 0 3-3V5a3 3 0 0 0-6 0v6a3 3 0 0 0 3 3z"}),r.jsx("path",{d:"M19 11a7 7 0 0 1-14 0"}),r.jsx("path",{d:"M12 18v4"}),r.jsx("path",{d:"M8 22h8"})]});case"speaker":return r.jsxs(r.Fragment,{children:[r.jsx("path",{d:"M11 5L6 9H2v6h4l5 4V5z"}),r.jsx("path",{d:"M15.5 8.5a5 5 0 0 1 0 7"}),r.jsx("path",{d:"M18 6a9 9 0 0 1 0 12"})]});case"pause":return r.jsxs(r.Fragment,{children:[r.jsx("rect",{x:"6",y:"4",width:"4",height:"16",rx:"1",fill:"currentColor",stroke:"none"}),r.jsx("rect",{x:"14",y:"4",width:"4",height:"16",rx:"1",fill:"currentColor",stroke:"none"})]});case"terminal":return r.jsxs(r.Fragment,{children:[r.jsx("rect",{x:"3",y:"4",width:"18",height:"16",rx:"2",ry:"2"}),r.jsx("path",{d:"M7 9l3 3-3 3"}),r.jsx("path",{d:"M12 15h5"})]});case"edit":return r.jsxs(r.Fragment,{children:[r.jsx("path",{d:"M12 20h9"}),r.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 r.jsxs(r.Fragment,{children:[r.jsx("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),r.jsx("path",{d:"M7 10l5 5 5-5"}),r.jsx("path",{d:"M12 15V3"})]});case"loader":return r.jsx("path",{d:"M21 12a9 9 0 1 1-3.3-6.9"});case"info":return r.jsxs(r.Fragment,{children:[r.jsx("circle",{cx:"12",cy:"12",r:"10"}),r.jsx("path",{d:"M12 16v-4"}),r.jsx("circle",{cx:"12",cy:"8",r:"0.75",fill:"currentColor",stroke:"none"})]});case"warning":return r.jsxs(r.Fragment,{children:[r.jsx("path",{d:"M12 3l10 18H2L12 3z"}),r.jsx("path",{d:"M12 9v4"}),r.jsx("circle",{cx:"12",cy:"17",r:"0.75",fill:"currentColor",stroke:"none"})]});case"error":return r.jsxs(r.Fragment,{children:[r.jsx("circle",{cx:"12",cy:"12",r:"10"}),r.jsx("path",{d:"M15 9l-6 6"}),r.jsx("path",{d:"M9 9l6 6"})]});case"copy":return r.jsxs(r.Fragment,{children:[r.jsx("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2"}),r.jsx("path",{d:"M5 15V5a2 2 0 0 1 2-2h10"})]});case"check":return r.jsx("path",{d:"M20 6L9 17l-5-5"});case"x":return r.jsxs(r.Fragment,{children:[r.jsx("path",{d:"M18 6L6 18"}),r.jsx("path",{d:"M6 6l12 12"})]});case"chevronDown":return r.jsx("path",{d:"M6 9l6 6 6-6"});case"chevronRight":return r.jsx("path",{d:"M9 18l6-6-6-6"});case"trash":return r.jsxs(r.Fragment,{children:[r.jsx("path",{d:"M3 6h18"}),r.jsx("path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"}),r.jsx("path",{d:"M6 6l1 16h10l1-16"}),r.jsx("path",{d:"M10 11v6"}),r.jsx("path",{d:"M14 11v6"})]});case"send":return r.jsxs(r.Fragment,{children:[r.jsx("path",{d:"M22 2L11 13"}),r.jsx("path",{d:"M22 2L15 22l-4-9-9-4 20-7z"})]});case"thumbsUp":return r.jsxs(r.Fragment,{children:[r.jsx("path",{d:"M7 10v11"}),r.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 r.jsxs(r.Fragment,{children:[r.jsx("path",{d:"M17 14V3"}),r.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 r.jsxs(r.Fragment,{children:[r.jsx("path",{d:"M7 10v11"}),r.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 r.jsxs(r.Fragment,{children:[r.jsx("path",{d:"M17 14V3"}),r.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 r.jsxs(r.Fragment,{children:[r.jsx("rect",{x:"1.5",y:"2",width:"3.6",height:"12",rx:"1"}),r.jsx("rect",{x:"6.2",y:"2",width:"3.6",height:"8.5",rx:"1"}),r.jsx("rect",{x:"10.9",y:"2",width:"3.6",height:"5.5",rx:"1"})]});case"inbox":return r.jsxs(r.Fragment,{children:[r.jsx("path",{d:"M2 9.5 L4 3.5 h8 l2 6"}),r.jsx("path",{d:"M2 9.5 v3 h12 v-3"}),r.jsx("path",{d:"M2 9.5 h3.4 l1 1.6 h3.2 l1-1.6 H14"})]});case"server":return r.jsxs(r.Fragment,{children:[r.jsx("rect",{x:"2",y:"2.5",width:"12",height:"4.6",rx:"1.2"}),r.jsx("rect",{x:"2",y:"8.9",width:"12",height:"4.6",rx:"1.2"}),r.jsx("circle",{cx:"4.6",cy:"4.8",r:"0.8",fill:"currentColor",stroke:"none"}),r.jsx("circle",{cx:"4.6",cy:"11.2",r:"0.8",fill:"currentColor",stroke:"none"})]});case"agent":return r.jsxs(r.Fragment,{children:[r.jsx("rect",{x:"3",y:"4.5",width:"10",height:"8",rx:"2"}),r.jsx("path",{d:"M8 4.5V2.2"}),r.jsx("circle",{cx:"8",cy:"1.8",r:"0.9",fill:"currentColor",stroke:"none"}),r.jsx("circle",{cx:"5.8",cy:"8.4",r:"0.9",fill:"currentColor",stroke:"none"}),r.jsx("circle",{cx:"10.2",cy:"8.4",r:"0.9",fill:"currentColor",stroke:"none"})]});case"playCircle":return r.jsxs(r.Fragment,{children:[r.jsx("circle",{cx:"8",cy:"8",r:"6.2"}),r.jsx("path",{d:"M6.5 5.6 L11 8 L6.5 10.4 Z",fill:"currentColor",stroke:"none"})]});case"list":return r.jsxs(r.Fragment,{children:[r.jsx("path",{d:"M2.5 4h11"}),r.jsx("path",{d:"M2.5 8h11"}),r.jsx("path",{d:"M2.5 12h7"})]});case"gear":return r.jsxs(r.Fragment,{children:[r.jsx("circle",{cx:"8",cy:"8",r:"2.2"}),r.jsx("path",{d:"M8 1.6v2"}),r.jsx("path",{d:"M8 12.4v2"}),r.jsx("path",{d:"M1.6 8h2"}),r.jsx("path",{d:"M12.4 8h2"}),r.jsx("path",{d:"M3.5 3.5l1.4 1.4"}),r.jsx("path",{d:"M11.1 11.1l1.4 1.4"}),r.jsx("path",{d:"M12.5 3.5l-1.4 1.4"}),r.jsx("path",{d:"M4.9 11.1l-1.4 1.4"})]});case"sparkle":return r.jsxs(r.Fragment,{children:[r.jsx("path",{d:"M12 3l1.9 5.1L19 10l-5.1 1.9L12 17l-1.9-5.1L5 10l5.1-1.9z"}),r.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 r.jsxs(r.Fragment,{children:[r.jsx("circle",{cx:"12",cy:"12",r:"9"}),r.jsx("path",{d:"M12 3a9 9 0 0 1 0 18z",fill:"currentColor",stroke:"none"})]});case"logout":return r.jsxs(r.Fragment,{children:[r.jsx("path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"}),r.jsx("path",{d:"M16 17l5-5-5-5"}),r.jsx("path",{d:"M21 12H9"})]});case"play":return r.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 r.jsx("rect",{x:"5",y:"5",width:"14",height:"14",rx:"2",fill:"currentColor",stroke:"none"});case"folder":return r.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 r.jsxs(r.Fragment,{children:[r.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),r.jsx("path",{d:"M14 2v6h6"})]});case"archive":return r.jsxs(r.Fragment,{children:[r.jsx("rect",{x:"2",y:"3",width:"20",height:"5",rx:"1"}),r.jsx("path",{d:"M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8"}),r.jsx("path",{d:"M10 12h4"})]});case"clock":return r.jsxs(r.Fragment,{children:[r.jsx("circle",{cx:"12",cy:"12",r:"10"}),r.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=wj.has(e);return r.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?r.jsx("title",{children:i}):null,vj(e)]})}const yp="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?`${yp}/${t}`:yp}function Cv(e,t){const n=String(t||"");if(n.startsWith("/"))throw new Error(`joinBaseUrl takes a relative path, got ${JSON.stringify(n)}.`);let i=String(e??"");for(;i.endsWith("/");)i=i.slice(0,-1);return i?`${i}/${n}`:n}function xj(e){const t=String(e||""),n=`/${yp}/`;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 wp(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 bj(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 $v(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 j_(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 Av(e){var l,u;if(!e)return{label:"Signed out",tone:"warn"};if(!e.has_session)return{label:"Signed out",tone:"warn"};const t=e.gateway||{},n=(l=t.principal)==null?void 0:l.user_id,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 jj(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(()=>Av(u),[u]),se=C=>{var N;c(C),(N=e.onStatusChange)==null||N.call(e,C)},ie=m.useRef(!1);if(m.useEffect(()=>{var N;if(!e.isOpen)return;const C=!ie.current;if(ie.current=!0,C&&e.initialStatus!==void 0&&e.initialStatus!==null){const P=e.initialStatus;se(P),typeof P.gateway_url=="string"&&P.gateway_url.trim()&&w(j_(P.gateway_url));const O=(N=P.gateway)==null?void 0:N.principal;O!=null&&O.user_id&&x(O.user_id);return}i(!0),H(""),wp(t).then(P=>{var ne;se(P),typeof P.gateway_url=="string"&&P.gateway_url.trim()&&w(j_(P.gateway_url));const O=(ne=P.gateway)==null?void 0:ne.principal;O!=null&&O.user_id&&x(O.user_id)}).catch(P=>H(`Failed to load connection status: ${String((P==null?void 0:P.message)||P)}`)).finally(()=>i(!1))},[e.isOpen]),m.useEffect(()=>{if(!e.isOpen)return;const C=N=>{N.key==="Escape"&&!N.defaultPrevented&&!e.blocking&&(N.preventDefault(),e.onClose())};return window.addEventListener("keydown",C),()=>window.removeEventListener("keydown",C)},[e.isOpen,e.blocking,e.onClose]),!e.isOpen||f)return null;const ue=async()=>{l(!0),H(""),Y("");try{const C=j_(p);w(C);const N=await bj({gateway_url:C,gateway_user_id:y,gateway_token:S,persist:L},t);se(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 $v(t),b("");const C=await wp(t).catch(()=>null);se(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 r.jsx("div",{className:"af-connect-overlay",role:"presentation",onMouseDown:C=>{!e.blocking&&C.target===C.currentTarget&&e.onClose()},children:r.jsx("div",{className:"af-connect-modal",role:"dialog","aria-modal":"true","aria-label":"Gateway connection",children:r.jsx(mj,{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 Sj(e){return!!(e&&e.ok===!0&&e.has_session===!0)}function kj(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 O;L.current+=1,f(N),(O=o.current)==null||O.call(o,N);const P=Sj(N);if(P)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=P)},[]),M=m.useCallback(async()=>{const N=L.current;try{const P=await wp(n);if(L.current!==N)return;D(P)}catch{if(L.current!==N)return;D(null)}},[n,D]),[H,Z]=m.useState(!1),[Y,X]=m.useState(null),se=m.useCallback(async()=>{Z(!0),X(null),L.current+=1;let N=null;try{await $v(n)}catch(P){N=String((P==null?void 0:P.message)||P||"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:se,modalProps:C}}function Nj(){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 Cj(){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 $j(e){const t=e.commandsPath||bt("commands"),n=Nj(),i=JSON.stringify({command_id:n,run_id:e.runId,type:"inject_guidance",payload:{guidance:e.guidance}}),o=e.csrfToken!==void 0?[e.csrfToken]:Cj();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 Aj(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 $j({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 r.jsxs("div",{className:`af-steer${e.className?` ${e.className}`:""}`,children:[r.jsxs("div",{className:"af-steer__row",children:[r.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}),r.jsx("button",{type:"button",className:"af-steer__send",disabled:!c,onClick:()=>void _(),title:"Send guidance (Cmd/Ctrl+Enter)",children:i.kind==="sending"?"Sending…":"Steer"})]}),r.jsx("div",{className:"af-steer__status",role:"status","aria-live":"polite",children:i.kind==="queued"?r.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"?r.jsx("span",{className:"af-steer__err",children:i.detail}):r.jsx("span",{className:"af-steer__hint",children:f})})]})}function Ej(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]),r.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?r.jsxs("div",{className:"af-drawer__header",children:[r.jsx("div",{className:"af-drawer__title",children:e.title}),r.jsxs("div",{className:"af-drawer__header-actions",children:[e.headerActions,r.jsx("button",{type:"button",className:"af-drawer__close","aria-label":"Close panel",onClick:e.onClose,children:"×"})]})]}):null,r.jsx("div",{className:"af-drawer__body",children:e.children})]})}const Tj={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"},Mj={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"}},Rj={framework:Tj,apps:Mj},_m=Rj;function Lj(){return Object.keys(_m.apps).sort()}function Ij(e,t){const n=Object.prototype.hasOwnProperty.call(_m.apps,e)?_m.apps[e]:void 0;if(!n)throw new Error(`appIdentity: unknown application id "${e}" (known: ${Lj().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 Pj(e,t){const n=_m.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 S_(e){return typeof e=="string"?e.trim():""}function ay(e,t){if(t!=null)return[["Gateway",`unavailable (${String(t).trim()||"unknown error"})`]];const n=e&&typeof e=="object"&&!Array.isArray(e)?e:{},i=S_(n.abstractgateway);if(!i)return[["Gateway","unavailable (the gateway did not report its version)"]];const o=S_(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 _=S_(u[f]);_&&l.push([`Gateway package ${f}`,_])}return l}const Oj='a[href], button:not(:disabled), input:not(:disabled), select:not(:disabled), textarea:not(:disabled), [tabindex]:not([tabindex="-1"])';function Dj(e,t,n){if(e.key!=="Tab"||!t)return;const i=Array.from(t.querySelectorAll(Oj));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 Fj=/https?:\/\/[^\s<>"]+/g;function zj(e,t){if(e==="Contact")return[{text:t,href:`mailto:${t}`}];const n=[];let i=0;for(const o of t.matchAll(Fj)){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 Bj({label:e,value:t}){return r.jsx("span",{children:zj(e,t).map((n,i)=>n.href===void 0?r.jsx(ve.Fragment,{children:n.text},i):n.href.startsWith("mailto:")?r.jsx("a",{className:"af-about__link",href:n.href,children:n.text},i):r.jsx("a",{className:"af-about__link",href:n.href,target:"_blank",rel:"noopener noreferrer",children:n.text},i))})}function Uj(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}Dj(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=Pj(e.identity,e.extraRows);return r.jsx("div",{className:"af-appearance-overlay af-about-overlay",onClick:e.onClose,role:"presentation",children:r.jsxs("div",{ref:n,className:"af-appearance af-about",role:"dialog","aria-modal":"true","aria-labelledby":i,onClick:c=>c.stopPropagation(),children:[r.jsx("div",{className:"af-appearance__title",id:i,children:l}),r.jsx("dl",{className:"af-about__rows",children:u.map(([c,f],_)=>r.jsxs("div",{className:"af-about__row",children:[r.jsx("dt",{className:"af-about__label",children:c}),r.jsx("dd",{className:"af-about__value",children:r.jsx(Bj,{label:c,value:f})})]},`${_}:${c}`))}),r.jsx("div",{className:"af-appearance__actions",children:r.jsx("button",{ref:t,type:"button",className:"af-appearance__close",onClick:e.onClose,children:"Close"})})]})})}function Wj(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 r.jsxs("div",{className:`af-topbar${e.className?` ${e.className}`:""}`,role:"group","aria-label":"App actions",children:[e.assistant?r.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:r.jsx(Qe,{name:"sparkle",size:16})}):null,e.appearance?r.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:r.jsx(Qe,{name:"contrast",size:16})}):null,u?r.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:r.jsx(Qe,{name:"info",size:16})}):null,e.extraActions,r.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:[r.jsx("span",{className:`af-topbar__dot af-topbar__dot--${n}`,"aria-hidden":"true"}),r.jsx("span",{className:"af-topbar__pill-label",children:c})]}),u?r.jsx(Uj,{open:o,onClose:()=>l(!1),identity:u.identity,extraRows:u.extraRows}):null]})}const am={theme:"dark",font_scale:"md",header_density:"standard"};function qj(e){const t=e&&typeof e=="object"?e:{};return{theme:typeof t.theme=="string"&&t.theme?t.theme:am.theme,font_scale:typeof t.font_scale=="string"&&t.font_scale?t.font_scale:am.font_scale,header_density:typeof t.header_density=="string"&&t.header_density?t.header_density:am.header_density}}function Hj(e){return`af_appearance_${e}_v1`}function Vj(e,t){const n=Hj(e),i=m.useMemo(()=>({...am,...(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=qj({...i,...JSON.parse(c)}))}catch{}try{sy(u.theme),iy({font_scale:u.font_scale,header_density:u.header_density})}catch{}return u});return m.useEffect(()=>{sy(o.theme),iy({font_scale:o.font_scale,header_density:o.header_density});try{localStorage.setItem(n,JSON.stringify(o))}catch{}},[n,o]),[o,l]}function Gj(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?r.jsx("div",{className:"af-appearance-overlay",onClick:e.onClose,role:"presentation",children:r.jsxs("div",{className:"af-appearance",role:"dialog","aria-modal":"true","aria-label":e.title||"Appearance",onClick:t=>t.stopPropagation(),children:[r.jsx("div",{className:"af-appearance__title",children:e.title||"Appearance"}),r.jsx("div",{className:"af-appearance__note",children:e.note||"Stored locally in this browser, per app."}),r.jsxs("div",{className:"af-appearance__grid",children:[r.jsx("label",{className:"af-appearance__label",children:"Theme"}),r.jsx(pj,{value:e.value.theme,onChange:t=>e.onChange({...e.value,theme:t})}),r.jsx("label",{className:"af-appearance__label",children:"Font size"}),r.jsx(gj,{value:e.value.font_scale,onChange:t=>e.onChange({...e.value,font_scale:t})}),r.jsx("label",{className:"af-appearance__label",children:"Header size"}),r.jsx(yj,{value:e.value.header_density,onChange:t=>e.onChange({...e.value,header_density:t})})]}),r.jsx("div",{className:"af-appearance__actions",children:r.jsx("button",{type:"button",className:"af-appearance__close",onClick:e.onClose,children:"Close"})})]})}):null}const Kj={diary:"var(--accent)",question:"#e7b45a",dream:"#c084dd",interest:"#7bd88a",lesson:"#6ea8d8",world_model:"#5eead4"};function ly(e){const t=String(e||"");return t.length>14?`${t.slice(0,10)}…${t.slice(-4)}`:t}function k_(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&&Kj[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?r.jsxs("span",{className:["af-memory-hint","af-memory-hint--text",e.className||""].filter(Boolean).join(" "),title:e.title,children:[r.jsx("span",{className:"af-memory-hint__dot",style:{background:c},"aria-hidden":"true"}),r.jsx("span",{className:"af-memory-hint__label",children:e.label}),u&&e.showId!==!1?r.jsx("code",{className:"af-memory-hint__id",children:ly(u)}):null]}):r.jsxs("span",{className:["af-memory-hint",e.className||""].filter(Boolean).join(" "),children:[r.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:[r.jsx("span",{className:"af-memory-hint__dot",style:{background:c},"aria-hidden":"true"}),r.jsx("span",{className:"af-memory-hint__label",children:e.label}),e.showId!==!1?r.jsx("code",{className:"af-memory-hint__id",children:ly(u)}):null,r.jsx("span",{className:"af-memory-hint__act","aria-hidden":"true",children:t?"…":"↗"})]}),e.command?r.jsx("code",{className:"af-memory-hint__cmd",children:e.command}):null,i?r.jsx("span",{className:"af-memory-hint__err",role:"alert",children:i}):null]})}const N_=bt("automations"),Yj=bt("trigger-sources");class cy 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 Jj(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 C_(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 Xj(){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 Zj(e){const t=e.newId??Xj,n=o=>`${N_}/${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(Cv(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 cy(Jj(_.status,w));if(!y||w===null||typeof w!="object")throw new cy({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",`${N_}${C_({status:o.status,cursor:o.cursor,limit:o.limit})}`),getAutomation:o=>i("GET",n(o)),createAutomation:o=>i("POST",N_,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${C_({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${C_({cursor:l.cursor,limit:l.limit})}`),listTriggerSources:()=>i("GET",Yj)}}const Qj=/^([1-9][0-9]*)([smhd])$/,eS={s:["second","seconds"],m:["minute","minutes"],h:["hour","hours"],d:["day","days"]};function tg(e){if(typeof e!="string")return null;const t=Qj.exec(e);return t?{amount:Number(t[1]),unit:t[2]}:null}function tS(e){const t=tg(e);if(!t)return`every ${e}`;const[n,i]=eS[t.unit];return t.amount===1?`every ${n}`:`every ${t.amount} ${i}`}function dl(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 Ev(e){const t=e;if(typeof t.every!="string")return t.start_at?`once at ${dl(t.start_at)}`:"once, now";const n=[`${tS(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 ${dl(t.until)}`),n.join(" · ")}function ng(e){return e.source_id==="schedule"&&e.source_version===1?Ev(e.config):e.source_id==="manual"&&e.source_version===1?"manual runs only":`${e.source_id}@${e.source_version}`}function Tv(e){return e==="growing"?"Growing — each run sees the previous runs":"Independent — each run starts fresh"}const nS={active:"Active",paused:"Paused",completed:"Completed",failed:"Failed",archived:"Archived"},Eo={pause:"automation.pause",resume:"automation.resume",run_now:"automation.run_now",stop_current:"automation.stop_current",archive:"automation.archive"},rS=new Set(["running","waiting","backoff"]);function sS(e,t=[]){return e.current_occurrence!=null}function Mv(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 Rv(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 pm(e,t=[],n=!1){const i=new Set(e.capabilities),o=e.status,l=sS(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 iS(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 oS(e){return[...e].sort((t,n)=>t.index-n.index).map(t=>{const n=iS(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:!rS.has(t.status)}})}function aS(e){const t=e.attention.items;return t.length?t[t.length-1].cursor:null}function Lv(e){const t=e.attention,n=[];return t.unseen_count>0&&n.push(`${t.unseen_count} unseen`),t.pending_waits>0&&n.push(`${t.pending_waits} waiting for you`),n.length?n.join(" · "):"nothing new"}const lS={unauthorized:"Sign in to the gateway to manage automations.",forbidden:"You are not allowed to do this with automations.",automation_not_found:"This automation does not exist (or is not yours).",occurrence_not_found:"That occurrence does not exist.",revision_conflict:"The automation changed since this view loaded. Reload it, then try again.",automation_busy:"An occurrence is already running or queued. Wait for it to finish.",invalid_state:"The automation's current state does not allow this.",identity_conflict:"This request id was already used for a different request.",invalid_request:"The gateway rejected the request as malformed.",invalid_definition:"The automation definition is not valid.",unsupported_feature:"The gateway does not support this yet.",unknown_trigger_source:"The gateway does not know this trigger source.",invalid_response:"The gateway gave an unexpected answer.",invalid_payload:"That answer could not be sent."};function gm(e){return{title:lS[e.code]??`The gateway refused the request (${e.code}).`,detail:e.message}}function rg(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 Iv(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 cS(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=Iv(e,n);if(t.every!==u.every&&t.every!==null&&(tg(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 uS=[{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 $_(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 dS(e){const t=e.trim().split(`
54
- `)[0].trim();return t.length>120?`${t.slice(0,119)}…`:t}function fS(e){const t=[],n={};if(e.when.kind==="once"){const o=$_(e.when.at);return o?n.start_at=o:t.push("Pick the date and time (UTC) to run once."),{config:n,errors:t}}const i=e.when.amount;if(!Number.isInteger(i)||i<1?t.push("The interval must be a whole number of at least 1."):n.every=`${i}${e.when.unit}`,e.startAt){const o=$_(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=$_(e.until);o?n.until=o:t.push("Stop at must be a date and time (UTC).")}return{config:n,errors:t}}function Pv(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()||dS(i);o.length>120&&n.push("Title is at most 120 characters.");const{config:l,errors:u}=fS(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 hS="Tools run without asking (you approve them now by creating this automation)";function mS(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 _S(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 Ov={ask_user:"Question for you",tool_approval:"Approval needed",event:"Waiting for an event"};class pS{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||gS(n.error))&&this.open.delete(t)}}function gS(e){return rg(e)&&e.status>0&&e.code!=="invalid_response"}function yS(){const e=globalThis.crypto;if(!e||typeof e.randomUUID!="function")throw new Error("crypto.randomUUID is unavailable; pass newId");return e.randomUUID()}class wS{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 uy(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 vS={active:"play",paused:"pause",completed:"check",failed:"error",archived:"archive"};function Dv(e){const t=String(e.status),n=vS[t];return r.jsxs("span",{className:`af-auto__status af-auto__status--${t}${e.className?` ${e.className}`:""}`,"data-state":t,children:[r.jsx("span",{className:"af-auto__status-word",children:nS[t]??t}),n?r.jsx(Qe,{name:n,size:e.iconSize??11,className:"af-auto__status-icon"}):null]})}const vp="Discuss — fork at this occurrence (own workspace, automation files read-only)",Fm=e=>r.jsx("div",{className:"af-auto-text","data-unformatted":"true",children:e});function xS(e){return rg(e)?e:{status:0,code:"client_error",message:e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}}function dy(e){const t=e.path.split(new RegExp("(?<=[/\\\\_-])"));return r.jsx("code",{className:"af-auto__path-text",children:t.map((n,i)=>r.jsxs(ve.Fragment,{children:[n,i<t.length-1?r.jsx("wbr",{}):null]},i))})}function bS(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 jS(e){const t=e.summary,n=Mv(t),i=bS(t,e.triggerSources),o=t.next_fire_at?`${dl(t.next_fire_at)} (${Rv(t.next_fire_at,e.nowMs??Date.now())})`:t.status==="paused"?"none while paused":"none scheduled";return r.jsxs("header",{className:"af-auto__head",children:[r.jsxs("div",{className:"af-auto__titlebar",children:[r.jsx("h2",{className:"af-auto__title",id:e.titleId,tabIndex:-1,children:t.title}),r.jsx(Dv,{status:t.status}),t.legacy?r.jsx("span",{className:"af-auto__legacy",children:"Legacy schedule"}):null]}),r.jsxs("dl",{className:"af-auto__facts",children:[r.jsx("dt",{children:"When"}),r.jsxs("dd",{"data-fact":"trigger",children:[ng(t.trigger),i?r.jsxs("span",{className:"af-auto__warn",role:"note",children:[" ",i]}):null]}),r.jsx("dt",{children:"Context"}),r.jsx("dd",{"data-fact":"context",children:Tv(t.context_mode)}),n?r.jsxs(r.Fragment,{children:[r.jsx("dt",{children:"Now"}),r.jsx("dd",{"data-fact":"current",className:"is-notable",children:n})]}):null,r.jsx("dt",{children:"Next run"}),r.jsx("dd",{"data-fact":"next",children:o}),r.jsx("dt",{children:"Runs"}),r.jsx("dd",{"data-fact":"count",children:t.occurrence_count}),t.workspace_root?r.jsxs(r.Fragment,{children:[r.jsx("dt",{children:"Workspace"}),r.jsx("dd",{"data-fact":"workspace",className:"af-auto__workspace",children:e.onOpenWorkspace?r.jsxs("button",{type:"button",className:"af-auto__path","data-action":"open-workspace",title:`Browse the automation's folder
55
- ${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:[r.jsx(Qe,{name:"folder",size:14,className:"af-auto__path-icon"}),r.jsx(dy,{path:t.workspace_root})]}):r.jsxs("span",{className:"af-auto__path af-auto__path--static",children:[r.jsx(Qe,{name:"folder",size:14,className:"af-auto__path-icon"}),r.jsx(dy,{path:t.workspace_root})]})})]}):null,r.jsx("dt",{children:"Attention"}),r.jsx("dd",{"data-fact":"attention",className:t.attention.unread||t.attention.pending_waits?"is-notable":void 0,children:Lv(t)}),t.revision!==null?r.jsxs(r.Fragment,{children:[r.jsx("dt",{children:"Revision"}),r.jsx("dd",{"data-fact":"revision",children:t.revision})]}):null]})]})}function SS(e){const t=e.definition,n=e.renderText??Fm,i=t.target.input_data.prompt,o=t.policy.retry,l=t.policy.tool_approval;return r.jsxs("details",{className:"af-auto__definition","data-definition-revision":t.revision,open:e.open,children:[r.jsxs("summary",{children:[r.jsx(Qe,{name:"chevronRight",size:14,className:"af-auto__definition-chevron"}),r.jsx(Qe,{name:"file",size:14}),r.jsx("span",{className:"af-auto__definition-title",children:"Definition"}),r.jsxs("span",{className:"af-auto__definition-meta",children:["revision ",t.revision]})]}),r.jsxs("dl",{className:"af-auto__facts",children:[r.jsx("dt",{children:"Target"}),r.jsx("dd",{"data-def":"target",children:r.jsx("code",{children:t.target.workflow_id})}),typeof i=="string"&&i?r.jsxs(r.Fragment,{children:[r.jsx("dt",{children:"Task"}),r.jsx("dd",{"data-def":"prompt",children:n(i)})]}):null,r.jsx("dt",{children:"Trigger"}),r.jsxs("dd",{"data-def":"trigger",children:[t.trigger.source_id,"@",t.trigger.source_version," · ",ng(t.trigger),r.jsx("pre",{className:"af-auto__json",children:JSON.stringify(t.trigger.config,null,2)})]}),r.jsx("dt",{children:"Context"}),r.jsx("dd",{"data-def":"context",children:Tv(t.context.mode)}),r.jsx("dt",{children:"Tools"}),r.jsx("dd",{"data-def":"tool_approval",children:l==="ask"?"Ask before each tool call (ask)":l==="auto"?"Run without asking (auto)":String(l)}),r.jsx("dt",{children:"Retries"}),r.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]}),r.jsx("dt",{children:"Revision"}),r.jsx("dd",{"data-def":"revision",children:t.revision})]})]})}const rl={pause:"Pause",resume:"Resume",run_now:"Run now",stop_current:"Stop current",revise:"Edit",archive:"Archive",discuss:"Discuss"},sl={pause:"pause",resume:"play",run_now:"playCircle",stop_current:"stop",revise:"edit",archive:"archive",discuss:"chat"};function kS(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=>rl[p]).join(", ")}: ${u}`});for(const p of c)l[p]=_}),{lines:o,describedBy:l}}function us(e){return r.jsxs(r.Fragment,{children:[r.jsx(Qe,{name:e.icon,size:14,className:"af-auto__btn-icon"}),r.jsx("span",{children:e.label})]})}function NS(e){const t=pm(e.summary,e.occurrences,e.busy),n=[e.summary.status==="paused"?"resume":"pause","run_now","stop_current","revise","archive"],i=kS(t,n,e.idBase??`af-auto-${e.summary.automation_id}`),o=(l,u,c)=>r.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?void 0:t[l].reason,"aria-describedby":i.describedBy[l],"aria-pressed":c==null?void 0:c.pressed,onClick:u,children:r.jsx(us,{icon:sl[l],label:(c==null?void 0:c.label)??rl[l]})},l);return r.jsxs("div",{className:"af-auto__controls-wrap",children:[r.jsxs("div",{className:"af-auto__actionbar",children:[r.jsxs("div",{className:"af-auto__controls",role:"toolbar","aria-label":"Automation controls",children:[e.summary.status==="paused"?o("resume",()=>e.onCommand(Eo.resume)):o("pause",()=>e.onCommand(Eo.pause)),o("run_now",()=>e.onCommand(Eo.run_now)),o("stop_current",()=>e.onCommand(Eo.stop_current)),o("revise",e.onToggleRevise,{pressed:e.reviseOpen,action:"edit"}),o("archive",e.onAskArchive,{danger:!0,label:"Archive…"})]}),r.jsx("span",{className:`af-auto__notice${e.notice?" af-auto__notice--on":""}`,role:"status",tabIndex:-1,children:e.notice?r.jsxs(r.Fragment,{children:[r.jsx(Qe,{name:"check",size:13}),r.jsx("span",{className:"af-auto__notice-text",children:e.notice}),e.onDismissNotice?r.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:r.jsx(Qe,{name:"x",size:12})}):null]}):null})]}),i.lines.length?r.jsxs("p",{className:"af-auto__reasons",children:[r.jsx(Qe,{name:"info",size:12,className:"af-auto__reasons-icon"}),i.lines.map(l=>r.jsx("span",{id:l.id,children:l.text},l.id))]}):null,e.summary.status==="paused"&&t.run_now.enabled?r.jsx("p",{className:"af-auto__hint",children:"Paused: scheduled runs are skipped. Run now works and keeps it paused."}):null,e.confirmingArchive?r.jsxs("div",{className:"af-auto__confirm",role:"group","aria-label":"Confirm archive",children:[r.jsxs("p",{children:["Archive “",e.summary.title,"”? Its history stays readable; it will not run again. The current run, if any, finishes."]}),r.jsxs("div",{className:"af-auto__row",children:[r.jsx("button",{type:"button",className:"af-auto__btn af-auto__btn--danger","data-action":"archive-confirm",disabled:!t.archive.enabled,onClick:()=>e.onCommand(Eo.archive),children:r.jsx(us,{icon:"archive",label:"Archive"})}),r.jsx("button",{type:"button",className:"af-auto__btn","data-action":"archive-cancel",onClick:e.onCancelArchive,children:r.jsx(us,{icon:"x",label:"Keep it"})})]})]}):null]})}const fy=[["m","minutes"],["h","hours"],["d","days"]];function CS(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 $S(e){const t=Iv(e.summary,e.definition),n=t.every?tg(t.every):null,i=n&&n.unit==="s"?[["s","seconds"],...fy]:fy,o=`af-auto-revise-${e.summary.automation_id}`;return r.jsxs("form",{className:"af-auto__revise","aria-labelledby":`${o}-heading`,onSubmit:l=>{l.preventDefault(),e.onSubmit(CS(l.currentTarget,t))},onKeyDown:l=>{l.key==="Escape"&&(l.preventDefault(),e.onCancel())},children:[r.jsxs("h3",{className:"af-auto__form-title",id:`${o}-heading`,children:[r.jsx(Qe,{name:"edit",size:14})," Edit automation"]}),r.jsxs("label",{className:"af-auto__field",htmlFor:`${o}-title`,children:[r.jsx("span",{children:"Title"}),r.jsx("input",{id:`${o}-title`,name:"title",defaultValue:t.title,maxLength:120,required:!0})]}),t.prompt!==null&&t.prompt!==void 0?r.jsxs("label",{className:"af-auto__field",htmlFor:`${o}-prompt`,children:[r.jsx("span",{children:"Task"}),r.jsx("textarea",{id:`${o}-prompt`,name:"prompt",defaultValue:t.prompt,rows:Math.min(10,Math.max(3,t.prompt.split(`
56
- `).length+1)),required:!0})]}):null,n?r.jsxs("fieldset",{className:"af-auto__field",children:[r.jsx("legend",{children:"Repeat every (UTC)"}),r.jsxs("div",{className:"af-auto__row",children:[r.jsx("input",{name:"every_amount",type:"number",min:1,step:1,defaultValue:n.amount,"aria-label":"Interval amount"}),r.jsx("select",{name:"every_unit",defaultValue:n.unit,"aria-label":"Interval unit",children:i.map(([l,u])=>r.jsx("option",{value:l,children:u},l))})]})]}):r.jsx("p",{className:"af-auto__hint",children:"This trigger has no interval to change."}),r.jsxs("fieldset",{className:"af-auto__field",children:[r.jsx("legend",{children:"Context"}),r.jsxs("label",{children:[r.jsx("input",{type:"radio",name:"context",value:"independent",defaultChecked:t.context==="independent"})," Independent — each run starts fresh"]}),r.jsxs("label",{children:[r.jsx("input",{type:"radio",name:"context",value:"growing",defaultChecked:t.context==="growing"})," Growing — each run sees the previous runs"]})]}),t.toolApproval?r.jsxs("fieldset",{className:"af-auto__field",children:[r.jsx("legend",{children:"Tools"}),r.jsxs("label",{children:[r.jsx("input",{type:"radio",name:"tool_approval",value:"auto",defaultChecked:t.toolApproval==="auto"})," Run without asking"]}),r.jsxs("label",{children:[r.jsx("input",{type:"radio",name:"tool_approval",value:"ask",defaultChecked:t.toolApproval==="ask"})," Ask before each tool call"]})]}):null,r.jsx("p",{className:"af-auto__hint",children:"Changes apply from the next run; a new interval never fires past ticks."}),e.errors.length?r.jsx("ul",{className:"af-auto__form-errors",role:"alert",children:e.errors.map(l=>r.jsx("li",{children:l},l))}):null,r.jsxs("div",{className:"af-auto__row",children:[r.jsx("button",{type:"submit",className:"af-auto__btn af-auto__btn--primary","data-action":"edit-save",disabled:e.busy,children:r.jsx(us,{icon:"check",label:"Save changes"})}),r.jsx("button",{type:"button",className:"af-auto__btn","data-action":"edit-cancel",onClick:e.onCancel,children:r.jsx(us,{icon:"x",label:"Cancel"})})]})]})}function xp(e,t){const n=e.elements.namedItem(t);return n&&typeof n.value=="string"?n.value.trim():""}function AS(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??Fm,l=u=>r.jsxs("div",{className:"af-auto-wait__prompt",id:n,children:[r.jsx("span",{className:"af-auto-wait__kind",children:Ov[t.kind]??"Waiting"}),t.prompt?o(t.prompt):r.jsxs("span",{children:[" ",u]})]});if(t.kind==="tool_approval"){const u=mS(t);return r.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?r.jsx("ul",{className:"af-auto-wait__calls","aria-label":"Tool calls to approve",children:u.map((c,f)=>r.jsxs("li",{"data-tool":c.name,children:[r.jsx("code",{className:"af-auto-wait__tool",children:c.name}),r.jsx("pre",{className:"af-auto-wait__args",children:JSON.stringify(c.arguments,null,2)})]},c.call_id??`${c.name}:${f}`))}):r.jsx("p",{className:"af-auto__hint",children:"The gateway did not list the tool calls; open the run to see them before approving."}),r.jsxs("div",{className:"af-auto__row",children:[r.jsx("button",{type:"button",className:"af-auto__btn af-auto__btn--primary","data-action":"wait-approve",disabled:e.busy,onClick:()=>i({approved:!0}),children:r.jsx(us,{icon:"check",label:"Approve"})}),r.jsx("button",{type:"button",className:"af-auto__btn af-auto__btn--danger","data-action":"wait-deny",disabled:e.busy,onClick:()=>i({approved:!1}),children:r.jsx(us,{icon:"x",label:"Deny"})})]})]})}return t.kind==="event"?r.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=_S(xp(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."),r.jsx("textarea",{name:"payload",rows:3,"aria-label":"Event payload (JSON)",placeholder:'{"key": "value"}',disabled:e.busy}),r.jsx("div",{className:"af-auto__row",children:r.jsx("button",{type:"submit",className:"af-auto__btn af-auto__btn--primary","data-action":"wait-send-event",disabled:e.busy,children:r.jsx(us,{icon:"send",label:"Send event"})})})]}):t.kind==="ask_user"?r.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=xp(u.currentTarget,"response");c&&i({response:c})},children:[l("The run is waiting for your input."),t.choices&&t.choices.length?r.jsx("div",{className:"af-auto__row",role:"group","aria-label":"Choices",children:t.choices.map(u=>r.jsx("button",{type:"button",className:"af-auto__btn","data-action":"wait-choice",disabled:e.busy,onClick:()=>i({response:u}),children:u},u))}):null,r.jsxs("div",{className:"af-auto__row",children:[r.jsx("input",{name:"response","aria-label":"Your answer",placeholder:"Your answer",disabled:e.busy}),r.jsx("button",{type:"submit",className:"af-auto__btn af-auto__btn--primary","data-action":"wait-answer",disabled:e.busy,children:r.jsx(us,{icon:"send",label:"Answer"})})]})]}):r.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."),r.jsxs("p",{className:"af-auto__hint",children:["This kind of wait (",String(t.kind),") cannot be answered here; open the run."]})]})}function ES(e){const{row:t,tone:n,badge:i,statusText:o}=e.view,l=`af-auto-occ-${t.run_id}`,u=e.renderText??Fm,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 r.jsxs("li",{className:`af-auto-occ af-auto-occ--${n}`,"data-index":t.index,"data-tone":n,"aria-labelledby":`${l}-h`,children:[r.jsxs("div",{className:`af-auto-turn af-auto-turn--trigger${p}`,"data-turn":"trigger",children:[r.jsxs("div",{className:"af-auto-turn__meta",id:`${l}-h`,children:[r.jsxs("span",{className:"af-auto-turn__index",children:["#",t.index]})," · ",t.trigger.summary," · fired ",dl(t.fired_at)]}),r.jsx("div",{className:"af-auto-turn__text",children:_("trigger",t.user_turn)})]}),r.jsxs("div",{className:`af-auto-turn af-auto-turn--answer${p}`,"data-turn":"answer",children:[r.jsxs("div",{className:"af-auto-turn__meta",children:[i?r.jsx("span",{className:`af-auto-badge af-auto-badge--${n}`,children:i}):null,r.jsx("span",{className:"af-auto-turn__status",children:o}),t.finished_at?r.jsxs("span",{children:[" · ",dl(t.finished_at)]}):null]}),t.notify?r.jsxs("div",{className:"af-auto-notify","data-notify":"true",children:[r.jsx("strong",{children:t.notify.title}),t.notify.body?r.jsx("div",{className:"af-auto-notify__body",children:u(t.notify.body)}):null]}):null,t.failure?r.jsxs("div",{className:"af-auto-failure","data-failure":t.failure.reason_code,children:[r.jsx("strong",{children:t.failure.reason_code}),": ",t.failure.message," ",r.jsxs("span",{className:"af-auto-turn__muted",children:["(after ",t.failure.attempts," ",t.failure.attempts===1?"attempt":"attempts",")"]})]}):null,t.answer?r.jsx("div",{className:"af-auto-turn__text",children:_("answer",t.answer)}):r.jsx("div",{className:"af-auto-turn__empty",children:w}),t.artifacts.length?r.jsx("ul",{className:"af-auto-artifacts","aria-label":"Artifacts",children:t.artifacts.map(y=>r.jsxs("li",{children:[e.onOpenResource?r.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:[r.jsx(Qe,{name:"file",size:13,className:"af-auto__btn-icon"})," ",y.name]}):r.jsx("span",{className:"af-auto-artifact__name",children:y.name})," ",r.jsx("span",{className:"af-auto-turn__muted",children:y.mime_type})]},y.artifact_id))}):null,t.waits.map(y=>r.jsx(AS,{wait:y,busy:e.busy,idBase:l,onAnswerWait:e.onAnswerWait,onWaitError:e.onWaitError,renderText:e.renderText},`${y.run_id}:${y.wait_key}`))]}),r.jsxs("div",{className:"af-auto-occ__foot",children:[r.jsxs("details",{className:"af-auto-occ__details",children:[r.jsx("summary",{children:"Run details"}),r.jsxs("dl",{className:"af-auto__facts",children:[r.jsx("dt",{children:"Run"}),r.jsx("dd",{children:r.jsx("code",{children:t.run_id})}),r.jsx("dt",{children:"Attempts"}),r.jsx("dd",{children:t.attempts})]}),r.jsxs("div",{className:"af-auto__row",children:[r.jsx("button",{type:"button",className:"af-auto__btn","data-action":"open-run",onClick:()=>e.onOpenRun(t.run_id),children:r.jsx(us,{icon:"list",label:"Open run ledger"})}),e.onOpenResource?r.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:r.jsx(us,{icon:"file",label:"Ledger (JSON)"})}):null,t.workspace_url&&e.onOpenWorkspace?r.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:r.jsx(us,{icon:"folder",label:"Workspace"})}):null]})]}),e.discussOpen?r.jsxs("form",{className:"af-auto-discuss","aria-label":`${vp}, from occurrence ${t.index}`,onSubmit:y=>{y.preventDefault();const x=xp(y.currentTarget,"prompt");x&&e.onDiscussSubmit(t.index,x)},children:[r.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."]}),r.jsx("textarea",{name:"prompt",rows:3,"aria-label":"Your message",placeholder:"Ask about this result…",required:!0}),r.jsxs("div",{className:"af-auto__row",children:[r.jsx("button",{type:"submit",className:"af-auto__btn af-auto__btn--primary","data-action":"discuss-submit",disabled:e.busy,children:r.jsx(us,{icon:"send",label:"Start discussion"})}),r.jsx("button",{type:"button",className:"af-auto__btn","data-action":"discuss-cancel",onClick:e.onDiscussCancel,children:r.jsx(us,{icon:"x",label:"Cancel"})})]})]}):r.jsxs(r.Fragment,{children:[r.jsx("button",{type:"button",className:"af-auto__btn af-auto__btn--quiet","data-action":"discuss",disabled:!c,"aria-describedby":f?`${l}-discuss-why`:void 0,onClick:()=>e.onDiscussOpen(t.index),children:r.jsx(us,{icon:sl.discuss,label:vp})}),f?r.jsx("span",{className:"af-auto__reasons",id:`${l}-discuss-why`,children:f}):null]})]})]})}const TS=5e3,MS={[Eo.pause]:"Pause sent.",[Eo.resume]:"Resume sent.",[Eo.run_now]:"Run requested.",[Eo.stop_current]:"Stop sent."};function RS(e){const{summary:t,busy:n}=e,i=e.renderText??Fm,o=m.useId(),l=m.useRef(null),[u,c]=m.useState(!1),f=e.editOpen!==void 0,p=pm(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),TS);return()=>clearTimeout(J)},[Y]),m.useEffect(()=>{var oe;if(!p)return;$([]);const J=uy(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[se,ie]=m.useState(null);m.useEffect(()=>{var J;se&&((J=uy(l.current,[...se,".af-auto__notice",".af-auto__title"]))==null||J.focus(),ie(null))},[se]);const ue=m.useRef(null);ue.current||(ue.current=new pS(e.newId??yS));const F=ue.current,C=J=>Z(xS(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)})},P=aS(t),O=m.useRef(e.onSeen);O.current=e.onSeen;const ne=m.useRef(null);ne.current||(ne.current=new wS),m.useEffect(()=>{const J=ne.current,oe=P?`${t.automation_id}|${P}`:null;if(!P||!J.next(oe,t))return;const fe=t;O.current(P).then(()=>J.succeeded(oe),me=>{J.failed(oe,fe),C(me)})});const B=pm(t,e.occurrences,n),z=oS(e.occurrences),G=t.occurrence_count-e.occurrences.length,T=H??e.error??null,Q=T?gm(T):null,K=t.attention;return r.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:[r.jsx(jS,{summary:t,triggerSources:e.triggerSources,titleId:o,nowMs:e.nowMs,onOpenWorkspace:e.onOpenWorkspace}),r.jsx(NS,{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===Eo.archive?(L(!1),X("Archive requested."),ie(['[data-action="archive"]'])):X(MS[J]??"Command sent.")}),onToggleRevise:()=>{$([]),S(!p)},onAskArchive:()=>L(!0),onCancelArchive:()=>{L(!1),ie(['[data-action="archive"]'])}}),p&&y?r.jsx($S,{summary:y.summary,definition:y.definition,busy:n,errors:b,onCancel:()=>{S(!1),ie(['[data-action="edit"]'])},onSubmit:J=>{const oe=y.summary,fe=cS(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?r.jsx(SS,{definition:e.definition,renderText:i}):null,Q?r.jsxs("div",{className:"af-auto__error",role:"alert","data-code":T==null?void 0:T.code,children:[r.jsx(Qe,{name:"error",size:14,className:"af-auto__btn-icon"}),r.jsxs("span",{className:"af-auto__error-text",children:[r.jsx("strong",{children:Q.title})," ",r.jsx("span",{children:Q.detail})]}),H?r.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:r.jsx(Qe,{name:"x",size:12})}):null]}):null,K.items.length||K.waits.length?r.jsx("section",{className:"af-auto__attention","aria-label":"Needs attention",children:r.jsxs("ul",{children:[K.items.map(J=>r.jsxs("li",{className:`af-auto__attention-item af-auto__attention-item--${J.kind}`,"data-cursor":J.cursor,children:[r.jsx("span",{className:`af-auto-badge af-auto-badge--${J.kind==="failure"?"failed":"notified"}`,children:J.kind==="failure"?"Failed":"Notified"})," ",r.jsx("strong",{children:J.title})," ",r.jsxs("span",{className:"af-auto-turn__muted",children:["#",J.index," · ",dl(J.at)]}),J.body?r.jsx("div",{className:"af-auto__attention-body",children:i(J.body)}):null]},J.cursor)),K.waits.map(J=>r.jsxs("li",{className:"af-auto__attention-item af-auto__attention-item--wait",children:[r.jsx("span",{className:"af-auto-badge af-auto-badge--waiting","data-wait-kind":J.kind,children:Ov[J.kind]??"Waiting for you"})," ",r.jsxs("span",{className:"af-auto-turn__muted",children:["#",J.index]}),J.prompt?r.jsx("div",{className:"af-auto__attention-body",children:i(J.prompt)}):null]},`${J.run_id}:${J.wait_key}`))]})}):null,G>0?r.jsx("button",{type:"button",className:"af-auto__btn af-auto__more","data-action":"load-more",disabled:n,onClick:e.onLoadMore,children:r.jsx(us,{icon:"history",label:`Load earlier occurrences (${G} more)`})}):null,z.length?r.jsx("ol",{className:"af-auto__timeline","aria-label":"Occurrences",children:z.map(J=>{const oe=`[data-index="${J.row.index}"]`;return r.jsx(ES,{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)})}):r.jsx("p",{className:"af-auto__empty",children:"No occurrences yet."})]})}function Fv(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}}function LS(e){const t=Fv(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 zv({tool:e,showCopy:t=!0}){const[n,i]=m.useState(!1),o=Fv(e.arguments),l=LS(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 r.jsxs("details",{className:`pc-tool-activity pc-tool-activity--${e.status}`,children:[r.jsxs("summary",{className:"pc-tool-activity__summary",children:[r.jsx("span",{className:"pc-tool-activity__state-icon","aria-hidden":"true",children:r.jsx(Qe,{name:e.status==="completed"?"check":e.status==="failed"?"x":e.status==="waiting"?"warning":"loader",size:15})}),r.jsx("strong",{children:e.name}),r.jsx("span",{className:"pc-tool-activity__preview",title:l.value,children:l.value?r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"pc-tool-activity__key",children:l.label}),u]}):"No parameters"}),r.jsx("span",{className:"pc-tool-activity__status",children:f[e.status]}),Number.isFinite(_)&&_>=0?r.jsxs("span",{className:"pc-tool-activity__duration",children:[(_/1e3).toFixed(1),"s"]}):null,r.jsx("span",{className:"pc-tool-activity__chevron","aria-hidden":"true",children:r.jsx(Qe,{name:"chevronRight",size:13})}),e.error?r.jsx("span",{className:"pc-tool-activity__error",title:e.error,children:c}):null]}),r.jsxs("div",{className:"pc-tool-activity__detail",children:[e.error?r.jsxs(r.Fragment,{children:[r.jsx("h4",{children:"Error"}),r.jsx("pre",{className:"pc-tool-activity__output",children:e.error})]}):null,r.jsxs("div",{className:"pc-tool-activity__detail-heading",children:[r.jsx("h4",{children:"Parameters"}),t?r.jsxs("button",{type:"button",onClick:async()=>i(await dc(JSON.stringify(e,null,2))),children:[r.jsx(Qe,{name:"copy",size:13}),n?"Copied":"Copy details"]}):null]}),p?r.jsx("dl",{className:"pc-tool-activity__parameters",children:p.map(([w,y])=>r.jsxs(ve.Fragment,{children:[r.jsx("dt",{children:w}),r.jsx("dd",{children:y&&typeof y=="object"?r.jsx(ds,{value:y}):r.jsx("code",{children:typeof y=="string"?y:JSON.stringify(y)})})]},w))}):e.arguments===void 0?r.jsx("p",{children:"Arguments are unavailable in this ledger."}):r.jsx(ds,{value:o}),e.output!==void 0?r.jsxs(r.Fragment,{children:[r.jsx("h4",{children:"Result"}),typeof e.output=="string"?r.jsx("pre",{className:"pc-tool-activity__output",children:e.output}):r.jsx("div",{className:"pc-tool-activity__output",children:r.jsx(ds,{value:e.output})})]}):null]})]})}function Bv({tools:e,showCopy:t}){const n=i=>e.filter(o=>o.status===i).length;return r.jsxs("section",{className:"pc-tool-group","aria-label":"Tool activity",children:[r.jsxs("div",{className:"pc-tool-group__heading",children:[r.jsx(Qe,{name:"terminal",size:14}),r.jsx("strong",{children:"Tools"}),r.jsxs("span",{children:[e.length," ",e.length===1?"call":"calls"]}),r.jsx("div",{}),n("running")?r.jsxs("span",{className:"pc-tool-group__running",children:[n("running")," running"]}):null,n("waiting")?r.jsxs("span",{className:"pc-tool-group__waiting",children:[n("waiting")," need approval"]}):null,n("failed")?r.jsxs("span",{className:"pc-tool-group__failed",children:[n("failed")," failed"]}):null,n("completed")?r.jsxs("span",{className:"pc-tool-group__completed",children:[n("completed")," done"]}):null]}),e.map(i=>r.jsx(zv,{tool:i,showCopy:t},i.id))]})}const Kr="not reported",ks=e=>e===void 0?Kr:Math.round(e).toLocaleString(),Vs=e=>{if(e===void 0)return Kr;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`},Uv=e=>e===void 0?Kr:`${Math.round(e).toLocaleString()} tok/s`,IS=(e,t)=>t>0?`${Math.round(e/t*100)}%`:"",ac=(e,t,n=`${t}s`)=>`${e.toLocaleString()} ${e===1?t:n}`,PS=e=>{const t=e.split("#")[0].replace(/\/+$/,"");return t.slice(t.lastIndexOf("/")+1)||e};function OS(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 ym(e){const t=[],n=(e.models||[]).map(PS),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 DS(e){const t=e.modelCalls||[],n=[],i=[{label:"Input",value:ks(e.inputTokens)},{label:"Output",value:ks(e.outputTokens)}];if(e.reasoningTokens!==void 0&&i.push({label:"Reasoning",value:ks(e.reasoningTokens),hint:"part of output"}),i.push({label:"Total",value:ks(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:`${ks(l)}${l+u?` (${IS(l,l+u)})`:""}`},{label:"Newly processed",value:ks(e.fedTokens)},{label:"Outcome",value:OS(t.map(f=>f.cacheOutcome))||(e.cacheOutcomes||[]).join(" · ")||Kr},{label:"Backend",value:(e.cacheBackends||[]).join(", ")||Kr}];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:Kr}]});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:`${ks(o[0].inputTokens)} tokens`}]}):o.length>1&&n.push({heading:"Context",rows:[{label:"First → last call",value:`${ks(o[0].inputTokens)} → ${ks(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),ks(l.inputTokens),l.cachedTokens===void 0?"—":ks(l.cachedTokens),l.fedTokens===void 0?"—":ks(l.fedTokens),ks(l.outputTokens),l.cacheOutcome||"—"])}}),{kind:"tokens",title:"Tokens",headline:e.totalTokens===void 0?Kr:`${e.totalTokens.toLocaleString()} total`,sections:n,footer:ym(e)}}function Dh(e,t,n,i){if(e===void 0)return Kr;const o=[Vs(e)];return t!==void 0&&o.push(`${t.toLocaleString()} ${i}${n!==void 0?` at ${Uv(n)}`:""}`),o.join(" · ")}function FS(e){var _,p,w;const t=e.modelCalls||[],n=[],i=e.durationMs,o=[{label:"Wall clock",value:Vs(i)}];if(o.push({label:"Model",value:e.genTimeMs===void 0?Kr:`${Vs(e.genTimeMs)} · ${ac(e.timedCalls||0,"call")}${e.timedCalls!==e.llmCalls?` (of ${e.llmCalls})`:""}`}),o.push({label:"Tools",value:e.toolTimeMs!==void 0?`${Vs(e.toolTimeMs)} · ${ac(e.toolBatches||0,"batch","batches")}`:e.toolCalls?Kr:"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?Vs(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:Dh(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:Dh(e.prefillMs,e.prefillNewTokens,e.prefillNewTokensPerSecond,"new tok"),hint:"derived: prompt ÷ provider rate"}):e.prefillMs!==void 0?l.push({label:"Prefill",value:`${Vs(e.prefillMs)}${e.promptTokensPerSecond!==void 0?` at ${Uv(e.promptTokensPerSecond)}`:""}`,hint:"provider rate over all prompt tokens, restored included"}):l.push({label:"Prefill",value:Kr}),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?Dh(e.generationPhaseMs,e.generationPhaseTokens,e.generationPhaseTokensPerSecond,"tok"):Dh(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?Kr:`${Math.round(f.acceptanceRate*100)}% · ${ks(f.acceptedTokens)} of ${ks(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`:Kr}${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:`${Vs(e.toolTimeMs)} · ${ac(e.toolBatches||0,"batch","batches")}`},{label:"Slowest",value:`${Vs(e.slowestToolBatch.ms)} · ${Wv(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?"—":`${Vs(y.promptMs)}${y.promptSource==="rate"?"*":""}`,y.promptNewTokensPerSecond===void 0?"—":Math.round(y.promptNewTokensPerSecond).toLocaleString(),y.generationMs===void 0?"—":Vs(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?Kr:`${Vs(i)} wall clock`,sections:n,footer:ym(e)}}function Wv(e){return e.tools.length===1?`${e.tools[0]} ×${e.calls}`:`${ac(e.calls,"call")} (${e.tools.join(", ")})`}function zS(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:ym(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?`${Vs(f.ms)}${f.sharedBatches?" +shared":""}`:f.sharedBatches?"shared":Kr])},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?Kr:`${Vs(e.toolTimeMs)} · ${ac(e.toolBatches||0,"batch","batches")}`}];return e.slowestToolBatch&&u.push({label:"Slowest batch",value:`${Vs(e.slowestToolBatch.ms)} · ${Wv(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:ym(e)}}function A_(e,t){return e==="tokens"?DS(t):e==="time"?FS(t):zS(t)}function BS(e){const t=e.detail;return r.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:[r.jsxs("div",{className:"pc-stat-detail-head",children:[r.jsx("span",{className:"pc-stat-detail-title",children:t.title}),r.jsx("span",{className:"pc-stat-detail-headline",children:t.headline})]}),t.sections.map(n=>{var i;return r.jsxs("div",{className:"pc-stat-detail-section",children:[r.jsx("div",{className:"pc-stat-detail-heading",children:n.heading}),(i=n.rows)!=null&&i.length?r.jsx("dl",{className:"pc-stat-detail-rows",children:n.rows.map(o=>r.jsxs(ve.Fragment,{children:[r.jsx("dt",{children:o.label}),r.jsxs("dd",{children:[r.jsx("span",{className:o.value===Kr?"pc-stat-detail-value pc-stat-detail-value--absent":"pc-stat-detail-value",children:o.value}),o.hint?r.jsx("span",{className:"pc-stat-detail-hint",children:o.hint}):null]})]},o.label))}):null,n.table?r.jsxs("table",{className:"pc-stat-detail-table",children:[r.jsx("thead",{children:r.jsx("tr",{children:n.table.columns.map(o=>r.jsx("th",{scope:"col",children:o},o))})}),r.jsx("tbody",{children:n.table.rows.map((o,l)=>r.jsx("tr",{children:o.map((u,c)=>r.jsx("td",{children:u},c))},l))})]}):null,n.note?r.jsx("p",{className:"pc-stat-detail-note",children:n.note}):null]},n.heading)}),r.jsx("div",{className:"pc-stat-detail-foot",children:t.footer.map(n=>r.jsx("div",{children:n},n))})]})}const aa=8;function US(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-aa-M,X=L.bottom+aa,se=Y>=aa?Y:X+M<=Z-aa?X:Math.max(aa,Z-aa-M),ie=Math.min(Math.max(aa,L.left),Math.max(aa,H-aa-D));o({top:se,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?r.jsx(BS,{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 r.jsxs(r.Fragment,{children:[r.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?r.jsx("span",{className:"pc-chat-stat-icon","aria-hidden":"true",children:e.icon}):null,r.jsx("span",{className:"pc-chat-stat-label",children:e.label})]}),S&&typeof document<"u"?Nv.createPortal(S,document.body):S]})}function WS(e){const t=e.totalTokens!==void 0?A_("tokens",e):null,n=A_("tools",e),i=e.durationMs!==void 0?A_("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(`
57
- `)}]:[],...i?[{label:`${(e.durationMs/1e3).toFixed(e.durationMs<1e4?1:0)}s`,detail:i}]:[]]}function qS(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 sg(e){var E;const t=e.message,n=m.useMemo(()=>qS(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?WS(b):[],[e.stats,b]);return t.toolActivity?r.jsx(zv,{tool:t.toolActivity,showCopy:e.showCopy}):r.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:[r.jsxs("div",{className:"pc-chat-header",children:[r.jsx("div",{className:"pc-chat-avatar","aria-hidden":"true",children:r.jsx(Qe,{name:n.icon,size:14})}),r.jsx("span",{className:"pc-chat-role",children:n.label}),f?r.jsxs("span",{className:"pc-chat-live-indicator",title:"The reply is still being written",children:[r.jsx("span",{className:"pc-chat-live-dot","aria-hidden":"true"}),"streaming"]}):null,f!=null&&f.caption?r.jsx("span",{className:"pc-chat-live-caption",children:f.caption}):null,r.jsx("span",{className:"pc-chat-header-spacer"}),o?r.jsx("span",{className:"pc-chat-time",children:o}):null,r.jsxs("div",{className:"pc-chat-header-actions",children:[_?r.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:r.jsx(Qe,{name:w,size:22})}):null,x?r.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:r.jsx(Qe,{name:"copy",size:22})}):null]})]}),f!=null&&f.reasoning?r.jsxs("details",{className:"pc-chat-thinking",children:[r.jsx("summary",{children:"Thinking"}),r.jsx("div",{className:"pc-chat-thinking-body",children:f.reasoning})]}):null,!f||String(t.content||"").trim()?r.jsx("div",{className:"pc-chat-body",children:r.jsx(Sv,{text:String(t.content||""),renderMarkdown:e.renderMarkdown,jsonCollapseAfterDepth:e.jsonCollapseAfterDepth,images:e.images||(n.variant==="user"?"inline":"link"),inlineImage:e.inlineImage})}):null,S.length?r.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 r.jsxs("button",{type:"button",className:"pc-chat-attachment-chip",title:Z||M,onClick:Y?void 0:L.onClick,disabled:Y,children:[r.jsx(Qe,{name:"paperclip",size:14}),H?r.jsx("span",{className:`pc-chat-attachment-target pc-chat-attachment-target--${H}`,children:H}):null,r.jsx("span",{className:"pc-chat-attachment-name",children:M})]},L.id||`${M}:${D}`)})}):null,$.length?r.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 r.jsx(US,{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 r.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?r.jsx("span",{className:"pc-chat-stat-icon","aria-hidden":"true",children:L.icon}):null,r.jsx("span",{className:"pc-chat-stat-label",children:M})]},L.id||`${M}:${D}`)})}):null]})}function HS(e,t){const n=Math.max(0,Math.trunc(t));return e.scrollHeight-e.scrollTop-e.clientHeight<=n}function ig(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(HS(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,_]),r.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?r.jsx(Bv,{tools:p.map(b=>b.toolActivity),showCopy:(S=e.messageProps)==null?void 0:S.showCopy},x):r.jsx(sg,{message:y,...e.messageProps||{}},x)}),e.after,r.jsx("div",{ref:o})]})}const og=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 r.jsxs("div",{className:["pc-composer",t.className].filter(Boolean).join(" "),children:[t.leading,r.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())}}),r.jsxs("div",{className:"pc-composer__row",children:[r.jsx("div",{className:"pc-composer__actions",children:t.actions}),r.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 VS(e){return!!(e&&typeof e[Symbol.asyncIterator]=="function")}function GS(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(VS(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:r.jsxs("div",{className:"pc-assistant__empty",children:[r.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?r.jsx("div",{className:"pc-assistant__suggestions",children:e.suggestions.map(b=>r.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 r.jsxs("div",{className:`pc-assistant${e.className?` ${e.className}`:""}`,children:[r.jsxs("div",{className:"pc-assistant__thread",children:[S,r.jsx(ig,{messages:i,autoScroll:!0}),y?r.jsx("div",{className:"pc-assistant__blocked",children:e.blockedNotice}):null]}),r.jsx("div",{className:"pc-assistant__composer",children:r.jsx(og,{value:u,onChange:c,onSubmit:()=>void x(u),placeholder:e.placeholder||"Ask about this app…",disabled:y,busy:f,rows:2,actions:f?r.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:{},bp=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 qv(e,t){const n=t.record,i=An(n.effect);if(i.type!=="tool_calls")return[];const o=An(n.result),l=bp(An(i.payload).tool_calls),u=bp(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 Ao(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 Hv(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 KS(e){return Ao(e,["reasoning_tokens","thinking_tokens"])??Ao(An(e.completion_tokens_details),["reasoning_tokens"])??Ao(An(e.output_tokens_details),["reasoning_tokens"])}function YS(e){const t=An(typeof e=="string"&&e.trim().startsWith("{")?Hv(e):e);return Zt(t.error_class)}function JS(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 E_(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=JS(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 qv(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),se=Ao(X,["input_tokens","prompt_tokens","prompt","input","in"]),ie=Ao(X,["output_tokens","completion_tokens","completion","output","out"]),ue=Ao(X,["total_tokens","total"])??(se!==void 0||ie!==void 0?(se||0)+(ie||0):void 0);ue!==void 0&&(se===void 0||ie===void 0||se+ie!==ue)&&(c=!0),se!==void 0&&(o.inputTokens=(o.inputTokens||0)+se),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),P=Su(N.prompt_tokens_per_second),O=Su(N.generation_tokens_per_second),ne=An(C.prompt_cache),B=Su(ne.cached_tokens),z=Su(ne.fed_tokens);if(P!==void 0||O!==void 0){if(o.measuredSpeedCalls=(o.measuredSpeedCalls||0)+1,P!==void 0&&P>0&&(o.promptTokensPerSecond=(o.promptTokensPerSecond||0)+P,se!==void 0)){const we=se/P*1e3;o.prefillMs=(o.prefillMs||0)+we,z!==void 0&&(f+=z,_+=we)}O!==void 0&&O>0&&(o.generationTokensPerSecond=(o.generationTokensPerSecond||0)+O,ie!==void 0&&(o.decodeMs=(o.decodeMs||0)+ie/O*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||se!==void 0&&ie!==void 0&&se+ie===ue)&&(se!==void 0&&(K.inputTokens=se),ie!==void 0&&(K.outputTokens=ie)),ue!==void 0&&(K.totalTokens=ue);const fe=KS(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),P!==void 0&&P>0&&(K.promptTokensPerSecond=P),O!==void 0&&O>0&&(K.generationTokensPerSecond=O),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&&se!==void 0&&(K.promptMs=se/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=Ao(me,["accepted_tokens"]),Be=Ao(me,["drafted_tokens"]),We=Ao(me,["rounds"]),_t=Ao(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 Oe=o.speculation||(o.speculation={calls:0,used:0});Oe.calls+=1,we.used&&(Oe.used+=1),we.mode&&(Oe.modes=gu(Oe.modes,we.mode)),we.draftKind&&(Oe.draftKinds=gu(Oe.draftKinds,we.draftKind)),Ae!==void 0&&Be!==void 0&&(Oe.acceptedTokens=(Oe.acceptedTokens||0)+Ae,Oe.draftedTokens=(Oe.draftedTokens||0)+Be),We!==void 0&&(Oe.rounds=(Oe.rounds||0)+We),_t!==void 0&&(Oe.draftLengths=gu(Oe.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=YS(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 se=Hv(D.arguments),ie=Zt(se.destination||se.destination_path||se.file_path||se.path||se.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 XS(e){const t=An(An(e).ledgers);return Object.entries(t).flatMap(([n,i])=>bp(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 Fh(e){if(!e)return!1;for(let t=0;t<e.length;t+=1)if(e[t]==="Files")return!0;return!1}function hy(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 my(e){return e===1?"Drop file to attach":typeof e=="number"&&e>1?`Drop ${e} files to attach`:"Drop files to attach"}function Vv(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 ZS(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 QS={"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 ek(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=QS[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 tk(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}=Vv(e);return i.map(o=>{const l=ek(o.name,o.type,t);return l===o.name?o:new File([o],l,{type:o.type,lastModified:o.lastModified})})}class nk{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 rk(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 sk(e){return(e instanceof Error?e.message:String(e||"Unknown error")).trim()||"Unknown error"}function ik(e){return r.jsxs("div",{className:"pc-workflow-interaction__error",role:"alert",children:[r.jsxs("span",{children:["Could not complete that action: ",e.message]}),r.jsx("button",{type:"button",className:"pc-workflow-interaction__retry",onClick:e.onRetry,disabled:e.disabled,children:"Try again"})]})}function ok(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,se)=>{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 se(),!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:sk(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,()=>rk(t,y.submission))};return r.jsxs("section",{className:"pc-workflow-interaction","aria-labelledby":`pc-workflow-interaction-${S}`,children:[r.jsxs("div",{className:"pc-workflow-interaction__heading",children:[r.jsx(Qe,{name:t.kind==="tool-approval"?"warning":t.kind==="event-wait"?"history":"info",size:16}),r.jsxs("div",{children:[r.jsx("h3",{tabIndex:-1,id:`pc-workflow-interaction-${S}`,children:t.title||(t.kind==="tool-approval"?"Tool approval required":"Input required")}),t.description?r.jsx("div",{className:"pc-workflow-interaction__description",children:t.description}):null]})]}),t.kind==="ask-user"?r.jsxs("div",{className:"pc-workflow-interaction__body",children:[r.jsx("div",{className:"pc-workflow-interaction__prompt",children:t.prompt}),(Y=t.choices)!=null&&Y.length?r.jsx("div",{className:"pc-workflow-interaction__choices","aria-label":"Choices",children:t.choices.map(X=>r.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:[r.jsx("span",{children:X.label}),X.description?r.jsx("small",{children:X.description}):null]},X.id))}):null,t.allowFreeText!==!1?r.jsxs("div",{className:"pc-workflow-interaction__entry",children:[r.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`),r.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"?r.jsxs("div",{className:"pc-workflow-interaction__body",children:[r.jsxs("div",{className:"pc-workflow-interaction__prompt",children:["Allow ",r.jsx("strong",{children:t.toolName})," to run?"]}),t.detail?r.jsx("div",{className:"pc-workflow-interaction__detail",children:t.detail}):null,r.jsxs("div",{className:"pc-workflow-interaction__buttons",children:[r.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"}),r.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?r.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?r.jsx("p",{className:"pc-workflow-interaction__scope",children:t.approveAllDescription}):null]}):r.jsxs("div",{className:"pc-workflow-interaction__body",children:[r.jsx("div",{className:"pc-workflow-interaction__prompt",children:t.prompt}),r.jsxs("label",{className:"pc-workflow-interaction__entry",children:[r.jsx("span",{children:t.payloadLabel||(t.eventName?`Payload for ${t.eventName}`:"Event payload")}),r.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`)]}),r.jsx("div",{className:"pc-workflow-interaction__buttons",children:r.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?r.jsx(ik,{message:y.message,onRetry:Z,disabled:M}):null,r.jsx("div",{className:"pc-workflow-interaction__outcome","aria-live":"polite",children:p})]})}function zh(e){return(e instanceof Error?e.message:String(e||"Unknown error")).trim()||"Unknown error"}function ak(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,se]=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:ZS(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:zh(fe)})}}}},P=m.useRef(N);P.current=N,m.useEffect(()=>{if(!Z||typeof window>"u")return;const K=new nk;let J=0;const oe=Oe=>!!(Y.current&&Oe instanceof Node&&Y.current.contains(Oe)),fe=()=>{K.reset(),J&&window.clearInterval(J),J=0,se(null)},me=()=>{J||(J=window.setInterval(()=>{K.active(Date.now())||fe()},250))},we=Oe=>{var Ye;if(!Fh((Ye=Oe.dataTransfer)==null?void 0:Ye.types))return;K.enter(Date.now());const et=oe(Oe.target),lt=hy(Oe.dataTransfer);se(Se=>Se&&Se.over===et&&Se.count===(lt??Se.count)?Se:{count:lt??(Se==null?void 0:Se.count)??null,over:et}),me()},Ae=Oe=>{var lt;if(!Fh((lt=Oe.dataTransfer)==null?void 0:lt.types))return;Oe.preventDefault(),K.over(Date.now());const et=oe(Oe.target);Oe.dataTransfer&&(Oe.dataTransfer.dropEffect=et&&!C.current?"copy":"none"),se(Ye=>Ye&&Ye.over===et?Ye:{count:(Ye==null?void 0:Ye.count)??hy(Oe.dataTransfer),over:et}),me()},Be=Oe=>{var et;Fh((et=Oe.dataTransfer)==null?void 0:et.types)&&(K.leave(Date.now())||fe())},We=Oe=>{var Le;if(!Fh((Le=Oe.dataTransfer)==null?void 0:Le.types))return;const et=oe(Oe.target),lt=Oe.defaultPrevented&&!et;if(Oe.preventDefault(),fe(),lt)return;if(!et){f({action:"attach",message:"drop files on the conversation to attach them."});return}const{files:Ye,folders:Se}=Vv(Oe.dataTransfer);P.current(Ye,Se)},_t=Oe=>{Oe.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 O=K=>{if(!Z||E)return;const J=tk(K.clipboardData);J.length&&(K.preventDefault(),N(J,[]))},ne=X?r.jsxs("div",{className:["pc-workflow-chat__dropzone",X.over?"is-over":"",E?"is-disabled":""].filter(Boolean).join(" "),"aria-hidden":"true",children:[r.jsx("span",{className:"pc-workflow-chat__dropzone-icon",children:r.jsx(Qe,{name:"paperclip",size:18})}),r.jsxs("span",{className:"pc-workflow-chat__dropzone-text",children:[r.jsx("strong",{children:E?"Attachments are unavailable right now":my(X.count)}),E?null:r.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":my(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:zh(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:zh(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:zh(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 r.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?r.jsx("header",{className:"pc-workflow-chat__header",children:e.header}):null,r.jsx("div",{className:"pc-workflow-chat__transcript",children:r.jsx(ig,{messages:Array.isArray(e.messages)?e.messages:[],empty:e.emptyState,autoScroll:!0,messageProps:{...e.messageProps,...e.renderMarkdown?{renderMarkdown:e.renderMarkdown}:{}},after:r.jsxs(r.Fragment,{children:[e.interaction?r.jsx(ok,{interaction:e.interaction,disabled:E}):null,$?r.jsx("div",{className:"pc-workflow-chat__blocked",role:"status",children:e.blockedNotice}):null]}),afterKey:`${e.interaction?`${e.interaction.kind}:${e.interaction.id}`:""}:${$?"blocked":""}`})}),c?r.jsxs("div",{className:"pc-workflow-chat__error",role:"alert",children:[r.jsxs("span",{children:["Could not ",c.action==="send"?"send this message":c.action==="attach"?"attach a file":"stop the run",": ",c.message]}),r.jsx("button",{type:"button",onClick:Q,disabled:E,children:"Try again"})]}):null,r.jsxs("div",{className:"pc-workflow-chat__composer",children:[r.jsx(og,{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?r.jsx("div",{className:"pc-workflow-chat__attachments",children:e.attachments}):null,overlay:ne,onPaste:Z?O:void 0,actions:r.jsxs(r.Fragment,{children:[e.onAttach?r.jsxs("button",{type:"button",className:"pc-workflow-chat__icon-button","aria-label":"Attach file",title:"Attach file",disabled:E||l,onClick:()=>void T(),children:[r.jsx(Qe,{name:"paperclip",size:16}),r.jsx("span",{children:l?"Attaching…":"Attach"})]}):null,e.composerExtras,L&&e.onCancel?r.jsxs("button",{type:"button",className:"pc-workflow-chat__stop",disabled:E||i||H,onClick:()=>void G(),children:[r.jsx(Qe,{name:"x",size:14}),r.jsx("span",{children:i||H?"Stopping…":"Stop"})]}):M?r.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?r.jsx("div",{className:"pc-sr-only",role:"status","aria-live":"polite",children:B}):null]}),e.footer?r.jsx("footer",{className:"pc-workflow-chat__footer",children:e.footer}):null]})}const T_="llm.delta",Bh="llm.delta_end";function lk(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Zl(e){return typeof e=="string"&&e.trim()!==""}function ck(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0}function uk(e){return"reason"in e}function dk(e,t){const n=lk(e),i=n==null?void 0:n.kind,o=typeof i=="string"&&i?i:n&&"reason"in n?Bh:T_,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!==T_&&i!==Bh&&l(`unknown kind ${JSON.stringify(i)}`),Zl(n.run_id)||l("run_id is missing"),Zl(n.call_id)||l("call_id is missing"),ck(n.seq)||l("seq is not a non-negative integer");const u=i?i===Bh:"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:Bh,...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:T_,...c,text:n.text,channel:n.channel,snapshot:n.snapshot})}const fk={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 hk(e){return`This reply is not streamed: ${e?fk[e]||`the gateway reported "${e}"`:"the gateway gave no reason"}. It appears when it is complete.`}function mk(e){return e.toolApprovalGranted?null:e.interaction}const _y={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 rf(e){return Array.isArray(e)?e:[]}function si(e){return kt(e==null?void 0:e.status).toLowerCase()||"unknown"}function Pr(e){return["completed","failed","cancelled"].includes(e.toLowerCase())}function Za(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 _k(e){const t=At(e);return Number((t==null?void 0:t.status)??(t==null?void 0:t.statusCode))}function M_(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 jp(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=jp(e);if(t)return t;if(!At(e)&&!Array.isArray(e))return"";try{return JSON.stringify(e,null,2)}catch{return""}}function py(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=rf(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 Gv(e){const t=At(e.result);return At(t==null?void 0:t.wait)}function Sp(e){return At(e.effect)||{}}function pk(e,t){return kt(e.run_id)||t}function gy(e){return kt(e.ended_at)||kt(e.started_at)||void 0}function yy(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=Sp(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=Gv(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 gk{constructor(t,n={}){this.transport=t,this.options=n,this.snapshot={..._y},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({..._y})}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=si(f);if(await this.ingestHistory(c,n,i),!this.live(i))return;if(this.set({...this.snapshot,run:f,status:p,loading:!1,..._&&!Pr(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 yy({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${M_(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(Pr(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||Pr(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||Pr(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){M_(t)!==M_(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||Pr(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=rf((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(Za(o))throw o;this.fail(o,!1)}if(await this.catchUp(t,n),!this.live(n)||Pr(si(this.runStates.get(t)||null)))return;this.childCatchUpAttempts.delete(t),this.watch(t,n)}catch(o){if(!this.live(n))return;if(this.watchedRuns.delete(t),t===this.rootRunId)throw o;if(Za(o)){this.fail(o);return}const l=(this.childCatchUpAttempts.get(t)||0)+1;if(this.childCatchUpAttempts.set(t,l),this.fail(o,!1),l>=5)return;await this.waitForRetry(Math.min(2e3,150*2**(l-1))),this.live(n)&&this.catchUpAndWatch(t,n)}}}async catchUp(t,n){var 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:rf(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)&&!Pr(si(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),Za(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(Pr(si(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=rf(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 _=py(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 rf(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)||py(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)||jp(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&&Pr(si(i))?yu(i.output):"")||(i?kt(t.answer)||jp(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,E_(XS(x)))}catch(x){if(!this.live(i))return;if(Za(x))throw x;this.fail(new Error(`Earlier turn activity could not be restored: ${x instanceof Error?x.message:String(x)}`),!1)}}else this.historicalRuns.set(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=_k(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"}),Za(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=pk(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 _=E_(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 yy(o))_!==l&&this.catchUpAndWatch(_,this.generation)}}foldRecord(t,n,i){var p,w;const o=Sp(n),l=kt(o.type).toLowerCase(),u=At(n.result),c=kt(n.status).toLowerCase(),f=gy(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||"");!Pr(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 _=Gv(n);if(c==="waiting"&&_&&!Pr(this.snapshot.status)&&!Pr(si(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 qv(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(Sp(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=dk(n)}catch(f){this.fail(f,!1);return}const o=`${i.run_id}:${i.call_id}`;if(uk(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 Pr(si(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:hk(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;Za(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),...Za(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),Pr(si(n))&&this.endLiveRepliesOfRun(t,si(n)),t!==this.rootRunId){Pr(si(n))&&((l=this.snapshot.interaction)==null?void 0:l.runId)===t&&this.set({...this.snapshot,interaction:null});return}const i=si(n),o=Pr(i);if(o){const u=yu(n.output);u&&this.upsertFinal(t,u,gy(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:E_(this.snapshot.records).statistics},u=this.snapshot.messages.findIndex(f=>f.id===o||String(f.id||"").startsWith(`answer:${t}:`)&&f.content===n);if(u<0){this.set({...this.snapshot,messages:[...this.snapshot.messages,l]});return}const c=[...this.snapshot.messages];c[u]=l,this.set({...this.snapshot,messages:c})}async refreshRunState(t,n){var 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&&!Pr(si(this.runStates.get(t)||null));){if(await this.waitForRetry(2e3),!this.live(n)||this.rootRunId!==t||Pr(si(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(Za(o)){this.fail(o);return}this.fail(o,!1)}}}waitForRetry(t){var o;const n=(o=this.controller)==null?void 0:o.signal;if(!n||n.aborted)return Promise.resolve();const 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 yk(e){const t=m.useMemo(()=>new gk(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 cs(e){return typeof e=="string"?e.trim():e==null?"":typeof e=="number"||typeof e=="boolean"?String(e):""}function wy(e){return["session","workflow","run","global"].includes(e)?e:null}function el(e){return{scope:cs(e==null?void 0:e.scope).toLowerCase(),name:cs(e==null?void 0:e.name)||cs(e==null?void 0:e.event_name),scopeId:cs(e==null?void 0:e.scope_id)||cs(e==null?void 0:e.scopeId),sessionId:cs(e==null?void 0:e.session_id)||cs(e==null?void 0:e.sessionId),workflowId:cs(e==null?void 0:e.workflow_id)||cs(e==null?void 0:e.workflowId),runId:cs(e==null?void 0:e.run_id)||cs(e==null?void 0:e.runId)}}function wk(e,t){const n=e.wait,i=cs(n.wait_key),o=[el(n),el(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);cs(f==null?void 0:f.wait_key)!==i&&cs(p==null?void 0:p.wait_key)!==i||o.push(el(u),el(p),el(Ql(p==null?void 0:p.details)),el(f),el(Ql(f==null?void 0:f.details)))}return o}function R_(e,t){return t.scopeId?t.scopeId:e==="session"?t.sessionId:e==="workflow"?t.workflowId:e==="run"?t.runId:"global"}function Kv(e,t,n){return{scope:e,scopeId:t,name:n,...e==="session"?{sessionId:t}:{},...e==="workflow"?{workflowId:t}:{},...e==="run"?{runId:t}:{}}}function vk(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?Kv(t,n,o):null}function xk(e,t=[],n){if(!e)return{target:null,error:"No event wait is available."};const i=cs(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=wy(o[1]);if(!l)return{target:null,error:"The event wait uses an unsupported scope."};const u=wk(e,Array.isArray(t)?t:[]),c=new Map;for(const y of u){const x=wy(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=R_(x,y);if(E&&E!==$)return{target:null,error:"Event metadata conflicts with the canonical wait target."};const L=Kv(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=R_(l,y);x&&f.add(x)}if(cs(n==null?void 0:n.run_id)===e.runId){const y=el(n||null),x=R_(l,y);x&&f.add(x)}const p=[...f].map(y=>vk(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 ag=e=>bt(`runs/${encodeURIComponent(e)}/workspace`);function bk(e){return ag(e)}function jk(e,t){return`${ag(e)}/files?${new URLSearchParams({path:t,recursive:"false"})}`}function Sk(e,t){return`${ag(e)}/content?${new URLSearchParams({path:t})}`}async function zm(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 kk(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 Nk(e,t,n){const i=await e(bk(t),{signal:n});if(!i.ok)throw await zm(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 Ck(e,t,n,i){const o=await e(jk(t,n),{signal:i});if(!o.ok)throw await zm(o,"The folder could not be listed");return kk(await o.json(),n)}async function $k(e,t,n,i){const o=await e(Sk(t,n),{signal:i});if(!o.ok)throw await zm(o,"The file could not be read");return await o.blob()}async function Ak(e,t,n,i){const o=await Nk(e,t,i);return{where:o,listing:o.exists?await Ck(e,t,n,i):null}}function Ek(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 Tk(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 Mk(e){return[...e].sort((t,n)=>t.type===n.type?t.name.localeCompare(n.name):t.type==="dir"?-1:1)}function Rk(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 Lk=new Set(["image/png","image/jpeg","image/gif","image/webp","image/avif","image/bmp","application/pdf","text/plain","application/json"]);function Ik(e){const t=String(e||"").split(";",1)[0].trim().toLowerCase();return Lk.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 Yv(e,t,n){const i=n==="open"?Ik(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 Pk(e,t,n){const i=await e(xj(t),{signal:n.signal});if(!i.ok)throw await zm(i,`${n.name} could not be read`);Yv(await i.blob(),n.name,n.mode??"open")}function Jv(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 Ak(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{Yv(await $k(t,n,L.path),L.name,D)}catch(M){_(String((M==null?void 0:M.message)||M))}finally{x("")}},[t,n]);return r.jsx(Ok,{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 Ok(e){var i,o,l,u;const t=e.listing?Rk(e.listing):"",n=(o=(i=e.where)==null?void 0:i.host)==null?void 0:o.hostname;return r.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:[r.jsxs("header",{className:"pc-ws__head",children:[r.jsxs("span",{className:"pc-ws__title",children:[r.jsx(Qe,{name:"folder",size:15})," ",e.title]}),r.jsx("span",{className:"pc-ws__spacer"}),r.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:r.jsx(Qe,{name:"refresh",size:14})}),e.onClose?r.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:r.jsx(Qe,{name:"x",size:14})}):null]}),e.where?r.jsxs("div",{className:"pc-ws__root",children:[r.jsx("code",{children:e.where.workspace_root}),n&&((u=e.where.host)==null?void 0:u.caller_is_this_machine)!==!0?r.jsxs("span",{className:"pc-ws__muted",children:[" on the gateway host ",n]}):null]}):null,e.note?r.jsx("div",{className:"pc-ws__muted",children:e.note}):null,r.jsx("nav",{className:"pc-ws__crumbs","aria-label":"Folder",children:Ek(e.path).map((c,f,_)=>f===_.length-1?r.jsx("span",{"aria-current":"page",children:c.label},c.path):r.jsxs(ve.Fragment,{children:[r.jsx("button",{type:"button",className:"pc-ws__crumb",onClick:()=>e.onNavigate(c.path),children:c.label}),r.jsx("span",{className:"pc-ws__muted",children:" / "})]},c.path))}),e.error?r.jsx("div",{className:"pc-ws__error",role:"alert",children:e.error}):null,e.loading&&!e.listing?r.jsx("div",{className:"pc-ws__muted",role:"status",children:"Loading…"}):null,e.where&&!e.where.exists?r.jsx("div",{className:"pc-ws__muted",children:"The folder does not exist yet: nothing has been written."}):null,e.listing?e.listing.entries.length?r.jsx("ul",{className:"pc-ws__entries",children:Mk(e.listing.entries).map(c=>r.jsx("li",{className:`pc-ws__entry${e.selectedPath===c.path?" is-selected":""}`,"data-type":c.type,"data-path":c.path,children:c.type==="dir"?r.jsxs("button",{type:"button",className:"pc-ws__name","data-action":"open-dir",onClick:()=>e.onNavigate(c.path),children:[r.jsx(Qe,{name:"folder",size:14})," ",c.name,"/"]}):r.jsxs(r.Fragment,{children:[e.onSelectFile?r.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:[r.jsx(Qe,{name:"file",size:14})," ",c.name]}):r.jsxs("span",{className:"pc-ws__name",children:[r.jsx(Qe,{name:"file",size:14})," ",c.name]}),r.jsx("span",{className:"pc-ws__size",children:Tk(c.size_bytes)}),e.onFile?r.jsxs(r.Fragment,{children:[r.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"}),r.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:r.jsx(Qe,{name:"download",size:14})})]}):null]})},c.path))}):r.jsx("div",{className:"pc-ws__muted",children:"This folder is empty."}):null,t?r.jsx("div",{className:"pc-ws__muted","data-hidden-note":"true",children:t}):null]})}function Xv(e){return r.jsx(Sv,{text:e,images:"link"})}const Dk={trigger:"Trigger",answer:"Automation"};function Fk(e){return r.jsx(sg,{message:{id:`${e.runId}:${e.kind}`,role:e.role,content:e.text,title:Dk[e.kind],runId:e.runId},images:"link"})}const zk={renderText:Xv,renderTurn:Fk};function Bk(e){const{fetchGateway:t,...n}=e,i=n.onOpenResource??(t?o=>Pk(t,o.url,{name:o.name}):void 0);return r.jsx(RS,{...n,onOpenResource:i,...zk})}function Uk(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:r.jsxs("div",{className:"pc-approval-summary",children:[r.jsx(Bv,{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"}))}),r.jsxs("details",{children:[r.jsx("summary",{children:"Review full tool arguments (JSON)"}),r.jsx(ds,{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=xk(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 Wk="# 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 Or(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`id_${Date.now()}_${Math.random().toString(16).slice(2)}`}function qk(e,t){return[...e.filter(n=>!n.local_error),t].map(n=>({role:n.role,content:n.content}))}function Uh(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?Math.trunc(e):0}function Hk(e){const t=Uh(e==null?void 0:e.dropped_messages);if(!e||t<=0)return null;const n=Uh(e.replayed_messages),i=Uh(e.dropped_tokens),o=Uh(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 Zv(e){const t=Hk(e.history);return t?r.jsx(sg,{message:{role:"system",level:"info",title:"History",content:t}}):null}const Vk=1500,Gk=12e4;function Kk(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 Yk=["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) ===",Wk,"=== END DOCUMENTATION ==="].join(`
58
- `),Jk="observer-docs-assistant";function vy(){return`${Jk}:${Or()}`}function Xk(e){return{prompt:e,system:Yk,tools:[],use_session_history:!0,use_context:!0}}function Zk(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 Qk(e,t,n=()=>{}){return async(i,o)=>{var f;const l=e(),u=await l.start_run(null,Xk(i),{bundle_id:"basic-agent",session_id:t()}),c=Date.now();for(;;){if(await Kk(Vk,o.signal),Date.now()-c>Gk)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 Zk(w.items)||"(the run completed but produced no readable answer — inspect it on the Observe page)"}}}}function eN(e){const t=m.useRef(e.gateway);t.current=e.gateway;const n=m.useRef(vy()),[i,o]=m.useState([]),[l,u]=m.useState(null),c=m.useMemo(()=>Qk(()=>t.current,()=>n.current,u),[]),[f]=m.useState(void 0),_=()=>{n.current=vy(),o([]),u(null)};return r.jsxs(Ej,{open:e.open,onClose:e.onClose,label:"Observer assistant",title:"Assistant",width:420,topOffset:e.topOffset,headerActions:r.jsx("button",{className:"btn",type:"button",disabled:!i.length,onClick:_,title:"Start a new conversation (nothing earlier is replayed)",children:"New conversation"}),children:[r.jsx(Zv,{history:l}),r.jsx(GS,{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:r.jsx("div",{children:"Answers are grounded in this app's documentation. Each question runs once through the connected gateway's basic agent."})})]})}const tN="api/local/reveal",nN="sw.js";function rN(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 wm="@default:",kp="abstractcode.agent.v1";function sN(e){const t=String(e||"").trim();if(t.startsWith(wm)){const i=t.slice(wm.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 iN(e){return e?e.kind==="default"?`${wm}${e.interface}`:`${e.bundle_id}:${e.flow_id}`:""}function oN(e){const t={};for(const i of e)for(const o of i.agent_default_interfaces||[])o&&!t[o]&&(t[o]=i.label);return[kp,...Object.keys(t).filter(i=>i!==kp).sort()].map(i=>({interface:i,value:`${wm}${i}`,label:`Gateway default agent · ${i}${t[i]?` (now: ${t[i]})`:""}`}))}function aN(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 lN(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 cN={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."},uN="#launch/automate";function dN(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 Np={when:"every",amount:"24",unit:"h",once_at:"",context:"independent",tool_approval:"auto",title:"",start_at:"",count:"",until:""},xy={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."},Qv=["use_context"],fN="This choice also sets the workflow's Use Context input: the workflow always reads the history the automation gives it.";function ex(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 hN(e,t){if(t.input_data===null)return{ok:!1,errors:["The inputs are not valid JSON."]};const n=lN(t.input_data),i=typeof n.prompt=="string"?n.prompt:"";delete n.prompt;for(const l of Qv)delete n[l];let o;try{o=aN(t.choice,t.bundle_ref_for,n)}catch(l){return{ok:!1,errors:[String((l==null?void 0:l.message)||l)]}}return Pv(ex(e,i),{target:o,requestId:t.request_id})}function mN(e){const t=Pv(ex(e,"preview"),{target:{flow_id:"@default",interface:kp},requestId:"preview"});if(!t.ok)return"";const n=t.body.trigger.config,i=Ev(n);return e.when==="once"?`Runs ${i}.`:`Runs ${i}, first run ${n.start_at?`at ${dl(n.start_at)}`:"now"}.`}class _N{constructor(t){Gr(this,"key","");Gr(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 pN(e,t,n){const i=hN(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 la(e){return typeof e=="string"?e:e??null}function gN(e){var t,n,i,o,l,u;return{run_id:String((e==null?void 0:e.run_id)||"").trim(),workflow_id:la(e==null?void 0:e.workflow_id),status:typeof(e==null?void 0:e.status)=="string"?String(e.status):"",created_at:la(e==null?void 0:e.created_at),updated_at:la(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:la(e==null?void 0:e.parent_run_id),session_id:la(e==null?void 0:e.session_id),actor_id:la(e==null?void 0:e.actor_id),session_kind:la(e==null?void 0:e.session_kind),automation_id:la(e==null?void 0:e.automation_id),role:la(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 tx(e){const t=cf(e);return t==="occurrence"?typeof e.occurrence_index=="number"?`occurrence #${e.occurrence_index}`:"occurrence":t==="legacy"?"legacy schedule":t||""}function by(e){return String((e==null?void 0:e.role)||"").trim()==="controller"}function yN(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 nx(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:ng(e.trigger),next_run:e.next_fire_at?`${dl(e.next_fire_at)} (${Rv(e.next_fire_at,t)})`:e.status==="paused"?"none while paused":"none scheduled",current:Mv(e),state:e.status,last:i?i.excerpt:"",last_status:i?`#${i.index} ${i.status}${o}`:"no runs yet",attention:l?Lv(e):null,legacy:n}}function rx(e){const t=e.last_occurrence;if(!t)return null;const i=["completed","failed","cancelled"].includes(String(t.status))?t.index:t.index-1;return i>=1?i:null}function wN(e,t){const n=pm(e,[],t),i=rx(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 vN(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 xN(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 bN=/^([1-9][0-9]*)([smhd])$/;function jN(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 SN(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={...Np},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=bN.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 _=jN(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 kN={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 NN(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 CN(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 jy(e){return e.show_archived||e.status_filter==="archived"?e.items:e.items.filter(t=>t.status!=="archived")}function Sy(e){return e.items.filter(t=>t.status==="archived").length}function lg(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 $N=3e4,Wh=50;function Yi(e){return rg(e)?e:{status:0,code:"client_error",message:e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}}function L_(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 AN{constructor(t,n,i=[1500,4e3]){Gr(this,"state",{...kN});Gr(this,"listeners",new Set);Gr(this,"list_seq",0);Gr(this,"detail_seq",0);Gr(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:Wh});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:Wh})]);if(i!==this.detail_seq)return;this.set({detail:{automation_id:n,summary:l??u.summary,definition:u.definition,occurrences:L_([],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:Wh})]),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:L_(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:Wh}),i=this.state.detail;if(!i||i.automation_id!==t.automation_id)return;this.set({detail:{...i,occurrences:L_(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:lg(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,CN(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.`:`${EN[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=xN(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 EN={pause:"Pause",resume:"Resume",run_now:"Run now",archive:"Archive"};function TN(e){const t=(n,i,o)=>r.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 r.jsxs("div",{className:"launch_mode",children:[r.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)]}),r.jsx("p",{className:"launch_mode_help",id:"launch_mode_help","data-mode-help":e.mode,"aria-live":"polite",children:cN[e.mode]})]})}function MN(e){const t=e.form,n=mN(t);return r.jsxs("div",{className:"automate_fields",children:[r.jsxs("fieldset",{"data-section":"when",children:[r.jsx("legend",{children:"When (UTC)"}),r.jsxs("div",{className:"automate_row",role:"radiogroup","aria-label":"Schedule kind",children:[r.jsxs("label",{children:[r.jsx("input",{type:"radio",name:"automate_when",value:"every",checked:t.when==="every",disabled:e.disabled,onChange:()=>e.on_change({when:"every"})})," Repeat"]}),r.jsxs("label",{children:[r.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"?r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"automate_row",role:"group","aria-label":"Presets",children:uS.map(i=>i.when.kind==="every"?r.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)}),r.jsxs("div",{className:"automate_row",children:[r.jsx("span",{children:"Every"}),r.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})}),r.jsxs("select",{value:t.unit,disabled:e.disabled,"aria-label":"Interval unit",onChange:i=>e.on_change({unit:i.target.value}),children:[r.jsx("option",{value:"m",children:"minutes"}),r.jsx("option",{value:"h",children:"hours"}),r.jsx("option",{value:"d",children:"days"})]})]})]}):r.jsxs("label",{className:"automate_row",children:[r.jsx("span",{children:"Run once at (UTC)"}),r.jsx("input",{type:"datetime-local",value:t.once_at,disabled:e.disabled,onChange:i=>e.on_change({once_at:i.target.value})})]}),r.jsx("div",{className:"automate_preview","aria-live":"polite","data-preview":"true",children:n||"Incomplete schedule."})]}),r.jsxs("fieldset",{"data-section":"context",children:[r.jsx("legend",{children:"Context"}),r.jsxs("label",{children:[r.jsx("input",{type:"radio",name:"automate_context",value:"independent",checked:t.context==="independent",disabled:e.disabled,onChange:()=>e.on_change({context:"independent"})})," ",r.jsx("strong",{children:"Independent"})," (default) — ",xy.independent]}),r.jsxs("label",{children:[r.jsx("input",{type:"radio",name:"automate_context",value:"growing",checked:t.context==="growing",disabled:e.disabled,onChange:()=>e.on_change({context:"growing"})})," ",r.jsx("strong",{children:"Growing"})," — ",xy.growing]}),r.jsx("p",{className:"help_text muted","data-context-owns":"use_context",children:fN})]}),r.jsxs("fieldset",{"data-section":"tools",children:[r.jsx("legend",{children:"Tools"}),r.jsxs("label",{children:[r.jsx("input",{type:"radio",name:"automate_tools",value:"auto",checked:t.tool_approval==="auto",disabled:e.disabled,onChange:()=>e.on_change({tool_approval:"auto"})})," ",hS,e.tools&&e.tools.length?r.jsxs("span",{className:"automate_preview",children:[" — ",e.tools.join(", ")]}):null]}),r.jsxs("label",{children:[r.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 RN(e){const t=e.form;return r.jsxs("div",{className:"automate_fields launch_grid","data-section":"advanced-schedule",children:[r.jsxs("label",{className:"launch_grid_cell",style:{gridColumn:"1 / -1"},children:[r.jsx("span",{className:"launch_label",children:"Title"}),r.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"?r.jsxs(r.Fragment,{children:[r.jsxs("label",{className:"launch_grid_cell",children:[r.jsx("span",{className:"launch_label",children:"First run at (UTC; empty = now)"}),r.jsx("input",{type:"datetime-local",value:t.start_at,disabled:e.disabled,onChange:n=>e.on_change({start_at:n.target.value})})]}),r.jsxs("label",{className:"launch_grid_cell",children:[r.jsx("span",{className:"launch_label",children:"Stop after this many runs"}),r.jsx("input",{type:"number",min:1,step:1,value:t.count,disabled:e.disabled,onChange:n=>e.on_change({count:n.target.value})})]}),r.jsxs("label",{className:"launch_grid_cell",children:[r.jsx("span",{className:"launch_label",children:"Stop at (UTC)"}),r.jsx("input",{type:"datetime-local",value:t.until,disabled:e.disabled,onChange:n=>e.on_change({until:n.target.value})})]})]}):null]})}const LN="abstractobserver";function IN(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 PN(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 ON=new Set(["completed","failed","cancelled"]);function DN(e){var D;const{gateway:t,discussion:n}=e,i=m.useMemo(()=>IN(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}=yk({transport:i,runId:o,enabled:e.connected,clientId:LN}),S=n.session,b=!!o&&!ON.has(x.status)&&x.status!=="idle",$=mk(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=PN(Y),se=await t.start_run(X.flow_id,{prompt:H},{bundle_id:X.bundle_id,session_id:S.session_id});l(se)}else{const Y=await e.on_fork(n.automation_id,n.occurrence_index,H);l(Y.run_id)}c("")}finally{_(!1)}}},L=r.jsxs("div",{className:"discussion_head",children:[r.jsxs("button",{type:"button",className:"btn btn_sm","data-action":"discussion-back",onClick:e.on_close,title:`Back to ${n.automation_title}`,children:[r.jsx(Qe,{name:"chevronRight",size:13,className:"flip_x"})," ",n.automation_title]}),r.jsxs("span",{className:"discussion_title",children:[r.jsx(Qe,{name:"chat",size:15})," Discussion — fork at #",n.occurrence_index]}),r.jsx("span",{className:"pane_spacer"}),S?r.jsxs(r.Fragment,{children:[r.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:[r.jsx(Qe,{name:"folder",size:14})," Its files"]}),r.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:[r.jsx(Qe,{name:"folder",size:14})," Automation files"]})]}):null]});return r.jsxs("section",{className:"pane auto_detail auto_discussion","data-discussion-session":(S==null?void 0:S.session_id)||void 0,children:[p&&S?r.jsx(Jv,{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,r.jsx(ak,{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:Uk($,y,{records:x.records,currentRun:x.run}),placeholder:S?"Ask a follow-up…":`Ask about run #${n.occurrence_index}…`,emptyState:r.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?r.jsx("div",{className:"observe_context_card error",role:"alert",children:x.error}):null})]})}const FN=5e3,zN=[["","All"],["active","Active"],["paused","Paused"],["completed","Completed"],["failed","Failed"],["archived","Archived"]],BN={pause:rl.pause,resume:rl.resume,run_now:rl.run_now,edit:rl.revise,archive:`${rl.archive}…`,discuss:rl.discuss},UN={pause:sl.pause,resume:sl.resume,run_now:sl.run_now,edit:sl.revise,archive:sl.archive,discuss:sl.discuss},WN={legacy_pause:"pause",legacy_resume:"play",legacy_run_now:"playCircle",open_run:"list",recreate:"refresh"};function qN(e){return r.jsx("span",{className:"auto_state","data-field":"state",children:r.jsx(Dv,{status:e.status})})}function qh(e){return r.jsxs("span",{className:`auto_fact${e.className?` ${e.className}`:""}`,"data-field":e.field,title:e.label,children:[r.jsx(Qe,{name:e.icon,size:12}),r.jsx("span",{children:e.children})]})}const HN={legacy_pause:"Suspend",legacy_resume:"Resume",legacy_run_now:"Run now",open_run:"Open run",recreate:"Recreate as automation"};function VN(e){const t=e.summary,n=nx(t),i=e.state.selected_id===t.automation_id,o=e.state.busy,l=(f,_,p,w,y,x,S)=>r.jsxs("button",{type:"button",className:`btn btn_sm auto_action${S?" auto_action_icon":""}${y?` ${y}`:""}`,"data-action":f,disabled:!p.enabled,title:S?p.enabled?_:`${_} ${p.reason??""}`.trim():p.reason,"aria-label":S?_:void 0,onClick:w,children:[x?r.jsx(Qe,{name:x,size:13}):null,S?null:r.jsx("span",{children:_})]},f);let u;if(n.legacy){const f=vN(t,o);u=[t.status==="paused"?"legacy_resume":"legacy_pause","legacy_run_now","open_run","recreate"].map(p=>l(p,HN[p],f[p],()=>e.h.on_legacy_action(t,p),void 0,WN[p]))}else{const f=wN(t,o);u=[t.status==="paused"?"resume":"pause","run_now","edit","discuss","archive"].map(p=>l(p,BN[p],f[p],()=>e.h.on_row_action(t,p),p==="archive"?"danger auto_action_end":void 0,UN[p],p==="archive"))}const c=e.state.confirm_archive_id===t.automation_id;return r.jsxs("li",{className:`auto_row${i?" selected":""}`,"data-automation-id":t.automation_id,"data-legacy":n.legacy?"true":void 0,children:[r.jsxs("button",{type:"button",className:"auto_row_main",onClick:()=>e.h.on_select(t.automation_id),"aria-current":i?"true":void 0,children:[r.jsxs("span",{className:"auto_row_title",children:[n.title,n.legacy?r.jsx("span",{className:"chip scheduled",children:"legacy"}):null,r.jsx(qN,{status:n.state}),n.attention?r.jsxs("span",{className:"chip warn auto_row_attention","data-field":"attention",children:[r.jsx(Qe,{name:"warning",size:12})," ",n.attention]}):null]}),r.jsxs("span",{className:"auto_row_facts",children:[r.jsx(qh,{icon:"refresh",field:"cadence",label:"When it runs",children:n.cadence}),n.current?r.jsx(qh,{icon:"loader",field:"current",label:"Running now",className:"auto_row_current",children:n.current}):null,r.jsxs(qh,{icon:"clock",field:"next",label:"Next run",children:["next: ",n.next_run]}),r.jsx(qh,{icon:"info",field:"last-status",label:"Last run",children:n.last_status})]}),n.last?r.jsx("span",{className:"auto_row_excerpt","data-field":"excerpt",children:Xv(n.last)}):null]}),r.jsx("div",{className:"auto_row_actions",role:"toolbar","aria-label":`Controls for ${n.title}`,children:u}),c?r.jsxs("div",{className:"auto_row_confirm",role:"group","aria-label":"Confirm archive",children:[r.jsxs("span",{children:["Archive “",n.title,"”? Its history stays readable; it will not run again."]}),r.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:[r.jsx(Qe,{name:"archive",size:13}),r.jsx("span",{children:"Archive"})]}),r.jsxs("button",{type:"button",className:"btn btn_sm auto_action","data-action":"archive-cancel",onClick:e.h.on_cancel_archive,children:[r.jsx(Qe,{name:"x",size:13}),r.jsx("span",{children:"Keep it"})]})]}):null]})}function GN(e){const t=e.state,n=t.error??t.list_error,i=n?gm(n):null;return r.jsxs("section",{className:"pane auto_list","aria-label":"Automations",children:[r.jsxs("div",{className:"pane_header",children:[r.jsx("span",{className:"pane_title",children:"Automations"}),r.jsx("span",{className:"pane_count",children:jy(t).length}),r.jsx("span",{className:"pane_spacer"}),r.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:zN.map(([o,l])=>r.jsx("option",{value:o,children:l},o||"all"))}),r.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:r.jsx(Qe,{name:t.loading?"loader":"refresh",size:14})}),r.jsxs("a",{className:`btn btn_sm auto_new${e.available.available?"":" disabled"}`,"data-action":"new",href:uN,"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:[r.jsx(Qe,{name:"plus",size:14}),r.jsx("span",{className:"auto_new_label",children:"New automation"})]})]}),r.jsxs("div",{className:"pane_body scroll",children:[e.available.available?null:r.jsx("div",{className:"warn_callout",role:"note","data-unavailable":"true",children:e.available.reason}),i?r.jsxs("div",{className:"observe_context_card error auto_list_error",role:"alert","data-code":n==null?void 0:n.code,children:[r.jsx(Qe,{name:"error",size:14}),r.jsxs("span",{className:"auto_list_msg",children:[r.jsx("strong",{children:i.title})," ",r.jsx("span",{children:i.detail})]}),t.error&&e.h.on_dismiss_error?r.jsx("button",{type:"button",className:"auto_dismiss","data-action":"dismiss-error","aria-label":"Dismiss",title:"Dismiss",onClick:e.h.on_dismiss_error,children:r.jsx(Qe,{name:"x",size:12})}):null]}):null,r.jsx("div",{className:`auto_notice${t.notice?" on":""}`,role:"status",children:t.notice?r.jsxs(r.Fragment,{children:[r.jsx(Qe,{name:"check",size:13}),r.jsx("span",{className:"auto_list_msg",children:t.notice}),e.h.on_dismiss_notice?r.jsx("button",{type:"button",className:"auto_dismiss","data-action":"dismiss-notice","aria-label":"Dismiss",title:"Dismiss",onClick:e.h.on_dismiss_notice,children:r.jsx(Qe,{name:"x",size:12})}):null]}):null}),e.available.available&&t.loaded&&!t.items.length?r.jsx("div",{className:"help_text muted",children:"No automations yet. Create one from Launch → Automate."}):null,Sy(t)>0&&t.status_filter!=="archived"?r.jsxs("label",{className:"auto_show_archived help_text muted",children:[r.jsx("input",{type:"checkbox","data-action":"show-archived",checked:t.show_archived,onChange:o=>e.h.on_show_archived(o.target.checked)})," Show archived (",Sy(t),")"]}):null,r.jsx("ul",{className:"auto_rows",children:jy(t).map(o=>r.jsx(VN,{summary:o,state:t,h:e.h},o.automation_id))})]})]})}function KN(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(_,lg(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 YN(e){const t=e.ctl.state.detail;if(!t&&e.ctl.state.selected_id)return r.jsx("section",{className:"pane auto_detail auto_detail_empty","aria-busy":"true",children:r.jsx("div",{className:"help_text muted",children:"Loading…"})});if(!t)return r.jsx("section",{className:"pane auto_detail auto_detail_empty",children:r.jsxs("div",{className:"help_text muted",children:["Select an automation to read its runs as a conversation, change it, or discuss a result (",vp.toLowerCase(),")."]})});if(lc(t.summary)){const i=nx(t.summary);return r.jsxs("section",{className:"pane auto_detail","data-legacy":"true",children:[r.jsxs("div",{className:"pane_header",children:[r.jsx("span",{className:"pane_title",children:i.title}),r.jsx("span",{className:"chip scheduled",children:"legacy"})]}),r.jsxs("div",{className:"pane_body",children:[r.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."]}),r.jsxs("div",{className:"auto_row_actions",children:[r.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"}),r.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=KN(e.ctl,e.host,e.edit);return r.jsxs("section",{className:"pane auto_detail",children:[e.browser??null,n?r.jsx(Bk,{...n}):null]})}function JN(e,t){if(t==="edit")return{kind:"edit"};if(t!=="discuss")return{kind:"forward"};const n=rx(e);return n===null?{kind:"none"}:{kind:"discuss",index:n}}function XN(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(),$N);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(),FN);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=JN(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 r.jsxs("div",{className:"page auto_page",children:[r.jsx(GN,{state:t.state,available:e.available,h:S}),n?r.jsx(DN,{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,lg($,L),$),i(D=>D&&{...D,session:L}),L},on_close:()=>i(null)},n.opened):r.jsx(YN,{ctl:t,host:x,h:S,edit:{open:!!w&&c===w.automation_id,on_change:b=>f(b&&w?w.automation_id:"")},browser:l?r.jsx(Jv,{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 ZN(){const e="0.2.0".trim();if(!e)throw new Error("AbstractObserver: __APP_VERSION__ is not defined; the vite/vitest config must inject it from package.json");return e}function QN(){return Ij("abstractobserver",ZN())}async function e1(e){let t;try{t=await e.gateway_about()}catch(n){return ay(null,n instanceof Error?n.message||n.name:String(n))}return ay(t)}class vm{constructor(t){this._maxSize=vm._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=vm._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 t1(e){try{return new URL(String(e)),!0}catch{return!1}}function n1({baseUrl:e,endpoint:t}){const n=String(t||"api/gateway/host/metrics/gpu");return t1(n)?n:e&&String(e).trim()?new URL(n,String(e)).toString():n}async function r1({token:e,getToken:t}){if(typeof t=="function"){const n=await t();return n==null?"":String(n)}return e==null?"":String(e)}function s1({token:e}){const t=String(e||"").trim();return t?{Authorization:`Bearer ${t}`}:{}}function i1(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 o1({baseUrl:e,endpoint:t,token:n,getToken:i,signal:o,fetchImpl:l}={}){const u=n1({baseUrl:e,endpoint:t}),c=await r1({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",...s1({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 a1(e){return Number.isFinite(e)?Math.min(1,Math.max(0,e)):0}function ky(e,t,n){return Number.isFinite(e)?Math.min(n,Math.max(t,e)):t}function Ny(e,t){const n=Number(e);return Number.isFinite(n)?Math.floor(n):t}function I_(e,t=1){const n=ky(Number(e)/100,0,1),i=Math.round(140-140*n),o=ky(Number(t),0,1);return o>=1?`hsl(${i} 85% 55%)`:`hsl(${i} 85% 55% / ${o})`}function Cy(e){const t={...Hd,...e||{}};return t.tickMs=Math.max(250,Ny(t.tickMs,Hd.tickMs)),t.historySize=Math.max(1,Math.min(200,Ny(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 l1(){return`
59
- :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}
60
- .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)}
61
- .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))}
62
- .wrap.icon .top{display:none}
63
- .wrap.icon .bars{height:var(--monitor-gpu-bars-height,18px)}
64
- .top{display:flex;align-items:baseline;justify-content:space-between;gap:10px}
65
- .label{font-size:var(--monitor-gpu-font-size,var(--font-size-sm,12px));opacity:.9}
66
- .value{font-variant-numeric:tabular-nums;font-size:var(--monitor-gpu-font-size,var(--font-size-sm,12px));opacity:.95}
67
- .bars{display:flex;align-items:flex-end;gap:2px;height:var(--monitor-gpu-bars-height,34px);overflow:hidden}
68
- .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}
69
- .bar.missing{background:var(--monitor-gpu-bar-missing,#62708a);opacity:.35}
70
- .bar.error{background:var(--monitor-gpu-bar-error,#ff6b6b);opacity:.7}
71
- .muted{opacity:.6}
72
- `}class c1{constructor(t,n={}){if(!t||typeof t!="object")throw new TypeError("target element is required");this._target=t,this._opts=Cy(n),this._buffer=new vm(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=l1();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=Cy({...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",I_(c,.95)),n.style.setProperty("--monitor-gpu-accent-glow",I_(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:a1(b/100),E=Math.max(2,Math.min(p,Math.round($*p)));y.style.height=`${E}px`,y.style.background=b==null?"":I_(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 o1({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=i1(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 u1(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 c1(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 d1(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}function Dr(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,`
73
- `).replace(/\r/g,`
74
- `).split(`
75
- `),u=l.slice(0,Math.max(1,i)).join(`
76
- `),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 f1(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 da(e){const t=Nn(e);return t===null?"—":f1(t)}function $y(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 cg(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 ha(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 h1(...e){for(const t of e){const n=Number(t);if(Number.isFinite(n))return n}return null}function Ci(e){const t=String(e||"").trim().toLowerCase();return t==="completed"||t==="failed"||t==="cancelled"}function Pu(e){const t=String(e||"").trim().toLowerCase();return t==="running"||t==="waiting"}function nc(e){return String((e==null?void 0:e.started_at)||(e==null?void 0:e.created_at)||"").trim()}function sx(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 ug(e,t=Date.now()){const n=Nn(nc(e));if(n===null)return-1;const i=Nn(sx(e));return Math.max(0,(i!==null?i:t)-n)}function fc(e,t=Date.now()){return cg(ug(e,t))}function m1(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 Ou(e){return String(e||"").trim().toLowerCase()}function Bm(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 _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,t.kind,t.type,t.source,t.format,t.content_format,t.name].map(n=>String(n||"").trim()).filter(Boolean).join(" ").toLowerCase()}function p1(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 g1(e){const t=String(e||"").trimStart().slice(0,4096).toLowerCase();return t?!!(/^<!doctype\s+html\b/.test(t)||/^<html[\s>]/.test(t)||/<head[\s>][\s\S]*<\/head>/.test(t)||/<body[\s>][\s\S]*<\/body>/.test(t)||/<(?:article|main|section|div|p|h[1-6]|meta|title|script|style)\b[\s\S]*>/.test(t)&&/<\/(?:article|main|section|div|p|h[1-6]|title|script|style)>/.test(t)):!1}function ix(e,t){var u,c,f,_,p;const n=Ou(e==null?void 0:e.content_type),i=Bm(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,`
77
- `).replace(/\r/g,`
78
- `).split(`
79
- `);return ox(l)}function y1(e){const n=String(e||"").replace(/\r\n/g,`
80
- `).replace(/\r/g,`
81
- `).split(`
82
- `),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(`
83
- `).trim();return!o.length&&!l?null:{metadata:o,body:l}}function w1(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 v1(e){const t=e.map(i=>i.trimEnd()).filter(Boolean).slice(0,20);if(!t.length)return!1;const n=t.filter(i=>/^(\[[^\]]+\]|\d{4}-\d{2}-\d{2}[t\s]|\w+:\s|traceback\b|error\b|warn\b|info\b)/i.test(i.trim())).length;return t.length>=4&&n/t.length>=.55?!0:ox(e)}function ox(e){const t=e.map(i=>i.trimEnd()).filter(Boolean).slice(0,20);if(!t.length)return!1;const n=t.filter(i=>/[{};]\s*$/.test(i)||/^\s*(import|export|const|let|var|function|class|def|if|for|while|return)\b/.test(i)).length;return t.length>=4&&n/t.length>=.55}function x1(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,`
84
- `).replace(/\r/g,`
85
- `).split(`
86
- `).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 b1(e,t){var _;const n=String(t||""),i=_1(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,`
87
- `).replace(/\r/g,`
88
- `).split(`
89
- `),l=o.map(p=>p.trim()).filter(Boolean);if(l.length<2||x1(n)||w1(o)||v1(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=Ou(e==null?void 0:e.modality),n=Ou(e==null?void 0:e.content_type),i=Bm(e),o=p1(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")||ix(e,"")?"text":"binary"}function xm(e,t){const n=Ou(e==null?void 0:e.content_type),i=Bm(e),o=String(t||"").trim();return n.includes("html")||i.endsWith(".html")||i.endsWith(".htm")||g1(t)?"html":ix(e,t)?"code":n.includes("markdown")||i.endsWith(".md")||i.endsWith(".markdown")?"markdown":n.includes("json")||i.endsWith(".json")||i.endsWith(".jsonl")||(o.startsWith("{")||o.startsWith("["))&&Dm(o)!==null?"json":b1(e,t)?"markdown":"text"}function dg(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=Ou(e==null?void 0:e.modality),o=Ou(e==null?void 0:e.content_type),l=Bm(e);return i==="document"||o.includes("pdf")||af(l,[".pdf",".doc",".docx",".ppt",".pptx",".xls",".xlsx"])?"document":"other"}return xm(e,t)}function O_(e){var _,p;const t=String(e||"").replace(/\r\n/g,`
90
- `).replace(/\r/g,`
91
- `).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(`
92
- `).map($=>`${c(l)}${$.trimEnd()}`));continue}const S=y.replace(/\s+/g," ").trim();S&&o.push(`${c(l)}${S}`)}return o.join(`
93
- `)}function j1(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 bm(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 S1=/^\s*<runtime_metadata>\s*([\s\S]*?)\s*<\/runtime_metadata>\s*/i;function fg(e){const t=typeof e=="string"?e:String(e??""),n=S1.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 ax(...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 Cp(e){if(e==null)return"";if(typeof e=="string")return e.trim();if(Array.isArray(e))return e.map(t=>Cp(t)).filter(Boolean).join(`
94
- `).trim();if(typeof e=="object"){const t=e.text??e.content??e.message??e.value;if(t!==e){const n=Cp(t);if(n)return n}}return""}function lx(e){const t=fg(Cp(e));return{text:t.text,runtime_metadata:t.metadata}}function k1(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=fg(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 _=lx((c==null?void 0:c.content)??(c==null?void 0:c.text)??c);if(_.text)return{text:_.text,runtime_metadata:ax(_.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 N1(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",_=lx((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=ax(_.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 cx(e){const t=String(e||"").trim().toLowerCase().replace(/\s+/g," ");return t==="please respond:"||t==="please respond"||t==="type response..."||t==="type response"}function C1(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 ux="inferred from the call's arguments (regex heuristic) — not a declared risk tier; declared tiers replace this when the grant API ships";function dx(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 hg(e,t){const n=String((e==null?void 0:e.reason)||"").trim().toLowerCase(),i=C1(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 fx(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 hx(e,t){const n=String((e==null?void 0:e.prompt)||"").trim(),i=fg(n),o=k1(t);return i.text&&!cx(i.text)?{text:i.text,runtime_metadata:i.metadata}:o.text?o:{text:i.text||n,runtime_metadata:i.metadata}}function $1(e,t){return hx(e,t).text}function A1(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 r.jsx("span",{className:`run_status_pill ${fl(t)}`,children:t})}function E1(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?hg(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 jm(e){const t=e==null?void 0:e.error;return t?typeof t=="string"?ht(t,{max_chars:220,max_lines:2}):ht(Dr(t,400),{max_chars:220,max_lines:2}):""}function T1(e){const t=E1(e);if(t)return t;const n=jm(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 mx(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 Ay(e){const t=mx(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 M1(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 R1(e,t){if(!e||typeof e!="object")return null;const n=M1(e),i=mx(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)||Ay({...e,ref:i,metadata:o,tags:f}),semantic_kind:x||Ay({...e,ref:i,metadata:o,tags:f}),render_kind:y||dg({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:h1(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 $p(e){return e.filename||e.title||(e.source_path?e.source_path.split("/").filter(Boolean).slice(-1)[0]:"")||Lt(e.artifact_id,16)}function L1(e,t){if(t==="type")return Tu(e);if(t==="run")return e.run_id||"(no run)";if(t==="turn")return Ap(e);if(t==="node")return Eu(e)||"(node unknown)";if(t==="workflow")return mg(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 mg(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 Ap(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 Ey(e){if(!e)return"provenance unavailable";const t=[],n=mg(e),i=Eu(e),o=uf(e),l=_x(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 rc(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 I1(e){return e==="html"?"HTML":e==="json"?"JSON":e==="audio"?"Unclassified audio":e==="code"?"Code":e.slice(0,1).toUpperCase()+e.slice(1)}function P1(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 O1(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 Ty(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 D1(e){const t=ha(e.created_at),n=da(e.created_at);return t==="—"?"Created —":`${t}${n&&n!=="—"?` (${n})`:""}`}function My(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=ha(n);return i==="—"?"—":i}function Ry(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 _x(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 F1(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 Ly(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 Iy(e){return e.source_path||e.filename||""}function Sm(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 Ep(e,t,n,i=""){const o=Sm(e,t,n),l=dg(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 Hh(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 px(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):Dr(e,320),n=typeof e.duration=="number"?Number(e.duration):-1;return{text:t,duration:n}}return{text:Dr(e,320),duration:-1}}function Sf(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 lm(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 B1(e){return!!(e&&String(e.status||"")==="waiting")}function gx(e){var n,i;const t=[];for(const o of e||[]){const l=o.record;if(String(((n=l==null?void 0:l.effect)==null?void 0:n.type)||"").trim()!=="llm_call")continue;const c=(i=l==null?void 0:l.effect)!=null&&i.payload&&typeof l.effect.payload=="object"?l.effect.payload:{},f=l!=null&&l.result&&typeof l.result=="object"?l.result:{},_=(f==null?void 0:f.usage)||(f==null?void 0:f.token_usage)||{},p=typeof c.prompt=="string"?c.prompt:Array.isArray(c.messages)?Dr(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?Dr(l.error,500):"",raw:l})}return t.sort((o,l)=>(Nn(l.ts)??0)-(Nn(o.ts)??0))}function Py(e){const t=e.size||18,n=lf(e.artifact),i=dg(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"?r.jsx("span",{className:o,children:r.jsxs("svg",{...l,children:[r.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),r.jsx("path",{d:"M7 15l3-3 3 3 2-2 4 4"}),r.jsx("circle",{cx:"8",cy:"9",r:"1.4"})]})}):n==="audio"?r.jsx("span",{className:o,children:r.jsxs("svg",{...l,children:[r.jsx("path",{d:"M4 12h2"}),r.jsx("path",{d:"M8 8v8"}),r.jsx("path",{d:"M12 5v14"}),r.jsx("path",{d:"M16 8v8"}),r.jsx("path",{d:"M20 12h-2"})]})}):n==="video"?r.jsx("span",{className:o,children:r.jsxs("svg",{...l,children:[r.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),r.jsx("path",{d:"M9 9l6 3-6 3V9z",fill:"currentColor",stroke:"none"})]})}):i==="code"?r.jsx("span",{className:o,children:r.jsxs("svg",{...l,children:[r.jsx("path",{d:"M8 8l-4 4 4 4"}),r.jsx("path",{d:"M16 8l4 4-4 4"}),r.jsx("path",{d:"M14 4l-4 16"})]})}):n==="text"?r.jsx("span",{className:o,children:r.jsxs("svg",{...l,children:[r.jsx("path",{d:"M7 3h7l5 5v13H7z"}),r.jsx("path",{d:"M14 3v6h6"}),r.jsx("path",{d:"M10 13h7"}),r.jsx("path",{d:"M10 17h5"})]})}):r.jsx("span",{className:o,children:r.jsxs("svg",{...l,children:[r.jsx("path",{d:"M7 3h7l5 5v13H7z"}),r.jsx("path",{d:"M14 3v6h6"}),r.jsx("path",{d:"M9 14h8"})]})})}const U1=2,W1=Number.MAX_SAFE_INTEGER;function q1(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 H1(e){const t=String(e||"");if(typeof DOMParser>"u")return[{kind:"text",text:O_(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:O_(t)||t}]}catch{return[{kind:"text",text:O_(t)||t}]}}function D_(e){return e.closing?r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"runtime_html_punct",children:"</"}),r.jsx("span",{className:"runtime_html_tag",children:e.tag}),r.jsx("span",{className:"runtime_html_punct",children:">"})]}):r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"runtime_html_punct",children:"<"}),r.jsx("span",{className:"runtime_html_tag",children:e.tag}),e.attrs.map(t=>r.jsxs(ve.Fragment,{children:[" ",r.jsx("span",{className:"runtime_html_attr",children:t.name}),r.jsx("span",{className:"runtime_html_punct",children:"="}),r.jsxs("span",{className:"runtime_html_value",children:['"',t.value,'"']})]},`${e.tag}:${t.name}:${t.value}`)),r.jsx("span",{className:"runtime_html_punct",children:e.selfClosing?" />":">"})]})}function yx(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 r.jsxs("div",{className:"html-tree__line",style:{paddingLeft:n},children:[r.jsx("span",{className:"runtime_html_punct",children:"<!DOCTYPE "}),r.jsx("span",{className:"runtime_html_tag",children:t.name}),r.jsx("span",{className:"runtime_html_punct",children:">"})]});if(t.kind==="comment")return r.jsx("div",{className:"html-tree__line",style:{paddingLeft:n},children:r.jsx("span",{className:"runtime_html_comment",children:`<!-- ${t.text.trim()} -->`})});if(t.kind==="text")return r.jsx("div",{className:"html-tree__line html-tree__text",style:{paddingLeft:n},children:t.text});if(!t.children.length)return r.jsx("div",{className:"html-tree__line",style:{paddingLeft:n},children:r.jsx(D_,{tag:t.tag,attrs:t.attrs,selfClosing:!0})});const u=t.children.find(c=>c.kind==="text");return r.jsxs("details",{className:"html-tree__details",open:o,onToggle:c=>l(c.currentTarget.open),children:[r.jsxs("summary",{className:"html-tree__summary",style:{paddingLeft:n},children:[r.jsx("span",{className:"html-tree__caret","aria-hidden":"true",children:o?"▾":"▸"}),r.jsx(D_,{tag:t.tag,attrs:t.attrs}),!o&&u?r.jsxs("span",{className:"html-tree__summary_text",children:[" ",q1(u.text)]}):null]}),o?r.jsxs("div",{className:"html-tree__children",children:[t.children.map((c,f)=>r.jsx(yx,{node:c,depth:e.depth+1,collapseAfterDepth:e.collapseAfterDepth,expansionMode:e.expansionMode,expansionVersion:e.expansionVersion},`${e.depth}:${t.kind}:${t.tag}:${f}`)),r.jsx("div",{className:"html-tree__line",style:{paddingLeft:n},children:r.jsx(D_,{tag:t.tag,attrs:[],closing:!0})})]}):null]})}function V1(e){const t=m.useMemo(()=>H1(e.text),[e.text]),[n,i]=m.useState({mode:"folded",version:0}),o=n.mode==="unfolded"?W1:U1;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 r.jsxs("div",{className:`${e.className} structured html_source_preview`,children:[r.jsx("div",{className:"html-tree__toolbar",children:r.jsx("button",{type:"button",className:"btn html-tree__toggle",onClick:l,"aria-expanded":n.mode==="unfolded",children:n.mode==="unfolded"?"Fold all":"Unfold all"})}),r.jsx("div",{className:"html-tree__tree",role:"tree","aria-label":"HTML source tree",children:t.map((u,c)=>r.jsx(yx,{node:u,depth:0,collapseAfterDepth:o,expansionMode:n.mode,expansionVersion:n.version},`root:${c}`))})]})}function G1(e){var i;const t=y1(e.text);if(!t)return r.jsx("div",{className:`${e.className} structured markdown_preview`,children:r.jsx(Ni,{text:e.text})});const n=((i=t.metadata.find(o=>o.label.toLowerCase()==="title"))==null?void 0:i.value)||"";return r.jsxs("div",{className:`${e.className} structured markdown_preview artifact_markdown_report`,children:[n?r.jsx("h1",{className:"artifact_markdown_title",children:n}):null,t.metadata.length?r.jsx("dl",{className:"artifact_markdown_meta",children:t.metadata.map(o=>{const l=/^https?:\/\//i.test(o.value);return r.jsxs("div",{children:[r.jsx("dt",{children:o.label}),r.jsx("dd",{children:l?r.jsx("a",{href:o.value,target:"_blank",rel:"noreferrer",children:o.value}):o.value})]},`${o.label}:${o.value}`)})}):null,r.jsx(Ni,{text:t.body||e.text})]})}function wx(e){const t=String(e.text||""),n=xm(e.artifact,t);if(n==="json"){const i=Dm(t);if(i!==null)return r.jsx("div",{className:`${e.className} structured`,children:r.jsx(ds,{value:i,collapseAfterDepth:4,showCopy:!1})})}return n==="markdown"?r.jsx(G1,{text:t,className:e.className}):n==="html"?r.jsx(V1,{text:t,className:e.className}):r.jsx("pre",{className:`mono ${e.className}`,children:t})}function K1(e){const t=e.preview,n=e.artifact;return n?t.loading?r.jsx("div",{className:"runtime_inline_preview empty",children:"Loading preview…"}):t.error?r.jsx("div",{className:"runtime_inline_preview empty danger",children:t.error}):t.kind==="image"&&t.url?r.jsx("img",{className:"runtime_inline_preview media",src:t.url,alt:$p(n)}):t.kind==="audio"&&t.url?r.jsx("audio",{className:"runtime_inline_preview audio",src:t.url,controls:!0}):t.kind==="video"&&t.url?r.jsx("video",{className:"runtime_inline_preview media",src:t.url,controls:!0}):r.jsx(wx,{artifact:n,text:t.text||"Preview unavailable. Use Preview or Download.",className:"runtime_inline_preview text"}):r.jsx("div",{className:"runtime_inline_preview empty",children:"Select an artifact to preview it here."})}function _g(e){const t=e==null?void 0:e.waiting;return t&&typeof t=="object"?t:null}function vx(e){const t=_g(e);return String((t==null?void 0:t.reason)||(e==null?void 0:e.waiting_reason)||"").trim().toLowerCase()}function Oy(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 Y1(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=_g(e),i=vx(e);return Bu(n).length?"tool_approval":i==="until"||String((e==null?void 0:e.role)||"").trim()==="controller"?"scheduled":i==="subworkflow"?"subworkflow":i==="event"?Oy(n)?"user_response":"external_event":i==="user"||Oy(n)?"user_response":"unknown_wait"}function xx(e){const t=_g(e),n=Bu(t),i=Uu(e);return i==="tool_approval"?`Tool approval: ${Y1(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 J1(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 Dy(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 X1(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=ug(e,n),f=Nn(e.updated_at||e.created_at)??0,_=o==="running"&&c>=14400*1e3,p=xx(e)||Dy(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,vx(e),p,Dy(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:J1(e),action_label:S,search_text:b,is_terminal:u,needs_user_action:x,is_stale:_,duration_ms:c,updated_ms:f}}function Z1(e,t={}){const n=t.now_ms??Date.now(),i=t.workflow_label_by_id??{};return e.map(o=>X1(o,{now_ms:n,workflow_label:i[String(o.workflow_id||"")]||String(o.workflow_id||"")}))}function Q1(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 eC(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 tC(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 nC(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(()=>Z1(e.runs,{workflow_label_by_id:e.workflow_label_by_id}),[e.runs,e.workflow_label_by_id]),w=m.useMemo(()=>Q1(p),[p]),y=m.useMemo(()=>{const F=eC(p,{queue:t,query:i});return tC(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?hg(M,H):""),Y=(x==null?void 0:x.expected_action)||(M?fx(M,H):""),X=M?$1(M,null):"",se=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 r.jsxs("div",{className:"runtime_ops_layout",children:[r.jsxs("aside",{className:"pane runtime_ops_filters",children:[r.jsxs("div",{className:"pane_header runtime_ops_filter_header",children:[r.jsx("span",{className:"pane_title",children:"Queues"}),r.jsx("div",{className:"pane_spacer"}),r.jsxs("button",{className:"btn btn_icon",onClick:e.gateway_connected?e.on_refresh_runs:e.on_reconnect,children:[r.jsx(Qe,{name:"refresh",size:14}),e.gateway_connected?"Refresh":"Reconnect"]})]}),r.jsxs("div",{className:"pane_body scroll runtime_ops_queue_list",children:[ue.map(F=>r.jsxs("button",{className:`runtime_ops_filter ${t===F.key?"selected":""}`,"aria-pressed":t===F.key,onClick:()=>n(F.key),children:[r.jsx("span",{children:F.label}),r.jsx("strong",{children:F.count.toLocaleString()})]},F.key)),r.jsx("div",{className:"runtime_ops_hint",children:"Counts are for the loaded runtime page. Refine search or refresh when supervising large runtimes."})]})]}),r.jsxs("section",{className:"pane runtime_ops_table_panel",children:[r.jsxs("div",{className:"pane_header runtime_ops_list_header",children:[r.jsx("span",{className:"pane_title",children:"Runs"}),r.jsx("span",{className:"pane_count",children:y.length.toLocaleString()}),r.jsx("div",{className:"pane_spacer"}),r.jsx("input",{value:i,onChange:F=>o(F.target.value),placeholder:"Search workflow, run, node, status, error"}),r.jsxs("select",{className:"seg_select",value:l,onChange:F=>u(F.target.value),children:[r.jsx("option",{value:"attention",children:"Attention order"}),r.jsx("option",{value:"recent",children:"Latest event"}),r.jsx("option",{value:"oldest",children:"Oldest event"}),r.jsx("option",{value:"duration",children:"Longest duration"}),r.jsx("option",{value:"tokens",children:"Most tokens"}),r.jsx("option",{value:"workflow",children:"Workflow"})]})]}),r.jsxs("div",{className:"pane_body scroll runtime_ops_rows",children:[y.length?null:r.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(),P=_[N]||0;return r.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:O=>{(O.key==="Enter"||O.key===" ")&&(O.preventDefault(),f(N),e.on_select_run(N))},children:[r.jsxs("div",{className:"runtime_ops_row_top",children:[r.jsx("strong",{className:"runtime_ops_row_name",children:ji(C,e.workflow_label_by_id)}),F.is_stale?r.jsx("span",{className:"chip warn",children:"stale"}):null,r.jsx(hl,{status:C.status})]}),r.jsxs("div",{className:"runtime_ops_row_sub",children:[r.jsx("span",{className:"mono",children:Lt(N,18)}),r.jsx("span",{children:da(C.updated_at||C.created_at)}),r.jsx("span",{children:fc(C)}),r.jsx("span",{className:"runtime_ops_row_reason",title:F.reason,children:F.reason})]}),r.jsxs("div",{className:"runtime_ops_row_foot",children:[r.jsxs("span",{className:"runtime_ops_row_facts",children:[r.jsxs("span",{children:[Number(C.llm_calls||0).toLocaleString()," llm"]}),r.jsxs("span",{children:[Number(C.tool_calls||0).toLocaleString()," tools"]}),r.jsxs("span",{children:[Number(C.tokens_total||0).toLocaleString()," tok"]}),r.jsxs("span",{children:[P.toLocaleString()," artifacts"]})]}),r.jsxs("div",{className:"runtime_ops_actions",children:[F.needs_user_action?r.jsx("button",{className:"btn primary",onClick:O=>{O.stopPropagation(),e.on_open_run(N)},children:F.action_label}):r.jsx("button",{className:"btn",onClick:O=>{O.stopPropagation(),e.on_open_run(N)},children:"Open"}),r.jsx("button",{className:"btn",onClick:O=>{O.stopPropagation(),e.on_open_ledger(N)},children:"Ledger"}),r.jsx("button",{className:"btn",onClick:O=>{O.stopPropagation(),e.on_select_run(N),e.on_open_logs()},children:"Logs"}),r.jsx("button",{className:"btn",onClick:O=>{O.stopPropagation(),e.on_filter_artifacts(N)},children:"Artifacts"})]})]})]},N)})]})]}),r.jsxs("aside",{className:"pane runtime_ops_inspector",children:[r.jsxs("div",{className:"pane_header",children:[r.jsx("span",{className:"pane_title",children:"Run inspector"}),S?r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"pane_spacer"}),r.jsx(hl,{status:S.status})]}):null]}),r.jsx("div",{className:"pane_body scroll runtime_ops_inspector_body",children:S?r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"runtime_ops_inspector_head",children:[r.jsx("h3",{children:ji(S,e.workflow_label_by_id)}),r.jsx("span",{className:"mono",children:Lt(b,28)})]}),r.jsxs("div",{className:"runtime_ops_decision",children:[r.jsx("strong",{children:(x==null?void 0:x.reason)||T1(S)}),r.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.")})]}),r.jsxs("div",{className:"artifact_detail_grid",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Started"}),r.jsx("strong",{children:ha(nc(S))})]}),r.jsxs("div",{children:[r.jsx("span",{children:"Elapsed"}),r.jsx("strong",{children:fc(S)})]}),r.jsxs("div",{children:[r.jsx("span",{children:"Last event"}),r.jsx("strong",{children:ha(S.updated_at||S.created_at)})]}),r.jsxs("div",{children:[r.jsx("span",{children:"Session"}),r.jsx("strong",{className:"mono",children:S.session_id?Lt(String(S.session_id),18):"—"})]}),r.jsxs("div",{children:[r.jsx("span",{children:"Node"}),r.jsx("strong",{className:"mono",children:S.current_node||"—"})]}),r.jsxs("div",{children:[r.jsx("span",{children:"Visible artifacts"}),r.jsx("strong",{children:se.toLocaleString()})]}),r.jsxs("div",{children:[r.jsx("span",{children:"Provider calls"}),r.jsx("strong",{children:Number(S.llm_calls||0).toLocaleString()})]}),r.jsxs("div",{children:[r.jsx("span",{children:"Tokens"}),r.jsx("strong",{children:Number(S.tokens_total||0).toLocaleString()})]})]}),$?r.jsxs("section",{className:"runtime_ops_session_context",children:[r.jsxs("div",{children:[r.jsx("span",{className:"run_hero_eyebrow",children:"Session context"}),r.jsx("strong",{className:"mono",children:Lt($,30)})]}),r.jsxs("div",{className:"runtime_ops_session_facts",children:[r.jsxs("span",{children:[L.toLocaleString()," loaded run",L===1?"":"s"]}),r.jsxs("span",{children:[D.toLocaleString()," visible artifact",D===1?"":"s"]})]}),r.jsxs("div",{className:"runtime_detail_actions compact",children:[r.jsx("button",{className:"btn",onClick:()=>e.on_filter_session_artifacts($),children:"Open session artifacts"}),r.jsx("button",{className:"btn",onClick:()=>void dc($),children:"Copy session id"})]})]}):null,M?r.jsxs("div",{className:"runtime_ops_wait_summary",children:[r.jsxs("div",{className:"runtime_ops_wait_header",children:[r.jsx("span",{className:"run_hero_eyebrow",children:"Blocked on"}),r.jsx("strong",{children:Z})]}),r.jsx("p",{children:Y}),X?r.jsxs("div",{className:"runtime_ops_wait_request",children:[r.jsx("span",{children:"Request"}),r.jsx(Ni,{text:X})]}):r.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?r.jsx("div",{className:"runtime_ops_wait_tools",children:H.map((F,C)=>r.jsxs(ve.Fragment,{children:[r.jsx("span",{className:"chip mono warn",children:String((F==null?void 0:F.name)||"tool")}),dx(F).map(N=>r.jsxs("span",{className:"chip muted",title:ux,children:[N,"~"]},`${C}:${N}`))]},`${String((F==null?void 0:F.name)||"tool")}:${C}`))}):null,r.jsxs("details",{className:"runtime_raw_details",children:[r.jsx("summary",{className:"muted",children:"Raw wait payload"}),r.jsx(ds,{value:M,collapseAfterDepth:3,showCopy:!0})]})]}):null,jm(S)?r.jsx("div",{className:"warn_callout",children:jm(S)}):null,r.jsxs("div",{className:"runtime_detail_actions",children:[r.jsx("button",{className:"btn primary",onClick:()=>e.on_open_run(b),children:"Open Observe"}),r.jsx("button",{className:"btn",onClick:()=>e.on_open_ledger(b),children:"Open ledger"}),r.jsx("button",{className:"btn",onClick:()=>e.on_filter_artifacts(b),children:"Open artifacts"}),r.jsx("button",{className:"btn",onClick:e.on_open_logs,children:"Open logs"}),r.jsx("button",{className:"btn",onClick:()=>void dc(b),children:"Copy run id"})]})]}):r.jsx("div",{className:"empty_state_inline",children:"Select a run to inspect why it is active or blocked."})})]})]})}function rC(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,P=(N==null?void 0:N.semantic_kind)||{},O=(N==null?void 0:N.render_kind)||{};for(const ne of n)C[ne]=Number(P[ne]||O[ne]||0);return C.audio=Number(P.audio||0),C.other=Number(P.other||0)+Number(P.artifact||0)+Number(P.binary||0)+Number(P["(none)"]||0),C},[e.artifact_facets,e.artifact_type_facets]),x=C=>{const N=new Set(o);N.has(C)?N.delete(C):N.add(C),e.on_type_filters_change(Array.from(N.values()))},S=m.useMemo(()=>{const C={waiting:[],running:[],failed:[],cancelled:[],completed:[],other:[]};for(const N of e.runs){const P=String(N.status||"").trim().toLowerCase();P==="waiting"?C.waiting.push(N):P==="running"?C.running.push(N):P==="failed"?C.failed.push(N):P==="cancelled"?C.cancelled.push(N):P==="completed"?C.completed.push(N):C.other.push(N)}return C},[e.runs]),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 P;const C=new Set,N=((P=e.artifact_facets)==null?void 0:P.run_id)||{};for(const O of Object.keys(N))O&&O!=="(none)"&&C.add(O);for(const O of e.artifacts)O.run_id&&C.add(O.run_id);for(const O of e.active_runs)O.run_id&&C.add(String(O.run_id));return Array.from(C).map(O=>e.run_by_id[O]||{run_id:O,workflow_id:null,status:"",created_at:null,updated_at:null}).sort((O,ne)=>{const B=Pu(O.status)?0:1,z=Pu(ne.status)?0:1;if(B!==z)return B-z;const G=Nn(O.updated_at||O.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(P=>{var B,z;const O=P.record||{};return[P.cursor,O.run_id,O.node_id,O.status,(B=O.effect)==null?void 0:B.type,O.started_at,O.ended_at,Dr(((z=O.effect)==null?void 0:z.payload)??{},900),Dr(O.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=gx(e.runtime_ledger_log_items);return C?N.filter(P=>[P.provider,P.model,P.run_id,P.node_id,P.status,P.error,P.prompt_preview,P.response_preview,P.tokens.prompt,P.tokens.completion,P.tokens.total].join(" ").toLowerCase().includes(C)):N},[e.runtime_ledger_log_items,e.runtime_log_query]),Y=Z.reduce((C,N)=>C+(Number(N.tokens.total)||0),0),X=Z.filter(C=>C.missing_response||C.error).length,se=m.useMemo(()=>{const C=e.runtime_log_query.trim().toLowerCase(),N=String(e.audit_log_text||"").replace(/\r\n/g,`
95
- `).replace(/\r/g,`
96
- `).split(`
97
- `).filter(Boolean);return C?N.filter(P=>P.toLowerCase().includes(C)):N},[e.audit_log_text,e.runtime_log_query]),ie=e.runtime_log_source==="run_ledger"||e.runtime_log_source==="provider_calls",ue=e.runtime_log_source==="run_ledger"?"Selected Run Ledger":e.runtime_log_source==="provider_calls"?"Provider Calls":"Gateway HTTP Audit",F=e.runtime_log_source==="run_ledger"?"Runtime execution records for the selected workflow run.":e.runtime_log_source==="provider_calls"?"Model/provider call records extracted from the selected run ledger.":"Global Gateway HTTP/audit tail. This is system activity, not artifact provenance.";return r.jsxs("div",{className:"page runtime_page",children:[r.jsxs("section",{className:"runtime_header",children:[r.jsxs("div",{children:[r.jsx("div",{className:"run_hero_eyebrow",children:"System"}),r.jsx("h2",{children:e.tab==="activity"?"Activity monitor":e.tab==="artifacts"?"Artifact explorer":e.tab==="memory"?"Active memory":"Logs"}),r.jsxs("div",{className:"run_hero_meta",children:[r.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?r.jsxs("span",{className:"chip muted",children:["filtered run ",r.jsx("span",{className:"mono",children:Lt(e.artifact_run_filter,18)})]}):null,e.session_id?r.jsxs("span",{className:"chip muted",children:["session ",r.jsx("span",{className:"mono",children:Lt(e.session_id,18)})]}):null]})]}),r.jsxs("div",{className:"metric_grid compact runtime_header_metrics",children:[r.jsxs("div",{className:"metric_tile",children:[r.jsx("span",{children:"Waiting"}),r.jsx("strong",{children:D(S.waiting.length)})]}),r.jsxs("div",{className:"metric_tile",children:[r.jsx("span",{children:"Running"}),r.jsx("strong",{children:D(S.running.length)})]}),r.jsxs("div",{className:"metric_tile",children:[r.jsx("span",{children:"Failed"}),r.jsx("strong",{children:D(S.failed.length)})]}),r.jsxs("div",{className:"metric_tile",children:[r.jsxs("span",{children:["Artifacts",u?" (filtered)":""]}),r.jsx("strong",{children:D(l)})]})]})]}),r.jsx("nav",{className:"runtime_mode_tabs",role:"tablist","aria-label":"System sections",children:["activity","artifacts","memory","logs"].map(C=>r.jsxs("button",{role:"tab","aria-selected":e.tab===C,className:`runtime_mode_tab ${e.tab===C?"active":""}`,onClick:()=>e.on_tab_change(C),children:[r.jsx(Qe,{name:C==="activity"?"history":C==="artifacts"?"download":C==="memory"?"agent":"terminal",size:14}),r.jsx("span",{children:C==="activity"?"Activity":C==="artifacts"?"Artifacts":C==="memory"?"Memory":"Logs"})]},C))}),e.gateway_connected?null:r.jsxs("div",{className:"runtime_offline_banner",role:"status",children:[r.jsxs("div",{children:[r.jsx("strong",{children:"Gateway offline"}),r.jsx("span",{children:"Activity, artifacts, memory, and logs are unavailable until the gateway reconnects."})]}),r.jsxs("div",{children:[r.jsx("button",{className:"btn primary",onClick:e.on_reconnect,children:"Reconnect"}),r.jsx("button",{className:"btn",onClick:e.on_open_settings,children:"Settings"})]})]}),e.error?r.jsx("div",{className:"warn_callout",children:e.error}):null,e.tab==="activity"?r.jsx(nC,{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?r.jsx("div",{className:"runtime_memory_panel",children:e.memory_panel}):r.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"?r.jsxs(r.Fragment,{children:[r.jsxs("section",{className:"pane runtime_artifact_toolbar","aria-label":"Find artifacts",children:[r.jsxs("div",{className:"runtime_artifact_toolbar_top",children:[r.jsxs("label",{className:"artifact_filter_field artifact_filter_search",children:[r.jsx("span",{children:"Search"}),r.jsx("input",{value:e.query,onChange:C=>e.on_query_change(C.target.value),placeholder:"title, path, hash, run, workflow, tag"})]}),r.jsxs("label",{className:"artifact_filter_field",children:[r.jsx("span",{children:"Scope"}),r.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:[r.jsx("option",{value:"all",children:"All runtime"}),r.jsx("option",{value:"session",children:"This session"}),r.jsx("option",{value:"run",children:"Selected run"})]})]}),r.jsxs("label",{className:"artifact_filter_field",children:[r.jsx("span",{children:"Group"}),r.jsxs("select",{className:"seg_select",value:e.group_by,onChange:C=>e.on_group_by_change(C.target.value),children:[r.jsx("option",{value:"type",children:"Type"}),r.jsx("option",{value:"time",children:"Date"}),r.jsx("option",{value:"turn",children:"Turn"}),r.jsx("option",{value:"node",children:"Node"}),r.jsx("option",{value:"workflow",children:"Workflow"}),r.jsx("option",{value:"run",children:"Run"}),r.jsx("option",{value:"location",children:"Location"}),r.jsx("option",{value:"source",children:"Source"})]})]}),r.jsxs("label",{className:"artifact_filter_field",children:[r.jsx("span",{children:"Sort"}),r.jsxs("select",{className:"seg_select",value:e.sort_by,onChange:C=>e.on_sort_by_change(C.target.value),children:[r.jsx("option",{value:"newest",children:"Newest"}),r.jsx("option",{value:"oldest",children:"Oldest"}),r.jsx("option",{value:"last_access",children:"Last accessed"}),r.jsx("option",{value:"turn",children:"Turn order"}),r.jsx("option",{value:"type",children:"Type"}),r.jsx("option",{value:"size_desc",children:"Largest"}),r.jsx("option",{value:"size_asc",children:"Smallest"})]})]}),r.jsxs("button",{className:"btn btn_icon",onClick:e.on_refresh_artifacts,disabled:!e.gateway_connected||e.loading,children:[r.jsx(Qe,{name:"refresh",size:14}),e.loading?"Loading…":"Refresh"]})]}),r.jsxs("div",{className:"artifact_filter_section",children:[r.jsxs("div",{className:"artifact_filter_label",children:["Type ",r.jsx("span",{className:"muted",children:"OR"})]}),r.jsxs("div",{className:"artifact_filter_chips",role:"group","aria-label":"Artifact type filters combine with OR",children:[n.map(C=>{const N=o.has(C),P=y[C]||0,O=I1(C);return r.jsxs("button",{type:"button","aria-pressed":N,"aria-label":`${N?"Remove":"Add"} ${O} artifact type filter. Type filters combine with OR.`,title:`${N?"Remove":"Add"} ${O}. Type filters combine with OR.`,className:`artifact_filter_chip ${N?"active":""}`,onClick:()=>x(C),children:[r.jsx("span",{children:O}),r.jsx("span",{className:"artifact_chip_count",children:e.gateway_connected?P.toLocaleString():"—"})]},C)}),e.type_filters.length?r.jsx("button",{type:"button",className:"artifact_filter_chip clear",onClick:()=>e.on_type_filters_change([]),children:"Clear types"}):null]})]}),r.jsxs("div",{className:"artifact_filter_section",children:[r.jsx("div",{className:"artifact_filter_label",children:"Date"}),r.jsx("div",{className:"artifact_filter_chips",role:"group","aria-label":"Artifact date filters",children:i.map(C=>r.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))})]})]}),r.jsx("div",{className:"artifact_scope_banner",children:e.artifact_run_filter?r.jsxs(r.Fragment,{children:["Showing artifacts for ",r.jsx("strong",{children:$||Lt(e.artifact_run_filter,18)}),".",r.jsx("button",{className:"btn",onClick:()=>L(""),children:"Show all"})]}):r.jsxs(r.Fragment,{children:["Showing artifacts across the selected runtime scope. Select a run to filter the inventory. ",e.artifact_total_bytes?r.jsxs("span",{className:"mono muted",children:["Total size ",rc(e.artifact_total_bytes)]}):null]})}),r.jsxs("div",{className:"runtime_artifacts_layout",children:[r.jsxs("aside",{className:"pane artifact_filter_rail",children:[r.jsxs("div",{className:"pane_header",children:[r.jsx("span",{className:"pane_title",children:"Runs"}),r.jsx("span",{className:"pane_count",children:E.length.toLocaleString()})]}),r.jsxs("div",{className:"pane_body scroll artifact_filter_rail_list",children:[r.jsxs("button",{className:`artifact_filter_run ${e.artifact_run_filter?"":"selected"}`,onClick:()=>L(""),children:[r.jsx("strong",{children:"All artifacts"}),r.jsx("span",{children:e.gateway_connected?`${l.toLocaleString()} match${l===1?"":"es"}`:"counts unavailable"})]}),E.map(C=>{const N=String(C.run_id||"").trim(),P=N===e.artifact_run_filter||N===(t==null?void 0:t.run_id);return r.jsxs("button",{className:`artifact_filter_run ${P?"selected":""}`,onClick:()=>L(N),title:N,children:[r.jsx("strong",{children:ji(C,e.workflow_label_by_id)}),r.jsx("span",{className:"mono",children:Lt(N,15)}),r.jsx("span",{children:fc(C)})]},N)})]})]}),r.jsxs("section",{className:"pane runtime_artifact_browser",children:[r.jsxs("div",{className:"pane_header artifact_browser_header",children:[r.jsx("span",{className:"pane_title",children:"Artifacts"}),r.jsx("span",{className:"pane_count",children:l?`${p.toLocaleString()}-${w.toLocaleString()} of ${l.toLocaleString()}`:"0 items"}),r.jsx("div",{className:"pane_spacer"}),f>1?r.jsxs("div",{className:"artifact_pagination","aria-label":"Artifact pages",children:[r.jsx("button",{className:"btn",onClick:()=>e.on_artifact_page_change(0),disabled:_<=0,children:"First"}),r.jsx("button",{className:"btn",onClick:()=>e.on_artifact_page_change(_-1),disabled:_<=0,children:"Prev"}),r.jsxs("span",{className:"muted artifact_page_label",children:["Page ",(_+1).toLocaleString()," / ",f.toLocaleString()]}),r.jsx("button",{className:"btn",onClick:()=>e.on_artifact_page_change(_+1),disabled:_>=f-1,children:"Next"}),r.jsx("button",{className:"btn",onClick:()=>e.on_artifact_page_change(f-1),disabled:_>=f-1,children:"Last"})]}):null]}),r.jsxs("div",{className:"pane_body scroll artifact_browser_body",children:[e.artifact_groups.length?null:r.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."}),r.jsx("div",{className:"artifact_group_list",children:e.artifact_groups.map(C=>r.jsxs("section",{className:"artifact_group",children:[r.jsxs("div",{className:"artifact_group_header",children:[r.jsx("span",{children:C.key}),r.jsx("span",{className:"artifact_group_count",children:C.items.length})]}),C.items.map(N=>{var z;const P=N.run_id&&e.run_by_id[N.run_id]||null,O=P?ji(P,e.workflow_label_by_id):mg(N),ne=Ly(N),B=Number(((z=N.access)==null?void 0:z.access_count)||0)||0;return r.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:[r.jsx(Py,{artifact:N,size:18}),r.jsxs("div",{className:"artifact_row_main",children:[r.jsxs("div",{className:"artifact_row_title",children:[r.jsx("strong",{children:Ry(Sm(N,e.run_by_id,e.workflow_label_by_id))}),r.jsx("span",{className:"artifact_type_badge",children:Tu(N)}),N.render_kind&&N.render_kind!==N.semantic_kind?r.jsx("span",{className:"artifact_type_badge muted",children:N.render_kind}):null,N.legacy_inferred?r.jsx("span",{className:"artifact_type_badge inferred",children:"legacy inferred"}):null]}),r.jsxs("div",{className:"artifact_row_facts",children:[r.jsxs("span",{children:[r.jsx("b",{children:"Created"})," ",D1(N)]}),r.jsxs("span",{children:[r.jsx("b",{children:"Size"})," ",rc(N.size_bytes)]}),r.jsxs("span",{children:[r.jsx("b",{children:"Last seen"})," ",My(N)]}),B?r.jsxs("span",{children:[r.jsx("b",{children:"Accesses"})," ",B.toLocaleString()]}):null,ne?r.jsxs("span",{children:[r.jsx("b",{children:"Media"})," ",ne]}):null,N.content_type?r.jsxs("span",{children:[r.jsx("b",{children:"MIME"})," ",N.content_type]}):null]}),r.jsxs("div",{className:"artifact_row_facts secondary",children:[O?r.jsxs("span",{children:[r.jsx("b",{children:"Workflow"})," ",O]}):null,N.run_id?r.jsxs("span",{className:"mono",children:[r.jsx("b",{children:"Run"})," ",Lt(N.run_id,13)]}):null,r.jsxs("span",{children:[r.jsx("b",{children:"Turn"})," ",Ap(N)]}),Eu(N)?r.jsxs("span",{className:"mono",children:[r.jsx("b",{children:"Node"})," ",Eu(N)]}):null,uf(N)?r.jsxs("span",{children:[r.jsx("b",{children:"Source"})," ",uf(N)]}):null]}),r.jsxs("div",{className:"artifact_row_facts tertiary",children:[r.jsxs("span",{className:"mono",children:[r.jsx("b",{children:"ID"})," ",Lt(N.artifact_id,22)]}),r.jsxs("span",{children:[r.jsx("b",{children:"Provenance"})," ",Ey(N)]})]}),Iy(N)?r.jsx("div",{className:"artifact_row_path mono",children:Iy(N)}):null]})]},N.artifact_id)})]},C.key))})]})]}),r.jsx("aside",{className:"runtime_detail",children:r.jsxs("section",{className:"overview_panel runtime_artifact_detail",children:[r.jsxs("div",{className:"overview_panel_header",children:[r.jsx("h3",{children:"Artifact Detail"}),t?r.jsx("span",{className:"chip mono muted",children:e.embedded_preview.render_kind?Ep(t,e.run_by_id,e.workflow_label_by_id,e.embedded_preview.text):Ep(t,e.run_by_id,e.workflow_label_by_id)}):null]}),t?r.jsxs(r.Fragment,{children:[(()=>{var z,G,T,Q,K,J,oe;const C=F1(t),N=_x(t),P=Ly(t),O=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 r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"artifact_detail_header",children:[r.jsx(Py,{artifact:t,size:22}),r.jsxs("div",{children:[r.jsx("div",{className:"artifact_detail_title",children:Ry(Sm(t,e.run_by_id,e.workflow_label_by_id))}),r.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"," • ",rc(t.size_bytes),t.legacy_inferred?" • legacy inferred":""]})]})]}),r.jsx(K1,{artifact:t,preview:e.embedded_preview}),r.jsxs("div",{className:"artifact_detail_grid",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Semantic type"}),r.jsx("strong",{children:Tu(t)})]}),r.jsxs("div",{children:[r.jsx("span",{children:"Render kind"}),r.jsx("strong",{children:t.render_kind||e.embedded_preview.render_kind||"—"})]}),r.jsxs("div",{children:[r.jsx("span",{children:"Created"}),r.jsx("strong",{children:ha(t.created_at)})]}),r.jsxs("div",{children:[r.jsx("span",{children:"Size"}),r.jsx("strong",{children:rc(t.size_bytes)})]}),r.jsxs("div",{children:[r.jsx("span",{children:"Last seen"}),r.jsx("strong",{children:My(t)})]}),r.jsxs("div",{children:[r.jsx("span",{children:"Accesses"}),r.jsx("strong",{children:O?O.toLocaleString():"—"})]}),r.jsxs("div",{children:[r.jsx("span",{children:"Run"}),r.jsx("strong",{className:"mono",children:t.run_id?Lt(t.run_id,24):"—"})]}),r.jsxs("div",{children:[r.jsx("span",{children:"Workflow"}),r.jsx("strong",{children:b?ji(b,e.workflow_label_by_id):"—"})]}),r.jsxs("div",{children:[r.jsx("span",{children:"Turn"}),r.jsx("strong",{children:Ap(t)})]}),r.jsxs("div",{children:[r.jsx("span",{children:"Node"}),r.jsx("strong",{className:"mono",children:Eu(t)||"—"})]}),r.jsxs("div",{children:[r.jsx("span",{children:"Provider/model"}),r.jsx("strong",{children:N||"—"})]}),r.jsxs("div",{children:[r.jsx("span",{children:"Media facts"}),r.jsx("strong",{children:P||"—"})]}),r.jsxs("div",{children:[r.jsx("span",{children:"Trace"}),r.jsx("strong",{children:t.provider_trace_available?"available":"not recorded"})]}),r.jsxs("div",{children:[r.jsx("span",{children:"Provenance"}),r.jsx("strong",{children:Ey(t)})]}),r.jsxs("div",{children:[r.jsx("span",{children:"Artifact id"}),r.jsx("strong",{className:"mono",children:Lt(t.artifact_id,30)})]}),t.sha256?r.jsxs("div",{children:[r.jsx("span",{children:"sha256"}),r.jsx("strong",{className:"mono",children:Lt(t.sha256,30)})]}):null]}),C?r.jsxs("div",{className:"artifact_provenance_panel",children:[r.jsx("div",{className:"artifact_filter_label",children:"Generation prompt / input"}),r.jsx("div",{className:"artifact_prompt_text",children:C})]}):r.jsxs("div",{className:"artifact_provenance_panel muted",children:[r.jsx("div",{className:"artifact_filter_label",children:"Generation prompt / input"}),r.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?r.jsxs("details",{className:"runtime_raw_details",children:[r.jsx("summary",{className:"mono muted",children:"Generation and producer metadata"}),r.jsx(ds,{value:{generation:t.generation,producer:t.producer,source_refs:t.source_refs},collapseAfterDepth:3,showCopy:!0})]}):null,t.source_path?r.jsx("div",{className:"artifact_detail_path mono",children:t.source_path}):null,r.jsxs("div",{className:"runtime_detail_actions",children:[r.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"}),r.jsx("button",{className:"btn",onClick:()=>e.on_download_artifact(t),disabled:!t.run_id,children:"Download"}),r.jsx("button",{className:"btn",onClick:()=>L(t.run_id),disabled:!t.run_id,children:"Show run artifacts"}),r.jsx("button",{className:"btn",onClick:()=>e.on_open_run(t.run_id),disabled:!t.run_id,children:"Open in Observe"}),r.jsx("button",{className:"btn",onClick:()=>e.on_open_ledger(t.run_id),disabled:!t.run_id,children:"Open run ledger"}),r.jsx("button",{className:"btn",onClick:()=>{ne&&window.open(ne,"_blank","noopener,noreferrer")},disabled:!ne,children:"Open provider trace"}),r.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"}),r.jsx("button",{className:"btn",onClick:()=>void dc(t.artifact_id),disabled:!t.artifact_id,children:"Copy artifact id"})]})]})})(),r.jsxs("details",{className:"runtime_raw_details",children:[r.jsx("summary",{className:"mono muted",children:"Raw metadata"}),r.jsx(ds,{value:t.raw,collapseAfterDepth:3,showCopy:!0})]})]}):r.jsx("div",{className:"empty_state_inline",children:"Select an artifact to inspect metadata, preview, or download content."})]})})]})]}):null,e.tab==="logs"?r.jsxs("section",{className:"overview_panel runtime_logs_panel",children:[r.jsxs("div",{className:"overview_panel_header",children:[r.jsxs("div",{children:[r.jsx("h3",{children:ue}),r.jsx("div",{className:"mono muted",children:F})]}),r.jsxs("div",{className:"actions",style:{marginTop:0},children:[ie&&e.runtime_ledger_log_meta?r.jsx("span",{className:"mono muted",children:e.runtime_ledger_log_meta}):null,e.runtime_log_source==="gateway_audit"&&e.audit_log_meta?r.jsx("span",{className:"mono muted",children:e.audit_log_meta}):null,r.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:[r.jsx(Qe,{name:"refresh",size:14}),ie?e.runtime_ledger_log_loading?"Loading…":"Refresh":e.audit_log_loading?"Loading…":"Refresh"]})]})]}),r.jsxs("div",{className:"runtime_log_toolbar",children:[r.jsxs("div",{className:"seg_toggle mono",children:[r.jsx("button",{className:`seg_btn ${e.runtime_log_source==="run_ledger"?"active":""}`,onClick:()=>e.on_runtime_log_source_change("run_ledger"),children:"Run ledger"}),r.jsx("button",{className:`seg_btn ${e.runtime_log_source==="provider_calls"?"active":""}`,onClick:()=>e.on_runtime_log_source_change("provider_calls"),children:"Provider calls"}),r.jsx("button",{className:`seg_btn ${e.runtime_log_source==="gateway_audit"?"active":""}`,onClick:()=>e.on_runtime_log_source_change("gateway_audit"),children:"Gateway audit"})]}),r.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"?r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"runtime_log_context",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Selected run"}),r.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?r.jsx("em",{className:"mono",children:Lt(e.selected_run_id,34)}):null]}),r.jsxs("div",{children:[r.jsx("span",{children:"Session"}),r.jsx("strong",{className:"mono",children:M!=null&&M.session_id?Lt(String(M.session_id),28):e.session_id?Lt(e.session_id,28):"—"})]}),r.jsxs("div",{className:"runtime_log_context_actions",children:[r.jsx("button",{className:"btn",onClick:()=>e.on_open_run(e.selected_run_id),disabled:!e.selected_run_id,children:"Open Observe"}),r.jsx("button",{className:"btn",onClick:()=>L(e.selected_run_id),disabled:!e.selected_run_id,children:"Run artifacts"})]})]}),e.runtime_ledger_log_error?r.jsx("div",{className:"warn_callout",children:e.runtime_ledger_log_error}):null,e.selected_run_id?null:r.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?r.jsx("div",{className:"empty_state_inline",children:"No ledger records match the current search."}):null,r.jsx("div",{className:"runtime_log_event_list","aria-label":"Selected run ledger records",children:H.map(C=>{var K,J;const N=C.record||{},P=String(((K=N==null?void 0:N.effect)==null?void 0:K.type)||"").trim(),O=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=px(N),T=P?ht(Dr(((J=N==null?void 0:N.effect)==null?void 0:J.payload)??{},1200),{max_chars:1200,max_lines:6}):"",Q=Sf(N)||(z?`Waiting for ${String(z.reason||"input")}`:"")||((N==null?void 0:N.result)!==void 0?Dr(N.result,700):"");return r.jsxs("article",{className:`runtime_log_event ${fl(O)}`,children:[r.jsxs("div",{className:"runtime_log_event_header",children:[r.jsxs("span",{className:"mono",children:["#",C.cursor]}),r.jsx(hl,{status:O||"record"}),P?r.jsx("span",{className:"chip mono muted",children:P}):null,ne?r.jsx("strong",{className:"mono",children:ne}):null,B?r.jsx("span",{className:"mono muted",children:ha(B)}):null]}),r.jsxs("div",{className:"runtime_log_event_body",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Request / activity"}),r.jsx("p",{children:[G||lm(N),T&&T!=="{}"?T:""].filter(Boolean).join(`
98
- `)})]}),r.jsxs("div",{children:[r.jsx("span",{children:"Outcome"}),r.jsx("p",{children:ht(Q||"—",{max_chars:1200,max_lines:6})})]})]}),r.jsxs("details",{className:"runtime_raw_details",children:[r.jsx("summary",{className:"mono muted",children:"Raw ledger record"}),r.jsx(ds,{value:N,collapseAfterDepth:3,showCopy:!0})]})]},`${e.selected_run_id}:${C.cursor}`)})})]}):e.runtime_log_source==="provider_calls"?r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"runtime_log_context",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Selected run"}),r.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?r.jsx("em",{className:"mono",children:Lt(e.selected_run_id,34)}):null]}),r.jsxs("div",{children:[r.jsx("span",{children:"Provider calls"}),r.jsx("strong",{children:Z.length.toLocaleString()}),r.jsx("em",{className:"mono",children:Y?`${Y.toLocaleString()} tokens`:"tokens not recorded"})]}),r.jsxs("div",{children:[r.jsx("span",{children:"Issues"}),r.jsx("strong",{children:X.toLocaleString()})]}),r.jsxs("div",{className:"runtime_log_context_actions",children:[r.jsx("button",{className:"btn",onClick:()=>e.on_open_run(e.selected_run_id),disabled:!e.selected_run_id,children:"Open Observe"}),r.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?r.jsx("div",{className:"warn_callout",children:e.runtime_ledger_log_error}):null,e.selected_run_id?null:r.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?r.jsx("div",{className:"empty_state_inline",children:"No provider calls are present in the selected run ledger, or none match the current search."}):null,r.jsx("div",{className:"provider_activity_list runtime_provider_log_list",children:Z.map(C=>r.jsxs("article",{className:`provider_activity ${C.error||C.missing_response?"danger":""}`,children:[r.jsxs("div",{className:"provider_activity_header",children:[r.jsxs("div",{children:[r.jsx("h4",{children:[C.provider||"provider unknown",C.model||"model unknown"].join(" / ")}),r.jsxs("div",{className:"timeline_subtitle",children:[C.node_id?r.jsx("span",{className:"mono",children:C.node_id}):null,C.run_id?r.jsx("span",{className:"mono",children:Lt(C.run_id,16)}):null,r.jsx("span",{children:cg(C.duration_ms)}),C.status?r.jsx(hl,{status:C.status}):null]})]}),r.jsxs("div",{className:"provider_tokens mono",children:[C.tokens.total?C.tokens.total.toLocaleString():"—"," tokens"]})]}),r.jsxs("div",{className:"provider_preview_grid",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Prompt / messages"}),r.jsx("p",{children:C.prompt_preview||"No prompt payload captured"})]}),r.jsxs("div",{children:[r.jsx("span",{children:"Response / error"}),r.jsx("p",{children:C.response_preview||C.error||"No response captured"})]})]}),r.jsxs("details",{className:"runtime_raw_details",children:[r.jsx("summary",{className:"mono muted",children:"Raw provider ledger record"}),r.jsx(ds,{value:C.raw,collapseAfterDepth:3,showCopy:!0})]})]},C.id))})]}):r.jsxs(r.Fragment,{children:[e.audit_log_error?r.jsx("div",{className:"warn_callout",children:e.audit_log_error}):null,r.jsx("pre",{className:"mono audit_log_tail",children:se.length?se.join(`
99
- `):"(audit tail not loaded or no lines match search)"})]})]}):null]})}const Vh=30;function sC(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 r.jsxs(r.Fragment,{children:[i.length?r.jsxs("div",{className:"field",children:[r.jsx("label",{children:"Expected response"}),r.jsxs("select",{className:"mono",value:t,onChange:c=>n(c.target.value),children:[r.jsx("option",{value:"",children:"(select)"}),i.map((c,f)=>r.jsx("option",{value:String(c),children:String(c)},f))]})]}):null,o?r.jsxs("div",{className:"field",children:[r.jsx("label",{children:i.length?"Or type a response":u?"Your answer":"Response to resume this wait"}),r.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,r.jsx("div",{className:"actions",children:r.jsx("button",{className:"btn primary",disabled:l||!t.trim(),onClick:()=>e.on_submit(t.trim()),children:"Submit response"})})]})}function Fy(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 zy(e){const t=cf(e.run);return t?r.jsx("span",{className:"chip scheduled run_tree_tag","data-tag":t,children:tx(e.run)}):null}function iC(e){const t=e.selected_run_id.trim(),n=e.root_run_id.trim()||t,i=e.sections.reduce((o,l)=>o+l.rows.reduce((u,c)=>{const f=[c.run,...c.children];return u+f.filter(_=>Pu(_.status)).length},0),0);return r.jsxs("aside",{className:"observatory_sidebar pane",children:[r.jsxs("div",{className:"run_nav_header pane_header",children:[r.jsx("span",{className:"pane_title",children:"Runs"}),r.jsxs("span",{className:"pane_count",children:[e.total_runs.toLocaleString()," runs • ",i.toLocaleString()," active"]}),r.jsx("span",{className:"pane_spacer"}),r.jsxs("button",{className:"btn btn_icon",onClick:e.on_refresh,disabled:e.loading,title:"Refresh workflow runs",children:[r.jsx(Qe,{name:"refresh",size:14}),e.loading?"…":""]})]}),r.jsxs("div",{className:"run_nav_controls",children:[r.jsx("input",{value:e.search,onChange:o=>e.on_search(o.target.value),placeholder:"Search runs, sessions, workflows"}),r.jsxs("div",{className:"run_nav_filter_row",children:[r.jsx("div",{className:"seg_toggle run_nav_segments",children:["active","waiting","terminal","failed","all"].map(o=>r.jsx("button",{className:`seg_btn ${e.filter===o?"active":""}`,onClick:()=>e.on_filter(o),children:o},o))}),r.jsxs("select",{className:"seg_select",value:e.group_by,onChange:o=>e.on_group_by(o.target.value),title:"Group workflow runs",children:[r.jsx("option",{value:"status",children:"Group by status"}),r.jsx("option",{value:"workflow",children:"Group by workflow"}),r.jsx("option",{value:"session",children:"Group by session"})]})]})]}),r.jsxs("div",{className:"run_tree",children:[e.sections.length?null:e.connected?r.jsx("div",{className:"run_tree_empty",children:"No runs match the current filters."}):r.jsxs("div",{className:"run_tree_empty",children:["Gateway offline — runs are unavailable."," ",r.jsx("button",{className:"btn btn_sm",onClick:e.on_sign_in,children:"Sign in"})]}),e.sections.map(o=>r.jsxs("section",{className:"run_tree_section",children:[r.jsxs("div",{className:"run_tree_section_header",children:[r.jsx("span",{children:o.label}),r.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 r.jsxs("div",{className:"run_tree_group",children:[r.jsxs("button",{className:`run_tree_item ${f?"selected":""} ${c===n?"root_context":""}`,onClick:()=>e.on_select(c,c),title:c,children:[r.jsxs("div",{className:"run_tree_item_top",children:[r.jsx("span",{className:"run_tree_label",children:Fy(u,e.workflow_label_by_id,e.automation_titles)}),r.jsx(zy,{run:u}),u.status?r.jsx(hl,{status:bm(u)}):null]}),r.jsxs("div",{className:"run_tree_meta",children:[r.jsx("span",{className:"mono",children:Lt(c,13)}),r.jsx("span",{children:nc(u)?da(nc(u)):"no start"}),r.jsx("span",{children:fc(u)})]})]}),l.children.length?r.jsx("div",{className:"run_tree_children",children:l.children.map(_=>{const p=String(_.run_id||"").trim();return r.jsxs("button",{className:`run_tree_item run_tree_child ${p===t?"selected":""}`,onClick:()=>e.on_select(p,c),title:p,children:[r.jsxs("div",{className:"run_tree_item_top",children:[r.jsx("span",{className:"run_tree_label",children:Fy(_,e.workflow_label_by_id,e.automation_titles)}),r.jsx(zy,{run:_}),r.jsx(hl,{status:bm(_)})]}),r.jsxs("div",{className:"run_tree_meta",children:[r.jsx("span",{className:"mono",children:Lt(p,13)}),r.jsx("span",{children:nc(_)?da(nc(_)):"child"}),r.jsx("span",{children:fc(_)})]})]},p)})}):null]},c)})]},o.key))]})]})}function By(){return r.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:r.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 oC(e){var $,E,L,D,M,H,Z;const t=e.run_id.trim(),[n,i]=m.useState(!1);if(!t)return r.jsx("div",{className:"run_overview",children:r.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=sx(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?cg((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=jm(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=Sf((H=e.records[Y])==null?void 0:H.record);if(X){b=X;break}}return r.jsxs("div",{className:"run_overview",children:[r.jsxs("section",{className:"run_hero run_hero_line",children:[r.jsx("h2",{className:"run_hero_title",title:o,children:o}),r.jsx(hl,{status:e.status_label}),t?r.jsx("span",{className:"chip mono muted",title:t,children:Lt(t,18)}):null,e.root_run_id&&e.root_run_id!==t?r.jsxs("span",{className:"chip mono muted",title:e.root_run_id,children:["root ",Lt(e.root_run_id,12)]}):null,r.jsx("span",{className:"run_hero_spacer"}),e.workspace_root?r.jsxs("button",{className:"btn btn_icon",onClick:e.on_reveal_workspace,title:`Open the run's workspace folder
100
- ${e.workspace_root}`,children:[r.jsx(By,{}),"Folder"]}):null,r.jsx("button",{className:"btn",onClick:e.on_generate_summary,disabled:!t||e.summary_generating,children:e.summary_generating?"Summarizing…":w?"Refresh summary":"Summarize"}),r.jsx("button",{className:"btn",onClick:e.on_open_runtime,title:"Open this run's artifacts in the System explorer",children:"Run artifacts"})]}),x?r.jsxs("section",{className:"overview_panel",children:[r.jsxs("div",{className:"overview_panel_header",children:[r.jsx("h3",{children:"Outcome"}),r.jsx("span",{className:`chip mono ${fl(e.status_label)}`,children:e.status_label||(S?"failed":"completed")})]}),S?r.jsx("div",{className:"error_callout",children:S}):null,b?r.jsx(Ni,{text:ht(b,{max_chars:4e3,max_lines:60})}):null,!S&&!b?r.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"},se=C=>{const N=C!=null&&C.tags&&typeof C.tags=="object"?C.tags:{},P=String((C==null?void 0:C.filename)||N.filename||"").trim();if(P)return P;const O=String(N.path||(C==null?void 0:C.source_path)||"").trim();return O?O.split("/").pop()||O:String((C==null?void 0:C.title)||"").trim()||String((C==null?void 0:C.artifact_id)||"").slice(0,14)},ie=C=>{var N;return r.jsxs("div",{className:"run_artifact_row",children:[r.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:se(C)}),r.jsx("span",{className:"chip mono muted",children:String((C==null?void 0:C.content_type)||"?").replace(/^application\//,"").replace(/^text\//,"")}),r.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`:""}),r.jsxs("span",{className:"run_artifact_actions",children:[r.jsx("button",{className:"btn",onClick:()=>e.on_preview_run_artifact(C),children:"Preview"}),r.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 r.jsxs("section",{className:"overview_panel",children:[r.jsxs("div",{className:"overview_panel_header",children:[r.jsx("h3",{children:"Artifacts"}),r.jsx("span",{className:"mono muted",children:Y.length?Y.length.toLocaleString():""}),e.workspace_root?r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"pane_spacer"}),r.jsxs("button",{className:"btn btn_icon",onClick:e.on_reveal_workspace,title:`Open the run's workspace folder
101
- ${e.workspace_root}`,children:[r.jsx(By,{}),"Workspace"]})]}):null]}),e.run_artifacts_error?r.jsx("div",{className:"warn_callout",children:e.run_artifacts_error}):null,e.run_artifacts_loading&&!Y.length?r.jsx("div",{className:"empty_state_inline",children:"Loading artifacts…"}):null,!e.run_artifacts_loading&&!Y.length&&!e.run_artifacts_error?r.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?r.jsx("div",{className:"run_artifact_list",children:ue.map(ie)}):null,!ue.length&&Y.length?r.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?r.jsxs("details",{className:"runtime_raw_details",children:[r.jsxs("summary",{className:"muted",children:["Internal state offloads (",F.length,")"]}),r.jsx("div",{className:"run_artifact_list",children:F.map(ie)})]}):null]})})(),r.jsxs("div",{className:"metric_grid",children:[r.jsxs("div",{className:"metric_tile",children:[r.jsx("span",{children:"Started"}),r.jsx("strong",{children:ha(l)})]}),r.jsxs("div",{className:"metric_tile",children:[r.jsx("span",{children:u?"Finished":"Running for"}),r.jsx("strong",{children:u?ha(u):c})]}),r.jsxs("div",{className:"metric_tile",children:[r.jsx("span",{children:"Total duration"}),r.jsx("strong",{children:c})]}),r.jsxs("div",{className:"metric_tile",children:[r.jsx("span",{children:"Ledger"}),r.jsx("strong",{children:(e.records_count+e.child_records_count).toLocaleString()})]}),r.jsxs("div",{className:"metric_tile",children:[r.jsx("span",{children:"Subworkflows"}),r.jsx("strong",{children:e.subrun_ids.length.toLocaleString()})]}),r.jsxs("div",{className:"metric_tile",children:[r.jsx("span",{children:"Provider calls"}),r.jsx("strong",{children:f.toLocaleString()})]}),r.jsxs("div",{className:"metric_tile",children:[r.jsx("span",{children:"Tokens"}),r.jsx("strong",{children:_?_.toLocaleString():"—"})]}),r.jsxs("div",{className:"metric_tile",children:[r.jsx("span",{children:"Assets"}),r.jsx("strong",{children:e.attachments_count.toLocaleString()})]})]}),r.jsxs("div",{className:"overview_columns",children:[r.jsxs("section",{className:"overview_panel",children:[r.jsxs("div",{className:"overview_panel_header",children:[r.jsx("h3",{children:x?"What happened":"What is happening"}),y?r.jsx("span",{className:"chip mono info",children:"waiting"}):null]}),y?r.jsxs("div",{className:"overview_fact_list",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Reason"}),r.jsx("strong",{children:String(y.reason||"unknown")})]}),y.wait_key?r.jsxs("div",{children:[r.jsx("span",{children:"Wait key"}),r.jsx("strong",{className:"mono",children:Lt(String(y.wait_key),34)})]}):null,(Z=y==null?void 0:y.details)!=null&&Z.sub_run_id?r.jsxs("div",{children:[r.jsx("span",{children:"Subworkflow"}),r.jsx("strong",{className:"mono",children:Lt(String(y.details.sub_run_id),24)})]}):null,y.prompt?r.jsxs("div",{children:[r.jsx("span",{children:"Prompt"}),r.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"?r.jsx("div",{className:"overview_fact_actions",children:r.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,se=String((X==null?void 0:X.node_id)||"").trim(),ie=se&&e.node_index?e.node_index[se]:null,ue=String((ie==null?void 0:ie.label)||se||"").trim(),F=String(((C=X==null?void 0:X.effect)==null?void 0:C.type)||"").trim();return ue||F?r.jsxs("div",{className:"overview_fact_list",children:[ue?r.jsxs("div",{children:[r.jsx("span",{children:x?"Ended at":"Last step"}),r.jsx("strong",{children:ue})]}):null,F?r.jsxs("div",{children:[r.jsx("span",{children:"Effect"}),r.jsx("strong",{className:"mono",children:F})]}):null]}):r.jsx("div",{className:"empty_state_inline",children:x?"Nothing in flight — the run is finished.":"No active wait is reported for this run."})})(),p?r.jsxs("div",{className:"warn_callout",children:[p," provider call(s) have missing responses or errors."]}):null]}),r.jsxs("section",{className:"overview_panel",children:[r.jsxs("div",{className:"overview_panel_header",children:[r.jsx("h3",{children:"Summary"}),e.latest_summary?r.jsx("span",{className:"chip mono ok",children:"saved"}):r.jsx("span",{className:"chip mono muted",children:"none"})]}),e.summary_error?r.jsx("div",{className:"warn_callout",children:e.summary_error}):null,w?r.jsx(Ni,{text:w}):r.jsx("div",{className:"empty_state_inline",children:"Generate a grounded summary from the root run and its subflows."})]})]}),e.subrun_ids.length?r.jsxs("section",{className:"overview_panel",children:[r.jsxs("div",{className:"overview_panel_header",children:[r.jsx("h3",{children:"Subworkflows"}),r.jsx("span",{className:"mono muted",children:e.subrun_ids.length})]}),r.jsx("div",{className:"subrun_chip_list",children:e.subrun_ids.map(Y=>r.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?r.jsxs("section",{className:"overview_panel",children:[r.jsxs("div",{className:"overview_panel_header",children:[r.jsx("h3",{children:"Session files"}),r.jsx("span",{className:"mono muted",children:e.attachments.length?`${e.attachments.length} file${e.attachments.length===1?"":"s"}`:""}),r.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?r.jsx("div",{className:"warn_callout",children:e.attachments_error}):null,e.attachments.length?r.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 se=Y!=null&&Y.tags&&typeof Y.tags=="object"?Y.tags:{},ie=String((se==null?void 0:se.path)||"").trim()?`@${String(se.path).trim()}`:String((se==null?void 0:se.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 r.jsxs("div",{className:"produced_row",children:[r.jsx("span",{className:"produced_name mono",title:X,children:ie}),r.jsx("span",{className:"mono muted",children:ue!==null?`${ue.toLocaleString()} B`:""}),r.jsxs("span",{className:"produced_actions",children:[r.jsx("button",{className:"btn btn_sm",onClick:()=>e.on_preview_attachment(Y),disabled:F,children:"Preview"}),r.jsx("button",{className:"btn btn_sm",onClick:()=>e.on_download_attachment(Y),disabled:F,children:"Download"})]})]},X)})}):r.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?r.jsxs("section",{className:"overview_panel",children:[r.jsxs("div",{className:"overview_panel_header",children:[r.jsx("h3",{children:"Chronology"}),r.jsx("span",{className:"mono muted",children:n||e.timeline_items.length<=Vh?`${e.timeline_items.length} steps`:`last ${Vh} of ${e.timeline_items.length} steps`}),e.timeline_items.length>Vh?r.jsx("button",{className:"btn btn_sm",onClick:()=>i(Y=>!Y),children:n?"Show fewer":"Show all"}):null]}),r.jsx(aC,{items:n?e.timeline_items:e.timeline_items.slice(-Vh),node_index:e.node_index,workflow_label_by_id:e.workflow_label_by_id,on_copy:e.on_copy})]}):null]})}function aC(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=Sf(o),S=l?Dr(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?Dr(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 r.jsxs("div",{className:"human_timeline",children:[e.items.length?null:r.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 r.jsxs("article",{className:`timeline_event ${o.cls}`,children:[r.jsx("div",{className:"timeline_marker"}),r.jsxs("div",{className:"timeline_event_body",children:[r.jsxs("div",{className:"timeline_event_header",children:[r.jsxs("div",{children:[r.jsx("h3",{children:o.title}),r.jsxs("div",{className:"timeline_subtitle",children:[r.jsx("span",{children:o.subtitle}),n.run_id?r.jsx("span",{className:"mono",children:Lt(String(n.run_id),13)}):null]})]}),r.jsxs("div",{className:"timeline_time",children:[r.jsx("span",{children:da(l)}),r.jsx("span",{className:"mono",title:l,children:ha(l)})]})]}),r.jsxs("div",{className:"timeline_payload_grid",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Requested"}),r.jsx("p",{className:"mono",children:o.request||"—"})]}),r.jsxs("div",{children:[r.jsx("span",{children:"Outcome"}),r.jsx("p",{children:o.outcome||"—"})]})]}),r.jsx("div",{className:"timeline_actions",children:r.jsxs("button",{className:"btn btn_icon",onClick:()=>e.on_copy(JSON.stringify(i,null,2)),children:[r.jsx(Qe,{name:"copy",size:14}),"JSON"]})})]})]},`${String(n.run_id||i.run_id||"")}:${n.cursor}`)})]})}function lC(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=Sf(t.data),x=!!(y&&y.trim()),S=da(t.ts);return r.jsxs("div",{className:`lc ${w}`,style:{"--lc-accent":f},children:[r.jsxs("div",{className:"lc_header",children:[r.jsx("span",{className:"lc_title",children:c}),r.jsxs("div",{className:"lc_header_right",children:[_?r.jsx("span",{className:`lc_status ${w}`,children:_}):null,r.jsx("span",{className:"lc_time",title:t.ts,children:S})]})]}),r.jsxs("div",{className:"lc_meta",children:[l?r.jsx("span",{className:"lc_chip",children:l}):null,t.effect_type?r.jsx("span",{className:"lc_chip",children:String(t.effect_type)}):null,t.cursor?r.jsxs("span",{className:"lc_chip",children:["#",t.cursor]}):null,t.run_id?r.jsx("span",{className:"lc_chip",children:Lt(String(t.run_id),10)}):null,t.kind!=="step"&&n?r.jsx("span",{className:"lc_chip",children:n}):null]}),t.preview?r.jsx("div",{className:"lc_preview",children:t.preview}):null,t.data?r.jsxs("div",{className:"lc_actions",children:[x?r.jsxs(r.Fragment,{children:[r.jsx("button",{className:"lc_btn",onClick:e.on_toggle_response,children:e.response_open?"Fold Response":"Unfold Response"}),r.jsx("button",{className:"lc_btn",onClick:()=>e.on_copy(String(y||"")),children:"Copy Response"})]}):null,r.jsx("button",{className:"lc_btn",onClick:e.on_toggle,children:e.open?"Fold JSON":"Unfold JSON"}),r.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?r.jsx("div",{className:"lc_body",children:r.jsx(Ni,{text:String(y||"")})}):null,e.open&&t.data?r.jsx("div",{className:"lc_body lc_body_json mono",children:r.jsx(ds,{value:t.data,collapseAfterDepth:3,showCopy:!1})}):null]})}class cC{constructor(){Gr(this,"_buffer","");Gr(this,"_current",{data_lines:[]})}push(t,n){for(this._buffer+=t;;){const i=this._buffer.indexOf(`
102
- `);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(`
103
- `)};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=Cv;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 bx(){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 Ot(e){const t=(e||"").trim(),n={};return t&&(n.Authorization=`Bearer ${t}`),{...n,...bx()}}async function Gn(e){try{const t=await e.text();return t!=null&&t.trim()?t.trim():`${e.status}`}catch{return`${e.status}`}}class uC extends Error{constructor(n,i){super(i);Gr(this,"status");this.name="GatewayRequestError",this.status=n}}async function F_(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 uC(e.status,`${t} (HTTP ${e.status}): ${i||e.statusText||"no reason given"}`)}class z_{constructor(t){Gr(this,"_cfg");Gr(this,"fetch_gateway",(t,n)=>fetch(zt(this._cfg.base_url,t),{...n,headers:{...n==null?void 0:n.headers,...Ot(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",...Ot(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:{...Ot(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:{...Ot(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:{...Ot(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:{...Ot(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:{...Ot(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:{...Ot(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:{...Ot(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:{...Ot(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:{...Ot(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:{...Ot(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:{...Ot(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:{...Ot(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:{...Ot(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:{...Ot(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:{...Ot(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:{...Ot(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:{...Ot(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:{...Ot(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:{...Ot(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",...Ot(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",...Ot(this._cfg.auth_token)},body:JSON.stringify(o)});if(!c.ok)throw await F_(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",...Ot(this._cfg.auth_token)},body:JSON.stringify(o)});if(!c.ok)throw await F_(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",...Ot(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",...Ot(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",...Ot(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:{...Ot(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:{...Ot(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:{...Ot(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:{...Ot(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:{...Ot(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:{...Ot(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:{...Ot(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:{...Ot(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:{...Ot(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:{...Ot(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:{...Ot(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:{...Ot(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 Zj({fetch:(n,i)=>fetch(n,i),baseUrl:this._cfg.base_url,headers:()=>Ot(t)})}async submit_command(t){const n=await fetch(zt(this._cfg.base_url,bt("commands")),{method:"POST",headers:{"Content-Type":"application/json",...Ot(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",...Ot(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",...Ot(this._cfg.auth_token)},signal:l});if(!c.ok)throw await F_(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 cC;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 dC(e){const t=(e||"").trim();return t?{Authorization:`Bearer ${t}`}:{}}class fC{constructor(t){Gr(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)||Or()),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:Or(),method:"tools/call",params:{name:n,arguments:o}},u=await fetch(this._cfg.url,{method:"POST",headers:{"Content-Type":"application/json",...dC(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 Uy{constructor(t,n){Gr(this,"pending",[]);Gr(this,"scheduled",!1);Gr(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 Wy(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 hC(e,t){const n=Nn(e.updated_at||e.created_at)??0;return(Nn(t.updated_at||t.created_at)??0)-n}function mC(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=Wy(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=Wy(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"?Pu(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 Pu(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(hC),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 _C={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"},pC=[{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 gC(){const[e,t]=m.useState(!0);return r.jsxs("div",{className:"pin-legend",children:[r.jsxs("button",{className:"pin-legend-toggle mono",type:"button",onClick:()=>t(n=>!n),title:"Pin Type Legend",children:[e?"?":"×"," Pin Types"]}),e?null:r.jsxs("div",{className:"pin-legend-content",children:[pC.map(n=>r.jsxs("div",{className:"pin-legend-row",children:[r.jsx("span",{className:"pin-legend-shape",style:{color:_C[n.type]},children:n.shape}),r.jsx("span",{className:"pin-legend-label mono",children:n.label}),r.jsx("span",{className:"pin-legend-desc mono",children:n.description})]},n.type)),r.jsxs("div",{className:"pin-legend-rules mono",children:[r.jsx("strong",{children:"Connection Rules:"}),r.jsxs("ul",{children:[r.jsx("li",{children:"Execution connects to Execution only"}),r.jsx("li",{children:'"Any" type accepts all data types'}),r.jsx("li",{children:"Same types always compatible"}),r.jsx("li",{children:"Array and Object are interchangeable"}),r.jsx("li",{children:'"Tools" is compatible with Array (specialized string[])'})]})]})]})]})}function cn(e){return typeof e=="string"?e:e==null?"":String(e)}function qy(e,t){const n=cn(e).trim();return n.length<=t?n:`${n.slice(0,Math.max(0,t-1))}…`}function jx(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 Sx(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 kx(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 yC(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(Sx(i)==="on_flow_start"){const o=cn(i==null?void 0:i.id).trim();if(o)return o}return""}function B_(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 wC(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=B_(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(!jx(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(Sx(y)!=="subflow")continue;const x=kx(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 $=yC(S);if(!$)continue;const L=(Array.isArray(S.nodes)?S.nodes:[]).find(se=>cn(se==null?void 0:se.id).trim()===$)||null;if(!L)continue;const D=B_(y),M=B_(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 vC(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 xC(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 Hy(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 bC(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=wC({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"?kx(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(!jx(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=xC({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:!vC(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,Oe=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)),Oe=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:Oe-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 r.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(),se=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 se[B.id]=="number"?Number(se[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(Hy({x:me,y:we,w:K,h:J},p))},P=(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=>Hy({x:(G||me).x-oe,y:(G||me).y-fe,w:(G||me).w,h:(G||me).h},p))},O=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 r.jsxs("div",{className:"graph_wrap",children:[r.jsxs("div",{className:"graph_corner",children:[r.jsxs("div",{className:"graph_corner_buttons",children:[r.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:"⤢"}),r.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:"+"}),r.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:"−"})]}),r.jsx(gC,{})]}),r.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;P(T,Q,z.start_view)}else if(z.mode==="pinch"&&G.length>=2){const T=G[0],Q=G[1],K=T.x-Q.x,J=T.y-Q.y,oe=Math.max(1,Math.hypot(K,J)),fe=z.start_dist/oe;N(z.anchor_svg,fe,z.start_view)}},onPointerUp:B=>{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:[r.jsxs("defs",{children:[r.jsx("marker",{id:"arrow",viewBox:"0 0 10 10",refX:"9",refY:"5",markerWidth:"8",markerHeight:"8",orient:"auto-start-reverse",children:r.jsx("path",{d:"M 0 0 L 10 5 L 0 10 z",fill:"rgba(148,163,184,0.55)"})}),r.jsxs("filter",{id:"glow",children:[r.jsx("feGaussianBlur",{stdDeviation:"3",result:"coloredBlur"}),r.jsxs("feMerge",{children:[r.jsx("feMergeNode",{in:"coloredBlur"}),r.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&&O.has(`${B.target}->${B.source}`),Be=Math.max(1,Math.hypot(oe,fe)),We=-fe/Be,_t=oe/Be,Oe=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*Oe: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 r.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=qy(oe,22),we=qy(fe,22);return r.jsxs("g",{className:K,transform:`translate(${B.x}, ${B.y})`,children:[r.jsx("rect",{className:"graph_node_bg",width:p.node_w,height:p.node_h,rx:12,ry:12}),r.jsx("rect",{className:"graph_node_bar",width:p.node_w,height:6,rx:12,ry:12,fill:J}),r.jsx("text",{className:"graph_node_label",x:12,y:28,children:me}),r.jsx("text",{className:"graph_node_type",x:12,y:46,children:we}),B.type==="on_schedule"?r.jsx("text",{className:"graph_node_icon",x:p.node_w-18,y:18,children:"⏰"}):null]},B.id)})]})]})}function Yr(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=Yr(e[n]))!==""&&(t+=(t&&" ")+i);else for(let n in e)e[n]&&(t+=(t&&" ")+n);return t}var U_={exports:{}},W_={},q_={exports:{}},H_={};/**
104
- * @license React
105
- * use-sync-external-store-shim.production.js
106
- *
107
- * Copyright (c) Meta Platforms, Inc. and affiliates.
108
- *
109
- * This source code is licensed under the MIT license found in the
110
- * LICENSE file in the root directory of this source tree.
111
- */var Vy;function jC(){if(Vy)return H_;Vy=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 H_.useSyncExternalStore=e.useSyncExternalStore!==void 0?e.useSyncExternalStore:p,H_}var Gy;function SC(){return Gy||(Gy=1,q_.exports=jC()),q_.exports}/**
112
- * @license React
113
- * use-sync-external-store-shim/with-selector.production.js
114
- *
115
- * Copyright (c) Meta Platforms, Inc. and affiliates.
116
- *
117
- * This source code is licensed under the MIT license found in the
118
- * LICENSE file in the root directory of this source tree.
119
- */var Ky;function kC(){if(Ky)return W_;Ky=1;var e=bf(),t=SC();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 W_.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($),$},W_}var Yy;function NC(){return Yy||(Yy=1,U_.exports=kC()),U_.exports}var CC=NC();const $C=Qp(CC),AC={},Jy=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:()=>{(AC?"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},EC=e=>e?Jy(e):Jy,{useDebugValue:TC}=ve,{useSyncExternalStoreWithSelector:MC}=$C,RC=e=>e;function Nx(e,t=RC,n){const i=MC(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return TC(i),i}const Xy=(e,t)=>{const n=EC(e),i=(o,l=t)=>Nx(n,o,l);return Object.assign(i,n),i},LC=(e,t)=>e?Xy(e,t):Xy;function Fr(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 IC={value:()=>{}};function Um(){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 cm(n)}function cm(e){this._=e}function PC(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}})}cm.prototype=Um.prototype={constructor:cm,on:function(e,t){var n=this._,i=PC(e+"",n),o,l=-1,u=i.length;if(arguments.length<2){for(;++l<u;)if((o=(e=i[l]).type)&&(o=OC(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]=Zy(n[o],e.name,t);else if(t==null)for(o in n)n[o]=Zy(n[o],e.name,null);return this},copy:function(){var e={},t=this._;for(var n in t)e[n]=t[n].slice();return new cm(e)},call:function(e,t){if((o=arguments.length-2)>0)for(var n=new Array(o),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 OC(e,t){for(var n=0,i=e.length,o;n<i;++n)if((o=e[n]).name===t)return o.value}function Zy(e,t,n){for(var i=0,o=e.length;i<o;++i)if(e[i].name===t){e[i]=IC,e=e.slice(0,i).concat(e.slice(i+1));break}return n!=null&&e.push({name:t,value:n}),e}var Tp="http://www.w3.org/1999/xhtml";const Qy={svg:"http://www.w3.org/2000/svg",xhtml:Tp,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function Wm(e){var t=e+="",n=t.indexOf(":");return n>=0&&(t=e.slice(0,n))!=="xmlns"&&(e=e.slice(n+1)),Qy.hasOwnProperty(t)?{space:Qy[t],local:e}:e}function DC(e){return function(){var t=this.ownerDocument,n=this.namespaceURI;return n===Tp&&t.documentElement.namespaceURI===Tp?t.createElement(e):t.createElementNS(n,e)}}function FC(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function Cx(e){var t=Wm(e);return(t.local?FC:DC)(t)}function zC(){}function pg(e){return e==null?zC:function(){return this.querySelector(e)}}function BC(e){typeof e!="function"&&(e=pg(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 UC(e){return e==null?[]:Array.isArray(e)?e:Array.from(e)}function WC(){return[]}function $x(e){return e==null?WC:function(){return this.querySelectorAll(e)}}function qC(e){return function(){return UC(e.apply(this,arguments))}}function HC(e){typeof e=="function"?e=qC(e):e=$x(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 Ax(e){return function(){return this.matches(e)}}function Ex(e){return function(t){return t.matches(e)}}var VC=Array.prototype.find;function GC(e){return function(){return VC.call(this.children,e)}}function KC(){return this.firstElementChild}function YC(e){return this.select(e==null?KC:GC(typeof e=="function"?e:Ex(e)))}var JC=Array.prototype.filter;function XC(){return Array.from(this.children)}function ZC(e){return function(){return JC.call(this.children,e)}}function QC(e){return this.selectAll(e==null?XC:ZC(typeof e=="function"?e:Ex(e)))}function e2(e){typeof e!="function"&&(e=Ax(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 Tx(e){return new Array(e.length)}function t2(){return new ii(this._enter||this._groups.map(Tx),this._parents)}function km(e,t){this.ownerDocument=e.ownerDocument,this.namespaceURI=e.namespaceURI,this._next=null,this._parent=e,this.__data__=t}km.prototype={constructor:km,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 n2(e){return function(){return e}}function r2(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 km(e,l[u]);for(;u<f;++u)(c=t[u])&&(o[u]=c)}function s2(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 km(e,l[c]);for(c=0;c<p;++c)(f=t[c])&&_.get(y[c])===f&&(o[c]=f)}function i2(e){return e.__data__}function o2(e,t){if(!arguments.length)return Array.from(this,i2);var n=t?s2:r2,i=this._parents,o=this._groups;typeof e!="function"&&(e=n2(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=a2(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 a2(e){return typeof e=="object"&&"length"in e?e:Array.from(e)}function l2(){return new ii(this._exit||this._groups.map(Tx),this._parents)}function c2(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 u2(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 d2(){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 f2(e){e||(e=h2);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 h2(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}function m2(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this}function _2(){return Array.from(this)}function p2(){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 g2(){let e=0;for(const t of this)++e;return e}function y2(){return!this.node()}function w2(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 v2(e){return function(){this.removeAttribute(e)}}function x2(e){return function(){this.removeAttributeNS(e.space,e.local)}}function b2(e,t){return function(){this.setAttribute(e,t)}}function j2(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function S2(e,t){return function(){var n=t.apply(this,arguments);n==null?this.removeAttribute(e):this.setAttribute(e,n)}}function k2(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 N2(e,t){var n=Wm(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?x2:v2:typeof t=="function"?n.local?k2:S2:n.local?j2:b2)(n,t))}function Mx(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function C2(e){return function(){this.style.removeProperty(e)}}function $2(e,t,n){return function(){this.style.setProperty(e,t,n)}}function A2(e,t,n){return function(){var i=t.apply(this,arguments);i==null?this.style.removeProperty(e):this.style.setProperty(e,i,n)}}function E2(e,t,n){return arguments.length>1?this.each((t==null?C2:typeof t=="function"?A2:$2)(e,t,n??"")):Du(this.node(),e)}function Du(e,t){return e.style.getPropertyValue(t)||Mx(e).getComputedStyle(e,null).getPropertyValue(t)}function T2(e){return function(){delete this[e]}}function M2(e,t){return function(){this[e]=t}}function R2(e,t){return function(){var n=t.apply(this,arguments);n==null?delete this[e]:this[e]=n}}function L2(e,t){return arguments.length>1?this.each((t==null?T2:typeof t=="function"?R2:M2)(e,t)):this.node()[e]}function Rx(e){return e.trim().split(/^|\s+/)}function gg(e){return e.classList||new Lx(e)}function Lx(e){this._node=e,this._names=Rx(e.getAttribute("class")||"")}Lx.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 Ix(e,t){for(var n=gg(e),i=-1,o=t.length;++i<o;)n.add(t[i])}function Px(e,t){for(var n=gg(e),i=-1,o=t.length;++i<o;)n.remove(t[i])}function I2(e){return function(){Ix(this,e)}}function P2(e){return function(){Px(this,e)}}function O2(e,t){return function(){(t.apply(this,arguments)?Ix:Px)(this,e)}}function D2(e,t){var n=Rx(e+"");if(arguments.length<2){for(var i=gg(this.node()),o=-1,l=n.length;++o<l;)if(!i.contains(n[o]))return!1;return!0}return this.each((typeof t=="function"?O2:t?I2:P2)(n,t))}function F2(){this.textContent=""}function z2(e){return function(){this.textContent=e}}function B2(e){return function(){var t=e.apply(this,arguments);this.textContent=t??""}}function U2(e){return arguments.length?this.each(e==null?F2:(typeof e=="function"?B2:z2)(e)):this.node().textContent}function W2(){this.innerHTML=""}function q2(e){return function(){this.innerHTML=e}}function H2(e){return function(){var t=e.apply(this,arguments);this.innerHTML=t??""}}function V2(e){return arguments.length?this.each(e==null?W2:(typeof e=="function"?H2:q2)(e)):this.node().innerHTML}function G2(){this.nextSibling&&this.parentNode.appendChild(this)}function K2(){return this.each(G2)}function Y2(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function J2(){return this.each(Y2)}function X2(e){var t=typeof e=="function"?e:Cx(e);return this.select(function(){return this.appendChild(t.apply(this,arguments))})}function Z2(){return null}function Q2(e,t){var n=typeof e=="function"?e:Cx(e),i=t==null?Z2:typeof t=="function"?t:pg(t);return this.select(function(){return this.insertBefore(n.apply(this,arguments),i.apply(this,arguments)||null)})}function e$(){var e=this.parentNode;e&&e.removeChild(this)}function t$(){return this.each(e$)}function n$(){var e=this.cloneNode(!1),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function r$(){var e=this.cloneNode(!0),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function s$(e){return this.select(e?r$:n$)}function i$(e){return arguments.length?this.property("__data__",e):this.node().__data__}function o$(e){return function(t){e.call(this,t,this.__data__)}}function a$(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 l$(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 c$(e,t,n){return function(){var i=this.__on,o,l=o$(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 u$(e,t,n){var i=a$(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?c$:l$,o=0;o<l;++o)this.each(c(i[o],t,n));return this}function Ox(e,t,n){var i=Mx(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 d$(e,t){return function(){return Ox(this,e,t)}}function f$(e,t){return function(){return Ox(this,e,t.apply(this,arguments))}}function h$(e,t){return this.each((typeof t=="function"?f$:d$)(e,t))}function*m$(){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 Dx=[null];function ii(e,t){this._groups=e,this._parents=t}function kf(){return new ii([[document.documentElement]],Dx)}function _$(){return this}ii.prototype=kf.prototype={constructor:ii,select:BC,selectAll:HC,selectChild:YC,selectChildren:QC,filter:e2,data:o2,enter:t2,exit:l2,join:c2,merge:u2,selection:_$,order:d2,sort:f2,call:m2,nodes:_2,node:p2,size:g2,empty:y2,each:w2,attr:N2,style:E2,property:L2,classed:D2,text:U2,html:V2,raise:K2,lower:J2,append:X2,insert:Q2,remove:t$,clone:s$,datum:i$,on:u$,dispatch:h$,[Symbol.iterator]:m$};function Si(e){return typeof e=="string"?new ii([[document.querySelector(e)]],[document.documentElement]):new ii([[e]],Dx)}function p$(e){let t;for(;t=e.sourceEvent;)e=t;return e}function Xi(e,t){if(e=p$(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 g$={passive:!1},df={capture:!0,passive:!1};function V_(e){e.stopImmediatePropagation()}function Mu(e){e.preventDefault(),e.stopImmediatePropagation()}function Fx(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 zx(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 Gh=e=>()=>e;function Mp(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}})}Mp.prototype.on=function(){var e=this._.on.apply(this._,arguments);return e===this._?this:e};function y$(e){return!e.ctrlKey&&!e.button}function w$(){return this.parentNode}function v$(e,t){return t??{x:e.x,y:e.y}}function x$(){return navigator.maxTouchPoints||"ontouchstart"in this}function b$(){var e=y$,t=w$,n=v$,i=x$,o={},l=Um("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,g$).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),Fx(M.view),V_(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),zx(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,se,ie;for(se=0;se<X;++se)(ie=D(this,Y,M,H,Z[se].identifier,Z[se]))&&(V_(M),ie("start",M,Z[se]))}}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])&&(V_(M),X("end",M,H[Y]))}function D(M,H,Z,Y,X,se){var ie=l.copy(),ue=Xi(se||Z,H),F,C,N;if((N=n.call(M,new Mp("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 P(O,ne,B){var z=ue,G;switch(O){case"start":o[X]=P,G=u++;break;case"end":delete o[X],--u;case"drag":ue=Xi(B||ne,H),G=u;break}ie.call(O,M,new Mp(O,{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:Gh(!!M),y):e},y.container=function(M){return arguments.length?(t=typeof M=="function"?M:Gh(M),y):t},y.subject=function(M){return arguments.length?(n=typeof M=="function"?M:Gh(M),y):n},y.touchable=function(M){return arguments.length?(i=typeof M=="function"?M:Gh(!!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 yg(e,t,n){e.prototype=t.prototype=n,n.constructor=e}function Bx(e,t){var n=Object.create(e.prototype);for(var i in t)n[i]=t[i];return n}function Nf(){}var ff=.7,Nm=1/ff,Ru="\\s*([+-]?\\d+)\\s*",hf="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",To="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",j$=/^#([0-9a-f]{3,8})$/,S$=new RegExp(`^rgb\\(${Ru},${Ru},${Ru}\\)$`),k$=new RegExp(`^rgb\\(${To},${To},${To}\\)$`),N$=new RegExp(`^rgba\\(${Ru},${Ru},${Ru},${hf}\\)$`),C$=new RegExp(`^rgba\\(${To},${To},${To},${hf}\\)$`),$$=new RegExp(`^hsl\\(${hf},${To},${To}\\)$`),A$=new RegExp(`^hsla\\(${hf},${To},${To},${hf}\\)$`),ew={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};yg(Nf,mf,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:tw,formatHex:tw,formatHex8:E$,formatHsl:T$,formatRgb:nw,toString:nw});function tw(){return this.rgb().formatHex()}function E$(){return this.rgb().formatHex8()}function T$(){return Ux(this).formatHsl()}function nw(){return this.rgb().formatRgb()}function mf(e){var t,n;return e=(e+"").trim().toLowerCase(),(t=j$.exec(e))?(n=t[1].length,t=parseInt(t[1],16),n===6?rw(t):n===3?new Gs(t>>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):n===8?Kh(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?Kh(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=S$.exec(e))?new Gs(t[1],t[2],t[3],1):(t=k$.exec(e))?new Gs(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=N$.exec(e))?Kh(t[1],t[2],t[3],t[4]):(t=C$.exec(e))?Kh(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=$$.exec(e))?ow(t[1],t[2]/100,t[3]/100,1):(t=A$.exec(e))?ow(t[1],t[2]/100,t[3]/100,t[4]):ew.hasOwnProperty(e)?rw(ew[e]):e==="transparent"?new Gs(NaN,NaN,NaN,0):null}function rw(e){return new Gs(e>>16&255,e>>8&255,e&255,1)}function Kh(e,t,n,i){return i<=0&&(e=t=n=NaN),new Gs(e,t,n,i)}function M$(e){return e instanceof Nf||(e=mf(e)),e?(e=e.rgb(),new Gs(e.r,e.g,e.b,e.opacity)):new Gs}function Rp(e,t,n,i){return arguments.length===1?M$(e):new Gs(e,t,n,i??1)}function Gs(e,t,n,i){this.r=+e,this.g=+t,this.b=+n,this.opacity=+i}yg(Gs,Rp,Bx(Nf,{brighter(e){return e=e==null?Nm:Math.pow(Nm,e),new Gs(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=e==null?ff:Math.pow(ff,e),new Gs(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new Gs(cc(this.r),cc(this.g),cc(this.b),Cm(this.opacity))},displayable(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:sw,formatHex:sw,formatHex8:R$,formatRgb:iw,toString:iw}));function sw(){return`#${sc(this.r)}${sc(this.g)}${sc(this.b)}`}function R$(){return`#${sc(this.r)}${sc(this.g)}${sc(this.b)}${sc((isNaN(this.opacity)?1:this.opacity)*255)}`}function iw(){const e=Cm(this.opacity);return`${e===1?"rgb(":"rgba("}${cc(this.r)}, ${cc(this.g)}, ${cc(this.b)}${e===1?")":`, ${e})`}`}function Cm(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 sc(e){return e=cc(e),(e<16?"0":"")+e.toString(16)}function ow(e,t,n,i){return i<=0?e=t=n=NaN:n<=0||n>=1?e=t=NaN:t<=0&&(e=NaN),new Zi(e,t,n,i)}function Ux(e){if(e instanceof Zi)return new Zi(e.h,e.s,e.l,e.opacity);if(e instanceof Nf||(e=mf(e)),!e)return new Zi;if(e instanceof Zi)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 Zi(u,c,f,e.opacity)}function L$(e,t,n,i){return arguments.length===1?Ux(e):new Zi(e,t,n,i??1)}function Zi(e,t,n,i){this.h=+e,this.s=+t,this.l=+n,this.opacity=+i}yg(Zi,L$,Bx(Nf,{brighter(e){return e=e==null?Nm:Math.pow(Nm,e),new Zi(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?ff:Math.pow(ff,e),new Zi(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 Gs(G_(e>=240?e-240:e+120,o,i),G_(e,o,i),G_(e<120?e+240:e-120,o,i),this.opacity)},clamp(){return new Zi(aw(this.h),Yh(this.s),Yh(this.l),Cm(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=Cm(this.opacity);return`${e===1?"hsl(":"hsla("}${aw(this.h)}, ${Yh(this.s)*100}%, ${Yh(this.l)*100}%${e===1?")":`, ${e})`}`}}));function aw(e){return e=(e||0)%360,e<0?e+360:e}function Yh(e){return Math.max(0,Math.min(1,e||0))}function G_(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 Wx=e=>()=>e;function I$(e,t){return function(n){return e+n*t}}function P$(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 O$(e){return(e=+e)==1?qx:function(t,n){return n-t?P$(t,n,e):Wx(isNaN(t)?n:t)}}function qx(e,t){var n=t-e;return n?I$(e,n):Wx(isNaN(e)?t:e)}const lw=(function e(t){var n=O$(t);function i(o,l){var u=n((o=Rp(o)).r,(l=Rp(l)).r),c=n(o.g,l.g),f=n(o.b,l.b),_=qx(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 il(e,t){return e=+e,t=+t,function(n){return e*(1-n)+t*n}}var Lp=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,K_=new RegExp(Lp.source,"g");function D$(e){return function(){return e}}function F$(e){return function(t){return e(t)+""}}function z$(e,t){var n=Lp.lastIndex=K_.lastIndex=0,i,o,l,u=-1,c=[],f=[];for(e=e+"",t=t+"";(i=Lp.exec(e))&&(o=K_.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:il(i,o)})),n=K_.lastIndex;return n<t.length&&(l=t.slice(n),c[u]?c[u]+=l:c[++u]=l),c.length<2?f[0]?F$(f[0].x):D$(t):(t=f.length,function(_){for(var p=0,w;p<t;++p)c[(w=f[p]).i]=w.x(_);return c.join("")})}var cw=180/Math.PI,Ip={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function Hx(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)*cw,skewX:Math.atan(f)*cw,scaleX:u,scaleY:c}}var Jh;function B$(e){const t=new(typeof DOMMatrix=="function"?DOMMatrix:WebKitCSSMatrix)(e+"");return t.isIdentity?Ip:Hx(t.a,t.b,t.c,t.d,t.e,t.f)}function U$(e){return e==null||(Jh||(Jh=document.createElementNS("http://www.w3.org/2000/svg","g")),Jh.setAttribute("transform",e),!(e=Jh.transform.baseVal.consolidate()))?Ip:(e=e.matrix,Hx(e.a,e.b,e.c,e.d,e.e,e.f))}function Vx(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:il(_,w)},{i:b-2,x:il(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:il(_,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:il(_,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:il(_,w)},{i:b-2,x:il(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 W$=Vx(B$,"px, ","px)","deg)"),q$=Vx(U$,", ",")",")"),H$=1e-12;function uw(e){return((e=Math.exp(e))+1/e)/2}function V$(e){return((e=Math.exp(e))-1/e)/2}function G$(e){return((e=Math.exp(2*e))-1)/(e+1)}const K$=(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<H$)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,se=uw(H),ie=_/(n*L)*(se*G$(t*X+H)-V$(H));return[c+ie*x,f+ie*S,_*se/uw(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,sf=0,Gd=0,Gx=1e3,$m,of,Am=0,hc=0,qm=0,_f=typeof performance=="object"&&performance.now?performance:Date,Kx=typeof window=="object"&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(e){setTimeout(e,17)};function wg(){return hc||(Kx(Y$),hc=_f.now()+qm)}function Y$(){hc=0}function Em(){this._call=this._time=this._next=null}Em.prototype=Yx.prototype={constructor:Em,restart:function(e,t,n){if(typeof e!="function")throw new TypeError("callback is not a function");n=(n==null?wg():+n)+(t==null?0:+t),!this._next&&of!==this&&(of?of._next=this:$m=this,of=this),this._call=e,this._time=n,Pp()},stop:function(){this._call&&(this._call=null,this._time=1/0,Pp())}};function Yx(e,t,n){var i=new Em;return i.restart(e,t,n),i}function J$(){wg(),++Fu;for(var e=$m,t;e;)(t=hc-e._time)>=0&&e._call.call(void 0,t),e=e._next;--Fu}function dw(){hc=(Am=_f.now())+qm,Fu=sf=0;try{J$()}finally{Fu=0,Z$(),hc=0}}function X$(){var e=_f.now(),t=e-Am;t>Gx&&(qm-=t,Am=e)}function Z$(){for(var e,t=$m,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:$m=n);of=e,Pp(i)}function Pp(e){if(!Fu){sf&&(sf=clearTimeout(sf));var t=e-hc;t>24?(e<1/0&&(sf=setTimeout(dw,e-_f.now()-qm)),Gd&&(Gd=clearInterval(Gd))):(Gd||(Am=_f.now(),Gd=setInterval(X$,Gx)),Fu=1,Kx(dw))}}function fw(e,t,n){var i=new Em;return t=t==null?0:+t,i.restart(o=>{i.stop(),e(o+t)},t,n),i}var Q$=Um("start","end","cancel","interrupt"),eA=[],Jx=0,hw=1,Op=2,um=3,mw=4,Dp=5,dm=6;function Hm(e,t,n,i,o,l){var u=e.__transition;if(!u)e.__transition={};else if(n in u)return;tA(e,n,{name:t,index:i,group:o,on:Q$,tween:eA,time:l.time,delay:l.delay,duration:l.duration,ease:l.ease,timer:null,state:Jx})}function vg(e,t){var n=to(e,t);if(n.state>Jx)throw new Error("too late; already scheduled");return n}function Mo(e,t){var n=to(e,t);if(n.state>um)throw new Error("too late; already running");return n}function to(e,t){var n=e.__transition;if(!n||!(n=n[t]))throw new Error("transition not found");return n}function tA(e,t,n){var i=e.__transition,o;i[t]=n,n.timer=Yx(l,0,n.time);function l(_){n.state=hw,n.timer.restart(u,n.delay,n.time),n.delay<=_&&u(_-n.delay)}function u(_){var p,w,y,x;if(n.state!==hw)return f();for(p in i)if(x=i[p],x.name===n.name){if(x.state===um)return fw(u);x.state===mw?(x.state=dm,x.timer.stop(),x.on.call("interrupt",e,e.__data__,x.index,x.group),delete i[p]):+p<t&&(x.state=dm,x.timer.stop(),x.on.call("cancel",e,e.__data__,x.index,x.group),delete i[p])}if(fw(function(){n.state===um&&(n.state=mw,n.timer.restart(c,n.delay,n.time),c(_))}),n.state=Op,n.on.call("start",e,e.__data__,n.index,n.group),n.state===Op){for(n.state=um,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=Dp,1),w=-1,y=o.length;++w<y;)o[w].call(e,p);n.state===Dp&&(n.on.call("end",e,e.__data__,n.index,n.group),f())}function f(){n.state=dm,n.timer.stop(),delete i[t];for(var _ in i)return;delete e.__transition}}function fm(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>Op&&i.state<Dp,i.state=dm,i.timer.stop(),i.on.call(o?"interrupt":"cancel",e,e.__data__,i.index,i.group),delete n[u]}l&&delete e.__transition}}function nA(e){return this.each(function(){fm(this,e)})}function rA(e,t){var n,i;return function(){var o=Mo(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 sA(e,t,n){var i,o;if(typeof n!="function")throw new Error;return function(){var l=Mo(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 iA(e,t){var n=this._id;if(e+="",arguments.length<2){for(var i=to(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?rA:sA)(n,e,t))}function xg(e,t,n){var i=e._id;return e.each(function(){var o=Mo(this,i);(o.value||(o.value={}))[t]=n.apply(this,arguments)}),function(o){return to(o,i).value[t]}}function Xx(e,t){var n;return(typeof t=="number"?il:t instanceof mf?lw:(n=mf(t))?(t=n,lw):z$)(e,t)}function oA(e){return function(){this.removeAttribute(e)}}function aA(e){return function(){this.removeAttributeNS(e.space,e.local)}}function lA(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 cA(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 uA(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 dA(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 fA(e,t){var n=Wm(e),i=n==="transform"?q$:Xx;return this.attrTween(e,typeof t=="function"?(n.local?dA:uA)(n,i,xg(this,"attr."+e,t)):t==null?(n.local?aA:oA)(n):(n.local?cA:lA)(n,i,t))}function hA(e,t){return function(n){this.setAttribute(e,t.call(this,n))}}function mA(e,t){return function(n){this.setAttributeNS(e.space,e.local,t.call(this,n))}}function _A(e,t){var n,i;function o(){var l=t.apply(this,arguments);return l!==i&&(n=(i=l)&&mA(e,l)),n}return o._value=t,o}function pA(e,t){var n,i;function o(){var l=t.apply(this,arguments);return l!==i&&(n=(i=l)&&hA(e,l)),n}return o._value=t,o}function gA(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=Wm(e);return this.tween(n,(i.local?_A:pA)(i,t))}function yA(e,t){return function(){vg(this,e).delay=+t.apply(this,arguments)}}function wA(e,t){return t=+t,function(){vg(this,e).delay=t}}function vA(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?yA:wA)(t,e)):to(this.node(),t).delay}function xA(e,t){return function(){Mo(this,e).duration=+t.apply(this,arguments)}}function bA(e,t){return t=+t,function(){Mo(this,e).duration=t}}function jA(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?xA:bA)(t,e)):to(this.node(),t).duration}function SA(e,t){if(typeof t!="function")throw new Error;return function(){Mo(this,e).ease=t}}function kA(e){var t=this._id;return arguments.length?this.each(SA(t,e)):to(this.node(),t).ease}function NA(e,t){return function(){var n=t.apply(this,arguments);if(typeof n!="function")throw new Error;Mo(this,e).ease=n}}function CA(e){if(typeof e!="function")throw new Error;return this.each(NA(this._id,e))}function $A(e){typeof e!="function"&&(e=Ax(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 ma(i,this._parents,this._name,this._id)}function AA(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 ma(u,this._parents,this._name,this._id)}function EA(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 TA(e,t,n){var i,o,l=EA(t)?vg:Mo;return function(){var u=l(this,e),c=u.on;c!==i&&(o=(i=c).copy()).on(t,n),u.on=o}}function MA(e,t){var n=this._id;return arguments.length<2?to(this.node(),n).on.on(e):this.each(TA(n,e,t))}function RA(e){return function(){var t=this.parentNode;for(var n in this.__transition)if(+n!==e)return;t&&t.removeChild(this)}}function LA(){return this.on("end.remove",RA(this._id))}function IA(e){var t=this._name,n=this._id;typeof e!="function"&&(e=pg(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,Hm(_[y],t,n,y,_,to(p,n)));return new ma(l,this._parents,t,n)}function PA(e){var t=this._name,n=this._id;typeof e!="function"&&(e=$x(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=to(p,n),b=0,$=y.length;b<$;++b)(x=y[b])&&Hm(x,t,n,b,y,S);l.push(y),u.push(p)}return new ma(l,u,t,n)}var OA=kf.prototype.constructor;function DA(){return new OA(this._groups,this._parents)}function FA(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 Zx(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 BA(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 UA(e,t){var n,i,o,l="style."+t,u="end."+l,c;return function(){var f=Mo(this,e),_=f.on,p=f.value[l]==null?c||(c=Zx(t)):void 0;(_!==n||o!==p)&&(i=(n=_).copy()).on(u,o=p),f.on=i}}function WA(e,t,n){var i=(e+="")=="transform"?W$:Xx;return t==null?this.styleTween(e,FA(e,i)).on("end.style."+e,Zx(e)):typeof t=="function"?this.styleTween(e,BA(e,i,xg(this,"style."+e,t))).each(UA(this._id,e)):this.styleTween(e,zA(e,i,t),n).on("end.style."+e,null)}function qA(e,t,n){return function(i){this.style.setProperty(e,t.call(this,i),n)}}function HA(e,t,n){var i,o;function l(){var u=t.apply(this,arguments);return u!==o&&(i=(o=u)&&qA(e,u,n)),i}return l._value=t,l}function VA(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,HA(e,t,n??""))}function GA(e){return function(){this.textContent=e}}function KA(e){return function(){var t=e(this);this.textContent=t??""}}function YA(e){return this.tween("text",typeof e=="function"?KA(xg(this,"text",e)):GA(e==null?"":e+""))}function JA(e){return function(t){this.textContent=e.call(this,t)}}function XA(e){var t,n;function i(){var o=e.apply(this,arguments);return o!==n&&(t=(n=o)&&JA(o)),t}return i._value=e,i}function ZA(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,XA(e))}function QA(){for(var e=this._name,t=this._id,n=Qx(),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=to(f,t);Hm(f,e,n,_,u,{time:p.time+p.delay+p.duration,delay:0,duration:p.duration,ease:p.ease})}return new ma(i,this._parents,e,n)}function eE(){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 _=Mo(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 tE=0;function ma(e,t,n,i){this._groups=e,this._parents=t,this._name=n,this._id=i}function Qx(){return++tE}var ca=kf.prototype;ma.prototype={constructor:ma,select:IA,selectAll:PA,selectChild:ca.selectChild,selectChildren:ca.selectChildren,filter:$A,merge:AA,selection:DA,transition:QA,call:ca.call,nodes:ca.nodes,node:ca.node,size:ca.size,empty:ca.empty,each:ca.each,on:MA,attr:fA,attrTween:gA,style:WA,styleTween:VA,text:YA,textTween:ZA,remove:LA,tween:iA,delay:vA,duration:jA,ease:kA,easeVarying:CA,end:eE,[Symbol.iterator]:ca[Symbol.iterator]};function nE(e){return((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2}var rE={time:null,delay:0,duration:250,ease:nE};function sE(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 iE(e){var t,n;e instanceof ma?(t=e._id,e=e._name):(t=Qx(),(n=rE).time=wg(),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[_])&&Hm(f,e,t,_,u,n||sE(f,t));return new ma(i,this._parents,e,t)}kf.prototype.interrupt=nA;kf.prototype.transition=iE;const Xh=e=>()=>e;function oE(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 ua(e,t,n){this.k=e,this.x=t,this.y=n}ua.prototype={constructor:ua,scale:function(e){return e===1?this:new ua(this.k*e,this.x,this.y)},translate:function(e,t){return e===0&t===0?this:new ua(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 fa=new ua(1,0,0);ua.prototype;function Y_(e){e.stopImmediatePropagation()}function Kd(e){e.preventDefault(),e.stopImmediatePropagation()}function aE(e){return(!e.ctrlKey||e.type==="wheel")&&!e.button}function lE(){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 _w(){return this.__zoom||fa}function cE(e){return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*(e.ctrlKey?10:1)}function uE(){return navigator.maxTouchPoints||"ontouchstart"in this}function dE(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 eb(){var e=aE,t=lE,n=dE,i=cE,o=uE,l=[0,1/0],u=[[-1/0,-1/0],[1/0,1/0]],c=250,f=K$,_=Um("start","zoom","end"),p,w,y,x=500,S=150,b=0,$=10;function E(N){N.property("__zoom",_w).on("wheel.zoom",X,{passive:!1}).on("mousedown.zoom",se).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,P,O,ne){var B=N.selection?N.selection():N;B.property("__zoom",_w),N!==B?H(N,P,O,ne):B.interrupt().each(function(){Z(this,arguments).event(ne).start().zoom(null,typeof P=="function"?P.apply(this,arguments):P).end()})},E.scaleBy=function(N,P,O,ne){E.scaleTo(N,function(){var B=this.__zoom.k,z=typeof P=="function"?P.apply(this,arguments):P;return B*z},O,ne)},E.scaleTo=function(N,P,O,ne){E.transform(N,function(){var B=t.apply(this,arguments),z=this.__zoom,G=O==null?M(B):typeof O=="function"?O.apply(this,arguments):O,T=z.invert(G),Q=typeof P=="function"?P.apply(this,arguments):P;return n(D(L(z,Q),G,T),B,u)},O,ne)},E.translateBy=function(N,P,O,ne){E.transform(N,function(){return n(this.__zoom.translate(typeof P=="function"?P.apply(this,arguments):P,typeof O=="function"?O.apply(this,arguments):O),t.apply(this,arguments),u)},null,ne)},E.translateTo=function(N,P,O,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(fa.translate(T[0],T[1]).scale(G.k).translate(typeof P=="function"?-P.apply(this,arguments):-P,typeof O=="function"?-O.apply(this,arguments):-O),z,u)},ne,B)};function L(N,P){return P=Math.max(l[0],Math.min(l[1],P)),P===N.k?N:new ua(P,N.x,N.y)}function D(N,P,O){var ne=P[0]-O[0]*N.k,B=P[1]-O[1]*N.k;return ne===N.x&&B===N.y?N:new ua(N.k,ne,B)}function M(N){return[(+N[0][0]+ +N[1][0])/2,(+N[0][1]+ +N[1][1])/2]}function H(N,P,O,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=O==null?M(T):typeof O=="function"?O.apply(B,z):O,K=Math.max(T[1][0]-T[0][0],T[1][1]-T[0][1]),J=B.__zoom,oe=typeof P=="function"?P.apply(B,z):P,fe=f(J.invert(Q).concat(K/J.k),oe.invert(Q).concat(K/oe.k));return function(me){if(me===1)me=oe;else{var we=fe(me),Ae=K/we[2];me=new ua(Ae,Q[0]-we[0]*Ae,Q[1]-we[1]*Ae)}G.zoom(null,me)}})}function Z(N,P,O){return!O&&N.__zooming||new Y(N,P)}function Y(N,P){this.that=N,this.args=P,this.active=0,this.sourceEvent=null,this.extent=t.apply(N,P),this.taps=0}Y.prototype={event:function(N){return N&&(this.sourceEvent=N),this},start:function(){return++this.active===1&&(this.that.__zooming=this,this.emit("start")),this},zoom:function(N,P){return this.mouse&&N!=="mouse"&&(this.mouse[1]=P.invert(this.mouse[0])),this.touch0&&N!=="touch"&&(this.touch0[1]=P.invert(this.touch0[0])),this.touch1&&N!=="touch"&&(this.touch1[1]=P.invert(this.touch1[0])),this.that.__zoom=P,this.emit("zoom"),this},end:function(){return--this.active===0&&(delete this.that.__zooming,this.emit("end")),this},emit:function(N){var P=Si(this.that).datum();_.call(N,this.that,new oE(N,{sourceEvent:this.sourceEvent,target:E,transform:this.that.__zoom,dispatch:_}),P)}};function X(N,...P){if(!e.apply(this,arguments))return;var O=Z(this,P).event(N),ne=this.__zoom,B=Math.max(l[0],Math.min(l[1],ne.k*Math.pow(2,i.apply(this,arguments)))),z=Xi(N);if(O.wheel)(O.mouse[0][0]!==z[0]||O.mouse[0][1]!==z[1])&&(O.mouse[1]=ne.invert(O.mouse[0]=z)),clearTimeout(O.wheel);else{if(ne.k===B)return;O.mouse=[z,ne.invert(z)],fm(this),O.start()}Kd(N),O.wheel=setTimeout(G,S),O.zoom("mouse",n(D(L(ne,B),O.mouse[0],O.mouse[1]),O.extent,u));function G(){O.wheel=null,O.end()}}function se(N,...P){if(y||!e.apply(this,arguments))return;var O=N.currentTarget,ne=Z(this,P,!0).event(N),B=Si(N.view).on("mousemove.zoom",Q,!0).on("mouseup.zoom",K,!0),z=Xi(N,O),G=N.clientX,T=N.clientY;Fx(N.view),Y_(N),ne.mouse=[z,this.__zoom.invert(z)],fm(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,O),ne.mouse[1]),ne.extent,u))}function K(J){B.on("mousemove.zoom mouseup.zoom",null),zx(J.view,ne.moved),Kd(J),ne.event(J).end()}}function ie(N,...P){if(e.apply(this,arguments)){var O=this.__zoom,ne=Xi(N.changedTouches?N.changedTouches[0]:N,this),B=O.invert(ne),z=O.k*(N.shiftKey?.5:2),G=n(D(L(O,z),ne,B),t.apply(this,P),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,...P){if(e.apply(this,arguments)){var O=N.touches,ne=O.length,B=Z(this,P,N.changedTouches.length===ne).event(N),z,G,T,Q;for(Y_(N),G=0;G<ne;++G)T=O[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)),fm(this),B.start())}}function F(N,...P){if(this.__zooming){var O=Z(this,P).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),O.touch0&&O.touch0[2]===G.identifier?O.touch0[0]=T:O.touch1&&O.touch1[2]===G.identifier&&(O.touch1[0]=T);if(G=O.that.__zoom,O.touch1){var K=O.touch0[0],J=O.touch0[1],oe=O.touch1[0],fe=O.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(O.touch0)T=O.touch0[0],Q=O.touch0[1];else return;O.zoom("touch",n(D(G,T,Q),O.extent,u))}}function C(N,...P){if(this.__zooming){var O=Z(this,P).event(N),ne=N.changedTouches,B=ne.length,z,G;for(Y_(N),y&&clearTimeout(y),y=setTimeout(function(){y=null},x),z=0;z<B;++z)G=ne[z],O.touch0&&O.touch0[2]===G.identifier?delete O.touch0:O.touch1&&O.touch1[2]===G.identifier&&delete O.touch1;if(O.touch1&&!O.touch0&&(O.touch0=O.touch1,delete O.touch1),O.touch0)O.touch0[1]=this.__zoom.invert(O.touch0[0]);else if(O.end(),O.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:Xh(+N),E):i},E.filter=function(N){return arguments.length?(e=typeof N=="function"?N:Xh(!!N),E):e},E.touchable=function(N){return arguments.length?(o=typeof N=="function"?N:Xh(!!N),E):o},E.extent=function(N){return arguments.length?(t=typeof N=="function"?N:Xh([[+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 Vm=m.createContext(null),fE=Vm.Provider,_a={error001:()=>"[React Flow]: Seems like you have not used zustand provider as an ancestor. Help: https://reactflow.dev/error#001",error002:()=>"It looks like you've created a new nodeTypes or edgeTypes object. If this wasn't on purpose please define the nodeTypes/edgeTypes outside of the component or memoize them.",error003:e=>`Node type "${e}" not found. Using fallback type "default".`,error004:()=>"The React Flow parent container needs a width and a height to render the graph.",error005:()=>"Only child nodes can use a parent extent.",error006:()=>"Can't create edge. An edge needs a source and a target.",error007:e=>`The old edge with id=${e} does not exist.`,error009:e=>`Marker type "${e}" doesn't exist.`,error008:(e,t)=>`Couldn't create edge for ${e?"target":"source"} handle id: "${e?t.targetHandle:t.sourceHandle}", edge id: ${t.id}.`,error010:()=>"Handle: No node id found. Make sure to only use a Handle inside a custom Node.",error011:e=>`Edge type "${e}" not found. Using fallback type "default".`,error012:e=>`Node with id "${e}" does not exist, it may have been removed. This can happen when a node is deleted before the "onNodeClick" handler is called.`},tb=_a.error001();function Rn(e,t){const n=m.useContext(Vm);if(n===null)throw new Error(tb);return Nx(n,e,t)}const Nr=()=>{const e=m.useContext(Vm);if(e===null)throw new Error(tb);return m.useMemo(()=>({getState:e.getState,setState:e.setState,subscribe:e.subscribe,destroy:e.destroy}),[e])},hE=e=>e.userSelectionActive?"none":"all";function pf({position:e,children:t,className:n,style:i,...o}){const l=Rn(hE),u=`${e}`.split("-");return ve.createElement("div",{className:Yr(["react-flow__panel",n,...u]),style:{...i,pointerEvents:l},...o},t)}function mE({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 _E=({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=Yr(["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 pE=m.memo(_E);const bg=e=>({width:e.offsetWidth,height:e.offsetHeight}),zu=(e,t=0,n=1)=>Math.min(Math.max(e,t),n),jg=(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])}),pw=(e,t,n)=>e<t?zu(Math.abs(e-t),1,50)/50:e>n?-zu(Math.abs(e-n),1,50)/50:0,nb=(e,t)=>{const n=pw(e.x,35,t.width-35)*20,i=pw(e.y,35,t.height-35)*20;return[n,i]},rb=e=>{var t;return((t=e.getRootNode)==null?void 0:t.call(e))||(window==null?void 0:window.document)},sb=(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}),ib=({x:e,y:t,x2:n,y2:i})=>({x:e,y:t,width:n-e,height:i-t}),gw=e=>({...e.positionAbsolute||{x:0,y:0},width:e.width||0,height:e.height||0}),gE=(e,t)=>ib(sb(gf(e),gf(t))),Fp=(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)},yE=e=>ki(e.width)&&ki(e.height)&&ki(e.x)&&ki(e.y),ki=e=>!isNaN(e)&&isFinite(e),pr=Symbol.for("internals"),ob=["Enter"," ","Escape"],wE=(e,t)=>{},vE=e=>"nativeEvent"in e;function zp(e){var o,l;const t=vE(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 ab=e=>"clientX"in e,cl=(e,t)=>{var l,u;const n=ab(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)}},Tm=()=>{var e;return typeof navigator<"u"&&((e=navigator==null?void 0:navigator.userAgent)==null?void 0:e.indexOf("Mac"))>=0},Cf=({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(pE,{x:n,y:i,label:o,labelStyle:l,labelShowBg:u,labelBgStyle:c,labelBgPadding:f,labelBgBorderRadius:_}):null);Cf.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 lb({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 cb({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 ll;(function(e){e.Bezier="default",e.Straight="straight",e.Step="step",e.SmoothStep="smoothstep",e.SimpleBezier="simplebezier"})(ll||(ll={}));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 yw({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 ub({sourceX:e,sourceY:t,sourcePosition:n=mt.Bottom,targetX:i,targetY:o,targetPosition:l=mt.Top}){const[u,c]=yw({pos:n,x1:e,y1:t,x2:i,y2:o}),[f,_]=yw({pos:l,x1:i,y1:o,x2:e,y2:t}),[p,w,y,x]=cb({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 Sg=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]=ub({sourceX:e,sourceY:t,sourcePosition:o,targetX:n,targetY:i,targetPosition:l});return ve.createElement(Cf,{path:$,labelX:E,labelY:L,label:u,labelStyle:c,labelShowBg:f,labelBgStyle:_,labelBgPadding:p,labelBgBorderRadius:w,style:y,markerEnd:x,markerStart:S,interactionWidth:b})});Sg.displayName="SimpleBezierEdge";const ww={[mt.Left]:{x:-1,y:0},[mt.Right]:{x:1,y:0},[mt.Top]:{x:0,y:-1},[mt.Bottom]:{x:0,y:1}},xE=({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},vw=(e,t)=>Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2));function bE({source:e,sourcePosition:t=mt.Bottom,target:n,targetPosition:i=mt.Top,center:o,offset:l}){const u=ww[t],c=ww[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=xE({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]=lb({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],P=f[C]>_[C],O=f[C]<_[C];(u[w]===1&&(!N&&P||N&&O)||u[w]!==1&&(!N&&O||N&&P))&&(x=w==="x"?Y:X)}const se={x:f.x+$.x,y:f.y+$.y},ie={x:_.x+E.x,y:_.y+E.y},ue=Math.max(Math.abs(se.x-x[0].x),Math.abs(ie.x-x[0].x)),F=Math.max(Math.abs(se.y-x[0].y),Math.abs(ie.y-x[0].y));ue>=F?(S=(se.x+ie.x)/2,b=x[0].y):(S=x[0].x,b=(se.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 jE(e,t,n,i){const o=Math.min(vw(e,t)/2,vw(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 Bp({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]=bE({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=jE(p[L-1],E,p[L+1],u):D=`${L===0?"M":"L"}${E.x} ${E.y}`,$+=D,$},""),w,y,x,S]}const Gm=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]=Bp({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(Cf,{path:E,labelX:L,labelY:D,label:o,labelStyle:l,labelShowBg:u,labelBgStyle:c,labelBgPadding:f,labelBgBorderRadius:_,style:p,markerEnd:x,markerStart:S,interactionWidth:$})});Gm.displayName="SmoothStepEdge";const kg=m.memo(e=>{var t;return ve.createElement(Gm,{...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])})});kg.displayName="StepEdge";function SE({sourceX:e,sourceY:t,targetX:n,targetY:i}){const[o,l,u,c]=lb({sourceX:e,sourceY:t,targetX:n,targetY:i});return[`M ${e},${t}L ${n},${i}`,o,l,u,c]}const Ng=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,$]=SE({sourceX:e,sourceY:t,targetX:n,targetY:i});return ve.createElement(Cf,{path:S,labelX:b,labelY:$,label:o,labelStyle:l,labelShowBg:u,labelBgStyle:c,labelBgPadding:f,labelBgBorderRadius:_,style:p,markerEnd:w,markerStart:y,interactionWidth:x})});Ng.displayName="StraightEdge";function Zh(e,t){return e>=0?.5*e:t*25*Math.sqrt(-e)}function xw({pos:e,x1:t,y1:n,x2:i,y2:o,c:l}){switch(e){case mt.Left:return[t-Zh(t-i,l),n];case mt.Right:return[t+Zh(i-t,l),n];case mt.Top:return[t,n-Zh(n-o,l)];case mt.Bottom:return[t,n+Zh(o-n,l)]}}function db({sourceX:e,sourceY:t,sourcePosition:n=mt.Bottom,targetX:i,targetY:o,targetPosition:l=mt.Top,curvature:u=.25}){const[c,f]=xw({pos:n,x1:e,y1:t,x2:i,y2:o,c:u}),[_,p]=xw({pos:l,x1:i,y1:o,x2:e,y2:t,c:u}),[w,y,x,S]=cb({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 Mm=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]=db({sourceX:e,sourceY:t,sourcePosition:o,targetX:n,targetY:i,targetPosition:l,curvature:b==null?void 0:b.curvature});return ve.createElement(Cf,{path:E,labelX:L,labelY:D,label:u,labelStyle:c,labelShowBg:f,labelBgStyle:_,labelBgPadding:p,labelBgBorderRadius:w,style:y,markerEnd:x,markerStart:S,interactionWidth:$})});Mm.displayName="BezierEdge";const Cg=m.createContext(null),kE=Cg.Provider;Cg.Consumer;const NE=()=>m.useContext(Cg),CE=e=>"id"in e&&"source"in e&&"target"in e,$E=({source:e,sourceHandle:t,target:n,targetHandle:i})=>`reactflow__edge-${e}${t||""}-${n}${i||""}`,Up=(e,t)=>typeof e>"u"?"":typeof e=="string"?e:`${t?`${t}__`:""}${Object.keys(e).sort().map(i=>`${i}=${e[i]}`).join("&")}`,AE=(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)),EE=(e,t)=>{if(!e.source||!e.target)return t;let n;return CE(e)?n={...e}:n={...e,id:$E(e)},AE(n,t)?t:t.concat(n)},Wp=({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},fb=({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}},Km=(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 sb(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 ib(n)},hb=(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=Fp(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)}),_},mb=(e,t)=>{const n=e.map(i=>i.id);return t.filter(i=>n.includes(i.source)||n.includes(i.target))},_b=(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 bw(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 TE(e,t,n,i,o,l){const{x:u,y:c}=cl(e),_=t.elementsFromPoint(u,c).find(S=>S.classList.contains("react-flow__handle"));if(_){const S=_.getAttribute("data-nodeid");if(S){const b=$g(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:pb()};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 ME={source:null,target:null,sourceHandle:null,targetHandle:null},pb=()=>({handleDomNode:null,isValid:!1,connection:ME,endHandle:null});function gb(e,t,n,i,o,l,u){const c=o==="target",f=u.querySelector(`.react-flow__handle[data-id="${e==null?void 0:e.nodeId}-${e==null?void 0:e.id}-${e==null?void 0:e.type}"]`),_={...pb(),handleDomNode:f};if(f){const p=$g(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 RE({nodes:e,nodeId:t,handleId:n,handleType:i}){return e.reduce((o,l)=>{if(l[pr]){const{handleBounds:u}=l[pr];let c=[],f=[];u&&(c=bw(l,u,"source",`${t}-${n}-${i}`),f=bw(l,u,"target",`${t}-${n}-${i}`)),o.push(...c,...f)}return o},[])}function $g(e,t){return e||(t!=null&&t.classList.contains("target")?"target":t!=null&&t.classList.contains("source")?"source":null)}function J_(e){e==null||e.classList.remove("valid","connecting","react-flow__handle-valid","react-flow__handle-connecting")}function LE(e,t){let n=null;return t?n="valid":e&&!t&&(n="invalid"),n}function yb({event:e,handleId:t,nodeId:n,onConnect:i,isTarget:o,getState:l,setState:u,isValidConnection:c,edgeUpdaterType:f,onEdgeUpdateEnd:_}){const p=rb(e.target),{connectionMode:w,domNode:y,autoPanOnConnect:x,connectionRadius:S,onConnectStart:b,panBy:$,getNodes:E,cancelConnection:L}=l();let D=0,M;const{x:H,y:Z}=cl(e),Y=p==null?void 0:p.elementFromPoint(H,Z),X=$g(f,Y),se=y==null?void 0:y.getBoundingClientRect();if(!se||!X)return;let ie,ue=cl(e,se),F=!1,C=null,N=!1,P=null;const O=RE({nodes:E(),nodeId:n,handleId:t,handleType:X}),ne=()=>{if(!x)return;const[G,T]=nb(ue,se);$({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=cl(G,se);const{handle:Q,validHandleResult:K}=TE(G,p,Wp(ue,T,!1,[1,1]),S,O,J=>gb(J,w,n,t,o?"target":"source",c,p));if(M=Q,F||(ne(),F=!0),P=K.handleDomNode,C=K.connection,N=K.isValid,u({connectionPosition:M&&N?fb({x:M.x,y:M.y},T):ue,connectionStatus:LE(!!M,N),connectionEndHandle:K.endHandle}),!M&&!N&&!P)return J_(ie);C.source!==C.target&&P&&(J_(ie),ie=P,P.classList.add("connecting","react-flow__handle-connecting"),P.classList.toggle("valid",N),P.classList.toggle("react-flow__handle-valid",N))}function z(G){var T,Q;(M||P)&&C&&N&&(i==null||i(C)),(Q=(T=l()).onConnectEnd)==null||Q.call(T,G),f&&(_==null||_(G)),J_(ie),L(),cancelAnimationFrame(D),F=!1,N=!1,C=null,P=null,p.removeEventListener("mousemove",B),p.removeEventListener("mouseup",z),p.removeEventListener("touchmove",B),p.removeEventListener("touchend",z)}p.addEventListener("mousemove",B),p.addEventListener("mouseup",z),p.addEventListener("touchmove",B),p.addEventListener("touchend",z)}const jw=()=>!0,IE=e=>({connectionStartHandle:e.connectionStartHandle,connectOnClick:e.connectOnClick,noPanClassName:e.noPanClassName}),PE=(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}},wb=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 se,ie;const S=u||null,b=e==="target",$=Nr(),E=NE(),{connectOnClick:L,noPanClassName:D}=Rn(IE,Fr),{connecting:M,clickConnecting:H}=Rn(PE(E,S,e),Fr);E||(ie=(se=$.getState()).onError)==null||ie.call(se,"010",_a.error010());const Z=ue=>{const{defaultEdgeOptions:F,onConnect:C,hasDefaultEdges:N}=$.getState(),P={...F,...ue};if(N){const{edges:O,setEdges:ne}=$.getState();ne(EE(P,O))}C==null||C(P),c==null||c(P)},Y=ue=>{if(!E)return;const F=ab(ue);o&&(F&&ue.button===0||!F)&&yb({event:ue,handleId:S,nodeId:E,onConnect:Z,isTarget:b,getState:$.getState,setState:$.setState,isValidConnection:n||$.getState().isValidConnection||jw}),F?p==null||p(ue):w==null||w(ue)},X=ue=>{const{onClickConnectStart:F,onClickConnectEnd:C,connectionClickStartHandle:N,connectionMode:P,isValidConnection:O}=$.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=rb(ue.target),B=n||O||jw,{connection:z,isValid:G}=gb({nodeId:E,id:S,type:e},P,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:Yr(["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)});wb.displayName="Handle";var Rm=m.memo(wb);const vb=({data:e,isConnectable:t,targetPosition:n=mt.Top,sourcePosition:i=mt.Bottom})=>ve.createElement(ve.Fragment,null,ve.createElement(Rm,{type:"target",position:n,isConnectable:t}),e==null?void 0:e.label,ve.createElement(Rm,{type:"source",position:i,isConnectable:t}));vb.displayName="DefaultNode";var qp=m.memo(vb);const xb=({data:e,isConnectable:t,sourcePosition:n=mt.Bottom})=>ve.createElement(ve.Fragment,null,e==null?void 0:e.label,ve.createElement(Rm,{type:"source",position:n,isConnectable:t}));xb.displayName="InputNode";var bb=m.memo(xb);const jb=({data:e,isConnectable:t,targetPosition:n=mt.Top})=>ve.createElement(ve.Fragment,null,ve.createElement(Rm,{type:"target",position:n,isConnectable:t}),e==null?void 0:e.label);jb.displayName="OutputNode";var Sb=m.memo(jb);const Ag=()=>null;Ag.displayName="GroupNode";const OE=e=>({selectedNodes:e.getNodes().filter(t=>t.selected),selectedEdges:e.edges.filter(t=>t.selected)}),Qh=e=>e.id;function DE(e,t){return Fr(e.selectedNodes.map(Qh),t.selectedNodes.map(Qh))&&Fr(e.selectedEdges.map(Qh),t.selectedEdges.map(Qh))}const kb=m.memo(({onSelectionChange:e})=>{const t=Nr(),{selectedNodes:n,selectedEdges:i}=Rn(OE,DE);return m.useEffect(()=>{const o={nodes:n,edges:i};e==null||e(o),t.getState().onSelectionChange.forEach(l=>l(o))},[n,i,e]),null});kb.displayName="SelectionListener";const FE=e=>!!e.onSelectionChange;function zE({onSelectionChange:e}){const t=Rn(FE);return e||t?ve.createElement(kb,{onSelectionChange:e}):null}const BE=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 UE=({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:se,defaultEdgeOptions:ie,fitView:ue,fitViewOptions:F,onNodesDelete:C,onEdgesDelete:N,onNodeDrag:P,onNodeDragStart:O,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:Oe,setMaxZoom:et,setTranslateExtent:lt,setNodeExtent:Ye,reset:Se}=Rn(BE,Fr),Le=Nr();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",se,Le.setState),Kt("fitViewOnInit",ue,Le.setState),Kt("fitViewOnInitOptions",F,Le.setState),Kt("onNodesDelete",C,Le.setState),Kt("onEdgesDelete",N,Le.setState),Kt("onNodeDrag",P,Le.setState),Kt("onNodeDragStart",O,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,Oe),vu($,et),vu(X,lt),vu(E,Ye),null},Sw={display:"none"},WE={position:"absolute",width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0px, 0px, 0px, 0px)",clipPath:"inset(100%)"},Nb="react-flow__node-desc",Cb="react-flow__edge-desc",qE="react-flow__aria-live",HE=e=>e.ariaLiveMessage;function VE({rfId:e}){const t=Rn(HE);return ve.createElement("div",{id:`${qE}-${e}`,"aria-live":"assertive","aria-atomic":"true",style:WE},t)}function GE({rfId:e,disableKeyboardA11y:t}){return ve.createElement(ve.Fragment,null,ve.createElement("div",{id:`${Nb}-${e}`,style:Sw},"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:`${Cb}-${e}`,style:Sw},"Press enter or space to select an edge. You can then press delete to remove it or escape to cancel."),!t&&ve.createElement(VE,{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)&&zp(x))return!1;const b=Nw(x.code,c);l.current.add(x[b]),kw(u,l.current,!1)&&(x.preventDefault(),i(!0))},w=x=>{if((!o.current||o.current&&!t.actInsideInputWithModifier)&&zp(x))return!1;const b=Nw(x.code,c);kw(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 kw(e,t,n){return e.filter(i=>n||i.length===t.size).some(i=>i.every(o=>t.has(o)))}function Nw(e,t){return t.includes(e)?"code":"key"}function $b(e,t,n,i){var u,c;if(!e.parentNode)return n;const o=t.get(e.parentNode),l=uc(o,i);return $b(o,t,{x:(n.x??0)+l.x,y:(n.y??0)+l.y,z:(((u=o[pr])==null?void 0:u.z)??0)>(n.z??0)?((c=o[pr])==null?void 0:c.z)??0:n.z??0},i)}function Ab(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}=$b(i,e,{...i.position,z:((o=i[pr])==null?void 0:o.z)??0},t);i.positionAbsolute={x:l,y:u},i[pr].z=c,n!=null&&n[i.id]&&(i[pr].isParent=!0)}})}function X_(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,pr,{enumerable:!1,value:{handleBounds:w||(y=_==null?void 0:_[pr])==null?void 0:y.handleBounds,z:f}}),o.set(c.id,p)}),Ab(o,n,l),o}function Eb(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 $=Km(S,w),{x:E,y:L,zoom:D}=_b($,i,o,t.minZoom??l,t.maxZoom??u,t.padding??.1),M=fa.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 KE(e,t){return e.forEach(n=>{const i=t.get(n.id);i&&t.set(i.id,{...i,[pr]:i[pr],selected:n.selected})}),new Map(t)}function YE(e,t){return t.map(n=>{const i=e.find(o=>o.id===n.id);return i&&(n.selected=i.selected),n})}function em({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:KE(e,o)}),u==null||u(e)),t!=null&&t.length&&(_&&i({edges:YE(t,l)}),c==null||c(t))}const xu=()=>{},JE={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},XE=e=>({d3Zoom:e.d3Zoom,d3Selection:e.d3Selection}),ZE=()=>{const e=Nr(),{d3Zoom:t,d3Selection:n}=Rn(XE,Fr);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,_=fa.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=>Eb(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=fa.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}=_b(o,u,c,f,_,(l==null?void 0:l.padding)??.1),x=fa.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"),Wp(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 Wp(w,l,u,c)},flowToScreenPosition:o=>{const{transform:l,domNode:u}=e.getState();if(!u)return o;const{x:c,y:f}=u.getBoundingClientRect(),_=fb(o,l);return{x:_.x+c,y:_.y+f}},viewportInitialized:!0}:JE,[t,n])};function Eg(){const e=ZE(),t=Nr(),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:se}=t.getState(),ie=(b||[]).map(P=>P.id),ue=($||[]).map(P=>P.id),F=L().reduce((P,O)=>{const ne=!ie.includes(O.id)&&O.parentNode&&P.find(z=>z.id===O.parentNode);return(typeof O.deletable=="boolean"?O.deletable:!0)&&(ie.includes(O.id)||ne)&&P.push(O),P},[]),C=D.filter(P=>typeof P.deletable=="boolean"?P.deletable:!0),N=C.filter(P=>ue.includes(P.id));if(F||N){const P=mb(F,C),O=[...N,...P],ne=O.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(O),se&&se(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 $=yE(b),E=$?null:t.getState().nodeInternals.get(b.id);return!$&&!E?[null,null,$]:[$?b:gw(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=gw(H),Y=Fp(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=Fp(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 QE={actInsideInputWithModifier:!1};var eT=({deleteKeyCode:e,multiSelectionKeyCode:t})=>{const n=Nr(),{deleteElements:i}=Eg(),o=vf(e,QE),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 tT(e){const t=Nr();m.useEffect(()=>{let n;const i=()=>{var l,u;if(!e.current)return;const o=bg(e.current);(o.height===0||o.width===0)&&((u=(l=t.getState()).onError)==null||u.call(l,"004",_a.error004())),t.setState({width:o.width||500,height:o.height||500})};return i(),window.addEventListener("resize",i),e.current&&(n=new ResizeObserver(()=>i()),n.observe(e.current)),()=>{window.removeEventListener("resize",i),n&&e.current&&n.unobserve(e.current)}},[])}const Tg={position:"absolute",width:"100%",height:"100%",top:0,left:0},nT=(e,t)=>e.x!==t.x||e.y!==t.y||e.zoom!==t.k,tm=e=>({x:e.x,y:e.y,zoom:e.k}),bu=(e,t)=>e.target.closest(`.${t}`),Cw=(e,t)=>t===2&&Array.isArray(e)&&e.includes(2),$w=e=>{const t=e.ctrlKey&&Tm()?10:1;return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*t},rT=e=>({d3Zoom:e.d3Zoom,d3Selection:e.d3Selection,d3ZoomHandler:e.d3ZoomHandler,userSelectionActive:e.userSelectionActive}),sT=({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=Nr(),Y=m.useRef(!1),X=m.useRef(!1),se=m.useRef(null),ie=m.useRef({x:0,y:0,zoom:0}),{d3Zoom:ue,d3Selection:F,d3ZoomHandler:C,userSelectionActive:N}=Rn(rT,Fr),P=vf($),O=m.useRef(0),ne=m.useRef(!1),B=m.useRef();return tT(se),m.useEffect(()=>{if(se.current){const z=se.current.getBoundingClientRect(),G=eb().scaleExtent([S,b]).translateExtent(x),T=Si(se.current).call(G),Q=fa.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($w),Z.setState({d3Zoom:G,d3Selection:T,d3ZoomHandler:T.on("wheel.zoom"),transform:[J.x,J.y,J.k],domNode:se.current.closest(".react-flow")})}},[]),m.useEffect(()=>{F&&ue&&(u&&!P&&!N?F.on("wheel.zoom",z=>{if(bu(z,D))return!1;z.preventDefault(),z.stopImmediatePropagation();const G=F.property("__zoom").k||1,T=Tm();if(z.ctrlKey&&l&&T){const Ae=Xi(z),Be=$w(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=tm(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,P,l,E,D,t,e,n]),m.useEffect(()=>{ue&&ue.on("start",z=>{var Q,K;if(!z.sourceEvent||z.sourceEvent.internal)return null;O.current=(Q=z.sourceEvent)==null?void 0:Q.button;const{onViewportChangeStart:G}=Z.getState(),T=tm(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&&Cw(w,O.current??0)),(e||G)&&!((T=z.sourceEvent)!=null&&T.internal)){const Q=tm(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&&Cw(w,O.current??0)&&!X.current&&i(z.sourceEvent),X.current=!1,(n||G)&&nT(ie.current,z.transform)){const T=tm(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=P||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"&&!P)||!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,P]),ve.createElement("div",{className:"react-flow__renderer",ref:se,style:Tg},L)},iT=e=>({userSelectionActive:e.userSelectionActive,userSelectionRect:e.userSelectionRect});function oT(){const{userSelectionActive:e,userSelectionRect:t}=Rn(iT,Fr);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 Aw(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 aT(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&&Aw(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&&Aw(i,u);break}case"remove":return i}return i.push(u),i},n)}function lT(e,t){return aT(e,t)}const ol=(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(ol(i.id,!0))):i.selected&&!o&&(i.selected=!1,n.push(ol(i.id,!1))),n},[])}const Z_=(e,t)=>n=>{n.target===t.current&&(e==null||e(n))},cT=e=>({userSelectionActive:e.userSelectionActive,elementsSelectable:e.elementsSelectable,dragging:e.paneDragging}),Tb=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=Nr(),S=m.useRef(0),b=m.useRef(0),$=m.useRef(),{userSelectionActive:E,elementsSelectable:L,dragging:D}=Rn(cT,Fr),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:P}=x.getState();if($.current=P==null?void 0:P.getBoundingClientRect(),!L||!e||C.button!==0||C.target!==y.current||!$.current)return;const{x:O,y:ne}=cl(C,$.current);N(),x.setState({userSelectionRect:{width:0,height:0,startX:O,startY:ne,x:O,y:ne}}),i==null||i(C)},se=C=>{const{userSelectionRect:N,nodeInternals:P,edges:O,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=cl(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=hb(P,oe,ne,t===yf.Partial,!0,G),we=mb(me,O).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(O,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:Yr(["react-flow__pane",{dragging:D,selection:e}]),onClick:F?void 0:Z_(H,y),onContextMenu:Z_(Z,y),onWheel:Z_(Y,y),onMouseEnter:F?void 0:f,onMouseDown:F?X:void 0,onMouseMove:F?se:_,onMouseUp:F?ie:void 0,onMouseLeave:F?ue:p,ref:y,style:Tg},w,ve.createElement(oT,null))});Tb.displayName="Pane";function Mb(e,t){if(!e.parentNode)return!1;const n=t.get(e.parentNode);return n?n.selected?!0:Mb(n,t):!1}function Ew(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 uT(e,t,n,i){return Array.from(e.values()).filter(o=>(o.selected||o.id===i)&&(!o.parentNode||!Mb(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 dT(e,t){return!t||t==="parent"?t:[t[0],[t[1][0]-(e.width||0),t[1][1]-(e.height||0)]]}function Rb(e,t,n,i,o=[0,0],l){const u=dT(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",_a.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"?jg(t,c):t;return{position:{x:_.x-f.x,y:_.y-f.y},positionAbsolute:_}}function Q_({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 Tw=(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,...bg(f)}})};function Jd(e,t,n){return n===void 0?n:i=>{const o=t().nodeInternals.get(e);o&&n(i,{...o})}}function Hp({id:e,store:t,unselect:n=!1,nodeRef:i}){const{addSelectedNodes:o,unselectNodesAndEdges:l,multiSelectionActive:u,nodeInternals:c,onError:f}=t.getState(),_=c.get(e);if(!_){f==null||f("012",_a.error012(e));return}t.setState({nodesSelectionActive:!1}),_.selected?(n||_.selected&&u)&&(l({nodes:[_],edges:[]}),requestAnimationFrame(()=>{var p;return(p=i==null?void 0:i.current)==null?void 0:p.blur()})):o([e])}function fT(){const e=Nr();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 ep(e){return(t,n,i)=>e==null?void 0:e(t,i)}function Lb({nodeRef:e,disabled:t=!1,noDragClassName:n,handleSelector:i,nodeId:o,isSelectable:l,selectNodesOnDrag:u}){const c=Nr(),[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=fT();return m.useEffect(()=>{if(e!=null&&e.current){const D=Si(e.current),M=({x:Y,y:X})=>{const{nodeInternals:se,onNodeDrag:ie,onSelectionDrag:ue,updateNodePositions:F,nodeExtent:C,snapGrid:N,snapToGrid:P,nodeOrigin:O,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=Km(p.current,O);z=gf(T)}if(p.current=p.current.map(T=>{const Q={x:Y-T.distance.x,y:X-T.distance.y};P&&(Q.x=N[0]*Math.round(Q.x/N[0]),Q.y=N[1]*Math.round(Q.y/N[1]));const K=[[C[0][0],C[0][1]],[C[1][0],C[1][1]]];p.current.length>1&&C&&!T.extent&&(K[0][0]=T.positionAbsolute.x-z.x+C[0][0],K[1][0]=T.positionAbsolute.x+(T.width??0)-z.x2+C[1][0],K[0][1]=T.positionAbsolute.y-z.y+C[0][1],K[1][1]=T.positionAbsolute.y+(T.height??0)-z.y2+C[1][1]);const J=Rb(T,Q,se,K,O,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:ep(ue);if(G&&b.current){const[T,Q]=Q_({nodeId:o,dragItems:p.current,nodeInternals:se});G(b.current,T,Q)}},H=()=>{if(!x.current)return;const[Y,X]=nb(S.current,x.current);if(Y!==0||X!==0){const{transform:se,panBy:ie}=c.getState();w.current.x=(w.current.x??0)-Y/se[2],w.current.y=(w.current.y??0)-X/se[2],ie({x:Y,y:X})&&M(w.current)}y.current=requestAnimationFrame(H)},Z=Y=>{var O;const{nodeInternals:X,multiSelectionActive:se,nodesDraggable:ie,unselectNodesAndEdges:ue,onNodeDragStart:F,onSelectionDragStart:C}=c.getState();E.current=!0;const N=o?F:ep(C);(!u||!l)&&!se&&o&&((O=X.get(o))!=null&&O.selected||ue()),o&&l&&u&&Hp({id:o,store:c,nodeRef:e});const P=L(Y);if(w.current=P,p.current=uT(X,ie,P,o),N&&p.current){const[ne,B]=Q_({nodeId:o,dragItems:p.current,nodeInternals:X});N(Y.sourceEvent,ne,B)}};if(t)D.on(".drag",null);else{const Y=b$().on("start",X=>{const{domNode:se,nodeDragThreshold:ie}=c.getState();ie===0&&Z(X);const ue=L(X);w.current=ue,x.current=(se==null?void 0:se.getBoundingClientRect())||null,S.current=cl(X.sourceEvent,x.current)}).on("drag",X=>{var F,C;const se=L(X),{autoPanOnNodeDrag:ie,nodeDragThreshold:ue}=c.getState();if(!$.current&&E.current&&ie&&($.current=!0,H()),!E.current){const N=se.xSnapped-(((F=w==null?void 0:w.current)==null?void 0:F.x)??0),P=se.ySnapped-(((C=w==null?void 0:w.current)==null?void 0:C.y)??0);Math.sqrt(N*N+P*P)>ue&&Z(X)}(w.current.x!==se.xSnapped||w.current.y!==se.ySnapped)&&p.current&&E.current&&(b.current=X.sourceEvent,S.current=cl(X.sourceEvent,x.current),M(se))}).on("end",X=>{if(E.current&&(_(!1),$.current=!1,E.current=!1,cancelAnimationFrame(y.current),p.current)){const{updateNodePositions:se,nodeInternals:ie,onNodeDragStop:ue,onSelectionDragStop:F}=c.getState(),C=o?ue:ep(F);if(se(p.current,!1,!1),C){const[N,P]=Q_({nodeId:o,dragItems:p.current,nodeInternals:ie});C(X.sourceEvent,N,P)}}}).filter(X=>{const se=X.target;return!X.button&&(!n||!Ew(se,`.${n}`,e))&&(!i||Ew(se,i,e))});return D.call(Y),()=>{D.on(".drag",null)}}}},[e,t,n,i,l,c,o,u,L]),f}function Ib(){const e=Nr();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}=Rb(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:se,resizeObserver:ie,dragHandle:ue,zIndex:F,isParent:C,noDragClassName:N,noPanClassName:P,initialized:O,disableKeyboardA11y:ne,ariaLabel:B,rfId:z,hasHandleBounds:G})=>{const T=Nr(),Q=m.useRef(null),K=m.useRef(Y),J=m.useRef(X),oe=m.useRef(i),fe=D||L||p||w||y||x,me=Ib(),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),Oe=Ye=>{const{nodeDragThreshold:Se}=T.getState();if(D&&(!Z||!L||Se>0)&&Hp({id:n,store:T,nodeRef:Q}),p){const Le=T.getState().nodeInternals.get(n);Le&&p(Ye,{...Le})}},et=Ye=>{if(!zp(Ye))if(ob.includes(Ye.key)&&D){const Se=Ye.key==="Escape";Hp({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&&!se){const Ye=Q.current;(!O||!G)&&(ie==null||ie.unobserve(Ye),ie==null||ie.observe(Ye))}},[se,O,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=Lb({nodeRef:Q,disabled:se||!L,noDragClassName:N,handleSelector:ue,nodeId:n,isSelectable:D,selectNodesOnDrag:Z});return se?null:ve.createElement("div",{className:Yr(["react-flow__node",`react-flow__node-${i}`,{[P]: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:O?"visible":"hidden",...$},"data-id":n,"data-testid":`rf__node-${n}`,onMouseEnter:we,onMouseMove:Ae,onMouseLeave:Be,onContextMenu:We,onClick:Oe,onDoubleClick:_t,onKeyDown:H?et:void 0,tabIndex:H?0:void 0,role:H?"button":void 0,"aria-describedby":ne?void 0:`${Nb}-${z}`,"aria-label":B},ve.createElement(kE,{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 hT=e=>{const t=e.getNodes().filter(n=>n.selected);return{...Km(t,e.nodeOrigin),transformString:`translate(${e.transform[0]}px,${e.transform[1]}px) scale(${e.transform[2]})`,userSelectionActive:e.userSelectionActive}};function mT({onSelectionContextMenu:e,noPanClassName:t,disableKeyboardA11y:n}){const i=Nr(),{width:o,height:l,x:u,y:c,transformString:f,userSelectionActive:_}=Rn(hT,Fr),p=Ib(),w=m.useRef(null);if(m.useEffect(()=>{var S;n||(S=w.current)==null||S.focus({preventScroll:!0})},[n]),Lb({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:Yr(["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 _T=m.memo(mT);const pT=e=>e.nodesSelectionActive,Pb=({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:se,panOnDrag:ie,defaultViewport:ue,translateExtent:F,minZoom:C,maxZoom:N,preventScrolling:P,onSelectionContextMenu:O,noWheelClassName:ne,noPanClassName:B,disableKeyboardA11y:z})=>{const G=Rn(pT),T=vf(w),Q=vf(E),K=Q||ie,J=Q||Z,oe=T||y&&K!==!0;return eT({deleteKeyCode:c,multiSelectionKeyCode:$}),ve.createElement(sT,{onMove:f,onMoveStart:_,onMoveEnd:p,onPaneContextMenu:l,elementsSelectable:D,zoomOnScroll:M,zoomOnPinch:H,panOnScroll:J,panOnScrollSpeed:Y,panOnScrollMode:X,zoomOnDoubleClick:se,panOnDrag:!T&&K,defaultViewport:ue,translateExtent:F,minZoom:C,maxZoom:N,zoomActivationKeyCode:L,preventScrolling:P,noWheelClassName:ne,noPanClassName:B},ve.createElement(Tb,{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(_T,{onSelectionContextMenu:O,noPanClassName:B,disableKeyboardA11y:z})))};Pb.displayName="FlowRenderer";var gT=m.memo(Pb);function yT(e){return Rn(m.useCallback(n=>e?hb(n.nodeInternals,{x:0,y:0,width:n.width,height:n.height},n.transform,!0):n.getNodes(),[e]))}function wT(e){const t={input:Xd(e.input||bb),default:Xd(e.default||qp),output:Xd(e.output||Sb),group:Xd(e.group||Ag)},n={},i=Object.keys(e).filter(o=>!["input","default","output","group"].includes(o)).reduce((o,l)=>(o[l]=Xd(e[l]||qp),o),n);return{...t,...i}}const vT=({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]},xT=e=>({nodesDraggable:e.nodesDraggable,nodesConnectable:e.nodesConnectable,nodesFocusable:e.nodesFocusable,elementsSelectable:e.elementsSelectable,updateNodeDimensions:e.updateNodeDimensions,onError:e.onError}),Ob=e=>{const{nodesDraggable:t,nodesConnectable:n,nodesFocusable:i,elementsSelectable:o,updateNodeDimensions:l,onError:u}=Rn(xT,Fr),c=yT(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:Tg},c.map(p=>{var H,Z,Y;let w=p.type||"default";e.nodeTypes[w]||(u==null||u("003",_a.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?jg(p.positionAbsolute,e.nodeExtent):p.positionAbsolute,L=(E==null?void 0:E.x)??0,D=(E==null?void 0:E.y)??0,M=vT({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[pr])==null?void 0:H.z)??0,isParent:!!((Z=p[pr])!=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[pr])!=null&&Y.handleBounds)})}))};Ob.displayName="NodeRenderer";var bT=m.memo(Ob);const jT=(e,t,n)=>n===mt.Left?e-t:n===mt.Right?e+t:e,ST=(e,t,n)=>n===mt.Top?e-t:n===mt.Bottom?e+t:e,Mw="react-flow__edgeupdater",Rw=({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:Yr([Mw,`${Mw}-${c}`]),cx:jT(t,i,e),cy:ST(n,i,e),r:i,stroke:"transparent",fill:"transparent"}),kT=()=>!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:se,hidden:ie,sourceHandleId:ue,targetHandleId:F,onContextMenu:C,onMouseEnter:N,onMouseMove:P,onMouseLeave:O,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,Oe]=m.useState(!1),et=Nr(),lt=m.useMemo(()=>`url('#${Up(Q,K)}')`,[Q,K]),Ye=m.useMemo(()=>`url('#${Up(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(Cr=>Cr.id===n);Ln&&(se&&(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,P),Ke=Yd(n,et.getState,O),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",Cr=En||kT,Kn=bn,lr=Dn.find(ce=>ce.id===n);Oe(!0),z==null||z(Mt,lr,wn);const Cs=ce=>{Oe(!1),G==null||G(ce,lr,wn)};yb({event:Mt,handleId:Ln,nodeId:jn,onConnect:ce=>B==null?void 0:B(lr,ce),isTarget:Kn,getState:et.getState,setState:et.setState,isValidConnection:Cr,edgeUpdaterType:wn,onEdgeUpdateEnd:Cs})},Qt=Mt=>Dt(Mt,!0),_n=Mt=>Dt(Mt,!1),Ut=()=>We(!0),It=()=>We(!1),un=!se&&!u,Bn=Mt=>{var bn;if(ob.includes(Mt.key)&&se){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:Yr(["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?`${Cb}-${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(Rw,{position:Y,centerX:D,centerY:M,radius:ne,onMouseDown:Qt,onMouseEnter:Ut,onMouseOut:It,type:"source"}),(fe==="target"||fe===!0)&&ve.createElement(Rw,{position:X,centerX:H,centerY:Z,radius:ne,onMouseDown:_n,onMouseEnter:Ut,onMouseOut:It,type:"target"})))};return t.displayName="EdgeWrapper",m.memo(t)};function NT(e){const t={default:ju(e.default||Mm),straight:ju(e.bezier||Ng),step:ju(e.step||kg),smoothstep:ju(e.step||Gm),simplebezier:ju(e.simplebezier||Sg)},n={},i=Object.keys(e).filter(o=>!["default","bezier"].includes(o)).reduce((o,l)=>(o[l]=ju(e[l]||Mm),o),n);return{...t,...i}}function Lw(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 Iw(e,t){return e?e.length===1||!t?e[0]:t&&e.find(n=>n.id===t)||null:null}const CT=(e,t,n,i,o,l)=>{const u=Lw(n,e,t),c=Lw(l,i,o);return{sourceX:u.x,sourceY:u.y,targetX:c.x,targetY:c.y}};function $T({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 Pw(e){var i,o,l,u,c;const t=((i=e==null?void 0:e[pr])==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 AT=[{level:0,isMaxLevel:!0,edges:[]}];function ET(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[pr])==null?void 0:p.z)||0,((w=y==null?void 0:y[pr])==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?AT:l}function TT(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)&&$T({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 ET(i,t,n)}const MT=({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"}),RT=({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"}),Ow={[wf.Arrow]:MT,[wf.ArrowClosed]:RT};function LT(e){const t=Nr();return m.useMemo(()=>{var o,l;return Object.prototype.hasOwnProperty.call(Ow,e)?Ow[e]:((l=(o=t.getState()).onError)==null||l.call(o,"009",_a.error009(e)),null)},[e])}const IT=({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=LT(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},PT=({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=Up(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))},Db=({defaultColor:e,rfId:t})=>{const n=Rn(m.useCallback(PT({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(IT,{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})))};Db.displayName="MarkerDefinitions";var OT=m.memo(Db);const DT=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}),Fb=({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(DT,Fr),se=TT(t,Y,n);return M?ve.createElement(ve.Fragment,null,se.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(OT,{defaultColor:e,rfId:i}),ve.createElement("g",null,ue.map(C=>{const[N,P,O]=Pw(Y.get(C.source)),[ne,B,z]=Pw(Y.get(C.target));if(!O||!z)return null;let G=C.type||"default";o[G]||(X==null||X("011",_a.error011(G)),G="default");const T=o[G]||o.default,Q=Z===mc.Strict?B.target:(B.target??[]).concat(B.source??[]),K=Iw(P.source,C.sourceHandle),J=Iw(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",_a.error008(K,C)),null;const{sourceX:Ae,sourceY:Be,targetX:We,targetY:_t}=CT(N,K,oe,ne,J,fe);return ve.createElement(T,{key:C.id,id:C.id,className:Yr([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};Fb.displayName="EdgeRenderer";var FT=m.memo(Fb);const zT=e=>`translate(${e.transform[0]}px,${e.transform[1]}px) scale(${e.transform[2]})`;function BT({children:e}){const t=Rn(zT);return ve.createElement("div",{className:"react-flow__viewport react-flow__container",style:{transform:t}},e)}function UT(e){const t=Eg(),n=m.useRef(!1);m.useEffect(()=>{!n.current&&t.viewportInitialized&&e&&(setTimeout(()=>e(t),1),n.current=!0)},[e,t.viewportInitialized])}const WT={[mt.Left]:mt.Right,[mt.Right]:mt.Left,[mt.Top]:mt.Bottom,[mt.Bottom]:mt.Top},zb=({nodeId:e,handleType:t,style:n,type:i=ll.Bezier,CustomComponent:o,connectionStatus:l})=>{var Z,Y,X;const{fromNode:u,handleId:c,toX:f,toY:_,connectionMode:p}=Rn(m.useCallback(se=>({fromNode:se.nodeInternals.get(e),handleId:se.connectionHandleId,toX:(se.connectionPosition.x-se.transform[0])/se.transform[2],toY:(se.connectionPosition.y-se.transform[1])/se.transform[2],connectionMode:se.connectionMode}),[e]),Fr),w=(Z=u==null?void 0:u[pr])==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(se=>se.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?WT[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===ll.Bezier?[M]=db(H):i===ll.Step?[M]=Bp({...H,borderRadius:0}):i===ll.SmoothStep?[M]=Bp(H):i===ll.SimpleBezier?[M]=ub(H):M=`M${$},${E} ${f},${_}`,ve.createElement("path",{d:M,fill:"none",className:"react-flow__connection-path",style:n})};zb.displayName="ConnectionLine";const qT=e=>({nodeId:e.connectionNodeId,handleType:e.connectionHandleType,nodesConnectable:e.nodesConnectable,connectionStatus:e.connectionStatus,width:e.width,height:e.height});function HT({containerStyle:e,style:t,type:n,component:i}){const{nodeId:o,handleType:l,nodesConnectable:u,width:c,height:f,connectionStatus:_}=Rn(qT,Fr);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:Yr(["react-flow__connection",_])},ve.createElement(zb,{nodeId:o,handleType:l,style:t,type:n,CustomComponent:i,connectionStatus:_})))}function Dw(e,t){return m.useRef(null),Nr(),m.useMemo(()=>t(e),[e])}const Bb=({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:se,zoomActivationKeyCode:ie,deleteKeyCode:ue,onlyRenderVisibleElements:F,elementsSelectable:C,selectNodesOnDrag:N,defaultViewport:P,translateExtent:O,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:Oe,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=Dw(e,wT),bn=Dw(t,NT);return UT(l),ve.createElement(gT,{onPaneClick:we,onPaneMouseEnter:Ae,onPaneMouseMove:Be,onPaneMouseLeave:We,onPaneContextMenu:Oe,onPaneScroll:_t,deleteKeyCode:ue,selectionKeyCode:H,selectionOnDrag:Z,selectionMode:Y,onSelectionStart:b,onSelectionEnd:$,multiSelectionKeyCode:X,panActivationKeyCode:se,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:P,translateExtent:O,minZoom:ne,maxZoom:B,onSelectionContextMenu:S,preventScrolling:z,noDragClassName:Ke,noWheelClassName:Dt,noPanClassName:Qt,disableKeyboardA11y:Ut},ve.createElement(BT,null,ve.createElement(FT,{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(HT,{style:L,type:E,component:D,containerStyle:M})),ve.createElement("div",{className:"react-flow__edgelabel-renderer"}),ve.createElement(bT,{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})))};Bb.displayName="GraphView";var VT=m.memo(Bb);const Vp=[[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY],[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY]],Qa={rfId:"1",width:0,height:0,transform:[0,0,1],nodeInternals:new Map,edges:[],onNodesChange:null,onEdgesChange:null,hasDefaultNodes:!1,hasDefaultEdges:!1,d3Zoom:null,d3Selection:null,d3ZoomHandler:void 0,minZoom:.5,maxZoom:2,translateExtent:Vp,nodeExtent:Vp,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:wE,isValidConnection:void 0},GT=()=>LC((e,t)=>({...Qa,setNodes:n=>{const{nodeInternals:i,nodeOrigin:o,elevateNodesOnSelect:l}=t();e({nodeInternals:X_(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?X_(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=bg($.nodeElement);!!(L.width&&L.height&&(E.width!==L.width||E.height!==L.height||$.forceUpdate))&&(o.set(E.id,{...E,[pr]:{...E[pr],handleBounds:{source:Tw(".source",$.nodeElement,y,_),target:Tw(".target",$.nodeElement,y,_)}},...L}),b.push({id:E.id,type:"dimensions",dimensions:L}))}return b},[]);Ab(o,_);const S=u||l&&!u&&Eb(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 _=lT(n,c()),p=X_(_,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=>ol(f,!0)):(u=$u(l(),n),c=$u(o,[])),em({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=>ol(f,!0)):(u=$u(o,n),c=$u(l(),[])),em({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,ol(p.id,!1))),_=c.map(p=>ol(p.id,!1));em({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=>ol(c.id,!1)),u=n.filter(c=>c.selected).map(c=>ol(c.id,!1));em({changedNodes:l,changedEdges:u,get:t,set:e})},setNodeExtent:n=>{const{nodeInternals:i}=t();i.forEach(o=>{o.positionAbsolute=jg(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 _=fa.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:Qa.connectionNodeId,connectionHandleId:Qa.connectionHandleId,connectionHandleType:Qa.connectionHandleType,connectionStatus:Qa.connectionStatus,connectionStartHandle:Qa.connectionStartHandle,connectionEndHandle:Qa.connectionEndHandle}),reset:()=>e({...Qa})}),Object.is),Mg=({children:e})=>{const t=m.useRef(null);return t.current||(t.current=GT()),ve.createElement(fE,{value:t.current},e)};Mg.displayName="ReactFlowProvider";const Ub=({children:e})=>m.useContext(Vm)?ve.createElement(ve.Fragment,null,e):ve.createElement(Mg,null,e);Ub.displayName="ReactFlowWrapper";const KT={input:bb,default:qp,output:Sb,group:Ag},YT={default:Mm,straight:Ng,step:kg,smoothstep:Gm,simplebezier:Sg},JT=[0,0],XT=[15,15],ZT={x:0,y:0,zoom:1},QT={width:"100%",height:"100%",overflow:"hidden",position:"relative",zIndex:0},Wb=m.forwardRef(({nodes:e,edges:t,defaultNodes:n,defaultEdges:i,className:o,nodeTypes:l=KT,edgeTypes:u=YT,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:se,onNodesDelete:ie,onEdgesDelete:ue,onSelectionChange:F,onSelectionDragStart:C,onSelectionDrag:N,onSelectionDragStop:P,onSelectionContextMenu:O,onSelectionStart:ne,onSelectionEnd:B,connectionMode:z=mc.Strict,connectionLineType:G=ll.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=Tm()?"Meta":"Control",zoomActivationKeyCode:Be=Tm()?"Meta":"Control",snapToGrid:We=!1,snapGrid:_t=XT,onlyRenderVisibleElements:Oe=!1,selectNodesOnDrag:et=!0,nodesDraggable:lt,nodesConnectable:Ye,nodesFocusable:Se,nodeOrigin:Le=JT,edgesFocusable:ct,edgesUpdatable:ge,elementsSelectable:De,defaultViewport:Ke=ZT,minZoom:Dt=.5,maxZoom:Qt=2,translateExtent:_n=Vp,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:Cr,onPaneMouseMove:Kn,onPaneMouseLeave:lr,onPaneScroll:Cs,onPaneContextMenu:Yn,children:ce,onEdgeUpdate:be,onEdgeContextMenu:Ge,onEdgeDoubleClick:Ve,onEdgeMouseEnter:rt,onEdgeMouseMove:ut,onEdgeMouseLeave:Et,onEdgeUpdateStart:jt,onEdgeUpdateEnd:qt,edgeUpdaterRadius:dt=10,onNodesChange:Yt,onEdgesChange:Bt,noDragClassName:Nt="nodrag",noWheelClassName:pt="nowheel",noPanClassName:Pt="nopan",fitView:$e=!1,fitViewOptions:Wt,connectOnClick:Ct=!0,attributionPosition:sn,proOptions:$t,defaultEdgeOptions:cr,elevateNodesOnSelect:ur=!0,elevateEdgesOnSelect:Jr=!1,disableKeyboardA11y:$r=!1,autoPanOnConnect:fs=!0,autoPanOnNodeDrag:Xr=!0,connectionRadius:no=20,isValidConnection:xe,onError:Jn,style:hn,id:ro,nodeDragThreshold:$i,...$s},hs)=>{const Ks=ro||"1";return ve.createElement("div",{...$s,style:{...hn,...QT},ref:hs,className:Yr(["react-flow",o]),"data-testid":"rf__wrapper",id:ro},ve.createElement(Ub,null,ve.createElement(VT,{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:Oe,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:Cr,onPaneMouseMove:Kn,onPaneMouseLeave:lr,onPaneScroll:Cs,onPaneContextMenu:Yn,onSelectionContextMenu:O,onSelectionStart:ne,onSelectionEnd:B,onEdgeUpdate:be,onEdgeContextMenu:Ge,onEdgeDoubleClick:Ve,onEdgeMouseEnter:rt,onEdgeMouseMove:ut,onEdgeMouseLeave:Et,onEdgeUpdateStart:jt,onEdgeUpdateEnd:qt,edgeUpdaterRadius:dt,defaultMarkerColor:un,noDragClassName:Nt,noWheelClassName:pt,noPanClassName:Pt,elevateEdgesOnSelect:Jr,rfId:Ks,disableKeyboardA11y:$r,nodeOrigin:Le,nodeExtent:It}),ve.createElement(UE,{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:ur,minZoom:Dt,maxZoom:Qt,nodeExtent:It,onNodesChange:Yt,onEdgesChange:Bt,snapToGrid:We,snapGrid:_t,connectionMode:z,translateExtent:_n,connectOnClick:Ct,defaultEdgeOptions:cr,fitView:$e,fitViewOptions:Wt,onNodesDelete:ie,onEdgesDelete:ue,onNodeDragStart:Y,onNodeDrag:X,onNodeDragStop:se,onSelectionDrag:N,onSelectionDragStart:C,onSelectionDragStop:P,noPanClassName:Pt,nodeOrigin:Le,rfId:Ks,autoPanOnConnect:fs,autoPanOnNodeDrag:Xr,onError:Jn,connectionRadius:no,isValidConnection:xe,nodeDragThreshold:$i}),ve.createElement(zE,{onSelectionChange:F}),ce,ve.createElement(mE,{proOptions:$t,position:sn}),ve.createElement(GE,{rfId:Ks,disableKeyboardA11y:$r})))});Wb.displayName="ReactFlow";const qb=({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:Yr(["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})};qb.displayName="MiniMapNode";var eM=m.memo(qb);const tM=e=>e.nodeOrigin,nM=e=>e.getNodes().filter(t=>!t.hidden&&t.width&&t.height),tp=e=>e instanceof Function?e:()=>e;function rM({nodeStrokeColor:e="transparent",nodeColor:t="#e2e2e2",nodeClassName:n="",nodeBorderRadius:i=5,nodeStrokeWidth:o=2,nodeComponent:l=eM,onClick:u}){const c=Rn(nM,Fr),f=Rn(tM),_=tp(t),p=tp(e),w=tp(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 sM=m.memo(rM);const iM=200,oM=150,aM=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?gE(Km(t,e.nodeOrigin),n):n,rfId:e.rfId}},lM="react-flow__minimap-desc";function Hb({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=Nr(),H=m.useRef(null),{boundingRect:Z,viewBB:Y,rfId:X}=Rn(aM,Fr),se=(e==null?void 0:e.width)??iM,ie=(e==null?void 0:e.height)??oM,ue=Z.width/se,F=Z.height/ie,C=Math.max(ue,F),N=C*se,P=C*ie,O=D*C,ne=Z.x-(N-Z.width)/2-O,B=Z.y-(P-Z.height)/2-O,z=N+O*2,G=P+O*2,T=`${lM}-${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 Oe=-Ae.sourceEvent.deltaY*(Ae.sourceEvent.deltaMode===1?.05:Ae.sourceEvent.deltaMode?1:.002)*L,et=Be[2]*Math.pow(2,Oe);_t.scaleTo(We,et)},me=Ae=>{const{transform:Be,d3Selection:We,d3Zoom:_t,translateExtent:Oe,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=fa.translate(Se.x,Se.y).scale(Be[2]),ge=_t.constrain()(ct,Le,Oe);_t.transform(We,ge)},we=eb().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:Yr(["react-flow__minimap",t]),"data-testid":"rf__minimap"},ve.createElement("svg",{width:se,height:ie,viewBox:`${ne} ${B} ${z} ${G}`,role:"img","aria-labelledby":T,ref:H,onClick:K},$&&ve.createElement("title",{id:T},$),ve.createElement(sM,{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-O},${B-O}h${z+O*2}v${G+O*2}h${-z-O*2}z
120
- M${Y.x},${Y.y}h${Y.width}v${Y.height}h${-Y.width}z`,fill:f,fillRule:"evenodd",stroke:_,strokeWidth:p,pointerEvents:"none"})))}Hb.displayName="MiniMap";var cM=m.memo(Hb);function uM(){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 dM(){return ve.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 5"},ve.createElement("path",{d:"M0 0h32v4.2H0z"}))}function fM(){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 hM(){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 mM(){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:Yr(["react-flow__controls-button",t]),...n},e);Au.displayName="ControlButton";const _M=e=>({isInteractive:e.nodesDraggable||e.nodesConnectable||e.elementsSelectable,minZoomReached:e.transform[2]<=e.minZoom,maxZoomReached:e.transform[2]>=e.maxZoom}),Vb=({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=Nr(),[x,S]=m.useState(!1),{isInteractive:b,minZoomReached:$,maxZoomReached:E}=Rn(_M,Fr),{zoomIn:L,zoomOut:D,fitView:M}=Eg();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:Yr(["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(uM,null)),ve.createElement(Au,{onClick:Z,className:"react-flow__controls-zoomout",title:"zoom out","aria-label":"zoom out",disabled:$},ve.createElement(dM,null))),n&&ve.createElement(Au,{className:"react-flow__controls-fitview",onClick:Y,title:"fit view","aria-label":"fit view"},ve.createElement(fM,null)),i&&ve.createElement(Au,{className:"react-flow__controls-interactive",onClick:X,title:"toggle interactivity","aria-label":"toggle interactivity"},b?ve.createElement(mM,null):ve.createElement(hM,null)),p)};Vb.displayName="Controls";var pM=m.memo(Vb),Qi;(function(e){e.Lines="lines",e.Dots="dots",e.Cross="cross"})(Qi||(Qi={}));function gM({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 yM({color:e,radius:t}){return ve.createElement("circle",{cx:t,cy:t,r:t,fill:e})}const wM={[Qi.Dots]:"#91919a",[Qi.Lines]:"#eee",[Qi.Cross]:"#e2e2e2"},vM={[Qi.Dots]:1,[Qi.Lines]:1,[Qi.Cross]:6},xM=e=>({transform:e.transform,patternId:`pattern-${e.rfId}`});function Gb({id:e,variant:t=Qi.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(xM,Fr),y=u||wM[t],x=i||vM[t],S=t===Qi.Dots,b=t===Qi.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:Yr(["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(yM,{color:y,radius:L/l}):ve.createElement(gM,{dimensions:D,color:y,lineWidth:o})),ve.createElement("rect",{x:"0",y:"0",width:"100%",height:"100%",fill:`url(#${w+e})`}))}Gb.displayName="Background";var bM=m.memo(Gb);function Kb(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 Lm(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 jM(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 SM(e){const t=String(e||"").trim();if(!t)return"";const n=t.indexOf(":");if(n<=0||n>=t.length-1)return Lm(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 Lm(t)}function Gp(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 Kp(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 Yb(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 kM(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 Fw(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 Gp(o);if(n==="circle")return kM(o,i);if(n==="radial")return Fw(o,e.edges,i);if(n==="force"){const l=Fw(o,e.edges,i),u=Yb(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 Gp(o)}function NM(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 CM(e,t={}){const n=!!(t.groupEdges??!0),i=Math.max(1,t.maxEdgeLabelPredicates??3),o=NM(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=Gp(u),f=u.map(y=>({id:y,type:"default",data:{label:SM(y),kind:jM(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?`${Lm(Y)}×${X}`:Lm(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 $M(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 zw={seed:1,dt:1,springLength:240,springStrength:.03,repulsionStrength:9e3,centeringStrength:.003,damping:.85,maxSpeed:90,maxRepulsionNodes:320};function nm(e,t={}){const n={...zw,...t,seed:typeof t.seed=="number"&&Number.isFinite(t.seed)?Math.trunc(t.seed):zw.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=Yb(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 AM(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),se=X*M/Y,ie=X*H/Y;e.acc[2*S]+=se,e.acc[2*S+1]+=ie,e.acc[2*b]-=se,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 EM(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 TM(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 Bw(e,t="session"){const n=String(e??"").trim().toLowerCase();return n==="run"||n==="session"||n==="global"||n==="all"?n:t}function MM(){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 RM(){return r.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16","aria-hidden":"true",focusable:"false",children:[r.jsx("rect",{x:"3",y:"3",width:"3",height:"3",rx:"1"}),r.jsx("rect",{x:"3",y:"7",width:"3",height:"3",rx:"1"}),r.jsx("rect",{x:"3",y:"11",width:"3",height:"3",rx:"1"}),r.jsx("rect",{x:"8",y:"3.5",width:"6",height:"2",rx:"1",fill:"none",strokeWidth:"1.4"}),r.jsx("rect",{x:"8",y:"7.5",width:"6",height:"2",rx:"1",fill:"none",strokeWidth:"1.4"}),r.jsx("rect",{x:"8",y:"11.5",width:"6",height:"2",rx:"1",fill:"none",strokeWidth:"1.4"})]})}function Jb(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=Jb(e,.6,2.4,1),n=240*t,i=9e3*t*t;return{springLength:n,repulsionStrength:i}}const xf="abstractuic_amx_saved_layouts_v1",Yp=.025,Jp=6,Xb=1e6;function Rg(){if(typeof window>"u")return null;try{return window.localStorage}catch{return null}}function Xp(e,t="grid"){const n=String(e??"").trim().toLowerCase();return n==="grid"||n==="circle"||n==="radial"||n==="force"?n:t}function LM(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 Uw(e){const t=Rg();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 _=Xp(c.kind,"grid"),p=typeof c.seed=="number"&&Number.isFinite(c.seed)?Math.trunc(c.seed):Kp(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=LM($);E&&(y[String(b)]=E)}const x=Kb(c.viewport,{minZoom:Yp,maxZoom:Jp,maxAbsTranslate:Xb})??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 IM(e,t){const n=Rg();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 PM(e){const t=Rg();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 OM(e){const t=String(e??"").trim();if(!t)return;const n=Number(t);if(Number.isFinite(n))return n}function np(e,t){const n=!!(t!=null&&t.allowZero),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 DM(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 FM(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 r.jsxs(r.Fragment,{children:[l,r.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 BM(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=BM(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 Zb(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 UM(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=Zb(f);return _>1?`${p}×${_}`:p}).join(" | "),c=o.length>n?` +${o.length-n}`:"";return`${u}${c}`.trim()}function WM({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 co;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),[se,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[P,O]=m.useState(""),[ne,B]=m.useState(!0),[z,G]=m.useState(!1),[T,Q]=m.useState(!0),[K]=m.useState(()=>({compact:MM(),show:!1})),J=K.compact,[oe,fe]=m.useState(K.show),[me,we]=m.useState(!1),Ae=E,Be=m.useMemo(()=>Kp(Ae),[Ae]),[We,_t]=m.useState("grid"),[Oe,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,Cr]=m.useState(""),[Kn,lr]=m.useState(""),Cs=m.useMemo(()=>{var ae;const U=(ae=n==null?void 0:n[0])==null?void 0:ae.scope;return Bw(U,"session")},[n]),[Yn,ce]=m.useState(Cs),[be,Ge]=m.useState("standard"),[Ve,rt]=m.useState(""),[ut,Et]=m.useState(""),[jt,qt]=m.useState(""),[dt,Yt]=m.useState(""),[Bt,Nt]=m.useState(""),[pt,Pt]=m.useState(""),[$e,Wt]=m.useState(""),[Ct,sn]=m.useState("qwen/qwen3-next-80b");m.useEffect(()=>{ce(Cs)},[E]);const $t=Array.isArray(n)?n:[],cr=typeof i=="string"?i:"",ur=Array.isArray(o)?o:[],Jr=typeof l=="number"?l:void 0,$r=typeof u=="number"?u:void 0,fs=typeof c=="number"?c:void 0,Xr=typeof f=="number"?f:void 0,no=_,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:cr,ro=(D==null?void 0:D.effort)??no,$i=(D==null?void 0:D.warnings)??xe,$s=m.useMemo(()=>new Set(["rdf:type","schema:name","skos:preflabel","skos:altlabel","dcterms:title","dcterms:identifier"]),[]),hs=m.useMemo(()=>T?Jn:(Jn||[]).filter(U=>!rp(U==null?void 0:U.predicate,$s)),[Jn,T,$s]),Ks=m.useMemo(()=>CM(Jn,{groupEdges:ne}),[Jn,ne]),it=m.useMemo(()=>{if(T)return Ks;const U=[];for(const ae of Ks.edges){const Ce=(ae&&ae.data&&Array.isArray(ae.data.assertions)?ae.data.assertions:[]).filter(Ue=>!rp(Ue==null?void 0:Ue.predicate,$s));if(!Ce.length)continue;const ke=UM(Ce);U.push({...ae,label:ke,data:{...ae.data,assertions:Ce,predicateSummary:ke}})}return{nodes:Ks.nodes,edges:U}},[Ks,T,$s]),tn=m.useMemo(()=>it.nodes.map(U=>U.id),[it.nodes]),gr=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]),dr=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]),so=P.trim().toLowerCase(),io=m.useMemo(()=>{var ae;if(!so)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(so)||ke.includes(so))&&U.add(je.id)}return U},[it.nodes,so]),pa=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:Oe}),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,Oe,tn,gr]),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,gr,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=Uw(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(pa(U.positions,Ce));return}Mt(!1),Dn("");const ae=Kp(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=nm(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:$M(it,U,ae,{directed:z})},[it,wn,Kn,z]),ms=!!(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:hs.length}},[z,it.edges,it.nodes.length,Kn,wn,hs.length]),_s=m.useMemo(()=>new Set((Fn==null?void 0:Fn.nodeIds)||[]),[Fn]),oo=m.useMemo(()=>new Set((Fn==null?void 0:Fn.edgeIds)||[]),[Fn]),[Qn,Zr]=m.useState(""),[fr,Ys]=m.useState(""),yr=!!(String(Qn||"").trim()||String(fr||"").trim()),ga=m.useMemo(()=>{const U=new Set,ae=new Set,je=String(Qn||"").trim(),Ce=String(fr||"").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,fr,Qn]);m.useEffect(()=>{Zr(""),Ys(""),Cr(""),lr("")},[E]);const[ao,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=nm(it,{seed:Oe,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}AM(gt,Ce),je+=Ce,jn(TM(gt)),(EM(gt)<=Ue||je>=ke)&&Ye(!1)};return U=window.requestAnimationFrame(ft),()=>{window.cancelAnimationFrame(U)}},[it,We,lt,Oe]);const ml=m.useMemo(()=>it.nodes.map(U=>{var rn;const ae=_s.has(U.id),je=io.has(U.id),Ce=Qn===U.id,ke=yr&&ga.nodes.has(U.id),Ue=Qd((rn=U.data)==null?void 0:rn.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,vr=ae?"rgba(168, 85, 247, 0.10)":je?"rgba(34, 211, 238, 0.08)":Ue.bg,Rt=ms?ae||Ce?1:.16:yr?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:vr,color:"rgba(255,255,255,0.92)",opacity:Rt,padding:8,fontSize:12,boxShadow:Ht,width:180,cursor:"pointer"}}}),[it.nodes,ms,io,En,Qn,_s,yr,ga.nodes]),Ai=m.useMemo(()=>it.edges.map(U=>{const ae=oo.has(U.id),je=fr===U.id,Ce=yr&&ga.edges.has(U.id),ke=ae?"rgba(168, 85, 247, 0.9)":yr?Ce||je?"rgba(96, 165, 250, 0.55)":"rgba(255,255,255,0.14)":"rgba(255,255,255,0.18)",Ue=ae?2.75:yr?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)":ms?"rgba(255,255,255,0.10)":"rgba(255,255,255,0.28)",gt=ms?ae||je?1:.1:yr?Ce||je?1:.08:1,Ft=ms?ae||je?1:0:yr?Ce||je?1:0:1,Ht=ms?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,ms,fr,oo,yr,ga.edges]),ps=m.useMemo(()=>{if(!fr)return[];const U=it.edges.find(je=>je.id===fr),ae=U&&U.data&&Array.isArray(U.data.assertions)?U.data.assertions:[];return Array.isArray(ae)?ae:[]},[it.edges,fr]),Ar=m.useMemo(()=>fr&&it.edges.find(U=>U.id===fr)||null,[it.edges,fr]),ya=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,$s)):[]},[Jn,Qn,T,$s]),As=m.useMemo(()=>fr?ps:ya,[ps,fr,ya]),ai=m.useMemo(()=>{const U=new Map;for(const ae of As){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||"")))},[As]),Ei=m.useMemo(()=>{const U=new Map;for(const ae of As){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||"")))},[As]),Qr=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]),Er=m.useCallback(async U=>{const ae=String(U??"");if(ae)try{await navigator.clipboard.writeText(ae)}catch{}},[]),Es=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]),es=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=nm(it,{seed:je,positions:Ce,...Zd(Se)}),Ye(!0))},[it,Se]),Ti=m.useCallback(()=>{if(We==="force"){if(lt){Ye(!1);return}ct.current=nm(it,{seed:Oe,positions:Ln.current,...Zd(Se)}),Ye(!0)}},[it,We,lt,Oe,Se]);m.useEffect(()=>()=>{typeof window>"u"||typeof window.cancelAnimationFrame=="function"&&un.current&&window.cancelAnimationFrame(un.current)},[]);const gs=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,vr=0;for(const Rt of tn){const rn=Ft[Rt];if(!rn||!Number.isFinite(rn.x)||!Number.isFinite(rn.y))continue;vr+=1;const Cn=[{x:rn.x,y:rn.y},{x:rn.x+90,y:rn.y+24}];for(const mn of Cn){const er=mn.x*ke+Ue,ns=mn.y*ke+ft;if(er>-ot&&er<je.width+ot&&ns>-ot&&ns<je.height+ot)return!1}if(Ht++,Ht>=gt)break}return vr?!0:null},[tn]),wr=m.useCallback(U=>{typeof window>"u"||typeof window.requestAnimationFrame!="function"||un.current||(un.current=window.requestAnimationFrame(()=>{un.current=0;const ae=gs();if(ae===null){if(It.current>=12)return;It.current+=1,window.setTimeout(()=>wr(`${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(()=>wr(`${U}:retry`),220)}))},[gs]);m.useEffect(()=>{Ut.current=0,_n.current=0,It.current=0,wr("mount")},[E,wr]),m.useEffect(()=>{wr("graph change")},[gr,wr]),m.useEffect(()=>{const U=Qt.current;if(!U||typeof window>"u"||typeof ResizeObserver!="function")return;const ae=new ResizeObserver(()=>wr("resize"));return ae.observe(U),()=>ae.disconnect()},[wr]);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=Kb(ke,{minZoom:Yp,maxZoom:Jp,maxAbsTranslate:Xb})??void 0;IM(Ae,{version:1,kind:We,seed:Oe,positions:ae,viewport:Ue,saved_at:U}),Mt(!0),Dn(U),Ye(!1)},[Ae,We,Oe,tn]),Ro=m.useCallback(()=>{const U=Uw(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(pa(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}}},[pa,it,Ae]),_l=m.useCallback(()=>{PM(Ae),Mt(!1),Dn("")},[Ae]),ts=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]),Lo=m.useMemo(()=>{const U=new Map;for(const ae of it.edges)U.set(ae.id,ae);return U},[it.edges]),Js=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=Lo.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},[Lo,Fn]),_c=m.useCallback(async()=>{if(w){ie(""),N(""),X(!0);try{const U=OM(Bt),ae=np(pt,{allowZero:!0,allowNegativeOne:!0}),je=np($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]),ys=m.useCallback(async()=>{if(!w)return;const U=String(wn||"").trim(),ae=String(Kn||"").trim();if(!U||!ae)return;const je=Math.max(200,np(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 rn=`${Rt.subject}|${Rt.predicate}|${Rt.object}|${String(Rt.observed_at||"")}|${String(Rt.scope||"")}|${String(Rt.owner_id||"")}`;Ue.has(rn)||(Ue.add(rn),ke.push(Rt))};for(const Rt of Jn)ft(Rt);const ot=z,gt=new Set,Ft=[U],Ht=new Set([U]),vr=async Rt=>{const rn=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(rn&&Array.isArray(rn.items)){for(const Cn of rn.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 er=mn.subject.trim();er&&!Ht.has(er)&&(Ht.add(er),Ft.push(er))}}}};for(;Ft.length&&gt.size<Ce&&!Ht.has(ae);){const Rt=Ft.shift();!Rt||gt.has(Rt)||(gt.add(Rt),await vr(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]),lo=m.useCallback(()=>{M(null),Z(null),ie(""),X(!1),N(""),F(!1),Cr(""),lr(""),Zr(""),Ys("")},[]),zr="Search KG",Io=it.nodes.length,Po=it.edges.length,Oo=hs.length;return r.jsxs("div",{className:"amx-root",children:[r.jsxs("div",{className:"amx-left",children:[r.jsx("div",{className:"amx-graphbar",role:"toolbar","aria-label":"Graph layout controls",children:r.jsxs("div",{className:"amx-graphbar-row",children:[r.jsx("span",{className:"amx-graphbar-title",children:"layout"}),r.jsxs("select",{value:We,onChange:U=>_t(Xp(U.target.value,We)),disabled:!tn.length,children:[r.jsx("option",{value:"grid",children:"grid (deterministic)"}),r.jsx("option",{value:"radial",children:"radial (bfs)"}),r.jsx("option",{value:"circle",children:"circle"}),r.jsx("option",{value:"force",children:"force (simulation)"})]}),We==="force"?r.jsxs("label",{className:"amx-graphbar-spread",children:[r.jsx("span",{className:"amx-graphbar-title",children:"spread"}),r.jsx("input",{type:"range",min:"0.7",max:"2.2",step:"0.1",value:Se,onChange:U=>Le(Jb(Number(U.target.value),.7,2.2,1))}),r.jsxs("span",{className:"amx-small",children:[Se.toFixed(1),"×"]})]}):null,r.jsx("button",{type:"button",className:"amx-btn",onClick:()=>es({kind:We,seed:Oe}),disabled:!tn.length,children:"Apply"}),r.jsx("button",{type:"button",className:"amx-btn",onClick:Ti,disabled:!tn.length||We!=="force",children:lt?"Pause simulation":"Play simulation"})]})}),r.jsxs("div",{className:"amx-graph","aria-label":"Knowledge graph",ref:Qt,children:[r.jsx(Mg,{children:r.jsxs(Wb,{nodes:ml,edges:Ai,defaultViewport:{x:0,y:0,zoom:1},minZoom:Yp,maxZoom:Jp,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,wr("init")},nodesDraggable:!0,nodesConnectable:!1,elementsSelectable:!0,onNodesChange:ts,onNodeClick:(U,ae)=>{Ys(""),Zr(ae.id)},onEdgeClick:(U,ae)=>{Zr(""),Ys(ae.id)},onPaneClick:()=>{Zr(""),Ys("")},children:[r.jsx(pM,{className:"amx-flow-controls",children:r.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:r.jsx(RM,{})})}),r.jsx(pf,{position:"bottom-right",className:"amx-panel-bottom-right",children:r.jsx("div",{className:"amx-panel-toggles",children:r.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?r.jsx(cM,{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?r.jsxs(pf,{position:"bottom-left",className:"amx-legend-panel",children:[r.jsx("div",{className:"amx-legend-title",children:"node colors"}),r.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})=>r.jsx("span",{className:"amx-legend-item",style:{borderColor:Qd(U).stroke},children:ae},U))})]}):null,r.jsx(bM,{gap:20,size:1,color:"rgba(255,255,255,0.06)"})]})},Ke),r.jsxs("details",{className:"amx-panel amx-controls",children:[r.jsxs("summary",{children:[r.jsx("span",{className:"amx-controls-title",children:zr}),r.jsxs("span",{className:"amx-small",children:[Oo," assertions · ",Io," nodes · ",Po," edges"]})]}),r.jsxs("div",{className:"amx-toolbar",style:{marginTop:10},children:[r.jsxs("div",{className:"amx-toolbar-grid",children:[r.jsxs("label",{children:["search / highlight",r.jsx("input",{value:P,onChange:U=>O(U.target.value),placeholder:"filter nodes by id/label"})]}),r.jsxs("label",{children:["group edges",r.jsxs("select",{value:String(ne),onChange:U=>B(U.target.value==="true"),children:[r.jsx("option",{value:"true",children:"group (subject→object)"}),r.jsx("option",{value:"false",children:"no grouping"})]})]}),r.jsxs("label",{children:["view",r.jsxs("select",{value:String(T),onChange:U=>Q(U.target.value==="true"),children:[r.jsx("option",{value:"true",children:"all assertions"}),r.jsx("option",{value:"false",children:"hide rdf:type / labels"})]})]}),r.jsxs("label",{children:["path mode",r.jsxs("select",{value:String(z),onChange:U=>G(U.target.value==="true"),children:[r.jsx("option",{value:"false",children:"undirected"}),r.jsx("option",{value:"true",children:"directed"})]})]})]}),r.jsxs("details",{className:"amx-details",children:[r.jsx("summary",{children:"layout"}),r.jsxs("div",{className:"amx-toolbar-grid",style:{marginTop:10},children:[r.jsxs("label",{children:["layout",r.jsxs("select",{value:We,onChange:U=>_t(Xp(U.target.value,We)),children:[r.jsx("option",{value:"grid",children:"grid (deterministic)"}),r.jsx("option",{value:"radial",children:"radial (bfs)"}),r.jsx("option",{value:"circle",children:"circle"}),r.jsx("option",{value:"force",children:"force (simulation)"})]})]}),r.jsxs("label",{children:["seed",r.jsx("input",{type:"number",step:"1",value:Oe,onChange:U=>et(Math.trunc(Number(U.target.value||0)||0))})]})]}),r.jsxs("div",{className:"amx-actions",style:{marginTop:10},children:[r.jsx("button",{type:"button",className:"amx-btn",onClick:()=>es({kind:We,seed:Oe}),disabled:!tn.length,children:"Apply layout"}),We==="force"?r.jsx("button",{type:"button",className:"amx-btn",onClick:Ti,disabled:!tn.length,children:lt?"Pause simulation":"Play simulation"}):null,r.jsx("button",{type:"button",className:"amx-btn",onClick:Mi,disabled:!tn.length,children:"Save layout"}),Bn?r.jsxs(r.Fragment,{children:[r.jsx("button",{type:"button",className:"amx-btn",onClick:Ro,children:"Load saved"}),r.jsx("button",{type:"button",className:"amx-btn",onClick:_l,children:"Clear saved"})]}):null]}),r.jsxs("div",{className:"amx-small",style:{marginTop:10,opacity:.9},children:["Drag nodes to adjust manually; use ",r.jsx("span",{className:"amx-mono",children:"Save layout"})," for a stable, replayable view.",Bn?r.jsxs("span",{children:[" ","(saved",bn?`: ${bn}`:"",")"]}):r.jsx("span",{children:" (no saved layout)"})]})]}),r.jsxs("details",{className:"amx-details",children:[r.jsx("summary",{children:"path"}),r.jsxs("div",{className:"amx-toolbar-grid",style:{marginTop:10},children:[r.jsxs("label",{children:["path start",r.jsxs("select",{value:wn,onChange:U=>Cr(U.target.value),children:[r.jsx("option",{value:"",children:"(none)"}),tn.map(U=>r.jsx("option",{value:U,children:(()=>{const ae=oi.get(U)||U;return ae===U?ae:`${ae} (${U})`})()},U))]})]}),r.jsxs("label",{children:["path end",r.jsxs("select",{value:Kn,onChange:U=>lr(U.target.value),children:[r.jsx("option",{value:"",children:"(none)"}),tn.map(U=>r.jsx("option",{value:U,children:(()=>{const ae=oi.get(U)||U;return ae===U?ae:`${ae} (${U})`})()},U))]})]})]}),Fn?r.jsx("div",{className:"amx-small",style:{marginTop:10},children:Js.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 r.jsxs("div",{children:[ae===0?r.jsx("span",{children:je}):null,ke,r.jsxs("span",{children:[Ce,Ue]})]},`${U.edgeId}:${ae}`)})}):wn&&Kn?r.jsxs("div",{className:"amx-small",style:{marginTop:10,opacity:.9},children:["No path found in the current subgraph (",(Tn==null?void 0:Tn.assertions)??Oo," 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?r.jsx("div",{style:{marginTop:10},children:r.jsx("button",{type:"button",className:"amx-btn",onClick:()=>void ys(),disabled:ue,children:ue?"Expanding…":"Expand neighborhood"})}):null]}):r.jsx("div",{className:"amx-small",style:{marginTop:10},children:"(no path)"})]}),r.jsxs("details",{className:"amx-details",children:[r.jsx("summary",{children:"query"}),r.jsxs("div",{className:"amx-toolbar-grid",style:{marginTop:10},children:[r.jsxs("label",{children:["query_text (semantic)",r.jsx("input",{value:Ve,onChange:U=>rt(U.target.value),placeholder:"e.g. emotion chip"})]}),r.jsxs("label",{children:["subject (exact)",r.jsx("input",{value:ut,onChange:U=>Et(U.target.value),placeholder:"e.g. ex:person-data"})]}),r.jsxs("label",{children:["predicate (exact)",r.jsx("input",{value:jt,onChange:U=>qt(U.target.value),placeholder:"e.g. schema:about"})]}),r.jsxs("label",{children:["object (exact)",r.jsx("input",{value:dt,onChange:U=>Yt(U.target.value),placeholder:"e.g. ex:concept-emotion-chip"})]}),r.jsxs("label",{children:["min_score",r.jsx("input",{type:"number",step:"any",value:Bt,onChange:U=>Nt(U.target.value),placeholder:"(auto)"})]}),r.jsxs("label",{children:["limit",r.jsx("input",{type:"number",min:"-1",step:"1",value:pt,onChange:U=>Pt(U.target.value),placeholder:"0/-1 = unlimited (if supported)"})]})]})]}),r.jsxs("details",{className:"amx-details",children:[r.jsx("summary",{children:"advanced"}),r.jsxs("div",{className:"amx-toolbar-grid",style:{marginTop:10},children:[r.jsxs("label",{children:["scope",r.jsxs("select",{value:Yn,onChange:U=>ce(Bw(U.target.value,Yn)),children:[r.jsx("option",{value:"run",children:"run"}),r.jsx("option",{value:"session",children:"session"}),r.jsx("option",{value:"global",children:"global"}),r.jsx("option",{value:"all",children:"all"})]})]}),r.jsxs("label",{children:["recall level",r.jsxs("select",{value:be,onChange:U=>Ge(U.target.value||"standard"),children:[r.jsx("option",{value:"urgent",children:"urgent"}),r.jsx("option",{value:"standard",children:"standard"}),r.jsx("option",{value:"deep",children:"deep"})]})]}),r.jsxs("label",{children:["max_input_tokens",r.jsx("input",{type:"number",min:"0",step:"1",value:$e,onChange:U=>Wt(U.target.value),placeholder:"(auto)"})]}),r.jsxs("label",{children:["model (budgeting)",r.jsx("input",{value:Ct,onChange:U=>sn(U.target.value),placeholder:"qwen/qwen3-next-80b"})]})]})]}),r.jsxs("div",{className:"amx-actions",children:[r.jsx("button",{type:"button",className:"amx-btn",onClick:()=>void _c(),disabled:!w||Y,children:Y?"Querying…":"Query store"}),r.jsx("button",{type:"button",className:"amx-btn",onClick:lo,disabled:!D&&!se&&!Y,children:"Reset to step output"}),D?r.jsxs("span",{className:"amx-small",children:["showing: ",H||"live query"]}):r.jsx("span",{className:"amx-small",children:"showing: step output"}),se?r.jsx("span",{className:"amx-small",style:{color:"var(--error, rgba(255, 80, 80, 0.95))"},children:se}):null,C?r.jsx("span",{className:"amx-small",style:{color:"var(--error, rgba(255, 80, 80, 0.95))"},children:C}):null]})]})]})]})]}),r.jsxs("div",{className:"amx-right",children:[r.jsxs("div",{className:"amx-panel",children:[r.jsx("h3",{children:"Details"}),r.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=DM(ro);return U?r.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:r.jsx("div",{className:"amx-small",style:{marginBottom:8,color:"var(--warning, rgba(255, 180, 90, 0.95))"},children:ae})})(),r.jsx("div",{className:"amx-small",style:{marginBottom:8,opacity:.9},children:(()=>{const U=(D==null?void 0:D.packets_version)??Jr,ae=(D==null?void 0:D.packed_count)??$r,je=(D==null?void 0:D.dropped)??fs,Ce=(D==null?void 0:D.estimated_tokens)??Xr,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)."})()}),r.jsx("div",{className:"amx-active-memory",children:zM(hn||"(empty)",P)}),(()=>{const U=D!=null&&D.packets&&Array.isArray(D.packets)?D.packets:ur;return!Array.isArray(U)||U.length===0?null:r.jsxs("div",{style:{marginTop:10},children:[r.jsxs("button",{type:"button",className:"amx-btn",onClick:()=>nn(ae=>!ae),children:[ao?"Hide":"Show"," packets (",U.length,")"]}),ao?r.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 r.jsxs("div",{className:"amx-item",children:[r.jsx("div",{className:"amx-mono",children:ke||"(packet)"}),ft||Ue!==null?r.jsxs("div",{className:"amx-small",children:[ft?`[${ft}]`:null,ft&&Ue!==null?" ":null,Ue!==null?`score:${Ue}`:null]}):null]},je)})}):null]})})(),r.jsx("div",{style:{marginTop:14,marginBottom:12,borderTop:"1px solid var(--ui-border-1, rgba(255,255,255,0.08))"}}),r.jsx("div",{className:"amx-small",style:{marginBottom:8,fontWeight:700,opacity:.9},children:"Inspect"}),r.jsx("div",{className:"amx-small",style:{marginBottom:8},children:"Click a node or edge to inspect its assertions."}),Qn?r.jsxs("div",{className:"amx-item",style:{marginBottom:10,display:"flex",justifyContent:"space-between",gap:10,alignItems:"center"},children:[r.jsxs("div",{style:{minWidth:0},children:[r.jsx("div",{className:"amx-mono",style:{fontSize:11,opacity:.95},children:oi.get(Qn)||Qn}),r.jsxs("div",{className:"amx-small",children:["kind=",dr.get(Qn)||"entity"," · id=",Qn]})]}),r.jsxs("div",{className:"amx-actions",children:[r.jsx("button",{type:"button",className:"amx-btn",onClick:()=>void Er(Qn),children:"Copy id"}),r.jsx("button",{type:"button",className:"amx-btn",onClick:Es,children:"Focus"})]})]}):Ar&&Ar.source&&Ar.target?r.jsxs("div",{className:"amx-item",style:{marginBottom:10,display:"flex",justifyContent:"space-between",gap:10,alignItems:"center"},children:[r.jsxs("div",{style:{minWidth:0},children:[r.jsxs("div",{className:"amx-mono",style:{fontSize:11,opacity:.95},children:[Ar.source," —",String(Ar.label||((co=Ar.data)==null?void 0:co.predicateSummary)||"").trim()||"?","→ ",Ar.target]}),r.jsxs("div",{className:"amx-small",children:["edge_id=",Ar.id]})]}),r.jsxs("div",{className:"amx-actions",children:[r.jsx("button",{type:"button",className:"amx-btn",onClick:()=>void Er(Ar.id),children:"Copy id"}),r.jsx("button",{type:"button",className:"amx-btn",onClick:Es,children:"Fit"})]})]}):r.jsx("div",{className:"amx-small",style:{marginBottom:10,opacity:.9},children:"(no selection)"}),r.jsx("div",{className:"amx-list",children:As.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=dr.get(je)||"entity",gt=dr.get(ke)||"entity",Ft=Qd(ot),Ht=Qd(gt),vr=ef(U.observed_at),Rt=FM(U),rn=U.provenance&&typeof U.provenance=="object"&&!Array.isArray(U.provenance)?U.provenance:null,Cn=rn&&typeof rn.span_id=="string"?rn.span_id.trim():"",mn=rn&&typeof rn.writer_run_id=="string"?rn.writer_run_id.trim():"",er=typeof U.owner_id=="string"?U.owner_id.trim():"",ns=mn||er,Xs=!!((S||x)&&Cn&&ns),Ri=!!(S&&mn&&!Cn),wa=Xs||Ri;return r.jsxs("div",{className:"amx-item amx-triple-card",children:[r.jsxs("div",{className:"amx-triple-row",children:[r.jsx("button",{type:"button",className:"amx-term",style:{borderColor:Ft.stroke,background:Ft.bg},title:je,onClick:()=>{je&&(Ys(""),Zr(je))},children:Ue||je||"(subject)"}),r.jsx("span",{className:"amx-arrow",children:"—"}),r.jsx("span",{className:"amx-predicate",title:Ce,children:Zb(Ce)||"(predicate)"}),r.jsx("span",{className:"amx-arrow",children:"→"}),r.jsx("button",{type:"button",className:"amx-term",style:{borderColor:Ht.stroke,background:Ht.bg},title:ke,onClick:()=>{ke&&(Ys(""),Zr(ke))},children:ft||ke||"(object)"})]}),r.jsxs("div",{className:"amx-triple-meta",children:[vr?r.jsxs("span",{className:"amx-small",title:String(U.observed_at||""),children:["[",vr,"]"]}):null,Rt?r.jsx("span",{className:"amx-small",children:Rt}):null]}),Cn||mn?r.jsxs("div",{className:"amx-triple-actions",children:[Cn?r.jsxs("span",{className:"amx-small",children:["span:",Cn]}):null,mn?r.jsxs("span",{className:"amx-small",children:["run:",mn]}):null,wa?r.jsx("button",{type:"button",className:"amx-btn",onClick:()=>{if(Xs&&Cn&&ns){Qr({run_id:ns,span_id:Cn,assertion:U});return}Ri&&mn&&Qr({run_id:mn,assertion:U})},children:"Open transcript"}):null]}):null]},ae)})})]}),r.jsxs("div",{className:"amx-panel",children:[r.jsx("h3",{children:"Transcript"}),r.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?r.jsxs("div",{style:{marginBottom:12},children:[r.jsx("div",{className:"amx-small",style:{marginBottom:6,opacity:.85},children:"spans"}),r.jsx("div",{className:"amx-list",style:{maxHeight:320},children:ai.slice(0,60).map(U=>r.jsxs("div",{className:"amx-item",style:{display:"flex",justifyContent:"space-between",gap:10,alignItems:"center"},children:[r.jsxs("div",{style:{minWidth:0},children:[r.jsxs("div",{className:"amx-mono",style:{fontSize:11,opacity:.95},children:["span:",U.span_id]}),r.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?r.jsx("button",{type:"button",className:"amx-btn",onClick:()=>Qr({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?r.jsxs("div",{style:{marginBottom:12},children:[r.jsx("div",{className:"amx-small",style:{marginBottom:6,opacity:.85},children:"runs (fallback)"}),r.jsx("div",{className:"amx-list",style:{maxHeight:240},children:Ei.slice(0,40).map(U=>r.jsxs("div",{className:"amx-item",style:{display:"flex",justifyContent:"space-between",gap:10,alignItems:"center"},children:[r.jsxs("div",{style:{minWidth:0},children:[r.jsxs("div",{className:"amx-mono",style:{fontSize:11,opacity:.95},children:["run:",U.run_id]}),r.jsxs("div",{className:"amx-small",children:["assertions=",U.count,U.last_observed_at_fmt?` · last=[${U.last_observed_at_fmt}]`:""]})]}),r.jsx("button",{type:"button",className:"amx-btn",onClick:()=>Qr({run_id:U.run_id,assertion:U.assertion}),children:"Open transcript"})]},U.run_id))})]}):null,!ai.length&&!(S&&Ei.length)?r.jsx("div",{className:"amx-small",children:"(no provenance)"}):null]})]})]})}function al({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 r.jsx("div",{className:`modal_backdrop${u?" fullscreen":""}`,onMouseDown:c=>{c.target===c.currentTarget&&l()},children:r.jsxs("div",{className:`modal_panel${u?" fullscreen":""}`,children:[r.jsxs("div",{className:"modal_header",children:[r.jsx("div",{className:"modal_title",children:t}),r.jsx("button",{className:"btn",onClick:l,children:"Close"})]}),r.jsx("div",{className:"modal_body",children:n}),i?r.jsx("div",{className:"modal_footer",children:i}):null]})})}function sp(e,t="session"){const n=String(e||"").trim().toLowerCase();return n==="run"||n==="session"||n==="global"||n==="all"?n:t}function tl(e){const t=typeof e=="string"?e.trim():"";if(!t)return null;const n=t.replace(/(\.\d{3})\d+/,"$1"),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 qM(e){const t=String(e??"").trim();if(!t)return"";if(/^\d{4}\/\d{2}\/\d{2} \d{2}:\d{2}$/.test(t))return t;const n=tl(t);return n!==null?tc(n):t}function Lg(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,`
121
- `).replace(/\\n/g,`
122
- `).replace(/\\t/g," "):""}function Qb(e){return String(e??"").replace(/[*_`~]/g,"")}function rm(e,t){const n=!!(t!=null&&t.strip_punct),i=Lg(e);let o=Qb(i).replace(/\s+/g," ").trim().toLowerCase();return n&&(o=o.replace(/[^\p{L}\p{N}\s]+/gu,"").replace(/\s+/g," ").trim()),o}function sm(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 Ww(e){const t=Lg(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(Qb(t)),n}function HM(e){const t=String(e??"").replace(/\r\n/g,`
123
- `).replace(/\r/g,`
124
- `);if(!t)return null;const n=t.split(`
125
- `);let i;const o=[],l=[];let u=null,c=[],f=!1;const _=()=>{if(!u)return;const y=c.join(`
126
- `).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(`
127
- `).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(`
128
- `)});return w.messages.length?w:null}function qw(e,t){const n=String(e||""),i=String(t||"");return i>n?i:n}function Hw(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 VM(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 GM({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,se]=m.useState([]),[ie,ue]=m.useState(!1),[F,C]=m.useState(!1),[N,P]=m.useState(""),[O,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 Lg(Ge).trim()},[J]),Oe=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:sm(ce,be)},[We,_t]),lt=m.useMemo(()=>{const ce=Oe,be=We;if(!ce||!be)return[];const Ge=[];for(let Ve=0;Ve<Math.min(ce.length,500);Ve++){const rt=ce[Ve],ut=(rt==null?void 0:rt.content)==null?"":String(rt.content);sm(ut,be)&&Ge.push(Ve)}return Ge},[We,Oe]),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=tl(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=tl(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(),rt=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=Hw(jt);if(rt.has(qt))continue;rt.add(qt),ut.push(jt);const dt=String(jt.observed_at||"").trim();dt&&(Et=qw(Et,dt))}E(ut),D(be==null?void 0:be.warnings),ge.current=rt,De.current=Et||Ve},[]),jn=m.useCallback(async ce=>{const be=sp(ce.scope,"session"),Ge=String(ce.subject||"").trim(),Ve=String(ce.predicate||"").trim(),rt=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(),Pt={scope:be,all_owners:_,limit:Bt,order:Yt};Ge&&(Pt.subject=Ge),Ve&&(Pt.predicate=Ve),rt&&(Pt.object=rt),ut&&(Pt.since=ut),Et&&(Pt.until=Et),jt&&(Pt.active_at=jt),qt&&(Pt.query_text=qt),typeof dt=="number"&&(Pt.min_score=dt),_||(be==="run"?Nt&&(Pt.run_id=Nt):be==="session"?pt?Pt.session_id=pt:Nt&&(Pt.run_id=Nt):be==="all"&&(Nt?Pt.run_id=Nt:pt&&(Pt.session_id=pt)));try{const $e=await e.kg_query(Pt),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 sn=await e.kg_query({...Pt,run_id:void 0,session_id:Nt}),$t=Array.isArray(sn==null?void 0:sn.items)?sn.items:[],cr=sn==null?void 0:sn.warnings;return{ok:(sn==null?void 0:sn.ok)!==!1,count:Number((sn==null?void 0:sn.count)||$t.length),items:$t,warnings:cr,raw:sn}}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),P(""),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 rt=[be],ut=typeof((Ve=ce.assertion)==null?void 0:Ve.owner_id)=="string"?String(ce.assertion.owner_id).trim():"";ut&&ut!==be&&rt.push(ut);let Et=null,jt=null;for(const qt of rt)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(rt){const ut=rt instanceof Error?rt.message:String(rt);P(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}),rt=(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(!rt.length)return null;if(rt.length===1)return rt[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 rt.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 Pt=Array.isArray(Nt.messages)?Nt.messages:null;if(Pt){for(const $e of Pt.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]),Cr=m.useCallback(async ce=>{const be=String(ce.run_id||"").trim();if(be){ue(!0),C(!0),P(""),z(be),T(""),K("run_input"),ne(`transcript run:${be}`),oe(null),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),rt=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)),rt&&typeof rt=="object"&&!Array.isArray(rt)){const Et=rt.context,qt=(Et&&typeof Et=="object"&&Array.isArray(Et.messages)?Et.messages:null)||(Array.isArray(rt.messages)?rt.messages:null);Array.isArray(qt)&&(ut.messages=qt);const dt=["text","prompt","task","message"];for(const Yt of dt){const Bt=rt[Yt];if(typeof Bt=="string"&&Bt.trim()){ut.note=Bt.trim();break}}ut.input_data=rt}!ut.messages&&!ut.note&&(ut.note=JSON.stringify(rt??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);P(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 lr=m.useCallback(async ce=>{const be=sp(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]),Cs=m.useCallback((ce,be)=>{var Ge;if((be==null?void 0:be.kind)==="live query"){const Ve=Dt.current;Ve&&(Ke.current={scope:sp(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=Hw(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=qw(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}),se(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();se(Ge=>Ge.filter(Ve=>Ve.expires_at_ms>be))},250);return()=>window.clearInterval(ce)},[X.length]),r.jsxs("div",{className:"mindmap_root",children:[r.jsxs("div",{className:"mindmap_bar",children:[r.jsx("button",{className:"btn",onClick:()=>void Kn(),disabled:Z,children:Z?"Loading…":"Load snapshot"}),r.jsxs("label",{className:"field_inline",children:[r.jsx("span",{className:"mono muted",children:"source"}),r.jsxs("select",{value:c,onChange:ce=>{const be=String(ce.target.value||"").trim();(be==="all"||be==="global"||be==="session"||be==="run")&&f(be)},children:[r.jsx("option",{value:"all",children:"all memory"}),r.jsx("option",{value:"global",children:"global"}),r.jsx("option",{value:"session",children:"session"}),r.jsx("option",{value:"run",children:"run"})]})]}),r.jsxs("label",{className:"field_inline",children:[r.jsx("span",{className:"mono muted",children:"live"}),r.jsx("input",{type:"checkbox",checked:p,onChange:ce=>w(!!ce.target.checked)})]}),c==="session"?r.jsxs("label",{className:"field_inline",children:[r.jsx("span",{className:"mono muted",children:"session_id"}),r.jsx("input",{className:"mono",value:l,onChange:ce=>u(String(ce.target.value||"")),placeholder:"(required)"})]}):null,c==="run"?r.jsxs("label",{className:"field_inline",children:[r.jsx("span",{className:"mono muted",children:"run_id"}),r.jsx("input",{className:"mono",value:i,onChange:ce=>o(String(ce.target.value||"")),placeholder:"(required)"})]}):null,r.jsxs("details",{className:"mindmap_details",children:[r.jsx("summary",{className:"mono muted",children:"advanced"}),r.jsx("div",{className:"mindmap_advanced",children:r.jsxs("div",{className:"field_inline",children:[r.jsx("span",{className:"mono muted",style:{width:84},children:"poll_ms"}),r.jsx("input",{type:"number",min:250,max:6e4,step:50,value:y,onChange:ce=>x(Math.max(250,Number(ce.target.value||0)||750))}),r.jsx("span",{className:"mono muted",children:"highlight_ms"}),r.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?r.jsx("div",{className:"mindmap_error mono",children:M}):null,r.jsxs("div",{className:"mindmap_explorer",children:[r.jsx(WM,{title:"mindmap",resetKey:Qt,queryMode:"replace",items:Dn,warnings:L,onQuery:lr,onItemsReplace:Cs,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(),rt=typeof be=="string"?String(be).trim():"";Ve&&(rt?Ln({run_id:Ve,span_id:rt,assertion:Ge}):Cr({run_id:Ve,assertion:Ge}))}},Qt),X.length?r.jsxs("div",{className:"mindmap_recent mindmap_overlay mindmap_overlay_recent",children:[r.jsx("div",{className:"mindmap_recent_title mono muted",children:"new assertions"}),r.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=>r.jsx("div",{className:"mindmap_recent_item mono",children:VM(ce.assertion)},ce.id))})]}):null,It?r.jsx("div",{className:"mindmap_timeline mindmap_overlay mindmap_overlay_timeline",children:r.jsxs("div",{className:"mindmap_timeline_row",children:[r.jsx("div",{className:"mindmap_timeline_label mono muted",children:tc(Math.min(typeof Mt=="number"?Mt:It.max_ms,It.real_max_ms))}),r.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)}}),r.jsxs("div",{className:"mindmap_timeline_counts mono muted",children:[Dn.length.toLocaleString(),"/",$.length.toLocaleString()]})]})}):null]}),r.jsxs(al,{open:ie,title:O||"source",onClose:()=>{ue(!1)},children:[F?r.jsx("div",{className:"mono muted",children:"Loading…"}):null,N?r.jsx("div",{className:"mindmap_error mono",children:N}):null,!F&&!N?r.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(),rt=tc(tl(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 r.jsxs("div",{className:"source_header",children:[r.jsxs("div",{className:"mono source_triple",title:`${be} --${Ge}--> ${Ve}`,children:[be," ",r.jsxs("span",{className:"muted",children:["—",Ge,"→"]})," ",Ve," ",rt?r.jsxs("span",{className:"muted",children:["[",rt,"]"]}):null]}),Et?r.jsxs("div",{className:"source_evidence",children:[r.jsx("div",{className:"mono muted",style:{fontSize:11,marginBottom:6},children:"evidence_quote"}),r.jsx("pre",{className:"mono source_evidence_quote",children:Et}),jt?r.jsxs("details",{className:"source_evidence_more",children:[r.jsx("summary",{className:"mono muted",children:"original_context"}),r.jsx("pre",{className:"mono source_evidence_quote",children:jt})]}):null]}):null]})})(),r.jsxs("div",{className:"mono muted",style:{marginBottom:10},children:["run_id=",B," · ",Q==="artifact"?`span_id=${G}`:"source=input_data"]}),r.jsxs("div",{className:"source_actions",children:[Se!==null?r.jsx("button",{className:"btn",onClick:()=>Le(Se),children:"Jump to evidence"}):null,Se===null&&et?r.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=Oe,Ve=_t,rt=be&&typeof be.created_at=="string"?String(be.created_at):"",ut=rt?tl(rt):null,Et=ut!==null?tc(ut):rt,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?tl(qt):null,Bt=dt?tl(dt):null,Nt=Yt!==null&&Bt!==null?`${tc(Yt)} → ${tc(Bt)}`:"";if(Ve){const pt=HM(Ve);if(pt){const Pt=We,$e=Pt?pt.messages.findIndex($t=>sm($t.content,Pt)):-1,Wt=Pt?Ww(Pt):[],Ct=pt.created_at||rt,sn=Ct?qM(Ct):rt?Et:"";return r.jsx("div",{className:"source_chat",children:pt.messages.map(($t,cr)=>{const ur=$t.role,Jr=!!(Pt&&sm($t.content,Pt)),$r=ur==="user"?"USER":ur==="assistant"?"ASSISTANT":"SYSTEM";return r.jsxs("div",{id:cr===$e?"source_note_msg_hit_0":void 0,className:`source_msg source_${ur} ${Jr?"source_match":""}`,children:[r.jsxs("div",{className:"source_msg_meta mono muted",children:[r.jsxs("span",{children:["#",cr+1," · ",$r,Jr?r.jsx("span",{className:"source_match_badge",children:"evidence"}):null]}),sn?r.jsx("span",{title:Ct||"",children:sn}):null]}),r.jsx("div",{className:"source_msg_body",children:r.jsx(Ni,{text:$t.content,highlights:Jr&&Wt.length?Wt:void 0,highlightClassName:"source_note_hit",highlightId:cr===$e?"source_note_hit_0":void 0})})]},`note_msg:${cr}`)})})}return r.jsxs("div",{className:"source_note",children:[rt?r.jsx("div",{className:"mono muted",style:{marginBottom:10},children:r.jsxs("span",{title:rt,children:["created_at=",Et]})}):null,r.jsx(Ni,{text:Ve,highlights:We?Ww(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 Pt=Array.from(pt.entries()).sort(($e,Wt)=>Wt[1]-$e[1]||$e[0].localeCompare(Wt[0])).map(([$e,Wt])=>`${$e}×${Wt}`).join(" · ");return r.jsxs("div",{className:"source_chat",children:[rt?r.jsxs("div",{className:"mono muted",style:{marginBottom:10},children:[r.jsxs("span",{title:rt,children:["created_at=",Et]})," · messages=",Ge.length]}):null,Nt?r.jsxs("div",{className:"mono muted",style:{marginBottom:10},children:["span=",Nt]}):null,Pt?r.jsxs("div",{className:"mono muted",style:{marginBottom:10},children:["participants: ",Pt]}):null,Ge.slice(0,200).map(($e,Wt)=>{var fs,Xr;const Ct=typeof($e==null?void 0:$e.role)=="string"?String($e.role):"unknown",sn=($e==null?void 0:$e.content)==null?"":String($e.content),$t=typeof($e==null?void 0:$e.timestamp)=="string"?String($e.timestamp):"",cr=$t?tl($t):null,ur=cr!==null?tc(cr):$t,Jr=typeof($e==null?void 0:$e.message_id)=="string"?String($e.message_id):typeof((fs=$e==null?void 0:$e.metadata)==null?void 0:fs.message_id)=="string"?String($e.metadata.message_id):typeof((Xr=$e==null?void 0:$e.metadata)==null?void 0:Xr.id)=="string"?String($e.metadata.id):"",$r=Ye.has(Wt);return r.jsxs("div",{id:`source_msg_${Wt}`,className:`source_msg source_${Ct} ${$r?"source_match":""}`,children:[r.jsxs("div",{className:"source_msg_meta mono muted",children:[r.jsxs("span",{children:["#",Wt+1," · ",Ct,$r?r.jsx("span",{className:"source_match_badge",children:"evidence"}):null,Jr?r.jsx("span",{className:"source_msg_id",children:Jr}):null]}),$t?r.jsx("span",{title:$t,children:ur}):null]}),r.jsx("div",{className:"source_msg_body",children:r.jsx(Ni,{text:sn})})]},Wt)})]})}return r.jsx("pre",{className:"mono source_raw",style:{whiteSpace:"pre-wrap",wordBreak:"break-word"},children:(typeof ce=="string"?ce:fe)||"(empty)"})})()]}):null]})]})}const ip=4;function KM(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 Vw(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 YM(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(Vw).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(Vw).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,ip),questions_total:n.length,problems:i.slice(0,ip),problems_total:i.length,lessons:l.slice(0,ip),lessons_total:u}}function op(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 Gw={review:"Review",working:"Working",pending:"Pending",done:"Done"},JM={review:"nothing needs you",working:"idle",pending:"nothing scheduled",done:"no recent runs"},XM={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 ZM(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 QM(e){const t=Uu(e);return t==="tool_approval"||t==="user_response"}function Kw(e,t=Date.now()){const n=ZM(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:xx(e),tool_names:o.map(u=>String((u==null?void 0:u.name)||"tool")).filter(Boolean),wait_key:String((i==null?void 0:i.wait_key)||"").trim(),allow_free_text:(i==null?void 0:i.allow_free_text)!==!1,prompt:String((i==null?void 0:i.prompt)||"").trim(),since_ms:l,duration_ms:ug(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:tx(e),automation_id:cf(e)==="occurrence"?String((e==null?void 0:e.automation_id)||"").trim():""}}function eR(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)||by(u)||QM(u)&&(l.add(c),i.review.push(Kw(u,n)))}for(const u of e||[]){const c=String((u==null?void 0:u.run_id)||"").trim();if(!u||!c||l.has(c)||by(u))continue;const f=Kw(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 Zp={"12h":12*36e5,"24h":24*36e5,"48h":48*36e5,"72h":72*36e5,"7d":7*864e5,"14d":14*864e5,"1m":30*864e5,all:null},ap={"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"},Yw="48h";function tR(e,t,n=Date.now()){const i=Zp[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 nR(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 rR=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 sR(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 iR(e){const t=String(e||"");return t.length>14?`${t.slice(0,6)}…${t.slice(-6)}`:t}function lp(e){const t=String(e||"").trim();return t.length>72?`${t.slice(0,70)}…`:t}function oR(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 hm(e){return e.toLowerCase().replace(/[_-]+/g," ")}function aR(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:hm(w),phase:w});const y=(_=n[w])==null?void 0:_.spoken_synonyms;if(Array.isArray(y))for(const x of y){const S=hm(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=hm(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 lR=["asleep","sleep","dream"],cR=["rest"],uR=["awake","idle"];function dR(e,t){const n=String(e||"").trim().toLowerCase();if(!n)return"unknown";if(t){const i=hm(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":lR.some(u=>n.includes(u))?t.initial:cR.some(u=>n.includes(u))&&t.phases.includes("personal")?"personal":uR.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 fR=new Set(["visit","work","personal","sleep","paused","resting","stopped","unknown"]),hR=new Set(["visit","work","personal","sleep","paused","resting","stopped","unknown"]);function mR(e){if(!e)return fR;const t=e.phases.filter(n=>hR.has(n));return new Set([...t,"paused","stopped","unknown"])}function _R(e){var Z,Y,X,se,ie,ue;const t=Date.now(),n=m.useMemo(()=>eR(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 Zp?F:Yw}catch{return Yw}}),w=m.useMemo(()=>tR(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",P=N&&!F.wait_key;return r.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:O=>{O.key==="Enter"&&O.target===O.currentTarget&&e.on_open_run(F.run_id)},children:[r.jsxs("div",{className:"mc_card_head",children:[r.jsx("span",{className:"mc_card_title",title:F.workflow,children:oR(F.workflow)}),(()=>{const O=F.failed?"failed":bm({status:F.status,paused:F.paused});return r.jsx("span",{className:`mc_status ${fl(O)}`,children:O==="unknown"?"?":O})})()]}),r.jsxs("div",{className:"mc_card_meta",children:[r.jsx("span",{className:"mono",title:F.run_id,children:iR(F.run_id)}),F.is_subrun?r.jsx("span",{title:"This wait lives in a child run of an agent workflow",children:"subrun"}):null,F.tag?r.jsx("span",{className:"mc_pill","data-tag":F.tag,children:F.tag_label}):null,F.automation_id?r.jsx("button",{type:"button",className:"btn btn_sm",title:"Open this occurrence's automation",onClick:O=>{O.stopPropagation(),e.on_open_automation(F.automation_id)},onKeyDown:O=>O.stopPropagation(),children:"Automation"}):null,F.duration_ms>=0?r.jsx("span",{children:sR(F.duration_ms)}):null,F.tokens_total!==null?r.jsxs("span",{children:[F.tokens_total.toLocaleString()," tk"]}):null,F.tool_calls!==null&&F.tool_calls>0?r.jsxs("span",{children:[F.tool_calls," tools"]}):null]}),F.is_scheduled&&F.schedule_interval?r.jsxs("div",{className:"mc_card_line",children:["every ",F.schedule_interval]}):null,F.failed&&F.error?r.jsx("div",{className:"mc_card_error",title:F.error,children:F.error.length>120?`${F.error.slice(0,118)}…`:F.error}):null,N?r.jsxs("div",{className:"mc_card_review_body",onClick:O=>O.stopPropagation(),onKeyDown:O=>O.stopPropagation(),children:[r.jsx("div",{className:"mc_card_reason",children:F.reason||"Needs a decision"}),F.prompt?r.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?r.jsxs("div",{className:"mc_card_tools",title:"Tool calls awaiting your approval",children:[F.tool_names.slice(0,4).map((O,ne)=>r.jsx("span",{className:"mc_tool_chip mono",children:O},`${O}_${ne}`)),F.tool_names.length>4?r.jsxs("span",{className:"mc_tool_chip",children:["+",F.tool_names.length-4," more"]}):null]}):null,F.since_ms!==null?r.jsxs("div",{className:"mc_card_waiting",children:["waiting ",tf(F.since_ms,t)]}):null,P?r.jsx("div",{className:"mc_card_line",title:"The wait has not registered a wait_key yet — open the run to inspect.",children:"wait key not published yet — open the run"}):null,P?r.jsx("div",{className:"mc_card_actions",children:r.jsx("button",{className:"btn",onClick:()=>e.on_open_run(F.run_id),children:"Open the run →"})}):F.wait_kind==="tool_approval"?r.jsxs("div",{className:"mc_card_actions",children:[r.jsx("button",{className:"btn success",disabled:C,onClick:()=>void M(F,{approved:!0}),children:C?"Resuming…":"Approve"}),r.jsx("button",{className:"btn danger",disabled:C,onClick:()=>void M(F,{approved:!1}),children:"Reject"})]}):r.jsx("div",{className:"mc_card_actions",children:r.jsx("button",{className:"btn primary",onClick:()=>e.on_open_run(F.run_id),children:"Review & answer →"})})]}):null]},F.run_id)}return r.jsxs("div",{className:"page page_scroll mc_page",children:[r.jsxs("div",{className:"mc_health",children:[r.jsx("span",{className:`mc_led ${e.gateway_connected?"ok":"bad"}`,title:e.gateway_connected?"Gateway connected":"Gateway unreachable"}),e.gateway_connected?null:r.jsx("span",{className:"mc_health_text",children:"gateway unreachable"}),e.runs_refreshed_at===null?r.jsx("span",{className:"mc_health_text muted mc_loading",children:"loading runs…"}):r.jsxs("div",{className:"mc_stats",children:[r.jsxs("div",{className:`mc_stat ${x?"is_hot":""}`,title:"runs blocked on a human decision (Review column)",children:[r.jsx("span",{className:"mc_stat_value",children:x}),r.jsx("span",{className:"mc_stat_label",children:"need you"})]}),r.jsxs("div",{className:`mc_stat ${S?"is_bad":""}`,title:"failed runs in the Done column",children:[r.jsx("span",{className:"mc_stat_value",children:S}),r.jsx("span",{className:"mc_stat_label",children:"failed"})]}),r.jsxs("div",{className:"mc_stat",title:"runs executing or parked listening",children:[r.jsx("span",{className:"mc_stat_value",children:n.working.length}),r.jsx("span",{className:"mc_stat_label",children:"working"})]})]}),r.jsx("span",{className:"mc_spacer"}),r.jsxs("div",{className:"mc_health_side",children:[y?r.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,r.jsx("button",{className:"btn",onClick:e.on_refresh,disabled:e.refreshing,children:e.refreshing?"Refreshing…":"Refresh"})]})]}),l?r.jsx("div",{className:"mc_error",children:l}):null,e.entities.length||e.entities_error?r.jsxs("div",{className:"mc_entities",children:[r.jsxs("div",{className:"mc_entities_head",children:[r.jsxs("span",{children:["Entities",e.entities_total>e.entities.length?` (${e.entities.length} of ${e.entities_total} — open the entity app for all)`:""]}),r.jsx("a",{className:"mc_entity_link",href:e.entity_app_href,target:"_blank",rel:"noreferrer",children:"open the entity app →"})]}),e.entities_error?r.jsx("div",{className:"muted",children:e.entities_error}):null,r.jsx("div",{className:"mc_entities_row",children:e.entities.map(F=>r.jsxs("div",{className:"mc_entity_cell",children:[r.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:[r.jsx("span",{className:"mc_entity_name",children:F.name}),(()=>{var z;const C=String(F.live_phase||F.state||"").trim(),N=dR(C,e.phase_graph),P=mR(e.phase_graph).has(N)?N:"other",O=((z=e.phase_graph)==null?void 0:z.initial)??"sleep",ne=/awake|idle/i.test(C)&&N===O,B=C&&C.toLowerCase()!==N?` — wire word: ${C}${ne?" (settling)":""}`:"";return r.jsx("span",{className:`mc_entity_phase mc_phase_${P}`,title:(F.live_phase?"phase (cognition wire)":"phase from card state — cognition wire unavailable")+B,children:N})})(),F.last_moment?r.jsx("span",{className:"mc_entity_moment",title:F.last_moment,children:F.last_moment.replace(/_/g," ")}):null,(()=>{if(F.working===!0)return r.jsx("span",{className:"mc_entity_live",title:"busy now (loop mid-day or live visit — store-read, never fabricated)",children:"● busy"});const C=nR(F.last_moment_at,t);return F.working===!1?r.jsxs("span",{className:"mc_entity_live muted",title:"idle (cognition wire)",children:["idle",C!==null?` · ${tf(t-C,t)} ago`:""]}):C===null?null:C<=rR?r.jsx("span",{className:"mc_entity_live",title:`last moment ${tf(t-C,t)} ago`,children:"● active"}):r.jsxs("span",{className:"mc_entity_live muted",title:"time since the last recorded moment",children:[tf(t-C,t)," ago"]})})(),F.tokens_total!==null?r.jsxs("span",{className:"muted mc_entity_spend",title:`lifetime billed tokens (home run ledger)${F.live_visit_tokens!==null?`; open visit: ${op(F.live_visit_tokens)} tk`:""}${F.spend_warning?`; ${F.spend_warning}`:""}`,children:[op(F.tokens_total)," tk",F.live_visit_tokens!==null?` (+${op(F.live_visit_tokens)})`:"",F.spend_warning?"*":""]}):null]}),F.open_questions_total||F.open_problems_total||F.lessons_total||F.dreams_brief?r.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(P=>P.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 P=>{const O=await e.on_read_diary(F.name,P);L({entity:F.name,entry:(O==null?void 0:O.entry)??O,seq:typeof(O==null?void 0:O.read_recorded_at_seq)=="number"?O.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 r.jsxs("div",{className:"mc_entity_hints_panel",children:[F.open_questions.map((P,O)=>r.jsx(k_,{kind:"question",label:P.title||lp(P.statement),entryId:P.entry_id,onOpen:C,title:P.statement||P.title},`q_${P.record_id||O}`)),F.open_problems.map((P,O)=>r.jsx(k_,{kind:"problem",label:P.title||lp(P.statement),entryId:P.entry_id,onOpen:C,title:P.statement||P.title},`p_${P.record_id||O}`)),F.lessons.map((P,O)=>r.jsx(k_,{kind:"lesson",label:P.title||lp(P.statement),entryId:P.entry_id,onOpen:C,title:P.statement||P.title},`l_${P.record_id||O}`)),F.dreams_brief?r.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?r.jsxs("span",{className:"muted mc_entity_hints_more",children:["+",N," more — open the entity app"]}):null]})})()]}):null,E?r.jsx(al,{open:!0,title:`${E.entity} — diary entry`,onClose:()=>L(null),children:r.jsxs("div",{className:"mc_diary_entry",children:[r.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}`:"",(se=E.entry)!=null&&se.entry_id?`id: ${E.entry.entry_id}`:""].filter(Boolean).join(" · ")}),r.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?r.jsx("div",{className:"mc_diary_gist",children:String(E.entry.gist)}):null,r.jsx("pre",{className:"mc_diary_text",children:String(((ue=E.entry)==null?void 0:ue.text)||"(entry carries no text)")})]})}):null,r.jsx("div",{className:"mc_board",children:Object.keys(Gw).map(F=>{const C=F==="done"?w.visible:n[F],N=F==="done"&&!c?C.slice(0,8):C;return r.jsxs("div",{className:`mc_column mc_column_${F}`,children:[r.jsxs("div",{className:"mc_column_head",children:[r.jsx("span",{className:"mc_column_title",children:Gw[F]}),F==="done"?r.jsx("select",{className:"mc_window_select",value:_,title:"Show terminal runs from this time window",onClick:P=>P.stopPropagation(),onChange:P=>{const O=P.target.value;p(O),f(!1);try{localStorage.setItem("abstractobserver_done_window_v1",O)}catch{}},children:Object.keys(Zp).map(P=>r.jsx("option",{value:P,children:ap[P]},P))}):null,r.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})]}),r.jsx("div",{className:"mc_column_hint muted",children:XM[F]}),r.jsxs("div",{className:"mc_column_cards",children:[N.map(P=>H(P)),C.length?null:r.jsx("div",{className:"mc_empty muted",children:e.runs_refreshed_at===null?"loading…":F==="done"&&w.hidden_count?`none in the ${ap[_]} — ${w.hidden_count} older`:JM[F]}),F==="done"&&C.length>8&&!c?r.jsxs("button",{className:"btn mc_more",onClick:()=>f(!0),children:["show all ",C.length]}):null,F==="done"&&w.hidden_count&&C.length?r.jsxs("div",{className:"mc_window_note muted",title:"Widen the window above to see older terminal runs",children:["+",w.hidden_count," older outside ",ap[_]]}):null]})]},F)})})]})}function Jw(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 Xw(e){const t=e.disabled===!0,n=m.useMemo(()=>Jw(e.options||[]),[e.options]),i=m.useMemo(()=>Jw(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 r.jsxs("div",{className:"multi_select",children:[r.jsxs("div",{className:"multi_select_row",children:[r.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)"]}),r.jsx("button",{className:"btn",type:"button",onClick:()=>e.onChange(n.slice()),disabled:t||!n.length||i.length===n.length,title:"Select all",children:"All"}),r.jsx("button",{className:"btn",type:"button",onClick:()=>e.onChange([]),disabled:t||i.length===0,title:"Clear selection",children:"Clear"})]}),i.length>0?r.jsx("div",{className:"multi_select_chips",children:i.map(w=>r.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:r.jsx("span",{className:"multi_select_chip_x",children:"×"})]},w))}):null,o?r.jsxs("div",{className:"multi_select_panel",children:[r.jsx("input",{className:"mono",value:u,onChange:w=>c(String(w.target.value||"")),placeholder:"filter…",disabled:t}),r.jsxs("div",{className:"multi_select_list",style:{maxHeight:`${p}px`},children:[f.map(w=>{const y=_.has(w);return r.jsxs("label",{className:`multi_select_item mono ${y?"checked":""}`,children:[r.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()))}}),r.jsx("span",{children:w})]},w)}),f.length?null:r.jsx("div",{className:"mono muted",children:"(no matches)"})]})]}):null]})}function pR(){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 gR(){if(typeof window>"u")return!1;const e=window;return!!(e!=null&&e.AudioContext||e!=null&&e.webkitAudioContext)}function yR(){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 wR(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 vR(e){const t=P=>{var O;return(O=e.on_error)==null?void 0:O.call(e,P)},n=m.useMemo(()=>gR(),[]),i=m.useMemo(()=>pR(),[]),[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 P=globalThis,O=(P==null?void 0:P.AudioContext)||(P==null?void 0:P.webkitAudioContext);if(!O)return null;if(!f.current){const z=new O,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 P=p.current;if(p.current=null,!!P){try{P.onended=null}catch{}try{P.stop()}catch{}try{P.disconnect()}catch{}}},$=()=>{b(),c.current="",u.current="",w.current=null,y.current=0,x.current=0,l({key:"",status:"idle"})};m.useEffect(()=>()=>{var P,O;$();try{(P=_.current)==null||P.disconnect()}catch{}try{(O=f.current)==null||O.close()}catch{}f.current=null,_.current=null,w.current=null},[]);const E=async(P,O,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=O,T.connect(G);const Q=Number.isFinite(Number(O.duration))?Number(O.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=P,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:P,status:"playing"})},L=async(P,O)=>{const ne=String(P||"").trim(),B=String(O||"").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:Or()}),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 wR(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),se=m.useRef([]),ie=m.useRef("");function ue(){var P,O;try{(O=(P=Y.current)==null?void 0:P.getTracks)==null||O.call(P).forEach(ne=>{try{ne.stop()}catch{}})}catch{}Y.current=null}m.useEffect(()=>()=>{var P,O;try{(O=(P=X.current)==null?void 0:P.stop)==null||O.call(P)}catch{}X.current=null,ue()},[]);async function F(P,O){var G;if(t==null||t(""),!P||!P.size||H)return;const ne=e.gateway,B=String(e.session_id||"").trim(),z=String(e.run_id||"").trim();if(!ne){t==null||t("Connect to the gateway first.");return}if(!B){t==null||t("Voice input unavailable (missing session_id).");return}if(!z){t==null||t("Voice input unavailable (missing run_id).");return}Z(!0);try{const T=String(O||P.type||"").toLowerCase(),Q=T.includes("mp4")?"m4a":T.includes("ogg")?"ogg":T.includes("wav")?"wav":"webm",K=new File([P],`recording.${Q}`,{type:T||"audio/webm"}),J=await ne.attachments_upload(B,K,{filename:K.name,content_type:K.type}),oe=await ne.audio_transcribe(z,{audio_artifact:J,request_id:Or()}),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)){se.current=[];try{const P=await navigator.mediaDevices.getUserMedia({audio:!0});Y.current=P;const O=yR();ie.current=O;const ne=O?new MediaRecorder(P,{mimeType:O}):new MediaRecorder(P);X.current=ne,ne.ondataavailable=B=>{try{B!=null&&B.data&&se.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(se.current,{type:ie.current||""});F(B,ie.current)}catch(B){t==null||t(String((B==null?void 0:B.message)||B||"Failed to build recording"))}},ne.start(),M(!0)}catch(P){ue(),X.current=null,M(!1);const O=String((P==null?void 0:P.message)||P||"Failed to access microphone");t==null||t(O.toLowerCase().includes("permission")?`Microphone permission denied: ${O}`:O)}}}function N(){const P=X.current;if(!(!D||!P)){X.current=null,M(!1);try{P.stop()}catch(O){t==null||t(String((O==null?void 0:O.message)||O||"Failed to stop recording"))}}}return m.useEffect(()=>{if(!D)return;const P=()=>N();return window.addEventListener("pointerup",P),window.addEventListener("pointercancel",P),()=>{window.removeEventListener("pointerup",P),window.removeEventListener("pointercancel",P)}},[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 im=500,Im="http://127.0.0.1:8080";function Zw(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 cp(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 up(e){const t=String(e||"").trim();return t.startsWith("abstract.")||t.startsWith("abstractcode.")}function xR(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 bR(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 dp(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 jR=/^[a-zA-Z0-9_-]+$/;function Qw(e){return jR.test(String(e||"").trim())}async function SR(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 ev(e){const t=String(e||"").trim();if(!t)throw new Error("session_id is required");if(Qw(t)){const i=`session_memory_${t}`;if(Qw(i))return i}return`session_memory_sha_${(await SR(t)).slice(0,32)}`}const tv=new Set(["abstract.status","abstract.summary","abstract.chat"]);function kR(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!tv.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&&tv.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!!Sf(e.data)}function NR(){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)||Im),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:Im,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 CR(e){localStorage.setItem("abstractobserver_settings",JSON.stringify({...e,auth_token:""}))}function $R(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 nv(e){const t=$R(e.metadata);return t.length?r.jsx("div",{className:"runtime_metadata_chips","aria-label":"Runtime metadata",children:t.map(n=>r.jsxs("span",{className:"chip mono muted",children:[n.label,": ",n.value]},`${n.label}:${n.value}`))}):null}function AR(){return typeof window>"u"?"":rN(window.location)}function ER(){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 TR(){var Kl,Yl,Lr,Gi,qs,Vr,Od,hu,mu,$h,Ki,Dd,_u;const[e,t]=m.useState("board"),[n,i]=m.useState(()=>NR()),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(()=>AR()),[x,S]=m.useState(""),[b,$]=m.useState(""),[E,L]=m.useState("{}"),[D]=m.useState(()=>ER()),[M,H]=m.useState(null),[Z,Y]=m.useState(!1),[X,se]=m.useState(""),[ie,ue]=m.useState(!1),[F,C]=m.useState(""),[N,P]=m.useState(!1),O=kj({appName:"AbstractObserver",variant:"dismissable",defaultGatewayUrl:typeof window<"u"&&((Lr=window.__ABSTRACT_UI_CONFIG__)==null?void 0:Lr.gateway_url)||Im,onStatusChange:g=>Bs(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(Np),[We,_t]=m.useState([]),[Oe,et]=m.useState(null),[lt,Ye]=m.useState(!1),[Se,Le]=m.useState([]),ct=m.useRef(new _N(Or)),[ge,De]=m.useState({available:!1,reason:"Sign in to a gateway to use automations."}),[Ke,Dt]=Vj("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,Cr]=m.useState(null),[Kn,lr]=m.useState([]),[Cs,Yn]=m.useState(0),[ce,be]=m.useState(""),Ge=m.useRef(!1),Ve=m.useRef(0),rt=m.useRef(0),[ut,Et]=m.useState(!1),[jt,qt]=m.useState([]),[dt,Yt]=m.useState([]),[Bt,Nt]=m.useState({}),[pt,Pt]=m.useState(!1),[$e,Wt]=m.useState(!1),[Ct,sn]=m.useState(!1),[$t,cr]=m.useState([]),[ur,Jr]=m.useState([]),$r=m.useRef(0),fs=m.useRef(null);fs.current||(fs.current=new Uy(g=>window.setTimeout(g,40),g=>cr(k=>k.concat(g))));const Xr=m.useRef(null);Xr.current||(Xr.current=new Uy(g=>window.setTimeout(g,40),g=>Jr(k=>k.concat(g))));const no=m.useRef({scanned:0,found:null}),[xe,Jn]=m.useState(null),[hn,ro]=m.useState(""),[$i,$s]=m.useState(!1),hs=m.useRef(null),[Ks,it]=m.useState({}),[tn,gr]=m.useState({}),[oi,dr]=m.useState(!1),[so,io]=m.useState(""),[pa,Fn]=m.useState(!0),[ms,Tn]=m.useState(""),[_s,oo]=m.useState(!1),[Qn,Zr]=m.useState(!1),[fr,Ys]=m.useState(6),[yr,ga]=m.useState("standard"),[ao,nn]=m.useState(""),[ml,Ai]=m.useState(""),[ps,Ar]=m.useState(!1),[ya,As]=m.useState(!1),[ai,Ei]=m.useState("pause"),[Qr,Er]=m.useState(""),[Es,es]=m.useState(""),[Ti,gs]=m.useState(""),wr=m.useRef(null),Mi=m.useRef(null),[Ro,_l]=m.useState(!1),ts=m.useRef(null),[Lo,Js]=m.useState(""),[_c,ys]=m.useState(""),[lo,zr]=m.useState(""),[Io,Po]=m.useState(""),[Oo,co]=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),[vr,Rt]=m.useState(""),[rn,Cn]=m.useState(""),[mn,er]=m.useState(""),[ns,Xs]=m.useState([]),[Ri,wa]=m.useState(!1),[$f,pc]=m.useState(""),[pl,gc]=m.useState(""),[yc,wc]=m.useState(!1),[Af,Do]=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(()=>ns.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}}),[ns]);m.useEffect(()=>{o&&u1()},[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({}),[Ym,Ef]=m.useState({}),[vc,en]=m.useState(""),[Ju,Jm]=m.useState(""),[Xu,Xm]=m.useState("all"),[Zu,Zm]=m.useState("status"),[tr,Br]=m.useState("overview"),[gl,Tf]=m.useState(!0),[va,xc]=m.useState("steps"),[Mf,Qu]=m.useState(""),[uo,ed]=m.useState(""),[Rf,bc]=m.useState([]),[td,nd]=m.useState(!1),[yl,fo]=m.useState(""),[Lf,xa]=m.useState(""),[Qm,jc]=m.useState([]),[rd,Sc]=m.useState(!1),[If,kc]=m.useState(""),[Pf,sd]=m.useState(!1),[e_,t_]=m.useState(""),[n_,ba]=m.useState(""),[Ts,ho]=m.useState(""),[Of,wl]=m.useState(!1),[Fo,ja]=m.useState(""),[mo,vl]=m.useState(null),[Nc,_o]=m.useState({}),[Cc,Li]=m.useState(!1),[$c,Sa]=m.useState(""),[zo,ka]=m.useState(!1),[Ac,Df]=m.useState(!1),[Ec,xl]=m.useState(()=>Date.now()),[li,Bo]=m.useState(""),[Ff,bl]=m.useState({}),[zf,ci]=m.useState({}),Uo=m.useRef([]),rs=m.useRef(null),po=m.useRef(""),Tc=m.useRef({}),ui=m.useRef({}),id=m.useRef({}),Na=m.useRef(new Set),[di,pn]=m.useState([]),Wo=m.useRef(""),Ii=m.useRef({}),Ms=m.useRef(null),Ur=m.useRef(null),Pi=m.useRef(0),fi=m.useRef({}),qo=m.useRef(!1),Rs=m.useRef(new Set),[Mc,Rc]=m.useState(""),[hi,Oi]=m.useState(""),ws=m.useRef(""),[jl,Sl]=m.useState(!1),[od,Ca]=m.useState(""),Lc=()=>({artifact_id:"",kind:"binary",render_kind:"",text:"",url:"",loading:!1,error:""}),[kl,ad]=m.useState("activity"),[ld,Bf]=m.useState([]),[Ic,Di]=m.useState(0),[Uf,Ho]=m.useState(0),[mi,$a]=m.useState({}),[Fi,Pc]=m.useState({}),[r_,Wf]=m.useState(!1),[Vo,Aa]=m.useState(""),[_i,Oc]=m.useState(""),[Go,go]=m.useState("all"),[Zs,Sn]=m.useState(""),[on,yo]=m.useState([]),[nr,ss]=m.useState("all"),[Ls,Ea]=m.useState("type"),[xr,Dc]=m.useState("newest"),[zi,cd]=m.useState(""),[wo,Ta]=m.useState(""),[pi,Ma]=m.useState(""),[Ko,Fc]=m.useState(0),[Ra,gi]=m.useState(()=>Lc()),[La,vo]=m.useState(!1),[Nl,zc]=m.useState(""),[Is,br]=m.useState(""),[Un,Ps]=m.useState(""),[Qs,Yo]=m.useState("text"),[qf,Cl]=m.useState(null),[ud,Tr]=m.useState(!1),[is,vn]=m.useState(""),[Os,dd]=m.useState(""),[Hf,Bc]=m.useState(""),[Uc,fd]=m.useState(!1),[Wc,hd]=m.useState(""),[Bi,md]=m.useState("run_ledger"),[s_,$l]=m.useState(""),[qc,Hc]=m.useState([]),[Vf,xo]=m.useState(""),[Gf,Al]=m.useState(!1),[Vc,bo]=m.useState(""),Pe=m.useMemo(()=>new z_({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]),rr=m.useMemo(()=>new AN(Pe.automations_client(),NN(Pe,Or,xt)),[Pe]),Gc=m.useSyncExternalStore(g=>rr.subscribe(g),()=>rr.state);m.useEffect(()=>{const g=()=>{const k=dN(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]),Ia=m.useMemo(()=>QN(),[]),[Ds,jo]=m.useState([]),Kc=m.useRef(0);function Kf(){const g=++Kc.current;jo([["Gateway","checking…"]]),e1(Pe).then(k=>{g===Kc.current&&jo(k)})}const Fs=m.useMemo(()=>n.worker_url.trim()?new fC({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]),jr=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=jr==null?void 0:jr.inputs;return Array.isArray(g)?g:[]},[jr]),Ui=m.useMemo(()=>bR(mo),[mo]),So=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=Zw(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=jr==null?void 0:jr.node_index;return A&&typeof A=="object"?A:{}},[xe,M,jr]);m.useEffect(()=>{CR(n)},[n]),m.useEffect(()=>()=>{Ms.current&&Ms.current.abort(),Ur.current&&Ur.current.abort(),wr.current&&window.clearTimeout(wr.current),Mi.current&&window.clearTimeout(Mi.current),rs.current&&window.clearTimeout(rs.current),ts.current&&window.clearTimeout(ts.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]),Yf=typeof(at==null?void 0:at.prompt)=="string"?String(at.prompt):"",Jo=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):"",Pa=typeof(at==null?void 0:at.workspace_access_mode)=="string"?String(at.workspace_access_mode):"",Xo=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(`
129
- `):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(`
130
- `):typeof g=="string"?String(g):""},[at]),Oa=So.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(()=>{gr({})},[b,x]),m.useEffect(()=>{at!==null&&it(g=>{const k={};for(const A of So){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]=d1(V)}return k})},[So,at,tn]);const ko=me?{kind:"default",interface:me}:b.trim()&&x.trim()?{kind:"bundle",bundle_id:b.trim(),flow_id:x.trim()}:null,In=iN(ko),vs=Array.isArray(at==null?void 0:at.skills)?at.skills.map(g=>String(g||"").trim()).filter(Boolean):[],xs=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]),Zo=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(),hr=!!(Wn&&N&&!Object.prototype.hasOwnProperty.call(Bt,Wn));m.useEffect(()=>{const g=Jo.trim();if(!g||Bt[g]||Ii.current[g])return;Ii.current[g]=!0;let k=!1;return(async()=>{try{const I=await Pe.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}},[Jo,Bt,Pe]),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 Pe.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,Pe,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 Da(g){const k=String(g||"").trim();if(!k)return se("Missing bundle_id"),null;se(""),Y(!0);try{const A=await Pe.get_bundle(k);return H(A),Jt({ts:xt(),kind:"info",title:`Loaded bundle ${k}`}),A}catch(A){return H(null),se(String((A==null?void 0:A.message)||A||"Failed to load bundle")),null}finally{Y(!1)}}function Qo(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 os(g=Pe,k){if(Ge.current&&!(k!=null&&k.force))return;Ge.current=!0;const A=ta.current;Ln(!0);try{const I=_e=>_e.map(gN).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!==ta.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)),Cr(Date.now()),rt.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))&&O.refresh().catch(()=>{}),/\b429\b/.test(q)||/too many requests/i.test(q)){const W=Math.min(12e4,Math.max(15e3,rt.current*2||15e3));rt.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 Sr(g){var te,Ee,_e;const k=ta.current;P(!0),Nt({});const[A,,I,q,W]=await Promise.allSettled([g.list_bundles(),os(g),g.discovery_tools(),g.discovery_providers({include_models:!1}),g.discovery_capabilities()]);if(k!==ta.current)return;if(A.status==="rejected"&&I.status==="rejected"&&q.status==="rejected"){P(!1),C(dp(A.reason,n)),Jt({ts:xt(),kind:"error",title:"Discovery failed",preview:ht(String(A.reason||""))});return}De(W.status==="fulfilled"?yN(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=Qo(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 ea(g){var k,A;C(""),P(!1),ue(!0);try{if(!(g!=null&&g.prefer_direct)&&(await O.refresh(),Tl.current))return;const I=String(n.auth_token||"").trim();if(!I){g!=null&&g.open_modal_if_needed&&O.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 z_({base_url:q,auth_token:I});await W.list_bundles(),i(V=>({...V,gateway_auth_mode:"direct"})),await Sr(W)}catch(I){C(dp(I,n))}finally{ue(!1)}}const Tl=m.useRef(!1),ta=m.useRef(0),zs=m.useRef(!1);function Bs(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(zs.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),Sr(new z_({base_url:"",auth_token:""})).catch(V=>C(dp(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&&!zs.current&&(zs.current=!0,ea({prefer_direct:!0})))}async function Ml(){if(!(ut||ie)){Et(!0);try{await Pe.reload_bundles();const g=await Pe.list_bundles(),k=Qo(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){$s(!0),en("");try{const A=await Pe.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 Pe.list_bundles(),q=Qo(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{$s(!1);try{hs.current&&(hs.current.value="")}catch{}}}}function Rl(g){ta.current+=1,g!=null&&g.keep_session||(O.signOut().catch(()=>{}),Tl.current=!1),ah(),$(""),S(""),ja(""),H(null),se(""),Y(!1),Bn([]),bn([]),En([]),Cr(null),lr([]),qt([]),Yt([]),Nt({}),C(""),P(!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),Pn("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),Pn("Copied to clipboard",2)}catch{Pn("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 Pe.get_run(g);k||Jn(q)}catch{}};A();const I=window.setInterval(A,2e3);return()=>{k=!0,window.clearInterval(I)}},[pt,c,Pe]),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 os(Pe)}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,Pe]);const[Jf,Qc]=m.useState(null);m.useEffect(()=>{if(!N){Qc(null);return}let g=!1;return(async()=>{try{const k=await Pe.get_entity_phases_spec();if(g)return;const A=aR(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){lr([]),be("");return}let g=!1,k=null;const A=async()=>{if(!(Ve.current>Date.now())){try{const I=await Pe.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([Pe.get_entity_card(V),Pe.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=YM(_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:KM(_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||(lr(W),Yn(I.entities.length),be(""))}catch(I){if(!g){lr([]);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,Pe]);async function Xf(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 Pe.submit_command({command_id:Or(),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}}),os(Pe,{force:!0}),window.setTimeout(()=>void os(Pe,{force:!0}),1200)}const Us=m.useMemo(()=>{const g=xe==null?void 0:xe.session_id;return typeof g=="string"?g.trim():g==null?"":String(g||"").trim()},[xe]),na=m.useMemo(()=>{const g=String(Us||"").trim();return g||String(D||"").trim()},[Us,D]);m.useEffect(()=>{if(!N||!na){co(""),Po("");return}(async()=>{try{const g=await ev(na);co(g)}catch{co("")}})()},[N,na]);const qn=vR({gateway:N?Pe:null,session_id:na,run_id:Oo,on_error:Po,on_transcript:g=>{const k=String(g||"").trim();k&&(ys(A=>{const I=String(A||"");return I.trim()?`${I.trimEnd()}
131
- ${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 Fa(){if(!td){if(!N||!Us){ed(""),bc([]),fo("");return}nd(!0),fo("");try{const g=await ev(Us);ed(g);const k=await Pe.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([]),fo("")):(bc([]),fo(k)),ed("")}finally{nd(!1)}}}async function Zf(){const g=Lf.trim();if(!g){Pn("This run recorded no workspace folder",2);return}try{const k=await fetch(tN,{method:"POST",headers:{"Content-Type":"application/json",...bx()},body:JSON.stringify({path:g})}),A=await k.json().catch(()=>({}));k.ok&&(A!=null&&A.ok)?Pn(`Opened ${String(A.path||g)}`,2):Pn(String((A==null?void 0:A.error)||`Folder reveal failed (${k.status})`),3)}catch(k){Pn(String((k==null?void 0:k.message)||k||"Folder reveal failed"),3)}}async function eu(g){const k=String(uo||"").trim();if(!k){Pn("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 Pe.download_run_artifact_content(k,A,{access:"download"});vd(Ee,te),Pn("Downloaded attachment",2)}catch(Ee){Pn(String((Ee==null?void 0:Ee.message)||Ee||"Download failed"),3)}}async function tu(g){const k=String(uo||"").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(t_(V),ba(""),ho(""),sd(!0),typeof te=="number"&&te>1e6){ba(`(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"))){ba(`(Binary attachment: ${Ee||"unknown"}; download to view.)`);return}wl(!0);try{const Ne=await(await Pe.download_run_artifact_content(k,A,{access:"download"})).text(),ze=14e3,qe=Ne.length>ze?`${Ne.slice(0,Math.max(0,ze-1))}…`:Ne;ba(qe)}catch(pe){ho(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){Pn("Artifact download needs a run id",3);return}const I=$p(g)||A;try{const q=await Pe.download_run_artifact_content(k,A,{access:"preview"});vd(q,P_(I)),Pn("Downloaded artifact",2)}catch(q){Pn(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){Pn("Artifact preview needs a run id",3);return}const I=$p(g),q=String((g==null?void 0:g.content_type)||"").trim().toLowerCase(),W=lf(g);if(zc(I||A),br(""),vn(""),Yo(W),Cl(g),vo(!0),Un&&(URL.revokeObjectURL(Un),Ps("")),W==="binary"){br(`(Binary artifact: ${q||"unknown"}; download to view.)`);return}if(W==="text"&&typeof g.size_bytes=="number"&&g.size_bytes>15e5){br(`(Text artifact is ${g.size_bytes.toLocaleString()} bytes; download to view.)`);return}Tr(!0);try{const V=await Pe.download_run_artifact_content(k,A,{access:"preview"});if(W==="text"){const te=await V.text(),Ee=xm(g,te),_e=Ee==="json"?15e5:Ee==="markdown"?25e4:Ee==="html"?3e5:22e3;br(te.length>_e&&Ee!=="text"?`${rc(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 Ps(URL.createObjectURL(V))}catch(V){vn(String((V==null?void 0:V.message)||V||"Preview failed"))}finally{Tr(!1)}}m.useEffect(()=>()=>{Un&&URL.revokeObjectURL(Un)},[Un]);async function Qf(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:`${rc(g.size_bytes)} text artifact. Use Preview for a larger view or Download to inspect locally.`,url:"",loading:!1,error:""};try{const q=await Pe.download_run_artifact_content(A,k,{access:"preview"});if(I==="text"){const W=await q.text(),V=xm(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"?`${rc(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 eh(g){if(Ra.url&&URL.revokeObjectURL(Ra.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 Qf(g))}m.useEffect(()=>{Fa()},[Pe,N,Us]);function Jt(g){const k=String(g.id||"").trim()||Or();Gu(A=>[{...g,id:k},...A].slice(0,800))}function Pn(g,k){gs(g),Mi.current&&window.clearTimeout(Mi.current),_l(!1),window.requestAnimationFrame(()=>_l(!0)),Mi.current=window.setTimeout(()=>{_l(!1),Mi.current=null},1500),wr.current&&(window.clearTimeout(wr.current),wr.current=null),k>0&&(wr.current=window.setTimeout(()=>{gs(""),wr.current=null},Math.max(1,k)*1e3))}function Wr(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 ru(g,k,A){const I=String(g||"").trim(),q=String(k||"").trim(),W=String(A||"").trim();if(!I||!q||!W)return;const V=Wr(I,q);V&&(Tc.current[W]=V,ui.current[W]=I,id.current[W]={parent_run_id:I,parent_node_id:q},Na.current.has(W)||(Na.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=po.current;po.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(Uo.current.push(k),Uo.current.length>8e3){const V=Uo.current.splice(0,1500);for(const te of V)delete W[te]}return W}),rs.current&&window.clearTimeout(rs.current),rs.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),rs.current=null},2200)}function bd(g,k){var Ie,ln,Tt;const A=String(k||"").trim()||c.trim();$r.current=g.cursor,(Ie=fs.current)==null||Ie.push({cursor:g.cursor,record:g.record}),A&&Rs.current.add(`${A}:${g.cursor}`);const I=Hh(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);Pn(He,vt)}const Ne=V?Wr(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&&ru(pe,V,xn)}}if(V&&(Ll(Wr(pe,V)),te==="waiting"||te==="running")){const He=Wr(pe,V);He&&(po.current=He,Bo(He))}let ze="step",qe=Ne||V||"(node?)",Ze="";if(I&&I.name&&up(I.name))ze=q==="abstract.message"?"message":"event",qe=q||I.name,Ze=ht(q==="abstract.steer_seen"?cp(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(Dr(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(Dr(W.result,360)):Ee?Ze=ht(Ee):Ze=ht(lm(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 i_(g,k){var Ze,Ie,ln;Pi.current=Math.max(Pi.current,k.cursor);const A=`${g}:${k.cursor}`;if(!!Rs.current.has(A))return;Rs.current.add(A),(Ze=Xr.current)==null||Ze.push({run_id:g,cursor:k.cursor,record:k.record});const q=Hh(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?Wr(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&&ru(g,te,vt),vt&&ws.current.trim()===String(g||"").trim()&&(ws.current=vt,Oi(vt))}}if(te&&(Ll(Wr(g,te)),_e==="waiting"||_e==="running")){const Tt=Wr(g,te);Tt&&(po.current=Tt,Bo(Tt))}if((_e==="completed"||_e==="failed")&&ws.current.trim()===String(g||"").trim()){const Tt=String(ui.current[String(g||"").trim()]||"").trim();Tt&&Tt!==c.trim()?(ws.current=Tt,Oi(Tt)):(ws.current="",Oi(""))}if(W==="abstract.status"&&g===c.trim()){const{text:Tt,duration:He}=wu(q==null?void 0:q.payload);Pn(Tt,He)}let Ne="step",ze=Ee||te||"(node?)",qe="";if(q&&q.name&&up(q.name))Ne=W==="abstract.message"?"message":"event",ze=`subrun • ${W||q.name}`,qe=ht(W==="abstract.steer_seen"?cp(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(Dr(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(Dr(V.result,360)):pe?qe=ht(pe):qe=ht(lm(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 th(g,k){var Ie,ln,Tt;const A=String(g||"").trim();if(!A)return;const I=`${A}:${k.cursor}`;if(!!Rs.current.has(I))return;Rs.current.add(I),(Ie=Xr.current)==null||Ie.push({run_id:A,cursor:k.cursor,record:k.record});const W=Hh(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?Wr(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&&ru(A,Ee,xn)}}if(Ee&&(Ll(Wr(A,Ee)),pe==="waiting"||pe==="running")){const He=Wr(A,Ee);He&&(po.current=He,Bo(He))}if(V==="abstract.status"&&A===c.trim()){const{text:He,duration:vt}=wu(W==null?void 0:W.payload);Pn(He,vt)}let ze="step",qe=_e||Ee||"(node?)",Ze="";if(W&&W.name&&up(W.name))ze=V==="abstract.message"?"message":"event",qe=`subrun • ${V||W.name}`,Ze=ht(V==="abstract.steer_seen"?cp(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(Dr(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(Dr(te.result,360)):Ne?Ze=ht(Ne):Ze=ht(lm(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 nh(g,k){var I,q;let A=k.after;for(;;){if((I=k.signal)!=null&&I.aborted)return A;const W=await Pe.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 $r.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),Pt(!1),(W=fs.current)==null||W.reset(),(V=Xr.current)==null||V.reset(),no.current={scanned:0,found:null},cr([]),$r.current=0,Jr([]),Rs.current=new Set,Gu([]),Yu({}),Ef({}),xc("steps"),Qu(""),gs(""),Jn(null),Js(""),xa(""),jc([]),kc(""),Bo(""),po.current="",bl({}),ci({}),Uo.current=[],xl(Date.now()),Tc.current=k?{[k]:""}:{},ui.current={},id.current={},Na.current=new Set,pn([]),Wo.current="",ws.current="",Oi(""),fi.current={},rs.current&&window.clearTimeout(rs.current),rs.current=null,ts.current&&window.clearTimeout(ts.current),ts.current=null,Ms.current&&Ms.current.abort(),Ur.current&&Ur.current.abort(),Ur.current=null,Pi.current=0,Rc("");const A=new AbortController;Ms.current=A;let I=!1;try{let _e="",pe="";try{const Ne=await Pe.get_run(k);Jn(Ne);const ze=typeof(Ne==null?void 0:Ne.workflow_id)=="string"?String(Ne.workflow_id):"",qe=Zw(ze);qe&&(_e=qe.bundle_id,pe=qe.flow_id)}catch{}try{const Ne=await Pe.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():"";xa(Ze)}catch{xa("")}(async()=>{Sc(!0),kc("");try{const Ne=await Pe.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),ja(pe),await Da(_e)),await nh(k,{after:0,signal:A.signal});try{const Ne=await Pe.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)Na.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)&&(ws.current=ln,Oi(ln))}catch{}}}catch{}Pt(!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}}),Pt(!1)}finally{Wt(!1)}if(!I||A.signal.aborted)return;(async()=>{let _e=250;for(;!A.signal.aborted;){try{const pe=await nh(k,{after:$r.current,signal:A.signal});await Pe.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=ko,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=(So||[]).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 Pe.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),os(),null}catch(I){const q=String((I==null?void 0:I.message)||I||"start failed");return en(q),q}finally{Wt(!1)}}async function sh(){if(_t([]),et(null),!ge.available){_t([ge.reason]);return}const g=pN(Ae,{choice:ko,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 Pe.automations_client().createAutomation(g.body);ct.current.reset(),Le([]),Be(Np),Jt({ts:xt(),kind:"info",title:"Automation created",preview:ht(`${g.body.title} · ${k.automation_id}`)}),t("automations"),await rr.refresh(),await rr.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 ih(){if(ro(""),oe==="automate"){await sh();return}const g=await rh();if(g){ro(g);return}Br("overview"),t("observe")}async function Pl(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),ja(g.flow_id),await Da(g.bundle_id)}}async function oh(g){const[k,A]=await Promise.all([Pe.get_run(g),Pe.get_run_input_data(g)]),I=SN(k,A);await Pl(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){Pn(`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 ea({open_modal_if_needed:!0}),k)return;Br("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 ah(){var g,k;Ms.current&&Ms.current.abort(),Ms.current=null,Ur.current&&Ur.current.abort(),Ur.current=null,Pi.current=0,Rc(""),f(""),p(""),Tc.current={},ui.current={},id.current={},Na.current=new Set,pn([]),Wo.current="",ws.current="",Oi(""),fi.current={},Js(""),rs.current&&window.clearTimeout(rs.current),rs.current=null,ts.current&&window.clearTimeout(ts.current),ts.current=null,Pt(!1),Wt(!1),sn(!1),$r.current=0,(g=fs.current)==null||g.reset(),(k=Xr.current)==null||k.reset(),no.current={scanned:0,found:null},cr([]),Jr([]),Rs.current=new Set,Jn(null),Gu([]),Yu({}),Bo(""),po.current="",bl({}),ci({}),Uo.current=[],xl(Date.now()),Pn("",-1),en(""),Sl(!1),Ca(""),Ue([]),ot(null),ys(""),zr(""),ae(!1),Ht(!1),Rt(""),Cn(""),er(""),Xs([]),wa(!1),pc(""),gc(""),wc(!1),Do("")}m.useEffect(()=>{Ue([]),ot(null),ys(""),zr(""),ae(!1),Ht(!1),Rt(""),Cn(""),er(""),Xs([]),wa(!1),pc(""),gc(""),wc(!1),Do("")},[c]),m.useEffect(()=>{tr==="chat"&&c.trim()&&N&&iu()},[tr,c,N,xe==null?void 0:xe.workflow_id]);async function Ws(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 Pe.submit_command({command_id:Or(),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 Pe.get_run(I);Jn(V)}}catch{}return os(Pe,{force:!0}),window.setTimeout(()=>void os(Pe,{force:!0}),900),window.setTimeout(()=>void os(Pe,{force:!0}),2400),null}catch(q){const W=String((q==null?void 0:q.message)||q||`${k} failed`);return en(W),W}}async function su(g,k){return Ws(c.trim(),g,k)}async function Ol(g,k="Stopped from AbstractObserver"){const A=String(g||"").trim();if(!A||!window.confirm(`Cancel run ${Lt(A,24)}?`))return;await Ws(A,"cancel",{reason:k})||Pn("Cancel submitted",2)}async function lh(){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(!Mr||ni||qi||Wi.toLowerCase()!=="waiting"||k!=="until"){en("This run is not a scheduled wait that can be triggered now.");return}en(""),sn(!0);try{const I={payload:{mode:"run_now",requested_at:xt()}},q=String(gn||"").trim();q&&(I.wait_key=q),await Pe.submit_command({command_id:Or(),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 Pe.get_run(g);Jn(W)}catch{}}catch(I){en(String((I==null?void 0:I.message)||I||"Failed to trigger scheduled run"))}finally{sn(!1)}}async function ch(g){const k=c.trim();if(!k)return en("Missing run_id"),"Missing run_id";if(_s)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(""),oo(!0),Wt(!0);try{await Pe.submit_command({command_id:Or(),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 Pe.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),oo(!1)}}async function uh(g){const k=c.trim();if(!k)return en("Missing run_id"),"Missing run_id";if(ps)return"Compaction already in progress";const A=typeof(g==null?void 0:g.preserve_recent)=="number"?g.preserve_recent:fr,I=Math.max(0,Math.min(500,Math.floor(Number.isFinite(A)?A:6))),q=(g==null?void 0:g.compression_mode)||yr,W=String((g==null?void 0:g.focus)??ao??"").trim();Ai(""),en(""),Ar(!0),Wt(!0);try{const V={preserve_recent:I,compression_mode:q};return W&&(V.focus=W),await Pe.submit_command({command_id:Or(),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),Ar(!1)}}async function jd(){const g=c.trim();if(!g){Ca("Missing run_id");return}if(!jl){Ca(""),Sl(!0);try{const k=n.maintenance_ai_provider.trim(),A=n.maintenance_ai_model.trim();await Pe.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){Ca(String((k==null?void 0:k.message)||k||"Failed to generate summary"))}finally{Sl(!1)}}}async function za(){const g=c.trim();if(!g){zr("Select a run first.");return}if(!N){zr("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}zr(""),Po(""),ae(!0);const I={id:`local:${Or()}`,role:"user",content:k,ts:xt()};Ue(q=>[...q,I]),ys("");try{const q=qk(ke,I),W=n.maintenance_ai_provider.trim(),V=n.maintenance_ai_model.trim(),te=await Pe.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:${Or()}`,role:"assistant",content:Ee,ts:_e}])}catch(q){const W=m1(q);zr(W),Ue(V=>[...V,{id:`local:${Or()}`,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 dh(g){if(!ke.length)return;const k=c.trim(),A=k?`Run ${k}`:"Chat",I=G0(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`;K0({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){Xs([]);return}if(N&&!Ri){pc(""),wa(!0);try{const k=await Pe.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){Xs([]);return}const q=400,W=I.map(_e=>({run_id:_e.run_id,after:Math.max(0,(_e.ledger_len||0)-q)})),V=await Pe.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):"",ls=typeof Ie.model=="string"?String(Ie.model):"",On=typeof Ie.message_count=="number"?Number(Ie.message_count):null,Ss=Ie.chat_artifact,Jl=Ss&&typeof Ss=="object"&&typeof Ss.$artifact=="string"?String(Ss.$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:On,provider:$n,model:ls,artifact_id:Jl})}}te.sort((_e,pe)=>String(pe.created_at||"").localeCompare(String(_e.created_at||""))),Xs(te)}catch(k){pc(String((k==null?void 0:k.message)||k||"Failed to load saved discussions"))}finally{wa(!1)}}}async function fh(){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 Pe.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})));er(V)}catch{er("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);Pn(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 hh(){const g=String(pl||"").trim();if(!g)return;const k=ns.find(q=>String(q.thread_id||"").trim()===g)||null;if(!k){Do("Saved discussion not found (refresh list).");return}if(!N){Do("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."))){Do(""),wc(!0);try{const W=await(await Pe.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),ys(""),zr(""),Rt(""),Cn(Ee||"");try{const pe=JSON.stringify(_e.map(Ne=>({role:Ne.role,content:Ne.content,ts:Ne.ts})));er(pe)}catch{er("1")}Pn("Loaded discussion",2)}catch(q){Do(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(""),sn(!0);try{await Pe.submit_command({command_id:Or(),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||{}}}),Js(A);try{const I=await Pe.get_run(k);Jn(I)}catch{}os(Pe,{force:!0}),window.setTimeout(()=>void os(Pe,{force:!0}),900),window.setTimeout(()=>void os(Pe,{force:!0}),2400),ts.current&&window.clearTimeout(ts.current),ts.current=window.setTimeout(()=>{Js(I=>I===A?"":I)},2e3)}catch(I){en(String((I==null?void 0:I.message)||I||"resume failed"))}finally{sn(!1)}}async function mh(g){if(!Fs){en("No worker configured");return}if(!Ct){en(""),sn(!0);try{const k=[];for(const A of g){const I=await Fs.call_tool(A);k.push(I)}await Dl({mode:"executed",results:k})}finally{sn(!1)}}}const sa=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",_h=an==="until"&&!!ti,Ba=!ni&&B1(zn)&&(!!gn||_h),ph=an==="user",Fl=an==="event"?nf(xR(gn)):"",gh=an==="event"&&Fl==="abstract.ask",yh=sa.length>0,ou=Ba&&gn&&(ph||gh||yh)&&Lo!==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):"",Ua={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:px(g.record)}}),zl=hg(Xt,sa),o_=fx(Xt,sa),Nd=hx(Xt,at),No=Nd.text,wh=Nd.runtime_metadata,ia=String((Xt==null?void 0:Xt.prompt)||"").trim(),wi=N1(at,6),a_=!!(ia&&cx(ia)),lu=!!(ia&&!a_),Cd=lu?"Question from workflow":No&&No!==ia?"Closest prior user request":"Request context",vh=A1(at,E),xh=!!E.trim(),kr=xe!=null&&xe.schedule&&typeof xe.schedule=="object"?xe.schedule:null,Hn=typeof(kr==null?void 0:kr.interval)=="string"?String(kr.interval).trim():"",l_=typeof(kr==null?void 0:kr.share_context)=="boolean"?!!kr.share_context:null,bh=typeof(kr==null?void 0:kr.repeat_count)=="number"?Number(kr.repeat_count):null,Mr=!!(xe!=null&&xe.is_scheduled)||!!kr,mr=Mr&&!!Hn,jh=Mr?qi?"Resume schedule":"Suspend schedule":Wi==="running"&&!qi?"Pause":"Resume",Xe=Mr?qi?"resume":"pause":jh==="Pause"?"pause":"resume",Wa=Mr?!c.trim()||$e||Ct||ni:!c.trim()||$e||Ct||ni||Xe==="resume"&&!qi,$d=Mr&&!qi&&!ni&&!$e&&!Ct&&Wi.toLowerCase()==="waiting"&&(String(((qs=xe==null?void 0:xe.waiting)==null?void 0:qs.reason)||"").trim().toLowerCase()==="until"||an==="until")&&!!String(ti||"").trim(),as=(Vr=xe==null?void 0:xe.limits)==null?void 0:Vr.tokens,Bl=typeof(as==null?void 0:as.pct)=="number"?Number(as.pct):null,qa=as==null?void 0:as.estimated_used,Ul=(as==null?void 0:as.max_input_tokens)??(as==null?void 0:as.max_tokens),Ad=m.useMemo(()=>{const g=no.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=Hh(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(()=>{ws.current=hi.trim()},[hi]),m.useEffect(()=>{const g=c.trim(),k=Hi.trim();if(!(pt&&an==="subworkflow"&&!!k&&k!==g)){Wo.current="",hi.trim()&&Oi("");return}Wo.current!==k&&(Wo.current=k,ws.current=k,Oi(k))},[pt,c,an,Hi,hi]),m.useEffect(()=>{_o({})},[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&&Mr?g:""},[pt,Mr,xe==null?void 0:xe.workflow_id]),Sh=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=Wr(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,(Od=xe==null?void 0:xe.waiting)==null?void 0:Od.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=Wr(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 ur)I&&I.record&&A(String(I.run_id||"").trim(),I.record);return g},[$t,ur,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(Wr(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((jr==null?void 0:jr.flow_id)||"").trim();g&&(Fo.trim()||ja(g))},[jr,Fo]),m.useEffect(()=>{const g=vi.trim(),k=b.trim(),A=Fo.trim();if(g){let q=!1;return Li(!0),Sa(""),Pe.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),Sa(String((W==null?void 0:W.message)||W||"Failed to load workflow flow")))}).finally(()=>{q||Li(!1)}),()=>{q=!0}}if(!k||!A){vl(null),Sa(""),Li(!1);return}let I=!1;return Li(!0),Sa(""),Pe.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&&_o(te=>({...te,[A]:V}))}).catch(q=>{I||(vl(null),Sa(String((q==null?void 0:q.message)||q||"Failed to load flow")))}).finally(()=>{I||Li(!1)}),()=>{I=!0}},[vi,b,Fo,Pe]),m.useEffect(()=>{const g=b.trim();if(!zo||!g||!mo)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(mo,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 Pe.get_bundle_flow(g,_e),Ne=pe==null?void 0:pe.flow,ze=Ne&&typeof Ne=="object"?Ne:null;if(!ze)continue;_o(qe=>qe[_e]?qe:{...qe,[_e]:ze})}catch{}}})(),()=>{k=!0}):void 0},[zo,b,mo,Nc,Pe]);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()&&(Bo(""),po.current="")},[ni,c,li]),m.useEffect(()=>{const g=hi.trim(),k=c.trim();if(!(pt&&!!g&&g!==k)){Ur.current&&Ur.current.abort(),Ur.current=null,Pi.current=0,Mc&&Rc("");return}if(Mc===g)return;Ur.current&&Ur.current.abort();const I=new AbortController;Ur.current=I,Pi.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 Pe.stream_ledger(g,{after:Pi.current,on_step:V=>i_(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,Pe,Mc]),m.useEffect(()=>{if(!pt||!c.trim())return;let g=!1;const k=async()=>{if(!g&&!qo.current&&di.length&&!(Ve.current>Date.now())){qo.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 Pe.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];th(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{qo.current=!1}}};k();const A=window.setInterval(()=>void k(),2e3);return()=>{g=!0,window.clearInterval(A),qo.current=!1}},[pt,c,di,Pe]);const sr=m.useMemo(()=>gl?Vu.filter(kR):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 ur)!A||!A.record||k.push({run_id:String(A.run_id||"").trim(),cursor:A.cursor,record:A.record});return k},[$t,ur,c]),ri=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]),kh=m.useMemo(()=>{const g=hi.trim();if(g)return g;let k="",A=-1;for(const[I,q]of Object.entries(ri))q>A&&(k=I,A=q);return k||c.trim()},[ri,hi,c]),Vi=(Mf.trim()||kh).trim(),bs=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(()=>U0(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]),Ha=String((xe==null?void 0:xe.status)||(yn==null?void 0:yn.status)||"").trim(),Nh=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&&Ha.toLowerCase()==="waiting",Ch=Ld&&Nh==="until",Wl=Nn(ti),ql=Ch&&Wl!==null?$y(Wl-Date.now()):"",Rr=j1(xe),Vt=Md&&Rd?"Suspended":Ld?"Scheduled":bm({status:Ha,paused:Rd,stop_reason:Rr});async function ir(){if(N){Wf(!0),Aa("");try{const g=Go,k=g==="session"?String(Zs||Us||D||"").trim():"",A=g==="run"?String(zi||c||"").trim():"",I=P1(nr),q=on.length?on.join(","):"",W=O1(xr),V=Math.max(0,Ko)*im,te=await Pe.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:im,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=R1(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=Ty(te);let qe=ze;if(on.length)try{const Ze=await Pe.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=Ty(Ze)}catch{qe=ze}Di(Number.isFinite(Ne)?Math.max(0,Ne):Ee.length),Ho(Number((pe==null?void 0:pe.total_bytes)??(pe==null?void 0:pe.byte_total)??0)||0),$a(ze),Pc(qe),Bf(Ee),Ma(Ze=>{var Ie;return Ze&&Ee.some(ln=>ln.artifact_id===Ze)?Ze:((Ie=Ee[0])==null?void 0:Ie.artifact_id)||""})}catch(g){Aa(String((g==null?void 0:g.message)||g||"Failed to load artifacts")),Bf([]),Di(0),Ho(0),$a({}),Pc({}),Ma("")}finally{Wf(!1)}}}async function Vn(){if(N){fd(!0),hd("");try{const g=await Pe.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 _r(g){if(!N)return;const k=String(g||wo||zi||c||"").trim();if(!k){Hc([]),xo(""),bo("Select a run in Activity or Artifacts to load its runtime ledger.");return}Al(!0),bo("");try{const A=await Pe.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;xo(`${I.length.toLocaleString()} record${I.length===1?"":"s"}${q>=2e3?" (first 2,000)":""}`)}catch(A){bo(String((A==null?void 0:A.message)||A||"Failed to load run ledger")),Hc([]),xo("")}finally{Al(!1)}}m.useEffect(()=>{N&&e==="runtime"&&ir()},[N,e,Go,Zs,zi,_i,on,nr,xr,Ko]),m.useEffect(()=>{N&&(Uc||Os||e==="runtime"&&Vn())},[N,e,tr]),m.useEffect(()=>{if(!N||e!=="runtime"||kl!=="logs"||Bi!=="run_ledger"&&Bi!=="provider_calls")return;const g=String(wo||zi||c||"").trim();g&&_r(g)},[N,e,kl,Bi,wo,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:Us||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):Us||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,Us]),Va=m.useMemo(()=>mC(Zn,{query:Ju,filter:Xu,group_by:Zu,workflow_label_by_id:xs,parent_hint:g=>ui.current[g]||""}),[Zn,Ju,Xu,Zu,xs]),or=m.useMemo(()=>gx(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]),js=m.useMemo(()=>{const g={};for(const k of Zn){const A=String(k.run_id||"").trim();A&&(g[A]=k)}return g},[Zn]),Ga=String(wo||zi||c||"").trim(),Vl=Ga&&js[Ga]||null,Ka=String(Zs||(Vl==null?void 0:Vl.session_id)||Us||D||"").trim(),qr=m.useMemo(()=>ld.map(g=>Sm(g,js,xs)),[ld,js,xs]);m.useEffect(()=>{Fc(0)},[_i,on,nr,zi,xr,Ls,Go,Zs]);const Id=Math.max(1,Math.ceil(Ic/im)),xi=Math.min(Math.max(0,Ko),Id-1);m.useEffect(()=>{Ko!==xi&&Fc(xi)},[Ko,xi]);const Hr=m.useMemo(()=>qr,[qr,xi]),du=m.useMemo(()=>{const g={};for(const k of Hr){const A=Ls==="type"?Ep(k,js,xs):L1(k,Ls);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(Ls==="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)})},[Hr,Ls,js,xs]),oa=m.useMemo(()=>{const g=pi.trim();return g?Hr.find(k=>k.artifact_id===g)||Hr[0]||null:Hr[0]||null},[Hr,pi]);m.useEffect(()=>{e!=="runtime"||kl!=="artifacts"||eh(oa)},[e,kl,oa==null?void 0:oa.artifact_id]),m.useEffect(()=>()=>{Ra.url&&URL.revokeObjectURL(Ra.url)},[Ra.url]);const Co=m.useMemo(()=>Zn.filter(g=>Pu(g.status)),[Zn]);m.useEffect(()=>{if(e!=="settings"&&e!=="launch"||!N||T)return;let g=!1;return(async()=>{const[k,A]=await Promise.all([Pe.list_skills(),Pe.list_mcp_servers()]);g||(G(k),J(A),Q(!0))})(),()=>{g=!0}},[e,N,T]);const fu=[{id:"board",label:"Board",icon:r.jsx(Qe,{name:"board",size:16})},{id:"observe",label:"Observe",icon:r.jsx(Qe,{name:"history",size:16})},{id:"runtime",label:"System",icon:r.jsx(Qe,{name:"server",size:16})},{id:"launch",label:"Launch",icon:r.jsx(Qe,{name:"send",size:16})},{id:"automations",label:"Automations",icon:r.jsx(Qe,{name:"refresh",size:16})}],$o={board:"Board",observe:"Observe",runtime:"System",launch:"Launch",automations:"Automations",settings:"Settings"},Gl=r.jsxs(r.Fragment,{children:[ko?r.jsxs("details",{className:"launch_capabilities",style:{marginTop:"10px"},children:[r.jsxs("summary",{className:"help_text muted",style:{cursor:"pointer"},children:["Capabilities",vs.length?` · ${vs.length} skill${vs.length===1?"":"s"}`:""]}),r.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?r.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?r.jsx("div",{className:"launch_skill_list",children:z.map(g=>{var q;const k=vs.includes(g.name),A=g.blocked===!0,I=g.requires_review===!0&&!A;return r.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(`
132
- `),children:[r.jsx("input",{type:"checkbox",checked:k,disabled:A||$e||Ct||lt,onChange:W=>{const V=W.target.checked?Array.from(new Set([...vs,g.name])):vs.filter(te=>te!==g.name);kn("skills",V.length?V:void 0)}}),r.jsx("span",{className:"launch_skill_name",children:g.name}),g.trust_level?r.jsx("span",{className:`chip ${A?"danger":I?"warn":"muted"}`,children:A?"blocked":I?"review":g.trust_level}):null,g.description?r.jsx("span",{className:"launch_skill_desc",children:g.description}):null]},g.name)})}):r.jsx("div",{className:"help_text muted",style:{marginTop:"8px"},children:"The gateway's skills shelf is empty."}),vs.length?r.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,r.jsxs("details",{style:{marginTop:"10px"},children:[r.jsx("summary",{className:"help_text muted",style:{cursor:"pointer"},children:"Workspace"}),r.jsx("div",{className:"help_text muted",style:{fontSize:"var(--font-size-sm)",marginTop:"8px"},children:"Controls what the agent can access via filesystem tools."}),r.jsxs("div",{className:"launch_grid",style:{marginTop:"8px"},children:[r.jsxs("div",{className:"launch_grid_cell",style:{gridColumn:"1 / -1"},children:[r.jsx("label",{className:"launch_label",children:"Workspace Root"}),r.jsx("input",{className:"mono",value:El,onChange:g=>kn("workspace_root",g.target.value),placeholder:"/path/to/workspace",disabled:$e||Ct}),r.jsx("div",{className:"help_text muted",style:{fontSize:"var(--font-size-xxs)"},children:"Empty = gateway default (isolated per-run workspace)"})]}),r.jsxs("div",{className:"launch_grid_cell",children:[r.jsx("label",{className:"launch_label",children:"Access Mode"}),r.jsxs("select",{className:"mono",value:(Pa||"workspace_only").trim()||"workspace_only",onChange:g=>kn("workspace_access_mode",g.target.value),disabled:$e||Ct,children:[r.jsx("option",{value:"workspace_only",children:"workspace_only"}),r.jsx("option",{value:"workspace_or_allowed",children:"workspace_or_allowed"}),r.jsx("option",{value:"all_except_ignored",children:"all_except_ignored"})]}),r.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."})]})]}),(Pa||"").trim()==="workspace_or_allowed"?r.jsxs("div",{className:"field",style:{marginTop:"8px"},children:[r.jsx("label",{className:"launch_label",children:"Allowed Paths"}),r.jsx("textarea",{className:"mono",rows:3,value:Xo,onChange:g=>kn("workspace_allowed_paths",g.target.value),placeholder:`/path/to/project
133
- /path/to/workspace`,disabled:$e||Ct,spellCheck:!1,autoCorrect:"off",autoCapitalize:"off",autoComplete:"off"}),r.jsx("div",{className:"help_text muted",style:{fontSize:"var(--font-size-xxs)"},children:"Newline-separated directories (absolute or relative to workspace_root)"})]}):null,r.jsxs("div",{className:"field",style:{marginTop:"8px"},children:[r.jsx("label",{className:"launch_label",children:"Ignored Paths"}),r.jsx("textarea",{className:"mono",rows:3,value:gd,onChange:g=>kn("workspace_ignored_paths",g.target.value),placeholder:`node_modules
134
- runtime
135
- secret`,disabled:$e||Ct,spellCheck:!1,autoCorrect:"off",autoCapitalize:"off",autoComplete:"off"}),r.jsx("div",{className:"help_text muted",style:{fontSize:"var(--font-size-xxs)"},children:"Newline-separated paths to block (absolute or relative to workspace_root)"})]})]}),r.jsxs("details",{className:"launch_bundles",style:{marginTop:"10px"},children:[r.jsx("summary",{className:"help_text muted",style:{cursor:"pointer"},children:"Workflow bundles"}),r.jsxs("div",{className:"launch_workflow_bar",style:{marginTop:"8px"},children:[r.jsx("input",{ref:hs,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)}}),r.jsx("button",{type:"button",className:"btn launch_btn_upload",onClick:()=>{var g;return(g=hs.current)==null?void 0:g.click()},disabled:!N||ie||$i||$e||Ct,title:"Upload a .flow bundle",children:$i?"…":"Upload .flow"}),r.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:[r.jsx(Qe,{name:"refresh",size:14}),ut?"…":"Reload bundles"]})]})]})]});function Ya(g){t("observe"),Br("overview"),ra(g)}const Pd={on_select:g=>void rr.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"){rr.ask_archive(g.automation_id);return}rr.row_action(g,k)},on_legacy_action:(g,k)=>{if(k==="open_run"){Ya(g.automation_id);return}if(k==="recreate"){oh(g.automation_id).catch(A=>rr.report_error(A));return}rr.legacy_action(g,k)},on_confirm_archive:g=>void rr.row_action(g,"archive"),on_cancel_archive:()=>rr.ask_archive(""),on_status_filter:g=>void rr.set_status_filter(g),on_refresh:()=>void rr.refresh(),on_new:()=>{fe("automate"),t("launch")},on_show_archived:g=>rr.set_show_archived(g)};return r.jsxs("div",{className:"app-shell shell",children:[r.jsxs("aside",{className:"shell_sidebar",children:[r.jsxs("div",{className:"shell_brand",title:"AbstractObserver (Web/PWA)",children:[r.jsx("span",{className:"logo-icon shell_brand_mark","aria-hidden":"true",children:r.jsxs("svg",{viewBox:"0 0 24 24",width:"20",height:"20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[r.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"}),r.jsx("circle",{cx:"12",cy:"12",r:"4.7",fill:"currentColor",opacity:"0.95"}),r.jsx("circle",{cx:"10.3",cy:"10.7",r:"1.6",fill:"#ffffff",opacity:"0.18"}),r.jsx("circle",{cx:"19",cy:"13.6",r:"1.2",fill:"currentColor"})]})}),r.jsx("span",{className:"shell_brand_name",children:"Observer"})]}),r.jsxs("nav",{className:"shell_nav",children:[fu.map(g=>r.jsxs("button",{className:`shell_nav_item ${e===g.id?"active":""}`,onClick:()=>t(g.id),type:"button",children:[r.jsx("span",{className:"shell_nav_icon",children:g.icon}),r.jsx("span",{className:"shell_nav_label",children:g.label})]},g.id)),r.jsxs("a",{className:"shell_nav_item",href:l,target:"_blank",rel:"noreferrer",title:"Open the entity app (memory graph + visits)",children:[r.jsx("span",{className:"shell_nav_icon",children:r.jsx(Qe,{name:"bot",size:16})}),r.jsx("span",{className:"shell_nav_label",children:"Entities ↗"})]}),r.jsxs("button",{className:`shell_nav_item ${e==="settings"?"active":""}`,onClick:()=>t("settings"),type:"button",children:[r.jsx("span",{className:"shell_nav_icon",children:r.jsx(Qe,{name:"settings",size:16})}),r.jsx("span",{className:"shell_nav_label",children:"Settings"})]})]}),r.jsx("div",{className:"shell_sidebar_footer",children:r.jsxs("div",{className:"shell_connection shell_connection_passive",title:N?"Gateway connected":ie?"Gateway: connecting…":"Gateway: signed out",children:[r.jsx("span",{className:`gateway_led ${N?"ok":ie?"warn":"err"}`,"aria-hidden":"true"}),r.jsx("span",{className:`shell_connection_label ${N&&((Ki=($h=ne==null?void 0:ne.gateway)==null?void 0:$h.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"})]})})]}),r.jsxs("div",{className:"shell_main",children:[r.jsxs("header",{className:"shell_header",children:[r.jsx("div",{className:"shell_header_title",children:$o[e]||"Observer"}),r.jsxs("div",{className:"shell_header_actions",children:[o?r.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,r.jsx(Wj,{assistant:{open:Ut,onToggle:()=>It(g=>!g),label:"Observer assistant (docs-grounded)"},appearance:{onOpen:()=>_n(!0)},about:{identity:Ia,extraRows:Ds,onOpen:Kf},connection:{phase:O.phase,signingOut:O.signingOut,onConnect:()=>O.openModal(),onDisconnect:()=>Rl()}})]})]}),r.jsx(jj,{...O.modalProps}),r.jsx(Gj,{open:Qt,onClose:()=>_n(!1),value:Ke,onChange:Dt}),r.jsx(eN,{open:Ut,onClose:()=>It(!1),connected:N,topOffset:44,gateway:Pe}),r.jsxs("div",{className:"app-body shell_content",children:[e==="board"?N?r.jsx(_R,{gateway_connected:N,runs:Mt,all_runs:Dn,runs_refreshed_at:wn,entities:Kn,entities_total:Cs,entities_error:ce,refreshing:jn,on_refresh:()=>void os(Pe,{force:!0}),on_open_run:g=>{t("observe"),Br("overview"),ra(g)},on_resume_wait:Xf,on_open_automation:g=>{t("automations"),rr.refresh().then(()=>rr.select(g))},entity_app_href:l,on_read_diary:(g,k)=>Pe.read_entity_diary_entry(g,k),phase_graph:Jf}):r.jsx("div",{className:"page page_scroll",children:r.jsx("div",{className:"page_inner constrained",children:r.jsxs("div",{className:"card mc_hero",children:[r.jsx("div",{className:"title",children:r.jsx("h1",{children:"Connect to your gateway"})}),r.jsxs("p",{className:"muted",children:["Mission Control shows every run and entity on one board — but nothing is connected yet.",F?` Last attempt: ${F}`:""]}),r.jsxs("div",{className:"row",style:{gap:"8px",alignItems:"center"},children:[r.jsx("button",{className:"btn primary",onClick:()=>O.openModal(),disabled:ie,children:ie?"Connecting…":"Sign in"}),r.jsx("button",{className:"btn",onClick:()=>void ea({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"?r.jsx("div",{className:"page page_scroll",children:r.jsxs("div",{className:"page_inner settings_col",children:[r.jsxs("section",{className:"pane",children:[r.jsxs("div",{className:"pane_header",children:[r.jsx("span",{className:"pane_title",children:"Gateway"}),r.jsx("span",{className:"pane_spacer"}),r.jsx("span",{className:`chip ${N?"ok":"warn"}`,children:Av(ne).label})]}),r.jsxs("div",{className:"pane_body settings_body",children:[r.jsxs("div",{className:"settings_row",children:[r.jsxs("div",{className:"settings_row_main",children:[r.jsx("div",{className:"settings_row_title",children:"Connection"}),r.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."})]}),r.jsxs("div",{className:"settings_row_actions",children:[r.jsx("button",{className:"btn",onClick:()=>O.openModal(),children:"Manage connection…"}),N?r.jsx("button",{className:"btn",onClick:()=>Rl(),title:"Sign this browser out of the gateway (this app's session only)",children:"Sign out"}):null]})]}),F?r.jsx("div",{className:"warn_callout",children:F}):null,r.jsxs("div",{className:"settings_row",children:[r.jsxs("div",{className:"settings_row_main",children:[r.jsx("div",{className:"settings_row_title",children:"Auto-connect on load"}),r.jsx("div",{className:"settings_row_help",children:"Reuse the browser session automatically when the app opens."})]}),r.jsx("div",{className:"settings_row_actions",children:r.jsxs("select",{value:n.auto_connect_gateway?"on":"off",onChange:g=>i(k=>({...k,auto_connect_gateway:g.target.value==="on"})),children:[r.jsx("option",{value:"on",children:"On"}),r.jsx("option",{value:"off",children:"Off"})]})})]}),r.jsxs("details",{className:"settings_advanced",children:[r.jsx("summary",{children:"Advanced: direct dev connection (bearer token, cross-origin)"}),r.jsxs("div",{className:"field",style:{marginTop:"8px"},children:[r.jsx("label",{children:"Gateway URL"}),r.jsx("input",{value:n.gateway_url,onChange:g=>i(k=>({...k,gateway_url:g.target.value})),placeholder:Im})]}),r.jsxs("div",{className:"field",children:[r.jsx("label",{children:"Dev bearer token"}),r.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"})]}),r.jsx("button",{className:"btn",onClick:()=>void ea({prefer_direct:!0}),disabled:ie,children:ie?"Connecting…":"Connect directly"})]})]})]}),r.jsxs("section",{className:"pane",children:[r.jsxs("div",{className:"pane_header",children:[r.jsx("span",{className:"pane_title",children:"Assistant"}),r.jsx("span",{className:"pane_spacer"}),r.jsx("span",{className:"chip muted",children:"docs Q&A + run Ask"})]}),r.jsxs("div",{className:"pane_body settings_body",children:[r.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."}),r.jsx(hj,{className:"field",providerLabel:"Provider",modelLabel:"Model",providerPlaceholder:"(gateway default)",modelPlaceholder:"(gateway default)",provider:n.maintenance_ai_provider,model:n.maintenance_ai_model,providers:yd,models:Mn.models,loadingProviders:ie,loadingModels:hr,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}))}),r.jsx("div",{className:"settings_subhead",children:"Skills"}),z===null?r.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?r.jsx("div",{className:"settings_choice_list",children:z.map(g=>{const k=n.assistant_skill_names.includes(g.name);return r.jsxs("label",{className:`settings_choice ${k?"on":""}`,title:g.description||g.name,children:[r.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)}))}),r.jsxs("span",{className:"settings_choice_name",children:[g.name,g.version?r.jsxs("em",{children:[" v",g.version]}):null]}),g.description?r.jsx("span",{className:"settings_choice_desc",children:g.description}):null]},g.name)})}):r.jsx("div",{className:"settings_row_help",children:"The gateway serves an empty skills inventory."}),r.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."}),r.jsx("div",{className:"settings_subhead",children:"MCP servers"}),r.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)."}),r.jsxs("div",{className:"settings_mcp_row",children:[r.jsx("input",{className:"mono",value:n.worker_url,onChange:g=>i(k=>({...k,worker_url:g.target.value})),placeholder:"https://your-mcp-worker-endpoint"}),r.jsx("input",{className:"mono",type:"password",value:n.worker_token,onChange:g=>i(k=>({...k,worker_token:g.target.value})),placeholder:"Bearer token (optional)"}),r.jsx("span",{className:`chip ${n.worker_url.trim()?"ok":"muted"}`,children:n.worker_url.trim()?"configured":"none"})]})]})]})]})}):null,e==="launch"?r.jsx("div",{className:"page page_scroll",children:r.jsx("div",{className:"page_inner constrained",children:r.jsxs("div",{className:"card",children:[r.jsx(TN,{mode:oe,automate_available:ge.available,automate_reason:ge.reason,on_change:fe}),oe==="automate"&&!ge.available&&N?r.jsx("div",{className:"warn_callout",role:"note",children:ge.reason}):null,oe==="automate"&&Se.length?r.jsx("div",{className:"help_text",role:"note",children:Se.map(g=>r.jsx("div",{children:g},g))}):null,N?null:r.jsxs("div",{className:"warn_callout",children:["Not connected."," ",r.jsx("button",{className:"btn primary",onClick:()=>O.openModal(),children:"Sign in"})," ","to launch workflows on this gateway."]}),oe==="automate"?r.jsx("div",{className:"section_title",children:"What"}):null,r.jsx("div",{className:"launch_workflow_bar",children:r.jsxs("select",{className:"launch_workflow_select","aria-label":"Workflow",value:In,onChange:async g=>{const k=sN(String(g.target.value||""));k&&await Pl(k)},disabled:ie||!N,children:[r.jsx("option",{value:"",children:Jc.length?"(select workflow)":pt?ie?"(loading workflows…)":"(no executable workflows published on this gateway)":"(sign in to load workflows)"}),r.jsx("optgroup",{label:"Gateway default",children:oN(un).map(g=>r.jsx("option",{value:g.value,children:g.label},g.value))}),r.jsx("optgroup",{label:"Workflows",children:Jc.map(g=>r.jsx("option",{value:g.workflow_id,children:g.label},g.workflow_id))})]})}),r.jsxs("div",{className:"field",children:[jr!=null&&jr.description?r.jsx("div",{className:"help_text muted",style:{fontSize:"var(--font-size-sm)",marginTop:"6px"},children:String(jr.description)}):null,Z?r.jsx("div",{className:"help_text muted",style:{fontSize:"var(--font-size-sm)"},children:"Loading workflow…"}):null,X?r.jsx("div",{className:"mono",style:{color:"rgba(239, 68, 68, 0.9)",fontSize:"var(--font-size-sm)"},children:X}):null]}),r.jsx("div",{className:"section_divider"}),r.jsx("div",{className:"section_title",children:"Inputs"}),ko?at===null?r.jsxs("div",{className:"log_item",style:{borderColor:"rgba(239, 68, 68, 0.35)",marginTop:"10px"},children:[r.jsxs("div",{className:"meta",children:[r.jsx("span",{className:"mono",children:"input error"}),r.jsx("span",{className:"mono",children:xt()})]}),r.jsx("div",{className:"body mono",children:"Invalid input JSON — reselect the workflow to reset its inputs."})]}):Oa?r.jsx("div",{className:"launch_inputs",children:(()=>{const g=$e||Ct,k=[],A=[];for(const W of So){if(!W||typeof W!="object")continue;const V=String(W.id||"").trim();if(!V||oe==="automate"&&Qv.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:Dr(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([...Zo,...He,...vt])).sort();return r.jsxs("div",{className:"launch_field_wide",children:[r.jsx("label",{className:"launch_label",children:_e}),r.jsx(Xw,{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 r.jsxs("div",{className:"launch_field_wide",children:[r.jsx("label",{className:"launch_label",children:_e}),r.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 r.jsxs("div",{className:"launch_field_wide",children:[r.jsx("label",{className:"launch_label",children:_e}),r.jsx(Xw,{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 r.jsxs("div",{className:V||"launch_field",children:[r.jsx("label",{className:"launch_label",children:_e}),r.jsxs("select",{value:He,onChange:vt=>kn(te,vt.target.value),disabled:g,children:[r.jsx("option",{value:"",children:Ie||"(select)"}),Xc.map(vt=>r.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(ls=>String(ls||"").trim()).filter(Boolean):[];return r.jsxs("div",{className:V||"launch_field",children:[r.jsx("label",{className:"launch_label",children:_e}),$n.length?r.jsxs("select",{value:He,onChange:ls=>kn(te,ls.target.value),disabled:g,children:[r.jsx("option",{value:"",children:Ie||"(select)"}),$n.map(ls=>r.jsx("option",{value:ls,children:ls},ls))]}):r.jsx("input",{value:He,onChange:ls=>kn(te,ls.target.value),placeholder:Ie||"model id",disabled:g})]},te)}if(pe==="boolean"){const He=typeof Ze=="boolean"?Ze?"true":"false":"";return r.jsxs("div",{className:V||"launch_field",children:[r.jsx("label",{className:"launch_label",children:_e}),r.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:[r.jsx("option",{value:"",children:Ie||"(default)"}),r.jsx("option",{value:"true",children:"Yes"}),r.jsx("option",{value:"false",children:"No"})]})]},te)}if(pe==="number"){const He=typeof Ze=="number"&&Number.isFinite(Ze)?String(Ze):"";return r.jsxs("div",{className:V||"launch_field",children:[r.jsx("label",{className:"launch_label",children:_e}),r.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(`
136
- `):"";return r.jsxs("div",{className:"launch_field_wide",children:[r.jsx("label",{className:"launch_label",children:_e}),r.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 Ks[te]=="string"?Ks[te]:"",vt=String(tn[te]||"").trim();return r.jsxs("div",{className:"launch_field_wide",children:[r.jsxs("label",{className:"launch_label",children:[_e," ",r.jsx("span",{className:"launch_label_type",children:pe})]}),r.jsx("textarea",{className:"mono",value:He,onChange:xn=>{const $n=String(xn.target.value??"");it(On=>({...On,[te]:$n}));const ls=$n.trim();if(!ls){gr(On=>{const Ss={...On};return delete Ss[te],Ss}),kn(te,void 0);return}try{const On=JSON.parse(ls);gr(Ss=>{const Jl={...Ss};return delete Jl[te],Jl}),kn(te,On)}catch(On){gr(Ss=>({...Ss,[te]:String((On==null?void 0:On.message)||On||"Invalid JSON")}))}},placeholder:Ie||"{...}",rows:3,disabled:g}),vt?r.jsx("div",{className:"launch_field_error",children:vt}):null]},te)}const ln=typeof Ze=="string"?String(Ze):"";return te==="prompt"||te==="system"?r.jsxs("div",{className:"launch_field_wide",children:[r.jsx("label",{className:"launch_label",children:_e}),r.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):r.jsxs("div",{className:V||"launch_field",children:[r.jsx("label",{className:"launch_label",children:_e}),r.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)}),r.jsxs(r.Fragment,{children:[k.map(W=>q(W)),A.length>0?r.jsx("div",{className:"launch_grid",children:A.map(W=>q(W,"launch_grid_cell"))}):null]})})()}):r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"field",style:{marginTop:"10px"},children:[r.jsx("label",{children:"Prompt (common)"}),r.jsx("textarea",{value:Yf,onChange:g=>kn("prompt",g.target.value),placeholder:"What do you want the workflow/agent to do?",rows:3,disabled:$e||Ct})]}),r.jsxs("div",{className:"row",children:[r.jsx("div",{className:"col",children:r.jsxs("div",{className:"field",children:[r.jsx("label",{children:"Provider (common)"}),r.jsx("input",{value:Jo,onChange:g=>kn("provider",g.target.value),placeholder:"lmstudio / ollama / openai / ...",disabled:$e||Ct})]})}),r.jsx("div",{className:"col",children:r.jsxs("div",{className:"field",children:[r.jsx("label",{children:"Model (common)"}),r.jsx("input",{value:yi,onChange:g=>kn("model",g.target.value),placeholder:"qwen/qwen3-next-80b / gpt-4.1 / ...",disabled:$e||Ct})]})})]})]}):r.jsx("div",{className:"help_text muted",style:{fontSize:"var(--font-size-sm)",marginTop:"8px"},children:"Select a workflow above to configure inputs."}),oe==="automate"?r.jsxs(r.Fragment,{children:[r.jsx(MN,{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}))}),r.jsxs("details",{className:"launch_advanced",style:{marginTop:"10px"},children:[r.jsxs("summary",{className:"help_text muted",style:{cursor:"pointer"},children:["Advanced",vs.length?` · ${vs.length} skill${vs.length===1?"":"s"}`:""]}),r.jsx(RN,{form:Ae,disabled:lt,on_change:g=>Be(k=>({...k,...g}))}),Gl]})]}):Gl,r.jsx("div",{className:"section_divider"}),hn?r.jsxs("div",{className:"observe_context_card error",style:{marginBottom:"10px"},children:[r.jsx("span",{className:"chip mono danger",children:"error"}),r.jsx("span",{className:"mono",children:hn})]}):null,oe==="automate"&&We.length?r.jsx("ul",{className:"automate_errors",role:"alert",children:We.map(g=>r.jsx("li",{children:g},g))}):null,oe==="automate"&&Oe?r.jsxs("div",{className:"observe_context_card error",role:"alert","data-code":Oe.code,style:{marginBottom:"10px"},children:[r.jsx("span",{className:"chip mono danger",children:Oe.code}),r.jsxs("span",{children:[r.jsx("strong",{children:gm(Oe).title})," ",gm(Oe).detail,Oe.field?r.jsxs("span",{className:"mono",children:[" (",Oe.field,")"]}):null]})]}):null,r.jsx("div",{className:"launch_actions_bar launch_actions_stack",children:(()=>{const g=oe==="automate",k=N?ko?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 r.jsxs(r.Fragment,{children:[r.jsx("button",{className:"launch_submit_btn",onClick:()=>void ih(),disabled:!!k,title:k,children:g?lt?"Creating…":"Create automation":$e?"Launching…":"Launch now"}),k&&!lt&&!$e?r.jsx("span",{className:"mono muted launch_disabled_reason",children:k}):null]})})()})]})})}):null,e==="automations"?r.jsx(XN,{ctl:rr,gateway:Pe,active:e==="automations"&&N,available:ge,h:Pd,host:{on_open_run:g=>Ya(g),on_open_session:(g,k)=>{Jt({ts:xt(),kind:"info",title:"Discussion started",preview:ht(k),data:g})}}}):null,e==="runtime"?r.jsx(rC,{gateway_connected:N,tab:kl,runs:Zn,active_runs:Co,all_artifacts:ld,artifacts:Hr,artifact_total_count:Ic,artifact_total_bytes:Uf,artifact_facets:mi,artifact_type_facets:Fi,artifact_page:xi,artifact_page_size:im,artifact_groups:du,selected_artifact:oa,embedded_preview:Ra,loading:r_,error:Vo,query:_i,scope:Go,type_filters:on,date_filter:nr,group_by:Ls,sort_by:xr,artifact_run_filter:zi,audit_log_text:Os,audit_log_meta:Hf,audit_log_loading:Uc,audit_log_error:Wc,workflow_label_by_id:xs,run_by_id:js,selected_run_id:Ga,session_id:Ka,runtime_log_source:Bi,runtime_log_query:s_,runtime_ledger_log_items:qc,runtime_ledger_log_meta:Vf,runtime_ledger_log_loading:Gf,runtime_ledger_log_error:Vc,on_tab_change:ad,on_query_change:Oc,on_scope_change:go,on_session_filter_change:Sn,on_type_filters_change:yo,on_date_filter_change:ss,on_group_by_change:Ea,on_sort_by_change:Dc,on_artifact_page_change:Fc,on_artifact_run_filter_change:g=>{const k=String(g||"").trim();cd(k),k&&Ta(k),k&&Go!=="run"&&go("run")},on_refresh_artifacts:()=>void ir(),on_refresh_audit:()=>void Vn(),on_refresh_runtime_ledger:g=>void _r(g),on_runtime_log_source_change:md,on_runtime_log_query_change:$l,on_select_run:g=>{const k=String(g||"").trim();Ta(k);const A=k&&js[k]||null,I=String((A==null?void 0:A.session_id)||"").trim();I&&Sn(I)},on_select_artifact:Ma,on_preview_artifact:g=>void nu(g),on_download_artifact:g=>void xd(g),on_open_run:g=>{Ta(String(g||"").trim()),t("observe"),Br("overview"),ra(g)},on_open_ledger:g=>{Ta(String(g||"").trim()),t("observe"),Br("ledger"),ra(g)},on_refresh_runs:()=>void os(Pe,{force:!0}),on_reconnect:()=>void ea({open_modal_if_needed:!0}),on_open_settings:()=>t("settings"),memory_panel:N?r.jsx(GM,{gateway:Pe,selected_run_id:wo,selected_session_id:Ka}):null}):null,e==="observe"?r.jsx("div",{className:"page observe_page",children:r.jsxs("div",{className:"observatory_layout",children:[r.jsx(iC,{sections:Va,selected_run_id:c,root_run_id:_,search:Ju,filter:Xu,group_by:Zu,loading:jn,connected:N,on_sign_in:()=>O.openModal(),total_runs:Zn.length,workflow_label_by_id:xs,automation_titles:_d,on_search:Jm,on_filter:Xm,on_group_by:Zm,on_refresh:()=>void os(),on_select:(g,k)=>void ra(g,{root_run_id:k||g})}),r.jsxs("div",{className:"observatory_main",children:[r.jsxs("div",{className:"observe_toolbar",children:[r.jsxs("div",{className:"observe_toolbar_row",children:[c.trim()?r.jsxs("div",{className:"observe_run_identity",title:c.trim(),children:[r.jsx("span",{className:"observe_run_name",children:xs[String((yn==null?void 0:yn.workflow_id)||"")]||String((yn==null?void 0:yn.workflow_id)||"").trim()||Lt(c.trim(),22)}),r.jsx("span",{className:"chip mono muted",children:Lt(c.trim(),14)}),r.jsx("span",{className:`chip ${fl(Vt||Ha,Rr)}`,title:String((Rr==null?void 0:Rr.headline)||""),children:Vt||Ha||"unknown"})]}):r.jsx("span",{className:"observe_run_identity_empty",children:"No run selected"}),r.jsx("span",{className:"observe_toolbar_spacer"}),c.trim()?r.jsxs(r.Fragment,{children:[r.jsx("button",{className:"btn",onClick:()=>{if(Xe==="pause"){Ei("pause"),Er(""),es(""),As(!0);return}su("resume")},disabled:Wa,children:jh}),$d?r.jsx("button",{className:"btn primary",onClick:()=>void lh(),disabled:$e||Ct||ni||qi,children:"Run now"}):null,r.jsx("button",{className:"btn danger",onClick:()=>{Ei("cancel"),Er(""),es(""),As(!0)},disabled:$e||Ct||ni,children:"Cancel"}),r.jsx("button",{className:"btn btn_icon",onClick:ah,title:"Clear the run view",children:r.jsx(Qe,{name:"x",size:14})})]}):null]}),c.trim()&&!ni?r.jsx("div",{className:"observe_steer_row",children:r.jsx(Aj,{runId:c.trim(),parked:Ba,submit:(g,k)=>Pe.submit_command({command_id:`steer-${Or()}`,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,Ba||Mr||vc?r.jsxs("div",{className:"observe_toolbar_context",children:[Ba?r.jsxs("div",{className:"observe_context_card info",children:[r.jsxs("div",{className:"observe_context_label",children:[(()=>{const g=Mr?qi?"suspended":"scheduled":"waiting";return r.jsx("span",{className:`chip ${fl(g)}`,children:g})})(),r.jsx("span",{className:"muted",children:an||"unknown"})]}),r.jsxs("div",{className:"observe_context_body",children:[gn?r.jsxs("span",{className:"mono",title:gn,children:[r.jsx("span",{className:"muted",children:"wait_key"}),": ",Lt(gn,46)]}):null,an==="event"&&Fl?r.jsxs("span",{className:"mono",children:[r.jsx("span",{className:"muted",children:"event"}),": ",Fl]}):null,an==="subworkflow"&&Hi?r.jsxs("span",{className:"mono",children:[r.jsx("span",{className:"muted",children:"child"}),": ",Lt(Hi,18)]}):null,an==="until"&&ti?r.jsxs("span",{className:"mono",title:ti,children:[r.jsx("span",{className:"muted",children:"until"}),": ",Lt(ti,46)]}):null,an==="until"&&ti?r.jsx("span",{className:"mono muted",children:(()=>{const g=Nn(ti),k=g!==null?new Date(g).toLocaleString():ti,A=g!==null?$y(g-Date.now()):"";return`Next at ${k}${A?` (in ${A})`:""}`})()}):null]}),an==="subworkflow"&&Hi?r.jsxs("div",{className:"observe_context_actions",children:[r.jsx("button",{className:"btn primary",onClick:async()=>{f(Hi),await Il(Hi)},disabled:$e,children:"Attach to child"}),_.trim()&&_.trim()!==c.trim()?r.jsx("button",{className:"btn",onClick:async()=>{f(_.trim()),await Il(_.trim())},disabled:$e,children:"Back to root"}):null]}):null]}):null,Mr?r.jsxs("div",{className:"observe_context_card muted",children:[r.jsxs("div",{className:"observe_context_label",children:[r.jsx("span",{className:"chip muted",children:"schedule"}),r.jsx("span",{className:"muted",children:mr?`every ${Hn}`:"once"})]}),r.jsxs("div",{className:"observe_context_body",children:[Hn?r.jsxs("span",{className:"mono",children:[r.jsx("span",{className:"muted",children:"interval"}),": ",Hn]}):null,r.jsxs("span",{className:"mono",children:[r.jsx("span",{className:"muted",children:"share ctx"}),": ",l_?"yes":"no"]}),typeof bh=="number"?r.jsxs("span",{className:"mono",children:[r.jsx("span",{className:"muted",children:"repeats"}),": ",bh]}):null]}),Bl!==null?r.jsxs("div",{className:"observe_context_budget",children:[r.jsxs("span",{className:"mono muted",children:[typeof qa=="number"&&typeof Ul=="number"?`${qa.toLocaleString()} / ${Ul.toLocaleString()}`:"",` • ${Math.round(Math.max(0,Math.min(1,Bl))*100)}%`]}),r.jsx("div",{className:"observe_budget_bar",children:r.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,r.jsxs("div",{className:"observe_context_actions",children:[mr?r.jsx("button",{className:"btn",onClick:()=>{io(Hn||""),Fn(!0),Tn(""),dr(!0)},disabled:$e||_s,children:"Edit schedule"}):null,mr?r.jsx("button",{className:"btn",onClick:()=>{Ai(""),Zr(!0)},disabled:$e||ps,children:"Compact context"}):null,r.jsx("button",{className:"btn",onClick:()=>void oh(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?r.jsxs("div",{className:"observe_context_card error",children:[r.jsx("span",{className:"chip danger",children:"error"}),r.jsx("span",{className:"mono",children:vc})]}):null]}):null]}),r.jsxs("div",{className:"card panel_card card_scroll observe_viewer observe_viewer_full",children:[r.jsxs("div",{className:"tab_bar",children:[r.jsxs("div",{role:"tablist","aria-label":"Run views",className:"observe_tablist",children:[r.jsx("button",{role:"tab","aria-selected":tr==="overview",className:`tab ${tr==="overview"?"active":""}`,onClick:()=>Br("overview"),children:"Story"}),r.jsx("button",{role:"tab","aria-selected":tr==="ledger",className:`tab ${tr==="ledger"?"active":""}`,onClick:()=>Br("ledger"),children:"Ledger"}),r.jsx("button",{role:"tab","aria-selected":tr==="graph",className:`tab ${tr==="graph"?"active":""}`,onClick:()=>Br("graph"),children:"Flow"}),r.jsx("button",{role:"tab","aria-selected":tr==="chat",className:`tab ${tr==="chat"?"active":""}`,onClick:()=>Br("chat"),children:"Ask"})]}),tr==="ledger"&&(sr.length>0||va==="cycles")?r.jsxs("div",{className:"tab_bar_controls",children:[r.jsxs("div",{className:"seg_toggle",children:[r.jsx("button",{className:`seg_btn ${va==="steps"?"active":""}`,onClick:()=>xc("steps"),children:"Steps"}),r.jsx("button",{className:`seg_btn ${va==="cycles"?"active":""}`,onClick:()=>xc("cycles"),children:"Cycles"})]}),va==="steps"?r.jsx("button",{className:`seg_action ${gl?"active":""}`,onClick:()=>Tf(g=>!g),title:gl?"Showing condensed view":"Showing all steps",children:gl?"Condensed":"All"}):r.jsxs("select",{className:"mono seg_select",value:Vi,onChange:g=>Qu(String(g.target.value||"")),disabled:!bs.length,title:"Select run for cycles view",children:[bs.length?null:r.jsx("option",{value:"",children:"(no runs)"}),bs.map(g=>{const k=typeof ri[g]=="number"?Number(ri[g]):0,A=`${Lt(g,18)}${k?` • ${k} llm`:""}`;return r.jsx("option",{value:g,children:A},g)})]}),r.jsx("button",{className:"seg_action",disabled:!$t.length&&!ur.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})),...ur.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(`
137
- `);Zc(q)},children:"Copy JSONL"})]}):null,tr==="graph"?r.jsxs("div",{className:"tab_bar_controls",children:[r.jsx("button",{className:`seg_action ${zo?"active":""}`,onClick:()=>ka(g=>!g),children:"Subflows"}),r.jsx("button",{className:`seg_action ${Ac?"active":""}`,onClick:()=>Df(g=>!g),children:"Path"}),cu.length?r.jsx("select",{className:"mono seg_select",value:Fo,onChange:g=>ja(String(g.target.value||"")),disabled:!!vi.trim()||!b.trim()||Cc,children:cu.map(g=>r.jsx("option",{value:g,children:g},g))}):null]}):null]}),tr==="overview"?r.jsx(oC,{run_id:c,run:yn,run_state:xe,status_label:Vt||Ha||"unknown",workflow_label_by_id:xs,root_run_id:_,subrun_ids:di,session_id:Us,records_count:$t.length,records:$t,child_records_count:ur.length,provider_activities:or,attachments_count:Rf.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&&(Ta(g),cd(g),go("run")),ad("artifacts"),t("runtime")},on_open_subrun:g=>void ra(g,{root_run_id:_||c||g}),on_answer_wait:()=>Js(""),workspace_root:Lf,on_reveal_workspace:()=>void Zf(),run_artifacts:Qm,run_artifacts_loading:rd,run_artifacts_error:If,on_preview_run_artifact:g=>void nu(g),on_download_run_artifact:g=>void xd(g),timeline_items:Hl,node_index:pd,attachments:Rf,attachments_loading:td,attachments_error:yl,attachments_ready:!!uo.trim(),on_refresh_attachments:()=>void Fa(),on_preview_attachment:g=>void tu(g),on_download_attachment:g=>void eu(g),on_copy:g=>void Zc(g)}):null,tr==="ledger"?r.jsx(r.Fragment,{children:va==="steps"?r.jsxs("div",{className:"log log_scroll",children:[sr.map(g=>r.jsx(lC,{item:g,open:Ku[g.id]===!0,on_toggle:()=>Yu(k=>({...k,[g.id]:!k[g.id]})),response_open:Ym[g.id]===!0,on_toggle_response:()=>Ef(k=>({...k,[g.id]:!k[g.id]})),node_index:pd,on_copy:k=>void Zc(k)},g.id)),sr.length?null:r.jsx("div",{className:"empty_state_inline",children:"(no ledger items)"})]}):r.jsx("div",{className:"log log_scroll",children:r.jsx(P0,{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,tr==="graph"?r.jsxs(r.Fragment,{children:[$c?r.jsxs("div",{className:"log_item log_item_danger",children:[r.jsxs("div",{className:"meta",children:[r.jsx("span",{children:"graph error"}),r.jsx("span",{className:"mono",children:xt()})]}),r.jsx("div",{className:"body mono",children:$c})]}):null,Cc?r.jsxs("div",{className:"log_item log_item_info",children:[r.jsxs("div",{className:"meta",children:[r.jsx("span",{children:"loading"}),r.jsx("span",{className:"mono",children:vi.trim()?vi.trim():Fo})]}),r.jsx("div",{className:"body mono",children:"Loading graph…"})]}):null,r.jsx("div",{className:"graph_panel",children:r.jsx(bC,{flow:mo,flow_by_id:Nc,expand_subflows:zo,simplify:!0,prefer_vertical:!0,vertical_compact:.78,schedule_next_in:ql,schedule_interval:Hn,node_last_ms:Td,active_node_id:Sh,recent_nodes:Ff,visited_nodes:zf,highlight_path:Ac,now_ms:Ec})})]}):null,r.jsxs(al,{open:Pf,title:e_||"Attachment",onClose:()=>{sd(!1),ba(""),ho(""),wl(!1)},actions:r.jsx(r.Fragment,{children:r.jsx("button",{className:"btn",onClick:()=>{sd(!1),ba(""),ho(""),wl(!1)},children:"Close"})}),children:[Of?r.jsx("div",{className:"mono muted",style:{fontSize:"var(--font-size-sm)",marginBottom:"8px"},children:"Loading…"}):null,Ts?r.jsx("div",{className:"mono",style:{color:"rgba(239, 68, 68, 0.9)",fontSize:"var(--font-size-sm)",marginBottom:"8px"},children:Ts}):null,r.jsx("pre",{className:"mono",style:{whiteSpace:"pre-wrap",maxHeight:"62vh",overflow:"auto",margin:0},children:n_||"(empty)"})]}),tr==="chat"?r.jsxs("div",{className:"ask_tab log_scroll",style:{marginTop:"6px"},children:[r.jsxs("div",{className:"ask_header",children:[r.jsx("span",{className:"ask_title",children:"Ask about this run"}),r.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")}),r.jsx("span",{className:"pane_spacer"}),r.jsx("span",{className:"ask_hint",children:"Read-only · grounded in this run + subflows"})]}),r.jsxs("details",{className:"ask_manage",children:[r.jsx("summary",{children:"History & export"}),r.jsxs("div",{className:"field",style:{marginTop:"10px"},children:[r.jsxs("div",{className:"actions",style:{justifyContent:"space-between",alignItems:"center",gap:"10px",flexWrap:"wrap",marginTop:0},children:[r.jsx("div",{style:{flex:1,minWidth:260},children:r.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),Do("")}})}),r.jsxs("div",{className:"actions",style:{justifyContent:"flex-end",marginTop:0},children:[r.jsx("button",{className:"btn",type:"button",disabled:!pl.trim()||!N||yc,onClick:()=>void hh(),children:yc?"Loading…":"Load"}),r.jsx("button",{className:"btn",type:"button",disabled:!ke.length||U||Ft||yc,onClick:()=>{Ue([]),ot(null),ys(""),zr(""),Rt(""),Cn(""),er("")},children:"Clear"}),r.jsx("button",{className:"btn",type:"button",onClick:()=>void iu(),disabled:!c.trim()||!N||Ri,children:Ri?"Refreshing…":"Refresh"})]})]}),r.jsxs("div",{className:"actions",style:{justifyContent:"flex-end",marginTop:"8px",flexWrap:"wrap"},children:[r.jsx("button",{className:"btn",type:"button",disabled:!ke.length||!c.trim()||!N||Ft||!qu,onClick:()=>void fh(),title:qu?"":"No changes since last save",children:Ft?"Saving…":!qu&&rn?"Saved":"Save discussion"}),r.jsx("button",{className:"btn",type:"button",disabled:!ke.length,onClick:()=>dh("download"),children:"Export Markdown"}),r.jsx("button",{className:"btn",type:"button",disabled:!ke.length,onClick:()=>dh("copy"),children:je==="copied"?"Copied":je==="failed"?"Copy failed":"Copy Markdown"})]}),rn?r.jsxs("div",{className:"chat_hint",children:["Last saved: ",da(rn)]}):null,vr?r.jsx("div",{className:"chat_hint chat_hint_danger",children:vr}):null,Af?r.jsx("div",{className:"chat_hint chat_hint_danger",children:Af}):null,$f?r.jsx("div",{className:"chat_hint chat_hint_danger",children:$f}):null]})]}),lo?r.jsxs("div",{className:"log_item log_item_danger",children:[r.jsxs("div",{className:"meta",children:[r.jsx("span",{children:"error"}),r.jsx("span",{className:"mono",children:xt()})]}),r.jsx("div",{className:"body mono",children:lo})]}):null,Io?r.jsxs("div",{className:"log_item log_item_danger",children:[r.jsxs("div",{className:"meta",children:[r.jsx("span",{children:"voice"}),r.jsx("span",{className:"mono",children:xt()})]}),r.jsx("div",{className:"body mono",children:Io})]}):null,r.jsx("div",{className:"chat_messages",style:{marginTop:"10px"},children:r.jsx(ig,{messages:ke,className:"log_scroll",after:r.jsx(Zv,{history:ft}),afterKey:ft?`${ft.replayed_messages}:${ft.dropped_messages}`:null,messageProps:qn.tts_supported&&N&&Oo.trim()?{onSpeakToggle:Sd,getSpeakState:kd,jsonCollapseAfterDepth:4}:{jsonCollapseAfterDepth:4},empty:r.jsx("div",{className:"chat_empty_hint",children:"Ask about this run (why failed, which tools, what happened in subflows)."})})}),r.jsx("div",{className:"chat_composer",style:{marginTop:"10px"},children:r.jsx(og,{ref:gt,value:_c,onChange:ys,onSubmit:()=>void za(),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:r.jsxs("button",{className:`btn btn_icon voice_btn${qn.voice_ptt_recording?" danger":""}`,type:"button",disabled:!N||!na.trim()||!Oo.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||!na.trim()||!Oo.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:[r.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()?r.jsxs("div",{className:`status_bar ${Ro?"pulse":""}`,children:[r.jsx("strong",{children:"Run"}),":"," ",r.jsx("span",{className:"mono",children:Vt||Ha||"unknown"}),Ch&&ql?r.jsxs("span",{className:"mono muted",children:[" • next in ",ql]}):null,Ti?r.jsxs("span",{className:"mono muted",children:[" • ",Ti]}):null]}):null]})]})]})}):null,r.jsxs(al,{open:La,title:Nl||"Artifact",onClose:()=>{vo(!1),br(""),vn(""),Tr(!1),Cl(null),Un&&(URL.revokeObjectURL(Un),Ps(""))},actions:r.jsx("button",{className:"btn",onClick:()=>{vo(!1),br(""),vn(""),Tr(!1),Cl(null),Un&&(URL.revokeObjectURL(Un),Ps(""))},children:"Close"}),children:[ud?r.jsx("div",{className:"mono muted",style:{fontSize:"var(--font-size-sm)",marginBottom:"8px"},children:"Loading…"}):null,is?r.jsx("div",{className:"mono",style:{color:"rgba(239, 68, 68, 0.9)",fontSize:"var(--font-size-sm)",marginBottom:"8px"},children:is}):null,Qs==="image"&&Un?r.jsx("img",{className:"runtime_preview_media",src:Un,alt:Nl||"Artifact preview"}):Qs==="audio"&&Un?r.jsx("audio",{className:"runtime_preview_media",controls:!0,src:Un}):Qs==="video"&&Un?r.jsx("video",{className:"runtime_preview_media",controls:!0,src:Un}):r.jsx(wx,{artifact:qf,text:Is||"(empty)",className:"runtime_preview_text"})]}),oi?r.jsxs(al,{open:oi,title:"Edit schedule",onClose:()=>{dr(!1),io(""),Fn(!0),Tn(""),oo(!1)},actions:r.jsxs(r.Fragment,{children:[r.jsx("button",{className:"btn",onClick:()=>{dr(!1),io(""),Fn(!0),Tn(""),oo(!1)},disabled:$e||_s,children:"Back"}),r.jsx("button",{className:"btn primary",onClick:async()=>{await ch({interval:so,apply_immediately:pa})||(dr(!1),Tn(""),oo(!1))},disabled:$e||_s||!so.trim(),children:"Save"})]}),children:[ms?r.jsxs("div",{className:"log_item",style:{borderColor:"rgba(239, 68, 68, 0.35)",marginBottom:"10px"},children:[r.jsxs("div",{className:"meta",children:[r.jsx("span",{className:"mono",children:"error"}),r.jsx("span",{className:"mono",children:xt()})]}),r.jsx("div",{className:"body mono",children:ms})]}):null,r.jsxs("div",{className:"field",children:[r.jsx("label",{children:"Interval"}),r.jsx("input",{className:"mono",value:so,onChange:g=>io(String(g.target.value||"")),placeholder:"20m / 1h / 0.5s / 250ms",disabled:$e||_s}),r.jsxs("div",{className:"mono muted",style:{fontSize:"var(--font-size-sm)"},children:["Accepted units: ",r.jsx("span",{className:"mono",children:"ms"}),", ",r.jsx("span",{className:"mono",children:"s"}),", ",r.jsx("span",{className:"mono",children:"m"}),","," ",r.jsx("span",{className:"mono",children:"h"}),", ",r.jsx("span",{className:"mono",children:"d"}),". This updates the existing scheduled run in place (no context loss)."]})]}),r.jsxs("div",{className:"field",children:[r.jsx("label",{children:"Quick picks"}),r.jsx("div",{className:"actions",style:{gap:"8px",flexWrap:"wrap"},children:["15m","30m","1h","2h","6h","1d"].map(g=>r.jsx("button",{className:"btn",onClick:()=>io(g),disabled:$e||_s,children:g},g))})]}),r.jsxs("div",{className:"field",children:[r.jsx("label",{children:"Apply"}),r.jsxs("label",{style:{display:"flex",gap:"10px",alignItems:"center"},children:[r.jsx("input",{type:"checkbox",checked:pa,onChange:g=>Fn(!!g.target.checked),disabled:$e||_s}),"Apply immediately (recompute next run from now if waiting)"]})]})]}):null,Qn?r.jsxs(al,{open:Qn,title:"Compact scheduled context",onClose:()=>{Zr(!1),Ai(""),Ar(!1)},actions:r.jsxs(r.Fragment,{children:[r.jsx("button",{className:"btn",onClick:()=>{Zr(!1),Ai(""),Ar(!1)},disabled:$e||ps,children:"Cancel"}),r.jsx("button",{className:"btn primary",onClick:async()=>{await uh({preserve_recent:fr,compression_mode:yr,focus:ao})||(Zr(!1),Ai(""),Ar(!1))},disabled:$e||ps,children:ps?"Compacting…":"Compact"})]}),children:[ml?r.jsxs("div",{className:"log_item",style:{borderColor:"rgba(239, 68, 68, 0.35)",marginBottom:"10px"},children:[r.jsxs("div",{className:"meta",children:[r.jsx("span",{className:"mono",children:"error"}),r.jsx("span",{className:"mono",children:xt()})]}),r.jsx("div",{className:"body mono",children:ml})]}):null,r.jsxs("div",{className:"field",children:[r.jsx("label",{children:"Preserve recent turns"}),r.jsx("input",{type:"number",min:1,value:String(fr),onChange:g=>Ys(Math.max(1,parseInt(g.target.value||"6",10)||6)),disabled:$e||ps})]}),r.jsxs("div",{className:"field",children:[r.jsx("label",{children:"Mode"}),r.jsxs("select",{value:yr,onChange:g=>ga(g.target.value),disabled:$e||ps,children:[r.jsx("option",{value:"light",children:"light"}),r.jsx("option",{value:"standard",children:"standard"}),r.jsx("option",{value:"heavy",children:"heavy"})]})]}),r.jsxs("div",{className:"field",children:[r.jsx("label",{children:"Focus (optional)"}),r.jsx("input",{className:"mono",value:ao,onChange:g=>nn(String(g.target.value||"")),placeholder:"e.g. important decisions, next steps…",disabled:$e||ps})]})]}):null,ya?r.jsxs(al,{open:ya,title:ai==="cancel"?"Cancel run":Mr?"Suspend schedule":"Pause run",onClose:()=>{As(!1),Er(""),es("")},actions:r.jsxs(r.Fragment,{children:[r.jsx("button",{className:"btn",onClick:()=>{As(!1),Er(""),es("")},disabled:$e||Ct,children:"Back"}),r.jsx("button",{className:`btn ${ai==="cancel"?"danger":"primary"}`,onClick:async()=>{es("");const g=await su(ai,{reason:Qr});if(g){es(g);return}As(!1),Er(""),es("")},disabled:$e||Ct,children:ai==="pause"?Mr?"Suspend":"Pause":"Cancel"})]}),children:[Es?r.jsxs("div",{className:"log_item",style:{borderColor:"rgba(239, 68, 68, 0.35)",marginBottom:"10px"},children:[r.jsxs("div",{className:"meta",children:[r.jsx("span",{className:"mono",children:"error"}),r.jsx("span",{className:"mono",children:xt()})]}),r.jsx("div",{className:"body mono",children:Es})]}):null,r.jsxs("div",{className:"field",children:[r.jsx("label",{children:"Reason (optional)"}),r.jsx("input",{className:"mono",value:Qr,onChange:g=>Er(g.target.value),placeholder:"reason…"})]})]}):null,ou?r.jsxs(al,{open:ou,title:zl,onClose:()=>{gn&&Js(gn)},actions:r.jsxs(r.Fragment,{children:[r.jsx("button",{className:"btn",onClick:()=>{Br("ledger"),t("observe"),gn&&Js(gn)},disabled:!c.trim(),children:"Open ledger"}),r.jsx("button",{className:"btn",onClick:()=>gn&&Js(gn),disabled:Ct,children:"Dismiss"}),sa.length?r.jsxs(r.Fragment,{children:[r.jsx("button",{className:"btn danger",disabled:Ct,onClick:()=>Dl({approved:!1}),children:"Reject"}),r.jsx("button",{className:"btn",disabled:Ct,onClick:()=>Dl({approved:!0}),children:"Approve only"}),r.jsx("button",{className:"btn primary",disabled:!Fs||Ct,onClick:()=>mh(sa),children:"Approve and execute"})]}):null]}),children:[r.jsxs("div",{className:"wait_context_panel",children:[r.jsxs("div",{className:"wait_context_header",children:[r.jsxs("div",{children:[r.jsx("div",{className:"run_hero_eyebrow",children:"What you need to do"}),r.jsx("strong",{children:zl}),r.jsx("p",{children:o_})]}),r.jsx(hl,{status:Wi||"waiting"})]}),No?r.jsxs("div",{className:`wait_request_card ${lu?"":"inferred"}`,children:[r.jsx("span",{children:Cd}),r.jsx(nv,{metadata:wh}),r.jsx(Ni,{text:No}),lu?null:r.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."})]}):r.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?r.jsxs("section",{className:"wait_context_block wait_conversation_context",children:[r.jsx("span",{children:"Recent session turns"}),r.jsx("div",{className:"wait_turn_list",children:wi.map((g,k)=>r.jsxs("div",{className:`wait_turn_row role_${g.role.replace(/[^a-z0-9_-]+/g,"_")}`,children:[r.jsxs("div",{className:"wait_turn_meta",children:[r.jsx("strong",{children:g.role==="assistant"?"Assistant":g.role==="user"||g.role==="human"?"User":g.role}),g.ts?r.jsx("span",{className:"mono muted",children:da(g.ts)}):null]}),r.jsx(nv,{metadata:g.runtime_metadata}),r.jsx(Ni,{text:ht(g.text,{max_chars:1200,max_lines:10})})]},`${g.role}:${k}`))})]}):null,r.jsxs("div",{className:"artifact_detail_grid",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Workflow"}),r.jsx("strong",{children:ji(Ua,xs)})]}),r.jsxs("div",{children:[r.jsx("span",{children:"Run"}),r.jsx("strong",{className:"mono",children:Lt(c.trim(),24)})]}),r.jsxs("div",{children:[r.jsx("span",{children:"Node"}),r.jsx("strong",{className:"mono",children:Ua.current_node||String((zn==null?void 0:zn.node_id)||"—")})]}),r.jsxs("div",{children:[r.jsx("span",{children:"Elapsed"}),r.jsx("strong",{children:fc(Ua)})]}),r.jsxs("div",{children:[r.jsx("span",{children:"Session"}),r.jsx("strong",{className:"mono",children:Ua.session_id?Lt(String(Ua.session_id),18):"—"})]}),r.jsxs("div",{children:[r.jsx("span",{children:"Wait key"}),r.jsx("strong",{className:"mono",children:Lt(gn,28)})]})]}),xh?r.jsxs("details",{className:"runtime_raw_details wait_full_input_details",open:!No,children:[r.jsx("summary",{className:"mono muted",children:"Full run input JSON"}),r.jsx("div",{className:"wait_shared_json",children:r.jsx(ds,{value:vh,collapseAfterDepth:4,showCopy:!0})})]}):null,r.jsxs("section",{className:"wait_context_block",children:[r.jsx("span",{children:"Recent workflow steps leading to this wait"}),r.jsxs("div",{className:"wait_event_list",children:[au.map(g=>r.jsxs("div",{className:"wait_event_row",children:[r.jsxs("span",{className:"mono",children:["#",g.cursor]}),r.jsx("strong",{children:g.summary||g.effect_type||g.status||"event"}),r.jsx("span",{className:"mono muted",children:[g.node_id,g.status,da(g.ts)].filter(Boolean).join(" · ")})]},`${g.cursor}:${g.node_id}:${g.status}`)),au.length?null:r.jsx("div",{className:"empty_state_inline",children:"No ledger context is loaded. Open the ledger before deciding."})]})]})]}),sa.length?r.jsxs("div",{className:"wait_action_panel",children:[r.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."}),r.jsx("div",{className:"wait_tool_list",children:sa.map((g,k)=>r.jsxs("div",{className:"wait_tool_card",children:[r.jsxs("div",{className:"wait_tool_header",children:[r.jsx("strong",{children:String((g==null?void 0:g.name)||"tool")}),r.jsxs("div",{className:"wait_tool_badges",children:[r.jsx("span",{className:"chip mono warn",children:"approval"}),dx(g).map(A=>r.jsxs("span",{className:"chip mono muted",title:ux,children:[A,"~"]},A))]})]}),r.jsx("div",{className:"wait_tool_args",children:r.jsx(ds,{value:(g==null?void 0:g.arguments)||{},collapseAfterDepth:3,showCopy:!0})})]},`${String((g==null?void 0:g.name)||"tool")}:${k}`))}),Fs?null:r.jsx("div",{className:"warn_callout",children:"No tool worker is configured, so Observer cannot execute these calls directly."}),r.jsx("div",{className:"actions",children:r.jsx("button",{className:"btn danger",onClick:()=>void Ol(c.trim(),"Cancelled from wait prompt"),disabled:!c.trim()||Ct,children:"Cancel whole run"})}),r.jsxs("details",{className:"runtime_raw_details",children:[r.jsx("summary",{className:"mono muted",children:"Diagnostics"}),r.jsx("div",{className:"wait_shared_json",children:r.jsx(ds,{value:Xt||{},collapseAfterDepth:3,showCopy:!0})})]})]}):r.jsxs("div",{className:"wait_action_panel",children:[r.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."}),r.jsx("div",{className:"wait_prompt_text",children:No||"No explicit prompt was provided. Open the ledger for context before responding."}),r.jsx(sC,{wait:Xt,disabled:Ct,on_submit:g=>Dl({response:g})}),r.jsx("div",{className:"actions",children:r.jsx("button",{className:"btn danger",onClick:()=>void Ol(c.trim(),"Cancelled from wait prompt"),disabled:!c.trim()||Ct,children:"Cancel whole run"})}),r.jsxs("details",{className:"runtime_raw_details",children:[r.jsx("summary",{className:"mono muted",children:"Diagnostics"}),r.jsx("div",{className:"wait_shared_json",children:r.jsx(ds,{value:Xt||{},collapseAfterDepth:3,showCopy:!0})})]})]})]}):null]})]})]})}if("serviceWorker"in navigator){window.addEventListener("load",()=>{navigator.serviceWorker.register(nN).then(t=>t.update()).catch(()=>{})});let e=!1;navigator.serviceWorker.addEventListener("controllerchange",()=>{e||(e=!0,window.location.reload())})}g0.createRoot(document.getElementById("root")).render(r.jsx(ve.StrictMode,{children:r.jsx(TR,{})}));
138
- //# sourceMappingURL=index-DL1LcmFy.js.map