@abstractframework/observer 0.6.2 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,150 +0,0 @@
1
- var tk=Object.defineProperty;var nk=(e,t,n)=>t in e?tk(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var Vs=(e,t,n)=>nk(e,typeof t!="symbol"?t+"":t,n);(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))r(o);new MutationObserver(o=>{for(const l of o)if(l.type==="childList")for(const u of l.addedNodes)u.tagName==="LINK"&&u.rel==="modulepreload"&&r(u)}).observe(document,{childList:!0,subtree:!0});function n(o){const l={};return o.integrity&&(l.integrity=o.integrity),o.referrerPolicy&&(l.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?l.credentials="include":o.crossOrigin==="anonymous"?l.credentials="omit":l.credentials="same-origin",l}function r(o){if(o.ep)return;o.ep=!0;const l=n(o);fetch(o.href,l)}})();function og(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var m_={exports:{}},zd={},__={exports:{}},Vt={};/**
2
- * @license React
3
- * react.production.min.js
4
- *
5
- * Copyright (c) Facebook, Inc. and its affiliates.
6
- *
7
- * This source code is licensed under the MIT license found in the
8
- * LICENSE file in the root directory of this source tree.
9
- */var sy;function sk(){if(sy)return Vt;sy=1;var e=Symbol.for("react.element"),t=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),r=Symbol.for("react.strict_mode"),o=Symbol.for("react.profiler"),l=Symbol.for("react.provider"),u=Symbol.for("react.context"),c=Symbol.for("react.forward_ref"),f=Symbol.for("react.suspense"),m=Symbol.for("react.memo"),_=Symbol.for("react.lazy"),g=Symbol.iterator;function w(R){return R===null||typeof R!="object"?null:(R=g&&R[g]||R["@@iterator"],typeof R=="function"?R:null)}var x={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},j=Object.assign,b={};function N(R,Z,X){this.props=R,this.context=Z,this.refs=b,this.updater=X||x}N.prototype.isReactComponent={},N.prototype.setState=function(R,Z){if(typeof R!="object"&&typeof R!="function"&&R!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,R,Z,"setState")},N.prototype.forceUpdate=function(R){this.updater.enqueueForceUpdate(this,R,"forceUpdate")};function C(){}C.prototype=N.prototype;function E(R,Z,X){this.props=R,this.context=Z,this.refs=b,this.updater=X||x}var T=E.prototype=new C;T.constructor=E,j(T,N.prototype),T.isPureReactComponent=!0;var I=Array.isArray,K=Object.prototype.hasOwnProperty,U={current:null},J={key:!0,ref:!0,__self:!0,__source:!0};function Y(R,Z,X){var ie,ne={},ye=null,he=null;if(Z!=null)for(ie in Z.ref!==void 0&&(he=Z.ref),Z.key!==void 0&&(ye=""+Z.key),Z)K.call(Z,ie)&&!J.hasOwnProperty(ie)&&(ne[ie]=Z[ie]);var pe=arguments.length-2;if(pe===1)ne.children=X;else if(1<pe){for(var Ne=Array(pe),Ue=0;Ue<pe;Ue++)Ne[Ue]=arguments[Ue+2];ne.children=Ne}if(R&&R.defaultProps)for(ie in pe=R.defaultProps,pe)ne[ie]===void 0&&(ne[ie]=pe[ie]);return{$$typeof:e,type:R,key:ye,ref:he,props:ne,_owner:U.current}}function re(R,Z){return{$$typeof:e,type:R.type,key:Z,ref:R.ref,props:R.props,_owner:R._owner}}function ce(R){return typeof R=="object"&&R!==null&&R.$$typeof===e}function fe(R){var Z={"=":"=0",":":"=2"};return"$"+R.replace(/[=:]/g,function(X){return Z[X]})}var W=/\/+/g;function O(R,Z){return typeof R=="object"&&R!==null&&R.key!=null?fe(""+R.key):Z.toString(36)}function $(R,Z,X,ie,ne){var ye=typeof R;(ye==="undefined"||ye==="boolean")&&(R=null);var he=!1;if(R===null)he=!0;else switch(ye){case"string":case"number":he=!0;break;case"object":switch(R.$$typeof){case e:case t:he=!0}}if(he)return he=R,ne=ne(he),R=ie===""?"."+O(he,0):ie,I(ne)?(X="",R!=null&&(X=R.replace(W,"$&/")+"/"),$(ne,Z,X,"",function(Ue){return Ue})):ne!=null&&(ce(ne)&&(ne=re(ne,X+(!ne.key||he&&he.key===ne.key?"":(""+ne.key).replace(W,"$&/")+"/")+R)),Z.push(ne)),1;if(he=0,ie=ie===""?".":ie+":",I(R))for(var pe=0;pe<R.length;pe++){ye=R[pe];var Ne=ie+O(ye,pe);he+=$(ye,Z,X,Ne,ne)}else if(Ne=w(R),typeof Ne=="function")for(R=Ne.call(R),pe=0;!(ye=R.next()).done;)ye=ye.value,Ne=ie+O(ye,pe++),he+=$(ye,Z,X,Ne,ne);else if(ye==="object")throw Z=String(R),Error("Objects are not valid as a React child (found: "+(Z==="[object Object]"?"object with keys {"+Object.keys(R).join(", ")+"}":Z)+"). If you meant to render a collection of children, use an array instead.");return he}function z(R,Z,X){if(R==null)return R;var ie=[],ne=0;return $(R,ie,"","",function(ye){return Z.call(X,ye,ne++)}),ie}function A(R){if(R._status===-1){var Z=R._result;Z=Z(),Z.then(function(X){(R._status===0||R._status===-1)&&(R._status=1,R._result=X)},function(X){(R._status===0||R._status===-1)&&(R._status=2,R._result=X)}),R._status===-1&&(R._status=0,R._result=Z)}if(R._status===1)return R._result.default;throw R._result}var ee={current:null},P={transition:null},F={ReactCurrentDispatcher:ee,ReactCurrentBatchConfig:P,ReactCurrentOwner:U};function G(){throw Error("act(...) is not supported in production builds of React.")}return Vt.Children={map:z,forEach:function(R,Z,X){z(R,function(){Z.apply(this,arguments)},X)},count:function(R){var Z=0;return z(R,function(){Z++}),Z},toArray:function(R){return z(R,function(Z){return Z})||[]},only:function(R){if(!ce(R))throw Error("React.Children.only expected to receive a single React element child.");return R}},Vt.Component=N,Vt.Fragment=n,Vt.Profiler=o,Vt.PureComponent=E,Vt.StrictMode=r,Vt.Suspense=f,Vt.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=F,Vt.act=G,Vt.cloneElement=function(R,Z,X){if(R==null)throw Error("React.cloneElement(...): The argument must be a React element, but you passed "+R+".");var ie=j({},R.props),ne=R.key,ye=R.ref,he=R._owner;if(Z!=null){if(Z.ref!==void 0&&(ye=Z.ref,he=U.current),Z.key!==void 0&&(ne=""+Z.key),R.type&&R.type.defaultProps)var pe=R.type.defaultProps;for(Ne in Z)K.call(Z,Ne)&&!J.hasOwnProperty(Ne)&&(ie[Ne]=Z[Ne]===void 0&&pe!==void 0?pe[Ne]:Z[Ne])}var Ne=arguments.length-2;if(Ne===1)ie.children=X;else if(1<Ne){pe=Array(Ne);for(var Ue=0;Ue<Ne;Ue++)pe[Ue]=arguments[Ue+2];ie.children=pe}return{$$typeof:e,type:R.type,key:ne,ref:ye,props:ie,_owner:he}},Vt.createContext=function(R){return R={$$typeof:u,_currentValue:R,_currentValue2:R,_threadCount:0,Provider:null,Consumer:null,_defaultValue:null,_globalName:null},R.Provider={$$typeof:l,_context:R},R.Consumer=R},Vt.createElement=Y,Vt.createFactory=function(R){var Z=Y.bind(null,R);return Z.type=R,Z},Vt.createRef=function(){return{current:null}},Vt.forwardRef=function(R){return{$$typeof:c,render:R}},Vt.isValidElement=ce,Vt.lazy=function(R){return{$$typeof:_,_payload:{_status:-1,_result:R},_init:A}},Vt.memo=function(R,Z){return{$$typeof:m,type:R,compare:Z===void 0?null:Z}},Vt.startTransition=function(R){var Z=P.transition;P.transition={};try{R()}finally{P.transition=Z}},Vt.unstable_act=G,Vt.useCallback=function(R,Z){return ee.current.useCallback(R,Z)},Vt.useContext=function(R){return ee.current.useContext(R)},Vt.useDebugValue=function(){},Vt.useDeferredValue=function(R){return ee.current.useDeferredValue(R)},Vt.useEffect=function(R,Z){return ee.current.useEffect(R,Z)},Vt.useId=function(){return ee.current.useId()},Vt.useImperativeHandle=function(R,Z,X){return ee.current.useImperativeHandle(R,Z,X)},Vt.useInsertionEffect=function(R,Z){return ee.current.useInsertionEffect(R,Z)},Vt.useLayoutEffect=function(R,Z){return ee.current.useLayoutEffect(R,Z)},Vt.useMemo=function(R,Z){return ee.current.useMemo(R,Z)},Vt.useReducer=function(R,Z,X){return ee.current.useReducer(R,Z,X)},Vt.useRef=function(R){return ee.current.useRef(R)},Vt.useState=function(R){return ee.current.useState(R)},Vt.useSyncExternalStore=function(R,Z,X){return ee.current.useSyncExternalStore(R,Z,X)},Vt.useTransition=function(){return ee.current.useTransition()},Vt.version="18.3.1",Vt}var ry;function Cf(){return ry||(ry=1,__.exports=sk()),__.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 iy;function rk(){if(iy)return zd;iy=1;var e=Cf(),t=Symbol.for("react.element"),n=Symbol.for("react.fragment"),r=Object.prototype.hasOwnProperty,o=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,l={key:!0,ref:!0,__self:!0,__source:!0};function u(c,f,m){var _,g={},w=null,x=null;m!==void 0&&(w=""+m),f.key!==void 0&&(w=""+f.key),f.ref!==void 0&&(x=f.ref);for(_ in f)r.call(f,_)&&!l.hasOwnProperty(_)&&(g[_]=f[_]);if(c&&c.defaultProps)for(_ in f=c.defaultProps,f)g[_]===void 0&&(g[_]=f[_]);return{$$typeof:t,type:c,key:w,ref:x,props:g,_owner:o.current}}return zd.Fragment=n,zd.jsx=u,zd.jsxs=u,zd}var oy;function ik(){return oy||(oy=1,m_.exports=rk()),m_.exports}var s=ik(),p=Cf();const ve=og(p);var Nh={},p_={exports:{}},Fr={},g_={exports:{}},y_={};/**
18
- * @license React
19
- * scheduler.production.min.js
20
- *
21
- * Copyright (c) Facebook, Inc. and its affiliates.
22
- *
23
- * This source code is licensed under the MIT license found in the
24
- * LICENSE file in the root directory of this source tree.
25
- */var ay;function ok(){return ay||(ay=1,(function(e){function t(P,F){var G=P.length;P.push(F);e:for(;0<G;){var R=G-1>>>1,Z=P[R];if(0<o(Z,F))P[R]=F,P[G]=Z,G=R;else break e}}function n(P){return P.length===0?null:P[0]}function r(P){if(P.length===0)return null;var F=P[0],G=P.pop();if(G!==F){P[0]=G;e:for(var R=0,Z=P.length,X=Z>>>1;R<X;){var ie=2*(R+1)-1,ne=P[ie],ye=ie+1,he=P[ye];if(0>o(ne,G))ye<Z&&0>o(he,ne)?(P[R]=he,P[ye]=G,R=ye):(P[R]=ne,P[ie]=G,R=ie);else if(ye<Z&&0>o(he,G))P[R]=he,P[ye]=G,R=ye;else break e}}return F}function o(P,F){var G=P.sortIndex-F.sortIndex;return G!==0?G:P.id-F.id}if(typeof performance=="object"&&typeof performance.now=="function"){var l=performance;e.unstable_now=function(){return l.now()}}else{var u=Date,c=u.now();e.unstable_now=function(){return u.now()-c}}var f=[],m=[],_=1,g=null,w=3,x=!1,j=!1,b=!1,N=typeof setTimeout=="function"?setTimeout:null,C=typeof clearTimeout=="function"?clearTimeout:null,E=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function T(P){for(var F=n(m);F!==null;){if(F.callback===null)r(m);else if(F.startTime<=P)r(m),F.sortIndex=F.expirationTime,t(f,F);else break;F=n(m)}}function I(P){if(b=!1,T(P),!j)if(n(f)!==null)j=!0,A(K);else{var F=n(m);F!==null&&ee(I,F.startTime-P)}}function K(P,F){j=!1,b&&(b=!1,C(Y),Y=-1),x=!0;var G=w;try{for(T(F),g=n(f);g!==null&&(!(g.expirationTime>F)||P&&!fe());){var R=g.callback;if(typeof R=="function"){g.callback=null,w=g.priorityLevel;var Z=R(g.expirationTime<=F);F=e.unstable_now(),typeof Z=="function"?g.callback=Z:g===n(f)&&r(f),T(F)}else r(f);g=n(f)}if(g!==null)var X=!0;else{var ie=n(m);ie!==null&&ee(I,ie.startTime-F),X=!1}return X}finally{g=null,w=G,x=!1}}var U=!1,J=null,Y=-1,re=5,ce=-1;function fe(){return!(e.unstable_now()-ce<re)}function W(){if(J!==null){var P=e.unstable_now();ce=P;var F=!0;try{F=J(!0,P)}finally{F?O():(U=!1,J=null)}}else U=!1}var O;if(typeof E=="function")O=function(){E(W)};else if(typeof MessageChannel<"u"){var $=new MessageChannel,z=$.port2;$.port1.onmessage=W,O=function(){z.postMessage(null)}}else O=function(){N(W,0)};function A(P){J=P,U||(U=!0,O())}function ee(P,F){Y=N(function(){P(e.unstable_now())},F)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(P){P.callback=null},e.unstable_continueExecution=function(){j||x||(j=!0,A(K))},e.unstable_forceFrameRate=function(P){0>P||125<P?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):re=0<P?Math.floor(1e3/P):5},e.unstable_getCurrentPriorityLevel=function(){return w},e.unstable_getFirstCallbackNode=function(){return n(f)},e.unstable_next=function(P){switch(w){case 1:case 2:case 3:var F=3;break;default:F=w}var G=w;w=F;try{return P()}finally{w=G}},e.unstable_pauseExecution=function(){},e.unstable_requestPaint=function(){},e.unstable_runWithPriority=function(P,F){switch(P){case 1:case 2:case 3:case 4:case 5:break;default:P=3}var G=w;w=P;try{return F()}finally{w=G}},e.unstable_scheduleCallback=function(P,F,G){var R=e.unstable_now();switch(typeof G=="object"&&G!==null?(G=G.delay,G=typeof G=="number"&&0<G?R+G:R):G=R,P){case 1:var Z=-1;break;case 2:Z=250;break;case 5:Z=1073741823;break;case 4:Z=1e4;break;default:Z=5e3}return Z=G+Z,P={id:_++,callback:F,priorityLevel:P,startTime:G,expirationTime:Z,sortIndex:-1},G>R?(P.sortIndex=G,t(m,P),n(f)===null&&P===n(m)&&(b?(C(Y),Y=-1):b=!0,ee(I,G-R))):(P.sortIndex=Z,t(f,P),j||x||(j=!0,A(K))),P},e.unstable_shouldYield=fe,e.unstable_wrapCallback=function(P){var F=w;return function(){var G=w;w=F;try{return P.apply(this,arguments)}finally{w=G}}}})(y_)),y_}var ly;function ak(){return ly||(ly=1,g_.exports=ok()),g_.exports}/**
26
- * @license React
27
- * react-dom.production.min.js
28
- *
29
- * Copyright (c) Facebook, Inc. and its affiliates.
30
- *
31
- * This source code is licensed under the MIT license found in the
32
- * LICENSE file in the root directory of this source tree.
33
- */var cy;function lk(){if(cy)return Fr;cy=1;var e=Cf(),t=ak();function n(i){for(var a="https://reactjs.org/docs/error-decoder.html?invariant="+i,d=1;d<arguments.length;d++)a+="&args[]="+encodeURIComponent(arguments[d]);return"Minified React error #"+i+"; visit "+a+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}var r=new Set,o={};function l(i,a){u(i,a),u(i+"Capture",a)}function u(i,a){for(o[i]=a,i=0;i<a.length;i++)r.add(a[i])}var c=!(typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),f=Object.prototype.hasOwnProperty,m=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,_={},g={};function w(i){return f.call(g,i)?!0:f.call(_,i)?!1:m.test(i)?g[i]=!0:(_[i]=!0,!1)}function x(i,a,d,h){if(d!==null&&d.type===0)return!1;switch(typeof a){case"function":case"symbol":return!0;case"boolean":return h?!1:d!==null?!d.acceptsBooleans:(i=i.toLowerCase().slice(0,5),i!=="data-"&&i!=="aria-");default:return!1}}function j(i,a,d,h){if(a===null||typeof a>"u"||x(i,a,d,h))return!0;if(h)return!1;if(d!==null)switch(d.type){case 3:return!a;case 4:return a===!1;case 5:return isNaN(a);case 6:return isNaN(a)||1>a}return!1}function b(i,a,d,h,v,k,L){this.acceptsBooleans=a===2||a===3||a===4,this.attributeName=h,this.attributeNamespace=v,this.mustUseProperty=d,this.propertyName=i,this.type=a,this.sanitizeURL=k,this.removeEmptyString=L}var N={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(i){N[i]=new b(i,0,!1,i,null,!1,!1)}),[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(i){var a=i[0];N[a]=new b(a,1,!1,i[1],null,!1,!1)}),["contentEditable","draggable","spellCheck","value"].forEach(function(i){N[i]=new b(i,2,!1,i.toLowerCase(),null,!1,!1)}),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(i){N[i]=new b(i,2,!1,i,null,!1,!1)}),"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(i){N[i]=new b(i,3,!1,i.toLowerCase(),null,!1,!1)}),["checked","multiple","muted","selected"].forEach(function(i){N[i]=new b(i,3,!0,i,null,!1,!1)}),["capture","download"].forEach(function(i){N[i]=new b(i,4,!1,i,null,!1,!1)}),["cols","rows","size","span"].forEach(function(i){N[i]=new b(i,6,!1,i,null,!1,!1)}),["rowSpan","start"].forEach(function(i){N[i]=new b(i,5,!1,i.toLowerCase(),null,!1,!1)});var C=/[\-:]([a-z])/g;function E(i){return i[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(i){var a=i.replace(C,E);N[a]=new b(a,1,!1,i,null,!1,!1)}),"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(i){var a=i.replace(C,E);N[a]=new b(a,1,!1,i,"http://www.w3.org/1999/xlink",!1,!1)}),["xml:base","xml:lang","xml:space"].forEach(function(i){var a=i.replace(C,E);N[a]=new b(a,1,!1,i,"http://www.w3.org/XML/1998/namespace",!1,!1)}),["tabIndex","crossOrigin"].forEach(function(i){N[i]=new b(i,1,!1,i.toLowerCase(),null,!1,!1)}),N.xlinkHref=new b("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1),["src","href","action","formAction"].forEach(function(i){N[i]=new b(i,1,!1,i.toLowerCase(),null,!0,!0)});function T(i,a,d,h){var v=N.hasOwnProperty(a)?N[a]:null;(v!==null?v.type!==0:h||!(2<a.length)||a[0]!=="o"&&a[0]!=="O"||a[1]!=="n"&&a[1]!=="N")&&(j(a,d,v,h)&&(d=null),h||v===null?w(a)&&(d===null?i.removeAttribute(a):i.setAttribute(a,""+d)):v.mustUseProperty?i[v.propertyName]=d===null?v.type===3?!1:"":d:(a=v.attributeName,h=v.attributeNamespace,d===null?i.removeAttribute(a):(v=v.type,d=v===3||v===4&&d===!0?"":""+d,h?i.setAttributeNS(h,a,d):i.setAttribute(a,d))))}var I=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,K=Symbol.for("react.element"),U=Symbol.for("react.portal"),J=Symbol.for("react.fragment"),Y=Symbol.for("react.strict_mode"),re=Symbol.for("react.profiler"),ce=Symbol.for("react.provider"),fe=Symbol.for("react.context"),W=Symbol.for("react.forward_ref"),O=Symbol.for("react.suspense"),$=Symbol.for("react.suspense_list"),z=Symbol.for("react.memo"),A=Symbol.for("react.lazy"),ee=Symbol.for("react.offscreen"),P=Symbol.iterator;function F(i){return i===null||typeof i!="object"?null:(i=P&&i[P]||i["@@iterator"],typeof i=="function"?i:null)}var G=Object.assign,R;function Z(i){if(R===void 0)try{throw Error()}catch(d){var a=d.stack.trim().match(/\n( *(at )?)/);R=a&&a[1]||""}return`
34
- `+R+i}var X=!1;function ie(i,a){if(!i||X)return"";X=!0;var d=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{if(a)if(a=function(){throw Error()},Object.defineProperty(a.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(a,[])}catch(we){var h=we}Reflect.construct(i,[],a)}else{try{a.call()}catch(we){h=we}i.call(a.prototype)}else{try{throw Error()}catch(we){h=we}i()}}catch(we){if(we&&h&&typeof we.stack=="string"){for(var v=we.stack.split(`
35
- `),k=h.stack.split(`
36
- `),L=v.length-1,Q=k.length-1;1<=L&&0<=Q&&v[L]!==k[Q];)Q--;for(;1<=L&&0<=Q;L--,Q--)if(v[L]!==k[Q]){if(L!==1||Q!==1)do if(L--,Q--,0>Q||v[L]!==k[Q]){var se=`
37
- `+v[L].replace(" at new "," at ");return i.displayName&&se.includes("<anonymous>")&&(se=se.replace("<anonymous>",i.displayName)),se}while(1<=L&&0<=Q);break}}}finally{X=!1,Error.prepareStackTrace=d}return(i=i?i.displayName||i.name:"")?Z(i):""}function ne(i){switch(i.tag){case 5:return Z(i.type);case 16:return Z("Lazy");case 13:return Z("Suspense");case 19:return Z("SuspenseList");case 0:case 2:case 15:return i=ie(i.type,!1),i;case 11:return i=ie(i.type.render,!1),i;case 1:return i=ie(i.type,!0),i;default:return""}}function ye(i){if(i==null)return null;if(typeof i=="function")return i.displayName||i.name||null;if(typeof i=="string")return i;switch(i){case J:return"Fragment";case U:return"Portal";case re:return"Profiler";case Y:return"StrictMode";case O:return"Suspense";case $:return"SuspenseList"}if(typeof i=="object")switch(i.$$typeof){case fe:return(i.displayName||"Context")+".Consumer";case ce:return(i._context.displayName||"Context")+".Provider";case W:var a=i.render;return i=i.displayName,i||(i=a.displayName||a.name||"",i=i!==""?"ForwardRef("+i+")":"ForwardRef"),i;case z:return a=i.displayName||null,a!==null?a:ye(i.type)||"Memo";case A:a=i._payload,i=i._init;try{return ye(i(a))}catch{}}return null}function he(i){var a=i.type;switch(i.tag){case 24:return"Cache";case 9:return(a.displayName||"Context")+".Consumer";case 10:return(a._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return i=a.render,i=i.displayName||i.name||"",a.displayName||(i!==""?"ForwardRef("+i+")":"ForwardRef");case 7:return"Fragment";case 5:return a;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return ye(a);case 8:return a===Y?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof a=="function")return a.displayName||a.name||null;if(typeof a=="string")return a}return null}function pe(i){switch(typeof i){case"boolean":case"number":case"string":case"undefined":return i;case"object":return i;default:return""}}function Ne(i){var a=i.type;return(i=i.nodeName)&&i.toLowerCase()==="input"&&(a==="checkbox"||a==="radio")}function Ue(i){var a=Ne(i)?"checked":"value",d=Object.getOwnPropertyDescriptor(i.constructor.prototype,a),h=""+i[a];if(!i.hasOwnProperty(a)&&typeof d<"u"&&typeof d.get=="function"&&typeof d.set=="function"){var v=d.get,k=d.set;return Object.defineProperty(i,a,{configurable:!0,get:function(){return v.call(this)},set:function(L){h=""+L,k.call(this,L)}}),Object.defineProperty(i,a,{enumerable:d.enumerable}),{getValue:function(){return h},setValue:function(L){h=""+L},stopTracking:function(){i._valueTracker=null,delete i[a]}}}}function We(i){i._valueTracker||(i._valueTracker=Ue(i))}function pt(i){if(!i)return!1;var a=i._valueTracker;if(!a)return!0;var d=a.getValue(),h="";return i&&(h=Ne(i)?i.checked?"true":"false":i.value),i=h,i!==d?(a.setValue(i),!0):!1}function Fe(i){if(i=i||(typeof document<"u"?document:void 0),typeof i>"u")return null;try{return i.activeElement||i.body}catch{return i.body}}function tt(i,a){var d=a.checked;return G({},a,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:d??i._wrapperState.initialChecked})}function lt(i,a){var d=a.defaultValue==null?"":a.defaultValue,h=a.checked!=null?a.checked:a.defaultChecked;d=pe(a.value!=null?a.value:d),i._wrapperState={initialChecked:h,initialValue:d,controlled:a.type==="checkbox"||a.type==="radio"?a.checked!=null:a.value!=null}}function Ke(i,a){a=a.checked,a!=null&&T(i,"checked",a,!1)}function je(i,a){Ke(i,a);var d=pe(a.value),h=a.type;if(d!=null)h==="number"?(d===0&&i.value===""||i.value!=d)&&(i.value=""+d):i.value!==""+d&&(i.value=""+d);else if(h==="submit"||h==="reset"){i.removeAttribute("value");return}a.hasOwnProperty("value")?ht(i,a.type,d):a.hasOwnProperty("defaultValue")&&ht(i,a.type,pe(a.defaultValue)),a.checked==null&&a.defaultChecked!=null&&(i.defaultChecked=!!a.defaultChecked)}function Re(i,a,d){if(a.hasOwnProperty("value")||a.hasOwnProperty("defaultValue")){var h=a.type;if(!(h!=="submit"&&h!=="reset"||a.value!==void 0&&a.value!==null))return;a=""+i._wrapperState.initialValue,d||a===i.value||(i.value=a),i.defaultValue=a}d=i.name,d!==""&&(i.name=""),i.defaultChecked=!!i._wrapperState.initialChecked,d!==""&&(i.name=d)}function ht(i,a,d){(a!=="number"||Fe(i.ownerDocument)!==i)&&(d==null?i.defaultValue=""+i._wrapperState.initialValue:i.defaultValue!==""+d&&(i.defaultValue=""+d))}var xe=Array.isArray;function Ie(i,a,d,h){if(i=i.options,a){a={};for(var v=0;v<d.length;v++)a["$"+d[v]]=!0;for(d=0;d<i.length;d++)v=a.hasOwnProperty("$"+i[d].value),i[d].selected!==v&&(i[d].selected=v),v&&h&&(i[d].defaultSelected=!0)}else{for(d=""+pe(d),a=null,v=0;v<i.length;v++){if(i[v].value===d){i[v].selected=!0,h&&(i[v].defaultSelected=!0);return}a!==null||i[v].disabled||(a=i[v])}a!==null&&(a.selected=!0)}}function qe(i,a){if(a.dangerouslySetInnerHTML!=null)throw Error(n(91));return G({},a,{value:void 0,defaultValue:void 0,children:""+i._wrapperState.initialValue})}function zt(i,a){var d=a.value;if(d==null){if(d=a.children,a=a.defaultValue,d!=null){if(a!=null)throw Error(n(92));if(xe(d)){if(1<d.length)throw Error(n(93));d=d[0]}a=d}a==null&&(a=""),d=a}i._wrapperState={initialValue:pe(d)}}function en(i,a){var d=pe(a.value),h=pe(a.defaultValue);d!=null&&(d=""+d,d!==i.value&&(i.value=d),a.defaultValue==null&&i.defaultValue!==d&&(i.defaultValue=d)),h!=null&&(i.defaultValue=""+h)}function bn(i){var a=i.textContent;a===i._wrapperState.initialValue&&a!==""&&a!==null&&(i.value=a)}function Wt(i){switch(i){case"svg":return"http://www.w3.org/2000/svg";case"math":return"http://www.w3.org/1998/Math/MathML";default:return"http://www.w3.org/1999/xhtml"}}function It(i,a){return i==null||i==="http://www.w3.org/1999/xhtml"?Wt(a):i==="http://www.w3.org/2000/svg"&&a==="foreignObject"?"http://www.w3.org/1999/xhtml":i}var Sn,ns=(function(i){return typeof MSApp<"u"&&MSApp.execUnsafeLocalFunction?function(a,d,h,v){MSApp.execUnsafeLocalFunction(function(){return i(a,d,h,v)})}:i})(function(i,a){if(i.namespaceURI!=="http://www.w3.org/2000/svg"||"innerHTML"in i)i.innerHTML=a;else{for(Sn=Sn||document.createElement("div"),Sn.innerHTML="<svg>"+a.valueOf().toString()+"</svg>",a=Sn.firstChild;i.firstChild;)i.removeChild(i.firstChild);for(;a.firstChild;)i.appendChild(a.firstChild)}});function Ot(i,a){if(a){var d=i.firstChild;if(d&&d===i.lastChild&&d.nodeType===3){d.nodeValue=a;return}}i.textContent=a}var pn={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},Bn=["Webkit","ms","Moz","O"];Object.keys(pn).forEach(function(i){Bn.forEach(function(a){a=a+i.charAt(0).toUpperCase()+i.substring(1),pn[a]=pn[i]})});function An(i,a,d){return a==null||typeof a=="boolean"||a===""?"":d||typeof a!="number"||a===0||pn.hasOwnProperty(i)&&pn[i]?(""+a).trim():a+"px"}function gn(i,a){i=i.style;for(var d in a)if(a.hasOwnProperty(d)){var h=d.indexOf("--")===0,v=An(d,a[d],h);d==="float"&&(d="cssFloat"),h?i.setProperty(d,v):i[d]=v}}var In=G({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function wn(i,a){if(a){if(In[i]&&(a.children!=null||a.dangerouslySetInnerHTML!=null))throw Error(n(137,i));if(a.dangerouslySetInnerHTML!=null){if(a.children!=null)throw Error(n(60));if(typeof a.dangerouslySetInnerHTML!="object"||!("__html"in a.dangerouslySetInnerHTML))throw Error(n(61))}if(a.style!=null&&typeof a.style!="object")throw Error(n(62))}}function ks(i,a){if(i.indexOf("-")===-1)return typeof a.is=="string";switch(i){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var Kn=null;function js(i){return i=i.target||i.srcElement||window,i.correspondingUseElement&&(i=i.correspondingUseElement),i.nodeType===3?i.parentNode:i}var Nr=null,On=null,le=null;function ke(i){if(i=Uo(i)){if(typeof Nr!="function")throw Error(n(280));var a=i.stateNode;a&&(a=Ma(a),Nr(i.stateNode,i.type,a))}}function Ye(i){On?le?le.push(i):le=[i]:On=i}function Ge(){if(On){var i=On,a=le;if(le=On=null,ke(i),a)for(i=0;i<a.length;i++)ke(a[i])}}function rt(i,a){return i(a)}function ct(){}var Et=!1;function kt(i,a,d){if(Et)return i(a,d);Et=!0;try{return rt(i,a,d)}finally{Et=!1,(On!==null||le!==null)&&(ct(),Ge())}}function Kt(i,a){var d=i.stateNode;if(d===null)return null;var h=Ma(d);if(h===null)return null;d=h[a];e:switch(a){case"onClick":case"onClickCapture":case"onDoubleClick":case"onDoubleClickCapture":case"onMouseDown":case"onMouseDownCapture":case"onMouseMove":case"onMouseMoveCapture":case"onMouseUp":case"onMouseUpCapture":case"onMouseEnter":(h=!h.disabled)||(i=i.type,h=!(i==="button"||i==="input"||i==="select"||i==="textarea")),i=!h;break e;default:i=!1}if(i)return null;if(d&&typeof d!="function")throw Error(n(231,a,typeof d));return d}var xt=!1;if(c)try{var Yt={};Object.defineProperty(Yt,"passive",{get:function(){xt=!0}}),window.addEventListener("test",Yt,Yt),window.removeEventListener("test",Yt,Yt)}catch{xt=!1}function qt(i,a,d,h,v,k,L,Q,se){var we=Array.prototype.slice.call(arguments,3);try{a.apply(d,we)}catch($e){this.onError($e)}}var Pt=!1,At=null,$t=!1,De=null,on={onError:function(i){Pt=!0,At=i}};function ut(i,a,d,h,v,k,L,Q,se){Pt=!1,At=null,qt.apply(on,arguments)}function tn(i,a,d,h,v,k,L,Q,se){if(ut.apply(this,arguments),Pt){if(Pt){var we=At;Pt=!1,At=null}else throw Error(n(198));$t||($t=!0,De=we)}}function dt(i){var a=i,d=i;if(i.alternate)for(;a.return;)a=a.return;else{i=a;do a=i,(a.flags&4098)!==0&&(d=a.return),i=a.return;while(i)}return a.tag===3?d:null}function Un(i){if(i.tag===13){var a=i.memoizedState;if(a===null&&(i=i.alternate,i!==null&&(a=i.memoizedState)),a!==null)return a.dehydrated}return null}function an(i){if(dt(i)!==i)throw Error(n(188))}function Ys(i){var a=i.alternate;if(!a){if(a=dt(i),a===null)throw Error(n(188));return a!==i?null:i}for(var d=i,h=a;;){var v=d.return;if(v===null)break;var k=v.alternate;if(k===null){if(h=v.return,h!==null){d=h;continue}break}if(v.child===k.child){for(k=v.child;k;){if(k===d)return an(v),i;if(k===h)return an(v),a;k=k.sibling}throw Error(n(188))}if(d.return!==h.return)d=v,h=k;else{for(var L=!1,Q=v.child;Q;){if(Q===d){L=!0,d=v,h=k;break}if(Q===h){L=!0,h=v,d=k;break}Q=Q.sibling}if(!L){for(Q=k.child;Q;){if(Q===d){L=!0,d=k,h=v;break}if(Q===h){L=!0,h=k,d=v;break}Q=Q.sibling}if(!L)throw Error(n(189))}}if(d.alternate!==h)throw Error(n(190))}if(d.tag!==3)throw Error(n(188));return d.stateNode.current===d?i:a}function ss(i){return i=Ys(i),i!==null?Wr(i):null}function Wr(i){if(i.tag===5||i.tag===6)return i;for(i=i.child;i!==null;){var a=Wr(i);if(a!==null)return a;i=i.sibling}return null}var dr=t.unstable_scheduleCallback,ii=t.unstable_cancelCallback,oi=t.unstable_shouldYield,Ps=t.unstable_requestPaint,ue=t.unstable_now,fr=t.unstable_getCurrentPriorityLevel,Gi=t.unstable_ImmediatePriority,hr=t.unstable_UserBlockingPriority,Cr=t.unstable_NormalPriority,qr=t.unstable_LowPriority,it=t.unstable_IdlePriority,cn=null,Ds=null;function Hr(i){if(Ds&&typeof Ds.onCommitFiberRoot=="function")try{Ds.onCommitFiberRoot(cn,i,void 0,(i.current.flags&128)===128)}catch{}}var rs=Math.clz32?Math.clz32:$o,Eo=Math.log,Ao=Math.LN2;function $o(i){return i>>>=0,i===0?32:31-(Eo(i)/Ao|0)|0}var Pn=64,mr=4194304;function Hn(i){switch(i&-i){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return i&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return i&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return i}}function Ki(i,a){var d=i.pendingLanes;if(d===0)return 0;var h=0,v=i.suspendedLanes,k=i.pingedLanes,L=d&268435455;if(L!==0){var Q=L&~v;Q!==0?h=Hn(Q):(k&=L,k!==0&&(h=Hn(k)))}else L=d&~v,L!==0?h=Hn(L):k!==0&&(h=Hn(k));if(h===0)return 0;if(a!==0&&a!==h&&(a&v)===0&&(v=h&-h,k=a&-a,v>=k||v===16&&(k&4194240)!==0))return a;if((h&4)!==0&&(h|=d&16),a=i.entangledLanes,a!==0)for(i=i.entanglements,a&=h;0<a;)d=31-rs(a),v=1<<d,h|=i[d],a&=~v;return h}function ai(i,a){switch(i){case 1:case 2:case 4:return a+250;case 8:case 16:case 32:case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return a+5e3;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return-1;case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function $n(i,a){for(var d=i.suspendedLanes,h=i.pingedLanes,v=i.expirationTimes,k=i.pendingLanes;0<k;){var L=31-rs(k),Q=1<<L,se=v[L];se===-1?((Q&d)===0||(Q&h)!==0)&&(v[L]=ai(Q,a)):se<=a&&(i.expiredLanes|=Q),k&=~Q}}function Fs(i){return i=i.pendingLanes&-1073741825,i!==0?i:i&1073741824?1073741824:0}function hs(){var i=Pn;return Pn<<=1,(Pn&4194240)===0&&(Pn=64),i}function Js(i){for(var a=[],d=0;31>d;d++)a.push(i);return a}function ms(i,a,d){i.pendingLanes|=a,a!==536870912&&(i.suspendedLanes=0,i.pingedLanes=0),i=i.eventTimes,a=31-rs(a),i[a]=d}function da(i,a){var d=i.pendingLanes&~a;i.pendingLanes=a,i.suspendedLanes=0,i.pingedLanes=0,i.expiredLanes&=a,i.mutableReadLanes&=a,i.entangledLanes&=a,a=i.entanglements;var h=i.eventTimes;for(i=i.expirationTimes;0<d;){var v=31-rs(d),k=1<<v;a[v]=0,h[v]=-1,i[v]=-1,d&=~k}}function Yi(i,a){var d=i.entangledLanes|=a;for(i=i.entanglements;d;){var h=31-rs(d),v=1<<h;v&a|i[h]&a&&(i[h]|=a),d&=~v}}var ln=0;function fa(i){return i&=-i,1<i?4<i?(i&268435455)!==0?16:536870912:4:1}var dc,To,_s,Er,Ar,Ji=!1,_r=[],Ss=null,pr=null,$r=null,Xs=new Map,Ni=new Map,is=[],Tr="mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput copy cut paste click change contextmenu reset submit".split(" ");function ha(i,a){switch(i){case"focusin":case"focusout":Ss=null;break;case"dragenter":case"dragleave":pr=null;break;case"mouseover":case"mouseout":$r=null;break;case"pointerover":case"pointerout":Xs.delete(a.pointerId);break;case"gotpointercapture":case"lostpointercapture":Ni.delete(a.pointerId)}}function gr(i,a,d,h,v,k){return i===null||i.nativeEvent!==k?(i={blockedOn:a,domEventName:d,eventSystemFlags:h,nativeEvent:k,targetContainers:[v]},a!==null&&(a=Uo(a),a!==null&&To(a)),i):(i.eventSystemFlags|=h,a=i.targetContainers,v!==null&&a.indexOf(v)===-1&&a.push(v),i)}function Xi(i,a,d,h,v){switch(a){case"focusin":return Ss=gr(Ss,i,a,d,h,v),!0;case"dragenter":return pr=gr(pr,i,a,d,h,v),!0;case"mouseover":return $r=gr($r,i,a,d,h,v),!0;case"pointerover":var k=v.pointerId;return Xs.set(k,gr(Xs.get(k)||null,i,a,d,h,v)),!0;case"gotpointercapture":return k=v.pointerId,Ni.set(k,gr(Ni.get(k)||null,i,a,d,h,v)),!0}return!1}function fc(i){var a=Gr(i.target);if(a!==null){var d=dt(a);if(d!==null){if(a=d.tag,a===13){if(a=Un(d),a!==null){i.blockedOn=a,Ar(i.priority,function(){_s(d)});return}}else if(a===3&&d.stateNode.current.memoizedState.isDehydrated){i.blockedOn=d.tag===3?d.stateNode.containerInfo:null;return}}}i.blockedOn=null}function Ci(i){if(i.blockedOn!==null)return!1;for(var a=i.targetContainers;0<a.length;){var d=oe(i.domEventName,i.eventSystemFlags,a[0],i.nativeEvent);if(d===null){d=i.nativeEvent;var h=new d.constructor(d.type,d);Kn=h,d.target.dispatchEvent(h),Kn=null}else return a=Uo(d),a!==null&&To(a),i.blockedOn=d,!1;a.shift()}return!0}function Zs(i,a,d){Ci(i)&&d.delete(a)}function $u(){Ji=!1,Ss!==null&&Ci(Ss)&&(Ss=null),pr!==null&&Ci(pr)&&(pr=null),$r!==null&&Ci($r)&&($r=null),Xs.forEach(Zs),Ni.forEach(Zs)}function Qs(i,a){i.blockedOn===a&&(i.blockedOn=null,Ji||(Ji=!0,t.unstable_scheduleCallback(t.unstable_NormalPriority,$u)))}function Zi(i){function a(v){return Qs(v,i)}if(0<_r.length){Qs(_r[0],i);for(var d=1;d<_r.length;d++){var h=_r[d];h.blockedOn===i&&(h.blockedOn=null)}}for(Ss!==null&&Qs(Ss,i),pr!==null&&Qs(pr,i),$r!==null&&Qs($r,i),Xs.forEach(a),Ni.forEach(a),d=0;d<is.length;d++)h=is[d],h.blockedOn===i&&(h.blockedOn=null);for(;0<is.length&&(d=is[0],d.blockedOn===null);)fc(d),d.blockedOn===null&&is.shift()}var er=I.ReactCurrentBatchConfig,Mo=!0;function li(i,a,d,h){var v=ln,k=er.transition;er.transition=null;try{ln=1,ci(i,a,d,h)}finally{ln=v,er.transition=k}}function ll(i,a,d,h){var v=ln,k=er.transition;er.transition=null;try{ln=4,ci(i,a,d,h)}finally{ln=v,er.transition=k}}function ci(i,a,d,h){if(Mo){var v=oe(i,a,d,h);if(v===null)Yu(i,a,h,B,d),ha(i,h);else if(Xi(v,i,a,d,h))h.stopPropagation();else if(ha(i,h),a&4&&-1<Tr.indexOf(i)){for(;v!==null;){var k=Uo(v);if(k!==null&&dc(k),k=oe(i,a,d,h),k===null&&Yu(i,a,h,B,d),k===v)break;v=k}v!==null&&h.stopPropagation()}else Yu(i,a,h,null,d)}}var B=null;function oe(i,a,d,h){if(B=null,i=js(h),i=Gr(i),i!==null)if(a=dt(i),a===null)i=null;else if(d=a.tag,d===13){if(i=Un(a),i!==null)return i;i=null}else if(d===3){if(a.stateNode.current.memoizedState.isDehydrated)return a.tag===3?a.stateNode.containerInfo:null;i=null}else a!==i&&(i=null);return B=i,null}function be(i){switch(i){case"cancel":case"click":case"close":case"contextmenu":case"copy":case"cut":case"auxclick":case"dblclick":case"dragend":case"dragstart":case"drop":case"focusin":case"focusout":case"input":case"invalid":case"keydown":case"keypress":case"keyup":case"mousedown":case"mouseup":case"paste":case"pause":case"play":case"pointercancel":case"pointerdown":case"pointerup":case"ratechange":case"reset":case"resize":case"seeked":case"submit":case"touchcancel":case"touchend":case"touchstart":case"volumechange":case"change":case"selectionchange":case"textInput":case"compositionstart":case"compositionend":case"compositionupdate":case"beforeblur":case"afterblur":case"beforeinput":case"blur":case"fullscreenchange":case"focus":case"hashchange":case"popstate":case"select":case"selectstart":return 1;case"drag":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"mousemove":case"mouseout":case"mouseover":case"pointermove":case"pointerout":case"pointerover":case"scroll":case"toggle":case"touchmove":case"wheel":case"mouseenter":case"mouseleave":case"pointerenter":case"pointerleave":return 4;case"message":switch(fr()){case Gi:return 1;case hr:return 4;case Cr:case qr:return 16;case it:return 536870912;default:return 16}default:return 16}}var Se=null,Ee=null,He=null;function Qe(){if(He)return He;var i,a=Ee,d=a.length,h,v="value"in Se?Se.value:Se.textContent,k=v.length;for(i=0;i<d&&a[i]===v[i];i++);var L=d-i;for(h=1;h<=L&&a[d-h]===v[k-h];h++);return He=v.slice(i,1<h?1-h:void 0)}function ot(i){var a=i.keyCode;return"charCode"in i?(i=i.charCode,i===0&&a===13&&(i=13)):i=a,i===10&&(i=13),32<=i||i===13?i:0}function mt(){return!0}function Dt(){return!1}function Xt(i){function a(d,h,v,k,L){this._reactName=d,this._targetInst=v,this.type=h,this.nativeEvent=k,this.target=L,this.currentTarget=null;for(var Q in i)i.hasOwnProperty(Q)&&(d=i[Q],this[Q]=d?d(k):k[Q]);return this.isDefaultPrevented=(k.defaultPrevented!=null?k.defaultPrevented:k.returnValue===!1)?mt:Dt,this.isPropagationStopped=Dt,this}return G(a.prototype,{preventDefault:function(){this.defaultPrevented=!0;var d=this.nativeEvent;d&&(d.preventDefault?d.preventDefault():typeof d.returnValue!="unknown"&&(d.returnValue=!1),this.isDefaultPrevented=mt)},stopPropagation:function(){var d=this.nativeEvent;d&&(d.stopPropagation?d.stopPropagation():typeof d.cancelBubble!="unknown"&&(d.cancelBubble=!0),this.isPropagationStopped=mt)},persist:function(){},isPersistent:mt}),a}var Xn={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(i){return i.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},Bt=Xt(Xn),un=G({},Xn,{view:0,detail:0}),vn=Xt(un),kn,ps,Ns,yr=G({},un,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:Iu,button:0,buttons:0,relatedTarget:function(i){return i.relatedTarget===void 0?i.fromElement===i.srcElement?i.toElement:i.fromElement:i.relatedTarget},movementX:function(i){return"movementX"in i?i.movementX:(i!==Ns&&(Ns&&i.type==="mousemove"?(kn=i.screenX-Ns.screenX,ps=i.screenY-Ns.screenY):ps=kn=0,Ns=i),kn)},movementY:function(i){return"movementY"in i?i.movementY:ps}}),Ro=Xt(yr),Lo=G({},yr,{dataTransfer:0}),cl=Xt(Lo),hc=G({},un,{relatedTarget:0}),mc=Xt(hc),_c=G({},Xn,{animationName:0,elapsedTime:0,pseudoElement:0}),Tu=Xt(_c),pc=G({},Xn,{clipboardData:function(i){return"clipboardData"in i?i.clipboardData:window.clipboardData}}),gc=Xt(pc),yc=G({},Xn,{data:0}),Mu=Xt(yc),Io={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},If={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"},Ru={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function Lu(i){var a=this.nativeEvent;return a.getModifierState?a.getModifierState(i):(i=Ru[i])?!!a[i]:!1}function Iu(){return Lu}var Ou=G({},un,{key:function(i){if(i.key){var a=Io[i.key]||i.key;if(a!=="Unidentified")return a}return i.type==="keypress"?(i=ot(i),i===13?"Enter":String.fromCharCode(i)):i.type==="keydown"||i.type==="keyup"?If[i.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:Iu,charCode:function(i){return i.type==="keypress"?ot(i):0},keyCode:function(i){return i.type==="keydown"||i.type==="keyup"?i.keyCode:0},which:function(i){return i.type==="keypress"?ot(i):i.type==="keydown"||i.type==="keyup"?i.keyCode:0}}),Pu=Xt(Ou),nn=G({},yr,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),wc=Xt(nn),zm=G({},un,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:Iu}),Du=Xt(zm),Bm=G({},Xn,{propertyName:0,elapsedTime:0,pseudoElement:0}),Fu=Xt(Bm),Um=G({},yr,{deltaX:function(i){return"deltaX"in i?i.deltaX:"wheelDeltaX"in i?-i.wheelDeltaX:0},deltaY:function(i){return"deltaY"in i?i.deltaY:"wheelDeltaY"in i?-i.wheelDeltaY:"wheelDelta"in i?-i.wheelDelta:0},deltaZ:0,deltaMode:0}),tr=Xt(Um),Qi=[9,13,27,32],vc=c&&"CompositionEvent"in window,ul=null;c&&"documentMode"in document&&(ul=document.documentMode);var ma=c&&"TextEvent"in window&&!ul,xc=c&&(!vc||ul&&8<ul&&11>=ul),_a=" ",zu=!1;function Of(i,a){switch(i){case"keyup":return Qi.indexOf(a.keyCode)!==-1;case"keydown":return a.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Pf(i){return i=i.detail,typeof i=="object"&&"data"in i?i.data:null}var pa=!1;function Df(i,a){switch(i){case"compositionend":return Pf(a);case"keypress":return a.which!==32?null:(zu=!0,_a);case"textInput":return i=a.data,i===_a&&zu?null:i;default:return null}}function Wm(i,a){if(pa)return i==="compositionend"||!vc&&Of(i,a)?(i=Qe(),He=Ee=Se=null,pa=!1,i):null;switch(i){case"paste":return null;case"keypress":if(!(a.ctrlKey||a.altKey||a.metaKey)||a.ctrlKey&&a.altKey){if(a.char&&1<a.char.length)return a.char;if(a.which)return String.fromCharCode(a.which)}return null;case"compositionend":return xc&&a.locale!=="ko"?null:a.data;default:return null}}var Ff={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};function zf(i){var a=i&&i.nodeName&&i.nodeName.toLowerCase();return a==="input"?!!Ff[i.type]:a==="textarea"}function Bu(i,a,d,h){Ye(h),a=Sc(a,"onChange"),0<a.length&&(d=new Bt("onChange","change",null,d,h),i.push({event:d,listeners:a}))}var ga=null,Oo=null;function ya(i){kc(i,0)}function eo(i){var a=Kr(i);if(pt(a))return i}function wa(i,a){if(i==="change")return a}var va=!1;if(c){var xa;if(c){var dl="oninput"in document;if(!dl){var Uu=document.createElement("div");Uu.setAttribute("oninput","return;"),dl=typeof Uu.oninput=="function"}xa=dl}else xa=!1;va=xa&&(!document.documentMode||9<document.documentMode)}function ba(){ga&&(ga.detachEvent("onpropertychange",Wu),Oo=ga=null)}function Wu(i){if(i.propertyName==="value"&&eo(Oo)){var a=[];Bu(a,Oo,i,js(i)),kt(ya,a)}}function fl(i,a,d){i==="focusin"?(ba(),ga=a,Oo=d,ga.attachEvent("onpropertychange",Wu)):i==="focusout"&&ba()}function hl(i){if(i==="selectionchange"||i==="keyup"||i==="keydown")return eo(Oo)}function qm(i,a){if(i==="click")return eo(a)}function qu(i,a){if(i==="input"||i==="change")return eo(a)}function Hm(i,a){return i===a&&(i!==0||1/i===1/a)||i!==i&&a!==a}var Vr=typeof Object.is=="function"?Object.is:Hm;function to(i,a){if(Vr(i,a))return!0;if(typeof i!="object"||i===null||typeof a!="object"||a===null)return!1;var d=Object.keys(i),h=Object.keys(a);if(d.length!==h.length)return!1;for(h=0;h<d.length;h++){var v=d[h];if(!f.call(a,v)||!Vr(i[v],a[v]))return!1}return!0}function ui(i){for(;i&&i.firstChild;)i=i.firstChild;return i}function Po(i,a){var d=ui(i);i=0;for(var h;d;){if(d.nodeType===3){if(h=i+d.textContent.length,i<=a&&h>=a)return{node:d,offset:a-i};i=h}e:{for(;d;){if(d.nextSibling){d=d.nextSibling;break e}d=d.parentNode}d=void 0}d=ui(d)}}function Bf(i,a){return i&&a?i===a?!0:i&&i.nodeType===3?!1:a&&a.nodeType===3?Bf(i,a.parentNode):"contains"in i?i.contains(a):i.compareDocumentPosition?!!(i.compareDocumentPosition(a)&16):!1:!1}function ml(){for(var i=window,a=Fe();a instanceof i.HTMLIFrameElement;){try{var d=typeof a.contentWindow.location.href=="string"}catch{d=!1}if(d)i=a.contentWindow;else break;a=Fe(i.document)}return a}function Hu(i){var a=i&&i.nodeName&&i.nodeName.toLowerCase();return a&&(a==="input"&&(i.type==="text"||i.type==="search"||i.type==="tel"||i.type==="url"||i.type==="password")||a==="textarea"||i.contentEditable==="true")}function Vu(i){var a=ml(),d=i.focusedElem,h=i.selectionRange;if(a!==d&&d&&d.ownerDocument&&Bf(d.ownerDocument.documentElement,d)){if(h!==null&&Hu(d)){if(a=h.start,i=h.end,i===void 0&&(i=a),"selectionStart"in d)d.selectionStart=a,d.selectionEnd=Math.min(i,d.value.length);else if(i=(a=d.ownerDocument||document)&&a.defaultView||window,i.getSelection){i=i.getSelection();var v=d.textContent.length,k=Math.min(h.start,v);h=h.end===void 0?k:Math.min(h.end,v),!i.extend&&k>h&&(v=h,h=k,k=v),v=Po(d,k);var L=Po(d,h);v&&L&&(i.rangeCount!==1||i.anchorNode!==v.node||i.anchorOffset!==v.offset||i.focusNode!==L.node||i.focusOffset!==L.offset)&&(a=a.createRange(),a.setStart(v.node,v.offset),i.removeAllRanges(),k>h?(i.addRange(a),i.extend(L.node,L.offset)):(a.setEnd(L.node,L.offset),i.addRange(a)))}}for(a=[],i=d;i=i.parentNode;)i.nodeType===1&&a.push({element:i,left:i.scrollLeft,top:i.scrollTop});for(typeof d.focus=="function"&&d.focus(),d=0;d<a.length;d++)i=a[d],i.element.scrollLeft=i.left,i.element.scrollTop=i.top}}var _l=c&&"documentMode"in document&&11>=document.documentMode,gs=null,di=null,no=null,so=!1;function bc(i,a,d){var h=d.window===d?d.document:d.nodeType===9?d:d.ownerDocument;so||gs==null||gs!==Fe(h)||(h=gs,"selectionStart"in h&&Hu(h)?h={start:h.selectionStart,end:h.selectionEnd}:(h=(h.ownerDocument&&h.ownerDocument.defaultView||window).getSelection(),h={anchorNode:h.anchorNode,anchorOffset:h.anchorOffset,focusNode:h.focusNode,focusOffset:h.focusOffset}),no&&to(no,h)||(no=h,h=Sc(di,"onSelect"),0<h.length&&(a=new Bt("onSelect","select",null,a,d),i.push({event:a,listeners:h}),a.target=gs)))}function ro(i,a){var d={};return d[i.toLowerCase()]=a.toLowerCase(),d["Webkit"+i]="webkit"+a,d["Moz"+i]="moz"+a,d}var wr={animationend:ro("Animation","AnimationEnd"),animationiteration:ro("Animation","AnimationIteration"),animationstart:ro("Animation","AnimationStart"),transitionend:ro("Transition","TransitionEnd")},ka={},ja={};c&&(ja=document.createElement("div").style,"AnimationEvent"in window||(delete wr.animationend.animation,delete wr.animationiteration.animation,delete wr.animationstart.animation),"TransitionEvent"in window||delete wr.transitionend.transition);function Ei(i){if(ka[i])return ka[i];if(!wr[i])return i;var a=wr[i],d;for(d in a)if(a.hasOwnProperty(d)&&d in ja)return ka[i]=a[d];return i}var Ai=Ei("animationend"),zs=Ei("animationiteration"),io=Ei("animationstart"),Do=Ei("transitionend"),pl=new Map,oo="abort auxClick cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll toggle touchMove waiting wheel".split(" ");function fi(i,a){pl.set(i,a),l(a,[i])}for(var Sa=0;Sa<oo.length;Sa++){var Mr=oo[Sa],ao=Mr.toLowerCase(),hi=Mr[0].toUpperCase()+Mr.slice(1);fi(ao,"on"+hi)}fi(Ai,"onAnimationEnd"),fi(zs,"onAnimationIteration"),fi(io,"onAnimationStart"),fi("dblclick","onDoubleClick"),fi("focusin","onFocus"),fi("focusout","onBlur"),fi(Do,"onTransitionEnd"),u("onMouseEnter",["mouseout","mouseover"]),u("onMouseLeave",["mouseout","mouseover"]),u("onPointerEnter",["pointerout","pointerover"]),u("onPointerLeave",["pointerout","pointerover"]),l("onChange","change click focusin focusout input keydown keyup selectionchange".split(" ")),l("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" ")),l("onBeforeInput",["compositionend","keypress","textInput","paste"]),l("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" ")),l("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" ")),l("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var Na="abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange resize seeked seeking stalled suspend timeupdate volumechange waiting".split(" "),gl=new Set("cancel close invalid load scroll toggle".split(" ").concat(Na));function Gu(i,a,d){var h=i.type||"unknown-event";i.currentTarget=d,tn(h,a,void 0,i),i.currentTarget=null}function kc(i,a){a=(a&4)!==0;for(var d=0;d<i.length;d++){var h=i[d],v=h.event;h=h.listeners;e:{var k=void 0;if(a)for(var L=h.length-1;0<=L;L--){var Q=h[L],se=Q.instance,we=Q.currentTarget;if(Q=Q.listener,se!==k&&v.isPropagationStopped())break e;Gu(v,Q,we),k=se}else for(L=0;L<h.length;L++){if(Q=h[L],se=Q.instance,we=Q.currentTarget,Q=Q.listener,se!==k&&v.isPropagationStopped())break e;Gu(v,Q,we),k=se}}}if($t)throw i=De,$t=!1,De=null,i}function Nn(i,a){var d=a[Bo];d===void 0&&(d=a[Bo]=new Set);var h=i+"__bubble";d.has(h)||(Ku(a,i,2,!1),d.add(h))}function jc(i,a,d){var h=0;a&&(h|=4),Ku(d,i,h,a)}var yl="_reactListening"+Math.random().toString(36).slice(2);function wl(i){if(!i[yl]){i[yl]=!0,r.forEach(function(d){d!=="selectionchange"&&(gl.has(d)||jc(d,!1,i),jc(d,!0,i))});var a=i.nodeType===9?i:i.ownerDocument;a===null||a[yl]||(a[yl]=!0,jc("selectionchange",!1,a))}}function Ku(i,a,d,h){switch(be(a)){case 1:var v=li;break;case 4:v=ll;break;default:v=ci}d=v.bind(null,a,d,i),v=void 0,!xt||a!=="touchstart"&&a!=="touchmove"&&a!=="wheel"||(v=!0),h?v!==void 0?i.addEventListener(a,d,{capture:!0,passive:v}):i.addEventListener(a,d,!0):v!==void 0?i.addEventListener(a,d,{passive:v}):i.addEventListener(a,d,!1)}function Yu(i,a,d,h,v){var k=h;if((a&1)===0&&(a&2)===0&&h!==null)e:for(;;){if(h===null)return;var L=h.tag;if(L===3||L===4){var Q=h.stateNode.containerInfo;if(Q===v||Q.nodeType===8&&Q.parentNode===v)break;if(L===4)for(L=h.return;L!==null;){var se=L.tag;if((se===3||se===4)&&(se=L.stateNode.containerInfo,se===v||se.nodeType===8&&se.parentNode===v))return;L=L.return}for(;Q!==null;){if(L=Gr(Q),L===null)return;if(se=L.tag,se===5||se===6){h=k=L;continue e}Q=Q.parentNode}}h=h.return}kt(function(){var we=k,$e=js(d),Me=[];e:{var Ce=pl.get(i);if(Ce!==void 0){var Je=Bt,nt=i;switch(i){case"keypress":if(ot(d)===0)break e;case"keydown":case"keyup":Je=Pu;break;case"focusin":nt="focus",Je=mc;break;case"focusout":nt="blur",Je=mc;break;case"beforeblur":case"afterblur":Je=mc;break;case"click":if(d.button===2)break e;case"auxclick":case"dblclick":case"mousedown":case"mousemove":case"mouseup":case"mouseout":case"mouseover":case"contextmenu":Je=Ro;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":Je=cl;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":Je=Du;break;case Ai:case zs:case io:Je=Tu;break;case Do:Je=Fu;break;case"scroll":Je=vn;break;case"wheel":Je=tr;break;case"copy":case"cut":case"paste":Je=gc;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":Je=wc}var st=(a&4)!==0,ts=!st&&i==="scroll",de=st?Ce!==null?Ce+"Capture":null:Ce;st=[];for(var ae=we,_e;ae!==null;){_e=ae;var Pe=_e.stateNode;if(_e.tag===5&&Pe!==null&&(_e=Pe,de!==null&&(Pe=Kt(ae,de),Pe!=null&&st.push(Ca(ae,Pe,_e)))),ts)break;ae=ae.return}0<st.length&&(Ce=new Je(Ce,nt,null,d,$e),Me.push({event:Ce,listeners:st}))}}if((a&7)===0){e:{if(Ce=i==="mouseover"||i==="pointerover",Je=i==="mouseout"||i==="pointerout",Ce&&d!==Kn&&(nt=d.relatedTarget||d.fromElement)&&(Gr(nt)||nt[vr]))break e;if((Je||Ce)&&(Ce=$e.window===$e?$e:(Ce=$e.ownerDocument)?Ce.defaultView||Ce.parentWindow:window,Je?(nt=d.relatedTarget||d.toElement,Je=we,nt=nt?Gr(nt):null,nt!==null&&(ts=dt(nt),nt!==ts||nt.tag!==5&&nt.tag!==6)&&(nt=null)):(Je=null,nt=we),Je!==nt)){if(st=Ro,Pe="onMouseLeave",de="onMouseEnter",ae="mouse",(i==="pointerout"||i==="pointerover")&&(st=wc,Pe="onPointerLeave",de="onPointerEnter",ae="pointer"),ts=Je==null?Ce:Kr(Je),_e=nt==null?Ce:Kr(nt),Ce=new st(Pe,ae+"leave",Je,d,$e),Ce.target=ts,Ce.relatedTarget=_e,Pe=null,Gr($e)===we&&(st=new st(de,ae+"enter",nt,d,$e),st.target=_e,st.relatedTarget=ts,Pe=st),ts=Pe,Je&&nt)t:{for(st=Je,de=nt,ae=0,_e=st;_e;_e=Fo(_e))ae++;for(_e=0,Pe=de;Pe;Pe=Fo(Pe))_e++;for(;0<ae-_e;)st=Fo(st),ae--;for(;0<_e-ae;)de=Fo(de),_e--;for(;ae--;){if(st===de||de!==null&&st===de.alternate)break t;st=Fo(st),de=Fo(de)}st=null}else st=null;Je!==null&&Uf(Me,Ce,Je,st,!1),nt!==null&&ts!==null&&Uf(Me,ts,nt,st,!0)}}e:{if(Ce=we?Kr(we):window,Je=Ce.nodeName&&Ce.nodeName.toLowerCase(),Je==="select"||Je==="input"&&Ce.type==="file")var at=wa;else if(zf(Ce))if(va)at=qu;else{at=hl;var gt=fl}else(Je=Ce.nodeName)&&Je.toLowerCase()==="input"&&(Ce.type==="checkbox"||Ce.type==="radio")&&(at=qm);if(at&&(at=at(i,we))){Bu(Me,at,d,$e);break e}gt&&gt(i,Ce,we),i==="focusout"&&(gt=Ce._wrapperState)&&gt.controlled&&Ce.type==="number"&&ht(Ce,"number",Ce.value)}switch(gt=we?Kr(we):window,i){case"focusin":(zf(gt)||gt.contentEditable==="true")&&(gs=gt,di=we,no=null);break;case"focusout":no=di=gs=null;break;case"mousedown":so=!0;break;case"contextmenu":case"mouseup":case"dragend":so=!1,bc(Me,d,$e);break;case"selectionchange":if(_l)break;case"keydown":case"keyup":bc(Me,d,$e)}var yt;if(vc)e:{switch(i){case"compositionstart":var Nt="onCompositionStart";break e;case"compositionend":Nt="onCompositionEnd";break e;case"compositionupdate":Nt="onCompositionUpdate";break e}Nt=void 0}else pa?Of(i,d)&&(Nt="onCompositionEnd"):i==="keydown"&&d.keyCode===229&&(Nt="onCompositionStart");Nt&&(xc&&d.locale!=="ko"&&(pa||Nt!=="onCompositionStart"?Nt==="onCompositionEnd"&&pa&&(yt=Qe()):(Se=$e,Ee="value"in Se?Se.value:Se.textContent,pa=!0)),gt=Sc(we,Nt),0<gt.length&&(Nt=new Mu(Nt,i,null,d,$e),Me.push({event:Nt,listeners:gt}),yt?Nt.data=yt:(yt=Pf(d),yt!==null&&(Nt.data=yt)))),(yt=ma?Df(i,d):Wm(i,d))&&(we=Sc(we,"onBeforeInput"),0<we.length&&($e=new Mu("onBeforeInput","beforeinput",null,d,$e),Me.push({event:$e,listeners:we}),$e.data=yt))}kc(Me,a)})}function Ca(i,a,d){return{instance:i,listener:a,currentTarget:d}}function Sc(i,a){for(var d=a+"Capture",h=[];i!==null;){var v=i,k=v.stateNode;v.tag===5&&k!==null&&(v=k,k=Kt(i,d),k!=null&&h.unshift(Ca(i,k,v)),k=Kt(i,a),k!=null&&h.push(Ca(i,k,v))),i=i.return}return h}function Fo(i){if(i===null)return null;do i=i.return;while(i&&i.tag!==5);return i||null}function Uf(i,a,d,h,v){for(var k=a._reactName,L=[];d!==null&&d!==h;){var Q=d,se=Q.alternate,we=Q.stateNode;if(se!==null&&se===h)break;Q.tag===5&&we!==null&&(Q=we,v?(se=Kt(d,k),se!=null&&L.unshift(Ca(d,se,Q))):v||(se=Kt(d,k),se!=null&&L.push(Ca(d,se,Q)))),d=d.return}L.length!==0&&i.push({event:a,listeners:L})}var Wf=/\r\n?/g,Vm=/\u0000|\uFFFD/g;function Ju(i){return(typeof i=="string"?i:""+i).replace(Wf,`
38
- `).replace(Vm,"")}function lo(i,a,d){if(a=Ju(a),Ju(i)!==a&&d)throw Error(n(425))}function Nc(){}var zo=null,vl=null;function Ea(i,a){return i==="textarea"||i==="noscript"||typeof a.children=="string"||typeof a.children=="number"||typeof a.dangerouslySetInnerHTML=="object"&&a.dangerouslySetInnerHTML!==null&&a.dangerouslySetInnerHTML.__html!=null}var Cc=typeof setTimeout=="function"?setTimeout:void 0,Aa=typeof clearTimeout=="function"?clearTimeout:void 0,qf=typeof Promise=="function"?Promise:void 0,Ec=typeof queueMicrotask=="function"?queueMicrotask:typeof qf<"u"?function(i){return qf.resolve(null).then(i).catch(Gm)}:Cc;function Gm(i){setTimeout(function(){throw i})}function co(i,a){var d=a,h=0;do{var v=d.nextSibling;if(i.removeChild(d),v&&v.nodeType===8)if(d=v.data,d==="/$"){if(h===0){i.removeChild(v),Zi(a);return}h--}else d!=="$"&&d!=="$?"&&d!=="$!"||h++;d=v}while(d);Zi(a)}function uo(i){for(;i!=null;i=i.nextSibling){var a=i.nodeType;if(a===1||a===3)break;if(a===8){if(a=i.data,a==="$"||a==="$!"||a==="$?")break;if(a==="/$")return null}}return i}function xl(i){i=i.previousSibling;for(var a=0;i;){if(i.nodeType===8){var d=i.data;if(d==="$"||d==="$!"||d==="$?"){if(a===0)return i;a--}else d==="/$"&&a++}i=i.previousSibling}return null}var $a=Math.random().toString(36).slice(2),ys="__reactFiber$"+$a,Ta="__reactProps$"+$a,vr="__reactContainer$"+$a,Bo="__reactEvents$"+$a,Hf="__reactListeners$"+$a,Xu="__reactHandles$"+$a;function Gr(i){var a=i[ys];if(a)return a;for(var d=i.parentNode;d;){if(a=d[vr]||d[ys]){if(d=a.alternate,a.child!==null||d!==null&&d.child!==null)for(i=xl(i);i!==null;){if(d=i[ys])return d;i=xl(i)}return a}i=d,d=i.parentNode}return null}function Uo(i){return i=i[ys]||i[vr],!i||i.tag!==5&&i.tag!==6&&i.tag!==13&&i.tag!==3?null:i}function Kr(i){if(i.tag===5||i.tag===6)return i.stateNode;throw Error(n(33))}function Ma(i){return i[Ta]||null}var Zu=[],fo=-1;function $i(i){return{current:i}}function En(i){0>fo||(i.current=Zu[fo],Zu[fo]=null,fo--)}function Cn(i,a){fo++,Zu[fo]=i.current,i.current=a}var xr={},fn=$i(xr),ws=$i(!1),Ti=xr;function Ra(i,a){var d=i.type.contextTypes;if(!d)return xr;var h=i.stateNode;if(h&&h.__reactInternalMemoizedUnmaskedChildContext===a)return h.__reactInternalMemoizedMaskedChildContext;var v={},k;for(k in d)v[k]=a[k];return h&&(i=i.stateNode,i.__reactInternalMemoizedUnmaskedChildContext=a,i.__reactInternalMemoizedMaskedChildContext=v),v}function nr(i){return i=i.childContextTypes,i!=null}function La(){En(ws),En(fn)}function Vf(i,a,d){if(fn.current!==xr)throw Error(n(168));Cn(fn,a),Cn(ws,d)}function bl(i,a,d){var h=i.stateNode;if(a=a.childContextTypes,typeof h.getChildContext!="function")return d;h=h.getChildContext();for(var v in h)if(!(v in a))throw Error(n(108,he(i)||"Unknown",v));return G({},d,h)}function kl(i){return i=(i=i.stateNode)&&i.__reactInternalMemoizedMergedChildContext||xr,Ti=fn.current,Cn(fn,i),Cn(ws,ws.current),!0}function jl(i,a,d){var h=i.stateNode;if(!h)throw Error(n(169));d?(i=bl(i,a,Ti),h.__reactInternalMemoizedMergedChildContext=i,En(ws),En(fn),Cn(fn,i)):En(ws),Cn(ws,d)}var mi=null,Sl=!1,Qu=!1;function ed(i){mi===null?mi=[i]:mi.push(i)}function Gf(i){Sl=!0,ed(i)}function Mi(){if(!Qu&&mi!==null){Qu=!0;var i=0,a=ln;try{var d=mi;for(ln=1;i<d.length;i++){var h=d[i];do h=h(!0);while(h!==null)}mi=null,Sl=!1}catch(v){throw mi!==null&&(mi=mi.slice(i+1)),dr(Gi,Mi),v}finally{ln=a,Qu=!1}}return null}var Ia=[],Wo=0,qo=null,Ac=0,Rr=[],Lr=0,Ho=null,Yr=1,Ri="";function Li(i,a){Ia[Wo++]=Ac,Ia[Wo++]=qo,qo=i,Ac=a}function Kf(i,a,d){Rr[Lr++]=Yr,Rr[Lr++]=Ri,Rr[Lr++]=Ho,Ho=i;var h=Yr;i=Ri;var v=32-rs(h)-1;h&=~(1<<v),d+=1;var k=32-rs(a)+v;if(30<k){var L=v-v%5;k=(h&(1<<L)-1).toString(32),h>>=L,v-=L,Yr=1<<32-rs(a)+v|d<<v|h,Ri=k+i}else Yr=1<<k|d<<v|h,Ri=i}function $c(i){i.return!==null&&(Li(i,1),Kf(i,1,0))}function td(i){for(;i===qo;)qo=Ia[--Wo],Ia[Wo]=null,Ac=Ia[--Wo],Ia[Wo]=null;for(;i===Ho;)Ho=Rr[--Lr],Rr[Lr]=null,Ri=Rr[--Lr],Rr[Lr]=null,Yr=Rr[--Lr],Rr[Lr]=null}var Bs=null,Te=null,Tt=!1,br=null;function nd(i,a){var d=bi(5,null,null,0);d.elementType="DELETED",d.stateNode=a,d.return=i,a=i.deletions,a===null?(i.deletions=[d],i.flags|=16):a.push(d)}function Tc(i,a){switch(i.tag){case 5:var d=i.type;return a=a.nodeType!==1||d.toLowerCase()!==a.nodeName.toLowerCase()?null:a,a!==null?(i.stateNode=a,Bs=i,Te=uo(a.firstChild),!0):!1;case 6:return a=i.pendingProps===""||a.nodeType!==3?null:a,a!==null?(i.stateNode=a,Bs=i,Te=null,!0):!1;case 13:return a=a.nodeType!==8?null:a,a!==null?(d=Ho!==null?{id:Yr,overflow:Ri}:null,i.memoizedState={dehydrated:a,treeContext:d,retryLane:1073741824},d=bi(18,null,null,0),d.stateNode=a,d.return=i,i.child=d,Bs=i,Te=null,!0):!1;default:return!1}}function sd(i){return(i.mode&1)!==0&&(i.flags&128)===0}function rd(i){if(Tt){var a=Te;if(a){var d=a;if(!Tc(i,a)){if(sd(i))throw Error(n(418));a=uo(d.nextSibling);var h=Bs;a&&Tc(i,a)?nd(h,d):(i.flags=i.flags&-4097|2,Tt=!1,Bs=i)}}else{if(sd(i))throw Error(n(418));i.flags=i.flags&-4097|2,Tt=!1,Bs=i}}}function Yf(i){for(i=i.return;i!==null&&i.tag!==5&&i.tag!==3&&i.tag!==13;)i=i.return;Bs=i}function Nl(i){if(i!==Bs)return!1;if(!Tt)return Yf(i),Tt=!0,!1;var a;if((a=i.tag!==3)&&!(a=i.tag!==5)&&(a=i.type,a=a!=="head"&&a!=="body"&&!Ea(i.type,i.memoizedProps)),a&&(a=Te)){if(sd(i))throw id(),Error(n(418));for(;a;)nd(i,a),a=uo(a.nextSibling)}if(Yf(i),i.tag===13){if(i=i.memoizedState,i=i!==null?i.dehydrated:null,!i)throw Error(n(317));e:{for(i=i.nextSibling,a=0;i;){if(i.nodeType===8){var d=i.data;if(d==="/$"){if(a===0){Te=uo(i.nextSibling);break e}a--}else d!=="$"&&d!=="$!"&&d!=="$?"||a++}i=i.nextSibling}Te=null}}else Te=Bs?uo(i.stateNode.nextSibling):null;return!0}function id(){for(var i=Te;i;)i=uo(i.nextSibling)}function Oa(){Te=Bs=null,Tt=!1}function Pa(i){br===null?br=[i]:br.push(i)}var Us=I.ReactCurrentBatchConfig;function Ft(i,a,d){if(i=d.ref,i!==null&&typeof i!="function"&&typeof i!="object"){if(d._owner){if(d=d._owner,d){if(d.tag!==1)throw Error(n(309));var h=d.stateNode}if(!h)throw Error(n(147,i));var v=h,k=""+i;return a!==null&&a.ref!==null&&typeof a.ref=="function"&&a.ref._stringRef===k?a.ref:(a=function(L){var Q=v.refs;L===null?delete Q[k]:Q[k]=L},a._stringRef=k,a)}if(typeof i!="string")throw Error(n(284));if(!d._owner)throw Error(n(290,i))}return i}function Zn(i,a){throw i=Object.prototype.toString.call(a),Error(n(31,i==="[object Object]"?"object with keys {"+Object.keys(a).join(", ")+"}":i))}function Mc(i){var a=i._init;return a(i._payload)}function od(i){function a(de,ae){if(i){var _e=de.deletions;_e===null?(de.deletions=[ae],de.flags|=16):_e.push(ae)}}function d(de,ae){if(!i)return null;for(;ae!==null;)a(de,ae),ae=ae.sibling;return null}function h(de,ae){for(de=new Map;ae!==null;)ae.key!==null?de.set(ae.key,ae):de.set(ae.index,ae),ae=ae.sibling;return de}function v(de,ae){return de=Ja(de,ae),de.index=0,de.sibling=null,de}function k(de,ae,_e){return de.index=_e,i?(_e=de.alternate,_e!==null?(_e=_e.index,_e<ae?(de.flags|=2,ae):_e):(de.flags|=2,ae)):(de.flags|=1048576,ae)}function L(de){return i&&de.alternate===null&&(de.flags|=2),de}function Q(de,ae,_e,Pe){return ae===null||ae.tag!==6?(ae=l_(_e,de.mode,Pe),ae.return=de,ae):(ae=v(ae,_e),ae.return=de,ae)}function se(de,ae,_e,Pe){var at=_e.type;return at===J?$e(de,ae,_e.props.children,Pe,_e.key):ae!==null&&(ae.elementType===at||typeof at=="object"&&at!==null&&at.$$typeof===A&&Mc(at)===ae.type)?(Pe=v(ae,_e.props),Pe.ref=Ft(de,ae,_e),Pe.return=de,Pe):(Pe=yh(_e.type,_e.key,_e.props,null,de.mode,Pe),Pe.ref=Ft(de,ae,_e),Pe.return=de,Pe)}function we(de,ae,_e,Pe){return ae===null||ae.tag!==4||ae.stateNode.containerInfo!==_e.containerInfo||ae.stateNode.implementation!==_e.implementation?(ae=c_(_e,de.mode,Pe),ae.return=de,ae):(ae=v(ae,_e.children||[]),ae.return=de,ae)}function $e(de,ae,_e,Pe,at){return ae===null||ae.tag!==7?(ae=Wl(_e,de.mode,Pe,at),ae.return=de,ae):(ae=v(ae,_e),ae.return=de,ae)}function Me(de,ae,_e){if(typeof ae=="string"&&ae!==""||typeof ae=="number")return ae=l_(""+ae,de.mode,_e),ae.return=de,ae;if(typeof ae=="object"&&ae!==null){switch(ae.$$typeof){case K:return _e=yh(ae.type,ae.key,ae.props,null,de.mode,_e),_e.ref=Ft(de,null,ae),_e.return=de,_e;case U:return ae=c_(ae,de.mode,_e),ae.return=de,ae;case A:var Pe=ae._init;return Me(de,Pe(ae._payload),_e)}if(xe(ae)||F(ae))return ae=Wl(ae,de.mode,_e,null),ae.return=de,ae;Zn(de,ae)}return null}function Ce(de,ae,_e,Pe){var at=ae!==null?ae.key:null;if(typeof _e=="string"&&_e!==""||typeof _e=="number")return at!==null?null:Q(de,ae,""+_e,Pe);if(typeof _e=="object"&&_e!==null){switch(_e.$$typeof){case K:return _e.key===at?se(de,ae,_e,Pe):null;case U:return _e.key===at?we(de,ae,_e,Pe):null;case A:return at=_e._init,Ce(de,ae,at(_e._payload),Pe)}if(xe(_e)||F(_e))return at!==null?null:$e(de,ae,_e,Pe,null);Zn(de,_e)}return null}function Je(de,ae,_e,Pe,at){if(typeof Pe=="string"&&Pe!==""||typeof Pe=="number")return de=de.get(_e)||null,Q(ae,de,""+Pe,at);if(typeof Pe=="object"&&Pe!==null){switch(Pe.$$typeof){case K:return de=de.get(Pe.key===null?_e:Pe.key)||null,se(ae,de,Pe,at);case U:return de=de.get(Pe.key===null?_e:Pe.key)||null,we(ae,de,Pe,at);case A:var gt=Pe._init;return Je(de,ae,_e,gt(Pe._payload),at)}if(xe(Pe)||F(Pe))return de=de.get(_e)||null,$e(ae,de,Pe,at,null);Zn(ae,Pe)}return null}function nt(de,ae,_e,Pe){for(var at=null,gt=null,yt=ae,Nt=ae=0,Rs=null;yt!==null&&Nt<_e.length;Nt++){yt.index>Nt?(Rs=yt,yt=null):Rs=yt.sibling;var mn=Ce(de,yt,_e[Nt],Pe);if(mn===null){yt===null&&(yt=Rs);break}i&&yt&&mn.alternate===null&&a(de,yt),ae=k(mn,ae,Nt),gt===null?at=mn:gt.sibling=mn,gt=mn,yt=Rs}if(Nt===_e.length)return d(de,yt),Tt&&Li(de,Nt),at;if(yt===null){for(;Nt<_e.length;Nt++)yt=Me(de,_e[Nt],Pe),yt!==null&&(ae=k(yt,ae,Nt),gt===null?at=yt:gt.sibling=yt,gt=yt);return Tt&&Li(de,Nt),at}for(yt=h(de,yt);Nt<_e.length;Nt++)Rs=Je(yt,de,Nt,_e[Nt],Pe),Rs!==null&&(i&&Rs.alternate!==null&&yt.delete(Rs.key===null?Nt:Rs.key),ae=k(Rs,ae,Nt),gt===null?at=Rs:gt.sibling=Rs,gt=Rs);return i&&yt.forEach(function(Xa){return a(de,Xa)}),Tt&&Li(de,Nt),at}function st(de,ae,_e,Pe){var at=F(_e);if(typeof at!="function")throw Error(n(150));if(_e=at.call(_e),_e==null)throw Error(n(151));for(var gt=at=null,yt=ae,Nt=ae=0,Rs=null,mn=_e.next();yt!==null&&!mn.done;Nt++,mn=_e.next()){yt.index>Nt?(Rs=yt,yt=null):Rs=yt.sibling;var Xa=Ce(de,yt,mn.value,Pe);if(Xa===null){yt===null&&(yt=Rs);break}i&&yt&&Xa.alternate===null&&a(de,yt),ae=k(Xa,ae,Nt),gt===null?at=Xa:gt.sibling=Xa,gt=Xa,yt=Rs}if(mn.done)return d(de,yt),Tt&&Li(de,Nt),at;if(yt===null){for(;!mn.done;Nt++,mn=_e.next())mn=Me(de,mn.value,Pe),mn!==null&&(ae=k(mn,ae,Nt),gt===null?at=mn:gt.sibling=mn,gt=mn);return Tt&&Li(de,Nt),at}for(yt=h(de,yt);!mn.done;Nt++,mn=_e.next())mn=Je(yt,de,Nt,mn.value,Pe),mn!==null&&(i&&mn.alternate!==null&&yt.delete(mn.key===null?Nt:mn.key),ae=k(mn,ae,Nt),gt===null?at=mn:gt.sibling=mn,gt=mn);return i&&yt.forEach(function(ek){return a(de,ek)}),Tt&&Li(de,Nt),at}function ts(de,ae,_e,Pe){if(typeof _e=="object"&&_e!==null&&_e.type===J&&_e.key===null&&(_e=_e.props.children),typeof _e=="object"&&_e!==null){switch(_e.$$typeof){case K:e:{for(var at=_e.key,gt=ae;gt!==null;){if(gt.key===at){if(at=_e.type,at===J){if(gt.tag===7){d(de,gt.sibling),ae=v(gt,_e.props.children),ae.return=de,de=ae;break e}}else if(gt.elementType===at||typeof at=="object"&&at!==null&&at.$$typeof===A&&Mc(at)===gt.type){d(de,gt.sibling),ae=v(gt,_e.props),ae.ref=Ft(de,gt,_e),ae.return=de,de=ae;break e}d(de,gt);break}else a(de,gt);gt=gt.sibling}_e.type===J?(ae=Wl(_e.props.children,de.mode,Pe,_e.key),ae.return=de,de=ae):(Pe=yh(_e.type,_e.key,_e.props,null,de.mode,Pe),Pe.ref=Ft(de,ae,_e),Pe.return=de,de=Pe)}return L(de);case U:e:{for(gt=_e.key;ae!==null;){if(ae.key===gt)if(ae.tag===4&&ae.stateNode.containerInfo===_e.containerInfo&&ae.stateNode.implementation===_e.implementation){d(de,ae.sibling),ae=v(ae,_e.children||[]),ae.return=de,de=ae;break e}else{d(de,ae);break}else a(de,ae);ae=ae.sibling}ae=c_(_e,de.mode,Pe),ae.return=de,de=ae}return L(de);case A:return gt=_e._init,ts(de,ae,gt(_e._payload),Pe)}if(xe(_e))return nt(de,ae,_e,Pe);if(F(_e))return st(de,ae,_e,Pe);Zn(de,_e)}return typeof _e=="string"&&_e!==""||typeof _e=="number"?(_e=""+_e,ae!==null&&ae.tag===6?(d(de,ae.sibling),ae=v(ae,_e),ae.return=de,de=ae):(d(de,ae),ae=l_(_e,de.mode,Pe),ae.return=de,de=ae),L(de)):d(de,ae)}return ts}var _i=od(!0),Vo=od(!1),ft=$i(null),Rc=null,ho=null,ad=null;function ld(){ad=ho=Rc=null}function Lc(i){var a=ft.current;En(ft),i._currentValue=a}function cd(i,a,d){for(;i!==null;){var h=i.alternate;if((i.childLanes&a)!==a?(i.childLanes|=a,h!==null&&(h.childLanes|=a)):h!==null&&(h.childLanes&a)!==a&&(h.childLanes|=a),i===d)break;i=i.return}}function Da(i,a){Rc=i,ad=ho=null,i=i.dependencies,i!==null&&i.firstContext!==null&&((i.lanes&a)!==0&&(As=!0),i.firstContext=null)}function Ir(i){var a=i._currentValue;if(ad!==i)if(i={context:i,memoizedValue:a,next:null},ho===null){if(Rc===null)throw Error(n(308));ho=i,Rc.dependencies={lanes:0,firstContext:i}}else ho=ho.next=i;return a}var Ii=null;function Jr(i){Ii===null?Ii=[i]:Ii.push(i)}function ud(i,a,d,h){var v=a.interleaved;return v===null?(d.next=d,Jr(a)):(d.next=v.next,v.next=d),a.interleaved=d,os(i,h)}function os(i,a){i.lanes|=a;var d=i.alternate;for(d!==null&&(d.lanes|=a),d=i,i=i.return;i!==null;)i.childLanes|=a,d=i.alternate,d!==null&&(d.childLanes|=a),d=i,i=i.return;return d.tag===3?d.stateNode:null}var as=!1;function Fa(i){i.updateQueue={baseState:i.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function Jf(i,a){i=i.updateQueue,a.updateQueue===i&&(a.updateQueue={baseState:i.baseState,firstBaseUpdate:i.firstBaseUpdate,lastBaseUpdate:i.lastBaseUpdate,shared:i.shared,effects:i.effects})}function Oi(i,a){return{eventTime:i,lane:a,tag:0,payload:null,callback:null,next:null}}function pi(i,a,d){var h=i.updateQueue;if(h===null)return null;if(h=h.shared,(sn&2)!==0){var v=h.pending;return v===null?a.next=a:(a.next=v.next,v.next=a),h.pending=a,os(i,d)}return v=h.interleaved,v===null?(a.next=a,Jr(h)):(a.next=v.next,v.next=a),h.interleaved=a,os(i,d)}function Cl(i,a,d){if(a=a.updateQueue,a!==null&&(a=a.shared,(d&4194240)!==0)){var h=a.lanes;h&=i.pendingLanes,d|=h,a.lanes=d,Yi(i,d)}}function Ic(i,a){var d=i.updateQueue,h=i.alternate;if(h!==null&&(h=h.updateQueue,d===h)){var v=null,k=null;if(d=d.firstBaseUpdate,d!==null){do{var L={eventTime:d.eventTime,lane:d.lane,tag:d.tag,payload:d.payload,callback:d.callback,next:null};k===null?v=k=L:k=k.next=L,d=d.next}while(d!==null);k===null?v=k=a:k=k.next=a}else v=k=a;d={baseState:h.baseState,firstBaseUpdate:v,lastBaseUpdate:k,shared:h.shared,effects:h.effects},i.updateQueue=d;return}i=d.lastBaseUpdate,i===null?d.firstBaseUpdate=a:i.next=a,d.lastBaseUpdate=a}function Oc(i,a,d,h){var v=i.updateQueue;as=!1;var k=v.firstBaseUpdate,L=v.lastBaseUpdate,Q=v.shared.pending;if(Q!==null){v.shared.pending=null;var se=Q,we=se.next;se.next=null,L===null?k=we:L.next=we,L=se;var $e=i.alternate;$e!==null&&($e=$e.updateQueue,Q=$e.lastBaseUpdate,Q!==L&&(Q===null?$e.firstBaseUpdate=we:Q.next=we,$e.lastBaseUpdate=se))}if(k!==null){var Me=v.baseState;L=0,$e=we=se=null,Q=k;do{var Ce=Q.lane,Je=Q.eventTime;if((h&Ce)===Ce){$e!==null&&($e=$e.next={eventTime:Je,lane:0,tag:Q.tag,payload:Q.payload,callback:Q.callback,next:null});e:{var nt=i,st=Q;switch(Ce=a,Je=d,st.tag){case 1:if(nt=st.payload,typeof nt=="function"){Me=nt.call(Je,Me,Ce);break e}Me=nt;break e;case 3:nt.flags=nt.flags&-65537|128;case 0:if(nt=st.payload,Ce=typeof nt=="function"?nt.call(Je,Me,Ce):nt,Ce==null)break e;Me=G({},Me,Ce);break e;case 2:as=!0}}Q.callback!==null&&Q.lane!==0&&(i.flags|=64,Ce=v.effects,Ce===null?v.effects=[Q]:Ce.push(Q))}else Je={eventTime:Je,lane:Ce,tag:Q.tag,payload:Q.payload,callback:Q.callback,next:null},$e===null?(we=$e=Je,se=Me):$e=$e.next=Je,L|=Ce;if(Q=Q.next,Q===null){if(Q=v.shared.pending,Q===null)break;Ce=Q,Q=Ce.next,Ce.next=null,v.lastBaseUpdate=Ce,v.shared.pending=null}}while(!0);if($e===null&&(se=Me),v.baseState=se,v.firstBaseUpdate=we,v.lastBaseUpdate=$e,a=v.shared.interleaved,a!==null){v=a;do L|=v.lane,v=v.next;while(v!==a)}else k===null&&(v.shared.lanes=0);wo|=L,i.lanes=L,i.memoizedState=Me}}function Tn(i,a,d){if(i=a.effects,a.effects=null,i!==null)for(a=0;a<i.length;a++){var h=i[a],v=h.callback;if(v!==null){if(h.callback=null,h=d,typeof v!="function")throw Error(n(191,v));v.call(h)}}}var za={},Or=$i(za),ls=$i(za),Ba=$i(za);function Xr(i){if(i===za)throw Error(n(174));return i}function El(i,a){switch(Cn(Ba,a),Cn(ls,i),Cn(Or,za),i=a.nodeType,i){case 9:case 11:a=(a=a.documentElement)?a.namespaceURI:It(null,"");break;default:i=i===8?a.parentNode:a,a=i.namespaceURI||null,i=i.tagName,a=It(a,i)}En(Or),Cn(Or,a)}function gi(){En(Or),En(ls),En(Ba)}function Pc(i){Xr(Ba.current);var a=Xr(Or.current),d=It(a,i.type);a!==d&&(Cn(ls,i),Cn(Or,d))}function dd(i){ls.current===i&&(En(Or),En(ls))}var Dn=$i(0);function Dc(i){for(var a=i;a!==null;){if(a.tag===13){var d=a.memoizedState;if(d!==null&&(d=d.dehydrated,d===null||d.data==="$?"||d.data==="$!"))return a}else if(a.tag===19&&a.memoizedProps.revealOrder!==void 0){if((a.flags&128)!==0)return a}else if(a.child!==null){a.child.return=a,a=a.child;continue}if(a===i)break;for(;a.sibling===null;){if(a.return===null||a.return===i)return null;a=a.return}a.sibling.return=a.return,a=a.sibling}return null}var Al=[];function Fc(){for(var i=0;i<Al.length;i++)Al[i]._workInProgressVersionPrimary=null;Al.length=0}var zc=I.ReactCurrentDispatcher,$l=I.ReactCurrentBatchConfig,Go=0,yn=null,Mn=null,Ht=null,Bc=!1,Tl=!1,Ml=0,Km=0;function Cs(){throw Error(n(321))}function fd(i,a){if(a===null)return!1;for(var d=0;d<a.length&&d<i.length;d++)if(!Vr(i[d],a[d]))return!1;return!0}function Jt(i,a,d,h,v,k){if(Go=k,yn=a,a.memoizedState=null,a.updateQueue=null,a.lanes=0,zc.current=i===null||i.memoizedState===null?_o:ti,i=d(h,v),Tl){k=0;do{if(Tl=!1,Ml=0,25<=k)throw Error(n(301));k+=1,Ht=Mn=null,a.updateQueue=null,zc.current=Xm,i=d(h,v)}while(Tl)}if(zc.current=ei,a=Mn!==null&&Mn.next!==null,Go=0,Ht=Mn=yn=null,Bc=!1,a)throw Error(n(300));return i}function Qn(){var i=Ml!==0;return Ml=0,i}function Fn(){var i={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return Ht===null?yn.memoizedState=Ht=i:Ht=Ht.next=i,Ht}function sr(){if(Mn===null){var i=yn.alternate;i=i!==null?i.memoizedState:null}else i=Mn.next;var a=Ht===null?yn.memoizedState:Ht.next;if(a!==null)Ht=a,Mn=i;else{if(i===null)throw Error(n(310));Mn=i,i={memoizedState:Mn.memoizedState,baseState:Mn.baseState,baseQueue:Mn.baseQueue,queue:Mn.queue,next:null},Ht===null?yn.memoizedState=Ht=i:Ht=Ht.next=i}return Ht}function mo(i,a){return typeof a=="function"?a(i):a}function Uc(i){var a=sr(),d=a.queue;if(d===null)throw Error(n(311));d.lastRenderedReducer=i;var h=Mn,v=h.baseQueue,k=d.pending;if(k!==null){if(v!==null){var L=v.next;v.next=k.next,k.next=L}h.baseQueue=v=k,d.pending=null}if(v!==null){k=v.next,h=h.baseState;var Q=L=null,se=null,we=k;do{var $e=we.lane;if((Go&$e)===$e)se!==null&&(se=se.next={lane:0,action:we.action,hasEagerState:we.hasEagerState,eagerState:we.eagerState,next:null}),h=we.hasEagerState?we.eagerState:i(h,we.action);else{var Me={lane:$e,action:we.action,hasEagerState:we.hasEagerState,eagerState:we.eagerState,next:null};se===null?(Q=se=Me,L=h):se=se.next=Me,yn.lanes|=$e,wo|=$e}we=we.next}while(we!==null&&we!==k);se===null?L=h:se.next=Q,Vr(h,a.memoizedState)||(As=!0),a.memoizedState=h,a.baseState=L,a.baseQueue=se,d.lastRenderedState=h}if(i=d.interleaved,i!==null){v=i;do k=v.lane,yn.lanes|=k,wo|=k,v=v.next;while(v!==i)}else v===null&&(d.lanes=0);return[a.memoizedState,d.dispatch]}function hd(i){var a=sr(),d=a.queue;if(d===null)throw Error(n(311));d.lastRenderedReducer=i;var h=d.dispatch,v=d.pending,k=a.memoizedState;if(v!==null){d.pending=null;var L=v=v.next;do k=i(k,L.action),L=L.next;while(L!==v);Vr(k,a.memoizedState)||(As=!0),a.memoizedState=k,a.baseQueue===null&&(a.baseState=k),d.lastRenderedState=k}return[k,h]}function Xf(){}function md(i,a){var d=yn,h=sr(),v=a(),k=!Vr(h.memoizedState,v);if(k&&(h.memoizedState=v,As=!0),h=h.queue,yd(Qf.bind(null,d,h,i),[i]),h.getSnapshot!==a||k||Ht!==null&&Ht.memoizedState.tag&1){if(d.flags|=2048,Zr(9,Zf.bind(null,d,h,v,a),void 0,null),es===null)throw Error(n(349));(Go&30)!==0||Rl(d,a,v)}return v}function Rl(i,a,d){i.flags|=16384,i={getSnapshot:a,value:d},a=yn.updateQueue,a===null?(a={lastEffect:null,stores:null},yn.updateQueue=a,a.stores=[i]):(d=a.stores,d===null?a.stores=[i]:d.push(i))}function Zf(i,a,d,h){a.value=d,a.getSnapshot=h,eh(a)&&_d(i)}function Qf(i,a,d){return d(function(){eh(a)&&_d(i)})}function eh(i){var a=i.getSnapshot;i=i.value;try{var d=a();return!Vr(i,d)}catch{return!0}}function _d(i){var a=os(i,1);a!==null&&Oe(a,i,1,-1)}function pd(i){var a=Fn();return typeof i=="function"&&(i=i()),a.memoizedState=a.baseState=i,i={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:mo,lastRenderedState:i},a.queue=i,i=i.dispatch=Ko.bind(null,yn,i),[a.memoizedState,i]}function Zr(i,a,d,h){return i={tag:i,create:a,destroy:d,deps:h,next:null},a=yn.updateQueue,a===null?(a={lastEffect:null,stores:null},yn.updateQueue=a,a.lastEffect=i.next=i):(d=a.lastEffect,d===null?a.lastEffect=i.next=i:(h=d.next,d.next=i,i.next=h,a.lastEffect=i)),i}function Wc(){return sr().memoizedState}function Ll(i,a,d,h){var v=Fn();yn.flags|=i,v.memoizedState=Zr(1|a,d,void 0,h===void 0?null:h)}function Ua(i,a,d,h){var v=sr();h=h===void 0?null:h;var k=void 0;if(Mn!==null){var L=Mn.memoizedState;if(k=L.destroy,h!==null&&fd(h,L.deps)){v.memoizedState=Zr(a,d,k,h);return}}yn.flags|=i,v.memoizedState=Zr(1|a,d,k,h)}function gd(i,a){return Ll(8390656,8,i,a)}function yd(i,a){return Ua(2048,8,i,a)}function th(i,a){return Ua(4,2,i,a)}function nh(i,a){return Ua(4,4,i,a)}function sh(i,a){if(typeof a=="function")return i=i(),a(i),function(){a(null)};if(a!=null)return i=i(),a.current=i,function(){a.current=null}}function rh(i,a,d){return d=d!=null?d.concat([i]):null,Ua(4,4,sh.bind(null,a,i),d)}function wd(){}function vd(i,a){var d=sr();a=a===void 0?null:a;var h=d.memoizedState;return h!==null&&a!==null&&fd(a,h[1])?h[0]:(d.memoizedState=[i,a],i)}function qc(i,a){var d=sr();a=a===void 0?null:a;var h=d.memoizedState;return h!==null&&a!==null&&fd(a,h[1])?h[0]:(i=i(),d.memoizedState=[i,a],i)}function ih(i,a,d){return(Go&21)===0?(i.baseState&&(i.baseState=!1,As=!0),i.memoizedState=d):(Vr(d,a)||(d=hs(),yn.lanes|=d,wo|=d,i.baseState=!0),a)}function Ym(i,a){var d=ln;ln=d!==0&&4>d?d:4,i(!0);var h=$l.transition;$l.transition={};try{i(!1),a()}finally{ln=d,$l.transition=h}}function Il(){return sr().memoizedState}function Jm(i,a,d){var h=Ae(i);if(d={lane:h,action:d,hasEagerState:!1,eagerState:null,next:null},Es(i))cs(a,d);else if(d=ud(i,a,d,h),d!==null){var v=me();Oe(d,i,h,v),Qr(d,a,h)}}function Ko(i,a,d){var h=Ae(i),v={lane:h,action:d,hasEagerState:!1,eagerState:null,next:null};if(Es(i))cs(a,v);else{var k=i.alternate;if(i.lanes===0&&(k===null||k.lanes===0)&&(k=a.lastRenderedReducer,k!==null))try{var L=a.lastRenderedState,Q=k(L,d);if(v.hasEagerState=!0,v.eagerState=Q,Vr(Q,L)){var se=a.interleaved;se===null?(v.next=v,Jr(a)):(v.next=se.next,se.next=v),a.interleaved=v;return}}catch{}finally{}d=ud(i,a,v,h),d!==null&&(v=me(),Oe(d,i,h,v),Qr(d,a,h))}}function Es(i){var a=i.alternate;return i===yn||a!==null&&a===yn}function cs(i,a){Tl=Bc=!0;var d=i.pending;d===null?a.next=a:(a.next=d.next,d.next=a),i.pending=a}function Qr(i,a,d){if((d&4194240)!==0){var h=a.lanes;h&=i.pendingLanes,d|=h,a.lanes=d,Yi(i,d)}}var ei={readContext:Ir,useCallback:Cs,useContext:Cs,useEffect:Cs,useImperativeHandle:Cs,useInsertionEffect:Cs,useLayoutEffect:Cs,useMemo:Cs,useReducer:Cs,useRef:Cs,useState:Cs,useDebugValue:Cs,useDeferredValue:Cs,useTransition:Cs,useMutableSource:Cs,useSyncExternalStore:Cs,useId:Cs,unstable_isNewReconciler:!1},_o={readContext:Ir,useCallback:function(i,a){return Fn().memoizedState=[i,a===void 0?null:a],i},useContext:Ir,useEffect:gd,useImperativeHandle:function(i,a,d){return d=d!=null?d.concat([i]):null,Ll(4194308,4,sh.bind(null,a,i),d)},useLayoutEffect:function(i,a){return Ll(4194308,4,i,a)},useInsertionEffect:function(i,a){return Ll(4,2,i,a)},useMemo:function(i,a){var d=Fn();return a=a===void 0?null:a,i=i(),d.memoizedState=[i,a],i},useReducer:function(i,a,d){var h=Fn();return a=d!==void 0?d(a):a,h.memoizedState=h.baseState=a,i={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:i,lastRenderedState:a},h.queue=i,i=i.dispatch=Jm.bind(null,yn,i),[h.memoizedState,i]},useRef:function(i){var a=Fn();return i={current:i},a.memoizedState=i},useState:pd,useDebugValue:wd,useDeferredValue:function(i){return Fn().memoizedState=i},useTransition:function(){var i=pd(!1),a=i[0];return i=Ym.bind(null,i[1]),Fn().memoizedState=i,[a,i]},useMutableSource:function(){},useSyncExternalStore:function(i,a,d){var h=yn,v=Fn();if(Tt){if(d===void 0)throw Error(n(407));d=d()}else{if(d=a(),es===null)throw Error(n(349));(Go&30)!==0||Rl(h,a,d)}v.memoizedState=d;var k={value:d,getSnapshot:a};return v.queue=k,gd(Qf.bind(null,h,k,i),[i]),h.flags|=2048,Zr(9,Zf.bind(null,h,k,d,a),void 0,null),d},useId:function(){var i=Fn(),a=es.identifierPrefix;if(Tt){var d=Ri,h=Yr;d=(h&~(1<<32-rs(h)-1)).toString(32)+d,a=":"+a+"R"+d,d=Ml++,0<d&&(a+="H"+d.toString(32)),a+=":"}else d=Km++,a=":"+a+"r"+d.toString(32)+":";return i.memoizedState=a},unstable_isNewReconciler:!1},ti={readContext:Ir,useCallback:vd,useContext:Ir,useEffect:yd,useImperativeHandle:rh,useInsertionEffect:th,useLayoutEffect:nh,useMemo:qc,useReducer:Uc,useRef:Wc,useState:function(){return Uc(mo)},useDebugValue:wd,useDeferredValue:function(i){var a=sr();return ih(a,Mn.memoizedState,i)},useTransition:function(){var i=Uc(mo)[0],a=sr().memoizedState;return[i,a]},useMutableSource:Xf,useSyncExternalStore:md,useId:Il,unstable_isNewReconciler:!1},Xm={readContext:Ir,useCallback:vd,useContext:Ir,useEffect:yd,useImperativeHandle:rh,useInsertionEffect:th,useLayoutEffect:nh,useMemo:qc,useReducer:hd,useRef:Wc,useState:function(){return hd(mo)},useDebugValue:wd,useDeferredValue:function(i){var a=sr();return Mn===null?a.memoizedState=i:ih(a,Mn.memoizedState,i)},useTransition:function(){var i=hd(mo)[0],a=sr().memoizedState;return[i,a]},useMutableSource:Xf,useSyncExternalStore:md,useId:Il,unstable_isNewReconciler:!1};function rr(i,a){if(i&&i.defaultProps){a=G({},a),i=i.defaultProps;for(var d in i)a[d]===void 0&&(a[d]=i[d]);return a}return a}function xd(i,a,d,h){a=i.memoizedState,d=d(h,a),d=d==null?a:G({},a,d),i.memoizedState=d,i.lanes===0&&(i.updateQueue.baseState=d)}var Wa={isMounted:function(i){return(i=i._reactInternals)?dt(i)===i:!1},enqueueSetState:function(i,a,d){i=i._reactInternals;var h=me(),v=Ae(i),k=Oi(h,v);k.payload=a,d!=null&&(k.callback=d),a=pi(i,k,v),a!==null&&(Oe(a,i,v,h),Cl(a,i,v))},enqueueReplaceState:function(i,a,d){i=i._reactInternals;var h=me(),v=Ae(i),k=Oi(h,v);k.tag=1,k.payload=a,d!=null&&(k.callback=d),a=pi(i,k,v),a!==null&&(Oe(a,i,v,h),Cl(a,i,v))},enqueueForceUpdate:function(i,a){i=i._reactInternals;var d=me(),h=Ae(i),v=Oi(d,h);v.tag=2,a!=null&&(v.callback=a),a=pi(i,v,h),a!==null&&(Oe(a,i,h,d),Cl(a,i,h))}};function oh(i,a,d,h,v,k,L){return i=i.stateNode,typeof i.shouldComponentUpdate=="function"?i.shouldComponentUpdate(h,k,L):a.prototype&&a.prototype.isPureReactComponent?!to(d,h)||!to(v,k):!0}function ah(i,a,d){var h=!1,v=xr,k=a.contextType;return typeof k=="object"&&k!==null?k=Ir(k):(v=nr(a)?Ti:fn.current,h=a.contextTypes,k=(h=h!=null)?Ra(i,v):xr),a=new a(d,k),i.memoizedState=a.state!==null&&a.state!==void 0?a.state:null,a.updater=Wa,i.stateNode=a,a._reactInternals=i,h&&(i=i.stateNode,i.__reactInternalMemoizedUnmaskedChildContext=v,i.__reactInternalMemoizedMaskedChildContext=k),a}function bd(i,a,d,h){i=a.state,typeof a.componentWillReceiveProps=="function"&&a.componentWillReceiveProps(d,h),typeof a.UNSAFE_componentWillReceiveProps=="function"&&a.UNSAFE_componentWillReceiveProps(d,h),a.state!==i&&Wa.enqueueReplaceState(a,a.state,null)}function Pi(i,a,d,h){var v=i.stateNode;v.props=d,v.state=i.memoizedState,v.refs={},Fa(i);var k=a.contextType;typeof k=="object"&&k!==null?v.context=Ir(k):(k=nr(a)?Ti:fn.current,v.context=Ra(i,k)),v.state=i.memoizedState,k=a.getDerivedStateFromProps,typeof k=="function"&&(xd(i,a,k,d),v.state=i.memoizedState),typeof a.getDerivedStateFromProps=="function"||typeof v.getSnapshotBeforeUpdate=="function"||typeof v.UNSAFE_componentWillMount!="function"&&typeof v.componentWillMount!="function"||(a=v.state,typeof v.componentWillMount=="function"&&v.componentWillMount(),typeof v.UNSAFE_componentWillMount=="function"&&v.UNSAFE_componentWillMount(),a!==v.state&&Wa.enqueueReplaceState(v,v.state,null),Oc(i,d,v,h),v.state=i.memoizedState),typeof v.componentDidMount=="function"&&(i.flags|=4194308)}function yi(i,a){try{var d="",h=a;do d+=ne(h),h=h.return;while(h);var v=d}catch(k){v=`
39
- Error generating stack: `+k.message+`
40
- `+k.stack}return{value:i,source:a,stack:v,digest:null}}function Hc(i,a,d){return{value:i,source:null,stack:d??null,digest:a??null}}function Vc(i,a){try{console.error(a.value)}catch(d){setTimeout(function(){throw d})}}var Zm=typeof WeakMap=="function"?WeakMap:Map;function kd(i,a,d){d=Oi(-1,d),d.tag=3,d.payload={element:null};var h=a.value;return d.callback=function(){y||(y=!0,S=h),Vc(i,a)},d}function Yo(i,a,d){d=Oi(-1,d),d.tag=3;var h=i.type.getDerivedStateFromError;if(typeof h=="function"){var v=a.value;d.payload=function(){return h(v)},d.callback=function(){Vc(i,a)}}var k=i.stateNode;return k!==null&&typeof k.componentDidCatch=="function"&&(d.callback=function(){Vc(i,a),typeof h!="function"&&(M===null?M=new Set([this]):M.add(this));var L=a.stack;this.componentDidCatch(a.value,{componentStack:L!==null?L:""})}),d}function lh(i,a,d){var h=i.pingCache;if(h===null){h=i.pingCache=new Zm;var v=new Set;h.set(a,v)}else v=h.get(a),v===void 0&&(v=new Set,h.set(a,v));v.has(d)||(v.add(d),i=W0.bind(null,i,a,d),a.then(i,i))}function Ol(i){do{var a;if((a=i.tag===13)&&(a=i.memoizedState,a=a!==null?a.dehydrated!==null:!0),a)return i;i=i.return}while(i!==null);return null}function jd(i,a,d,h,v){return(i.mode&1)===0?(i===a?i.flags|=65536:(i.flags|=128,d.flags|=131072,d.flags&=-52805,d.tag===1&&(d.alternate===null?d.tag=17:(a=Oi(-1,1),a.tag=2,pi(d,a,1))),d.lanes|=1),i):(i.flags|=65536,i.lanes=v,i)}var Qm=I.ReactCurrentOwner,As=!1;function Ws(i,a,d,h){a.child=i===null?Vo(a,null,d,h):_i(a,i.child,d,h)}function ch(i,a,d,h,v){d=d.render;var k=a.ref;return Da(a,v),h=Jt(i,a,d,h,k,v),d=Qn(),i!==null&&!As?(a.updateQueue=i.updateQueue,a.flags&=-2053,i.lanes&=~v,Di(i,a,v)):(Tt&&d&&$c(a),a.flags|=1,Ws(i,a,h,v),a.child)}function uh(i,a,d,h,v){if(i===null){var k=d.type;return typeof k=="function"&&!a_(k)&&k.defaultProps===void 0&&d.compare===null&&d.defaultProps===void 0?(a.tag=15,a.type=k,ir(i,a,k,h,v)):(i=yh(d.type,null,h,a,a.mode,v),i.ref=a.ref,i.return=a,a.child=i)}if(k=i.child,(i.lanes&v)===0){var L=k.memoizedProps;if(d=d.compare,d=d!==null?d:to,d(L,h)&&i.ref===a.ref)return Di(i,a,v)}return a.flags|=1,i=Ja(k,h),i.ref=a.ref,i.return=a,a.child=i}function ir(i,a,d,h,v){if(i!==null){var k=i.memoizedProps;if(to(k,h)&&i.ref===a.ref)if(As=!1,a.pendingProps=h=k,(i.lanes&v)!==0)(i.flags&131072)!==0&&(As=!0);else return a.lanes=i.lanes,Di(i,a,v)}return Gc(i,a,d,h,v)}function Jo(i,a,d){var h=a.pendingProps,v=h.children,k=i!==null?i.memoizedState:null;if(h.mode==="hidden")if((a.mode&1)===0)a.memoizedState={baseLanes:0,cachePool:null,transitions:null},Cn(Qo,ar),ar|=d;else{if((d&1073741824)===0)return i=k!==null?k.baseLanes|d:d,a.lanes=a.childLanes=1073741824,a.memoizedState={baseLanes:i,cachePool:null,transitions:null},a.updateQueue=null,Cn(Qo,ar),ar|=i,null;a.memoizedState={baseLanes:0,cachePool:null,transitions:null},h=k!==null?k.baseLanes:d,Cn(Qo,ar),ar|=h}else k!==null?(h=k.baseLanes|d,a.memoizedState=null):h=d,Cn(Qo,ar),ar|=h;return Ws(i,a,v,d),a.child}function dh(i,a){var d=a.ref;(i===null&&d!==null||i!==null&&i.ref!==d)&&(a.flags|=512,a.flags|=2097152)}function Gc(i,a,d,h,v){var k=nr(d)?Ti:fn.current;return k=Ra(a,k),Da(a,v),d=Jt(i,a,d,h,k,v),h=Qn(),i!==null&&!As?(a.updateQueue=i.updateQueue,a.flags&=-2053,i.lanes&=~v,Di(i,a,v)):(Tt&&h&&$c(a),a.flags|=1,Ws(i,a,d,v),a.child)}function or(i,a,d,h,v){if(nr(d)){var k=!0;kl(a)}else k=!1;if(Da(a,v),a.stateNode===null)Pr(i,a),ah(a,d,h),Pi(a,d,h,v),h=!0;else if(i===null){var L=a.stateNode,Q=a.memoizedProps;L.props=Q;var se=L.context,we=d.contextType;typeof we=="object"&&we!==null?we=Ir(we):(we=nr(d)?Ti:fn.current,we=Ra(a,we));var $e=d.getDerivedStateFromProps,Me=typeof $e=="function"||typeof L.getSnapshotBeforeUpdate=="function";Me||typeof L.UNSAFE_componentWillReceiveProps!="function"&&typeof L.componentWillReceiveProps!="function"||(Q!==h||se!==we)&&bd(a,L,h,we),as=!1;var Ce=a.memoizedState;L.state=Ce,Oc(a,h,L,v),se=a.memoizedState,Q!==h||Ce!==se||ws.current||as?(typeof $e=="function"&&(xd(a,d,$e,h),se=a.memoizedState),(Q=as||oh(a,d,Q,h,Ce,se,we))?(Me||typeof L.UNSAFE_componentWillMount!="function"&&typeof L.componentWillMount!="function"||(typeof L.componentWillMount=="function"&&L.componentWillMount(),typeof L.UNSAFE_componentWillMount=="function"&&L.UNSAFE_componentWillMount()),typeof L.componentDidMount=="function"&&(a.flags|=4194308)):(typeof L.componentDidMount=="function"&&(a.flags|=4194308),a.memoizedProps=h,a.memoizedState=se),L.props=h,L.state=se,L.context=we,h=Q):(typeof L.componentDidMount=="function"&&(a.flags|=4194308),h=!1)}else{L=a.stateNode,Jf(i,a),Q=a.memoizedProps,we=a.type===a.elementType?Q:rr(a.type,Q),L.props=we,Me=a.pendingProps,Ce=L.context,se=d.contextType,typeof se=="object"&&se!==null?se=Ir(se):(se=nr(d)?Ti:fn.current,se=Ra(a,se));var Je=d.getDerivedStateFromProps;($e=typeof Je=="function"||typeof L.getSnapshotBeforeUpdate=="function")||typeof L.UNSAFE_componentWillReceiveProps!="function"&&typeof L.componentWillReceiveProps!="function"||(Q!==Me||Ce!==se)&&bd(a,L,h,se),as=!1,Ce=a.memoizedState,L.state=Ce,Oc(a,h,L,v);var nt=a.memoizedState;Q!==Me||Ce!==nt||ws.current||as?(typeof Je=="function"&&(xd(a,d,Je,h),nt=a.memoizedState),(we=as||oh(a,d,we,h,Ce,nt,se)||!1)?($e||typeof L.UNSAFE_componentWillUpdate!="function"&&typeof L.componentWillUpdate!="function"||(typeof L.componentWillUpdate=="function"&&L.componentWillUpdate(h,nt,se),typeof L.UNSAFE_componentWillUpdate=="function"&&L.UNSAFE_componentWillUpdate(h,nt,se)),typeof L.componentDidUpdate=="function"&&(a.flags|=4),typeof L.getSnapshotBeforeUpdate=="function"&&(a.flags|=1024)):(typeof L.componentDidUpdate!="function"||Q===i.memoizedProps&&Ce===i.memoizedState||(a.flags|=4),typeof L.getSnapshotBeforeUpdate!="function"||Q===i.memoizedProps&&Ce===i.memoizedState||(a.flags|=1024),a.memoizedProps=h,a.memoizedState=nt),L.props=h,L.state=nt,L.context=se,h=we):(typeof L.componentDidUpdate!="function"||Q===i.memoizedProps&&Ce===i.memoizedState||(a.flags|=4),typeof L.getSnapshotBeforeUpdate!="function"||Q===i.memoizedProps&&Ce===i.memoizedState||(a.flags|=1024),h=!1)}return Pl(i,a,d,h,k,v)}function Pl(i,a,d,h,v,k){dh(i,a);var L=(a.flags&128)!==0;if(!h&&!L)return v&&jl(a,d,!1),Di(i,a,k);h=a.stateNode,Qm.current=a;var Q=L&&typeof d.getDerivedStateFromError!="function"?null:h.render();return a.flags|=1,i!==null&&L?(a.child=_i(a,i.child,null,k),a.child=_i(a,null,Q,k)):Ws(i,a,Q,k),a.memoizedState=h.state,v&&jl(a,d,!0),a.child}function Sd(i){var a=i.stateNode;a.pendingContext?Vf(i,a.pendingContext,a.pendingContext!==a.context):a.context&&Vf(i,a.context,!1),El(i,a.containerInfo)}function Nd(i,a,d,h,v){return Oa(),Pa(v),a.flags|=256,Ws(i,a,d,h),a.child}var Cd={dehydrated:null,treeContext:null,retryLane:0};function Ed(i){return{baseLanes:i,cachePool:null,transitions:null}}function fh(i,a,d){var h=a.pendingProps,v=Dn.current,k=!1,L=(a.flags&128)!==0,Q;if((Q=L)||(Q=i!==null&&i.memoizedState===null?!1:(v&2)!==0),Q?(k=!0,a.flags&=-129):(i===null||i.memoizedState!==null)&&(v|=1),Cn(Dn,v&1),i===null)return rd(a),i=a.memoizedState,i!==null&&(i=i.dehydrated,i!==null)?((a.mode&1)===0?a.lanes=1:i.data==="$!"?a.lanes=8:a.lanes=1073741824,null):(L=h.children,i=h.fallback,k?(h=a.mode,k=a.child,L={mode:"hidden",children:L},(h&1)===0&&k!==null?(k.childLanes=0,k.pendingProps=L):k=wh(L,h,0,null),i=Wl(i,h,d,null),k.return=a,i.return=a,k.sibling=i,a.child=k,a.child.memoizedState=Ed(d),a.memoizedState=Cd,i):qs(a,L));if(v=i.memoizedState,v!==null&&(Q=v.dehydrated,Q!==null))return hh(i,a,L,h,Q,v,d);if(k){k=h.fallback,L=a.mode,v=i.child,Q=v.sibling;var se={mode:"hidden",children:h.children};return(L&1)===0&&a.child!==v?(h=a.child,h.childLanes=0,h.pendingProps=se,a.deletions=null):(h=Ja(v,se),h.subtreeFlags=v.subtreeFlags&14680064),Q!==null?k=Ja(Q,k):(k=Wl(k,L,d,null),k.flags|=2),k.return=a,h.return=a,h.sibling=k,a.child=h,h=k,k=a.child,L=i.child.memoizedState,L=L===null?Ed(d):{baseLanes:L.baseLanes|d,cachePool:null,transitions:L.transitions},k.memoizedState=L,k.childLanes=i.childLanes&~d,a.memoizedState=Cd,h}return k=i.child,i=k.sibling,h=Ja(k,{mode:"visible",children:h.children}),(a.mode&1)===0&&(h.lanes=d),h.return=a,h.sibling=null,i!==null&&(d=a.deletions,d===null?(a.deletions=[i],a.flags|=16):d.push(i)),a.child=h,a.memoizedState=null,h}function qs(i,a){return a=wh({mode:"visible",children:a},i.mode,0,null),a.return=i,i.child=a}function po(i,a,d,h){return h!==null&&Pa(h),_i(a,i.child,null,d),i=qs(a,a.pendingProps.children),i.flags|=2,a.memoizedState=null,i}function hh(i,a,d,h,v,k,L){if(d)return a.flags&256?(a.flags&=-257,h=Hc(Error(n(422))),po(i,a,L,h)):a.memoizedState!==null?(a.child=i.child,a.flags|=128,null):(k=h.fallback,v=a.mode,h=wh({mode:"visible",children:h.children},v,0,null),k=Wl(k,v,L,null),k.flags|=2,h.return=a,k.return=a,h.sibling=k,a.child=h,(a.mode&1)!==0&&_i(a,i.child,null,L),a.child.memoizedState=Ed(L),a.memoizedState=Cd,k);if((a.mode&1)===0)return po(i,a,L,null);if(v.data==="$!"){if(h=v.nextSibling&&v.nextSibling.dataset,h)var Q=h.dgst;return h=Q,k=Error(n(419)),h=Hc(k,h,void 0),po(i,a,L,h)}if(Q=(L&i.childLanes)!==0,As||Q){if(h=es,h!==null){switch(L&-L){case 4:v=2;break;case 16:v=8;break;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:v=32;break;case 536870912:v=268435456;break;default:v=0}v=(v&(h.suspendedLanes|L))!==0?0:v,v!==0&&v!==k.retryLane&&(k.retryLane=v,os(i,v),Oe(h,i,v,-1))}return o_(),h=Hc(Error(n(421))),po(i,a,L,h)}return v.data==="$?"?(a.flags|=128,a.child=i.child,a=q0.bind(null,i),v._reactRetry=a,null):(i=k.treeContext,Te=uo(v.nextSibling),Bs=a,Tt=!0,br=null,i!==null&&(Rr[Lr++]=Yr,Rr[Lr++]=Ri,Rr[Lr++]=Ho,Yr=i.id,Ri=i.overflow,Ho=a),a=qs(a,h.children),a.flags|=4096,a)}function Ad(i,a,d){i.lanes|=a;var h=i.alternate;h!==null&&(h.lanes|=a),cd(i.return,a,d)}function Dl(i,a,d,h,v){var k=i.memoizedState;k===null?i.memoizedState={isBackwards:a,rendering:null,renderingStartTime:0,last:h,tail:d,tailMode:v}:(k.isBackwards=a,k.rendering=null,k.renderingStartTime=0,k.last=h,k.tail=d,k.tailMode=v)}function $d(i,a,d){var h=a.pendingProps,v=h.revealOrder,k=h.tail;if(Ws(i,a,h.children,d),h=Dn.current,(h&2)!==0)h=h&1|2,a.flags|=128;else{if(i!==null&&(i.flags&128)!==0)e:for(i=a.child;i!==null;){if(i.tag===13)i.memoizedState!==null&&Ad(i,d,a);else if(i.tag===19)Ad(i,d,a);else if(i.child!==null){i.child.return=i,i=i.child;continue}if(i===a)break e;for(;i.sibling===null;){if(i.return===null||i.return===a)break e;i=i.return}i.sibling.return=i.return,i=i.sibling}h&=1}if(Cn(Dn,h),(a.mode&1)===0)a.memoizedState=null;else switch(v){case"forwards":for(d=a.child,v=null;d!==null;)i=d.alternate,i!==null&&Dc(i)===null&&(v=d),d=d.sibling;d=v,d===null?(v=a.child,a.child=null):(v=d.sibling,d.sibling=null),Dl(a,!1,v,d,k);break;case"backwards":for(d=null,v=a.child,a.child=null;v!==null;){if(i=v.alternate,i!==null&&Dc(i)===null){a.child=v;break}i=v.sibling,v.sibling=d,d=v,v=i}Dl(a,!0,d,null,k);break;case"together":Dl(a,!1,null,null,void 0);break;default:a.memoizedState=null}return a.child}function Pr(i,a){(a.mode&1)===0&&i!==null&&(i.alternate=null,a.alternate=null,a.flags|=2)}function Di(i,a,d){if(i!==null&&(a.dependencies=i.dependencies),wo|=a.lanes,(d&a.childLanes)===0)return null;if(i!==null&&a.child!==i.child)throw Error(n(153));if(a.child!==null){for(i=a.child,d=Ja(i,i.pendingProps),a.child=d,d.return=a;i.sibling!==null;)i=i.sibling,d=d.sibling=Ja(i,i.pendingProps),d.return=a;d.sibling=null}return a.child}function e_(i,a,d){switch(a.tag){case 3:Sd(a),Oa();break;case 5:Pc(a);break;case 1:nr(a.type)&&kl(a);break;case 4:El(a,a.stateNode.containerInfo);break;case 10:var h=a.type._context,v=a.memoizedProps.value;Cn(ft,h._currentValue),h._currentValue=v;break;case 13:if(h=a.memoizedState,h!==null)return h.dehydrated!==null?(Cn(Dn,Dn.current&1),a.flags|=128,null):(d&a.child.childLanes)!==0?fh(i,a,d):(Cn(Dn,Dn.current&1),i=Di(i,a,d),i!==null?i.sibling:null);Cn(Dn,Dn.current&1);break;case 19:if(h=(d&a.childLanes)!==0,(i.flags&128)!==0){if(h)return $d(i,a,d);a.flags|=128}if(v=a.memoizedState,v!==null&&(v.rendering=null,v.tail=null,v.lastEffect=null),Cn(Dn,Dn.current),h)break;return null;case 22:case 23:return a.lanes=0,Jo(i,a,d)}return Di(i,a,d)}var Td,go,Kc,mh;Td=function(i,a){for(var d=a.child;d!==null;){if(d.tag===5||d.tag===6)i.appendChild(d.stateNode);else if(d.tag!==4&&d.child!==null){d.child.return=d,d=d.child;continue}if(d===a)break;for(;d.sibling===null;){if(d.return===null||d.return===a)return;d=d.return}d.sibling.return=d.return,d=d.sibling}},go=function(){},Kc=function(i,a,d,h){var v=i.memoizedProps;if(v!==h){i=a.stateNode,Xr(Or.current);var k=null;switch(d){case"input":v=tt(i,v),h=tt(i,h),k=[];break;case"select":v=G({},v,{value:void 0}),h=G({},h,{value:void 0}),k=[];break;case"textarea":v=qe(i,v),h=qe(i,h),k=[];break;default:typeof v.onClick!="function"&&typeof h.onClick=="function"&&(i.onclick=Nc)}wn(d,h);var L;d=null;for(we in v)if(!h.hasOwnProperty(we)&&v.hasOwnProperty(we)&&v[we]!=null)if(we==="style"){var Q=v[we];for(L in Q)Q.hasOwnProperty(L)&&(d||(d={}),d[L]="")}else we!=="dangerouslySetInnerHTML"&&we!=="children"&&we!=="suppressContentEditableWarning"&&we!=="suppressHydrationWarning"&&we!=="autoFocus"&&(o.hasOwnProperty(we)?k||(k=[]):(k=k||[]).push(we,null));for(we in h){var se=h[we];if(Q=v!=null?v[we]:void 0,h.hasOwnProperty(we)&&se!==Q&&(se!=null||Q!=null))if(we==="style")if(Q){for(L in Q)!Q.hasOwnProperty(L)||se&&se.hasOwnProperty(L)||(d||(d={}),d[L]="");for(L in se)se.hasOwnProperty(L)&&Q[L]!==se[L]&&(d||(d={}),d[L]=se[L])}else d||(k||(k=[]),k.push(we,d)),d=se;else we==="dangerouslySetInnerHTML"?(se=se?se.__html:void 0,Q=Q?Q.__html:void 0,se!=null&&Q!==se&&(k=k||[]).push(we,se)):we==="children"?typeof se!="string"&&typeof se!="number"||(k=k||[]).push(we,""+se):we!=="suppressContentEditableWarning"&&we!=="suppressHydrationWarning"&&(o.hasOwnProperty(we)?(se!=null&&we==="onScroll"&&Nn("scroll",i),k||Q===se||(k=[])):(k=k||[]).push(we,se))}d&&(k=k||[]).push("style",d);var we=k;(a.updateQueue=we)&&(a.flags|=4)}},mh=function(i,a,d,h){d!==h&&(a.flags|=4)};function Fl(i,a){if(!Tt)switch(i.tailMode){case"hidden":a=i.tail;for(var d=null;a!==null;)a.alternate!==null&&(d=a),a=a.sibling;d===null?i.tail=null:d.sibling=null;break;case"collapsed":d=i.tail;for(var h=null;d!==null;)d.alternate!==null&&(h=d),d=d.sibling;h===null?a||i.tail===null?i.tail=null:i.tail.sibling=null:h.sibling=null}}function $s(i){var a=i.alternate!==null&&i.alternate.child===i.child,d=0,h=0;if(a)for(var v=i.child;v!==null;)d|=v.lanes|v.childLanes,h|=v.subtreeFlags&14680064,h|=v.flags&14680064,v.return=i,v=v.sibling;else for(v=i.child;v!==null;)d|=v.lanes|v.childLanes,h|=v.subtreeFlags,h|=v.flags,v.return=i,v=v.sibling;return i.subtreeFlags|=h,i.childLanes=d,a}function t_(i,a,d){var h=a.pendingProps;switch(td(a),a.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return $s(a),null;case 1:return nr(a.type)&&La(),$s(a),null;case 3:return h=a.stateNode,gi(),En(ws),En(fn),Fc(),h.pendingContext&&(h.context=h.pendingContext,h.pendingContext=null),(i===null||i.child===null)&&(Nl(a)?a.flags|=4:i===null||i.memoizedState.isDehydrated&&(a.flags&256)===0||(a.flags|=1024,br!==null&&(rn(br),br=null))),go(i,a),$s(a),null;case 5:dd(a);var v=Xr(Ba.current);if(d=a.type,i!==null&&a.stateNode!=null)Kc(i,a,d,h,v),i.ref!==a.ref&&(a.flags|=512,a.flags|=2097152);else{if(!h){if(a.stateNode===null)throw Error(n(166));return $s(a),null}if(i=Xr(Or.current),Nl(a)){h=a.stateNode,d=a.type;var k=a.memoizedProps;switch(h[ys]=a,h[Ta]=k,i=(a.mode&1)!==0,d){case"dialog":Nn("cancel",h),Nn("close",h);break;case"iframe":case"object":case"embed":Nn("load",h);break;case"video":case"audio":for(v=0;v<Na.length;v++)Nn(Na[v],h);break;case"source":Nn("error",h);break;case"img":case"image":case"link":Nn("error",h),Nn("load",h);break;case"details":Nn("toggle",h);break;case"input":lt(h,k),Nn("invalid",h);break;case"select":h._wrapperState={wasMultiple:!!k.multiple},Nn("invalid",h);break;case"textarea":zt(h,k),Nn("invalid",h)}wn(d,k),v=null;for(var L in k)if(k.hasOwnProperty(L)){var Q=k[L];L==="children"?typeof Q=="string"?h.textContent!==Q&&(k.suppressHydrationWarning!==!0&&lo(h.textContent,Q,i),v=["children",Q]):typeof Q=="number"&&h.textContent!==""+Q&&(k.suppressHydrationWarning!==!0&&lo(h.textContent,Q,i),v=["children",""+Q]):o.hasOwnProperty(L)&&Q!=null&&L==="onScroll"&&Nn("scroll",h)}switch(d){case"input":We(h),Re(h,k,!0);break;case"textarea":We(h),bn(h);break;case"select":case"option":break;default:typeof k.onClick=="function"&&(h.onclick=Nc)}h=v,a.updateQueue=h,h!==null&&(a.flags|=4)}else{L=v.nodeType===9?v:v.ownerDocument,i==="http://www.w3.org/1999/xhtml"&&(i=Wt(d)),i==="http://www.w3.org/1999/xhtml"?d==="script"?(i=L.createElement("div"),i.innerHTML="<script><\/script>",i=i.removeChild(i.firstChild)):typeof h.is=="string"?i=L.createElement(d,{is:h.is}):(i=L.createElement(d),d==="select"&&(L=i,h.multiple?L.multiple=!0:h.size&&(L.size=h.size))):i=L.createElementNS(i,d),i[ys]=a,i[Ta]=h,Td(i,a,!1,!1),a.stateNode=i;e:{switch(L=ks(d,h),d){case"dialog":Nn("cancel",i),Nn("close",i),v=h;break;case"iframe":case"object":case"embed":Nn("load",i),v=h;break;case"video":case"audio":for(v=0;v<Na.length;v++)Nn(Na[v],i);v=h;break;case"source":Nn("error",i),v=h;break;case"img":case"image":case"link":Nn("error",i),Nn("load",i),v=h;break;case"details":Nn("toggle",i),v=h;break;case"input":lt(i,h),v=tt(i,h),Nn("invalid",i);break;case"option":v=h;break;case"select":i._wrapperState={wasMultiple:!!h.multiple},v=G({},h,{value:void 0}),Nn("invalid",i);break;case"textarea":zt(i,h),v=qe(i,h),Nn("invalid",i);break;default:v=h}wn(d,v),Q=v;for(k in Q)if(Q.hasOwnProperty(k)){var se=Q[k];k==="style"?gn(i,se):k==="dangerouslySetInnerHTML"?(se=se?se.__html:void 0,se!=null&&ns(i,se)):k==="children"?typeof se=="string"?(d!=="textarea"||se!=="")&&Ot(i,se):typeof se=="number"&&Ot(i,""+se):k!=="suppressContentEditableWarning"&&k!=="suppressHydrationWarning"&&k!=="autoFocus"&&(o.hasOwnProperty(k)?se!=null&&k==="onScroll"&&Nn("scroll",i):se!=null&&T(i,k,se,L))}switch(d){case"input":We(i),Re(i,h,!1);break;case"textarea":We(i),bn(i);break;case"option":h.value!=null&&i.setAttribute("value",""+pe(h.value));break;case"select":i.multiple=!!h.multiple,k=h.value,k!=null?Ie(i,!!h.multiple,k,!1):h.defaultValue!=null&&Ie(i,!!h.multiple,h.defaultValue,!0);break;default:typeof v.onClick=="function"&&(i.onclick=Nc)}switch(d){case"button":case"input":case"select":case"textarea":h=!!h.autoFocus;break e;case"img":h=!0;break e;default:h=!1}}h&&(a.flags|=4)}a.ref!==null&&(a.flags|=512,a.flags|=2097152)}return $s(a),null;case 6:if(i&&a.stateNode!=null)mh(i,a,i.memoizedProps,h);else{if(typeof h!="string"&&a.stateNode===null)throw Error(n(166));if(d=Xr(Ba.current),Xr(Or.current),Nl(a)){if(h=a.stateNode,d=a.memoizedProps,h[ys]=a,(k=h.nodeValue!==d)&&(i=Bs,i!==null))switch(i.tag){case 3:lo(h.nodeValue,d,(i.mode&1)!==0);break;case 5:i.memoizedProps.suppressHydrationWarning!==!0&&lo(h.nodeValue,d,(i.mode&1)!==0)}k&&(a.flags|=4)}else h=(d.nodeType===9?d:d.ownerDocument).createTextNode(h),h[ys]=a,a.stateNode=h}return $s(a),null;case 13:if(En(Dn),h=a.memoizedState,i===null||i.memoizedState!==null&&i.memoizedState.dehydrated!==null){if(Tt&&Te!==null&&(a.mode&1)!==0&&(a.flags&128)===0)id(),Oa(),a.flags|=98560,k=!1;else if(k=Nl(a),h!==null&&h.dehydrated!==null){if(i===null){if(!k)throw Error(n(318));if(k=a.memoizedState,k=k!==null?k.dehydrated:null,!k)throw Error(n(317));k[ys]=a}else Oa(),(a.flags&128)===0&&(a.memoizedState=null),a.flags|=4;$s(a),k=!1}else br!==null&&(rn(br),br=null),k=!0;if(!k)return a.flags&65536?a:null}return(a.flags&128)!==0?(a.lanes=d,a):(h=h!==null,h!==(i!==null&&i.memoizedState!==null)&&h&&(a.child.flags|=8192,(a.mode&1)!==0&&(i===null||(Dn.current&1)!==0?Yn===0&&(Yn=3):o_())),a.updateQueue!==null&&(a.flags|=4),$s(a),null);case 4:return gi(),go(i,a),i===null&&wl(a.stateNode.containerInfo),$s(a),null;case 10:return Lc(a.type._context),$s(a),null;case 17:return nr(a.type)&&La(),$s(a),null;case 19:if(En(Dn),k=a.memoizedState,k===null)return $s(a),null;if(h=(a.flags&128)!==0,L=k.rendering,L===null)if(h)Fl(k,!1);else{if(Yn!==0||i!==null&&(i.flags&128)!==0)for(i=a.child;i!==null;){if(L=Dc(i),L!==null){for(a.flags|=128,Fl(k,!1),h=L.updateQueue,h!==null&&(a.updateQueue=h,a.flags|=4),a.subtreeFlags=0,h=d,d=a.child;d!==null;)k=d,i=h,k.flags&=14680066,L=k.alternate,L===null?(k.childLanes=0,k.lanes=i,k.child=null,k.subtreeFlags=0,k.memoizedProps=null,k.memoizedState=null,k.updateQueue=null,k.dependencies=null,k.stateNode=null):(k.childLanes=L.childLanes,k.lanes=L.lanes,k.child=L.child,k.subtreeFlags=0,k.deletions=null,k.memoizedProps=L.memoizedProps,k.memoizedState=L.memoizedState,k.updateQueue=L.updateQueue,k.type=L.type,i=L.dependencies,k.dependencies=i===null?null:{lanes:i.lanes,firstContext:i.firstContext}),d=d.sibling;return Cn(Dn,Dn.current&1|2),a.child}i=i.sibling}k.tail!==null&&ue()>ea&&(a.flags|=128,h=!0,Fl(k,!1),a.lanes=4194304)}else{if(!h)if(i=Dc(L),i!==null){if(a.flags|=128,h=!0,d=i.updateQueue,d!==null&&(a.updateQueue=d,a.flags|=4),Fl(k,!0),k.tail===null&&k.tailMode==="hidden"&&!L.alternate&&!Tt)return $s(a),null}else 2*ue()-k.renderingStartTime>ea&&d!==1073741824&&(a.flags|=128,h=!0,Fl(k,!1),a.lanes=4194304);k.isBackwards?(L.sibling=a.child,a.child=L):(d=k.last,d!==null?d.sibling=L:a.child=L,k.last=L)}return k.tail!==null?(a=k.tail,k.rendering=a,k.tail=a.sibling,k.renderingStartTime=ue(),a.sibling=null,d=Dn.current,Cn(Dn,h?d&1|2:d&1),a):($s(a),null);case 22:case 23:return Ms(),h=a.memoizedState!==null,i!==null&&i.memoizedState!==null!==h&&(a.flags|=8192),h&&(a.mode&1)!==0?(ar&1073741824)!==0&&($s(a),a.subtreeFlags&6&&(a.flags|=8192)):$s(a),null;case 24:return null;case 25:return null}throw Error(n(156,a.tag))}function n_(i,a){switch(td(a),a.tag){case 1:return nr(a.type)&&La(),i=a.flags,i&65536?(a.flags=i&-65537|128,a):null;case 3:return gi(),En(ws),En(fn),Fc(),i=a.flags,(i&65536)!==0&&(i&128)===0?(a.flags=i&-65537|128,a):null;case 5:return dd(a),null;case 13:if(En(Dn),i=a.memoizedState,i!==null&&i.dehydrated!==null){if(a.alternate===null)throw Error(n(340));Oa()}return i=a.flags,i&65536?(a.flags=i&-65537|128,a):null;case 19:return En(Dn),null;case 4:return gi(),null;case 10:return Lc(a.type._context),null;case 22:case 23:return Ms(),null;case 24:return null;default:return null}}var Rn=!1,Vn=!1,s_=typeof WeakSet=="function"?WeakSet:Set,Xe=null;function Xo(i,a){var d=i.ref;if(d!==null)if(typeof d=="function")try{d(null)}catch(h){Jn(i,a,h)}else d.current=null}function Yc(i,a,d){try{d()}catch(h){Jn(i,a,h)}}var Md=!1;function _h(i,a){if(zo=Mo,i=ml(),Hu(i)){if("selectionStart"in i)var d={start:i.selectionStart,end:i.selectionEnd};else e:{d=(d=i.ownerDocument)&&d.defaultView||window;var h=d.getSelection&&d.getSelection();if(h&&h.rangeCount!==0){d=h.anchorNode;var v=h.anchorOffset,k=h.focusNode;h=h.focusOffset;try{d.nodeType,k.nodeType}catch{d=null;break e}var L=0,Q=-1,se=-1,we=0,$e=0,Me=i,Ce=null;t:for(;;){for(var Je;Me!==d||v!==0&&Me.nodeType!==3||(Q=L+v),Me!==k||h!==0&&Me.nodeType!==3||(se=L+h),Me.nodeType===3&&(L+=Me.nodeValue.length),(Je=Me.firstChild)!==null;)Ce=Me,Me=Je;for(;;){if(Me===i)break t;if(Ce===d&&++we===v&&(Q=L),Ce===k&&++$e===h&&(se=L),(Je=Me.nextSibling)!==null)break;Me=Ce,Ce=Me.parentNode}Me=Je}d=Q===-1||se===-1?null:{start:Q,end:se}}else d=null}d=d||{start:0,end:0}}else d=null;for(vl={focusedElem:i,selectionRange:d},Mo=!1,Xe=a;Xe!==null;)if(a=Xe,i=a.child,(a.subtreeFlags&1028)!==0&&i!==null)i.return=a,Xe=i;else for(;Xe!==null;){a=Xe;try{var nt=a.alternate;if((a.flags&1024)!==0)switch(a.tag){case 0:case 11:case 15:break;case 1:if(nt!==null){var st=nt.memoizedProps,ts=nt.memoizedState,de=a.stateNode,ae=de.getSnapshotBeforeUpdate(a.elementType===a.type?st:rr(a.type,st),ts);de.__reactInternalSnapshotBeforeUpdate=ae}break;case 3:var _e=a.stateNode.containerInfo;_e.nodeType===1?_e.textContent="":_e.nodeType===9&&_e.documentElement&&_e.removeChild(_e.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(n(163))}}catch(Pe){Jn(a,a.return,Pe)}if(i=a.sibling,i!==null){i.return=a.return,Xe=i;break}Xe=a.return}return nt=Md,Md=!1,nt}function Zo(i,a,d){var h=a.updateQueue;if(h=h!==null?h.lastEffect:null,h!==null){var v=h=h.next;do{if((v.tag&i)===i){var k=v.destroy;v.destroy=void 0,k!==void 0&&Yc(a,d,k)}v=v.next}while(v!==h)}}function yo(i,a){if(a=a.updateQueue,a=a!==null?a.lastEffect:null,a!==null){var d=a=a.next;do{if((d.tag&i)===i){var h=d.create;d.destroy=h()}d=d.next}while(d!==a)}}function qa(i){var a=i.ref;if(a!==null){var d=i.stateNode;switch(i.tag){case 5:i=d;break;default:i=d}typeof a=="function"?a(i):a.current=i}}function Rd(i){var a=i.alternate;a!==null&&(i.alternate=null,Rd(a)),i.child=null,i.deletions=null,i.sibling=null,i.tag===5&&(a=i.stateNode,a!==null&&(delete a[ys],delete a[Ta],delete a[Bo],delete a[Hf],delete a[Xu])),i.stateNode=null,i.return=null,i.dependencies=null,i.memoizedProps=null,i.memoizedState=null,i.pendingProps=null,i.stateNode=null,i.updateQueue=null}function Ld(i){return i.tag===5||i.tag===3||i.tag===4}function Id(i){e:for(;;){for(;i.sibling===null;){if(i.return===null||Ld(i.return))return null;i=i.return}for(i.sibling.return=i.return,i=i.sibling;i.tag!==5&&i.tag!==6&&i.tag!==18;){if(i.flags&2||i.child===null||i.tag===4)continue e;i.child.return=i,i=i.child}if(!(i.flags&2))return i.stateNode}}function wi(i,a,d){var h=i.tag;if(h===5||h===6)i=i.stateNode,a?d.nodeType===8?d.parentNode.insertBefore(i,a):d.insertBefore(i,a):(d.nodeType===8?(a=d.parentNode,a.insertBefore(i,d)):(a=d,a.appendChild(i)),d=d._reactRootContainer,d!=null||a.onclick!==null||(a.onclick=Nc));else if(h!==4&&(i=i.child,i!==null))for(wi(i,a,d),i=i.sibling;i!==null;)wi(i,a,d),i=i.sibling}function Od(i,a,d){var h=i.tag;if(h===5||h===6)i=i.stateNode,a?d.insertBefore(i,a):d.appendChild(i);else if(h!==4&&(i=i.child,i!==null))for(Od(i,a,d),i=i.sibling;i!==null;)Od(i,a,d),i=i.sibling}var zn=null,kr=!1;function vi(i,a,d){for(d=d.child;d!==null;)Pd(i,a,d),d=d.sibling}function Pd(i,a,d){if(Ds&&typeof Ds.onCommitFiberUnmount=="function")try{Ds.onCommitFiberUnmount(cn,d)}catch{}switch(d.tag){case 5:Vn||Xo(d,a);case 6:var h=zn,v=kr;zn=null,vi(i,a,d),zn=h,kr=v,zn!==null&&(kr?(i=zn,d=d.stateNode,i.nodeType===8?i.parentNode.removeChild(d):i.removeChild(d)):zn.removeChild(d.stateNode));break;case 18:zn!==null&&(kr?(i=zn,d=d.stateNode,i.nodeType===8?co(i.parentNode,d):i.nodeType===1&&co(i,d),Zi(i)):co(zn,d.stateNode));break;case 4:h=zn,v=kr,zn=d.stateNode.containerInfo,kr=!0,vi(i,a,d),zn=h,kr=v;break;case 0:case 11:case 14:case 15:if(!Vn&&(h=d.updateQueue,h!==null&&(h=h.lastEffect,h!==null))){v=h=h.next;do{var k=v,L=k.destroy;k=k.tag,L!==void 0&&((k&2)!==0||(k&4)!==0)&&Yc(d,a,L),v=v.next}while(v!==h)}vi(i,a,d);break;case 1:if(!Vn&&(Xo(d,a),h=d.stateNode,typeof h.componentWillUnmount=="function"))try{h.props=d.memoizedProps,h.state=d.memoizedState,h.componentWillUnmount()}catch(Q){Jn(d,a,Q)}vi(i,a,d);break;case 21:vi(i,a,d);break;case 22:d.mode&1?(Vn=(h=Vn)||d.memoizedState!==null,vi(i,a,d),Vn=h):vi(i,a,d);break;default:vi(i,a,d)}}function Dd(i){var a=i.updateQueue;if(a!==null){i.updateQueue=null;var d=i.stateNode;d===null&&(d=i.stateNode=new s_),a.forEach(function(h){var v=H0.bind(null,i,h);d.has(h)||(d.add(h),h.then(v,v))})}}function ni(i,a){var d=a.deletions;if(d!==null)for(var h=0;h<d.length;h++){var v=d[h];try{var k=i,L=a,Q=L;e:for(;Q!==null;){switch(Q.tag){case 5:zn=Q.stateNode,kr=!1;break e;case 3:zn=Q.stateNode.containerInfo,kr=!0;break e;case 4:zn=Q.stateNode.containerInfo,kr=!0;break e}Q=Q.return}if(zn===null)throw Error(n(160));Pd(k,L,v),zn=null,kr=!1;var se=v.alternate;se!==null&&(se.return=null),v.return=null}catch(we){Jn(v,a,we)}}if(a.subtreeFlags&12854)for(a=a.child;a!==null;)Ha(a,i),a=a.sibling}function Ha(i,a){var d=i.alternate,h=i.flags;switch(i.tag){case 0:case 11:case 14:case 15:if(ni(a,i),Ts(i),h&4){try{Zo(3,i,i.return),yo(3,i)}catch(st){Jn(i,i.return,st)}try{Zo(5,i,i.return)}catch(st){Jn(i,i.return,st)}}break;case 1:ni(a,i),Ts(i),h&512&&d!==null&&Xo(d,d.return);break;case 5:if(ni(a,i),Ts(i),h&512&&d!==null&&Xo(d,d.return),i.flags&32){var v=i.stateNode;try{Ot(v,"")}catch(st){Jn(i,i.return,st)}}if(h&4&&(v=i.stateNode,v!=null)){var k=i.memoizedProps,L=d!==null?d.memoizedProps:k,Q=i.type,se=i.updateQueue;if(i.updateQueue=null,se!==null)try{Q==="input"&&k.type==="radio"&&k.name!=null&&Ke(v,k),ks(Q,L);var we=ks(Q,k);for(L=0;L<se.length;L+=2){var $e=se[L],Me=se[L+1];$e==="style"?gn(v,Me):$e==="dangerouslySetInnerHTML"?ns(v,Me):$e==="children"?Ot(v,Me):T(v,$e,Me,we)}switch(Q){case"input":je(v,k);break;case"textarea":en(v,k);break;case"select":var Ce=v._wrapperState.wasMultiple;v._wrapperState.wasMultiple=!!k.multiple;var Je=k.value;Je!=null?Ie(v,!!k.multiple,Je,!1):Ce!==!!k.multiple&&(k.defaultValue!=null?Ie(v,!!k.multiple,k.defaultValue,!0):Ie(v,!!k.multiple,k.multiple?[]:"",!1))}v[Ta]=k}catch(st){Jn(i,i.return,st)}}break;case 6:if(ni(a,i),Ts(i),h&4){if(i.stateNode===null)throw Error(n(162));v=i.stateNode,k=i.memoizedProps;try{v.nodeValue=k}catch(st){Jn(i,i.return,st)}}break;case 3:if(ni(a,i),Ts(i),h&4&&d!==null&&d.memoizedState.isDehydrated)try{Zi(a.containerInfo)}catch(st){Jn(i,i.return,st)}break;case 4:ni(a,i),Ts(i);break;case 13:ni(a,i),Ts(i),v=i.child,v.flags&8192&&(k=v.memoizedState!==null,v.stateNode.isHidden=k,!k||v.alternate!==null&&v.alternate.memoizedState!==null||(eu=ue())),h&4&&Dd(i);break;case 22:if($e=d!==null&&d.memoizedState!==null,i.mode&1?(Vn=(we=Vn)||$e,ni(a,i),Vn=we):ni(a,i),Ts(i),h&8192){if(we=i.memoizedState!==null,(i.stateNode.isHidden=we)&&!$e&&(i.mode&1)!==0)for(Xe=i,$e=i.child;$e!==null;){for(Me=Xe=$e;Xe!==null;){switch(Ce=Xe,Je=Ce.child,Ce.tag){case 0:case 11:case 14:case 15:Zo(4,Ce,Ce.return);break;case 1:Xo(Ce,Ce.return);var nt=Ce.stateNode;if(typeof nt.componentWillUnmount=="function"){h=Ce,d=Ce.return;try{a=h,nt.props=a.memoizedProps,nt.state=a.memoizedState,nt.componentWillUnmount()}catch(st){Jn(h,d,st)}}break;case 5:Xo(Ce,Ce.return);break;case 22:if(Ce.memoizedState!==null){zl(Me);continue}}Je!==null?(Je.return=Ce,Xe=Je):zl(Me)}$e=$e.sibling}e:for($e=null,Me=i;;){if(Me.tag===5){if($e===null){$e=Me;try{v=Me.stateNode,we?(k=v.style,typeof k.setProperty=="function"?k.setProperty("display","none","important"):k.display="none"):(Q=Me.stateNode,se=Me.memoizedProps.style,L=se!=null&&se.hasOwnProperty("display")?se.display:null,Q.style.display=An("display",L))}catch(st){Jn(i,i.return,st)}}}else if(Me.tag===6){if($e===null)try{Me.stateNode.nodeValue=we?"":Me.memoizedProps}catch(st){Jn(i,i.return,st)}}else if((Me.tag!==22&&Me.tag!==23||Me.memoizedState===null||Me===i)&&Me.child!==null){Me.child.return=Me,Me=Me.child;continue}if(Me===i)break e;for(;Me.sibling===null;){if(Me.return===null||Me.return===i)break e;$e===Me&&($e=null),Me=Me.return}$e===Me&&($e=null),Me.sibling.return=Me.return,Me=Me.sibling}}break;case 19:ni(a,i),Ts(i),h&4&&Dd(i);break;case 21:break;default:ni(a,i),Ts(i)}}function Ts(i){var a=i.flags;if(a&2){try{e:{for(var d=i.return;d!==null;){if(Ld(d)){var h=d;break e}d=d.return}throw Error(n(160))}switch(h.tag){case 5:var v=h.stateNode;h.flags&32&&(Ot(v,""),h.flags&=-33);var k=Id(i);Od(i,k,v);break;case 3:case 4:var L=h.stateNode.containerInfo,Q=Id(i);wi(i,Q,L);break;default:throw Error(n(161))}}catch(se){Jn(i,i.return,se)}i.flags&=-3}a&4096&&(i.flags&=-4097)}function r_(i,a,d){Xe=i,Va(i)}function Va(i,a,d){for(var h=(i.mode&1)!==0;Xe!==null;){var v=Xe,k=v.child;if(v.tag===22&&h){var L=v.memoizedState!==null||Rn;if(!L){var Q=v.alternate,se=Q!==null&&Q.memoizedState!==null||Vn;Q=Rn;var we=Vn;if(Rn=L,(Vn=se)&&!we)for(Xe=v;Xe!==null;)L=Xe,se=L.child,L.tag===22&&L.memoizedState!==null?Jc(v):se!==null?(se.return=L,Xe=se):Jc(v);for(;k!==null;)Xe=k,Va(k),k=k.sibling;Xe=v,Rn=Q,Vn=we}ph(i)}else(v.subtreeFlags&8772)!==0&&k!==null?(k.return=v,Xe=k):ph(i)}}function ph(i){for(;Xe!==null;){var a=Xe;if((a.flags&8772)!==0){var d=a.alternate;try{if((a.flags&8772)!==0)switch(a.tag){case 0:case 11:case 15:Vn||yo(5,a);break;case 1:var h=a.stateNode;if(a.flags&4&&!Vn)if(d===null)h.componentDidMount();else{var v=a.elementType===a.type?d.memoizedProps:rr(a.type,d.memoizedProps);h.componentDidUpdate(v,d.memoizedState,h.__reactInternalSnapshotBeforeUpdate)}var k=a.updateQueue;k!==null&&Tn(a,k,h);break;case 3:var L=a.updateQueue;if(L!==null){if(d=null,a.child!==null)switch(a.child.tag){case 5:d=a.child.stateNode;break;case 1:d=a.child.stateNode}Tn(a,L,d)}break;case 5:var Q=a.stateNode;if(d===null&&a.flags&4){d=Q;var se=a.memoizedProps;switch(a.type){case"button":case"input":case"select":case"textarea":se.autoFocus&&d.focus();break;case"img":se.src&&(d.src=se.src)}}break;case 6:break;case 4:break;case 12:break;case 13:if(a.memoizedState===null){var we=a.alternate;if(we!==null){var $e=we.memoizedState;if($e!==null){var Me=$e.dehydrated;Me!==null&&Zi(Me)}}}break;case 19:case 17:case 21:case 22:case 23:case 25:break;default:throw Error(n(163))}Vn||a.flags&512&&qa(a)}catch(Ce){Jn(a,a.return,Ce)}}if(a===i){Xe=null;break}if(d=a.sibling,d!==null){d.return=a.return,Xe=d;break}Xe=a.return}}function zl(i){for(;Xe!==null;){var a=Xe;if(a===i){Xe=null;break}var d=a.sibling;if(d!==null){d.return=a.return,Xe=d;break}Xe=a.return}}function Jc(i){for(;Xe!==null;){var a=Xe;try{switch(a.tag){case 0:case 11:case 15:var d=a.return;try{yo(4,a)}catch(se){Jn(a,d,se)}break;case 1:var h=a.stateNode;if(typeof h.componentDidMount=="function"){var v=a.return;try{h.componentDidMount()}catch(se){Jn(a,v,se)}}var k=a.return;try{qa(a)}catch(se){Jn(a,k,se)}break;case 5:var L=a.return;try{qa(a)}catch(se){Jn(a,L,se)}}}catch(se){Jn(a,a.return,se)}if(a===i){Xe=null;break}var Q=a.sibling;if(Q!==null){Q.return=a.return,Xe=Q;break}Xe=a.return}}var i_=Math.ceil,Xc=I.ReactCurrentDispatcher,Zc=I.ReactCurrentOwner,jr=I.ReactCurrentBatchConfig,sn=0,es=null,Gn=null,us=0,ar=0,Qo=$i(0),Yn=0,Ga=null,wo=0,Bl=0,Qc=0,Ka=null,Hs=null,eu=0,ea=1/0,xi=null,y=!1,S=null,M=null,D=!1,q=null,H=0,V=0,te=null,Le=-1,ge=0;function me(){return(sn&6)!==0?ue():Le!==-1?Le:Le=ue()}function Ae(i){return(i.mode&1)===0?1:(sn&2)!==0&&us!==0?us&-us:Us.transition!==null?(ge===0&&(ge=hs()),ge):(i=ln,i!==0||(i=window.event,i=i===void 0?16:be(i.type)),i)}function Oe(i,a,d,h){if(50<V)throw V=0,te=null,Error(n(185));ms(i,d,h),((sn&2)===0||i!==es)&&(i===es&&((sn&2)===0&&(Bl|=d),Yn===4&&Be(i,us)),ze(i,h),d===1&&sn===0&&(a.mode&1)===0&&(ea=ue()+500,Sl&&Mi()))}function ze(i,a){var d=i.callbackNode;$n(i,a);var h=Ki(i,i===es?us:0);if(h===0)d!==null&&ii(d),i.callbackNode=null,i.callbackPriority=0;else if(a=h&-h,i.callbackPriority!==a){if(d!=null&&ii(d),a===1)i.tag===0?Gf(bt.bind(null,i)):ed(bt.bind(null,i)),Ec(function(){(sn&6)===0&&Mi()}),d=null;else{switch(fa(h)){case 1:d=Gi;break;case 4:d=hr;break;case 16:d=Cr;break;case 536870912:d=it;break;default:d=Cr}d=Xg(d,Ze.bind(null,i))}i.callbackPriority=a,i.callbackNode=d}}function Ze(i,a){if(Le=-1,ge=0,(sn&6)!==0)throw Error(n(327));var d=i.callbackNode;if(tu()&&i.callbackNode!==d)return null;var h=Ki(i,i===es?us:0);if(h===0)return null;if((h&30)!==0||(h&i.expiredLanes)!==0||a)a=gh(i,h);else{a=h;var v=sn;sn|=2;var k=Ya();(es!==i||us!==a)&&(xi=null,ea=ue()+500,ds(i,a));do try{B0();break}catch(Q){Dr(i,Q)}while(!0);ld(),Xc.current=k,sn=v,Gn!==null?a=0:(es=null,us=0,a=Yn)}if(a!==0){if(a===2&&(v=Fs(i),v!==0&&(h=v,a=Ve(i,v))),a===1)throw d=Ga,ds(i,0),Be(i,h),ze(i,ue()),d;if(a===6)Be(i,h);else{if(v=i.current.alternate,(h&30)===0&&!Rt(v)&&(a=gh(i,h),a===2&&(k=Fs(i),k!==0&&(h=k,a=Ve(i,k))),a===1))throw d=Ga,ds(i,0),Be(i,h),ze(i,ue()),d;switch(i.finishedWork=v,i.finishedLanes=h,a){case 0:case 1:throw Error(n(345));case 2:Ul(i,Hs,xi);break;case 3:if(Be(i,h),(h&130023424)===h&&(a=eu+500-ue(),10<a)){if(Ki(i,0)!==0)break;if(v=i.suspendedLanes,(v&h)!==h){me(),i.pingedLanes|=i.suspendedLanes&v;break}i.timeoutHandle=Cc(Ul.bind(null,i,Hs,xi),a);break}Ul(i,Hs,xi);break;case 4:if(Be(i,h),(h&4194240)===h)break;for(a=i.eventTimes,v=-1;0<h;){var L=31-rs(h);k=1<<L,L=a[L],L>v&&(v=L),h&=~k}if(h=v,h=ue()-h,h=(120>h?120:480>h?480:1080>h?1080:1920>h?1920:3e3>h?3e3:4320>h?4320:1960*i_(h/1960))-h,10<h){i.timeoutHandle=Cc(Ul.bind(null,i,Hs,xi),h);break}Ul(i,Hs,xi);break;case 5:Ul(i,Hs,xi);break;default:throw Error(n(329))}}}return ze(i,ue()),i.callbackNode===d?Ze.bind(null,i):null}function Ve(i,a){var d=Ka;return i.current.memoizedState.isDehydrated&&(ds(i,a).flags|=256),i=gh(i,a),i!==2&&(a=Hs,Hs=d,a!==null&&rn(a)),i}function rn(i){Hs===null?Hs=i:Hs.push.apply(Hs,i)}function Rt(i){for(var a=i;;){if(a.flags&16384){var d=a.updateQueue;if(d!==null&&(d=d.stores,d!==null))for(var h=0;h<d.length;h++){var v=d[h],k=v.getSnapshot;v=v.value;try{if(!Vr(k(),v))return!1}catch{return!1}}}if(d=a.child,a.subtreeFlags&16384&&d!==null)d.return=a,a=d;else{if(a===i)break;for(;a.sibling===null;){if(a.return===null||a.return===i)return!0;a=a.return}a.sibling.return=a.return,a=a.sibling}}return!0}function Be(i,a){for(a&=~Qc,a&=~Bl,i.suspendedLanes|=a,i.pingedLanes&=~a,i=i.expirationTimes;0<a;){var d=31-rs(a),h=1<<d;i[d]=-1,a&=~h}}function bt(i){if((sn&6)!==0)throw Error(n(327));tu();var a=Ki(i,0);if((a&1)===0)return ze(i,ue()),null;var d=gh(i,a);if(i.tag!==0&&d===2){var h=Fs(i);h!==0&&(a=h,d=Ve(i,h))}if(d===1)throw d=Ga,ds(i,0),Be(i,a),ze(i,ue()),d;if(d===6)throw Error(n(345));return i.finishedWork=i.current.alternate,i.finishedLanes=a,Ul(i,Hs,xi),ze(i,ue()),null}function xn(i,a){var d=sn;sn|=1;try{return i(a)}finally{sn=d,sn===0&&(ea=ue()+500,Sl&&Mi())}}function hn(i){q!==null&&q.tag===0&&(sn&6)===0&&tu();var a=sn;sn|=1;var d=jr.transition,h=ln;try{if(jr.transition=null,ln=1,i)return i()}finally{ln=h,jr.transition=d,sn=a,(sn&6)===0&&Mi()}}function Ms(){ar=Qo.current,En(Qo)}function ds(i,a){i.finishedWork=null,i.finishedLanes=0;var d=i.timeoutHandle;if(d!==-1&&(i.timeoutHandle=-1,Aa(d)),Gn!==null)for(d=Gn.return;d!==null;){var h=d;switch(td(h),h.tag){case 1:h=h.type.childContextTypes,h!=null&&La();break;case 3:gi(),En(ws),En(fn),Fc();break;case 5:dd(h);break;case 4:gi();break;case 13:En(Dn);break;case 19:En(Dn);break;case 10:Lc(h.type._context);break;case 22:case 23:Ms()}d=d.return}if(es=i,Gn=i=Ja(i.current,null),us=ar=a,Yn=0,Ga=null,Qc=Bl=wo=0,Hs=Ka=null,Ii!==null){for(a=0;a<Ii.length;a++)if(d=Ii[a],h=d.interleaved,h!==null){d.interleaved=null;var v=h.next,k=d.pending;if(k!==null){var L=k.next;k.next=v,h.next=L}d.pending=h}Ii=null}return i}function Dr(i,a){do{var d=Gn;try{if(ld(),zc.current=ei,Bc){for(var h=yn.memoizedState;h!==null;){var v=h.queue;v!==null&&(v.pending=null),h=h.next}Bc=!1}if(Go=0,Ht=Mn=yn=null,Tl=!1,Ml=0,Zc.current=null,d===null||d.return===null){Yn=1,Ga=a,Gn=null;break}e:{var k=i,L=d.return,Q=d,se=a;if(a=us,Q.flags|=32768,se!==null&&typeof se=="object"&&typeof se.then=="function"){var we=se,$e=Q,Me=$e.tag;if(($e.mode&1)===0&&(Me===0||Me===11||Me===15)){var Ce=$e.alternate;Ce?($e.updateQueue=Ce.updateQueue,$e.memoizedState=Ce.memoizedState,$e.lanes=Ce.lanes):($e.updateQueue=null,$e.memoizedState=null)}var Je=Ol(L);if(Je!==null){Je.flags&=-257,jd(Je,L,Q,k,a),Je.mode&1&&lh(k,we,a),a=Je,se=we;var nt=a.updateQueue;if(nt===null){var st=new Set;st.add(se),a.updateQueue=st}else nt.add(se);break e}else{if((a&1)===0){lh(k,we,a),o_();break e}se=Error(n(426))}}else if(Tt&&Q.mode&1){var ts=Ol(L);if(ts!==null){(ts.flags&65536)===0&&(ts.flags|=256),jd(ts,L,Q,k,a),Pa(yi(se,Q));break e}}k=se=yi(se,Q),Yn!==4&&(Yn=2),Ka===null?Ka=[k]:Ka.push(k),k=L;do{switch(k.tag){case 3:k.flags|=65536,a&=-a,k.lanes|=a;var de=kd(k,se,a);Ic(k,de);break e;case 1:Q=se;var ae=k.type,_e=k.stateNode;if((k.flags&128)===0&&(typeof ae.getDerivedStateFromError=="function"||_e!==null&&typeof _e.componentDidCatch=="function"&&(M===null||!M.has(_e)))){k.flags|=65536,a&=-a,k.lanes|=a;var Pe=Yo(k,Q,a);Ic(k,Pe);break e}}k=k.return}while(k!==null)}Gg(d)}catch(at){a=at,Gn===d&&d!==null&&(Gn=d=d.return);continue}break}while(!0)}function Ya(){var i=Xc.current;return Xc.current=ei,i===null?ei:i}function o_(){(Yn===0||Yn===3||Yn===2)&&(Yn=4),es===null||(wo&268435455)===0&&(Bl&268435455)===0||Be(es,us)}function gh(i,a){var d=sn;sn|=2;var h=Ya();(es!==i||us!==a)&&(xi=null,ds(i,a));do try{z0();break}catch(v){Dr(i,v)}while(!0);if(ld(),sn=d,Xc.current=h,Gn!==null)throw Error(n(261));return es=null,us=0,Yn}function z0(){for(;Gn!==null;)Vg(Gn)}function B0(){for(;Gn!==null&&!oi();)Vg(Gn)}function Vg(i){var a=Jg(i.alternate,i,ar);i.memoizedProps=i.pendingProps,a===null?Gg(i):Gn=a,Zc.current=null}function Gg(i){var a=i;do{var d=a.alternate;if(i=a.return,(a.flags&32768)===0){if(d=t_(d,a,ar),d!==null){Gn=d;return}}else{if(d=n_(d,a),d!==null){d.flags&=32767,Gn=d;return}if(i!==null)i.flags|=32768,i.subtreeFlags=0,i.deletions=null;else{Yn=6,Gn=null;return}}if(a=a.sibling,a!==null){Gn=a;return}Gn=a=i}while(a!==null);Yn===0&&(Yn=5)}function Ul(i,a,d){var h=ln,v=jr.transition;try{jr.transition=null,ln=1,U0(i,a,d,h)}finally{jr.transition=v,ln=h}return null}function U0(i,a,d,h){do tu();while(q!==null);if((sn&6)!==0)throw Error(n(327));d=i.finishedWork;var v=i.finishedLanes;if(d===null)return null;if(i.finishedWork=null,i.finishedLanes=0,d===i.current)throw Error(n(177));i.callbackNode=null,i.callbackPriority=0;var k=d.lanes|d.childLanes;if(da(i,k),i===es&&(Gn=es=null,us=0),(d.subtreeFlags&2064)===0&&(d.flags&2064)===0||D||(D=!0,Xg(Cr,function(){return tu(),null})),k=(d.flags&15990)!==0,(d.subtreeFlags&15990)!==0||k){k=jr.transition,jr.transition=null;var L=ln;ln=1;var Q=sn;sn|=4,Zc.current=null,_h(i,d),Ha(d,i),Vu(vl),Mo=!!zo,vl=zo=null,i.current=d,r_(d),Ps(),sn=Q,ln=L,jr.transition=k}else i.current=d;if(D&&(D=!1,q=i,H=v),k=i.pendingLanes,k===0&&(M=null),Hr(d.stateNode),ze(i,ue()),a!==null)for(h=i.onRecoverableError,d=0;d<a.length;d++)v=a[d],h(v.value,{componentStack:v.stack,digest:v.digest});if(y)throw y=!1,i=S,S=null,i;return(H&1)!==0&&i.tag!==0&&tu(),k=i.pendingLanes,(k&1)!==0?i===te?V++:(V=0,te=i):V=0,Mi(),null}function tu(){if(q!==null){var i=fa(H),a=jr.transition,d=ln;try{if(jr.transition=null,ln=16>i?16:i,q===null)var h=!1;else{if(i=q,q=null,H=0,(sn&6)!==0)throw Error(n(331));var v=sn;for(sn|=4,Xe=i.current;Xe!==null;){var k=Xe,L=k.child;if((Xe.flags&16)!==0){var Q=k.deletions;if(Q!==null){for(var se=0;se<Q.length;se++){var we=Q[se];for(Xe=we;Xe!==null;){var $e=Xe;switch($e.tag){case 0:case 11:case 15:Zo(8,$e,k)}var Me=$e.child;if(Me!==null)Me.return=$e,Xe=Me;else for(;Xe!==null;){$e=Xe;var Ce=$e.sibling,Je=$e.return;if(Rd($e),$e===we){Xe=null;break}if(Ce!==null){Ce.return=Je,Xe=Ce;break}Xe=Je}}}var nt=k.alternate;if(nt!==null){var st=nt.child;if(st!==null){nt.child=null;do{var ts=st.sibling;st.sibling=null,st=ts}while(st!==null)}}Xe=k}}if((k.subtreeFlags&2064)!==0&&L!==null)L.return=k,Xe=L;else e:for(;Xe!==null;){if(k=Xe,(k.flags&2048)!==0)switch(k.tag){case 0:case 11:case 15:Zo(9,k,k.return)}var de=k.sibling;if(de!==null){de.return=k.return,Xe=de;break e}Xe=k.return}}var ae=i.current;for(Xe=ae;Xe!==null;){L=Xe;var _e=L.child;if((L.subtreeFlags&2064)!==0&&_e!==null)_e.return=L,Xe=_e;else e:for(L=ae;Xe!==null;){if(Q=Xe,(Q.flags&2048)!==0)try{switch(Q.tag){case 0:case 11:case 15:yo(9,Q)}}catch(at){Jn(Q,Q.return,at)}if(Q===L){Xe=null;break e}var Pe=Q.sibling;if(Pe!==null){Pe.return=Q.return,Xe=Pe;break e}Xe=Q.return}}if(sn=v,Mi(),Ds&&typeof Ds.onPostCommitFiberRoot=="function")try{Ds.onPostCommitFiberRoot(cn,i)}catch{}h=!0}return h}finally{ln=d,jr.transition=a}}return!1}function Kg(i,a,d){a=yi(d,a),a=kd(i,a,1),i=pi(i,a,1),a=me(),i!==null&&(ms(i,1,a),ze(i,a))}function Jn(i,a,d){if(i.tag===3)Kg(i,i,d);else for(;a!==null;){if(a.tag===3){Kg(a,i,d);break}else if(a.tag===1){var h=a.stateNode;if(typeof a.type.getDerivedStateFromError=="function"||typeof h.componentDidCatch=="function"&&(M===null||!M.has(h))){i=yi(d,i),i=Yo(a,i,1),a=pi(a,i,1),i=me(),a!==null&&(ms(a,1,i),ze(a,i));break}}a=a.return}}function W0(i,a,d){var h=i.pingCache;h!==null&&h.delete(a),a=me(),i.pingedLanes|=i.suspendedLanes&d,es===i&&(us&d)===d&&(Yn===4||Yn===3&&(us&130023424)===us&&500>ue()-eu?ds(i,0):Qc|=d),ze(i,a)}function Yg(i,a){a===0&&((i.mode&1)===0?a=1:(a=mr,mr<<=1,(mr&130023424)===0&&(mr=4194304)));var d=me();i=os(i,a),i!==null&&(ms(i,a,d),ze(i,d))}function q0(i){var a=i.memoizedState,d=0;a!==null&&(d=a.retryLane),Yg(i,d)}function H0(i,a){var d=0;switch(i.tag){case 13:var h=i.stateNode,v=i.memoizedState;v!==null&&(d=v.retryLane);break;case 19:h=i.stateNode;break;default:throw Error(n(314))}h!==null&&h.delete(a),Yg(i,d)}var Jg;Jg=function(i,a,d){if(i!==null)if(i.memoizedProps!==a.pendingProps||ws.current)As=!0;else{if((i.lanes&d)===0&&(a.flags&128)===0)return As=!1,e_(i,a,d);As=(i.flags&131072)!==0}else As=!1,Tt&&(a.flags&1048576)!==0&&Kf(a,Ac,a.index);switch(a.lanes=0,a.tag){case 2:var h=a.type;Pr(i,a),i=a.pendingProps;var v=Ra(a,fn.current);Da(a,d),v=Jt(null,a,h,i,v,d);var k=Qn();return a.flags|=1,typeof v=="object"&&v!==null&&typeof v.render=="function"&&v.$$typeof===void 0?(a.tag=1,a.memoizedState=null,a.updateQueue=null,nr(h)?(k=!0,kl(a)):k=!1,a.memoizedState=v.state!==null&&v.state!==void 0?v.state:null,Fa(a),v.updater=Wa,a.stateNode=v,v._reactInternals=a,Pi(a,h,i,d),a=Pl(null,a,h,!0,k,d)):(a.tag=0,Tt&&k&&$c(a),Ws(null,a,v,d),a=a.child),a;case 16:h=a.elementType;e:{switch(Pr(i,a),i=a.pendingProps,v=h._init,h=v(h._payload),a.type=h,v=a.tag=G0(h),i=rr(h,i),v){case 0:a=Gc(null,a,h,i,d);break e;case 1:a=or(null,a,h,i,d);break e;case 11:a=ch(null,a,h,i,d);break e;case 14:a=uh(null,a,h,rr(h.type,i),d);break e}throw Error(n(306,h,""))}return a;case 0:return h=a.type,v=a.pendingProps,v=a.elementType===h?v:rr(h,v),Gc(i,a,h,v,d);case 1:return h=a.type,v=a.pendingProps,v=a.elementType===h?v:rr(h,v),or(i,a,h,v,d);case 3:e:{if(Sd(a),i===null)throw Error(n(387));h=a.pendingProps,k=a.memoizedState,v=k.element,Jf(i,a),Oc(a,h,null,d);var L=a.memoizedState;if(h=L.element,k.isDehydrated)if(k={element:h,isDehydrated:!1,cache:L.cache,pendingSuspenseBoundaries:L.pendingSuspenseBoundaries,transitions:L.transitions},a.updateQueue.baseState=k,a.memoizedState=k,a.flags&256){v=yi(Error(n(423)),a),a=Nd(i,a,h,d,v);break e}else if(h!==v){v=yi(Error(n(424)),a),a=Nd(i,a,h,d,v);break e}else for(Te=uo(a.stateNode.containerInfo.firstChild),Bs=a,Tt=!0,br=null,d=Vo(a,null,h,d),a.child=d;d;)d.flags=d.flags&-3|4096,d=d.sibling;else{if(Oa(),h===v){a=Di(i,a,d);break e}Ws(i,a,h,d)}a=a.child}return a;case 5:return Pc(a),i===null&&rd(a),h=a.type,v=a.pendingProps,k=i!==null?i.memoizedProps:null,L=v.children,Ea(h,v)?L=null:k!==null&&Ea(h,k)&&(a.flags|=32),dh(i,a),Ws(i,a,L,d),a.child;case 6:return i===null&&rd(a),null;case 13:return fh(i,a,d);case 4:return El(a,a.stateNode.containerInfo),h=a.pendingProps,i===null?a.child=_i(a,null,h,d):Ws(i,a,h,d),a.child;case 11:return h=a.type,v=a.pendingProps,v=a.elementType===h?v:rr(h,v),ch(i,a,h,v,d);case 7:return Ws(i,a,a.pendingProps,d),a.child;case 8:return Ws(i,a,a.pendingProps.children,d),a.child;case 12:return Ws(i,a,a.pendingProps.children,d),a.child;case 10:e:{if(h=a.type._context,v=a.pendingProps,k=a.memoizedProps,L=v.value,Cn(ft,h._currentValue),h._currentValue=L,k!==null)if(Vr(k.value,L)){if(k.children===v.children&&!ws.current){a=Di(i,a,d);break e}}else for(k=a.child,k!==null&&(k.return=a);k!==null;){var Q=k.dependencies;if(Q!==null){L=k.child;for(var se=Q.firstContext;se!==null;){if(se.context===h){if(k.tag===1){se=Oi(-1,d&-d),se.tag=2;var we=k.updateQueue;if(we!==null){we=we.shared;var $e=we.pending;$e===null?se.next=se:(se.next=$e.next,$e.next=se),we.pending=se}}k.lanes|=d,se=k.alternate,se!==null&&(se.lanes|=d),cd(k.return,d,a),Q.lanes|=d;break}se=se.next}}else if(k.tag===10)L=k.type===a.type?null:k.child;else if(k.tag===18){if(L=k.return,L===null)throw Error(n(341));L.lanes|=d,Q=L.alternate,Q!==null&&(Q.lanes|=d),cd(L,d,a),L=k.sibling}else L=k.child;if(L!==null)L.return=k;else for(L=k;L!==null;){if(L===a){L=null;break}if(k=L.sibling,k!==null){k.return=L.return,L=k;break}L=L.return}k=L}Ws(i,a,v.children,d),a=a.child}return a;case 9:return v=a.type,h=a.pendingProps.children,Da(a,d),v=Ir(v),h=h(v),a.flags|=1,Ws(i,a,h,d),a.child;case 14:return h=a.type,v=rr(h,a.pendingProps),v=rr(h.type,v),uh(i,a,h,v,d);case 15:return ir(i,a,a.type,a.pendingProps,d);case 17:return h=a.type,v=a.pendingProps,v=a.elementType===h?v:rr(h,v),Pr(i,a),a.tag=1,nr(h)?(i=!0,kl(a)):i=!1,Da(a,d),ah(a,h,v),Pi(a,h,v,d),Pl(null,a,h,!0,i,d);case 19:return $d(i,a,d);case 22:return Jo(i,a,d)}throw Error(n(156,a.tag))};function Xg(i,a){return dr(i,a)}function V0(i,a,d,h){this.tag=i,this.key=d,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=a,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=h,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function bi(i,a,d,h){return new V0(i,a,d,h)}function a_(i){return i=i.prototype,!(!i||!i.isReactComponent)}function G0(i){if(typeof i=="function")return a_(i)?1:0;if(i!=null){if(i=i.$$typeof,i===W)return 11;if(i===z)return 14}return 2}function Ja(i,a){var d=i.alternate;return d===null?(d=bi(i.tag,a,i.key,i.mode),d.elementType=i.elementType,d.type=i.type,d.stateNode=i.stateNode,d.alternate=i,i.alternate=d):(d.pendingProps=a,d.type=i.type,d.flags=0,d.subtreeFlags=0,d.deletions=null),d.flags=i.flags&14680064,d.childLanes=i.childLanes,d.lanes=i.lanes,d.child=i.child,d.memoizedProps=i.memoizedProps,d.memoizedState=i.memoizedState,d.updateQueue=i.updateQueue,a=i.dependencies,d.dependencies=a===null?null:{lanes:a.lanes,firstContext:a.firstContext},d.sibling=i.sibling,d.index=i.index,d.ref=i.ref,d}function yh(i,a,d,h,v,k){var L=2;if(h=i,typeof i=="function")a_(i)&&(L=1);else if(typeof i=="string")L=5;else e:switch(i){case J:return Wl(d.children,v,k,a);case Y:L=8,v|=8;break;case re:return i=bi(12,d,a,v|2),i.elementType=re,i.lanes=k,i;case O:return i=bi(13,d,a,v),i.elementType=O,i.lanes=k,i;case $:return i=bi(19,d,a,v),i.elementType=$,i.lanes=k,i;case ee:return wh(d,v,k,a);default:if(typeof i=="object"&&i!==null)switch(i.$$typeof){case ce:L=10;break e;case fe:L=9;break e;case W:L=11;break e;case z:L=14;break e;case A:L=16,h=null;break e}throw Error(n(130,i==null?i:typeof i,""))}return a=bi(L,d,a,v),a.elementType=i,a.type=h,a.lanes=k,a}function Wl(i,a,d,h){return i=bi(7,i,h,a),i.lanes=d,i}function wh(i,a,d,h){return i=bi(22,i,h,a),i.elementType=ee,i.lanes=d,i.stateNode={isHidden:!1},i}function l_(i,a,d){return i=bi(6,i,null,a),i.lanes=d,i}function c_(i,a,d){return a=bi(4,i.children!==null?i.children:[],i.key,a),a.lanes=d,a.stateNode={containerInfo:i.containerInfo,pendingChildren:null,implementation:i.implementation},a}function K0(i,a,d,h,v){this.tag=a,this.containerInfo=i,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=Js(0),this.expirationTimes=Js(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Js(0),this.identifierPrefix=h,this.onRecoverableError=v,this.mutableSourceEagerHydrationData=null}function u_(i,a,d,h,v,k,L,Q,se){return i=new K0(i,a,d,Q,se),a===1?(a=1,k===!0&&(a|=8)):a=0,k=bi(3,null,null,a),i.current=k,k.stateNode=i,k.memoizedState={element:h,isDehydrated:d,cache:null,transitions:null,pendingSuspenseBoundaries:null},Fa(k),i}function Y0(i,a,d){var h=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:U,key:h==null?null:""+h,children:i,containerInfo:a,implementation:d}}function Zg(i){if(!i)return xr;i=i._reactInternals;e:{if(dt(i)!==i||i.tag!==1)throw Error(n(170));var a=i;do{switch(a.tag){case 3:a=a.stateNode.context;break e;case 1:if(nr(a.type)){a=a.stateNode.__reactInternalMemoizedMergedChildContext;break e}}a=a.return}while(a!==null);throw Error(n(171))}if(i.tag===1){var d=i.type;if(nr(d))return bl(i,d,a)}return a}function Qg(i,a,d,h,v,k,L,Q,se){return i=u_(d,h,!0,i,v,k,L,Q,se),i.context=Zg(null),d=i.current,h=me(),v=Ae(d),k=Oi(h,v),k.callback=a??null,pi(d,k,v),i.current.lanes=v,ms(i,v,h),ze(i,h),i}function vh(i,a,d,h){var v=a.current,k=me(),L=Ae(v);return d=Zg(d),a.context===null?a.context=d:a.pendingContext=d,a=Oi(k,L),a.payload={element:i},h=h===void 0?null:h,h!==null&&(a.callback=h),i=pi(v,a,L),i!==null&&(Oe(i,v,L,k),Cl(i,v,L)),L}function xh(i){if(i=i.current,!i.child)return null;switch(i.child.tag){case 5:return i.child.stateNode;default:return i.child.stateNode}}function ey(i,a){if(i=i.memoizedState,i!==null&&i.dehydrated!==null){var d=i.retryLane;i.retryLane=d!==0&&d<a?d:a}}function d_(i,a){ey(i,a),(i=i.alternate)&&ey(i,a)}function J0(){return null}var ty=typeof reportError=="function"?reportError:function(i){console.error(i)};function f_(i){this._internalRoot=i}bh.prototype.render=f_.prototype.render=function(i){var a=this._internalRoot;if(a===null)throw Error(n(409));vh(i,a,null,null)},bh.prototype.unmount=f_.prototype.unmount=function(){var i=this._internalRoot;if(i!==null){this._internalRoot=null;var a=i.containerInfo;hn(function(){vh(null,i,null,null)}),a[vr]=null}};function bh(i){this._internalRoot=i}bh.prototype.unstable_scheduleHydration=function(i){if(i){var a=Er();i={blockedOn:null,target:i,priority:a};for(var d=0;d<is.length&&a!==0&&a<is[d].priority;d++);is.splice(d,0,i),d===0&&fc(i)}};function h_(i){return!(!i||i.nodeType!==1&&i.nodeType!==9&&i.nodeType!==11)}function kh(i){return!(!i||i.nodeType!==1&&i.nodeType!==9&&i.nodeType!==11&&(i.nodeType!==8||i.nodeValue!==" react-mount-point-unstable "))}function ny(){}function X0(i,a,d,h,v){if(v){if(typeof h=="function"){var k=h;h=function(){var we=xh(L);k.call(we)}}var L=Qg(a,h,i,0,null,!1,!1,"",ny);return i._reactRootContainer=L,i[vr]=L.current,wl(i.nodeType===8?i.parentNode:i),hn(),L}for(;v=i.lastChild;)i.removeChild(v);if(typeof h=="function"){var Q=h;h=function(){var we=xh(se);Q.call(we)}}var se=u_(i,0,!1,null,null,!1,!1,"",ny);return i._reactRootContainer=se,i[vr]=se.current,wl(i.nodeType===8?i.parentNode:i),hn(function(){vh(a,se,d,h)}),se}function jh(i,a,d,h,v){var k=d._reactRootContainer;if(k){var L=k;if(typeof v=="function"){var Q=v;v=function(){var se=xh(L);Q.call(se)}}vh(a,L,i,v)}else L=X0(d,a,i,v,h);return xh(L)}dc=function(i){switch(i.tag){case 3:var a=i.stateNode;if(a.current.memoizedState.isDehydrated){var d=Hn(a.pendingLanes);d!==0&&(Yi(a,d|1),ze(a,ue()),(sn&6)===0&&(ea=ue()+500,Mi()))}break;case 13:hn(function(){var h=os(i,1);if(h!==null){var v=me();Oe(h,i,1,v)}}),d_(i,1)}},To=function(i){if(i.tag===13){var a=os(i,134217728);if(a!==null){var d=me();Oe(a,i,134217728,d)}d_(i,134217728)}},_s=function(i){if(i.tag===13){var a=Ae(i),d=os(i,a);if(d!==null){var h=me();Oe(d,i,a,h)}d_(i,a)}},Er=function(){return ln},Ar=function(i,a){var d=ln;try{return ln=i,a()}finally{ln=d}},Nr=function(i,a,d){switch(a){case"input":if(je(i,d),a=d.name,d.type==="radio"&&a!=null){for(d=i;d.parentNode;)d=d.parentNode;for(d=d.querySelectorAll("input[name="+JSON.stringify(""+a)+'][type="radio"]'),a=0;a<d.length;a++){var h=d[a];if(h!==i&&h.form===i.form){var v=Ma(h);if(!v)throw Error(n(90));pt(h),je(h,v)}}}break;case"textarea":en(i,d);break;case"select":a=d.value,a!=null&&Ie(i,!!d.multiple,a,!1)}},rt=xn,ct=hn;var Z0={usingClientEntryPoint:!1,Events:[Uo,Kr,Ma,Ye,Ge,xn]},Fd={findFiberByHostInstance:Gr,bundleType:0,version:"18.3.1",rendererPackageName:"react-dom"},Q0={bundleType:Fd.bundleType,version:Fd.version,rendererPackageName:Fd.rendererPackageName,rendererConfig:Fd.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:I.ReactCurrentDispatcher,findHostInstanceByFiber:function(i){return i=ss(i),i===null?null:i.stateNode},findFiberByHostInstance:Fd.findFiberByHostInstance||J0,findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null,reconcilerVersion:"18.3.1-next-f1338f8080-20240426"};if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"){var Sh=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!Sh.isDisabled&&Sh.supportsFiber)try{cn=Sh.inject(Q0),Ds=Sh}catch{}}return Fr.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=Z0,Fr.createPortal=function(i,a){var d=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!h_(a))throw Error(n(200));return Y0(i,a,null,d)},Fr.createRoot=function(i,a){if(!h_(i))throw Error(n(299));var d=!1,h="",v=ty;return a!=null&&(a.unstable_strictMode===!0&&(d=!0),a.identifierPrefix!==void 0&&(h=a.identifierPrefix),a.onRecoverableError!==void 0&&(v=a.onRecoverableError)),a=u_(i,1,!1,null,null,d,!1,h,v),i[vr]=a.current,wl(i.nodeType===8?i.parentNode:i),new f_(a)},Fr.findDOMNode=function(i){if(i==null)return null;if(i.nodeType===1)return i;var a=i._reactInternals;if(a===void 0)throw typeof i.render=="function"?Error(n(188)):(i=Object.keys(i).join(","),Error(n(268,i)));return i=ss(a),i=i===null?null:i.stateNode,i},Fr.flushSync=function(i){return hn(i)},Fr.hydrate=function(i,a,d){if(!kh(a))throw Error(n(200));return jh(null,i,a,!0,d)},Fr.hydrateRoot=function(i,a,d){if(!h_(i))throw Error(n(405));var h=d!=null&&d.hydratedSources||null,v=!1,k="",L=ty;if(d!=null&&(d.unstable_strictMode===!0&&(v=!0),d.identifierPrefix!==void 0&&(k=d.identifierPrefix),d.onRecoverableError!==void 0&&(L=d.onRecoverableError)),a=Qg(a,null,i,1,d??null,v,!1,k,L),i[vr]=a.current,wl(i),h)for(i=0;i<h.length;i++)d=h[i],v=d._getVersion,v=v(d._source),a.mutableSourceEagerHydrationData==null?a.mutableSourceEagerHydrationData=[d,v]:a.mutableSourceEagerHydrationData.push(d,v);return new bh(a)},Fr.render=function(i,a,d){if(!kh(a))throw Error(n(200));return jh(null,i,a,!1,d)},Fr.unmountComponentAtNode=function(i){if(!kh(i))throw Error(n(40));return i._reactRootContainer?(hn(function(){jh(null,null,i,!1,function(){i._reactRootContainer=null,i[vr]=null})}),!0):!1},Fr.unstable_batchedUpdates=xn,Fr.unstable_renderSubtreeIntoContainer=function(i,a,d,h){if(!kh(d))throw Error(n(200));if(i==null||i._reactInternals===void 0)throw Error(n(38));return jh(i,a,d,!1,h)},Fr.version="18.3.1-next-f1338f8080-20240426",Fr}var uy;function Nv(){if(uy)return p_.exports;uy=1;function e(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),p_.exports=lk(),p_.exports}var dy;function ck(){if(dy)return Nh;dy=1;var e=Nv();return Nh.createRoot=e.createRoot,Nh.hydrateRoot=e.hydrateRoot,Nh}var uk=ck();const dk=og(uk),Cv=[{id:"dark",label:"Dark (Abstract)",group:"dark",swatches:["#1a1a2e","#16213e","#0f3460","#e94560","#60a5fa","#27ae60"]},{id:"observer-night",label:"Observer Night",group:"dark",swatches:["#0b0f14","#10161e","#161e28","#e8a54a","#6ea8d8","#7bc98c"]},{id:"catppuccin-mocha",label:"Catppuccin Mocha",group:"dark",swatches:["#1e1e2e","#181825","#313244","#cba6f7","#89b4fa","#a6e3a1"]},{id:"catppuccin-macchiato",label:"Catppuccin Macchiato",group:"dark",swatches:["#24273a","#1e2030","#363a4f","#c6a0f6","#8aadf4","#a6da95"]},{id:"catppuccin-frappe",label:"Catppuccin Frappe",group:"dark",swatches:["#303446","#292c3c","#414559","#ca9ee6","#8caaee","#a6d189"]},{id:"rose-pine",label:"Rose Pine",group:"dark",swatches:["#191724","#1f1d2e","#26233a","#c4a7e7","#31748f","#9ccfd8"]},{id:"rose-pine-moon",label:"Rose Pine Moon",group:"dark",swatches:["#232136","#2a273f","#393552","#c4a7e7","#3e8fb0","#9ccfd8"]},{id:"tokyo-night",label:"Tokyo Night",group:"dark",swatches:["#1a1b26","#24283b","#414868","#7aa2f7","#2ac3de","#9ece6a"]},{id:"nord",label:"Nord",group:"dark",swatches:["#2e3440","#3b4252","#434c5e","#88c0d0","#5e81ac","#a3be8c"]},{id:"one-dark",label:"One Dark",group:"dark",swatches:["#282c34","#21252b","#3a3f4b","#61afef","#c678dd","#98c379"]},{id:"dracula",label:"Dracula",group:"dark",swatches:["#282a36","#343746","#44475a","#ff79c6","#8be9fd","#50fa7b"]},{id:"monokai",label:"Monokai",group:"dark",swatches:["#272822","#2d2e27","#3e3d32","#66d9ef","#a1efe4","#a6e22e"]},{id:"gruvbox",label:"Gruvbox",group:"dark",swatches:["#282828","#3c3836","#504945","#fe8019","#83a598","#b8bb26"]},{id:"solarized-dark",label:"Solarized Dark",group:"dark",swatches:["#002b36","#073642","#0b4b5a","#268bd2","#2aa198","#859900"]},{id:"everforest-dark",label:"Everforest Dark",group:"dark",swatches:["#2b3339","#323c41","#3a464c","#a7c080","#7fbbb3","#a7c080"]},{id:"catppuccin-latte",label:"Catppuccin Latte",group:"light",swatches:["#eff1f5","#e6e9ef","#ccd0da","#8839ef","#1e66f5","#40a02b"]},{id:"rose-pine-dawn",label:"Rose Pine Dawn",group:"light",swatches:["#faf4ed","#fffaf3","#f2e9e1","#907aa9","#56949f","#286983"]},{id:"one-light",label:"One Light",group:"light",swatches:["#fafafa","#ffffff","#e5e5e6","#4078f2","#a626a4","#50a14f"]},{id:"everforest-light",label:"Everforest Light",group:"light",swatches:["#fdf6e3","#fffbef","#e8e0cc","#4f8f5a","#3a94c5","#4f8f5a"]},{id:"solarized-light",label:"Solarized Light",group:"light",swatches:["#fdf6e3","#eee8d5","#e3ddc9","#268bd2","#2aa198","#859900"]},{id:"light",label:"Light",group:"light",swatches:["#f7f7fb","#ffffff","#e6e8f0","#e94560","#2563eb","#16a34a"]}];Cv.map(e=>({id:e.id,label:e.label}));function fk(e){return`theme-${String(e||"").trim()||"dark"}`}function fy(e){try{const t=document.documentElement,n=Array.from(t.classList).filter(r=>r.startsWith("theme-"));for(const r of n)t.classList.remove(r);t.classList.add(fk(e))}catch{}}const dp=[{id:"sm",label:"Small",scale:.9},{id:"md",label:"Medium",scale:1},{id:"lg",label:"Large",scale:1.1},{id:"xl",label:"Extra Large",scale:1.2}],fp=[{id:"compact",label:"Compact",density:.85},{id:"standard",label:"Standard",density:1},{id:"spacious",label:"Spacious",density:1.2}];function hk(e){const t=String(e).trim();return dp.find(n=>n.id===t)||dp[1]}function mk(e){const t=String(e).trim();return fp.find(n=>n.id===t)||fp[1]}function hy(e){try{const t=document.documentElement,n=hk(e.font_scale||"md"),r=mk(e.header_density||"standard");t.style.setProperty("--font-scale",String(n.scale)),t.style.setProperty("--header-density",String(r.density))}catch{}}const w_={sm:"(max-width: 767.98px)",md:"(max-width: 1023.98px)",short:"(max-height: 500px)"};function _k(e){try{return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia(e).matches}catch{return!1}}function my(e){const[t,n]=p.useState(()=>_k(e));return p.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const r=window.matchMedia(e),o=()=>n(r.matches);return o(),typeof r.addEventListener=="function"?r.addEventListener("change",o):r.addListener(o),()=>{typeof r.removeEventListener=="function"?r.removeEventListener("change",o):r.removeListener(o)}},[e]),t}let Bd=null;function pk(e,t){const n=Math.max(0,Math.round(e));if(!(t.scale<=1.01))return{vvHeight:n,keyboardInset:0};const r=Math.max(0,Math.min(n,Math.round(t.height))),o=Math.max(0,Math.round(e-t.height-Math.max(0,t.offsetTop)));return{vvHeight:r,keyboardInset:o}}function gk(){if(Bd)return Bd;if(typeof window>"u"||typeof document>"u")return()=>{};const e=window.visualViewport;if(!e)return()=>{};const t=document.documentElement;let n=0;const r=()=>{n=0;const{vvHeight:l,keyboardInset:u}=pk(window.innerHeight,{height:e.height,offsetTop:e.offsetTop,scale:e.scale||1});t.style.setProperty("--vv-height",`${l}px`),t.style.setProperty("--keyboard-inset",`${u}px`)},o=()=>{n||(n=window.requestAnimationFrame(r))};return r(),e.addEventListener("resize",o),e.addEventListener("scroll",o),window.addEventListener("orientationchange",o),Bd=()=>{e.removeEventListener("resize",o),e.removeEventListener("scroll",o),window.removeEventListener("orientationchange",o),n&&window.cancelAnimationFrame(n),t.style.removeProperty("--vv-height"),t.style.removeProperty("--keyboard-inset"),Bd=null},Bd}var Ev=Nv();function nu(...e){return e.filter(Boolean).join(" ")}function bu({value:e,options:t,placeholder:n="Select…",disabled:r=!1,loading:o=!1,searchable:l=!0,searchPlaceholder:u="Search…",allowCustom:c=!1,clearable:f=!1,minPopoverWidth:m=240,variant:_="panel",className:g,triggerClassName:w,ariaLabel:x,id:j,includeValueOption:b=!1,onOpen:N,customOptionLabel:C,validateCustomValue:E,onChange:T,renderOption:I,renderValue:K}){const U=p.useRef(null),J=p.useRef(null),Y=p.useRef(null),re=p.useRef(N),ce=p.useId(),fe=j||`af-select-${ce.replace(/[^a-zA-Z0-9_-]/g,"")}`,W=`${fe}-listbox`,[O,$]=p.useState(!1),[z,A]=p.useState(""),[ee,P]=p.useState(0),[F,G]=p.useState("bottom"),[R,Z]=p.useState({left:0,top:0,width:0});p.useEffect(()=>{re.current=N},[N]);const X=p.useMemo(()=>{if(!b)return t;const xe=String(e??"").trim();return!xe||t.some(Ie=>Ie.value===xe)?t:[...t,{value:xe,label:xe}]},[b,t,e]),ie=p.useMemo(()=>{const xe=String(e??"");return X.find(Ie=>Ie.value===xe)||null},[X,e]),ne=p.useMemo(()=>(ie==null?void 0:ie.label)||String(e||"").trim()||"",[ie,e]),ye=p.useMemo(()=>{const xe=z.trim().toLowerCase();return xe?X.filter(Ie=>Ie.label.toLowerCase().includes(xe)||Ie.value.toLowerCase().includes(xe)):X},[X,z]),he=p.useMemo(()=>{if(!c)return null;const xe=z.trim();if(!xe||X.some(zt=>zt.value===xe))return null;const qe=(E==null?void 0:E(xe,{options:X}))||"";return{value:xe,label:C?C(xe):`Use "${xe}"`,disabled:!!qe,reason:qe}},[c,C,X,z,E]),pe=p.useMemo(()=>{const xe=he?[he,...ye]:ye;if(xe.length>0)return xe;const Ie=String(e??"").trim();return o&&Ie?[{value:Ie,label:ne||Ie}]:xe},[he,ye,o,ne,e]),Ne=p.useCallback(()=>{const xe=U.current;if(!xe)return;const Ie=xe.getBoundingClientRect(),qe=Math.max(Ie.width,m),zt=Math.max(8,Math.min(Ie.left,window.innerWidth-qe-8)),en=window.innerHeight-Ie.bottom,bn=Ie.top,Wt=en>=220||en>=bn?"bottom":"top";G(Wt);const It=Wt==="bottom"?Ie.bottom+6:Ie.top-6;Z({left:zt,top:It,width:qe})},[m]),Ue=p.useCallback(()=>{$(!1),A("")},[]);p.useEffect(()=>{var xe;O&&((xe=re.current)==null||xe.call(re))},[O]),p.useEffect(()=>{if(!O)return;Ne();const xe=()=>Ne();return window.addEventListener("resize",xe),window.addEventListener("scroll",xe,!0),()=>{window.removeEventListener("resize",xe),window.removeEventListener("scroll",xe,!0)}},[O,Ne]),p.useEffect(()=>{if(!O)return;const xe=Ie=>{var zt,en;const qe=Ie.target;qe&&((zt=U.current)!=null&&zt.contains(qe)||(en=J.current)!=null&&en.contains(qe)||Ue())};return document.addEventListener("mousedown",xe,!0),()=>document.removeEventListener("mousedown",xe,!0)},[O,Ue]),p.useEffect(()=>{if(!O)return;const xe=Math.max(0,pe.findIndex(Ie=>Ie.value===e));P(xe===-1?0:xe),l&&setTimeout(()=>{var Ie;return(Ie=Y.current)==null?void 0:Ie.focus()},0)},[O,l,e,pe]);const We=xe=>{var qe;const Ie=pe.find(zt=>zt.value===xe);Ie!=null&&Ie.disabled||(T(xe),Ue(),(qe=U.current)==null||qe.focus())},pt=xe=>{var Ie,qe;if(xe.key==="Escape")return xe.preventDefault(),Ue(),(Ie=U.current)==null||Ie.focus(),!0;if(xe.key==="Tab")return Ue(),(qe=U.current)==null||qe.focus(),!1;if(xe.key==="ArrowDown")return xe.preventDefault(),P(zt=>Math.min(zt+1,Math.max(0,pe.length-1))),!0;if(xe.key==="ArrowUp")return xe.preventDefault(),P(zt=>Math.max(zt-1,0)),!0;if(xe.key==="Home")return xe.preventDefault(),P(0),!0;if(xe.key==="End")return xe.preventDefault(),P(Math.max(0,pe.length-1)),!0;if(xe.key==="Enter"){xe.preventDefault();const zt=pe[ee];return zt&&We(zt.value),!0}return!1},Fe=xe=>{if(!r){if(O){if(pt(xe))return;if(xe.key===" "&&!l){xe.preventDefault();const Ie=pe[ee];Ie&&We(Ie.value)}return}(xe.key==="Enter"||xe.key===" "||xe.key==="ArrowDown"||xe.key==="ArrowUp")&&(xe.preventDefault(),$(!0))}},tt=!!String(e||"").trim(),lt=tt?ne:n,Ke=he!=null&&he.disabled?he.reason||"Unavailable":"",je=O&&pe.length>0?`${fe}-opt-${ee}`:void 0,Re=s.jsx("span",{className:nu("af-select-value",!tt&&"af-select-value--placeholder"),children:o&&!tt?"Loading…":lt}),ht=K?K(ie,String(e||"")):Re;return s.jsxs("span",{className:nu("af-select",_==="pin"?"af-select--pin":"af-select--panel",g),children:[s.jsxs("button",{ref:U,id:fe,type:"button",className:nu("af-select-trigger",f&&tt&&"af-select-trigger--clearable",w),disabled:r,onMouseDown:xe=>xe.stopPropagation(),onClick:xe=>{xe.stopPropagation(),!r&&$(Ie=>!Ie)},onKeyDown:Fe,role:l?void 0:"combobox","aria-haspopup":"listbox","aria-expanded":O,"aria-controls":O?W:void 0,"aria-activedescendant":l?void 0:je,"aria-label":x,children:[ht,s.jsx("span",{className:nu("af-select-caret",O&&"af-select-caret--open"),children:"▾"})]}),f&&tt?s.jsx("button",{type:"button",className:"af-select-clear-btn","aria-label":"Clear selection",disabled:r,onMouseDown:xe=>{xe.preventDefault(),xe.stopPropagation()},onClick:xe=>{var Ie;xe.preventDefault(),xe.stopPropagation(),T(""),Ue(),(Ie=U.current)==null||Ie.focus()},title:"Clear",children:"×"}):null,O?Ev.createPortal(s.jsxs("div",{ref:J,className:nu("af-select-popover",F==="top"&&"af-select-popover--top"),style:{position:"fixed",left:`${R.left}px`,top:`${R.top}px`,width:`${R.width}px`},onMouseDown:xe=>xe.stopPropagation(),onClick:xe=>xe.stopPropagation(),onWheel:xe=>xe.stopPropagation(),onKeyDown:pt,tabIndex:-1,children:[l?s.jsxs("div",{className:"af-select-search",children:[s.jsx("input",{ref:Y,className:"af-select-search-input",value:z,onChange:xe=>A(xe.target.value),placeholder:u,onKeyDown:pt,role:"combobox","aria-expanded":!0,"aria-controls":W,"aria-activedescendant":je,"aria-invalid":!!Ke,"aria-describedby":Ke?`${fe}-custom-error`:void 0}),Ke?s.jsx("div",{id:`${fe}-custom-error`,className:"af-select-custom-error",role:"alert",children:Ke}):null]}):null,s.jsx("div",{className:"af-select-options",role:"listbox",id:W,"aria-label":x,children:o&&pe.length===0?s.jsx("div",{className:"af-select-empty",children:"Loading…"}):pe.length===0?s.jsx("div",{className:"af-select-empty",children:"No results"}):pe.map((xe,Ie)=>{var It;const qe=xe.value===e,zt=Ie===ee,en=String(xe.group||"").trim(),bn=Ie>0?String(((It=pe[Ie-1])==null?void 0:It.group)||"").trim():"",Wt=!!en&&en!==bn;return s.jsxs(ve.Fragment,{children:[Wt?s.jsx("div",{className:"af-select-group",role:"presentation",children:en}):null,s.jsx("div",{id:`${fe}-opt-${Ie}`,role:"option","aria-selected":qe,className:nu("af-select-option",qe&&"af-select-option--selected",zt&&"af-select-option--highlighted",xe.disabled&&"af-select-option--disabled"),title:xe.disabled?xe.reason||"Unavailable":void 0,onMouseEnter:()=>P(Ie),onMouseDown:Sn=>{Sn.preventDefault(),Sn.stopPropagation()},onClick:()=>We(xe.value),"aria-disabled":xe.disabled?!0:void 0,children:I?I(xe,{selected:qe,highlighted:zt}):s.jsxs(s.Fragment,{children:[s.jsxs("span",{className:"af-select-option-label",children:[s.jsx("span",{children:xe.label}),xe.reason?s.jsx("small",{className:"af-select-option-reason",children:xe.reason}):null]}),qe?s.jsx("span",{className:"af-select-check",children:"✓"}):null]})})]},xe.value)})})]}),document.body):null]})}function yk(e){const t=new Set,n=[];for(const r of e||[]){if(!r||typeof r!="object")continue;const o=String(r.name||"").trim();!o||t.has(o)||(t.add(o),n.push({name:o,display_name:typeof r.display_name=="string"?r.display_name:void 0}))}return n.sort((r,o)=>r.name.localeCompare(o.name)),n}function wk(e){const t=new Set,n=[];for(const r of e||[]){const o=String(r||"").trim();!o||t.has(o)||(t.add(o),n.push(o))}return n.sort(),n}function vk(e){const t=e.disabled===!0,n=e.layout||"stack",r=e.allowGatewayDefault!==!1,o=String(e.gatewayDefaultLabel||"(gateway default)"),l=String(e.providerLabel||"Provider"),u=String(e.modelLabel||"Model"),c=String(e.providerPlaceholder||"(select)"),f=String(e.modelPlaceholder||"(select)"),m=String(e.provider||"").trim(),_=String(e.model||"").trim(),g=yk(e.providers),w=wk(e.models),x=t||!!e.loadingProviders,j=t||!!e.loadingModels,b=[...r?[{value:"",label:o}]:[],...g.map(C=>({value:C.name,label:C.display_name?`${C.display_name} (${C.name})`:C.name}))],N=[...r?[{value:"",label:o}]:[],...w.map(C=>({value:C,label:C}))];return s.jsxs("div",{className:e.className,style:n==="row"?{display:"flex",gap:"10px",flexWrap:"wrap",alignItems:"flex-start"}:{display:"flex",flexDirection:"column",gap:"10px"},children:[s.jsxs("div",{style:n==="row"?{flex:"1 1 260px",minWidth:240}:void 0,children:[s.jsx("label",{children:l}),s.jsx(bu,{value:m,options:b,placeholder:r?o:c,disabled:x,loading:!!e.loadingProviders,searchable:!0,allowCustom:e.allowCustomProvider===!0,clearable:r,variant:"panel",triggerClassName:e.selectClassName,ariaLabel:l,onChange:C=>e.onChange({provider:String(C||"").trim(),model:""})}),e.loadingProviders?s.jsx("div",{className:"mono muted",style:{fontSize:"12px",marginTop:"6px"},children:"Loading providers…"}):null,e.providerError?s.jsx("div",{className:"mono",style:{color:"var(--error)",fontSize:"12px",marginTop:"6px"},children:e.providerError}):null]}),s.jsxs("div",{style:n==="row"?{flex:"1 1 260px",minWidth:240}:void 0,children:[s.jsx("label",{children:u}),s.jsx(bu,{value:_,options:N,placeholder:r?o:f,disabled:j,loading:!!e.loadingModels,searchable:!0,allowCustom:e.allowCustomModel===!0,clearable:r,variant:"panel",triggerClassName:e.selectClassName,ariaLabel:u,onChange:C=>e.onChange({provider:m,model:String(C||"").trim()})}),e.loadingModels?s.jsx("div",{className:"mono muted",style:{fontSize:"12px",marginTop:"6px"},children:"Loading models…"}):null,e.modelError?s.jsx("div",{className:"mono",style:{color:"var(--error)",fontSize:"12px",marginTop:"6px"},children:e.modelError}):null]})]})}function _y(...e){return e.filter(Boolean).join(" ")}function xk({kicker:e="AbstractGateway connection",title:t="Connect to AbstractGateway",description:n="Sign in with the Gateway user token assigned by the Gateway admin.",statusLabel:r="Not signed in",statusTone:o="neutral",showGatewayUrl:l=!1,gatewayUrl:u="",gatewayUrlPlaceholder:c="http://127.0.0.1:8080",onGatewayUrlChange:f,userId:m,userPlaceholder:_="admin",onUserIdChange:g,token:w,tokenPlaceholder:x="Paste Gateway user token",showToken:j=!1,onTokenChange:b,onShowTokenChange:N,remember:C=!1,rememberLabel:E="Remember this browser",onRememberChange:T,loading:I=!1,submitting:K=!1,submitDisabled:U=!1,submitLabel:J="Sign in",submittingLabel:Y="Signing in...",closeLabel:re="Close",signOutLabel:ce="Sign out",showClose:fe=!1,showSignOut:W=!1,error:O,message:$,className:z,onSubmit:A,onClose:ee,onSignOut:P}){const F=I||K,G=F||U||!String(m||"").trim()||!String(w||"").trim(),R=Z=>{Z.preventDefault(),!G&&A()};return s.jsxs("form",{className:_y("af-gateway-signin",z),onSubmit:R,children:[s.jsxs("div",{className:"af-gateway-signin__hero",children:[s.jsxs("div",{children:[s.jsx("div",{className:"af-gateway-signin__kicker",children:e}),s.jsx("h2",{children:t}),n?s.jsx("p",{children:n}):null]}),s.jsx("div",{className:"af-gateway-signin__mark","aria-hidden":"true",children:"↔"})]}),s.jsx("div",{className:"af-gateway-signin__status-row",children:s.jsx("span",{className:_y("af-gateway-signin__status",`af-gateway-signin__status--${o}`),children:r})}),s.jsxs("div",{className:"af-gateway-signin__form",children:[l?s.jsxs(s.Fragment,{children:[s.jsx("label",{className:"af-gateway-signin__label",htmlFor:"gateway-session-url",children:"Gateway URL"}),s.jsx("input",{id:"gateway-session-url",value:u,onChange:Z=>f==null?void 0:f(Z.target.value),placeholder:c,autoComplete:"url",disabled:F})]}):null,s.jsx("label",{className:"af-gateway-signin__label",htmlFor:"gateway-session-user",children:"Gateway user"}),s.jsx("input",{id:"gateway-session-user",value:m,onChange:Z=>g(Z.target.value),placeholder:_,autoComplete:"username",disabled:F}),s.jsx("label",{className:"af-gateway-signin__label",htmlFor:"gateway-session-token",children:"Gateway token"}),s.jsxs("div",{className:"af-gateway-signin__token-input",children:[s.jsx("input",{id:"gateway-session-token",type:j?"text":"password",value:w,onChange:Z=>b(Z.target.value),placeholder:x,autoComplete:"off","data-1p-ignore":"","data-lpignore":"true","data-bwignore":"",spellCheck:!1,disabled:F}),s.jsx("button",{className:"af-gateway-signin__secondary",type:"button",onClick:()=>N==null?void 0:N(!j),disabled:F,children:j?"Hide":"Show"})]}),s.jsxs("label",{className:"af-gateway-signin__checkbox",children:[s.jsx("input",{type:"checkbox",checked:!!C,onChange:Z=>T==null?void 0:T(Z.target.checked),disabled:F}),E]})]}),O?s.jsx("div",{className:"af-gateway-signin__message af-gateway-signin__message--error",children:O}):null,!O&&$?s.jsx("div",{className:"af-gateway-signin__message af-gateway-signin__message--ok",children:$}):null,s.jsxs("div",{className:"af-gateway-signin__actions",children:[fe?s.jsx("button",{className:"af-gateway-signin__secondary",type:"button",onClick:ee,disabled:F,children:re}):null,W?s.jsx("button",{className:"af-gateway-signin__secondary",type:"button",onClick:()=>void(P==null?void 0:P()),disabled:F,children:ce}):null,s.jsx("button",{className:"af-gateway-signin__primary",type:"submit",disabled:G,children:K?Y:J})]})]})}function bk(e){return e==="light"?"Light":"Dark"}function kk(e){const t=e.themes&&e.themes.length?e.themes:Cv,n=e.showSwatches!==!1,r=e.variant||"panel",o=p.useMemo(()=>{const u={};for(const c of t)u[c.id]=c;return u},[t]),l=p.useMemo(()=>t.map(u=>({value:u.id,label:u.label,group:bk(u.group)})),[t]);return s.jsx(bu,{value:e.value,options:l,placeholder:e.placeholder||"Select theme…",disabled:e.disabled===!0,searchable:!0,allowCustom:!1,clearable:!1,variant:r,className:e.className,triggerClassName:e.triggerClassName,onChange:u=>e.onChange(String(u||"").trim()),renderValue:(u,c)=>{const f=String(c||"").trim(),m=o[f],_=(m==null?void 0:m.label)||f||e.placeholder||"Select theme…",g=(m==null?void 0:m.swatches)||null,w=!f;return s.jsxs("span",{className:"af-theme-value",children:[s.jsx("span",{className:`af-theme-label ${w?"af-theme-label--placeholder":""}`.trim(),children:_}),n&&g?s.jsx("span",{className:"af-theme-swatches","aria-hidden":"true",children:g.map((x,j)=>s.jsx("span",{className:"af-theme-swatch",style:{background:x}},`${f}:${j}`))}):null]})},renderOption:(u,c)=>{const f=String(u.value||"").trim(),m=o[f],_=(m==null?void 0:m.swatches)||null;return s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"af-theme-option-label",children:u.label}),s.jsxs("span",{className:"af-theme-option-right",children:[n&&_?s.jsx("span",{className:"af-theme-swatches","aria-hidden":"true",children:_.map((g,w)=>s.jsx("span",{className:"af-theme-swatch",style:{background:g}},`${f}:${w}`))}):null,c.selected?s.jsx("span",{className:"af-select-check",children:"✓"}):null]})]})}})}function jk(e){const t=e.scales&&e.scales.length?e.scales:dp,n=e.variant||"panel",r=p.useMemo(()=>t.map(o=>({value:o.id,label:o.label})),[t]);return s.jsx(bu,{value:e.value,options:r,placeholder:e.placeholder||"Font size…",disabled:e.disabled===!0,searchable:!1,allowCustom:!1,clearable:!1,variant:n,className:e.className,triggerClassName:e.triggerClassName,onChange:o=>e.onChange(String(o||"").trim())})}function Sk(e){const t=e.densities&&e.densities.length?e.densities:fp,n=e.variant||"panel",r=p.useMemo(()=>t.map(o=>({value:o.id,label:o.label})),[t]);return s.jsx(bu,{value:e.value,options:r,placeholder:e.placeholder||"Header size…",disabled:e.disabled===!0,searchable:!1,allowCustom:!1,clearable:!1,variant:n,className:e.className,triggerClassName:e.triggerClassName,onChange:o=>e.onChange(String(o||"").trim())})}const Nk=new Set(["board","inbox","server","agent","playCircle","list","gear"]);function Ck(e){switch(e){case"chat":return s.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H8l-5 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"});case"plus":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M12 5v14"}),s.jsx("path",{d:"M5 12h14"})]});case"history":return s.jsxs(s.Fragment,{children:[s.jsx("circle",{cx:"12",cy:"12",r:"9"}),s.jsx("path",{d:"M12 7v5l3 3"})]});case"refresh":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M21 12a9 9 0 0 0-15.5-6.4L3 8"}),s.jsx("path",{d:"M3 3v5h5"}),s.jsx("path",{d:"M3 12a9 9 0 0 0 15.5 6.4L21 16"}),s.jsx("path",{d:"M21 21v-5h-5"})]});case"settings":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M4 6h16"}),s.jsx("circle",{cx:"8",cy:"6",r:"2"}),s.jsx("path",{d:"M4 12h16"}),s.jsx("circle",{cx:"16",cy:"12",r:"2"}),s.jsx("path",{d:"M4 18h16"}),s.jsx("circle",{cx:"10",cy:"18",r:"2"})]});case"user":return s.jsxs(s.Fragment,{children:[s.jsx("circle",{cx:"12",cy:"8",r:"4"}),s.jsx("path",{d:"M4 21a8 8 0 0 1 16 0"})]});case"bot":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M12 2v3"}),s.jsx("rect",{x:"5",y:"6",width:"14",height:"14",rx:"3"}),s.jsx("circle",{cx:"9",cy:"13",r:"1",fill:"currentColor",stroke:"none"}),s.jsx("circle",{cx:"15",cy:"13",r:"1",fill:"currentColor",stroke:"none"}),s.jsx("path",{d:"M9 17h6"})]});case"paperclip":return s.jsx("path",{d:"M21.44 11.05l-9.19 9.19a5.5 5.5 0 0 1-7.78-7.78l9.19-9.19a3.5 3.5 0 0 1 4.95 4.95l-9.2 9.19a1.5 1.5 0 0 1-2.12-2.12l8.49-8.48"});case"mic":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M12 14a3 3 0 0 0 3-3V5a3 3 0 0 0-6 0v6a3 3 0 0 0 3 3z"}),s.jsx("path",{d:"M19 11a7 7 0 0 1-14 0"}),s.jsx("path",{d:"M12 18v4"}),s.jsx("path",{d:"M8 22h8"})]});case"speaker":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M11 5L6 9H2v6h4l5 4V5z"}),s.jsx("path",{d:"M15.5 8.5a5 5 0 0 1 0 7"}),s.jsx("path",{d:"M18 6a9 9 0 0 1 0 12"})]});case"pause":return s.jsxs(s.Fragment,{children:[s.jsx("rect",{x:"6",y:"4",width:"4",height:"16",rx:"1",fill:"currentColor",stroke:"none"}),s.jsx("rect",{x:"14",y:"4",width:"4",height:"16",rx:"1",fill:"currentColor",stroke:"none"})]});case"terminal":return s.jsxs(s.Fragment,{children:[s.jsx("rect",{x:"3",y:"4",width:"18",height:"16",rx:"2",ry:"2"}),s.jsx("path",{d:"M7 9l3 3-3 3"}),s.jsx("path",{d:"M12 15h5"})]});case"edit":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M12 20h9"}),s.jsx("path",{d:"M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4 12.5-12.5z"})]});case"download":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),s.jsx("path",{d:"M7 10l5 5 5-5"}),s.jsx("path",{d:"M12 15V3"})]});case"loader":return s.jsx("path",{d:"M21 12a9 9 0 1 1-3.3-6.9"});case"info":return s.jsxs(s.Fragment,{children:[s.jsx("circle",{cx:"12",cy:"12",r:"10"}),s.jsx("path",{d:"M12 16v-4"}),s.jsx("circle",{cx:"12",cy:"8",r:"0.75",fill:"currentColor",stroke:"none"})]});case"warning":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M12 3l10 18H2L12 3z"}),s.jsx("path",{d:"M12 9v4"}),s.jsx("circle",{cx:"12",cy:"17",r:"0.75",fill:"currentColor",stroke:"none"})]});case"error":return s.jsxs(s.Fragment,{children:[s.jsx("circle",{cx:"12",cy:"12",r:"10"}),s.jsx("path",{d:"M15 9l-6 6"}),s.jsx("path",{d:"M9 9l6 6"})]});case"copy":return s.jsxs(s.Fragment,{children:[s.jsx("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2"}),s.jsx("path",{d:"M5 15V5a2 2 0 0 1 2-2h10"})]});case"check":return s.jsx("path",{d:"M20 6L9 17l-5-5"});case"x":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M18 6L6 18"}),s.jsx("path",{d:"M6 6l12 12"})]});case"chevronDown":return s.jsx("path",{d:"M6 9l6 6 6-6"});case"chevronRight":return s.jsx("path",{d:"M9 18l6-6-6-6"});case"trash":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M3 6h18"}),s.jsx("path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"}),s.jsx("path",{d:"M6 6l1 16h10l1-16"}),s.jsx("path",{d:"M10 11v6"}),s.jsx("path",{d:"M14 11v6"})]});case"send":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M22 2L11 13"}),s.jsx("path",{d:"M22 2L15 22l-4-9-9-4 20-7z"})]});case"thumbsUp":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M7 10v11"}),s.jsx("path",{d:"M7 10l4.5-8a2 2 0 0 1 3.6 1.5L14 8h5.2a2 2 0 0 1 2 2.4l-1.6 8a2 2 0 0 1-2 1.6H7"})]});case"thumbsDown":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M17 14V3"}),s.jsx("path",{d:"M17 14l-4.5 8a2 2 0 0 1-3.6-1.5L10 16H4.8a2 2 0 0 1-2-2.4l1.6-8a2 2 0 0 1 2-1.6H17"})]});case"thumbsUpFilled":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M7 10v11"}),s.jsx("path",{d:"M7 10l4.5-8a2 2 0 0 1 3.6 1.5L14 8h5.2a2 2 0 0 1 2 2.4l-1.6 8a2 2 0 0 1-2 1.6H7z",fill:"currentColor",stroke:"none"})]});case"thumbsDownFilled":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M17 14V3"}),s.jsx("path",{d:"M17 14l-4.5 8a2 2 0 0 1-3.6-1.5L10 16H4.8a2 2 0 0 1-2-2.4l1.6-8a2 2 0 0 1 2-1.6H17z",fill:"currentColor",stroke:"none"})]});case"board":return s.jsxs(s.Fragment,{children:[s.jsx("rect",{x:"1.5",y:"2",width:"3.6",height:"12",rx:"1"}),s.jsx("rect",{x:"6.2",y:"2",width:"3.6",height:"8.5",rx:"1"}),s.jsx("rect",{x:"10.9",y:"2",width:"3.6",height:"5.5",rx:"1"})]});case"inbox":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M2 9.5 L4 3.5 h8 l2 6"}),s.jsx("path",{d:"M2 9.5 v3 h12 v-3"}),s.jsx("path",{d:"M2 9.5 h3.4 l1 1.6 h3.2 l1-1.6 H14"})]});case"server":return s.jsxs(s.Fragment,{children:[s.jsx("rect",{x:"2",y:"2.5",width:"12",height:"4.6",rx:"1.2"}),s.jsx("rect",{x:"2",y:"8.9",width:"12",height:"4.6",rx:"1.2"}),s.jsx("circle",{cx:"4.6",cy:"4.8",r:"0.8",fill:"currentColor",stroke:"none"}),s.jsx("circle",{cx:"4.6",cy:"11.2",r:"0.8",fill:"currentColor",stroke:"none"})]});case"agent":return s.jsxs(s.Fragment,{children:[s.jsx("rect",{x:"3",y:"4.5",width:"10",height:"8",rx:"2"}),s.jsx("path",{d:"M8 4.5V2.2"}),s.jsx("circle",{cx:"8",cy:"1.8",r:"0.9",fill:"currentColor",stroke:"none"}),s.jsx("circle",{cx:"5.8",cy:"8.4",r:"0.9",fill:"currentColor",stroke:"none"}),s.jsx("circle",{cx:"10.2",cy:"8.4",r:"0.9",fill:"currentColor",stroke:"none"})]});case"playCircle":return s.jsxs(s.Fragment,{children:[s.jsx("circle",{cx:"8",cy:"8",r:"6.2"}),s.jsx("path",{d:"M6.5 5.6 L11 8 L6.5 10.4 Z",fill:"currentColor",stroke:"none"})]});case"list":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M2.5 4h11"}),s.jsx("path",{d:"M2.5 8h11"}),s.jsx("path",{d:"M2.5 12h7"})]});case"gear":return s.jsxs(s.Fragment,{children:[s.jsx("circle",{cx:"8",cy:"8",r:"2.2"}),s.jsx("path",{d:"M8 1.6v2"}),s.jsx("path",{d:"M8 12.4v2"}),s.jsx("path",{d:"M1.6 8h2"}),s.jsx("path",{d:"M12.4 8h2"}),s.jsx("path",{d:"M3.5 3.5l1.4 1.4"}),s.jsx("path",{d:"M11.1 11.1l1.4 1.4"}),s.jsx("path",{d:"M12.5 3.5l-1.4 1.4"}),s.jsx("path",{d:"M4.9 11.1l-1.4 1.4"})]});case"sparkle":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M12 3l1.9 5.1L19 10l-5.1 1.9L12 17l-1.9-5.1L5 10l5.1-1.9z"}),s.jsx("path",{d:"M18.5 15.5l.8 2.2 2.2.8-2.2.8-.8 2.2-.8-2.2-2.2-.8 2.2-.8z"})]});case"contrast":return s.jsxs(s.Fragment,{children:[s.jsx("circle",{cx:"12",cy:"12",r:"9"}),s.jsx("path",{d:"M12 3a9 9 0 0 1 0 18z",fill:"currentColor",stroke:"none"})]});case"logout":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"}),s.jsx("path",{d:"M16 17l5-5-5-5"}),s.jsx("path",{d:"M21 12H9"})]});case"play":return s.jsx("path",{d:"M7 4.5v15a1 1 0 0 0 1.5.86l12-7.5a1 1 0 0 0 0-1.72l-12-7.5A1 1 0 0 0 7 4.5z",fill:"currentColor",stroke:"none"});case"stop":return s.jsx("rect",{x:"5",y:"5",width:"14",height:"14",rx:"2",fill:"currentColor",stroke:"none"});case"folder":return s.jsx("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"});case"file":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),s.jsx("path",{d:"M14 2v6h6"})]});case"archive":return s.jsxs(s.Fragment,{children:[s.jsx("rect",{x:"2",y:"3",width:"20",height:"5",rx:"1"}),s.jsx("path",{d:"M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8"}),s.jsx("path",{d:"M10 12h4"})]});case"clock":return s.jsxs(s.Fragment,{children:[s.jsx("circle",{cx:"12",cy:"12",r:"10"}),s.jsx("path",{d:"M12 6v6h4"})]});default:return null}}function et({name:e,size:t=16,className:n,title:r,...o}){const l=r?void 0:!0,u=Nk.has(e);return s.jsxs("svg",{width:t,height:t,viewBox:u?"0 0 16 16":"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:u?1.4:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,"aria-hidden":l,role:r?"img":"presentation",...o,children:[r?s.jsx("title",{children:r}):null,Ck(e)]})}const hp="api/gateway",Ef="api/connection/gateway";function wt(e){const t=String(e||"");if(t.startsWith("/"))throw new Error(`gatewayApiPath takes a route relative to the gateway API, got ${JSON.stringify(t)}.`);return t?`${hp}/${t}`:hp}function ag(e,t){const n=String(t||"");if(n.startsWith("/"))throw new Error(`joinBaseUrl takes a relative path, got ${JSON.stringify(n)}.`);let r=String(e??"");for(;r.endsWith("/");)r=r.slice(0,-1);return r?`${r}/${n}`:n}function Ek(e){const t=String(e||""),n=`/${hp}/`;if(!t.startsWith(n)||t.length===n.length)throw new Error(`Not a gateway API path: ${JSON.stringify(t)} (expected ${JSON.stringify(n)}…).`);const r=t.slice(n.length).split(/[?#]/,1)[0];if(/\\|%2f|%5c/i.test(r))throw new Error(`Not a gateway API path: ${JSON.stringify(t)} (encoded slash or backslash).`);for(const o of r.split("/")){const l=o.replace(/%2e/gi,".");if(l==="."||l==="..")throw new Error(`Not a gateway API path: ${JSON.stringify(t)} (a "." or ".." segment).`)}return t.slice(1)}function Ak(e){return!String(e.unavailableReason||"").trim()&&!e.busy}function $k(e){return Ak(e)?!e.checked:null}let Tk=0;function No(e){const{label:t,checked:n,onChange:r,description:o,reasonVisible:l=!0,describedBy:u,hint:c,busy:f=!1,variant:m="inline",ariaLabel:_,className:g,id:w,action:x}=e,j=String(e.unavailableReason||"").trim(),b=!!j,N=u||(w?`${w}-reason`:b?`af-switch-reason-${++Tk}`:void 0),C=["af-switch",m==="row"?"af-switch--row":m==="sm"?"af-switch--sm":"",b?"af-switch--unavailable":"",g||""].filter(Boolean).join(" "),E=I=>{const K=$k({checked:n,unavailableReason:j,busy:f});if(K===null){I.preventDefault();return}r==null||r(K)},T=s.jsxs("button",{type:"button",role:"switch",id:w,className:C,"data-action":x,"aria-checked":n?"true":"false","aria-disabled":b?"true":void 0,"aria-describedby":b?N:void 0,"aria-busy":f?"true":void 0,"aria-label":_,"aria-description":o?void 0:c,title:b?c?`${j}
41
- ${c}`:j:c,onClick:E,children:[s.jsx("span",{className:"af-switch__track","aria-hidden":"true",children:s.jsx("span",{className:"af-switch__thumb"})}),s.jsxs("span",{className:"af-switch__text",children:[s.jsx("span",{className:"af-switch__label",children:t}),o?s.jsx("span",{className:"af-switch__desc",children:o}):null]})]});return!b||u?T:s.jsxs("span",{className:m==="row"?"af-switch-wrap af-switch-wrap--row":"af-switch-wrap",children:[T,s.jsx("span",{id:N,className:l?"af-switch__reason":"af-switch__reason af-switch__reason--hidden",children:j})]})}function Mk(e){const t=String(e.unavailableReason||"").trim(),n=["af-switch","af-switch--native",e.variant==="row"?"af-switch--row":"",t?"af-switch--unavailable":""].filter(Boolean).join(" "),r=t?`${e.id||e.name}-reason`:void 0,o=s.jsxs("label",{className:n,title:t||void 0,"data-action":e.action,children:[s.jsx("input",{type:"checkbox",role:"switch",className:"af-switch__input",id:e.id,name:e.name,defaultChecked:e.defaultChecked,onChange:l=>{var u;return(u=e.onChange)==null?void 0:u.call(e,l.target.checked)},disabled:!!t,"aria-describedby":r}),s.jsx("span",{className:"af-switch__track","aria-hidden":"true",children:s.jsx("span",{className:"af-switch__thumb"})}),s.jsx("span",{className:"af-switch__text",children:s.jsx("span",{className:"af-switch__label",children:e.label})})]});return t?s.jsxs("span",{className:e.variant==="row"?"af-switch-wrap af-switch-wrap--row":"af-switch-wrap",children:[o,s.jsx("span",{id:r,className:"af-switch__reason",children:t})]}):o}async function mp(e=Ef){const t=await fetch(e),n=await t.json().catch(()=>null);if(!t.ok){const r=n&&typeof n=="object"&&n.detail?String(n.detail):`HTTP ${t.status}`;throw new Error(r)}return n}async function Rk(e,t=Ef){const n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),r=await n.json().catch(()=>null);if(!n.ok){const o=r&&typeof r=="object"&&r.detail?String(r.detail):`HTTP ${n.status}`;throw new Error(o)}return r}async function Av(e=Ef){const t=await fetch(e,{method:"DELETE"});if(!t.ok){const n=await t.json().catch(()=>({})),r=n&&typeof n=="object"&&n.detail?String(n.detail):`HTTP ${t.status}`;throw new Error(r)}}function v_(e){let t=String(e||"").trim();for(let n=0;n<2&&t;n+=1){try{const l=JSON.parse(t);if(typeof l=="string"&&l!==t){t=l.trim();continue}}catch{}const r=t[0],o=t[t.length-1];if(r==='"'&&o==='"'||r==="'"&&o==="'"){t=t.slice(1,-1).trim();continue}break}return t.replace(/\/+$/,"")}function $v(e){var l,u;if(!e)return{label:"Signed out",tone:"warn"};if(!e.has_session)return{label:"Signed out",tone:"warn"};const t=e.gateway||{},n=(l=t.principal)==null?void 0:l.user_id,r=(u=t.principal)==null?void 0:u.runtime_id;if(t.ok&&n)return{label:`Signed in as ${n}${r?` · runtime ${r}`:""}`,tone:"ok"};if(t.ok)return{label:"Signed in",tone:"ok"};const o=t.error||t.detail;return typeof o=="string"&&o.trim()?{label:"Session rejected — sign in again",tone:"err"}:{label:"Sign in required",tone:"err"}}function Lk(e){const t=e.connectionPath||Ef,[n,r]=p.useState(!1),[o,l]=p.useState(!1),[u,c]=p.useState(null),[f,m]=p.useState(!1);p.useEffect(()=>{e.isOpen||m(!1)},[e.isOpen]);const[_,g]=p.useState(e.defaultGatewayUrl||"http://127.0.0.1:8080"),[w,x]=p.useState("admin"),[j,b]=p.useState(""),[N,C]=p.useState(!1),[E,T]=p.useState(!0),[I,K]=p.useState(""),[U,J]=p.useState(""),Y=p.useMemo(()=>$v(u),[u]),re=O=>{var $;c(O),($=e.onStatusChange)==null||$.call(e,O)},ce=p.useRef(!1);if(p.useEffect(()=>{var $;if(!e.isOpen)return;const O=!ce.current;if(ce.current=!0,O&&e.initialStatus!==void 0&&e.initialStatus!==null){const z=e.initialStatus;re(z),typeof z.gateway_url=="string"&&z.gateway_url.trim()&&g(v_(z.gateway_url));const A=($=z.gateway)==null?void 0:$.principal;A!=null&&A.user_id&&x(A.user_id);return}r(!0),K(""),mp(t).then(z=>{var ee;re(z),typeof z.gateway_url=="string"&&z.gateway_url.trim()&&g(v_(z.gateway_url));const A=(ee=z.gateway)==null?void 0:ee.principal;A!=null&&A.user_id&&x(A.user_id)}).catch(z=>K(`Failed to load connection status: ${String((z==null?void 0:z.message)||z)}`)).finally(()=>r(!1))},[e.isOpen]),p.useEffect(()=>{if(!e.isOpen)return;const O=$=>{$.key==="Escape"&&!$.defaultPrevented&&!e.blocking&&($.preventDefault(),e.onClose())};return window.addEventListener("keydown",O),()=>window.removeEventListener("keydown",O)},[e.isOpen,e.blocking,e.onClose]),!e.isOpen||f)return null;const fe=async()=>{l(!0),K(""),J("");try{const O=v_(_);g(O);const $=await Rk({gateway_url:O,gateway_user_id:w,gateway_token:j,persist:E},t);re($),b(""),m(!0),e.onClose()}catch(O){K(String((O==null?void 0:O.message)||O))}finally{l(!1)}},W=async()=>{l(!0),K(""),J("");try{await Av(t),b("");const O=await mp(t).catch(()=>null);re(O),J("Signed out. This browser no longer holds a gateway session.")}catch(O){K(String((O==null?void 0:O.message)||O))}finally{l(!1)}};return s.jsx("div",{className:"af-connect-overlay",role:"presentation",onMouseDown:O=>{!e.blocking&&O.target===O.currentTarget&&e.onClose()},children:s.jsx("div",{className:"af-connect-modal",role:"dialog","aria-modal":"true","aria-label":"Gateway connection",children:s.jsx(xk,{kicker:`${e.appName||"AbstractFramework"} connection`,title:"Connect this browser to AbstractGateway",description:"Sign in with a Gateway user token. The app exchanges it for an HTTP-only browser session and never stores the raw token.",statusLabel:Y.label,statusTone:Y.tone,showGatewayUrl:!0,gatewayUrl:_,onGatewayUrlChange:O=>g(O),userId:w,onUserIdChange:x,token:j,tokenPlaceholder:u!=null&&u.has_session?"(browser session already signed in)":"Paste Gateway user token",showToken:N,onTokenChange:b,onShowTokenChange:C,remember:E,rememberLabel:"Keep this browser signed in",onRememberChange:T,loading:n,submitting:o,submittingLabel:"Signing in...",showClose:!e.blocking,onClose:e.onClose,showSignOut:!e.blocking&&!!(u!=null&&u.has_session),onSignOut:W,error:I,message:U,onSubmit:fe})})})}function Ik(e){return!!(e&&e.ok===!0&&e.has_session===!0)}function Ok(e){const t=e||{},n=t.connectionPath||Ef,r=t.variant||"dismissable",o=p.useRef(t.onStatusChange);o.current=t.onStatusChange;const l=p.useRef(r);l.current=r;const u=p.useRef(!!t.autoOpenMidSession);u.current=!!t.autoOpenMidSession;const[c,f]=p.useState(null),[m,_]=p.useState("loading"),[g,w]=p.useState(!1),x=p.useRef(!1),j=p.useRef(!1),b=p.useRef("loading"),N=p.useRef("none"),C=p.useRef(!1),E=p.useRef(0),T=p.useCallback($=>{var A;E.current+=1,f($),(A=o.current)==null||A.call(o,$);const z=Ik($);if(z)_("connected"),b.current="connected",x.current=!1,N.current="none",j.current||w(!1);else if($!==null){const ee=b.current;_("disconnected"),b.current="disconnected",ee!=="disconnected"&&(N.current=C.current?"signout":ee==="connected"?"mid":"boot");const P=l.current==="blocking"||N.current!=="mid"||u.current;!x.current&&P&&w(!0)}$!==null&&(j.current=z)},[]),I=p.useCallback(async()=>{const $=E.current;try{const z=await mp(n);if(E.current!==$)return;T(z)}catch{if(E.current!==$)return;T(null)}},[n,T]),[K,U]=p.useState(!1),[J,Y]=p.useState(null),re=p.useCallback(async()=>{U(!0),Y(null),E.current+=1;let $=null;try{await Av(n)}catch(z){$=String((z==null?void 0:z.message)||z||"Sign-out request failed")}C.current=!0;try{await I()}finally{C.current=!1}Y($),U(!1)},[n,I]),ce=p.useRef(!1);p.useEffect(()=>{ce.current||(ce.current=!0,I())},[I]);const fe=p.useCallback(()=>{w(!0)},[]),W=p.useCallback(()=>{const $=b.current;r==="blocking"&&$==="disconnected"||($==="disconnected"&&(x.current=!0),w(!1))},[r]),O=p.useMemo(()=>({isOpen:g,onClose:W,blocking:r==="blocking"&&m!=="connected",appName:t.appName,connectionPath:n,defaultGatewayUrl:t.defaultGatewayUrl,initialStatus:c,onStatusChange:T}),[g,W,r,m,t.appName,n,t.defaultGatewayUrl,c,T]);return{status:c,phase:m,connected:m==="connected",modalOpen:g,signingOut:K,signOutError:J,openModal:fe,refresh:I,signOut:re,modalProps:O}}function Pk(){return globalThis.crypto}function Dk(e){if(e.length<16)throw new Error("uuidV4FromBytes: needs 16 bytes");const t=Array.from(e.subarray(0,16));t[6]=t[6]&15|64,t[8]=t[8]&63|128;const n=t.map(r=>r.toString(16).padStart(2,"0")).join("");return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}function Nm(){const e=Pk();if(e&&typeof e.randomUUID=="function")try{return e.randomUUID()}catch{}if(e&&typeof e.getRandomValues=="function")return Dk(e.getRandomValues(new Uint8Array(16)));throw new Error("randomId: Web Crypto (crypto.getRandomValues) is unavailable")}function Fk(e){return globalThis.isSecureContext!==!1?null:`This page is loaded over http, so ${e} is unavailable — open it over https (for example through tailscale serve; the gateway console's Network page explains how) or on the gateway's own computer.`}function zk(){return Nm()}function Bk(){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 Uk(e){const t=e.commandsPath||wt("commands"),n=zk(),r=JSON.stringify({command_id:n,run_id:e.runId,type:"inject_guidance",payload:{guidance:e.guidance}}),o=e.csrfToken!==void 0?[e.csrfToken]:Bk();o.length===0&&o.push("");let l=null;for(const u of o){const c=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json",...u?{"x-abstract-csrf":u}:{}},body:r}),f=await c.json().catch(()=>null);if(!c.ok){const m=f&&typeof f=="object"&&f.detail?String(f.detail):`HTTP ${c.status}`;if(l=new Error(m),c.status===403&&f&&typeof f=="object"&&f.reason_code==="csrf_required")continue;throw l}return{accepted:!!(f!=null&&f.accepted),duplicate:!!(f!=null&&f.duplicate),seq:Number((f==null?void 0:f.seq)??0)}}throw l||new Error("Steer submit failed")}function Wk(e){const[t,n]=p.useState(""),[r,o]=p.useState({kind:"idle"}),l=p.useRef(!1),u=p.useRef(0);p.useEffect(()=>{u.current+=1,o({kind:"idle"})},[e.runId]);const c=!e.disabled&&t.trim().length>0&&r.kind!=="sending",f=p.useMemo(()=>e.parked?"Run is waiting — your guidance delivers at its next wake (steers do not wake runs).":"Delivers at the run's next loop boundary.",[e.parked]),m=async()=>{var x;const g=t.trim();if(!g||l.current||e.disabled)return;l.current=!0;const w=u.current;o({kind:"sending"});try{const j=e.submit?await e.submit(e.runId,g):await Uk({runId:e.runId,guidance:g,commandsPath:e.commandsPath});if(u.current!==w)return;if(!j.accepted&&!j.duplicate){o({kind:"error",detail:"The gateway did not accept this steer (accepted=false)."});return}o({kind:"queued",seq:j.seq,duplicate:j.duplicate}),n(""),(x=e.onSent)==null||x.call(e,{...j,guidance:g})}catch(j){u.current===w&&o({kind:"error",detail:String((j==null?void 0:j.message)||j)})}finally{l.current=!1}},_=g=>{g.key==="Enter"&&(g.metaKey||g.ctrlKey)&&(g.preventDefault(),m())};return s.jsxs("div",{className:`af-steer${e.className?` ${e.className}`:""}`,children:[s.jsxs("div",{className:"af-steer__row",children:[s.jsx("textarea",{className:"af-steer__input",value:t,rows:2,placeholder:e.placeholder||"Steer this run…","aria-label":e.ariaLabel||"Steer message",disabled:e.disabled||r.kind==="sending",onChange:g=>{n(g.target.value),(r.kind==="error"||r.kind==="queued")&&o({kind:"idle"})},onKeyDown:_}),s.jsx("button",{type:"button",className:"af-steer__send",disabled:!c,onClick:()=>void m(),title:"Send guidance (Cmd/Ctrl+Enter)",children:r.kind==="sending"?"Sending…":"Steer"})]}),s.jsx("div",{className:"af-steer__status",role:"status","aria-live":"polite",children:r.kind==="queued"?s.jsxs("span",{className:"af-steer__ok",children:[r.duplicate?`Already queued (seq ${r.seq}).`:`Queued (seq ${r.seq}).`," ",f," ","Watch for the steer_seen ack in the run ledger."]}):r.kind==="error"?s.jsx("span",{className:"af-steer__err",children:r.detail}):s.jsx("span",{className:"af-steer__hint",children:f})})]})}function qk(e){const t=e.closeOnEscape!==!1,n=p.useRef(null);return p.useEffect(()=>{if(!e.open||!t)return;const r=o=>{o.key!=="Escape"||o.defaultPrevented||(o.preventDefault(),e.onClose())};return window.addEventListener("keydown",r),()=>window.removeEventListener("keydown",r)},[e.open,t,e.onClose]),p.useEffect(()=>{const r=n.current;r&&(e.open?r.removeAttribute("inert"):r.setAttribute("inert",""))},[e.open]),s.jsxs(s.Fragment,{children:[e.backdrop&&e.open?s.jsx("div",{className:"af-drawer-backdrop","aria-hidden":"true",onClick:e.onClose,style:{top:e.topOffset||0}}):null,s.jsxs("div",{ref:n,className:`af-drawer${e.side==="left"?" af-drawer--left":""}${e.topOffset?" af-drawer--offset":""}${e.open?" af-drawer--open":""}${e.className?` ${e.className}`:""}`,style:{width:e.width||420,top:e.topOffset||0,display:e.open?void 0:"none"},role:"complementary","aria-label":e.label,"aria-hidden":e.open?void 0:!0,children:[e.title!==void 0?s.jsxs("div",{className:"af-drawer__header",children:[s.jsx("div",{className:"af-drawer__title",children:e.title}),s.jsxs("div",{className:"af-drawer__header-actions",children:[e.headerActions,s.jsx("button",{type:"button",className:"af-drawer__close","aria-label":"Close panel",onClick:e.onClose,children:"×"})]})]}):null,s.jsx("div",{className:"af-drawer__body",children:e.children})]})]})}const Hk={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"},Vk={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"}},Gk={framework:Hk,apps:Vk},im=Gk;function Kk(){return Object.keys(im.apps).sort()}function Yk(e,t){const n=Object.prototype.hasOwnProperty.call(im.apps,e)?im.apps[e]:void 0;if(!n)throw new Error(`appIdentity: unknown application id "${e}" (known: ${Kk().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 Jk(e,t){const n=im.framework,r=[["Application",`${e.name} ${e.version}`],["Part of",`${n.name} — ${n.website}`],["Author",`${n.author} (${n.years})`],["Copyright",n.copyright],["Website",e.website],["Source",e.repo],["Documentation",e.docs],["Report an issue",e.issues],["Give feedback",e.feedback],["Contact",n.contact_email]];for(const[o,l]of t||[])r.push([String(o),String(l)]);return r}function x_(e){return typeof e=="string"?e.trim():""}function py(e,t){if(t!=null)return[["Gateway",`unavailable (${String(t).trim()||"unknown error"})`]];const n=e&&typeof e=="object"&&!Array.isArray(e)?e:{},r=x_(n.abstractgateway);if(!r)return[["Gateway","unavailable (the gateway did not report its version)"]];const o=x_(n.abstractframework),l=[["Gateway",`AbstractGateway ${r}`],["Gateway framework",o?`AbstractFramework ${o}`:"not installed on the gateway host"]],u=n.packages&&typeof n.packages=="object"&&!Array.isArray(n.packages)?n.packages:{},c=Object.keys(u).filter(f=>f!=="abstractgateway"&&f!=="abstractframework").sort((f,m)=>f<m?-1:f>m?1:0);for(const f of c){const m=x_(u[f]);m&&l.push([`Gateway package ${f}`,m])}return l}const Xk='a[href], button:not(:disabled), input:not(:disabled), select:not(:disabled), textarea:not(:disabled), [tabindex]:not([tabindex="-1"])';function Zk(e,t,n){if(e.key!=="Tab"||!t)return;const r=Array.from(t.querySelectorAll(Xk));if(r.length===0){e.preventDefault();return}const o=r[0],l=r[r.length-1],u=!!n&&t.contains(n);e.shiftKey?(n===o||!u)&&(e.preventDefault(),l.focus()):(n===l||!u)&&(e.preventDefault(),o.focus())}const Qk=/https?:\/\/[^\s<>"]+/g;function ej(e,t){if(e==="Contact")return[{text:t,href:`mailto:${t}`}];const n=[];let r=0;for(const o of t.matchAll(Qk)){const l=o.index??0;l>r&&n.push({text:t.slice(r,l)}),n.push({text:o[0],href:o[0]}),r=l+o[0].length}return(r<t.length||n.length===0)&&n.push({text:t.slice(r)}),n}function tj({label:e,value:t}){return s.jsx("span",{children:ej(e,t).map((n,r)=>n.href===void 0?s.jsx(ve.Fragment,{children:n.text},r):n.href.startsWith("mailto:")?s.jsx("a",{className:"af-about__link",href:n.href,children:n.text},r):s.jsx("a",{className:"af-about__link",href:n.href,target:"_blank",rel:"noopener noreferrer",children:n.text},r))})}function nj(e){const t=p.useRef(null),n=p.useRef(null),r=p.useId(),o=p.useRef(e.onClose);if(o.current=e.onClose,p.useEffect(()=>{var m;if(!e.open)return;const c=document.activeElement;(m=t.current)==null||m.focus();const f=_=>{if(!_.defaultPrevented){if(_.key==="Escape"){_.preventDefault(),o.current();return}Zk(_,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=Jk(e.identity,e.extraRows);return s.jsx("div",{className:"af-appearance-overlay af-about-overlay",onClick:e.onClose,role:"presentation",children:s.jsxs("div",{ref:n,className:"af-appearance af-about",role:"dialog","aria-modal":"true","aria-labelledby":r,onClick:c=>c.stopPropagation(),children:[s.jsx("div",{className:"af-appearance__title",id:r,children:l}),s.jsx("dl",{className:"af-about__rows",children:u.map(([c,f],m)=>s.jsxs("div",{className:"af-about__row",children:[s.jsx("dt",{className:"af-about__label",children:c}),s.jsx("dd",{className:"af-about__value",children:s.jsx(tj,{label:c,value:f})})]},`${m}:${c}`))}),s.jsx("div",{className:"af-appearance__actions",children:s.jsx("button",{ref:t,type:"button",className:"af-appearance__close",onClick:e.onClose,children:"Close"})})]})})}function sj(e){const{connection:t}=e,n=t.phase,r=t.signingOut===!0,[o,l]=p.useState(!1),u=e.about,c=r?"Signing out…":n==="connected"?"Disconnect":n==="loading"?"Connecting…":"Connect",f=n==="connected"?"Disconnect from gateway":n==="loading"?"Checking gateway session…":"Connect to gateway";return s.jsxs("div",{className:`af-topbar${e.className?` ${e.className}`:""}`,role:"group","aria-label":"App actions",children:[e.assistant?s.jsx("button",{type:"button",className:`af-topbar__btn${e.assistant.open?" is-active":""}`,"aria-pressed":e.assistant.open,"aria-label":e.assistant.label||"Open assistant",title:e.assistant.label||"Assistant",onClick:e.assistant.onToggle,children:s.jsx(et,{name:"sparkle",size:16})}):null,e.appearance?s.jsx("button",{type:"button",className:"af-topbar__btn","aria-label":e.appearance.label||"Appearance (theme and typography)",title:e.appearance.label||"Appearance",onClick:e.appearance.onOpen,children:s.jsx(et,{name:"contrast",size:16})}):null,u?s.jsx("button",{type:"button",className:"af-topbar__btn af-topbar__btn--about","aria-label":u.label||`About ${u.identity.name}`,title:u.label||"About","aria-haspopup":"dialog",onClick:()=>{var m;l(!0),(m=u.onOpen)==null||m.call(u)},children:s.jsx(et,{name:"info",size:16})}):null,e.extraActions,s.jsxs("button",{type:"button",className:`af-topbar__pill af-topbar__pill--${n}`,onClick:n==="connected"?t.onDisconnect:t.onConnect,disabled:r,title:f,"aria-label":f,children:[s.jsx("span",{className:`af-topbar__dot af-topbar__dot--${n}`,"aria-hidden":"true"}),s.jsx("span",{className:"af-topbar__pill-label",children:c})]}),u?s.jsx(nj,{open:o,onClose:()=>l(!1),identity:u.identity,extraRows:u.extraRows}):null]})}const Jh={theme:"dark",font_scale:"md",header_density:"standard"};function rj(e){const t=e&&typeof e=="object"?e:{};return{theme:typeof t.theme=="string"&&t.theme?t.theme:Jh.theme,font_scale:typeof t.font_scale=="string"&&t.font_scale?t.font_scale:Jh.font_scale,header_density:typeof t.header_density=="string"&&t.header_density?t.header_density:Jh.header_density}}function ij(e){return`af_appearance_${e}_v1`}function oj(e,t){const n=ij(e),r=p.useMemo(()=>({...Jh,...(t==null?void 0:t.defaults)||{}}),[JSON.stringify((t==null?void 0:t.defaults)||{})]),[o,l]=p.useState(()=>{let u=r;try{const c=localStorage.getItem(n)??(t!=null&&t.legacyKey?localStorage.getItem(t.legacyKey):null);c&&(u=rj({...r,...JSON.parse(c)}))}catch{}try{fy(u.theme),hy({font_scale:u.font_scale,header_density:u.header_density})}catch{}return u});return p.useEffect(()=>{fy(o.theme),hy({font_scale:o.font_scale,header_density:o.header_density});try{localStorage.setItem(n,JSON.stringify(o))}catch{}},[n,o]),[o,l]}function aj(e){return p.useEffect(()=>{if(!e.open)return;const t=n=>{n.key!=="Escape"||n.defaultPrevented||(n.preventDefault(),e.onClose())};return window.addEventListener("keydown",t),()=>window.removeEventListener("keydown",t)},[e.open,e.onClose]),e.open?s.jsx("div",{className:"af-appearance-overlay",onClick:e.onClose,role:"presentation",children:s.jsxs("div",{className:"af-appearance",role:"dialog","aria-modal":"true","aria-label":e.title||"Appearance",onClick:t=>t.stopPropagation(),children:[s.jsx("div",{className:"af-appearance__title",children:e.title||"Appearance"}),s.jsx("div",{className:"af-appearance__note",children:e.note||"Stored locally in this browser, per app."}),s.jsxs("div",{className:"af-appearance__grid",children:[s.jsx("label",{className:"af-appearance__label",children:"Theme"}),s.jsx(kk,{value:e.value.theme,onChange:t=>e.onChange({...e.value,theme:t})}),s.jsx("label",{className:"af-appearance__label",children:"Font size"}),s.jsx(jk,{value:e.value.font_scale,onChange:t=>e.onChange({...e.value,font_scale:t})}),s.jsx("label",{className:"af-appearance__label",children:"Header size"}),s.jsx(Sk,{value:e.value.header_density,onChange:t=>e.onChange({...e.value,header_density:t})})]}),s.jsx("div",{className:"af-appearance__actions",children:s.jsx("button",{type:"button",className:"af-appearance__close",onClick:e.onClose,children:"Close"})})]})}):null}const lj={diary:"var(--accent)",question:"#e7b45a",dream:"#c084dd",interest:"#7bd88a",lesson:"#6ea8d8",world_model:"#5eead4"};function gy(e){const t=String(e||"");return t.length>14?`${t.slice(0,10)}…${t.slice(-4)}`:t}function b_(e){const[t,n]=p.useState(!1),[r,o]=p.useState(null),l=p.useRef(!1),u=typeof e.entryId=="string"&&e.entryId.trim()?e.entryId.trim():null,c=e.kind&&lj[e.kind]||"var(--text-muted)",f=p.useCallback(async()=>{if(!(!u||!e.onOpen||l.current)){l.current=!0,n(!0),o(null);try{await e.onOpen(u)}catch(m){o(String((m==null?void 0:m.message)||m||"could not open"))}finally{l.current=!1,n(!1)}}},[u,e.onOpen]);return!u||!e.onOpen?s.jsxs("span",{className:["af-memory-hint","af-memory-hint--text",e.className||""].filter(Boolean).join(" "),title:e.title,children:[s.jsx("span",{className:"af-memory-hint__dot",style:{background:c},"aria-hidden":"true"}),s.jsx("span",{className:"af-memory-hint__label",children:e.label}),u&&e.showId!==!1?s.jsx("code",{className:"af-memory-hint__id",children:gy(u)}):null]}):s.jsxs("span",{className:["af-memory-hint",e.className||""].filter(Boolean).join(" "),children:[s.jsxs("button",{type:"button",className:"af-memory-hint__btn",onClick:()=>void f(),disabled:t,title:e.title||(e.command?e.command:`open ${u}`),"aria-label":`Open ${e.kind||"memory"} entry: ${e.label}`,children:[s.jsx("span",{className:"af-memory-hint__dot",style:{background:c},"aria-hidden":"true"}),s.jsx("span",{className:"af-memory-hint__label",children:e.label}),e.showId!==!1?s.jsx("code",{className:"af-memory-hint__id",children:gy(u)}):null,s.jsx("span",{className:"af-memory-hint__act","aria-hidden":"true",children:t?"…":"↗"})]}),e.command?s.jsx("code",{className:"af-memory-hint__cmd",children:e.command}):null,r?s.jsx("span",{className:"af-memory-hint__err",role:"alert",children:r}):null]})}const k_=wt("automations"),cj=wt("trigger-sources"),uj=wt("me/email");class yy 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 dj(e,t){const n=t&&typeof t=="object"?t.detail:void 0;if(n&&typeof n=="object"&&!Array.isArray(n)){const r=n;if(typeof r.reason_code=="string"&&r.reason_code&&typeof r.message=="string"){const o={status:e,code:r.reason_code,message:r.message};return typeof r.field=="string"&&(o.field=r.field),typeof r.command_id=="string"&&(o.command_id=r.command_id),o}}return{status:e,code:"invalid_response",message:`The gateway answered HTTP ${e} without an automation error envelope.`}}function j_(e){const t=new URLSearchParams;for(const[r,o]of Object.entries(e))o!==void 0&&t.set(r,String(o));const n=t.toString();return n?`?${n}`:""}function fj(){return Nm()}function hj(e){const t=e.newId??fj,n=o=>`${k_}/${encodeURIComponent(o)}`;async function r(o,l,u){const c={accept:"application/json",...e.headers?e.headers():{}},f={method:o,headers:c};u!==void 0&&(c["content-type"]="application/json",f.body=JSON.stringify(u));const m=await e.fetch(ag(e.baseUrl,l),f),_=await m.text();let g,w=!1;if(_)try{g=JSON.parse(_),w=!0}catch{w=!1}if(!m.ok)throw new yy(dj(m.status,g));if(!w||g===null||typeof g!="object")throw new yy({status:m.status,code:"invalid_response",message:`The gateway answered ${o} ${l} with a body that is not a JSON object.`});return g}return{listAutomations:(o={})=>r("GET",`${k_}${j_({status:o.status,cursor:o.cursor,limit:o.limit})}`),getAutomation:o=>r("GET",n(o)),createAutomation:o=>r("POST",k_,o),reviseAutomation:(o,l)=>r("PATCH",n(o),{command_id:l.command_id??t(),...l.expected_revision!==void 0?{expected_revision:l.expected_revision}:{},changes:l.changes}),sendAutomationCommand:(o,l)=>r("POST",`${n(o)}/commands`,{command_id:l.command_id??t(),type:l.type,...l.payload!==void 0?{payload:l.payload}:{}}),listOccurrences:(o,l={})=>r("GET",`${n(o)}/occurrences${j_({cursor:l.cursor,limit:l.limit})}`),discuss:(o,l)=>r("POST",`${n(o)}/discuss`,{request_id:l.request_id??t(),occurrence_index:l.occurrence_index,prompt:l.prompt}),markSeen:(o,l)=>r("POST",`${n(o)}/seen`,{attention_cursor:l}),listAttention:(o,l={})=>r("GET",`${n(o)}/attention${j_({cursor:l.cursor,limit:l.limit})}`),listTriggerSources:()=>r("GET",cj),getMyEmail:()=>r("GET",uj)}}function Tv(e){const t=e==null?void 0:e._runtime,n=Array.isArray(t==null?void 0:t.allowed_tools)?t.allowed_tools:null,r=Array.isArray(e==null?void 0:e.tools)?e.tools:n;return Array.isArray(r)?r.filter(o=>typeof o=="string"&&(!n||n.includes(o))):null}function Mv(e,t){const n={...e},r=e._runtime&&typeof e._runtime=="object"?{...e._runtime}:{};return t===null?(delete n.tools,delete r.allowed_tools):(n.tools=[...t],r.allowed_tools=[...t]),Object.keys(r).length?n._runtime=r:delete n._runtime,n}function mj(e){const t=["prompt","tools","provider","model","temperature","seed","max_iterations","max_in_tokens","system","_limits"],n={};for(const o of t)o in e&&(n[o]=e[o]);const r=e._runtime;if(r&&typeof r=="object"){const o={};for(const l of["allowed_tools","provider","model","thinking","speculation","stream"])l in r&&(o[l]=r[l]);Object.keys(o).length&&(n._runtime=o)}return n}function _p(e){return e.flow_id==="@default"?"@default":`${"bundle_ref"in e?e.bundle_ref:""}:${e.flow_id}`}const _j={active:"Active",pause:"Pause",resume:"Resume",run_now:"Run now",stop_current:"Stop current",revise:"Edit",archive:"Archive",discuss:"Discuss"},pj={active:`On: it runs on its schedule. Off: paused, scheduled runs are skipped.
42
- Pausing lets a run in progress finish, without further retries; Run now still works and keeps it paused.
43
- Making it active again restarts the schedule at its next time after now; times missed while paused are skipped.`,pause:`Stop scheduled runs until you resume.
44
- A run in progress finishes; a pending retry is cancelled. Run now still works.`,resume:`Restart the schedule at its next time after now.
45
- Times missed while paused are skipped; resuming does not run it now.`,run_now:`Run it once now, without waiting for the schedule.
46
- The schedule does not move: the next scheduled run keeps its time, or starts right after this run if its time comes first.
47
- Does not count toward a run limit. Works while paused; it stays paused.
48
- Not available while a run is in progress.`,stop_current:`Cancel the run in progress, or its pending retry.
49
- It ends as cancelled, with no failure notice. The schedule continues.`,revise:`Change the task, schedule or settings.
50
- Changes apply from the next run; a run in progress keeps its inputs. A changed schedule restarts from now, so no past time runs.`,archive:`Stop it for good: it will not run again.
51
- A run in progress finishes; the history stays readable.`,discuss:`Talk about the results in a separate conversation, seeded with the runs up to this one.
52
- It has its own workspace (the automation's files are read-only) and never changes the automation.`},gj="Next scheduled run: {time}.",yj="Growing context: later runs see this run in their history.",wj={run_now:{name:"playCircle"}},vj={trigger_label:"When an email arrives",not_set_up:"Connect a mailbox first — open My email",open_my_email:"open My email",filters_legend:"Only mail that matches (all optional)",from_in:"From these addresses",from_domain_in:"From these domains",to_in:"Sent to these addresses",subject_contains:"Subject contains",has_attachment:"Attachments",has_attachment_any:"any",has_attachment_yes:"only with attachments",has_attachment_no:"only without attachments",list_hint:"Separate entries with commas or new lines. Exact addresses and domains only (no patterns).",every_label:"Check for new mail every",interval_rule:"An automation that runs a model on new mail checks once an hour by default; one that needs no model checks every 60 s. The shortest interval is 60 s.",max_batch_label:"At most this many emails per run",max_batch_hint:"The rest wait for the next run. Each email is read once by this automation; mail that arrived before it was created, or while it is paused, is not processed.",untrusted_hint:"Incoming mail is data, never instructions: the automation acts only on its task. Link-opening tools (fetch_url, browser_probe) always ask for your approval.",notify_label:"Email result",notify_hint:"Email each completed run’s result to the selected recipients.",recipients_legend:"Recipients",recipients_self:"Only me (default)",recipients_list:"Me and these addresses",recipients_hint:"Separate multiple addresses with commas."},Rv={labels:_j,hints:pj,run_now_next_run_line:gj,run_now_growing_line:yj,icons:wj,email:vj},xj=/^([1-9][0-9]*)([smhd])$/,bj={s:["second","seconds"],m:["minute","minutes"],h:["hour","hours"],d:["day","days"]};function Af(e){if(typeof e!="string")return null;const t=xj.exec(e);return t?{amount:Number(t[1]),unit:t[2]}:null}function Lv(e){const t=Af(e);if(!t)return`every ${e}`;const[n,r]=bj[t.unit];return t.amount===1?`every ${n}`:`every ${t.amount} ${r}`}function la(e){if(!e)return"";const t=Date.parse(e);if(Number.isNaN(t))return e;const n=new Date(t).toISOString(),r=n.slice(17,19);return`${n.slice(0,10)} ${n.slice(11,16)}${r==="00"?"":`:${r}`} UTC`}function Iv(e){const t=e;if(typeof t.every!="string")return t.start_at?`once at ${la(t.start_at)}`:"once, now";const n=[`${Lv(t.every)} (UTC)`];return typeof t.count=="number"&&n.push(`${t.count} ${t.count===1?"run":"runs"} max`),typeof t.until=="string"&&n.push(`until ${la(t.until)}`),n.join(" · ")}function lg(e){return e.source_id==="schedule"&&e.source_version===1?Iv(e.config):e.source_id==="manual"&&e.source_version===1?"manual runs only":Cm(e)?Wv(e.config):`${e.source_id}@${e.source_version}`}function Ov(e){return e==="growing"?"Growing — each run sees the previous runs":"Independent — each run starts fresh"}const kj={active:"Active",paused:"Paused",completed:"Completed",failed:"Failed",archived:"Archived"},Ut=Rv.email,Pv="email.received",Dv=1,jj="1h",Sj="60s",Fv=60,cg=100,pp=1e3,wy=200,vy=200,xy=50;function Cm(e){return!!e&&e.source_id===Pv&&e.source_version===Dv}function Em(e){return!!e&&e.effective_enabled===!0}function zv(e){const t=[];for(const n of String(e??"").split(/[\s,;]+/)){const r=n.trim().toLowerCase();r&&!t.includes(r)&&t.push(r)}return t}const Nj=/[\s<>,;:"()[\]]/;function gp(e){const t=e.trim().toLowerCase(),n=t.indexOf("@");return n<=0||n===t.length-1?!1:!t.slice(n+1).includes("@")&&!Nj.test(t)}function Cj(e){const t=e.trim().toLowerCase();return!!t&&!t.includes("@")&&t.includes(".")&&!t.startsWith(".")&&!t.endsWith(".")&&!/[\s<>,;:"()[\]/*]/.test(t)}const Bv={usesModel:!0,every:null,maxBatch:null,fromIn:"",fromDomainIn:"",toIn:"",subjectContains:"",hasAttachment:"any"};function ug(e){return e?jj:Sj}function Uv(e){const t=Af(e);return t?t.amount*{s:1,m:60,h:3600,d:86400}[t.unit]:null}function S_(e,t,n,r,o){const l=zv(e);if(!l.length)return null;const u=l.filter(c=>!n(c));return u.length&&o.push(`${t}: ${u.join(", ")} ${u.length===1?"is not":"are not"} ${r}.`),l.length>wy&&o.push(`${t}: at most ${wy} entries.`),l}function Ej(e){const t=[],n={uses_model:e.usesModel};e.every===null?n.every=ug(e.usesModel):!Number.isInteger(e.every.amount)||e.every.amount<1?t.push("The check interval must be a whole number of at least 1."):n.every=`${e.every.amount}${e.every.unit}`,n.every!==void 0&&(Uv(n.every)??0)<Fv&&t.push("The check interval is at least 60 seconds."),e.maxBatch===null?n.max_batch=cg:!Number.isInteger(e.maxBatch)||e.maxBatch<1||e.maxBatch>pp?t.push(`At most this many emails per run: a whole number from 1 to ${pp}.`):n.max_batch=e.maxBatch;const r={},o=S_(e.fromIn,Ut.from_in,gp,"an email address",t);o&&(r.from_in=o);const l=S_(e.fromDomainIn,Ut.from_domain_in,Cj,"a domain like example.com",t);l&&(r.from_domain_in=l);const u=S_(e.toIn,Ut.to_in,gp,"an email address",t);u&&(r.to_in=u);const c=e.subjectContains.trim();return c&&(c.length>vy||/[\r\n]/.test(c)?t.push(`${Ut.subject_contains}: one line of at most ${vy} characters.`):r.subject_contains=c),e.hasAttachment==="yes"?r.has_attachment=!0:e.hasAttachment==="no"&&(r.has_attachment=!1),Object.keys(r).length&&(n.filter=r),{config:n,errors:t}}function Wv(e){const t=e,n=t.filter??{},r=["when an email arrives"],o=[...n.from_in??[],...n.from_domain_in??[]];o.length&&r.push(`from ${o.join(", ")}`),n.to_in&&n.to_in.length&&r.push(`to ${n.to_in.join(", ")}`),typeof n.subject_contains=="string"&&n.subject_contains&&r.push(`subject contains “${n.subject_contains}”`),n.has_attachment===!0&&r.push("with attachments"),n.has_attachment===!1&&r.push("without attachments");const l=typeof t.every=="string"?t.every:ug(t.uses_model!==!1);r.push(`checked ${Lv(l)}`);const u=typeof t.max_batch=="number"?t.max_batch:cg;return r.push(`up to ${u} per run`),r.join(" · ")}const lf={mode:"self",addresses:""};function yp(e){if(e.mode==="self")return{recipients:["self"],errors:[]};const t=[],n=zv(e.addresses).filter(o=>o!=="self");n.length||t.push("Name at least one address the automation may email, or choose Only me.");const r=n.filter(o=>!gp(o));return r.length&&t.push(`${Ut.recipients_list}: ${r.join(", ")} ${r.length===1?"is not an email address":"are not email addresses"}.`),n.length+1>xy&&t.push(`At most ${xy-1} addresses.`),{recipients:["self",...n],errors:t}}function Aj(e){const t=(e??[]).filter(n=>n!=="self");return t.length?{mode:"list",addresses:t.join(", ")}:{mode:"self",addresses:""}}function $j(e){const t=(e??["self"]).filter(n=>n!=="self");return t.length?`Me and ${t.join(", ")}`:"Only me"}function qv(e,t=["self"]){return{channels:e?["console","email"]:["console"],...t.some(n=>n!=="self")?{recipients:t}:{}}}function Hv(e){return!!e&&Array.isArray(e.channels)&&e.channels.includes("email")}function Tj(e){return Hv(e)?"In the console and by email":"In the console"}const ko={pause:"automation.pause",resume:"automation.resume",run_now:"automation.run_now",stop_current:"automation.stop_current",archive:"automation.archive"},Mj=new Set(["running","waiting","backoff"]);function Rj(e,t=[]){return e.current_occurrence!=null}function Vv(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 Gv(e,t){const n=Date.parse(e);if(Number.isNaN(n))return"";const r=Math.round((n-t)/6e4);if(r<=0)return"due now";if(r<60)return`in ${r} min`;const o=Math.floor(r/60);return o<24?`in ${o} h${r%60?` ${r%60} min`:""}`:`in ${Math.floor(o/24)} d${o%24?` ${o%24} h`:""}`}function om(e,t=[],n=!1){const r=new Set(e.capabilities),o=e.status,l=Rj(e,t),u=(_,g,w)=>n?{enabled:!1,reason:"Working…"}:e.legacy?{enabled:!1,reason:"Legacy schedule: managed with its existing controls."}:r.has(_)?o==="archived"?{enabled:!1,reason:"Archived: history is kept, nothing runs."}:g?{enabled:!0}:{enabled:!1,reason:w}:{enabled:!1,reason:"Not permitted for this automation."},c=o==="active"||o==="paused",f=o==="active"?"pause":"resume";return{active:n?{enabled:!1,reason:"Working…"}:e.legacy?{enabled:!1,reason:"Legacy schedule: managed with its existing controls."}:o==="archived"?{enabled:!1,reason:"Archived: history is kept, nothing runs."}:c?r.has(f)?{enabled:!0}:{enabled:!1,reason:"Not permitted for this automation."}:{enabled:!1,reason:"The automation has ended."},pause:u("pause",o==="active",o==="paused"?"Already paused.":"The automation has ended."),resume:u("resume",o==="paused",o==="active"?"Already running on schedule.":"The automation has ended."),run_now:u("run_now",c&&!l,l?"An occurrence is in progress.":"The automation has ended."),stop_current:u("stop_current",l,"Nothing is running."),revise:u("revise",!0,""),archive:u("archive",!0,""),discuss:n?{enabled:!1,reason:"Working…"}:e.legacy?{enabled:!1,reason:"Legacy schedule: discussion is not available."}:r.has("discuss")?{enabled:!0}:{enabled:!1,reason:"Discussion is not permitted for this automation."}}}function Lj(e){return e.status==="active"?ko.pause:ko.resume}function Ij(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 Oj(e){return[...e].sort((t,n)=>t.index-n.index).map(t=>{const n=Ij(t),r=`${t.attempts} ${t.attempts===1?"attempt":"attempts"}`,o=n==="failed"?`Failed after ${r}`:n==="waiting"?"Waiting for you":n==="notified"?"Notified":n==="running"?"Running":null,l=t.status==="completed"&&t.attempts>1?`completed after ${r}`:t.status;return{row:t,tone:n,notable:n==="failed"||n==="waiting"||n==="notified",badge:o,statusText:l,canDiscuss:!Mj.has(t.status)}})}function Pj(e){const t=e.attention.items;return t.length?t[t.length-1].cursor:null}function Kv(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 Dj={unauthorized:"Sign in to the gateway to manage automations.",forbidden:"You are not allowed to do this with automations.",automation_not_found:"This automation does not exist (or is not yours).",occurrence_not_found:"That occurrence does not exist.",revision_conflict:"The automation changed since this view loaded. Reload it, then try again.",automation_busy:"An occurrence is already running or queued. Wait for it to finish.",invalid_state:"The automation's current state does not allow this.",identity_conflict:"This request id was already used for a different request.",invalid_request:"The gateway rejected the request as malformed.",invalid_definition:"The automation definition is not valid.",unsupported_feature:"The gateway does not support this yet.",unknown_trigger_source:"The gateway does not know this trigger source.",invalid_response:"The gateway gave an unexpected answer.",invalid_payload:"That answer could not be sent."};function am(e){return{title:Dj[e.code]??`The gateway refused the request (${e.code}).`,detail:e.message}}function dg(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 Yv(e,t){var l,u,c;const n=e.trigger,r=n.source_id==="schedule"||Cm(n)?n.config.every:void 0,o=t?t.target.input_data.prompt:void 0;return{title:e.title,every:typeof r=="string"?r:null,context:e.context_mode,growingMaxTokens:Number(((u=(l=t==null?void 0:t.context)==null?void 0:l.growing)==null?void 0:u.max_tokens)??e.growing_max_tokens??df),prompt:typeof o=="string"?o:null,toolApproval:t?t.policy.tool_approval:null,tools:Tv(t==null?void 0:t.target.input_data),notifyEmail:t?Hv(t.notify):null,emailRecipients:t?Aj((c=t.notify)==null?void 0:c.recipients):null}}function Fj(e,t,n){var f;const r=[],o={},l=t.title.trim();l?l.length>120?r.push("Title is at most 120 characters."):l!==e.title&&(o.title=l):r.push("Title is required.");const u=Yv(e,n);if(t.every!==u.every&&t.every!==null){const m=Cm(e.trigger);if(!Af(t.every))r.push("Interval must be a whole number of minutes, hours or days.");else if(m&&(Uv(t.every)??0)<Fv)r.push("The check interval is at least 60 seconds.");else{const _={...e.trigger.config,every:t.every};m&&delete _.start_at,o.trigger={source_id:e.trigger.source_id,source_version:e.trigger.source_version,config:_}}}const c=t.context==="growing"?t.growingMaxTokens??u.growingMaxTokens:u.growingMaxTokens;if(Xv(c)||r.push(Jv),(t.context!==e.context_mode||c!==u.growingMaxTokens)&&(o.context=Zv(t.context,c)),n&&typeof u.prompt=="string"&&typeof t.prompt=="string"&&t.prompt.trim()!==u.prompt.trim()){const m=t.prompt.trim();m?o.target={bundle_ref:n.target.bundle_ref,flow_id:n.target.flow_id,input_data:{...n.target.input_data,prompt:m}}:r.push("Task is required.")}if(n&&t.tools!==void 0&&JSON.stringify(t.tools)!==JSON.stringify(u.tools)){const m=o.target||{bundle_ref:n.target.bundle_ref,flow_id:n.target.flow_id,input_data:n.target.input_data};o.target={...m,input_data:Mv(m.input_data||{},t.tools)}}if(n&&t.toolApproval&&t.toolApproval!==u.toolApproval&&(o.policy={tool_approval:t.toolApproval}),n&&typeof t.notifyEmail=="boolean"){const m=yp(t.notifyEmail?t.emailRecipients??lf:u.emailRecipients??lf),_=yp(u.emailRecipients??lf).recipients;m.errors.length?r.push(...m.errors):(t.notifyEmail!==u.notifyEmail||JSON.stringify(m.recipients)!==JSON.stringify(_))&&(o.notify=qv(t.notifyEmail,m.recipients))}if(r.length)return{errors:r};if(n&&t.target&&_p(t.target)!==_p(n.target)){const m=((f=o.target)==null?void 0:f.input_data)||n.target.input_data;o.target={...t.target,input_data:mj(m)}}return Object.keys(o).length?o:null}const df=5e4,zj="Limits history carried into the next run, keeping recent whole turns. The newest turn is kept even if oversized. New messages and tool results can grow context beyond this budget.",Jv="Max growing context must be a positive whole number of tokens.";function Xv(e){return Number.isSafeInteger(e)&&e>0}function Zv(e,t){return{mode:e,...t!==df?{growing:{max_tokens:t}}:{}}}const Bj=[{label:"every 5 minutes",when:{kind:"every",amount:5,unit:"m"}},{label:"every 30 minutes",when:{kind:"every",amount:30,unit:"m"}},{label:"every hour",when:{kind:"every",amount:1,unit:"h"}},{label:"every 8 hours",when:{kind:"every",amount:8,unit:"h"}},{label:"every 24 hours",when:{kind:"every",amount:24,unit:"h"}},{label:"every 7 days",when:{kind:"every",amount:7,unit:"d"}}];function N_(e){if(!e)return null;const t=/^(\d{4}-\d{2}-\d{2})T(\d{2}:\d{2})(:\d{2})?$/.exec(e.trim());if(!t)return null;const n=`${t[1]}T${t[2]}${t[3]??":00"}Z`;return Number.isNaN(Date.parse(n))?null:n}function Uj(e){const t=e.trim().split(`
53
- `)[0].trim();return t.length>120?`${t.slice(0,119)}…`:t}function Wj(e){const t=[],n={};if(e.when.kind==="once"){const o=N_(e.when.at);return o?n.start_at=o:t.push("Pick the date and time (UTC) to run once."),{config:n,errors:t}}const r=e.when.amount;if(!Number.isInteger(r)||r<1?t.push("The interval must be a whole number of at least 1."):n.every=`${r}${e.when.unit}`,e.startAt){const o=N_(e.startAt);o?n.start_at=o:t.push("First run must be a date and time (UTC).")}if(e.count!==void 0&&(!Number.isInteger(e.count)||e.count<1?t.push("Maximum runs must be a whole number of at least 1."):n.count=e.count),e.until){const o=N_(e.until);o?n.until=o:t.push("Stop at must be a date and time (UTC).")}return{config:n,errors:t}}function wp(e,t){const n=[];t.target||n.push("Choose what to run.");const r=e.prompt.trim();r||n.push("Write the task to run.");const o=(e.title??"").trim()||Uj(r);o.length>120&&n.push("Title is at most 120 characters.");const l=e.trigger==="email",u=l?Ej(e.email??Bv):Wj(e);n.push(...u.errors);const c=e.notifyEmail&&e.emailRecipients&&e.emailRecipients.mode==="list"?yp(e.emailRecipients):null;c&&n.push(...c.errors);const f=e.growingMaxTokens??df;if(e.context==="growing"&&!Xv(f)&&n.push(Jv),n.length||!t.target)return{ok:!1,errors:n};const m={...t.target,input_data:{...t.target.input_data??{},prompt:r}},_={request_id:t.requestId,title:o,target:m,trigger:l?{source_id:Pv,source_version:Dv,config:u.config}:{source_id:"schedule",source_version:1,config:u.config},context:Zv(e.context,e.context==="growing"?f:df),policy:{tool_approval:e.toolApproval??"auto"}};return e.notifyEmail===!0&&(_.notify=qv(!0,c==null?void 0:c.recipients)),{ok:!0,body:_}}const qj="Tools run without asking (you approve them now by creating this automation)";function Hj(e){if(e.kind!=="tool_approval"||!Array.isArray(e.details))return null;const t=[];for(const n of e.details){if(!n||typeof n!="object"||Array.isArray(n))return null;const r=n;if(typeof r.name!="string"||!r.arguments||typeof r.arguments!="object"||Array.isArray(r.arguments)||r.call_id!==void 0&&typeof r.call_id!="string")return null;t.push({name:r.name,arguments:r.arguments,...typeof r.call_id=="string"?{call_id:r.call_id}:{}})}return t}function Vj(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 Qv={ask_user:"Question for you",tool_approval:"Approval needed",event:"Waiting for an event"};class Gj{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||Kj(n.error))&&this.open.delete(t)}}function Kj(e){return dg(e)&&e.status>0&&e.code!=="invalid_response"}function Yj(){return Nm()}class Jj{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 by(e,t){if(!e)return null;for(const n of t){const r=e.querySelector(n);if(r&&r.disabled!==!0&&typeof r.focus=="function")return r}return null}function ky(e){const t=Array.from(new Set(e.map(n=>String(n||"").trim()).filter(Boolean)));return t.sort((n,r)=>n.localeCompare(r)),t}function vp(e){const t=e.disabled===!0,n=p.useMemo(()=>ky([...e.options||[],...e.value||[]]),[e.options,e.value]),r=p.useMemo(()=>ky(e.value||[]),[e.value]),[o,l]=p.useState(!1),[u,c]=p.useState(""),f=p.useMemo(()=>{const g=u.trim().toLowerCase();return g?n.filter(w=>w.toLowerCase().includes(g)):n},[n,u]),m=p.useMemo(()=>new Set(r),[r]),_=typeof e.max_list_height_px=="number"?e.max_list_height_px:220;return s.jsxs("div",{className:"af_multi_select",children:[s.jsxs("div",{className:"af_multi_select_row",children:[s.jsxs("button",{className:"btn",type:"button",onClick:()=>l(g=>!g),disabled:t||!n.length,"aria-expanded":o,children:[o?"Hide":"Select"," • ",r.length>0?`${r.length} of ${n.length}`:e.placeholder||"(none)"]}),s.jsx("button",{className:"btn",type:"button",onClick:()=>e.onChange(n.slice()),disabled:t||!n.length||r.length===n.length,title:"Select all",children:"All"}),s.jsx("button",{className:"btn",type:"button",onClick:()=>e.onChange([]),disabled:t||r.length===0,title:"Clear selection",children:"Clear"})]}),r.length>0?s.jsx("div",{className:"af_multi_select_chips",children:r.map(g=>s.jsxs("button",{type:"button",disabled:t,"aria-label":`Remove ${g}`,className:"af_multi_select_chip",title:g,onClick:()=>{if(t)return;const w=new Set(m);w.delete(g),e.onChange(Array.from(w.values()))},children:[g,t?null:s.jsx("span",{className:"af_multi_select_chip_x",children:"×"})]},g))}):null,o?s.jsxs("div",{className:"af_multi_select_panel",children:[s.jsx("input",{className:"mono",value:u,onChange:g=>c(String(g.target.value||"")),placeholder:"filter…","aria-label":"Filter options",disabled:t}),s.jsxs("div",{className:"af_multi_select_list",style:{maxHeight:`${_}px`},children:[f.map(g=>{const w=m.has(g);return s.jsxs("label",{className:`af_multi_select_item mono ${w?"checked":""}`,children:[s.jsx("input",{type:"checkbox",checked:w,disabled:t,onChange:x=>{const j=new Set(m);x.target.checked?j.add(g):j.delete(g),e.onChange(Array.from(j.values()))}}),s.jsx("span",{children:g})]},g)}),f.length?null:s.jsx("div",{className:"mono muted",children:"(no matches)"})]})]}):null]})}function ex(e){return s.jsxs("div",{className:"af-auto__field","data-field":"tool-selection",children:[s.jsxs("label",{children:[s.jsx("input",{type:"checkbox",checked:e.value===null,disabled:e.disabled,onChange:t=>e.onChange(t.target.checked?null:[])})," Use workflow default tools"]}),e.value!==null?s.jsx(vp,{options:e.availableTools,value:e.value,disabled:e.disabled,placeholder:"No tools enabled",onChange:e.onChange}):null,s.jsx("p",{className:"af-auto__hint",children:"Choose which tools this automation can use. An empty selection disables tools. Gateway restrictions always apply."})]})}const tx="@default",nx="No workflows available for this app — ask your admin.",sx={shared:"Shared",mine:"Mine"};class Za extends Error{constructor(t){super(t),this.name="WorkflowPickerContractError"}}function Xj(e,t={}){const n=String(e||"").trim();if(!n)throw new Error("executableWorkflowsPath needs the interface the app runs (e.g. abstractcode.agent.v1).");return`bundles?executable_for=${encodeURIComponent(n)}${t.allVersions?"&all_versions=true":""}`}function Zj(e={}){return e.allVersions?"bundles?all_versions=true":"bundles"}function Qj(e,t={}){return e===null?Zj(t):Xj(e,t)}function ia(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function Ls(e){return typeof e=="string"?e.trim():""}const Ch="update the gateway";function eS(e,t){var c,f;const n=ia(e.default_agent_workflows);if(!n)return{status:"unavailable",reason:"the gateway does not report a default workflow"};const r=ia(n[t]);if(!r)return{status:"unavailable",reason:Ls((f=ia((c=ia(e.default_agent_workflows_unavailable))==null?void 0:c[t]))==null?void 0:f.reason)||`no default workflow for ${t}`};const o=Ls(r.bundle_id),l=Ls(r.flow_id);if(!o||!l)return{status:"unavailable",reason:"the gateway's default workflow is missing its bundle or flow"};const u=Ls(r.bundle_version);return{status:"ok",name:Ls(r.name)||l,bundleId:o,bundleVersion:u,flowId:l,workflowId:Ls(r.workflow_id)||`${o}${u?`@${u}`:""}:${l}`}}function tS(e,t,n={}){var c;const r=ia(e);if(!r)throw new Za("The gateway's workflow list is not a JSON object.");const o=Ls(r.executable_for);if(t===null){if(o)throw new Za(`Asked for every workflow, the gateway listed only ${o}.`)}else if(o!==t)throw new Za(o?`The gateway listed workflows for ${o}, not ${t}.`:`This gateway does not filter workflows per app (no executable_for in its answer): ${Ch}.`);if(!Array.isArray(r.items))throw new Za("The gateway's workflow list has no items.");const l=[];for(const f of r.items){const m=ia(f),_=Ls(m==null?void 0:m.bundle_id);if(!m||!_)throw new Za("The gateway listed a workflow without a bundle id.");const g=ia(m.owner),w=Ls(g==null?void 0:g.kind);if(w!=="gateway"&&w!=="user")throw new Za(`The gateway did not say who owns ${_} (owner missing): ${Ch}.`);if(typeof m.shipped!="boolean")throw new Za(`The gateway did not say whether ${_} ships with it (shipped missing): ${Ch}.`);const x=Ls(m.bundle_version),j=Array.isArray(m.entrypoints)?m.entrypoints:[];for(const b of j){const N=ia(b),C=Ls(N==null?void 0:N.flow_id);if(!N||!C)continue;const E=Array.isArray(N.interfaces)?N.interfaces.map(Ls).filter(Boolean):[];if(t===null){if(!E.length)continue}else if(!E.includes(t))throw new Za(`The gateway offered ${_}:${C}, which does not declare ${t}: ${Ch}.`);l.push({value:Ls(N.workflow_id)||`${_}${x?`@${x}`:""}:${C}`,bundleId:_,bundleVersion:x,flowId:C,name:Ls(N.name)||Ls((c=ia(m.metadata))==null?void 0:c.name)||_,description:Ls(N.description)||Ls(m.description),registryScope:Ls(m.registry_scope)||"private",group:w==="user"?"mine":"shared",shipped:m.shipped,interfaces:E,...t===null?{showInterfaces:!0}:{}})}}const u=n.defaultInterface??t;return{interfaceId:t,entries:l,gatewayDefault:u?eS(r,u):{status:"unavailable",reason:"no interface named for the gateway default"}}}function nS(e){const t=(n,r)=>n.name.localeCompare(r.name)||r.bundleVersion.localeCompare(n.bundleVersion,void 0,{numeric:!0})||n.value.localeCompare(r.value);return["shared","mine"].map(n=>({id:n,label:sx[n],entries:e.filter(r=>r.group===n).sort(t)})).filter(n=>n.entries.length>0)}const sS={"abstractcode.agent.v1":"Code agent","abstractassistant.agent.v1":"Assistant","abstractcode.coding.v1":"Coding",tools:"tools",event:"event",chat:"chat"};function rS(e){return sS[e]??e}function iS(e,t=[]){const n=e.bundleVersion?`@${e.bundleVersion}`:"";return e.showInterfaces?[[...new Set(e.interfaces.map(rS))].join(", "),n].filter(Boolean).join(" · "):n}function oS(e){return e.value}function aS(e){return e?e.status==="unavailable"?e.reason:`${e.name}${e.bundleVersion?` @${e.bundleVersion}`:""}`:""}function lS(e,t,n){return n<=0?null:e==="ArrowDown"?t<0?0:Math.min(n-1,t+1):e==="ArrowUp"?t<0?n-1:Math.max(0,t-1):e==="Home"?0:e==="End"?n-1:null}function cS(e,t=!0){const n=(e==null?void 0:e.entries)??[],r=[];t&&r.push({key:"default",value:tx,name:"Gateway default",detail:aS((e==null?void 0:e.gatewayDefault)??null),group:null,entry:null});for(const o of nS(n))for(const l of o.entries)r.push({key:l.value,value:l.value,name:l.name,detail:iS(l,n),title:oS(l),group:o.id,entry:l});return r}async function uS(e,t,n){var l;const r=await fetch(ag(e,wt(t)),{credentials:"include",headers:{Accept:"application/json"},signal:n}),o=await r.json().catch(()=>null);if(!r.ok){const u=((l=o==null?void 0:o.detail)==null?void 0:l.message)||(o==null?void 0:o.message)||(typeof(o==null?void 0:o.detail)=="string"?o.detail:"");throw new Error(u||`The gateway answered ${r.status}.`)}return o}function dS(e){var n;const t=e;return String(((n=t==null?void 0:t.detail)==null?void 0:n.message)||(t==null?void 0:t.message)||t||"The workflow list could not be loaded.")}function rx(e){const{interfaceId:t,defaultInterface:n,allVersions:r=!1,enabled:o=!0,gatewayBaseUrl:l,reloadKey:u}=e,c=p.useRef(e.request);c.current=e.request;const[f,m]=p.useState(0),[_,g]=p.useState({status:"idle",data:null,error:""});p.useEffect(()=>{if(!o){g({status:"idle",data:null,error:""});return}const x=new AbortController;g(N=>({...N,status:"loading",error:""}));const j=Qj(t,{allVersions:r});return(c.current?c.current(j,{signal:x.signal}):uS(l,j,x.signal)).then(N=>{x.signal.aborted||g({status:"ready",data:tS(N,t,{defaultInterface:n}),error:""})}).catch(N=>{x.signal.aborted||g({status:"error",data:null,error:dS(N)})}),()=>x.abort()},[t,n,r,o,l,u,f]);const w=p.useCallback(()=>m(x=>x+1),[]);return{..._,reload:w}}function fS(e){if(!e||typeof window>"u")return{};const t=e.getBoundingClientRect(),n=window.innerWidth,r=window.innerHeight,o=Math.min(Math.max(t.width,300),440,n-32),l=Math.max(16,Math.min(t.left,n-16-o)),u=r-t.bottom-16;return u>=220||u>=t.top?{position:"fixed",left:l,width:o,top:t.bottom+4,maxHeight:Math.max(160,u)}:{position:"fixed",left:l,width:o,bottom:r-t.top+4,maxHeight:Math.max(160,t.top-16)}}function ix(...e){return e.filter(Boolean).join(" ")}function ox(e){const t=rx({interfaceId:e.interfaceId,defaultInterface:e.defaultInterface,request:e.request,gatewayBaseUrl:e.gatewayBaseUrl,allVersions:e.allVersions,enabled:e.workflows?!1:e.enabled!==!1}),n=e.workflows??t,r=e.showDefault!==!1&&(e.interfaceId!==null||!!e.defaultInterface),o=p.useId().replace(/:/g,""),l=`${o}-list`,[u,c]=p.useState(!1),[f,m]=p.useState(-1),_=p.useRef(null),g=p.useRef(null),[w,x]=p.useState({}),j=p.useMemo(()=>cS(n.data,r),[n.data,r]),b=j.find(J=>J.value===e.value),N=b?{name:b.name,detail:b.detail}:e.currentLabel?{name:e.currentLabel.name,detail:e.currentLabel.detail||""}:n.status==="loading"?{name:"Loading workflows…",detail:""}:{name:e.value===tx?"Gateway default":"Choose a workflow",detail:""},C=String(e.unavailableReason||"").trim(),E=!C&&n.status==="ready",T=p.useCallback(()=>{c(!1),m(-1)},[]),I=p.useCallback(()=>{if(!E)return;x(fS(g.current)),c(!0);const J=j.findIndex(Y=>Y.value===e.value);m(J>=0?J:0)},[E,j,e.value]),K=p.useCallback(J=>{var Y;T(),J.value!==e.value&&e.onChange(J.value,J.entry),(Y=g.current)==null||Y.focus()},[T,e]);p.useEffect(()=>{if(!u)return;const J=re=>{_.current&&!_.current.contains(re.target)&&T()},Y=()=>T();return document.addEventListener("mousedown",J),document.addEventListener("touchstart",J),window.addEventListener("resize",Y),()=>{document.removeEventListener("mousedown",J),document.removeEventListener("touchstart",J),window.removeEventListener("resize",Y)}},[u,T]),p.useEffect(()=>{var Y;if(!u||f<0)return;const J=typeof document<"u"?document.getElementById(`${o}-opt-${f}`):null;(Y=J==null?void 0:J.scrollIntoView)==null||Y.call(J,{block:"nearest"})},[u,f,o]);const U=J=>{if(!u){["Enter"," ","ArrowDown","ArrowUp"].includes(J.key)&&(J.preventDefault(),I());return}if(J.key==="Escape"){J.preventDefault(),T();return}if(J.key==="Tab"){T();return}if(J.key==="Enter"||J.key===" "){J.preventDefault(),f>=0&&j[f]&&K(j[f]);return}const Y=lS(J.key,f,j.length);Y!==null&&(J.preventDefault(),m(Y))};return s.jsxs("div",{ref:_,className:ix("af-workflow-picker",e.className),"data-interface":e.interfaceId??"any",children:[s.jsxs("button",{ref:g,id:e.id,type:"button",role:"combobox",className:"af-workflow-picker__trigger","aria-label":e.ariaLabel||"Workflow","aria-describedby":`${o}-value`,"aria-haspopup":"listbox","aria-expanded":u,"aria-controls":l,"aria-activedescendant":u&&f>=0?`${o}-opt-${f}`:void 0,"aria-disabled":E?void 0:!0,title:C||void 0,onClick:()=>u?T():I(),onKeyDown:U,children:[s.jsxs("span",{className:"af-workflow-picker__value",id:`${o}-value`,children:[s.jsx("span",{className:"af-workflow-picker__name",children:N.name}),N.detail?s.jsx("span",{className:"af-workflow-picker__detail",children:N.detail}):null]}),s.jsx("span",{className:"af-workflow-picker__caret","aria-hidden":"true"})]}),u?s.jsx(hS,{id:l,idBase:o,rows:j,value:e.value,highlight:f,ariaLabel:e.ariaLabel||"Workflow",style:w,onHighlight:m,onChoose:K}):null,n.status==="error"?s.jsx("span",{className:"af-workflow-picker__error",role:"alert",children:n.error}):n.status==="ready"&&j.every(J=>!J.entry)&&!r?s.jsx("span",{className:"af-workflow-picker__empty",role:"status",children:nx}):null]})}function hS(e){const t=(l,u)=>s.jsxs("div",{id:`${e.idBase}-opt-${u}`,role:"option","aria-selected":l.value===e.value,"data-value":l.value,title:l.title,className:ix("af-workflow-picker__option",u===e.highlight&&"af-workflow-picker__option--highlighted",l.value===e.value&&"af-workflow-picker__option--selected"),onMouseEnter:()=>e.onHighlight(u),onMouseDown:c=>c.preventDefault(),onClick:()=>e.onChoose(l),children:[s.jsx("span",{className:"af-workflow-picker__name",children:l.name}),l.detail?s.jsx("span",{className:"af-workflow-picker__detail",children:l.detail}):null]},l.key),n=e.rows.map((l,u)=>({row:l,index:u})),r=n.filter(l=>l.row.group===null),o=["shared","mine"].map(l=>({g:l,items:n.filter(u=>u.row.group===l)})).filter(l=>l.items.length>0);return s.jsxs("div",{id:e.id,role:"listbox","aria-label":e.ariaLabel,className:"af-workflow-picker__list",style:e.style,children:[r.map(l=>t(l.row,l.index)),o.map(({g:l,items:u})=>s.jsxs("div",{role:"group","aria-labelledby":`${e.idBase}-g-${l}`,"data-group":l,children:[s.jsx("div",{id:`${e.idBase}-g-${l}`,className:"af-workflow-picker__group",role:"presentation",children:sx[l]}),u.map(c=>t(c.row,c.index))]},l)),o.length===0?s.jsx("p",{className:"af-workflow-picker__empty",children:nx}):null]})}function mS(e){const t=_p(e.target);return s.jsxs("div",{className:"af-auto__field",children:[s.jsx("span",{children:"Workflow"}),s.jsx(ox,{...e.options,ariaLabel:"Automation workflow",value:t,currentLabel:{name:t},onChange:(n,r)=>e.onChange(n==="@default"?{flow_id:"@default",interface:e.options.interfaceId||e.options.defaultInterface||"abstractcode.agent.v1"}:{bundle_ref:`${r.bundleId}@${r.bundleVersion}`,flow_id:r.flowId})})]})}async function _S(e,t){var w,x;const n=e.flow_id==="@default"?(x=(w=t.workflows)==null?void 0:w.data)==null?void 0:x.gatewayDefault:null,r="bundle_ref"in e?e.bundle_ref:(n==null?void 0:n.status)==="ok"?`${n.bundleId}@${n.bundleVersion}`:"",o=e.flow_id!=="@default"?e.flow_id:(n==null?void 0:n.status)==="ok"?n.flowId:"";if(!r||!o||!t.request)throw new Error("Workflow inputs could not be checked. Refresh the workflow list and try again.");const l=r.lastIndexOf("@"),u=l<0?r:r.slice(0,l),c=l<0?"":r.slice(l+1),f=await t.request(`bundles/${encodeURIComponent(u)}/flows/${encodeURIComponent(o)}/input_schema${c?`?bundle_version=${encodeURIComponent(c)}`:""}`,{signal:new AbortController().signal}),m=(f==null?void 0:f.input_data_schema)||f;if(!m||typeof m!="object"||!m.properties)throw new Error("This workflow does not report its input requirements. Choose another workflow.");const _={...f.defaults||{}};for(const[j,b]of Object.entries(m.properties))b&&"default"in b&&(_[j]=b.default);Object.assign(_,e.input_data||{});const g=(Array.isArray(m.required)?m.required:[]).filter(j=>_[j]===void 0);if(g.length)throw new Error(`This workflow needs additional inputs: ${g.join(", ")}. Configure a new automation from that workflow's input form, or choose a compatible workflow.`);return{...e,input_data:_}}function xp(e){if(Em(e.status))return null;const t=Ut.not_set_up,n=Ut.open_my_email,r=t.endsWith(n)?t.slice(0,t.length-n.length):`${t} `,o=e.status&&e.status.admin_disabled&&typeof e.status.admin_disabled.cause=="string"?e.status.admin_disabled.cause:"";return s.jsxs("p",{className:"af-auto__hint af-email__notice",role:"note","data-email-setup":"missing",children:[r,e.onOpenMyEmail?s.jsx("button",{type:"button",className:"af-auto__linkbtn","data-action":"open-my-email",onClick:e.onOpenMyEmail,children:n}):n,o?s.jsxs("span",{className:"af-email__cause",children:[" (",o,")"]}):null]})}function pS(e){const t=e.value,n=c=>e.onChange({...t,...c}),r=c=>`${e.idBase}-email-${c}`,o=Af(ug(t.usesModel)),l=t.every??(o&&o.unit==="s"?{amount:Math.max(1,Math.round(o.amount/60)),unit:"m"}:{amount:o?o.amount:1,unit:o?o.unit:"h"}),u=e.disabled===!0;return s.jsxs("div",{className:"af-email__trigger","data-field":"email-trigger",children:[s.jsxs("div",{className:"af-auto__row",children:[s.jsx("span",{children:Ut.every_label}),s.jsx("input",{type:"number",min:1,step:1,value:String(l.amount),disabled:u,"aria-label":"Check interval amount",name:"email_every_amount",onChange:c=>n({every:{amount:Number(c.target.value),unit:l.unit}})}),s.jsxs("select",{value:l.unit,disabled:u,"aria-label":"Check interval unit",name:"email_every_unit",onChange:c=>n({every:{amount:l.amount,unit:c.target.value}}),children:[s.jsx("option",{value:"m",children:"minutes"}),s.jsx("option",{value:"h",children:"hours"}),s.jsx("option",{value:"d",children:"days"})]})]}),s.jsx("p",{className:"af-auto__hint","data-email-rule":"interval",children:Ut.interval_rule}),s.jsxs("label",{className:"af-auto__field",htmlFor:r("batch"),children:[s.jsx("span",{children:Ut.max_batch_label}),s.jsx("input",{id:r("batch"),name:"email_max_batch",type:"number",min:1,max:pp,step:1,disabled:u,value:String(t.maxBatch??cg),onChange:c=>n({maxBatch:c.target.value.trim()===""?null:Number(c.target.value)})})]}),s.jsx("p",{className:"af-auto__hint",children:Ut.max_batch_hint}),s.jsxs("fieldset",{className:"af-auto__field af-email__filters",disabled:u,children:[s.jsx("legend",{children:Ut.filters_legend}),s.jsxs("label",{className:"af-auto__field",htmlFor:r("from"),children:[s.jsx("span",{children:Ut.from_in}),s.jsx("input",{id:r("from"),name:"email_from_in",value:t.fromIn,spellCheck:!1,placeholder:"alice@example.com, billing@example.org",onChange:c=>n({fromIn:c.target.value})})]}),s.jsxs("label",{className:"af-auto__field",htmlFor:r("domain"),children:[s.jsx("span",{children:Ut.from_domain_in}),s.jsx("input",{id:r("domain"),name:"email_from_domain_in",value:t.fromDomainIn,spellCheck:!1,placeholder:"example.com",onChange:c=>n({fromDomainIn:c.target.value})})]}),s.jsxs("label",{className:"af-auto__field",htmlFor:r("to"),children:[s.jsx("span",{children:Ut.to_in}),s.jsx("input",{id:r("to"),name:"email_to_in",value:t.toIn,spellCheck:!1,onChange:c=>n({toIn:c.target.value})})]}),s.jsxs("label",{className:"af-auto__field",htmlFor:r("subject"),children:[s.jsx("span",{children:Ut.subject_contains}),s.jsx("input",{id:r("subject"),name:"email_subject_contains",value:t.subjectContains,maxLength:200,onChange:c=>n({subjectContains:c.target.value})})]}),s.jsxs("label",{className:"af-auto__field",htmlFor:r("attach"),children:[s.jsx("span",{children:Ut.has_attachment}),s.jsxs("select",{id:r("attach"),name:"email_has_attachment",value:t.hasAttachment,onChange:c=>n({hasAttachment:c.target.value}),children:[s.jsx("option",{value:"any",children:Ut.has_attachment_any}),s.jsx("option",{value:"yes",children:Ut.has_attachment_yes}),s.jsx("option",{value:"no",children:Ut.has_attachment_no})]})]}),s.jsx("p",{className:"af-auto__hint",children:Ut.list_hint})]})]})}function gS(e){const t=r=>`${e.idBase}-email-${r}`,n=e.disabled===!0;return s.jsxs("div",{className:"af-email__options","data-field":"email-options",children:[s.jsx(No,{variant:"row",action:"notify-email",label:Ut.notify_label,checked:e.notifyEmail,unavailableReason:n?"Connect a mailbox first.":null,onChange:r=>e.onNotifyEmailChange(r)}),s.jsxs("p",{className:"af-auto__hint",children:[Ut.notify_hint," Turn on Email result to choose yourself or other email addresses."]}),e.notifyEmail?s.jsxs("fieldset",{className:"af-auto__field",disabled:n,"data-field":"email-recipients",children:[s.jsx("legend",{children:Ut.recipients_legend}),s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:t("rcpt"),value:"self",checked:e.recipients.mode==="self",onChange:()=>e.onRecipientsChange({...e.recipients,mode:"self"})})," ",Ut.recipients_self]}),s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:t("rcpt"),value:"list",checked:e.recipients.mode==="list",onChange:()=>e.onRecipientsChange({...e.recipients,mode:"list"})})," ",Ut.recipients_list]}),e.recipients.mode==="list"?s.jsx("textarea",{name:"email_recipient_list","aria-label":Ut.recipients_list,rows:2,spellCheck:!1,value:e.recipients.addresses,placeholder:"colleague@example.com",onChange:r=>e.onRecipientsChange({mode:"list",addresses:r.target.value})}):null,s.jsx("p",{className:"af-auto__hint",children:Ut.recipients_hint})]}):null]})}const yS={active:"play",paused:"pause",completed:"check",failed:"error",archived:"archive"};function ax(e){const t=String(e.status),n=yS[t];return s.jsxs("span",{className:`af-auto__status af-auto__status--${t}${e.className?` ${e.className}`:""}`,"data-state":t,children:[s.jsx("span",{className:"af-auto__status-word",children:kj[t]??t}),n?s.jsx(et,{name:n,size:e.iconSize??11,className:"af-auto__status-icon"}):null]})}const bp="Discuss — fork at this occurrence (own workspace, automation files read-only)",Am=e=>s.jsx("div",{className:"af-auto-text","data-unformatted":"true",children:e});function wS(e){return dg(e)?e:{status:0,code:"client_error",message:e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}}function jy(e){const t=e.path.split(new RegExp("(?<=[/\\\\_-])"));return s.jsx("code",{className:"af-auto__path-text",children:t.map((n,r)=>s.jsxs(ve.Fragment,{children:[n,r<t.length-1?s.jsx("wbr",{}):null]},r))})}function vS(e,t){const n=e.trigger,r=t.find(o=>o.id===n.source_id&&o.version===n.source_version);return r?"available"in r&&r.available===!1?`Trigger source ${n.source_id}@${n.source_version} is unavailable${r.unavailable_reason?`: ${r.unavailable_reason}`:"."}`:null:`This gateway does not list the trigger source ${n.source_id}@${n.source_version}.`}function xS(e){const t=e.summary,n=Vv(t),r=vS(t,e.triggerSources),o=t.next_fire_at?`${la(t.next_fire_at)} (${Gv(t.next_fire_at,e.nowMs??Date.now())})`:t.status==="paused"?"none while paused":"none scheduled";return s.jsxs("header",{className:"af-auto__head",children:[s.jsxs("div",{className:"af-auto__titlebar",children:[s.jsx("h2",{className:"af-auto__title",id:e.titleId,tabIndex:-1,children:t.title}),s.jsx(ax,{status:t.status}),t.legacy?s.jsx("span",{className:"af-auto__legacy",children:"Legacy schedule"}):null]}),s.jsxs("dl",{className:"af-auto__facts",children:[e.workflowLabel?s.jsxs(s.Fragment,{children:[s.jsx("dt",{children:"Workflow"}),s.jsx("dd",{"data-fact":"workflow",children:e.workflowLabel})]}):null,s.jsx("dt",{children:"When"}),s.jsxs("dd",{"data-fact":"trigger",children:[lg(t.trigger),r?s.jsxs("span",{className:"af-auto__warn",role:"note",children:[" ",r]}):null]}),s.jsx("dt",{children:"Context"}),s.jsx("dd",{"data-fact":"context",children:Ov(t.context_mode)}),n?s.jsxs(s.Fragment,{children:[s.jsx("dt",{children:"Now"}),s.jsx("dd",{"data-fact":"current",className:"is-notable",children:n})]}):null,s.jsx("dt",{children:"Next run"}),s.jsx("dd",{"data-fact":"next",children:o}),s.jsx("dt",{children:"Runs"}),s.jsx("dd",{"data-fact":"count",children:t.occurrence_count}),t.workspace_root?s.jsxs(s.Fragment,{children:[s.jsx("dt",{children:"Workspace"}),s.jsx("dd",{"data-fact":"workspace",className:"af-auto__workspace",children:e.onOpenWorkspace?s.jsxs("button",{type:"button",className:"af-auto__path","data-action":"open-workspace",title:`Browse the automation's folder
54
- ${t.workspace_root}`,"aria-label":`Browse the automation's folder ${t.workspace_root}`,onClick:()=>{var l;return(l=e.onOpenWorkspace)==null?void 0:l.call(e,t.automation_id)},children:[s.jsx(et,{name:"folder",size:14,className:"af-auto__path-icon"}),s.jsx(jy,{path:t.workspace_root})]}):s.jsxs("span",{className:"af-auto__path af-auto__path--static",children:[s.jsx(et,{name:"folder",size:14,className:"af-auto__path-icon"}),s.jsx(jy,{path:t.workspace_root})]})})]}):null,s.jsx("dt",{children:"Attention"}),s.jsx("dd",{"data-fact":"attention",className:t.attention.unread||t.attention.pending_waits?"is-notable":void 0,children:Kv(t)}),t.revision!==null?s.jsxs(s.Fragment,{children:[s.jsx("dt",{children:"Revision"}),s.jsx("dd",{"data-fact":"revision",children:t.revision})]}):null]})]})}function bS(e){var u,c;const t=e.definition,n=e.renderText??Am,r=t.target.input_data.prompt,o=t.policy.retry,l=t.policy.tool_approval;return s.jsxs("details",{className:"af-auto__definition","data-definition-revision":t.revision,open:e.open,children:[s.jsxs("summary",{children:[s.jsx(et,{name:"chevronRight",size:14,className:"af-auto__definition-chevron"}),s.jsx(et,{name:"file",size:14}),s.jsx("span",{className:"af-auto__definition-title",children:"Definition"}),s.jsxs("span",{className:"af-auto__definition-meta",children:["revision ",t.revision]})]}),s.jsxs("dl",{className:"af-auto__facts",children:[s.jsx("dt",{children:"Target"}),s.jsx("dd",{"data-def":"target",children:s.jsx("code",{children:t.target.workflow_id})}),typeof r=="string"&&r?s.jsxs(s.Fragment,{children:[s.jsx("dt",{children:"Task"}),s.jsx("dd",{"data-def":"prompt",children:n(r)})]}):null,s.jsx("dt",{children:"Trigger"}),s.jsxs("dd",{"data-def":"trigger",children:[t.trigger.source_id,"@",t.trigger.source_version," · ",lg(t.trigger),s.jsx("pre",{className:"af-auto__json",children:JSON.stringify(t.trigger.config,null,2)})]}),s.jsx("dt",{children:"Context"}),s.jsxs("dd",{"data-def":"context",children:[Ov(t.context.mode),t.context.mode==="growing"?` · ${Number(((u=t.context.growing)==null?void 0:u.max_tokens)??5e4).toLocaleString()} tokens`:""]}),s.jsx("dt",{children:"Tools"}),s.jsx("dd",{"data-def":"tool_approval",children:l==="ask"?"Ask before each tool call (ask)":l==="auto"?"Run without asking (auto)":String(l)}),s.jsx("dt",{children:"Notify"}),s.jsx("dd",{"data-def":"notify",children:Tj(t.notify)}),(c=t.notify)!=null&&c.channels.includes("email")?s.jsxs(s.Fragment,{children:[s.jsx("dt",{children:"Recipients"}),s.jsx("dd",{"data-def":"email_recipients",children:$j(t.notify.recipients)})]}):null,s.jsx("dt",{children:"Retries"}),s.jsxs("dd",{"data-def":"retry",children:[o.max_attempts," ",o.max_attempts===1?"attempt":"attempts",", backoff ",o.backoff.initial," ×",o.backoff.factor," up to ",o.backoff.max]}),s.jsx("dt",{children:"Revision"}),s.jsx("dd",{"data-def":"revision",children:t.revision})]})]})}const $f=Rv,xo=$f.labels,Bi={active:"play",pause:"pause",resume:"play",run_now:$f.icons.run_now.name,stop_current:"stop",revise:"edit",archive:"archive",discuss:"chat"},kp=$f.hints,kS=$f.run_now_next_run_line,jS=$f.run_now_growing_line;function lm(e,t){const n=[kp[e]];return e==="run_now"&&t&&(t.next_fire_at&&n.push(kS.replace("{time}",la(t.next_fire_at))),t.context_mode==="growing"&&n.push(jS)),n.join(`
55
- `)}function SS(e,t,n){const r=new Map;for(const u of t){const c=e[u];if(c.enabled)continue;const f=c.reason??"Not available now.";r.set(f,[...r.get(f)??[],u])}const o=[],l={};return[...r.entries()].forEach(([u,c],f)=>{const m=`${n}-why-${f}`;o.push({id:m,text:`${c.map(_=>xo[_]).join(", ")}: ${u}`});for(const _ of c)l[_]=m}),{lines:o,describedBy:l}}function ur(e){return s.jsxs(s.Fragment,{children:[s.jsx(et,{name:e.icon,size:14,className:"af-auto__btn-icon"}),s.jsx("span",{children:e.label})]})}function NS(e){const t=om(e.summary,e.occurrences,e.busy),r=SS(t,["active","run_now","stop_current","revise","archive"],e.idBase??`af-auto-${e.summary.automation_id}`),o=(l,u,c)=>{const f=lm(l,e.summary);return s.jsx("button",{type:"button",className:`af-auto__btn${c!=null&&c.danger?" af-auto__btn--danger":""}`,"data-action":(c==null?void 0:c.action)??l,disabled:!t[l].enabled,title:t[l].enabled?f:`${t[l].reason}
56
- ${f}`,"aria-description":f,"aria-describedby":r.describedBy[l],"aria-pressed":c==null?void 0:c.pressed,onClick:u,children:s.jsx(ur,{icon:Bi[l],label:(c==null?void 0:c.label)??xo[l]})},l)};return s.jsxs("div",{className:"af-auto__controls-wrap",children:[s.jsxs("div",{className:"af-auto__actionbar",children:[s.jsxs("div",{className:"af-auto__controls",role:"toolbar","aria-label":"Automation controls",children:[s.jsx(No,{className:"af-auto__switch",action:"active",label:xo.active,checked:e.summary.status==="active",unavailableReason:t.active.enabled?null:t.active.reason??"Not available now.",describedBy:r.describedBy.active,busy:e.busy,hint:lm("active",e.summary),onChange:()=>e.onCommand(Lj(e.summary))},"active"),o("run_now",()=>e.onCommand(ko.run_now)),o("stop_current",()=>e.onCommand(ko.stop_current)),o("revise",e.onToggleRevise,{pressed:e.reviseOpen,action:"edit"}),o("archive",e.onAskArchive,{danger:!0,label:"Archive…"})]}),s.jsx("span",{className:`af-auto__notice${e.notice?" af-auto__notice--on":""}`,role:"status",tabIndex:-1,children:e.notice?s.jsxs(s.Fragment,{children:[s.jsx(et,{name:"check",size:13}),s.jsx("span",{className:"af-auto__notice-text",children:e.notice}),e.onDismissNotice?s.jsx("button",{type:"button",className:"af-auto__icon-btn af-auto__icon-btn--bare","data-action":"dismiss-notice","aria-label":"Dismiss",title:"Dismiss",onClick:e.onDismissNotice,children:s.jsx(et,{name:"x",size:12})}):null]}):null})]}),r.lines.length?s.jsxs("p",{className:"af-auto__reasons",children:[s.jsx(et,{name:"info",size:12,className:"af-auto__reasons-icon"}),r.lines.map(l=>s.jsx("span",{id:l.id,children:l.text},l.id))]}):null,e.summary.status==="paused"&&t.run_now.enabled?s.jsx("p",{className:"af-auto__hint",children:"Paused: scheduled runs are skipped. Run now works and keeps it paused."}):null,e.confirmingArchive?s.jsxs("div",{className:"af-auto__confirm",role:"group","aria-label":"Confirm archive",children:[s.jsxs("p",{children:["Archive “",e.summary.title,"”? Its history stays readable; it will not run again. The current run, if any, finishes."]}),s.jsxs("div",{className:"af-auto__row",children:[s.jsx("button",{type:"button",className:"af-auto__btn af-auto__btn--danger","data-action":"archive-confirm",disabled:!t.archive.enabled,onClick:()=>e.onCommand(ko.archive),children:s.jsx(ur,{icon:"archive",label:"Archive"})}),s.jsx("button",{type:"button",className:"af-auto__btn","data-action":"archive-cancel",onClick:e.onCancelArchive,children:s.jsx(ur,{icon:"x",label:"Keep it"})})]})]}):null]})}const Sy=[["m","minutes"],["h","hours"],["d","days"]];function CS(e,t){const n=N=>{const C=e.elements.namedItem(N);return C&&typeof C.value=="string"?C.value:null},r=n("every_amount"),o=n("every_unit"),l=r!==null&&o!==null?`${r.trim()}${o}`:t.every,u=e.elements.namedItem("context"),c=u&&(u.value==="growing"||u.value==="independent")?u.value:t.context,f=n("prompt"),m=e.elements.namedItem("tool_approval"),_=m&&(m.value==="auto"||m.value==="ask")?m.value:t.toolApproval??null,g=e.elements.namedItem("notify_email"),w=g&&typeof g.checked=="boolean"?g.checked:t.notifyEmail??null,x=e.elements.namedItem("email_recipients"),j=n("email_recipient_list"),b=x&&(x.value==="self"||x.value==="list")?{mode:x.value,addresses:j??""}:t.emailRecipients??null;return{title:n("title")??t.title,every:l,context:c,growingMaxTokens:n("growing_max_tokens")===null?t.growingMaxTokens:Number(n("growing_max_tokens")),prompt:f??t.prompt??null,toolApproval:_,notifyEmail:w,emailRecipients:b}}function ES(e){const t=Yv(e.summary,e.definition),[n,r]=p.useState(),[o,l]=p.useState(t.tools??null),[u,c]=p.useState(t.context),[f,m]=p.useState(!!t.notifyEmail),_=t.every?Af(t.every):null,g=_&&_.unit==="s"?[["s","seconds"],...Sy]:Sy,w=`af-auto-revise-${e.summary.automation_id}`,x=Em(e.emailStatus),j=Cm(e.summary.trigger);return s.jsxs("form",{className:"af-auto__revise","aria-labelledby":`${w}-heading`,onSubmit:b=>{b.preventDefault(),e.onSubmit({...CS(b.currentTarget,t),...n?{target:n}:{},...e.availableTools!==void 0?{tools:o}:{}})},onKeyDown:b=>{b.key==="Escape"&&(b.preventDefault(),e.onCancel())},children:[s.jsxs("h3",{className:"af-auto__form-title",id:`${w}-heading`,children:[s.jsx(et,{name:"edit",size:14})," Edit automation"]}),e.definition&&e.workflowPickerOptions?s.jsx(mS,{target:n||e.definition.target,options:e.workflowPickerOptions,onChange:r}):null,s.jsxs("label",{className:"af-auto__field",htmlFor:`${w}-title`,children:[s.jsx("span",{children:"Title"}),s.jsx("input",{id:`${w}-title`,name:"title",defaultValue:t.title,maxLength:120,required:!0})]}),t.prompt!==null&&t.prompt!==void 0?s.jsxs("label",{className:"af-auto__field",htmlFor:`${w}-prompt`,children:[s.jsx("span",{children:"Task"}),s.jsx("textarea",{id:`${w}-prompt`,name:"prompt",defaultValue:t.prompt,rows:Math.min(10,Math.max(3,t.prompt.split(`
57
- `).length+1)),required:!0})]}):null,_?s.jsxs("fieldset",{className:"af-auto__field",children:[s.jsx("legend",{children:j?Ut.every_label:"Repeat every (UTC)"}),s.jsxs("div",{className:"af-auto__row",children:[s.jsx("input",{name:"every_amount",type:"number",min:1,step:1,defaultValue:_.amount,"aria-label":"Interval amount"}),s.jsx("select",{name:"every_unit",defaultValue:_.unit,"aria-label":"Interval unit",children:g.map(([b,N])=>s.jsx("option",{value:b,children:N},b))})]}),j?s.jsx("p",{className:"af-auto__hint","data-email-rule":"interval",children:Ut.interval_rule}):null]}):s.jsx("p",{className:"af-auto__hint",children:"This trigger has no interval to change."}),s.jsxs("fieldset",{className:"af-auto__field",children:[s.jsx("legend",{children:"Context"}),s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:"context",value:"independent",defaultChecked:t.context==="independent",onChange:()=>c("independent")})," Independent — each run starts fresh"]}),s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:"context",value:"growing",defaultChecked:t.context==="growing",onChange:()=>c("growing")})," Growing — each run sees the previous runs"]}),s.jsx("div",{hidden:u!=="growing",children:s.jsxs("label",{className:"af-auto__field",children:[s.jsx("span",{children:"Max growing context (tokens)"}),s.jsx("input",{name:"growing_max_tokens",type:"number",min:1,step:1,disabled:e.busy||u!=="growing",defaultValue:t.growingMaxTokens}),s.jsx("span",{className:"af-auto__hint",children:zj})]})})]}),t.toolApproval?s.jsxs("fieldset",{className:"af-auto__field",children:[s.jsx("legend",{children:"Tools"}),e.availableTools!==void 0?s.jsx(ex,{availableTools:e.availableTools,value:o,onChange:l,disabled:e.busy}):null,s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:"tool_approval",value:"auto",defaultChecked:t.toolApproval==="auto"})," Run without asking"]}),s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:"tool_approval",value:"ask",defaultChecked:t.toolApproval==="ask"})," Ask before each tool call"]})]}):null,t.notifyEmail!==null&&t.notifyEmail!==void 0&&t.emailRecipients?s.jsxs("fieldset",{className:"af-auto__field","data-field":"email",children:[s.jsx("legend",{children:"Mailbox"}),x?null:s.jsx(xp,{status:e.emailStatus,onOpenMyEmail:e.onOpenMyEmail}),s.jsx(Mk,{variant:"row",action:"notify-email",name:"notify_email",label:Ut.notify_label,defaultChecked:!!t.notifyEmail,onChange:m,unavailableReason:!x&&!t.notifyEmail?"Connect a mailbox first.":null}),s.jsxs("p",{className:"af-auto__hint",children:[Ut.notify_hint," Turn on Email result to choose yourself or other email addresses."]}),s.jsx("div",{hidden:!f,children:s.jsxs("fieldset",{className:"af-auto__field",disabled:!f,"data-field":"email-recipients",children:[s.jsx("legend",{children:Ut.recipients_legend}),s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:"email_recipients",value:"self",defaultChecked:t.emailRecipients.mode==="self"})," ",Ut.recipients_self]}),s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:"email_recipients",value:"list",defaultChecked:t.emailRecipients.mode==="list",disabled:!x&&t.emailRecipients.mode!=="list"})," ",Ut.recipients_list]}),s.jsx("textarea",{name:"email_recipient_list","aria-label":Ut.recipients_list,rows:2,spellCheck:!1,defaultValue:t.emailRecipients.addresses,disabled:!x&&t.emailRecipients.mode!=="list"}),s.jsx("p",{className:"af-auto__hint",children:Ut.recipients_hint})]})})]}):null,s.jsx("p",{className:"af-auto__hint",children:"Changes apply from the next run; a new interval never fires past ticks."}),e.errors.length?s.jsx("ul",{className:"af-auto__form-errors",role:"alert",children:e.errors.map(b=>s.jsx("li",{children:b},b))}):null,s.jsxs("div",{className:"af-auto__row",children:[s.jsx("button",{type:"submit",className:"af-auto__btn af-auto__btn--primary","data-action":"edit-save",disabled:e.busy,children:s.jsx(ur,{icon:"check",label:"Save changes"})}),s.jsx("button",{type:"button",className:"af-auto__btn","data-action":"edit-cancel",onClick:e.onCancel,children:s.jsx(ur,{icon:"x",label:"Cancel"})})]})]})}function jp(e,t){const n=e.elements.namedItem(t);return n&&typeof n.value=="string"?n.value.trim():""}function AS(e){const t=e.wait,n=`${e.idBase}-${t.run_id}-${t.wait_key}-prompt`,r=u=>e.onAnswerWait(t.run_id,t.wait_key,u),o=e.renderText??Am,l=u=>s.jsxs("div",{className:"af-auto-wait__prompt",id:n,children:[s.jsx("span",{className:"af-auto-wait__kind",children:Qv[t.kind]??"Waiting"}),t.prompt?o(t.prompt):s.jsxs("span",{children:[" ",u]})]});if(t.kind==="tool_approval"){const u=Hj(t);return s.jsxs("div",{className:"af-auto-wait af-auto-wait--tool_approval",role:"group","data-wait-key":t.wait_key,"data-wait-kind":t.kind,"aria-labelledby":n,children:[l("A tool call needs your approval."),u&&u.length?s.jsx("ul",{className:"af-auto-wait__calls","aria-label":"Tool calls to approve",children:u.map((c,f)=>s.jsxs("li",{"data-tool":c.name,children:[s.jsx("code",{className:"af-auto-wait__tool",children:c.name}),s.jsx("pre",{className:"af-auto-wait__args",children:JSON.stringify(c.arguments,null,2)})]},c.call_id??`${c.name}:${f}`))}):s.jsx("p",{className:"af-auto__hint",children:"The gateway did not list the tool calls; open the run to see them before approving."}),s.jsxs("div",{className:"af-auto__row",children:[s.jsx("button",{type:"button",className:"af-auto__btn af-auto__btn--primary","data-action":"wait-approve",disabled:e.busy,onClick:()=>r({approved:!0}),children:s.jsx(ur,{icon:"check",label:"Approve"})}),s.jsx("button",{type:"button",className:"af-auto__btn af-auto__btn--danger","data-action":"wait-deny",disabled:e.busy,onClick:()=>r({approved:!1}),children:s.jsx(ur,{icon:"x",label:"Deny"})})]})]})}return t.kind==="event"?s.jsxs("form",{className:"af-auto-wait af-auto-wait--event","data-wait-key":t.wait_key,"data-wait-kind":t.kind,"aria-labelledby":n,onSubmit:u=>{var f;u.preventDefault();const c=Vj(jp(u.currentTarget,"payload"));c.ok?r({payload:c.payload}):(f=e.onWaitError)==null||f.call(e,c.error)},children:[l("The run waits for an event."),s.jsx("textarea",{name:"payload",rows:3,"aria-label":"Event payload (JSON)",placeholder:'{"key": "value"}',disabled:e.busy}),s.jsx("div",{className:"af-auto__row",children:s.jsx("button",{type:"submit",className:"af-auto__btn af-auto__btn--primary","data-action":"wait-send-event",disabled:e.busy,children:s.jsx(ur,{icon:"send",label:"Send event"})})})]}):t.kind==="ask_user"?s.jsxs("form",{className:"af-auto-wait af-auto-wait--ask_user","data-wait-key":t.wait_key,"data-wait-kind":t.kind,"aria-labelledby":n,onSubmit:u=>{u.preventDefault();const c=jp(u.currentTarget,"response");c&&r({response:c})},children:[l("The run is waiting for your input."),t.choices&&t.choices.length?s.jsx("div",{className:"af-auto__row",role:"group","aria-label":"Choices",children:t.choices.map(u=>s.jsx("button",{type:"button",className:"af-auto__btn","data-action":"wait-choice",disabled:e.busy,onClick:()=>r({response:u}),children:u},u))}):null,s.jsxs("div",{className:"af-auto__row",children:[s.jsx("input",{name:"response","aria-label":"Your answer",placeholder:"Your answer",disabled:e.busy}),s.jsx("button",{type:"submit",className:"af-auto__btn af-auto__btn--primary","data-action":"wait-answer",disabled:e.busy,children:s.jsx(ur,{icon:"send",label:"Answer"})})]})]}):s.jsxs("div",{className:"af-auto-wait",role:"group","data-wait-key":t.wait_key,"data-wait-kind":String(t.kind),"aria-labelledby":n,children:[l("The run is waiting."),s.jsxs("p",{className:"af-auto__hint",children:["This kind of wait (",String(t.kind),") cannot be answered here; open the run."]})]})}function $S(e){const{row:t,tone:n,badge:r,statusText:o}=e.view,l=`af-auto-occ-${t.run_id}`,u=e.renderText??Am,c=e.discuss.enabled&&e.view.canDiscuss&&!e.busy,f=e.discuss.enabled?e.view.canDiscuss?null:"Available once this occurrence finishes.":e.discuss.reason??"Not available.",m=(w,x)=>e.renderTurn?e.renderTurn({kind:w,role:w==="trigger"?"user":"assistant",text:x,index:t.index,runId:t.run_id}):u(x),_=e.renderTurn?" af-auto-turn--card":"",g=n==="failed"?t.failure?"No answer.":"No answer: the run failed.":n==="waiting"?"Waiting for your answer.":n==="running"?"Running…":"No answer.";return s.jsxs("li",{className:`af-auto-occ af-auto-occ--${n}`,"data-index":t.index,"data-tone":n,"aria-labelledby":`${l}-h`,children:[s.jsxs("div",{className:`af-auto-turn af-auto-turn--trigger${_}`,"data-turn":"trigger",children:[s.jsxs("div",{className:"af-auto-turn__meta",id:`${l}-h`,children:[s.jsxs("span",{className:"af-auto-turn__index",children:["#",t.index]})," · ",t.trigger.summary," · fired ",la(t.fired_at)]}),s.jsx("div",{className:"af-auto-turn__text",children:m("trigger",t.user_turn)})]}),s.jsxs("div",{className:`af-auto-turn af-auto-turn--answer${_}`,"data-turn":"answer",children:[s.jsxs("div",{className:"af-auto-turn__meta",children:[r?s.jsx("span",{className:`af-auto-badge af-auto-badge--${n}`,children:r}):null,s.jsx("span",{className:"af-auto-turn__status",children:o}),t.finished_at?s.jsxs("span",{children:[" · ",la(t.finished_at)]}):null]}),t.notify?s.jsxs("div",{className:"af-auto-notify","data-notify":"true",children:[s.jsx("strong",{children:t.notify.title}),t.notify.body?s.jsx("div",{className:"af-auto-notify__body",children:u(t.notify.body)}):null]}):null,t.failure?s.jsxs("div",{className:"af-auto-failure","data-failure":t.failure.reason_code,children:[s.jsx("strong",{children:t.failure.reason_code}),": ",t.failure.message," ",s.jsxs("span",{className:"af-auto-turn__muted",children:["(after ",t.failure.attempts," ",t.failure.attempts===1?"attempt":"attempts",")"]})]}):null,t.answer?s.jsx("div",{className:"af-auto-turn__text",children:m("answer",t.answer)}):s.jsx("div",{className:"af-auto-turn__empty",children:g}),t.artifacts.length?s.jsx("ul",{className:"af-auto-artifacts","aria-label":"Artifacts",children:t.artifacts.map(w=>s.jsxs("li",{children:[e.onOpenResource?s.jsxs("button",{type:"button",className:"af-auto__linkbtn","data-action":"open-artifact",onClick:()=>{var x;return(x=e.onOpenResource)==null?void 0:x.call(e,{kind:"artifact",url:w.url,name:w.name,mimeType:w.mime_type,runId:t.run_id})},children:[s.jsx(et,{name:"file",size:13,className:"af-auto__btn-icon"})," ",w.name]}):s.jsx("span",{className:"af-auto-artifact__name",children:w.name})," ",s.jsx("span",{className:"af-auto-turn__muted",children:w.mime_type})]},w.artifact_id))}):null,t.waits.map(w=>s.jsx(AS,{wait:w,busy:e.busy,idBase:l,onAnswerWait:e.onAnswerWait,onWaitError:e.onWaitError,renderText:e.renderText},`${w.run_id}:${w.wait_key}`))]}),s.jsxs("div",{className:"af-auto-occ__foot",children:[s.jsxs("details",{className:"af-auto-occ__details",children:[s.jsx("summary",{children:"Run details"}),s.jsxs("dl",{className:"af-auto__facts",children:[s.jsx("dt",{children:"Run"}),s.jsx("dd",{children:s.jsx("code",{children:t.run_id})}),s.jsx("dt",{children:"Attempts"}),s.jsx("dd",{children:t.attempts})]}),s.jsxs("div",{className:"af-auto__row",children:[s.jsx("button",{type:"button",className:"af-auto__btn","data-action":"open-run",onClick:()=>e.onOpenRun(t.run_id),children:s.jsx(ur,{icon:"list",label:"Open run ledger"})}),e.onOpenResource?s.jsx("button",{type:"button",className:"af-auto__btn","data-action":"open-ledger-json",onClick:()=>{var w;return(w=e.onOpenResource)==null?void 0:w.call(e,{kind:"ledger",url:t.ledger_url,name:`run-${t.run_id}-ledger.json`,runId:t.run_id})},children:s.jsx(ur,{icon:"file",label:"Ledger (JSON)"})}):null,t.workspace_url&&e.onOpenWorkspace?s.jsx("button",{type:"button",className:"af-auto__btn","data-action":"open-workspace",title:"Browse this run's folder",onClick:()=>{var w;return(w=e.onOpenWorkspace)==null?void 0:w.call(e,t.run_id)},children:s.jsx(ur,{icon:"folder",label:"Workspace"})}):null]})]}),e.discussOpen?s.jsxs("form",{className:"af-auto-discuss","aria-label":`${bp}, from occurrence ${t.index}`,onSubmit:w=>{w.preventDefault();const x=jp(w.currentTarget,"prompt");x&&e.onDiscussSubmit(t.index,x)},children:[s.jsxs("p",{className:"af-auto__hint",children:["Starts a new session that forks this automation at #",t.index," with its full history (runs 1–",t.index,"). It works in its own writable workspace; the automation's files are mounted read-only for the file tools (shell commands are not sandboxed), and nothing is written back into the automation's session."]}),s.jsx("textarea",{name:"prompt",rows:3,"aria-label":"Your message",placeholder:"Ask about this result…",required:!0}),s.jsxs("div",{className:"af-auto__row",children:[s.jsx("button",{type:"submit",className:"af-auto__btn af-auto__btn--primary","data-action":"discuss-submit",disabled:e.busy,children:s.jsx(ur,{icon:"send",label:"Start discussion"})}),s.jsx("button",{type:"button",className:"af-auto__btn","data-action":"discuss-cancel",onClick:e.onDiscussCancel,children:s.jsx(ur,{icon:"x",label:"Cancel"})})]})]}):s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"af-auto__btn af-auto__btn--quiet","data-action":"discuss",disabled:!c,title:kp.discuss,"aria-description":kp.discuss,"aria-describedby":f?`${l}-discuss-why`:void 0,onClick:()=>e.onDiscussOpen(t.index),children:s.jsx(ur,{icon:Bi.discuss,label:bp})}),f?s.jsx("span",{className:"af-auto__reasons",id:`${l}-discuss-why`,children:f}):null]})]})]})}const TS=5e3,MS={[ko.pause]:"Automation paused.",[ko.resume]:"Automation active.",[ko.run_now]:"Run requested.",[ko.stop_current]:"Stop requested."};function RS(e){var ie;const{summary:t,busy:n}=e,r=e.renderText??Am,o=p.useId(),l=p.useRef(null),[u,c]=p.useState(!1),f=e.editOpen!==void 0,_=om(t,e.occurrences,!1).revise.enabled&&(f?e.editOpen===!0:u),g=p.useRef(null);_?(!g.current||g.current.summary.automation_id!==t.automation_id)&&(g.current={summary:t,definition:e.definition}):g.current=null;const w=g.current,x=p.useRef(e.onEditOpenChange);x.current=e.onEditOpenChange;const j=ne=>{var ye;f||c(ne),(ye=x.current)==null||ye.call(x,ne)},[b,N]=p.useState([]),[C,E]=p.useState(!1),[T,I]=p.useState(null),[K,U]=p.useState(null),[J,Y]=p.useState(null);p.useEffect(()=>{if(!J)return;const ne=setTimeout(()=>Y(null),TS);return()=>clearTimeout(ne)},[J]),p.useEffect(()=>{var ye;if(!_)return;N([]);const ne=by(l.current,['.af-auto__revise [name="title"]']);ne==null||ne.focus(),(ye=ne==null?void 0:ne.scrollIntoView)==null||ye.call(ne,{block:"nearest"})},[_,t.automation_id]);const[re,ce]=p.useState(null);p.useEffect(()=>{var ne;re&&((ne=by(l.current,[...re,".af-auto__notice",".af-auto__title"]))==null||ne.focus(),ce(null))},[re]);const fe=p.useRef(null);fe.current||(fe.current=new Gj(e.newId??Yj));const W=fe.current,O=ne=>U(wS(ne)),$=(ne,ye,he)=>{U(null),Y(null),ye(W.idFor(ne)).then(pe=>{W.settle(ne,{ok:!0}),he(pe)},pe=>{W.settle(ne,{ok:!1,error:pe}),O(pe)})},z=Pj(t),A=p.useRef(e.onSeen);A.current=e.onSeen;const ee=p.useRef(null);ee.current||(ee.current=new Jj),p.useEffect(()=>{const ne=ee.current,ye=z?`${t.automation_id}|${z}`:null;if(!z||!ne.next(ye,t))return;const he=t;A.current(z).then(()=>ne.succeeded(ye),pe=>{ne.failed(ye,he),O(pe)})});const P=om(t,e.occurrences,n),F=Oj(e.occurrences),G=t.occurrence_count-e.occurrences.length,R=K??e.error??null,Z=R?am(R):null,X=t.attention;return s.jsxs("section",{ref:l,className:`af-auto${e.className?` ${e.className}`:""}`,"aria-labelledby":o,"aria-busy":n,"data-text-rendering":e.renderText?"rich":"unformatted",children:[s.jsx(xS,{summary:t,workflowLabel:(ie=e.definition)==null?void 0:ie.target.workflow_id,triggerSources:e.triggerSources,titleId:o,nowMs:e.nowMs,onOpenWorkspace:e.onOpenWorkspace}),s.jsx(NS,{summary:t,occurrences:e.occurrences,busy:n,confirmingArchive:C,reviseOpen:_,notice:J,onDismissNotice:()=>Y(null),idBase:`${o}-ctl`,onCommand:ne=>$(`command:${ne}`,ye=>e.onCommand(ne,void 0,{command_id:ye}),()=>{ne===ko.archive?(E(!1),Y("Archive requested."),ce(['[data-action="archive"]'])):Y(MS[ne]??"Command sent.")}),onToggleRevise:()=>{N([]),j(!_)},onAskArchive:()=>E(!0),onCancelArchive:()=>{E(!1),ce(['[data-action="archive"]'])}}),_&&w?s.jsx(ES,{summary:w.summary,definition:w.definition,busy:n,errors:b,availableTools:e.availableTools,workflowPickerOptions:e.workflowPickerOptions,emailStatus:e.emailStatus,onOpenMyEmail:e.onOpenMyEmail,onCancel:()=>{j(!1),ce(['[data-action="edit"]'])},onSubmit:ne=>{const ye=w.summary,he=Fj(ye,ne,w.definition);if(he===null){N(["Nothing changed."]);return}if("errors"in he){N(he.errors);return}N([]),$(`revise:${ye.revision}:${JSON.stringify(he)}`,async pe=>{const Ne=ne.target&&he.target?{...he,target:await(e.prepareTarget?e.prepareTarget(he.target):_S(he.target,e.workflowPickerOptions))}:he;return e.onRevise(Ne,ye.revision,{command_id:pe})},()=>{Y("Saved; applies from the next run."),j(!1),ce(['[data-action="edit"]'])})}}):e.definition?s.jsx(bS,{definition:e.definition,renderText:r}):null,Z?s.jsxs("div",{className:"af-auto__error",role:"alert","data-code":R==null?void 0:R.code,children:[s.jsx(et,{name:"error",size:14,className:"af-auto__btn-icon"}),s.jsxs("span",{className:"af-auto__error-text",children:[s.jsx("strong",{children:Z.title})," ",s.jsx("span",{children:Z.detail})]}),K?s.jsx("button",{type:"button",className:"af-auto__icon-btn af-auto__icon-btn--bare","data-action":"dismiss-error","aria-label":"Dismiss",title:"Dismiss",onClick:()=>U(null),children:s.jsx(et,{name:"x",size:12})}):null]}):null,X.items.length||X.waits.length?s.jsx("section",{className:"af-auto__attention","aria-label":"Needs attention",children:s.jsxs("ul",{children:[X.items.map(ne=>s.jsxs("li",{className:`af-auto__attention-item af-auto__attention-item--${ne.kind}`,"data-cursor":ne.cursor,children:[s.jsx("span",{className:`af-auto-badge af-auto-badge--${ne.kind==="failure"?"failed":"notified"}`,children:ne.kind==="failure"?"Failed":"Notified"})," ",s.jsx("strong",{children:ne.title})," ",s.jsxs("span",{className:"af-auto-turn__muted",children:["#",ne.index," · ",la(ne.at)]}),ne.body?s.jsx("div",{className:"af-auto__attention-body",children:r(ne.body)}):null]},ne.cursor)),X.waits.map(ne=>s.jsxs("li",{className:"af-auto__attention-item af-auto__attention-item--wait",children:[s.jsx("span",{className:"af-auto-badge af-auto-badge--waiting","data-wait-kind":ne.kind,children:Qv[ne.kind]??"Waiting for you"})," ",s.jsxs("span",{className:"af-auto-turn__muted",children:["#",ne.index]}),ne.prompt?s.jsx("div",{className:"af-auto__attention-body",children:r(ne.prompt)}):null]},`${ne.run_id}:${ne.wait_key}`))]})}):null,G>0?s.jsx("button",{type:"button",className:"af-auto__btn af-auto__more","data-action":"load-more",disabled:n,onClick:e.onLoadMore,children:s.jsx(ur,{icon:"history",label:`Load earlier occurrences (${G} more)`})}):null,F.length?s.jsx("ol",{className:"af-auto__timeline","aria-label":"Occurrences",children:F.map(ne=>{const ye=`[data-index="${ne.row.index}"]`;return s.jsx($S,{view:ne,busy:n,discuss:P.discuss,renderText:r,renderTurn:e.renderTurn,onOpenWorkspace:e.onOpenWorkspace,onOpenResource:e.onOpenResource?he=>{var pe;U(null);try{Promise.resolve((pe=e.onOpenResource)==null?void 0:pe.call(e,he)).catch(O)}catch(Ne){O(Ne)}}:void 0,discussOpen:T===ne.row.index,onOpenRun:e.onOpenRun,onAnswerWait:(he,pe,Ne)=>{U(null),e.onAnswerWait(he,pe,Ne).then(()=>Y("Answer sent."),O)},onWaitError:he=>U({status:0,code:"invalid_payload",message:he}),onDiscussOpen:I,onDiscussCancel:()=>{I(null),ce([`${ye} [data-action="discuss"]`])},onDiscussSubmit:(he,pe)=>$(`discuss:${he}:${pe}`,Ne=>e.onDiscuss(he,pe,{request_id:Ne}),Ne=>{I(null),Y(`Discussion started (session ${Ne.session_id}).`),ce([`${ye} [data-action="discuss"]`])})},ne.row.run_id)})}):s.jsx("p",{className:"af-auto__empty",children:"No occurrences yet."})]})}function $m(e){const t=String(e??"").trim();if(!t||!(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]")))return null;try{return JSON.parse(t)}catch{return null}}function LS(e){if(e==null)return"";if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}}function IS(e){const t=String(e.role||"message").trim()||"message",n=String(e.title||"").trim(),r=String(e.ts||"").trim(),o=[t];return n&&o.push(n),r&&o.push(r),o.join(" · ")}function OS(e){return e.endsWith(`
58
- `)?e:`${e}
59
- `}function PS(e){return String(e||"").trimStart().startsWith("```")}function DS(e,t){const r=[`# ${String((t==null?void 0:t.heading)||"Chat").trim()||"Chat"}`,""];for(const o of e){const l=IS(o);r.push(`## ${l}`,"");const u=String(o.content||""),c=$m(u);c!==null&&!PS(u)?r.push("```json",LS(c).trimEnd(),"```",""):r.push(OS(u).trimEnd(),""),r.push("---","")}for(;r.length&&!r[r.length-1].trim();)r.pop();return r.length&&r[r.length-1]==="---"&&r.pop(),`${r.join(`
60
- `).trimEnd()}
61
- `}async function ic(e){var n;const t=String(e||"");if(!t)return!1;try{if(typeof navigator<"u"&&typeof((n=navigator.clipboard)==null?void 0:n.writeText)=="function")return await navigator.clipboard.writeText(t),!0}catch{}try{const r=document.createElement("textarea");r.value=t,r.style.position="fixed",r.style.left="-9999px",document.body.appendChild(r),r.select();const o=document.execCommand("copy")===!0;return document.body.removeChild(r),o}catch{return!1}}function FS(e){const t=String(e.filename||"").trim()||"export.txt",n=String(e.text||""),r=String(e.mime),o=new Blob([n],{type:r}),l=URL.createObjectURL(o),u=document.createElement("a");u.href=l,u.download=t,document.body.appendChild(u),u.click(),u.remove(),window.setTimeout(()=>URL.revokeObjectURL(l),1e3)}const zS=3,BS=Number.MAX_SAFE_INTEGER;function lx(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function cx(e){return Array.isArray(e)}function US(e){if(e==null)return"";if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}}function fu({kind:e,children:t}){return s.jsx("span",{className:`pc-json-token ${e}`,children:t})}function WS(e){const t=JSON.stringify(e.value),n=t.length>96||t.includes("\\n")||t.includes("\\r")||t.includes("\\t"),[r,o]=p.useState(!n||e.expansionMode==="unfolded");return p.useEffect(()=>{n&&o(e.expansionMode==="unfolded")},[n,e.expansionMode,e.expansionVersion]),n?s.jsxs("span",{className:`pc-json-string ${r?"open":"collapsed"}`,children:[s.jsx("button",{type:"button",className:"pc-json-string__toggle",onClick:()=>o(l=>!l),"aria-label":r?"Collapse string value":"Expand string value","aria-expanded":r,children:r?"▾":"▸"}),r?s.jsx("span",{className:"pc-json-token string pc-json-string__value",children:t}):s.jsxs("button",{type:"button",className:"pc-json-string__preview",onClick:()=>o(!0),"aria-label":"Expand string value",children:[s.jsx("span",{className:"pc-json-token string pc-json-string__preview_text",children:t}),s.jsx("span",{className:"pc-json-string__suffix",children:"(...)"})]})]}):s.jsx(fu,{kind:"string",children:t})}function qS(e,t,n){return e===null?s.jsx(fu,{kind:"null",children:"null"}):typeof e=="string"?s.jsx(WS,{value:e,expansionMode:t,expansionVersion:n}):typeof e=="number"?s.jsx(fu,{kind:"number",children:String(e)}):typeof e=="boolean"?s.jsx(fu,{kind:"boolean",children:e?"true":"false"}):s.jsx(fu,{kind:"string",children:JSON.stringify(String(e))})}function HS(e){return cx(e)?e.length===1?"1 item":`${e.length} items`:lx(e)?Object.keys(e).length===1?"1 key":`${Object.keys(e).length} keys`:""}function ux(e){const{label:t,value:n,depth:r,collapseAfterDepth:o,expansionMode:l,expansionVersion:u,trailingComma:c}=e,f=r*14,m=lx(n),_=cx(n),g=m||_,w=r<o,[x,j]=p.useState(w);p.useEffect(()=>{j(w)},[w,u]);const b=t?s.jsxs(s.Fragment,{children:[s.jsx(fu,{kind:"key",children:JSON.stringify(t)}),": "]}):null;if(!g)return s.jsxs("div",{className:"pc-json-viewer__line",style:{paddingLeft:f},children:[b,qS(n,l,u),c?",":""]});const N=_?"[":"{",C=_?"]":"}",E=HS(n),T=x?`${N}`:`${N}…${C}${E?` (${E})`:""}`,I=_?n.map((K,U)=>({key:String(U),label:void 0,value:K})):Object.entries(n).map(([K,U])=>({key:K,label:K,value:U}));return s.jsxs("details",{className:"pc-json-viewer__details",open:x,onToggle:K=>j(K.currentTarget.open),children:[s.jsxs("summary",{className:"pc-json-viewer__summary",style:{paddingLeft:f},children:[b,s.jsx("span",{className:"pc-json-viewer__caret","aria-hidden":"true",children:x?"▾":"▸"}),s.jsx("span",{className:"pc-json-viewer__punct",children:T}),!x&&c?s.jsx("span",{className:"pc-json-viewer__punct",children:","}):null]}),x?s.jsx("div",{className:"pc-json-viewer__children",children:I.length===0?s.jsxs("div",{className:"pc-json-viewer__line",style:{paddingLeft:f},children:[s.jsx("span",{className:"pc-json-viewer__punct",children:C}),c?",":""]}):s.jsxs(s.Fragment,{children:[I.map((K,U)=>{const J=U===I.length-1;return s.jsx(ux,{label:K.label,value:K.value,depth:r+1,collapseAfterDepth:o,expansionMode:l,expansionVersion:u,trailingComma:!J},`${r}:${t||"root"}:${K.key}`)}),s.jsxs("div",{className:"pc-json-viewer__line",style:{paddingLeft:f},children:[s.jsx("span",{className:"pc-json-viewer__punct",children:C}),c?",":""]})]})}):null]})}function VS(e){const t=e.trim();if(!t)return e;if(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))try{return JSON.parse(t)}catch{return e}return e}function Is(e){const{value:t,className:n,showCopy:r=!0}=e,[o,l]=p.useState({mode:"folded",version:0}),[u,c]=p.useState("idle"),f=typeof e.collapseAfterDepth=="number"&&(Number.isFinite(e.collapseAfterDepth)||e.collapseAfterDepth===1/0)&&e.collapseAfterDepth>=0?e.collapseAfterDepth===1/0?Number.MAX_SAFE_INTEGER:Math.trunc(e.collapseAfterDepth):zS,m=o.mode==="unfolded"?BS:f,_=p.useMemo(()=>typeof t=="string"?VS(t):t,[t]),g=p.useMemo(()=>US(t),[t]),w=["pc-json-viewer",n].filter(Boolean).join(" ");p.useEffect(()=>{l(j=>({mode:"folded",version:j.version+1}))},[_]);const x=()=>{l(j=>({mode:j.mode==="unfolded"?"folded":"unfolded",version:j.version+1}))};return s.jsxs("div",{className:w,children:[s.jsxs("div",{className:"pc-json-viewer__toolbar",children:[s.jsx("button",{type:"button",className:"pc-btn pc-json-viewer__toggle-all",onClick:x,"aria-expanded":o.mode==="unfolded",children:o.mode==="unfolded"?"Fold all":"Unfold all"}),r?s.jsx("button",{type:"button",className:"pc-btn pc-json-viewer__copy",onClick:()=>void ic(g).then(j=>{c(j?"copied":"failed"),window.setTimeout(()=>c("idle"),2e3)}),children:u==="copied"?"Copied":u==="failed"?"Copy failed — select and copy":"Copy JSON"}):null]}),s.jsx("div",{className:"pc-json-viewer__tree",role:"tree","aria-label":"JSON viewer",children:s.jsx(ux,{value:_,depth:0,collapseAfterDepth:m,expansionMode:o.mode,expansionVersion:o.version,trailingComma:!1})})]})}function Ud(e,t){const n=String(e??"");if(!t||!t.needles.length)return[n];const r=[],o=n.toLowerCase();let l=0;for(;l<n.length;){let u=-1,c="";for(let _=0;_<t.needlesLower.length;_++){const g=t.needlesLower[_];if(!g)continue;const w=o.indexOf(g,l);if(w===-1)continue;const x=t.needles[_]||"";x&&(u===-1||w<u||w===u&&x.length>c.length)&&(u=w,c=x)}if(u===-1||!c){r.push(n.slice(l));break}u>l&&r.push(n.slice(l,u));const f=t.hits===0&&t.id?t.id:void 0,m=n.slice(u,u+c.length);r.push(s.jsx("span",{id:f,className:t.className,children:m},`hl:${t.hits}`)),t.hits+=1,l=u+c.length}return r}function dx(e){const t=String(e||"").trim();if(t&&/^(https?:|mailto:|tel:|#|\/)/i.test(t))return t}const Sp="http://same-origin.invalid/";function GS(e){try{const t=new URL(e,Sp);return t.protocol==="http:"&&t.origin===new URL(Sp).origin}catch{return!1}}function fx(e){const t=String(e||"").trim();return dx(t)??(t&&GS(t)?t:void 0)}let Zl=null;function KS(e){const t=String(e||"").trim();if(!t)return!1;const n=typeof document<"u"&&document.baseURI?document.baseURI:null;if(n===null&&/^[a-z][a-z0-9+.-]*:/i.test(t))return!1;const r=n??Sp;let o,l;try{o=new URL(r).origin,l=new URL(t,r)}catch{return!1}return l.protocol!=="http:"&&l.protocol!=="https:"?!1:l.origin===o}function hx(e,t,n){return s.jsx("a",{className:"pc-md_link pc-md_image_link",href:t,target:"_blank",rel:"noopener noreferrer",children:`image: ${n||t}`},e)}function sl(e,t){const n=[],r=String(e??"");let o=0,l="";const u=()=>{if(l){for(const c of Ud(l,t))n.push(c);l=""}};for(;o<r.length;){const c=r[o];if(c==="!"&&r[o+1]==="["){const f=r.indexOf("]",o+2);if(f!==-1&&r[f+1]==="("){const m=r.indexOf(")",f+2);if(m!==-1){const _=r.slice(o+2,f),g=fx(r.slice(f+2,m));if(g&&Zl&&!Zl(g)){u(),n.push(hx(`img:${o}`,g,_)),o=m+1;continue}if(g){u(),n.push(s.jsxs("span",{className:"pc-md_image_inline",children:[s.jsx("img",{className:"pc-md_img",src:g,alt:_,loading:"lazy"}),_?s.jsx("span",{className:"pc-md_img_caption",children:t?Ud(_,t):_}):null]},`img:${o}`)),o=m+1;continue}}}}if(c==="["){const f=r.indexOf("]",o+1);if(f!==-1&&r[f+1]==="("){const m=r.indexOf(")",f+2);if(m!==-1){const _=r.slice(o+1,f),g=dx(r.slice(f+2,m));if(g){u(),n.push(s.jsx("a",{className:"pc-md_link",href:g,target:g.startsWith("#")?void 0:"_blank",rel:"noreferrer",children:sl(_,t)},`link:${o}`)),o=m+1;continue}}}}if(c==="`"){const f=r.indexOf("`",o+1);if(f!==-1){u();const m=r.slice(o+1,f);n.push(s.jsx("code",{children:t?Ud(m,t):m},`code:${o}`)),o=f+1;continue}}if(c==="*"&&r[o+1]==="*"){const f=r.indexOf("**",o+2);if(f!==-1){u();const m=r.slice(o+2,f);n.push(s.jsx("strong",{children:t?Ud(m,t):m},`bold:${o}`)),o=f+2;continue}}if(c==="*"&&r[o+1]!=="*"){const f=r.indexOf("*",o+1);if(f!==-1){u();const m=r.slice(o+1,f);n.push(s.jsx("em",{children:t?Ud(m,t):m},`em:${o}`)),o=f+1;continue}}l+=c,o+=1}return u(),n}function YS(e){return String(e??"").replace(/\r\n/g,`
62
- `).replace(/\r/g,`
63
- `).split(`
64
- `)}function Xh(e){const n=String(e??"").match(/^([ \t]*)(?:([-*+])|(\d{1,9})[.)])\s+(.*)$/);return n?{indent:n[1].replace(/\t/g," ").length,ordered:!!n[3],start:n[3]?Math.max(1,parseInt(n[3],10)||1):1,content:n[4]??""}:null}function JS(e){const t=[];for(const o of e){const l=Xh(o);l?t.push(l):t.length>0&&o.trim()&&(t[t.length-1].content+=` ${o.trim()}`)}const n=[],r=[];for(const o of t){for(;r.length>0&&o.indent<r[r.length-1].indent;)r.pop();let l=r.length>0?r[r.length-1]:null;if(l&&o.indent>l.indent){const u=l.node.items,c=u[u.length-1];if(c){const f={ordered:o.ordered,start:o.start,items:[]};c.children.push(f),r.push({indent:o.indent,node:f}),l=r[r.length-1]}}else if(l&&l.node.ordered!==o.ordered){r.pop();const u=r.length>0?r[r.length-1]:null,c={ordered:o.ordered,start:o.start,items:[]};if(u){const f=u.node.items,m=f[f.length-1];m?m.children.push(c):u.node.items.push({content:"",children:[c]})}else n.push(c);r.push({indent:o.indent,node:c}),l=r[r.length-1]}if(!l){const u={ordered:o.ordered,start:o.start,items:[]};n.push(u),r.push({indent:o.indent,node:u}),l=r[r.length-1]}l.node.items.push({content:o.content,children:[]})}return n}function mx(e,t,n){const r=e.items.map((o,l)=>s.jsxs("li",{children:[sl(o.content,t),o.children.map((u,c)=>mx(u,t,`${n}:${l}:${c}`))]},`${n}:li:${l}`));return e.ordered?s.jsx("ol",{className:"pc-md_ol",start:e.start!==1?e.start:void 0,children:r},n):s.jsx("ul",{className:"pc-md_ul",children:r},n)}function XS(e,t,n){return JS(e).map((r,o)=>mx(r,t,`${n}:${o}`))}function Ny(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 Cy(e){let t=String(e??"").trim();if(!t)return!1;t.startsWith("|")&&(t=t.slice(1)),t.endsWith("|")&&(t=t.slice(0,-1));const n=t.split("|").map(r=>String(r??"").trim());return n.length<2?!1:n.every(r=>/^:?-{3,}:?$/.test(r))}const Ey=/^(#{1,5})\s+(.*)$/;function Ay(e){return e.trim().startsWith("```")}function $y(e){return e.trimStart().startsWith(">")}function qi(e){const t=Zl;Zl=e.images==="link"?e.inlineImage||KS:null;try{return ZS(e)}finally{Zl=t}}function ZS({text:e,className:t,highlight:n,highlights:r,highlightClassName:o,highlightId:l}){const u=YS(e),c=[],f=[];Array.isArray(r)&&f.push(...r),typeof n=="string"&&n.trim()&&f.push(n);const m=Array.from(new Set(f.map(x=>String(x??"").trim()).filter(Boolean))).filter(x=>x.length>=4),_=m.length?{needles:m,needlesLower:m.map(x=>x.toLowerCase()),className:o||"pc-md_hl",id:l,hits:0}:null;let g=0;for(;g<u.length;){const x=String(u[g]??"");if(!x.trim()){g+=1;continue}const j=x.trim();if(/^([-_*])(\s*\1){2,}$/.test(j)){c.push(s.jsx("hr",{className:"pc-md_hr"},`hr:${g}`)),g+=1;continue}const b=x.match(/^\s*!\[([^\]]*)\]\(([^)]+)\)\s*$/);if(b){const E=fx(b[2]||"");if(E&&Zl&&!Zl(E)){c.push(s.jsx("p",{className:"pc-md_p",children:hx(`img:${g}`,E,b[1]||"")},`p:${g}`)),g+=1;continue}if(E){const T=b[1]||"";c.push(s.jsxs("figure",{className:"pc-md_figure",children:[s.jsx("img",{className:"pc-md_img",src:E,alt:T,loading:"lazy"}),T?s.jsx("figcaption",{children:sl(T,_)}):null]},`figure:${g}`)),g+=1;continue}}if(Ay(x)){const T=x.trim().replace(/```/g,"").trim(),I=[];for(g+=1;g<u.length&&!String(u[g]??"").trim().startsWith("```");)I.push(String(u[g]??"")),g+=1;g<u.length&&(g+=1);const K=I.join(`
65
- `);c.push(s.jsx("pre",{className:"pc-md_pre",children:s.jsx("code",{className:T?`language-${T}`:void 0,children:K})},`pre:${g}`));continue}const N=x.match(Ey);if(N){const E=N[1].length,T=N[2]||"",I=sl(T,_);E===1?c.push(s.jsx("h1",{children:I},`h1:${g}`)):E===2?c.push(s.jsx("h2",{children:I},`h2:${g}`)):E===3?c.push(s.jsx("h3",{children:I},`h3:${g}`)):E===4?c.push(s.jsx("h4",{children:I},`h4:${g}`)):c.push(s.jsx("h5",{children:I},`h5:${g}`)),g+=1;continue}if($y(x)){const E=[];for(;g<u.length&&String(u[g]??"").trimStart().startsWith(">");){const I=String(u[g]??"").trimStart();E.push(I.replace(/^>\s?/,"")),g+=1}c.push(s.jsx("blockquote",{className:"pc-md_quote",children:E.map((T,I)=>s.jsxs(ve.Fragment,{children:[sl(T,_),I<E.length-1?s.jsx("br",{}):null]},`q:${g}:${I}`))},`quote:${g}`));continue}if(x.includes("|")&&g+1<u.length&&Cy(String(u[g+1]??""))){const E=Ny(x),T=Math.max(1,E.length),I=[];for(g+=2;g<u.length;){const K=String(u[g]??"");if(!K.trim()||!K.includes("|"))break;const U=Ny(K),J=[];for(let Y=0;Y<T;Y++)J.push(U[Y]??"");I.push(J),g+=1}c.push(s.jsx("div",{className:"pc-md_table_wrap",children:s.jsxs("table",{className:"pc-md_table",children:[s.jsx("thead",{children:s.jsx("tr",{children:E.slice(0,T).map((K,U)=>s.jsx("th",{children:sl(K,_)},`th:${g}:${U}`))})}),s.jsx("tbody",{children:I.map((K,U)=>s.jsx("tr",{children:K.map((J,Y)=>s.jsx("td",{children:sl(J,_)},`td:${g}:${U}:${Y}`))},`tr:${g}:${U}`))})]})},`table:${g}`));continue}if(Xh(x)){const E=[];for(;g<u.length;){const T=String(u[g]??"");if(!T.trim()||T.trimStart().startsWith("```"))break;if(Xh(T)||/^\s{2,}\S/.test(T)){E.push(T),g+=1;continue}break}c.push(s.jsx(ve.Fragment,{children:XS(E,_,`list:${g}`)},`list:${g}`));continue}const C=[];for(;g<u.length&&String(u[g]??"").trim()&&!(C.length>0&&Xh(String(u[g]??"")));){const E=String(u[g]??"");if(C.length>0&&(Ey.test(E)||Ay(E)||$y(E))||C.length>0&&E.includes("|")&&g+1<u.length&&Cy(String(u[g+1]??"")))break;C.push(E),g+=1}c.push(s.jsx("p",{className:"pc-md_p",children:C.map((E,T)=>s.jsxs(ve.Fragment,{children:[sl(E,_),T<C.length-1?s.jsx("br",{}):null]},`pl:${g}:${T}`))},`p:${g}`))}const w=["pc-md",t].filter(Boolean).join(" ");return s.jsx("div",{className:w,children:c})}function _x(e){const t=String(e.text??""),n=p.useMemo(()=>$m(t),[t]),r=["pc-chat-content",e.className].filter(Boolean).join(" ");return n!==null?s.jsx("div",{className:r,children:s.jsx(Is,{value:n,collapseAfterDepth:e.jsonCollapseAfterDepth})}):e.renderMarkdown?s.jsx("div",{className:r,children:e.renderMarkdown(t)}):s.jsx("div",{className:r,children:s.jsx(qi,{text:t,images:e.images,inlineImage:e.inlineImage})})}function px(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}}function QS(e){const t=px(e);if(!t||typeof t!="object"||Array.isArray(t))return{label:"input",value:t==null?"":String(t)};const n=Object.entries(t),o=["command","query","url","file_path","path","pattern","name"].map(l=>n.find(([u])=>u===l)).find(Boolean)||n[0];return o?{label:o[0].replace(/_/g," "),value:typeof o[1]=="string"?o[1]:JSON.stringify(o[1])??""}:{label:"",value:""}}function gx({tool:e,showCopy:t=!0}){const[n,r]=p.useState(!1),o=px(e.arguments),l=QS(e.arguments),u=["file path","path"].includes(l.label)&&l.value.length>60?`${l.value.split(/[\\/]/).pop()} · ${l.value.slice(0,24)}…`:l.value,c=e.error&&/^File ['"].+['"] does not exist\.?$/.test(e.error)?"File not found. Expand for the exact path.":e.error&&e.error.length>180?`${e.error.slice(0,100)}…${e.error.slice(-70)}`:e.error,f={running:"Running",waiting:"Approval needed",completed:"Done",failed:"Failed"},m=e.startedAt&&e.endedAt?Date.parse(e.endedAt)-Date.parse(e.startedAt):NaN,_=o&&typeof o=="object"&&!Array.isArray(o)?Object.entries(o):null;return s.jsxs("details",{className:`pc-tool-activity pc-tool-activity--${e.status}`,children:[s.jsxs("summary",{className:"pc-tool-activity__summary",children:[s.jsx("span",{className:"pc-tool-activity__state-icon","aria-hidden":"true",children:s.jsx(et,{name:e.status==="completed"?"check":e.status==="failed"?"x":e.status==="waiting"?"warning":"loader",size:15})}),s.jsx("strong",{children:e.name}),s.jsx("span",{className:"pc-tool-activity__preview",title:l.value,children:l.value?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"pc-tool-activity__key",children:l.label}),u]}):"No parameters"}),s.jsx("span",{className:"pc-tool-activity__status",children:f[e.status]}),Number.isFinite(m)&&m>=0?s.jsxs("span",{className:"pc-tool-activity__duration",children:[(m/1e3).toFixed(1),"s"]}):null,s.jsx("span",{className:"pc-tool-activity__chevron","aria-hidden":"true",children:s.jsx(et,{name:"chevronRight",size:13})}),e.error?s.jsx("span",{className:"pc-tool-activity__error",title:e.error,children:c}):null]}),s.jsxs("div",{className:"pc-tool-activity__detail",children:[e.error?s.jsxs(s.Fragment,{children:[s.jsx("h4",{children:"Error"}),s.jsx("pre",{className:"pc-tool-activity__output",children:e.error})]}):null,s.jsxs("div",{className:"pc-tool-activity__detail-heading",children:[s.jsx("h4",{children:"Parameters"}),t?s.jsxs("button",{type:"button",onClick:async()=>r(await ic(JSON.stringify(e,null,2))),children:[s.jsx(et,{name:"copy",size:13}),n?"Copied":"Copy details"]}):null]}),_?s.jsx("dl",{className:"pc-tool-activity__parameters",children:_.map(([g,w])=>s.jsxs(ve.Fragment,{children:[s.jsx("dt",{children:g}),s.jsx("dd",{children:w&&typeof w=="object"?s.jsx(Is,{value:w}):s.jsx("code",{children:typeof w=="string"?w:JSON.stringify(w)})})]},g))}):e.arguments===void 0?s.jsx("p",{children:"Arguments are unavailable in this ledger."}):s.jsx(Is,{value:o}),e.output!==void 0?s.jsxs(s.Fragment,{children:[s.jsx("h4",{children:"Result"}),typeof e.output=="string"?s.jsx("pre",{className:"pc-tool-activity__output",children:e.output}):s.jsx("div",{className:"pc-tool-activity__output",children:s.jsx(Is,{value:e.output})})]}):null]})]})}function yx({tools:e,showCopy:t}){const n=r=>e.filter(o=>o.status===r).length;return s.jsxs("section",{className:"pc-tool-group","aria-label":"Tool activity",children:[s.jsxs("div",{className:"pc-tool-group__heading",children:[s.jsx(et,{name:"terminal",size:14}),s.jsx("strong",{children:"Tools"}),s.jsxs("span",{children:[e.length," ",e.length===1?"call":"calls"]}),s.jsx("div",{}),n("running")?s.jsxs("span",{className:"pc-tool-group__running",children:[n("running")," running"]}):null,n("waiting")?s.jsxs("span",{className:"pc-tool-group__waiting",children:[n("waiting")," need approval"]}):null,n("failed")?s.jsxs("span",{className:"pc-tool-group__failed",children:[n("failed")," failed"]}):null,n("completed")?s.jsxs("span",{className:"pc-tool-group__completed",children:[n("completed")," done"]}):null]}),e.map(r=>s.jsx(gx,{tool:r,showCopy:t},r.id))]})}const Gs="not reported",Sr=e=>e===void 0?Gs:Math.round(e).toLocaleString(),Br=e=>{if(e===void 0)return Gs;if(e<6e4)return`${(e/1e3).toFixed(1)}s`;const t=Math.round(e/1e3);return`${Math.floor(t/60)}m ${String(t%60).padStart(2,"0")}s`},wx=e=>e===void 0?Gs:`${Math.round(e).toLocaleString()} tok/s`,e1=(e,t)=>t>0?`${Math.round(e/t*100)}%`:"",Ql=(e,t,n=`${t}s`)=>`${e.toLocaleString()} ${e===1?t:n}`,t1=e=>{const t=e.split("#")[0].replace(/\/+$/,"");return t.slice(t.lastIndexOf("/")+1)||e};function n1(e){const t=new Map;for(const n of e)n&&t.set(n,(t.get(n)||0)+1);return[...t].map(([n,r])=>r>1?`${n} ×${r}`:n).join(" · ")}function cm(e){const t=[],n=(e.models||[]).map(t1),r=e.providers||[];return(n.length||r.length)&&t.push([n.join(", ")||"model not reported",r.join(", ")].filter(Boolean).join(" · ")),t.push("From the run ledger; summed across this turn and its child runs."),t}function s1(e){const t=e.modelCalls||[],n=[],r=[{label:"Input",value:Sr(e.inputTokens)},{label:"Output",value:Sr(e.outputTokens)}];if(e.reasoningTokens!==void 0&&r.push({label:"Reasoning",value:Sr(e.reasoningTokens),hint:"part of output"}),r.push({label:"Total",value:Sr(e.totalTokens)}),n.push({heading:`Usage · ${Ql(e.llmCalls,"model call")}`,rows:r}),e.measuredCacheCalls){const l=e.cachedTokens||0,u=e.fedTokens||0,c=[{label:"Reused from cache",value:`${Sr(l)}${l+u?` (${e1(l,l+u)})`:""}`},{label:"Newly processed",value:Sr(e.fedTokens)},{label:"Outcome",value:n1(t.map(f=>f.cacheOutcome))||(e.cacheOutcomes||[]).join(" · ")||Gs},{label:"Backend",value:(e.cacheBackends||[]).join(", ")||Gs}];e.measuredCacheCalls!==e.llmCalls&&c.push({label:"Measured on",value:`${e.measuredCacheCalls} of ${e.llmCalls} calls`}),n.push({heading:"Prompt cache",rows:c})}else e.llmCalls&&n.push({heading:"Prompt cache",rows:[{label:"Cache reuse",value:Gs}]});const o=t.filter(l=>l.inputTokens!==void 0);return o.length===1&&t.length===1?n.push({heading:"Context",rows:[{label:"Prompt size",value:`${Sr(o[0].inputTokens)} tokens`}]}):o.length>1&&n.push({heading:"Context",rows:[{label:"First → last call",value:`${Sr(o[0].inputTokens)} → ${Sr(o[o.length-1].inputTokens)} tokens`}],note:"Each call re-sends the conversation, so the input total counts the context once per call."}),t.length>1&&n.push({heading:"Per call",table:{columns:["#","Input","Cached","New","Output","Cache"],rows:t.map((l,u)=>[String(u+1),Sr(l.inputTokens),l.cachedTokens===void 0?"—":Sr(l.cachedTokens),l.fedTokens===void 0?"—":Sr(l.fedTokens),Sr(l.outputTokens),l.cacheOutcome||"—"])}}),{kind:"tokens",title:"Tokens",headline:e.totalTokens===void 0?Gs:`${e.totalTokens.toLocaleString()} total`,sections:n,footer:cm(e)}}function Eh(e,t,n,r){if(e===void 0)return Gs;const o=[Br(e)];return t!==void 0&&o.push(`${t.toLocaleString()} ${r}${n!==void 0?` at ${wx(n)}`:""}`),o.join(" · ")}function r1(e){var m,_,g;const t=e.modelCalls||[],n=[],r=e.durationMs,o=[{label:"Wall clock",value:Br(r)}];if(o.push({label:"Model",value:e.genTimeMs===void 0?Gs:`${Br(e.genTimeMs)} · ${Ql(e.timedCalls||0,"call")}${e.timedCalls!==e.llmCalls?` (of ${e.llmCalls})`:""}`}),o.push({label:"Tools",value:e.toolTimeMs!==void 0?`${Br(e.toolTimeMs)} · ${Ql(e.toolBatches||0,"batch","batches")}`:e.toolCalls?Gs:"none",hint:e.toolTimeIncludesApproval?"includes approval wait":void 0}),r!==void 0&&e.genTimeMs!==void 0){const w=r-e.genTimeMs-(e.toolTimeMs||0);o.push({label:"Orchestration",value:w>=0?Br(w):"overlaps (parallel runs)",hint:"wall − model − tools: routing, hand-offs, model load"})}n.push({heading:"Turn",rows:o});const l=[],u=e.ttftCalls||0,c=e.promptPhaseCalls||0;e.promptPhaseMs!==void 0?l.push({label:u&&u===c?"Prefill (TTFT)":"Prefill",value:Eh(e.promptPhaseMs,e.promptPhaseNewTokens,e.promptPhaseTokensPerSecond,"new tok"),hint:u===c?"measured time to first token":u?`TTFT measured on ${u} of ${c}; rest from provider rate`:"derived: prompt ÷ provider rate"}):e.prefillMs!==void 0&&e.prefillNewTokensPerSecond!==void 0?l.push({label:"Prefill",value:Eh(e.prefillMs,e.prefillNewTokens,e.prefillNewTokensPerSecond,"new tok"),hint:"derived: prompt ÷ provider rate"}):e.prefillMs!==void 0?l.push({label:"Prefill",value:`${Br(e.prefillMs)}${e.promptTokensPerSecond!==void 0?` at ${wx(e.promptTokensPerSecond)}`:""}`,hint:"provider rate over all prompt tokens, restored included"}):l.push({label:"Prefill",value:Gs}),e.cachedTokens&&(e.promptPhaseMs??e.prefillMs)!==void 0&&l.push({label:"Restored",value:`${e.cachedTokens.toLocaleString()} tok from cache`,hint:"not recomputed"}),l.push({label:"Generation",value:e.generationPhaseMs!==void 0?Eh(e.generationPhaseMs,e.generationPhaseTokens,e.generationPhaseTokensPerSecond,"tok"):Eh(e.decodeMs,e.outputTokens,e.generationTokensPerSecond,"tok")}),e.measuredSpeedCalls&&e.measuredSpeedCalls!==e.llmCalls&&l.push({label:"Speeds from",value:`${e.measuredSpeedCalls} of ${e.llmCalls} calls`}),n.push({heading:"Model",rows:l});const f=e.speculation;if(f){const w=(f.draftKinds||[]).map(j=>j.toUpperCase()).join(", "),x=[{label:"Mode",value:`${f.used?"on":"off"}${w?` · ${w}`:""}${(m=f.modes)!=null&&m.length?` (${f.modes.join(", ")})`:""}`,hint:f.calls!==e.llmCalls||f.used!==f.calls?`used on ${f.used} of ${e.llmCalls} calls`:void 0},{label:"Acceptance",value:f.acceptanceRate===void 0?Gs:`${Math.round(f.acceptanceRate*100)}% · ${Sr(f.acceptedTokens)} of ${Sr(f.draftedTokens)} drafted`}];((_=f.draftLengths)!=null&&_.length||f.rounds!==void 0)&&x.push({label:"Draft length",value:`${(g=f.draftLengths)!=null&&g.length?`${f.draftLengths.join("/")} tok/round`:Gs}${f.rounds!==void 0?` · ${f.rounds.toLocaleString()} rounds`:""}`}),n.push({heading:"Speculation",rows:x})}return e.slowestToolBatch&&n.push({heading:"Tools",rows:[{label:"Total",value:`${Br(e.toolTimeMs)} · ${Ql(e.toolBatches||0,"batch","batches")}`},{label:"Slowest",value:`${Br(e.slowestToolBatch.ms)} · ${vx(e.slowestToolBatch)}`}],note:e.toolTimeIncludesApproval?"Gated calls are timed from request to result, so this includes waiting for your approval.":void 0}),t.length>1&&n.push({heading:"Per call",table:{columns:["#","Prefill","New tok/s","Gen","Gen tok/s","Cache"],rows:t.map((w,x)=>[String(x+1),w.promptMs===void 0?"—":`${Br(w.promptMs)}${w.promptSource==="rate"?"*":""}`,w.promptNewTokensPerSecond===void 0?"—":Math.round(w.promptNewTokensPerSecond).toLocaleString(),w.generationMs===void 0?"—":Br(w.generationMs),w.generationTokensPerSecond===void 0?"—":Math.round(w.generationTokensPerSecond).toLocaleString(),w.cacheOutcome||"—"])},note:t.some(w=>w.promptSource==="rate")?"* derived from the provider's prompt rate (no TTFT event).":void 0}),{kind:"time",title:"Time",headline:r===void 0?Gs:`${Br(r)} wall clock`,sections:n,footer:cm(e)}}function vx(e){return e.tools.length===1?`${e.tools[0]} ×${e.calls}`:`${Ql(e.calls,"call")} (${e.tools.join(", ")})`}function i1(e){const t=[],n=(e.toolsWaiting||0)+(e.toolsRunning||0);if(!e.toolCalls&&!n)return t.push({heading:"Outcome",rows:[{label:"Tools called",value:"none"}]}),{kind:"tools",title:"Tools",headline:"none",sections:t,footer:cm(e)};const r=[{label:"Succeeded",value:(e.toolCalls-(e.toolsFailed||0)).toLocaleString()},{label:"Failed",value:(e.toolsFailed||0).toLocaleString()}];e.toolsRunning&&r.push({label:"Running",value:e.toolsRunning.toLocaleString()}),e.toolsWaiting&&r.push({label:"Awaiting approval",value:e.toolsWaiting.toLocaleString(),hint:"not run yet — not a failure"}),t.push({heading:"Outcome",rows:r});const o=Object.entries(e.toolBreakdown||{}).sort((c,f)=>f[1].calls-c[1].calls||c[0].localeCompare(f[0]));o.length&&t.push({heading:"By tool",table:{columns:["Tool","Calls","Failed","Time"],rows:o.map(([c,f])=>[c,f.calls.toLocaleString(),f.failed.toLocaleString(),f.ms!==void 0?`${Br(f.ms)}${f.sharedBatches?" +shared":""}`:f.sharedBatches?"shared":Gs])},note:o.some(([,c])=>c.sharedBatches)?"A batch that mixed tools ran them together; its time is not split between them.":void 0});const l=o.filter(([,c])=>c.errors&&Object.keys(c.errors).length);l.length&&t.push({heading:"Failures",rows:l.map(([c,f])=>({label:c,value:Object.entries(f.errors).sort((m,_)=>_[1]-m[1]).map(([m,_])=>_>1?`${m} ×${_}`:m).join(" · ")}))});const u=[{label:"Tool time",value:e.toolTimeMs===void 0?Gs:`${Br(e.toolTimeMs)} · ${Ql(e.toolBatches||0,"batch","batches")}`}];return e.slowestToolBatch&&u.push({label:"Slowest batch",value:`${Br(e.slowestToolBatch.ms)} · ${vx(e.slowestToolBatch)}`}),t.push({heading:"Timing",rows:u,note:e.toolTimeIncludesApproval?"Gated calls are timed from request to result, so this includes waiting for your approval.":void 0}),{kind:"tools",title:"Tools",headline:`${Ql(e.toolCalls,"call")}${e.toolsFailed?` · ${e.toolsFailed} failed`:""}`,sections:t,footer:cm(e)}}function C_(e,t){return e==="tokens"?s1(t):e==="time"?r1(t):i1(t)}function o1(e){const t=e.detail;return s.jsxs("div",{ref:e.panelRef,id:e.id,role:"tooltip",className:`pc-stat-detail pc-stat-detail--${t.kind}`,style:e.style,onMouseEnter:e.onMouseEnter,onMouseLeave:e.onMouseLeave,children:[s.jsxs("div",{className:"pc-stat-detail-head",children:[s.jsx("span",{className:"pc-stat-detail-title",children:t.title}),s.jsx("span",{className:"pc-stat-detail-headline",children:t.headline})]}),t.sections.map(n=>{var r;return s.jsxs("div",{className:"pc-stat-detail-section",children:[s.jsx("div",{className:"pc-stat-detail-heading",children:n.heading}),(r=n.rows)!=null&&r.length?s.jsx("dl",{className:"pc-stat-detail-rows",children:n.rows.map(o=>s.jsxs(ve.Fragment,{children:[s.jsx("dt",{children:o.label}),s.jsxs("dd",{children:[s.jsx("span",{className:o.value===Gs?"pc-stat-detail-value pc-stat-detail-value--absent":"pc-stat-detail-value",children:o.value}),o.hint?s.jsx("span",{className:"pc-stat-detail-hint",children:o.hint}):null]})]},o.label))}):null,n.table?s.jsxs("table",{className:"pc-stat-detail-table",children:[s.jsx("thead",{children:s.jsx("tr",{children:n.table.columns.map(o=>s.jsx("th",{scope:"col",children:o},o))})}),s.jsx("tbody",{children:n.table.rows.map((o,l)=>s.jsx("tr",{children:o.map((u,c)=>s.jsx("td",{children:u},c))},l))})]}):null,n.note?s.jsx("p",{className:"pc-stat-detail-note",children:n.note}):null]},n.heading)}),s.jsx("div",{className:"pc-stat-detail-foot",children:t.footer.map(n=>s.jsx("div",{children:n},n))})]})}const ta=8;function a1(e){const[t,n]=p.useState(!!e.defaultOpen),[r,o]=p.useState(null),l=p.useRef(null),u=p.useRef(null),c=p.useRef(null),f=`pc-stat-${p.useId().replace(/[^a-zA-Z0-9_-]/g,"")}`,m=p.useCallback(()=>{c.current!==null&&window.clearTimeout(c.current),c.current=null},[]),_=p.useCallback(()=>{m(),n(!0)},[m]),g=p.useCallback(()=>{m(),c.current=window.setTimeout(()=>n(!1),120)},[m]);p.useEffect(()=>m,[m]),p.useLayoutEffect(()=>{if(!t){o(null);return}const b=()=>{const N=l.current,C=u.current;if(!N||!C)return;const E=N.getBoundingClientRect(),T=C.offsetWidth,I=C.offsetHeight,K=window.innerWidth,U=window.innerHeight,J=E.top-ta-I,Y=E.bottom+ta,re=J>=ta?J:Y+I<=U-ta?Y:Math.max(ta,U-ta-I),ce=Math.min(Math.max(ta,E.left),Math.max(ta,K-ta-T));o({top:re,left:ce})};return b(),window.addEventListener("resize",b),window.addEventListener("scroll",b,!0),()=>{window.removeEventListener("resize",b),window.removeEventListener("scroll",b,!0)}},[t]),p.useEffect(()=>{if(!t)return;const b=N=>{N.key==="Escape"&&n(!1)};return document.addEventListener("keydown",b),()=>document.removeEventListener("keydown",b)},[t]);const w=typeof e.onClick=="function",x=w?"button":"span",j=t?s.jsx(o1,{detail:e.detail,id:f,panelRef:u,onMouseEnter:m,onMouseLeave:g,style:{position:"fixed",top:(r==null?void 0:r.top)??0,left:(r==null?void 0:r.left)??0,visibility:r?"visible":"hidden"}}):null;return s.jsxs(s.Fragment,{children:[s.jsxs(x,{ref:l,...w?{type:"button"}:{tabIndex:0},className:["pc-chat-stat","pc-chat-stat--detail",w?"pc-chat-stat--clickable":"",e.className].filter(Boolean).join(" "),"aria-label":`${e.label} — ${e.detail.title.toLowerCase()} details`,"aria-describedby":t?f:void 0,"data-stat-kind":e.detail.kind,onMouseEnter:_,onMouseLeave:g,onFocus:_,onBlur:()=>n(!1),onKeyDown:b=>{b.key==="Escape"&&n(!1)},onClick:w?()=>{var b;return(b=e.onClick)==null?void 0:b.call(e)}:void 0,children:[e.icon?s.jsx("span",{className:"pc-chat-stat-icon","aria-hidden":"true",children:e.icon}):null,s.jsx("span",{className:"pc-chat-stat-label",children:e.label})]}),j&&typeof document<"u"?Ev.createPortal(j,document.body):j]})}function l1(e){const t=e.totalTokens!==void 0?C_("tokens",e):null,n=C_("tools",e),r=e.durationMs!==void 0?C_("time",e):null;return[...t?[{label:`${e.totalTokens.toLocaleString()} tokens`,detail:t}]:[],{label:`${e.toolCalls} ${e.toolCalls===1?"tool":"tools"}`,detail:n},...e.changedFiles.length?[{label:`${e.changedFiles.length} ${e.changedFiles.length===1?"file":"files"} changed`,title:e.changedFiles.join(`
66
- `)}]:[],...r?[{label:`${(e.durationMs/1e3).toFixed(e.durationMs<1e4?1:0)}s`,detail:r}]:[]]}function c1(e){const t=String(e.role||"").trim().toLowerCase()||"system",n=String(e.kind||"").trim().toLowerCase(),r=String(e.level||"").trim().toLowerCase();return t==="system"&&n==="report_bug"?{label:String(e.title||"").trim()||"Bug report",icon:"warning",variant:"report_bug"}:t==="system"&&n==="report_feature"?{label:String(e.title||"").trim()||"Feature request",icon:"check",variant:"report_feature"}:t==="user"?{label:String(e.title||"").trim()||"You",icon:"user",variant:"user"}:t==="assistant"?{label:String(e.title||"").trim()||"Agent",icon:"bot",variant:"assistant"}:{label:String(e.title||"").trim()||(r==="error"?"Error":r==="warn"?"Warning":"System"),icon:r==="error"?"error":r==="warn"?"warning":"info",variant:r==="error"?"error":r==="warn"?"warn":"status"}}const u1=new Set(["blob:","data:","http:","https:"]);function Ty(e){const t=String(e||"").trim();if(t)try{const n=typeof window<"u"&&window.location?window.location.href:"http://same-origin.invalid/";return u1.has(new URL(t,n).protocol)?t:void 0}catch{return}}function d1({item:e}){const[t,n]=p.useState(!1),r=Ty(e.src),o=e.href?Ty(e.href):void 0,l=e.kind==="image"||e.kind==="audio"||e.kind==="video"?e.kind:null;if(!l||!r&&!o)return null;const u=l==="image"?"Image":l==="video"?"Video":"Audio",c=String(e.label||"").trim()||`Generated ${u.toLowerCase()}`,f=()=>n(!0);return s.jsxs("figure",{className:`pc-chat-media__item pc-chat-media__item--${l}`,children:[r&&l==="image"?s.jsx("img",{className:"pc-chat-media__image",src:r,alt:c,loading:"lazy",onError:f}):null,r&&l==="video"?s.jsx("video",{className:"pc-chat-media__video",src:r,controls:!0,playsInline:!0,preload:"metadata","aria-label":c,onError:f}):null,r&&l==="audio"?s.jsx("audio",{className:"pc-chat-media__audio",src:r,controls:!0,preload:"metadata","aria-label":c,onError:f}):null,t?s.jsxs("div",{className:"pc-chat-media__error",role:"note",children:[u," could not be decoded by this browser",o?"; open the raw file with the link.":"."]}):null,o?s.jsx("figcaption",{className:"pc-chat-media__caption",children:s.jsx("a",{className:"pc-chat-media__link",href:o,target:"_blank",rel:"noopener noreferrer",children:c})}):null]})}function fg(e){var K;const t=e.message,n=p.useMemo(()=>c1(t),[t.kind,t.level,t.role,t.title]),r=String(t.ts||"").trim(),o=p.useMemo(()=>{if(!r)return"";const U=new Date(r);return Number.isFinite(U.getTime())?U.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):""},[r]),[l,u]=p.useState("idle"),c=p.useRef(null);p.useEffect(()=>()=>{c.current!==null&&window.clearTimeout(c.current)},[]);const f=t.live,m=!f&&typeof e.onSpeakToggle=="function"&&n.variant==="assistant"&&!!String(t.content||"").trim(),_=m&&((K=e.getSpeakState)==null?void 0:K.call(e,t))||"idle",g=_==="loading"?"loader":_==="playing"?"pause":"speaker",w=_==="loading"?"Generating audio…":_==="playing"?"Pause":_==="paused"?"Resume":"Speak (TTS)",x=e.showCopy!==!1,j=Array.isArray(e.attachments)?e.attachments:[],b=t.statistics,N=t.stats,C=p.useMemo(()=>Array.isArray(e.stats)?e.stats:Array.isArray(N)?N:b?l1(b):[],[e.stats,N,b]),E=Array.isArray(t.media)?t.media:[],T=String(f?f.reasoning||"":t.reasoning||""),I=!!String(t.content||"").trim();return t.toolActivity?s.jsx(gx,{tool:t.toolActivity,showCopy:e.showCopy}):s.jsxs("div",{className:["pc-chat-item",`pc-chat-item--${n.variant}`,f?"pc-chat-item--live":"",e.className].filter(Boolean).join(" "),...f?{"aria-busy":!0}:{},children:[s.jsxs("div",{className:"pc-chat-header",children:[s.jsx("div",{className:"pc-chat-avatar","aria-hidden":"true",children:s.jsx(et,{name:n.icon,size:14})}),s.jsx("span",{className:"pc-chat-role",children:n.label}),f?s.jsxs("span",{className:"pc-chat-live-indicator",title:f.label?`Pending: ${f.label}`:"The reply is still being written",children:[s.jsx("span",{className:"pc-chat-live-dot","aria-hidden":"true"}),f.label||"streaming"]}):null,f!=null&&f.caption?s.jsx("span",{className:"pc-chat-live-caption",children:f.caption}):null,s.jsx("span",{className:"pc-chat-header-spacer"}),o?s.jsx("span",{className:"pc-chat-time",children:o}):null,s.jsxs("div",{className:"pc-chat-header-actions",children:[m?s.jsx("button",{className:"pc-chat-icon-btn",type:"button","aria-label":w,title:w,onClick:()=>{var U;return(U=e.onSpeakToggle)==null?void 0:U.call(e,t)},children:s.jsx(et,{name:g,size:22,className:_==="loading"?"pc-chat-speak-spinner":void 0})}):null,x?s.jsx("button",{className:`pc-chat-icon-btn ${l!=="idle"?`pc-chat-icon-btn--${l}`:""}`.trim(),type:"button","aria-label":"Copy message",title:l==="idle"?"Copy":l==="copied"?"Copied":"Copy failed",onClick:async()=>{const U=await ic(String(t.content||""));u(U?"copied":"failed"),c.current!==null&&window.clearTimeout(c.current),c.current=window.setTimeout(()=>u("idle"),900)},children:s.jsx(et,{name:"copy",size:22})}):null]})]}),T.trim()?s.jsxs("details",{className:"pc-chat-thinking",children:[s.jsx("summary",{children:"Thinking"}),s.jsx("div",{className:"pc-chat-thinking-body",children:T})]}):null,I||!f&&!E.length?s.jsx("div",{className:"pc-chat-body",children:s.jsx(_x,{text:String(t.content||""),renderMarkdown:e.renderMarkdown,jsonCollapseAfterDepth:e.jsonCollapseAfterDepth,images:e.images||(n.variant==="user"?"inline":"link"),inlineImage:e.inlineImage})}):null,E.length?s.jsx("div",{className:"pc-chat-media",children:E.slice(0,24).map((U,J)=>s.jsx(d1,{item:U},U.id||`${U.kind}:${U.src}:${J}`))}):null,j.length?s.jsx("div",{className:"pc-chat-attachments","aria-label":"Attachments",children:j.slice(0,24).map((U,J)=>{const Y=String(U.label||"").trim()||"attachment",re=String(U.target||"").trim(),ce=String(U.title||"").trim(),fe=!!U.disabled||typeof U.onClick!="function";return s.jsxs("button",{type:"button",className:"pc-chat-attachment-chip",title:ce||Y,onClick:fe?void 0:U.onClick,disabled:fe,children:[s.jsx(et,{name:"paperclip",size:14}),re?s.jsx("span",{className:`pc-chat-attachment-target pc-chat-attachment-target--${re}`,children:re}):null,s.jsx("span",{className:"pc-chat-attachment-name",children:Y})]},U.id||`${Y}:${J}`)})}):null,C.length?s.jsx("div",{className:"pc-chat-stats","aria-label":"Stats",children:C.slice(0,12).map((U,J)=>{const Y=String(U.label||"").trim();if(!Y)return null;if(U.detail)return s.jsx(a1,{label:Y,detail:U.detail,icon:U.icon,onClick:U.onClick},U.id||`${Y}:${J}`);const re=String(U.title||"").trim(),ce=typeof U.onClick=="function",fe=ce?"button":"span";return s.jsxs(fe,{...ce?{type:"button"}:{},className:["pc-chat-stat",ce?"pc-chat-stat--clickable":""].filter(Boolean).join(" "),title:re||void 0,onClick:ce?()=>{var W;return(W=U.onClick)==null?void 0:W.call(U)}:void 0,children:[U.icon?s.jsx("span",{className:"pc-chat-stat-icon","aria-hidden":"true",children:U.icon}):null,s.jsx("span",{className:"pc-chat-stat-label",children:Y})]},U.id||`${Y}:${J}`)})}):null]})}function f1(e,t){const n=Math.max(0,Math.trunc(t));return e.scrollHeight-e.scrollTop-e.clientHeight<=n}function hg(e){const t=typeof e.autoScrollThresholdPx=="number"&&Number.isFinite(e.autoScrollThresholdPx)?e.autoScrollThresholdPx:120,n=e.autoScroll!==!1,r=p.useRef(null),o=p.useRef(null),[l,u]=p.useState(!0),c=p.useMemo(()=>Array.isArray(e.messages)?e.messages:[],[e.messages]),f=p.useMemo(()=>{var g;const _=[];for(const w of c){const x=_[_.length-1];w.toolActivity&&((g=x==null?void 0:x[0])!=null&&g.toolActivity)&&x[0].runId===w.runId?x.push(w):_.push([w])}return _},[c]);p.useEffect(()=>{if(!n)return;const _=r.current;if(!_)return;const g=()=>{u(f1(_,t))};return _.addEventListener("scroll",g,{passive:!0}),g(),()=>_.removeEventListener("scroll",g)},[n,t]);const m=p.useMemo(()=>{let _=0;for(const g of c)if(_+=String(g.content??"").length,Array.isArray(g.media))for(const w of g.media)_+=String((w==null?void 0:w.src)??"").length+1;return`${c.length}:${_}:${String(e.afterKey??"")}`},[c,e.afterKey]);return p.useEffect(()=>{if(!n||!l)return;const _=r.current;_&&(_.scrollTop=_.scrollHeight)},[n,l,m]),p.useEffect(()=>{if(!n)return;const _=r.current;if(!_)return;const g=()=>{l&&(_.scrollTop=_.scrollHeight)};return _.addEventListener("load",g,!0),_.addEventListener("loadedmetadata",g,!0),()=>{_.removeEventListener("load",g,!0),_.removeEventListener("loadedmetadata",g,!0)}},[n,l]),s.jsxs("div",{ref:r,className:["pc-chat-thread",e.className].filter(Boolean).join(" "),children:[c.length?null:e.empty||null,f.map((_,g)=>{var j;const w=_[0],x=String(w.id||"")||String(w.ts||"")+":"+String(w.role||"")+":"+g;return w.toolActivity?s.jsx(yx,{tools:_.map(b=>b.toolActivity),showCopy:(j=e.messageProps)==null?void 0:j.showCopy},x):s.jsx(fg,{message:w,...e.messageProps||{}},x)}),e.after,s.jsx("div",{ref:o})]})}const mg=ve.forwardRef(function(t,n){const r=typeof t.rows=="number"&&Number.isFinite(t.rows)?Math.max(1,Math.trunc(t.rows)):3,o=!!t.disabled,l=!!t.busy,u=!o&&!l&&!!String(t.value||"").trim();return s.jsxs("div",{className:["pc-composer",t.className].filter(Boolean).join(" "),children:[t.leading,s.jsx("textarea",{ref:n,className:["pc-composer__textarea",t.textareaClassName].filter(Boolean).join(" "),value:t.value,onChange:c=>t.onChange(c.target.value),rows:r,style:{"--pc-composer-rows":String(r)},spellCheck:!1,autoCorrect:"off",autoCapitalize:"off",autoComplete:"off",placeholder:t.placeholder||"","aria-label":t.ariaLabel||t.placeholder||"Message",disabled:o,autoFocus:!!t.autoFocus,onPaste:t.onPaste,onKeyDown:c=>{c.key!=="Enter"||c.shiftKey||c.nativeEvent.isComposing||c.keyCode===229||(c.preventDefault(),u&&t.onSubmit())}}),s.jsxs("div",{className:"pc-composer__row",children:[s.jsx("div",{className:"pc-composer__actions",children:t.actions}),s.jsx("button",{type:"button",className:t.sendButtonClassName||"pc-btn",disabled:!u,onClick:()=>t.onSubmit(),children:l?t.busyLabel||"Thinking…":t.sendLabel||"Send"})]}),t.overlay]})});function h1(e){return!!(e&&typeof e[Symbol.asyncIterator]=="function")}function m1(e){const[t,n]=p.useState([]),r=e.messages??t,o=b=>{e.onMessagesChange&&e.onMessagesChange(b),e.messages===void 0&&n(b)},l=p.useRef(r);l.current=r;const[u,c]=p.useState(""),[f,m]=p.useState(!1),_=p.useRef(null),g=e.assistantName||"Assistant",w=!!e.blockedNotice,x=async b=>{const N=String(b||"").trim();if(!N||f||w)return;c("");const C=l.current,E=[...C,{role:"user",content:N,ts:new Date().toISOString()}];o(E),m(!0);const T=new AbortController;_.current=T;try{const I=e.ask(N,{signal:T.signal,history:C});if(h1(I)){let K="";const U=[...E,{role:"assistant",title:g,content:"",ts:new Date().toISOString()}];o(U);for await(const J of I){if(T.signal.aborted)break;K+=String(J??""),o([...E,{role:"assistant",title:g,content:K,ts:new Date().toISOString()}])}!K.trim()&&!T.signal.aborted&&o([...E,{role:"assistant",title:g,content:"#FALLBACK the assistant returned no answer.",level:"warn",ts:new Date().toISOString()}])}else{const K=String(await I??"").trim();o([...E,K?{role:"assistant",title:g,content:K,ts:new Date().toISOString()}:{role:"assistant",title:g,content:"#FALLBACK the assistant returned no answer.",level:"warn",ts:new Date().toISOString()}])}}catch(I){T.signal.aborted||o([...l.current,{role:"assistant",title:g,content:`#FALLBACK assistant request failed: ${String((I==null?void 0:I.message)||I||"unknown error")}`,level:"error",ts:new Date().toISOString()}])}finally{_.current===T&&(_.current=null),m(!1)}},j=p.useMemo(()=>r.length>0?null:s.jsxs("div",{className:"pc-assistant__empty",children:[s.jsx("div",{className:"pc-assistant__empty-text",children:e.emptyState||"Ask about this app — answers are grounded in its documentation."}),e.suggestions&&e.suggestions.length>0?s.jsx("div",{className:"pc-assistant__suggestions",children:e.suggestions.map(b=>s.jsx("button",{type:"button",className:"pc-assistant__suggestion",onClick:()=>void x(b),disabled:f||w,children:b},b))}):null]}),[r.length,e.emptyState,e.suggestions,f,w]);return s.jsxs("div",{className:`pc-assistant${e.className?` ${e.className}`:""}`,children:[s.jsxs("div",{className:"pc-assistant__thread",children:[j,s.jsx(hg,{messages:r,autoScroll:!0}),w?s.jsx("div",{className:"pc-assistant__blocked",children:e.blockedNotice}):null]}),s.jsx("div",{className:"pc-assistant__composer",children:s.jsx(mg,{value:u,onChange:c,onSubmit:()=>void x(u),placeholder:e.placeholder||"Ask about this app…",disabled:w,busy:f,rows:2,actions:f?s.jsx("button",{type:"button",className:"pc-btn",onClick:()=>{var b;(b=_.current)==null||b.abort()},children:"Stop"}):null})})]})}const jn=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},Zh=e=>Array.isArray(e)?e.map(jn):[],Zt=e=>typeof e=="string"?e:"",Wd=e=>Zt(e.runtime_call_id||e.call_uid),qd=e=>Zt(e.call_id||e.id);function xx(e,t){const n=t.record,r=jn(n.effect);if(r.type!=="tool_calls")return[];const o=jn(n.result),l=Zh(jn(r.payload).tool_calls),u=l.length||n.status!=="waiting"?l:Zh(jn(jn(o.wait).details).tool_calls),c=Zh(o.results),f=u.length?u:c,m=[];return f.forEach((_,g)=>{let w=Wd(_)?c.filter(U=>Wd(U)===Wd(_)):[];!w.length&&qd(_)&&u.filter(U=>qd(U)===qd(_)).length===1&&(w=c.filter(U=>qd(U)===qd(_)));const x=u.length?w.length===1?w[0]:u.length===c.length?c[g]:{}:_,j=Wd(_)||Wd(x)||`${Zt(n.idempotency_key)||Zt(n.step_id)||t.cursor}:${g}`,b=`${t.runId}:${j}`,N=e.get(b),C=Zt(_.name||x.name)||(N==null?void 0:N.name);if(!C)return;const E=n.status==="completed"||n.status==="failed",T=n.status==="failed"||x.success===!1||!!x.error,I=_.arguments??x.arguments??(N==null?void 0:N.arguments),K={...N,id:b,runId:t.runId,name:C,arguments:I,status:E?T?"failed":"completed":n.status==="waiting"?"waiting":"running",...typeof x.success=="boolean"?{success:x.success}:{},...x.output!==void 0||x.result!==void 0?{output:x.output??x.result}:{},...x.error?{error:String(x.error)}:{},startedAt:(N==null?void 0:N.startedAt)||Zt(n.started_at)||void 0,endedAt:E&&Zt(n.ended_at)||(N==null?void 0:N.endedAt)};N&&["completed","failed"].includes(N.status)&&!E||(e.set(b,K),m.push(K))}),m}function uu(e){if(e==null||e===""||typeof e=="boolean")return;const t=Number(e);return Number.isFinite(t)&&t>=0?t:void 0}function vo(e,t){for(const n of t){const r=e==null?void 0:e[n];if(r==null||r===""||typeof r=="boolean")continue;const o=Number(r);if(Number.isFinite(o)&&o>=0)return Math.trunc(o)}}function bx(e){if(typeof e=="string")try{return jn(JSON.parse(e))}catch{return{}}return jn(e)}function su(e,t){if(t===void 0||t==="")return e;const n=e||[];return n.includes(t)||n.push(t),n}function _1(e){return vo(e,["reasoning_tokens","thinking_tokens"])??vo(jn(e.completion_tokens_details),["reasoning_tokens"])??vo(jn(e.output_tokens_details),["reasoning_tokens"])}function p1(e){const t=jn(typeof e=="string"&&e.trim().startsWith("{")?bx(e):e);return Zt(t.error_class)}function g1(e){const t=new Map;for(const n of e){const r=n.record;if(jn(r.effect).type!=="emit_event")continue;const o=jn(r.result);if(Zt(o.name)!=="abstract.progress")continue;const l=jn(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=uu(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,N,C,E;const t=new Map,n=new Set,r=new Set,o={llmCalls:0,toolCalls:0,changedFiles:[]};let l=1/0,u=-1/0,c=!1,f=0,m=0,_=0;const g=g1(e),w=[],x=new Set;for(const T of e){const I=T.record,K=`${T.runId}:${I.step_id||T.cursor}:${I.status}`;if(n.has(K))continue;n.add(K);for(const pe of[I.started_at,I.ended_at]){const Ne=Date.parse(Zt(pe));Number.isFinite(Ne)&&(l=Math.min(l,Ne),u=Math.max(u,Ne))}for(const pe of xx(t,T))pe.status==="waiting"&&x.add(pe.id);if(jn(I.effect).type!=="llm_call"||I.status!=="completed")continue;o.llmCalls+=1;const U=jn(I.result),J=jn(U.output),Y=jn(U.usage||U.token_usage||U.tokens||J.usage||J.token_usage||J.tokens),re=vo(Y,["input_tokens","prompt_tokens","prompt","input","in"]),ce=vo(Y,["output_tokens","completion_tokens","completion","output","out"]),fe=vo(Y,["total_tokens","total"])??(re!==void 0||ce!==void 0?(re||0)+(ce||0):void 0);fe!==void 0&&(re===void 0||ce===void 0||re+ce!==fe)&&(c=!0),re!==void 0&&(o.inputTokens=(o.inputTokens||0)+re),ce!==void 0&&(o.outputTokens=(o.outputTokens||0)+ce),fe!==void 0&&(o.totalTokens=(o.totalTokens||0)+fe);const W=uu(U.gen_time??J.gen_time);W!==void 0&&(o.genTimeMs=(o.genTimeMs||0)+W,o.timedCalls=(o.timedCalls||0)+1);const O=jn(U.metadata||J.metadata),$=jn(O.performance),z=uu($.prompt_tokens_per_second),A=uu($.generation_tokens_per_second),ee=jn(O.prompt_cache),P=uu(ee.cached_tokens),F=uu(ee.fed_tokens);if(z!==void 0||A!==void 0){if(o.measuredSpeedCalls=(o.measuredSpeedCalls||0)+1,z!==void 0&&z>0&&(o.promptTokensPerSecond=(o.promptTokensPerSecond||0)+z,re!==void 0)){const pe=re/z*1e3;o.prefillMs=(o.prefillMs||0)+pe,F!==void 0&&(f+=F,m+=pe)}A!==void 0&&A>0&&(o.generationTokensPerSecond=(o.generationTokensPerSecond||0)+A,ce!==void 0&&(o.decodeMs=(o.decodeMs||0)+ce/A*1e3))}if(P!==void 0||F!==void 0){o.measuredCacheCalls=(o.measuredCacheCalls||0)+1,o.cachedTokens=(o.cachedTokens||0)+(P||0),o.fedTokens=(o.fedTokens||0)+(F||0);const pe=Zt(ee.outcome);if(pe){const Ne=o.cacheOutcomes||[];Ne.includes(pe)||Ne.push(pe),o.cacheOutcomes=Ne}}const G=Zt(I.step_id)||void 0,R=G&&g.get(`${T.runId}:${G}`)||{},Z=jn(U.route),X={runId:T.runId};G&&(X.stepId=G),Zt(I.started_at)&&(X.startedAt=Zt(I.started_at));const ie=Zt(U.model||J.model)||Zt(Z.model)||R.model,ne=Zt(Z.provider)||Zt(jn(O._provider_request).provider)||R.provider||Zt(U.provider);ie&&(X.model=ie),ne&&(X.provider=ne),ie&&(o.models=su(o.models,ie)),ne&&(o.providers=su(o.providers,ne)),(fe===void 0||re!==void 0&&ce!==void 0&&re+ce===fe)&&(re!==void 0&&(X.inputTokens=re),ce!==void 0&&(X.outputTokens=ce)),fe!==void 0&&(X.totalTokens=fe);const ye=_1(Y);ye!==void 0&&(X.reasoningTokens=ye,o.reasoningTokens=(o.reasoningTokens||0)+ye),P!==void 0&&(X.cachedTokens=P),F!==void 0&&(X.fedTokens=F),Zt(ee.outcome)&&(X.cacheOutcome=Zt(ee.outcome)),Zt(ee.backend)&&(X.cacheBackend=Zt(ee.backend),o.cacheBackends=su(o.cacheBackends,X.cacheBackend)),W!==void 0&&(X.genTimeMs=W),z!==void 0&&z>0&&(X.promptTokensPerSecond=z),A!==void 0&&A>0&&(X.generationTokensPerSecond=A),R.ttftS!==void 0?(X.ttftMs=R.ttftS*1e3,X.promptMs=X.ttftMs,X.promptSource="ttft",o.ttftMs=(o.ttftMs||0)+X.ttftMs,o.ttftCalls=(o.ttftCalls||0)+1):X.promptTokensPerSecond!==void 0&&re!==void 0&&(X.promptMs=re/X.promptTokensPerSecond*1e3,X.promptSource="rate"),X.promptMs!==void 0&&(o.promptPhaseMs=(o.promptPhaseMs||0)+X.promptMs,o.promptPhaseCalls=(o.promptPhaseCalls||0)+1,F!==void 0&&X.promptMs>0&&(X.promptNewTokensPerSecond=F/(X.promptMs/1e3),o.promptPhaseNewTokens=(o.promptPhaseNewTokens||0)+F,_+=X.promptMs)),X.ttftMs!==void 0&&W!==void 0&&W>=X.ttftMs?X.generationMs=W-X.ttftMs:X.generationTokensPerSecond!==void 0&&ce!==void 0&&(X.generationMs=ce/X.generationTokensPerSecond*1e3),X.generationMs!==void 0&&ce!==void 0&&(o.generationPhaseMs=(o.generationPhaseMs||0)+X.generationMs,o.generationPhaseTokens=(o.generationPhaseTokens||0)+ce);const he=jn(O.speculation);if(Object.keys(he).length){const pe={};Zt(he.mode)&&(pe.mode=Zt(he.mode)),typeof he.used=="boolean"&&(pe.used=he.used),Zt(he.draft_kind)&&(pe.draftKind=Zt(he.draft_kind));const Ne=vo(he,["accepted_tokens"]),Ue=vo(he,["drafted_tokens"]),We=vo(he,["rounds"]),pt=vo(he,["num_draft_tokens"]);Ne!==void 0&&(pe.acceptedTokens=Ne),Ue!==void 0&&(pe.draftedTokens=Ue),Ne!==void 0&&Ue&&(pe.acceptanceRate=Ne/Ue),We!==void 0&&(pe.rounds=We),pt!==void 0&&(pe.draftLength=pt),X.speculation=pe;const Fe=o.speculation||(o.speculation={calls:0,used:0});Fe.calls+=1,pe.used&&(Fe.used+=1),pe.mode&&(Fe.modes=su(Fe.modes,pe.mode)),pe.draftKind&&(Fe.draftKinds=su(Fe.draftKinds,pe.draftKind)),Ne!==void 0&&Ue!==void 0&&(Fe.acceptedTokens=(Fe.acceptedTokens||0)+Ne,Fe.draftedTokens=(Fe.draftedTokens||0)+Ue),We!==void 0&&(Fe.rounds=(Fe.rounds||0)+We),pt!==void 0&&(Fe.draftLengths=su(Fe.draftLengths,pt))}w.push(X)}w.length&&(w.every(T=>T.startedAt)&&w.sort((T,I)=>Date.parse(T.startedAt)-Date.parse(I.startedAt)),o.modelCalls=w),_>0&&o.promptPhaseNewTokens!==void 0&&(o.promptPhaseTokensPerSecond=o.promptPhaseNewTokens/(_/1e3)),o.generationPhaseMs&&o.generationPhaseTokens!==void 0&&(o.generationPhaseTokensPerSecond=o.generationPhaseTokens/(o.generationPhaseMs/1e3)),(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)),m>0&&(o.prefillNewTokens=f,o.prefillNewTokensPerSecond=f/(m/1e3));const j=new Map;for(const T of t.values()){if(T.status==="waiting"){o.toolsWaiting=(o.toolsWaiting||0)+1;continue}if(T.status==="running"){o.toolsRunning=(o.toolsRunning||0)+1;continue}if(!["completed","failed"].includes(T.status))continue;o.toolCalls+=1;const I=T.status==="failed";I&&(o.toolsFailed=(o.toolsFailed||0)+1);const K=o.toolBreakdown||(o.toolBreakdown={}),U=K[T.name]||(K[T.name]={calls:0,failed:0});if(U.calls+=1,I){U.failed+=1;const fe=p1(T.output);fe&&((U.errors||(U.errors={}))[fe]=(((N=U.errors)==null?void 0:N[fe])||0)+1)}const J=Date.parse(Zt(T.startedAt)),Y=Date.parse(Zt(T.endedAt));if(Number.isFinite(J)&&Number.isFinite(Y)&&Y>=J){const fe=`${T.runId}|${T.startedAt}|${T.endedAt}`,W=j.get(fe)||{ms:Y-J,calls:0,names:new Map,waited:!1};W.calls+=1,W.names.set(T.name,(W.names.get(T.name)||0)+1),x.has(T.id)&&(W.waited=!0),j.set(fe,W)}if(T.success!==!0||!["write_file","create_file","save_file","edit_file","update_file","replace_in_file","delete_file","remove_file","move_file","rename_file","copy_file"].includes(T.name))continue;const re=bx(T.arguments),ce=Zt(re.destination||re.destination_path||re.file_path||re.path||re.filename);ce&&r.add(ce)}for(const T of j.values()){o.toolBatches=(o.toolBatches||0)+1,o.toolTimeMs=(o.toolTimeMs||0)+T.ms,T.waited&&(o.toolTimeIncludesApproval=!0);const I=[...T.names.keys()].sort();(!o.slowestToolBatch||T.ms>o.slowestToolBatch.ms)&&(o.slowestToolBatch={ms:T.ms,calls:T.calls,tools:I});const K=(C=o.toolBreakdown)==null?void 0:C[I[0]];if(I.length===1&&K)K.ms=(K.ms||0)+T.ms;else for(const U of I){const J=(E=o.toolBreakdown)==null?void 0:E[U];J&&(J.sharedBatches=(J.sharedBatches||0)+1)}}return o.changedFiles=[...r],c&&(delete o.inputTokens,delete o.outputTokens),Number.isFinite(l)&&Number.isFinite(u)&&(o.durationMs=Math.max(0,u-l)),{tools:[...t.values()],statistics:o}}function y1(e){const t=jn(jn(e).ledgers);return Object.entries(t).flatMap(([n,r])=>Zh(jn(r).items).map((o,l)=>({runId:n,cursor:Number(o.cursor)||l+1,record:Object.keys(jn(o.record)).length?jn(o.record):o})))}function Ah(e){if(!e)return!1;for(let t=0;t<e.length;t+=1)if(e[t]==="Files")return!0;return!1}function My(e){var r;const t=e==null?void 0:e.items;if(!t||!t.length)return null;let n=0;for(let o=0;o<t.length;o+=1)((r=t[o])==null?void 0:r.kind)==="file"&&(n+=1);return n>0?n:null}function Ry(e){return e===1?"Drop file to attach":typeof e=="number"&&e>1?`Drop ${e} files to attach`:"Drop files to attach"}function kx(e){const t=[],n=[],r=e==null?void 0:e.items;if(r&&r.length){for(let l=0;l<r.length;l+=1){const u=r[l];if(!u||u.kind!=="file")continue;const c=typeof u.webkitGetAsEntry=="function"?u.webkitGetAsEntry():null,f=typeof u.getAsFile=="function"?u.getAsFile():null;c!=null&&c.isDirectory?n.push(c.name||(f==null?void 0:f.name)||"folder"):f&&t.push(f)}return{files:t,folders:n}}const o=e==null?void 0:e.files;if(o)for(let l=0;l<o.length;l+=1)o[l]&&t.push(o[l]);return{files:t,folders:n}}function w1(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 v1={"image/png":"png","image/jpeg":"jpg","image/gif":"gif","image/webp":"webp","image/heic":"heic","image/tiff":"tiff","image/bmp":"bmp"};function Hd(e){return String(e).padStart(2,"0")}function x1(e,t,n){const r=String(e||"").trim();if(r&&!/^image\.(png|jpe?g|gif|webp|heic|tiff?|bmp)$/i.test(r))return r;const o=v1[String(t||"").toLowerCase()]||r.split(".").pop()||"bin",l=`${n.getFullYear()}-${Hd(n.getMonth()+1)}-${Hd(n.getDate())} at ${Hd(n.getHours())}.${Hd(n.getMinutes())}.${Hd(n.getSeconds())}`;return`${String(t||"").startsWith("image/")||!r?"Pasted image":"Pasted file"} ${l}.${o}`}function b1(e,t=new Date){if(!e)return[];const n=e.types?Array.from(e.types):[];if(n.includes("text/plain")&&n.includes("text/html"))return[];const{files:r}=kx(e);return r.map(o=>{const l=x1(o.name,o.type,t);return l===o.name?o:new File([o],l,{type:o.type,lastModified:o.lastModified})})}class k1{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 j1(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 S1(e){return(e instanceof Error?e.message:String(e||"Unknown error")).trim()||"Unknown error"}function N1(e){return s.jsxs("div",{className:"pc-workflow-interaction__error",role:"alert",children:[s.jsxs("span",{children:["Could not complete that action: ",e.message]}),s.jsx("button",{type:"button",className:"pc-workflow-interaction__retry",onClick:e.onRetry,disabled:e.disabled,children:"Try again"})]})}function C1(e){var J;const t=e.interaction,[n,r]=p.useState(""),[o,l]=p.useState(()=>t.kind==="event-wait"&&t.initialPayload||""),[u,c]=p.useState(null),[f,m]=p.useState(!1),[_,g]=p.useState(""),[w,x]=p.useState(null),j=`${t.kind}:${t.id}`,b=p.useRef(j),N=p.useRef(!1),C=p.useRef(!1),E=p.useRef(!0),T=p.useRef(0);b.current!==j&&(b.current=j,N.current=!1,C.current=!1,T.current+=1);const I=!!e.disabled||u!==null||f||N.current||C.current,K=async(Y,re)=>{var W;if(e.disabled||N.current||C.current)return;const ce=j,fe=++T.current;N.current=!0,x(null),g(""),c(Y);try{if(await re(),!E.current||b.current!==ce||T.current!==fe)return;C.current=!0,m(!0),g("Response sent. Waiting for the workflow to continue.")}catch(O){if(!E.current||b.current!==ce||T.current!==fe)return;x({submission:Y,message:S1(O)}),g("The action failed. You can try again."),(W=e.onError)==null||W.call(e,O)}finally{if(!E.current||b.current!==ce||T.current!==fe)return;N.current=!1,c(null)}};p.useEffect(()=>{r(""),l(t.kind==="event-wait"&&t.initialPayload||""),x(null),c(null),m(!1),g("")},[j]),p.useEffect(()=>(E.current=!0,()=>{E.current=!1,T.current+=1,N.current=!1}),[]);const U=()=>{w&&K(w.submission,()=>j1(t,w.submission))};return s.jsxs("section",{className:"pc-workflow-interaction","aria-labelledby":`pc-workflow-interaction-${j}`,children:[s.jsxs("div",{className:"pc-workflow-interaction__heading",children:[s.jsx(et,{name:t.kind==="tool-approval"?"warning":t.kind==="event-wait"?"history":"info",size:16}),s.jsxs("div",{children:[s.jsx("h3",{tabIndex:-1,id:`pc-workflow-interaction-${j}`,children:t.title||(t.kind==="tool-approval"?"Tool approval required":"Input required")}),t.description?s.jsx("div",{className:"pc-workflow-interaction__description",children:t.description}):null]})]}),t.kind==="ask-user"?s.jsxs("div",{className:"pc-workflow-interaction__body",children:[s.jsx("div",{className:"pc-workflow-interaction__prompt",children:t.prompt}),(J=t.choices)!=null&&J.length?s.jsx("div",{className:"pc-workflow-interaction__choices","aria-label":"Choices",children:t.choices.map(Y=>s.jsxs("button",{type:"button",className:"pc-workflow-interaction__choice",disabled:I||Y.disabled,onClick:()=>void K({kind:"choice",answer:Y.id},()=>t.onSubmit(Y.id)),children:[s.jsx("span",{children:Y.label}),Y.description?s.jsx("small",{children:Y.description}):null]},Y.id))}):null,t.allowFreeText!==!1?s.jsxs("div",{className:"pc-workflow-interaction__entry",children:[s.jsx("textarea",{"aria-label":"Response",value:n,onChange:Y=>r(Y.target.value),placeholder:t.freeTextPlaceholder||"Type a response",rows:2,disabled:I,onKeyDown:Y=>{Y.key!=="Enter"||Y.shiftKey||Y.nativeEvent.isComposing||Y.keyCode===229||(Y.preventDefault(),n.trim()&&K({kind:"free-text",answer:n},()=>t.onSubmit(n)))}},`${j}:text`),s.jsx("button",{type:"button",className:"pc-btn",disabled:I||!n.trim(),onClick:()=>void K({kind:"free-text",answer:n},()=>t.onSubmit(n)),children:(u==null?void 0:u.kind)==="free-text"?"Sending…":t.submitLabel||"Submit"})]}):null]}):t.kind==="tool-approval"?s.jsxs("div",{className:"pc-workflow-interaction__body",children:[s.jsxs("div",{className:"pc-workflow-interaction__prompt",children:["Allow ",s.jsx("strong",{children:t.toolName})," to run?"]}),t.detail?s.jsx("div",{className:"pc-workflow-interaction__detail",children:t.detail}):null,s.jsxs("div",{className:"pc-workflow-interaction__buttons",children:[s.jsx("button",{type:"button",className:"pc-workflow-interaction__deny",disabled:I,onClick:()=>void K({kind:"deny"},t.onDeny),children:(u==null?void 0:u.kind)==="deny"?"Denying…":t.denyLabel||"Deny"}),s.jsx("button",{type:"button",className:"pc-btn",disabled:I,onClick:()=>void K({kind:"approve"},t.onApprove),children:(u==null?void 0:u.kind)==="approve"?"Approving…":t.approveLabel||"Approve"}),t.onApproveAll?s.jsx("button",{type:"button",className:"pc-workflow-interaction__allow-all",disabled:I,onClick:()=>void K({kind:"approve-all"},t.onApproveAll),children:(u==null?void 0:u.kind)==="approve-all"?"Approving…":t.approveAllLabel||"Allow all"}):null]}),t.onApproveAll&&t.approveAllDescription?s.jsx("p",{className:"pc-workflow-interaction__scope",children:t.approveAllDescription}):null]}):s.jsxs("div",{className:"pc-workflow-interaction__body",children:[s.jsx("div",{className:"pc-workflow-interaction__prompt",children:t.prompt}),s.jsxs("label",{className:"pc-workflow-interaction__entry",children:[s.jsx("span",{children:t.payloadLabel||(t.eventName?`Payload for ${t.eventName}`:"Event payload")}),s.jsx("textarea",{value:o,onChange:Y=>l(Y.target.value),placeholder:t.payloadPlaceholder||"Enter payload",rows:2,"aria-label":t.payloadLabel||(t.eventName?`Payload for ${t.eventName}`:"Event payload"),disabled:I},`${j}:payload`)]}),s.jsx("div",{className:"pc-workflow-interaction__buttons",children:s.jsx("button",{type:"button",className:"pc-btn",disabled:I,onClick:()=>void K({kind:"event",payload:o},()=>t.onSend(o)),children:(u==null?void 0:u.kind)==="event"?"Sending…":t.sendLabel||"Send event"})})]}),w?s.jsx(N1,{message:w.message,onRetry:U,disabled:I}):null,s.jsx("div",{className:"pc-workflow-interaction__outcome","aria-live":"polite",children:_})]})}function $h(e){return(e instanceof Error?e.message:String(e||"Unknown error")).trim()||"Unknown error"}function E1(e){const[t,n]=p.useState(!1),[r,o]=p.useState(!1),[l,u]=p.useState(!1),[c,f]=p.useState(null),m=p.useRef(!0),_=p.useRef(!1),g=p.useRef(!1),w=p.useRef(!1),x=p.useRef(0),j=p.useRef(0),b=p.useRef(0);p.useEffect(()=>(m.current=!0,()=>{m.current=!1,x.current+=1,j.current+=1,b.current+=1,_.current=!1,g.current=!1,w.current=!1}),[]);const N=!!e.blockedNotice,C=!!e.disabled||N,E=!!e.busy||t,T=t||!!e.busy&&!e.sendWhileBusy,I=e.stopState||null,K=(I==null?void 0:I.phase)==="stopping",U=typeof e.onFiles=="function",J=p.useRef(null),[Y,re]=p.useState(null),[ce,fe]=p.useState(""),W=p.useRef(e.onFiles);W.current=e.onFiles;const O=p.useRef(C);O.current=C;const $=async(X,ie)=>{const ne=W.current;if(ne){if(O.current){f({action:"attach",message:"attachments are unavailable right now."});return}if(ie.length)f({action:"attach",message:w1(ie)});else if(X.length)f(null);else{f({action:"attach",message:"the drop contained no files."});return}if(X.length){fe(`Attaching ${X.length} ${X.length===1?"file":"files"}…`);try{await ne(X)}catch(ye){m.current&&f({action:"attach",message:$h(ye)})}}}},z=p.useRef($);z.current=$,p.useEffect(()=>{if(!U||typeof window>"u")return;const X=new k1;let ie=0;const ne=Fe=>!!(J.current&&Fe instanceof Node&&J.current.contains(Fe)),ye=()=>{X.reset(),ie&&window.clearInterval(ie),ie=0,re(null)},he=()=>{ie||(ie=window.setInterval(()=>{X.active(Date.now())||ye()},250))},pe=Fe=>{var Ke;if(!Ah((Ke=Fe.dataTransfer)==null?void 0:Ke.types))return;X.enter(Date.now());const tt=ne(Fe.target),lt=My(Fe.dataTransfer);re(je=>je&&je.over===tt&&je.count===(lt??je.count)?je:{count:lt??(je==null?void 0:je.count)??null,over:tt}),he()},Ne=Fe=>{var lt;if(!Ah((lt=Fe.dataTransfer)==null?void 0:lt.types))return;Fe.preventDefault(),X.over(Date.now());const tt=ne(Fe.target);Fe.dataTransfer&&(Fe.dataTransfer.dropEffect=tt&&!O.current?"copy":"none"),re(Ke=>Ke&&Ke.over===tt?Ke:{count:(Ke==null?void 0:Ke.count)??My(Fe.dataTransfer),over:tt}),he()},Ue=Fe=>{var tt;Ah((tt=Fe.dataTransfer)==null?void 0:tt.types)&&(X.leave(Date.now())||ye())},We=Fe=>{var Re;if(!Ah((Re=Fe.dataTransfer)==null?void 0:Re.types))return;const tt=ne(Fe.target),lt=Fe.defaultPrevented&&!tt;if(Fe.preventDefault(),ye(),lt)return;if(!tt){f({action:"attach",message:"drop files on the conversation to attach them."});return}const{files:Ke,folders:je}=kx(Fe.dataTransfer);z.current(Ke,je)},pt=Fe=>{Fe.key==="Escape"&&X.depth>0&&ye()};return window.addEventListener("dragenter",pe),window.addEventListener("dragover",Ne),window.addEventListener("dragleave",Ue),window.addEventListener("drop",We),window.addEventListener("dragend",ye),window.addEventListener("blur",ye),window.addEventListener("keydown",pt),()=>{window.removeEventListener("dragenter",pe),window.removeEventListener("dragover",Ne),window.removeEventListener("dragleave",Ue),window.removeEventListener("drop",We),window.removeEventListener("dragend",ye),window.removeEventListener("blur",ye),window.removeEventListener("keydown",pt),ie&&window.clearInterval(ie)}},[U]);const A=X=>{if(!U||C)return;const ie=b1(X.clipboardData);ie.length&&(X.preventDefault(),$(ie,[]))},ee=Y?s.jsxs("div",{className:["pc-workflow-chat__dropzone",Y.over?"is-over":"",C?"is-disabled":""].filter(Boolean).join(" "),"aria-hidden":"true",children:[s.jsx("span",{className:"pc-workflow-chat__dropzone-icon",children:s.jsx(et,{name:"paperclip",size:18})}),s.jsxs("span",{className:"pc-workflow-chat__dropzone-text",children:[s.jsx("strong",{children:C?"Attachments are unavailable right now":Ry(Y.count)}),C?null:s.jsx("span",{children:Y.over?"Release to upload to this conversation":"Drop anywhere on the conversation"})]})]}):null,P=Y?C?"Attachments are unavailable right now":Ry(Y.count):ce,F=async()=>{const X=String(e.draft||"");if(C||_.current||!e.sendWhileBusy&&e.busy||!X.trim())return;const ie=++x.current;_.current=!0,f(null),n(!0);try{await e.onSend(X)}catch(ne){m.current&&x.current===ie&&f({action:"send",message:$h(ne)})}finally{m.current&&x.current===ie&&(_.current=!1,n(!1))}},G=async()=>{if(C||g.current||!e.onCancel)return;const X=++j.current;g.current=!0,f(null),o(!0);try{await e.onCancel()}catch(ie){m.current&&j.current===X&&f({action:"cancel",message:$h(ie)})}finally{m.current&&j.current===X&&(g.current=!1,o(!1))}},R=async()=>{if(C||w.current||!e.onAttach)return;const X=++b.current;w.current=!0,f(null),u(!0);try{await e.onAttach()}catch(ie){m.current&&b.current===X&&f({action:"attach",message:$h(ie)})}finally{m.current&&b.current===X&&(w.current=!1,u(!1))}},Z=()=>{c&&(c.action==="send"&&F(),c.action==="cancel"&&G(),c.action==="attach"&&R())};return s.jsxs("section",{ref:J,className:["pc-workflow-chat",Y?"pc-workflow-chat--dragging":"",Y!=null&&Y.over?"pc-workflow-chat--drag-over":"",e.className].filter(Boolean).join(" "),"aria-label":"Workflow chat","data-stream-replies":e.streamReplies||"gateway_default",children:[e.header?s.jsx("header",{className:"pc-workflow-chat__header",children:e.header}):null,s.jsx("div",{className:"pc-workflow-chat__transcript",children:s.jsx(hg,{messages:Array.isArray(e.messages)?e.messages:[],empty:e.emptyState,autoScroll:!0,messageProps:{...e.messageProps,...e.renderMarkdown?{renderMarkdown:e.renderMarkdown}:{}},after:s.jsxs(s.Fragment,{children:[e.interaction?s.jsx(C1,{interaction:e.interaction,disabled:C}):null,N?s.jsx("div",{className:"pc-workflow-chat__blocked",role:"status",children:e.blockedNotice}):null]}),afterKey:`${e.interaction?`${e.interaction.kind}:${e.interaction.id}`:""}:${N?"blocked":""}`})}),c?s.jsxs("div",{className:"pc-workflow-chat__error",role:"alert",children:[s.jsxs("span",{children:["Could not ",c.action==="send"?"send this message":c.action==="attach"?"attach a file":"stop the run",": ",c.message]}),s.jsx("button",{type:"button",onClick:Z,disabled:C,children:"Try again"})]}):null,s.jsxs("div",{className:"pc-workflow-chat__composer",children:[s.jsx(mg,{value:e.draft,onChange:e.onDraftChange,onSubmit:()=>void F(),placeholder:e.placeholder||"Send a message",ariaLabel:"Message",disabled:C,busy:T,sendLabel:e.sendLabel,busyLabel:e.busyLabel,rows:2,leading:e.attachments?s.jsx("div",{className:"pc-workflow-chat__attachments",children:e.attachments}):null,overlay:ee,onPaste:U?A:void 0,actions:s.jsxs(s.Fragment,{children:[e.onAttach?s.jsxs("button",{type:"button",className:"pc-workflow-chat__icon-button","aria-label":"Attach file",title:"Attach file",disabled:C||l,onClick:()=>void R(),children:[s.jsx(et,{name:"paperclip",size:16}),s.jsx("span",{children:l?"Attaching…":"Attach"})]}):null,e.composerExtras,E&&e.onCancel?s.jsxs("button",{type:"button",className:"pc-workflow-chat__stop",disabled:C||r||K,onClick:()=>void G(),children:[s.jsx(et,{name:"x",size:14}),s.jsx("span",{children:r||K?"Stopping…":"Stop"})]}):I?s.jsx("span",{className:`pc-workflow-chat__stop-state pc-workflow-chat__stop-state--${I.phase}`,role:"status","aria-live":"polite",children:I.label}):null]})}),U?s.jsx("div",{className:"pc-sr-only",role:"status","aria-live":"polite",children:P}):null]}),e.footer?s.jsx("footer",{className:"pc-workflow-chat__footer",children:e.footer}):null]})}const A_="llm.delta",Th="llm.delta_end";function A1(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function ql(e){return typeof e=="string"&&e.trim()!==""}function $1(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0}function T1(e){return"reason"in e}function M1(e,t){const n=A1(e),r=n==null?void 0:n.kind,o=typeof r=="string"&&r?r:n&&"reason"in n?Th:A_,l=f=>{throw new Error(`Malformed ${o} event from the gateway: ${f}`)};if(!n)return l("the payload is not an object");r!==void 0&&r!==A_&&r!==Th&&l(`unknown kind ${JSON.stringify(r)}`),ql(n.run_id)||l("run_id is missing"),ql(n.call_id)||l("call_id is missing"),$1(n.seq)||l("seq is not a non-negative integer");const u=r?r===Th:"reason"in n;n.root_run_id!==void 0&&!ql(n.root_run_id)&&l("root_run_id is not a run id"),n.parent_run_id!==void 0&&n.parent_run_id!==null&&!ql(n.parent_run_id)&&l("parent_run_id is neither a run id nor null");const c={run_id:n.run_id,...ql(n.root_run_id)?{root_run_id:n.root_run_id}:{},...n.parent_run_id!==void 0?{parent_run_id:n.parent_run_id}:{},...ql(n.node_id)?{node_id:n.node_id}:{},call_id:n.call_id,seq:n.seq};return u?(["completed","failed","cancelled","unavailable"].includes(String(n.reason))||l(`unknown reason ${JSON.stringify(n.reason)}`),n.detail!==void 0&&n.detail!==null&&typeof n.detail!="string"&&l("detail is not a string"),{kind:Th,...c,reason:n.reason,...ql(n.detail)?{detail:n.detail}:{}}):(typeof n.text!="string"&&l("text is not a string"),n.channel!=="content"&&n.channel!=="reasoning"&&l(`unknown channel ${JSON.stringify(n.channel)}`),typeof n.snapshot!="boolean"&&l("snapshot is not a boolean"),{kind:A_,...c,text:n.text,channel:n.channel,snapshot:n.snapshot})}const R1={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 L1(e){return`This reply is not streamed: ${e?R1[e]||`the gateway reported "${e}"`:"the gateway gave no reason"}. It appears when it is complete.`}function I1(e){return e.toolApprovalGranted?null:e.interaction}const Ly={messages:[],records:[],run:null,interaction:null,status:"idle",displayStatus:"",loading:!1,error:null,connection:"idle",toolApprovalGranted:!1,stop:null};function St(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function vt(e){return typeof e=="string"?e.trim():e==null?"":typeof e=="number"||typeof e=="boolean"?String(e):""}function rf(e){return Array.isArray(e)?e:[]}function zr(e){return vt(e==null?void 0:e.status).toLowerCase()||"unknown"}function vs(e){return["completed","failed","cancelled"].includes(e.toLowerCase())}function Qa(e){const t=St(e),n=Number((t==null?void 0:t.status)??(t==null?void 0:t.statusCode));return n===401||n===403}function O1(e){const t=St(e);return Number((t==null?void 0:t.status)??(t==null?void 0:t.statusCode))}function $_(e){const t=n=>{if(Array.isArray(n))return n.map(t);const r=St(n);if(!r)return n;const o={};for(const l of Object.keys(r).sort())o[l]=t(r[l]);return o};try{return JSON.stringify(t(e))}catch{return"[unserializable]"}}function Np(e){if(typeof e=="string")return e.trim();const t=St(e);if(!t)return"";for(const n of["answer","response","message","text","content","output"]){const r=t[n];if(typeof r=="string"&&r.trim())return r.trim()}return""}function ru(e){const t=Np(e);if(t)return t;if(!St(e)&&!Array.isArray(e))return"";try{return JSON.stringify(e,null,2)}catch{return""}}function Iy(e){if(!e)return"";for(const r of["prompt","request","task","message","query","input"]){const o=vt(e[r]);if(o)return o}const t=St(e.context);for(const r of["task","message"]){const o=vt(t==null?void 0:t[r]);if(o)return o}const n=rf(t==null?void 0:t.messages);for(let r=n.length-1;r>=0;r-=1){const o=St(n[r]);if(vt(o==null?void 0:o.role).toLowerCase()!=="user")continue;const l=vt(o==null?void 0:o.content);if(l)return l}return""}function jx(e){const t=St(e.result);return St(t==null?void 0:t.wait)}function T_(e){return e?vt(e.reason)==="subworkflow"||vt(e.wait_key).startsWith("subworkflow:"):!1}function Oy(e,t){return!!(e&&e.runId===t.runId&&vt(e.wait.wait_key)===vt(t.wait.wait_key))}function Cp(e){return St(e.effect)||{}}function P1(e,t){return vt(e.run_id)||t}function Py(e){return vt(e.ended_at)||vt(e.started_at)||void 0}function Dy(e){const t=new Set,n=m=>{const _=vt(m);_&&t.add(_)},r=St(e.result);n(r==null?void 0:r.sub_run_id),n(r==null?void 0:r.subRunId),n(r==null?void 0:r.child_run_id);const o=Cp(e),l=St(o.payload);vt(o.type)==="start_subworkflow"&&(n(l==null?void 0:l.sub_run_id),n(l==null?void 0:l.subRunId),n(l==null?void 0:l.child_run_id));const u=jx(e),c=St(u==null?void 0:u.details);n(c==null?void 0:c.sub_run_id),n(c==null?void 0:c.subRunId),n(c==null?void 0:c.child_run_id);const f=vt(u==null?void 0:u.wait_key);return f.startsWith("subworkflow:")&&n(f.slice(12)),[...t]}class D1{constructor(t,n={}){this.transport=t,this.options=n,this.snapshot={...Ly},this.subscribers=new Set,this.controller=null,this.generation=0,this.rootRunId="",this.cursors=new Map,this.seenRecords=new Set,this.seenMessages=new Set,this.watchedRuns=new Set,this.childCatchUpAttempts=new Map,this.runStates=new Map,this.historicalRuns=new Map,this.historicalRunFailures=new Map,this.commandIds=new Map,this.toolActivities=new Map,this.historicalEvidence=new Map,this.approvedWaits=new Set,this.grantedToolWaits=new Set,this.resolvedWaits=new Set,this.approvalEpoch=0,this.toolApprovalPolicy=null,this.toolApprovalSuspended=!1,this.toolApprovalStopped=!1,this.displayStatusAt=-1/0,this.stopRequested=!1,this.stopFollowing=!1,this.openLlmSteps=new Set,this.forcedStop=null,this.liveReplies=new Map,this.closedLiveCalls=new Set,this.shownLiveCalls=new Set,this.liveDirty=new Set,this.liveRenderTimer=null,this.lastLiveRender=-1/0;const r=n.liveRenderIntervalMs??60;if(typeof r!="number"||!Number.isFinite(r)||r<0)throw new Error(`liveRenderIntervalMs must be a non-negative number of milliseconds, got ${JSON.stringify(n.liveRenderIntervalMs)}`);this.liveRenderIntervalMs=r}subscribe(t){return this.subscribers.add(t),()=>this.subscribers.delete(t)}getSnapshot(){return this.snapshot}reset(){var t;this.toolApprovalSuspended=!1,this.toolApprovalStopped=!1,this.approvalEpoch+=1,this.displayStatusAt=-1/0,this.stopRequested=!1,this.stopFollowing=!1,this.openLlmSteps.clear(),this.forcedStop=null,this.generation+=1,(t=this.controller)==null||t.abort(),this.controller=null,this.rootRunId="",this.cursors.clear(),this.seenRecords.clear(),this.seenMessages.clear(),this.watchedRuns.clear(),this.childCatchUpAttempts.clear(),this.runStates.clear(),this.historicalRuns.clear(),this.historicalRunFailures.clear(),this.commandIds.clear(),this.toolActivities.clear(),this.historicalEvidence.clear(),this.approvedWaits.clear(),this.grantedToolWaits.clear(),this.resolvedWaits.clear(),this.liveReplies.clear(),this.closedLiveCalls.clear(),this.shownLiveCalls.clear(),this.liveDirty.clear(),this.lastLiveRender=-1/0,this.liveRenderTimer&&(clearTimeout(this.liveRenderTimer),this.liveRenderTimer=null),this.set({...Ly})}dispose(){this.reset(),this.subscribers.clear()}async load(t){const n=vt(t);if(this.reset(),!n)return;const r=++this.generation,o=new AbortController;this.controller=o,this.rootRunId=n,this.set({...this.snapshot,loading:!0,status:"loading",error:null,connection:"connecting"});try{const[l,u]=await Promise.all([this.transport.getRun(n,o.signal),this.transport.getHistory(n,o.signal)]);if(!this.live(r))return;const c=St(l),f=St(c==null?void 0:c.waiting),m=zr(c);if(await this.ingestHistory(u,n,r),!this.live(r))return;if(this.set({...this.snapshot,run:c,status:m,loading:!1,...f&&!vs(m)?{interaction:this.interactionWith({runId:n,wait:f})}:{}}),c&&this.updateRunState(n,c),f)for(const _ of Dy({result:{wait:f}}))_!==n&&this.catchUpAndWatch(_,r);await this.catchUpAndWatch(n,r),this.pollRootLifecycle(n,r)}catch(l){!o.signal.aborted&&this.live(r)&&this.fail(l)}}async sendCommand(t,n={}){var _,g;t==="cancel"&&(this.toolApprovalStopped=!0,this.revokeToolApproval(),this.stopRequested=!0,this.recomputeStop());const r=vt(n.wait_key),o=t==="resume"?r?this.interactionRunId()||this.rootRunId:this.rootRunId:t==="emit_event"?this.interactionRunId()||this.rootRunId:this.rootRunId;if(!o)throw new Error("No workflow run is loaded");const l=t==="resume"&&r&&((_=this.snapshot.interaction)==null?void 0:_.stepId)||"",u=`${o}\0${t}\0${l}\0${$_(n)}`;let c=this.commandIds.get(u);c||(c=this.newCommandId(),this.commandIds.set(u,c));const f=this.generation,m=(g=this.controller)==null?void 0:g.signal;try{const w=await this.transport.submitCommand({command_id:c,run_id:o,type:t,payload:n,...this.options.clientId?{client_id:this.options.clientId}:{}},m);if(!this.live(f))return w;const x=St(w);if(x&&x.accepted===!1)throw t==="cancel"&&(this.stopRequested=!1,this.recomputeStop()),new Error(vt(x.detail)||"Gateway did not accept the command");return this.commandIds.delete(u),o===this.rootRunId&&["pause","resume","cancel"].includes(t)&&this.refreshRunState(o,f),w}catch(w){throw this.live(f)&&this.fail(w,!1),w}}resume(t){const n=this.requireInteraction();return this.sendCommand("resume",{wait_key:vt(n.wait.wait_key),payload:{response:t}})}approve(t,n){const r=this.requireInteraction();if(vs(this.snapshot.status))throw new Error("This run has already ended.");if(n&&(r.runId!==n.runId||vt(r.wait.wait_key)!==n.waitKey||n.stepId!==void 0&&r.stepId!==n.stepId))throw new Error("This approval request has changed. Review the current request before deciding.");if(t&&this.toolApprovalPolicy&&!this.toolCallsMatch(r,this.toolApprovalPolicy.enabledTools))throw new Error("This request includes an unavailable or unselected tool. It cannot be authorized. Deny this request or stop the run and change Tools settings.");const o=this.generation;return this.sendCommand("resume",{wait_key:vt(r.wait.wait_key),payload:{approved:!!t}}).then(l=>{if(!this.live(o))return l;const u=this.occurrenceKey(r);return this.approvedWaits.add(u),t&&this.isToolApproval(r)&&!this.grantedToolWaits.has(u)&&(this.grantedToolWaits.add(u),this.set({...this.snapshot})),l})}async approveWithPolicyChange(t,n){const r=this.generation,o=this.approvalEpoch;if(!this.isToolApproval(this.requireInteraction()))throw new Error("This is not a tool approval request.");await this.approve(!0,t),!(!this.live(r)||o!==this.approvalEpoch||this.toolApprovalStopped||vs(this.snapshot.status))&&n()}async allowAllToolsForRun(t){const n=this.generation,r=this.approvalEpoch,o=this.requireInteraction();if(!this.isToolApproval(o))throw new Error("This is not a tool approval request.");await this.approve(!0,t),!(!this.live(n)||r!==this.approvalEpoch||vs(this.snapshot.status))&&(this.approvedWaits.add(`${t.runId}:${t.waitKey}${o.stepId?`:${o.stepId}`:""}`),this.set({...this.snapshot,autoApproveTools:!0}))}revokeToolApproval(){this.approvalEpoch+=1,this.toolApprovalSuspended=!0,this.set({...this.snapshot,autoApproveTools:!1})}setToolApprovalPolicy(t){$_(t)!==$_(this.toolApprovalPolicy)&&(this.approvalEpoch+=1,this.toolApprovalSuspended=!1,this.toolApprovalPolicy=t?{enabledTools:[...t.enabledTools],autoApproveTools:[...t.autoApproveTools]}:null,this.set({...this.snapshot}))}occurrenceKey(t){return`${t.runId}:${vt(t.wait.wait_key)}${t.stepId?`:${t.stepId}`:""}`}interactionWith(t){const n=this.snapshot.interaction;return n&&T_(t.wait)&&!T_(n.wait)?n:n&&Oy(n,t)&&t.stepId===void 0&&n.stepId!==void 0?{...t,stepId:n.stepId}:t}adoptDurableWait(t,n){const r=St(n.waiting);if(!r||zr(n)!=="waiting"||T_(r)||vs(this.snapshot.status)||this.resolvedWaits.has(`${t}:${vt(r.wait_key)}`))return;const o=this.interactionWith({runId:t,wait:r}),l=this.snapshot.interaction;l&&Oy(l,o)&&l.stepId===o.stepId||this.set({...this.snapshot,interaction:o})}coveredByStandingPermission(t,n){var r;return t.loading||this.toolApprovalStopped||this.toolApprovalSuspended||!this.toolApprovalPolicy&&!t.autoApproveTools||vs(t.status)||((r=t.run)==null?void 0:r.paused)===!0||t.status==="paused"||!n||!this.isToolApproval(n)||this.toolApprovalPolicy&&(!this.toolCallsMatch(n,this.toolApprovalPolicy.enabledTools)||!this.toolCallsMatch(n,this.toolApprovalPolicy.autoApproveTools))?!1:!!vt(n.wait.wait_key)}present(t){const n=t.interaction,r=n?this.occurrenceKey(n):"",o=!!(n&&this.isToolApproval(n)&&(this.grantedToolWaits.has(r)||!this.approvedWaits.has(r)&&this.coveredByStandingPermission({...t,loading:!1},n)));if(!o&&!this.snapshot.toolApprovalGranted&&!t.toolApprovalGranted)return t.toolApprovalGranted===!1?t:{...t,toolApprovalGranted:!1};let l=!1;const u=t.messages.map(c=>{var _;const f=c.toolActivity;if(!f||((_=this.toolActivities.get(f.id))==null?void 0:_.status)!=="waiting")return c;const m=o&&f.runId===(n==null?void 0:n.runId)?"running":"waiting";return f.status===m?c:(l=!0,this.toolMessage({...f,status:m}))});return{...t,toolApprovalGranted:o,...l?{messages:u}:{}}}toolCallsMatch(t,n){var o;const r=rf((o=St(t.wait.details))==null?void 0:o.tool_calls);return r.length>0&&r.every(l=>{var c;const u=vt((c=St(l))==null?void 0:c.name);return!!u&&n.includes(u)})}isToolApproval(t){const n=St(t.wait.details);return(n==null?void 0:n.mode)==="approval_required"||(n==null?void 0:n.kind)==="tool_approval"}autoApproveCurrentWait(){const t=this.snapshot.interaction;if(!this.coveredByStandingPermission(this.snapshot,t))return;const n={runId:t.runId,waitKey:vt(t.wait.wait_key),stepId:t.stepId},r=this.occurrenceKey(t);if(this.approvedWaits.has(r))return;this.approvedWaits.add(r),this.grantedToolWaits.add(r);const o=this.generation,l=this.approvalEpoch;this.approve(!0,n).catch(u=>{if(this.live(o)){if(this.grantedToolWaits.delete(r),l!==this.approvalEpoch){this.set({...this.snapshot});return}this.toolApprovalSuspended=!0,this.set({...this.snapshot,autoApproveTools:!1}),this.fail(u,!1)}})}emitEvent(t){return this.sendCommand("emit_event",t)}cancel(){return this.sendCommand("cancel",{})}requireInteraction(){if(!this.snapshot.interaction)throw new Error("This workflow is not waiting for input");if(!vt(this.snapshot.interaction.wait.wait_key))throw new Error("The workflow wait has no wait_key");return this.snapshot.interaction}interactionRunId(){var t;return((t=this.snapshot.interaction)==null?void 0:t.runId)||""}live(t){var n;return t===this.generation&&!((n=this.controller)!=null&&n.signal.aborted)}set(t){this.snapshot=this.present(t);for(const n of this.subscribers)n();this.autoApproveCurrentWait()}async catchUpAndWatch(t,n){var r;if(!(!this.live(n)||this.watchedRuns.has(t))){this.watchedRuns.add(t);try{if(t!==this.rootRunId)try{const o=St(await this.transport.getRun(t,(r=this.controller)==null?void 0:r.signal));if(!this.live(n))return;o&&this.updateRunState(t,o)}catch(o){if(!this.live(n))return;if(Qa(o))throw o;this.fail(o,!1)}if(await this.catchUp(t,n),!this.live(n)||vs(zr(this.runStates.get(t)||null)))return;this.childCatchUpAttempts.delete(t),this.watch(t,n)}catch(o){if(!this.live(n))return;if(this.watchedRuns.delete(t),t===this.rootRunId)throw o;if(Qa(o)){this.fail(o);return}const l=(this.childCatchUpAttempts.get(t)||0)+1;if(this.childCatchUpAttempts.set(t,l),this.fail(o,!1),l>=5)return;await this.waitForRetry(Math.min(2e3,150*2**(l-1))),this.live(n)&&this.catchUpAndWatch(t,n)}}}async catchUp(t,n){var r;for(let o=0;o<100&&this.live(n);o+=1){const l=this.cursors.get(t)||0,u=await this.transport.getLedger(t,l,(r=this.controller)==null?void 0:r.signal);if(!this.live(n))return;const c=St(u),f=Array.isArray(u)?u:rf(c==null?void 0:c.items);for(const _ of f)this.ingestItem(t,_);const m=Number(c==null?void 0:c.next_after);if(!f.length||!Number.isFinite(m)||m<=l)break;this.cursors.set(t,m)}}async watch(t,n){try{await this.followStream(t,n)}finally{this.live(n)&&this.closeLiveRepliesVia(t)}}async followStream(t,n){var o;let r=0;for(;this.live(n)&&!vs(zr(this.runStates.get(t)||null));){const l=this.cursors.get(t)||0;this.set({...this.snapshot,connection:r?"reconnecting":"connecting"});try{let u=!1;const c=()=>{!this.live(n)||u||(u=!0,this.set({...this.snapshot,connection:"connected",error:null}))};if(this.dropLiveRepliesVia(t),await this.transport.streamLedger(t,l,m=>{this.live(n)&&(c(),this.ingestItem(t,m))},this.controller.signal,c,m=>{this.live(n)&&(c(),this.ingestDelta(t,m))}),!this.live(n)||(await this.catchUp(t,n),!this.live(n)))return;const f=St(await this.transport.getRun(t,(o=this.controller)==null?void 0:o.signal));if(!this.live(n))return;f&&this.updateRunState(t,f),r+=1}catch(u){if(!this.live(n))return;if(r+=1,this.fail(u,!1),Qa(u)){this.set({...this.snapshot,connection:"disconnected"});return}}if(r>=5||!this.live(n))break;await this.waitForRetry(Math.min(2e3,150*2**(r-1)))}if(this.live(n)){if(vs(zr(this.runStates.get(t)||null))){this.set({...this.snapshot,connection:"disconnected"});return}this.set({...this.snapshot,connection:"disconnected",error:this.snapshot.error||"Ledger stream reconnect limit reached. Reconnect the workflow to continue."})}}async ingestHistory(t,n,r){const o=St(t);if(!o)return;const l=St(o.session),u=rf(l==null?void 0:l.turns).map(St).filter(m=>!!m);if(await this.hydrateHistoricalSessionRuns(u,n,r),!this.live(r))return;for(const m of u){const _=vt(m==null?void 0:m.run_id)||n;this.ingestSessionTurn(m,n,_!==n&&this.historicalRuns.get(_)||null)}const c=`turn:${n}:user`;if(!this.seenMessages.has(c)){const m=Iy(St(o.input_data));m&&this.addMessage({id:c,role:"user",content:m})}const f=St(o.ledgers);if(f)for(const[m,_]of Object.entries(f)){const g=St(_);for(const w of rf(g==null?void 0:g.items))this.ingestItem(m,w)}}ingestSessionTurn(t,n,r){if(!t)return;const o=vt(t.run_id)||n,l=St(t.input_data)||St(t.input)||{},u=vt(t.prompt)||Iy(l);u&&this.addMessage({id:`turn:${o}:user`,role:"user",content:u,ts:vt(t.created_at)||void 0});const c=this.historicalRunFailures.get(o);if(c){const g=vt(t.answer)||Np(t.output),w=c.missing?"is unavailable because the run no longer exists":"could not be restored",x=g?` Saved reply (not verified as the final result): ${g}`:"";this.addMessage({id:`history:${o}:unavailable`,role:"system",level:"warn",title:"History",content:`The final output for an earlier turn ${w}.${x}`});return}const m=(r&&vs(zr(r))?ru(r.output):"")||(r?vt(t.answer)||Np(t.output):""),_=this.historicalEvidence.get(o);for(const g of(_==null?void 0:_.tools)||[])this.upsertTool(g);m&&this.addRunAssistantMessage(o,{id:`final:${o}`,role:"assistant",content:m,runId:o,statistics:_==null?void 0:_.statistics,ts:vt(t.updated_at)||void 0})}async hydrateHistoricalSessionRuns(t,n,r){const o=[...new Set(t.map(f=>vt(f.run_id)).filter(f=>f&&f!==n&&!this.historicalRuns.has(f)&&!this.historicalRunFailures.has(f)))];if(!o.length||!this.live(r))return;let l=0,u=!1;const c=async()=>{var f,m,_;for(;!u&&this.live(r);){const g=o[l++];if(!g)return;try{const w=St(await this.transport.getRun(g,(f=this.controller)==null?void 0:f.signal));if(!this.live(r))return;if(w){this.historicalRuns.set(g,w);try{const x=await this.transport.getHistory(g,(m=this.controller)==null?void 0:m.signal);if(!this.live(r))return;this.historicalEvidence.set(g,E_(y1(x)))}catch(x){if(!this.live(r))return;if(Qa(x))throw x;this.fail(new Error(`Earlier turn activity could not be restored: ${x instanceof Error?x.message:String(x)}`),!1)}}else this.historicalRuns.set(g,null),this.historicalRunFailures.set(g,{missing:!1,detail:"gateway returned an invalid historical run snapshot"})}catch(w){if(!this.live(r))return;const x=O1(w)===404;this.historicalRuns.set(g,null),this.historicalRunFailures.set(g,{missing:x,detail:w instanceof Error?w.message:vt((_=St(w))==null?void 0:_.detail)||"request failed"}),Qa(w)&&(u=!0,this.fail(w))}}};if(await Promise.all(Array.from({length:Math.min(4,o.length)},()=>c())),u&&this.live(r))for(const f of o)!this.historicalRuns.has(f)&&!this.historicalRunFailures.has(f)&&(this.historicalRuns.set(f,null),this.historicalRunFailures.set(f,{missing:!1,detail:"authorization expired before this historical run could be restored"}))}ingestItem(t,n){const r=St(n),o=St(r==null?void 0:r.record)||r;if(!o)return;const l=P1(o,t),u=Number(r==null?void 0:r.cursor),c=Number.isFinite(u)&&u>0?u:(this.cursors.get(l)||0)+1,f=`${l}:${c}`;if(!this.seenRecords.has(f)){if(this.seenRecords.add(f),this.cursors.set(l,Math.max(this.cursors.get(l)||0,c)),this.set({...this.snapshot,records:[...this.snapshot.records,{cursor:c,record:o,runId:l}]}),this.foldRecord(l,o,f),this.snapshot.messages.some(m=>m.id===`final:${this.rootRunId}`)){const m=E_(this.snapshot.records).statistics;this.set({...this.snapshot,messages:this.snapshot.messages.map(_=>_.id===`final:${this.rootRunId}`?{..._,statistics:m}:_)})}for(const m of Dy(o))m!==l&&this.catchUpAndWatch(m,this.generation)}}foldRecord(t,n,r){var _,g,w;const o=Cp(n),l=vt(o.type).toLowerCase(),u=St(n.result),c=vt(n.status).toLowerCase(),f=Py(n);if(this.foldStopEvidence(t,n,l,c),["llm_call","tool_calls"].includes(l)&&["started","running"].includes(c)){const x=Date.parse(f||"");(!Number.isFinite(x)||x>=this.displayStatusAt)&&(Number.isFinite(x)&&(this.displayStatusAt=x),this.snapshot.displayStatus&&this.set({...this.snapshot,displayStatus:""}))}if(l==="answer_user"&&c==="completed"){const x=ru(u)||ru(St(o.payload));x&&this.addRunAssistantMessage(t,{id:`answer:${t}:${r}`,role:"assistant",content:x,ts:f})}if(l==="emit_event"&&c==="completed"){const x=St(o.payload)||{},j=St(u),b=vt(x.name)||vt(j==null?void 0:j.name),N=x.payload!==void 0?x.payload:j==null?void 0:j.payload;if(["abstract.message","abstractcode.message"].includes(b)){const C=ru(N);if(C){const E=vt((_=St(N))==null?void 0:_.level).toLowerCase(),T=E==="error"?"error":["warn","warning"].includes(E)?"warn":"info";this.addMessage({id:`event:${t}:${r}`,role:"system",title:"Workflow",content:C,level:T,ts:f})}}if(["abstract.status","abstractcode.status"].includes(b)){const C=St(N),E=C?C.status??C.text??C.value:N,T=Date.parse(f||"");!vs(this.snapshot.status)&&typeof E=="string"&&(!Number.isFinite(T)||T>=this.displayStatusAt)&&(Number.isFinite(T)&&(this.displayStatusAt=T),this.set({...this.snapshot,displayStatus:E.trim()}))}if(["abstract.tool_execution","abstractcode.tool_execution","abstract.tool_result","abstractcode.tool_result"].includes(b)){const C=ru(N);C&&this.addMessage({id:`event:${t}:${r}`,role:"system",title:"Tool activity",content:C,ts:f})}}const m=jx(n);if(c==="waiting"&&m&&!vs(this.snapshot.status)&&!vs(zr(this.runStates.get(t)||null))&&(this.resolvedWaits.delete(`${t}:${vt(m.wait_key)}`),this.set({...this.snapshot,interaction:this.interactionWith({runId:t,wait:m,...vt(n.step_id)?{stepId:vt(n.step_id)}:{}})})),l==="tool_calls")for(const x of xx(this.toolActivities,{runId:t,cursor:this.cursors.get(t)||0,record:n}))this.upsertTool(x);if(l==="resume"&&(u==null?void 0:u.resumed)===!0){const x=vt((g=St(o.payload))==null?void 0:g.wait_key);x&&this.resolvedWaits.add(`${t}:${x}`),((w=this.snapshot.interaction)==null?void 0:w.runId)===t&&(this.set({...this.snapshot,interaction:null}),this.refreshRunState(t,this.generation))}}foldStopEvidence(t,n,r,o){let l=!1;if(r==="llm_call"){const u=vt(n.step_id);if(u){const c=`${t}:${u}`;o==="started"?(this.openLlmSteps.add(c),l=!0):["completed","failed","cancelled","waiting"].includes(o)&&(l=this.openLlmSteps.delete(c)||l),["completed","failed","cancelled"].includes(o)&&this.closeLiveReply(c)}}if(r==="emit_event"&&o==="completed"){const u=St(Cp(n).payload)||{},c=St(n.result),f=vt(u.name)||vt(c==null?void 0:c.name),m=St(u.payload!==void 0?u.payload:c==null?void 0:c.payload);f==="abstract.status"&&vt(m==null?void 0:m.killed_by)==="kill_switch"&&(this.forcedStop=m,l=!0)}l&&this.recomputeStop()}recomputeStop(){let t=null;this.forcedStop?t={phase:"forced",label:vt(this.forcedStop.text)||"Stop forced: inference killed",record:this.forcedStop}:this.stopRequested&&(t=this.snapshot.status==="cancelled"&&this.openLlmSteps.size===0?{phase:"stopped",label:"Stopped"}:{phase:"stopping",label:"Stopping…"});const n=this.snapshot.stop||null;((n==null?void 0:n.phase)!==(t==null?void 0:t.phase)||(n==null?void 0:n.label)!==(t==null?void 0:t.label))&&this.set({...this.snapshot,stop:t}),(t==null?void 0:t.phase)==="stopping"&&this.snapshot.status==="cancelled"&&this.followStop(this.generation)}async followStop(t){var n;if(!this.stopFollowing){this.stopFollowing=!0;try{let r=500,o=null;for(;this.live(t)&&((n=this.snapshot.stop)==null?void 0:n.phase)==="stopping";){if(await this.waitForRetry(r),!this.live(t))return;const l=[this.rootRunId,...[...this.watchedRuns].filter(c=>c!==this.rootRunId)];let u=!1;for(const c of l)try{await this.catchUp(c,t)}catch(f){u=!0,this.live(t)&&(this.fail(f,!1),o=this.snapshot.error)}!u&&o&&this.snapshot.error===o&&(this.set({...this.snapshot,error:null}),o=null),r=Math.min(5e3,r*2)}}finally{this.generation===t&&(this.stopFollowing=!1)}}}addMessage(t){const n=vt(t.id)||`${t.role}:${t.content}:${t.ts||""}`;this.seenMessages.has(n)||(this.seenMessages.add(n),this.set({...this.snapshot,messages:[...this.snapshot.messages,{...t,id:n}]}))}toolMessage(t){return{id:`tool:${t.id}`,role:"system",kind:"tool_activity",title:"Tool activity",runId:t.runId,toolActivity:t,content:JSON.stringify({tool:t.name,status:t.status,arguments:t.arguments,output:t.output,error:t.error},null,2),ts:t.endedAt||t.startedAt}}upsertTool(t){const n=this.toolMessage(t),r=this.snapshot.messages.findIndex(l=>l.id===n.id);if(r<0){this.addMessage(n);return}const o=[...this.snapshot.messages];o[r]=n,this.set({...this.snapshot,messages:o})}addRunAssistantMessage(t,n){this.closeLiveRepliesOfRun(t);const r=`answer:${t}:`,o=`final:${t}`;this.snapshot.messages.some(l=>l.role==="assistant"&&l.content===n.content&&(l.id===o||String(l.id||"").startsWith(r)))||this.addMessage(n)}ingestDelta(t,n){let r;try{r=M1(n)}catch(f){this.fail(f,!1);return}const o=`${r.run_id}:${r.call_id}`;if(T1(r)){if(r.reason==="unavailable"){this.noteStreamUnavailable(r);return}if(r.reason==="cancelled"&&r.detail==="reinvoked"){this.closeLiveReply(o,"restarted");return}this.closeLiveReply(o,r.reason==="completed"?void 0:r.reason);return}if(this.closedLiveCalls.has(o)||this.runEnded(r.run_id)||this.runEnded(this.rootRunId))return;const l=this.liveReplies.get(o)||{runId:r.run_id,callId:r.call_id,nodeId:r.node_id||"",via:t,text:"",reasoning:"",seq:{content:-1,reasoning:-1}},u=r.channel==="reasoning"?"reasoning":"text",c=l.seq[r.channel];if(r.snapshot){if(r.seq<c)return;l[u]=r.text}else{if(r.seq<=c)return;l[u]+=r.text}l.seq[r.channel]=r.seq,l.via=t,this.liveReplies.set(o,l),this.liveDirty.add(o),this.scheduleLiveRender()}runEnded(t){return vs(zr(this.runStates.get(t)||null))}scheduleLiveRender(){if(this.liveRenderTimer)return;const t=this.lastLiveRender+this.liveRenderIntervalMs-Date.now();if(t<=0){this.renderLiveReplies();return}this.liveRenderTimer=setTimeout(()=>{this.liveRenderTimer=null,this.renderLiveReplies()},t)}renderLiveReplies(){if(this.lastLiveRender=Date.now(),!this.liveDirty.size)return;const t=[...this.snapshot.messages];for(const n of this.liveDirty){const r=this.liveReplies.get(n);if(!r)continue;const o=this.liveMessage(r),l=t.findIndex(u=>u.id===o.id);l<0?t.push(o):t[l]=o,this.shownLiveCalls.add(n)}this.liveDirty.clear(),this.set({...this.snapshot,messages:t})}liveMessage(t){const n=t.runId!==this.rootRunId;return{id:`live:${t.runId}:${t.callId}`,role:"assistant",content:t.text,runId:t.runId,live:{callId:t.callId,reasoning:t.reasoning,...n?{caption:`sub-agent · ${t.nodeId||t.runId}`}:{}}}}closeLiveReply(t,n){this.closedLiveCalls.add(t);const r=this.liveReplies.get(t);if(!r){n==="restarted"&&this.shownLiveCalls.has(t)&&this.addMessage(this.restartNote(t));return}this.liveReplies.delete(t),this.liveDirty.delete(t);const o=`live:${r.runId}:${r.callId}`,l=this.snapshot.messages.findIndex(c=>c.id===o);if(l<0)return;const u=[...this.snapshot.messages];if(n==="restarted"){const c=this.restartNote(t);this.seenMessages.add(String(c.id)),u[l]=c}else if(n){const c=`live-end:${r.runId}:${r.callId}`;this.seenMessages.add(c),u[l]={id:c,role:"system",level:"warn",title:"Reply",runId:r.runId,content:n==="failed"?"The reply stopped because the model call failed.":"The reply stopped because the model call was cancelled."}}else u.splice(l,1);this.set({...this.snapshot,messages:u})}restartNote(t){const n=t.slice(0,t.indexOf(":"));return{id:`live-end:${t}`,role:"system",level:"info",title:"Reply",runId:n,content:"Reply restarted: the model call was interrupted and is running again."}}noteStreamUnavailable(t){const n=`${t.run_id}:${t.call_id}`;this.closeLiveReply(n),this.addMessage({id:`stream-unavailable:${t.run_id}:${t.detail||"unknown"}`,role:"system",level:"info",title:"Reply",runId:t.run_id,content:L1(t.detail)})}closeLiveRepliesOfRun(t){for(const n of[...this.liveReplies.values()])n.runId===t&&this.closeLiveReply(`${n.runId}:${n.callId}`)}closeLiveRepliesVia(t,n){for(const r of[...this.liveReplies.values()])(r.via===t||r.runId===t)&&this.closeLiveReply(`${r.runId}:${r.callId}`,n)}endLiveRepliesOfRun(t,n){const r=n==="failed"||n==="cancelled"?n:void 0;if(t===this.rootRunId){for(const o of[...this.liveReplies.values()])this.closeLiveReply(`${o.runId}:${o.callId}`,r);this.closedLiveCalls.clear(),this.shownLiveCalls.clear();return}this.closeLiveRepliesVia(t,r);for(const o of[...this.closedLiveCalls])o.startsWith(`${t}:`)&&this.closedLiveCalls.delete(o);for(const o of[...this.shownLiveCalls])o.startsWith(`${t}:`)&&this.shownLiveCalls.delete(o)}dropLiveRepliesVia(t){const n=new Set;for(const[r,o]of this.liveReplies)o.via===t&&(this.liveReplies.delete(r),this.liveDirty.delete(r),n.add(`live:${o.runId}:${o.callId}`));n.size&&this.set({...this.snapshot,messages:this.snapshot.messages.filter(r=>!n.has(String(r.id)))})}fail(t,n=!0){var r,o,l;Qa(t)&&(this.approvalEpoch+=1,this.toolApprovalStopped=!0,this.toolApprovalSuspended=!0,(o=(r=this.options).onAuthError)==null||o.call(r,t)),this.set({...this.snapshot,error:t instanceof Error?t.message:vt((l=St(t))==null?void 0:l.detail)||String(t),...Qa(t)?{autoApproveTools:!1}:{},...n?{connection:"disconnected"}:{}})}newCommandId(){const t=globalThis.crypto;if(t&&typeof t.randomUUID=="function")return t.randomUUID();if(t&&typeof t.getRandomValues=="function"){const n=t.getRandomValues(new Uint8Array(16));n[6]=n[6]&15|64,n[8]=n[8]&63|128;const r=Array.from(n,o=>o.toString(16).padStart(2,"0")).join("");return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20)}`}return`workflow-${Date.now()}-${Math.random().toString(36).slice(2)}`}updateRunState(t,n){var l;if(this.runStates.set(t,n),vs(zr(n))&&this.endLiveRepliesOfRun(t,zr(n)),t!==this.rootRunId){vs(zr(n))&&((l=this.snapshot.interaction)==null?void 0:l.runId)===t?this.set({...this.snapshot,interaction:null}):this.adoptDurableWait(t,n);return}const r=zr(n),o=vs(r);if(o){const u=ru(n.output);u&&this.upsertFinal(t,u,Py(n))}this.set({...this.snapshot,run:n,status:r,...o?{interaction:null,autoApproveTools:!1,displayStatus:""}:{}}),o||this.adoptDurableWait(t,n),(this.stopRequested||this.forcedStop)&&this.recomputeStop()}upsertFinal(t,n,r){this.closeLiveRepliesOfRun(t);const o=`final:${t}`;this.seenMessages.add(o);const l={id:o,role:"assistant",content:n,ts:r,runId:t,statistics:E_(this.snapshot.records).statistics},u=this.snapshot.messages.findIndex(f=>f.id===o||String(f.id||"").startsWith(`answer:${t}:`)&&f.content===n);if(u<0){this.set({...this.snapshot,messages:[...this.snapshot.messages,l]});return}const c=[...this.snapshot.messages];c[u]=l,this.set({...this.snapshot,messages:c})}async refreshRunState(t,n){var r;try{const o=St(await this.transport.getRun(t,(r=this.controller)==null?void 0:r.signal));o&&this.live(n)&&this.updateRunState(t,o)}catch(o){this.live(n)&&this.fail(o,!1)}}async pollRootLifecycle(t,n){var r;for(;this.live(n)&&this.rootRunId===t&&!vs(zr(this.runStates.get(t)||null));){if(await this.waitForRetry(2e3),!this.live(n)||this.rootRunId!==t||vs(zr(this.runStates.get(t)||null)))return;try{const o=St(await this.transport.getRun(t,(r=this.controller)==null?void 0:r.signal));o&&this.live(n)&&this.rootRunId===t&&this.updateRunState(t,o)}catch(o){if(!this.live(n))return;if(Qa(o)){this.fail(o);return}this.fail(o,!1)}}}waitForRetry(t){var o;const n=(o=this.controller)==null?void 0:o.signal;if(!n||n.aborted)return Promise.resolve();const r=n;return new Promise(l=>{const u=setTimeout(f,t),c=()=>{clearTimeout(u),f()};function f(){r.removeEventListener("abort",c),l()}r.addEventListener("abort",c,{once:!0})})}}function F1(e){const t=p.useMemo(()=>new D1(e.transport,{onAuthError:e.onAuthError,clientId:e.clientId,...e.liveRenderIntervalMs!==void 0?{liveRenderIntervalMs:e.liveRenderIntervalMs}:{}}),[e.transport,e.onAuthError,e.clientId,e.authScopeKey,e.liveRenderIntervalMs]),n=p.useSyncExternalStore(o=>t.subscribe(o),()=>t.getSnapshot(),()=>t.getSnapshot()),r=String(e.runId||"").trim();return p.useEffect(()=>{t.setToolApprovalPolicy(e.enabled===!1?{enabledTools:[],autoApproveTools:[]}:e.toolApprovalPolicy??null)},[t,e.toolApprovalPolicy,e.enabled]),p.useEffect(()=>{if(e.enabled===!1||!r){t.reset();return}return t.load(r),()=>t.reset()},[t,r,e.enabled]),{controller:t,snapshot:n}}function Hl(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function lr(e){return typeof e=="string"?e.trim():e==null?"":typeof e=="number"||typeof e=="boolean"?String(e):""}function Fy(e){return["session","workflow","run","global"].includes(e)?e:null}function tl(e){return{scope:lr(e==null?void 0:e.scope).toLowerCase(),name:lr(e==null?void 0:e.name)||lr(e==null?void 0:e.event_name),scopeId:lr(e==null?void 0:e.scope_id)||lr(e==null?void 0:e.scopeId),sessionId:lr(e==null?void 0:e.session_id)||lr(e==null?void 0:e.sessionId),workflowId:lr(e==null?void 0:e.workflow_id)||lr(e==null?void 0:e.workflowId),runId:lr(e==null?void 0:e.run_id)||lr(e==null?void 0:e.runId)}}function z1(e,t){const n=e.wait,r=lr(n.wait_key),o=[tl(n),tl(Hl(n.details))];for(const l of t){if(l.runId!==e.runId)continue;const u=l.record,c=Hl(u.result),f=Hl(c==null?void 0:c.wait),m=Hl(u.effect),_=Hl(m==null?void 0:m.payload);lr(f==null?void 0:f.wait_key)!==r&&lr(_==null?void 0:_.wait_key)!==r||o.push(tl(u),tl(_),tl(Hl(_==null?void 0:_.details)),tl(f),tl(Hl(f==null?void 0:f.details)))}return o}function M_(e,t){return t.scopeId?t.scopeId:e==="session"?t.sessionId:e==="workflow"?t.workflowId:e==="run"?t.runId:"global"}function Sx(e,t,n){return{scope:e,scopeId:t,name:n,...e==="session"?{sessionId:t}:{},...e==="workflow"?{workflowId:t}:{},...e==="run"?{runId:t}:{}}}function B1(e,t,n){if(!n)return null;const r=`evt:${t}:${n}:`;if(!e.startsWith(r))return null;const o=e.slice(r.length);return o?Sx(t,n,o):null}function U1(e,t=[],n){if(!e)return{target:null,error:"No event wait is available."};const r=lr(e.wait.wait_key),o=/^evt:(session|workflow|run|global):/.exec(r);if(!o)return{target:null,error:"The gateway did not provide a canonical event wait key."};const l=Fy(o[1]);if(!l)return{target:null,error:"The event wait uses an unsupported scope."};const u=z1(e,Array.isArray(t)?t:[]),c=new Map;for(const w of u){const x=Fy(w.scope);if(!x||!w.name)continue;if(x!==l)return{target:null,error:"Event metadata conflicts with the canonical wait scope."};const j=`evt:${x}:`,b=`:${w.name}`;if(!r.startsWith(j)||!r.endsWith(b)||r.length<=j.length+b.length)return{target:null,error:"Event metadata does not exactly match the canonical wait key."};const N=r.slice(j.length,-b.length),C=M_(x,w);if(C&&C!==N)return{target:null,error:"Event metadata conflicts with the canonical wait target."};const E=Sx(x,N,w.name);c.set(`${E.scope}\0${E.scopeId}\0${E.name}`,E)}if(c.size>1)return{target:null,error:"Multiple event targets match this wait; routing is unavailable."};if(c.size===1)return{target:[...c.values()][0]};const f=new Set;l==="run"&&f.add(e.runId),l==="global"&&f.add("global");for(const w of u){const x=M_(l,w);x&&f.add(x)}if(lr(n==null?void 0:n.run_id)===e.runId){const w=tl(n||null),x=M_(l,w);x&&f.add(x)}const _=[...f].map(w=>B1(r,l,w)).filter(w=>!!w),g=new Map(_.map(w=>[`${w.scope}\0${w.scopeId}\0${w.name}`,w]));return g.size===1?{target:[...g.values()][0]}:g.size>1?{target:null,error:"The event key is ambiguous for the available scope metadata."}:{target:null,error:"The gateway did not provide enough canonical event routing metadata."}}const _g=e=>wt(`runs/${encodeURIComponent(e)}/workspace`);function W1(e){return _g(e)}function q1(e,t){return`${_g(e)}/files?${new URLSearchParams({path:t,recursive:"false"})}`}function H1(e,t){return`${_g(e)}/content?${new URLSearchParams({path:t})}`}async function Tm(e,t){let n="";try{const r=await e.text();try{const o=JSON.parse(r),l=(o==null?void 0:o.detail)??(o==null?void 0:o.error)??(o==null?void 0:o.message);n=typeof l=="string"?l:l&&typeof l.message=="string"?l.message:r}catch{n=r}}catch{n=""}return new Error(`${t} (HTTP ${e.status}): ${n.trim()||e.statusText||"no reason given"}`)}function V1(e,t){const n=e&&typeof e=="object"&&!Array.isArray(e)?e:null,r=u=>{throw new Error(`Unexpected /workspace/files response from the gateway: ${u}.`)};if(!n)return r("not an object");Array.isArray(n.entries)||r("no `entries` list"),typeof n.truncated!="boolean"&&r("no `truncated` flag");const o=n.entries.map((u,c)=>{const f=u&&typeof u=="object"?u:{};return(typeof f.name!="string"||typeof f.path!="string"||f.type!=="file"&&f.type!=="dir")&&r(`entry ${c+1} lacks a name, path or file/dir type`),f}),l=n.hidden&&typeof n.hidden=="object"&&!Array.isArray(n.hidden)?n.hidden:void 0;return{path:typeof n.path=="string"?n.path:t,entries:o,truncated:n.truncated,...l?{hidden:l}:{}}}async function G1(e,t,n){const r=await e(W1(t),{signal:n});if(!r.ok)throw await Tm(r,"The workspace is not available");const o=await r.json();if(!o||typeof o.workspace_root!="string"||typeof o.exists!="boolean")throw new Error("Unexpected /workspace response from the gateway: no `workspace_root` / `exists`.");return o}async function K1(e,t,n,r){const o=await e(q1(t,n),{signal:r});if(!o.ok)throw await Tm(o,"The folder could not be listed");return V1(await o.json(),n)}async function Y1(e,t,n,r){const o=await e(H1(t,n),{signal:r});if(!o.ok)throw await Tm(o,"The file could not be read");return await o.blob()}async function J1(e,t,n,r){const o=await G1(e,t,r);return{where:o,listing:o.exists?await K1(e,t,n,r):null}}function X1(e){const t=String(e||"").split("/").filter(Boolean),n=[{label:"Workspace",path:""}];return t.forEach((r,o)=>n.push({label:r,path:t.slice(0,o+1).join("/")})),n}function Z1(e){if(typeof e!="number"||!Number.isFinite(e)||e<0)return"";if(e<1024)return`${e} B`;const t=["KiB","MiB","GiB","TiB"];let n=e/1024,r=0;for(;n>=1024&&r<t.length-1;)n/=1024,r+=1;return`${n<10?n.toFixed(1):Math.round(n)} ${t[r]}`}function Q1(e){return[...e].sort((t,n)=>t.type===n.type?t.name.localeCompare(n.name):t.type==="dir"?-1:1)}function eN(e){const t=e.hidden||{},n=Number(t.blocked||0)+Number(t.outside_links||0)+Number(t.other||0),r=[];return n>0&&r.push(`${n} ${n===1?"entry":"entries"} hidden by the gateway's workspace rules`),e.truncated&&r.push("the list is truncated"),r.join("; ")}const tN=new Set(["image/png","image/jpeg","image/gif","image/webp","image/avif","image/bmp","application/pdf","text/plain","application/json"]);function nN(e){const t=String(e||"").split(";",1)[0].trim().toLowerCase();return tN.has(t)?{mode:"open",type:t}:t.startsWith("text/")||t.endsWith("+xml")||t.endsWith("+json")||t.endsWith("/xml")||t.endsWith("/javascript")||t.endsWith("/x-yaml")||t.endsWith("/toml")?{mode:"open",type:"text/plain;charset=utf-8"}:{mode:"download"}}function Nx(e,t,n){const r=n==="open"?nN(e.type):{mode:"download"},o=r.mode==="open"&&r.type!==e.type?new Blob([e],{type:r.type}):e,l=URL.createObjectURL(o);if(r.mode==="open")window.open(l,"_blank","noopener");else{const u=document.createElement("a");u.href=l,u.download=t,document.body.appendChild(u),u.click(),u.remove()}window.setTimeout(()=>URL.revokeObjectURL(l),6e4)}async function sN(e,t,n){const r=await e(Ek(t),{signal:n.signal});if(!r.ok)throw await Tm(r,`${n.name} could not be read`);Nx(await r.blob(),n.name,n.mode??"open")}function Cx(e){const{fetchGateway:t,runId:n}=e,[r,o]=p.useState({runId:n,path:""}),l=r.runId===n?r.path:"",[u,c]=p.useState(null),[f,m]=p.useState(""),[_,g]=p.useState(!!n),[w,x]=p.useState(""),[j,b]=p.useState(0);p.useEffect(()=>{if(!n)return;const E=new AbortController;return g(!0),m(""),(async()=>{try{const T=await J1(t,n,l,E.signal);E.signal.aborted||c({runId:n,...T})}catch(T){E.signal.aborted||m(String((T==null?void 0:T.message)||T))}finally{E.signal.aborted||g(!1)}})(),()=>E.abort()},[t,n,l,j,e.refreshKey]);const N=u&&u.runId===n?u:null,C=p.useCallback(async(E,T)=>{x(E.path),m("");try{Nx(await Y1(t,n,E.path),E.name,T)}catch(I){m(String((I==null?void 0:I.message)||I))}finally{x("")}},[t,n]);return s.jsx(rN,{title:e.title,note:e.note,where:(N==null?void 0:N.where)??null,path:l,listing:(N==null?void 0:N.listing)??null,error:f,loading:_,fileBusy:w,selectedPath:e.selectedPath,className:e.className,onNavigate:E=>o({runId:n,path:E}),onRefresh:()=>b(E=>E+1),onFile:e.onSelectFile?void 0:(E,T)=>void C(E,T),onSelectFile:e.onSelectFile,onClose:e.onClose})}function rN(e){var r,o,l,u;const t=e.listing?eN(e.listing):"",n=(o=(r=e.where)==null?void 0:r.host)==null?void 0:o.hostname;return s.jsxs("section",{className:`pc-ws${e.className?` ${e.className}`:""}`,"aria-label":e.title,"data-workspace-root":((l=e.where)==null?void 0:l.workspace_root)||void 0,children:[s.jsxs("header",{className:"pc-ws__head",children:[s.jsxs("span",{className:"pc-ws__title",children:[s.jsx(et,{name:"folder",size:15})," ",e.title]}),s.jsx("span",{className:"pc-ws__spacer"}),s.jsx("button",{type:"button",className:"pc-ws__icon-btn","data-action":"refresh-folder",onClick:e.onRefresh,disabled:e.loading,title:"Refresh","aria-label":"Refresh the folder",children:s.jsx(et,{name:"refresh",size:14})}),e.onClose?s.jsx("button",{type:"button",className:"pc-ws__icon-btn","data-action":"close-folder",onClick:e.onClose,title:"Close","aria-label":"Close the file browser",children:s.jsx(et,{name:"x",size:14})}):null]}),e.where?s.jsxs("div",{className:"pc-ws__root",children:[s.jsx("code",{children:e.where.workspace_root}),n&&((u=e.where.host)==null?void 0:u.caller_is_this_machine)!==!0?s.jsxs("span",{className:"pc-ws__muted",children:[" on the gateway host ",n]}):null]}):null,e.note?s.jsx("div",{className:"pc-ws__muted",children:e.note}):null,s.jsx("nav",{className:"pc-ws__crumbs","aria-label":"Folder",children:X1(e.path).map((c,f,m)=>f===m.length-1?s.jsx("span",{"aria-current":"page",children:c.label},c.path):s.jsxs(ve.Fragment,{children:[s.jsx("button",{type:"button",className:"pc-ws__crumb",onClick:()=>e.onNavigate(c.path),children:c.label}),s.jsx("span",{className:"pc-ws__muted",children:" / "})]},c.path))}),e.error?s.jsx("div",{className:"pc-ws__error",role:"alert",children:e.error}):null,e.loading&&!e.listing?s.jsx("div",{className:"pc-ws__muted",role:"status",children:"Loading…"}):null,e.where&&!e.where.exists?s.jsx("div",{className:"pc-ws__muted",children:"The folder does not exist yet: nothing has been written."}):null,e.listing?e.listing.entries.length?s.jsx("ul",{className:"pc-ws__entries",children:Q1(e.listing.entries).map(c=>s.jsx("li",{className:`pc-ws__entry${e.selectedPath===c.path?" is-selected":""}`,"data-type":c.type,"data-path":c.path,children:c.type==="dir"?s.jsxs("button",{type:"button",className:"pc-ws__name","data-action":"open-dir",onClick:()=>e.onNavigate(c.path),children:[s.jsx(et,{name:"folder",size:14})," ",c.name,"/"]}):s.jsxs(s.Fragment,{children:[e.onSelectFile?s.jsxs("button",{type:"button",className:"pc-ws__name","data-action":"select-file","aria-pressed":e.selectedPath===c.path,onClick:()=>{var f;return(f=e.onSelectFile)==null?void 0:f.call(e,c)},children:[s.jsx(et,{name:"file",size:14})," ",c.name]}):s.jsxs("span",{className:"pc-ws__name",children:[s.jsx(et,{name:"file",size:14})," ",c.name]}),s.jsx("span",{className:"pc-ws__size",children:Z1(c.size_bytes)}),e.onFile?s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"pc-ws__btn","data-action":"open-file",disabled:e.fileBusy===c.path,onClick:()=>{var f;return(f=e.onFile)==null?void 0:f.call(e,c,"open")},children:"Open"}),s.jsx("button",{type:"button",className:"pc-ws__icon-btn","data-action":"download-file",disabled:e.fileBusy===c.path,onClick:()=>{var f;return(f=e.onFile)==null?void 0:f.call(e,c,"download")},title:`Download ${c.name}`,"aria-label":`Download ${c.name}`,children:s.jsx(et,{name:"download",size:14})})]}):null]})},c.path))}):s.jsx("div",{className:"pc-ws__muted",children:"This folder is empty."}):null,t?s.jsx("div",{className:"pc-ws__muted","data-hidden-note":"true",children:t}):null]})}function Ex(e){return s.jsx(_x,{text:e,images:"link"})}const iN={trigger:"Trigger",answer:"Automation"};function Ax(e,t){return s.jsx(fg,{...t,message:{id:`${e.runId}:${e.kind}`,role:e.role,content:e.text,title:iN[e.kind],runId:e.runId},images:"link"})}const oN={renderText:Ex,renderTurn:Ax};function aN(e){const{fetchGateway:t,messageProps:n,...r}=e,o=r.onOpenResource??(t?l=>sN(t,l.url,{name:l.name}):void 0);return s.jsx(RS,{...r,onOpenResource:o,...oN,renderTurn:l=>Ax(l,n)})}function lN(e,t,n={}){if(!e)return null;const r=e.wait,o=`${e.runId}:${r.wait_key}:${e.stepId||""}`,l=r.details||{};if(l.mode==="approval_required"||l.kind==="tool_approval"){const c=Array.isArray(l.tool_calls)?l.tool_calls:[],f={runId:e.runId,waitKey:String(r.wait_key||""),stepId:e.stepId},m=[...new Set(c.map(g=>String((g==null?void 0:g.name)||"tool")))],_=n.onPermissionsAll;return{id:o,kind:"tool-approval",title:`${c.length||"Requested"} ${c.length===1?"action needs":"actions need"} permission`,toolName:m.join(", ")||"the requested tools",description:"Review the targets below. Allow once approves this batch only.",detail:s.jsxs("div",{className:"pc-approval-summary",children:[s.jsx(yx,{tools:c.map((g,w)=>({id:String((g==null?void 0:g.call_id)||(g==null?void 0:g.id)||w),runId:e.runId,name:(g==null?void 0:g.name)||"Tool",arguments:g==null?void 0:g.arguments,status:"waiting"}))}),s.jsxs("details",{children:[s.jsx("summary",{children:"Review full tool arguments (JSON)"}),s.jsx(Is,{value:c.length?c:l})]})]}),approveLabel:"Allow once",denyLabel:"Deny",approveAllLabel:_?"Allow all enabled tools":void 0,approveAllDescription:_?"Sets permissions: all for this Gateway account, including future turns. Unchecked tools stay unavailable; explicit Ask overrides and Gateway restrictions remain enforced. Questions still need your answer.":void 0,onApproveAll:_?async()=>{await t.approveWithPolicyChange(f,()=>{_()})}:void 0,onApprove:async()=>{await t.approve(!0,f)},onDeny:async()=>{await t.approve(!1,f)}}}if(r.reason==="user"||r.reason==="ask_user")return{id:o,kind:"ask-user",title:"A question for you",prompt:String(r.prompt||l.prompt||"How would you like to continue?"),allowFreeText:r.allow_free_text!==!1,choices:(Array.isArray(r.choices)?r.choices:[]).map(c=>typeof c=="object"&&c!==null?{id:String(c.value??c.id??c.label),label:String(c.label??c.text??c.value??c.id),description:c.description}:{id:String(c),label:String(c)}),onSubmit:async c=>{await t.resume(c)}};const u=String(r.wait_key||"");if(r.reason==="event"||u.startsWith("evt:")){const c=U1(e,n.records||[],n.currentRun??null),f=c.target,m=(f==null?void 0:f.name)||"";return{id:o,kind:"event-wait",title:f?"Waiting for an event":"Event routing unavailable",eventName:m,prompt:String(r.prompt||`This workflow will continue when “${m||"its trigger"}” arrives.`),description:f?"You can also send the expected event here.":`This event cannot be sent safely. ${c.error}`,initialPayload:"{}",payloadLabel:"Event data (JSON)",sendLabel:"Send event",onSend:async _=>{if(!f)throw new Error(c.error);const g=JSON.parse(_||"{}"),w={name:f.name,scope:f.scope,payload:g};f.scope==="session"?w.session_id=f.scopeId:f.scope==="workflow"?w.workflow_id=f.scopeId:f.scope==="run"&&(w.run_id=f.scopeId),await t.emitEvent(w)}}}return null}const cN='# AbstractObserver\n\n> Gateway-only observability UI (Web/PWA) for AbstractFramework runs: a browser SPA + tiny Node.js CLI that connects to an AbstractGateway HTTP API (HTTP fetch + SSE ledger streaming) and submits durable commands.\n\nThis repository is UI-only:\n- The packaged CLI (`bin/cli.js` + `bin/server.js`) serves `dist/` (SPA fallback) at `/` or through the gateway at `/apps/observer/` (app-server mount contract: identity header, `<base href>`, cookie path, forwarded client address) and proxies `api/` to the Gateway after browser-session sign-in, using `@abstractframework/app-server`.\n- The browser talks to same-origin `/api` in hosted mode; direct Gateway URLs remain available for local development via `src/lib/gateway_client.ts` (treat this file as the source of truth for HTTP endpoints and request shapes).\n- Hosted sign-in uses Gateway URL + user + token only to create an app-scoped browser session. Settings persistence strips Gateway bearer tokens. With `@abstractframework/app-server` 0.1.10 or newer the proxy sends the browser\'s connection address as `X-Forwarded-For` and `X-AbstractFramework-App-Proxy: abstractobserver` to the Gateway.\n- On non-local hosted UI hostnames, the server-configured Gateway URL is authoritative; browser-supplied Gateway URL changes are rejected unless `ABSTRACTOBSERVER_ALLOW_REMOTE_BROWSER_GATEWAY_CONFIG=1` is enabled behind access control. Forwarded host headers are trusted only when `ABSTRACTOBSERVER_TRUST_PROXY_HEADERS=1` or `ABSTRACTGATEWAY_TRUST_PROXY_HEADERS=1`.\n\n## Quickstart\n- Run packaged UI server (no build step): `npx --yes --package @abstractframework/observer -- abstractobserver`\n- Dev server (Vite; proxies `/api` in dev): `npm install && npm run dev`\n- Unit tests (Vitest): `npm test`\n- Production build (writes `dist/`): `npm run build`\n- Regenerate `llms-full.txt`: `npm run llms:full`\n\nNotes:\n- Build output lives in `dist/` and is served by `bin/cli.js` (don’t edit `dist/` manually).\n- `@abstractframework/ui-kit` and `@abstractframework/panel-chat` are npm dependencies; the monitor packages are Vite aliases to sibling `../abstractuic/*/src` (see `vite.config.ts` and `docs/development.md`).\n- Responsive layout (phones, tablets, small windows): `docs/getting-started.md` → "Responsive layout"; rules in `src/ui/responsive.css`.\n- On/off switches and opening the Observer over plain http from another computer (voice needs https): `docs/getting-started.md` → "Switches", "Open the Observer from another computer over http"; fallbacks in `src/lib/secure-context.ts`.\n- `llms.txt` format reference: https://llmstxt.org/\n\n## Documentation (start here)\n- [README](README.md): Install and quickstart\n- [Getting started](docs/getting-started.md): Run the UI and connect to a gateway; Ask about a run (whole conversation, History note when the 50k-token window drops older messages, error cards never sent back) vs the top-bar Assistant (one gateway session per conversation, New conversation, no tools)\n- [FAQ](docs/faq.md): Common questions (grounded in code), including the CLI `/api` session proxy, the About dialog, chat history windows and the tool-less Assistant\n- [Docs index](docs/README.md): What to read next\n- [Architecture](docs/architecture.md): Components, data flow, diagrams\n- [Configuration](docs/configuration.md): launch flags, serving under the gateway at /apps/observer/, UI settings, deployment patterns\n- [API](docs/api.md): Gateway endpoints used by the UI, including Runtime Activity run pages and canonical artifact envelope search/stats for Runtime Artifact Explorer\n- [Automations](docs/automations.md): configurable growing-context budgets and result email; Launch → Automate (what, when in UTC intervals, independent/growing context, tool approval), the Automations page (icon controls, Edit: the row\'s Edit opens the form — title, task, interval, context, tools —, 409 conflicts), runs as a conversation, answering waits by kind, the automation\'s files (browse, open, download through the gateway), Discuss as an in-page chat with a fork, automation tags on Board/Observe/System, legacy schedules and Recreate, the stub gateway\n- [Development](docs/development.md): Local dev, workspace deps, tests, build\n- [Security](docs/security.md): Trust boundaries and operational guidance\n- [Troubleshooting](docs/troubleshooting.md): Common issues and fixes (CORS, mixed content, 401 under `/api`, About shows the gateway unavailable, stale service worker, automations)\n\n## Key entrypoints (code)\n- [CLI](bin/cli.js) and [app server](bin/server.js): launch flags (`--gateway-url`, `--port`, `--host`, `--monitor-gpu`, `--entity-app-url`, `--gateway-dir`), mount-capable handler, session proxy, folder reveal (browsers on this machine only)\n- [App shell + pages](src/ui/app.tsx): settings, page routing, observe/launch flows, durable commands\n- [Gateway client](src/lib/gateway_client.ts): HTTP client + SSE ledger streaming (API source of truth)\n- [Automations rules + controller](src/ui/automations.ts): workflow choice (`@default`), create body, run tags, capability gate, legacy prefill, typed wait answers, page controller\n- [Automations page](src/ui/automations_page.tsx) and [Automate fields](src/ui/automate_form.tsx): the page, rows and the ui-kit `AutomationPanel` wiring; the When/Context/Tools fields\n- [Discussion chat](src/ui/automation_discussion.tsx): panel-chat `WorkflowChat` + `presentInteraction` over the gateway client; folders through panel-chat `WorkspaceBrowser` (`/runs/{id}/workspace*`)\n- [Automations stub gateway](scripts/automations_stub_server.mjs): dev/test stub serving the ui-kit fixtures\n- [Vite config](vite.config.ts): workspace aliases + dev session proxy and `/api` fallback proxy\n- [Package metadata](package.json): npm name/version, scripts, Node engine\n- [llms-full generator](scripts/generate-llms-full.mjs): defines which files are embedded into `llms-full.txt`\n\n## Ecosystem context\n- [AbstractFramework](https://github.com/lpalbou/AbstractFramework): ecosystem entrypoint and component map\n- [AbstractRuntime](https://github.com/lpalbou/abstractruntime): durable workflow runtime behind the gateway ledger\n- [AbstractCore](https://github.com/lpalbou/abstractcore): unified LLM + tools layer commonly used by workflows\n\n## Common tasks\n- Add/change a gateway capability: update `src/lib/gateway_client.ts` (source of truth) → update `docs/api.md` → run `npm test` + `npm run build`.\n- Change CLI behavior/config: update `bin/cli.js` / `bin/server.js` → update `docs/configuration.md` → run `npm run build`.\n- Update docs for agents: edit docs → regenerate `llms-full.txt` with `npm run llms:full`.\n\n## Optional (project meta)\n- [Changelog](CHANGELOG.md): Release notes\n- [Contributing](CONTRIBUTING.md): How to develop and submit changes\n- [Security policy](SECURITY.md): Responsible vulnerability reporting\n- [Acknowledgments](ACKNOWLEDGMENTS.md): Credits\n- [Code of conduct](CODE_OF_CONDUCT.md): Conduct expectations and reporting\n- [License](LICENSE): MIT license\n';function xs(){return Nm()}function uN(e,t){return[...e.filter(n=>!n.local_error),t].map(n=>({role:n.role,content:n.content}))}function Mh(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?Math.trunc(e):0}function dN(e){const t=Mh(e==null?void 0:e.dropped_messages);if(!e||t<=0)return null;const n=Mh(e.replayed_messages),r=Mh(e.dropped_tokens),o=Mh(e.max_tokens),l=[`Earlier messages not replayed: ${t.toLocaleString("en-US")}${r?` (~${r.toLocaleString("en-US")} tokens)`:""}.`,`The model read the newest ${n.toLocaleString("en-US")} message${n===1?"":"s"}`+(o?` (history window: the most recent ${o.toLocaleString("en-US")} tokens of whole messages).`:".")];return e.oversize_turn_kept&&l.push("Your latest message alone is larger than the window; it was sent whole."),l.join(" ")}function $x(e){const t=dN(e.history);return t?s.jsx(fg,{message:{role:"system",level:"info",title:"History",content:t}}):null}const fN=1500,hN=12e4;function mN(e,t){return new Promise((n,r)=>{const o=setTimeout(n,e);t.addEventListener("abort",()=>{clearTimeout(o),r(new DOMException("aborted","AbortError"))},{once:!0})})}const _N=["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) ===",cN,"=== END DOCUMENTATION ==="].join(`
67
- `),pN="observer-docs-assistant";function zy(){return`${pN}:${xs()}`}function gN(e){return{prompt:e,system:_N,tools:[],use_session_history:!0,use_context:!0}}function yN(e){var t,n;for(let r=e.length-1;r>=0;r--){const o=e[r],l=o!=null&&o.result&&typeof o.result=="object"?o.result:null,u=[(t=l==null?void 0:l.response)==null?void 0:t.content,(n=l==null?void 0:l.response)==null?void 0:n.text,l==null?void 0:l.output,l==null?void 0:l.content,l==null?void 0:l.text];for(const c of u){const f=typeof c=="string"?c.trim():"";if(f)return f}}return""}function wN(e,t,n=()=>{}){return async(r,o)=>{var f;const l=e(),u=await l.start_run(null,gN(r),{bundle_id:"basic-agent",session_id:t()}),c=Date.now();for(;;){if(await mN(fN,o.signal),Date.now()-c>hN)throw new Error("The assistant run timed out (120s). The run is still visible on the Observe page.");const m=await l.get_run(u),_=String((m==null?void 0:m.status)||"").trim().toLowerCase();if(_==="failed"||_==="cancelled"){const g=String(((f=m==null?void 0:m.error)==null?void 0:f.message)||(m==null?void 0:m.error)||"run "+_).slice(0,400);throw new Error(`The assistant run ${_}: ${g}`)}if(_==="completed"){n((m==null?void 0:m.session_history)??null);const g=await l.get_ledger(u,{after:0,limit:500,signal:o.signal});return yN(g.items)||"(the run completed but produced no readable answer — inspect it on the Observe page)"}}}}function vN(e){const t=p.useRef(e.gateway);t.current=e.gateway;const n=p.useRef(zy()),[r,o]=p.useState([]),[l,u]=p.useState(null),c=p.useMemo(()=>wN(()=>t.current,()=>n.current,u),[]),[f]=p.useState(void 0),m=()=>{n.current=zy(),o([]),u(null)};return s.jsxs(qk,{open:e.open,onClose:e.onClose,label:"Observer assistant",title:"Assistant",width:420,topOffset:e.topOffset,headerActions:s.jsx("button",{className:"btn",type:"button",disabled:!r.length,onClick:m,title:"Start a new conversation (nothing earlier is replayed)",children:"New conversation"}),children:[s.jsx($x,{history:l}),s.jsx(m1,{ask:c,messages:r,onMessagesChange:o,assistantName:"Observer",placeholder:"Ask about the observer…",blockedNotice:e.connected?f:"Connect to the gateway to use the assistant.",suggestions:["How do I see why a run failed?","Where do I find the artifacts a run produced?","What does the Board's Review column mean?","How do I launch a workflow on a schedule?"],emptyState:s.jsx("div",{children:"Answers are grounded in this app's documentation. Each question runs once through the connected gateway's basic agent."})})]})}function xN(e,t){switch(t.type){case"open":return!0;case"close":case"page_change":case"layout_change":return!1;case"escape":return t.default_prevented||t.other_modal_open?e:!1}}function bN(e,t){return e?t?{aside:{"aria-label":"Navigation",role:"dialog","aria-modal":"true"},main:{inert:"","aria-hidden":"true"}}:{aside:{"aria-label":"Navigation",inert:"","aria-hidden":"true"},main:{}}:{aside:{"aria-label":"Navigation"},main:{}}}function kN(e,t,n){return e<=0?-1:t<0?n?e-1:0:(t+(n?e-1:1))%e}const jN='a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';function SN(e){return typeof document>"u"?!1:Array.from(document.querySelectorAll('[role="dialog"][aria-modal="true"]')).some(t=>t!==e)}function NN(e){const[t,n]=p.useReducer(xN,!1),r=p.useRef(null),o=p.useRef(null),l=p.useRef(!1);return p.useEffect(()=>{n({type:"page_change"})},[e.page]),p.useEffect(()=>{n({type:"layout_change"})},[e.is_drawer]),p.useEffect(()=>{var u;if(t){l.current=!0;const c=o.current,f=(c==null?void 0:c.querySelector(".shell_nav_item.active"))||(c==null?void 0:c.querySelector(".shell_nav_item"));f==null||f.focus();const m=_=>{if(_.key==="Escape"){n({type:"escape",default_prevented:_.defaultPrevented,other_modal_open:SN(o.current)});return}if(_.key!=="Tab"||!o.current)return;const g=Array.from(o.current.querySelectorAll(jN)).filter(x=>x.offsetParent!==null||x===document.activeElement),w=kN(g.length,g.indexOf(document.activeElement),_.shiftKey);w>=0&&(_.preventDefault(),g[w].focus())};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)}l.current&&(l.current=!1,(u=r.current)==null||u.focus())},[t]),{open:t,set_open:u=>n({type:u?"open":"close"}),toggle_ref:r,sidebar_ref:o,attrs:bN(e.is_drawer,t)}}const CN="api/local/reveal",EN="sw.js",Ep="#run/";function AN(e){return`${Ep}${encodeURIComponent(String(e||"").trim())}`}function Tx(e){const t=String(e||"");if(!t.startsWith(Ep))return"";const n=t.slice(Ep.length).split("?")[0];if(!n||n.includes("/"))return"";try{return decodeURIComponent(n).trim()}catch{return""}}function $N(e){return`Run ${e} cannot be opened: it does not exist on this gateway, or your account cannot see it.`}function TN(e){const t=Tx(e.hash);if(t)return t;const n=u=>/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(u),r=u=>{const c=u.split("/").filter(Boolean);return c.length?c[c.length-1].trim():""},o=r(String(e.hash||"").replace(/^#/,""));if(n(o))return o;const l=r(String(e.pathname||""));return n(l)?l:""}const MN={llm_call:"llm_call",tool_calls:"tool",tool_invoke:"tool",entity_tools_execute:"tool",start_subworkflow:"subflow",emit_event:"event",wait_event:"wait",wait_until:"wait",resume:"resume",ask_user:"ask",answer_user:"answer",model_residency:"model",memory_query:"memory",memory_tag:"memory",memory_compact:"memory",memory_note:"memory",memory_rehydrate:"memory",memory_kg_assert:"memory",memory_kg_query:"memory",memory_kg_resolve:"memory",memory_recall:"memory",memory_access:"memory",memory_form:"memory",memory_adjust:"memory",memory_appraise:"memory",memory_consolidate:"memory",memory_probe:"memory",memory_tend:"memory",diary_write:"memory",diary_read:"memory",life_query:"memory",entity_tools_query:"memory",vars_query:"memory"},RN=new Set(["wait","resume","memory","model","node"]),LN=new Set(["abstract.status","abstract.progress","abstract.steer_seen","abstract.summary"]),IN={llm_call:"LLM call",tool:"Tools",subflow:"Subflow",event:"Event",wait:"Wait",resume:"Resume",ask:"Question",answer:"Answer",memory:"Memory",model:"Model",node:"Node",other:"Effect"};function ON(e){const t=String(e||"").trim();return t?MN[t]||"other":"node"}function PN(e,t,n){return n?!1:e==="event"?LN.has(String(t||"").trim()):RN.has(e)}const DN=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function FN(e){const t=new TextEncoder().encode(e),n=t.length*8,r=t.length+9+63>>6<<6,o=new Uint8Array(r);o.set(t),o[t.length]=128;const l=new DataView(o.buffer);l.setUint32(r-8,Math.floor(n/4294967296)),l.setUint32(r-4,n>>>0);const u=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),c=new Uint32Array(64);for(let f=0;f<r;f+=64){for(let C=0;C<16;C++)c[C]=l.getUint32(f+C*4);for(let C=16;C<64;C++){const E=c[C-15],T=c[C-2],I=(E>>>7|E<<25)^(E>>>18|E<<14)^E>>>3,K=(T>>>17|T<<15)^(T>>>19|T<<13)^T>>>10;c[C]=c[C-16]+I+c[C-7]+K>>>0}let[m,_,g,w,x,j,b,N]=u;for(let C=0;C<64;C++){const E=(x>>>6|x<<26)^(x>>>11|x<<21)^(x>>>25|x<<7),T=x&j^~x&b,I=N+E+T+DN[C]+c[C]>>>0,K=(m>>>2|m<<30)^(m>>>13|m<<19)^(m>>>22|m<<10),U=m&_^m&g^_&g,J=K+U>>>0;N=b,b=j,j=x,x=w+I>>>0,w=g,g=_,_=m,m=I+J>>>0}u[0]=u[0]+m>>>0,u[1]=u[1]+_>>>0,u[2]=u[2]+g>>>0,u[3]=u[3]+w>>>0,u[4]=u[4]+x>>>0,u[5]=u[5]+j>>>0,u[6]=u[6]+b>>>0,u[7]=u[7]+N>>>0}return Array.from(u,f=>f.toString(16).padStart(8,"0")).join("")}const Ap="$slim";function zN(e){return!!(e&&typeof e=="object"&&!Array.isArray(e)&&e[Ap]&&typeof e[Ap]=="object")}function BN(e){const t=new Map;for(const n of e||[]){if(!n||typeof n!="object"||String(n.status||"")!=="started")continue;const r=String(n.step_id||""),o=n.effect&&typeof n.effect=="object"?n.effect.payload:null;r&&o&&typeof o=="object"&&!t.has(r)&&t.set(r,o)}return t}function UN(e,t){const n=[];for(const r of t)if(r==="system"){if(typeof e.system_prompt!="string"||!e.system_prompt)return null;n.push({role:"system",content:e.system_prompt})}else if(r==="messages"){if(!Array.isArray(e.messages))return null;for(const o of e.messages)o&&typeof o=="object"&&n.push({...o})}else if(r==="prompt"){if(typeof e.prompt!="string"||!e.prompt)return null;n.push({role:"user",content:e.prompt})}else return null;return n}function WN(e,t){const n=e&&e[Ap];if(!n||typeof n!="object")return{state:"missing",reason:"not a $slim marker"};const r=t.get(String(n.step_id||""));if(!r)return{state:"missing",reason:"its started record is not in the loaded ledger"};let o;if(n.kind==="started_payload_field"){const u=String(n.field||"");if(!(u in r))return{state:"missing",reason:`the started record has no "${u}" field`};o=r[u]}else if(n.kind==="started_messages_layout"){if(o=Array.isArray(n.layout)?UN(r,n.layout.map(String)):null,!o)return{state:"missing",reason:"the started record cannot rebuild these messages"}}else return{state:"missing",reason:`unknown $slim kind "${String(n.kind||"")}"`};if(Array.isArray(n.appendix)&&n.appendix.length){if(!Array.isArray(o))return{state:"missing",reason:"appendix on a non-list value"};const u=o.map(f=>f&&typeof f=="object"?{...f}:f),c=[...n.appendix].sort((f,m)=>Number((f==null?void 0:f.at)??-1)-Number((m==null?void 0:m.at)??-1));for(const f of c){const m=Number(f==null?void 0:f.at);if(!Number.isInteger(m)||m<0||m>u.length)return{state:"missing",reason:"appendix position out of range"};u.splice(m,0,f.item)}o=u}return FN(JSON.stringify(o))!==String(n.sha256||"")?{state:"unverified",value:o,reason:"checksum differs from the record"}:{state:"resolved",value:o}}function qN(e,t){const n=[],r=[],o=(l,u,c)=>{if(c>14)return l;if(zN(l)){const f=WN(l,t);return f.state==="missing"?(n.push({path:u,reason:f.reason}),l):(f.state==="unverified"&&r.push({path:u,reason:f.reason}),f.value)}if(Array.isArray(l)){let f=null;return l.forEach((m,_)=>{const g=o(m,`${u}[${_}]`,c+1);g!==m&&((f??(f=[...l]))[_]=g)}),f??l}if(l&&typeof l=="object"){let f=null;for(const m of Object.keys(l)){const _=o(l[m],u?`${u}.${m}`:m,c+1);_!==l[m]&&((f??(f={...l}))[m]=_)}return f??l}return l};return{value:o(e,"",0),unresolved:n,unverified:r}}function By(e){const t=Date.parse(String(e||""));return Number.isFinite(t)?t:null}function Mx(e){const t=e==null?void 0:e.result;return t&&typeof t=="object"&&Array.isArray(t.results)?t.results:[]}function HN(e,t){return e?String(e.status||"")==="failed"||e.error?!0:t==="tool"&&Mx(e).some(n=>n&&n.success===!1):!1}function Rx(e,t){var m,_,g,w,x,j;const n=String(t||"").trim(),r=(e||[]).filter(b=>b&&b.record&&String(b.run_id||b.record.run_id||"").trim()===n).sort((b,N)=>(b.cursor||0)-(N.cursor||0)),o=BN(r.map(b=>b.record)),l=new Map,u=[];for(const b of r){const N=b.record,E=String(N.step_id||"")||`cursor:${b.cursor}`;let T=l.get(E);T||(T={cursor:b.cursor,started:null,latest:N,latest_cursor:b.cursor},l.set(E,T),u.push(E)),String(N.status||"")==="started"&&!T.started&&(T.started=N),b.cursor>=T.latest_cursor&&(T.latest=N,T.latest_cursor=b.cursor)}let c=0;const f=[];for(const b of u){const N=l.get(b),C=qN(N.latest,o),E=C.value,T=String(((m=E==null?void 0:E.effect)==null?void 0:m.type)||((g=(_=N.started)==null?void 0:_.effect)==null?void 0:g.type)||"").trim(),I=ON(T),K=I==="event"?String(((x=(w=E==null?void 0:E.effect)==null?void 0:w.payload)==null?void 0:x.name)||"").trim():"";I==="llm_call"&&(c+=1);const U=HN(E,I),J=String(((j=N.started)==null?void 0:j.started_at)||(E==null?void 0:E.started_at)||""),Y=String((E==null?void 0:E.ended_at)||""),re=By(J),ce=By(Y);f.push({id:`${n}:${b}`,run_id:n,step_id:String((E==null?void 0:E.step_id)||""),node_id:String((E==null?void 0:E.node_id)||""),kind:I,effect_type:T,event_name:K,status:String((E==null?void 0:E.status)||""),cursor:N.cursor,started_at:J,ended_at:Y,duration_ms:re!==null&&ce!==null?Math.max(0,ce-re):null,started:N.started,record:E,failed:U,housekeeping:PN(I,K,U),cycle:c,unresolved:C.unresolved,unverified:C.unverified})}return f}function VN(e){const t=[];for(const n of e){let r=t[t.length-1];(!r||r.cycle!==n.cycle)&&(r={cycle:n.cycle,steps:[],llm:null},t.push(r)),n.kind==="llm_call"&&!r.llm&&(r.llm=n),r.steps.push(n)}return t}const GN={view:"cycles",only:"all",all_steps:!1,q:""};function KN(e,t,n){const r=String(t.q||"").trim().toLowerCase();return e.filter(o=>!(t.only==="llm"&&o.kind!=="llm_call"||t.only==="tools"&&o.kind!=="tool"||t.only==="failed"&&!o.failed||t.only==="all"&&!t.all_steps&&o.housekeeping||r&&!n(o).includes(r)))}const YN=["all","llm","tools","failed"];function Uy(e){const t=String(e||""),n=t.indexOf("?");if(n<0)return{...GN};const r=new URLSearchParams(t.slice(n+1)),o=String(r.get("only")||"");return{view:r.get("view")==="steps"?"steps":"cycles",only:YN.includes(o)?o:"all",all_steps:r.get("all")==="1",q:String(r.get("q")||"")}}function JN(e,t){const n=String(e||"").split("?")[0],r=new URLSearchParams;t.view!=="cycles"&&r.set("view",t.view),t.only!=="all"&&r.set("only",t.only),t.all_steps&&r.set("all","1"),t.q.trim()&&r.set("q",t.q);const o=r.toString();return o?`${n}?${o}`:n}function pu(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>typeof t=="string"?t:typeof(t==null?void 0:t.text)=="string"?t.text:t!=null&&t.type?`[${String(t.type)}]`:JSON.stringify(t)).join(`
68
- `):e==null?"":JSON.stringify(e,null,2)}function Lx(e){if(typeof e!="string")return e??{};try{return JSON.parse(e)}catch{return e}}function Ix(e){return Array.isArray(e)?e.filter(t=>t&&typeof t=="object").map(t=>{var n,r;return{name:String(t.name||((n=t.function)==null?void 0:n.name)||"?"),arguments:Lx(t.arguments??((r=t.function)==null?void 0:r.arguments))}}):[]}function Wy(e){const t={role:String((e==null?void 0:e.role)||"?"),content:pu(e==null?void 0:e.content)},n=Ix(e==null?void 0:e.tool_calls);return n.length&&(t.tool_calls=n),e!=null&&e.name&&(t.name=String(e.name)),t}function qy(e){const t=Number(e);return Number.isFinite(t)&&e!==null&&e!==void 0?t:null}const XN={"effect.payload.system_prompt":"System","effect.payload.messages":"Messages","effect.payload.prompt":"Prompt","effect.payload.tools":"Tools offered","result.metadata._provider_request.payload.messages":"Messages sent"};function pg(e){var x,j,b,N,C,E;const t=e.record||{},n=((j=(x=e.started)==null?void 0:x.effect)!=null&&j.payload&&typeof e.started.effect.payload=="object"?e.started.effect.payload:(b=t==null?void 0:t.effect)==null?void 0:b.payload)||{},r=t!=null&&t.result&&typeof t.result=="object"?t.result:{},o=r.usage||r.token_usage||{},l=[],u=e.unverified.map(T=>`${T.path}: ${T.reason}`);for(const T of e.unresolved){const I=XN[T.path];I&&l.push(`${I}: ${T.reason}`)}const c=(C=(N=r==null?void 0:r.metadata)==null?void 0:N._provider_request)==null?void 0:C.payload;let f="",m=[],_="";if(c&&Array.isArray(c.messages)){_="sent";for(const T of c.messages)String((T==null?void 0:T.role)||"")==="system"&&!m.length?f+=(f?`
69
-
70
- `:"")+pu(T.content):m.push(Wy(T))}else(Array.isArray(n.messages)||typeof n.prompt=="string")&&(_="payload",m=(Array.isArray(n.messages)?n.messages:[]).map(Wy),typeof n.prompt=="string"&&n.prompt.trim()&&m.push({role:"user",content:n.prompt}));!f&&typeof n.system_prompt=="string"&&(f=n.system_prompt);const w=(Array.isArray(n.tools)?n.tools:Array.isArray(c==null?void 0:c.tools)?c.tools:[]).filter(T=>T&&typeof T=="object").map(T=>{const I=T.function&&typeof T.function=="object"?T.function:T;return{name:String(I.name||"?"),description:String(I.description||""),schema:I.parameters??I.input_schema??null}});return{provider:String(n.provider||r.provider||""),model:String(n.model||r.model||""),tokens_in:qy(o.prompt_tokens??o.input_tokens),tokens_out:qy(o.completion_tokens??o.output_tokens),system:f,messages:m,messages_source:_,tools:w,response:pu(r.content??r.response??""),tool_calls:Ix(r.tool_calls),reasoning:pu(r.reasoning??((E=r==null?void 0:r.metadata)==null?void 0:E.reasoning)??""),missing:l,unverified:u}}function gg(e){var o,l,u,c;const t=((l=(o=e.record)==null?void 0:o.effect)==null?void 0:l.payload)||((c=(u=e.started)==null?void 0:u.effect)==null?void 0:c.payload)||{},n=(Array.isArray(t.tool_calls)?t.tool_calls:[]).map(f=>{var m,_;return{name:String((f==null?void 0:f.name)||((m=f==null?void 0:f.function)==null?void 0:m.name)||"?"),arguments:Lx((f==null?void 0:f.arguments)??((_=f==null?void 0:f.function)==null?void 0:_.arguments)),call_id:String((f==null?void 0:f.call_id)||(f==null?void 0:f.id)||"")}}),r=Mx(e.record).map(f=>({name:String((f==null?void 0:f.name)||"?"),success:typeof(f==null?void 0:f.success)=="boolean"?f.success:null,output:(f==null?void 0:f.output)==null?"":pu(f.output),error:(f==null?void 0:f.error)==null?"":pu(f.error),call_id:String((f==null?void 0:f.call_id)||"")}));return{calls:n,results:r}}function ZN(e){return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).map(([t,n])=>`${t}=${JSON.stringify(n)}`).join(", "):typeof e=="string"?e:JSON.stringify(e??"")}function Ox(e){var r,o,l;const t=(r=e==null?void 0:e.result)==null?void 0:r.wait,n=typeof(t==null?void 0:t.wait_key)=="string"&&t.wait_key.startsWith("subworkflow:")?t.wait_key.slice(12):"";return String(((o=t==null?void 0:t.details)==null?void 0:o.sub_run_id)||((l=e==null?void 0:e.result)==null?void 0:l.sub_run_id)||n||"").trim()}function Px(e){var n,r,o,l,u,c,f,m,_,g,w;const t=e.record||{};switch(e.kind){case"llm_call":{const x=pg(e);return x.tokens_in!==null||x.tokens_out!==null?`${(x.tokens_in??0).toLocaleString("en-US")} in · ${(x.tokens_out??0).toLocaleString("en-US")} out`:""}case"tool":{const x=gg(e).calls;if(!x.length)return"";const j=`${x[0].name}(${ZN(x[0].arguments)})`;return x.length>1?`${j} +${x.length-1} more`:j}case"event":return e.event_name;case"subflow":{const x=Ox(t);return[String(((r=(n=t==null?void 0:t.effect)==null?void 0:n.payload)==null?void 0:r.workflow_id)||""),x].filter(Boolean).join(" · ")}case"wait":case"resume":return String(((l=(o=t==null?void 0:t.result)==null?void 0:o.wait)==null?void 0:l.reason)||((c=(u=t==null?void 0:t.effect)==null?void 0:u.payload)==null?void 0:c.reason)||"");case"ask":return String(((m=(f=t==null?void 0:t.effect)==null?void 0:f.payload)==null?void 0:m.prompt)||"");case"answer":return String(((g=(_=t==null?void 0:t.effect)==null?void 0:_.payload)==null?void 0:g.message)||((w=t==null?void 0:t.result)==null?void 0:w.message)||"");default:return e.effect_type}}function Dx(e){return e.kind==="llm_call"?pg(e).model:""}function QN(e,t){var r,o;const n=[e.kind,e.effect_type,e.event_name,e.node_id,t,e.status,Px(e),Dx(e)];try{n.push(JSON.stringify(((o=(r=e.started)==null?void 0:r.effect)==null?void 0:o.payload)??null)),n.push(JSON.stringify(e.record??null))}catch{}return n.join(`
71
- `).toLowerCase()}function e2(e){var r,o;const t=Array.from(new Set((e||[]).map(l=>{var u;return String(l.run_id||((u=l.record)==null?void 0:u.run_id)||"").trim()}).filter(Boolean))),n={llm_calls:0,tokens:0,tool_calls:0,tool_failures:0};for(const l of t)for(const u of Rx(e,l))if(u.kind==="llm_call"){n.llm_calls+=1;const c=((o=(r=u.record)==null?void 0:r.result)==null?void 0:o.usage)||{};n.tokens+=Number(c.total_tokens??Number(c.prompt_tokens??c.input_tokens??0)+Number(c.completion_tokens??c.output_tokens??0))||0}else if(u.kind==="tool"){const c=gg(u);n.tool_calls+=Math.max(c.calls.length,c.results.length),n.tool_failures+=c.results.filter(f=>f.success===!1).length}return n}function t2(e){const t=[];return e.llm_calls&&t.push(`${e.llm_calls} LLM call${e.llm_calls===1?"":"s"}`),e.tokens&&t.push(`${e.tokens.toLocaleString("en-US")} tokens`),e.tool_calls&&t.push(`${e.tool_calls} tool call${e.tool_calls===1?"":"s"}${e.tool_failures?`, ${e.tool_failures} failed`:""}`),t.join(" · ")}function Ct(){return new Date().toISOString()}function n2(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}function cr(e,t){try{const n=JSON.stringify(e);return typeof n!="string"?String(e):n.length<=t?n:`${n.slice(0,Math.max(0,t-1))}…`}catch{const n=String(e);return n.length<=t?n:`${n.slice(0,Math.max(0,t-1))}…`}}function jt(e,t){const n=typeof(t==null?void 0:t.max_chars)=="number"?t.max_chars:360,r=typeof(t==null?void 0:t.max_lines)=="number"?t.max_lines:2,l=String(e||"").replace(/\r\n/g,`
72
- `).replace(/\r/g,`
73
- `).split(`
74
- `),u=l.slice(0,Math.max(1,r)).join(`
75
- `),c=l.length>r,f=u.length>n?`${u.slice(0,Math.max(0,n-1))}…`:u;return c&&f===u?`${u}…`:f}function Qt(e,t){const n=String(e||"");return n.length<=t?n:`${n.slice(0,Math.max(0,t-1))}…`}function Hy(e){const t=String(e||"").trim();return t&&t.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")||"untitled"}function qn(e){const t=typeof e=="string"?e.trim():"";if(!t)return null;const n=t.replace(/(\.\d{3})\d+/,"$1"),r=Date.parse(n);return Number.isFinite(r)?r:null}function s2(e){const t=Date.now()-e,n=Math.floor(t/1e3),r=Math.floor(n/60),o=Math.floor(r/60),l=Math.floor(o/24);return n<60?"just now":r<60?`${r}m ago`:o<24?`${o}h ago`:l<=3?`${l}d ago`:new Date(e).toLocaleDateString(void 0,{month:"short",day:"numeric"})}function ec(e){const t=qn(e);return t===null?"—":s2(t)}function Vy(e){if(!Number.isFinite(e))return"";const t=Math.floor(e/1e3);if(t<=0)return"now";const n=Math.floor(t/60),r=Math.floor(n/60),o=Math.floor(r/24),l=t%60,u=n%60,c=r%24;return o>0?`${o}d ${c}h`:r>0?`${r}h ${u}m`:n>0?`${n}m ${l}s`:`${t}s`}function yg(e){if(typeof e!="number"||!Number.isFinite(e)||e<0)return"—";const t=Math.floor(e/1e3),n=t%60,r=Math.floor(t/60),o=r%60,l=Math.floor(r/60),u=l%24,c=Math.floor(l/24);return c>0?`${c}d ${u}h`:l>0?`${l}h ${o}m`:r>0?`${r}m ${n}s`:`${Math.max(0,t)}s`}function ku(e){const t=qn(e);return t===null?"—":new Date(t).toLocaleString()}function _n(...e){for(const t of e){const n=String(t??"").trim();if(n)return n}return""}function r2(...e){for(const t of e){const n=Number(t);if(Number.isFinite(n))return n}return null}function So(e){const t=String(e||"").trim().toLowerCase();return t==="completed"||t==="failed"||t==="cancelled"}function ju(e){const t=String(e||"").trim().toLowerCase();return t==="running"||t==="waiting"}function hu(e){return String((e==null?void 0:e.started_at)||(e==null?void 0:e.created_at)||"").trim()}function i2(e){const t=String((e==null?void 0:e.status)||"").trim();return So(t)?String((e==null?void 0:e.finished_at)||(e==null?void 0:e.updated_at)||"").trim():""}function wg(e,t=Date.now()){const n=qn(hu(e));if(n===null)return-1;const r=qn(i2(e));return Math.max(0,(r!==null?r:t)-n)}function oc(e,t=Date.now()){return yg(wg(e,t))}function o2(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 a2(e){var n;const t=((n=e==null?void 0:e.output)==null?void 0:n.stop_reason)??(e==null?void 0:e.stop_reason)??null;return t&&typeof t=="object"?t:null}function um(e){const t=String((e==null?void 0:e.status)??"").trim().toLowerCase(),n=t==="completed"||t==="failed"||t==="cancelled";return e!=null&&e.paused&&!n?"paused":t==="completed"&&(e!=null&&e.stop_reason)&&e.stop_reason.finished===!1?"stopped":t||"unknown"}function ac(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 l2={all:"All",llm:"LLM calls",tools:"Tools",failed:"Failed"};function ki(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}function bo(e){return s.jsxs("details",{className:"rs_section",open:e.open,children:[s.jsxs("summary",{children:[s.jsx("span",{className:"rs_section_title",children:e.title}),e.meta?s.jsx("span",{className:"rs_section_meta",children:e.meta}):null,e.copy!==void 0?s.jsx("button",{type:"button",className:"rs_copy",onClick:t=>{t.preventDefault(),t.stopPropagation(),e.on_copy(e.copy||"")},children:"Copy"}):null]}),s.jsx("div",{className:"rs_section_body",children:e.children})]})}function R_(e){return`${e.toLocaleString("en-US")} chars`}function vg(e){const t=e.step.started&&e.step.started!==e.step.record?{started:e.step.started,record:e.step.record}:e.step.record;return s.jsx(bo,{title:"Raw JSON",copy:ki(t),on_copy:e.on_copy,children:s.jsx("div",{className:"rs_json mono",children:s.jsx(Is,{value:t,collapseAfterDepth:2,showCopy:!1})})})}function c2(e){const t=pg(e.step),n=!t.system&&!t.messages.length&&!t.missing.length;return s.jsxs(s.Fragment,{children:[t.missing.map(r=>s.jsxs("p",{className:"rs_notice",children:["Prompt body not kept: ",r,"."]},r)),n?s.jsx("p",{className:"rs_notice",children:"Prompt body not kept: this record carries no request messages."}):null,t.unverified.length?s.jsxs("p",{className:"rs_notice",children:["Rebuilt prompt may differ from what was sent: ",t.unverified.join("; "),"."]}):null,t.system?s.jsx(bo,{title:"System",meta:R_(t.system.length),copy:t.system,on_copy:e.on_copy,children:s.jsx("pre",{className:"rs_text",children:t.system})}):null,t.messages.length?s.jsx(bo,{title:"Messages",meta:`${t.messages.length}${t.messages_source==="sent"?" · as sent":""}`,copy:ki(t.messages),on_copy:e.on_copy,children:s.jsx("ol",{className:"rs_messages",children:t.messages.map((r,o)=>{var l;return s.jsxs("li",{className:`rs_msg rs_msg_${r.role}`,children:[s.jsxs("span",{className:"rs_role",children:[r.role,r.name?` · ${r.name}`:""]}),r.content?s.jsx("pre",{className:"rs_text",children:r.content}):null,(l=r.tool_calls)==null?void 0:l.map((u,c)=>s.jsx("pre",{className:"rs_text mono",children:`${u.name}(${ki(u.arguments)})`},c))]},o)})})}):null,t.tools.length?s.jsx(bo,{title:"Tools offered",meta:String(t.tools.length),copy:ki(t.tools),on_copy:e.on_copy,children:s.jsx("ul",{className:"rs_tools",children:t.tools.map(r=>s.jsxs("li",{children:[s.jsx("strong",{className:"mono",children:r.name}),r.description?s.jsxs("span",{children:[" — ",r.description]}):null]},r.name))})}):null,s.jsxs(bo,{title:"Response",meta:t.tool_calls.length?`${t.tool_calls.length} tool call${t.tool_calls.length===1?"":"s"}`:t.response?R_(t.response.length):"empty",copy:t.response||ki(t.tool_calls),open:!0,on_copy:e.on_copy,children:[t.response?s.jsx("div",{className:"rs_markdown",children:s.jsx(qi,{text:t.response})}):null,t.tool_calls.map((r,o)=>s.jsx("pre",{className:"rs_text mono",children:`${r.name}(${ki(r.arguments)})`},o)),!t.response&&!t.tool_calls.length?s.jsx("p",{className:"rs_muted",children:"No text and no tool call."}):null]}),t.reasoning?s.jsx(bo,{title:"Reasoning",meta:R_(t.reasoning.length),copy:t.reasoning,on_copy:e.on_copy,children:s.jsx("pre",{className:"rs_text",children:t.reasoning})}):null,s.jsx(vg,{step:e.step,on_copy:e.on_copy})]})}function u2(e){const t=gg(e.step);return s.jsxs(s.Fragment,{children:[s.jsx(bo,{title:"Calls",meta:String(t.calls.length),copy:ki(t.calls),open:!0,on_copy:e.on_copy,children:t.calls.map((n,r)=>s.jsx("pre",{className:"rs_text mono",children:`${n.name}(${ki(n.arguments)})`},r))}),s.jsxs(bo,{title:"Results",meta:String(t.results.length),copy:ki(t.results),open:!0,on_copy:e.on_copy,children:[t.results.length?null:s.jsx("p",{className:"rs_muted",children:"No result recorded yet."}),s.jsx("ol",{className:"rs_messages",children:t.results.map((n,r)=>s.jsxs("li",{className:`rs_msg ${n.success===!1?"rs_msg_failed":""}`,children:[s.jsxs("span",{className:"rs_role",children:[n.name," · ",n.success===!1?"failed":n.success?"ok":"unknown"]}),n.error?s.jsx("pre",{className:"rs_text",children:n.error}):null,n.output?s.jsx("pre",{className:"rs_text",children:n.output}):null]},r))})]}),s.jsx(vg,{step:e.step,on_copy:e.on_copy})]})}function d2(e){var o,l,u;const t=e.step.record||{},n=((l=(o=e.step.started)==null?void 0:o.effect)==null?void 0:l.payload)??((u=t==null?void 0:t.effect)==null?void 0:u.payload),r=e.step.kind==="subflow"?Ox(t):"";return s.jsxs(s.Fragment,{children:[r&&e.on_open_run?s.jsxs("p",{className:"rs_line_actions",children:[s.jsx("span",{className:"mono",children:r}),s.jsx("button",{type:"button",className:"btn btn_sm",onClick:()=>{var c;return(c=e.on_open_run)==null?void 0:c.call(e,r)},children:"Open"})]}):null,t.error?s.jsx("pre",{className:"rs_text rs_error",children:typeof t.error=="string"?t.error:ki(t.error)}):null,n!=null?s.jsx(bo,{title:"Payload",copy:ki(n),on_copy:e.on_copy,children:s.jsx("div",{className:"rs_json mono",children:s.jsx(Is,{value:n,collapseAfterDepth:2,showCopy:!1})})}):null,t.result!==void 0&&t.result!==null?s.jsx(bo,{title:"Result",copy:ki(t.result),on_copy:e.on_copy,children:s.jsx("div",{className:"rs_json mono",children:s.jsx(Is,{value:t.result,collapseAfterDepth:2,showCopy:!1})})}):null,s.jsx(vg,{step:e.step,on_copy:e.on_copy})]})}function f2(e){const t=e.step,n=Px(t),r=Dx(t),o=t.failed&&t.status!=="failed"?"failed":t.status;return s.jsxs("article",{className:`rs_card ${t.failed?"rs_failed":""}`,"data-kind":t.kind,"data-step-id":t.step_id||void 0,children:[s.jsxs("button",{type:"button",className:"rs_card_head","aria-expanded":e.open,onClick:e.on_toggle,children:[s.jsx("span",{className:"rs_chevron","aria-hidden":"true",children:e.open?"▾":"▸"}),s.jsx("span",{className:"rs_kind",children:IN[t.kind]}),s.jsx("span",{className:"rs_node",children:e.node_label||t.node_id||t.effect_type||"step"}),s.jsx("span",{className:`rs_status ${ac(o)}`,children:o||"—"}),s.jsx("span",{className:"rs_dur",children:t.duration_ms!==null?yg(t.duration_ms):""}),r?s.jsx("span",{className:"rs_detail",children:r}):null,n?s.jsx("span",{className:"rs_line",children:n}):null]}),e.open?s.jsx("div",{className:"rs_card_body",children:t.kind==="llm_call"?s.jsx(c2,{step:t,on_copy:e.on_copy}):t.kind==="tool"?s.jsx(u2,{step:t,on_copy:e.on_copy}):s.jsx(d2,{step:t,on_copy:e.on_copy,on_open_run:e.on_open_run})}):null]})}function h2(e){const{state:t}=e,n=p.useMemo(()=>Rx(e.items,e.run_id),[e.items,e.run_id]),[r,o]=p.useState({}),l=j=>e.node_label(j.run_id,j.node_id),u=p.useMemo(()=>new Map,[n]),f=KN(n,t,j=>{let b=u.get(j.id);return b===void 0&&(b=QN(j,l(j)),u.set(j.id,b)),b}),m=n.some(j=>j.kind==="llm_call"),_=n.reduce((j,b)=>b.kind==="llm_call"?j+1:j,0),g=n.length-f.length,w=j=>e.on_state({...t,...j}),x=j=>s.jsx(f2,{step:j,node_label:l(j),open:r[j.id]===!0,on_toggle:()=>o(b=>({...b,[j.id]:!b[j.id]})),on_copy:e.on_copy,on_open_run:e.on_open_run},j.id);return s.jsxs("div",{className:"rs_view",children:[s.jsxs("div",{className:"rs_count",children:[s.jsxs("span",{children:[f.length," of ",n.length," steps",m?` · ${_} cycle${_===1?"":"s"}`:"",g&&t.only==="all"&&!t.all_steps&&!t.q?` · ${g} housekeeping hidden`:""]}),e.run_options.length>1?s.jsx("select",{className:"seg_select mono",value:e.run_id,onChange:j=>e.on_select_run(String(j.target.value||"")),"aria-label":"Run",children:e.run_options.map(j=>s.jsxs("option",{value:j,children:[Qt(j,14),e.run_llm_counts[j]?` · ${e.run_llm_counts[j]} LLM`:""]},j))}):null]}),s.jsxs("div",{className:"rs_toolbar",children:[s.jsx("div",{className:"seg_toggle",role:"radiogroup","aria-label":"Layout",children:["cycles","steps"].map(j=>s.jsx("button",{type:"button",role:"radio","aria-checked":t.view===j,className:`seg_btn ${t.view===j?"active":""}`,onClick:()=>w({view:j}),children:j==="cycles"?"Cycles":"Steps"},j))}),s.jsx("div",{className:"seg_toggle",role:"radiogroup","aria-label":"Show",children:["all","llm","tools","failed"].map(j=>s.jsx("button",{type:"button",role:"radio","data-filter":j,"aria-checked":t.only===j,className:`seg_btn ${t.only===j?"active":""}`,onClick:()=>w({only:j}),children:l2[j]},j))}),s.jsx("input",{className:"rs_search",type:"search",value:t.q,onChange:j=>w({q:j.target.value}),placeholder:"Search steps","aria-label":"Search steps",autoComplete:"off",spellCheck:!1}),t.only==="all"?s.jsx(No,{label:"All steps",action:"show-all-steps",hint:"Also list status events, waits, resumes and memory bookkeeping.",checked:t.all_steps,onChange:j=>w({all_steps:j})}):null]}),n.length?null:s.jsx("p",{className:"rs_muted",children:"No steps recorded for this run yet."}),n.length&&!f.length?s.jsx("p",{className:"rs_muted",children:"No step matches."}):null,t.view==="cycles"&&m?VN(f).map(j=>s.jsxs("section",{className:"rs_cycle","data-cycle":j.cycle,children:[s.jsx("h3",{className:"rs_cycle_head",children:j.cycle===0?"Before the first call":`Cycle ${j.cycle}`}),j.steps.map(x)]},j.cycle)):f.map(x)]})}function m2(e){const[t,n]=p.useState(!1),r=e.answer.length>Gy,o=t||!r?e.answer:`${e.answer.slice(0,Gy).trimEnd()}…`;return s.jsxs("section",{className:"rs_outcome","aria-label":"Run summary",children:[s.jsxs("p",{className:"rs_outcome_facts",children:[s.jsx("span",{className:`rs_status ${ac(e.status)}`,children:e.status||"unknown"}),[e.duration,e.facts].filter(Boolean).join(" · ")]}),e.error?s.jsx("p",{className:"rs_text rs_error",children:e.error}):null,!e.error&&e.answer?s.jsxs("div",{className:"rs_markdown rs_outcome_text",children:[s.jsx(qi,{text:o}),r?s.jsx("button",{type:"button",className:"rs_link","aria-expanded":t,onClick:()=>n(l=>!l),children:t?"Less":"More"}):null]}):null,s.jsxs("div",{className:"rs_outcome_actions",children:[e.waiting_for_user&&e.on_answer_wait?s.jsx("button",{type:"button",className:"btn primary",onClick:e.on_answer_wait,children:"Answer"}):null,s.jsx("button",{type:"button",className:"btn",onClick:e.on_open_artifacts,title:"This run's artifacts in System",children:"Artifacts"}),e.workspace_root?s.jsx("button",{type:"button",className:"btn",onClick:e.on_reveal_workspace,title:e.workspace_root,children:"Folder"}):null]})]})}const Gy=600,_2="@default:",tc="abstractcode.agent.v1";function Ky(e,t){var n;return e?e.kind==="default"?e.interface===tc?"@default":"":((n=t.find(r=>r.bundleId===e.bundle_id&&r.flowId===e.flow_id))==null?void 0:n.value)??"":""}function p2(e,t){return e==="@default"?{kind:"default",interface:tc}:t?{kind:"bundle",bundle_id:t.bundleId,flow_id:t.flowId}:null}function g2(e){return e?e.kind==="default"?`${_2}${e.interface}`:`${e.bundle_id}:${e.flow_id}`:""}function y2(e,t,n){if(!e)return null;if(e.kind==="default")return{flow_id:"@default",interface:e.interface,input_data:n};const r=String(t(e.bundle_id)||"").trim();if(!r)throw new Error(`The gateway listed no bundle_ref for bundle "${e.bundle_id}". Reload bundles, then try again.`);return{bundle_ref:r,flow_id:e.flow_id,input_data:n}}function w2(e){const t={};for(const[n,r]of Object.entries(e||{}))if(typeof r=="string"){const o=r.trim();o&&(t[n]=o)}else r!==void 0&&(t[n]=r);return t}const v2={once:"Run once: start this workflow now, a single run you can watch in Observe.",automate:"Automate: create an automation that runs this workflow on a schedule (every N minutes, hours or days), when an email arrives, or when you ask; manage it on the Automations page."};function x2(e){const t=String(e||"").trim();if(!t)return null;try{const n=new URL(t);return n.protocol!=="http:"&&n.protocol!=="https:"?null:`${n.origin}${n.pathname.replace(/\/+$/,"")}/console#users`}catch{return null}}const b2="#launch/automate";function k2(e){const t=Tx(String(e||""));if(t)return{page:"run",run_id:t};const n=String(e||"").replace(/^#\/?/,"");if(n==="automations")return{page:"automations"};const r=/^launch(?:\/(once|automate))?$/.exec(n);return r?{page:"launch",mode:r[1]||"once"}:null}const $p={when:"every",email:Bv,notify_email:!1,email_recipients:lf,amount:"24",unit:"h",once_at:"",context:"independent",growing_max_tokens:String(df),tool_approval:"auto",title:"",start_at:"",count:"",until:""},Yy={independent:"Each run starts fresh in its own session. Runs never see each other.",growing:"Each run is a new turn of one conversation and sees the previous runs. The most recent whole turns are replayed within your token budget; older runs drop out. The newest turn is kept whole even if it exceeds the budget."},Fx=["use_context"],j2="This choice also sets the workflow's Use Context input: the workflow always reads the history the automation gives it.";function Tp(e,t,n=!1){const r=e.when==="every";return{prompt:t,when:e.when==="once"?{kind:"once",at:e.once_at}:{kind:"every",amount:Number(e.amount),unit:e.unit},...n&&e.when==="email"?{trigger:"email",email:e.email}:{},...n&&e.notify_email?{notifyEmail:!0}:{},...n&&e.email_recipients.mode==="list"?{emailRecipients:e.email_recipients}:{},context:e.context,growingMaxTokens:Number(e.growing_max_tokens),toolApproval:e.tool_approval,title:e.title,...r&&e.start_at?{startAt:e.start_at}:{},...r&&e.count.trim()?{count:Number(e.count)}:{},...r&&e.until?{until:e.until}:{}}}function S2(e,t){if(t.input_data===null)return{ok:!1,errors:["The inputs are not valid JSON."]};if(e.when==="email"&&!t.email_usable)return{ok:!1,errors:[Ut.not_set_up]};const n=w2(t.input_data),r=typeof n.prompt=="string"?n.prompt:"";delete n.prompt;for(const l of Fx)delete n[l];let o;try{o=y2(t.choice,t.bundle_ref_for,n)}catch(l){return{ok:!1,errors:[String((l==null?void 0:l.message)||l)]}}return wp(Tp(e,r,t.email_usable===!0),{target:o,requestId:t.request_id})}function N2(e,t=!1){if(e.when==="email"){if(!t)return"";const l=wp(Tp(e,"preview",!0),{target:{flow_id:"@default",interface:tc},requestId:"preview"});return l.ok?`Runs ${Wv(l.body.trigger.config)}.`:""}const n=wp(Tp(e,"preview"),{target:{flow_id:"@default",interface:tc},requestId:"preview"});if(!n.ok)return"";const r=n.body.trigger.config,o=Iv(r);return e.when==="once"?`Runs ${o}.`:`Runs ${o}, first run ${r.start_at?`at ${la(r.start_at)}`:"now"}.`}class C2{constructor(t){Vs(this,"key","");Vs(this,"id","");this.mint=t}id_for(t){return(!this.id||t!==this.key)&&(this.key=t,this.id=this.mint()),this.id}reset(){this.key="",this.id=""}}function E2(e,t,n){const r=S2(e,{...t,request_id:""});if(!r.ok)return r;const{request_id:o,...l}=r.body,u=n.id_for(JSON.stringify(l));return{ok:!0,body:{...r.body,request_id:u}}}function na(e){return typeof e=="string"?e:e??null}function A2(e){var t,n,r,o,l,u;return{run_id:String((e==null?void 0:e.run_id)||"").trim(),workflow_id:na(e==null?void 0:e.workflow_id),status:typeof(e==null?void 0:e.status)=="string"?String(e.status):"",created_at:na(e==null?void 0:e.created_at),updated_at:na(e==null?void 0:e.updated_at),ledger_len:typeof(e==null?void 0:e.ledger_len)=="number"?Number(e.ledger_len):(e==null?void 0:e.ledger_len)??null,parent_run_id:na(e==null?void 0:e.parent_run_id),session_id:na(e==null?void 0:e.session_id),actor_id:na(e==null?void 0:e.actor_id),session_kind:na(e==null?void 0:e.session_kind),automation_id:na(e==null?void 0:e.automation_id),role:na(e==null?void 0:e.role),occurrence_index:typeof(e==null?void 0:e.occurrence_index)=="number"?Number(e.occurrence_index):null,is_scheduled:typeof(e==null?void 0:e.is_scheduled)=="boolean"?!!e.is_scheduled:(e==null?void 0:e.is_scheduled)??null,paused:typeof(e==null?void 0:e.paused)=="boolean"?!!e.paused:(e==null?void 0:e.paused)??null,waiting_reason:typeof((t=e==null?void 0:e.waiting)==null?void 0:t.reason)=="string"?String(e.waiting.reason):((n=e==null?void 0:e.waiting)==null?void 0:n.reason)??null,schedule_interval:typeof((r=e==null?void 0:e.schedule)==null?void 0:r.interval)=="string"?String(e.schedule.interval).trim():((o=e==null?void 0:e.schedule)==null?void 0:o.interval)??null,schedule_target_workflow_id:typeof((l=e==null?void 0:e.schedule)==null?void 0:l.target_workflow_id)=="string"?String(e.schedule.target_workflow_id).trim():((u=e==null?void 0:e.schedule)==null?void 0:u.target_workflow_id)??null,current_node:typeof(e==null?void 0:e.current_node)=="string"?String(e.current_node).trim():(e==null?void 0:e.current_node)??null,llm_calls:typeof(e==null?void 0:e.llm_calls)=="number"?Number(e.llm_calls):(e==null?void 0:e.llm_calls)??null,tool_calls:typeof(e==null?void 0:e.tool_calls)=="number"?Number(e.tool_calls):(e==null?void 0:e.tool_calls)??null,tokens_total:typeof(e==null?void 0:e.tokens_total)=="number"?Number(e.tokens_total):(e==null?void 0:e.tokens_total)??null,error:(e==null?void 0:e.error)??null,waiting:(e==null?void 0:e.waiting)??null}}function ff(e){const t=String((e==null?void 0:e.role)||"").trim(),n=String((e==null?void 0:e.session_kind)||"").trim();return t==="controller"?"automation":t==="occurrence"||t==="descendant"||n==="occurrence"?"occurrence":t==="discussion"||n==="discussion"?"discussion":t==="legacy_schedule"||(e==null?void 0:e.is_scheduled)===!0?"legacy":null}function zx(e){const t=ff(e);return t==="occurrence"?typeof e.occurrence_index=="number"?`occurrence #${e.occurrence_index}`:"occurrence":t==="legacy"?"legacy schedule":t||""}function Jy(e){return String((e==null?void 0:e.role)||"").trim()==="controller"}function $2(e){var n,r,o;const t=(o=(r=(n=e==null?void 0:e.capabilities)==null?void 0:n.contracts)==null?void 0:r.common)==null?void 0:o.automations;return t&&typeof t=="object"&&t.available===!0?{available:!0,reason:""}:t&&typeof t=="object"&&t.available===!1?{available:!1,reason:"This gateway has the Automations API turned off."}:{available:!1,reason:"This gateway does not advertise the Automations API (capabilities.contracts.common.automations). Update AbstractGateway to use automations; legacy schedules stay manageable from their run view."}}function nc(e){return e.legacy===!0||e.capabilities.includes("legacy")}function Bx(e,t=Date.now()){const n=nc(e),r=e.last_occurrence,o=r&&r.attempts>1?` after ${r.attempts} attempts`:"",l=e.attention.unread||e.attention.pending_waits>0;return{id:e.automation_id,title:e.title,cadence:lg(e.trigger),next_run:e.next_fire_at?`${la(e.next_fire_at)} (${Gv(e.next_fire_at,t)})`:e.status==="paused"?"none while paused":"none scheduled",current:Vv(e),state:e.status,last:r?r.excerpt:"",last_status:r?`#${r.index} ${r.status}${o}`:"no runs yet",attention:l?Kv(e):null,legacy:n}}function Ux(e){const t=e.last_occurrence;if(!t)return null;const r=["completed","failed","cancelled"].includes(String(t.status))?t.index:t.index-1;return r>=1?r:null}function T2(e,t){const n=om(e,[],t),r=Ux(e),o=t?{enabled:!1,reason:"Working…"}:nc(e)?{enabled:!1,reason:"Legacy schedule: managed with its existing controls."}:e.capabilities.includes("discuss")?r===null?{enabled:!1,reason:e.last_occurrence?"Available once the first run finishes.":"No occurrence to discuss yet."}:{enabled:!0,reason:`Discuss run #${r} in a new chat (a fork of this automation).`}:{enabled:!1,reason:"Not permitted for this automation."};return{active:n.active,pause:n.pause,resume:n.resume,run_now:n.run_now,edit:n.revise,archive:n.archive,discuss:o}}function M2(e,t){const n=l=>({enabled:!1,reason:l});if(t)return{legacy_pause:n("Working…"),legacy_resume:n("Working…"),legacy_run_now:n("Working…"),open_run:{enabled:!0},recreate:n("Working…")};const r=e.status==="paused",o=e.status==="active"||e.status==="paused";return{legacy_pause:r?n("Already suspended."):o?{enabled:!0}:n("The schedule has ended."),legacy_resume:r?{enabled:!0}:n(o?"Already running on schedule.":"The schedule has ended."),legacy_run_now:e.status==="active"?{enabled:!0}:n(r?"The schedule is off: switch Active on first.":"The schedule has ended."),open_run:{enabled:!0},recreate:{enabled:!0}}}function R2(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 L2=/^([1-9][0-9]*)([smhd])$/;function I2(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 O2(e,t){const n=e!=null&&e.schedule&&typeof e.schedule=="object"?e.schedule:null;if(!n)throw new Error("This run carries no legacy schedule metadata; nothing to recreate.");const r=String(n.target_bundle_ref||"").trim(),o=String(n.target_host_bundle_id||n.target_bundle_id||(r.includes("@")?r.slice(0,r.lastIndexOf("@")):"")||(t==null?void 0:t.bundle_id)||"").trim(),l=String(n.target_flow_id||(t==null?void 0:t.flow_id)||"").trim();if(!o||!l)throw new Error("The legacy schedule does not name its target workflow.");const u=[],c={...$p},f=typeof n.interval=="string"?n.interval.trim():"";if(!f)c.when="once",u.push("The legacy schedule ran once; pick the date and time (UTC) to run.");else{const w=L2.exec(f);let x=w?Number(w[1]):0,j=w?w[2]:"";j==="s"&&x%60===0&&(x=x/60,j="m"),j==="m"||j==="h"||j==="d"?(c.amount=String(x),c.unit=j):u.push(`The legacy interval "${f}" is not a whole number of minutes, hours or days; choose an interval.`)}typeof n.repeat_count=="number"&&n.repeat_count>=1&&(c.count=String(n.repeat_count));const m=I2(n.repeat_until);m&&(c.until=m),c.context=n.share_context===!1?"independent":"growing";const _=t&&typeof t.input_data=="object"&&t.input_data&&!Array.isArray(t.input_data)?t.input_data:{},g={};for(const[w,x]of Object.entries(_))w==="workflow_selection"||w.startsWith("_")||(g[w]=x);return{choice:{kind:"bundle",bundle_id:o,flow_id:l},input_data:g,form:c,notes:u}}const P2={items:[],loaded:!1,loading:!1,list_error:null,error:null,refreshed_at:null,status_filter:"",show_archived:!1,selected_id:"",detail:null,trigger_sources:[],busy:!1,notice:"",confirm_archive_id:"",email_status:null};function D2(e,t,n){return{answer_wait:async(r,o,l)=>{await e.submit_command({command_id:t(),run_id:r,type:"resume",payload:{wait_key:o,payload:l},client_id:"web_pwa"})},legacy_command:async(r,o,l)=>{await e.submit_command({command_id:t(),run_id:r,type:o,payload:l,client_id:"web_pwa"})},now_iso:n}}function F2(e,t){if(e==="ask_user"){if(typeof t.response!="string")throw new Error("An ask_user wait is answered with {response: string}.");return{response:t.response}}if(e==="tool_approval"){if(typeof t.approved!="boolean")throw new Error("A tool_approval wait is answered with {approved: true|false}.");const n=t.tool_ids;if(n!==void 0&&!(Array.isArray(n)&&n.every(r=>typeof r=="string")))throw new Error("tool_ids must be a list of strings.");return{approved:t.approved,...n!==void 0?{tool_ids:n}:{}}}if(e==="event"){if(!("payload"in t))throw new Error("An event wait is answered with {payload}.");return{payload:t.payload}}throw new Error(`This wait has no known kind (${JSON.stringify(e)}); the gateway must type its waits (ask_user, tool_approval, event).`)}function L_(e){return e.show_archived||e.status_filter==="archived"?e.items:e.items.filter(t=>t.status!=="archived")}function Xy(e){return e.items.filter(t=>t.status==="archived").length}function xg(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 z2=3e4,Rh=50;function Fi(e){return dg(e)?e:{status:0,code:"client_error",message:e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}}function I_(e,t){const n=new Map;for(const r of e)n.set(r.run_id,r);for(const r of t)n.set(r.run_id,r);return Array.from(n.values()).sort((r,o)=>o.index-r.index)}class B2{constructor(t,n,r=[1500,4e3]){Vs(this,"state",{...P2});Vs(this,"listeners",new Set);Vs(this,"list_seq",0);Vs(this,"detail_seq",0);Vs(this,"sources_loaded",!1);this.client=t,this.host=n,this.followups_ms=r}subscribe(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}set(t){this.state={...this.state,...t};for(const n of this.listeners)n()}async list_all(){const t=[];let n;for(let r=0;r<200;r+=1){const o=await this.client.listAutomations({...this.state.status_filter?{status:this.state.status_filter}:{},...n?{cursor:n}:{},limit:Rh});if(t.push(...o.items),!o.next_cursor)return t;n=o.next_cursor}throw new Error("GET /api/gateway/automations kept returning next_cursor after 200 pages.")}async load_email_status(){try{const t=await this.client.getMyEmail();this.set({email_status:t&&typeof t=="object"?t:null})}catch{this.set({email_status:null})}}get email_usable(){return Em(this.state.email_status)}async refresh(){const t=++this.list_seq;this.set({loading:!0});try{const n=await this.list_all();if(this.load_email_status(),t!==this.list_seq)return;const r=this.state.detail,o=r?n.find(l=>l.automation_id===r.automation_id):void 0;this.set({items:n,loaded:!0,loading:!1,list_error:null,refreshed_at:Date.now(),...r&&o?{detail:{...r,summary:o}}:{}}),r&&await this.reload_occurrences(r.automation_id)}catch(n){if(t!==this.list_seq)return;this.set({loading:!1,loaded:!0,list_error:Fi(n)})}}async set_status_filter(t){this.set({status_filter:t}),await this.refresh()}async load_trigger_sources(){if(this.sources_loaded)return;const t=await this.client.listTriggerSources();this.sources_loaded=!0,this.set({trigger_sources:t.items})}async select(t){var o;const n=String(t||"").trim(),r=++this.detail_seq;if(!n){this.set({selected_id:"",detail:null});return}this.set({selected_id:n,notice:"",...((o=this.state.detail)==null?void 0:o.automation_id)!==n?{detail:null}:{}});try{const l=this.state.items.find(f=>f.automation_id===n);if(l&&nc(l)){this.set({detail:{automation_id:n,summary:l,definition:null,occurrences:[],next_cursor:null,error:null}});return}const[u,c]=await Promise.all([this.client.getAutomation(n),this.client.listOccurrences(n,{limit:Rh})]);if(r!==this.detail_seq)return;this.set({detail:{automation_id:n,summary:l??u.summary,definition:u.definition,occurrences:I_([],c.items),next_cursor:c.next_cursor,error:null}}),await this.load_trigger_sources()}catch(l){if(r!==this.detail_seq)return;this.set({error:Fi(l)})}}async reload_occurrences(t){const n=this.state.detail;if(!n||n.automation_id!==t||nc(n.summary))return;const[r,o]=await Promise.all([this.client.getAutomation(t),this.client.listOccurrences(t,{limit:Rh})]),l=this.state.detail;if(!l||l.automation_id!==t)return;const u=this.state.items.find(c=>c.automation_id===t);this.set({detail:{...l,summary:u??r.summary,definition:r.definition,occurrences:I_(l.occurrences,o.items),next_cursor:l.occurrences.length>o.items.length?l.next_cursor:o.next_cursor}})}async load_more(){const t=this.state.detail;if(!(!t||!t.next_cursor))try{const n=await this.client.listOccurrences(t.automation_id,{cursor:t.next_cursor,limit:Rh}),r=this.state.detail;if(!r||r.automation_id!==t.automation_id)return;this.set({detail:{...r,occurrences:I_(r.occurrences,n.items),next_cursor:n.next_cursor}})}catch(n){this.set({error:Fi(n)})}}async after_change(t){await this.refresh();for(const n of this.followups_ms)setTimeout(()=>void this.refresh(),n)}async command(t,n,r,o){this.set({busy:!0});try{const l=await this.client.sendAutomationCommand(t,{type:n,...r?{payload:r}:{},...o?{command_id:o}:{}});return await this.after_change(t),l}catch(l){throw Fi(l)}finally{this.set({busy:!1})}}async revise(t,n,r,o){this.set({busy:!0});try{const l=await this.client.reviseAutomation(t,{changes:n,...r!==null?{expected_revision:r}:{},...o?{command_id:o}:{}});return await this.after_change(t),l}catch(l){throw Fi(l)}finally{this.set({busy:!1})}}async discuss(t,n,r,o){this.set({busy:!0});try{const l=await this.client.discuss(t,{occurrence_index:n,prompt:r,...o?{request_id:o}:{}});return this.set({notice:xg(n,l)}),l}catch(l){throw Fi(l)}finally{this.set({busy:!1})}}async seen(t,n){try{await this.client.markSeen(t,n)}catch(r){throw Fi(r)}}async answer_wait(t,n,r,o){var l;this.set({busy:!0});try{const u=(((l=this.state.detail)==null?void 0:l.occurrences)||[]).flatMap(c=>c.waits).find(c=>c.run_id===n&&c.wait_key===r);if(!u)throw new Error(`No loaded wait ${r} on run ${n}; reload the automation.`);await this.host.answer_wait(n,r,F2(u.kind,o)),await this.after_change(t)}catch(u){throw Fi(u)}finally{this.set({busy:!1})}}async row_action(t,n){const r=`automation.${n}`;this.set({error:null,notice:""});try{await this.command(t.automation_id,r),this.set({notice:n==="run_now"&&t.status==="paused"?`Run now sent to “${t.title}”; it stays paused.`:n==="pause"||n==="resume"?Zy(t.title,n==="resume"):`${U2[n]} sent to “${t.title}”.`,confirm_archive_id:""})}catch(o){this.set({error:Fi(o)})}}set_show_archived(t){this.set({show_archived:t})}ask_archive(t){this.set({confirm_archive_id:t})}async legacy_action(t,n){if(!nc(t))throw new Error("legacy_action on a non-legacy automation");const r=R2(n,this.host.now_iso());this.set({busy:!0,error:null,notice:""});try{await this.host.legacy_command(t.automation_id,r.type,r.payload),this.set({notice:n==="legacy_run_now"?`Run now sent to “${t.title}”.`:Zy(t.title,n==="legacy_resume")}),await this.refresh()}catch(o){this.set({error:Fi(o)})}finally{this.set({busy:!1})}}report_error(t){this.set({error:Fi(t)})}clear_notice(){this.set({notice:"",error:null})}dismiss_notice(){this.state.notice&&this.set({notice:""})}dismiss_error(){this.state.error&&this.set({error:null})}}function Zy(e,t){return t?`“${e}” is active: it runs on its schedule.`:`“${e}” is paused: scheduled runs are skipped.`}const U2={run_now:"Run now",archive:"Archive"};function W2(e){const t=(n,r,o)=>s.jsx("button",{type:"button",role:"radio","aria-checked":e.mode===n,className:`seg_btn ${e.mode===n?"active":""}`,"data-mode":n,title:o,onClick:()=>e.on_change(n),children:r});return s.jsxs("div",{className:"launch_mode",children:[s.jsxs("div",{className:"seg_toggle launch_mode_switch",role:"radiogroup","aria-label":"Launch mode","aria-describedby":"launch_mode_help",children:[t("once","Run once"),t("automate","Automate",e.automate_available?void 0:e.automate_reason)]}),s.jsx("p",{className:"launch_mode_help",id:"launch_mode_help","data-mode-help":e.mode,"aria-live":"polite",children:v2[e.mode]})]})}function q2(e){const t=e.form,n=Em(e.email_status),r=t.when==="email"&&!n?"every":t.when,o=N2(t,n);return s.jsxs("div",{className:"automate_fields",children:[s.jsxs("fieldset",{"data-section":"when",children:[s.jsx("legend",{children:"When (UTC)"}),s.jsxs("div",{className:"automate_row",role:"radiogroup","aria-label":"Schedule kind",children:[s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:"automate_when",value:"every",checked:r==="every",disabled:e.disabled,onChange:()=>e.on_change({when:"every"})})," Repeat"]}),s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:"automate_when",value:"once",checked:r==="once",disabled:e.disabled,onChange:()=>e.on_change({when:"once"})})," Once at…"]}),s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:"automate_when",value:"email",checked:r==="email",disabled:e.disabled||!n,onChange:()=>e.on_change({when:"email"})})," ",Ut.trigger_label]})]}),n?null:s.jsx(xp,{status:e.email_status,onOpenMyEmail:e.on_open_my_email}),r==="email"?s.jsx(pS,{value:t.email,onChange:l=>e.on_change({email:l}),disabled:e.disabled,idBase:"automate"}):r==="every"?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"automate_row",role:"group","aria-label":"Presets",children:Bj.map(l=>l.when.kind==="every"?s.jsx("button",{type:"button",className:"btn btn_sm","data-preset":l.label,"aria-pressed":Number(t.amount)===l.when.amount&&t.unit===l.when.unit,disabled:e.disabled,onClick:()=>{l.when.kind==="every"&&e.on_change({amount:String(l.when.amount),unit:l.when.unit})},children:l.label},l.label):null)}),s.jsxs("div",{className:"automate_row",children:[s.jsx("span",{children:"Every"}),s.jsx("input",{type:"number",min:1,step:1,value:t.amount,disabled:e.disabled,"aria-label":"Interval amount",onChange:l=>e.on_change({amount:l.target.value})}),s.jsxs("select",{value:t.unit,disabled:e.disabled,"aria-label":"Interval unit",onChange:l=>e.on_change({unit:l.target.value}),children:[s.jsx("option",{value:"m",children:"minutes"}),s.jsx("option",{value:"h",children:"hours"}),s.jsx("option",{value:"d",children:"days"})]})]})]}):s.jsxs("label",{className:"automate_row",children:[s.jsx("span",{children:"Run once at (UTC)"}),s.jsx("input",{type:"datetime-local",value:t.once_at,disabled:e.disabled,onChange:l=>e.on_change({once_at:l.target.value})})]}),s.jsx("div",{className:"automate_preview","aria-live":"polite","data-preview":"true",children:o||(r==="email"?"Incomplete email trigger.":"Incomplete schedule.")})]}),s.jsxs("fieldset",{"data-section":"context",children:[s.jsx("legend",{children:"Context"}),s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:"automate_context",value:"independent",checked:t.context==="independent",disabled:e.disabled,onChange:()=>e.on_change({context:"independent"})})," ",s.jsx("strong",{children:"Independent"})," (default) — ",Yy.independent]}),s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:"automate_context",value:"growing",checked:t.context==="growing",disabled:e.disabled,onChange:()=>e.on_change({context:"growing"})})," ",s.jsx("strong",{children:"Growing"})," — ",Yy.growing]}),t.context==="growing"?s.jsxs("label",{children:["Max growing context (tokens)",s.jsx("input",{type:"number",min:1,step:1,required:!0,value:t.growing_max_tokens,disabled:e.disabled,onChange:l=>e.on_change({growing_max_tokens:l.target.value})})]}):null,s.jsx("p",{className:"help_text muted","data-context-owns":"use_context",children:j2})]}),s.jsxs("fieldset",{"data-section":"tools",children:[s.jsx("legend",{children:"Tools"}),e.available_tools&&e.on_tools_change?s.jsx(ex,{availableTools:e.available_tools,value:e.tools??null,onChange:e.on_tools_change,disabled:e.disabled}):null,r==="email"?s.jsx("p",{className:"help_text muted","data-email-rule":"untrusted",children:Ut.untrusted_hint}):null,s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:"automate_tools",value:"auto",checked:t.tool_approval==="auto",disabled:e.disabled,onChange:()=>e.on_change({tool_approval:"auto"})})," ",qj,e.tools&&e.tools.length?s.jsxs("span",{className:"automate_preview",children:[" — ",e.tools.join(", ")]}):null]}),s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:"automate_tools",value:"ask",checked:t.tool_approval==="ask",disabled:e.disabled,onChange:()=>e.on_change({tool_approval:"ask"})})," Ask each time — every tool call waits for your approval on the Automations page"]})]}),s.jsxs("fieldset",{"data-section":"email",children:[s.jsx("legend",{children:"Email"}),n?null:s.jsx(xp,{status:e.email_status,onOpenMyEmail:e.on_open_my_email}),s.jsx(gS,{notifyEmail:n&&t.notify_email,onNotifyEmailChange:l=>e.on_change({notify_email:l}),recipients:n?t.email_recipients:lf,onRecipientsChange:l=>e.on_change({email_recipients:l}),disabled:e.disabled||!n,idBase:"automate"})]})]})}function H2(e){const t=e.form;return s.jsxs("div",{className:"automate_fields launch_grid","data-section":"advanced-schedule",children:[s.jsxs("label",{className:"launch_grid_cell",style:{gridColumn:"1 / -1"},children:[s.jsx("span",{className:"launch_label",children:"Title"}),s.jsx("input",{value:t.title,maxLength:120,disabled:e.disabled,placeholder:"Defaults to the prompt's first line",onChange:n=>e.on_change({title:n.target.value})})]}),t.when==="every"?s.jsxs(s.Fragment,{children:[s.jsxs("label",{className:"launch_grid_cell",children:[s.jsx("span",{className:"launch_label",children:"First run at (UTC; empty = now)"}),s.jsx("input",{type:"datetime-local",value:t.start_at,disabled:e.disabled,onChange:n=>e.on_change({start_at:n.target.value})})]}),s.jsxs("label",{className:"launch_grid_cell",children:[s.jsx("span",{className:"launch_label",children:"Stop after this many runs"}),s.jsx("input",{type:"number",min:1,step:1,value:t.count,disabled:e.disabled,onChange:n=>e.on_change({count:n.target.value})})]}),s.jsxs("label",{className:"launch_grid_cell",children:[s.jsx("span",{className:"launch_label",children:"Stop at (UTC)"}),s.jsx("input",{type:"datetime-local",value:t.until,disabled:e.disabled,onChange:n=>e.on_change({until:n.target.value})})]})]}):null]})}const V2="abstractobserver";function G2(e){return{getRun:t=>e.get_run(t),getHistory:t=>e.get_run_history_bundle(t,{include_subruns:!0,include_session:!0,ledger_mode:"full"}),getLedger:(t,n,r)=>e.get_ledger(t,{after:n,limit:200,signal:r}),streamLedger:(t,n,r,o,l)=>e.stream_ledger(t,{after:n,on_step:r,signal:o,on_open:l}),submitCommand:t=>e.submit_command(t)}}function K2(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 Y2=new Set(["completed","failed","cancelled"]);function J2(e){var T;const{gateway:t,discussion:n}=e,r=p.useMemo(()=>G2(t),[t]),[o,l]=p.useState(((T=n.session)==null?void 0:T.run_id)||""),[u,c]=p.useState(""),[f,m]=p.useState(!1),[_,g]=p.useState(""),{controller:w,snapshot:x}=F1({transport:r,runId:o,enabled:e.connected,clientId:V2}),j=n.session,b=!!o&&!Y2.has(x.status)&&x.status!=="idle",N=I1(x),C=async I=>{var U;const K=I.trim();if(K){m(!0);try{if(j){const J=String(((U=x.run)==null?void 0:U.workflow_id)||""),Y=K2(J),re=await t.start_run(Y.flow_id,{prompt:K},{bundle_id:Y.bundle_id,session_id:j.session_id});l(re)}else{const J=await e.on_fork(n.automation_id,n.occurrence_index,K);l(J.run_id)}c("")}finally{m(!1)}}},E=s.jsxs("div",{className:"discussion_head",children:[s.jsxs("button",{type:"button",className:"btn btn_sm","data-action":"discussion-back",onClick:e.on_close,title:`Back to ${n.automation_title}`,children:[s.jsx(et,{name:"chevronRight",size:13,className:"flip_x"})," ",n.automation_title]}),s.jsxs("span",{className:"discussion_title",children:[s.jsx(et,{name:"chat",size:15})," Discussion — fork at #",n.occurrence_index]}),s.jsx("span",{className:"pane_spacer"}),j?s.jsxs(s.Fragment,{children:[s.jsxs("button",{type:"button",className:`btn btn_sm${_==="own"?" active":""}`,"data-action":"discussion-files",onClick:()=>g(_==="own"?"":"own"),title:j.workspace_root,children:[s.jsx(et,{name:"folder",size:14})," Its files"]}),s.jsxs("button",{type:"button",className:`btn btn_sm${_==="mounted"?" active":""}`,"data-action":"automation-files",onClick:()=>g(_==="mounted"?"":"mounted"),title:j.mounted_workspace,children:[s.jsx(et,{name:"folder",size:14})," Automation files"]})]}):null]});return s.jsxs("section",{className:"pane auto_detail auto_discussion","data-discussion-session":(j==null?void 0:j.session_id)||void 0,children:[_&&j?s.jsx(Cx,{fetchGateway:t.fetch_gateway,runId:_==="own"?j.run_id:n.automation_id,title:_==="own"?"Discussion files":"Automation files",note:_==="own"?"The discussion's own writable folder.":"Mounted read-only for the discussion's file tools; nothing is written back.",onClose:()=>g(""),refreshKey:x.status}):null,s.jsx(E1,{header:E,messages:x.messages,draft:u,onDraftChange:c,onSend:C,busy:b||f,busyLabel:f?j?"Starting…":"Forking the automation…":N?"Waiting for you":"Working…",onCancel:b?()=>w.cancel():void 0,stopState:x.stop??null,disabled:!e.connected,interaction:lN(N,w,{records:x.records,currentRun:x.run}),placeholder:j?"Ask a follow-up…":`Ask about run #${n.occurrence_index}…`,emptyState:s.jsxs("div",{className:"help_text muted discussion_intro",children:["A new session that forks this automation at #",n.occurrence_index," with its history (runs 1–",n.occurrence_index,"). It works in its own writable workspace; the automation's files are mounted read-only for the file tools (shell commands are not sandboxed), and nothing is written back into the automation."]}),footer:x.error?s.jsx("div",{className:"observe_context_card error",role:"alert",children:x.error}):null})]})}function Wx(e){return`abstractobserver_list_open_${e}`}function qx(){try{return typeof localStorage>"u"?null:localStorage}catch{return null}}function X2(e,t=qx()){try{return(t==null?void 0:t.getItem(Wx(e)))!=="0"}catch{return!0}}function Z2(e,t,n=qx()){try{n==null||n.setItem(Wx(e),t?"1":"0")}catch{}}function hf(e){const[t,n]=p.useState(()=>X2(e)),r=p.useCallback(()=>{n(o=>{const l=!o;return Z2(e,l),l})},[e]);return[t,r]}function mf(e){return s.jsxs("button",{type:"button",className:`list_disclosure${e.className?` ${e.className}`:""}`,"aria-expanded":e.open,"aria-controls":e.controls,onClick:e.on_toggle,title:e.open?`Hide ${e.title.toLowerCase()}`:`Show ${e.title.toLowerCase()}`,children:[s.jsx(et,{name:e.open?"chevronDown":"chevronRight",size:14}),s.jsx("span",{className:"pane_title",children:e.title}),e.count!==void 0?s.jsx("span",{className:"pane_count",children:e.count}):null]})}const Q2=5e3,eC=[["","All"],["active","Active"],["paused","Paused"],["completed","Completed"],["failed","Failed"],["archived","Archived"]],tC={pause:xo.pause,resume:xo.resume,run_now:xo.run_now,edit:xo.revise,archive:`${xo.archive}…`,discuss:xo.discuss},nC={pause:Bi.pause,resume:Bi.resume,run_now:Bi.run_now,edit:Bi.revise,archive:Bi.archive,discuss:Bi.discuss},sC={pause:"pause",resume:"resume",run_now:"run_now",edit:"revise",archive:"archive",discuss:"discuss"},rC={legacy_pause:Bi.pause,legacy_resume:Bi.resume,legacy_run_now:Bi.run_now,open_run:"list",recreate:"refresh"};function iC(e){return s.jsx("span",{className:"auto_state","data-field":"state",children:s.jsx(ax,{status:e.status})})}function Lh(e){return s.jsxs("span",{className:`auto_fact${e.className?` ${e.className}`:""}`,"data-field":e.field,title:e.label,children:[s.jsx(et,{name:e.icon,size:12}),s.jsx("span",{children:e.children})]})}const oC={legacy_pause:"Suspend",legacy_resume:"Resume",legacy_run_now:"Run now",open_run:"Open run",recreate:"Recreate as automation"},aC="On: the schedule runs at its times. Off: suspended, scheduled runs are skipped until it is on again.";function Qy(e){const t=e.busy||e.ctl.enabled?null:e.ctl.reason||"Not available now.";return s.jsx(No,{variant:"sm",className:"auto_switch",action:"active",id:`auto-active-${e.summary.automation_id}`,label:xo.active,checked:e.summary.status==="active",unavailableReason:t,busy:e.busy,hint:e.hint,onChange:e.onChange})}function lC(e){const t=e.summary,n=Bx(t),r=e.state.selected_id===t.automation_id,o=e.state.busy,l=(f,m,_,g,w,x,j,b)=>s.jsxs("button",{type:"button",className:`btn btn_sm auto_action${j?" auto_action_icon":""}${w?` ${w}`:""}`,"data-action":f,disabled:!_.enabled,title:[j?m:null,_.enabled?null:_.reason,b].filter(Boolean).join(`
76
- `)||void 0,"aria-label":j?m:void 0,"aria-description":b,onClick:g,children:[x?s.jsx(et,{name:x,size:13}):null,j?null:s.jsx("span",{children:m})]},f);let u;if(n.legacy){const f=M2(t,o),m=t.status==="paused"?"legacy_resume":"legacy_pause",_=["legacy_run_now","open_run","recreate"];u=[s.jsx(Qy,{summary:t,busy:o,ctl:f[m],hint:aC,onChange:()=>e.h.on_legacy_action(t,m)},"active"),..._.map(g=>l(g,oC[g],f[g],()=>e.h.on_legacy_action(t,g),void 0,rC[g]))]}else{const f=T2(t,o),m=t.status==="active"?"pause":"resume",_=["run_now","edit","discuss","archive"];u=[s.jsx(Qy,{summary:t,busy:o,ctl:f.active,hint:lm("active",t),onChange:()=>e.h.on_row_action(t,m)},"active"),..._.map(g=>l(g,tC[g],f[g],()=>e.h.on_row_action(t,g),g==="archive"?"danger auto_action_end":void 0,nC[g],g==="archive",lm(sC[g],t)))]}const c=e.state.confirm_archive_id===t.automation_id;return s.jsxs("li",{className:`auto_row${r?" selected":""}`,"data-automation-id":t.automation_id,"data-legacy":n.legacy?"true":void 0,children:[s.jsxs("button",{type:"button",className:"auto_row_main",onClick:()=>e.h.on_select(t.automation_id),"aria-current":r?"true":void 0,children:[s.jsxs("span",{className:"auto_row_title",children:[n.title,n.legacy?s.jsx("span",{className:"chip scheduled",children:"legacy"}):null,s.jsx(iC,{status:n.state}),n.attention?s.jsxs("span",{className:"chip warn auto_row_attention","data-field":"attention",children:[s.jsx(et,{name:"warning",size:12})," ",n.attention]}):null]}),s.jsxs("span",{className:"auto_row_facts",children:[s.jsx(Lh,{icon:"refresh",field:"cadence",label:"When it runs",children:n.cadence}),n.current?s.jsx(Lh,{icon:"loader",field:"current",label:"Running now",className:"auto_row_current",children:n.current}):null,s.jsxs(Lh,{icon:"clock",field:"next",label:"Next run",children:["next: ",n.next_run]}),s.jsx(Lh,{icon:"info",field:"last-status",label:"Last run",children:n.last_status})]}),n.last?s.jsx("span",{className:"auto_row_excerpt","data-field":"excerpt",children:Ex(n.last)}):null]}),s.jsx("div",{className:"auto_row_actions",role:"toolbar","aria-label":`Controls for ${n.title}`,children:u}),c?s.jsxs("div",{className:"auto_row_confirm",role:"group","aria-label":"Confirm archive",children:[s.jsxs("span",{children:["Archive “",n.title,"”? Its history stays readable; it will not run again."]}),s.jsxs("button",{type:"button",className:"btn btn_sm danger auto_action","data-action":"archive-confirm",disabled:o,onClick:()=>e.h.on_confirm_archive(t),children:[s.jsx(et,{name:"archive",size:13}),s.jsx("span",{children:"Archive"})]}),s.jsxs("button",{type:"button",className:"btn btn_sm auto_action","data-action":"archive-cancel",onClick:e.h.on_cancel_archive,children:[s.jsx(et,{name:"x",size:13}),s.jsx("span",{children:"Keep it"})]})]}):null]})}function cC(e){const t=e.state,n=e.list?e.list.open:!0,r=t.error??t.list_error,o=r?am(r):null;return s.jsxs("section",{className:`pane auto_list${n?"":" list_collapsed"}`,"aria-label":"Automations",children:[s.jsxs("div",{className:"pane_header",children:[e.list?s.jsx(mf,{open:n,on_toggle:e.list.on_toggle,controls:"auto_list_body",title:"Automations",count:L_(t).length}):s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"pane_title",children:"Automations"}),s.jsx("span",{className:"pane_count",children:L_(t).length})]}),s.jsx("span",{className:"pane_spacer"}),s.jsx("select",{className:"seg_select",value:t.status_filter,onChange:l=>e.h.on_status_filter(l.target.value),"aria-label":"Filter by status",children:eC.map(([l,u])=>s.jsx("option",{value:l,children:u},l||"all"))}),s.jsx("button",{type:"button",className:"btn btn_sm auto_icon_btn","data-action":"refresh",onClick:e.h.on_refresh,disabled:t.loading||!e.available.available,title:"Refresh","aria-label":"Refresh",children:s.jsx(et,{name:t.loading?"loader":"refresh",size:14})}),s.jsxs("a",{className:`btn btn_sm auto_new${e.available.available?"":" disabled"}`,"data-action":"new",href:b2,"aria-disabled":!e.available.available,title:"New automation: opens Launch in Automate mode","aria-label":"New automation",onClick:l=>{l.preventDefault(),e.available.available&&e.h.on_new()},children:[s.jsx(et,{name:"plus",size:14}),s.jsx("span",{className:"auto_new_label",children:"New automation"})]})]}),s.jsxs("div",{className:"pane_body scroll",id:"auto_list_body",hidden:!n,children:[e.available.available?null:s.jsx("div",{className:"warn_callout",role:"note","data-unavailable":"true",children:e.available.reason}),o?s.jsxs("div",{className:"observe_context_card error auto_list_error",role:"alert","data-code":r==null?void 0:r.code,children:[s.jsx(et,{name:"error",size:14}),s.jsxs("span",{className:"auto_list_msg",children:[s.jsx("strong",{children:o.title})," ",s.jsx("span",{children:o.detail})]}),t.error&&e.h.on_dismiss_error?s.jsx("button",{type:"button",className:"auto_dismiss","data-action":"dismiss-error","aria-label":"Dismiss",title:"Dismiss",onClick:e.h.on_dismiss_error,children:s.jsx(et,{name:"x",size:12})}):null]}):null,s.jsx("div",{className:`auto_notice${t.notice?" on":""}`,role:"status",children:t.notice?s.jsxs(s.Fragment,{children:[s.jsx(et,{name:"check",size:13}),s.jsx("span",{className:"auto_list_msg",children:t.notice}),e.h.on_dismiss_notice?s.jsx("button",{type:"button",className:"auto_dismiss","data-action":"dismiss-notice","aria-label":"Dismiss",title:"Dismiss",onClick:e.h.on_dismiss_notice,children:s.jsx(et,{name:"x",size:12})}):null]}):null}),e.available.available&&t.loaded&&!t.items.length?s.jsx("div",{className:"help_text muted",children:"No automations yet. Create one from Launch → Automate."}):null,Xy(t)>0&&t.status_filter!=="archived"?s.jsx("div",{className:"auto_show_archived",children:s.jsx(No,{variant:"sm",action:"show-archived",label:`Archived (${Xy(t)})`,hint:"List archived automations too. Their history stays readable; they do not run.",checked:t.show_archived,onChange:l=>e.h.on_show_archived(l)})}):null,s.jsx("ul",{className:"auto_rows",children:L_(t).map(l=>s.jsx(lC,{summary:l,state:t,h:e.h},l.automation_id))})]})]})}function uC(e,t,n){const r=e.state,o=r.detail;if(!o||nc(o.summary))return null;const l=o.automation_id;return{summary:o.summary,...o.definition?{definition:o.definition}:{},occurrences:o.occurrences,triggerSources:r.trigger_sources,busy:r.busy,...o.error?{error:o.error}:{},onRevise:(u,c,f)=>e.revise(l,u,c,f==null?void 0:f.command_id),onCommand:(u,c,f)=>e.command(l,u,c,f==null?void 0:f.command_id),onDiscuss:async(u,c,f)=>{const m=await e.discuss(l,u,c,f==null?void 0:f.request_id);return t.on_open_session(m,xg(u,m),u),m},onSeen:u=>e.seen(l,u),onLoadMore:()=>void e.load_more(),onOpenRun:u=>t.on_open_run(u),...t.on_open_workspace?{onOpenWorkspace:t.on_open_workspace}:{},...t.fetch_gateway?{fetchGateway:t.fetch_gateway}:{},onAnswerWait:(u,c,f)=>e.answer_wait(l,u,c,f),...n?{editOpen:n.open,onEditOpenChange:n.on_change}:{},emailStatus:r.email_status,...t.on_open_my_email?{onOpenMyEmail:()=>{var u;return(u=t.on_open_my_email)==null?void 0:u.call(t)}}:{}}}function dC(e){const t=e.ctl.state.detail;if(!t&&e.ctl.state.selected_id)return s.jsx("section",{className:"pane auto_detail auto_detail_empty","aria-busy":"true",children:s.jsx("div",{className:"help_text muted",children:"Loading…"})});if(!t)return s.jsx("section",{className:"pane auto_detail auto_detail_empty",children:s.jsxs("div",{className:"help_text muted",children:["Select an automation to read its runs as a conversation, change it, or discuss a result (",bp.toLowerCase(),")."]})});if(nc(t.summary)){const r=Bx(t.summary);return s.jsxs("section",{className:"pane auto_detail","data-legacy":"true",children:[s.jsxs("div",{className:"pane_header",children:[s.jsx("span",{className:"pane_title",children:r.title}),s.jsx("span",{className:"chip scheduled",children:"legacy"})]}),s.jsxs("div",{className:"pane_body",children:[s.jsxs("p",{className:"help_text",children:["A schedule created before automations (",r.cadence,"). It keeps working with its existing controls: suspend, resume, run now and edit the interval from its run view. “Recreate as automation” opens Launch → Automate prefilled with its workflow, inputs and interval; the legacy schedule is not changed."]}),s.jsxs("div",{className:"auto_row_actions",children:[s.jsx("button",{type:"button",className:"btn btn_sm","data-action":"open_run",onClick:()=>e.h.on_legacy_action(t.summary,"open_run"),children:"Open run"}),s.jsx("button",{type:"button",className:"btn btn_sm primary","data-action":"recreate",onClick:()=>e.h.on_legacy_action(t.summary,"recreate"),children:"Recreate as automation"})]})]})]})}const n=uC(e.ctl,e.host,e.edit);return s.jsxs("section",{className:"pane auto_detail",children:[e.browser??null,n?s.jsx(aN,{...n,workflowPickerOptions:e.workflowPickerOptions,availableTools:e.availableTools}):null]})}function fC(e,t){if(t==="edit")return{kind:"edit"};if(t!=="discuss")return{kind:"forward"};const n=Ux(e);return n===null?{kind:"none"}:{kind:"discuss",index:n}}function hC(e){const t=e.ctl,[n,r]=hf("automations"),[o,l]=p.useState(null),u=C=>l(E=>({...C,opened:((E==null?void 0:E.opened)||0)+1})),[c,f]=p.useState(""),[m,_]=p.useState("");p.useSyncExternalStore(C=>t.subscribe(C),()=>t.state,()=>t.state);const[g,w]=p.useState(()=>typeof document>"u"||document.visibilityState!=="hidden");p.useEffect(()=>{const C=()=>w(document.visibilityState!=="hidden");return document.addEventListener("visibilitychange",C),()=>document.removeEventListener("visibilitychange",C)},[]),p.useEffect(()=>{if(!e.active||!g||!e.available.available)return;t.refresh();const C=window.setInterval(()=>void t.refresh(),z2);return()=>window.clearInterval(C)},[t,e.active,g,e.available.available]);const x=t.state.detail,j=t.state.notice;p.useEffect(()=>{if(!j)return;const C=window.setTimeout(()=>t.dismiss_notice(),Q2);return()=>window.clearTimeout(C)},[t,j]);const b={...e.host,on_open_workspace:C=>f(E=>E===C?"":C),fetch_gateway:e.gateway.fetch_gateway,on_open_session:(C,E,T)=>{e.host.on_open_session(C,E,T),x&&u({automation_id:x.automation_id,automation_title:x.summary.title,occurrence_index:T,session:C})}},N={...e.h,on_select:C=>{l(null),f(""),C!==m&&_(""),e.h.on_select(C)},on_dismiss_notice:()=>t.dismiss_notice(),on_dismiss_error:()=>t.dismiss_error(),on_row_action:(C,E)=>{const T=fC(C,E);T.kind==="forward"?e.h.on_row_action(C,E):T.kind==="edit"?(l(null),f(""),_(C.automation_id),e.h.on_select(C.automation_id)):T.kind==="discuss"&&(e.h.on_select(C.automation_id),u({automation_id:C.automation_id,automation_title:C.title,occurrence_index:T.index}))}};return s.jsxs("div",{className:`page auto_page${n?"":" list_collapsed"}`,children:[s.jsx(cC,{state:t.state,available:e.available,h:N,list:{open:n,on_toggle:r}}),o?s.jsx(J2,{gateway:e.gateway,discussion:o,connected:e.active,on_fork:async(C,E,T)=>{const I=await t.discuss(C,E,T);return e.host.on_open_session(I,xg(E,I),E),l(K=>K&&{...K,session:I}),I},on_close:()=>l(null)},o.opened):s.jsx(dC,{workflowPickerOptions:e.workflowPickerOptions,availableTools:e.availableTools,ctl:t,host:b,h:N,edit:{open:!!x&&m===x.automation_id,on_change:C=>_(C&&x?x.automation_id:"")},browser:c?s.jsx(Cx,{fetchGateway:e.gateway.fetch_gateway,runId:c,title:c===(x==null?void 0:x.automation_id)?"Automation files":"Run files",onClose:()=>f("")}):void 0})]})}function mC(e){return s.jsx(No,{variant:"row",action:"auto-connect",label:"Auto-connect on load",description:"Reuse the browser session automatically when the app opens.",checked:e.checked,onChange:e.onChange})}function _C(e){return s.jsx("div",{className:`settings_choice ${e.checked?"on":""}`,children:s.jsx(No,{variant:"row",action:"assistant-skill",label:s.jsxs("span",{className:"settings_choice_name",children:[e.name,e.version?s.jsxs("em",{children:[" v",e.version]}):null]}),ariaLabel:e.name,description:e.description||void 0,checked:e.checked,onChange:e.onChange})})}const pC="On: the schedule runs at its times. Off: suspended, scheduled runs are skipped until it is on again.";function gC(e){return s.jsx(No,{variant:"sm",action:"schedule-active",className:"observe_schedule_switch",label:"Active",hint:pC,checked:e.active,unavailableReason:e.unavailableReason,busy:e.busy,onChange:e.onChange})}function yC(e){return s.jsx(No,{variant:"sm",action:"mindmap-live",label:"Live",hint:"Refresh the map as new memory arrives.",checked:e.checked,onChange:e.onChange})}function wC(e){return s.jsx(No,{variant:"row",action:"apply-immediately",label:"Apply immediately",description:"Recompute the next run from now if the schedule is waiting.",checked:e.checked,busy:e.busy,onChange:e.onChange})}function vC(){const e="0.6.2".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 xC(){return Yk("abstractobserver",vC())}async function bC(e){let t;try{t=await e.gateway_about()}catch(n){return py(null,n instanceof Error?n.message||n.name:String(n))}return py(t)}class dm{constructor(t){this._maxSize=dm._normalizeMaxSize(t),this._values=[]}get maxSize(){return this._maxSize}get size(){return this._values.length}static _normalizeMaxSize(t){const n=Number(t);return!Number.isFinite(n)||n<=0?1:Math.min(1e3,Math.floor(n))}setMaxSize(t){const n=dm._normalizeMaxSize(t);this._maxSize=n,this._values.length>n&&(this._values=this._values.slice(this._values.length-n))}clear(){this._values=[]}push(t){const n=Number(t),r=Number.isFinite(n)?n:null;this._values.push(r),this._values.length>this._maxSize&&this._values.splice(0,this._values.length-this._maxSize)}values(){return this._values.slice()}last(){return this._values.length?this._values[this._values.length-1]:null}}function kC(e){try{return new URL(String(e)),!0}catch{return!1}}function jC({baseUrl:e,endpoint:t}){const n=String(t||"api/gateway/host/metrics/gpu");return kC(n)?n:e&&String(e).trim()?new URL(n,String(e)).toString():n}async function SC({token:e,getToken:t}){if(typeof t=="function"){const n=await t();return n==null?"":String(n)}return e==null?"":String(e)}function NC({token:e}){const t=String(e||"").trim();return t?{Authorization:`Bearer ${t}`}:{}}function CC(e){if(!e||typeof e!="object")return null;const t=Number(e.utilization_gpu_pct);if(Number.isFinite(t))return t;const n=e.gpus;if(Array.isArray(n)&&n.length){const r=n.map(l=>Number(l&&l.utilization_gpu_pct)).filter(l=>Number.isFinite(l));return r.length?r.reduce((l,u)=>l+u,0)/r.length:null}return null}async function EC({baseUrl:e,endpoint:t,token:n,getToken:r,signal:o,fetchImpl:l}={}){const u=jC({baseUrl:e,endpoint:t}),c=await SC({token:n,getToken:r}),f=l||globalThis.fetch;if(typeof f!="function")return{ok:!1,status:0,error:"fetch_unavailable",payload:null};let m;try{m=await f(u,{method:"GET",headers:{Accept:"application/json",...NC({token:c})},signal:o})}catch(g){return{ok:!1,status:0,error:"network_error",detail:g instanceof Error?g.message:String(g),payload:null}}let _=null;try{_=await m.json()}catch{_=null}return{ok:m.ok,status:m.status,error:m.ok?null:"http_error",payload:_}}const Vd=Object.freeze({tickMs:1500,historySize:20,endpoint:"api/gateway/host/metrics/gpu",baseUrl:"",mode:"full"});function AC(e){return Number.isFinite(e)?Math.min(1,Math.max(0,e)):0}function ew(e,t,n){return Number.isFinite(e)?Math.min(n,Math.max(t,e)):t}function tw(e,t){const n=Number(e);return Number.isFinite(n)?Math.floor(n):t}function O_(e,t=1){const n=ew(Number(e)/100,0,1),r=Math.round(140-140*n),o=ew(Number(t),0,1);return o>=1?`hsl(${r} 85% 55%)`:`hsl(${r} 85% 55% / ${o})`}function nw(e){const t={...Vd,...e||{}};return t.tickMs=Math.max(250,tw(t.tickMs,Vd.tickMs)),t.historySize=Math.max(1,Math.min(200,tw(t.historySize,Vd.historySize))),t.endpoint=String(t.endpoint||Vd.endpoint),t.baseUrl=String(t.baseUrl||""),t.mode=String(t.mode||Vd.mode).trim().toLowerCase(),t.mode!=="icon"&&(t.mode="full"),t}function $C(){return`
77
- :host{display:inline-block;font-family:ui-sans-serif,system-ui,-apple-system,Segoe UI,Roboto,Helvetica,Arial,"Apple Color Emoji","Segoe UI Emoji";line-height:1}
78
- .wrap{box-sizing:border-box;display:flex;flex-direction:column;gap:6px;padding:var(--monitor-gpu-padding,8px 10px);border:1px solid var(--monitor-gpu-border,#2a2f3a);border-radius:var(--monitor-gpu-radius,10px);background:var(--monitor-gpu-bg,#0b1020);color:var(--monitor-gpu-fg,#e7eaf0);width:var(--monitor-gpu-width,180px)}
79
- .wrap.icon{gap:var(--monitor-gpu-gap,4px);padding:var(--monitor-gpu-padding,4px);border-radius:var(--monitor-gpu-radius,999px);width:var(--monitor-gpu-width,30px);background:linear-gradient(180deg,rgba(255,255,255,0.08),rgba(255,255,255,0.02)),var(--monitor-gpu-bg,#0b1020);box-shadow:0 0 14px var(--monitor-gpu-accent-glow, rgba(76,195,255,0.18))}
80
- .wrap.icon .top{display:none}
81
- .wrap.icon .bars{height:var(--monitor-gpu-bars-height,18px)}
82
- .top{display:flex;align-items:baseline;justify-content:space-between;gap:10px}
83
- .label{font-size:var(--monitor-gpu-font-size,var(--font-size-sm,12px));opacity:.9}
84
- .value{font-variant-numeric:tabular-nums;font-size:var(--monitor-gpu-font-size,var(--font-size-sm,12px));opacity:.95}
85
- .bars{display:flex;align-items:flex-end;gap:2px;height:var(--monitor-gpu-bars-height,34px);overflow:hidden}
86
- .bar{flex:1;min-width:0;border-radius:2px;background:var(--monitor-gpu-bar,#4cc3ff);height:2px;opacity:.9;transition:height .25s ease, background .25s ease, opacity .25s ease}
87
- .bar.missing{background:var(--monitor-gpu-bar-missing,#62708a);opacity:.35}
88
- .bar.error{background:var(--monitor-gpu-bar-error,#ff6b6b);opacity:.7}
89
- .muted{opacity:.6}
90
- `}class TC{constructor(t,n={}){if(!t||typeof t!="object")throw new TypeError("target element is required");this._target=t,this._opts=nw(n),this._buffer=new dm(this._opts.historySize),this._timer=null,this._timer_gen=0,this._running=!1,this._abort=null,this._resumeTimer=null,this._mounted=!1,this._els=null,this._token=n.token,this._getToken=n.getToken,this._stoppedForAuth=!1}get options(){return{...this._opts}}set token(t){this._token=t,String(this._token||"").trim()&&this._stoppedForAuth&&(this._stoppedForAuth=!1,this.start())}get token(){return this._token}set getToken(t){this._getToken=t}get getToken(){return this._getToken}mount(){if(this._mounted)return;if(typeof document>"u")throw new Error("MonitorGpuWidget requires a browser DOM");const t=this._target;t.textContent="";const n=document.createElement("style");n.textContent=$C();const r=document.createElement("div");r.className=this._opts.mode==="icon"?"wrap icon":"wrap";const o=document.createElement("div");o.className="top";const l=document.createElement("div");l.className="label",l.textContent="GPU";const u=document.createElement("div");u.className="value muted",u.textContent="—",o.appendChild(l),o.appendChild(u);const c=document.createElement("div");c.className="bars",r.appendChild(o),r.appendChild(c),t.appendChild(n),t.appendChild(r),this._els={wrap:r,value:u,bars:c},this._mounted=!0,this._rebuildBars(),this._render()}start(){this.mount(),!this._running&&(this._running=!0,this._timer_gen+=1,this._poll_loop(this._timer_gen))}stop(){this._running=!1,this._timer_gen+=1,this._timer&&(clearTimeout(this._timer),this._timer=null),this._resumeTimer&&(clearTimeout(this._resumeTimer),this._resumeTimer=null),this._abort&&(this._abort.abort(),this._abort=null)}destroy(){this.stop(),this._target&&this._mounted&&(this._target.textContent=""),this._mounted=!1,this._els=null}setOptions(t){const n=nw({...this._opts,...t||{}}),r=n.historySize!==this._opts.historySize,o=n.tickMs!==this._opts.tickMs,l=n.mode!==this._opts.mode;this._opts=n,l&&this._mounted&&this._els&&this._els.wrap&&(this._els.wrap.className=n.mode==="icon"?"wrap icon":"wrap"),r&&(this._buffer.setMaxSize(n.historySize),this._mounted&&this._rebuildBars()),o&&this._running?(this.stop(),this.start()):this._mounted&&this._render()}push(t){this._buffer.push(t),this._render()}_rebuildBars(){if(!this._els)return;const{bars:t}=this._els;t.textContent="";for(let n=0;n<this._opts.historySize;n+=1){const r=document.createElement("div");r.className="bar missing",r.style.height="2px",t.appendChild(r)}}_render({error:t=!1}={}){if(!this._els)return;const{wrap:n,value:r,bars:o}=this._els,l=this._buffer.values(),u=this._buffer.last(),c=Number.isFinite(u)?Math.max(0,Math.min(100,u)):null;c==null?(r.textContent=t?"N/A":"—",r.classList.add("muted")):(r.textContent=`${c.toFixed(0)}%`,r.classList.remove("muted")),n&&(n.title=c==null?"GPU —":`GPU ${c.toFixed(0)}%`,c==null?(n.style.removeProperty("--monitor-gpu-accent"),n.style.removeProperty("--monitor-gpu-accent-glow")):(n.style.setProperty("--monitor-gpu-accent",O_(c,.95)),n.style.setProperty("--monitor-gpu-accent-glow",O_(c,.35))));const f=Array.from(o.children),m=Math.max(0,f.length-l.length),_=Math.max(2,o&&typeof o.clientHeight=="number"&&o.clientHeight>0?o.clientHeight:34);for(let g=0;g<f.length;g+=1){const w=f[g],x=g-m,j=x>=0?l[x]:null,b=Number.isFinite(j)?j:null,N=b==null?0:AC(b/100),C=Math.max(2,Math.min(_,Math.round(N*_)));w.style.height=`${C}px`,w.style.background=b==null?"":O_(b),w.className="bar",b==null&&w.classList.add("missing"),t&&w.classList.add("error")}}async _tick(){const t=String(this._token||"").trim(),n=this._getToken,r=!!t||typeof n=="function";this._abort&&this._abort.abort(),this._abort=new AbortController;const o=await EC({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=CC(l);if(!o.ok){if(this._buffer.push(null),this._render({error:!0}),o.status===401||o.status===403){const f=String(this._token||"").trim(),m=typeof this._getToken=="function";if(!r&&(!!f||m))return;this._stoppedForAuth=!0,this.stop()}else o.status===429&&(this.stop(),this._resumeTimer=setTimeout(()=>{this._resumeTimer=null,this._mounted&&this.start()},3e4));return}if(!u||c==null){this._buffer.push(null),this._render();return}this._buffer.push(c),this._render()}async _poll_loop(t){!this._running||t!==this._timer_gen||(await this._tick(),!(!this._running||t!==this._timer_gen)&&(this._timer=setTimeout(()=>{this._timer=null,this._poll_loop(t)},this._opts.tickMs)))}}function MC(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 TC(o,{}),this._upgradeProperty("token"),this._upgradeProperty("getToken"),this._upgradeProperty("mode")}_upgradeProperty(o){if(!Object.prototype.hasOwnProperty.call(this,o))return;const l=this[o];try{delete this[o]}catch{}this[o]=l}connectedCallback(){this._controller.setOptions(this._readAttrs());const o=()=>{this.isConnected&&this._controller.start()};typeof queueMicrotask=="function"?queueMicrotask(o):Promise.resolve().then(o)}disconnectedCallback(){this._controller.destroy()}attributeChangedCallback(){this._controller.setOptions(this._readAttrs())}_readAttrs(){const o=this.getAttribute("tick-ms"),l=this.getAttribute("history-size"),u=this.getAttribute("endpoint"),c=this.getAttribute("base-url"),f=this.getAttribute("mode");return{...o!=null?{tickMs:o}:{},...l!=null?{historySize:l}:{},...u!=null?{endpoint:u}:{},...c!=null?{baseUrl:c}:{},...f!=null?{mode:f}:{}}}set token(o){this._controller.token=o}get token(){return this._controller.token}set getToken(o){this._controller.getToken=o}get getToken(){return this._controller.getToken}set tickMs(o){this._controller.setOptions({tickMs:o})}get tickMs(){return this._controller.options.tickMs}set historySize(o){this._controller.setOptions({historySize:o})}get historySize(){return this._controller.options.historySize}set endpoint(o){this._controller.setOptions({endpoint:o})}get endpoint(){return this._controller.options.endpoint}set baseUrl(o){this._controller.setOptions({baseUrl:o})}get baseUrl(){return this._controller.options.baseUrl}set mode(o){this._controller.setOptions({mode:o})}get mode(){return this._controller.options.mode}}globalThis.customElements.define(e,n)}function Su(e){return String(e||"").trim().toLowerCase()}function Mm(e){return`${(e==null?void 0:e.filename)||""} ${(e==null?void 0:e.source_path)||""}`.trim().toLowerCase()}function cf(e,t){return t.some(n=>e.endsWith(n))}function RC(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 LC(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 IC(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 Hx(e,t){var u,c,f,m,_;const n=Su(e==null?void 0:e.content_type),r=Mm(e),o=[e==null?void 0:e.semantic_kind,e==null?void 0:e.render_kind,e==null?void 0:e.task,(u=e==null?void 0:e.tags)==null?void 0:u.semantic_kind,(c=e==null?void 0:e.tags)==null?void 0:c.render_kind,(f=e==null?void 0:e.tags)==null?void 0:f.task,(m=e==null?void 0:e.tags)==null?void 0:m.kind,(_=e==null?void 0:e.tags)==null?void 0:_.type].map(g=>String(g||"").trim().toLowerCase()).filter(Boolean).join(" ");if(/(^|[^a-z0-9])(code|source_code|script|program|executable)([^a-z0-9]|$)/i.test(o)||n.includes("javascript")||n.includes("typescript")||n.includes("x-python")||n.includes("x-shellscript")||n.includes("x-rust")||n.includes("x-go")||n.includes("x-java")||n.includes("x-csrc")||n.includes("x-c++src")||cf(r,[".py",".js",".jsx",".ts",".tsx",".mjs",".cjs",".sh",".bash",".zsh",".go",".rs",".java",".c",".cc",".cpp",".h",".hpp",".cs",".php",".rb",".swift",".kt",".sql"]))return!0;const l=String(t||"").replace(/\r\n/g,`
91
- `).replace(/\r/g,`
92
- `).split(`
93
- `);return Vx(l)}function OC(e){const n=String(e||"").replace(/\r\n/g,`
94
- `).replace(/\r/g,`
95
- `).split(`
96
- `),r=n.findIndex(u=>/^Markdown Content:\s*$/i.test(u.trim()));if(r===-1)return null;const o=[];for(const u of n.slice(0,r)){const c=u.match(/^\s*([A-Za-z][A-Za-z0-9 /_-]{1,40}):\s*(.+?)\s*$/);c&&o.push({label:c[1].trim(),value:c[2].trim()})}const l=n.slice(r+1).join(`
97
- `).trim();return!o.length&&!l?null:{metadata:o,body:l}}function PC(e){const t=e.map(n=>n.trim()).filter(Boolean).slice(0,8);if(t.length<2)return!1;for(const n of[","," ",";"]){const r=t.map(o=>o.split(n).length);if(r[0]>=3&&r.every(o=>Math.abs(o-r[0])<=1))return!0}return!1}function DC(e){const t=e.map(r=>r.trimEnd()).filter(Boolean).slice(0,20);if(!t.length)return!1;const n=t.filter(r=>/^(\[[^\]]+\]|\d{4}-\d{2}-\d{2}[t\s]|\w+:\s|traceback\b|error\b|warn\b|info\b)/i.test(r.trim())).length;return t.length>=4&&n/t.length>=.55?!0:Vx(e)}function Vx(e){const t=e.map(r=>r.trimEnd()).filter(Boolean).slice(0,20);if(!t.length)return!1;const n=t.filter(r=>/[{};]\s*$/.test(r)||/^\s*(import|export|const|let|var|function|class|def|if|for|while|return)\b/.test(r)).length;return t.length>=4&&n/t.length>=.55}function FC(e){const t=String(e||"");if(!t.trim())return!1;const n=t.match(/\\[A-Za-z]{2,}\b/g)||[];if(n.length>=1&&/\\(?:setcctype|sectctype|documentclass|begin|end|maketitle|geq|leq|cite|ref|label)\b/.test(t)||n.length>=4)return!0;const o=t.replace(/\r\n/g,`
98
- `).replace(/\r/g,`
99
- `).split(`
100
- `).map(f=>f.trim()).filter(Boolean).slice(0,80);if(o.length<12)return!1;const l=o.filter(f=>f.length<=28).length,u=o.filter(f=>/^[,.;:()†]+$/.test(f)).length;return o.filter(f=>/^(abstract\.?|introduction|references|appendix|figure\s+\d+|table\s+\d+)\b/i.test(f)).length>=2&&(l/o.length>=.45||u>=2)}function zC(e,t){var m;const n=String(t||""),r=RC(e);if(/(^|[^a-z0-9])(markdown|mdown)([^a-z0-9]|$)/i.test(r))return!0;if(!n.trim())return!1;if(/(^|\n)\s*Markdown Content:\s*(\n|$)/i.test(n)||n.includes("```")||/(^|\n)\s*#{1,6}\s+\S/.test(n)||/(^|\n)[ \t]*[-*][ \t]+\S/.test(n)||/(^|\n)[ \t]*\d+[\.)][ \t]+\S/.test(n)||/\*\*[^*\n][\s\S]*?\*\*/.test(n)||/\[[^\]\n]+\]\([^)]+\)/.test(n)||/(^|\n)\s*\|.+\|\s*(\n|$)/.test(n)&&/(^|\n)\s*\|?\s*:?-{3,}:?\s*(\|\s*:?-{3,}:?\s*)+\|?\s*(\n|$)/.test(n))return!0;const o=n.replace(/\r\n/g,`
101
- `).replace(/\r/g,`
102
- `).split(`
103
- `),l=o.map(_=>_.trim()).filter(Boolean);if(l.length<2||FC(n)||PC(o)||DC(o))return!1;const u=((m=n.match(/[A-Za-z][A-Za-z'-]+/g))==null?void 0:m.length)||0,c=o.filter(_=>!_.trim()).length,f=l.filter(_=>/[A-Za-z]{3,}/.test(_)&&_.length>=12).length;return u>=24&&f>=2&&(c>=1||l[0].length<=140)}function uf(e){const t=Su(e==null?void 0:e.modality),n=Su(e==null?void 0:e.content_type),r=Mm(e),o=LC(e);return t==="image"||n.startsWith("image/")||cf(r,[".png",".jpg",".jpeg",".gif",".webp",".bmp",".svg",".tif",".tiff",".heic"])?"image":t==="audio"||t==="voice"||t==="music"||t==="sound"||n.startsWith("audio/")||/(tts|stt|voice|music|sound|speech|audio)/i.test(o)||cf(r,[".wav",".mp3",".m4a",".aac",".flac",".ogg",".opus",".aiff",".mid",".midi"])?"audio":t==="video"||n.startsWith("video/")||cf(r,[".mp4",".mov",".webm",".mkv",".avi",".m4v"])?"video":!n||t==="text"||n.startsWith("text/")||n.includes("json")||n.includes("yaml")||n.includes("toml")||n.includes("xml")||n.includes("html")||n.includes("markdown")||n.includes("csv")||Hx(e,"")?"text":"binary"}function fm(e,t){const n=Su(e==null?void 0:e.content_type),r=Mm(e),o=String(t||"").trim();return n.includes("html")||r.endsWith(".html")||r.endsWith(".htm")||IC(t)?"html":Hx(e,t)?"code":n.includes("markdown")||r.endsWith(".md")||r.endsWith(".markdown")?"markdown":n.includes("json")||r.endsWith(".json")||r.endsWith(".jsonl")||(o.startsWith("{")||o.startsWith("["))&&$m(o)!==null?"json":zC(e,t)?"markdown":"text"}function bg(e,t=""){const n=uf(e);if(n==="image"||n==="video")return n;if(n==="audio"){const r=(e==null?void 0:e.tags)||{},o=[e==null?void 0:e.semantic_kind,e==null?void 0:e.modality,e==null?void 0:e.task,r.semantic_kind,r.modality,r.kind,r.task,r.source,e==null?void 0:e.filename,e==null?void 0:e.source_path].map(l=>String(l||"").trim().toLowerCase()).filter(Boolean).join(" ");return/(^|[^a-z0-9])(voice|tts|speech)([^a-z0-9]|$)/i.test(o)?"voice":/(^|[^a-z0-9])(music|song|instrumental|t2m)([^a-z0-9]|$)/i.test(o)?"music":/(^|[^a-z0-9])(sound|sfx|recording)([^a-z0-9]|$)/i.test(o)?"sound":"audio"}if(n==="binary"){const r=Su(e==null?void 0:e.modality),o=Su(e==null?void 0:e.content_type),l=Mm(e);return r==="document"||o.includes("pdf")||cf(l,[".pdf",".doc",".docx",".ppt",".pptx",".xls",".xlsx"])?"document":"other"}return fm(e,t)}function P_(e){var m,_;const t=String(e||"").replace(/\r\n/g,`
104
- `).replace(/\r/g,`
105
- `).trim();if(!t)return"";const n=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]),r=t.match(/<!--[\s\S]*?-->|<!doctype\b[^>]*>|<!\[CDATA\[[\s\S]*?\]\]>|<\/?[A-Za-z][^>]*>|[^<]+/gi)||[t],o=[];let l=0,u="";const c=g=>" ".repeat(Math.max(0,g)),f=(g,w)=>{const x=g.match(/^(<\/?|<!)([^\s/>]+)([\s\S]*?)(\/?>)$/);if(!x||g.length<=120||g.startsWith("</")||g.startsWith("<!"))return[`${c(w)}${g.trim()}`];const j=(x[3]||"").trim();if(!j)return[`${c(w)}${g.trim()}`];const b=j.match(/[^\s="'<>`]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'<>`]+))?/g)||[j];return[`${c(w)}${x[1]}${x[2]}`,...b.map(N=>`${c(w+1)}${N.trim()}`),`${c(w)}${x[4]}`]};for(const g of r){const w=String(g||"");if(!w.trim())continue;const x=w.trim().toLowerCase();if(x.startsWith("</")){const b=((m=x.match(/^<\/\s*([a-z0-9:-]+)/))==null?void 0:m[1])||"";u&&b===u&&(u=""),l=Math.max(0,l-1),o.push(`${c(l)}${w.trim()}`);continue}if(w.trimStart().startsWith("<")){o.push(...f(w,l));const b=((_=x.match(/^<\s*([a-z0-9:-]+)/))==null?void 0:_[1])||"";/\/>\s*$/.test(w)||x.startsWith("<!")||n.has(b)||(l+=1,(b==="script"||b==="style")&&(u=b));continue}if(u){const b=w.trim();b&&o.push(...b.split(`
106
- `).map(N=>`${c(l)}${N.trimEnd()}`));continue}const j=w.replace(/\s+/g," ").trim();j&&o.push(`${c(l)}${j}`)}return o.join(`
107
- `)}const BC=/^\s*<runtime_metadata>\s*([\s\S]*?)\s*<\/runtime_metadata>\s*/i;function kg(e){const t=typeof e=="string"?e:String(e??""),n=BC.exec(t);if(!n)return{text:t.trim(),metadata:null,stripped:!1};let r=null;try{const o=JSON.parse(String(n[1]||"").trim());o&&typeof o=="object"&&!Array.isArray(o)&&(r=o)}catch{r=null}return{text:t.slice(n[0].length).trim(),metadata:r,stripped:!0}}function Gx(...e){const t={};for(const n of e)if(!(!n||typeof n!="object"||Array.isArray(n)))for(const[r,o]of Object.entries(n))o==null||String(o).trim()===""||(t[r]=o);return Object.keys(t).length?t:null}function Mp(e){if(e==null)return"";if(typeof e=="string")return e.trim();if(Array.isArray(e))return e.map(t=>Mp(t)).filter(Boolean).join(`
108
- `).trim();if(typeof e=="object"){const t=e.text??e.content??e.message??e.value;if(t!==e){const n=Mp(t);if(n)return n}}return""}function Kx(e){const t=kg(Mp(e));return{text:t.text,runtime_metadata:t.metadata}}function UC(e){var r,o;if(!e)return{text:"",runtime_metadata:null};const t=typeof e.prompt=="string"?String(e.prompt).trim():"";if(t){const l=kg(t);return{text:l.text,runtime_metadata:l.metadata}}const n=[(r=e.context)==null?void 0:r.messages,e.messages,e.conversation,e.history].filter(Array.isArray);for(const l of n)for(let u=l.length-1;u>=0;u-=1){const c=l[u],f=String((c==null?void 0:c.role)||(c==null?void 0:c.speaker)||"").trim().toLowerCase();if(f&&f!=="user"&&f!=="human")continue;const m=Kx((c==null?void 0:c.content)??(c==null?void 0:c.text)??c);if(m.text)return{text:m.text,runtime_metadata:Gx(m.runtime_metadata,c!=null&&c.runtime_metadata&&typeof c.runtime_metadata=="object"?c.runtime_metadata:null,(o=c==null?void 0:c.metadata)!=null&&o.runtime_metadata&&typeof c.metadata.runtime_metadata=="object"?c.metadata.runtime_metadata:null)}}return{text:"",runtime_metadata:null}}function WC(e,t=6){var l,u;if(!e)return[];const r=[(l=e.context)==null?void 0:l.messages,e.messages,e.conversation,e.history].filter(Array.isArray).find(c=>c.length)||[],o=[];for(const c of r){const f=String((c==null?void 0:c.role)||(c==null?void 0:c.speaker)||(c==null?void 0:c.author)||"").trim().toLowerCase()||"message",m=Kx((c==null?void 0:c.content)??(c==null?void 0:c.text)??(c==null?void 0:c.message)??c),_=m.text;if(!_)continue;const g=String((c==null?void 0:c.ts)||(c==null?void 0:c.timestamp)||(c==null?void 0:c.created_at)||(c==null?void 0:c.time)||"").trim(),w=Gx(m.runtime_metadata,c!=null&&c.runtime_metadata&&typeof c.runtime_metadata=="object"?c.runtime_metadata:null,(u=c==null?void 0:c.metadata)!=null&&u.runtime_metadata&&typeof c.metadata.runtime_metadata=="object"?c.metadata.runtime_metadata:null);o.push({role:f,text:_,ts:g,runtime_metadata:w})}return o.slice(Math.max(0,o.length-Math.max(1,t)))}function Yx(e){const t=String(e||"").trim().toLowerCase().replace(/\s+/g," ");return t==="please respond:"||t==="please respond"||t==="type response..."||t==="type response"}function qC(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 Jx="inferred from the call's arguments (regex heuristic) — not a declared risk tier; declared tiers replace this when the grant API ships";function Xx(e){const t=String((e==null?void 0:e.name)||"").trim().toLowerCase(),n=e!=null&&e.arguments&&typeof e.arguments=="object"?e.arguments:{},r=String((n==null?void 0:n.command)||(n==null?void 0:n.cmd)||(n==null?void 0:n.shell)||"").trim().toLowerCase(),o=[];return(t.includes("execute_command")||t.includes("terminal")||r)&&o.push("Shell"),/[;&|]?\s*(rm|rmdir|mv|chmod|chown|sudo)\b/.test(r)&&o.push("Destructive risk"),/(^|\s)(curl|wget|scp|ssh|nc|ncat|ftp)\b/.test(r)&&o.push("Network"),/(^|\s)(cat|sed|rg|grep|ls|find|pwd)\b/.test(r)&&!/[>|]\s*\S/.test(r)&&o.push("Read path"),/[>|]\s*\S|(^|\s)(tee|touch|mkdir|cp)\b/.test(r)&&o.push("Filesystem write"),o.length||o.push("Tool call"),Array.from(new Set(o)).slice(0,4)}function jg(e,t){const n=String((e==null?void 0:e.reason)||"").trim().toLowerCase(),r=qC(t);return t.length?`Approval required: ${r||"tool call"}`:n==="user"?"Waiting for your answer":n==="event"?"Waiting for a user response event":n==="subworkflow"?"Waiting for a subworkflow":n==="until"?"Scheduled wait":n?`Waiting: ${n}`:"Waiting for input"}function Zx(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 Qx(e,t){const n=String((e==null?void 0:e.prompt)||"").trim(),r=kg(n),o=UC(t);return r.text&&!Yx(r.text)?{text:r.text,runtime_metadata:r.metadata}:o.text?o:{text:r.text||n,runtime_metadata:r.metadata}}function HC(e,t){return Qx(e,t).text}function VC(e,t){return e||String(t||"").trim()||{}}function Ui(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 lc(e){const t=String(e.status||"unknown").trim()||"unknown";return s.jsx("span",{className:`run_status_pill ${ac(t)}`,children:t})}function GC(e){var l;const t=String((e==null?void 0:e.status)||"").trim().toLowerCase();if(So(t))return"";const n=e!=null&&e.waiting&&typeof e.waiting=="object"?e.waiting:null,r=String((n==null?void 0:n.reason)||(e==null?void 0:e.waiting_reason)||"").trim().toLowerCase(),o=Array.isArray((l=n==null?void 0:n.details)==null?void 0:l.tool_calls)?n.details.tool_calls:[];return o.length?jg(n,o):r==="user"?"Waiting for your answer":r==="event"?"Waiting for a response event":r==="subworkflow"?"Waiting for subworkflow":r==="until"?"Scheduled wait":r?`Waiting: ${r}`:t==="waiting"?"Waiting, reason unknown":""}function hm(e){const t=e==null?void 0:e.error;return t?typeof t=="string"?jt(t,{max_chars:220,max_lines:2}):jt(cr(t,400),{max_chars:220,max_lines:2}):""}function KC(e){const t=GC(e);if(t)return t;const n=hm(e);if(n)return n;const r=String((e==null?void 0:e.current_node)||"").trim();if(r)return`Current node: ${r}`;const o=String((e==null?void 0:e.status)||"").trim().toLowerCase();return o==="running"?"Running":So(o)?"Terminal":"No current activity reported"}function eb(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 sw(e){const t=eb(e),n=e!=null&&e.metadata&&typeof e.metadata=="object"?e.metadata:e!=null&&e.meta&&typeof e.meta=="object"?e.meta:{},r=e!=null&&e.tags&&typeof e.tags=="object"?e.tags:{},o=_n(e==null?void 0:e.modality,t==null?void 0:t.modality,n==null?void 0:n.modality,r.modality).toLowerCase();if(o)return o;const l=_n(e==null?void 0:e.content_type,e==null?void 0:e.mime_type,e==null?void 0:e.mime,t==null?void 0:t.content_type,t==null?void 0:t.mime_type,t==null?void 0:t.mime,n==null?void 0:n.content_type,r.content_type).toLowerCase();return l.startsWith("image/")?"image":l.startsWith("audio/")?"audio":l.startsWith("video/")?"video":l.includes("pdf")?"document":l.startsWith("text/")||l.includes("json")||l.includes("markdown")||l.includes("csv")?"text":"artifact"}function YC(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 JC(e,t){if(!e||typeof e!="object")return null;const n=YC(e),r=eb(e),o=e!=null&&e.metadata&&typeof e.metadata=="object"?e.metadata:e!=null&&e.meta&&typeof e.meta=="object"?e.meta:{},l=n!=null&&n.descriptor&&typeof n.descriptor=="object"?n.descriptor:e!=null&&e.descriptor&&typeof e.descriptor=="object"?e.descriptor:{},u=_n(n.artifact_id,e.artifact_id,e.$artifact,e.id,r.artifact_id,r.$artifact,r.id,o.artifact_id,o.$artifact);if(!u)return null;const c={...r.tags&&typeof r.tags=="object"?r.tags:{},...o.tags&&typeof o.tags=="object"?o.tags:{},...n.tags&&typeof n.tags=="object"?n.tags:{},...e.tags&&typeof e.tags=="object"?e.tags:{}},f={};for(const[I,K]of Object.entries(c)){const U=String(I||"").trim();U&&(f[U]=String(K??""))}const m=_n(n.filename,e.filename,r.filename,o.filename,f.filename,f.name,e.name,r.name),_=_n(n.source_path,e.source_path,r.source_path,o.source_path,e.path,r.path,f.path,f.source_path,f.file_path),g=_n(n.content_type,e.content_type,e.mime_type,e.mime,r.content_type,r.mime_type,r.mime,o.content_type,f.content_type),w=_n(n.render_kind,l.render_kind,e.render_kind,f.render_kind),x=_n(n.semantic_kind,l.semantic_kind,e.semantic_kind,f.semantic_kind,f.artifact_type),j=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=n.provenance&&typeof n.provenance=="object"?n.provenance:e.provenance&&typeof e.provenance=="object"?e.provenance:l.provenance&&typeof l.provenance=="object"?l.provenance:{},C=n.generation&&typeof n.generation=="object"?n.generation:e.generation&&typeof e.generation=="object"?e.generation:l.generation&&typeof l.generation=="object"?l.generation:{},E=n.media&&typeof n.media=="object"?n.media:e.media&&typeof e.media=="object"?e.media:l.media&&typeof l.media=="object"?l.media:{},T=n.links&&typeof n.links=="object"?n.links:e.links&&typeof e.links=="object"?e.links:l.links&&typeof l.links=="object"?l.links:{};return{artifact_id:u,run_id:_n(n.run_id,e.run_id,r.run_id,o.run_id,f.run_id,N.run_id),content_type:g,modality:_n(n.modality,e.modality,l.modality,f.modality)||sw({...e,ref:r,metadata:o,tags:f}),semantic_kind:x||sw({...e,ref:r,metadata:o,tags:f}),render_kind:w||bg({content_type:g,filename:m,source_path:_,modality:_n(n.modality,e.modality,f.modality),tags:f}),task:_n(n.task,l.task,e.task,f.task,f.provider_task),classification_source:_n(n.classification_source,l.classification_source,e.classification_source),session_id:_n(n.session_id,l.session_id,e.session_id,f.session_id),workflow_id:_n(n.workflow_id,l.workflow_id,e.workflow_id,f.workflow_id,f.workflow),node_id:_n(n.node_id,l.node_id,e.node_id,f.node_id,f.node),step_id:_n(n.step_id,l.step_id,e.step_id,f.step_id),effect_id:_n(n.effect_id,l.effect_id,e.effect_id,f.effect_id,f.effect_idempotency_key),turn_id:_n(n.turn_id,l.turn_id,e.turn_id,f.turn_id,f.turn),ledger_cursor:_n(n.ledger_cursor,l.ledger_cursor,e.ledger_cursor,f.ledger_cursor,f.step_cursor),parent_run_id:_n(n.parent_run_id,l.parent_run_id,e.parent_run_id,f.parent_run_id),actor_id:_n(n.actor_id,l.actor_id,e.actor_id,f.actor_id),title:_n(n.title,e.title,f.title,f.label,f.name),created_at:_n(n.created_at,e.created_at,r.created_at,o.created_at,f.created_at),size_bytes:r2(n.size_bytes,e.size_bytes,r.size_bytes,o.size_bytes,f.size_bytes),filename:m,source_path:_,sha256:_n(n.sha256,e.sha256,r.sha256,o.sha256,f.sha256),tags:f,producer:b,provenance:N,generation:C,media:E,source_refs:Array.isArray(n.source_refs)?n.source_refs:Array.isArray(e.source_refs)?e.source_refs:[],access:j,links:T,available_actions:Array.isArray(n.available_actions)?n.available_actions.map(String):Array.isArray(e.available_actions)?e.available_actions.map(String):[],provider_trace_available:!!(n.provider_trace_available??e.provider_trace_available),audit_available:!!(n.audit_available??e.audit_available),legacy_inferred:!!((n.legacy_inferred??e.legacy_inferred)||/(?:legacy|inferred|runtime_tags|runtime_mime)/i.test(_n(n.classification_source,l.classification_source,e.classification_source))),descriptor:l,source:t,raw:e}}function Rp(e){return e.filename||e.title||(e.source_path?e.source_path.split("/").filter(Boolean).slice(-1)[0]:"")||Qt(e.artifact_id,16)}function XC(e,t){if(t==="type")return yu(e);if(t==="run")return e.run_id||"(no run)";if(t==="turn")return Lp(e);if(t==="node")return gu(e)||"(node unknown)";if(t==="workflow")return Sg(e)||"(workflow unknown)";if(t==="location"){const o=(e.source_path||e.filename||"").split("/").filter(Boolean);return o.length>1?o.slice(0,-1).join("/"):"(root)"}if(t==="source")return _f(e)||e.source||"artifact";const n=qn(e.created_at);return n===null?"(unknown time)":new Date(n).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}function Sg(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 gu(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 Lp(e){const t=(e==null?void 0:e.tags)||{},n=String((e==null?void 0:e.turn_id)||t.turn_id||t.turn||t.cycle||(e==null?void 0:e.ledger_cursor)||t.ledger_cursor||t.step_cursor||"").trim();if(n)return`turn ${n}`;const r=gu(e),o=qn(e==null?void 0:e.created_at),l=o===null?"unknown time":new Date(o).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}),u=e!=null&&e.run_id?Qt(String(e.run_id),10):"unknown run";return r?`${u} · ${r} · ${l}`:`${u} · ${l}`}function rw(e){if(!e)return"provenance unavailable";const t=[],n=Sg(e),r=gu(e),o=_f(e),l=tb(e);return n&&t.push(n),r&&t.push(r),o&&t.push(o),l&&t.push(l),t.length?t.join(" · "):"provenance unavailable"}function Yl(e){if(typeof e!="number"||!Number.isFinite(e)||e<0)return"—";const t=["B","KB","MB","GB","TB"];let n=e,r=0;for(;n>=1024&&r<t.length-1;)n/=1024,r+=1;const o=r===0?0:n>=10?1:2;return`${n.toFixed(o)} ${t[r]}`}function yu(e){const t=String((e==null?void 0:e.semantic_kind)||(e==null?void 0:e.modality)||"").trim().toLowerCase(),n=String((e==null?void 0:e.render_kind)||"").trim().toLowerCase(),r=t||n||"artifact";return{voice:"Voice",music:"Music",sound:"Sound",recording:"Recording",audio:"Unclassified audio",image:"Image",video:"Video",markdown:"Markdown",html:"HTML",json:"JSON",document:"Document",code:"Code",text:"Text",binary:"Other",artifact:"Other"}[r]||r.replace(/[_-]+/g," ").replace(/\b\w/g,l=>l.toUpperCase())}function ZC(e){return e==="html"?"HTML":e==="json"?"JSON":e==="audio"?"Unclassified audio":e==="code"?"Code":e.slice(0,1).toUpperCase()+e.slice(1)}function QC(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 eE(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 iw(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 tE(e){const t=ku(e.created_at),n=ec(e.created_at);return t==="—"?"Created —":`${t}${n&&n!=="—"?` (${n})`:""}`}function ow(e){var o;const t=e.tags||{},n=String(((o=e.access)==null?void 0:o.last_accessed_at)||t.last_accessed_at||t.accessed_at||t.updated_at||e.created_at||"").trim(),r=ku(n);return r==="—"?"—":r}function aw(e){const t=e.tags||{},n=String(e.title||t.title||t.name||t.label||e.filename||"").trim();if(n)return n;const r=String(e.source_path||t.path||"").trim();if(r)return r.split("/").filter(Boolean).slice(-1)[0]||r;const o=_f(e),l=yu(e);return o?`${l} ${o}`:`${l} artifact`}function _f(e){var n;const t=e.tags||{};return String(e.task||((n=e.provenance)==null?void 0:n.source)||t.task||t.kind||t.source||e.source||"").trim()}function tb(e){var r,o,l,u,c,f,m,_;if(!e)return"";const t=_n((r=e.producer)==null?void 0:r.provider,(o=e.producer)==null?void 0:o.provider_id,(l=e.provenance)==null?void 0:l.provider,(u=e.generation)==null?void 0:u.provider),n=_n((c=e.producer)==null?void 0:c.model,(f=e.producer)==null?void 0:f.model_id,(m=e.provenance)==null?void 0:m.model,(_=e.generation)==null?void 0:_.model);return t&&n?`${t} / ${n}`:t||n}function nE(e){var t,n,r,o;return e?_n((t=e.generation)==null?void 0:t.prompt,(n=e.generation)==null?void 0:n.input,(r=e.generation)==null?void 0:r.text,(o=e.provenance)==null?void 0:o.prompt):""}function lw(e){if(!e)return"";const t=e.media||{},n=Number(t.duration_s??t.duration_seconds??t.duration),r=Number(t.width??t.image_width??t.video_width),o=Number(t.height??t.image_height??t.video_height),l=Number(t.sample_rate??t.sample_rate_hz),u=Number(t.channels);if(Number.isFinite(n)&&n>0){const f=[`${n>=60?`${Math.floor(n/60)}m ${Math.round(n%60)}s`:`${n.toFixed(n>=10?1:2)}s`}`];return Number.isFinite(l)&&l>0&&f.push(`${Math.round(l/1e3)} kHz`),Number.isFinite(u)&&u>0&&f.push(`${u} ch`),f.join(" · ")}if(Number.isFinite(r)&&Number.isFinite(o)&&r>0&&o>0)return`${Math.round(r)} x ${Math.round(o)}`;const c=Number(t.page_count??t.pages);return Number.isFinite(c)&&c>0?`${Math.round(c)} pages`:""}function cw(e){return e.source_path||e.filename||""}function mm(e,t,n){const r=e.run_id&&t[e.run_id]||null;if(!r)return e;const o=Ui(r,n),l={...e.tags||{}};return o&&!l.workflow&&(l.workflow=o),o&&!l.workflow_id&&(l.workflow_id=o),{...e,workflow_id:e.workflow_id||o,tags:l}}function Ip(e,t,n,r=""){const o=mm(e,t,n),l=bg(o,r);return{json:"JSON",html:"HTML",markdown:"Markdown",code:"Code",voice:"Voice",music:"Music",sound:"Sound",audio:"Unclassified audio",image:"Image",video:"Video",document:"Document",text:"Text",other:"Other"}[l]||yu(o)}function ra(e){var r;const t=e,n=(r=t==null?void 0:t.result)==null?void 0:r.wait;return!n||typeof n!="object"?null:n}function Ih(e){var l,u,c;const t=e,n=t==null?void 0:t.effect;if(!n||typeof n!="object"||String(n.type||"")!=="emit_event")return null;const r=String(((l=n==null?void 0:n.payload)==null?void 0:l.name)||((u=n==null?void 0:n.payload)==null?void 0:u.event_name)||"").trim();if(!r)return null;const o=(c=n==null?void 0:n.payload)==null?void 0:c.payload;return{name:r,payload:o}}function Tf(e){const t=e,n=t==null?void 0:t.details;if(!n||typeof n!="object")return[];if(Array.isArray(n))return n.filter(o=>o&&typeof o=="object"&&typeof o.name=="string");const r=n==null?void 0:n.tool_calls;return Array.isArray(r)?r:[]}function sE(e){var o,l;const t=String((e==null?void 0:e.status)||"").trim(),n=String(((o=e==null?void 0:e.effect)==null?void 0:o.type)||"").trim(),r=(l=e==null?void 0:e.effect)!=null&&l.payload&&typeof e.effect.payload=="object"?String(e.effect.payload.name||"").trim():"";return n==="emit_event"&&r?r:n||t||"record"}function nb(e){if(!e||typeof e!="object")return"Ledger record";const t=String(e.node_id||"").trim(),n=String(e.status||"").trim(),r=sE(e),o=ra(e);if(o){const l=String(o.reason||"").trim();if(String(o.prompt||"").trim())return`${t||"node"} is waiting for a response`;if(l)return`${t||"node"} is waiting (${l})`}return e.error?`${t||"node"} failed`:n==="completed"?`${t||"node"} completed ${r}`:n==="running"?`${t||"node"} started ${r}`:n==="waiting"?`${t||"node"} is waiting`:[t,n,r].filter(Boolean).join(" · ")||"Ledger record"}function iu(e){if(typeof e=="string")return{text:e,duration:-1};if(e&&typeof e=="object"){const t=typeof e.text=="string"?String(e.text):typeof e.value=="string"?String(e.value):typeof e.message=="string"?String(e.message):cr(e,320),n=typeof e.duration=="number"?Number(e.duration):-1;return{text:t,duration:n}}return{text:cr(e,320),duration:-1}}function sb(e){var u,c,f,m,_,g,w,x,j;if(!e||typeof e!="object")return"";const t=String(((u=e==null?void 0:e.effect)==null?void 0:u.type)||"").trim(),n=e==null?void 0:e.result,r=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 N=b,C=[N.response,N.answer,N.message,N.text,N.content];for(const E of C){const T=r(E);if(T)return T}return""};if(t==="answer_user"){const b=r(n==null?void 0:n.message)||r((c=n==null?void 0:n.output)==null?void 0:c.message)||r((f=n==null?void 0:n.output)==null?void 0:f.response)||r((_=(m=e==null?void 0:e.effect)==null?void 0:m.payload)==null?void 0:_.message)||r((w=(g=e==null?void 0:e.effect)==null?void 0:g.payload)==null?void 0:w.text)||r((j=(x=e==null?void 0:e.effect)==null?void 0:x.payload)==null?void 0:j.content);if(b)return b}if(t==="llm_call"){const b=o(n)||r(n==null?void 0:n.output)||o(n==null?void 0:n.output)||r(n==null?void 0:n.response);if(b)return b}return r(n==null?void 0:n.output)||o(n==null?void 0:n.output)||o(n)||r(n==null?void 0:n.response)}function Qh(e){var o;const t=String((e==null?void 0:e.node_id)||""),n=String((e==null?void 0:e.status)||""),r=String(((o=e==null?void 0:e.effect)==null?void 0:o.type)||"");return`${t||"(node?)"} • ${n||"(status?)"} • ${r||"(effect?)"}`}function rE(e){return!!(e&&String(e.status||"")==="waiting")}function iE(e){var n,r;const t=[];for(const o of e||[]){const l=o.record;if(String(((n=l==null?void 0:l.effect)==null?void 0:n.type)||"").trim()!=="llm_call")continue;const c=(r=l==null?void 0:l.effect)!=null&&r.payload&&typeof l.effect.payload=="object"?l.effect.payload:{},f=l!=null&&l.result&&typeof l.result=="object"?l.result:{},m=(f==null?void 0:f.usage)||(f==null?void 0:f.token_usage)||{},_=typeof c.prompt=="string"?c.prompt:Array.isArray(c.messages)?cr(c.messages,1800):"",g=typeof f.content=="string"?f.content:typeof f.response=="string"?f.response:typeof l.result=="string"?String(l.result):"",w=qn(l.started_at),x=qn(l.ended_at),j=Number(m.prompt_tokens??m.input_tokens??0)||0,b=Number(m.completion_tokens??m.output_tokens??0)||0;t.push({id:`${String(o.run_id||l.run_id||"")}:${o.cursor}`,cursor:Number(o.cursor||0),ts:String(l.ended_at||l.started_at||""),run_id:String(o.run_id||l.run_id||"").trim(),node_id:String(l.node_id||"").trim(),provider:String(c.provider||f.provider||f.runtime_provider||"").trim(),model:String(c.model||f.model||f.runtime_model||"").trim(),prompt_preview:jt(_,{max_chars:1200,max_lines:10}),response_preview:jt(g,{max_chars:1200,max_lines:10}),missing_response:!String(g||"").trim(),tokens:{prompt:j,completion:b,total:Number(m.total_tokens??j+b)||0},duration_ms:w!==null&&x!==null?Math.max(0,x-w):typeof f.gen_time=="number"?Number(f.gen_time)*1e3:null,status:String(l.status||"").trim(),error:l.error?cr(l.error,500):"",raw:l})}return t.sort((o,l)=>(qn(l.ts)??0)-(qn(o.ts)??0))}function uw(e){const t=e.size||18,n=uf(e.artifact),r=bg(e.artifact,""),o=`artifact_glyph ${r==="code"?"code":n}`,l={width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:1.8,strokeLinecap:"round",strokeLinejoin:"round"};return n==="image"?s.jsx("span",{className:o,children:s.jsxs("svg",{...l,children:[s.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),s.jsx("path",{d:"M7 15l3-3 3 3 2-2 4 4"}),s.jsx("circle",{cx:"8",cy:"9",r:"1.4"})]})}):n==="audio"?s.jsx("span",{className:o,children:s.jsxs("svg",{...l,children:[s.jsx("path",{d:"M4 12h2"}),s.jsx("path",{d:"M8 8v8"}),s.jsx("path",{d:"M12 5v14"}),s.jsx("path",{d:"M16 8v8"}),s.jsx("path",{d:"M20 12h-2"})]})}):n==="video"?s.jsx("span",{className:o,children:s.jsxs("svg",{...l,children:[s.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),s.jsx("path",{d:"M9 9l6 3-6 3V9z",fill:"currentColor",stroke:"none"})]})}):r==="code"?s.jsx("span",{className:o,children:s.jsxs("svg",{...l,children:[s.jsx("path",{d:"M8 8l-4 4 4 4"}),s.jsx("path",{d:"M16 8l4 4-4 4"}),s.jsx("path",{d:"M14 4l-4 16"})]})}):n==="text"?s.jsx("span",{className:o,children:s.jsxs("svg",{...l,children:[s.jsx("path",{d:"M7 3h7l5 5v13H7z"}),s.jsx("path",{d:"M14 3v6h6"}),s.jsx("path",{d:"M10 13h7"}),s.jsx("path",{d:"M10 17h5"})]})}):s.jsx("span",{className:o,children:s.jsxs("svg",{...l,children:[s.jsx("path",{d:"M7 3h7l5 5v13H7z"}),s.jsx("path",{d:"M14 3v6h6"}),s.jsx("path",{d:"M9 14h8"})]})})}const oE=2,aE=Number.MAX_SAFE_INTEGER;function lE(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 cE(e){const t=String(e||"");if(typeof DOMParser>"u")return[{kind:"text",text:P_(t)||t}];try{const n=new DOMParser().parseFromString(t,"text/html"),r=[];n.doctype&&r.push({kind:"doctype",name:n.doctype.name||"html"});const o=l=>{if(l.nodeType===Node.TEXT_NODE){const u=String(l.textContent||"").trim();return u?{kind:"text",text:u}:null}if(l.nodeType===Node.COMMENT_NODE)return{kind:"comment",text:String(l.textContent||"")};if(l.nodeType===Node.ELEMENT_NODE){const u=l,c=Array.from(u.attributes||[]).map(m=>({name:m.name,value:m.value})),f=Array.from(u.childNodes||[]).map(o).filter(Boolean);return{kind:"element",tag:u.tagName.toLowerCase(),attrs:c,children:f}}return null};if(n.documentElement){const l=o(n.documentElement);l&&r.push(l)}return r.length?r:[{kind:"text",text:P_(t)||t}]}catch{return[{kind:"text",text:P_(t)||t}]}}function D_(e){return e.closing?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"runtime_html_punct",children:"</"}),s.jsx("span",{className:"runtime_html_tag",children:e.tag}),s.jsx("span",{className:"runtime_html_punct",children:">"})]}):s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"runtime_html_punct",children:"<"}),s.jsx("span",{className:"runtime_html_tag",children:e.tag}),e.attrs.map(t=>s.jsxs(ve.Fragment,{children:[" ",s.jsx("span",{className:"runtime_html_attr",children:t.name}),s.jsx("span",{className:"runtime_html_punct",children:"="}),s.jsxs("span",{className:"runtime_html_value",children:['"',t.value,'"']})]},`${e.tag}:${t.name}:${t.value}`)),s.jsx("span",{className:"runtime_html_punct",children:e.selfClosing?" />":">"})]})}function rb(e){const t=e.node,n=e.depth*14,r=e.depth<e.collapseAfterDepth,[o,l]=p.useState(r);if(p.useEffect(()=>{l(r)},[r,e.expansionVersion]),t.kind==="doctype")return s.jsxs("div",{className:"html-tree__line",style:{paddingLeft:n},children:[s.jsx("span",{className:"runtime_html_punct",children:"<!DOCTYPE "}),s.jsx("span",{className:"runtime_html_tag",children:t.name}),s.jsx("span",{className:"runtime_html_punct",children:">"})]});if(t.kind==="comment")return s.jsx("div",{className:"html-tree__line",style:{paddingLeft:n},children:s.jsx("span",{className:"runtime_html_comment",children:`<!-- ${t.text.trim()} -->`})});if(t.kind==="text")return s.jsx("div",{className:"html-tree__line html-tree__text",style:{paddingLeft:n},children:t.text});if(!t.children.length)return s.jsx("div",{className:"html-tree__line",style:{paddingLeft:n},children:s.jsx(D_,{tag:t.tag,attrs:t.attrs,selfClosing:!0})});const u=t.children.find(c=>c.kind==="text");return s.jsxs("details",{className:"html-tree__details",open:o,onToggle:c=>l(c.currentTarget.open),children:[s.jsxs("summary",{className:"html-tree__summary",style:{paddingLeft:n},children:[s.jsx("span",{className:"html-tree__caret","aria-hidden":"true",children:o?"▾":"▸"}),s.jsx(D_,{tag:t.tag,attrs:t.attrs}),!o&&u?s.jsxs("span",{className:"html-tree__summary_text",children:[" ",lE(u.text)]}):null]}),o?s.jsxs("div",{className:"html-tree__children",children:[t.children.map((c,f)=>s.jsx(rb,{node:c,depth:e.depth+1,collapseAfterDepth:e.collapseAfterDepth,expansionMode:e.expansionMode,expansionVersion:e.expansionVersion},`${e.depth}:${t.kind}:${t.tag}:${f}`)),s.jsx("div",{className:"html-tree__line",style:{paddingLeft:n},children:s.jsx(D_,{tag:t.tag,attrs:[],closing:!0})})]}):null]})}function uE(e){const t=p.useMemo(()=>cE(e.text),[e.text]),[n,r]=p.useState({mode:"folded",version:0}),o=n.mode==="unfolded"?aE:oE;p.useEffect(()=>{r(u=>({mode:"folded",version:u.version+1}))},[e.text]);const l=()=>{r(u=>({mode:u.mode==="unfolded"?"folded":"unfolded",version:u.version+1}))};return s.jsxs("div",{className:`${e.className} structured html_source_preview`,children:[s.jsx("div",{className:"html-tree__toolbar",children:s.jsx("button",{type:"button",className:"btn html-tree__toggle",onClick:l,"aria-expanded":n.mode==="unfolded",children:n.mode==="unfolded"?"Fold all":"Unfold all"})}),s.jsx("div",{className:"html-tree__tree",role:"tree","aria-label":"HTML source tree",children:t.map((u,c)=>s.jsx(rb,{node:u,depth:0,collapseAfterDepth:o,expansionMode:n.mode,expansionVersion:n.version},`root:${c}`))})]})}function dE(e){var r;const t=OC(e.text);if(!t)return s.jsx("div",{className:`${e.className} structured markdown_preview`,children:s.jsx(qi,{text:e.text})});const n=((r=t.metadata.find(o=>o.label.toLowerCase()==="title"))==null?void 0:r.value)||"";return s.jsxs("div",{className:`${e.className} structured markdown_preview artifact_markdown_report`,children:[n?s.jsx("h1",{className:"artifact_markdown_title",children:n}):null,t.metadata.length?s.jsx("dl",{className:"artifact_markdown_meta",children:t.metadata.map(o=>{const l=/^https?:\/\//i.test(o.value);return s.jsxs("div",{children:[s.jsx("dt",{children:o.label}),s.jsx("dd",{children:l?s.jsx("a",{href:o.value,target:"_blank",rel:"noreferrer",children:o.value}):o.value})]},`${o.label}:${o.value}`)})}):null,s.jsx(qi,{text:t.body||e.text})]})}function ib(e){const t=String(e.text||""),n=fm(e.artifact,t);if(n==="json"){const r=$m(t);if(r!==null)return s.jsx("div",{className:`${e.className} structured`,children:s.jsx(Is,{value:r,collapseAfterDepth:4,showCopy:!1})})}return n==="markdown"?s.jsx(dE,{text:t,className:e.className}):n==="html"?s.jsx(uE,{text:t,className:e.className}):s.jsx("pre",{className:`mono ${e.className}`,children:t})}function fE(e){const t=e.preview,n=e.artifact;return n?t.loading?s.jsx("div",{className:"runtime_inline_preview empty",children:"Loading preview…"}):t.error?s.jsx("div",{className:"runtime_inline_preview empty danger",children:t.error}):t.kind==="image"&&t.url?s.jsx("img",{className:"runtime_inline_preview media",src:t.url,alt:Rp(n)}):t.kind==="audio"&&t.url?s.jsx("audio",{className:"runtime_inline_preview audio",src:t.url,controls:!0}):t.kind==="video"&&t.url?s.jsx("video",{className:"runtime_inline_preview media",src:t.url,controls:!0}):s.jsx(ib,{artifact:n,text:t.text||"Preview unavailable. Use Preview or Download.",className:"runtime_inline_preview text"}):s.jsx("div",{className:"runtime_inline_preview empty",children:"Select an artifact to preview it here."})}function Ng(e){const t=e==null?void 0:e.waiting;return t&&typeof t=="object"?t:null}function ob(e){const t=Ng(e);return String((t==null?void 0:t.reason)||(e==null?void 0:e.waiting_reason)||"").trim().toLowerCase()}function dw(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 hE(e){const t=e.map(n=>String((n==null?void 0:n.name)||"tool").trim()).filter(Boolean);return t.length?`${t.slice(0,3).join(", ")}${t.length>3?` +${t.length-3}`:""}`:""}function Au(e){const t=String((e==null?void 0:e.status)||"").trim().toLowerCase();if(So(t)||t!=="waiting")return"none";const n=Ng(e),r=ob(e);return Tf(n).length?"tool_approval":r==="until"||String((e==null?void 0:e.role)||"").trim()==="controller"?"scheduled":r==="subworkflow"?"subworkflow":r==="event"?dw(n)?"user_response":"external_event":r==="user"||dw(n)?"user_response":"unknown_wait"}function ab(e){const t=Ng(e),n=Tf(t),r=Au(e);return r==="tool_approval"?`Tool approval: ${hE(n)||"tool call"}`:r==="user_response"?Array.isArray(t==null?void 0:t.choices)&&t.choices.length>0?"Choice required":"User response needed":r==="scheduled"?String((e==null?void 0:e.role)||"").trim()==="controller"?"Automation waiting for its next run":"Scheduled wait":r==="subworkflow"?"Waiting for subworkflow":r==="external_event"?"Waiting for external event":r==="unknown_wait"?"Waiting, context unclear":""}function mE(e){const t=Au(e);if(t==="tool_approval")return"Review the tool request, then approve, reject, or cancel the whole run.";if(t==="user_response")return"Answer the workflow request. Submit resumes only this wait.";if(t==="scheduled")return"No response is needed. The run resumes when the scheduled time arrives or it is manually resumed.";if(t==="subworkflow")return"No direct response is needed. Inspect the child workflow or cancel the parent run.";if(t==="external_event")return"No direct response is available here. Inspect the ledger or the event source.";if(t==="unknown_wait")return"No clear prompt was provided. Review the input and recent ledger before taking action.";const n=String((e==null?void 0:e.status)||"").trim().toLowerCase();return n==="failed"?"Open the ledger, artifacts, or logs to inspect the failure.":n==="running"?"Watch the ledger/provider traces or cancel the workflow if it should stop.":So(n)?"Open the ledger and artifacts for the final outcome.":"Open the run to inspect current activity."}function fw(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 _E(e,t={}){const n=t.now_ms??Date.now(),r=t.workflow_label??"",o=String(e.status||"unknown").trim().toLowerCase()||"unknown",l=Au(e),u=So(o),c=wg(e,n),f=qn(e.updated_at||e.created_at)??0,m=o==="running"&&c>=14400*1e3,_=ab(e)||fw(e)||(e.current_node?`Current node: ${e.current_node}`:o==="running"?"Running":u?"Terminal":"No current activity reported");let g="all";l==="tool_approval"?g="tool_approval":l==="user_response"?g="user_wait":l==="scheduled"?g="scheduled":l==="subworkflow"||l==="external_event"?g="subflows":o==="failed"?g="failed":o==="running"?g="running":u&&(g="finished");const w=l==="tool_approval"?0:l==="user_response"?1:l==="unknown_wait"?2:o==="failed"?3:m?4:o==="running"?5:l!=="none"?6:u?8:7,x=l==="tool_approval"||l==="user_response",j=l==="tool_approval"?"Open approval":l==="user_response"?"Open wait":"Open Observe",b=[e.run_id,e.workflow_id,r,e.session_id,e.parent_run_id,e.status,e.current_node,ob(e),_,fw(e)].join(" ").toLowerCase();return{run:e,run_id:String(e.run_id||"").trim(),status:o,wait_kind:l,queue:g,attention_rank:w,reason:_,expected_action:mE(e),action_label:j,search_text:b,is_terminal:u,needs_user_action:x,is_stale:m,duration_ms:c,updated_ms:f}}function pE(e,t={}){const n=t.now_ms??Date.now(),r=t.workflow_label_by_id??{};return e.map(o=>_E(o,{now_ms:n,workflow_label:r[String(o.workflow_id||"")]||String(o.workflow_id||"")}))}function gE(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 yE(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 wE(e,t){const n=[...e];return n.sort((r,o)=>{if(t==="recent")return o.updated_ms-r.updated_ms;if(t==="oldest")return r.updated_ms-o.updated_ms;if(t==="duration")return o.duration_ms-r.duration_ms;if(t==="tokens")return(Number(o.run.tokens_total||0)||0)-(Number(r.run.tokens_total||0)||0);if(t==="workflow")return String(r.run.workflow_id||"").localeCompare(String(o.run.workflow_id||""));const l=r.attention_rank-o.attention_rank;return l!==0?l:o.updated_ms-r.updated_ms}),n}function vE(e){const[t,n]=p.useState("attention"),[r,o]=hf("system_queues"),[l,u]=hf("system_runs"),[c,f]=p.useState(""),[m,_]=p.useState("attention"),[g,w]=p.useState(""),x=p.useMemo(()=>{const A={};for(const ee of e.artifacts){const P=String(ee.run_id||"").trim();P&&(A[P]=(A[P]||0)+1)}return A},[e.artifacts]),j=p.useMemo(()=>pE(e.runs,{workflow_label_by_id:e.workflow_label_by_id}),[e.runs,e.workflow_label_by_id]),b=p.useMemo(()=>gE(j),[j]),N=p.useMemo(()=>{const A=yE(j,{queue:t,query:c});return wE(A,m)},[j,t,c,m]),C=N.find(A=>String(A.run_id||"")===g)||N.find(A=>String(A.run_id||"")===e.selected_run_id)||N[0]||null,E=(C==null?void 0:C.run)||null,T=String((E==null?void 0:E.run_id)||"").trim(),I=String((E==null?void 0:E.session_id)||"").trim(),K=p.useMemo(()=>I?new Set(e.runs.filter(A=>String(A.session_id||"").trim()===I).map(A=>String(A.run_id||"").trim()).filter(Boolean)):new Set,[e.runs,I]),U=I?K.size:0,J=p.useMemo(()=>I?e.artifacts.filter(A=>String(A.session_id||"").trim()===I||K.has(String(A.run_id||"").trim())).length:0,[e.artifacts,I,K]),Y=E!=null&&E.waiting&&typeof E.waiting=="object"?E.waiting:null,re=Y?Tf(Y):[],ce=(C==null?void 0:C.reason)||(Y?jg(Y,re):""),fe=(C==null?void 0:C.expected_action)||(Y?Zx(Y,re):""),W=Y?HC(Y,null):"",O=T&&x[T]||0,$=So(E==null?void 0:E.status),z=[{key:"attention",label:"Needs attention",count:b.attention},{key:"user_wait",label:"Needs my response",count:b.user_wait},{key:"tool_approval",label:"Tool approvals",count:b.tool_approval},{key:"running",label:"Running",count:b.running},{key:"failed",label:"Failed",count:b.failed},{key:"scheduled",label:"Scheduled",count:b.scheduled},{key:"subflows",label:"Subflows / external events",count:b.subflows},{key:"finished",label:"Finished",count:b.finished},{key:"all",label:"All loaded",count:b.all}];return s.jsxs("div",{className:`runtime_ops_layout${r?"":" queues_collapsed"}${l?"":" runs_collapsed"}`,children:[s.jsxs("aside",{className:`pane runtime_ops_filters${r?"":" list_collapsed"}`,children:[s.jsxs("div",{className:"pane_header runtime_ops_filter_header",children:[s.jsx(mf,{open:r,on_toggle:o,controls:"runtime_ops_queues",title:"Queues"}),s.jsx("div",{className:"pane_spacer"}),s.jsxs("button",{className:"btn btn_icon",onClick:e.gateway_connected?e.on_refresh_runs:e.on_reconnect,children:[s.jsx(et,{name:"refresh",size:14}),e.gateway_connected?"Refresh":"Reconnect"]})]}),s.jsxs("div",{className:"pane_body scroll runtime_ops_queue_list",id:"runtime_ops_queues",hidden:!r,children:[z.map(A=>s.jsxs("button",{className:`runtime_ops_filter ${t===A.key?"selected":""}`,"aria-pressed":t===A.key,onClick:()=>n(A.key),children:[s.jsx("span",{children:A.label}),s.jsx("strong",{children:A.count.toLocaleString()})]},A.key)),s.jsx("div",{className:"runtime_ops_hint",children:"Counts are for the loaded runtime page. Refine search or refresh when supervising large runtimes."})]})]}),s.jsxs("section",{className:`pane runtime_ops_table_panel${l?"":" list_collapsed"}`,children:[s.jsxs("div",{className:"pane_header runtime_ops_list_header",children:[s.jsx(mf,{open:l,on_toggle:u,controls:"runtime_ops_runs",title:"Runs",count:N.length.toLocaleString()}),s.jsx("div",{className:"pane_spacer"}),s.jsx("input",{value:c,onChange:A=>f(A.target.value),placeholder:"Search workflow, run, node, status, error"}),s.jsxs("select",{className:"seg_select",value:m,onChange:A=>_(A.target.value),children:[s.jsx("option",{value:"attention",children:"Attention order"}),s.jsx("option",{value:"recent",children:"Latest event"}),s.jsx("option",{value:"oldest",children:"Oldest event"}),s.jsx("option",{value:"duration",children:"Longest duration"}),s.jsx("option",{value:"tokens",children:"Most tokens"}),s.jsx("option",{value:"workflow",children:"Workflow"})]})]}),s.jsxs("div",{className:"pane_body scroll runtime_ops_rows",id:"runtime_ops_runs",hidden:!l,children:[N.length?null:s.jsx("div",{className:"runtime_ops_empty",children:e.gateway_connected?"No runs match this queue.":"Gateway offline. Runtime activity cannot be loaded until the connection is restored."}),N.map(A=>{const ee=A.run,P=String(ee.run_id||"").trim(),F=x[P]||0;return s.jsxs("div",{className:`raised runtime_ops_row ${P===T?"selected":""}`,"aria-current":P===T?"true":void 0,tabIndex:0,onClick:()=>{w(P),e.on_select_run(P)},onKeyDown:G=>{(G.key==="Enter"||G.key===" ")&&(G.preventDefault(),w(P),e.on_select_run(P))},children:[s.jsxs("div",{className:"runtime_ops_row_top",children:[s.jsx("strong",{className:"runtime_ops_row_name",children:Ui(ee,e.workflow_label_by_id)}),A.is_stale?s.jsx("span",{className:"chip warn",children:"stale"}):null,s.jsx(lc,{status:ee.status})]}),s.jsxs("div",{className:"runtime_ops_row_sub",children:[s.jsx("span",{className:"mono",children:Qt(P,18)}),s.jsx("span",{children:ec(ee.updated_at||ee.created_at)}),s.jsx("span",{children:oc(ee)}),s.jsx("span",{className:"runtime_ops_row_reason",title:A.reason,children:A.reason})]}),s.jsxs("div",{className:"runtime_ops_row_foot",children:[s.jsxs("span",{className:"runtime_ops_row_facts",children:[s.jsxs("span",{children:[Number(ee.llm_calls||0).toLocaleString()," llm"]}),s.jsxs("span",{children:[Number(ee.tool_calls||0).toLocaleString()," tools"]}),s.jsxs("span",{children:[Number(ee.tokens_total||0).toLocaleString()," tok"]}),s.jsxs("span",{children:[F.toLocaleString()," artifacts"]})]}),s.jsxs("div",{className:"runtime_ops_actions",children:[A.needs_user_action?s.jsx("button",{className:"btn primary",onClick:G=>{G.stopPropagation(),e.on_open_run(P)},children:A.action_label}):s.jsx("button",{className:"btn",onClick:G=>{G.stopPropagation(),e.on_open_run(P)},children:"Open"}),s.jsx("button",{className:"btn",onClick:G=>{G.stopPropagation(),e.on_open_ledger(P)},children:"Ledger"}),s.jsx("button",{className:"btn",onClick:G=>{G.stopPropagation(),e.on_select_run(P),e.on_open_logs()},children:"Logs"}),s.jsx("button",{className:"btn",onClick:G=>{G.stopPropagation(),e.on_filter_artifacts(P)},children:"Artifacts"})]})]})]},P)})]})]}),s.jsxs("aside",{className:"pane runtime_ops_inspector",children:[s.jsxs("div",{className:"pane_header",children:[s.jsx("span",{className:"pane_title",children:"Run inspector"}),E?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"pane_spacer"}),s.jsx(lc,{status:E.status})]}):null]}),s.jsx("div",{className:"pane_body scroll runtime_ops_inspector_body",children:E?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"runtime_ops_inspector_head",children:[s.jsx("h3",{children:Ui(E,e.workflow_label_by_id)}),s.jsx("span",{className:"mono",children:Qt(T,28)})]}),s.jsxs("div",{className:"runtime_ops_decision",children:[s.jsx("strong",{children:(C==null?void 0:C.reason)||KC(E)}),s.jsx("span",{children:(C==null?void 0:C.expected_action)||(String(E.status||"").toLowerCase()==="waiting"?"This run is paused until the pending wait is resolved or the run is cancelled.":$?"This run is terminal. Open the ledger for the narrative and final error/output.":"This run is active or recently updated. Use ledger/provider logs to inspect live work.")})]}),s.jsxs("div",{className:"artifact_detail_grid",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Started"}),s.jsx("strong",{children:ku(hu(E))})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Elapsed"}),s.jsx("strong",{children:oc(E)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Last event"}),s.jsx("strong",{children:ku(E.updated_at||E.created_at)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Session"}),s.jsx("strong",{className:"mono",children:E.session_id?Qt(String(E.session_id),18):"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Node"}),s.jsx("strong",{className:"mono",children:E.current_node||"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Visible artifacts"}),s.jsx("strong",{children:O.toLocaleString()})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Provider calls"}),s.jsx("strong",{children:Number(E.llm_calls||0).toLocaleString()})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Tokens"}),s.jsx("strong",{children:Number(E.tokens_total||0).toLocaleString()})]})]}),I?s.jsxs("section",{className:"runtime_ops_session_context",children:[s.jsxs("div",{children:[s.jsx("span",{className:"run_hero_eyebrow",children:"Session context"}),s.jsx("strong",{className:"mono",children:Qt(I,30)})]}),s.jsxs("div",{className:"runtime_ops_session_facts",children:[s.jsxs("span",{children:[U.toLocaleString()," loaded run",U===1?"":"s"]}),s.jsxs("span",{children:[J.toLocaleString()," visible artifact",J===1?"":"s"]})]}),s.jsxs("div",{className:"runtime_detail_actions compact",children:[s.jsx("button",{className:"btn",onClick:()=>e.on_filter_session_artifacts(I),children:"Open session artifacts"}),s.jsx("button",{className:"btn",onClick:()=>void ic(I),children:"Copy session id"})]})]}):null,Y?s.jsxs("div",{className:"runtime_ops_wait_summary",children:[s.jsxs("div",{className:"runtime_ops_wait_header",children:[s.jsx("span",{className:"run_hero_eyebrow",children:"Blocked on"}),s.jsx("strong",{children:ce})]}),s.jsx("p",{children:fe}),W?s.jsxs("div",{className:"runtime_ops_wait_request",children:[s.jsx("span",{children:"Request"}),s.jsx(qi,{text:W})]}):s.jsx("div",{className:"runtime_ops_wait_request muted",children:"No explicit prompt is attached to this wait. Open Observe or the ledger for full run context before responding."}),re.length?s.jsx("div",{className:"runtime_ops_wait_tools",children:re.map((A,ee)=>s.jsxs(ve.Fragment,{children:[s.jsx("span",{className:"chip mono warn",children:String((A==null?void 0:A.name)||"tool")}),Xx(A).map(P=>s.jsxs("span",{className:"chip muted",title:Jx,children:[P,"~"]},`${ee}:${P}`))]},`${String((A==null?void 0:A.name)||"tool")}:${ee}`))}):null,s.jsxs("details",{className:"runtime_raw_details",children:[s.jsx("summary",{className:"muted",children:"Raw wait payload"}),s.jsx(Is,{value:Y,collapseAfterDepth:3,showCopy:!0})]})]}):null,hm(E)?s.jsx("div",{className:"warn_callout",children:hm(E)}):null,s.jsxs("div",{className:"runtime_detail_actions",children:[s.jsx("button",{className:"btn primary",onClick:()=>e.on_open_run(T),children:"Open Observe"}),s.jsx("button",{className:"btn",onClick:()=>e.on_open_ledger(T),children:"Open ledger"}),s.jsx("button",{className:"btn",onClick:()=>e.on_filter_artifacts(T),children:"Open artifacts"}),s.jsx("button",{className:"btn",onClick:e.on_open_logs,children:"Open logs"}),s.jsx("button",{className:"btn",onClick:()=>void ic(T),children:"Copy run id"})]})]}):s.jsx("div",{className:"empty_state_inline",children:"Select a run to inspect why it is active or blocked."})})]})]})}function xE(e){const t=e.selected_artifact,n=["voice","music","sound","recording","audio","image","video","markdown","html","json","document","code","text","other"],r=[{value:"all",label:"Any time"},{value:"hour",label:"Last hour"},{value:"today",label:"Today"},{value:"week",label:"7 days"},{value:"month",label:"30 days"}],o=p.useMemo(()=>new Set(e.type_filters),[e.type_filters]),l=Math.max(0,Number(e.artifact_total_count||0)),u=!!e.query.trim()||e.type_filters.length>0||e.date_filter!=="all"||e.scope!=="all"||!!e.artifact_run_filter.trim(),c=Math.max(1,Number(e.artifact_page_size||500)),f=Math.max(1,Math.ceil(l/c)),m=Math.min(Math.max(0,Number(e.artifact_page||0)),f-1),_=l?m*c+1:0,g=Math.min(l,m*c+e.artifacts.length),w=p.useMemo(()=>{const O={},$=e.artifact_type_facets&&Object.keys(e.artifact_type_facets).length?e.artifact_type_facets:e.artifact_facets,z=($==null?void 0:$.semantic_kind)||{},A=($==null?void 0:$.render_kind)||{};for(const ee of n)O[ee]=Number(z[ee]||A[ee]||0);return O.audio=Number(z.audio||0),O.other=Number(z.other||0)+Number(z.artifact||0)+Number(z.binary||0)+Number(z["(none)"]||0),O},[e.artifact_facets,e.artifact_type_facets]),x=O=>{const $=new Set(o);$.has(O)?$.delete(O):$.add(O),e.on_type_filters_change(Array.from($.values()))},j=p.useMemo(()=>{const O={waiting:[],running:[],failed:[],cancelled:[],completed:[],other:[]};for(const $ of e.runs){const z=String($.status||"").trim().toLowerCase();z==="waiting"?O.waiting.push($):z==="running"?O.running.push($):z==="failed"?O.failed.push($):z==="cancelled"?O.cancelled.push($):z==="completed"?O.completed.push($):O.other.push($)}return O},[e.runs]),b=t!=null&&t.run_id&&e.run_by_id[t.run_id]||null,N=e.artifact_run_filter?Ui(e.run_by_id[e.artifact_run_filter],e.workflow_label_by_id):"",C=p.useMemo(()=>{var z;const O=new Set,$=((z=e.artifact_facets)==null?void 0:z.run_id)||{};for(const A of Object.keys($))A&&A!=="(none)"&&O.add(A);for(const A of e.artifacts)A.run_id&&O.add(A.run_id);for(const A of e.active_runs)A.run_id&&O.add(String(A.run_id));return Array.from(O).map(A=>e.run_by_id[A]||{run_id:A,workflow_id:null,status:"",created_at:null,updated_at:null}).sort((A,ee)=>{const P=ju(A.status)?0:1,F=ju(ee.status)?0:1;if(P!==F)return P-F;const G=qn(A.updated_at||A.created_at)??0;return(qn(ee.updated_at||ee.created_at)??0)-G}).slice(0,160)},[e.artifacts,e.active_runs,e.run_by_id,e.artifact_facets]),E=O=>{e.on_artifact_run_filter_change(O),e.on_session_filter_change(""),e.on_scope_change(O?"run":"all")},T=O=>e.gateway_connected?Math.max(0,Number(O||0)).toLocaleString():"—",I=e.selected_run_id&&e.run_by_id[e.selected_run_id]||null,K=p.useMemo(()=>{const O=e.runtime_log_query.trim().toLowerCase(),$=e.runtime_ledger_log_items||[];return O?$.filter(z=>{var P,F;const A=z.record||{};return[z.cursor,A.run_id,A.node_id,A.status,(P=A.effect)==null?void 0:P.type,A.started_at,A.ended_at,cr(((F=A.effect)==null?void 0:F.payload)??{},900),cr(A.result??{},900)].join(" ").toLowerCase().includes(O)}):$},[e.runtime_ledger_log_items,e.runtime_log_query]),U=p.useMemo(()=>{const O=e.runtime_log_query.trim().toLowerCase(),$=iE(e.runtime_ledger_log_items);return O?$.filter(z=>[z.provider,z.model,z.run_id,z.node_id,z.status,z.error,z.prompt_preview,z.response_preview,z.tokens.prompt,z.tokens.completion,z.tokens.total].join(" ").toLowerCase().includes(O)):$},[e.runtime_ledger_log_items,e.runtime_log_query]),J=U.reduce((O,$)=>O+(Number($.tokens.total)||0),0),Y=U.filter(O=>O.missing_response||O.error).length,re=p.useMemo(()=>{const O=e.runtime_log_query.trim().toLowerCase(),$=String(e.audit_log_text||"").replace(/\r\n/g,`
109
- `).replace(/\r/g,`
110
- `).split(`
111
- `).filter(Boolean);return O?$.filter(z=>z.toLowerCase().includes(O)):$},[e.audit_log_text,e.runtime_log_query]),ce=e.runtime_log_source==="run_ledger"||e.runtime_log_source==="provider_calls",fe=e.runtime_log_source==="run_ledger"?"Selected Run Ledger":e.runtime_log_source==="provider_calls"?"Provider Calls":"Gateway HTTP Audit",W=e.runtime_log_source==="run_ledger"?"Runtime execution records for the selected workflow run.":e.runtime_log_source==="provider_calls"?"Model/provider call records extracted from the selected run ledger.":"Global Gateway HTTP/audit tail. This is system activity, not artifact provenance.";return s.jsxs("div",{className:"page runtime_page",children:[s.jsxs("section",{className:"runtime_header",children:[s.jsxs("div",{children:[s.jsx("div",{className:"run_hero_eyebrow",children:"System"}),s.jsx("h2",{children:e.tab==="activity"?"Activity monitor":e.tab==="artifacts"?"Artifact explorer":e.tab==="memory"?"Active memory":"Logs"}),s.jsxs("div",{className:"run_hero_meta",children:[s.jsx("span",{className:`status_pill ${e.gateway_connected?"ok":"warn"}`,children:e.gateway_connected?"gateway connected":"gateway offline"}),e.tab==="artifacts"&&e.artifact_run_filter?s.jsxs("span",{className:"chip muted",children:["filtered run ",s.jsx("span",{className:"mono",children:Qt(e.artifact_run_filter,18)})]}):null,e.session_id?s.jsxs("span",{className:"chip muted",children:["session ",s.jsx("span",{className:"mono",children:Qt(e.session_id,18)})]}):null]})]}),s.jsxs("div",{className:"metric_grid compact runtime_header_metrics",children:[s.jsxs("div",{className:"metric_tile",children:[s.jsx("span",{children:"Waiting"}),s.jsx("strong",{children:T(j.waiting.length)})]}),s.jsxs("div",{className:"metric_tile",children:[s.jsx("span",{children:"Running"}),s.jsx("strong",{children:T(j.running.length)})]}),s.jsxs("div",{className:"metric_tile",children:[s.jsx("span",{children:"Failed"}),s.jsx("strong",{children:T(j.failed.length)})]}),s.jsxs("div",{className:"metric_tile",children:[s.jsxs("span",{children:["Artifacts",u?" (filtered)":""]}),s.jsx("strong",{children:T(l)})]})]})]}),s.jsx("nav",{className:"runtime_mode_tabs",role:"tablist","aria-label":"System sections",children:["activity","artifacts","memory","logs"].map(O=>s.jsxs("button",{role:"tab","aria-selected":e.tab===O,className:`runtime_mode_tab ${e.tab===O?"active":""}`,onClick:()=>e.on_tab_change(O),children:[s.jsx(et,{name:O==="activity"?"history":O==="artifacts"?"download":O==="memory"?"agent":"terminal",size:14}),s.jsx("span",{children:O==="activity"?"Activity":O==="artifacts"?"Artifacts":O==="memory"?"Memory":"Logs"})]},O))}),e.gateway_connected?null:s.jsxs("div",{className:"runtime_offline_banner",role:"status",children:[s.jsxs("div",{children:[s.jsx("strong",{children:"Gateway offline"}),s.jsx("span",{children:"Activity, artifacts, memory, and logs are unavailable until the gateway reconnects."})]}),s.jsxs("div",{children:[s.jsx("button",{className:"btn primary",onClick:e.on_reconnect,children:"Reconnect"}),s.jsx("button",{className:"btn",onClick:e.on_open_settings,children:"Settings"})]})]}),e.error?s.jsx("div",{className:"warn_callout",children:e.error}):null,e.tab==="activity"?s.jsx(vE,{gateway_connected:e.gateway_connected,runs:e.runs,artifacts:e.artifacts,selected_run_id:e.selected_run_id,workflow_label_by_id:e.workflow_label_by_id,on_select_run:e.on_select_run,on_open_run:e.on_open_run,on_open_ledger:e.on_open_ledger,on_refresh_runs:e.on_refresh_runs,on_reconnect:e.on_reconnect,on_open_logs:()=>e.on_tab_change("logs"),on_filter_artifacts:O=>{E(O),e.on_select_run(O),e.on_tab_change("artifacts")},on_filter_session_artifacts:O=>{O&&(e.on_artifact_run_filter_change(""),e.on_session_filter_change(O),e.on_scope_change("session"),e.on_tab_change("artifacts"))}}):null,e.tab==="memory"?e.memory_panel?s.jsx("div",{className:"runtime_memory_panel",children:e.memory_panel}):s.jsx("div",{className:"empty_state_inline",children:"The memory explorer needs a gateway connection — sign in to browse knowledge-graph assertions."}):null,e.tab==="artifacts"?s.jsxs(s.Fragment,{children:[s.jsxs("section",{className:"pane runtime_artifact_toolbar","aria-label":"Find artifacts",children:[s.jsxs("div",{className:"runtime_artifact_toolbar_top",children:[s.jsxs("label",{className:"artifact_filter_field artifact_filter_search",children:[s.jsx("span",{children:"Search"}),s.jsx("input",{value:e.query,onChange:O=>e.on_query_change(O.target.value),placeholder:"title, path, hash, run, workflow, tag"})]}),s.jsxs("label",{className:"artifact_filter_field",children:[s.jsx("span",{children:"Scope"}),s.jsxs("select",{className:"seg_select",value:e.scope,onChange:O=>{const $=O.target.value;$!=="run"&&e.on_artifact_run_filter_change(""),$==="session"?e.on_session_filter_change(e.session_id):e.on_session_filter_change(""),e.on_scope_change($)},children:[s.jsx("option",{value:"all",children:"All runtime"}),s.jsx("option",{value:"session",children:"This session"}),s.jsx("option",{value:"run",children:"Selected run"})]})]}),s.jsxs("label",{className:"artifact_filter_field",children:[s.jsx("span",{children:"Group"}),s.jsxs("select",{className:"seg_select",value:e.group_by,onChange:O=>e.on_group_by_change(O.target.value),children:[s.jsx("option",{value:"type",children:"Type"}),s.jsx("option",{value:"time",children:"Date"}),s.jsx("option",{value:"turn",children:"Turn"}),s.jsx("option",{value:"node",children:"Node"}),s.jsx("option",{value:"workflow",children:"Workflow"}),s.jsx("option",{value:"run",children:"Run"}),s.jsx("option",{value:"location",children:"Location"}),s.jsx("option",{value:"source",children:"Source"})]})]}),s.jsxs("label",{className:"artifact_filter_field",children:[s.jsx("span",{children:"Sort"}),s.jsxs("select",{className:"seg_select",value:e.sort_by,onChange:O=>e.on_sort_by_change(O.target.value),children:[s.jsx("option",{value:"newest",children:"Newest"}),s.jsx("option",{value:"oldest",children:"Oldest"}),s.jsx("option",{value:"last_access",children:"Last accessed"}),s.jsx("option",{value:"turn",children:"Turn order"}),s.jsx("option",{value:"type",children:"Type"}),s.jsx("option",{value:"size_desc",children:"Largest"}),s.jsx("option",{value:"size_asc",children:"Smallest"})]})]}),s.jsxs("button",{className:"btn btn_icon",onClick:e.on_refresh_artifacts,disabled:!e.gateway_connected||e.loading,children:[s.jsx(et,{name:"refresh",size:14}),e.loading?"Loading…":"Refresh"]})]}),s.jsxs("div",{className:"artifact_filter_section",children:[s.jsxs("div",{className:"artifact_filter_label",children:["Type ",s.jsx("span",{className:"muted",children:"OR"})]}),s.jsxs("div",{className:"artifact_filter_chips",role:"group","aria-label":"Artifact type filters combine with OR",children:[n.map(O=>{const $=o.has(O),z=w[O]||0,A=ZC(O);return s.jsxs("button",{type:"button","aria-pressed":$,"aria-label":`${A} artifact type filter. Type filters combine with OR.`,title:`${A}: ${$?"in the filter":"not in the filter"}. Type filters combine with OR.`,className:`artifact_filter_chip ${$?"active":""}`,onClick:()=>x(O),children:[s.jsx("span",{children:A}),s.jsx("span",{className:"artifact_chip_count",children:e.gateway_connected?z.toLocaleString():"—"})]},O)}),e.type_filters.length?s.jsx("button",{type:"button",className:"artifact_filter_chip clear",onClick:()=>e.on_type_filters_change([]),children:"Clear types"}):null]})]}),s.jsxs("div",{className:"artifact_filter_section",children:[s.jsx("div",{className:"artifact_filter_label",children:"Date"}),s.jsx("div",{className:"artifact_filter_chips",role:"group","aria-label":"Artifact date filters",children:r.map(O=>s.jsx("button",{type:"button","aria-pressed":e.date_filter===O.value,className:`artifact_filter_chip ${e.date_filter===O.value?"active":""}`,onClick:()=>e.on_date_filter_change(O.value),children:O.label},O.value))})]})]}),s.jsx("div",{className:"artifact_scope_banner",children:e.artifact_run_filter?s.jsxs(s.Fragment,{children:["Showing artifacts for ",s.jsx("strong",{children:N||Qt(e.artifact_run_filter,18)}),".",s.jsx("button",{className:"btn",onClick:()=>E(""),children:"Show all"})]}):s.jsxs(s.Fragment,{children:["Showing artifacts across the selected runtime scope. Select a run to filter the inventory. ",e.artifact_total_bytes?s.jsxs("span",{className:"mono muted",children:["Total size ",Yl(e.artifact_total_bytes)]}):null]})}),s.jsxs("div",{className:"runtime_artifacts_layout",children:[s.jsxs("aside",{className:"pane artifact_filter_rail",children:[s.jsxs("div",{className:"pane_header",children:[s.jsx("span",{className:"pane_title",children:"Runs"}),s.jsx("span",{className:"pane_count",children:C.length.toLocaleString()})]}),s.jsxs("div",{className:"pane_body scroll artifact_filter_rail_list",children:[s.jsxs("button",{className:`artifact_filter_run ${e.artifact_run_filter?"":"selected"}`,onClick:()=>E(""),children:[s.jsx("strong",{children:"All artifacts"}),s.jsx("span",{children:e.gateway_connected?`${l.toLocaleString()} match${l===1?"":"es"}`:"counts unavailable"})]}),C.map(O=>{const $=String(O.run_id||"").trim(),z=$===e.artifact_run_filter||$===(t==null?void 0:t.run_id);return s.jsxs("button",{className:`artifact_filter_run ${z?"selected":""}`,onClick:()=>E($),title:$,children:[s.jsx("strong",{children:Ui(O,e.workflow_label_by_id)}),s.jsx("span",{className:"mono",children:Qt($,15)}),s.jsx("span",{children:oc(O)})]},$)})]})]}),s.jsxs("section",{className:"pane runtime_artifact_browser",children:[s.jsxs("div",{className:"pane_header artifact_browser_header",children:[s.jsx("span",{className:"pane_title",children:"Artifacts"}),s.jsx("span",{className:"pane_count",children:l?`${_.toLocaleString()}-${g.toLocaleString()} of ${l.toLocaleString()}`:"0 items"}),s.jsx("div",{className:"pane_spacer"}),f>1?s.jsxs("div",{className:"artifact_pagination","aria-label":"Artifact pages",children:[s.jsx("button",{className:"btn",onClick:()=>e.on_artifact_page_change(0),disabled:m<=0,children:"First"}),s.jsx("button",{className:"btn",onClick:()=>e.on_artifact_page_change(m-1),disabled:m<=0,children:"Prev"}),s.jsxs("span",{className:"muted artifact_page_label",children:["Page ",(m+1).toLocaleString()," / ",f.toLocaleString()]}),s.jsx("button",{className:"btn",onClick:()=>e.on_artifact_page_change(m+1),disabled:m>=f-1,children:"Next"}),s.jsx("button",{className:"btn",onClick:()=>e.on_artifact_page_change(f-1),disabled:m>=f-1,children:"Last"})]}):null]}),s.jsxs("div",{className:"pane_body scroll artifact_browser_body",children:[e.artifact_groups.length?null:s.jsx("div",{className:"empty_state_inline",children:e.gateway_connected?"No artifacts match the current filters.":"Gateway offline. Artifact inventory cannot be loaded until the connection is restored."}),s.jsx("div",{className:"artifact_group_list",children:e.artifact_groups.map(O=>s.jsxs("section",{className:"artifact_group",children:[s.jsxs("div",{className:"artifact_group_header",children:[s.jsx("span",{children:O.key}),s.jsx("span",{className:"artifact_group_count",children:O.items.length})]}),O.items.map($=>{var F;const z=$.run_id&&e.run_by_id[$.run_id]||null,A=z?Ui(z,e.workflow_label_by_id):Sg($),ee=lw($),P=Number(((F=$.access)==null?void 0:F.access_count)||0)||0;return s.jsxs("button",{className:`artifact_row ${(t==null?void 0:t.artifact_id)===$.artifact_id?"selected":""}`,onClick:()=>{e.on_select_artifact($.artifact_id),$.run_id&&e.on_select_run($.run_id)},title:$.artifact_id,children:[s.jsx(uw,{artifact:$,size:18}),s.jsxs("div",{className:"artifact_row_main",children:[s.jsxs("div",{className:"artifact_row_title",children:[s.jsx("strong",{children:aw(mm($,e.run_by_id,e.workflow_label_by_id))}),s.jsx("span",{className:"artifact_type_badge",children:yu($)}),$.render_kind&&$.render_kind!==$.semantic_kind?s.jsx("span",{className:"artifact_type_badge muted",children:$.render_kind}):null,$.legacy_inferred?s.jsx("span",{className:"artifact_type_badge inferred",children:"legacy inferred"}):null]}),s.jsxs("div",{className:"artifact_row_facts",children:[s.jsxs("span",{children:[s.jsx("b",{children:"Created"})," ",tE($)]}),s.jsxs("span",{children:[s.jsx("b",{children:"Size"})," ",Yl($.size_bytes)]}),s.jsxs("span",{children:[s.jsx("b",{children:"Last seen"})," ",ow($)]}),P?s.jsxs("span",{children:[s.jsx("b",{children:"Accesses"})," ",P.toLocaleString()]}):null,ee?s.jsxs("span",{children:[s.jsx("b",{children:"Media"})," ",ee]}):null,$.content_type?s.jsxs("span",{children:[s.jsx("b",{children:"MIME"})," ",$.content_type]}):null]}),s.jsxs("div",{className:"artifact_row_facts secondary",children:[A?s.jsxs("span",{children:[s.jsx("b",{children:"Workflow"})," ",A]}):null,$.run_id?s.jsxs("span",{className:"mono",children:[s.jsx("b",{children:"Run"})," ",Qt($.run_id,13)]}):null,s.jsxs("span",{children:[s.jsx("b",{children:"Turn"})," ",Lp($)]}),gu($)?s.jsxs("span",{className:"mono",children:[s.jsx("b",{children:"Node"})," ",gu($)]}):null,_f($)?s.jsxs("span",{children:[s.jsx("b",{children:"Source"})," ",_f($)]}):null]}),s.jsxs("div",{className:"artifact_row_facts tertiary",children:[s.jsxs("span",{className:"mono",children:[s.jsx("b",{children:"ID"})," ",Qt($.artifact_id,22)]}),s.jsxs("span",{children:[s.jsx("b",{children:"Provenance"})," ",rw($)]})]}),cw($)?s.jsx("div",{className:"artifact_row_path mono",children:cw($)}):null]})]},$.artifact_id)})]},O.key))})]})]}),s.jsx("aside",{className:"runtime_detail",children:s.jsxs("section",{className:"overview_panel runtime_artifact_detail",children:[s.jsxs("div",{className:"overview_panel_header",children:[s.jsx("h3",{children:"Artifact Detail"}),t?s.jsx("span",{className:"chip mono muted",children:e.embedded_preview.render_kind?Ip(t,e.run_by_id,e.workflow_label_by_id,e.embedded_preview.text):Ip(t,e.run_by_id,e.workflow_label_by_id)}):null]}),t?s.jsxs(s.Fragment,{children:[(()=>{var F,G,R,Z,X,ie,ne;const O=nE(t),$=tb(t),z=lw(t),A=Number(((F=t.access)==null?void 0:F.access_count)||0)||0,ee=_n((G=t.links)==null?void 0:G.provider_trace,(R=t.links)==null?void 0:R.provider_trace_url,(Z=t.links)==null?void 0:Z.provider_trace_id),P=_n((X=t.links)==null?void 0:X.audit,(ie=t.links)==null?void 0:ie.audit_tail,(ne=t.links)==null?void 0:ne.audit_url);return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"artifact_detail_header",children:[s.jsx(uw,{artifact:t,size:22}),s.jsxs("div",{children:[s.jsx("div",{className:"artifact_detail_title",children:aw(mm(t,e.run_by_id,e.workflow_label_by_id))}),s.jsxs("div",{className:"artifact_detail_subtitle",children:[yu(t)," • ",t.render_kind||e.embedded_preview.render_kind||t.modality||"artifact"," • ",t.content_type||"unknown MIME"," • ",Yl(t.size_bytes),t.legacy_inferred?" • legacy inferred":""]})]})]}),s.jsx(fE,{artifact:t,preview:e.embedded_preview}),s.jsxs("div",{className:"artifact_detail_grid",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Semantic type"}),s.jsx("strong",{children:yu(t)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Render kind"}),s.jsx("strong",{children:t.render_kind||e.embedded_preview.render_kind||"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Created"}),s.jsx("strong",{children:ku(t.created_at)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Size"}),s.jsx("strong",{children:Yl(t.size_bytes)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Last seen"}),s.jsx("strong",{children:ow(t)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Accesses"}),s.jsx("strong",{children:A?A.toLocaleString():"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Run"}),s.jsx("strong",{className:"mono",children:t.run_id?Qt(t.run_id,24):"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Workflow"}),s.jsx("strong",{children:b?Ui(b,e.workflow_label_by_id):"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Turn"}),s.jsx("strong",{children:Lp(t)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Node"}),s.jsx("strong",{className:"mono",children:gu(t)||"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Provider/model"}),s.jsx("strong",{children:$||"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Media facts"}),s.jsx("strong",{children:z||"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Trace"}),s.jsx("strong",{children:t.provider_trace_available?"available":"not recorded"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Provenance"}),s.jsx("strong",{children:rw(t)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Artifact id"}),s.jsx("strong",{className:"mono",children:Qt(t.artifact_id,30)})]}),t.sha256?s.jsxs("div",{children:[s.jsx("span",{children:"sha256"}),s.jsx("strong",{className:"mono",children:Qt(t.sha256,30)})]}):null]}),O?s.jsxs("div",{className:"artifact_provenance_panel",children:[s.jsx("div",{className:"artifact_filter_label",children:"Generation prompt / input"}),s.jsx("div",{className:"artifact_prompt_text",children:O})]}):s.jsxs("div",{className:"artifact_provenance_panel muted",children:[s.jsx("div",{className:"artifact_filter_label",children:"Generation prompt / input"}),s.jsx("div",{className:"artifact_prompt_text",children:"Generation prompt not recorded by the runtime artifact descriptor."})]}),Object.keys(t.generation||{}).length||Object.keys(t.producer||{}).length?s.jsxs("details",{className:"runtime_raw_details",children:[s.jsx("summary",{className:"mono muted",children:"Generation and producer metadata"}),s.jsx(Is,{value:{generation:t.generation,producer:t.producer,source_refs:t.source_refs},collapseAfterDepth:3,showCopy:!0})]}):null,t.source_path?s.jsx("div",{className:"artifact_detail_path mono",children:t.source_path}):null,s.jsxs("div",{className:"runtime_detail_actions",children:[s.jsx("button",{className:"btn primary",onClick:()=>e.on_preview_artifact(t),disabled:!t.run_id,children:e.embedded_preview.render_kind==="html"?"Open as web page":"Open full preview"}),s.jsx("button",{className:"btn",onClick:()=>e.on_download_artifact(t),disabled:!t.run_id,children:"Download"}),s.jsx("button",{className:"btn",onClick:()=>E(t.run_id),disabled:!t.run_id,children:"Show run artifacts"}),s.jsx("button",{className:"btn",onClick:()=>e.on_open_run(t.run_id),disabled:!t.run_id,children:"Open in Observe"}),s.jsx("button",{className:"btn",onClick:()=>e.on_open_ledger(t.run_id),disabled:!t.run_id,children:"Open run ledger"}),s.jsx("button",{className:"btn",onClick:()=>{ee&&window.open(ee,"_blank","noopener,noreferrer")},disabled:!ee,children:"Open provider trace"}),s.jsx("button",{className:"btn",onClick:()=>{P?window.open(P,"_blank","noopener,noreferrer"):e.on_tab_change("logs")},disabled:!P&&!t.audit_available,children:"Open audit trail"}),s.jsx("button",{className:"btn",onClick:()=>void ic(t.artifact_id),disabled:!t.artifact_id,children:"Copy artifact id"})]})]})})(),s.jsxs("details",{className:"runtime_raw_details",children:[s.jsx("summary",{className:"mono muted",children:"Raw metadata"}),s.jsx(Is,{value:t.raw,collapseAfterDepth:3,showCopy:!0})]})]}):s.jsx("div",{className:"empty_state_inline",children:"Select an artifact to inspect metadata, preview, or download content."})]})})]})]}):null,e.tab==="logs"?s.jsxs("section",{className:"overview_panel runtime_logs_panel",children:[s.jsxs("div",{className:"overview_panel_header",children:[s.jsxs("div",{children:[s.jsx("h3",{children:fe}),s.jsx("div",{className:"mono muted",children:W})]}),s.jsxs("div",{className:"actions",style:{marginTop:0},children:[ce&&e.runtime_ledger_log_meta?s.jsx("span",{className:"mono muted",children:e.runtime_ledger_log_meta}):null,e.runtime_log_source==="gateway_audit"&&e.audit_log_meta?s.jsx("span",{className:"mono muted",children:e.audit_log_meta}):null,s.jsxs("button",{className:"btn btn_icon",onClick:()=>{ce?e.on_refresh_runtime_ledger(e.selected_run_id):e.on_refresh_audit()},disabled:ce?e.runtime_ledger_log_loading:e.audit_log_loading,children:[s.jsx(et,{name:"refresh",size:14}),ce?e.runtime_ledger_log_loading?"Loading…":"Refresh":e.audit_log_loading?"Loading…":"Refresh"]})]})]}),s.jsxs("div",{className:"runtime_log_toolbar",children:[s.jsxs("div",{className:"seg_toggle mono",children:[s.jsx("button",{className:`seg_btn ${e.runtime_log_source==="run_ledger"?"active":""}`,onClick:()=>e.on_runtime_log_source_change("run_ledger"),children:"Run ledger"}),s.jsx("button",{className:`seg_btn ${e.runtime_log_source==="provider_calls"?"active":""}`,onClick:()=>e.on_runtime_log_source_change("provider_calls"),children:"Provider calls"}),s.jsx("button",{className:`seg_btn ${e.runtime_log_source==="gateway_audit"?"active":""}`,onClick:()=>e.on_runtime_log_source_change("gateway_audit"),children:"Gateway audit"})]}),s.jsx("input",{className:"mono",value:e.runtime_log_query,onChange:O=>e.on_runtime_log_query_change(O.target.value),placeholder:"Search node, status, effect, payload, error"})]}),e.runtime_log_source==="run_ledger"?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"runtime_log_context",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Selected run"}),s.jsx("strong",{children:I?Ui(I,e.workflow_label_by_id):e.selected_run_id?Qt(e.selected_run_id,24):"No run selected"}),e.selected_run_id?s.jsx("em",{className:"mono",children:Qt(e.selected_run_id,34)}):null]}),s.jsxs("div",{children:[s.jsx("span",{children:"Session"}),s.jsx("strong",{className:"mono",children:I!=null&&I.session_id?Qt(String(I.session_id),28):e.session_id?Qt(e.session_id,28):"—"})]}),s.jsxs("div",{className:"runtime_log_context_actions",children:[s.jsx("button",{className:"btn",onClick:()=>e.on_open_run(e.selected_run_id),disabled:!e.selected_run_id,children:"Open Observe"}),s.jsx("button",{className:"btn",onClick:()=>E(e.selected_run_id),disabled:!e.selected_run_id,children:"Run artifacts"})]})]}),e.runtime_ledger_log_error?s.jsx("div",{className:"warn_callout",children:e.runtime_ledger_log_error}):null,e.selected_run_id?null:s.jsx("div",{className:"empty_state_inline",children:"Select a run in Activity or Artifact Explorer to inspect its runtime ledger."}),e.selected_run_id&&!K.length&&!e.runtime_ledger_log_loading?s.jsx("div",{className:"empty_state_inline",children:"No ledger records match the current search."}):null,s.jsx("div",{className:"runtime_log_event_list","aria-label":"Selected run ledger records",children:K.map(O=>{var X,ie;const $=O.record||{},z=String(((X=$==null?void 0:$.effect)==null?void 0:X.type)||"").trim(),A=String(($==null?void 0:$.status)||"").trim(),ee=String(($==null?void 0:$.node_id)||"").trim(),P=_n($==null?void 0:$.ended_at,$==null?void 0:$.started_at,$==null?void 0:$.ts),F=ra($),G=nb($),R=z?jt(cr(((ie=$==null?void 0:$.effect)==null?void 0:ie.payload)??{},1200),{max_chars:1200,max_lines:6}):"",Z=sb($)||(F?`Waiting for ${String(F.reason||"input")}`:"")||(($==null?void 0:$.result)!==void 0?cr($.result,700):"");return s.jsxs("article",{className:`runtime_log_event ${ac(A)}`,children:[s.jsxs("div",{className:"runtime_log_event_header",children:[s.jsxs("span",{className:"mono",children:["#",O.cursor]}),s.jsx(lc,{status:A||"record"}),z?s.jsx("span",{className:"chip mono muted",children:z}):null,ee?s.jsx("strong",{className:"mono",children:ee}):null,P?s.jsx("span",{className:"mono muted",children:ku(P)}):null]}),s.jsxs("div",{className:"runtime_log_event_body",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Request / activity"}),s.jsx("p",{children:[G||Qh($),R&&R!=="{}"?R:""].filter(Boolean).join(`
112
- `)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Outcome"}),s.jsx("p",{children:jt(Z||"—",{max_chars:1200,max_lines:6})})]})]}),s.jsxs("details",{className:"runtime_raw_details",children:[s.jsx("summary",{className:"mono muted",children:"Raw ledger record"}),s.jsx(Is,{value:$,collapseAfterDepth:3,showCopy:!0})]})]},`${e.selected_run_id}:${O.cursor}`)})})]}):e.runtime_log_source==="provider_calls"?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"runtime_log_context",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Selected run"}),s.jsx("strong",{children:I?Ui(I,e.workflow_label_by_id):e.selected_run_id?Qt(e.selected_run_id,24):"No run selected"}),e.selected_run_id?s.jsx("em",{className:"mono",children:Qt(e.selected_run_id,34)}):null]}),s.jsxs("div",{children:[s.jsx("span",{children:"Provider calls"}),s.jsx("strong",{children:U.length.toLocaleString()}),s.jsx("em",{className:"mono",children:J?`${J.toLocaleString()} tokens`:"tokens not recorded"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Issues"}),s.jsx("strong",{children:Y.toLocaleString()})]}),s.jsxs("div",{className:"runtime_log_context_actions",children:[s.jsx("button",{className:"btn",onClick:()=>e.on_open_run(e.selected_run_id),disabled:!e.selected_run_id,children:"Open Observe"}),s.jsx("button",{className:"btn",onClick:()=>e.on_runtime_log_source_change("run_ledger"),disabled:!e.selected_run_id,children:"Run ledger"})]})]}),e.runtime_ledger_log_error?s.jsx("div",{className:"warn_callout",children:e.runtime_ledger_log_error}):null,e.selected_run_id?null:s.jsx("div",{className:"empty_state_inline",children:"Select a run in Activity or Artifact Explorer to inspect provider calls."}),e.selected_run_id&&!U.length&&!e.runtime_ledger_log_loading?s.jsx("div",{className:"empty_state_inline",children:"No provider calls are present in the selected run ledger, or none match the current search."}):null,s.jsx("div",{className:"provider_activity_list runtime_provider_log_list",children:U.map(O=>s.jsxs("article",{className:`provider_activity ${O.error||O.missing_response?"danger":""}`,children:[s.jsxs("div",{className:"provider_activity_header",children:[s.jsxs("div",{children:[s.jsx("h4",{children:[O.provider||"provider unknown",O.model||"model unknown"].join(" / ")}),s.jsxs("div",{className:"timeline_subtitle",children:[O.node_id?s.jsx("span",{className:"mono",children:O.node_id}):null,O.run_id?s.jsx("span",{className:"mono",children:Qt(O.run_id,16)}):null,s.jsx("span",{children:yg(O.duration_ms)}),O.status?s.jsx(lc,{status:O.status}):null]})]}),s.jsxs("div",{className:"provider_tokens mono",children:[O.tokens.total?O.tokens.total.toLocaleString():"—"," tokens"]})]}),s.jsxs("div",{className:"provider_preview_grid",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Prompt / messages"}),s.jsx("p",{children:O.prompt_preview||"No prompt payload captured"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Response / error"}),s.jsx("p",{children:O.response_preview||O.error||"No response captured"})]})]}),s.jsxs("details",{className:"runtime_raw_details",children:[s.jsx("summary",{className:"mono muted",children:"Raw provider ledger record"}),s.jsx(Is,{value:O.raw,collapseAfterDepth:3,showCopy:!0})]})]},O.id))})]}):s.jsxs(s.Fragment,{children:[e.audit_log_error?s.jsx("div",{className:"warn_callout",children:e.audit_log_error}):null,s.jsx("pre",{className:"mono audit_log_tail",children:re.length?re.join(`
113
- `):"(audit tail not loaded or no lines match search)"})]})]}):null]})}function bE(e){const[t,n]=p.useState(""),r=Array.isArray(e.wait.choices)?e.wait.choices:[],o=e.wait.allow_free_text!==!1,l=e.disabled===!0,u=String(e.wait.prompt||"").trim();return s.jsxs(s.Fragment,{children:[r.length?s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Expected response"}),s.jsxs("select",{className:"mono",value:t,onChange:c=>n(c.target.value),children:[s.jsx("option",{value:"",children:"(select)"}),r.map((c,f)=>s.jsx("option",{value:String(c),children:String(c)},f))]})]}):null,o?s.jsxs("div",{className:"field",children:[s.jsx("label",{children:r.length?"Or type a response":u?"Your answer":"Response to resume this wait"}),s.jsx("textarea",{className:"mono wait_response_input",value:t,onChange:c=>n(c.target.value),placeholder:u?"Type your answer to the request above…":"Type the response the workflow is waiting for…",rows:4})]}):null,s.jsx("div",{className:"actions",children:s.jsx("button",{className:"btn primary",disabled:l||!t.trim(),onClick:()=>e.on_submit(t.trim()),children:"Submit response"})})]})}function hw(e,t,n){if(ff(e)==="automation"){const r=String(e.automation_id||e.run_id||"").trim();return n[r]||"Automation"}return Ui(e,t)}function mw(e){const t=ff(e.run);return t?s.jsx("span",{className:"chip scheduled run_tree_tag","data-tag":t,children:zx(e.run)}):null}function kE(e){const t=e.selected_run_id.trim(),n=e.list?e.list.open:!0,r=e.root_run_id.trim()||t,o=e.sections.reduce((l,u)=>l+u.rows.reduce((c,f)=>{const m=[f.run,...f.children];return c+m.filter(_=>ju(_.status)).length},0),0);return s.jsxs("aside",{className:`observatory_sidebar pane${n?"":" list_collapsed"}`,children:[s.jsxs("div",{className:"run_nav_header pane_header",children:[e.list?s.jsx(mf,{open:n,on_toggle:e.list.on_toggle,controls:"run_nav_controls run_nav_tree",title:"Runs",count:`${e.total_runs.toLocaleString()} runs • ${o.toLocaleString()} active`}):s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"pane_title",children:"Runs"}),s.jsxs("span",{className:"pane_count",children:[e.total_runs.toLocaleString()," runs • ",o.toLocaleString()," active"]})]}),s.jsx("span",{className:"pane_spacer"}),s.jsxs("button",{className:"btn btn_icon",onClick:e.on_refresh,disabled:e.loading,title:"Refresh workflow runs",children:[s.jsx(et,{name:"refresh",size:14}),e.loading?"…":""]})]}),s.jsxs("div",{className:"run_nav_controls",id:"run_nav_controls",hidden:!n,children:[s.jsx("input",{value:e.search,onChange:l=>e.on_search(l.target.value),placeholder:"Search runs, sessions, workflows"}),s.jsxs("div",{className:"run_nav_filter_row",children:[s.jsx("div",{className:"seg_toggle run_nav_segments",children:["active","waiting","terminal","failed","all"].map(l=>s.jsx("button",{className:`seg_btn ${e.filter===l?"active":""}`,onClick:()=>e.on_filter(l),children:l},l))}),s.jsxs("select",{className:"seg_select",value:e.group_by,onChange:l=>e.on_group_by(l.target.value),title:"Group workflow runs",children:[s.jsx("option",{value:"status",children:"Group by status"}),s.jsx("option",{value:"workflow",children:"Group by workflow"}),s.jsx("option",{value:"session",children:"Group by session"})]})]})]}),s.jsxs("div",{className:"run_tree",id:"run_nav_tree",hidden:!n,children:[e.sections.length?null:e.connected?s.jsx("div",{className:"run_tree_empty",children:"No runs match the current filters."}):s.jsxs("div",{className:"run_tree_empty",children:["Gateway offline — runs are unavailable."," ",s.jsx("button",{className:"btn btn_sm",onClick:e.on_sign_in,children:"Sign in"})]}),e.sections.map(l=>s.jsxs("section",{className:"run_tree_section",children:[s.jsxs("div",{className:"run_tree_section_header",children:[s.jsx("span",{children:l.label}),s.jsx("span",{className:"mono",children:l.rows.length})]}),l.rows.map(u=>{const c=u.run,f=String(c.run_id||"").trim(),m=f===t;return s.jsxs("div",{className:"run_tree_group",children:[s.jsxs("button",{className:`run_tree_item ${m?"selected":""} ${f===r?"root_context":""}`,onClick:()=>e.on_select(f,f),title:f,children:[s.jsxs("div",{className:"run_tree_item_top",children:[s.jsx("span",{className:"run_tree_label",children:hw(c,e.workflow_label_by_id,e.automation_titles)}),s.jsx(mw,{run:c}),c.status?s.jsx(lc,{status:um(c)}):null]}),s.jsxs("div",{className:"run_tree_meta",children:[s.jsx("span",{className:"mono",children:Qt(f,13)}),s.jsx("span",{children:hu(c)?ec(hu(c)):"no start"}),s.jsx("span",{children:oc(c)})]})]}),u.children.length?s.jsx("div",{className:"run_tree_children",children:u.children.map(_=>{const g=String(_.run_id||"").trim();return s.jsxs("button",{className:`run_tree_item run_tree_child ${g===t?"selected":""}`,onClick:()=>e.on_select(g,f),title:g,children:[s.jsxs("div",{className:"run_tree_item_top",children:[s.jsx("span",{className:"run_tree_label",children:hw(_,e.workflow_label_by_id,e.automation_titles)}),s.jsx(mw,{run:_}),s.jsx(lc,{status:um(_)})]}),s.jsxs("div",{className:"run_tree_meta",children:[s.jsx("span",{className:"mono",children:Qt(g,13)}),s.jsx("span",{children:hu(_)?ec(hu(_)):"child"}),s.jsx("span",{children:oc(_)})]})]},g)})}):null]},f)})]},l.key))]})]})}class jE{constructor(){Vs(this,"_buffer","");Vs(this,"_current",{data_lines:[]})}push(t,n){for(this._buffer+=t;;){const r=this._buffer.indexOf(`
114
- `);if(r===-1)return;const o=this._buffer.slice(0,r);this._buffer=this._buffer.slice(r+1);const l=o.endsWith("\r")?o.slice(0,-1):o;if(l.startsWith(":"))continue;if(l===""){if(this._current.data_lines.length>0||this._current.event||this._current.id){const m={id:this._current.id,event:this._current.event,data:this._current.data_lines.join(`
115
- `)};n(m)}this._current={data_lines:[]};continue}const u=l.indexOf(":"),c=u===-1?l:l.slice(0,u),f=u===-1?"":l.slice(u+1).trimStart();if(c==="id"){this._current.id=f;continue}if(c==="event"){this._current.event=f;continue}if(c==="data"){this._current.data_lines.push(f);continue}}}}const Lt=ag;function si(e,t=3e4){const n=AbortSignal.timeout(t);if(!e)return n;const r=AbortSignal.any;return typeof r=="function"?r([e,n]):e}function lb(){var t;const e={};try{const n=(t=document.cookie.split(";").map(r=>r.trim()).find(r=>r.startsWith("abstractobserver_gateway_csrf=")))==null?void 0:t.slice(30);n&&(e["X-AbstractObserver-CSRF"]=decodeURIComponent(n))}catch{}return e}function Mt(e){const t=(e||"").trim(),n={};return t&&(n.Authorization=`Bearer ${t}`),{...n,...lb()}}async function Wn(e){try{const t=await e.text();return t!=null&&t.trim()?t.trim():`${e.status}`}catch{return`${e.status}`}}class SE extends Error{constructor(n,r){super(r);Vs(this,"status");this.name="GatewayRequestError",this.status=n}}async function Oh(e,t){let n="";try{n=(await e.text()).trim()}catch{n=""}let r=n;try{const o=JSON.parse(n),l=o&&typeof o=="object"?o.detail:void 0;typeof l=="string"&&l.trim()?r=l.trim():l&&typeof l=="object"&&typeof l.message=="string"&&l.message.trim()&&(r=l.message.trim())}catch{}return new SE(e.status,`${t} (HTTP ${e.status}): ${r||e.statusText||"no reason given"}`)}class F_{constructor(t){Vs(this,"_cfg");Vs(this,"fetch_gateway",(t,n)=>fetch(Lt(this._cfg.base_url,t),{...n,headers:{...n==null?void 0:n.headers,...Mt(this._cfg.auth_token)}}));this._cfg={...t,base_url:(t.base_url||"").trim()}}async start_run(t,n,r){const o=String((r==null?void 0:r.bundle_id)||"").trim(),l=(r==null?void 0:r.session_id)===null||(r==null?void 0:r.session_id)===void 0?"":String(r.session_id||"").trim(),u=String(t||"").trim(),c=String((r==null?void 0:r.interface)||"").trim();if(u==="@default"&&(!c||o))throw new Error("start_run: flow_id '@default' needs `interface` and no bundle_id");const f={input_data:n||{}};o&&(f.bundle_id=o),u&&(f.flow_id=u),u==="@default"&&(f.interface=c),l&&(f.session_id=l);const m=await fetch(Lt(this._cfg.base_url,wt("runs/start")),{method:"POST",headers:{"Content-Type":"application/json",...Mt(this._cfg.auth_token)},body:JSON.stringify(f)});if(!m.ok)throw new Error(`start_run failed: ${m.status}`);const _=await m.json(),g=_==null?void 0:_.run_id;if(typeof g!="string"||!g)throw new Error("start_run: missing run_id");return g}async list_mcp_servers(){for(const t of[wt("mcp/servers"),wt("mcp"),wt("discovery/mcp")])try{const n=await fetch(Lt(this._cfg.base_url,t),{headers:{...Mt(this._cfg.auth_token)},signal:si()});if(n.status===404||!n.ok)continue;const r=await n.json(),o=Array.isArray(r)?r:Array.isArray(r==null?void 0:r.servers)?r.servers:Array.isArray(r==null?void 0:r.items)?r.items:null;if(!o)continue;return o.map(l=>({name:String((l==null?void 0:l.name)||(l==null?void 0:l.id)||"").trim(),url:typeof(l==null?void 0:l.url)=="string"?l.url:void 0,description:typeof(l==null?void 0:l.description)=="string"?l.description:void 0,auth_required:typeof(l==null?void 0:l.auth_required)=="boolean"?l.auth_required:void 0})).filter(l=>l.name)}catch{return null}return null}async list_skills(){for(const t of[wt("skills"),wt("skills/registry")])try{const n=await fetch(Lt(this._cfg.base_url,t),{headers:{...Mt(this._cfg.auth_token)},signal:si()});if(n.status===404||!n.ok)continue;const r=await n.json(),o=Array.isArray(r)?r:Array.isArray(r==null?void 0:r.skills)?r.skills:Array.isArray(r==null?void 0:r.items)?r.items:null;if(!o)continue;return o.map(l=>({name:String((l==null?void 0:l.name)||(l==null?void 0:l.id)||"").trim(),description:typeof(l==null?void 0:l.description)=="string"?l.description:void 0,version:typeof(l==null?void 0:l.version)=="string"?l.version:void 0,trust_level:typeof(l==null?void 0:l.trust_level)=="string"?l.trust_level:void 0,blocked:typeof(l==null?void 0:l.blocked)=="boolean"?l.blocked:void 0,requires_review:typeof(l==null?void 0:l.requires_review)=="boolean"?l.requires_review:void 0,tree_hash:typeof(l==null?void 0:l.tree_hash)=="string"?l.tree_hash:void 0,reasons:Array.isArray(l==null?void 0:l.reasons)?l.reasons.map(u=>String(u||"")).filter(Boolean):void 0})).filter(l=>l.name)}catch{return null}return null}async get_run(t){const n=await fetch(Lt(this._cfg.base_url,wt(`runs/${encodeURIComponent(t)}`)),{headers:{...Mt(this._cfg.auth_token)}});if(!n.ok)throw new Error(`get_run failed: ${await Wn(n)}`);return await n.json()}async find_run(t){const n=await fetch(Lt(this._cfg.base_url,wt(`runs/${encodeURIComponent(t)}`)),{headers:{...Mt(this._cfg.auth_token)}});if(n.status===404||n.status===403)return null;if(!n.ok)throw await Oh(n,"Opening the run failed");return await n.json()}async get_run_history_bundle(t,n){const r=String(t||"").trim();if(!r)throw new Error("get_run_history_bundle: run_id is required");const o=new URLSearchParams;(n==null?void 0:n.include_subruns)===!1&&o.set("include_subruns","false"),(n==null?void 0:n.include_session)===!0&&o.set("include_session","true"),typeof(n==null?void 0:n.session_turn_limit)=="number"&&Number.isFinite(n.session_turn_limit)&&o.set("session_turn_limit",String(Math.max(1,Math.trunc(n.session_turn_limit)))),n!=null&&n.ledger_mode&&o.set("ledger_mode",String(n.ledger_mode)),typeof(n==null?void 0:n.ledger_max_items)=="number"&&Number.isFinite(n.ledger_max_items)&&o.set("ledger_max_items",String(Math.max(0,Math.trunc(n.ledger_max_items))));const l=Lt(this._cfg.base_url,wt(`runs/${encodeURIComponent(r)}/history_bundle?${o.toString()}`)),u=await fetch(l,{headers:{...Mt(this._cfg.auth_token)}});if(!u.ok)throw new Error(`get_run_history_bundle failed: ${await Wn(u)}`);return await u.json()}async list_runs(t){const n=typeof(t==null?void 0:t.limit)=="number"?t.limit:50,r=String((t==null?void 0:t.status)||"").trim(),o=String((t==null?void 0:t.workflow_id)||"").trim(),l=String((t==null?void 0:t.session_id)||"").trim(),u=(t==null?void 0:t.root_only)===!0,c=new URLSearchParams;c.set("limit",String(n)),r&&c.set("status",r),o&&c.set("workflow_id",o),l&&c.set("session_id",l),u&&c.set("root_only","true"),typeof(t==null?void 0:t.include_ledger_len)=="boolean"&&c.set("include_ledger_len",String(t.include_ledger_len)),typeof(t==null?void 0:t.include_metrics)=="boolean"&&c.set("include_metrics",String(t.include_metrics)),typeof(t==null?void 0:t.include_drafts)=="boolean"&&c.set("include_drafts",String(t.include_drafts));const f=Lt(this._cfg.base_url,wt(`runs?${c.toString()}`)),m=await fetch(f,{headers:{...Mt(this._cfg.auth_token)},signal:AbortSignal.timeout(3e4)});if(!m.ok)throw new Error(`list_runs failed: ${await Wn(m)}`);return await m.json()}async audit_log_tail(t){const n=typeof(t==null?void 0:t.max_bytes)=="number"?Math.max(1024,Math.min(4e5,Math.floor(t.max_bytes))):8e4,r=Lt(this._cfg.base_url,wt(`audit/tail?max_bytes=${encodeURIComponent(String(n))}`)),o=await fetch(r,{headers:{...Mt(this._cfg.auth_token)}});if(!o.ok)throw new Error(`audit_log_tail failed: ${await Wn(o)}`);return await o.json()}async gateway_about(){const t=await fetch(Lt(this._cfg.base_url,wt("about")),{headers:{...Mt(this._cfg.auth_token)},signal:si(void 0,1e4)});if(!t.ok)throw new Error(`HTTP ${t.status}`);return await t.json()}async get_run_input_data(t){const n=String(t||"").trim();if(!n)throw new Error("get_run_input_data: run_id is required");const r=await fetch(Lt(this._cfg.base_url,wt(`runs/${encodeURIComponent(n)}/input_data`)),{headers:{...Mt(this._cfg.auth_token)}});if(!r.ok)throw new Error(`get_run_input_data failed: ${await Wn(r)}`);return await r.json()}async list_run_artifacts(t,n){const r=String(t||"").trim();if(!r)throw new Error("list_run_artifacts: run_id is required");const o=typeof(n==null?void 0:n.limit)=="number"?n.limit:200,l=typeof(n==null?void 0:n.offset)=="number"?Math.max(0,Math.floor(n.offset)):0,u=Lt(this._cfg.base_url,wt(`runs/${encodeURIComponent(r)}/artifacts?limit=${encodeURIComponent(String(o))}&offset=${encodeURIComponent(String(l))}`)),c=await fetch(u,{headers:{...Mt(this._cfg.auth_token)}});if(!c.ok)throw new Error(`list_run_artifacts failed: ${await Wn(c)}`);return await c.json()}async list_session_artifacts(t,n){const r=String(t||"").trim();if(!r)throw new Error("list_session_artifacts: session_id is required");const o=typeof(n==null?void 0:n.limit)=="number"?n.limit:200,l=typeof(n==null?void 0:n.offset)=="number"?Math.max(0,Math.floor(n.offset)):0,u=Lt(this._cfg.base_url,wt(`sessions/${encodeURIComponent(r)}/artifacts?limit=${encodeURIComponent(String(o))}&offset=${encodeURIComponent(String(l))}`)),c=await fetch(u,{headers:{...Mt(this._cfg.auth_token)}});if(!c.ok)throw new Error(`list_session_artifacts failed: ${await Wn(c)}`);return await c.json()}async search_artifacts(t){const n=new URLSearchParams;n.set("scope",String((t==null?void 0:t.scope)||"all").trim()||"all");const r=String((t==null?void 0:t.session_id)||"").trim(),o=String((t==null?void 0:t.run_id)||"").trim(),l=String((t==null?void 0:t.modality)||"").trim(),u=String((t==null?void 0:t.artifact_kind)||"").trim(),c=String((t==null?void 0:t.semantic_kind)||"").trim(),f=String((t==null?void 0:t.render_kind)||"").trim(),m=String((t==null?void 0:t.workflow_id)||"").trim(),_=String((t==null?void 0:t.node_id)||"").trim(),g=String((t==null?void 0:t.content_type)||"").trim(),w=String((t==null?void 0:t.query)||"").trim(),x=String((t==null?void 0:t.tags)||"").trim(),j=String((t==null?void 0:t.cursor)||"").trim(),b=String((t==null?void 0:t.order_by)||"").trim(),N=String((t==null?void 0:t.order)||"").trim(),C=String((t==null?void 0:t.created_after)||"").trim(),E=String((t==null?void 0:t.created_before)||"").trim(),T=typeof(t==null?void 0:t.limit)=="number"?t.limit:500,I=typeof(t==null?void 0:t.offset)=="number"?Math.max(0,Math.floor(t.offset)):0;r&&n.set("session_id",r),o&&n.set("run_id",o),l&&n.set("modality",l),u&&n.set("artifact_kind",u),c&&n.set("semantic_kind",c),f&&n.set("render_kind",f),m&&n.set("workflow_id",m),_&&n.set("node_id",_),g&&n.set("content_type",g),w&&n.set("query",w),x&&n.set("tags",x),j&&n.set("cursor",j),b&&n.set("order_by",b),N&&n.set("order",N),C&&n.set("created_after",C),E&&n.set("created_before",E),t!=null&&t.include_stats&&n.set("include_stats","true"),n.set("limit",String(T)),n.set("offset",String(I));const K=await fetch(Lt(this._cfg.base_url,wt(`artifacts/search?${n.toString()}`)),{headers:{...Mt(this._cfg.auth_token)}});if(!K.ok)throw new Error(`search_artifacts failed: ${await Wn(K)}`);return await K.json()}async artifact_stats(t){const n=new URLSearchParams;n.set("scope",String((t==null?void 0:t.scope)||"all").trim()||"all");for(const o of["session_id","run_id","modality","semantic_kind","render_kind","workflow_id","node_id","content_type","query","tags","created_after","created_before"]){const l=String((t==null?void 0:t[o])||"").trim();l&&n.set(o,l)}const r=await fetch(Lt(this._cfg.base_url,wt(`artifacts/stats?${n.toString()}`)),{headers:{...Mt(this._cfg.auth_token)}});if(!r.ok)throw new Error(`artifact_stats failed: ${await Wn(r)}`);return await r.json()}async download_run_artifact_content(t,n,r){const o=String(t||"").trim(),l=String(n||"").trim();if(!o)throw new Error("download_run_artifact_content: run_id is required");if(!l)throw new Error("download_run_artifact_content: artifact_id is required");const u=String((r==null?void 0:r.access)||"").trim(),c=u?`?access=${encodeURIComponent(u)}`:"",f=Lt(this._cfg.base_url,wt(`runs/${encodeURIComponent(o)}/artifacts/${encodeURIComponent(l)}/content${c}`)),m=await fetch(f,{headers:{...Mt(this._cfg.auth_token)}});if(!m.ok)throw new Error(`download_run_artifact_content failed: ${await Wn(m)}`);return await m.blob()}async list_entities(){const t=await fetch(Lt(this._cfg.base_url,wt("entities")),{headers:{...Mt(this._cfg.auth_token)},signal:si()});if(!t.ok)throw new Error(`list_entities failed: ${await Wn(t)}`);const n=await t.json();return{entities:Array.isArray(n==null?void 0:n.entities)?n.entities:[]}}async get_entity_phases_spec(){const t=await fetch(Lt(this._cfg.base_url,wt("entities/spec/phases")),{headers:{...Mt(this._cfg.auth_token)},signal:si()});if(!t.ok)throw new Error(`get_entity_phases_spec failed: ${await Wn(t)}`);return await t.json()}async get_entity_cognition(t){const n=await fetch(Lt(this._cfg.base_url,wt(`entities/${encodeURIComponent(t)}/cognition`)),{headers:{...Mt(this._cfg.auth_token)},signal:si()});if(!n.ok)throw new Error(`get_entity_cognition failed: ${await Wn(n)}`);return await n.json()}async get_entity_card(t){const n=String(t||"").trim();if(!n)throw new Error("get_entity_card: name is required");const r=await fetch(Lt(this._cfg.base_url,wt(`entities/${encodeURIComponent(n)}/card`)),{headers:{...Mt(this._cfg.auth_token)},signal:si()});if(!r.ok)throw new Error(`get_entity_card failed: ${await Wn(r)}`);return await r.json()}async read_entity_diary_entry(t,n){const r=String(t||"").trim(),o=String(n||"").trim();if(!r||!o)throw new Error("read_entity_diary_entry: name and entry_id are required");const l=Lt(this._cfg.base_url,wt(`entities/${encodeURIComponent(r)}/diary/${encodeURIComponent(o)}?reason=${encodeURIComponent("observer board hint chip")}`)),u=await fetch(l,{headers:{...Mt(this._cfg.auth_token)},signal:si()});if(!u.ok)throw new Error(`read_entity_diary_entry failed: ${await Wn(u)}`);return await u.json()}async get_ledger(t,n){const r=Number((n==null?void 0:n.after)||0),o=Number((n==null?void 0:n.limit)||0),l=Lt(this._cfg.base_url,wt(`runs/${encodeURIComponent(t)}/ledger?after=${encodeURIComponent(String(r))}&limit=${encodeURIComponent(String(o))}`)),u=await fetch(l,{headers:{...Mt(this._cfg.auth_token)},signal:si(n==null?void 0:n.signal)});if(!u.ok)throw new Error(`get_ledger failed: ${u.status}`);const c=await u.json(),f=Array.isArray(c==null?void 0:c.items)?c.items:[],m=typeof(c==null?void 0:c.next_after)=="number"?c.next_after:r;return{items:f,next_after:m}}async get_ledger_batch(t){const n=Array.isArray(t==null?void 0:t.runs)?t.runs:[],r=Number((t==null?void 0:t.limit)||0),o=await fetch(Lt(this._cfg.base_url,wt("runs/ledger/batch")),{method:"POST",headers:{"Content-Type":"application/json",...Mt(this._cfg.auth_token)},body:JSON.stringify({runs:n,limit:r}),signal:si()});if(!o.ok)throw new Error(`get_ledger_batch failed: ${o.status}`);const l=await o.json(),c=(l&&typeof l=="object"?l:{}).runs;return{runs:c&&typeof c=="object"?c:{}}}async generate_run_summary(t,n){const r=String(t||"").trim();if(!r)throw new Error("generate_run_summary: run_id is required");const o={include_subruns:(n==null?void 0:n.include_subruns)!==!1},l=typeof(n==null?void 0:n.provider)=="string"?String(n.provider).trim():"";l&&(o.provider=l);const u=typeof(n==null?void 0:n.model)=="string"?String(n.model).trim():"";u&&(o.model=u);const c=await fetch(Lt(this._cfg.base_url,wt(`runs/${encodeURIComponent(r)}/summary`)),{method:"POST",headers:{"Content-Type":"application/json",...Mt(this._cfg.auth_token)},body:JSON.stringify(o)});if(!c.ok)throw await Oh(c,"The gateway could not summarize this run");return await c.json()}async run_chat(t,n){const r=String(t||"").trim();if(!r)throw new Error("run_chat: run_id is required");const o={include_subruns:(n==null?void 0:n.include_subruns)!==!1,messages:Array.isArray(n==null?void 0:n.messages)?n.messages:[],persist:!!(n!=null&&n.persist)},l=typeof(n==null?void 0:n.provider)=="string"?String(n.provider).trim():"";l&&(o.provider=l);const u=typeof(n==null?void 0:n.model)=="string"?String(n.model).trim():"";u&&(o.model=u);const c=await fetch(Lt(this._cfg.base_url,wt(`runs/${encodeURIComponent(r)}/chat`)),{method:"POST",headers:{"Content-Type":"application/json",...Mt(this._cfg.auth_token)},body:JSON.stringify(o)});if(!c.ok)throw await Oh(c,"The gateway could not answer");return await c.json()}async audio_transcribe(t,n){const r=String(t||"").trim();if(!r)throw new Error("audio_transcribe: run_id is required");const o=n==null?void 0:n.audio_artifact;if(!o||typeof o!="object")throw new Error("audio_transcribe: audio_artifact is required");if(!String(o.$artifact||"").trim())throw new Error("audio_transcribe: audio_artifact.$artifact is required");const u={audio_artifact:o},c=String((n==null?void 0:n.language)||"").trim();c&&(u.language=c);const f=String((n==null?void 0:n.request_id)||"").trim();f&&(u.request_id=f);const m=await fetch(Lt(this._cfg.base_url,wt(`runs/${encodeURIComponent(r)}/audio/transcribe`)),{method:"POST",headers:{"Content-Type":"application/json",...Mt(this._cfg.auth_token)},body:JSON.stringify(u)});if(!m.ok)throw new Error(`audio_transcribe failed: ${await Wn(m)}`);const _=await m.json(),g=String((_==null?void 0:_.text)||"");return{ok:!!(_!=null&&_.ok),run_id:String((_==null?void 0:_.run_id)||""),request_id:String((_==null?void 0:_.request_id)||""),text:g,transcript_artifact:_==null?void 0:_.transcript_artifact}}async voice_tts(t,n){const r=String(t||"").trim();if(!r)throw new Error("voice_tts: run_id is required");const o=String((n==null?void 0:n.text)||"").trim();if(!o)throw new Error("voice_tts: text is required");const l={text:o},u=String((n==null?void 0:n.voice)||"").trim();u&&(l.voice=u);const c=String((n==null?void 0:n.format)||"").trim();c&&(l.format=c);const f=String((n==null?void 0:n.request_id)||"").trim();f&&(l.request_id=f);const m=await fetch(Lt(this._cfg.base_url,wt(`runs/${encodeURIComponent(r)}/voice/tts`)),{method:"POST",headers:{"Content-Type":"application/json",...Mt(this._cfg.auth_token)},body:JSON.stringify(l)});if(!m.ok)throw new Error(`voice_tts failed: ${await Wn(m)}`);const _=await m.json();return{ok:!!(_!=null&&_.ok),run_id:String((_==null?void 0:_.run_id)||""),request_id:String((_==null?void 0:_.request_id)||""),audio_artifact:_==null?void 0:_.audio_artifact}}async save_chat_thread(t,n){const r=String(t||"").trim();if(!r)throw new Error("save_chat_thread: run_id is required");const o={include_subruns:(n==null?void 0:n.include_subruns)!==!1,messages:Array.isArray(n==null?void 0:n.messages)?n.messages:[]},l=typeof(n==null?void 0:n.provider)=="string"?String(n.provider).trim():"";l&&(o.provider=l);const u=typeof(n==null?void 0:n.model)=="string"?String(n.model).trim():"";u&&(o.model=u);const c=typeof(n==null?void 0:n.title)=="string"?String(n.title).trim():"";c&&(o.title=c);const f=await fetch(Lt(this._cfg.base_url,wt(`runs/${encodeURIComponent(r)}/chat_threads`)),{method:"POST",headers:{"Content-Type":"application/json",...Mt(this._cfg.auth_token)},body:JSON.stringify(o)});if(!f.ok)throw new Error(`save_chat_thread failed: ${await Wn(f)}`);return await f.json()}async list_bundles(){const t=await fetch(Lt(this._cfg.base_url,wt("bundles")),{headers:{...Mt(this._cfg.auth_token)},signal:si()});if(!t.ok)throw new Error(`list_bundles failed: ${t.status}`);return await t.json()}async get_gateway_json(t,n){const r=await fetch(Lt(this._cfg.base_url,wt(t)),{headers:{...Mt(this._cfg.auth_token)},signal:n??si()});if(!r.ok)throw new Error(await Wn(r));return await r.json()}async reload_bundles(){const t=await fetch(Lt(this._cfg.base_url,wt("bundles/reload")),{method:"POST",headers:{...Mt(this._cfg.auth_token)}});if(!t.ok)throw new Error(`reload_bundles failed: ${t.status}`);return await t.json()}async upload_bundle(t,n){const r=(n==null?void 0:n.overwrite)===!0,o=(n==null?void 0:n.reload)!==!1,l=new FormData;l.set("overwrite",r?"true":"false"),l.set("reload",o?"true":"false"),l.set("file",t,t.name||"upload.flow");const u=await fetch(Lt(this._cfg.base_url,wt("bundles/upload")),{method:"POST",headers:{...Mt(this._cfg.auth_token)},body:l});if(!u.ok)throw new Error(`upload_bundle failed: ${await Wn(u)}`);return await u.json()}async attachments_upload(t,n,r){const o=String(t||"").trim();if(!o)throw new Error("attachments_upload: session_id is required");if(!n)throw new Error("attachments_upload: file is required");const l=String((r==null?void 0:r.filename)||"").trim()||String((n==null?void 0:n.name)||"").trim()||"upload.bin",u=String((r==null?void 0:r.content_type)||"").trim()||String((n==null?void 0:n.type)||"").trim(),c=new FormData;c.append("session_id",o),c.append("file",n,l),c.append("filename",l),u&&c.append("content_type",u);const f=await fetch(Lt(this._cfg.base_url,wt("attachments/upload")),{method:"POST",headers:{...Mt(this._cfg.auth_token)},body:c});if(!f.ok)throw new Error(`attachments_upload failed: ${await Wn(f)}`);const m=await f.json(),_=m==null?void 0:m.attachment;if(!_||typeof _!="object")throw new Error("attachments_upload: missing attachment");if(!String(_.$artifact||"").trim())throw new Error("attachments_upload: missing attachment.$artifact");return _}async remove_bundle(t,n){const r=String(t||"").trim();if(!r)throw new Error("remove_bundle: bundle_id is required");const o=new URLSearchParams,l=String((n==null?void 0:n.bundle_version)||"").trim();l&&o.set("bundle_version",l),o.set("reload",(n==null?void 0:n.reload)===!1?"false":"true");const u=Lt(this._cfg.base_url,wt(`bundles/${encodeURIComponent(r)}?${o.toString()}`)),c=await fetch(u,{method:"DELETE",headers:{...Mt(this._cfg.auth_token)}});if(!c.ok)throw new Error(`remove_bundle failed: ${await Wn(c)}`);return await c.json()}async discovery_tools(){const t=await fetch(Lt(this._cfg.base_url,wt("discovery/tools")),{headers:{...Mt(this._cfg.auth_token)}});if(!t.ok)throw new Error(`discovery_tools failed: ${t.status}`);return await t.json()}async discovery_providers(t){const n=(t==null?void 0:t.include_models)===!0,r=Lt(this._cfg.base_url,wt(`discovery/providers?include_models=${encodeURIComponent(String(n))}`)),o=await fetch(r,{headers:{...Mt(this._cfg.auth_token)}});if(!o.ok)throw new Error(`discovery_providers failed: ${o.status}`);return await o.json()}async discovery_provider_models(t){const n=String(t||"").trim();if(!n)throw new Error("discovery_provider_models: provider_name is required");const r=await fetch(Lt(this._cfg.base_url,wt(`discovery/providers/${encodeURIComponent(n)}/models`)),{headers:{...Mt(this._cfg.auth_token)}});if(!r.ok)throw new Error(`discovery_provider_models failed: ${r.status}`);return await r.json()}async get_bundle(t){const n=String(t||"").trim();if(!n)throw new Error("get_bundle: bundle_id is required");const r=await fetch(Lt(this._cfg.base_url,wt(`bundles/${encodeURIComponent(n)}`)),{headers:{...Mt(this._cfg.auth_token)}});if(!r.ok)throw new Error(`get_bundle failed: ${r.status}`);return await r.json()}async get_bundle_flow(t,n){const r=String(t||"").trim(),o=String(n||"").trim();if(!r)throw new Error("get_bundle_flow: bundle_id is required");if(!o)throw new Error("get_bundle_flow: flow_id is required");const l=await fetch(Lt(this._cfg.base_url,wt(`bundles/${encodeURIComponent(r)}/flows/${encodeURIComponent(o)}`)),{headers:{...Mt(this._cfg.auth_token)}});if(!l.ok)throw new Error(`get_bundle_flow failed: ${l.status}`);return await l.json()}async get_workflow_flow(t){const n=String(t||"").trim();if(!n)throw new Error("get_workflow_flow: workflow_id is required");const r=await fetch(Lt(this._cfg.base_url,wt(`workflows/${encodeURIComponent(n)}/flow`)),{headers:{...Mt(this._cfg.auth_token)}});if(!r.ok)throw new Error(`get_workflow_flow failed: ${r.status}`);return await r.json()}async discovery_capabilities(){const t=await fetch(Lt(this._cfg.base_url,wt("discovery/capabilities")),{headers:{...Mt(this._cfg.auth_token)},signal:si()});if(!t.ok)throw new Error(`discovery_capabilities failed: ${await Wn(t)}`);return await t.json()}automations_client(){const t=this._cfg.auth_token;return hj({fetch:(n,r)=>fetch(n,r),baseUrl:this._cfg.base_url,headers:()=>Mt(t)})}async submit_command(t){const n=await fetch(Lt(this._cfg.base_url,wt("commands")),{method:"POST",headers:{"Content-Type":"application/json",...Mt(this._cfg.auth_token)},body:JSON.stringify(t)});if(!n.ok)throw new Error(`submit_command failed: ${n.status}`);return await n.json()}async kg_query(t){const n=String((t==null?void 0:t.scope)||"session").trim().toLowerCase(),r=String((t==null?void 0:t.order)||"desc").trim().toLowerCase(),o=typeof(t==null?void 0:t.limit)=="number"&&Number.isFinite(t.limit)?Number(t.limit):500,l={scope:n,order:r,limit:o},u=String((t==null?void 0:t.run_id)||"").trim();u&&(l.run_id=u);const c=String((t==null?void 0:t.session_id)||"").trim();c&&(l.session_id=c);const f=String((t==null?void 0:t.owner_id)||"").trim();f&&(l.owner_id=f),t!=null&&t.all_owners&&(l.all_owners=!0);const m=String((t==null?void 0:t.subject)||"").trim();m&&(l.subject=m);const _=String((t==null?void 0:t.predicate)||"").trim();_&&(l.predicate=_);const g=String((t==null?void 0:t.object)||"").trim();g&&(l.object=g);const w=String((t==null?void 0:t.since)||"").trim();w&&(l.since=w);const x=String((t==null?void 0:t.until)||"").trim();x&&(l.until=x);const j=String((t==null?void 0:t.active_at)||"").trim();j&&(l.active_at=j);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 N=await fetch(Lt(this._cfg.base_url,wt("kg/query")),{method:"POST",headers:{"Content-Type":"application/json",...Mt(this._cfg.auth_token)},body:JSON.stringify(l)});if(!N.ok)throw new Error(`kg_query failed: ${await Wn(N)}`);return await N.json()}async stream_ledger(t,n){var g;const r=Number((n==null?void 0:n.after)||0),o=n.on_step,l=n.signal,u=Lt(this._cfg.base_url,wt(`runs/${encodeURIComponent(t)}/ledger/stream?after=${encodeURIComponent(String(r))}`)),c=await fetch(u,{headers:{Accept:"text/event-stream",...Mt(this._cfg.auth_token)},signal:l});if(!c.ok)throw await Oh(c,"The ledger stream was refused");if(!c.body)throw new Error("stream_ledger: response body is missing");(g=n.on_open)==null||g.call(n);const f=c.body.getReader(),m=new TextDecoder("utf-8"),_=new jE;for(;;){const{value:w,done:x}=await f.read();if(x)return;const j=m.decode(w,{stream:!0});_.push(j,b=>{if(!(b.event!=="step"||!b.data))try{const N=JSON.parse(b.data);N&&typeof N.cursor=="number"&&N.record&&o(N)}catch{}})}}}const Op=Fk("voice and camera")??"Voice and camera are not supported in this browser (getUserMedia unavailable).",NE="Copy failed — select and copy";function Pp(){var t;const e=globalThis.navigator;return typeof((t=e==null?void 0:e.mediaDevices)==null?void 0:t.getUserMedia)=="function"}function CE(e){var o;const t=globalThis.document;if(!t||!t.body||typeof t.execCommand!="function")return!1;const n=t.createElement("textarea");n.value=e,n.setAttribute("readonly",""),n.style.position="fixed",n.style.top="0",n.style.left="-9999px",n.style.opacity="0";const r=t.activeElement;t.body.appendChild(n);try{return n.select(),n.setSelectionRange(0,e.length),t.execCommand("copy")===!0}catch{return!1}finally{t.body.removeChild(n);try{(o=r==null?void 0:r.focus)==null||o.call(r)}catch{}}}async function EE(e){var r;const t=String(e??""),n=globalThis.navigator;if(typeof((r=n==null?void 0:n.clipboard)==null?void 0:r.writeText)=="function")try{return await n.clipboard.writeText(t),!0}catch{}return CE(t)}const AE=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function $E(e){const t=e.length,n=new Uint8Array(t+9+63>>6<<6);n.set(e),n[t]=128;const r=new DataView(n.buffer);r.setUint32(n.length-8,Math.floor(t/536870912),!1),r.setUint32(n.length-4,t<<3>>>0,!1);const o=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),l=new Uint32Array(64),u=(c,f)=>c>>>f|c<<32-f;for(let c=0;c<n.length;c+=64){for(let N=0;N<16;N++)l[N]=r.getUint32(c+N*4,!1);for(let N=16;N<64;N++){const C=u(l[N-15],7)^u(l[N-15],18)^l[N-15]>>>3,E=u(l[N-2],17)^u(l[N-2],19)^l[N-2]>>>10;l[N]=l[N-16]+C+l[N-7]+E>>>0}let[f,m,_,g,w,x,j,b]=[o[0],o[1],o[2],o[3],o[4],o[5],o[6],o[7]];for(let N=0;N<64;N++){const C=u(w,6)^u(w,11)^u(w,25),E=w&x^~w&j,T=b+C+E+AE[N]+l[N]>>>0,I=u(f,2)^u(f,13)^u(f,22),K=f&m^f&_^m&_,U=I+K>>>0;b=j,j=x,x=w,w=g+T>>>0,g=_,_=m,m=f,f=T+U>>>0}o[0]=o[0]+f>>>0,o[1]=o[1]+m>>>0,o[2]=o[2]+_>>>0,o[3]=o[3]+g>>>0,o[4]=o[4]+w>>>0,o[5]=o[5]+x>>>0,o[6]=o[6]+j>>>0,o[7]=o[7]+b>>>0}return Array.from(o,c=>c.toString(16).padStart(8,"0")).join("")}async function TE(e){var r;const t=new TextEncoder().encode(String(e??"")),n=(r=globalThis.crypto)==null?void 0:r.subtle;if(n&&typeof n.digest=="function"){const o=await n.digest("SHA-256",t);return Array.from(new Uint8Array(o),l=>l.toString(16).padStart(2,"0")).join("")}return $E(t)}function ME(e){const t=(e||"").trim();return t?{Authorization:`Bearer ${t}`}:{}}class RE{constructor(t){Vs(this,"_cfg");this._cfg={...t,url:(t.url||"").trim()}}async call_tool(t){const n=String((t==null?void 0:t.name)||"").trim(),r=String((t==null?void 0:t.call_id)||(t==null?void 0:t.id)||xs()),o=t!=null&&t.arguments&&typeof t.arguments=="object"?t.arguments:{};if(!n)return{call_id:r,name:"",success:!1,output:null,error:"Missing tool name"};const l={jsonrpc:"2.0",id:xs(),method:"tools/call",params:{name:n,arguments:o}},u=await fetch(this._cfg.url,{method:"POST",headers:{"Content-Type":"application/json",...ME(this._cfg.auth_token)},body:JSON.stringify(l)});if(!u.ok)return{call_id:r,name:n,success:!1,output:null,error:`Worker HTTP ${u.status}`};const c=await u.json().catch(()=>null),f=c==null?void 0:c.result,m=!!(f!=null&&f.isError),g=(Array.isArray(f==null?void 0:f.content)?f.content:[]).find(x=>x&&x.type==="text"&&typeof x.text=="string"),w=(g==null?void 0:g.text)??"";return m?{call_id:r,name:n,success:!1,output:null,error:w||"Tool failed"}:{call_id:r,name:n,success:!0,output:w,error:null}}}class _w{constructor(t,n){Vs(this,"pending",[]);Vs(this,"scheduled",!1);Vs(this,"generation",0);this.schedule=t,this.on_flush=n}push(t){if(this.pending.push(t),this.scheduled)return;this.scheduled=!0;const n=this.generation;this.schedule(()=>{if(n!==this.generation)return;this.scheduled=!1;const r=this.pending;this.pending=[],r.length&&this.on_flush(r)})}reset(){this.generation+=1,this.pending=[],this.scheduled=!1}pending_count(){return this.pending.length}}function pw(e,t=""){const n=String(e.role||"").trim(),r=String(e.automation_id||"").trim();return n==="occurrence"&&r&&r!==e.run_id?r:String(e.parent_run_id||t||"").trim()}function LE(e,t){const n=qn(e.updated_at||e.created_at)??0;return(qn(t.updated_at||t.created_at)??0)-n}function IE(e,t){const n=t.query.trim().toLowerCase(),r=[...e],o={};for(const w of r){const x=String(w.run_id||"").trim();x&&(o[x]=w)}for(const w of e){const x=pw(w);if(String(w.role||"")==="occurrence"&&x&&!o[x]){const j={run_id:x,workflow_id:null,status:"",role:"controller",session_kind:"automation",automation_id:x,updated_at:w.updated_at??null,created_at:w.created_at??null};o[x]=j,r.push(j)}}const l={},u={};for(const w of r){const x=String(w.run_id||"").trim();if(!x)continue;const j=pw(w,t.parent_hint?t.parent_hint(x):"");u[x]=j,j&&(l[j]||(l[j]=[])).push(w)}const c=w=>{const x=String(w.status||"").trim().toLowerCase();return t.filter==="all"?!0:t.filter==="active"?ju(x):t.filter==="waiting"?x==="waiting":t.filter==="terminal"?So(x):t.filter==="failed"?x==="failed":!0},f=w=>{if(!n)return!0;const x=String(w.workflow_id||w.schedule_target_workflow_id||"").trim(),j=x?t.workflow_label_by_id[x]||x:"";return[w.run_id,x,j,w.session_id,w.status,w.session_kind,w.automation_id].join(" ").toLowerCase().includes(n)},m=[];for(const w of r){const x=String(w.run_id||"").trim();if(!x)continue;const j=u[x];(!j||!o[j])&&m.push(x)}const _={},g=w=>{if(t.group_by==="workflow"){const j=String(w.schedule_target_workflow_id||w.workflow_id||"").trim()||"(unknown workflow)";return{key:j,label:t.workflow_label_by_id[j]||j}}if(t.group_by==="session"){const j=String(w.session_id||"").trim()||"(no session)";return{key:j,label:j}}const x=String(w.status||"").trim().toLowerCase()||"unknown";return ju(x)?{key:"active",label:"Active"}:x==="failed"?{key:"failed",label:"Failed"}:So(x)?{key:"finished",label:"Finished"}:{key:x,label:x}};for(const w of m){const x=o[w];if(!x)continue;const j=[...l[w]||[]].sort(LE),b=j.some(C=>c(C)&&f(C));if(!(c(x)&&f(x))&&!b)continue;const N=g(x);_[N.key]||(_[N.key]={key:N.key,label:N.label,rows:[]}),_[N.key].rows.push({run:x,children:j})}return Object.values(_).sort((w,x)=>{const j={active:0,waiting:1,failed:2,finished:3},b=j[w.key]??10,N=j[x.key]??10;return b!==N?b-N:w.label.localeCompare(x.label)})}const OE={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"},PE=[{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 DE(){const[e,t]=p.useState(!0);return s.jsxs("div",{className:"pin-legend",children:[s.jsxs("button",{className:"pin-legend-toggle mono",type:"button",onClick:()=>t(n=>!n),title:"Pin Type Legend",children:[e?"?":"×"," Pin Types"]}),e?null:s.jsxs("div",{className:"pin-legend-content",children:[PE.map(n=>s.jsxs("div",{className:"pin-legend-row",children:[s.jsx("span",{className:"pin-legend-shape",style:{color:OE[n.type]},children:n.shape}),s.jsx("span",{className:"pin-legend-label mono",children:n.label}),s.jsx("span",{className:"pin-legend-desc mono",children:n.description})]},n.type)),s.jsxs("div",{className:"pin-legend-rules mono",children:[s.jsx("strong",{children:"Connection Rules:"}),s.jsxs("ul",{children:[s.jsx("li",{children:"Execution connects to Execution only"}),s.jsx("li",{children:'"Any" type accepts all data types'}),s.jsx("li",{children:"Same types always compatible"}),s.jsx("li",{children:"Array and Object are interchangeable"}),s.jsx("li",{children:'"Tools" is compatible with Array (specialized string[])'})]})]})]})]})}function dn(e){return typeof e=="string"?e:e==null?"":String(e)}function gw(e,t){const n=dn(e).trim();return n.length<=t?n:`${n.slice(0,Math.max(0,t-1))}…`}function cb(e){const t=dn(e==null?void 0:e.targetHandle),n=dn(e==null?void 0:e.sourceHandle);return!!(t==="exec-in"||n==="exec-out"||t.includes("exec")||n.includes("exec"))}function ub(e){if(!e||typeof e!="object")return"";const t=e!=null&&e.data&&typeof e.data=="object"?e.data:{};return dn((t==null?void 0:t.nodeType)||(e==null?void 0:e.type)||"").trim()}function db(e){if(!e||typeof e!="object")return"";const t=e!=null&&e.data&&typeof e.data=="object"?e.data:{},n=(t==null?void 0:t.subflowId)||(t==null?void 0:t.flowId),r=dn(n).trim();if(!r)return"";if(r.includes(":")){const o=r.split(":",2);if(o.length===2&&o[1])return o[1].trim()}return r}function FE(e){const t=dn(e==null?void 0:e.entryNode).trim();if(t)return t;const n=Array.isArray(e==null?void 0:e.nodes)?e.nodes:[];for(const r of n)if(ub(r)==="on_flow_start"){const o=dn(r==null?void 0:r.id).trim();if(o)return o}return""}function z_(e){const t=e!=null&&e.position&&typeof e.position=="object"?e.position:{},n=typeof t.x=="number"?t.x:0,r=typeof t.y=="number"?t.y:0;return{x:n,y:r}}function Gd(e,t){const n=dn(e).trim(),r=dn(t).trim();return r?n?`${n}::${r}`:r:""}function zE(e){const t=e.root&&typeof e.root=="object"?e.root:{};if(!e.expand_subflows)return t;const n=[],r=[],o=new Set,l=(u,c,f,m)=>{if(!u||typeof u!="object"||n.length>=e.max_nodes||r.length>=e.max_edges)return;const _=Array.isArray(u.nodes)?u.nodes:[],g=Array.isArray(u.edges)?u.edges:[];for(const w of _){const x=dn(w==null?void 0:w.id).trim();if(!x)continue;const j=Gd(c,x);if(!j||o.has(j))continue;const b=z_(w),N={...w,id:j,position:{x:b.x+f.x,y:b.y+f.y}};if(n.push(N),o.add(j),n.length>=e.max_nodes)break}for(const w of g){if(!cb(w))continue;const x=dn(w==null?void 0:w.source).trim(),j=dn(w==null?void 0:w.target).trim();if(!x||!j)continue;const b=Gd(c,x),N=Gd(c,j);if(!b||!N)continue;const C=dn(w==null?void 0:w.id).trim(),E=C?`${b}->${N}::${C}`:`${b}->${N}`;if(r.push({...w,id:E,source:b,target:N}),r.length>=e.max_edges)break}if(!(m>=e.max_depth))for(const w of _){if(n.length>=e.max_nodes||r.length>=e.max_edges)return;if(ub(w)!=="subflow")continue;const x=db(w);if(!x)continue;const j=e.flow_by_id[x];if(!j||typeof j!="object")continue;const b=Gd(c,dn(w==null?void 0:w.id));if(!b)continue;const N=FE(j);if(!N)continue;const E=(Array.isArray(j.nodes)?j.nodes:[]).find(re=>dn(re==null?void 0:re.id).trim()===N)||null;if(!E)continue;const T=z_(w),I=z_(E),J={x:T.x+f.x+240-I.x,y:T.y+f.y+0-I.y},Y=Gd(b,N);r.push({id:`${b}=>${Y}`,source:b,target:Y,sourceHandle:"exec-out",targetHandle:"exec-in"}),l(j,b,J,m+1)}};return l(t,"",{x:0,y:0},0),{...t,id:dn(t.id),nodes:n,edges:r}}function BE(e){const t=dn(e).trim().toLowerCase();return t?!!(t.startsWith("literal")||t.includes("literal")||t==="concat"||t==="join"||t==="cast"||t==="parse_json"||t==="stringify_json"||t==="break_object"||t==="get_property"||t==="set_property"||t.includes("get_property")||t.includes("set_property")||t==="get_variable"||t==="set_variable"||t.includes("get_variable")||t.includes("set_variable")||t==="json_schema"):!1}function UE(e){const t=e.nodes.filter(l=>e.keep_id(l.id)),n=new Set(t.map(l=>l.id)),r={};for(const l of e.edges)r[l.source]||(r[l.source]=[]),r[l.source].push(l.target);const o=new Map;for(const l of t){const u=new Set,c=(r[l.id]||[]).slice();for(;c.length;){const f=c.pop();if(!f||u.has(f))continue;if(u.add(f),n.has(f)){const _=`${l.id}->${f}`;o.has(_)||o.set(_,{id:_,source:l.id,target:f});continue}const m=r[f]||[];for(const _ of m)u.has(_)||c.push(_);if(o.size>=e.max_edges)break}if(o.size>=e.max_edges)break}return{nodes:t,edges:Array.from(o.values())}}function yw(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 WE(e){const t=typeof e.now_ms=="number"?e.now_ms:Date.now(),n=e.flow,r=dn(e.active_node_id),o=e.recent_nodes||{},l=e.visited_nodes||{},u=e.highlight_path===!0,c=typeof e.vertical_compact=="number"?Math.max(.4,Math.min(1,e.vertical_compact)):.78,{nodes:f,edges:m,bounds:_}=p.useMemo(()=>{const P=zE({root:n||{},flow_by_id:e.flow_by_id||{},expand_subflows:e.expand_subflows===!0,max_depth:3,max_nodes:700,max_edges:900}),F=Array.isArray(P.nodes)?P.nodes:[],G=Array.isArray(P.edges)?P.edges:[];let R=[];for(const je of F){const Re=dn(je==null?void 0:je.id).trim();if(!Re)continue;const ht=je!=null&&je.position&&typeof je.position=="object"?je.position:{},xe=typeof ht.x=="number"?ht.x:0,Ie=typeof ht.y=="number"?ht.y:0,qe=je!=null&&je.data&&typeof je.data=="object"?je.data:{},zt=dn((qe==null?void 0:qe.label)||(je==null?void 0:je.label)||Re)||Re,en=dn((qe==null?void 0:qe.nodeType)||(je==null?void 0:je.type)||"unknown")||"unknown",bn=dn((qe==null?void 0:qe.headerColor)||(je==null?void 0:je.headerColor)||"")||"",Wt=qe!=null&&qe.eventConfig&&typeof qe.eventConfig=="object"?qe.eventConfig:null,It=Wt&&typeof Wt.schedule=="string"?dn(Wt.schedule).trim():"",Sn=Wt&&typeof Wt.recurrent=="boolean"?!!Wt.recurrent:void 0,ns=en==="subflow"?db(je):"",Ot=It||Sn!==void 0||ns?{schedule:It||void 0,recurrent:Sn,subflow_id:ns||void 0}:void 0;R.push({id:Re,x:xe,y:Ie,label:zt,type:en,color:bn,meta:Ot})}const Z={};for(const je of R)Z[je.id]=je;let X=[];for(const je of G){if(!cb(je))continue;const Re=dn(je==null?void 0:je.source).trim(),ht=dn(je==null?void 0:je.target).trim();!Re||!ht||X.push({id:dn((je==null?void 0:je.id)||`${Re}->${ht}`),source:Re,target:ht})}const ie=new Set(R.map(je=>je.id));if(X=X.filter(je=>ie.has(je.source)&&ie.has(je.target)),e.simplify===!0){const Re=UE({nodes:R,edges:X,keep_id:ht=>{if(r&&ht===r)return!0;const xe=Z[ht];if(!xe)return!1;const Ie=dn(xe.type).trim().toLowerCase();return Ie==="on_flow_start"||Ie==="on_flow_end"||Ie==="subflow"?!0:!BE(Ie)},max_edges:900});R=Re.nodes,X=Re.edges}if(e.prefer_vertical===!0&&R.length>=2){const je=R.map(qe=>qe.x),Re=R.map(qe=>qe.y),ht=Math.max(...je)-Math.min(...je),xe=Math.max(...Re)-Math.min(...Re);ht>=xe&&(R=R.map(qe=>({...qe,x:qe.y,y:qe.x})));const Ie=Math.min(...R.map(qe=>qe.y));R=R.map(qe=>({...qe,y:Ie+(qe.y-Ie)*c}))}const ne={};for(const je of R)ne[je.id]=je;const ye=160,he=56,pe=ye/2,Ne=he/2;let Ue=0,We=0,pt=0,Fe=0;R.length&&(Ue=Math.min(...R.map(je=>je.x)),We=Math.min(...R.map(je=>je.y)),pt=Math.max(...R.map(je=>je.x+ye)),Fe=Math.max(...R.map(je=>je.y+he)));let tt=0;if(X.length){const je=new Set(X.map(Re=>`${Re.source}->${Re.target}`));for(const Re of X){if(!je.has(`${Re.target}->${Re.source}`))continue;const ht=ne[Re.source],xe=ne[Re.target];if(!ht||!xe)continue;const Ie=ht.x+pe,qe=ht.y+Ne,zt=xe.x+pe,en=xe.y+Ne,bn=Math.max(1,Math.hypot(zt-Ie,en-qe)),Wt=Math.max(28,Math.min(72,bn*.14)),It=Math.min(200,Wt*3.5);It>tt&&(tt=It)}}const lt=60+tt,Ke={x:Ue-lt,y:We-lt,w:pt-Ue+lt*2,h:Fe-We+lt*2,node_w:ye,node_h:he};return{nodes:R,edges:X,bounds:Ke}},[n,e.flow_by_id,e.expand_subflows,e.simplify,e.prefer_vertical,r,c]);if(!n)return s.jsx("div",{className:"graph_empty mono",children:"(no graph loaded)"});const g=p.useRef(null),[w,x]=p.useState(()=>({x:_.x,y:_.y,w:_.w,h:_.h})),j=p.useRef(w);j.current=w,p.useEffect(()=>{x({x:_.x,y:_.y,w:_.w,h:_.h})},[_.x,_.y,_.w,_.h]);const b=p.useRef(new Map),N=p.useRef(null),C=`${w.x} ${w.y} ${w.w} ${w.h}`,E={};for(const P of f)E[P.id]=P;const T=P=>{let F=dn(P).trim();if(!F)return"";if(E[F])return F;for(;F.includes("::");)if(F=F.slice(0,Math.max(0,F.lastIndexOf("::"))),E[F])return F;return""},I=T(r),K={};for(const[P,F]of Object.entries(o)){if(typeof F!="number")continue;const G=T(P);G&&(K[G]=Math.max(K[G]||0,F))}const U={};if(u)for(const[P,F]of Object.entries(l)){if(typeof F!="number")continue;const G=T(P);G&&(U[G]=typeof U[G]=="number"?Math.min(U[G],F):F)}const J=dn(e.schedule_next_in).trim(),Y=dn(e.schedule_interval).trim(),re=e.node_last_ms&&typeof e.node_last_ms=="object"?e.node_last_ms:{},ce=P=>{try{const F=new Date(P),G=String(F.getHours()).padStart(2,"0"),R=String(F.getMinutes()).padStart(2,"0");return`${G}:${R}`}catch{return""}},fe=(P,F)=>{var X,ie;const G=dn((X=P.meta)==null?void 0:X.schedule).trim();if(!(((ie=P.meta)==null?void 0:ie.recurrent)===!0))return F&&J?`next ${J}`:G&&G.length<=12&&!G.includes("T")?`in ${G}`:"scheduled";const Z=G||Y;return Z?F&&J?`${Z} • next ${J}`:`every ${Z}`:F&&J?`next ${J}`:"scheduled"},W=P=>{var ye;const F=dn((ye=P.meta)==null?void 0:ye.subflow_id).trim(),G=F&&e.flow_by_id?e.flow_by_id[F]:null,Z=dn(G==null?void 0:G.name).trim()||F||P.label||P.id,X=typeof re[P.id]=="number"?Number(re[P.id]):null,ie=X!==null?ce(X):"",ne=ie?`last ${ie}`:"subflow";return{label:Z,sub:ne}},O=(P,F,G)=>{const R=G||j.current,Z=g.current;if(!Z)return{x:P,y:F};const X=Z.getBoundingClientRect(),ie=X.width>0?(P-X.left)/X.width:0,ne=X.height>0?(F-X.top)/X.height:0;return{x:R.x+ie*R.w,y:R.y+ne*R.h}},$=(P,F,G)=>{const R=G||j.current,Z=Math.max(.12,Math.min(8,F)),X=R.w*Z,ie=R.h*Z,ne=R.w>0?(P.x-R.x)/R.w:.5,ye=R.h>0?(P.y-R.y)/R.h:.5,he=P.x-ne*X,pe=P.y-ye*ie;x(yw({x:he,y:pe,w:X,h:ie},_))},z=(P,F,G)=>{const R=G||j.current,Z=g.current;if(!Z)return;const X=Z.getBoundingClientRect(),ie=.88,ne=X.width>0?P/X.width*R.w*ie:0,ye=X.height>0?F/X.height*R.h*ie:0;x(he=>yw({x:(G||he).x-ne,y:(G||he).y-ye,w:(G||he).w,h:(G||he).h},_))},A=p.useMemo(()=>{const P=new Set;for(const F of m)P.add(`${F.source}->${F.target}`);return P},[m]),ee=(P,F,G,R)=>{const Z=_.node_w,X=_.node_h,ie=Math.abs(G),ne=Math.abs(R);if(ie<1e-6&&ne<1e-6)return{x:P,y:F};const ye=ie>1e-6?Z/2/ie:Number.POSITIVE_INFINITY,he=ne>1e-6?X/2/ne:Number.POSITIVE_INFINITY,pe=Math.min(ye,he);return{x:P+G*pe,y:F+R*pe}};return s.jsxs("div",{className:"graph_wrap",children:[s.jsxs("div",{className:"graph_corner",children:[s.jsxs("div",{className:"graph_corner_buttons",children:[s.jsx("button",{className:"btn graph_corner_btn",type:"button",onClick:()=>x({x:_.x,y:_.y,w:_.w,h:_.h}),title:"Recenter",children:"⤢"}),s.jsx("button",{className:"btn graph_corner_btn",type:"button",onClick:()=>{const P=g.current;if(!P)return;const F=P.getBoundingClientRect(),G=O(F.left+F.width/2,F.top+F.height/2);$(G,.84)},title:"Zoom in",children:"+"}),s.jsx("button",{className:"btn graph_corner_btn",type:"button",onClick:()=>{const P=g.current;if(!P)return;const F=P.getBoundingClientRect(),G=O(F.left+F.width/2,F.top+F.height/2);$(G,1.18)},title:"Zoom out",children:"−"})]}),s.jsx(DE,{})]}),s.jsxs("svg",{ref:g,className:"graph_svg",viewBox:C,role:"img","aria-label":"Workflow execution graph",onWheel:P=>{P.preventDefault();const F=O(P.clientX,P.clientY),G=typeof P.deltaY=="number"?P.deltaY:0,R=typeof P.deltaMode=="number"?Number(P.deltaMode):0,Z=R===1?G*24:R===2?G*800:G,X=45e-5*1.15*1.1;let ie=Math.exp(Z*X);ie=Math.max(.86,Math.min(1.16,ie)),$(F,ie)},onPointerDown:P=>{var G,R;(R=(G=P.currentTarget).setPointerCapture)==null||R.call(G,P.pointerId),b.current.set(P.pointerId,{x:P.clientX,y:P.clientY});const F=Array.from(b.current.values());if(F.length===1)N.current={mode:"pan",start_view:j.current,start_client:{x:P.clientX,y:P.clientY},start_dist:0,anchor_svg:{x:0,y:0}};else if(F.length>=2){const Z=F[0],X=F[1],ie=Z.x-X.x,ne=Z.y-X.y,ye=Math.max(1,Math.hypot(ie,ne)),he={x:(Z.x+X.x)/2,y:(Z.y+X.y)/2},pe=j.current;N.current={mode:"pinch",start_view:pe,start_client:he,start_dist:ye,anchor_svg:O(he.x,he.y,pe)}}},onPointerMove:P=>{if(!b.current.has(P.pointerId))return;b.current.set(P.pointerId,{x:P.clientX,y:P.clientY});const F=N.current;if(!F)return;const G=Array.from(b.current.values());if(F.mode==="pan"&&G.length===1){const R=P.clientX-F.start_client.x,Z=P.clientY-F.start_client.y;z(R,Z,F.start_view)}else if(F.mode==="pinch"&&G.length>=2){const R=G[0],Z=G[1],X=R.x-Z.x,ie=R.y-Z.y,ne=Math.max(1,Math.hypot(X,ie)),ye=F.start_dist/ne;$(F.anchor_svg,ye,F.start_view)}},onPointerUp:P=>{b.current.delete(P.pointerId),b.current.size===0&&(N.current=null)},onPointerCancel:P=>{b.current.delete(P.pointerId),b.current.size===0&&(N.current=null)},children:[s.jsxs("defs",{children:[s.jsx("marker",{id:"arrow",viewBox:"0 0 10 10",refX:"9",refY:"5",markerWidth:"8",markerHeight:"8",orient:"auto-start-reverse",children:s.jsx("path",{d:"M 0 0 L 10 5 L 0 10 z",fill:"rgba(148,163,184,0.55)"})}),s.jsxs("filter",{id:"glow",children:[s.jsx("feGaussianBlur",{stdDeviation:"3",result:"coloredBlur"}),s.jsxs("feMerge",{children:[s.jsx("feMergeNode",{in:"coloredBlur"}),s.jsx("feMergeNode",{in:"SourceGraphic"})]})]})]}),m.map(P=>{const F=E[P.source],G=E[P.target];if(!F||!G)return null;const R=F.x+_.node_w/2,Z=F.y+_.node_h/2,X=G.x+_.node_w/2,ie=G.y+_.node_h/2,ne=X-R,ye=ie-Z,he=ee(R,Z,ne,ye),pe=ee(X,ie,-ne,-ye),Ne=P.source!==P.target&&A.has(`${P.target}->${P.source}`),Ue=Math.max(1,Math.hypot(ne,ye)),We=-ye/Ue,pt=ne/Ue,Fe=String(P.source)<String(P.target)?1:-1,lt=Math.abs(ne)>=Math.abs(ye)?ne>=0:ye>=0,Ke=!Ne||lt,je=Math.max(28,Math.min(72,Ue*.14)),Re=Math.min(200,je*3.5),ht=Ne&&!Ke?Re*Fe:0,xe=(he.x+pe.x)/2+We*ht,Ie=(he.y+pe.y)/2+pt*ht,qe=Ne&&!Ke?`M ${he.x} ${he.y} Q ${xe} ${Ie} ${pe.x} ${pe.y}`:`M ${he.x} ${he.y} L ${pe.x} ${pe.y}`,zt=u&&U&&U[P.source]!==void 0&&U[P.target]!==void 0;return s.jsx("path",{d:qe,className:`graph_edge ${zt?"visited":""}`,markerEnd:"url(#arrow)",fill:"none"},P.id)}),f.map(P=>{const G=(typeof K[P.id]=="number"?K[P.id]:0)>t,R=I&&P.id===I,Z=u&&U&&U[P.id]!==void 0,X=`graph_node ${R?"active":G?"recent":""} ${Z?"visited":""}`,ie=P.color||"rgba(255,255,255,0.16)";let ne=P.label||P.id,ye=P.type;if(P.type==="on_schedule")ye=fe(P,!!R);else if(P.type==="subflow"){const Ne=W(P);ne=Ne.label,ye=Ne.sub}const he=gw(ne,22),pe=gw(ye,22);return s.jsxs("g",{className:X,transform:`translate(${P.x}, ${P.y})`,children:[s.jsx("rect",{className:"graph_node_bg",width:_.node_w,height:_.node_h,rx:12,ry:12}),s.jsx("rect",{className:"graph_node_bar",width:_.node_w,height:6,rx:12,ry:12,fill:ie}),s.jsx("text",{className:"graph_node_label",x:12,y:28,children:he}),s.jsx("text",{className:"graph_node_type",x:12,y:46,children:pe}),P.type==="on_schedule"?s.jsx("text",{className:"graph_node_icon",x:_.node_w-18,y:18,children:"⏰"}):null]},P.id)})]})]})}function Ks(e){if(typeof e=="string"||typeof e=="number")return""+e;let t="";if(Array.isArray(e))for(let n=0,r;n<e.length;n++)(r=Ks(e[n]))!==""&&(t+=(t&&" ")+r);else for(let n in e)e[n]&&(t+=(t&&" ")+n);return t}var B_={exports:{}},U_={},W_={exports:{}},q_={};/**
116
- * @license React
117
- * use-sync-external-store-shim.production.js
118
- *
119
- * Copyright (c) Meta Platforms, Inc. and affiliates.
120
- *
121
- * This source code is licensed under the MIT license found in the
122
- * LICENSE file in the root directory of this source tree.
123
- */var ww;function qE(){if(ww)return q_;ww=1;var e=Cf();function t(g,w){return g===w&&(g!==0||1/g===1/w)||g!==g&&w!==w}var n=typeof Object.is=="function"?Object.is:t,r=e.useState,o=e.useEffect,l=e.useLayoutEffect,u=e.useDebugValue;function c(g,w){var x=w(),j=r({inst:{value:x,getSnapshot:w}}),b=j[0].inst,N=j[1];return l(function(){b.value=x,b.getSnapshot=w,f(b)&&N({inst:b})},[g,x,w]),o(function(){return f(b)&&N({inst:b}),g(function(){f(b)&&N({inst:b})})},[g]),u(x),x}function f(g){var w=g.getSnapshot;g=g.value;try{var x=w();return!n(g,x)}catch{return!0}}function m(g,w){return w()}var _=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?m:c;return q_.useSyncExternalStore=e.useSyncExternalStore!==void 0?e.useSyncExternalStore:_,q_}var vw;function HE(){return vw||(vw=1,W_.exports=qE()),W_.exports}/**
124
- * @license React
125
- * use-sync-external-store-shim/with-selector.production.js
126
- *
127
- * Copyright (c) Meta Platforms, Inc. and affiliates.
128
- *
129
- * This source code is licensed under the MIT license found in the
130
- * LICENSE file in the root directory of this source tree.
131
- */var xw;function VE(){if(xw)return U_;xw=1;var e=Cf(),t=HE();function n(m,_){return m===_&&(m!==0||1/m===1/_)||m!==m&&_!==_}var r=typeof Object.is=="function"?Object.is:n,o=t.useSyncExternalStore,l=e.useRef,u=e.useEffect,c=e.useMemo,f=e.useDebugValue;return U_.useSyncExternalStoreWithSelector=function(m,_,g,w,x){var j=l(null);if(j.current===null){var b={hasValue:!1,value:null};j.current=b}else b=j.current;j=c(function(){function C(U){if(!E){if(E=!0,T=U,U=w(U),x!==void 0&&b.hasValue){var J=b.value;if(x(J,U))return I=J}return I=U}if(J=I,r(T,U))return J;var Y=w(U);return x!==void 0&&x(J,Y)?(T=U,J):(T=U,I=Y)}var E=!1,T,I,K=g===void 0?null:g;return[function(){return C(_())},K===null?void 0:function(){return C(K())}]},[_,g,w,x]);var N=o(m,j[0],j[1]);return u(function(){b.hasValue=!0,b.value=N},[N]),f(N),N},U_}var bw;function GE(){return bw||(bw=1,B_.exports=VE()),B_.exports}var KE=GE();const YE=og(KE),JE={},kw=e=>{let t;const n=new Set,r=(_,g)=>{const w=typeof _=="function"?_(t):_;if(!Object.is(w,t)){const x=t;t=g??(typeof w!="object"||w===null)?w:Object.assign({},t,w),n.forEach(j=>j(t,x))}},o=()=>t,f={setState:r,getState:o,getInitialState:()=>m,subscribe:_=>(n.add(_),()=>n.delete(_)),destroy:()=>{(JE?"production":void 0)!=="production"&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),n.clear()}},m=t=e(r,o,f);return f},XE=e=>e?kw(e):kw,{useDebugValue:ZE}=ve,{useSyncExternalStoreWithSelector:QE}=YE,eA=e=>e;function fb(e,t=eA,n){const r=QE(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return ZE(r),r}const jw=(e,t)=>{const n=XE(e),r=(o,l=t)=>fb(n,o,l);return Object.assign(r,n),r},tA=(e,t)=>e?jw(e,t):jw;function Os(e,t){if(Object.is(e,t))return!0;if(typeof e!="object"||e===null||typeof t!="object"||t===null)return!1;if(e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(const[r,o]of e)if(!Object.is(o,t.get(r)))return!1;return!0}if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(const r of e)if(!t.has(r))return!1;return!0}const n=Object.keys(e);if(n.length!==Object.keys(t).length)return!1;for(const r of n)if(!Object.prototype.hasOwnProperty.call(t,r)||!Object.is(e[r],t[r]))return!1;return!0}var nA={value:()=>{}};function Rm(){for(var e=0,t=arguments.length,n={},r;e<t;++e){if(!(r=arguments[e]+"")||r in n||/[\s.]/.test(r))throw new Error("illegal type: "+r);n[r]=[]}return new em(n)}function em(e){this._=e}function sA(e,t){return e.trim().split(/^|\s+/).map(function(n){var r="",o=n.indexOf(".");if(o>=0&&(r=n.slice(o+1),n=n.slice(0,o)),n&&!t.hasOwnProperty(n))throw new Error("unknown type: "+n);return{type:n,name:r}})}em.prototype=Rm.prototype={constructor:em,on:function(e,t){var n=this._,r=sA(e+"",n),o,l=-1,u=r.length;if(arguments.length<2){for(;++l<u;)if((o=(e=r[l]).type)&&(o=rA(n[o],e.name)))return o;return}if(t!=null&&typeof t!="function")throw new Error("invalid callback: "+t);for(;++l<u;)if(o=(e=r[l]).type)n[o]=Sw(n[o],e.name,t);else if(t==null)for(o in n)n[o]=Sw(n[o],e.name,null);return this},copy:function(){var e={},t=this._;for(var n in t)e[n]=t[n].slice();return new em(e)},call:function(e,t){if((o=arguments.length-2)>0)for(var n=new Array(o),r=0,o,l;r<o;++r)n[r]=arguments[r+2];if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(l=this._[e],r=0,o=l.length;r<o;++r)l[r].value.apply(t,n)},apply:function(e,t,n){if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(var r=this._[e],o=0,l=r.length;o<l;++o)r[o].value.apply(t,n)}};function rA(e,t){for(var n=0,r=e.length,o;n<r;++n)if((o=e[n]).name===t)return o.value}function Sw(e,t,n){for(var r=0,o=e.length;r<o;++r)if(e[r].name===t){e[r]=nA,e=e.slice(0,r).concat(e.slice(r+1));break}return n!=null&&e.push({name:t,value:n}),e}var Dp="http://www.w3.org/1999/xhtml";const Nw={svg:"http://www.w3.org/2000/svg",xhtml:Dp,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function Lm(e){var t=e+="",n=t.indexOf(":");return n>=0&&(t=e.slice(0,n))!=="xmlns"&&(e=e.slice(n+1)),Nw.hasOwnProperty(t)?{space:Nw[t],local:e}:e}function iA(e){return function(){var t=this.ownerDocument,n=this.namespaceURI;return n===Dp&&t.documentElement.namespaceURI===Dp?t.createElement(e):t.createElementNS(n,e)}}function oA(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function hb(e){var t=Lm(e);return(t.local?oA:iA)(t)}function aA(){}function Cg(e){return e==null?aA:function(){return this.querySelector(e)}}function lA(e){typeof e!="function"&&(e=Cg(e));for(var t=this._groups,n=t.length,r=new Array(n),o=0;o<n;++o)for(var l=t[o],u=l.length,c=r[o]=new Array(u),f,m,_=0;_<u;++_)(f=l[_])&&(m=e.call(f,f.__data__,_,l))&&("__data__"in f&&(m.__data__=f.__data__),c[_]=m);return new ri(r,this._parents)}function cA(e){return e==null?[]:Array.isArray(e)?e:Array.from(e)}function uA(){return[]}function mb(e){return e==null?uA:function(){return this.querySelectorAll(e)}}function dA(e){return function(){return cA(e.apply(this,arguments))}}function fA(e){typeof e=="function"?e=dA(e):e=mb(e);for(var t=this._groups,n=t.length,r=[],o=[],l=0;l<n;++l)for(var u=t[l],c=u.length,f,m=0;m<c;++m)(f=u[m])&&(r.push(e.call(f,f.__data__,m,u)),o.push(f));return new ri(r,o)}function _b(e){return function(){return this.matches(e)}}function pb(e){return function(t){return t.matches(e)}}var hA=Array.prototype.find;function mA(e){return function(){return hA.call(this.children,e)}}function _A(){return this.firstElementChild}function pA(e){return this.select(e==null?_A:mA(typeof e=="function"?e:pb(e)))}var gA=Array.prototype.filter;function yA(){return Array.from(this.children)}function wA(e){return function(){return gA.call(this.children,e)}}function vA(e){return this.selectAll(e==null?yA:wA(typeof e=="function"?e:pb(e)))}function xA(e){typeof e!="function"&&(e=_b(e));for(var t=this._groups,n=t.length,r=new Array(n),o=0;o<n;++o)for(var l=t[o],u=l.length,c=r[o]=[],f,m=0;m<u;++m)(f=l[m])&&e.call(f,f.__data__,m,l)&&c.push(f);return new ri(r,this._parents)}function gb(e){return new Array(e.length)}function bA(){return new ri(this._enter||this._groups.map(gb),this._parents)}function _m(e,t){this.ownerDocument=e.ownerDocument,this.namespaceURI=e.namespaceURI,this._next=null,this._parent=e,this.__data__=t}_m.prototype={constructor:_m,appendChild:function(e){return this._parent.insertBefore(e,this._next)},insertBefore:function(e,t){return this._parent.insertBefore(e,t)},querySelector:function(e){return this._parent.querySelector(e)},querySelectorAll:function(e){return this._parent.querySelectorAll(e)}};function kA(e){return function(){return e}}function jA(e,t,n,r,o,l){for(var u=0,c,f=t.length,m=l.length;u<m;++u)(c=t[u])?(c.__data__=l[u],r[u]=c):n[u]=new _m(e,l[u]);for(;u<f;++u)(c=t[u])&&(o[u]=c)}function SA(e,t,n,r,o,l,u){var c,f,m=new Map,_=t.length,g=l.length,w=new Array(_),x;for(c=0;c<_;++c)(f=t[c])&&(w[c]=x=u.call(f,f.__data__,c,t)+"",m.has(x)?o[c]=f:m.set(x,f));for(c=0;c<g;++c)x=u.call(e,l[c],c,l)+"",(f=m.get(x))?(r[c]=f,f.__data__=l[c],m.delete(x)):n[c]=new _m(e,l[c]);for(c=0;c<_;++c)(f=t[c])&&m.get(w[c])===f&&(o[c]=f)}function NA(e){return e.__data__}function CA(e,t){if(!arguments.length)return Array.from(this,NA);var n=t?SA:jA,r=this._parents,o=this._groups;typeof e!="function"&&(e=kA(e));for(var l=o.length,u=new Array(l),c=new Array(l),f=new Array(l),m=0;m<l;++m){var _=r[m],g=o[m],w=g.length,x=EA(e.call(_,_&&_.__data__,m,r)),j=x.length,b=c[m]=new Array(j),N=u[m]=new Array(j),C=f[m]=new Array(w);n(_,g,b,N,C,x,t);for(var E=0,T=0,I,K;E<j;++E)if(I=b[E]){for(E>=T&&(T=E+1);!(K=N[T])&&++T<j;);I._next=K||null}}return u=new ri(u,r),u._enter=c,u._exit=f,u}function EA(e){return typeof e=="object"&&"length"in e?e:Array.from(e)}function AA(){return new ri(this._exit||this._groups.map(gb),this._parents)}function $A(e,t,n){var r=this.enter(),o=this,l=this.exit();return typeof e=="function"?(r=e(r),r&&(r=r.selection())):r=r.append(e+""),t!=null&&(o=t(o),o&&(o=o.selection())),n==null?l.remove():n(l),r&&o?r.merge(o).order():o}function TA(e){for(var t=e.selection?e.selection():e,n=this._groups,r=t._groups,o=n.length,l=r.length,u=Math.min(o,l),c=new Array(o),f=0;f<u;++f)for(var m=n[f],_=r[f],g=m.length,w=c[f]=new Array(g),x,j=0;j<g;++j)(x=m[j]||_[j])&&(w[j]=x);for(;f<o;++f)c[f]=n[f];return new ri(c,this._parents)}function MA(){for(var e=this._groups,t=-1,n=e.length;++t<n;)for(var r=e[t],o=r.length-1,l=r[o],u;--o>=0;)(u=r[o])&&(l&&u.compareDocumentPosition(l)^4&&l.parentNode.insertBefore(u,l),l=u);return this}function RA(e){e||(e=LA);function t(g,w){return g&&w?e(g.__data__,w.__data__):!g-!w}for(var n=this._groups,r=n.length,o=new Array(r),l=0;l<r;++l){for(var u=n[l],c=u.length,f=o[l]=new Array(c),m,_=0;_<c;++_)(m=u[_])&&(f[_]=m);f.sort(t)}return new ri(o,this._parents).order()}function LA(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}function IA(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this}function OA(){return Array.from(this)}function PA(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var r=e[t],o=0,l=r.length;o<l;++o){var u=r[o];if(u)return u}return null}function DA(){let e=0;for(const t of this)++e;return e}function FA(){return!this.node()}function zA(e){for(var t=this._groups,n=0,r=t.length;n<r;++n)for(var o=t[n],l=0,u=o.length,c;l<u;++l)(c=o[l])&&e.call(c,c.__data__,l,o);return this}function BA(e){return function(){this.removeAttribute(e)}}function UA(e){return function(){this.removeAttributeNS(e.space,e.local)}}function WA(e,t){return function(){this.setAttribute(e,t)}}function qA(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function HA(e,t){return function(){var n=t.apply(this,arguments);n==null?this.removeAttribute(e):this.setAttribute(e,n)}}function VA(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 GA(e,t){var n=Lm(e);if(arguments.length<2){var r=this.node();return n.local?r.getAttributeNS(n.space,n.local):r.getAttribute(n)}return this.each((t==null?n.local?UA:BA:typeof t=="function"?n.local?VA:HA:n.local?qA:WA)(n,t))}function yb(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function KA(e){return function(){this.style.removeProperty(e)}}function YA(e,t,n){return function(){this.style.setProperty(e,t,n)}}function JA(e,t,n){return function(){var r=t.apply(this,arguments);r==null?this.style.removeProperty(e):this.style.setProperty(e,r,n)}}function XA(e,t,n){return arguments.length>1?this.each((t==null?KA:typeof t=="function"?JA:YA)(e,t,n??"")):Nu(this.node(),e)}function Nu(e,t){return e.style.getPropertyValue(t)||yb(e).getComputedStyle(e,null).getPropertyValue(t)}function ZA(e){return function(){delete this[e]}}function QA(e,t){return function(){this[e]=t}}function e$(e,t){return function(){var n=t.apply(this,arguments);n==null?delete this[e]:this[e]=n}}function t$(e,t){return arguments.length>1?this.each((t==null?ZA:typeof t=="function"?e$:QA)(e,t)):this.node()[e]}function wb(e){return e.trim().split(/^|\s+/)}function Eg(e){return e.classList||new vb(e)}function vb(e){this._node=e,this._names=wb(e.getAttribute("class")||"")}vb.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 xb(e,t){for(var n=Eg(e),r=-1,o=t.length;++r<o;)n.add(t[r])}function bb(e,t){for(var n=Eg(e),r=-1,o=t.length;++r<o;)n.remove(t[r])}function n$(e){return function(){xb(this,e)}}function s$(e){return function(){bb(this,e)}}function r$(e,t){return function(){(t.apply(this,arguments)?xb:bb)(this,e)}}function i$(e,t){var n=wb(e+"");if(arguments.length<2){for(var r=Eg(this.node()),o=-1,l=n.length;++o<l;)if(!r.contains(n[o]))return!1;return!0}return this.each((typeof t=="function"?r$:t?n$:s$)(n,t))}function o$(){this.textContent=""}function a$(e){return function(){this.textContent=e}}function l$(e){return function(){var t=e.apply(this,arguments);this.textContent=t??""}}function c$(e){return arguments.length?this.each(e==null?o$:(typeof e=="function"?l$:a$)(e)):this.node().textContent}function u$(){this.innerHTML=""}function d$(e){return function(){this.innerHTML=e}}function f$(e){return function(){var t=e.apply(this,arguments);this.innerHTML=t??""}}function h$(e){return arguments.length?this.each(e==null?u$:(typeof e=="function"?f$:d$)(e)):this.node().innerHTML}function m$(){this.nextSibling&&this.parentNode.appendChild(this)}function _$(){return this.each(m$)}function p$(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function g$(){return this.each(p$)}function y$(e){var t=typeof e=="function"?e:hb(e);return this.select(function(){return this.appendChild(t.apply(this,arguments))})}function w$(){return null}function v$(e,t){var n=typeof e=="function"?e:hb(e),r=t==null?w$:typeof t=="function"?t:Cg(t);return this.select(function(){return this.insertBefore(n.apply(this,arguments),r.apply(this,arguments)||null)})}function x$(){var e=this.parentNode;e&&e.removeChild(this)}function b$(){return this.each(x$)}function k$(){var e=this.cloneNode(!1),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function j$(){var e=this.cloneNode(!0),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function S$(e){return this.select(e?j$:k$)}function N$(e){return arguments.length?this.property("__data__",e):this.node().__data__}function C$(e){return function(t){e.call(this,t,this.__data__)}}function E$(e){return e.trim().split(/^|\s+/).map(function(t){var n="",r=t.indexOf(".");return r>=0&&(n=t.slice(r+1),t=t.slice(0,r)),{type:t,name:n}})}function A$(e){return function(){var t=this.__on;if(t){for(var n=0,r=-1,o=t.length,l;n<o;++n)l=t[n],(!e.type||l.type===e.type)&&l.name===e.name?this.removeEventListener(l.type,l.listener,l.options):t[++r]=l;++r?t.length=r:delete this.__on}}}function $$(e,t,n){return function(){var r=this.__on,o,l=C$(t);if(r){for(var u=0,c=r.length;u<c;++u)if((o=r[u]).type===e.type&&o.name===e.name){this.removeEventListener(o.type,o.listener,o.options),this.addEventListener(o.type,o.listener=l,o.options=n),o.value=t;return}}this.addEventListener(e.type,l,n),o={type:e.type,name:e.name,value:t,listener:l,options:n},r?r.push(o):this.__on=[o]}}function T$(e,t,n){var r=E$(e+""),o,l=r.length,u;if(arguments.length<2){var c=this.node().__on;if(c){for(var f=0,m=c.length,_;f<m;++f)for(o=0,_=c[f];o<l;++o)if((u=r[o]).type===_.type&&u.name===_.name)return _.value}return}for(c=t?$$:A$,o=0;o<l;++o)this.each(c(r[o],t,n));return this}function kb(e,t,n){var r=yb(e),o=r.CustomEvent;typeof o=="function"?o=new o(t,n):(o=r.document.createEvent("Event"),n?(o.initEvent(t,n.bubbles,n.cancelable),o.detail=n.detail):o.initEvent(t,!1,!1)),e.dispatchEvent(o)}function M$(e,t){return function(){return kb(this,e,t)}}function R$(e,t){return function(){return kb(this,e,t.apply(this,arguments))}}function L$(e,t){return this.each((typeof t=="function"?R$:M$)(e,t))}function*I$(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var r=e[t],o=0,l=r.length,u;o<l;++o)(u=r[o])&&(yield u)}var jb=[null];function ri(e,t){this._groups=e,this._parents=t}function Mf(){return new ri([[document.documentElement]],jb)}function O$(){return this}ri.prototype=Mf.prototype={constructor:ri,select:lA,selectAll:fA,selectChild:pA,selectChildren:vA,filter:xA,data:CA,enter:bA,exit:AA,join:$A,merge:TA,selection:O$,order:MA,sort:RA,call:IA,nodes:OA,node:PA,size:DA,empty:FA,each:zA,attr:GA,style:XA,property:t$,classed:i$,text:c$,html:h$,raise:_$,lower:g$,append:y$,insert:v$,remove:b$,clone:S$,datum:N$,on:T$,dispatch:L$,[Symbol.iterator]:I$};function ji(e){return typeof e=="string"?new ri([[document.querySelector(e)]],[document.documentElement]):new ri([[e]],jb)}function P$(e){let t;for(;t=e.sourceEvent;)e=t;return e}function zi(e,t){if(e=P$(e),t===void 0&&(t=e.currentTarget),t){var n=t.ownerSVGElement||t;if(n.createSVGPoint){var r=n.createSVGPoint();return r.x=e.clientX,r.y=e.clientY,r=r.matrixTransform(t.getScreenCTM().inverse()),[r.x,r.y]}if(t.getBoundingClientRect){var o=t.getBoundingClientRect();return[e.clientX-o.left-t.clientLeft,e.clientY-o.top-t.clientTop]}}return[e.pageX,e.pageY]}const D$={passive:!1},pf={capture:!0,passive:!1};function H_(e){e.stopImmediatePropagation()}function wu(e){e.preventDefault(),e.stopImmediatePropagation()}function Sb(e){var t=e.document.documentElement,n=ji(e).on("dragstart.drag",wu,pf);"onselectstart"in t?n.on("selectstart.drag",wu,pf):(t.__noselect=t.style.MozUserSelect,t.style.MozUserSelect="none")}function Nb(e,t){var n=e.document.documentElement,r=ji(e).on("dragstart.drag",null);t&&(r.on("click.drag",wu,pf),setTimeout(function(){r.on("click.drag",null)},0)),"onselectstart"in n?r.on("selectstart.drag",null):(n.style.MozUserSelect=n.__noselect,delete n.__noselect)}const Ph=e=>()=>e;function Fp(e,{sourceEvent:t,subject:n,target:r,identifier:o,active:l,x:u,y:c,dx:f,dy:m,dispatch:_}){Object.defineProperties(this,{type:{value:e,enumerable:!0,configurable:!0},sourceEvent:{value:t,enumerable:!0,configurable:!0},subject:{value:n,enumerable:!0,configurable:!0},target:{value:r,enumerable:!0,configurable:!0},identifier:{value:o,enumerable:!0,configurable:!0},active:{value:l,enumerable:!0,configurable:!0},x:{value:u,enumerable:!0,configurable:!0},y:{value:c,enumerable:!0,configurable:!0},dx:{value:f,enumerable:!0,configurable:!0},dy:{value:m,enumerable:!0,configurable:!0},_:{value:_}})}Fp.prototype.on=function(){var e=this._.on.apply(this._,arguments);return e===this._?this:e};function F$(e){return!e.ctrlKey&&!e.button}function z$(){return this.parentNode}function B$(e,t){return t??{x:e.x,y:e.y}}function U$(){return navigator.maxTouchPoints||"ontouchstart"in this}function W$(){var e=F$,t=z$,n=B$,r=U$,o={},l=Rm("start","drag","end"),u=0,c,f,m,_,g=0;function w(I){I.on("mousedown.drag",x).filter(r).on("touchstart.drag",N).on("touchmove.drag",C,D$).on("touchend.drag touchcancel.drag",E).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function x(I,K){if(!(_||!e.call(this,I,K))){var U=T(this,t.call(this,I,K),I,K,"mouse");U&&(ji(I.view).on("mousemove.drag",j,pf).on("mouseup.drag",b,pf),Sb(I.view),H_(I),m=!1,c=I.clientX,f=I.clientY,U("start",I))}}function j(I){if(wu(I),!m){var K=I.clientX-c,U=I.clientY-f;m=K*K+U*U>g}o.mouse("drag",I)}function b(I){ji(I.view).on("mousemove.drag mouseup.drag",null),Nb(I.view,m),wu(I),o.mouse("end",I)}function N(I,K){if(e.call(this,I,K)){var U=I.changedTouches,J=t.call(this,I,K),Y=U.length,re,ce;for(re=0;re<Y;++re)(ce=T(this,J,I,K,U[re].identifier,U[re]))&&(H_(I),ce("start",I,U[re]))}}function C(I){var K=I.changedTouches,U=K.length,J,Y;for(J=0;J<U;++J)(Y=o[K[J].identifier])&&(wu(I),Y("drag",I,K[J]))}function E(I){var K=I.changedTouches,U=K.length,J,Y;for(_&&clearTimeout(_),_=setTimeout(function(){_=null},500),J=0;J<U;++J)(Y=o[K[J].identifier])&&(H_(I),Y("end",I,K[J]))}function T(I,K,U,J,Y,re){var ce=l.copy(),fe=zi(re||U,K),W,O,$;if(($=n.call(I,new Fp("beforestart",{sourceEvent:U,target:w,identifier:Y,active:u,x:fe[0],y:fe[1],dx:0,dy:0,dispatch:ce}),J))!=null)return W=$.x-fe[0]||0,O=$.y-fe[1]||0,function z(A,ee,P){var F=fe,G;switch(A){case"start":o[Y]=z,G=u++;break;case"end":delete o[Y],--u;case"drag":fe=zi(P||ee,K),G=u;break}ce.call(A,I,new Fp(A,{sourceEvent:ee,subject:$,target:w,identifier:Y,active:G,x:fe[0]+W,y:fe[1]+O,dx:fe[0]-F[0],dy:fe[1]-F[1],dispatch:ce}),J)}}return w.filter=function(I){return arguments.length?(e=typeof I=="function"?I:Ph(!!I),w):e},w.container=function(I){return arguments.length?(t=typeof I=="function"?I:Ph(I),w):t},w.subject=function(I){return arguments.length?(n=typeof I=="function"?I:Ph(I),w):n},w.touchable=function(I){return arguments.length?(r=typeof I=="function"?I:Ph(!!I),w):r},w.on=function(){var I=l.on.apply(l,arguments);return I===l?w:I},w.clickDistance=function(I){return arguments.length?(g=(I=+I)*I,w):Math.sqrt(g)},w}function Ag(e,t,n){e.prototype=t.prototype=n,n.constructor=e}function Cb(e,t){var n=Object.create(e.prototype);for(var r in t)n[r]=t[r];return n}function Rf(){}var gf=.7,pm=1/gf,vu="\\s*([+-]?\\d+)\\s*",yf="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",jo="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",q$=/^#([0-9a-f]{3,8})$/,H$=new RegExp(`^rgb\\(${vu},${vu},${vu}\\)$`),V$=new RegExp(`^rgb\\(${jo},${jo},${jo}\\)$`),G$=new RegExp(`^rgba\\(${vu},${vu},${vu},${yf}\\)$`),K$=new RegExp(`^rgba\\(${jo},${jo},${jo},${yf}\\)$`),Y$=new RegExp(`^hsl\\(${yf},${jo},${jo}\\)$`),J$=new RegExp(`^hsla\\(${yf},${jo},${jo},${yf}\\)$`),Cw={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};Ag(Rf,wf,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:Ew,formatHex:Ew,formatHex8:X$,formatHsl:Z$,formatRgb:Aw,toString:Aw});function Ew(){return this.rgb().formatHex()}function X$(){return this.rgb().formatHex8()}function Z$(){return Eb(this).formatHsl()}function Aw(){return this.rgb().formatRgb()}function wf(e){var t,n;return e=(e+"").trim().toLowerCase(),(t=q$.exec(e))?(n=t[1].length,t=parseInt(t[1],16),n===6?$w(t):n===3?new Ur(t>>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):n===8?Dh(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?Dh(t>>12&15|t>>8&240,t>>8&15|t>>4&240,t>>4&15|t&240,((t&15)<<4|t&15)/255):null):(t=H$.exec(e))?new Ur(t[1],t[2],t[3],1):(t=V$.exec(e))?new Ur(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=G$.exec(e))?Dh(t[1],t[2],t[3],t[4]):(t=K$.exec(e))?Dh(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=Y$.exec(e))?Rw(t[1],t[2]/100,t[3]/100,1):(t=J$.exec(e))?Rw(t[1],t[2]/100,t[3]/100,t[4]):Cw.hasOwnProperty(e)?$w(Cw[e]):e==="transparent"?new Ur(NaN,NaN,NaN,0):null}function $w(e){return new Ur(e>>16&255,e>>8&255,e&255,1)}function Dh(e,t,n,r){return r<=0&&(e=t=n=NaN),new Ur(e,t,n,r)}function Q$(e){return e instanceof Rf||(e=wf(e)),e?(e=e.rgb(),new Ur(e.r,e.g,e.b,e.opacity)):new Ur}function zp(e,t,n,r){return arguments.length===1?Q$(e):new Ur(e,t,n,r??1)}function Ur(e,t,n,r){this.r=+e,this.g=+t,this.b=+n,this.opacity=+r}Ag(Ur,zp,Cb(Rf,{brighter(e){return e=e==null?pm:Math.pow(pm,e),new Ur(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=e==null?gf:Math.pow(gf,e),new Ur(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new Ur(sc(this.r),sc(this.g),sc(this.b),gm(this.opacity))},displayable(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:Tw,formatHex:Tw,formatHex8:eT,formatRgb:Mw,toString:Mw}));function Tw(){return`#${Jl(this.r)}${Jl(this.g)}${Jl(this.b)}`}function eT(){return`#${Jl(this.r)}${Jl(this.g)}${Jl(this.b)}${Jl((isNaN(this.opacity)?1:this.opacity)*255)}`}function Mw(){const e=gm(this.opacity);return`${e===1?"rgb(":"rgba("}${sc(this.r)}, ${sc(this.g)}, ${sc(this.b)}${e===1?")":`, ${e})`}`}function gm(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function sc(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function Jl(e){return e=sc(e),(e<16?"0":"")+e.toString(16)}function Rw(e,t,n,r){return r<=0?e=t=n=NaN:n<=0||n>=1?e=t=NaN:t<=0&&(e=NaN),new Wi(e,t,n,r)}function Eb(e){if(e instanceof Wi)return new Wi(e.h,e.s,e.l,e.opacity);if(e instanceof Rf||(e=wf(e)),!e)return new Wi;if(e instanceof Wi)return e;e=e.rgb();var t=e.r/255,n=e.g/255,r=e.b/255,o=Math.min(t,n,r),l=Math.max(t,n,r),u=NaN,c=l-o,f=(l+o)/2;return c?(t===l?u=(n-r)/c+(n<r)*6:n===l?u=(r-t)/c+2:u=(t-n)/c+4,c/=f<.5?l+o:2-l-o,u*=60):c=f>0&&f<1?0:u,new Wi(u,c,f,e.opacity)}function tT(e,t,n,r){return arguments.length===1?Eb(e):new Wi(e,t,n,r??1)}function Wi(e,t,n,r){this.h=+e,this.s=+t,this.l=+n,this.opacity=+r}Ag(Wi,tT,Cb(Rf,{brighter(e){return e=e==null?pm:Math.pow(pm,e),new Wi(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?gf:Math.pow(gf,e),new Wi(this.h,this.s,this.l*e,this.opacity)},rgb(){var e=this.h%360+(this.h<0)*360,t=isNaN(e)||isNaN(this.s)?0:this.s,n=this.l,r=n+(n<.5?n:1-n)*t,o=2*n-r;return new Ur(V_(e>=240?e-240:e+120,o,r),V_(e,o,r),V_(e<120?e+240:e-120,o,r),this.opacity)},clamp(){return new Wi(Lw(this.h),Fh(this.s),Fh(this.l),gm(this.opacity))},displayable(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl(){const e=gm(this.opacity);return`${e===1?"hsl(":"hsla("}${Lw(this.h)}, ${Fh(this.s)*100}%, ${Fh(this.l)*100}%${e===1?")":`, ${e})`}`}}));function Lw(e){return e=(e||0)%360,e<0?e+360:e}function Fh(e){return Math.max(0,Math.min(1,e||0))}function V_(e,t,n){return(e<60?t+(n-t)*e/60:e<180?n:e<240?t+(n-t)*(240-e)/60:t)*255}const Ab=e=>()=>e;function nT(e,t){return function(n){return e+n*t}}function sT(e,t,n){return e=Math.pow(e,n),t=Math.pow(t,n)-e,n=1/n,function(r){return Math.pow(e+r*t,n)}}function rT(e){return(e=+e)==1?$b:function(t,n){return n-t?sT(t,n,e):Ab(isNaN(t)?n:t)}}function $b(e,t){var n=t-e;return n?nT(e,n):Ab(isNaN(e)?t:e)}const Iw=(function e(t){var n=rT(t);function r(o,l){var u=n((o=zp(o)).r,(l=zp(l)).r),c=n(o.g,l.g),f=n(o.b,l.b),m=$b(o.opacity,l.opacity);return function(_){return o.r=u(_),o.g=c(_),o.b=f(_),o.opacity=m(_),o+""}}return r.gamma=e,r})(1);function rl(e,t){return e=+e,t=+t,function(n){return e*(1-n)+t*n}}var Bp=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,G_=new RegExp(Bp.source,"g");function iT(e){return function(){return e}}function oT(e){return function(t){return e(t)+""}}function aT(e,t){var n=Bp.lastIndex=G_.lastIndex=0,r,o,l,u=-1,c=[],f=[];for(e=e+"",t=t+"";(r=Bp.exec(e))&&(o=G_.exec(t));)(l=o.index)>n&&(l=t.slice(n,l),c[u]?c[u]+=l:c[++u]=l),(r=r[0])===(o=o[0])?c[u]?c[u]+=o:c[++u]=o:(c[++u]=null,f.push({i:u,x:rl(r,o)})),n=G_.lastIndex;return n<t.length&&(l=t.slice(n),c[u]?c[u]+=l:c[++u]=l),c.length<2?f[0]?oT(f[0].x):iT(t):(t=f.length,function(m){for(var _=0,g;_<t;++_)c[(g=f[_]).i]=g.x(m);return c.join("")})}var Ow=180/Math.PI,Up={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function Tb(e,t,n,r,o,l){var u,c,f;return(u=Math.sqrt(e*e+t*t))&&(e/=u,t/=u),(f=e*n+t*r)&&(n-=e*f,r-=t*f),(c=Math.sqrt(n*n+r*r))&&(n/=c,r/=c,f/=c),e*r<t*n&&(e=-e,t=-t,f=-f,u=-u),{translateX:o,translateY:l,rotate:Math.atan2(t,e)*Ow,skewX:Math.atan(f)*Ow,scaleX:u,scaleY:c}}var zh;function lT(e){const t=new(typeof DOMMatrix=="function"?DOMMatrix:WebKitCSSMatrix)(e+"");return t.isIdentity?Up:Tb(t.a,t.b,t.c,t.d,t.e,t.f)}function cT(e){return e==null||(zh||(zh=document.createElementNS("http://www.w3.org/2000/svg","g")),zh.setAttribute("transform",e),!(e=zh.transform.baseVal.consolidate()))?Up:(e=e.matrix,Tb(e.a,e.b,e.c,e.d,e.e,e.f))}function Mb(e,t,n,r){function o(m){return m.length?m.pop()+" ":""}function l(m,_,g,w,x,j){if(m!==g||_!==w){var b=x.push("translate(",null,t,null,n);j.push({i:b-4,x:rl(m,g)},{i:b-2,x:rl(_,w)})}else(g||w)&&x.push("translate("+g+t+w+n)}function u(m,_,g,w){m!==_?(m-_>180?_+=360:_-m>180&&(m+=360),w.push({i:g.push(o(g)+"rotate(",null,r)-2,x:rl(m,_)})):_&&g.push(o(g)+"rotate("+_+r)}function c(m,_,g,w){m!==_?w.push({i:g.push(o(g)+"skewX(",null,r)-2,x:rl(m,_)}):_&&g.push(o(g)+"skewX("+_+r)}function f(m,_,g,w,x,j){if(m!==g||_!==w){var b=x.push(o(x)+"scale(",null,",",null,")");j.push({i:b-4,x:rl(m,g)},{i:b-2,x:rl(_,w)})}else(g!==1||w!==1)&&x.push(o(x)+"scale("+g+","+w+")")}return function(m,_){var g=[],w=[];return m=e(m),_=e(_),l(m.translateX,m.translateY,_.translateX,_.translateY,g,w),u(m.rotate,_.rotate,g,w),c(m.skewX,_.skewX,g,w),f(m.scaleX,m.scaleY,_.scaleX,_.scaleY,g,w),m=_=null,function(x){for(var j=-1,b=w.length,N;++j<b;)g[(N=w[j]).i]=N.x(x);return g.join("")}}}var uT=Mb(lT,"px, ","px)","deg)"),dT=Mb(cT,", ",")",")"),fT=1e-12;function Pw(e){return((e=Math.exp(e))+1/e)/2}function hT(e){return((e=Math.exp(e))-1/e)/2}function mT(e){return((e=Math.exp(2*e))-1)/(e+1)}const _T=(function e(t,n,r){function o(l,u){var c=l[0],f=l[1],m=l[2],_=u[0],g=u[1],w=u[2],x=_-c,j=g-f,b=x*x+j*j,N,C;if(b<fT)C=Math.log(w/m)/t,N=function(J){return[c+J*x,f+J*j,m*Math.exp(t*J*C)]};else{var E=Math.sqrt(b),T=(w*w-m*m+r*b)/(2*m*n*E),I=(w*w-m*m-r*b)/(2*w*n*E),K=Math.log(Math.sqrt(T*T+1)-T),U=Math.log(Math.sqrt(I*I+1)-I);C=(U-K)/t,N=function(J){var Y=J*C,re=Pw(K),ce=m/(n*E)*(re*mT(t*Y+K)-hT(K));return[c+ce*x,f+ce*j,m*re/Pw(t*Y+K)]}}return N.duration=C*1e3*t/Math.SQRT2,N}return o.rho=function(l){var u=Math.max(.001,+l),c=u*u,f=c*c;return e(u,c,f)},o})(Math.SQRT2,2,4);var Cu=0,of=0,Kd=0,Rb=1e3,ym,af,wm=0,cc=0,Im=0,vf=typeof performance=="object"&&performance.now?performance:Date,Lb=typeof window=="object"&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(e){setTimeout(e,17)};function $g(){return cc||(Lb(pT),cc=vf.now()+Im)}function pT(){cc=0}function vm(){this._call=this._time=this._next=null}vm.prototype=Ib.prototype={constructor:vm,restart:function(e,t,n){if(typeof e!="function")throw new TypeError("callback is not a function");n=(n==null?$g():+n)+(t==null?0:+t),!this._next&&af!==this&&(af?af._next=this:ym=this,af=this),this._call=e,this._time=n,Wp()},stop:function(){this._call&&(this._call=null,this._time=1/0,Wp())}};function Ib(e,t,n){var r=new vm;return r.restart(e,t,n),r}function gT(){$g(),++Cu;for(var e=ym,t;e;)(t=cc-e._time)>=0&&e._call.call(void 0,t),e=e._next;--Cu}function Dw(){cc=(wm=vf.now())+Im,Cu=of=0;try{gT()}finally{Cu=0,wT(),cc=0}}function yT(){var e=vf.now(),t=e-wm;t>Rb&&(Im-=t,wm=e)}function wT(){for(var e,t=ym,n,r=1/0;t;)t._call?(r>t._time&&(r=t._time),e=t,t=t._next):(n=t._next,t._next=null,t=e?e._next=n:ym=n);af=e,Wp(r)}function Wp(e){if(!Cu){of&&(of=clearTimeout(of));var t=e-cc;t>24?(e<1/0&&(of=setTimeout(Dw,e-vf.now()-Im)),Kd&&(Kd=clearInterval(Kd))):(Kd||(wm=vf.now(),Kd=setInterval(yT,Rb)),Cu=1,Lb(Dw))}}function Fw(e,t,n){var r=new vm;return t=t==null?0:+t,r.restart(o=>{r.stop(),e(o+t)},t,n),r}var vT=Rm("start","end","cancel","interrupt"),xT=[],Ob=0,zw=1,qp=2,tm=3,Bw=4,Hp=5,nm=6;function Om(e,t,n,r,o,l){var u=e.__transition;if(!u)e.__transition={};else if(n in u)return;bT(e,n,{name:t,index:r,group:o,on:vT,tween:xT,time:l.time,delay:l.delay,duration:l.duration,ease:l.ease,timer:null,state:Ob})}function Tg(e,t){var n=Vi(e,t);if(n.state>Ob)throw new Error("too late; already scheduled");return n}function Co(e,t){var n=Vi(e,t);if(n.state>tm)throw new Error("too late; already running");return n}function Vi(e,t){var n=e.__transition;if(!n||!(n=n[t]))throw new Error("transition not found");return n}function bT(e,t,n){var r=e.__transition,o;r[t]=n,n.timer=Ib(l,0,n.time);function l(m){n.state=zw,n.timer.restart(u,n.delay,n.time),n.delay<=m&&u(m-n.delay)}function u(m){var _,g,w,x;if(n.state!==zw)return f();for(_ in r)if(x=r[_],x.name===n.name){if(x.state===tm)return Fw(u);x.state===Bw?(x.state=nm,x.timer.stop(),x.on.call("interrupt",e,e.__data__,x.index,x.group),delete r[_]):+_<t&&(x.state=nm,x.timer.stop(),x.on.call("cancel",e,e.__data__,x.index,x.group),delete r[_])}if(Fw(function(){n.state===tm&&(n.state=Bw,n.timer.restart(c,n.delay,n.time),c(m))}),n.state=qp,n.on.call("start",e,e.__data__,n.index,n.group),n.state===qp){for(n.state=tm,o=new Array(w=n.tween.length),_=0,g=-1;_<w;++_)(x=n.tween[_].value.call(e,e.__data__,n.index,n.group))&&(o[++g]=x);o.length=g+1}}function c(m){for(var _=m<n.duration?n.ease.call(null,m/n.duration):(n.timer.restart(f),n.state=Hp,1),g=-1,w=o.length;++g<w;)o[g].call(e,_);n.state===Hp&&(n.on.call("end",e,e.__data__,n.index,n.group),f())}function f(){n.state=nm,n.timer.stop(),delete r[t];for(var m in r)return;delete e.__transition}}function sm(e,t){var n=e.__transition,r,o,l=!0,u;if(n){t=t==null?null:t+"";for(u in n){if((r=n[u]).name!==t){l=!1;continue}o=r.state>qp&&r.state<Hp,r.state=nm,r.timer.stop(),r.on.call(o?"interrupt":"cancel",e,e.__data__,r.index,r.group),delete n[u]}l&&delete e.__transition}}function kT(e){return this.each(function(){sm(this,e)})}function jT(e,t){var n,r;return function(){var o=Co(this,e),l=o.tween;if(l!==n){r=n=l;for(var u=0,c=r.length;u<c;++u)if(r[u].name===t){r=r.slice(),r.splice(u,1);break}}o.tween=r}}function ST(e,t,n){var r,o;if(typeof n!="function")throw new Error;return function(){var l=Co(this,e),u=l.tween;if(u!==r){o=(r=u).slice();for(var c={name:t,value:n},f=0,m=o.length;f<m;++f)if(o[f].name===t){o[f]=c;break}f===m&&o.push(c)}l.tween=o}}function NT(e,t){var n=this._id;if(e+="",arguments.length<2){for(var r=Vi(this.node(),n).tween,o=0,l=r.length,u;o<l;++o)if((u=r[o]).name===e)return u.value;return null}return this.each((t==null?jT:ST)(n,e,t))}function Mg(e,t,n){var r=e._id;return e.each(function(){var o=Co(this,r);(o.value||(o.value={}))[t]=n.apply(this,arguments)}),function(o){return Vi(o,r).value[t]}}function Pb(e,t){var n;return(typeof t=="number"?rl:t instanceof wf?Iw:(n=wf(t))?(t=n,Iw):aT)(e,t)}function CT(e){return function(){this.removeAttribute(e)}}function ET(e){return function(){this.removeAttributeNS(e.space,e.local)}}function AT(e,t,n){var r,o=n+"",l;return function(){var u=this.getAttribute(e);return u===o?null:u===r?l:l=t(r=u,n)}}function $T(e,t,n){var r,o=n+"",l;return function(){var u=this.getAttributeNS(e.space,e.local);return u===o?null:u===r?l:l=t(r=u,n)}}function TT(e,t,n){var r,o,l;return function(){var u,c=n(this),f;return c==null?void this.removeAttribute(e):(u=this.getAttribute(e),f=c+"",u===f?null:u===r&&f===o?l:(o=f,l=t(r=u,c)))}}function MT(e,t,n){var r,o,l;return function(){var u,c=n(this),f;return c==null?void this.removeAttributeNS(e.space,e.local):(u=this.getAttributeNS(e.space,e.local),f=c+"",u===f?null:u===r&&f===o?l:(o=f,l=t(r=u,c)))}}function RT(e,t){var n=Lm(e),r=n==="transform"?dT:Pb;return this.attrTween(e,typeof t=="function"?(n.local?MT:TT)(n,r,Mg(this,"attr."+e,t)):t==null?(n.local?ET:CT)(n):(n.local?$T:AT)(n,r,t))}function LT(e,t){return function(n){this.setAttribute(e,t.call(this,n))}}function IT(e,t){return function(n){this.setAttributeNS(e.space,e.local,t.call(this,n))}}function OT(e,t){var n,r;function o(){var l=t.apply(this,arguments);return l!==r&&(n=(r=l)&&IT(e,l)),n}return o._value=t,o}function PT(e,t){var n,r;function o(){var l=t.apply(this,arguments);return l!==r&&(n=(r=l)&&LT(e,l)),n}return o._value=t,o}function DT(e,t){var n="attr."+e;if(arguments.length<2)return(n=this.tween(n))&&n._value;if(t==null)return this.tween(n,null);if(typeof t!="function")throw new Error;var r=Lm(e);return this.tween(n,(r.local?OT:PT)(r,t))}function FT(e,t){return function(){Tg(this,e).delay=+t.apply(this,arguments)}}function zT(e,t){return t=+t,function(){Tg(this,e).delay=t}}function BT(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?FT:zT)(t,e)):Vi(this.node(),t).delay}function UT(e,t){return function(){Co(this,e).duration=+t.apply(this,arguments)}}function WT(e,t){return t=+t,function(){Co(this,e).duration=t}}function qT(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?UT:WT)(t,e)):Vi(this.node(),t).duration}function HT(e,t){if(typeof t!="function")throw new Error;return function(){Co(this,e).ease=t}}function VT(e){var t=this._id;return arguments.length?this.each(HT(t,e)):Vi(this.node(),t).ease}function GT(e,t){return function(){var n=t.apply(this,arguments);if(typeof n!="function")throw new Error;Co(this,e).ease=n}}function KT(e){if(typeof e!="function")throw new Error;return this.each(GT(this._id,e))}function YT(e){typeof e!="function"&&(e=_b(e));for(var t=this._groups,n=t.length,r=new Array(n),o=0;o<n;++o)for(var l=t[o],u=l.length,c=r[o]=[],f,m=0;m<u;++m)(f=l[m])&&e.call(f,f.__data__,m,l)&&c.push(f);return new ca(r,this._parents,this._name,this._id)}function JT(e){if(e._id!==this._id)throw new Error;for(var t=this._groups,n=e._groups,r=t.length,o=n.length,l=Math.min(r,o),u=new Array(r),c=0;c<l;++c)for(var f=t[c],m=n[c],_=f.length,g=u[c]=new Array(_),w,x=0;x<_;++x)(w=f[x]||m[x])&&(g[x]=w);for(;c<r;++c)u[c]=t[c];return new ca(u,this._parents,this._name,this._id)}function XT(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 ZT(e,t,n){var r,o,l=XT(t)?Tg:Co;return function(){var u=l(this,e),c=u.on;c!==r&&(o=(r=c).copy()).on(t,n),u.on=o}}function QT(e,t){var n=this._id;return arguments.length<2?Vi(this.node(),n).on.on(e):this.each(ZT(n,e,t))}function eM(e){return function(){var t=this.parentNode;for(var n in this.__transition)if(+n!==e)return;t&&t.removeChild(this)}}function tM(){return this.on("end.remove",eM(this._id))}function nM(e){var t=this._name,n=this._id;typeof e!="function"&&(e=Cg(e));for(var r=this._groups,o=r.length,l=new Array(o),u=0;u<o;++u)for(var c=r[u],f=c.length,m=l[u]=new Array(f),_,g,w=0;w<f;++w)(_=c[w])&&(g=e.call(_,_.__data__,w,c))&&("__data__"in _&&(g.__data__=_.__data__),m[w]=g,Om(m[w],t,n,w,m,Vi(_,n)));return new ca(l,this._parents,t,n)}function sM(e){var t=this._name,n=this._id;typeof e!="function"&&(e=mb(e));for(var r=this._groups,o=r.length,l=[],u=[],c=0;c<o;++c)for(var f=r[c],m=f.length,_,g=0;g<m;++g)if(_=f[g]){for(var w=e.call(_,_.__data__,g,f),x,j=Vi(_,n),b=0,N=w.length;b<N;++b)(x=w[b])&&Om(x,t,n,b,w,j);l.push(w),u.push(_)}return new ca(l,u,t,n)}var rM=Mf.prototype.constructor;function iM(){return new rM(this._groups,this._parents)}function oM(e,t){var n,r,o;return function(){var l=Nu(this,e),u=(this.style.removeProperty(e),Nu(this,e));return l===u?null:l===n&&u===r?o:o=t(n=l,r=u)}}function Db(e){return function(){this.style.removeProperty(e)}}function aM(e,t,n){var r,o=n+"",l;return function(){var u=Nu(this,e);return u===o?null:u===r?l:l=t(r=u,n)}}function lM(e,t,n){var r,o,l;return function(){var u=Nu(this,e),c=n(this),f=c+"";return c==null&&(f=c=(this.style.removeProperty(e),Nu(this,e))),u===f?null:u===r&&f===o?l:(o=f,l=t(r=u,c))}}function cM(e,t){var n,r,o,l="style."+t,u="end."+l,c;return function(){var f=Co(this,e),m=f.on,_=f.value[l]==null?c||(c=Db(t)):void 0;(m!==n||o!==_)&&(r=(n=m).copy()).on(u,o=_),f.on=r}}function uM(e,t,n){var r=(e+="")=="transform"?uT:Pb;return t==null?this.styleTween(e,oM(e,r)).on("end.style."+e,Db(e)):typeof t=="function"?this.styleTween(e,lM(e,r,Mg(this,"style."+e,t))).each(cM(this._id,e)):this.styleTween(e,aM(e,r,t),n).on("end.style."+e,null)}function dM(e,t,n){return function(r){this.style.setProperty(e,t.call(this,r),n)}}function fM(e,t,n){var r,o;function l(){var u=t.apply(this,arguments);return u!==o&&(r=(o=u)&&dM(e,u,n)),r}return l._value=t,l}function hM(e,t,n){var r="style."+(e+="");if(arguments.length<2)return(r=this.tween(r))&&r._value;if(t==null)return this.tween(r,null);if(typeof t!="function")throw new Error;return this.tween(r,fM(e,t,n??""))}function mM(e){return function(){this.textContent=e}}function _M(e){return function(){var t=e(this);this.textContent=t??""}}function pM(e){return this.tween("text",typeof e=="function"?_M(Mg(this,"text",e)):mM(e==null?"":e+""))}function gM(e){return function(t){this.textContent=e.call(this,t)}}function yM(e){var t,n;function r(){var o=e.apply(this,arguments);return o!==n&&(t=(n=o)&&gM(o)),t}return r._value=e,r}function wM(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,yM(e))}function vM(){for(var e=this._name,t=this._id,n=Fb(),r=this._groups,o=r.length,l=0;l<o;++l)for(var u=r[l],c=u.length,f,m=0;m<c;++m)if(f=u[m]){var _=Vi(f,t);Om(f,e,n,m,u,{time:_.time+_.delay+_.duration,delay:0,duration:_.duration,ease:_.ease})}return new ca(r,this._parents,e,n)}function xM(){var e,t,n=this,r=n._id,o=n.size();return new Promise(function(l,u){var c={value:u},f={value:function(){--o===0&&l()}};n.each(function(){var m=Co(this,r),_=m.on;_!==e&&(t=(e=_).copy(),t._.cancel.push(c),t._.interrupt.push(c),t._.end.push(f)),m.on=t}),o===0&&l()})}var bM=0;function ca(e,t,n,r){this._groups=e,this._parents=t,this._name=n,this._id=r}function Fb(){return++bM}var sa=Mf.prototype;ca.prototype={constructor:ca,select:nM,selectAll:sM,selectChild:sa.selectChild,selectChildren:sa.selectChildren,filter:YT,merge:JT,selection:iM,transition:vM,call:sa.call,nodes:sa.nodes,node:sa.node,size:sa.size,empty:sa.empty,each:sa.each,on:QT,attr:RT,attrTween:DT,style:uM,styleTween:hM,text:pM,textTween:wM,remove:tM,tween:NT,delay:BT,duration:qT,ease:VT,easeVarying:KT,end:xM,[Symbol.iterator]:sa[Symbol.iterator]};function kM(e){return((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2}var jM={time:null,delay:0,duration:250,ease:kM};function SM(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 NM(e){var t,n;e instanceof ca?(t=e._id,e=e._name):(t=Fb(),(n=jM).time=$g(),e=e==null?null:e+"");for(var r=this._groups,o=r.length,l=0;l<o;++l)for(var u=r[l],c=u.length,f,m=0;m<c;++m)(f=u[m])&&Om(f,e,t,m,u,n||SM(f,t));return new ca(r,this._parents,e,t)}Mf.prototype.interrupt=kT;Mf.prototype.transition=NM;const Bh=e=>()=>e;function CM(e,{sourceEvent:t,target:n,transform:r,dispatch:o}){Object.defineProperties(this,{type:{value:e,enumerable:!0,configurable:!0},sourceEvent:{value:t,enumerable:!0,configurable:!0},target:{value:n,enumerable:!0,configurable:!0},transform:{value:r,enumerable:!0,configurable:!0},_:{value:o}})}function oa(e,t,n){this.k=e,this.x=t,this.y=n}oa.prototype={constructor:oa,scale:function(e){return e===1?this:new oa(this.k*e,this.x,this.y)},translate:function(e,t){return e===0&t===0?this:new oa(this.k,this.x+this.k*e,this.y+this.k*t)},apply:function(e){return[e[0]*this.k+this.x,e[1]*this.k+this.y]},applyX:function(e){return e*this.k+this.x},applyY:function(e){return e*this.k+this.y},invert:function(e){return[(e[0]-this.x)/this.k,(e[1]-this.y)/this.k]},invertX:function(e){return(e-this.x)/this.k},invertY:function(e){return(e-this.y)/this.k},rescaleX:function(e){return e.copy().domain(e.range().map(this.invertX,this).map(e.invert,e))},rescaleY:function(e){return e.copy().domain(e.range().map(this.invertY,this).map(e.invert,e))},toString:function(){return"translate("+this.x+","+this.y+") scale("+this.k+")"}};var aa=new oa(1,0,0);oa.prototype;function K_(e){e.stopImmediatePropagation()}function Yd(e){e.preventDefault(),e.stopImmediatePropagation()}function EM(e){return(!e.ctrlKey||e.type==="wheel")&&!e.button}function AM(){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 Uw(){return this.__zoom||aa}function $M(e){return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*(e.ctrlKey?10:1)}function TM(){return navigator.maxTouchPoints||"ontouchstart"in this}function MM(e,t,n){var r=e.invertX(t[0][0])-n[0][0],o=e.invertX(t[1][0])-n[1][0],l=e.invertY(t[0][1])-n[0][1],u=e.invertY(t[1][1])-n[1][1];return e.translate(o>r?(r+o)/2:Math.min(0,r)||Math.max(0,o),u>l?(l+u)/2:Math.min(0,l)||Math.max(0,u))}function zb(){var e=EM,t=AM,n=MM,r=$M,o=TM,l=[0,1/0],u=[[-1/0,-1/0],[1/0,1/0]],c=250,f=_T,m=Rm("start","zoom","end"),_,g,w,x=500,j=150,b=0,N=10;function C($){$.property("__zoom",Uw).on("wheel.zoom",Y,{passive:!1}).on("mousedown.zoom",re).on("dblclick.zoom",ce).filter(o).on("touchstart.zoom",fe).on("touchmove.zoom",W).on("touchend.zoom touchcancel.zoom",O).style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}C.transform=function($,z,A,ee){var P=$.selection?$.selection():$;P.property("__zoom",Uw),$!==P?K($,z,A,ee):P.interrupt().each(function(){U(this,arguments).event(ee).start().zoom(null,typeof z=="function"?z.apply(this,arguments):z).end()})},C.scaleBy=function($,z,A,ee){C.scaleTo($,function(){var P=this.__zoom.k,F=typeof z=="function"?z.apply(this,arguments):z;return P*F},A,ee)},C.scaleTo=function($,z,A,ee){C.transform($,function(){var P=t.apply(this,arguments),F=this.__zoom,G=A==null?I(P):typeof A=="function"?A.apply(this,arguments):A,R=F.invert(G),Z=typeof z=="function"?z.apply(this,arguments):z;return n(T(E(F,Z),G,R),P,u)},A,ee)},C.translateBy=function($,z,A,ee){C.transform($,function(){return n(this.__zoom.translate(typeof z=="function"?z.apply(this,arguments):z,typeof A=="function"?A.apply(this,arguments):A),t.apply(this,arguments),u)},null,ee)},C.translateTo=function($,z,A,ee,P){C.transform($,function(){var F=t.apply(this,arguments),G=this.__zoom,R=ee==null?I(F):typeof ee=="function"?ee.apply(this,arguments):ee;return n(aa.translate(R[0],R[1]).scale(G.k).translate(typeof z=="function"?-z.apply(this,arguments):-z,typeof A=="function"?-A.apply(this,arguments):-A),F,u)},ee,P)};function E($,z){return z=Math.max(l[0],Math.min(l[1],z)),z===$.k?$:new oa(z,$.x,$.y)}function T($,z,A){var ee=z[0]-A[0]*$.k,P=z[1]-A[1]*$.k;return ee===$.x&&P===$.y?$:new oa($.k,ee,P)}function I($){return[(+$[0][0]+ +$[1][0])/2,(+$[0][1]+ +$[1][1])/2]}function K($,z,A,ee){$.on("start.zoom",function(){U(this,arguments).event(ee).start()}).on("interrupt.zoom end.zoom",function(){U(this,arguments).event(ee).end()}).tween("zoom",function(){var P=this,F=arguments,G=U(P,F).event(ee),R=t.apply(P,F),Z=A==null?I(R):typeof A=="function"?A.apply(P,F):A,X=Math.max(R[1][0]-R[0][0],R[1][1]-R[0][1]),ie=P.__zoom,ne=typeof z=="function"?z.apply(P,F):z,ye=f(ie.invert(Z).concat(X/ie.k),ne.invert(Z).concat(X/ne.k));return function(he){if(he===1)he=ne;else{var pe=ye(he),Ne=X/pe[2];he=new oa(Ne,Z[0]-pe[0]*Ne,Z[1]-pe[1]*Ne)}G.zoom(null,he)}})}function U($,z,A){return!A&&$.__zooming||new J($,z)}function J($,z){this.that=$,this.args=z,this.active=0,this.sourceEvent=null,this.extent=t.apply($,z),this.taps=0}J.prototype={event:function($){return $&&(this.sourceEvent=$),this},start:function(){return++this.active===1&&(this.that.__zooming=this,this.emit("start")),this},zoom:function($,z){return this.mouse&&$!=="mouse"&&(this.mouse[1]=z.invert(this.mouse[0])),this.touch0&&$!=="touch"&&(this.touch0[1]=z.invert(this.touch0[0])),this.touch1&&$!=="touch"&&(this.touch1[1]=z.invert(this.touch1[0])),this.that.__zoom=z,this.emit("zoom"),this},end:function(){return--this.active===0&&(delete this.that.__zooming,this.emit("end")),this},emit:function($){var z=ji(this.that).datum();m.call($,this.that,new CM($,{sourceEvent:this.sourceEvent,target:C,transform:this.that.__zoom,dispatch:m}),z)}};function Y($,...z){if(!e.apply(this,arguments))return;var A=U(this,z).event($),ee=this.__zoom,P=Math.max(l[0],Math.min(l[1],ee.k*Math.pow(2,r.apply(this,arguments)))),F=zi($);if(A.wheel)(A.mouse[0][0]!==F[0]||A.mouse[0][1]!==F[1])&&(A.mouse[1]=ee.invert(A.mouse[0]=F)),clearTimeout(A.wheel);else{if(ee.k===P)return;A.mouse=[F,ee.invert(F)],sm(this),A.start()}Yd($),A.wheel=setTimeout(G,j),A.zoom("mouse",n(T(E(ee,P),A.mouse[0],A.mouse[1]),A.extent,u));function G(){A.wheel=null,A.end()}}function re($,...z){if(w||!e.apply(this,arguments))return;var A=$.currentTarget,ee=U(this,z,!0).event($),P=ji($.view).on("mousemove.zoom",Z,!0).on("mouseup.zoom",X,!0),F=zi($,A),G=$.clientX,R=$.clientY;Sb($.view),K_($),ee.mouse=[F,this.__zoom.invert(F)],sm(this),ee.start();function Z(ie){if(Yd(ie),!ee.moved){var ne=ie.clientX-G,ye=ie.clientY-R;ee.moved=ne*ne+ye*ye>b}ee.event(ie).zoom("mouse",n(T(ee.that.__zoom,ee.mouse[0]=zi(ie,A),ee.mouse[1]),ee.extent,u))}function X(ie){P.on("mousemove.zoom mouseup.zoom",null),Nb(ie.view,ee.moved),Yd(ie),ee.event(ie).end()}}function ce($,...z){if(e.apply(this,arguments)){var A=this.__zoom,ee=zi($.changedTouches?$.changedTouches[0]:$,this),P=A.invert(ee),F=A.k*($.shiftKey?.5:2),G=n(T(E(A,F),ee,P),t.apply(this,z),u);Yd($),c>0?ji(this).transition().duration(c).call(K,G,ee,$):ji(this).call(C.transform,G,ee,$)}}function fe($,...z){if(e.apply(this,arguments)){var A=$.touches,ee=A.length,P=U(this,z,$.changedTouches.length===ee).event($),F,G,R,Z;for(K_($),G=0;G<ee;++G)R=A[G],Z=zi(R,this),Z=[Z,this.__zoom.invert(Z),R.identifier],P.touch0?!P.touch1&&P.touch0[2]!==Z[2]&&(P.touch1=Z,P.taps=0):(P.touch0=Z,F=!0,P.taps=1+!!_);_&&(_=clearTimeout(_)),F&&(P.taps<2&&(g=Z[0],_=setTimeout(function(){_=null},x)),sm(this),P.start())}}function W($,...z){if(this.__zooming){var A=U(this,z).event($),ee=$.changedTouches,P=ee.length,F,G,R,Z;for(Yd($),F=0;F<P;++F)G=ee[F],R=zi(G,this),A.touch0&&A.touch0[2]===G.identifier?A.touch0[0]=R:A.touch1&&A.touch1[2]===G.identifier&&(A.touch1[0]=R);if(G=A.that.__zoom,A.touch1){var X=A.touch0[0],ie=A.touch0[1],ne=A.touch1[0],ye=A.touch1[1],he=(he=ne[0]-X[0])*he+(he=ne[1]-X[1])*he,pe=(pe=ye[0]-ie[0])*pe+(pe=ye[1]-ie[1])*pe;G=E(G,Math.sqrt(he/pe)),R=[(X[0]+ne[0])/2,(X[1]+ne[1])/2],Z=[(ie[0]+ye[0])/2,(ie[1]+ye[1])/2]}else if(A.touch0)R=A.touch0[0],Z=A.touch0[1];else return;A.zoom("touch",n(T(G,R,Z),A.extent,u))}}function O($,...z){if(this.__zooming){var A=U(this,z).event($),ee=$.changedTouches,P=ee.length,F,G;for(K_($),w&&clearTimeout(w),w=setTimeout(function(){w=null},x),F=0;F<P;++F)G=ee[F],A.touch0&&A.touch0[2]===G.identifier?delete A.touch0:A.touch1&&A.touch1[2]===G.identifier&&delete A.touch1;if(A.touch1&&!A.touch0&&(A.touch0=A.touch1,delete A.touch1),A.touch0)A.touch0[1]=this.__zoom.invert(A.touch0[0]);else if(A.end(),A.taps===2&&(G=zi(G,this),Math.hypot(g[0]-G[0],g[1]-G[1])<N)){var R=ji(this).on("dblclick.zoom");R&&R.apply(this,arguments)}}}return C.wheelDelta=function($){return arguments.length?(r=typeof $=="function"?$:Bh(+$),C):r},C.filter=function($){return arguments.length?(e=typeof $=="function"?$:Bh(!!$),C):e},C.touchable=function($){return arguments.length?(o=typeof $=="function"?$:Bh(!!$),C):o},C.extent=function($){return arguments.length?(t=typeof $=="function"?$:Bh([[+$[0][0],+$[0][1]],[+$[1][0],+$[1][1]]]),C):t},C.scaleExtent=function($){return arguments.length?(l[0]=+$[0],l[1]=+$[1],C):[l[0],l[1]]},C.translateExtent=function($){return arguments.length?(u[0][0]=+$[0][0],u[1][0]=+$[1][0],u[0][1]=+$[0][1],u[1][1]=+$[1][1],C):[[u[0][0],u[0][1]],[u[1][0],u[1][1]]]},C.constrain=function($){return arguments.length?(n=$,C):n},C.duration=function($){return arguments.length?(c=+$,C):c},C.interpolate=function($){return arguments.length?(f=$,C):f},C.on=function(){var $=m.on.apply(m,arguments);return $===m?C:$},C.clickDistance=function($){return arguments.length?(b=($=+$)*$,C):Math.sqrt(b)},C.tapDistance=function($){return arguments.length?(N=+$,C):N},C}const Pm=p.createContext(null),RM=Pm.Provider,ua={error001:()=>"[React Flow]: Seems like you have not used zustand provider as an ancestor. Help: https://reactflow.dev/error#001",error002:()=>"It looks like you've created a new nodeTypes or edgeTypes object. If this wasn't on purpose please define the nodeTypes/edgeTypes outside of the component or memoize them.",error003:e=>`Node type "${e}" not found. Using fallback type "default".`,error004:()=>"The React Flow parent container needs a width and a height to render the graph.",error005:()=>"Only child nodes can use a parent extent.",error006:()=>"Can't create edge. An edge needs a source and a target.",error007:e=>`The old edge with id=${e} does not exist.`,error009:e=>`Marker type "${e}" doesn't exist.`,error008:(e,t)=>`Couldn't create edge for ${e?"target":"source"} handle id: "${e?t.targetHandle:t.sourceHandle}", edge id: ${t.id}.`,error010:()=>"Handle: No node id found. Make sure to only use a Handle inside a custom Node.",error011:e=>`Edge type "${e}" not found. Using fallback type "default".`,error012:e=>`Node with id "${e}" does not exist, it may have been removed. This can happen when a node is deleted before the "onNodeClick" handler is called.`},Bb=ua.error001();function Ln(e,t){const n=p.useContext(Pm);if(n===null)throw new Error(Bb);return fb(n,e,t)}const bs=()=>{const e=p.useContext(Pm);if(e===null)throw new Error(Bb);return p.useMemo(()=>({getState:e.getState,setState:e.setState,subscribe:e.subscribe,destroy:e.destroy}),[e])},LM=e=>e.userSelectionActive?"none":"all";function xf({position:e,children:t,className:n,style:r,...o}){const l=Ln(LM),u=`${e}`.split("-");return ve.createElement("div",{className:Ks(["react-flow__panel",n,...u]),style:{...r,pointerEvents:l},...o},t)}function IM({proOptions:e,position:t="bottom-right"}){return e!=null&&e.hideAttribution?null:ve.createElement(xf,{position:t,className:"react-flow__attribution","data-message":"Please only hide this attribution when you are subscribed to React Flow Pro: https://reactflow.dev/pro"},ve.createElement("a",{href:"https://reactflow.dev",target:"_blank",rel:"noopener noreferrer","aria-label":"React Flow attribution"},"React Flow"))}const OM=({x:e,y:t,label:n,labelStyle:r={},labelShowBg:o=!0,labelBgStyle:l={},labelBgPadding:u=[2,4],labelBgBorderRadius:c=2,children:f,className:m,..._})=>{const g=p.useRef(null),[w,x]=p.useState({x:0,y:0,width:0,height:0}),j=Ks(["react-flow__edge-textwrapper",m]);return p.useEffect(()=>{if(g.current){const b=g.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-w.width/2} ${t-w.height/2})`,className:j,visibility:w.width?"visible":"hidden",..._},o&&ve.createElement("rect",{width:w.width+2*u[0],x:-u[0],y:-u[1],height:w.height+2*u[1],className:"react-flow__edge-textbg",style:l,rx:c,ry:c}),ve.createElement("text",{className:"react-flow__edge-text",y:w.height/2,dy:"0.3em",ref:g,style:r},n),f)};var PM=p.memo(OM);const Rg=e=>({width:e.offsetWidth,height:e.offsetHeight}),Eu=(e,t=0,n=1)=>Math.min(Math.max(e,t),n),Lg=(e={x:0,y:0},t)=>({x:Eu(e.x,t[0][0],t[1][0]),y:Eu(e.y,t[0][1],t[1][1])}),Ww=(e,t,n)=>e<t?Eu(Math.abs(e-t),1,50)/50:e>n?-Eu(Math.abs(e-n),1,50)/50:0,Ub=(e,t)=>{const n=Ww(e.x,35,t.width-35)*20,r=Ww(e.y,35,t.height-35)*20;return[n,r]},Wb=e=>{var t;return((t=e.getRootNode)==null?void 0:t.call(e))||(window==null?void 0:window.document)},qb=(e,t)=>({x:Math.min(e.x,t.x),y:Math.min(e.y,t.y),x2:Math.max(e.x2,t.x2),y2:Math.max(e.y2,t.y2)}),bf=({x:e,y:t,width:n,height:r})=>({x:e,y:t,x2:e+n,y2:t+r}),Hb=({x:e,y:t,x2:n,y2:r})=>({x:e,y:t,width:n-e,height:r-t}),qw=e=>({...e.positionAbsolute||{x:0,y:0},width:e.width||0,height:e.height||0}),DM=(e,t)=>Hb(qb(bf(e),bf(t))),Vp=(e,t)=>{const n=Math.max(0,Math.min(e.x+e.width,t.x+t.width)-Math.max(e.x,t.x)),r=Math.max(0,Math.min(e.y+e.height,t.y+t.height)-Math.max(e.y,t.y));return Math.ceil(n*r)},FM=e=>Si(e.width)&&Si(e.height)&&Si(e.x)&&Si(e.y),Si=e=>!isNaN(e)&&isFinite(e),fs=Symbol.for("internals"),Vb=["Enter"," ","Escape"],zM=(e,t)=>{},BM=e=>"nativeEvent"in e;function Gp(e){var o,l;const t=BM(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 Gb=e=>"clientX"in e,al=(e,t)=>{var l,u;const n=Gb(e),r=n?e.clientX:(l=e.touches)==null?void 0:l[0].clientX,o=n?e.clientY:(u=e.touches)==null?void 0:u[0].clientY;return{x:r-((t==null?void 0:t.left)??0),y:o-((t==null?void 0:t.top)??0)}},xm=()=>{var e;return typeof navigator<"u"&&((e=navigator==null?void 0:navigator.userAgent)==null?void 0:e.indexOf("Mac"))>=0},Lf=({id:e,path:t,labelX:n,labelY:r,label:o,labelStyle:l,labelShowBg:u,labelBgStyle:c,labelBgPadding:f,labelBgBorderRadius:m,style:_,markerEnd:g,markerStart:w,interactionWidth:x=20})=>ve.createElement(ve.Fragment,null,ve.createElement("path",{id:e,style:_,d:t,fill:"none",className:"react-flow__edge-path",markerEnd:g,markerStart:w}),x&&ve.createElement("path",{d:t,fill:"none",strokeOpacity:0,strokeWidth:x,className:"react-flow__edge-interaction"}),o&&Si(n)&&Si(r)?ve.createElement(PM,{x:n,y:r,label:o,labelStyle:l,labelShowBg:u,labelBgStyle:c,labelBgPadding:f,labelBgBorderRadius:m}):null);Lf.displayName="BaseEdge";function Jd(e,t,n){return n===void 0?n:r=>{const o=t().edges.find(l=>l.id===e);o&&n(r,{...o})}}function Kb({sourceX:e,sourceY:t,targetX:n,targetY:r}){const o=Math.abs(n-e)/2,l=n<e?n+o:n-o,u=Math.abs(r-t)/2,c=r<t?r+u:r-u;return[l,c,o,u]}function Yb({sourceX:e,sourceY:t,targetX:n,targetY:r,sourceControlX:o,sourceControlY:l,targetControlX:u,targetControlY:c}){const f=e*.125+o*.375+u*.375+n*.125,m=t*.125+l*.375+c*.375+r*.125,_=Math.abs(f-e),g=Math.abs(m-t);return[f,m,_,g]}var uc;(function(e){e.Strict="strict",e.Loose="loose"})(uc||(uc={}));var Xl;(function(e){e.Free="free",e.Vertical="vertical",e.Horizontal="horizontal"})(Xl||(Xl={}));var kf;(function(e){e.Partial="partial",e.Full="full"})(kf||(kf={}));var ol;(function(e){e.Bezier="default",e.Straight="straight",e.Step="step",e.SmoothStep="smoothstep",e.SimpleBezier="simplebezier"})(ol||(ol={}));var jf;(function(e){e.Arrow="arrow",e.ArrowClosed="arrowclosed"})(jf||(jf={}));var _t;(function(e){e.Left="left",e.Top="top",e.Right="right",e.Bottom="bottom"})(_t||(_t={}));function Hw({pos:e,x1:t,y1:n,x2:r,y2:o}){return e===_t.Left||e===_t.Right?[.5*(t+r),n]:[t,.5*(n+o)]}function Jb({sourceX:e,sourceY:t,sourcePosition:n=_t.Bottom,targetX:r,targetY:o,targetPosition:l=_t.Top}){const[u,c]=Hw({pos:n,x1:e,y1:t,x2:r,y2:o}),[f,m]=Hw({pos:l,x1:r,y1:o,x2:e,y2:t}),[_,g,w,x]=Yb({sourceX:e,sourceY:t,targetX:r,targetY:o,sourceControlX:u,sourceControlY:c,targetControlX:f,targetControlY:m});return[`M${e},${t} C${u},${c} ${f},${m} ${r},${o}`,_,g,w,x]}const Ig=p.memo(({sourceX:e,sourceY:t,targetX:n,targetY:r,sourcePosition:o=_t.Bottom,targetPosition:l=_t.Top,label:u,labelStyle:c,labelShowBg:f,labelBgStyle:m,labelBgPadding:_,labelBgBorderRadius:g,style:w,markerEnd:x,markerStart:j,interactionWidth:b})=>{const[N,C,E]=Jb({sourceX:e,sourceY:t,sourcePosition:o,targetX:n,targetY:r,targetPosition:l});return ve.createElement(Lf,{path:N,labelX:C,labelY:E,label:u,labelStyle:c,labelShowBg:f,labelBgStyle:m,labelBgPadding:_,labelBgBorderRadius:g,style:w,markerEnd:x,markerStart:j,interactionWidth:b})});Ig.displayName="SimpleBezierEdge";const Vw={[_t.Left]:{x:-1,y:0},[_t.Right]:{x:1,y:0},[_t.Top]:{x:0,y:-1},[_t.Bottom]:{x:0,y:1}},UM=({source:e,sourcePosition:t=_t.Bottom,target:n})=>t===_t.Left||t===_t.Right?e.x<n.x?{x:1,y:0}:{x:-1,y:0}:e.y<n.y?{x:0,y:1}:{x:0,y:-1},Gw=(e,t)=>Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2));function WM({source:e,sourcePosition:t=_t.Bottom,target:n,targetPosition:r=_t.Top,center:o,offset:l}){const u=Vw[t],c=Vw[r],f={x:e.x+u.x*l,y:e.y+u.y*l},m={x:n.x+c.x*l,y:n.y+c.y*l},_=UM({source:f,sourcePosition:t,target:m}),g=_.x!==0?"x":"y",w=_[g];let x=[],j,b;const N={x:0,y:0},C={x:0,y:0},[E,T,I,K]=Kb({sourceX:e.x,sourceY:e.y,targetX:n.x,targetY:n.y});if(u[g]*c[g]===-1){j=o.x||E,b=o.y||T;const J=[{x:j,y:f.y},{x:j,y:m.y}],Y=[{x:f.x,y:b},{x:m.x,y:b}];u[g]===w?x=g==="x"?J:Y:x=g==="x"?Y:J}else{const J=[{x:f.x,y:m.y}],Y=[{x:m.x,y:f.y}];if(g==="x"?x=u.x===w?Y:J:x=u.y===w?J:Y,t===r){const O=Math.abs(e[g]-n[g]);if(O<=l){const $=Math.min(l-1,l-O);u[g]===w?N[g]=(f[g]>e[g]?-1:1)*$:C[g]=(m[g]>n[g]?-1:1)*$}}if(t!==r){const O=g==="x"?"y":"x",$=u[g]===c[O],z=f[O]>m[O],A=f[O]<m[O];(u[g]===1&&(!$&&z||$&&A)||u[g]!==1&&(!$&&A||$&&z))&&(x=g==="x"?J:Y)}const re={x:f.x+N.x,y:f.y+N.y},ce={x:m.x+C.x,y:m.y+C.y},fe=Math.max(Math.abs(re.x-x[0].x),Math.abs(ce.x-x[0].x)),W=Math.max(Math.abs(re.y-x[0].y),Math.abs(ce.y-x[0].y));fe>=W?(j=(re.x+ce.x)/2,b=x[0].y):(j=x[0].x,b=(re.y+ce.y)/2)}return[[e,{x:f.x+N.x,y:f.y+N.y},...x,{x:m.x+C.x,y:m.y+C.y},n],j,b,I,K]}function qM(e,t,n,r){const o=Math.min(Gw(e,t)/2,Gw(t,n)/2,r),{x:l,y:u}=t;if(e.x===l&&l===n.x||e.y===u&&u===n.y)return`L${l} ${u}`;if(e.y===u){const m=e.x<n.x?-1:1,_=e.y<n.y?1:-1;return`L ${l+o*m},${u}Q ${l},${u} ${l},${u+o*_}`}const c=e.x<n.x?1:-1,f=e.y<n.y?-1:1;return`L ${l},${u+o*f}Q ${l},${u} ${l+o*c},${u}`}function Kp({sourceX:e,sourceY:t,sourcePosition:n=_t.Bottom,targetX:r,targetY:o,targetPosition:l=_t.Top,borderRadius:u=5,centerX:c,centerY:f,offset:m=20}){const[_,g,w,x,j]=WM({source:{x:e,y:t},sourcePosition:n,target:{x:r,y:o},targetPosition:l,center:{x:c,y:f},offset:m});return[_.reduce((N,C,E)=>{let T="";return E>0&&E<_.length-1?T=qM(_[E-1],C,_[E+1],u):T=`${E===0?"M":"L"}${C.x} ${C.y}`,N+=T,N},""),g,w,x,j]}const Dm=p.memo(({sourceX:e,sourceY:t,targetX:n,targetY:r,label:o,labelStyle:l,labelShowBg:u,labelBgStyle:c,labelBgPadding:f,labelBgBorderRadius:m,style:_,sourcePosition:g=_t.Bottom,targetPosition:w=_t.Top,markerEnd:x,markerStart:j,pathOptions:b,interactionWidth:N})=>{const[C,E,T]=Kp({sourceX:e,sourceY:t,sourcePosition:g,targetX:n,targetY:r,targetPosition:w,borderRadius:b==null?void 0:b.borderRadius,offset:b==null?void 0:b.offset});return ve.createElement(Lf,{path:C,labelX:E,labelY:T,label:o,labelStyle:l,labelShowBg:u,labelBgStyle:c,labelBgPadding:f,labelBgBorderRadius:m,style:_,markerEnd:x,markerStart:j,interactionWidth:N})});Dm.displayName="SmoothStepEdge";const Og=p.memo(e=>{var t;return ve.createElement(Dm,{...e,pathOptions:p.useMemo(()=>{var n;return{borderRadius:0,offset:(n=e.pathOptions)==null?void 0:n.offset}},[(t=e.pathOptions)==null?void 0:t.offset])})});Og.displayName="StepEdge";function HM({sourceX:e,sourceY:t,targetX:n,targetY:r}){const[o,l,u,c]=Kb({sourceX:e,sourceY:t,targetX:n,targetY:r});return[`M ${e},${t}L ${n},${r}`,o,l,u,c]}const Pg=p.memo(({sourceX:e,sourceY:t,targetX:n,targetY:r,label:o,labelStyle:l,labelShowBg:u,labelBgStyle:c,labelBgPadding:f,labelBgBorderRadius:m,style:_,markerEnd:g,markerStart:w,interactionWidth:x})=>{const[j,b,N]=HM({sourceX:e,sourceY:t,targetX:n,targetY:r});return ve.createElement(Lf,{path:j,labelX:b,labelY:N,label:o,labelStyle:l,labelShowBg:u,labelBgStyle:c,labelBgPadding:f,labelBgBorderRadius:m,style:_,markerEnd:g,markerStart:w,interactionWidth:x})});Pg.displayName="StraightEdge";function Uh(e,t){return e>=0?.5*e:t*25*Math.sqrt(-e)}function Kw({pos:e,x1:t,y1:n,x2:r,y2:o,c:l}){switch(e){case _t.Left:return[t-Uh(t-r,l),n];case _t.Right:return[t+Uh(r-t,l),n];case _t.Top:return[t,n-Uh(n-o,l)];case _t.Bottom:return[t,n+Uh(o-n,l)]}}function Xb({sourceX:e,sourceY:t,sourcePosition:n=_t.Bottom,targetX:r,targetY:o,targetPosition:l=_t.Top,curvature:u=.25}){const[c,f]=Kw({pos:n,x1:e,y1:t,x2:r,y2:o,c:u}),[m,_]=Kw({pos:l,x1:r,y1:o,x2:e,y2:t,c:u}),[g,w,x,j]=Yb({sourceX:e,sourceY:t,targetX:r,targetY:o,sourceControlX:c,sourceControlY:f,targetControlX:m,targetControlY:_});return[`M${e},${t} C${c},${f} ${m},${_} ${r},${o}`,g,w,x,j]}const bm=p.memo(({sourceX:e,sourceY:t,targetX:n,targetY:r,sourcePosition:o=_t.Bottom,targetPosition:l=_t.Top,label:u,labelStyle:c,labelShowBg:f,labelBgStyle:m,labelBgPadding:_,labelBgBorderRadius:g,style:w,markerEnd:x,markerStart:j,pathOptions:b,interactionWidth:N})=>{const[C,E,T]=Xb({sourceX:e,sourceY:t,sourcePosition:o,targetX:n,targetY:r,targetPosition:l,curvature:b==null?void 0:b.curvature});return ve.createElement(Lf,{path:C,labelX:E,labelY:T,label:u,labelStyle:c,labelShowBg:f,labelBgStyle:m,labelBgPadding:_,labelBgBorderRadius:g,style:w,markerEnd:x,markerStart:j,interactionWidth:N})});bm.displayName="BezierEdge";const Dg=p.createContext(null),VM=Dg.Provider;Dg.Consumer;const GM=()=>p.useContext(Dg),KM=e=>"id"in e&&"source"in e&&"target"in e,YM=({source:e,sourceHandle:t,target:n,targetHandle:r})=>`reactflow__edge-${e}${t||""}-${n}${r||""}`,Yp=(e,t)=>typeof e>"u"?"":typeof e=="string"?e:`${t?`${t}__`:""}${Object.keys(e).sort().map(r=>`${r}=${e[r]}`).join("&")}`,JM=(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)),XM=(e,t)=>{if(!e.source||!e.target)return t;let n;return KM(e)?n={...e}:n={...e,id:YM(e)},JM(n,t)?t:t.concat(n)},Jp=({x:e,y:t},[n,r,o],l,[u,c])=>{const f={x:(e-n)/o,y:(t-r)/o};return l?{x:u*Math.round(f.x/u),y:c*Math.round(f.y/c)}:f},Zb=({x:e,y:t},[n,r,o])=>({x:e*o+n,y:t*o+r}),rc=(e,t=[0,0])=>{if(!e)return{x:0,y:0,positionAbsolute:{x:0,y:0}};const n=(e.width??0)*t[0],r=(e.height??0)*t[1],o={x:e.position.x-n,y:e.position.y-r};return{...o,positionAbsolute:e.positionAbsolute?{x:e.positionAbsolute.x-n,y:e.positionAbsolute.y-r}:o}},Fm=(e,t=[0,0])=>{if(e.length===0)return{x:0,y:0,width:0,height:0};const n=e.reduce((r,o)=>{const{x:l,y:u}=rc(o,t).positionAbsolute;return qb(r,bf({x:l,y:u,width:o.width||0,height:o.height||0}))},{x:1/0,y:1/0,x2:-1/0,y2:-1/0});return Hb(n)},Qb=(e,t,[n,r,o]=[0,0,1],l=!1,u=!1,c=[0,0])=>{const f={x:(t.x-n)/o,y:(t.y-r)/o,width:t.width/o,height:t.height/o},m=[];return e.forEach(_=>{const{width:g,height:w,selectable:x=!0,hidden:j=!1}=_;if(u&&!x||j)return!1;const{positionAbsolute:b}=rc(_,c),N={x:b.x,y:b.y,width:g||0,height:w||0},C=Vp(f,N),E=typeof g>"u"||typeof w>"u"||g===null||w===null,T=l&&C>0,I=(g||0)*(w||0);(E||T||C>=I||_.dragging)&&m.push(_)}),m},e0=(e,t)=>{const n=e.map(r=>r.id);return t.filter(r=>n.includes(r.source)||n.includes(r.target))},t0=(e,t,n,r,o,l=.1)=>{const u=t/(e.width*(1+l)),c=n/(e.height*(1+l)),f=Math.min(u,c),m=Eu(f,r,o),_=e.x+e.width/2,g=e.y+e.height/2,w=t/2-_*m,x=n/2-g*m;return{x:w,y:x,zoom:m}},Vl=(e,t=0)=>e.transition().duration(t);function Yw(e,t,n,r){return(t[n]||[]).reduce((o,l)=>{var u,c;return`${e.id}-${l.id}-${n}`!==r&&o.push({id:l.id||null,type:n,nodeId:e.id,x:(((u=e.positionAbsolute)==null?void 0:u.x)??0)+l.x+l.width/2,y:(((c=e.positionAbsolute)==null?void 0:c.y)??0)+l.y+l.height/2}),o},[])}function ZM(e,t,n,r,o,l){const{x:u,y:c}=al(e),m=t.elementsFromPoint(u,c).find(j=>j.classList.contains("react-flow__handle"));if(m){const j=m.getAttribute("data-nodeid");if(j){const b=Fg(void 0,m),N=m.getAttribute("data-handleid"),C=l({nodeId:j,id:N,type:b});if(C){const E=o.find(T=>T.nodeId===j&&T.type===b&&T.id===N);return{handle:{id:N,type:b,nodeId:j,x:(E==null?void 0:E.x)||n.x,y:(E==null?void 0:E.y)||n.y},validHandleResult:C}}}}let _=[],g=1/0;if(o.forEach(j=>{const b=Math.sqrt((j.x-n.x)**2+(j.y-n.y)**2);if(b<=r){const N=l(j);b<=g&&(b<g?_=[{handle:j,validHandleResult:N}]:b===g&&_.push({handle:j,validHandleResult:N}),g=b)}}),!_.length)return{handle:null,validHandleResult:n0()};if(_.length===1)return _[0];const w=_.some(({validHandleResult:j})=>j.isValid),x=_.some(({handle:j})=>j.type==="target");return _.find(({handle:j,validHandleResult:b})=>x?j.type==="target":w?b.isValid:!0)||_[0]}const QM={source:null,target:null,sourceHandle:null,targetHandle:null},n0=()=>({handleDomNode:null,isValid:!1,connection:QM,endHandle:null});function s0(e,t,n,r,o,l,u){const c=o==="target",f=u.querySelector(`.react-flow__handle[data-id="${e==null?void 0:e.nodeId}-${e==null?void 0:e.id}-${e==null?void 0:e.type}"]`),m={...n0(),handleDomNode:f};if(f){const _=Fg(void 0,f),g=f.getAttribute("data-nodeid"),w=f.getAttribute("data-handleid"),x=f.classList.contains("connectable"),j=f.classList.contains("connectableend"),b={source:c?g:n,sourceHandle:c?w:r,target:c?n:g,targetHandle:c?r:w};m.connection=b,x&&j&&(t===uc.Strict?c&&_==="source"||!c&&_==="target":g!==n||w!==r)&&(m.endHandle={nodeId:g,handleId:w,type:_},m.isValid=l(b))}return m}function eR({nodes:e,nodeId:t,handleId:n,handleType:r}){return e.reduce((o,l)=>{if(l[fs]){const{handleBounds:u}=l[fs];let c=[],f=[];u&&(c=Yw(l,u,"source",`${t}-${n}-${r}`),f=Yw(l,u,"target",`${t}-${n}-${r}`)),o.push(...c,...f)}return o},[])}function Fg(e,t){return e||(t!=null&&t.classList.contains("target")?"target":t!=null&&t.classList.contains("source")?"source":null)}function Y_(e){e==null||e.classList.remove("valid","connecting","react-flow__handle-valid","react-flow__handle-connecting")}function tR(e,t){let n=null;return t?n="valid":e&&!t&&(n="invalid"),n}function r0({event:e,handleId:t,nodeId:n,onConnect:r,isTarget:o,getState:l,setState:u,isValidConnection:c,edgeUpdaterType:f,onEdgeUpdateEnd:m}){const _=Wb(e.target),{connectionMode:g,domNode:w,autoPanOnConnect:x,connectionRadius:j,onConnectStart:b,panBy:N,getNodes:C,cancelConnection:E}=l();let T=0,I;const{x:K,y:U}=al(e),J=_==null?void 0:_.elementFromPoint(K,U),Y=Fg(f,J),re=w==null?void 0:w.getBoundingClientRect();if(!re||!Y)return;let ce,fe=al(e,re),W=!1,O=null,$=!1,z=null;const A=eR({nodes:C(),nodeId:n,handleId:t,handleType:Y}),ee=()=>{if(!x)return;const[G,R]=Ub(fe,re);N({x:G,y:R}),T=requestAnimationFrame(ee)};u({connectionPosition:fe,connectionStatus:null,connectionNodeId:n,connectionHandleId:t,connectionHandleType:Y,connectionStartHandle:{nodeId:n,handleId:t,type:Y},connectionEndHandle:null}),b==null||b(e,{nodeId:n,handleId:t,handleType:Y});function P(G){const{transform:R}=l();fe=al(G,re);const{handle:Z,validHandleResult:X}=ZM(G,_,Jp(fe,R,!1,[1,1]),j,A,ie=>s0(ie,g,n,t,o?"target":"source",c,_));if(I=Z,W||(ee(),W=!0),z=X.handleDomNode,O=X.connection,$=X.isValid,u({connectionPosition:I&&$?Zb({x:I.x,y:I.y},R):fe,connectionStatus:tR(!!I,$),connectionEndHandle:X.endHandle}),!I&&!$&&!z)return Y_(ce);O.source!==O.target&&z&&(Y_(ce),ce=z,z.classList.add("connecting","react-flow__handle-connecting"),z.classList.toggle("valid",$),z.classList.toggle("react-flow__handle-valid",$))}function F(G){var R,Z;(I||z)&&O&&$&&(r==null||r(O)),(Z=(R=l()).onConnectEnd)==null||Z.call(R,G),f&&(m==null||m(G)),Y_(ce),E(),cancelAnimationFrame(T),W=!1,$=!1,O=null,z=null,_.removeEventListener("mousemove",P),_.removeEventListener("mouseup",F),_.removeEventListener("touchmove",P),_.removeEventListener("touchend",F)}_.addEventListener("mousemove",P),_.addEventListener("mouseup",F),_.addEventListener("touchmove",P),_.addEventListener("touchend",F)}const Jw=()=>!0,nR=e=>({connectionStartHandle:e.connectionStartHandle,connectOnClick:e.connectOnClick,noPanClassName:e.noPanClassName}),sR=(e,t,n)=>r=>{const{connectionStartHandle:o,connectionEndHandle:l,connectionClickStartHandle:u}=r;return{connecting:(o==null?void 0:o.nodeId)===e&&(o==null?void 0:o.handleId)===t&&(o==null?void 0:o.type)===n||(l==null?void 0:l.nodeId)===e&&(l==null?void 0:l.handleId)===t&&(l==null?void 0:l.type)===n,clickConnecting:(u==null?void 0:u.nodeId)===e&&(u==null?void 0:u.handleId)===t&&(u==null?void 0:u.type)===n}},i0=p.forwardRef(({type:e="source",position:t=_t.Top,isValidConnection:n,isConnectable:r=!0,isConnectableStart:o=!0,isConnectableEnd:l=!0,id:u,onConnect:c,children:f,className:m,onMouseDown:_,onTouchStart:g,...w},x)=>{var re,ce;const j=u||null,b=e==="target",N=bs(),C=GM(),{connectOnClick:E,noPanClassName:T}=Ln(nR,Os),{connecting:I,clickConnecting:K}=Ln(sR(C,j,e),Os);C||(ce=(re=N.getState()).onError)==null||ce.call(re,"010",ua.error010());const U=fe=>{const{defaultEdgeOptions:W,onConnect:O,hasDefaultEdges:$}=N.getState(),z={...W,...fe};if($){const{edges:A,setEdges:ee}=N.getState();ee(XM(z,A))}O==null||O(z),c==null||c(z)},J=fe=>{if(!C)return;const W=Gb(fe);o&&(W&&fe.button===0||!W)&&r0({event:fe,handleId:j,nodeId:C,onConnect:U,isTarget:b,getState:N.getState,setState:N.setState,isValidConnection:n||N.getState().isValidConnection||Jw}),W?_==null||_(fe):g==null||g(fe)},Y=fe=>{const{onClickConnectStart:W,onClickConnectEnd:O,connectionClickStartHandle:$,connectionMode:z,isValidConnection:A}=N.getState();if(!C||!$&&!o)return;if(!$){W==null||W(fe,{nodeId:C,handleId:j,handleType:e}),N.setState({connectionClickStartHandle:{nodeId:C,type:e,handleId:j}});return}const ee=Wb(fe.target),P=n||A||Jw,{connection:F,isValid:G}=s0({nodeId:C,id:j,type:e},z,$.nodeId,$.handleId||null,$.type,P,ee);G&&U(F),O==null||O(fe),N.setState({connectionClickStartHandle:null})};return ve.createElement("div",{"data-handleid":j,"data-nodeid":C,"data-handlepos":t,"data-id":`${C}-${j}-${e}`,className:Ks(["react-flow__handle",`react-flow__handle-${t}`,"nodrag",T,m,{source:!b,target:b,connectable:r,connectablestart:o,connectableend:l,connecting:K,connectionindicator:r&&(o&&!I||l&&I)}]),onMouseDown:J,onTouchStart:J,onClick:E?Y:void 0,ref:x,...w},f)});i0.displayName="Handle";var km=p.memo(i0);const o0=({data:e,isConnectable:t,targetPosition:n=_t.Top,sourcePosition:r=_t.Bottom})=>ve.createElement(ve.Fragment,null,ve.createElement(km,{type:"target",position:n,isConnectable:t}),e==null?void 0:e.label,ve.createElement(km,{type:"source",position:r,isConnectable:t}));o0.displayName="DefaultNode";var Xp=p.memo(o0);const a0=({data:e,isConnectable:t,sourcePosition:n=_t.Bottom})=>ve.createElement(ve.Fragment,null,e==null?void 0:e.label,ve.createElement(km,{type:"source",position:n,isConnectable:t}));a0.displayName="InputNode";var l0=p.memo(a0);const c0=({data:e,isConnectable:t,targetPosition:n=_t.Top})=>ve.createElement(ve.Fragment,null,ve.createElement(km,{type:"target",position:n,isConnectable:t}),e==null?void 0:e.label);c0.displayName="OutputNode";var u0=p.memo(c0);const zg=()=>null;zg.displayName="GroupNode";const rR=e=>({selectedNodes:e.getNodes().filter(t=>t.selected),selectedEdges:e.edges.filter(t=>t.selected)}),Wh=e=>e.id;function iR(e,t){return Os(e.selectedNodes.map(Wh),t.selectedNodes.map(Wh))&&Os(e.selectedEdges.map(Wh),t.selectedEdges.map(Wh))}const d0=p.memo(({onSelectionChange:e})=>{const t=bs(),{selectedNodes:n,selectedEdges:r}=Ln(rR,iR);return p.useEffect(()=>{const o={nodes:n,edges:r};e==null||e(o),t.getState().onSelectionChange.forEach(l=>l(o))},[n,r,e]),null});d0.displayName="SelectionListener";const oR=e=>!!e.onSelectionChange;function aR({onSelectionChange:e}){const t=Ln(oR);return e||t?ve.createElement(d0,{onSelectionChange:e}):null}const lR=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 ou(e,t){p.useEffect(()=>{typeof e<"u"&&t(e)},[e])}function Gt(e,t,n){p.useEffect(()=>{typeof t<"u"&&n({[e]:t})},[t])}const cR=({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,onConnect:o,onConnectStart:l,onConnectEnd:u,onClickConnectStart:c,onClickConnectEnd:f,nodesDraggable:m,nodesConnectable:_,nodesFocusable:g,edgesFocusable:w,edgesUpdatable:x,elevateNodesOnSelect:j,minZoom:b,maxZoom:N,nodeExtent:C,onNodesChange:E,onEdgesChange:T,elementsSelectable:I,connectionMode:K,snapGrid:U,snapToGrid:J,translateExtent:Y,connectOnClick:re,defaultEdgeOptions:ce,fitView:fe,fitViewOptions:W,onNodesDelete:O,onEdgesDelete:$,onNodeDrag:z,onNodeDragStart:A,onNodeDragStop:ee,onSelectionDrag:P,onSelectionDragStart:F,onSelectionDragStop:G,noPanClassName:R,nodeOrigin:Z,rfId:X,autoPanOnConnect:ie,autoPanOnNodeDrag:ne,onError:ye,connectionRadius:he,isValidConnection:pe,nodeDragThreshold:Ne})=>{const{setNodes:Ue,setEdges:We,setDefaultNodesAndEdges:pt,setMinZoom:Fe,setMaxZoom:tt,setTranslateExtent:lt,setNodeExtent:Ke,reset:je}=Ln(lR,Os),Re=bs();return p.useEffect(()=>{const ht=r==null?void 0:r.map(xe=>({...xe,...ce}));return pt(n,ht),()=>{je()}},[]),Gt("defaultEdgeOptions",ce,Re.setState),Gt("connectionMode",K,Re.setState),Gt("onConnect",o,Re.setState),Gt("onConnectStart",l,Re.setState),Gt("onConnectEnd",u,Re.setState),Gt("onClickConnectStart",c,Re.setState),Gt("onClickConnectEnd",f,Re.setState),Gt("nodesDraggable",m,Re.setState),Gt("nodesConnectable",_,Re.setState),Gt("nodesFocusable",g,Re.setState),Gt("edgesFocusable",w,Re.setState),Gt("edgesUpdatable",x,Re.setState),Gt("elementsSelectable",I,Re.setState),Gt("elevateNodesOnSelect",j,Re.setState),Gt("snapToGrid",J,Re.setState),Gt("snapGrid",U,Re.setState),Gt("onNodesChange",E,Re.setState),Gt("onEdgesChange",T,Re.setState),Gt("connectOnClick",re,Re.setState),Gt("fitViewOnInit",fe,Re.setState),Gt("fitViewOnInitOptions",W,Re.setState),Gt("onNodesDelete",O,Re.setState),Gt("onEdgesDelete",$,Re.setState),Gt("onNodeDrag",z,Re.setState),Gt("onNodeDragStart",A,Re.setState),Gt("onNodeDragStop",ee,Re.setState),Gt("onSelectionDrag",P,Re.setState),Gt("onSelectionDragStart",F,Re.setState),Gt("onSelectionDragStop",G,Re.setState),Gt("noPanClassName",R,Re.setState),Gt("nodeOrigin",Z,Re.setState),Gt("rfId",X,Re.setState),Gt("autoPanOnConnect",ie,Re.setState),Gt("autoPanOnNodeDrag",ne,Re.setState),Gt("onError",ye,Re.setState),Gt("connectionRadius",he,Re.setState),Gt("isValidConnection",pe,Re.setState),Gt("nodeDragThreshold",Ne,Re.setState),ou(e,Ue),ou(t,We),ou(b,Fe),ou(N,tt),ou(Y,lt),ou(C,Ke),null},Xw={display:"none"},uR={position:"absolute",width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0px, 0px, 0px, 0px)",clipPath:"inset(100%)"},f0="react-flow__node-desc",h0="react-flow__edge-desc",dR="react-flow__aria-live",fR=e=>e.ariaLiveMessage;function hR({rfId:e}){const t=Ln(fR);return ve.createElement("div",{id:`${dR}-${e}`,"aria-live":"assertive","aria-atomic":"true",style:uR},t)}function mR({rfId:e,disableKeyboardA11y:t}){return ve.createElement(ve.Fragment,null,ve.createElement("div",{id:`${f0}-${e}`,style:Xw},"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:`${h0}-${e}`,style:Xw},"Press enter or space to select an edge. You can then press delete to remove it or escape to cancel."),!t&&ve.createElement(hR,{rfId:e}))}var Sf=(e=null,t={actInsideInputWithModifier:!0})=>{const[n,r]=p.useState(!1),o=p.useRef(!1),l=p.useRef(new Set([])),[u,c]=p.useMemo(()=>{if(e!==null){const m=(Array.isArray(e)?e:[e]).filter(g=>typeof g=="string").map(g=>g.split("+")),_=m.reduce((g,w)=>g.concat(...w),[]);return[m,_]}return[[],[]]},[e]);return p.useEffect(()=>{const f=typeof document<"u"?document:null,m=(t==null?void 0:t.target)||f;if(e!==null){const _=x=>{if(o.current=x.ctrlKey||x.metaKey||x.shiftKey,(!o.current||o.current&&!t.actInsideInputWithModifier)&&Gp(x))return!1;const b=Qw(x.code,c);l.current.add(x[b]),Zw(u,l.current,!1)&&(x.preventDefault(),r(!0))},g=x=>{if((!o.current||o.current&&!t.actInsideInputWithModifier)&&Gp(x))return!1;const b=Qw(x.code,c);Zw(u,l.current,!0)?(r(!1),l.current.clear()):l.current.delete(x[b]),x.key==="Meta"&&l.current.clear(),o.current=!1},w=()=>{l.current.clear(),r(!1)};return m==null||m.addEventListener("keydown",_),m==null||m.addEventListener("keyup",g),window.addEventListener("blur",w),()=>{m==null||m.removeEventListener("keydown",_),m==null||m.removeEventListener("keyup",g),window.removeEventListener("blur",w)}}},[e,r]),n};function Zw(e,t,n){return e.filter(r=>n||r.length===t.size).some(r=>r.every(o=>t.has(o)))}function Qw(e,t){return t.includes(e)?"code":"key"}function m0(e,t,n,r){var u,c;if(!e.parentNode)return n;const o=t.get(e.parentNode),l=rc(o,r);return m0(o,t,{x:(n.x??0)+l.x,y:(n.y??0)+l.y,z:(((u=o[fs])==null?void 0:u.z)??0)>(n.z??0)?((c=o[fs])==null?void 0:c.z)??0:n.z??0},r)}function _0(e,t,n){e.forEach(r=>{var o;if(r.parentNode&&!e.has(r.parentNode))throw new Error(`Parent node ${r.parentNode} not found`);if(r.parentNode||n!=null&&n[r.id]){const{x:l,y:u,z:c}=m0(r,e,{...r.position,z:((o=r[fs])==null?void 0:o.z)??0},t);r.positionAbsolute={x:l,y:u},r[fs].z=c,n!=null&&n[r.id]&&(r[fs].isParent=!0)}})}function J_(e,t,n,r){const o=new Map,l={},u=r?1e3:0;return e.forEach(c=>{var w;const f=(Si(c.zIndex)?c.zIndex:0)+(c.selected?u:0),m=t.get(c.id),_={...c,positionAbsolute:{x:c.position.x,y:c.position.y}};c.parentNode&&(l[c.parentNode]=!0);const g=(m==null?void 0:m.type)&&(m==null?void 0:m.type)!==c.type;Object.defineProperty(_,fs,{enumerable:!1,value:{handleBounds:g||(w=m==null?void 0:m[fs])==null?void 0:w.handleBounds,z:f}}),o.set(c.id,_)}),_0(o,n,l),o}function p0(e,t={}){const{getNodes:n,width:r,height:o,minZoom:l,maxZoom:u,d3Zoom:c,d3Selection:f,fitViewOnInitDone:m,fitViewOnInit:_,nodeOrigin:g}=e(),w=t.initial&&!m&&_;if(c&&f&&(w||!t.initial)){const j=n().filter(N=>{var E;const C=t.includeHiddenNodes?N.width&&N.height:!N.hidden;return(E=t.nodes)!=null&&E.length?C&&t.nodes.some(T=>T.id===N.id):C}),b=j.every(N=>N.width&&N.height);if(j.length>0&&b){const N=Fm(j,g),{x:C,y:E,zoom:T}=t0(N,r,o,t.minZoom??l,t.maxZoom??u,t.padding??.1),I=aa.translate(C,E).scale(T);return typeof t.duration=="number"&&t.duration>0?c.transform(Vl(f,t.duration),I):c.transform(f,I),!0}}return!1}function _R(e,t){return e.forEach(n=>{const r=t.get(n.id);r&&t.set(r.id,{...r,[fs]:r[fs],selected:n.selected})}),new Map(t)}function pR(e,t){return t.map(n=>{const r=e.find(o=>o.id===n.id);return r&&(n.selected=r.selected),n})}function qh({changedNodes:e,changedEdges:t,get:n,set:r}){const{nodeInternals:o,edges:l,onNodesChange:u,onEdgesChange:c,hasDefaultNodes:f,hasDefaultEdges:m}=n();e!=null&&e.length&&(f&&r({nodeInternals:_R(e,o)}),u==null||u(e)),t!=null&&t.length&&(m&&r({edges:pR(t,l)}),c==null||c(t))}const au=()=>{},gR={zoomIn:au,zoomOut:au,zoomTo:au,getZoom:()=>1,setViewport:au,getViewport:()=>({x:0,y:0,zoom:1}),fitView:()=>!1,setCenter:au,fitBounds:au,project:e=>e,screenToFlowPosition:e=>e,flowToScreenPosition:e=>e,viewportInitialized:!1},yR=e=>({d3Zoom:e.d3Zoom,d3Selection:e.d3Selection}),wR=()=>{const e=bs(),{d3Zoom:t,d3Selection:n}=Ln(yR,Os);return p.useMemo(()=>n&&t?{zoomIn:o=>t.scaleBy(Vl(n,o==null?void 0:o.duration),1.2),zoomOut:o=>t.scaleBy(Vl(n,o==null?void 0:o.duration),1/1.2),zoomTo:(o,l)=>t.scaleTo(Vl(n,l==null?void 0:l.duration),o),getZoom:()=>e.getState().transform[2],setViewport:(o,l)=>{const[u,c,f]=e.getState().transform,m=aa.translate(o.x??u,o.y??c).scale(o.zoom??f);t.transform(Vl(n,l==null?void 0:l.duration),m)},getViewport:()=>{const[o,l,u]=e.getState().transform;return{x:o,y:l,zoom:u}},fitView:o=>p0(e.getState,o),setCenter:(o,l,u)=>{const{width:c,height:f,maxZoom:m}=e.getState(),_=typeof(u==null?void 0:u.zoom)<"u"?u.zoom:m,g=c/2-o*_,w=f/2-l*_,x=aa.translate(g,w).scale(_);t.transform(Vl(n,u==null?void 0:u.duration),x)},fitBounds:(o,l)=>{const{width:u,height:c,minZoom:f,maxZoom:m}=e.getState(),{x:_,y:g,zoom:w}=t0(o,u,c,f,m,(l==null?void 0:l.padding)??.1),x=aa.translate(_,g).scale(w);t.transform(Vl(n,l==null?void 0:l.duration),x)},project:o=>{const{transform:l,snapToGrid:u,snapGrid:c}=e.getState();return console.warn("[DEPRECATED] `project` is deprecated. Instead use `screenToFlowPosition`. There is no need to subtract the react flow bounds anymore! https://reactflow.dev/api-reference/types/react-flow-instance#screen-to-flow-position"),Jp(o,l,u,c)},screenToFlowPosition:o=>{const{transform:l,snapToGrid:u,snapGrid:c,domNode:f}=e.getState();if(!f)return o;const{x:m,y:_}=f.getBoundingClientRect(),g={x:o.x-m,y:o.y-_};return Jp(g,l,u,c)},flowToScreenPosition:o=>{const{transform:l,domNode:u}=e.getState();if(!u)return o;const{x:c,y:f}=u.getBoundingClientRect(),m=Zb(o,l);return{x:m.x+c,y:m.y+f}},viewportInitialized:!0}:gR,[t,n])};function Bg(){const e=wR(),t=bs(),n=p.useCallback(()=>t.getState().getNodes().map(b=>({...b})),[]),r=p.useCallback(b=>t.getState().nodeInternals.get(b),[]),o=p.useCallback(()=>{const{edges:b=[]}=t.getState();return b.map(N=>({...N}))},[]),l=p.useCallback(b=>{const{edges:N=[]}=t.getState();return N.find(C=>C.id===b)},[]),u=p.useCallback(b=>{const{getNodes:N,setNodes:C,hasDefaultNodes:E,onNodesChange:T}=t.getState(),I=N(),K=typeof b=="function"?b(I):b;if(E)C(K);else if(T){const U=K.length===0?I.map(J=>({type:"remove",id:J.id})):K.map(J=>({item:J,type:"reset"}));T(U)}},[]),c=p.useCallback(b=>{const{edges:N=[],setEdges:C,hasDefaultEdges:E,onEdgesChange:T}=t.getState(),I=typeof b=="function"?b(N):b;if(E)C(I);else if(T){const K=I.length===0?N.map(U=>({type:"remove",id:U.id})):I.map(U=>({item:U,type:"reset"}));T(K)}},[]),f=p.useCallback(b=>{const N=Array.isArray(b)?b:[b],{getNodes:C,setNodes:E,hasDefaultNodes:T,onNodesChange:I}=t.getState();if(T){const U=[...C(),...N];E(U)}else if(I){const K=N.map(U=>({item:U,type:"add"}));I(K)}},[]),m=p.useCallback(b=>{const N=Array.isArray(b)?b:[b],{edges:C=[],setEdges:E,hasDefaultEdges:T,onEdgesChange:I}=t.getState();if(T)E([...C,...N]);else if(I){const K=N.map(U=>({item:U,type:"add"}));I(K)}},[]),_=p.useCallback(()=>{const{getNodes:b,edges:N=[],transform:C}=t.getState(),[E,T,I]=C;return{nodes:b().map(K=>({...K})),edges:N.map(K=>({...K})),viewport:{x:E,y:T,zoom:I}}},[]),g=p.useCallback(({nodes:b,edges:N})=>{const{nodeInternals:C,getNodes:E,edges:T,hasDefaultNodes:I,hasDefaultEdges:K,onNodesDelete:U,onEdgesDelete:J,onNodesChange:Y,onEdgesChange:re}=t.getState(),ce=(b||[]).map(z=>z.id),fe=(N||[]).map(z=>z.id),W=E().reduce((z,A)=>{const ee=!ce.includes(A.id)&&A.parentNode&&z.find(F=>F.id===A.parentNode);return(typeof A.deletable=="boolean"?A.deletable:!0)&&(ce.includes(A.id)||ee)&&z.push(A),z},[]),O=T.filter(z=>typeof z.deletable=="boolean"?z.deletable:!0),$=O.filter(z=>fe.includes(z.id));if(W||$){const z=e0(W,O),A=[...$,...z],ee=A.reduce((P,F)=>(P.includes(F.id)||P.push(F.id),P),[]);if((K||I)&&(K&&t.setState({edges:T.filter(P=>!ee.includes(P.id))}),I&&(W.forEach(P=>{C.delete(P.id)}),t.setState({nodeInternals:new Map(C)}))),ee.length>0&&(J==null||J(A),re&&re(ee.map(P=>({id:P,type:"remove"})))),W.length>0&&(U==null||U(W),Y)){const P=W.map(F=>({id:F.id,type:"remove"}));Y(P)}}},[]),w=p.useCallback(b=>{const N=FM(b),C=N?null:t.getState().nodeInternals.get(b.id);return!N&&!C?[null,null,N]:[N?b:qw(C),C,N]},[]),x=p.useCallback((b,N=!0,C)=>{const[E,T,I]=w(b);return E?(C||t.getState().getNodes()).filter(K=>{if(!I&&(K.id===T.id||!K.positionAbsolute))return!1;const U=qw(K),J=Vp(U,E);return N&&J>0||J>=E.width*E.height}):[]},[]),j=p.useCallback((b,N,C=!0)=>{const[E]=w(b);if(!E)return!1;const T=Vp(E,N);return C&&T>0||T>=E.width*E.height},[]);return p.useMemo(()=>({...e,getNodes:n,getNode:r,getEdges:o,getEdge:l,setNodes:u,setEdges:c,addNodes:f,addEdges:m,toObject:_,deleteElements:g,getIntersectingNodes:x,isNodeIntersecting:j}),[e,n,r,o,l,u,c,f,m,_,g,x,j])}const vR={actInsideInputWithModifier:!1};var xR=({deleteKeyCode:e,multiSelectionKeyCode:t})=>{const n=bs(),{deleteElements:r}=Bg(),o=Sf(e,vR),l=Sf(t);p.useEffect(()=>{if(o){const{edges:u,getNodes:c}=n.getState(),f=c().filter(_=>_.selected),m=u.filter(_=>_.selected);r({nodes:f,edges:m}),n.setState({nodesSelectionActive:!1})}},[o]),p.useEffect(()=>{n.setState({multiSelectionActive:l})},[l])};function bR(e){const t=bs();p.useEffect(()=>{let n;const r=()=>{var l,u;if(!e.current)return;const o=Rg(e.current);(o.height===0||o.width===0)&&((u=(l=t.getState()).onError)==null||u.call(l,"004",ua.error004())),t.setState({width:o.width||500,height:o.height||500})};return r(),window.addEventListener("resize",r),e.current&&(n=new ResizeObserver(()=>r()),n.observe(e.current)),()=>{window.removeEventListener("resize",r),n&&e.current&&n.unobserve(e.current)}},[])}const Ug={position:"absolute",width:"100%",height:"100%",top:0,left:0},kR=(e,t)=>e.x!==t.x||e.y!==t.y||e.zoom!==t.k,Hh=e=>({x:e.x,y:e.y,zoom:e.k}),lu=(e,t)=>e.target.closest(`.${t}`),ev=(e,t)=>t===2&&Array.isArray(e)&&e.includes(2),tv=e=>{const t=e.ctrlKey&&xm()?10:1;return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*t},jR=e=>({d3Zoom:e.d3Zoom,d3Selection:e.d3Selection,d3ZoomHandler:e.d3ZoomHandler,userSelectionActive:e.userSelectionActive}),SR=({onMove:e,onMoveStart:t,onMoveEnd:n,onPaneContextMenu:r,zoomOnScroll:o=!0,zoomOnPinch:l=!0,panOnScroll:u=!1,panOnScrollSpeed:c=.5,panOnScrollMode:f=Xl.Free,zoomOnDoubleClick:m=!0,elementsSelectable:_,panOnDrag:g=!0,defaultViewport:w,translateExtent:x,minZoom:j,maxZoom:b,zoomActivationKeyCode:N,preventScrolling:C=!0,children:E,noWheelClassName:T,noPanClassName:I})=>{const K=p.useRef(),U=bs(),J=p.useRef(!1),Y=p.useRef(!1),re=p.useRef(null),ce=p.useRef({x:0,y:0,zoom:0}),{d3Zoom:fe,d3Selection:W,d3ZoomHandler:O,userSelectionActive:$}=Ln(jR,Os),z=Sf(N),A=p.useRef(0),ee=p.useRef(!1),P=p.useRef();return bR(re),p.useEffect(()=>{if(re.current){const F=re.current.getBoundingClientRect(),G=zb().scaleExtent([j,b]).translateExtent(x),R=ji(re.current).call(G),Z=aa.translate(w.x,w.y).scale(Eu(w.zoom,j,b)),X=[[0,0],[F.width,F.height]],ie=G.constrain()(Z,X,x);G.transform(R,ie),G.wheelDelta(tv),U.setState({d3Zoom:G,d3Selection:R,d3ZoomHandler:R.on("wheel.zoom"),transform:[ie.x,ie.y,ie.k],domNode:re.current.closest(".react-flow")})}},[]),p.useEffect(()=>{W&&fe&&(u&&!z&&!$?W.on("wheel.zoom",F=>{if(lu(F,T))return!1;F.preventDefault(),F.stopImmediatePropagation();const G=W.property("__zoom").k||1,R=xm();if(F.ctrlKey&&l&&R){const Ne=zi(F),Ue=tv(F),We=G*Math.pow(2,Ue);fe.scaleTo(W,We,Ne,F);return}const Z=F.deltaMode===1?20:1;let X=f===Xl.Vertical?0:F.deltaX*Z,ie=f===Xl.Horizontal?0:F.deltaY*Z;!R&&F.shiftKey&&f!==Xl.Vertical&&(X=F.deltaY*Z,ie=0),fe.translateBy(W,-(X/G)*c,-(ie/G)*c,{internal:!0});const ne=Hh(W.property("__zoom")),{onViewportChangeStart:ye,onViewportChange:he,onViewportChangeEnd:pe}=U.getState();clearTimeout(P.current),ee.current||(ee.current=!0,t==null||t(F,ne),ye==null||ye(ne)),ee.current&&(e==null||e(F,ne),he==null||he(ne),P.current=setTimeout(()=>{n==null||n(F,ne),pe==null||pe(ne),ee.current=!1},150))},{passive:!1}):typeof O<"u"&&W.on("wheel.zoom",function(F,G){if(!C||lu(F,T))return null;F.preventDefault(),O.call(this,F,G)},{passive:!1}))},[$,u,f,W,fe,O,z,l,C,T,t,e,n]),p.useEffect(()=>{fe&&fe.on("start",F=>{var Z,X;if(!F.sourceEvent||F.sourceEvent.internal)return null;A.current=(Z=F.sourceEvent)==null?void 0:Z.button;const{onViewportChangeStart:G}=U.getState(),R=Hh(F.transform);J.current=!0,ce.current=R,((X=F.sourceEvent)==null?void 0:X.type)==="mousedown"&&U.setState({paneDragging:!0}),G==null||G(R),t==null||t(F.sourceEvent,R)})},[fe,t]),p.useEffect(()=>{fe&&($&&!J.current?fe.on("zoom",null):$||fe.on("zoom",F=>{var R;const{onViewportChange:G}=U.getState();if(U.setState({transform:[F.transform.x,F.transform.y,F.transform.k]}),Y.current=!!(r&&ev(g,A.current??0)),(e||G)&&!((R=F.sourceEvent)!=null&&R.internal)){const Z=Hh(F.transform);G==null||G(Z),e==null||e(F.sourceEvent,Z)}}))},[$,fe,e,g,r]),p.useEffect(()=>{fe&&fe.on("end",F=>{if(!F.sourceEvent||F.sourceEvent.internal)return null;const{onViewportChangeEnd:G}=U.getState();if(J.current=!1,U.setState({paneDragging:!1}),r&&ev(g,A.current??0)&&!Y.current&&r(F.sourceEvent),Y.current=!1,(n||G)&&kR(ce.current,F.transform)){const R=Hh(F.transform);ce.current=R,clearTimeout(K.current),K.current=setTimeout(()=>{G==null||G(R),n==null||n(F.sourceEvent,R)},u?150:0)}})},[fe,u,g,n,r]),p.useEffect(()=>{fe&&fe.filter(F=>{const G=z||o,R=l&&F.ctrlKey;if((g===!0||Array.isArray(g)&&g.includes(1))&&F.button===1&&F.type==="mousedown"&&(lu(F,"react-flow__node")||lu(F,"react-flow__edge")))return!0;if(!g&&!G&&!u&&!m&&!l||$||!m&&F.type==="dblclick"||lu(F,T)&&F.type==="wheel"||lu(F,I)&&(F.type!=="wheel"||u&&F.type==="wheel"&&!z)||!l&&F.ctrlKey&&F.type==="wheel"||!G&&!u&&!R&&F.type==="wheel"||!g&&(F.type==="mousedown"||F.type==="touchstart")||Array.isArray(g)&&!g.includes(F.button)&&(F.type==="mousedown"||F.type==="touchstart"))return!1;const Z=Array.isArray(g)&&g.includes(F.button)||!F.button||F.button<=1;return(!F.ctrlKey||F.type==="wheel")&&Z})},[$,fe,o,l,u,m,g,_,z]),ve.createElement("div",{className:"react-flow__renderer",ref:re,style:Ug},E)},NR=e=>({userSelectionActive:e.userSelectionActive,userSelectionRect:e.userSelectionRect});function CR(){const{userSelectionActive:e,userSelectionRect:t}=Ln(NR,Os);return e&&t?ve.createElement("div",{className:"react-flow__selection react-flow__container",style:{width:t.width,height:t.height,transform:`translate(${t.x}px, ${t.y}px)`}}):null}function nv(e,t){const n=e.find(r=>r.id===t.parentNode);if(n){const r=t.position.x+t.width-n.width,o=t.position.y+t.height-n.height;if(r>0||o>0||t.position.x<0||t.position.y<0){if(n.style={...n.style},n.style.width=n.style.width??n.width,n.style.height=n.style.height??n.height,r>0&&(n.style.width+=r),o>0&&(n.style.height+=o),t.position.x<0){const l=Math.abs(t.position.x);n.position.x=n.position.x-l,n.style.width+=l,t.position.x=0}if(t.position.y<0){const l=Math.abs(t.position.y);n.position.y=n.position.y-l,n.style.height+=l,t.position.y=0}n.width=n.style.width,n.height=n.style.height}}}function ER(e,t){if(e.some(r=>r.type==="reset"))return e.filter(r=>r.type==="reset").map(r=>r.item);const n=e.filter(r=>r.type==="add").map(r=>r.item);return t.reduce((r,o)=>{const l=e.filter(c=>c.id===o.id);if(l.length===0)return r.push(o),r;const u={...o};for(const c of l)if(c)switch(c.type){case"select":{u.selected=c.selected;break}case"position":{typeof c.position<"u"&&(u.position=c.position),typeof c.positionAbsolute<"u"&&(u.positionAbsolute=c.positionAbsolute),typeof c.dragging<"u"&&(u.dragging=c.dragging),u.expandParent&&nv(r,u);break}case"dimensions":{typeof c.dimensions<"u"&&(u.width=c.dimensions.width,u.height=c.dimensions.height),typeof c.updateStyle<"u"&&(u.style={...u.style||{},...c.dimensions}),typeof c.resizing=="boolean"&&(u.resizing=c.resizing),u.expandParent&&nv(r,u);break}case"remove":return r}return r.push(u),r},n)}function AR(e,t){return ER(e,t)}const il=(e,t)=>({id:e,type:"select",selected:t});function mu(e,t){return e.reduce((n,r)=>{const o=t.includes(r.id);return!r.selected&&o?(r.selected=!0,n.push(il(r.id,!0))):r.selected&&!o&&(r.selected=!1,n.push(il(r.id,!1))),n},[])}const X_=(e,t)=>n=>{n.target===t.current&&(e==null||e(n))},$R=e=>({userSelectionActive:e.userSelectionActive,elementsSelectable:e.elementsSelectable,dragging:e.paneDragging}),g0=p.memo(({isSelecting:e,selectionMode:t=kf.Full,panOnDrag:n,onSelectionStart:r,onSelectionEnd:o,onPaneClick:l,onPaneContextMenu:u,onPaneScroll:c,onPaneMouseEnter:f,onPaneMouseMove:m,onPaneMouseLeave:_,children:g})=>{const w=p.useRef(null),x=bs(),j=p.useRef(0),b=p.useRef(0),N=p.useRef(),{userSelectionActive:C,elementsSelectable:E,dragging:T}=Ln($R,Os),I=()=>{x.setState({userSelectionActive:!1,userSelectionRect:null}),j.current=0,b.current=0},K=O=>{l==null||l(O),x.getState().resetSelectedElements(),x.setState({nodesSelectionActive:!1})},U=O=>{if(Array.isArray(n)&&(n!=null&&n.includes(2))){O.preventDefault();return}u==null||u(O)},J=c?O=>c(O):void 0,Y=O=>{const{resetSelectedElements:$,domNode:z}=x.getState();if(N.current=z==null?void 0:z.getBoundingClientRect(),!E||!e||O.button!==0||O.target!==w.current||!N.current)return;const{x:A,y:ee}=al(O,N.current);$(),x.setState({userSelectionRect:{width:0,height:0,startX:A,startY:ee,x:A,y:ee}}),r==null||r(O)},re=O=>{const{userSelectionRect:$,nodeInternals:z,edges:A,transform:ee,onNodesChange:P,onEdgesChange:F,nodeOrigin:G,getNodes:R}=x.getState();if(!e||!N.current||!$)return;x.setState({userSelectionActive:!0,nodesSelectionActive:!1});const Z=al(O,N.current),X=$.startX??0,ie=$.startY??0,ne={...$,x:Z.x<X?Z.x:X,y:Z.y<ie?Z.y:ie,width:Math.abs(Z.x-X),height:Math.abs(Z.y-ie)},ye=R(),he=Qb(z,ne,ee,t===kf.Partial,!0,G),pe=e0(he,A).map(Ue=>Ue.id),Ne=he.map(Ue=>Ue.id);if(j.current!==Ne.length){j.current=Ne.length;const Ue=mu(ye,Ne);Ue.length&&(P==null||P(Ue))}if(b.current!==pe.length){b.current=pe.length;const Ue=mu(A,pe);Ue.length&&(F==null||F(Ue))}x.setState({userSelectionRect:ne})},ce=O=>{if(O.button!==0)return;const{userSelectionRect:$}=x.getState();!C&&$&&O.target===w.current&&(K==null||K(O)),x.setState({nodesSelectionActive:j.current>0}),I(),o==null||o(O)},fe=O=>{C&&(x.setState({nodesSelectionActive:j.current>0}),o==null||o(O)),I()},W=E&&(e||C);return ve.createElement("div",{className:Ks(["react-flow__pane",{dragging:T,selection:e}]),onClick:W?void 0:X_(K,w),onContextMenu:X_(U,w),onWheel:X_(J,w),onMouseEnter:W?void 0:f,onMouseDown:W?Y:void 0,onMouseMove:W?re:m,onMouseUp:W?ce:void 0,onMouseLeave:W?fe:_,ref:w,style:Ug},g,ve.createElement(CR,null))});g0.displayName="Pane";function y0(e,t){if(!e.parentNode)return!1;const n=t.get(e.parentNode);return n?n.selected?!0:y0(n,t):!1}function sv(e,t,n){let r=e;do{if(r!=null&&r.matches(t))return!0;if(r===n.current)return!1;r=r.parentElement}while(r);return!1}function TR(e,t,n,r){return Array.from(e.values()).filter(o=>(o.selected||o.id===r)&&(!o.parentNode||!y0(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 MR(e,t){return!t||t==="parent"?t:[t[0],[t[1][0]-(e.width||0),t[1][1]-(e.height||0)]]}function w0(e,t,n,r,o=[0,0],l){const u=MR(e,e.extent||r);let c=u;if(e.extent==="parent"&&!e.expandParent)if(e.parentNode&&e.width&&e.height){const _=n.get(e.parentNode),{x:g,y:w}=rc(_,o).positionAbsolute;c=_&&Si(g)&&Si(w)&&Si(_.width)&&Si(_.height)?[[g+e.width*o[0],w+e.height*o[1]],[g+_.width-e.width+e.width*o[0],w+_.height-e.height+e.height*o[1]]]:c}else l==null||l("005",ua.error005()),c=u;else if(e.extent&&e.parentNode&&e.extent!=="parent"){const _=n.get(e.parentNode),{x:g,y:w}=rc(_,o).positionAbsolute;c=[[e.extent[0][0]+g,e.extent[0][1]+w],[e.extent[1][0]+g,e.extent[1][1]+w]]}let f={x:0,y:0};if(e.parentNode){const _=n.get(e.parentNode);f=rc(_,o).positionAbsolute}const m=c&&c!=="parent"?Lg(t,c):t;return{position:{x:m.x-f.x,y:m.y-f.y},positionAbsolute:m}}function Z_({nodeId:e,dragItems:t,nodeInternals:n}){const r=t.map(o=>({...n.get(o.id),position:o.position,positionAbsolute:o.positionAbsolute}));return[e?r.find(o=>o.id===e):r[0],r]}const rv=(e,t,n,r)=>{const o=t.querySelectorAll(e);if(!o||!o.length)return null;const l=Array.from(o),u=t.getBoundingClientRect(),c={x:u.width*r[0],y:u.height*r[1]};return l.map(f=>{const m=f.getBoundingClientRect();return{id:f.getAttribute("data-handleid"),position:f.getAttribute("data-handlepos"),x:(m.left-u.left-c.x)/n,y:(m.top-u.top-c.y)/n,...Rg(f)}})};function Xd(e,t,n){return n===void 0?n:r=>{const o=t().nodeInternals.get(e);o&&n(r,{...o})}}function Zp({id:e,store:t,unselect:n=!1,nodeRef:r}){const{addSelectedNodes:o,unselectNodesAndEdges:l,multiSelectionActive:u,nodeInternals:c,onError:f}=t.getState(),m=c.get(e);if(!m){f==null||f("012",ua.error012(e));return}t.setState({nodesSelectionActive:!1}),m.selected?(n||m.selected&&u)&&(l({nodes:[m],edges:[]}),requestAnimationFrame(()=>{var _;return(_=r==null?void 0:r.current)==null?void 0:_.blur()})):o([e])}function RR(){const e=bs();return p.useCallback(({sourceEvent:n})=>{const{transform:r,snapGrid:o,snapToGrid:l}=e.getState(),u=n.touches?n.touches[0].clientX:n.clientX,c=n.touches?n.touches[0].clientY:n.clientY,f={x:(u-r[0])/r[2],y:(c-r[1])/r[2]};return{xSnapped:l?o[0]*Math.round(f.x/o[0]):f.x,ySnapped:l?o[1]*Math.round(f.y/o[1]):f.y,...f}},[])}function Q_(e){return(t,n,r)=>e==null?void 0:e(t,r)}function v0({nodeRef:e,disabled:t=!1,noDragClassName:n,handleSelector:r,nodeId:o,isSelectable:l,selectNodesOnDrag:u}){const c=bs(),[f,m]=p.useState(!1),_=p.useRef([]),g=p.useRef({x:null,y:null}),w=p.useRef(0),x=p.useRef(null),j=p.useRef({x:0,y:0}),b=p.useRef(null),N=p.useRef(!1),C=p.useRef(!1),E=RR();return p.useEffect(()=>{if(e!=null&&e.current){const T=ji(e.current),I=({x:J,y:Y})=>{const{nodeInternals:re,onNodeDrag:ce,onSelectionDrag:fe,updateNodePositions:W,nodeExtent:O,snapGrid:$,snapToGrid:z,nodeOrigin:A,onError:ee}=c.getState();g.current={x:J,y:Y};let P=!1,F={x:0,y:0,x2:0,y2:0};if(_.current.length>1&&O){const R=Fm(_.current,A);F=bf(R)}if(_.current=_.current.map(R=>{const Z={x:J-R.distance.x,y:Y-R.distance.y};z&&(Z.x=$[0]*Math.round(Z.x/$[0]),Z.y=$[1]*Math.round(Z.y/$[1]));const X=[[O[0][0],O[0][1]],[O[1][0],O[1][1]]];_.current.length>1&&O&&!R.extent&&(X[0][0]=R.positionAbsolute.x-F.x+O[0][0],X[1][0]=R.positionAbsolute.x+(R.width??0)-F.x2+O[1][0],X[0][1]=R.positionAbsolute.y-F.y+O[0][1],X[1][1]=R.positionAbsolute.y+(R.height??0)-F.y2+O[1][1]);const ie=w0(R,Z,re,X,A,ee);return P=P||R.position.x!==ie.position.x||R.position.y!==ie.position.y,R.position=ie.position,R.positionAbsolute=ie.positionAbsolute,R}),!P)return;W(_.current,!0,!0),m(!0);const G=o?ce:Q_(fe);if(G&&b.current){const[R,Z]=Z_({nodeId:o,dragItems:_.current,nodeInternals:re});G(b.current,R,Z)}},K=()=>{if(!x.current)return;const[J,Y]=Ub(j.current,x.current);if(J!==0||Y!==0){const{transform:re,panBy:ce}=c.getState();g.current.x=(g.current.x??0)-J/re[2],g.current.y=(g.current.y??0)-Y/re[2],ce({x:J,y:Y})&&I(g.current)}w.current=requestAnimationFrame(K)},U=J=>{var A;const{nodeInternals:Y,multiSelectionActive:re,nodesDraggable:ce,unselectNodesAndEdges:fe,onNodeDragStart:W,onSelectionDragStart:O}=c.getState();C.current=!0;const $=o?W:Q_(O);(!u||!l)&&!re&&o&&((A=Y.get(o))!=null&&A.selected||fe()),o&&l&&u&&Zp({id:o,store:c,nodeRef:e});const z=E(J);if(g.current=z,_.current=TR(Y,ce,z,o),$&&_.current){const[ee,P]=Z_({nodeId:o,dragItems:_.current,nodeInternals:Y});$(J.sourceEvent,ee,P)}};if(t)T.on(".drag",null);else{const J=W$().on("start",Y=>{const{domNode:re,nodeDragThreshold:ce}=c.getState();ce===0&&U(Y);const fe=E(Y);g.current=fe,x.current=(re==null?void 0:re.getBoundingClientRect())||null,j.current=al(Y.sourceEvent,x.current)}).on("drag",Y=>{var W,O;const re=E(Y),{autoPanOnNodeDrag:ce,nodeDragThreshold:fe}=c.getState();if(!N.current&&C.current&&ce&&(N.current=!0,K()),!C.current){const $=re.xSnapped-(((W=g==null?void 0:g.current)==null?void 0:W.x)??0),z=re.ySnapped-(((O=g==null?void 0:g.current)==null?void 0:O.y)??0);Math.sqrt($*$+z*z)>fe&&U(Y)}(g.current.x!==re.xSnapped||g.current.y!==re.ySnapped)&&_.current&&C.current&&(b.current=Y.sourceEvent,j.current=al(Y.sourceEvent,x.current),I(re))}).on("end",Y=>{if(C.current&&(m(!1),N.current=!1,C.current=!1,cancelAnimationFrame(w.current),_.current)){const{updateNodePositions:re,nodeInternals:ce,onNodeDragStop:fe,onSelectionDragStop:W}=c.getState(),O=o?fe:Q_(W);if(re(_.current,!1,!1),O){const[$,z]=Z_({nodeId:o,dragItems:_.current,nodeInternals:ce});O(Y.sourceEvent,$,z)}}}).filter(Y=>{const re=Y.target;return!Y.button&&(!n||!sv(re,`.${n}`,e))&&(!r||sv(re,r,e))});return T.call(J),()=>{T.on(".drag",null)}}}},[e,t,n,r,l,c,o,u,E]),f}function x0(){const e=bs();return p.useCallback(n=>{const{nodeInternals:r,nodeExtent:o,updateNodePositions:l,getNodes:u,snapToGrid:c,snapGrid:f,onError:m,nodesDraggable:_}=e.getState(),g=u().filter(E=>E.selected&&(E.draggable||_&&typeof E.draggable>"u")),w=c?f[0]:5,x=c?f[1]:5,j=n.isShiftPressed?4:1,b=n.x*w*j,N=n.y*x*j,C=g.map(E=>{if(E.positionAbsolute){const T={x:E.positionAbsolute.x+b,y:E.positionAbsolute.y+N};c&&(T.x=f[0]*Math.round(T.x/f[0]),T.y=f[1]*Math.round(T.y/f[1]));const{positionAbsolute:I,position:K}=w0(E,T,r,o,void 0,m);E.position=K,E.positionAbsolute=I}return E});l(C,!0,!1)},[])}const xu={ArrowUp:{x:0,y:-1},ArrowDown:{x:0,y:1},ArrowLeft:{x:-1,y:0},ArrowRight:{x:1,y:0}};var Zd=e=>{const t=({id:n,type:r,data:o,xPos:l,yPos:u,xPosOrigin:c,yPosOrigin:f,selected:m,onClick:_,onMouseEnter:g,onMouseMove:w,onMouseLeave:x,onContextMenu:j,onDoubleClick:b,style:N,className:C,isDraggable:E,isSelectable:T,isConnectable:I,isFocusable:K,selectNodesOnDrag:U,sourcePosition:J,targetPosition:Y,hidden:re,resizeObserver:ce,dragHandle:fe,zIndex:W,isParent:O,noDragClassName:$,noPanClassName:z,initialized:A,disableKeyboardA11y:ee,ariaLabel:P,rfId:F,hasHandleBounds:G})=>{const R=bs(),Z=p.useRef(null),X=p.useRef(J),ie=p.useRef(Y),ne=p.useRef(r),ye=T||E||_||g||w||x,he=x0(),pe=Xd(n,R.getState,g),Ne=Xd(n,R.getState,w),Ue=Xd(n,R.getState,x),We=Xd(n,R.getState,j),pt=Xd(n,R.getState,b),Fe=Ke=>{const{nodeDragThreshold:je}=R.getState();if(T&&(!U||!E||je>0)&&Zp({id:n,store:R,nodeRef:Z}),_){const Re=R.getState().nodeInternals.get(n);Re&&_(Ke,{...Re})}},tt=Ke=>{if(!Gp(Ke))if(Vb.includes(Ke.key)&&T){const je=Ke.key==="Escape";Zp({id:n,store:R,unselect:je,nodeRef:Z})}else!ee&&E&&m&&Object.prototype.hasOwnProperty.call(xu,Ke.key)&&(R.setState({ariaLiveMessage:`Moved selected node ${Ke.key.replace("Arrow","").toLowerCase()}. New position, x: ${~~l}, y: ${~~u}`}),he({x:xu[Ke.key].x,y:xu[Ke.key].y,isShiftPressed:Ke.shiftKey}))};p.useEffect(()=>()=>{Z.current&&(ce==null||ce.unobserve(Z.current))},[]),p.useEffect(()=>{if(Z.current&&!re){const Ke=Z.current;(!A||!G)&&(ce==null||ce.unobserve(Ke),ce==null||ce.observe(Ke))}},[re,A,G]),p.useEffect(()=>{const Ke=ne.current!==r,je=X.current!==J,Re=ie.current!==Y;Z.current&&(Ke||je||Re)&&(Ke&&(ne.current=r),je&&(X.current=J),Re&&(ie.current=Y),R.getState().updateNodeDimensions([{id:n,nodeElement:Z.current,forceUpdate:!0}]))},[n,r,J,Y]);const lt=v0({nodeRef:Z,disabled:re||!E,noDragClassName:$,handleSelector:fe,nodeId:n,isSelectable:T,selectNodesOnDrag:U});return re?null:ve.createElement("div",{className:Ks(["react-flow__node",`react-flow__node-${r}`,{[z]:E},C,{selected:m,selectable:T,parent:O,dragging:lt}]),ref:Z,style:{zIndex:W,transform:`translate(${c}px,${f}px)`,pointerEvents:ye?"all":"none",visibility:A?"visible":"hidden",...N},"data-id":n,"data-testid":`rf__node-${n}`,onMouseEnter:pe,onMouseMove:Ne,onMouseLeave:Ue,onContextMenu:We,onClick:Fe,onDoubleClick:pt,onKeyDown:K?tt:void 0,tabIndex:K?0:void 0,role:K?"button":void 0,"aria-describedby":ee?void 0:`${f0}-${F}`,"aria-label":P},ve.createElement(VM,{value:n},ve.createElement(e,{id:n,data:o,type:r,xPos:l,yPos:u,selected:m,isConnectable:I,sourcePosition:J,targetPosition:Y,dragging:lt,dragHandle:fe,zIndex:W})))};return t.displayName="NodeWrapper",p.memo(t)};const LR=e=>{const t=e.getNodes().filter(n=>n.selected);return{...Fm(t,e.nodeOrigin),transformString:`translate(${e.transform[0]}px,${e.transform[1]}px) scale(${e.transform[2]})`,userSelectionActive:e.userSelectionActive}};function IR({onSelectionContextMenu:e,noPanClassName:t,disableKeyboardA11y:n}){const r=bs(),{width:o,height:l,x:u,y:c,transformString:f,userSelectionActive:m}=Ln(LR,Os),_=x0(),g=p.useRef(null);if(p.useEffect(()=>{var j;n||(j=g.current)==null||j.focus({preventScroll:!0})},[n]),v0({nodeRef:g}),m||!o||!l)return null;const w=e?j=>{const b=r.getState().getNodes().filter(N=>N.selected);e(j,b)}:void 0,x=j=>{Object.prototype.hasOwnProperty.call(xu,j.key)&&_({x:xu[j.key].x,y:xu[j.key].y,isShiftPressed:j.shiftKey})};return ve.createElement("div",{className:Ks(["react-flow__nodesselection","react-flow__container",t]),style:{transform:f}},ve.createElement("div",{ref:g,className:"react-flow__nodesselection-rect",onContextMenu:w,tabIndex:n?void 0:-1,onKeyDown:n?void 0:x,style:{width:o,height:l,top:c,left:u}}))}var OR=p.memo(IR);const PR=e=>e.nodesSelectionActive,b0=({children:e,onPaneClick:t,onPaneMouseEnter:n,onPaneMouseMove:r,onPaneMouseLeave:o,onPaneContextMenu:l,onPaneScroll:u,deleteKeyCode:c,onMove:f,onMoveStart:m,onMoveEnd:_,selectionKeyCode:g,selectionOnDrag:w,selectionMode:x,onSelectionStart:j,onSelectionEnd:b,multiSelectionKeyCode:N,panActivationKeyCode:C,zoomActivationKeyCode:E,elementsSelectable:T,zoomOnScroll:I,zoomOnPinch:K,panOnScroll:U,panOnScrollSpeed:J,panOnScrollMode:Y,zoomOnDoubleClick:re,panOnDrag:ce,defaultViewport:fe,translateExtent:W,minZoom:O,maxZoom:$,preventScrolling:z,onSelectionContextMenu:A,noWheelClassName:ee,noPanClassName:P,disableKeyboardA11y:F})=>{const G=Ln(PR),R=Sf(g),Z=Sf(C),X=Z||ce,ie=Z||U,ne=R||w&&X!==!0;return xR({deleteKeyCode:c,multiSelectionKeyCode:N}),ve.createElement(SR,{onMove:f,onMoveStart:m,onMoveEnd:_,onPaneContextMenu:l,elementsSelectable:T,zoomOnScroll:I,zoomOnPinch:K,panOnScroll:ie,panOnScrollSpeed:J,panOnScrollMode:Y,zoomOnDoubleClick:re,panOnDrag:!R&&X,defaultViewport:fe,translateExtent:W,minZoom:O,maxZoom:$,zoomActivationKeyCode:E,preventScrolling:z,noWheelClassName:ee,noPanClassName:P},ve.createElement(g0,{onSelectionStart:j,onSelectionEnd:b,onPaneClick:t,onPaneMouseEnter:n,onPaneMouseMove:r,onPaneMouseLeave:o,onPaneContextMenu:l,onPaneScroll:u,panOnDrag:X,isSelecting:!!ne,selectionMode:x},e,G&&ve.createElement(OR,{onSelectionContextMenu:A,noPanClassName:P,disableKeyboardA11y:F})))};b0.displayName="FlowRenderer";var DR=p.memo(b0);function FR(e){return Ln(p.useCallback(n=>e?Qb(n.nodeInternals,{x:0,y:0,width:n.width,height:n.height},n.transform,!0):n.getNodes(),[e]))}function zR(e){const t={input:Zd(e.input||l0),default:Zd(e.default||Xp),output:Zd(e.output||u0),group:Zd(e.group||zg)},n={},r=Object.keys(e).filter(o=>!["input","default","output","group"].includes(o)).reduce((o,l)=>(o[l]=Zd(e[l]||Xp),o),n);return{...t,...r}}const BR=({x:e,y:t,width:n,height:r,origin:o})=>!n||!r?{x:e,y:t}:o[0]<0||o[1]<0||o[0]>1||o[1]>1?{x:e,y:t}:{x:e-n*o[0],y:t-r*o[1]},UR=e=>({nodesDraggable:e.nodesDraggable,nodesConnectable:e.nodesConnectable,nodesFocusable:e.nodesFocusable,elementsSelectable:e.elementsSelectable,updateNodeDimensions:e.updateNodeDimensions,onError:e.onError}),k0=e=>{const{nodesDraggable:t,nodesConnectable:n,nodesFocusable:r,elementsSelectable:o,updateNodeDimensions:l,onError:u}=Ln(UR,Os),c=FR(e.onlyRenderVisibleElements),f=p.useRef(),m=p.useMemo(()=>{if(typeof ResizeObserver>"u")return null;const _=new ResizeObserver(g=>{const w=g.map(x=>({id:x.target.getAttribute("data-id"),nodeElement:x.target,forceUpdate:!0}));l(w)});return f.current=_,_},[]);return p.useEffect(()=>()=>{var _;(_=f==null?void 0:f.current)==null||_.disconnect()},[]),ve.createElement("div",{className:"react-flow__nodes",style:Ug},c.map(_=>{var K,U,J;let g=_.type||"default";e.nodeTypes[g]||(u==null||u("003",ua.error003(g)),g="default");const w=e.nodeTypes[g]||e.nodeTypes.default,x=!!(_.draggable||t&&typeof _.draggable>"u"),j=!!(_.selectable||o&&typeof _.selectable>"u"),b=!!(_.connectable||n&&typeof _.connectable>"u"),N=!!(_.focusable||r&&typeof _.focusable>"u"),C=e.nodeExtent?Lg(_.positionAbsolute,e.nodeExtent):_.positionAbsolute,E=(C==null?void 0:C.x)??0,T=(C==null?void 0:C.y)??0,I=BR({x:E,y:T,width:_.width??0,height:_.height??0,origin:e.nodeOrigin});return ve.createElement(w,{key:_.id,id:_.id,className:_.className,style:_.style,type:g,data:_.data,sourcePosition:_.sourcePosition||_t.Bottom,targetPosition:_.targetPosition||_t.Top,hidden:_.hidden,xPos:E,yPos:T,xPosOrigin:I.x,yPosOrigin:I.y,selectNodesOnDrag:e.selectNodesOnDrag,onClick:e.onNodeClick,onMouseEnter:e.onNodeMouseEnter,onMouseMove:e.onNodeMouseMove,onMouseLeave:e.onNodeMouseLeave,onContextMenu:e.onNodeContextMenu,onDoubleClick:e.onNodeDoubleClick,selected:!!_.selected,isDraggable:x,isSelectable:j,isConnectable:b,isFocusable:N,resizeObserver:m,dragHandle:_.dragHandle,zIndex:((K=_[fs])==null?void 0:K.z)??0,isParent:!!((U=_[fs])!=null&&U.isParent),noDragClassName:e.noDragClassName,noPanClassName:e.noPanClassName,initialized:!!_.width&&!!_.height,rfId:e.rfId,disableKeyboardA11y:e.disableKeyboardA11y,ariaLabel:_.ariaLabel,hasHandleBounds:!!((J=_[fs])!=null&&J.handleBounds)})}))};k0.displayName="NodeRenderer";var WR=p.memo(k0);const qR=(e,t,n)=>n===_t.Left?e-t:n===_t.Right?e+t:e,HR=(e,t,n)=>n===_t.Top?e-t:n===_t.Bottom?e+t:e,iv="react-flow__edgeupdater",ov=({position:e,centerX:t,centerY:n,radius:r=10,onMouseDown:o,onMouseEnter:l,onMouseOut:u,type:c})=>ve.createElement("circle",{onMouseDown:o,onMouseEnter:l,onMouseOut:u,className:Ks([iv,`${iv}-${c}`]),cx:qR(t,r,e),cy:HR(n,r,e),r,stroke:"transparent",fill:"transparent"}),VR=()=>!0;var cu=e=>{const t=({id:n,className:r,type:o,data:l,onClick:u,onEdgeDoubleClick:c,selected:f,animated:m,label:_,labelStyle:g,labelShowBg:w,labelBgStyle:x,labelBgPadding:j,labelBgBorderRadius:b,style:N,source:C,target:E,sourceX:T,sourceY:I,targetX:K,targetY:U,sourcePosition:J,targetPosition:Y,elementsSelectable:re,hidden:ce,sourceHandleId:fe,targetHandleId:W,onContextMenu:O,onMouseEnter:$,onMouseMove:z,onMouseLeave:A,edgeUpdaterRadius:ee,onEdgeUpdate:P,onEdgeUpdateStart:F,onEdgeUpdateEnd:G,markerEnd:R,markerStart:Z,rfId:X,ariaLabel:ie,isFocusable:ne,isUpdatable:ye,pathOptions:he,interactionWidth:pe})=>{const Ne=p.useRef(null),[Ue,We]=p.useState(!1),[pt,Fe]=p.useState(!1),tt=bs(),lt=p.useMemo(()=>`url('#${Yp(Z,X)}')`,[Z,X]),Ke=p.useMemo(()=>`url('#${Yp(R,X)}')`,[R,X]);if(ce)return null;const je=Ot=>{var wn;const{edges:pn,addSelectedEdges:Bn,unselectNodesAndEdges:An,multiSelectionActive:gn}=tt.getState(),In=pn.find(ks=>ks.id===n);In&&(re&&(tt.setState({nodesSelectionActive:!1}),In.selected&&gn?(An({nodes:[],edges:[In]}),(wn=Ne.current)==null||wn.blur()):Bn([n])),u&&u(Ot,In))},Re=Jd(n,tt.getState,c),ht=Jd(n,tt.getState,O),xe=Jd(n,tt.getState,$),Ie=Jd(n,tt.getState,z),qe=Jd(n,tt.getState,A),zt=(Ot,pn)=>{if(Ot.button!==0)return;const{edges:Bn,isValidConnection:An}=tt.getState(),gn=pn?E:C,In=(pn?W:fe)||null,wn=pn?"target":"source",ks=An||VR,Kn=pn,js=Bn.find(le=>le.id===n);Fe(!0),F==null||F(Ot,js,wn);const Nr=le=>{Fe(!1),G==null||G(le,js,wn)};r0({event:Ot,handleId:In,nodeId:gn,onConnect:le=>P==null?void 0:P(js,le),isTarget:Kn,getState:tt.getState,setState:tt.setState,isValidConnection:ks,edgeUpdaterType:wn,onEdgeUpdateEnd:Nr})},en=Ot=>zt(Ot,!0),bn=Ot=>zt(Ot,!1),Wt=()=>We(!0),It=()=>We(!1),Sn=!re&&!u,ns=Ot=>{var pn;if(Vb.includes(Ot.key)&&re){const{unselectNodesAndEdges:Bn,addSelectedEdges:An,edges:gn}=tt.getState();Ot.key==="Escape"?((pn=Ne.current)==null||pn.blur(),Bn({edges:[gn.find(wn=>wn.id===n)]})):An([n])}};return ve.createElement("g",{className:Ks(["react-flow__edge",`react-flow__edge-${o}`,r,{selected:f,animated:m,inactive:Sn,updating:Ue}]),onClick:je,onDoubleClick:Re,onContextMenu:ht,onMouseEnter:xe,onMouseMove:Ie,onMouseLeave:qe,onKeyDown:ne?ns:void 0,tabIndex:ne?0:void 0,role:ne?"button":"img","data-testid":`rf__edge-${n}`,"aria-label":ie===null?void 0:ie||`Edge from ${C} to ${E}`,"aria-describedby":ne?`${h0}-${X}`:void 0,ref:Ne},!pt&&ve.createElement(e,{id:n,source:C,target:E,selected:f,animated:m,label:_,labelStyle:g,labelShowBg:w,labelBgStyle:x,labelBgPadding:j,labelBgBorderRadius:b,data:l,style:N,sourceX:T,sourceY:I,targetX:K,targetY:U,sourcePosition:J,targetPosition:Y,sourceHandleId:fe,targetHandleId:W,markerStart:lt,markerEnd:Ke,pathOptions:he,interactionWidth:pe}),ye&&ve.createElement(ve.Fragment,null,(ye==="source"||ye===!0)&&ve.createElement(ov,{position:J,centerX:T,centerY:I,radius:ee,onMouseDown:en,onMouseEnter:Wt,onMouseOut:It,type:"source"}),(ye==="target"||ye===!0)&&ve.createElement(ov,{position:Y,centerX:K,centerY:U,radius:ee,onMouseDown:bn,onMouseEnter:Wt,onMouseOut:It,type:"target"})))};return t.displayName="EdgeWrapper",p.memo(t)};function GR(e){const t={default:cu(e.default||bm),straight:cu(e.bezier||Pg),step:cu(e.step||Og),smoothstep:cu(e.step||Dm),simplebezier:cu(e.simplebezier||Ig)},n={},r=Object.keys(e).filter(o=>!["default","bezier"].includes(o)).reduce((o,l)=>(o[l]=cu(e[l]||bm),o),n);return{...t,...r}}function av(e,t,n=null){const r=((n==null?void 0:n.x)||0)+t.x,o=((n==null?void 0:n.y)||0)+t.y,l=(n==null?void 0:n.width)||t.width,u=(n==null?void 0:n.height)||t.height;switch(e){case _t.Top:return{x:r+l/2,y:o};case _t.Right:return{x:r+l,y:o+u/2};case _t.Bottom:return{x:r+l/2,y:o+u};case _t.Left:return{x:r,y:o+u/2}}}function lv(e,t){return e?e.length===1||!t?e[0]:t&&e.find(n=>n.id===t)||null:null}const KR=(e,t,n,r,o,l)=>{const u=av(n,e,t),c=av(l,r,o);return{sourceX:u.x,sourceY:u.y,targetX:c.x,targetY:c.y}};function YR({sourcePos:e,targetPos:t,sourceWidth:n,sourceHeight:r,targetWidth:o,targetHeight:l,width:u,height:c,transform:f}){const m={x:Math.min(e.x,t.x),y:Math.min(e.y,t.y),x2:Math.max(e.x+n,t.x+o),y2:Math.max(e.y+r,t.y+l)};m.x===m.x2&&(m.x2+=1),m.y===m.y2&&(m.y2+=1);const _=bf({x:(0-f[0])/f[2],y:(0-f[1])/f[2],width:u/f[2],height:c/f[2]}),g=Math.max(0,Math.min(_.x2,m.x2)-Math.max(_.x,m.x)),w=Math.max(0,Math.min(_.y2,m.y2)-Math.max(_.y,m.y));return Math.ceil(g*w)>0}function cv(e){var r,o,l,u,c;const t=((r=e==null?void 0:e[fs])==null?void 0:r.handleBounds)||null,n=t&&(e==null?void 0:e.width)&&(e==null?void 0:e.height)&&typeof((o=e==null?void 0:e.positionAbsolute)==null?void 0:o.x)<"u"&&typeof((l=e==null?void 0:e.positionAbsolute)==null?void 0:l.y)<"u";return[{x:((u=e==null?void 0:e.positionAbsolute)==null?void 0:u.x)||0,y:((c=e==null?void 0:e.positionAbsolute)==null?void 0:c.y)||0,width:(e==null?void 0:e.width)||0,height:(e==null?void 0:e.height)||0},t,!!n]}const JR=[{level:0,isMaxLevel:!0,edges:[]}];function XR(e,t,n=!1){let r=-1;const o=e.reduce((u,c)=>{var _,g;const f=Si(c.zIndex);let m=f?c.zIndex:0;if(n){const w=t.get(c.target),x=t.get(c.source),j=c.selected||(w==null?void 0:w.selected)||(x==null?void 0:x.selected),b=Math.max(((_=x==null?void 0:x[fs])==null?void 0:_.z)||0,((g=w==null?void 0:w[fs])==null?void 0:g.z)||0,1e3);m=(f?c.zIndex:0)+(j?b:0)}return u[m]?u[m].push(c):u[m]=[c],r=m>r?m:r,u},{}),l=Object.entries(o).map(([u,c])=>{const f=+u;return{edges:c,level:f,isMaxLevel:f===r}});return l.length===0?JR:l}function ZR(e,t,n){const r=Ln(p.useCallback(o=>e?o.edges.filter(l=>{const u=t.get(l.source),c=t.get(l.target);return(u==null?void 0:u.width)&&(u==null?void 0:u.height)&&(c==null?void 0:c.width)&&(c==null?void 0:c.height)&&YR({sourcePos:u.positionAbsolute||{x:0,y:0},targetPos:c.positionAbsolute||{x:0,y:0},sourceWidth:u.width,sourceHeight:u.height,targetWidth:c.width,targetHeight:c.height,width:o.width,height:o.height,transform:o.transform})}):o.edges,[e,t]));return XR(r,t,n)}const QR=({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"}),e3=({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"}),uv={[jf.Arrow]:QR,[jf.ArrowClosed]:e3};function t3(e){const t=bs();return p.useMemo(()=>{var o,l;return Object.prototype.hasOwnProperty.call(uv,e)?uv[e]:((l=(o=t.getState()).onError)==null||l.call(o,"009",ua.error009(e)),null)},[e])}const n3=({id:e,type:t,color:n,width:r=12.5,height:o=12.5,markerUnits:l="strokeWidth",strokeWidth:u,orient:c="auto-start-reverse"})=>{const f=t3(t);return f?ve.createElement("marker",{className:"react-flow__arrowhead",id:e,markerWidth:`${r}`,markerHeight:`${o}`,viewBox:"-10 -10 20 20",markerUnits:l,orient:c,refX:"0",refY:"0"},ve.createElement(f,{color:n,strokeWidth:u})):null},s3=({defaultColor:e,rfId:t})=>n=>{const r=[];return n.edges.reduce((o,l)=>([l.markerStart,l.markerEnd].forEach(u=>{if(u&&typeof u=="object"){const c=Yp(u,t);r.includes(c)||(o.push({id:c,color:u.color||e,...u}),r.push(c))}}),o),[]).sort((o,l)=>o.id.localeCompare(l.id))},j0=({defaultColor:e,rfId:t})=>{const n=Ln(p.useCallback(s3({defaultColor:e,rfId:t}),[e,t]),(r,o)=>!(r.length!==o.length||r.some((l,u)=>l.id!==o[u].id)));return ve.createElement("defs",null,n.map(r=>ve.createElement(n3,{id:r.id,key:r.id,type:r.type,color:r.color,width:r.width,height:r.height,markerUnits:r.markerUnits,strokeWidth:r.strokeWidth,orient:r.orient})))};j0.displayName="MarkerDefinitions";var r3=p.memo(j0);const i3=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}),S0=({defaultMarkerColor:e,onlyRenderVisibleElements:t,elevateEdgesOnSelect:n,rfId:r,edgeTypes:o,noPanClassName:l,onEdgeUpdate:u,onEdgeContextMenu:c,onEdgeMouseEnter:f,onEdgeMouseMove:m,onEdgeMouseLeave:_,onEdgeClick:g,edgeUpdaterRadius:w,onEdgeDoubleClick:x,onEdgeUpdateStart:j,onEdgeUpdateEnd:b,children:N})=>{const{edgesFocusable:C,edgesUpdatable:E,elementsSelectable:T,width:I,height:K,connectionMode:U,nodeInternals:J,onError:Y}=Ln(i3,Os),re=ZR(t,J,n);return I?ve.createElement(ve.Fragment,null,re.map(({level:ce,edges:fe,isMaxLevel:W})=>ve.createElement("svg",{key:ce,style:{zIndex:ce},width:I,height:K,className:"react-flow__edges react-flow__container"},W&&ve.createElement(r3,{defaultColor:e,rfId:r}),ve.createElement("g",null,fe.map(O=>{const[$,z,A]=cv(J.get(O.source)),[ee,P,F]=cv(J.get(O.target));if(!A||!F)return null;let G=O.type||"default";o[G]||(Y==null||Y("011",ua.error011(G)),G="default");const R=o[G]||o.default,Z=U===uc.Strict?P.target:(P.target??[]).concat(P.source??[]),X=lv(z.source,O.sourceHandle),ie=lv(Z,O.targetHandle),ne=(X==null?void 0:X.position)||_t.Bottom,ye=(ie==null?void 0:ie.position)||_t.Top,he=!!(O.focusable||C&&typeof O.focusable>"u"),pe=typeof u<"u"&&(O.updatable||E&&typeof O.updatable>"u");if(!X||!ie)return Y==null||Y("008",ua.error008(X,O)),null;const{sourceX:Ne,sourceY:Ue,targetX:We,targetY:pt}=KR($,X,ne,ee,ie,ye);return ve.createElement(R,{key:O.id,id:O.id,className:Ks([O.className,l]),type:G,data:O.data,selected:!!O.selected,animated:!!O.animated,hidden:!!O.hidden,label:O.label,labelStyle:O.labelStyle,labelShowBg:O.labelShowBg,labelBgStyle:O.labelBgStyle,labelBgPadding:O.labelBgPadding,labelBgBorderRadius:O.labelBgBorderRadius,style:O.style,source:O.source,target:O.target,sourceHandleId:O.sourceHandle,targetHandleId:O.targetHandle,markerEnd:O.markerEnd,markerStart:O.markerStart,sourceX:Ne,sourceY:Ue,targetX:We,targetY:pt,sourcePosition:ne,targetPosition:ye,elementsSelectable:T,onEdgeUpdate:u,onContextMenu:c,onMouseEnter:f,onMouseMove:m,onMouseLeave:_,onClick:g,edgeUpdaterRadius:w,onEdgeDoubleClick:x,onEdgeUpdateStart:j,onEdgeUpdateEnd:b,rfId:r,ariaLabel:O.ariaLabel,isFocusable:he,isUpdatable:pe,pathOptions:"pathOptions"in O?O.pathOptions:void 0,interactionWidth:O.interactionWidth})})))),N):null};S0.displayName="EdgeRenderer";var o3=p.memo(S0);const a3=e=>`translate(${e.transform[0]}px,${e.transform[1]}px) scale(${e.transform[2]})`;function l3({children:e}){const t=Ln(a3);return ve.createElement("div",{className:"react-flow__viewport react-flow__container",style:{transform:t}},e)}function c3(e){const t=Bg(),n=p.useRef(!1);p.useEffect(()=>{!n.current&&t.viewportInitialized&&e&&(setTimeout(()=>e(t),1),n.current=!0)},[e,t.viewportInitialized])}const u3={[_t.Left]:_t.Right,[_t.Right]:_t.Left,[_t.Top]:_t.Bottom,[_t.Bottom]:_t.Top},N0=({nodeId:e,handleType:t,style:n,type:r=ol.Bezier,CustomComponent:o,connectionStatus:l})=>{var U,J,Y;const{fromNode:u,handleId:c,toX:f,toY:m,connectionMode:_}=Ln(p.useCallback(re=>({fromNode:re.nodeInternals.get(e),handleId:re.connectionHandleId,toX:(re.connectionPosition.x-re.transform[0])/re.transform[2],toY:(re.connectionPosition.y-re.transform[1])/re.transform[2],connectionMode:re.connectionMode}),[e]),Os),g=(U=u==null?void 0:u[fs])==null?void 0:U.handleBounds;let w=g==null?void 0:g[t];if(_===uc.Loose&&(w=w||(g==null?void 0:g[t==="source"?"target":"source"])),!u||!w)return null;const x=c?w.find(re=>re.id===c):w[0],j=x?x.x+x.width/2:(u.width??0)/2,b=x?x.y+x.height/2:u.height??0,N=(((J=u.positionAbsolute)==null?void 0:J.x)??0)+j,C=(((Y=u.positionAbsolute)==null?void 0:Y.y)??0)+b,E=x==null?void 0:x.position,T=E?u3[E]:null;if(!E||!T)return null;if(o)return ve.createElement(o,{connectionLineType:r,connectionLineStyle:n,fromNode:u,fromHandle:x,fromX:N,fromY:C,toX:f,toY:m,fromPosition:E,toPosition:T,connectionStatus:l});let I="";const K={sourceX:N,sourceY:C,sourcePosition:E,targetX:f,targetY:m,targetPosition:T};return r===ol.Bezier?[I]=Xb(K):r===ol.Step?[I]=Kp({...K,borderRadius:0}):r===ol.SmoothStep?[I]=Kp(K):r===ol.SimpleBezier?[I]=Jb(K):I=`M${N},${C} ${f},${m}`,ve.createElement("path",{d:I,fill:"none",className:"react-flow__connection-path",style:n})};N0.displayName="ConnectionLine";const d3=e=>({nodeId:e.connectionNodeId,handleType:e.connectionHandleType,nodesConnectable:e.nodesConnectable,connectionStatus:e.connectionStatus,width:e.width,height:e.height});function f3({containerStyle:e,style:t,type:n,component:r}){const{nodeId:o,handleType:l,nodesConnectable:u,width:c,height:f,connectionStatus:m}=Ln(d3,Os);return!(o&&l&&c&&u)?null:ve.createElement("svg",{style:e,width:c,height:f,className:"react-flow__edges react-flow__connectionline react-flow__container"},ve.createElement("g",{className:Ks(["react-flow__connection",m])},ve.createElement(N0,{nodeId:o,handleType:l,style:t,type:n,CustomComponent:r,connectionStatus:m})))}function dv(e,t){return p.useRef(null),bs(),p.useMemo(()=>t(e),[e])}const C0=({nodeTypes:e,edgeTypes:t,onMove:n,onMoveStart:r,onMoveEnd:o,onInit:l,onNodeClick:u,onEdgeClick:c,onNodeDoubleClick:f,onEdgeDoubleClick:m,onNodeMouseEnter:_,onNodeMouseMove:g,onNodeMouseLeave:w,onNodeContextMenu:x,onSelectionContextMenu:j,onSelectionStart:b,onSelectionEnd:N,connectionLineType:C,connectionLineStyle:E,connectionLineComponent:T,connectionLineContainerStyle:I,selectionKeyCode:K,selectionOnDrag:U,selectionMode:J,multiSelectionKeyCode:Y,panActivationKeyCode:re,zoomActivationKeyCode:ce,deleteKeyCode:fe,onlyRenderVisibleElements:W,elementsSelectable:O,selectNodesOnDrag:$,defaultViewport:z,translateExtent:A,minZoom:ee,maxZoom:P,preventScrolling:F,defaultMarkerColor:G,zoomOnScroll:R,zoomOnPinch:Z,panOnScroll:X,panOnScrollSpeed:ie,panOnScrollMode:ne,zoomOnDoubleClick:ye,panOnDrag:he,onPaneClick:pe,onPaneMouseEnter:Ne,onPaneMouseMove:Ue,onPaneMouseLeave:We,onPaneScroll:pt,onPaneContextMenu:Fe,onEdgeUpdate:tt,onEdgeContextMenu:lt,onEdgeMouseEnter:Ke,onEdgeMouseMove:je,onEdgeMouseLeave:Re,edgeUpdaterRadius:ht,onEdgeUpdateStart:xe,onEdgeUpdateEnd:Ie,noDragClassName:qe,noWheelClassName:zt,noPanClassName:en,elevateEdgesOnSelect:bn,disableKeyboardA11y:Wt,nodeOrigin:It,nodeExtent:Sn,rfId:ns})=>{const Ot=dv(e,zR),pn=dv(t,GR);return c3(l),ve.createElement(DR,{onPaneClick:pe,onPaneMouseEnter:Ne,onPaneMouseMove:Ue,onPaneMouseLeave:We,onPaneContextMenu:Fe,onPaneScroll:pt,deleteKeyCode:fe,selectionKeyCode:K,selectionOnDrag:U,selectionMode:J,onSelectionStart:b,onSelectionEnd:N,multiSelectionKeyCode:Y,panActivationKeyCode:re,zoomActivationKeyCode:ce,elementsSelectable:O,onMove:n,onMoveStart:r,onMoveEnd:o,zoomOnScroll:R,zoomOnPinch:Z,zoomOnDoubleClick:ye,panOnScroll:X,panOnScrollSpeed:ie,panOnScrollMode:ne,panOnDrag:he,defaultViewport:z,translateExtent:A,minZoom:ee,maxZoom:P,onSelectionContextMenu:j,preventScrolling:F,noDragClassName:qe,noWheelClassName:zt,noPanClassName:en,disableKeyboardA11y:Wt},ve.createElement(l3,null,ve.createElement(o3,{edgeTypes:pn,onEdgeClick:c,onEdgeDoubleClick:m,onEdgeUpdate:tt,onlyRenderVisibleElements:W,onEdgeContextMenu:lt,onEdgeMouseEnter:Ke,onEdgeMouseMove:je,onEdgeMouseLeave:Re,onEdgeUpdateStart:xe,onEdgeUpdateEnd:Ie,edgeUpdaterRadius:ht,defaultMarkerColor:G,noPanClassName:en,elevateEdgesOnSelect:!!bn,disableKeyboardA11y:Wt,rfId:ns},ve.createElement(f3,{style:E,type:C,component:T,containerStyle:I})),ve.createElement("div",{className:"react-flow__edgelabel-renderer"}),ve.createElement(WR,{nodeTypes:Ot,onNodeClick:u,onNodeDoubleClick:f,onNodeMouseEnter:_,onNodeMouseMove:g,onNodeMouseLeave:w,onNodeContextMenu:x,selectNodesOnDrag:$,onlyRenderVisibleElements:W,noPanClassName:en,noDragClassName:qe,disableKeyboardA11y:Wt,nodeOrigin:It,nodeExtent:Sn,rfId:ns})))};C0.displayName="GraphView";var h3=p.memo(C0);const Qp=[[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY],[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY]],el={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:Qp,nodeExtent:Qp,nodesSelectionActive:!1,userSelectionActive:!1,userSelectionRect:null,connectionNodeId:null,connectionHandleId:null,connectionHandleType:"source",connectionPosition:{x:0,y:0},connectionStatus:null,connectionMode:uc.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:zM,isValidConnection:void 0},m3=()=>tA((e,t)=>({...el,setNodes:n=>{const{nodeInternals:r,nodeOrigin:o,elevateNodesOnSelect:l}=t();e({nodeInternals:J_(n,r,o,l)})},getNodes:()=>Array.from(t().nodeInternals.values()),setEdges:n=>{const{defaultEdgeOptions:r={}}=t();e({edges:n.map(o=>({...r,...o}))})},setDefaultNodesAndEdges:(n,r)=>{const o=typeof n<"u",l=typeof r<"u",u=o?J_(n,new Map,t().nodeOrigin,t().elevateNodesOnSelect):new Map;e({nodeInternals:u,edges:l?r:[],hasDefaultNodes:o,hasDefaultEdges:l})},updateNodeDimensions:n=>{const{onNodesChange:r,nodeInternals:o,fitViewOnInit:l,fitViewOnInitDone:u,fitViewOnInitOptions:c,domNode:f,nodeOrigin:m}=t(),_=f==null?void 0:f.querySelector(".react-flow__viewport");if(!_)return;const g=window.getComputedStyle(_),{m22:w}=new window.DOMMatrixReadOnly(g.transform),x=n.reduce((b,N)=>{const C=o.get(N.id);if(C){const E=Rg(N.nodeElement);!!(E.width&&E.height&&(C.width!==E.width||C.height!==E.height||N.forceUpdate))&&(o.set(C.id,{...C,[fs]:{...C[fs],handleBounds:{source:rv(".source",N.nodeElement,w,m),target:rv(".target",N.nodeElement,w,m)}},...E}),b.push({id:C.id,type:"dimensions",dimensions:E}))}return b},[]);_0(o,m);const j=u||l&&!u&&p0(t,{initial:!0,...c});e({nodeInternals:new Map(o),fitViewOnInitDone:j}),(x==null?void 0:x.length)>0&&(r==null||r(x))},updateNodePositions:(n,r=!0,o=!1)=>{const{triggerNodeChanges:l}=t(),u=n.map(c=>{const f={id:c.id,type:"position",dragging:o};return r&&(f.positionAbsolute=c.positionAbsolute,f.position=c.position),f});l(u)},triggerNodeChanges:n=>{const{onNodesChange:r,nodeInternals:o,hasDefaultNodes:l,nodeOrigin:u,getNodes:c,elevateNodesOnSelect:f}=t();if(n!=null&&n.length){if(l){const m=AR(n,c()),_=J_(m,o,u,f);e({nodeInternals:_})}r==null||r(n)}},addSelectedNodes:n=>{const{multiSelectionActive:r,edges:o,getNodes:l}=t();let u,c=null;r?u=n.map(f=>il(f,!0)):(u=mu(l(),n),c=mu(o,[])),qh({changedNodes:u,changedEdges:c,get:t,set:e})},addSelectedEdges:n=>{const{multiSelectionActive:r,edges:o,getNodes:l}=t();let u,c=null;r?u=n.map(f=>il(f,!0)):(u=mu(o,n),c=mu(l(),[])),qh({changedNodes:c,changedEdges:u,get:t,set:e})},unselectNodesAndEdges:({nodes:n,edges:r}={})=>{const{edges:o,getNodes:l}=t(),u=n||l(),c=r||o,f=u.map(_=>(_.selected=!1,il(_.id,!1))),m=c.map(_=>il(_.id,!1));qh({changedNodes:f,changedEdges:m,get:t,set:e})},setMinZoom:n=>{const{d3Zoom:r,maxZoom:o}=t();r==null||r.scaleExtent([n,o]),e({minZoom:n})},setMaxZoom:n=>{const{d3Zoom:r,minZoom:o}=t();r==null||r.scaleExtent([o,n]),e({maxZoom:n})},setTranslateExtent:n=>{var r;(r=t().d3Zoom)==null||r.translateExtent(n),e({translateExtent:n})},resetSelectedElements:()=>{const{edges:n,getNodes:r}=t(),l=r().filter(c=>c.selected).map(c=>il(c.id,!1)),u=n.filter(c=>c.selected).map(c=>il(c.id,!1));qh({changedNodes:l,changedEdges:u,get:t,set:e})},setNodeExtent:n=>{const{nodeInternals:r}=t();r.forEach(o=>{o.positionAbsolute=Lg(o.position,n)}),e({nodeExtent:n,nodeInternals:new Map(r)})},panBy:n=>{const{transform:r,width:o,height:l,d3Zoom:u,d3Selection:c,translateExtent:f}=t();if(!u||!c||!n.x&&!n.y)return!1;const m=aa.translate(r[0]+n.x,r[1]+n.y).scale(r[2]),_=[[0,0],[o,l]],g=u==null?void 0:u.constrain()(m,_,f);return u.transform(c,g),r[0]!==g.x||r[1]!==g.y||r[2]!==g.k},cancelConnection:()=>e({connectionNodeId:el.connectionNodeId,connectionHandleId:el.connectionHandleId,connectionHandleType:el.connectionHandleType,connectionStatus:el.connectionStatus,connectionStartHandle:el.connectionStartHandle,connectionEndHandle:el.connectionEndHandle}),reset:()=>e({...el})}),Object.is),Wg=({children:e})=>{const t=p.useRef(null);return t.current||(t.current=m3()),ve.createElement(RM,{value:t.current},e)};Wg.displayName="ReactFlowProvider";const E0=({children:e})=>p.useContext(Pm)?ve.createElement(ve.Fragment,null,e):ve.createElement(Wg,null,e);E0.displayName="ReactFlowWrapper";const _3={input:l0,default:Xp,output:u0,group:zg},p3={default:bm,straight:Pg,step:Og,smoothstep:Dm,simplebezier:Ig},g3=[0,0],y3=[15,15],w3={x:0,y:0,zoom:1},v3={width:"100%",height:"100%",overflow:"hidden",position:"relative",zIndex:0},A0=p.forwardRef(({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,className:o,nodeTypes:l=_3,edgeTypes:u=p3,onNodeClick:c,onEdgeClick:f,onInit:m,onMove:_,onMoveStart:g,onMoveEnd:w,onConnect:x,onConnectStart:j,onConnectEnd:b,onClickConnectStart:N,onClickConnectEnd:C,onNodeMouseEnter:E,onNodeMouseMove:T,onNodeMouseLeave:I,onNodeContextMenu:K,onNodeDoubleClick:U,onNodeDragStart:J,onNodeDrag:Y,onNodeDragStop:re,onNodesDelete:ce,onEdgesDelete:fe,onSelectionChange:W,onSelectionDragStart:O,onSelectionDrag:$,onSelectionDragStop:z,onSelectionContextMenu:A,onSelectionStart:ee,onSelectionEnd:P,connectionMode:F=uc.Strict,connectionLineType:G=ol.Bezier,connectionLineStyle:R,connectionLineComponent:Z,connectionLineContainerStyle:X,deleteKeyCode:ie="Backspace",selectionKeyCode:ne="Shift",selectionOnDrag:ye=!1,selectionMode:he=kf.Full,panActivationKeyCode:pe="Space",multiSelectionKeyCode:Ne=xm()?"Meta":"Control",zoomActivationKeyCode:Ue=xm()?"Meta":"Control",snapToGrid:We=!1,snapGrid:pt=y3,onlyRenderVisibleElements:Fe=!1,selectNodesOnDrag:tt=!0,nodesDraggable:lt,nodesConnectable:Ke,nodesFocusable:je,nodeOrigin:Re=g3,edgesFocusable:ht,edgesUpdatable:xe,elementsSelectable:Ie,defaultViewport:qe=w3,minZoom:zt=.5,maxZoom:en=2,translateExtent:bn=Qp,preventScrolling:Wt=!0,nodeExtent:It,defaultMarkerColor:Sn="#b1b1b7",zoomOnScroll:ns=!0,zoomOnPinch:Ot=!0,panOnScroll:pn=!1,panOnScrollSpeed:Bn=.5,panOnScrollMode:An=Xl.Free,zoomOnDoubleClick:gn=!0,panOnDrag:In=!0,onPaneClick:wn,onPaneMouseEnter:ks,onPaneMouseMove:Kn,onPaneMouseLeave:js,onPaneScroll:Nr,onPaneContextMenu:On,children:le,onEdgeUpdate:ke,onEdgeContextMenu:Ye,onEdgeDoubleClick:Ge,onEdgeMouseEnter:rt,onEdgeMouseMove:ct,onEdgeMouseLeave:Et,onEdgeUpdateStart:kt,onEdgeUpdateEnd:Kt,edgeUpdaterRadius:xt=10,onNodesChange:Yt,onEdgesChange:qt,noDragClassName:Pt="nodrag",noWheelClassName:At="nowheel",noPanClassName:$t="nopan",fitView:De=!1,fitViewOptions:on,connectOnClick:ut=!0,attributionPosition:tn,proOptions:dt,defaultEdgeOptions:Un,elevateNodesOnSelect:an=!0,elevateEdgesOnSelect:Ys=!1,disableKeyboardA11y:ss=!1,autoPanOnConnect:Wr=!0,autoPanOnNodeDrag:dr=!0,connectionRadius:ii=20,isValidConnection:oi,onError:Ps,style:ue,id:fr,nodeDragThreshold:Gi,...hr},Cr)=>{const qr=fr||"1";return ve.createElement("div",{...hr,style:{...ue,...v3},ref:Cr,className:Ks(["react-flow",o]),"data-testid":"rf__wrapper",id:fr},ve.createElement(E0,null,ve.createElement(h3,{onInit:m,onMove:_,onMoveStart:g,onMoveEnd:w,onNodeClick:c,onEdgeClick:f,onNodeMouseEnter:E,onNodeMouseMove:T,onNodeMouseLeave:I,onNodeContextMenu:K,onNodeDoubleClick:U,nodeTypes:l,edgeTypes:u,connectionLineType:G,connectionLineStyle:R,connectionLineComponent:Z,connectionLineContainerStyle:X,selectionKeyCode:ne,selectionOnDrag:ye,selectionMode:he,deleteKeyCode:ie,multiSelectionKeyCode:Ne,panActivationKeyCode:pe,zoomActivationKeyCode:Ue,onlyRenderVisibleElements:Fe,selectNodesOnDrag:tt,defaultViewport:qe,translateExtent:bn,minZoom:zt,maxZoom:en,preventScrolling:Wt,zoomOnScroll:ns,zoomOnPinch:Ot,zoomOnDoubleClick:gn,panOnScroll:pn,panOnScrollSpeed:Bn,panOnScrollMode:An,panOnDrag:In,onPaneClick:wn,onPaneMouseEnter:ks,onPaneMouseMove:Kn,onPaneMouseLeave:js,onPaneScroll:Nr,onPaneContextMenu:On,onSelectionContextMenu:A,onSelectionStart:ee,onSelectionEnd:P,onEdgeUpdate:ke,onEdgeContextMenu:Ye,onEdgeDoubleClick:Ge,onEdgeMouseEnter:rt,onEdgeMouseMove:ct,onEdgeMouseLeave:Et,onEdgeUpdateStart:kt,onEdgeUpdateEnd:Kt,edgeUpdaterRadius:xt,defaultMarkerColor:Sn,noDragClassName:Pt,noWheelClassName:At,noPanClassName:$t,elevateEdgesOnSelect:Ys,rfId:qr,disableKeyboardA11y:ss,nodeOrigin:Re,nodeExtent:It}),ve.createElement(cR,{nodes:e,edges:t,defaultNodes:n,defaultEdges:r,onConnect:x,onConnectStart:j,onConnectEnd:b,onClickConnectStart:N,onClickConnectEnd:C,nodesDraggable:lt,nodesConnectable:Ke,nodesFocusable:je,edgesFocusable:ht,edgesUpdatable:xe,elementsSelectable:Ie,elevateNodesOnSelect:an,minZoom:zt,maxZoom:en,nodeExtent:It,onNodesChange:Yt,onEdgesChange:qt,snapToGrid:We,snapGrid:pt,connectionMode:F,translateExtent:bn,connectOnClick:ut,defaultEdgeOptions:Un,fitView:De,fitViewOptions:on,onNodesDelete:ce,onEdgesDelete:fe,onNodeDragStart:J,onNodeDrag:Y,onNodeDragStop:re,onSelectionDrag:$,onSelectionDragStart:O,onSelectionDragStop:z,noPanClassName:$t,nodeOrigin:Re,rfId:qr,autoPanOnConnect:Wr,autoPanOnNodeDrag:dr,onError:Ps,connectionRadius:ii,isValidConnection:oi,nodeDragThreshold:Gi}),ve.createElement(aR,{onSelectionChange:W}),le,ve.createElement(IM,{proOptions:dt,position:tn}),ve.createElement(mR,{rfId:qr,disableKeyboardA11y:ss})))});A0.displayName="ReactFlow";const $0=({id:e,x:t,y:n,width:r,height:o,style:l,color:u,strokeColor:c,strokeWidth:f,className:m,borderRadius:_,shapeRendering:g,onClick:w,selected:x})=>{const{background:j,backgroundColor:b}=l||{},N=u||j||b;return ve.createElement("rect",{className:Ks(["react-flow__minimap-node",{selected:x},m]),x:t,y:n,rx:_,ry:_,width:r,height:o,fill:N,stroke:c,strokeWidth:f,shapeRendering:g,onClick:w?C=>w(C,e):void 0})};$0.displayName="MiniMapNode";var x3=p.memo($0);const b3=e=>e.nodeOrigin,k3=e=>e.getNodes().filter(t=>!t.hidden&&t.width&&t.height),ep=e=>e instanceof Function?e:()=>e;function j3({nodeStrokeColor:e="transparent",nodeColor:t="#e2e2e2",nodeClassName:n="",nodeBorderRadius:r=5,nodeStrokeWidth:o=2,nodeComponent:l=x3,onClick:u}){const c=Ln(k3,Os),f=Ln(b3),m=ep(t),_=ep(e),g=ep(n),w=typeof window>"u"||window.chrome?"crispEdges":"geometricPrecision";return ve.createElement(ve.Fragment,null,c.map(x=>{const{x:j,y:b}=rc(x,f).positionAbsolute;return ve.createElement(l,{key:x.id,x:j,y:b,width:x.width,height:x.height,style:x.style,selected:x.selected,className:g(x),color:m(x),borderRadius:r,strokeColor:_(x),strokeWidth:o,shapeRendering:w,onClick:u,id:x.id})}))}var S3=p.memo(j3);const N3=200,C3=150,E3=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?DM(Fm(t,e.nodeOrigin),n):n,rfId:e.rfId}},A3="react-flow__minimap-desc";function T0({style:e,className:t,nodeStrokeColor:n="transparent",nodeColor:r="#e2e2e2",nodeClassName:o="",nodeBorderRadius:l=5,nodeStrokeWidth:u=2,nodeComponent:c,maskColor:f="rgb(240, 240, 240, 0.6)",maskStrokeColor:m="none",maskStrokeWidth:_=1,position:g="bottom-right",onClick:w,onNodeClick:x,pannable:j=!1,zoomable:b=!1,ariaLabel:N="React Flow mini map",inversePan:C=!1,zoomStep:E=10,offsetScale:T=5}){const I=bs(),K=p.useRef(null),{boundingRect:U,viewBB:J,rfId:Y}=Ln(E3,Os),re=(e==null?void 0:e.width)??N3,ce=(e==null?void 0:e.height)??C3,fe=U.width/re,W=U.height/ce,O=Math.max(fe,W),$=O*re,z=O*ce,A=T*O,ee=U.x-($-U.width)/2-A,P=U.y-(z-U.height)/2-A,F=$+A*2,G=z+A*2,R=`${A3}-${Y}`,Z=p.useRef(0);Z.current=O,p.useEffect(()=>{if(K.current){const ne=ji(K.current),ye=Ne=>{const{transform:Ue,d3Selection:We,d3Zoom:pt}=I.getState();if(Ne.sourceEvent.type!=="wheel"||!We||!pt)return;const Fe=-Ne.sourceEvent.deltaY*(Ne.sourceEvent.deltaMode===1?.05:Ne.sourceEvent.deltaMode?1:.002)*E,tt=Ue[2]*Math.pow(2,Fe);pt.scaleTo(We,tt)},he=Ne=>{const{transform:Ue,d3Selection:We,d3Zoom:pt,translateExtent:Fe,width:tt,height:lt}=I.getState();if(Ne.sourceEvent.type!=="mousemove"||!We||!pt)return;const Ke=Z.current*Math.max(1,Ue[2])*(C?-1:1),je={x:Ue[0]-Ne.sourceEvent.movementX*Ke,y:Ue[1]-Ne.sourceEvent.movementY*Ke},Re=[[0,0],[tt,lt]],ht=aa.translate(je.x,je.y).scale(Ue[2]),xe=pt.constrain()(ht,Re,Fe);pt.transform(We,xe)},pe=zb().on("zoom",j?he:null).on("zoom.wheel",b?ye:null);return ne.call(pe),()=>{ne.on("zoom",null)}}},[j,b,C,E]);const X=w?ne=>{const ye=zi(ne);w(ne,{x:ye[0],y:ye[1]})}:void 0,ie=x?(ne,ye)=>{const he=I.getState().nodeInternals.get(ye);x(ne,he)}:void 0;return ve.createElement(xf,{position:g,style:e,className:Ks(["react-flow__minimap",t]),"data-testid":"rf__minimap"},ve.createElement("svg",{width:re,height:ce,viewBox:`${ee} ${P} ${F} ${G}`,role:"img","aria-labelledby":R,ref:K,onClick:X},N&&ve.createElement("title",{id:R},N),ve.createElement(S3,{onClick:ie,nodeColor:r,nodeStrokeColor:n,nodeBorderRadius:l,nodeClassName:o,nodeStrokeWidth:u,nodeComponent:c}),ve.createElement("path",{className:"react-flow__minimap-mask",d:`M${ee-A},${P-A}h${F+A*2}v${G+A*2}h${-F-A*2}z
132
- M${J.x},${J.y}h${J.width}v${J.height}h${-J.width}z`,fill:f,fillRule:"evenodd",stroke:m,strokeWidth:_,pointerEvents:"none"})))}T0.displayName="MiniMap";var $3=p.memo(T0);function T3(){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 M3(){return ve.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 5"},ve.createElement("path",{d:"M0 0h32v4.2H0z"}))}function R3(){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 L3(){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 I3(){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 _u=({children:e,className:t,...n})=>ve.createElement("button",{type:"button",className:Ks(["react-flow__controls-button",t]),...n},e);_u.displayName="ControlButton";const O3=e=>({isInteractive:e.nodesDraggable||e.nodesConnectable||e.elementsSelectable,minZoomReached:e.transform[2]<=e.minZoom,maxZoomReached:e.transform[2]>=e.maxZoom}),M0=({style:e,showZoom:t=!0,showFitView:n=!0,showInteractive:r=!0,fitViewOptions:o,onZoomIn:l,onZoomOut:u,onFitView:c,onInteractiveChange:f,className:m,children:_,position:g="bottom-left"})=>{const w=bs(),[x,j]=p.useState(!1),{isInteractive:b,minZoomReached:N,maxZoomReached:C}=Ln(O3,Os),{zoomIn:E,zoomOut:T,fitView:I}=Bg();if(p.useEffect(()=>{j(!0)},[]),!x)return null;const K=()=>{E(),l==null||l()},U=()=>{T(),u==null||u()},J=()=>{I(o),c==null||c()},Y=()=>{w.setState({nodesDraggable:!b,nodesConnectable:!b,elementsSelectable:!b}),f==null||f(!b)};return ve.createElement(xf,{className:Ks(["react-flow__controls",m]),position:g,style:e,"data-testid":"rf__controls"},t&&ve.createElement(ve.Fragment,null,ve.createElement(_u,{onClick:K,className:"react-flow__controls-zoomin",title:"zoom in","aria-label":"zoom in",disabled:C},ve.createElement(T3,null)),ve.createElement(_u,{onClick:U,className:"react-flow__controls-zoomout",title:"zoom out","aria-label":"zoom out",disabled:N},ve.createElement(M3,null))),n&&ve.createElement(_u,{className:"react-flow__controls-fitview",onClick:J,title:"fit view","aria-label":"fit view"},ve.createElement(R3,null)),r&&ve.createElement(_u,{className:"react-flow__controls-interactive",onClick:Y,title:"toggle interactivity","aria-label":"toggle interactivity"},b?ve.createElement(I3,null):ve.createElement(L3,null)),_)};M0.displayName="Controls";var P3=p.memo(M0),Hi;(function(e){e.Lines="lines",e.Dots="dots",e.Cross="cross"})(Hi||(Hi={}));function D3({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 F3({color:e,radius:t}){return ve.createElement("circle",{cx:t,cy:t,r:t,fill:e})}const z3={[Hi.Dots]:"#91919a",[Hi.Lines]:"#eee",[Hi.Cross]:"#e2e2e2"},B3={[Hi.Dots]:1,[Hi.Lines]:1,[Hi.Cross]:6},U3=e=>({transform:e.transform,patternId:`pattern-${e.rfId}`});function R0({id:e,variant:t=Hi.Dots,gap:n=20,size:r,lineWidth:o=1,offset:l=2,color:u,style:c,className:f}){const m=p.useRef(null),{transform:_,patternId:g}=Ln(U3,Os),w=u||z3[t],x=r||B3[t],j=t===Hi.Dots,b=t===Hi.Cross,N=Array.isArray(n)?n:[n,n],C=[N[0]*_[2]||1,N[1]*_[2]||1],E=x*_[2],T=b?[E,E]:C,I=j?[E/l,E/l]:[T[0]/l,T[1]/l];return ve.createElement("svg",{className:Ks(["react-flow__background",f]),style:{...c,position:"absolute",width:"100%",height:"100%",top:0,left:0},ref:m,"data-testid":"rf__background"},ve.createElement("pattern",{id:g+e,x:_[0]%C[0],y:_[1]%C[1],width:C[0],height:C[1],patternUnits:"userSpaceOnUse",patternTransform:`translate(-${I[0]},-${I[1]})`},j?ve.createElement(F3,{color:w,radius:E/l}):ve.createElement(D3,{dimensions:T,color:w,lineWidth:o})),ve.createElement("rect",{x:"0",y:"0",width:"100%",height:"100%",fill:`url(#${g+e})`}))}R0.displayName="Background";var W3=p.memo(R0);function L0(e,t={}){const n=e&&typeof e=="object"&&!Array.isArray(e)?e:null;if(!n)return null;const r=typeof n.x=="number"&&Number.isFinite(n.x)?n.x:null,o=typeof n.y=="number"&&Number.isFinite(n.y)?n.y:null,l=typeof n.zoom=="number"&&Number.isFinite(n.zoom)?n.zoom:null;if(r===null||o===null||l===null)return null;const u=typeof t.maxAbsTranslate=="number"&&Number.isFinite(t.maxAbsTranslate)?Math.abs(t.maxAbsTranslate):1e6;if(Math.abs(r)>u||Math.abs(o)>u)return null;const c=typeof t.minZoom=="number"&&Number.isFinite(t.minZoom)?t.minZoom:.025,f=typeof t.maxZoom=="number"&&Number.isFinite(t.maxZoom)?t.maxZoom:6,m=Math.min(c,f),_=Math.max(c,f);return{x:r,y:o,zoom:Math.min(_,Math.max(m,l))}}function jm(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 q3(e){const t=String(e||"").trim();if(!t)return"entity";const n=t.indexOf(":");if(n<=0||n>=t.length-1)return"entity";const r=t.slice(0,n).toLowerCase(),o=t.slice(n+1).toLowerCase();if(r==="ex"){const l=o.indexOf("-"),u=l>0?o.slice(0,l):o;return u==="person"?"person":u==="org"?"org":u==="concept"?"concept":u==="claim"?"claim":u==="event"?"event":u==="doc"?"doc":u==="thing"?"thing":"entity"}return r==="schema"||r==="skos"||r==="dcterms"||r==="rdf"||r==="cito"?"vocab":"entity"}function H3(e){const t=String(e||"").trim();if(!t)return"";const n=t.indexOf(":");if(n<=0||n>=t.length-1)return jm(t);const r=t.slice(0,n).toLowerCase(),o=t.slice(n+1);if(r==="ex"){const l=o.indexOf("-");if(l>0&&l<o.length-1)return o.slice(l+1)}return jm(t)}function eg(e){const r=Math.max(1,Math.ceil(Math.sqrt(e.length))),o={};for(let l=0;l<e.length;l++){const u=Math.floor(l/r),c=l%r;o[e[l]]={x:c*240,y:u*120}}return o}function tg(e){const t=String(e??"");let n=2166136261;for(let r=0;r<t.length;r++)n^=t.charCodeAt(r),n=Math.imul(n,16777619);return n>>>0}function I0(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 V3(e,t){const n={},r=e.length;if(!r)return n;const o=Math.max(260,Math.sqrt(r)*150),l=t%360*Math.PI/180;for(let u=0;u<r;u++){const c=l+2*Math.PI*u/r;n[e[u]]={x:o*Math.cos(c),y:o*Math.sin(c)}}return n}function fv(e,t,n){var j;const r={};if(!e.length)return r;const o=new Map;for(const b of e)o.set(b,new Set);for(const b of t){const N=String((b==null?void 0:b.source)||"").trim(),C=String((b==null?void 0:b.target)||"").trim();if(!N||!C||N===C)continue;const E=o.get(N),T=o.get(C);E&&E.add(C),T&&T.add(N)}let l=e[0],u=-1;for(const b of e){const N=((j=o.get(b))==null?void 0:j.size)??0;(N>u||N===u&&b.localeCompare(l)<0)&&(l=b,u=N)}const c=new Map,f=[];for(c.set(l,0),f.push(l);f.length;){const b=f.shift(),N=c.get(b)??0,C=Array.from(o.get(b)??[]);C.sort((E,T)=>E.localeCompare(T));for(const E of C)c.has(E)||(c.set(E,N+1),f.push(E))}let m=0;for(const b of c.values())m=Math.max(m,b);for(const b of e)c.has(b)||c.set(b,m+1);const _=new Map;for(const b of e){const N=c.get(b)??0,C=_.get(N);C?C.push(b):_.set(N,[b])}const g=Array.from(_.keys()).sort((b,N)=>b-N),w=260,x=n%360*Math.PI/180;for(const b of g){const N=_.get(b)||[];if(N.sort((I,K)=>I.localeCompare(K)),b===0){if(N.length===1)r[N[0]]={x:0,y:0};else for(let K=0;K<N.length;K++){const U=x+2*Math.PI*K/N.length;r[N[K]]={x:80*Math.cos(U),y:80*Math.sin(U)}}continue}const C=w*b,E=N.length;if(E===1){r[N[0]]={x:C,y:0};continue}const T=x+b*.35;for(let I=0;I<E;I++){const K=T+2*Math.PI*I/E;r[N[I]]={x:C*Math.cos(K),y:C*Math.sin(K)}}}return r}function du(e,t={}){const n=t.kind??"grid",r=typeof t.seed=="number"&&Number.isFinite(t.seed)?Math.trunc(t.seed):0,o=e.nodes.map(l=>l.id);if(n==="grid")return eg(o);if(n==="circle")return V3(o,r);if(n==="radial")return fv(o,e.edges,r);if(n==="force"){const l=fv(o,e.edges,r),u=I0(r||1),c=Math.max(10,Math.min(42,Math.sqrt(o.length)*2.75)),f={};for(const m of o){const _=l[m]||{x:0,y:0};f[m]={x:_.x+(u()-.5)*c,y:_.y+(u()-.5)*c}}return f}return eg(o)}function G3(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 K3(e,t={}){const n=!!(t.groupEdges??!0),r=Math.max(1,t.maxEdgeLabelPredicates??3),o=G3(e),l=new Set;for(const w of o){const x=String(w.subject||"").trim(),j=String(w.object||"").trim();x&&l.add(x),j&&l.add(j)}const u=Array.from(l);u.sort((w,x)=>w.localeCompare(x));const c=eg(u),f=u.map(w=>({id:w,type:"default",data:{label:H3(w),kind:q3(w)},position:c[w]||{x:0,y:0}})),m=new Map,_=(w,x)=>{const j=String(w.subject||"").trim(),b=String(w.object||"").trim(),N=String(w.predicate||"").trim();return n?`edge:${j}:${b}`:`edge:${x}:${j}:${N}:${b}`};for(let w=0;w<o.length;w++){const x=o[w],j=_(x,w),b=m.get(j);b?b.push(x):m.set(j,[x])}const g=[];for(const[w,x]of m.entries()){const j=x[0],b=String(j.subject||"").trim(),N=String(j.object||"").trim();if(!b||!N)continue;const C=new Map;for(const J of x){const Y=String(J.predicate||"").trim();Y&&C.set(Y,(C.get(Y)||0)+1)}const E=Array.from(C.entries());E.sort((J,Y)=>Y[1]-J[1]||J[0].localeCompare(Y[0]));const I=E.slice(0,r).map(([J,Y])=>Y>1?`${jm(J)}×${Y}`:jm(J)).join(" | "),K=E.length>r?` +${E.length-r}`:"",U=`${I}${K}`.trim();g.push({id:w,source:b,target:N,label:U,animated:!1,data:{assertions:x,predicateSummary:U}})}return{nodes:f,edges:g}}function Y3(e,t,n,r={}){const o=r.directed!==!1,l=String(t||"").trim(),u=String(n||"").trim();if(!l||!u)return null;if(l===u)return{nodeIds:[l],edgeIds:[]};const c=new Map,f=(b,N,C)=>{const E=c.get(b);E?E.push({to:N,edgeId:C}):c.set(b,[{to:N,edgeId:C}])};for(const b of e.edges)f(b.source,b.target,b.id),o||f(b.target,b.source,b.id);const m=[l],_=new Map,g=new Map;for(_.set(l,null),g.set(l,null);m.length;){const b=m.shift(),N=c.get(b)||[];for(const C of N)if(!_.has(C.to)){if(_.set(C.to,b),g.set(C.to,C.edgeId),C.to===u){m.length=0;break}m.push(C.to)}}if(!_.has(u))return null;const w=[],x=[];let j=u;for(;j;){w.push(j);const b=g.get(j);b&&x.push(b),j=_.get(j)||null}return w.reverse(),x.reverse(),{nodeIds:w,edgeIds:x}}const hv={seed:1,dt:1,springLength:240,springStrength:.03,repulsionStrength:9e3,centeringStrength:.003,damping:.85,maxSpeed:90,maxRepulsionNodes:320};function Vh(e,t={}){const n={...hv,...t,seed:typeof t.seed=="number"&&Number.isFinite(t.seed)?Math.trunc(t.seed):hv.seed},r=e.nodes.map(x=>x.id),o=r.length,l=new Float64Array(2*o),u=new Float64Array(2*o),c=new Float64Array(2*o),f=new Map;for(let x=0;x<o;x++)f.set(r[x],x);const m=t.positions??du(e,{kind:"force",seed:n.seed}),_=I0(n.seed||1),g=Math.max(8,Math.min(38,Math.sqrt(o)*2.25));for(let x=0;x<o;x++){const j=r[x],b=m[j],N=typeof(b==null?void 0:b.x)=="number"&&Number.isFinite(b.x)?b.x:(_()-.5)*500,C=typeof(b==null?void 0:b.y)=="number"&&Number.isFinite(b.y)?b.y:(_()-.5)*500;l[2*x]=N+(_()-.5)*g,l[2*x+1]=C+(_()-.5)*g,u[2*x]=0,u[2*x+1]=0}const w=[];for(const x of e.edges){const j=f.get(String((x==null?void 0:x.source)||"").trim()),b=f.get(String((x==null?void 0:x.target)||"").trim());typeof j!="number"||typeof b!="number"||j===b||w.push(j,b)}return{nodeIds:r,pos:l,vel:u,acc:c,edges:new Uint32Array(w),options:n,tick:0}}function J3(e,t=1){const n=e.nodeIds.length;if(!n)return;const r=e.options,o=r.dt;for(let l=0;l<Math.max(1,Math.trunc(t));l++){if(e.acc.fill(0),n<=r.maxRepulsionNodes){const x=r.repulsionStrength;for(let j=0;j<n;j++){const b=e.pos[2*j],N=e.pos[2*j+1];for(let C=j+1;C<n;C++){const E=e.pos[2*C]-b,T=e.pos[2*C+1]-N,I=E*E+T*T+1e-6,K=1/Math.sqrt(I),U=x/I,J=U*E*K,Y=U*T*K;e.acc[2*j]-=J,e.acc[2*j+1]-=Y,e.acc[2*C]+=J,e.acc[2*C+1]+=Y}}}const c=r.springLength,f=r.springStrength,m=e.edges;for(let x=0;x<m.length;x+=2){const j=m[x],b=m[x+1],N=e.pos[2*j],C=e.pos[2*j+1],E=e.pos[2*b],T=e.pos[2*b+1],I=E-N,K=T-C,U=I*I+K*K+1e-6,J=Math.sqrt(U),Y=f*(J-c),re=Y*I/J,ce=Y*K/J;e.acc[2*j]+=re,e.acc[2*j+1]+=ce,e.acc[2*b]-=re,e.acc[2*b+1]-=ce}const _=r.centeringStrength;for(let x=0;x<n;x++)e.acc[2*x]+=-_*e.pos[2*x],e.acc[2*x+1]+=-_*e.pos[2*x+1];const g=r.damping,w=r.maxSpeed;for(let x=0;x<n;x++){let j=(e.vel[2*x]+e.acc[2*x]*o)*g,b=(e.vel[2*x+1]+e.acc[2*x+1]*o)*g;const N=Math.sqrt(j*j+b*b);if(N>w){const C=w/N;j*=C,b*=C}e.vel[2*x]=j,e.vel[2*x+1]=b,e.pos[2*x]+=j*o,e.pos[2*x+1]+=b*o}e.tick+=1}}function X3(e){const t=e.nodeIds.length;if(!t)return 0;let n=0;for(let r=0;r<t;r++){const o=e.vel[2*r],l=e.vel[2*r+1];n+=Math.sqrt(o*o+l*l)}return n/t}function Z3(e){const t={},n=e.nodeIds.length;for(let r=0;r<n;r++)t[e.nodeIds[r]]={x:e.pos[2*r],y:e.pos[2*r+1]};return t}function mv(e,t="session"){const n=String(e??"").trim().toLowerCase();return n==="run"||n==="session"||n==="global"||n==="all"?n:t}function Q3(){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 eL(){return s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16","aria-hidden":"true",focusable:"false",children:[s.jsx("rect",{x:"3",y:"3",width:"3",height:"3",rx:"1"}),s.jsx("rect",{x:"3",y:"7",width:"3",height:"3",rx:"1"}),s.jsx("rect",{x:"3",y:"11",width:"3",height:"3",rx:"1"}),s.jsx("rect",{x:"8",y:"3.5",width:"6",height:"2",rx:"1",fill:"none",strokeWidth:"1.4"}),s.jsx("rect",{x:"8",y:"7.5",width:"6",height:"2",rx:"1",fill:"none",strokeWidth:"1.4"}),s.jsx("rect",{x:"8",y:"11.5",width:"6",height:"2",rx:"1",fill:"none",strokeWidth:"1.4"})]})}function O0(e,t,n,r){const o=typeof e=="number"&&Number.isFinite(e)?e:r;return Math.min(n,Math.max(t,o))}function Qd(e){const t=O0(e,.6,2.4,1),n=240*t,r=9e3*t*t;return{springLength:n,repulsionStrength:r}}const Nf="abstractuic_amx_saved_layouts_v1",ng=.025,sg=6,P0=1e6;function qg(){if(typeof window>"u")return null;try{return window.localStorage}catch{return null}}function rg(e,t="grid"){const n=String(e??"").trim().toLowerCase();return n==="grid"||n==="circle"||n==="radial"||n==="force"?n:t}function tL(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:null;if(!t)return null;const n=typeof t.x=="number"&&Number.isFinite(t.x)?t.x:null,r=typeof t.y=="number"&&Number.isFinite(t.y)?t.y:null;return n===null||r===null?null:{x:n,y:r}}function _v(e){const t=qg();if(!t)return null;const n=String(e??"").trim();if(!n)return null;try{const r=t.getItem(Nf);if(!r)return null;const o=JSON.parse(r),l=o&&typeof o=="object"&&!Array.isArray(o)?o:null;if(!l)return null;const u=l[n],c=u&&typeof u=="object"&&!Array.isArray(u)?u:null;if(!c)return null;const f=c.version===1?1:null;if(f===null)return null;const m=rg(c.kind,"grid"),_=typeof c.seed=="number"&&Number.isFinite(c.seed)?Math.trunc(c.seed):tg(n),g=c.positions&&typeof c.positions=="object"&&!Array.isArray(c.positions)?c.positions:null,w={};if(g)for(const[b,N]of Object.entries(g)){const C=tL(N);C&&(w[String(b)]=C)}const x=L0(c.viewport,{minZoom:ng,maxZoom:sg,maxAbsTranslate:P0})??void 0,j=typeof c.saved_at=="string"&&c.saved_at.trim()?c.saved_at.trim():"";return{version:f,kind:m,seed:_,positions:w,viewport:x,saved_at:j}}catch{return null}}function nL(e,t){const n=qg();if(!n)return;const r=String(e??"").trim();if(r)try{const o=n.getItem(Nf),l=o?JSON.parse(o):null,u=l&&typeof l=="object"&&!Array.isArray(l)?{...l}:{};u[r]=t,n.setItem(Nf,JSON.stringify(u))}catch{}}function sL(e){const t=qg();if(!t)return;const n=String(e??"").trim();if(n)try{const r=t.getItem(Nf);if(!r)return;const o=JSON.parse(r),l=o&&typeof o=="object"&&!Array.isArray(o)?{...o}:null;if(!l||!(n in l))return;delete l[n],t.setItem(Nf,JSON.stringify(l))}catch{}}function rL(e){const t=String(e??"").trim();if(!t)return;const n=Number(t);if(Number.isFinite(n))return n}function tp(e,t){const n=!!(t!=null&&t.allowZero),r=!!(t!=null&&t.allowNegativeOne),o=String(e??"").trim();if(!o)return;const l=Number(o);if(!Number.isFinite(l))return;const u=Math.trunc(l);if(r&&u===-1)return-1;if(!(!n&&u<=0)&&!(n&&u<0))return u}function iL(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e,n=typeof t.recall_level=="string"?t.recall_level:"",r=t.applied&&typeof t.applied=="object"&&!Array.isArray(t.applied)?t.applied:null,o=[];return n&&o.push(`recall_level=${n}`),r&&(typeof r.limit=="number"&&o.push(`limit=${r.limit}`),typeof r.min_score=="number"&&o.push(`min_score=${r.min_score}`),typeof r.max_input_tokens=="number"&&o.push(`max_input_tokens=${r.max_input_tokens}`)),o.length?o.join(" · "):null}function oL(e){if(!e||typeof e!="object")return null;const t=[],n=typeof e.scope=="string"?e.scope.trim():"",r=typeof e.owner_id=="string"?e.owner_id.trim():"";n&&t.push(`scope=${n}`),r&&t.push(`owner_id=${r}`);const o=typeof e.confidence=="number"&&Number.isFinite(e.confidence)?e.confidence:null;o!==null&&t.push(`confidence=${o.toFixed(3)}`);const l=e.provenance&&typeof e.provenance=="object"&&!Array.isArray(e.provenance)?e.provenance:null;if(l){const m=typeof l.writer_run_id=="string"?l.writer_run_id.trim():"",_=typeof l.writer_workflow_id=="string"?l.writer_workflow_id.trim():"";m&&t.push(`writer_run_id=${m}`),_&&t.push(`writer_workflow_id=${_}`)}const u=e.attributes&&typeof e.attributes=="object"&&!Array.isArray(e.attributes)?e.attributes:null,c=u&&u._retrieval&&typeof u._retrieval=="object"&&!Array.isArray(u._retrieval)?u._retrieval:null,f=c&&typeof c.score=="number"&&Number.isFinite(c.score)?c.score:null;return f!==null&&t.push(`score=${f.toFixed(3)}`),t.length?t.join(" · "):null}function aL(e,t){const n=String(e??""),r=String(t??"").trim();if(!r)return n;const o=n.toLowerCase().indexOf(r.toLowerCase());if(o<0)return n;const l=n.slice(0,o),u=n.slice(o,o+r.length),c=n.slice(o+r.length);return s.jsxs(s.Fragment,{children:[l,s.jsx("span",{className:"amx-hl",children:u}),c]})}function ef(e){const t=String(e??"").trim().toLowerCase();return t==="person"?{stroke:"rgba(96, 165, 250, 0.82)",bg:"rgba(96, 165, 250, 0.10)",minimap:"rgba(96, 165, 250, 0.85)"}:t==="org"?{stroke:"rgba(34, 197, 94, 0.78)",bg:"rgba(34, 197, 94, 0.10)",minimap:"rgba(34, 197, 94, 0.82)"}:t==="concept"?{stroke:"rgba(168, 85, 247, 0.78)",bg:"rgba(168, 85, 247, 0.10)",minimap:"rgba(168, 85, 247, 0.82)"}:t==="claim"?{stroke:"rgba(251, 191, 36, 0.78)",bg:"rgba(251, 191, 36, 0.10)",minimap:"rgba(251, 191, 36, 0.82)"}:t==="event"?{stroke:"rgba(239, 68, 68, 0.74)",bg:"rgba(239, 68, 68, 0.10)",minimap:"rgba(239, 68, 68, 0.80)"}:t==="doc"?{stroke:"rgba(14, 165, 233, 0.74)",bg:"rgba(14, 165, 233, 0.10)",minimap:"rgba(14, 165, 233, 0.80)"}:t==="vocab"?{stroke:"rgba(148, 163, 184, 0.55)",bg:"rgba(148, 163, 184, 0.06)",minimap:"rgba(148, 163, 184, 0.70)"}:t==="thing"?{stroke:"rgba(255, 255, 255, 0.20)",bg:"rgba(255, 255, 255, 0.04)",minimap:"rgba(255, 255, 255, 0.30)"}:{stroke:"rgba(255, 255, 255, 0.14)",bg:"rgba(0, 0, 0, 0.18)",minimap:"rgba(255, 255, 255, 0.24)"}}function lL(e){const t=typeof e=="string"?e.trim():"";if(!t)return null;const n=t.replace(/(\.\d{3})\d+/,"$1"),r=Date.parse(n);return Number.isFinite(r)?r:null}function tf(e){const t=lL(e);if(t===null)return"";const n=new Date(t),r=n.getUTCFullYear(),o=String(n.getUTCMonth()+1).padStart(2,"0"),l=String(n.getUTCDate()).padStart(2,"0"),u=String(n.getUTCHours()).padStart(2,"0"),c=String(n.getUTCMinutes()).padStart(2,"0");return`${r}/${o}/${l} ${u}:${c}`}function D0(e){const t=String(e??"").trim();if(!t)return"";const n=t.indexOf(":");return n!==-1&&n<t.length-1?t.slice(n+1):t}function np(e,t){const n=String(e??"").trim().toLowerCase();return!!(n&&t.has(n))}function cL(e,t={}){const n=Math.max(1,t.maxPredicates??3),r=new Map;for(const f of e){const m=String((f==null?void 0:f.predicate)||"").trim();m&&r.set(m,(r.get(m)||0)+1)}const o=Array.from(r.entries());o.sort((f,m)=>m[1]-f[1]||f[0].localeCompare(m[0]));const u=o.slice(0,n).map(([f,m])=>{const _=D0(f);return m>1?`${_}×${m}`:_}).join(" | "),c=o.length>n?` +${o.length-n}`:"";return`${u}${c}`.trim()}function uL({resetKey:e,queryMode:t,items:n,activeMemoryText:r,packets:o,packetsVersion:l,packedCount:u,dropped:c,estimatedTokens:f,effort:m,warnings:_,onQuery:g,onItemsReplace:w,onOpenSpan:x,onOpenTranscript:j}){var ci;const b=p.useRef(null),N=p.useMemo(()=>{const B=n==null?void 0:n[0],oe=n==null?void 0:n[n.length-1],be=B?`${B.subject}|${B.predicate}|${B.object}`:"",Se=oe?`${oe.subject}|${oe.predicate}|${oe.object}`:"";return`${(n==null?void 0:n.length)||0}:${be}:${Se}`},[n]),C=String(e??N),E=t==="replace"?"replace":"override",[T,I]=p.useState(null),[K,U]=p.useState(null),[J,Y]=p.useState(!1),[re,ce]=p.useState(""),[fe,W]=p.useState(!1),[O,$]=p.useState("");p.useEffect(()=>{I(null),U(null),ce(""),Y(!1),$(""),W(!1)},[C]);const[z,A]=p.useState(""),[ee,P]=p.useState(!0),[F,G]=p.useState(!1),[R,Z]=p.useState(!0),[X]=p.useState(()=>({compact:Q3(),show:!1})),ie=X.compact,[ne,ye]=p.useState(X.show),[he,pe]=p.useState(!1),Ne=C,Ue=p.useMemo(()=>tg(Ne),[Ne]),[We,pt]=p.useState("grid"),[Fe,tt]=p.useState(Ue),[lt,Ke]=p.useState(!1),[je,Re]=p.useState(1),ht=p.useRef(null),xe=p.useRef(null),Ie=p.useRef(!1),[qe,zt]=p.useState(0),en=p.useRef(null),bn=p.useRef(0),Wt=p.useRef(0),It=p.useRef(0),Sn=p.useRef(0),[ns,Ot]=p.useState(!1),[pn,Bn]=p.useState(""),[An,gn]=p.useState({}),In=p.useRef({});p.useEffect(()=>{In.current=An},[An]);const[wn,ks]=p.useState(""),[Kn,js]=p.useState(""),Nr=p.useMemo(()=>{var oe;const B=(oe=n==null?void 0:n[0])==null?void 0:oe.scope;return mv(B,"session")},[n]),[On,le]=p.useState(Nr),[ke,Ye]=p.useState("standard"),[Ge,rt]=p.useState(""),[ct,Et]=p.useState(""),[kt,Kt]=p.useState(""),[xt,Yt]=p.useState(""),[qt,Pt]=p.useState(""),[At,$t]=p.useState(""),[De,on]=p.useState(""),[ut,tn]=p.useState("qwen/qwen3-next-80b");p.useEffect(()=>{le(Nr)},[C]);const dt=Array.isArray(n)?n:[],Un=typeof r=="string"?r:"",an=Array.isArray(o)?o:[],Ys=typeof l=="number"?l:void 0,ss=typeof u=="number"?u:void 0,Wr=typeof c=="number"?c:void 0,dr=typeof f=="number"?f:void 0,ii=m,oi=_,Ps=E==="override"&&(T!=null&&T.items)&&Array.isArray(T.items)?T.items:dt,ue=typeof(T==null?void 0:T.active_memory_text)=="string"&&T.active_memory_text.trim()?T.active_memory_text:Un,fr=(T==null?void 0:T.effort)??ii,Gi=(T==null?void 0:T.warnings)??oi,hr=p.useMemo(()=>new Set(["rdf:type","schema:name","skos:preflabel","skos:altlabel","dcterms:title","dcterms:identifier"]),[]),Cr=p.useMemo(()=>R?Ps:(Ps||[]).filter(B=>!np(B==null?void 0:B.predicate,hr)),[Ps,R,hr]),qr=p.useMemo(()=>K3(Ps,{groupEdges:ee}),[Ps,ee]),it=p.useMemo(()=>{if(R)return qr;const B=[];for(const oe of qr.edges){const Se=(oe&&oe.data&&Array.isArray(oe.data.assertions)?oe.data.assertions:[]).filter(He=>!np(He==null?void 0:He.predicate,hr));if(!Se.length)continue;const Ee=cL(Se);B.push({...oe,label:Ee,data:{...oe.data,assertions:Se,predicateSummary:Ee}})}return{nodes:qr.nodes,edges:B}},[qr,R,hr]),cn=p.useMemo(()=>it.nodes.map(B=>B.id),[it.nodes]),Ds=p.useMemo(()=>{const B=cn[0]||"",oe=cn[cn.length-1]||"";return`${cn.length}:${B}:${oe}`},[cn]),Hr=p.useMemo(()=>{var oe;const B=new Map;for(const be of it.nodes)B.set(be.id,String(((oe=be.data)==null?void 0:oe.label)||be.id));return B},[it.nodes]),rs=p.useMemo(()=>{var oe;const B=new Map;for(const be of it.nodes)B.set(be.id,String(((oe=be.data)==null?void 0:oe.kind)||""));return B},[it.nodes]),Eo=z.trim().toLowerCase(),Ao=p.useMemo(()=>{var oe;if(!Eo)return new Set;const B=new Set;for(const be of it.nodes){const Se=String(be.id||"").toLowerCase(),Ee=String(((oe=be.data)==null?void 0:oe.label)||"").toLowerCase();(Se.includes(Eo)||Ee.includes(Eo))&&B.add(be.id)}return B},[it.nodes,Eo]),$o=p.useCallback((B,oe)=>{const be={};for(const Se of cn){const Ee=B[Se]||oe[Se];be[Se]=Ee?{x:Ee.x,y:Ee.y}:{x:0,y:0}}return be},[cn]);p.useEffect(()=>{gn(B=>{const oe=du(it,{kind:We,seed:Fe}),be={};for(const Se of cn){const Ee=B[Se]||oe[Se];be[Se]=Ee?{x:Ee.x,y:Ee.y}:{x:0,y:0}}return be})},[it,We,Fe,cn,Ds]),p.useEffect(()=>{if(!Ie.current)return;const B=b.current;if(!(!B||typeof B.fitView!="function")&&cn.length){Ie.current=!1;try{B.fitView({padding:.2,duration:0})}catch{try{B.fitView({padding:.2})}catch{}}}},[cn.length,Ds,An]),p.useEffect(()=>{Ke(!1),ht.current=null,xe.current=null,Ie.current=!1,bn.current=0,Wt.current=0,It.current=0;const B=_v(Ne);if(B&&Object.keys(B.positions||{}).length){if(pt(B.kind),tt(B.seed),Ot(!0),Bn(B.saved_at||""),B.viewport){xe.current=B.viewport;const Ee=b.current;if(Ee&&typeof Ee.setViewport=="function"){try{Ee.setViewport(B.viewport,{duration:0})}catch{try{Ee.setViewport(B.viewport)}catch{}}xe.current=null}}else Ie.current=!0;const Se=du(it,{kind:B.kind,seed:B.seed});gn($o(B.positions,Se));return}Ot(!1),Bn("");const oe=tg(Ne);tt(oe);const be=du(it,{kind:We,seed:oe});gn(be),We==="force"&&it.nodes.length>0&&it.nodes.length<=320&&(ht.current=Vh(it,{seed:oe,positions:be,...Qd(je)}),Ke(!0))},[Ne]);const Pn=p.useMemo(()=>{const B=String(wn||"").trim(),oe=String(Kn||"").trim();return!B||!oe?null:Y3(it,B,oe,{directed:F})},[it,wn,Kn,F]),mr=!!(Pn&&String(wn||"").trim()&&String(Kn||"").trim()),Hn=p.useMemo(()=>{const B=String(wn||"").trim(),oe=String(Kn||"").trim();if(!B||!oe)return null;const be=F,Se=new Map,Ee=(ot,mt)=>{const Dt=Se.get(ot);Dt?Dt.push(mt):Se.set(ot,[mt])};for(const ot of it.edges)Ee(ot.source,ot.target),be||Ee(ot.target,ot.source);const He=new Set,Qe=[];for(He.add(B),Qe.push(B);Qe.length;){const ot=Qe.shift(),mt=Se.get(ot)||[];for(const Dt of mt)He.has(Dt)||(He.add(Dt),Qe.push(Dt))}return{reachableFromStart:He.size,endReachable:He.has(oe),nodes:it.nodes.length,edges:it.edges.length,assertions:Cr.length}},[F,it.edges,it.nodes.length,Kn,wn,Cr.length]),Ki=p.useMemo(()=>new Set((Pn==null?void 0:Pn.nodeIds)||[]),[Pn]),ai=p.useMemo(()=>new Set((Pn==null?void 0:Pn.edgeIds)||[]),[Pn]),[$n,Fs]=p.useState(""),[hs,Js]=p.useState(""),ms=!!(String($n||"").trim()||String(hs||"").trim()),da=p.useMemo(()=>{const B=new Set,oe=new Set,be=String($n||"").trim(),Se=String(hs||"").trim();if(be){B.add(be);for(const Ee of it.edges)(Ee.source===be||Ee.target===be)&&(oe.add(Ee.id),B.add(Ee.source),B.add(Ee.target));return{nodes:B,edges:oe}}if(Se){const Ee=it.edges.find(He=>He.id===Se);Ee&&(oe.add(Ee.id),B.add(Ee.source),B.add(Ee.target))}return{nodes:B,edges:oe}},[it.edges,hs,$n]);p.useEffect(()=>{Fs(""),Js(""),ks(""),js("")},[C]);const[Yi,ln]=p.useState(!1);p.useEffect(()=>{ln(!1)},[C]),p.useEffect(()=>{lt||(ht.current=null)},[lt]),p.useEffect(()=>{if(We!=="force")return;const B=ht.current;if(!B)return;const oe=Qd(je);B.options.springLength=oe.springLength,B.options.repulsionStrength=oe.repulsionStrength},[We,je]),p.useEffect(()=>{We!=="force"&&lt&&Ke(!1)},[We,lt]),p.useEffect(()=>{if(!lt||We!=="force"||it.nodes.length===0||typeof window>"u"||typeof window.requestAnimationFrame!="function")return;ht.current||(ht.current=Vh(it,{seed:Fe,positions:In.current,...Qd(je)}));let B=0,oe=0,be=0;const Se=it.nodes.length<=140?2:1,Ee=1600,He=.08,Qe=ot=>{if(B=window.requestAnimationFrame(Qe),ot-oe<33)return;oe=ot;const mt=ht.current;if(!mt){Ke(!1);return}J3(mt,Se),be+=Se,gn(Z3(mt)),(X3(mt)<=He||be>=Ee)&&Ke(!1)};return B=window.requestAnimationFrame(Qe),()=>{window.cancelAnimationFrame(B)}},[it,We,lt,Fe]);const fa=p.useMemo(()=>it.nodes.map(B=>{var un;const oe=Ki.has(B.id),be=Ao.has(B.id),Se=$n===B.id,Ee=ms&&da.nodes.has(B.id),He=ef((un=B.data)==null?void 0:un.kind),Qe="rgba(34, 211, 238, 0.88)",ot=be?"0 0 0 1px rgba(34, 211, 238, 0.34), 0 0 16px rgba(34, 211, 238, 0.26), 0 0 44px rgba(34, 211, 238, 0.14)":"",mt=oe?"rgba(168, 85, 247, 0.9)":be?Qe:He.stroke,Dt=Se?"0 0 0 2px rgba(255,255,255,0.20), 0 18px 46px rgba(0,0,0,0.55)":Ee?"0 0 0 1px rgba(96, 165, 250, 0.28), 0 12px 34px rgba(0,0,0,0.45)":void 0,Xt=ot&&Dt?`${ot}, ${Dt}`:Dt||ot||void 0,Xn=oe?"rgba(168, 85, 247, 0.10)":be?"rgba(34, 211, 238, 0.08)":He.bg,Bt=mr?oe||Se?1:.16:ms?Ee||Se?1:.1:1;return{...B,position:An[B.id]?{x:An[B.id].x,y:An[B.id].y}:B.position,style:{...B.style||{},border:`1px solid ${mt}`,borderRadius:10,background:Xn,color:"rgba(255,255,255,0.92)",opacity:Bt,padding:8,fontSize:12,boxShadow:Xt,width:180,cursor:"pointer"}}}),[it.nodes,mr,Ao,An,$n,Ki,ms,da.nodes]),dc=p.useMemo(()=>it.edges.map(B=>{const oe=ai.has(B.id),be=hs===B.id,Se=ms&&da.edges.has(B.id),Ee=oe?"rgba(168, 85, 247, 0.9)":ms?Se||be?"rgba(96, 165, 250, 0.55)":"rgba(255,255,255,0.14)":"rgba(255,255,255,0.18)",He=oe?2.75:ms?Se||be?2.25:1.25:1.5,Qe=be?"drop-shadow(0 0 10px rgba(168, 85, 247, 0.25))":void 0,ot=oe?"rgba(168, 85, 247, 0.9)":mr?"rgba(255,255,255,0.10)":"rgba(255,255,255,0.28)",mt=mr?oe||be?1:.1:ms?Se||be?1:.08:1,Dt=mr?oe||be?1:0:ms?Se||be?1:0:1,Xt=mr?oe||be?String(B.label||""):"":String(B.label||"");return{...B,label:Xt,style:{...B.style||{},stroke:Ee,strokeWidth:He,filter:Qe,opacity:mt},animated:!1,markerEnd:{type:jf.ArrowClosed,color:ot,width:20,height:20},labelShowBg:!0,labelBgPadding:[6,3],labelBgBorderRadius:10,labelBgStyle:{fill:`rgba(0, 0, 0, ${.38*Dt})`,stroke:`rgba(255, 255, 255, ${.14*Dt})`,strokeWidth:1},labelStyle:{fill:`rgba(255, 255, 255, ${.92*Dt})`,fontSize:10,fontWeight:600,letterSpacing:.2,textTransform:"lowercase"}}}),[it.edges,mr,hs,ai,ms,da.edges]),To=p.useMemo(()=>{if(!hs)return[];const B=it.edges.find(be=>be.id===hs),oe=B&&B.data&&Array.isArray(B.data.assertions)?B.data.assertions:[];return Array.isArray(oe)?oe:[]},[it.edges,hs]),_s=p.useMemo(()=>hs&&it.edges.find(B=>B.id===hs)||null,[it.edges,hs]),Er=p.useMemo(()=>{const B=String($n||"").trim();return B?Ps.filter(oe=>!oe||typeof oe!="object"||!(oe.subject===B||oe.object===B)?!1:R?!0:!np(oe.predicate,hr)):[]},[Ps,$n,R,hr]),Ar=p.useMemo(()=>hs?To:Er,[To,hs,Er]),Ji=p.useMemo(()=>{const B=new Map;for(const oe of Ar){if(!oe||typeof oe!="object")continue;const be=oe.provenance&&typeof oe.provenance=="object"&&!Array.isArray(oe.provenance)?oe.provenance:null,Se=be&&typeof be.span_id=="string"?be.span_id.trim():"",Ee=be&&typeof be.writer_run_id=="string"?be.writer_run_id.trim():"",He=typeof oe.owner_id=="string"?oe.owner_id.trim():"",Qe=Ee||He;if(!Qe||!Se)continue;const ot=`${Qe}|${Se}`,mt=B.get(ot),Dt=typeof oe.observed_at=="string"?oe.observed_at.trim():"";mt?(mt.count+=1,Dt&&(!mt.last_observed_at||Dt>mt.last_observed_at)&&(mt.last_observed_at=Dt,mt.last_observed_at_fmt=tf(Dt),mt.assertion=oe)):B.set(ot,{span_run_id:Qe,span_id:Se,writer_run_id:Ee,count:1,last_observed_at:Dt,last_observed_at_fmt:tf(Dt),assertion:oe})}return Array.from(B.values()).sort((oe,be)=>String(be.last_observed_at||"").localeCompare(String(oe.last_observed_at||"")))},[Ar]),_r=p.useMemo(()=>{const B=new Map;for(const oe of Ar){if(!oe||typeof oe!="object")continue;const be=oe.provenance&&typeof oe.provenance=="object"&&!Array.isArray(oe.provenance)?oe.provenance:null,Se=be&&typeof be.span_id=="string"?be.span_id.trim():"",Ee=be&&typeof be.writer_run_id=="string"?be.writer_run_id.trim():"";if(!Ee||Se)continue;const He=B.get(Ee),Qe=typeof oe.observed_at=="string"?oe.observed_at.trim():"";He?(He.count+=1,Qe&&(!He.last_observed_at||Qe>He.last_observed_at)&&(He.last_observed_at=Qe,He.last_observed_at_fmt=tf(Qe),He.assertion=oe)):B.set(Ee,{run_id:Ee,count:1,last_observed_at:Qe,last_observed_at_fmt:tf(Qe),assertion:oe})}return Array.from(B.values()).sort((oe,be)=>String(be.last_observed_at||"").localeCompare(String(oe.last_observed_at||"")))},[Ar]),Ss=p.useCallback(B=>{const oe=String(B.run_id||"").trim(),be=typeof B.span_id=="string"?String(B.span_id).trim():"";if(oe){if(j){try{j({run_id:oe,span_id:be||void 0,assertion:B.assertion})}catch{}return}if(x&&be)try{x({run_id:oe,span_id:be,assertion:B.assertion})}catch{}}},[x,j]),pr=p.useCallback(async B=>{var be;const oe=String(B??"");if(oe){try{if(typeof((be=navigator.clipboard)==null?void 0:be.writeText)=="function"){await navigator.clipboard.writeText(oe);return}}catch{}try{const Se=document.createElement("textarea");Se.value=oe,Se.style.position="fixed",Se.style.left="-9999px",document.body.appendChild(Se),Se.select(),document.execCommand("copy"),document.body.removeChild(Se)}catch{}}},[]),$r=p.useCallback(()=>{const B=b.current;if(!(!B||typeof B.fitView!="function")){if($n&&typeof B.getNode=="function"){const oe=B.getNode($n);if(oe){B.fitView({nodes:[oe],padding:.55,duration:350});return}}B.fitView({padding:.2,duration:350})}},[$n]),Xs=p.useCallback(B=>{const oe=B.kind,be=Math.trunc(B.seed);Ke(!1),ht.current=null,xe.current=null,pt(oe),tt(be);const Se=du(it,{kind:oe,seed:be});gn(Se),oe==="force"&&(B.autoPlay??!0)&&it.nodes.length>0&&it.nodes.length<=320&&(ht.current=Vh(it,{seed:be,positions:Se,...Qd(je)}),Ke(!0))},[it,je]),Ni=p.useCallback(()=>{if(We==="force"){if(lt){Ke(!1);return}ht.current=Vh(it,{seed:Fe,positions:In.current,...Qd(je)}),Ke(!0)}},[it,We,lt,Fe,je]);p.useEffect(()=>()=>{typeof window>"u"||typeof window.cancelAnimationFrame=="function"&&Sn.current&&window.cancelAnimationFrame(Sn.current)},[]);const is=p.useCallback(()=>{const B=b.current;if(!B||typeof B.getViewport!="function"||!cn.length)return null;const oe=en.current;if(!oe)return null;const be=oe.getBoundingClientRect();if(!Number.isFinite(be.width)||!Number.isFinite(be.height)||be.width<64||be.height<64)return null;const Se=B.getViewport(),Ee=typeof(Se==null?void 0:Se.zoom)=="number"&&Number.isFinite(Se.zoom)?Se.zoom:null,He=typeof(Se==null?void 0:Se.x)=="number"&&Number.isFinite(Se.x)?Se.x:null,Qe=typeof(Se==null?void 0:Se.y)=="number"&&Number.isFinite(Se.y)?Se.y:null;if(Ee===null||He===null||Qe===null||Ee<=0)return null;const ot=140,mt=Math.min(cn.length,180),Dt=In.current;let Xt=0,Xn=0;for(const Bt of cn){const un=Dt[Bt];if(!un||!Number.isFinite(un.x)||!Number.isFinite(un.y))continue;Xn+=1;const vn=[{x:un.x,y:un.y},{x:un.x+90,y:un.y+24}];for(const kn of vn){const ps=kn.x*Ee+He,Ns=kn.y*Ee+Qe;if(ps>-ot&&ps<be.width+ot&&Ns>-ot&&Ns<be.height+ot)return!1}if(Xt++,Xt>=mt)break}return Xn?!0:null},[cn]),Tr=p.useCallback(B=>{typeof window>"u"||typeof window.requestAnimationFrame!="function"||Sn.current||(Sn.current=window.requestAnimationFrame(()=>{Sn.current=0;const oe=is();if(oe===null){if(It.current>=12)return;It.current+=1,window.setTimeout(()=>Tr(`${B}:probe`),120);return}if(oe!==!0){It.current=0,Wt.current=0;return}It.current=0;const be=b.current;if(be&&typeof be.fitView=="function")try{be.fitView({padding:.2,duration:0})}catch{try{be.fitView({padding:.2})}catch{}}if(Wt.current+=1,Wt.current>=4&&bn.current<1){Wt.current=0,bn.current+=1,zt(Se=>Se+1);return}Wt.current<8&&window.setTimeout(()=>Tr(`${B}:retry`),220)}))},[is]);p.useEffect(()=>{Wt.current=0,bn.current=0,It.current=0,Tr("mount")},[C,Tr]),p.useEffect(()=>{Tr("graph change")},[Ds,Tr]),p.useEffect(()=>{const B=en.current;if(!B||typeof window>"u"||typeof ResizeObserver!="function")return;const oe=new ResizeObserver(()=>Tr("resize"));return oe.observe(B),()=>oe.disconnect()},[Tr]);const ha=p.useCallback(()=>{const B=new Date().toISOString(),oe={};for(const Qe of cn){const ot=In.current[Qe];ot&&typeof ot.x=="number"&&typeof ot.y=="number"&&(oe[Qe]={x:ot.x,y:ot.y})}const be=b.current,Se=be&&typeof be.toObject=="function"?be.toObject():null,Ee=Se&&Se.viewport?Se.viewport:be&&typeof be.getViewport=="function"?be.getViewport():null,He=L0(Ee,{minZoom:ng,maxZoom:sg,maxAbsTranslate:P0})??void 0;nL(Ne,{version:1,kind:We,seed:Fe,positions:oe,viewport:He,saved_at:B}),Ot(!0),Bn(B),Ke(!1)},[Ne,We,Fe,cn]),gr=p.useCallback(()=>{const B=_v(Ne);if(!B)return;Ke(!1),ht.current=null,pt(B.kind),tt(B.seed),Ot(!0),Bn(B.saved_at||""),xe.current=B.viewport||null,Ie.current=!B.viewport;const oe=du(it,{kind:B.kind,seed:B.seed});if(gn($o(B.positions,oe)),B.viewport){const be=b.current;if(be&&typeof be.setViewport=="function"){try{be.setViewport(B.viewport,{duration:0})}catch{try{be.setViewport(B.viewport)}catch{}}xe.current=null}}},[$o,it,Ne]),Xi=p.useCallback(()=>{sL(Ne),Ot(!1),Bn("")},[Ne]),fc=p.useCallback(B=>{if(!Array.isArray(B)||B.length===0)return;let oe=!1;gn(be=>{let Se=be,Ee=!1;for(const He of B){const Qe=He&&typeof He=="object"&&"id"in He&&typeof He.id=="string"?String(He.id):"",ot=(He==null?void 0:He.type)==="position"?He==null?void 0:He.position:null;Qe&&ot&&typeof ot.x=="number"&&typeof ot.y=="number"&&(Ee||(Se={...be},Ee=!0),Se[Qe]={x:ot.x,y:ot.y},He!=null&&He.dragging&&(oe=!0))}return Ee?Se:be}),oe&&lt&&Ke(!1)},[lt]),Ci=p.useMemo(()=>{const B=new Map;for(const oe of it.edges)B.set(oe.id,oe);return B},[it.edges]),Zs=p.useMemo(()=>{var Se;if(!Pn)return[];const B=Pn.nodeIds||[],oe=Pn.edgeIds||[],be=[];for(let Ee=0;Ee<Math.min(B.length-1,oe.length);Ee++){const He=B[Ee],Qe=B[Ee+1],ot=oe[Ee],mt=Ci.get(ot),Dt=String(((Se=mt==null?void 0:mt.data)==null?void 0:Se.predicateSummary)||(mt==null?void 0:mt.label)||"").trim(),Xt=mt&&mt.source===He&&mt.target===Qe?"forward":mt&&mt.source===Qe&&mt.target===He?"reverse":"unknown";be.push({from:He,to:Qe,edgeId:ot,predicate:Dt,dir:Xt})}return be},[Ci,Pn]),$u=p.useCallback(async()=>{if(g){ce(""),$(""),Y(!0);try{const B=rL(qt),oe=tp(At,{allowZero:!0,allowNegativeOne:!0}),be=tp(De,{allowZero:!0}),Se=await g({scope:On,owner_id:void 0,recall_level:ke,query_text:Ge||void 0,subject:ct||void 0,predicate:kt||void 0,object:xt||void 0,min_score:B,limit:oe,max_input_tokens:be,model:ut||void 0});I(Se),U("live query"),E==="replace"&&w&&Se&&Array.isArray(Se.items)&&w(Se.items,{kind:"live query",result:Se})}catch(B){const oe=B instanceof Error?B.message:String(B);ce(oe||"Query failed")}finally{Y(!1)}}},[At,De,qt,ut,xt,w,g,kt,E,Ge,ke,On,ct]),Qs=p.useCallback(async()=>{if(!g)return;const B=String(wn||"").trim(),oe=String(Kn||"").trim();if(!B||!oe)return;const be=Math.max(200,tp(At)??80),Se=60;$(""),ce(""),W(!0);try{const Ee=[],He=new Set,Qe=Bt=>{if(!Bt||typeof Bt!="object"||typeof Bt.subject!="string"||typeof Bt.predicate!="string"||typeof Bt.object!="string")return;const un=`${Bt.subject}|${Bt.predicate}|${Bt.object}|${String(Bt.observed_at||"")}|${String(Bt.scope||"")}|${String(Bt.owner_id||"")}`;He.has(un)||(He.add(un),Ee.push(Bt))};for(const Bt of Ps)Qe(Bt);const ot=F,mt=new Set,Dt=[B],Xt=new Set([B]),Xn=async Bt=>{const un=await g({scope:On,recall_level:ke,min_score:0,limit:be,subject:Bt,query_text:void 0,max_input_tokens:0,model:void 0});if(un&&Array.isArray(un.items)){for(const vn of un.items)if(Qe(vn),typeof vn.subject=="string"&&vn.subject.trim()===Bt&&typeof vn.object=="string"){const kn=vn.object.trim();kn&&!Xt.has(kn)&&(Xt.add(kn),Dt.push(kn))}}if(!ot){const vn=await g({scope:On,recall_level:ke,min_score:0,limit:be,object:Bt,query_text:void 0,max_input_tokens:0,model:void 0});if(vn&&Array.isArray(vn.items)){for(const kn of vn.items)if(Qe(kn),typeof kn.object=="string"&&kn.object.trim()===Bt&&typeof kn.subject=="string"){const ps=kn.subject.trim();ps&&!Xt.has(ps)&&(Xt.add(ps),Dt.push(ps))}}}};for(;Dt.length&&mt.size<Se&&!Xt.has(oe);){const Bt=Dt.shift();!Bt||mt.has(Bt)||(mt.add(Bt),await Xn(Bt))}I({ok:!0,count:Ee.length,items:Ee,active_memory_text:ue,raw:{expanded_for_path:!0,expanded_nodes:mt.size,discovered_nodes:Xt.size,merged:Ee.length,directed:ot}}),U("expanded neighborhood"),E==="replace"&&w&&w(Ee,{kind:"expanded neighborhood",result:{ok:!0,count:Ee.length,items:Ee,active_memory_text:ue,raw:{expanded_for_path:!0,expanded_nodes:mt.size,discovered_nodes:Xt.size,merged:Ee.length,directed:ot}}})}catch(Ee){const He=Ee instanceof Error?Ee.message:String(Ee);$(He||"Expand neighborhood failed")}finally{W(!1)}},[F,ue,Ps,At,w,g,Kn,wn,E,ke,On]),Zi=p.useCallback(()=>{I(null),U(null),ce(""),Y(!1),$(""),W(!1),ks(""),js(""),Fs(""),Js("")},[]),er="Search KG",Mo=it.nodes.length,li=it.edges.length,ll=Cr.length;return s.jsx("div",{className:"amx-host",children:s.jsxs("div",{className:"amx-root",children:[s.jsxs("div",{className:"amx-left",children:[s.jsx("div",{className:"amx-graphbar",role:"toolbar","aria-label":"Graph layout controls",children:s.jsxs("div",{className:"amx-graphbar-row",children:[s.jsx("span",{className:"amx-graphbar-title",children:"layout"}),s.jsxs("select",{value:We,onChange:B=>pt(rg(B.target.value,We)),disabled:!cn.length,children:[s.jsx("option",{value:"grid",children:"grid (deterministic)"}),s.jsx("option",{value:"radial",children:"radial (bfs)"}),s.jsx("option",{value:"circle",children:"circle"}),s.jsx("option",{value:"force",children:"force (simulation)"})]}),We==="force"?s.jsxs("label",{className:"amx-graphbar-spread",children:[s.jsx("span",{className:"amx-graphbar-title",children:"spread"}),s.jsx("input",{type:"range",min:"0.7",max:"2.2",step:"0.1",value:je,onChange:B=>Re(O0(Number(B.target.value),.7,2.2,1))}),s.jsxs("span",{className:"amx-small",children:[je.toFixed(1),"×"]})]}):null,s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>Xs({kind:We,seed:Fe}),disabled:!cn.length,children:"Apply"}),s.jsx("button",{type:"button",className:"amx-btn",onClick:Ni,disabled:!cn.length||We!=="force",children:lt?"Pause simulation":"Play simulation"})]})}),s.jsxs("div",{className:"amx-graph","aria-label":"Knowledge graph",ref:en,children:[s.jsx(Wg,{children:s.jsxs(A0,{nodes:fa,edges:dc,defaultViewport:{x:0,y:0,zoom:1},minZoom:ng,maxZoom:sg,onInit:B=>{b.current=B;const oe=xe.current;if(oe&&typeof B.setViewport=="function")try{B.setViewport(oe,{duration:0})}catch{try{B.setViewport(oe)}catch{}}if(Ie.current&&typeof B.fitView=="function")try{B.fitView({padding:.2,duration:0})}catch{try{B.fitView({padding:.2})}catch{}}xe.current=null,Ie.current=!1,Tr("init")},nodesDraggable:!0,nodesConnectable:!1,elementsSelectable:!0,onNodesChange:fc,onNodeClick:(B,oe)=>{Js(""),Fs(oe.id)},onEdgeClick:(B,oe)=>{Fs(""),Js(oe.id)},onPaneClick:()=>{Fs(""),Js("")},children:[s.jsx(P3,{className:"amx-flow-controls",children:s.jsx(_u,{type:"button",className:`amx-control-legend ${he?"amx-control-legend-active":""}`,onClick:()=>pe(B=>!B),title:he?"Hide node color legend":"Show node color legend","aria-label":he?"Hide node color legend":"Show node color legend",children:s.jsx(eL,{})})}),s.jsx(xf,{position:"bottom-right",className:"amx-panel-bottom-right",children:s.jsx("div",{className:"amx-panel-toggles",children:s.jsx("button",{type:"button",className:"amx-minimap-toggle",onClick:()=>ye(B=>!B),title:ne?"Hide minimap preview":"Show minimap preview","aria-label":ne?"Hide minimap preview":"Show minimap preview",children:ne?"minimap on":"minimap off"})})}),ne?s.jsx($3,{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:ie?120:160,height:ie?80:110,marginBottom:56},nodeColor:B=>{var oe;return ef((oe=B.data)==null?void 0:oe.kind).minimap}}):null,he?s.jsxs(xf,{position:"bottom-left",className:"amx-legend-panel",children:[s.jsx("div",{className:"amx-legend-title",children:"node colors"}),s.jsx("div",{className:"amx-legend",children:[{k:"person",label:"person"},{k:"org",label:"org"},{k:"concept",label:"concept"},{k:"claim",label:"claim"},{k:"event",label:"event"},{k:"doc",label:"doc"},{k:"vocab",label:"vocab"}].map(({k:B,label:oe})=>s.jsx("span",{className:"amx-legend-item",style:{borderColor:ef(B).stroke},children:oe},B))})]}):null,s.jsx(W3,{gap:20,size:1,color:"rgba(255,255,255,0.06)"})]})},qe),s.jsxs("details",{className:"amx-panel amx-controls",children:[s.jsxs("summary",{children:[s.jsx("span",{className:"amx-controls-title",children:er}),s.jsxs("span",{className:"amx-small",children:[ll," assertions · ",Mo," nodes · ",li," edges"]})]}),s.jsxs("div",{className:"amx-toolbar",style:{marginTop:10},children:[s.jsxs("div",{className:"amx-toolbar-grid",children:[s.jsxs("label",{children:["search / highlight",s.jsx("input",{value:z,onChange:B=>A(B.target.value),placeholder:"filter nodes by id/label"})]}),s.jsxs("label",{children:["group edges",s.jsxs("select",{value:String(ee),onChange:B=>P(B.target.value==="true"),children:[s.jsx("option",{value:"true",children:"group (subject→object)"}),s.jsx("option",{value:"false",children:"no grouping"})]})]}),s.jsxs("label",{children:["view",s.jsxs("select",{value:String(R),onChange:B=>Z(B.target.value==="true"),children:[s.jsx("option",{value:"true",children:"all assertions"}),s.jsx("option",{value:"false",children:"hide rdf:type / labels"})]})]}),s.jsxs("label",{children:["path mode",s.jsxs("select",{value:String(F),onChange:B=>G(B.target.value==="true"),children:[s.jsx("option",{value:"false",children:"undirected"}),s.jsx("option",{value:"true",children:"directed"})]})]})]}),s.jsxs("details",{className:"amx-details",children:[s.jsx("summary",{children:"layout"}),s.jsxs("div",{className:"amx-toolbar-grid",style:{marginTop:10},children:[s.jsxs("label",{children:["layout",s.jsxs("select",{value:We,onChange:B=>pt(rg(B.target.value,We)),children:[s.jsx("option",{value:"grid",children:"grid (deterministic)"}),s.jsx("option",{value:"radial",children:"radial (bfs)"}),s.jsx("option",{value:"circle",children:"circle"}),s.jsx("option",{value:"force",children:"force (simulation)"})]})]}),s.jsxs("label",{children:["seed",s.jsx("input",{type:"number",step:"1",value:Fe,onChange:B=>tt(Math.trunc(Number(B.target.value||0)||0))})]})]}),s.jsxs("div",{className:"amx-actions",style:{marginTop:10},children:[s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>Xs({kind:We,seed:Fe}),disabled:!cn.length,children:"Apply layout"}),We==="force"?s.jsx("button",{type:"button",className:"amx-btn",onClick:Ni,disabled:!cn.length,children:lt?"Pause simulation":"Play simulation"}):null,s.jsx("button",{type:"button",className:"amx-btn",onClick:ha,disabled:!cn.length,children:"Save layout"}),ns?s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"amx-btn",onClick:gr,children:"Load saved"}),s.jsx("button",{type:"button",className:"amx-btn",onClick:Xi,children:"Clear saved"})]}):null]}),s.jsxs("div",{className:"amx-small",style:{marginTop:10,opacity:.9},children:["Drag nodes to adjust manually; use ",s.jsx("span",{className:"amx-mono",children:"Save layout"})," for a stable, replayable view.",ns?s.jsxs("span",{children:[" ","(saved",pn?`: ${pn}`:"",")"]}):s.jsx("span",{children:" (no saved layout)"})]})]}),s.jsxs("details",{className:"amx-details",children:[s.jsx("summary",{children:"path"}),s.jsxs("div",{className:"amx-toolbar-grid",style:{marginTop:10},children:[s.jsxs("label",{children:["path start",s.jsxs("select",{value:wn,onChange:B=>ks(B.target.value),children:[s.jsx("option",{value:"",children:"(none)"}),cn.map(B=>s.jsx("option",{value:B,children:(()=>{const oe=Hr.get(B)||B;return oe===B?oe:`${oe} (${B})`})()},B))]})]}),s.jsxs("label",{children:["path end",s.jsxs("select",{value:Kn,onChange:B=>js(B.target.value),children:[s.jsx("option",{value:"",children:"(none)"}),cn.map(B=>s.jsx("option",{value:B,children:(()=>{const oe=Hr.get(B)||B;return oe===B?oe:`${oe} (${B})`})()},B))]})]})]}),Pn?s.jsx("div",{className:"amx-small",style:{marginTop:10},children:Zs.map((B,oe)=>{const be=Hr.get(B.from)||B.from,Se=Hr.get(B.to)||B.to,Ee=B.dir==="reverse"?" ← ":" → ",He=B.predicate?` (${B.predicate})`:"";return s.jsxs("div",{children:[oe===0?s.jsx("span",{children:be}):null,Ee,s.jsxs("span",{children:[Se,He]})]},`${B.edgeId}:${oe}`)})}):wn&&Kn?s.jsxs("div",{className:"amx-small",style:{marginTop:10,opacity:.9},children:["No path found in the current subgraph (",(Hn==null?void 0:Hn.assertions)??ll," assertions · ",(Hn==null?void 0:Hn.nodes)??it.nodes.length," nodes ·"," ",(Hn==null?void 0:Hn.edges)??it.edges.length," edges). Start reaches ",(Hn==null?void 0:Hn.reachableFromStart)??0," nodes.",g?s.jsx("div",{style:{marginTop:10},children:s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>void Qs(),disabled:fe,children:fe?"Expanding…":"Expand neighborhood"})}):null]}):s.jsx("div",{className:"amx-small",style:{marginTop:10},children:"(no path)"})]}),s.jsxs("details",{className:"amx-details",children:[s.jsx("summary",{children:"query"}),s.jsxs("div",{className:"amx-toolbar-grid",style:{marginTop:10},children:[s.jsxs("label",{children:["query_text (semantic)",s.jsx("input",{value:Ge,onChange:B=>rt(B.target.value),placeholder:"e.g. emotion chip"})]}),s.jsxs("label",{children:["subject (exact)",s.jsx("input",{value:ct,onChange:B=>Et(B.target.value),placeholder:"e.g. ex:person-data"})]}),s.jsxs("label",{children:["predicate (exact)",s.jsx("input",{value:kt,onChange:B=>Kt(B.target.value),placeholder:"e.g. schema:about"})]}),s.jsxs("label",{children:["object (exact)",s.jsx("input",{value:xt,onChange:B=>Yt(B.target.value),placeholder:"e.g. ex:concept-emotion-chip"})]}),s.jsxs("label",{children:["min_score",s.jsx("input",{type:"number",step:"any",value:qt,onChange:B=>Pt(B.target.value),placeholder:"(auto)"})]}),s.jsxs("label",{children:["limit",s.jsx("input",{type:"number",min:"-1",step:"1",value:At,onChange:B=>$t(B.target.value),placeholder:"0/-1 = unlimited (if supported)"})]})]})]}),s.jsxs("details",{className:"amx-details",children:[s.jsx("summary",{children:"advanced"}),s.jsxs("div",{className:"amx-toolbar-grid",style:{marginTop:10},children:[s.jsxs("label",{children:["scope",s.jsxs("select",{value:On,onChange:B=>le(mv(B.target.value,On)),children:[s.jsx("option",{value:"run",children:"run"}),s.jsx("option",{value:"session",children:"session"}),s.jsx("option",{value:"global",children:"global"}),s.jsx("option",{value:"all",children:"all"})]})]}),s.jsxs("label",{children:["recall level",s.jsxs("select",{value:ke,onChange:B=>Ye(B.target.value||"standard"),children:[s.jsx("option",{value:"urgent",children:"urgent"}),s.jsx("option",{value:"standard",children:"standard"}),s.jsx("option",{value:"deep",children:"deep"})]})]}),s.jsxs("label",{children:["max_input_tokens",s.jsx("input",{type:"number",min:"0",step:"1",value:De,onChange:B=>on(B.target.value),placeholder:"(auto)"})]}),s.jsxs("label",{children:["model (budgeting)",s.jsx("input",{value:ut,onChange:B=>tn(B.target.value),placeholder:"qwen/qwen3-next-80b"})]})]})]}),s.jsxs("div",{className:"amx-actions",children:[s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>void $u(),disabled:!g||J,children:J?"Querying…":"Query store"}),s.jsx("button",{type:"button",className:"amx-btn",onClick:Zi,disabled:!T&&!re&&!J,children:"Reset to step output"}),T?s.jsxs("span",{className:"amx-small",children:["showing: ",K||"live query"]}):s.jsx("span",{className:"amx-small",children:"showing: step output"}),re?s.jsx("span",{className:"amx-small",style:{color:"var(--error, rgba(255, 80, 80, 0.95))"},children:re}):null,O?s.jsx("span",{className:"amx-small",style:{color:"var(--error, rgba(255, 80, 80, 0.95))"},children:O}):null]})]})]})]})]}),s.jsxs("div",{className:"amx-right",children:[s.jsxs("div",{className:"amx-panel",children:[s.jsx("h3",{children:"Details"}),s.jsx("div",{className:"amx-small",style:{marginBottom:8},children:"Derived from `memory_kg_query` packetization (max_input_tokens); safe to inject into an LLM system prompt."}),(()=>{const B=iL(fr);return B?s.jsx("div",{className:"amx-small",style:{marginBottom:8,opacity:.9},children:B}):null})(),(()=>{const B=Gi;if(!B)return null;const oe=typeof B=="string"?B:Array.isArray(B)?B.map(be=>String(be)).join(" · "):JSON.stringify(B);return!oe||!oe.trim()?null:s.jsx("div",{className:"amx-small",style:{marginBottom:8,color:"var(--warning, rgba(255, 180, 90, 0.95))"},children:oe})})(),s.jsx("div",{className:"amx-small",style:{marginBottom:8,opacity:.9},children:(()=>{const B=(T==null?void 0:T.packets_version)??Ys,oe=(T==null?void 0:T.packed_count)??ss,be=(T==null?void 0:T.dropped)??Wr,Se=(T==null?void 0:T.estimated_tokens)??dr,Ee=[];return typeof B=="number"&&Ee.push(`packets_v${B}`),typeof oe=="number"&&Ee.push(`packed=${oe}`),typeof be=="number"&&Ee.push(`dropped=${be}`),typeof Se=="number"&&Ee.push(`est_tokens=${Se}`),Ee.length?Ee.join(" · "):"No packetization stats (set max_input_tokens > 0)."})()}),s.jsx("div",{className:"amx-active-memory",children:aL(ue||"(empty)",z)}),(()=>{const B=T!=null&&T.packets&&Array.isArray(T.packets)?T.packets:an;return!Array.isArray(B)||B.length===0?null:s.jsxs("div",{style:{marginTop:10},children:[s.jsxs("button",{type:"button",className:"amx-btn",onClick:()=>ln(oe=>!oe),children:[Yi?"Hide":"Show"," packets (",B.length,")"]}),Yi?s.jsx("div",{className:"amx-list",style:{marginTop:10},children:B.slice(0,120).map((oe,be)=>{const Se=oe&&typeof oe=="object"&&!Array.isArray(oe)?oe:null,Ee=Se&&typeof Se.statement=="string"?Se.statement:typeof oe=="string"?oe:"",He=Se&&(typeof Se.retrieval_score=="number"||typeof Se.retrieval_score=="string")?Se.retrieval_score:null,Qe=Se&&typeof Se.observed_at=="string"?Se.observed_at:null;return s.jsxs("div",{className:"amx-item",children:[s.jsx("div",{className:"amx-mono",children:Ee||"(packet)"}),Qe||He!==null?s.jsxs("div",{className:"amx-small",children:[Qe?`[${Qe}]`:null,Qe&&He!==null?" ":null,He!==null?`score:${He}`:null]}):null]},be)})}):null]})})(),s.jsx("div",{style:{marginTop:14,marginBottom:12,borderTop:"1px solid var(--ui-border-1, rgba(255,255,255,0.08))"}}),s.jsx("div",{className:"amx-small",style:{marginBottom:8,fontWeight:700,opacity:.9},children:"Inspect"}),s.jsx("div",{className:"amx-small",style:{marginBottom:8},children:"Click a node or edge to inspect its assertions."}),$n?s.jsxs("div",{className:"amx-item",style:{marginBottom:10,display:"flex",justifyContent:"space-between",gap:10,alignItems:"center"},children:[s.jsxs("div",{style:{minWidth:0},children:[s.jsx("div",{className:"amx-mono",style:{fontSize:11,opacity:.95},children:Hr.get($n)||$n}),s.jsxs("div",{className:"amx-small",children:["kind=",rs.get($n)||"entity"," · id=",$n]})]}),s.jsxs("div",{className:"amx-actions",children:[s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>void pr($n),children:"Copy id"}),s.jsx("button",{type:"button",className:"amx-btn",onClick:$r,children:"Focus"})]})]}):_s&&_s.source&&_s.target?s.jsxs("div",{className:"amx-item",style:{marginBottom:10,display:"flex",justifyContent:"space-between",gap:10,alignItems:"center"},children:[s.jsxs("div",{style:{minWidth:0},children:[s.jsxs("div",{className:"amx-mono",style:{fontSize:11,opacity:.95},children:[_s.source," —",String(_s.label||((ci=_s.data)==null?void 0:ci.predicateSummary)||"").trim()||"?","→ ",_s.target]}),s.jsxs("div",{className:"amx-small",children:["edge_id=",_s.id]})]}),s.jsxs("div",{className:"amx-actions",children:[s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>void pr(_s.id),children:"Copy id"}),s.jsx("button",{type:"button",className:"amx-btn",onClick:$r,children:"Fit"})]})]}):s.jsx("div",{className:"amx-small",style:{marginBottom:10,opacity:.9},children:"(no selection)"}),s.jsx("div",{className:"amx-list",children:Ar.slice(0,80).map((B,oe)=>{const be=String(B.subject||"").trim(),Se=String(B.predicate||"").trim(),Ee=String(B.object||"").trim(),He=Hr.get(be)||be,Qe=Hr.get(Ee)||Ee,ot=rs.get(be)||"entity",mt=rs.get(Ee)||"entity",Dt=ef(ot),Xt=ef(mt),Xn=tf(B.observed_at),Bt=oL(B),un=B.provenance&&typeof B.provenance=="object"&&!Array.isArray(B.provenance)?B.provenance:null,vn=un&&typeof un.span_id=="string"?un.span_id.trim():"",kn=un&&typeof un.writer_run_id=="string"?un.writer_run_id.trim():"",ps=typeof B.owner_id=="string"?B.owner_id.trim():"",Ns=kn||ps,yr=!!((j||x)&&vn&&Ns),Ro=!!(j&&kn&&!vn),Lo=yr||Ro;return s.jsxs("div",{className:"amx-item amx-triple-card",children:[s.jsxs("div",{className:"amx-triple-row",children:[s.jsx("button",{type:"button",className:"amx-term",style:{borderColor:Dt.stroke,background:Dt.bg},title:be,onClick:()=>{be&&(Js(""),Fs(be))},children:He||be||"(subject)"}),s.jsx("span",{className:"amx-arrow",children:"—"}),s.jsx("span",{className:"amx-predicate",title:Se,children:D0(Se)||"(predicate)"}),s.jsx("span",{className:"amx-arrow",children:"→"}),s.jsx("button",{type:"button",className:"amx-term",style:{borderColor:Xt.stroke,background:Xt.bg},title:Ee,onClick:()=>{Ee&&(Js(""),Fs(Ee))},children:Qe||Ee||"(object)"})]}),s.jsxs("div",{className:"amx-triple-meta",children:[Xn?s.jsxs("span",{className:"amx-small",title:String(B.observed_at||""),children:["[",Xn,"]"]}):null,Bt?s.jsx("span",{className:"amx-small",children:Bt}):null]}),vn||kn?s.jsxs("div",{className:"amx-triple-actions",children:[vn?s.jsxs("span",{className:"amx-small",children:["span:",vn]}):null,kn?s.jsxs("span",{className:"amx-small",children:["run:",kn]}):null,Lo?s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>{if(yr&&vn&&Ns){Ss({run_id:Ns,span_id:vn,assertion:B});return}Ro&&kn&&Ss({run_id:kn,assertion:B})},children:"Open transcript"}):null]}):null]},oe)})})]}),s.jsxs("div",{className:"amx-panel",children:[s.jsx("h3",{children:"Transcript"}),s.jsx("div",{className:"amx-small",style:{marginBottom:8},children:"Pivot from a triple to its provenance transcript (span/note artifact, or run input fallback)."}),Ji.length?s.jsxs("div",{style:{marginBottom:12},children:[s.jsx("div",{className:"amx-small",style:{marginBottom:6,opacity:.85},children:"spans"}),s.jsx("div",{className:"amx-list",style:{maxHeight:320},children:Ji.slice(0,60).map(B=>s.jsxs("div",{className:"amx-item",style:{display:"flex",justifyContent:"space-between",gap:10,alignItems:"center"},children:[s.jsxs("div",{style:{minWidth:0},children:[s.jsxs("div",{className:"amx-mono",style:{fontSize:11,opacity:.95},children:["span:",B.span_id]}),s.jsxs("div",{className:"amx-small",children:["run_id=",B.span_run_id," · assertions=",B.count,B.last_observed_at_fmt?` · last=[${B.last_observed_at_fmt}]`:""]})]}),x||j?s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>Ss({run_id:B.span_run_id,span_id:B.span_id,assertion:B.assertion}),children:"Open transcript"}):null]},`${B.span_run_id}|${B.span_id}`))})]}):null,j&&_r.length?s.jsxs("div",{style:{marginBottom:12},children:[s.jsx("div",{className:"amx-small",style:{marginBottom:6,opacity:.85},children:"runs (fallback)"}),s.jsx("div",{className:"amx-list",style:{maxHeight:240},children:_r.slice(0,40).map(B=>s.jsxs("div",{className:"amx-item",style:{display:"flex",justifyContent:"space-between",gap:10,alignItems:"center"},children:[s.jsxs("div",{style:{minWidth:0},children:[s.jsxs("div",{className:"amx-mono",style:{fontSize:11,opacity:.95},children:["run:",B.run_id]}),s.jsxs("div",{className:"amx-small",children:["assertions=",B.count,B.last_observed_at_fmt?` · last=[${B.last_observed_at_fmt}]`:""]})]}),s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>Ss({run_id:B.run_id,assertion:B.assertion}),children:"Open transcript"})]},B.run_id))})]}):null,!Ji.length&&!(j&&_r.length)?s.jsx("div",{className:"amx-small",children:"(no provenance)"}):null]})]})]})})}function Kl({open:e,title:t,children:n,actions:r,variant:o="default",onClose:l}){const u=p.useId();if(p.useEffect(()=>{if(!e)return;const f=m=>{m.key==="Escape"&&l()};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[e,l]),!e)return null;const c=o==="fullscreen";return s.jsx("div",{className:`modal_backdrop${c?" fullscreen":""}`,onMouseDown:f=>{f.target===f.currentTarget&&l()},children:s.jsxs("div",{className:`modal_panel${c?" fullscreen":""}`,role:"dialog","aria-modal":"true","aria-labelledby":u,children:[s.jsxs("div",{className:"modal_header",children:[s.jsx("div",{className:"modal_title",id:u,children:t}),s.jsx("button",{className:"btn",onClick:l,children:"Close"})]}),s.jsx("div",{className:"modal_body",children:n}),r?s.jsx("div",{className:"modal_footer",children:r}):null]})})}function sp(e,t="session"){const n=String(e||"").trim().toLowerCase();return n==="run"||n==="session"||n==="global"||n==="all"?n:t}function nl(e){const t=typeof e=="string"?e.trim():"";if(!t)return null;const n=t.replace(/(\.\d{3})\d+/,"$1"),r=Date.parse(n);return Number.isFinite(r)?r:null}function Gl(e){if(typeof e!="number"||!Number.isFinite(e))return"—";const t=new Date(e),n=t.getUTCFullYear(),r=String(t.getUTCMonth()+1).padStart(2,"0"),o=String(t.getUTCDate()).padStart(2,"0"),l=String(t.getUTCHours()).padStart(2,"0"),u=String(t.getUTCMinutes()).padStart(2,"0");return`${n}/${r}/${o} ${l}:${u}`}function dL(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=nl(t);return n!==null?Gl(n):t}function Hg(e){const t=typeof e=="string"?e:String(e??"");return t?!t.includes("\\n")&&!t.includes("\\r")&&!t.includes("\\t")?t:t.replace(/\\r\\n/g,`
133
- `).replace(/\\n/g,`
134
- `).replace(/\\t/g," "):""}function F0(e){return String(e??"").replace(/[*_`~]/g,"")}function Gh(e,t){const n=!!(t!=null&&t.strip_punct),r=Hg(e);let o=F0(r).replace(/\s+/g," ").trim().toLowerCase();return n&&(o=o.replace(/[^\p{L}\p{N}\s]+/gu,"").replace(/\s+/g," ").trim()),o}function Kh(e,t){const n=String(t??"").trim();if(!n)return!1;const r=Gh(n,{strip_punct:!1});if(!r)return!1;if(Gh(String(e??""),{strip_punct:!1}).includes(r))return!0;const l=Gh(n,{strip_punct:!0});return l?Gh(String(e??""),{strip_punct:!0}).includes(l):!1}function pv(e){const t=Hg(e).trim();if(!t)return[];const n=[],r=u=>{const c=String(u??"").replace(/\s+/g," ").trim();c&&(c.length<6||n.includes(c)||n.push(c))},o=t.search(/[`*_~]/);if(o>0){const u=t.slice(0,o);u.replace(/\s+/g," ").trim().length>=10&&r(u)}const l=[/`([^`]+)`/g,/\*\*([^*]+)\*\*/g,/__([^_]+)__/g,/\*([^*]+)\*/g,/_([^_]+)_/g];for(const u of l){let c;for(;(c=u.exec(t))!==null;){const f=String(c[1]??"").trim();f&&r(f)}}return r(F0(t)),n}function fL(e){const t=String(e??"").replace(/\r\n/g,`
135
- `).replace(/\r/g,`
136
- `);if(!t)return null;const n=t.split(`
137
- `);let r;const o=[],l=[];let u=null,c=[],f=!1;const m=()=>{if(!u)return;const w=c.join(`
138
- `).trim();w&&l.push({role:u,lines:[w]}),u=null,c=[]};for(const w of n){const x=r?null:w.match(/^\s*created_at\s*=\s*(.+)\s*$/i);if(x&&x[1]){r=x[1].trim();continue}const j=w.match(/^\s*(USER|ASSISTANT|SYSTEM)\s*:\s*(.*)$/i);if(j){f=!0,m();const b=String(j[1]||"").trim().toLowerCase();u=b==="user"?"user":b==="assistant"?"assistant":"system";const N=String(j[2]??"");c=N?[N]:[];continue}u?c.push(w):o.push(w)}if(m(),!f||!l.length)return null;const _=o.join(`
139
- `).trim(),g={messages:[]};r&&(g.created_at=r),_&&g.messages.push({role:"system",content:_});for(const w of l)g.messages.push({role:w.role,content:w.lines.join(`
140
- `)});return g.messages.length?g:null}function gv(e,t){const n=String(e||""),r=String(t||"");return r>n?r:n}function yv(e){const t=String((e==null?void 0:e.subject)||"").trim(),n=String((e==null?void 0:e.predicate)||"").trim(),r=String((e==null?void 0:e.object)||"").trim(),o=String((e==null?void 0:e.observed_at)||"").trim(),l=String((e==null?void 0:e.scope)||"").trim(),u=String((e==null?void 0:e.owner_id)||"").trim();return`${t}|${n}|${r}|${o}|${l}|${u}`}function hL(e){const t=String((e==null?void 0:e.observed_at)||"").trim(),n=String((e==null?void 0:e.subject)||"").trim(),r=String((e==null?void 0:e.predicate)||"").trim(),o=String((e==null?void 0:e.object)||"").trim(),l=String((e==null?void 0:e.scope)||"").trim(),u=String((e==null?void 0:e.owner_id)||"").trim(),c=[];l&&c.push(`scope=${l}`),u&&c.push(`owner=${u}`);const f=c.length?` (${c.join(", ")})`:"";return`${t?`[${t}] `:""}${n} --${r}--> ${o}${f}`}function mL({gateway:e,selected_run_id:t,selected_session_id:n}){const[r,o]=p.useState(String(t||"").trim()),[l,u]=p.useState(String(n||"").trim()),[c,f]=p.useState("all"),m=c==="all",[_,g]=p.useState(!0),[w,x]=p.useState(750),[j,b]=p.useState(5e3),[N,C]=p.useState([]),[E,T]=p.useState(void 0),[I,K]=p.useState(""),[U,J]=p.useState(!1),[Y,re]=p.useState([]),[ce,fe]=p.useState(!1),[W,O]=p.useState(!1),[$,z]=p.useState(""),[A,ee]=p.useState(""),[P,F]=p.useState(""),[G,R]=p.useState(""),[Z,X]=p.useState("artifact"),[ie,ne]=p.useState(null),[ye,he]=p.useState(""),[pe,Ne]=p.useState(null),Ue=p.useRef(!1),We=p.useMemo(()=>{const le=pe,ke=le!=null&&le.attributes&&typeof le.attributes=="object"&&!Array.isArray(le.attributes)?le.attributes:null;return(ke&&typeof ke.evidence_quote=="string"?String(ke.evidence_quote):"").trim()},[pe]),pt=p.useMemo(()=>{const le=ie,ke=le&&typeof le=="object"&&!Array.isArray(le)?le:null,Ye=ke&&typeof ke.note=="string"?String(ke.note):"";return Hg(Ye).trim()},[ie]),Fe=p.useMemo(()=>{const le=ie&&typeof ie=="object"&&!Array.isArray(ie)?ie:null,ke=le&&Array.isArray(le.messages)?le.messages:null;return Array.isArray(ke)?ke:null},[ie]),tt=p.useMemo(()=>{const le=pt,ke=We;return!le||!ke?!1:Kh(le,ke)},[We,pt]),lt=p.useMemo(()=>{const le=Fe,ke=We;if(!le||!ke)return[];const Ye=[];for(let Ge=0;Ge<Math.min(le.length,500);Ge++){const rt=le[Ge],ct=(rt==null?void 0:rt.content)==null?"":String(rt.content);Kh(ct,ke)&&Ye.push(Ge)}return Ye},[We,Fe]),Ke=p.useMemo(()=>new Set(lt),[lt]),je=lt.length?lt[0]:null,Re=p.useCallback(le=>{const ke=document.getElementById(`source_msg_${le}`);ke&&typeof ke.scrollIntoView=="function"&&ke.scrollIntoView({block:"center",behavior:"smooth"})},[]),ht=p.useCallback(()=>{const le=document.getElementById("source_note_hit_0")||document.getElementById("source_note_msg_hit_0");le&&typeof le.scrollIntoView=="function"&&le.scrollIntoView({block:"center",behavior:"smooth"})},[]);p.useEffect(()=>{if(ce&&!(W||$)&&!Ue.current){if(je!==null){Ue.current=!0,window.setTimeout(()=>Re(je),0);return}if(tt){Ue.current=!0,window.setTimeout(()=>ht(),0);return}}},[Re,ht,$,je,W,tt,ce]);const xe=p.useRef(new Set),Ie=p.useRef(""),qe=p.useRef(null),zt=p.useRef(null);p.useEffect(()=>{o(String(t||"").trim())},[t]),p.useEffect(()=>{u(String(n||"").trim())},[n]);const en=p.useMemo(()=>{const le=String(r||"").trim(),ke=String(l||"").trim();return`mindmap:${c}:${le}:${ke}`},[r,l,c]),bn=p.useMemo(()=>{let le=null,ke=null;for(const Ye of N){const Ge=nl(Ye==null?void 0:Ye.observed_at);Ge!==null&&(le=le===null?Ge:Math.min(le,Ge),ke=ke===null?Ge:Math.max(ke,Ge))}return{min_ms:le,max_ms:ke}},[N]),Wt=1e3,It=p.useMemo(()=>{const le=bn.min_ms,ke=bn.max_ms;if(typeof le!="number"||typeof ke!="number"||!Number.isFinite(le)||!Number.isFinite(ke))return null;if(ke<=le)return{min_ms:le,max_ms:le,real_max_ms:ke};const Ye=le+Math.ceil((ke-le)/Wt)*Wt;return{min_ms:le,max_ms:Ye,real_max_ms:ke}},[bn.max_ms,bn.min_ms]),[Sn,ns]=p.useState(!0),[Ot,pn]=p.useState(null);p.useEffect(()=>{Sn&&It&&pn(It.max_ms)},[Sn,It]);const Bn=p.useMemo(()=>{const le=typeof Ot=="number"?Ot:null;return le===null?N:N.filter(ke=>{const Ye=nl(ke==null?void 0:ke.observed_at);return Ye===null?!0:Ye<=le})},[N,Ot]),An=p.useCallback((le,ke)=>{const Ye=Array.isArray(le)?le:[],Ge=String(Ie.current||"").trim(),rt=new Set,ct=[];let Et="";for(const kt of Ye){if(!kt||typeof kt!="object"||typeof kt.subject!="string"||typeof kt.predicate!="string"||typeof kt.object!="string")continue;const Kt=yv(kt);if(rt.has(Kt))continue;rt.add(Kt),ct.push(kt);const xt=String(kt.observed_at||"").trim();xt&&(Et=gv(Et,xt))}C(ct),T(ke==null?void 0:ke.warnings),xe.current=rt,Ie.current=Et||Ge},[]),gn=p.useCallback(async le=>{const ke=sp(le.scope,"session"),Ye=String(le.subject||"").trim(),Ge=String(le.predicate||"").trim(),rt=String(le.object||"").trim(),ct=String(le.since||"").trim(),Et=String(le.until||"").trim(),kt=String(le.active_at||"").trim(),Kt=String(le.query_text||"").trim(),xt=typeof le.min_score=="number"&&Number.isFinite(le.min_score)?Number(le.min_score):void 0,Yt=le.order==="asc"?"asc":"desc",qt=typeof le.limit=="number"&&Number.isFinite(le.limit)?Number(le.limit):0,Pt=String(r||"").trim(),At=String(l||"").trim(),$t={scope:ke,all_owners:m,limit:qt,order:Yt};Ye&&($t.subject=Ye),Ge&&($t.predicate=Ge),rt&&($t.object=rt),ct&&($t.since=ct),Et&&($t.until=Et),kt&&($t.active_at=kt),Kt&&($t.query_text=Kt),typeof xt=="number"&&($t.min_score=xt),m||(ke==="run"?Pt&&($t.run_id=Pt):ke==="session"?At?$t.session_id=At:Pt&&($t.run_id=Pt):ke==="all"&&(Pt?$t.run_id=Pt:At&&($t.session_id=At)));try{const De=await e.kg_query($t),on=Array.isArray(De==null?void 0:De.items)?De.items:[],ut=De==null?void 0:De.warnings;return{ok:(De==null?void 0:De.ok)!==!1,count:Number((De==null?void 0:De.count)||on.length),items:on,warnings:ut,raw:De}}catch(De){const on=De instanceof Error?De.message:String(De);if(on.includes("Run '")&&on.includes("not found")&&!At&&(ke==="session"||ke==="all")&&Pt){const tn=await e.kg_query({...$t,run_id:void 0,session_id:Pt}),dt=Array.isArray(tn==null?void 0:tn.items)?tn.items:[],Un=tn==null?void 0:tn.warnings;return{ok:(tn==null?void 0:tn.ok)!==!1,count:Number((tn==null?void 0:tn.count)||dt.length),items:dt,warnings:Un,raw:tn}}throw new Error(on||"KG query failed")}},[m,e,r,l]),In=p.useCallback(async le=>{var Ge;const ke=String(le.run_id||"").trim(),Ye=String(le.span_id||"").trim();if(!(!ke||!Ye)){fe(!0),O(!0),z(""),F(ke),R(Ye),X("artifact"),ee(`source span:${Ye}`),ne(null),he(""),Ne(le.assertion&&typeof le.assertion=="object"?le.assertion:null),Ue.current=!1;try{const rt=[ke],ct=typeof((Ge=le.assertion)==null?void 0:Ge.owner_id)=="string"?String(le.assertion.owner_id).trim():"";ct&&ct!==ke&&rt.push(ct);let Et=null,kt=null;for(const Kt of rt)try{kt=await(await e.download_run_artifact_content(Kt,Ye)).text(),Kt!==ke&&F(Kt);break}catch(xt){Et=xt instanceof Error?xt.message:String(xt)}if(kt==null)throw new Error(Et||"Failed to load source span");he(kt);try{const Kt=JSON.parse(kt);ne(Kt)}catch{ne(null)}}catch(rt){const ct=rt instanceof Error?rt.message:String(rt);z(ct||"Failed to load source span")}finally{O(!1)}}},[e]),wn=p.useCallback(async le=>{const ke=String(le.run_id||"").trim();if(!ke)return null;try{const Ye=await e.list_run_artifacts(ke,{limit:200}),rt=(Array.isArray(Ye==null?void 0:Ye.items)?Ye.items:[]).map(xt=>{const Yt=typeof(xt==null?void 0:xt.artifact_id)=="string"?String(xt.artifact_id).trim():"",qt=xt!=null&&xt.tags&&typeof xt.tags=="object"&&!Array.isArray(xt.tags)?xt.tags:null,Pt=qt&&typeof qt.kind=="string"?String(qt.kind).trim():"";return{artifact_id:Yt,kind:Pt}}).filter(xt=>!!(xt.artifact_id&&(xt.kind==="conversation_span"||xt.kind==="memory_note")));if(!rt.length)return null;if(rt.length===1)return rt[0].artifact_id;const ct=le.assertion,Et=ct!=null&&ct.attributes&&typeof ct.attributes=="object"&&!Array.isArray(ct.attributes)?ct.attributes:null,Kt=(Et&&typeof Et.evidence_quote=="string"?String(Et.evidence_quote):"").trim();if(!Kt)return null;for(const xt of rt.slice(0,10))try{const qt=await(await e.download_run_artifact_content(ke,xt.artifact_id)).text(),Pt=JSON.parse(qt);if(Pt&&typeof Pt=="object"){const At=typeof Pt.note=="string"?String(Pt.note):"";if(At&&At.includes(Kt))return xt.artifact_id;const $t=Array.isArray(Pt.messages)?Pt.messages:null;if($t){for(const De of $t.slice(0,200))if(((De==null?void 0:De.content)==null?"":String(De.content)).includes(Kt))return xt.artifact_id}}}catch{}}catch{}return null},[e]),ks=p.useCallback(async le=>{const ke=String(le.run_id||"").trim();if(ke){fe(!0),O(!0),z(""),F(ke),R(""),X("run_input"),ee(`transcript run:${ke}`),ne(null),he(""),Ne(le.assertion&&typeof le.assertion=="object"?le.assertion:null),Ue.current=!1;try{const Ye=await wn({run_id:ke,assertion:le.assertion});if(Ye){await In({run_id:ke,span_id:Ye,assertion:le.assertion});return}const Ge=await e.get_run_input_data(ke),rt=Ge&&typeof Ge=="object"&&!Array.isArray(Ge)?Ge.input_data:null,ct={kind:"run_input_data",run_id:ke};if(Ge&&typeof(Ge==null?void 0:Ge.workflow_id)=="string"&&(ct.workflow_id=String(Ge.workflow_id)),rt&&typeof rt=="object"&&!Array.isArray(rt)){const Et=rt.context,Kt=(Et&&typeof Et=="object"&&Array.isArray(Et.messages)?Et.messages:null)||(Array.isArray(rt.messages)?rt.messages:null);Array.isArray(Kt)&&(ct.messages=Kt);const xt=["text","prompt","task","message"];for(const Yt of xt){const qt=rt[Yt];if(typeof qt=="string"&&qt.trim()){ct.note=qt.trim();break}}ct.input_data=rt}!ct.messages&&!ct.note&&(ct.note=JSON.stringify(rt??Ge??{},null,2));try{const Et=await e.get_run(ke),kt=Et&&typeof(Et==null?void 0:Et.created_at)=="string"?String(Et.created_at):"";kt&&(ct.created_at=kt)}catch{}ne(ct),he(JSON.stringify(Ge,null,2))}catch(Ye){const Ge=Ye instanceof Error?Ye.message:String(Ye);z(Ge||"Failed to load run input transcript")}finally{O(!1)}}},[e,In,wn]),Kn=p.useCallback(async()=>{K(""),J(!0);try{const le=c==="all"?"all":c,ke=await gn({scope:le,limit:0,order:"desc"});An(ke.items||[],{warnings:ke.warnings}),qe.current={scope:le}}catch(le){const ke=le instanceof Error?le.message:String(le);K(ke||"Load failed")}finally{J(!1)}},[gn,An,c]);p.useEffect(()=>{N.length||Kn()},[]);const js=p.useCallback(async le=>{const ke=sp(le.scope,"session");return zt.current=le,await gn({scope:ke,subject:le.subject,predicate:le.predicate,object:le.object,query_text:le.query_text,min_score:le.min_score,since:le.since,until:le.until,active_at:le.active_at,limit:typeof le.limit=="number"?le.limit:0,order:"desc"})},[gn]),Nr=p.useCallback((le,ke)=>{var Ye;if((ke==null?void 0:ke.kind)==="live query"){const Ge=zt.current;Ge&&(qe.current={scope:sp(Ge.scope,"session"),subject:typeof Ge.subject=="string"?Ge.subject:void 0,predicate:typeof Ge.predicate=="string"?Ge.predicate:void 0,object:typeof Ge.object=="string"?Ge.object:void 0})}An(le,{warnings:(Ye=ke==null?void 0:ke.result)==null?void 0:Ye.warnings})},[An]),On=p.useCallback(async()=>{const le=qe.current;if(!le)return;const ke=String(Ie.current||"").trim(),Ye=await gn({scope:le.scope,subject:le.subject,predicate:le.predicate,object:le.object,since:ke||void 0,order:"asc",limit:0}),Ge=Array.isArray(Ye.items)?Ye.items:[];if(!Ge.length)return;const ct=Date.now()+Math.max(250,Math.min(2e4,j)),Et=xe.current,kt=[],Kt=[];let xt=String(Ie.current||"").trim();for(const Yt of Ge){if(!Yt||typeof Yt!="object"||typeof Yt.subject!="string"||typeof Yt.predicate!="string"||typeof Yt.object!="string")continue;const qt=yv(Yt);if(Et.has(qt))continue;Et.add(qt),kt.push(Yt),Kt.push({id:qt,assertion:Yt,expires_at_ms:ct});const Pt=String(Yt.observed_at||"").trim();Pt&&(xt=gv(xt,Pt))}kt.length&&(Ie.current=xt,C(Yt=>{const qt=Yt.concat(kt);return qt.sort((Pt,At)=>String((At==null?void 0:At.observed_at)||"").localeCompare(String((Pt==null?void 0:Pt.observed_at)||""))),qt}),re(Yt=>{const qt=Yt.concat(Kt);return qt.sort((Pt,At)=>At.expires_at_ms-Pt.expires_at_ms),qt.slice(0,30)}))},[j,gn]);return p.useEffect(()=>{if(!_)return;let le=!1,ke=null;const Ye=async()=>{if(!le){try{await On()}catch{}le||(ke=window.setTimeout(()=>void Ye(),Math.max(250,Math.min(6e4,w))))}};return Ye(),()=>{le=!0,ke!==null&&window.clearTimeout(ke)}},[_,w,On]),p.useEffect(()=>{if(!Y.length)return;const le=window.setInterval(()=>{const ke=Date.now();re(Ye=>Ye.filter(Ge=>Ge.expires_at_ms>ke))},250);return()=>window.clearInterval(le)},[Y.length]),s.jsxs("div",{className:"mindmap_root",children:[s.jsxs("div",{className:"mindmap_bar",children:[s.jsx("button",{className:"btn",onClick:()=>void Kn(),disabled:U,children:U?"Loading…":"Load snapshot"}),s.jsxs("label",{className:"field_inline",children:[s.jsx("span",{className:"mono muted",children:"source"}),s.jsxs("select",{value:c,onChange:le=>{const ke=String(le.target.value||"").trim();(ke==="all"||ke==="global"||ke==="session"||ke==="run")&&f(ke)},children:[s.jsx("option",{value:"all",children:"all memory"}),s.jsx("option",{value:"global",children:"global"}),s.jsx("option",{value:"session",children:"session"}),s.jsx("option",{value:"run",children:"run"})]})]}),s.jsx(yC,{checked:_,onChange:g}),c==="session"?s.jsxs("label",{className:"field_inline",children:[s.jsx("span",{className:"mono muted",children:"session_id"}),s.jsx("input",{className:"mono",value:l,onChange:le=>u(String(le.target.value||"")),placeholder:"(required)"})]}):null,c==="run"?s.jsxs("label",{className:"field_inline",children:[s.jsx("span",{className:"mono muted",children:"run_id"}),s.jsx("input",{className:"mono",value:r,onChange:le=>o(String(le.target.value||"")),placeholder:"(required)"})]}):null,s.jsxs("details",{className:"mindmap_details",children:[s.jsx("summary",{className:"mono muted",children:"advanced"}),s.jsx("div",{className:"mindmap_advanced",children:s.jsxs("div",{className:"field_inline",children:[s.jsx("span",{className:"mono muted",style:{width:84},children:"poll_ms"}),s.jsx("input",{type:"number",min:250,max:6e4,step:50,value:w,onChange:le=>x(Math.max(250,Number(le.target.value||0)||750))}),s.jsx("span",{className:"mono muted",children:"highlight_ms"}),s.jsx("input",{type:"number",min:250,max:2e4,step:250,value:j,onChange:le=>b(Math.max(250,Number(le.target.value||0)||5e3))})]})})]})]}),I?s.jsx("div",{className:"mindmap_error mono",children:I}):null,s.jsxs("div",{className:"mindmap_explorer",children:[s.jsx(uL,{title:"mindmap",resetKey:en,queryMode:"replace",items:Bn,warnings:E,onQuery:js,onItemsReplace:Nr,onOpenSpan:({run_id:le,span_id:ke,assertion:Ye})=>{In({run_id:le,span_id:ke,assertion:Ye})},onOpenTranscript:({run_id:le,span_id:ke,assertion:Ye})=>{const Ge=String(le||"").trim(),rt=typeof ke=="string"?String(ke).trim():"";Ge&&(rt?In({run_id:Ge,span_id:rt,assertion:Ye}):ks({run_id:Ge,assertion:Ye}))}},en),Y.length?s.jsxs("div",{className:"mindmap_recent mindmap_overlay mindmap_overlay_recent",children:[s.jsx("div",{className:"mindmap_recent_title mono muted",children:"new assertions"}),s.jsx("div",{className:"mindmap_recent_list",children:Y.slice().sort((le,ke)=>ke.expires_at_ms-le.expires_at_ms).slice(0,12).map(le=>s.jsx("div",{className:"mindmap_recent_item mono",children:hL(le.assertion)},le.id))})]}):null,It?s.jsx("div",{className:"mindmap_timeline mindmap_overlay mindmap_overlay_timeline",children:s.jsxs("div",{className:"mindmap_timeline_row",children:[s.jsx("div",{className:"mindmap_timeline_label mono muted",children:Gl(Math.min(typeof Ot=="number"?Ot:It.max_ms,It.real_max_ms))}),s.jsx("input",{className:"mindmap_slider",type:"range",min:It.min_ms,max:It.max_ms,step:Wt,value:typeof Ot=="number"?Ot:It.max_ms,onChange:le=>{const ke=Number(le.target.value||0);pn(ke),ns(ke>=It.max_ms)}}),s.jsxs("div",{className:"mindmap_timeline_counts mono muted",children:[Bn.length.toLocaleString(),"/",N.length.toLocaleString()]})]})}):null]}),s.jsxs(Kl,{open:ce,title:A||"source",onClose:()=>{fe(!1)},children:[W?s.jsx("div",{className:"mono muted",children:"Loading…"}):null,$?s.jsx("div",{className:"mindmap_error mono",children:$}):null,!W&&!$?s.jsxs("div",{className:"source_span",children:[(()=>{const le=pe;if(!le)return null;const ke=String(le.subject||"").trim(),Ye=String(le.predicate||"").trim(),Ge=String(le.object||"").trim(),rt=Gl(nl(le.observed_at)),ct=le.attributes&&typeof le.attributes=="object"&&!Array.isArray(le.attributes)?le.attributes:null,Et=ct&&typeof ct.evidence_quote=="string"?String(ct.evidence_quote):"",kt=ct&&typeof ct.original_context=="string"?String(ct.original_context):"";return s.jsxs("div",{className:"source_header",children:[s.jsxs("div",{className:"mono source_triple",title:`${ke} --${Ye}--> ${Ge}`,children:[ke," ",s.jsxs("span",{className:"muted",children:["—",Ye,"→"]})," ",Ge," ",rt?s.jsxs("span",{className:"muted",children:["[",rt,"]"]}):null]}),Et?s.jsxs("div",{className:"source_evidence",children:[s.jsx("div",{className:"mono muted",style:{fontSize:11,marginBottom:6},children:"evidence_quote"}),s.jsx("pre",{className:"mono source_evidence_quote",children:Et}),kt?s.jsxs("details",{className:"source_evidence_more",children:[s.jsx("summary",{className:"mono muted",children:"original_context"}),s.jsx("pre",{className:"mono source_evidence_quote",children:kt})]}):null]}):null]})})(),s.jsxs("div",{className:"mono muted",style:{marginBottom:10},children:["run_id=",P," · ",Z==="artifact"?`span_id=${G}`:"source=input_data"]}),s.jsxs("div",{className:"source_actions",children:[je!==null?s.jsx("button",{className:"btn",onClick:()=>Re(je),children:"Jump to evidence"}):null,je===null&&tt?s.jsx("button",{className:"btn",onClick:()=>ht(),children:"Jump to evidence"}):null]}),(()=>{const le=ie,ke=le&&typeof le=="object"&&!Array.isArray(le)?le:null,Ye=Fe,Ge=pt,rt=ke&&typeof ke.created_at=="string"?String(ke.created_at):"",ct=rt?nl(rt):null,Et=ct!==null?Gl(ct):rt,kt=ke&&ke.span&&typeof ke.span=="object"&&!Array.isArray(ke.span)?ke.span:null,Kt=kt&&typeof kt.from_timestamp=="string"?String(kt.from_timestamp):"",xt=kt&&typeof kt.to_timestamp=="string"?String(kt.to_timestamp):"",Yt=Kt?nl(Kt):null,qt=xt?nl(xt):null,Pt=Yt!==null&&qt!==null?`${Gl(Yt)} → ${Gl(qt)}`:"";if(Ge){const At=fL(Ge);if(At){const $t=We,De=$t?At.messages.findIndex(dt=>Kh(dt.content,$t)):-1,on=$t?pv($t):[],ut=At.created_at||rt,tn=ut?dL(ut):rt?Et:"";return s.jsx("div",{className:"source_chat",children:At.messages.map((dt,Un)=>{const an=dt.role,Ys=!!($t&&Kh(dt.content,$t)),ss=an==="user"?"USER":an==="assistant"?"ASSISTANT":"SYSTEM";return s.jsxs("div",{id:Un===De?"source_note_msg_hit_0":void 0,className:`source_msg source_${an} ${Ys?"source_match":""}`,children:[s.jsxs("div",{className:"source_msg_meta mono muted",children:[s.jsxs("span",{children:["#",Un+1," · ",ss,Ys?s.jsx("span",{className:"source_match_badge",children:"evidence"}):null]}),tn?s.jsx("span",{title:ut||"",children:tn}):null]}),s.jsx("div",{className:"source_msg_body",children:s.jsx(qi,{text:dt.content,highlights:Ys&&on.length?on:void 0,highlightClassName:"source_note_hit",highlightId:Un===De?"source_note_hit_0":void 0})})]},`note_msg:${Un}`)})})}return s.jsxs("div",{className:"source_note",children:[rt?s.jsx("div",{className:"mono muted",style:{marginBottom:10},children:s.jsxs("span",{title:rt,children:["created_at=",Et]})}):null,s.jsx(qi,{text:Ge,highlights:We?pv(We):void 0,highlightClassName:"source_note_hit",highlightId:"source_note_hit_0"})]})}if(Ye){const At=new Map;for(const De of Ye){const on=typeof(De==null?void 0:De.role)=="string"?String(De.role):"unknown";At.set(on,(At.get(on)||0)+1)}const $t=Array.from(At.entries()).sort((De,on)=>on[1]-De[1]||De[0].localeCompare(on[0])).map(([De,on])=>`${De}×${on}`).join(" · ");return s.jsxs("div",{className:"source_chat",children:[rt?s.jsxs("div",{className:"mono muted",style:{marginBottom:10},children:[s.jsxs("span",{title:rt,children:["created_at=",Et]})," · messages=",Ye.length]}):null,Pt?s.jsxs("div",{className:"mono muted",style:{marginBottom:10},children:["span=",Pt]}):null,$t?s.jsxs("div",{className:"mono muted",style:{marginBottom:10},children:["participants: ",$t]}):null,Ye.slice(0,200).map((De,on)=>{var Wr,dr;const ut=typeof(De==null?void 0:De.role)=="string"?String(De.role):"unknown",tn=(De==null?void 0:De.content)==null?"":String(De.content),dt=typeof(De==null?void 0:De.timestamp)=="string"?String(De.timestamp):"",Un=dt?nl(dt):null,an=Un!==null?Gl(Un):dt,Ys=typeof(De==null?void 0:De.message_id)=="string"?String(De.message_id):typeof((Wr=De==null?void 0:De.metadata)==null?void 0:Wr.message_id)=="string"?String(De.metadata.message_id):typeof((dr=De==null?void 0:De.metadata)==null?void 0:dr.id)=="string"?String(De.metadata.id):"",ss=Ke.has(on);return s.jsxs("div",{id:`source_msg_${on}`,className:`source_msg source_${ut} ${ss?"source_match":""}`,children:[s.jsxs("div",{className:"source_msg_meta mono muted",children:[s.jsxs("span",{children:["#",on+1," · ",ut,ss?s.jsx("span",{className:"source_match_badge",children:"evidence"}):null,Ys?s.jsx("span",{className:"source_msg_id",children:Ys}):null]}),dt?s.jsx("span",{title:dt,children:an}):null]}),s.jsx("div",{className:"source_msg_body",children:s.jsx(qi,{text:tn})})]},on)})]})}return s.jsx("pre",{className:"mono source_raw",style:{whiteSpace:"pre-wrap",wordBreak:"break-word"},children:(typeof le=="string"?le:ye)||"(empty)"})})()]}):null]})]})}const rp=4;function _L(e){var l;const t=(l=e==null?void 0:e.discoveries)==null?void 0:l.dreams_signals_brief;if(!t||typeof t!="object"||Array.isArray(t))return null;const n=typeof t.count=="number"&&Number.isInteger(t.count)&&t.count>0?t.count:0;if(!n)return null;const r=u=>Array.isArray(u)?u.filter(c=>typeof c=="string").map(c=>c.trim()).filter(Boolean):[],o=typeof t.dreams=="number"&&Number.isInteger(t.dreams)&&t.dreams>0?t.dreams:null;return{count:n,kinds:r(t.kinds),felt_tones:r(t.felt_tones),dreams:o}}function wv(e){if(!e||typeof e!="object")return null;const t=String(e.title||"").trim(),n=String(e.statement||"").trim();if(!t&&!n)return null;const r=typeof e.entry_id=="string"&&e.entry_id.trim()?e.entry_id.trim():null;return{record_id:String(e.record_id||"").trim(),title:t,statement:n,entry_id:r}}function pL(e){var c,f;const t=m=>{var g;const _=(g=e==null?void 0:e[m])==null?void 0:g.open;return Array.isArray(_)?_.map(wv).filter(w=>w!==null):[]},n=t("questions"),r=t("problems"),o=(c=e==null?void 0:e.lessons)==null?void 0:c.lessons,l=Array.isArray(o)?o.map(wv).filter(m=>m!==null):[],u=typeof((f=e==null?void 0:e.lessons)==null?void 0:f.total)=="number"?e.lessons.total:l.length;return{questions:n.slice(0,rp),questions_total:n.length,problems:r.slice(0,rp),problems_total:r.length,lessons:l.slice(0,rp),lessons_total:u}}function ip(e){return e===null||!Number.isFinite(e)||e<0?"":e<1e3?String(Math.round(e)):e<1e6?`${(e/1e3).toFixed(e<1e4?1:0)}k`:`${(e/1e6).toFixed(1)}M`}const vv={review:"Review",working:"Working",pending:"Pending",done:"Done"},gL={review:"nothing needs you",working:"idle",pending:"nothing scheduled",done:"no recent runs"},yL={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 wL(e){const t=String((e==null?void 0:e.status)||"").trim().toLowerCase();if(So(t))return"done";const n=Au(e);return n==="tool_approval"||n==="user_response"?"review":n==="scheduled"||t==="pending"||t==="queued"||t==="created"?"pending":"working"}function vL(e){const t=Au(e);return t==="tool_approval"||t==="user_response"}function xv(e,t=Date.now()){const n=wL(e),r=e!=null&&e.waiting&&typeof e.waiting=="object"?e.waiting:null,o=Tf(r),l=qn((r==null?void 0:r.since)||(e==null?void 0:e.updated_at)||(e==null?void 0:e.created_at)||"");return{run_id:String((e==null?void 0:e.run_id)||""),column:n,workflow:String((e==null?void 0:e.workflow_id)||"").trim()||"(workflow?)",status:String((e==null?void 0:e.status)||"").trim().toLowerCase(),wait_kind:Au(e),reason:ab(e),tool_names:o.map(u=>String((u==null?void 0:u.name)||"tool")).filter(Boolean),wait_key:String((r==null?void 0:r.wait_key)||"").trim(),allow_free_text:(r==null?void 0:r.allow_free_text)!==!1,prompt:String((r==null?void 0:r.prompt)||"").trim(),since_ms:l,duration_ms:wg(e,t),tokens_total:typeof(e==null?void 0:e.tokens_total)=="number"?e.tokens_total:null,llm_calls:typeof(e==null?void 0:e.llm_calls)=="number"?e.llm_calls:null,tool_calls:typeof(e==null?void 0:e.tool_calls)=="number"?e.tool_calls:null,is_scheduled:!!(e!=null&&e.is_scheduled),schedule_interval:String((e==null?void 0:e.schedule_interval)||"").trim(),failed:String((e==null?void 0:e.status)||"").trim().toLowerCase()==="failed",error:String((e==null?void 0:e.error)||"").trim(),paused:!!(e!=null&&e.paused),is_subrun:!!String((e==null?void 0:e.parent_run_id)||"").trim(),tag:ff(e),tag_label:zx(e),automation_id:ff(e)==="occurrence"?String((e==null?void 0:e.automation_id)||"").trim():""}}function xL(e,t,n=Date.now()){const r={pending:[],working:[],review:[],done:[]},o=t&&t.length?t:e,l=new Set;for(const u of o||[]){const c=String((u==null?void 0:u.run_id)||"").trim();!u||!c||l.has(c)||Jy(u)||vL(u)&&(l.add(c),r.review.push(xv(u,n)))}for(const u of e||[]){const c=String((u==null?void 0:u.run_id)||"").trim();if(!u||!c||l.has(c)||Jy(u))continue;const f=xv(u,n);r[f.column].push(f)}return r.review.sort((u,c)=>(u.since_ms??0)-(c.since_ms??0)),r.working.sort((u,c)=>(c.since_ms??0)-(u.since_ms??0)),r.pending.sort((u,c)=>(c.since_ms??0)-(u.since_ms??0)),r.done.sort((u,c)=>Number(c.failed)-Number(u.failed)||(c.since_ms??0)-(u.since_ms??0)),r}const ig={"12h":12*36e5,"24h":24*36e5,"48h":48*36e5,"72h":72*36e5,"7d":7*864e5,"14d":14*864e5,"1m":30*864e5,all:null},op={"12h":"last 12h","24h":"last 24h","48h":"last 48h","72h":"last 72h","7d":"last 7 days","14d":"last 14 days","1m":"last month",all:"all loaded"},bv="48h";function bL(e,t,n=Date.now()){const r=ig[t]??null;if(r===null)return{visible:e,hidden_count:0};const o=n-r,l=[];let u=0;for(const c of e)c.since_ms===null||c.since_ms>=o?l.push(c):u+=1;return{visible:l,hidden_count:u}}function kL(e,t=Date.now()){const n=String(e||"").trim();if(!n)return null;const r=Date.parse(n);return Number.isFinite(r)?Math.max(0,t-r):null}const jL=6e4;function nf(e,t=Date.now()){if(e===null||!Number.isFinite(e))return"";const n=Math.max(0,t-e);return n<6e4?`${Math.round(n/1e3)}s`:n<36e5?`${Math.round(n/6e4)}m`:n<864e5?`${(n/36e5).toFixed(1)}h`:`${(n/864e5).toFixed(1)}d`}function SL(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 NL(e){const t=String(e||"");return t.length>14?`${t.slice(0,6)}…${t.slice(-6)}`:t}function ap(e){const t=String(e||"").trim();return t.length>72?`${t.slice(0,70)}…`:t}function CL(e){const t=String(e||"");let n=t.includes(":")?t.slice(t.lastIndexOf(":")+1):t;if(t.includes(":")&&/^[0-9a-f]{6,}$/i.test(n.trim())){const r=t.slice(0,t.lastIndexOf(":"));/[a-z]/i.test(r)&&!/^[0-9a-f]+$/i.test(r.replace(/[@.\-_]/g,""))&&(n=r)}return n.length>34?`${n.slice(0,32)}…`:n}function rm(e){return e.toLowerCase().replace(/[_-]+/g," ")}function EL(e){var m,_;const t=e!=null&&e.spec&&typeof e.spec=="object"?e.spec:null,n=t!=null&&t.phases&&typeof t.phases=="object"&&!Array.isArray(t.phases)?t.phases:null;if(!n)return null;const r=Object.keys(n).filter(g=>g&&typeof g=="string");if(!r.length)return null;const o=[];for(const g of r){o.push({needle:rm(g),phase:g});const w=(m=n[g])==null?void 0:m.spoken_synonyms;if(Array.isArray(w))for(const x of w){const j=rm(String(x||"").trim());j&&o.push({needle:j,phase:g})}}const u=(typeof t.initial_phase=="string"&&r.includes(t.initial_phase)?t.initial_phase:null)??(r.includes("sleep")?"sleep":null);if(!u)return null;const c=[],f=(_=t==null?void 0:t.state_mode_axis)==null?void 0:_.words;if(f&&typeof f=="object"&&!Array.isArray(f))for(const[g,w]of Object.entries(f)){const x=String((w==null?void 0:w.phase)||"").trim(),j=rm(String(g||"").trim());j&&r.includes(x)&&c.push({needle:j,phase:x})}return{phases:r,synonyms:o,modes:c,initial:u,version:typeof t.version=="number"?t.version:null,sha256:String((e==null?void 0:e.sha256)||"").trim()}}const AL=["asleep","sleep","dream"],$L=["rest"],TL=["awake","idle"];function ML(e,t){const n=String(e||"").trim().toLowerCase();if(!n)return"unknown";if(t){const r=rm(n),o=t.synonyms.filter(u=>r.includes(u.needle)).sort((u,c)=>c.needle.length-u.needle.length);if(o.length)return o[0].phase;const l=t.modes.filter(u=>r.includes(u.needle)).sort((u,c)=>c.needle.length-u.needle.length);return l.length?l[0].phase:n.includes("task")&&!n.includes("no_task")&&t.phases.includes("work")?"work":AL.some(u=>n.includes(u))?t.initial:$L.some(u=>n.includes(u))&&t.phases.includes("personal")?"personal":TL.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 RL=new Set(["visit","work","personal","sleep","paused","resting","stopped","unknown"]),LL=new Set(["visit","work","personal","sleep","paused","resting","stopped","unknown"]);function IL(e){if(!e)return RL;const t=e.phases.filter(n=>LL.has(n));return new Set([...t,"paused","stopped","unknown"])}function OL(e){const[t,n]=hf(`board_${e.col}`),r=`mc_column_body_${e.col}`;return s.jsxs("div",{className:`mc_column mc_column_${e.col}${t?"":" list_collapsed"}`,children:[s.jsxs("div",{className:"mc_column_head",children:[s.jsx(mf,{open:t,on_toggle:n,controls:r,title:e.title,className:"mc_column_title"}),e.head]}),s.jsx("div",{className:"mc_column_body",id:r,hidden:!t,children:e.children})]})}function PL(e){var U,J,Y,re,ce,fe;const t=Date.now(),n=p.useMemo(()=>xL(e.runs,e.all_runs,Date.now()),[e.runs,e.all_runs]),[r,o]=p.useState(""),[l,u]=p.useState(""),[c,f]=p.useState(!1),[m,_]=p.useState(()=>{try{const W=localStorage.getItem("abstractobserver_done_window_v1");return W&&W in ig?W:bv}catch{return bv}}),g=p.useMemo(()=>bL(n.done,m,t),[n.done,m]),w=nf(e.runs_refreshed_at,t),x=n.review.length,j=g.visible.filter(W=>W.failed).length,[b,N]=p.useState(""),[C,E]=p.useState(null),T=W=>`${W.run_id}:${W.wait_key}:${W.since_ms??""}`;p.useEffect(()=>{r&&(n.review.some(W=>T(W)===r)||o(""))},[n,r]);async function I(W,O){o(T(W)),u("");try{await e.on_resume_wait(W.run_id,W.wait_key,O)}catch($){u(`${W.run_id}: ${String(($==null?void 0:$.message)||$||"resume failed")}`),o("")}}function K(W){const O=r===T(W),$=W.column==="review",z=$&&!W.wait_key;return s.jsxs("div",{className:`mc_card ${$?"mc_card_review":""} ${W.failed?"mc_card_failed":""}`,onClick:()=>e.on_open_run(W.run_id),role:"button",tabIndex:0,onKeyDown:A=>{A.key==="Enter"&&A.target===A.currentTarget&&e.on_open_run(W.run_id)},children:[s.jsxs("div",{className:"mc_card_head",children:[s.jsx("span",{className:"mc_card_title",title:W.workflow,children:CL(W.workflow)}),(()=>{const A=W.failed?"failed":um({status:W.status,paused:W.paused});return s.jsx("span",{className:`mc_status ${ac(A)}`,children:A==="unknown"?"?":A})})()]}),s.jsxs("div",{className:"mc_card_meta",children:[s.jsx("span",{className:"mono",title:W.run_id,children:NL(W.run_id)}),W.is_subrun?s.jsx("span",{title:"This wait lives in a child run of an agent workflow",children:"subrun"}):null,W.tag?s.jsx("span",{className:"mc_pill","data-tag":W.tag,children:W.tag_label}):null,W.automation_id?s.jsx("button",{type:"button",className:"btn btn_sm",title:"Open this occurrence's automation",onClick:A=>{A.stopPropagation(),e.on_open_automation(W.automation_id)},onKeyDown:A=>A.stopPropagation(),children:"Automation"}):null,W.duration_ms>=0?s.jsx("span",{children:SL(W.duration_ms)}):null,W.tokens_total!==null?s.jsxs("span",{children:[W.tokens_total.toLocaleString()," tk"]}):null,W.tool_calls!==null&&W.tool_calls>0?s.jsxs("span",{children:[W.tool_calls," tools"]}):null]}),W.is_scheduled&&W.schedule_interval?s.jsxs("div",{className:"mc_card_line",children:["every ",W.schedule_interval]}):null,W.failed&&W.error?s.jsx("div",{className:"mc_card_error",title:W.error,children:W.error.length>120?`${W.error.slice(0,118)}…`:W.error}):null,$?s.jsxs("div",{className:"mc_card_review_body",onClick:A=>A.stopPropagation(),onKeyDown:A=>A.stopPropagation(),children:[s.jsx("div",{className:"mc_card_reason",children:W.reason||"Needs a decision"}),W.prompt?s.jsx("div",{className:"mc_card_prompt",title:W.prompt,children:W.prompt.length>240?`${W.prompt.slice(0,238)}…`:W.prompt}):null,W.tool_names.length?s.jsxs("div",{className:"mc_card_tools",title:"Tool calls awaiting your approval",children:[W.tool_names.slice(0,4).map((A,ee)=>s.jsx("span",{className:"mc_tool_chip mono",children:A},`${A}_${ee}`)),W.tool_names.length>4?s.jsxs("span",{className:"mc_tool_chip",children:["+",W.tool_names.length-4," more"]}):null]}):null,W.since_ms!==null?s.jsxs("div",{className:"mc_card_waiting",children:["waiting ",nf(W.since_ms,t)]}):null,z?s.jsx("div",{className:"mc_card_line",title:"The wait has not registered a wait_key yet — open the run to inspect.",children:"wait key not published yet — open the run"}):null,z?s.jsx("div",{className:"mc_card_actions",children:s.jsx("button",{className:"btn",onClick:()=>e.on_open_run(W.run_id),children:"Open the run →"})}):W.wait_kind==="tool_approval"?s.jsxs("div",{className:"mc_card_actions",children:[s.jsx("button",{className:"btn success",disabled:O,onClick:()=>void I(W,{approved:!0}),children:O?"Resuming…":"Approve"}),s.jsx("button",{className:"btn danger",disabled:O,onClick:()=>void I(W,{approved:!1}),children:"Reject"})]}):s.jsx("div",{className:"mc_card_actions",children:s.jsx("button",{className:"btn primary",onClick:()=>e.on_open_run(W.run_id),children:"Review & answer →"})})]}):null]},W.run_id)}return s.jsxs("div",{className:"page page_scroll mc_page",children:[s.jsxs("div",{className:"mc_health",children:[s.jsx("span",{className:`mc_led ${e.gateway_connected?"ok":"bad"}`,title:e.gateway_connected?"Gateway connected":"Gateway unreachable"}),e.gateway_connected?null:s.jsx("span",{className:"mc_health_text",children:"gateway unreachable"}),e.runs_refreshed_at===null?s.jsx("span",{className:"mc_health_text muted mc_loading",children:"loading runs…"}):s.jsxs("div",{className:"mc_stats",children:[s.jsxs("div",{className:`mc_stat ${x?"is_hot":""}`,title:"runs blocked on a human decision (Review column)",children:[s.jsx("span",{className:"mc_stat_value",children:x}),s.jsx("span",{className:"mc_stat_label",children:"need you"})]}),s.jsxs("div",{className:`mc_stat ${j?"is_bad":""}`,title:"failed runs in the Done column",children:[s.jsx("span",{className:"mc_stat_value",children:j}),s.jsx("span",{className:"mc_stat_label",children:"failed"})]}),s.jsxs("div",{className:"mc_stat",title:"runs executing or parked listening",children:[s.jsx("span",{className:"mc_stat_value",children:n.working.length}),s.jsx("span",{className:"mc_stat_label",children:"working"})]})]}),s.jsx("span",{className:"mc_spacer"}),s.jsxs("div",{className:"mc_health_side",children:[w?s.jsxs("span",{className:"mc_health_text muted",title:"age of the last runs poll — the board is only as live as this",children:["data ",w," old"]}):null,s.jsx("button",{className:"btn",onClick:e.on_refresh,disabled:e.refreshing,children:e.refreshing?"Refreshing…":"Refresh"})]})]}),l?s.jsx("div",{className:"mc_error",children:l}):null,e.entities.length||e.entities_error?s.jsxs("div",{className:"mc_entities",children:[s.jsxs("div",{className:"mc_entities_head",children:[s.jsxs("span",{children:["Entities",e.entities_total>e.entities.length?` (${e.entities.length} of ${e.entities_total} — open the entity app for all)`:""]}),s.jsx("a",{className:"mc_entity_link",href:e.entity_app_href,target:"_blank",rel:"noreferrer",children:"open the entity app →"})]}),e.entities_error?s.jsx("div",{className:"muted",children:e.entities_error}):null,s.jsx("div",{className:"mc_entities_row",children:e.entities.map(W=>s.jsxs("div",{className:"mc_entity_cell",children:[s.jsxs("a",{className:"mc_entity",href:`${e.entity_app_href}${e.entity_app_href.includes("?")?"&":"?"}entity=${encodeURIComponent(W.name)}&live=1`,target:"_blank",rel:"noreferrer",title:[W.error,W.age_days!==null?`${W.age_days.toFixed(0)} days old`:"",W.last_moment].filter(Boolean).join(" — ")||W.name,children:[s.jsx("span",{className:"mc_entity_name",children:W.name}),(()=>{var F;const O=String(W.live_phase||W.state||"").trim(),$=ML(O,e.phase_graph),z=IL(e.phase_graph).has($)?$:"other",A=((F=e.phase_graph)==null?void 0:F.initial)??"sleep",ee=/awake|idle/i.test(O)&&$===A,P=O&&O.toLowerCase()!==$?` — wire word: ${O}${ee?" (settling)":""}`:"";return s.jsx("span",{className:`mc_entity_phase mc_phase_${z}`,title:(W.live_phase?"phase (cognition wire)":"phase from card state — cognition wire unavailable")+P,children:$})})(),W.last_moment?s.jsx("span",{className:"mc_entity_moment",title:W.last_moment,children:W.last_moment.replace(/_/g," ")}):null,(()=>{if(W.working===!0)return s.jsx("span",{className:"mc_entity_live",title:"busy now (loop mid-day or live visit — store-read, never fabricated)",children:"● busy"});const O=kL(W.last_moment_at,t);return W.working===!1?s.jsxs("span",{className:"mc_entity_live muted",title:"idle (cognition wire)",children:["idle",O!==null?` · ${nf(t-O,t)} ago`:""]}):O===null?null:O<=jL?s.jsx("span",{className:"mc_entity_live",title:`last moment ${nf(t-O,t)} ago`,children:"● active"}):s.jsxs("span",{className:"mc_entity_live muted",title:"time since the last recorded moment",children:[nf(t-O,t)," ago"]})})(),W.tokens_total!==null?s.jsxs("span",{className:"muted mc_entity_spend",title:`lifetime billed tokens (home run ledger)${W.live_visit_tokens!==null?`; open visit: ${ip(W.live_visit_tokens)} tk`:""}${W.spend_warning?`; ${W.spend_warning}`:""}`,children:[ip(W.tokens_total)," tk",W.live_visit_tokens!==null?` (+${ip(W.live_visit_tokens)})`:"",W.spend_warning?"*":""]}):null]}),W.open_questions_total||W.open_problems_total||W.lessons_total||W.dreams_brief?s.jsx("button",{type:"button",className:"mc_entity_hints_btn","aria-expanded":b===W.name,title:"open questions / problems + distilled lessons + night signals from the entity card — click to expand",onClick:()=>N(b===W.name?"":W.name),children:[W.open_questions_total?`${W.open_questions_total} question${W.open_questions_total>1?"s":""}`:"",W.open_problems_total?`${W.open_problems_total} problem${W.open_problems_total>1?"s":""}`:"",W.lessons_total?`${W.lessons_total} lesson${W.lessons_total>1?"s":""}`:"",W.dreams_brief?`night: ${W.dreams_brief.count} signal${W.dreams_brief.count>1?"s":""}`:""].filter(Boolean).join(" · ")}):null]},W.name))}),(()=>{if(!b)return null;const W=e.entities.find(z=>z.name===b);if(!W||!W.open_questions.length&&!W.open_problems.length&&!W.lessons.length&&!W.dreams_brief)return null;const O=e.on_read_diary?async z=>{const A=await e.on_read_diary(W.name,z);E({entity:W.name,entry:(A==null?void 0:A.entry)??A,seq:typeof(A==null?void 0:A.read_recorded_at_seq)=="number"?A.read_recorded_at_seq:null})}:void 0,$=W.open_questions_total-W.open_questions.length+(W.open_problems_total-W.open_problems.length)+(W.lessons_total-W.lessons.length);return s.jsxs("div",{className:"mc_entity_hints_panel",children:[W.open_questions.map((z,A)=>s.jsx(b_,{kind:"question",label:z.title||ap(z.statement),entryId:z.entry_id,onOpen:O,title:z.statement||z.title},`q_${z.record_id||A}`)),W.open_problems.map((z,A)=>s.jsx(b_,{kind:"problem",label:z.title||ap(z.statement),entryId:z.entry_id,onOpen:O,title:z.statement||z.title},`p_${z.record_id||A}`)),W.lessons.map((z,A)=>s.jsx(b_,{kind:"lesson",label:z.title||ap(z.statement),entryId:z.entry_id,onOpen:O,title:z.statement||z.title},`l_${z.record_id||A}`)),W.dreams_brief?s.jsxs("span",{className:"mc_entity_dreams muted",title:"night signals carried by STANDING dreams (the sleep pass's maintenance stream; count = signals, not dreams); felt tones color the content, they never rank it — the entity app renders the full stream",children:["night signals: ",W.dreams_brief.count,W.dreams_brief.dreams?` across ${W.dreams_brief.dreams} dream${W.dreams_brief.dreams>1?"s":""}`:"",W.dreams_brief.kinds.length?` — ${W.dreams_brief.kinds.slice(0,6).join(", ")}${W.dreams_brief.kinds.length>6?` +${W.dreams_brief.kinds.length-6} more`:""}`:"",W.dreams_brief.felt_tones.length?` · felt: ${W.dreams_brief.felt_tones.slice(0,6).join(", ")}`:""]}):null,$>0?s.jsxs("span",{className:"muted mc_entity_hints_more",children:["+",$," more — open the entity app"]}):null]})})()]}):null,C?s.jsx(Kl,{open:!0,title:`${C.entity} — diary entry`,onClose:()=>E(null),children:s.jsxs("div",{className:"mc_diary_entry",children:[s.jsx("div",{className:"mc_diary_meta muted",children:[(U=C.entry)!=null&&U.kind?`kind: ${C.entry.kind}`:"",(J=C.entry)!=null&&J.visibility?`visibility: ${C.entry.visibility}`:"",(Y=C.entry)!=null&&Y.written_at?`written: ${C.entry.written_at}`:"",(re=C.entry)!=null&&re.entry_id?`id: ${C.entry.entry_id}`:""].filter(Boolean).join(" · ")}),s.jsxs("div",{className:"mc_diary_recorded muted",children:["this read was recorded in ",C.entity,"’s stream",C.seq!==null?` (seq ${C.seq})`:""]}),(ce=C.entry)!=null&&ce.gist?s.jsx("div",{className:"mc_diary_gist",children:String(C.entry.gist)}):null,s.jsx("pre",{className:"mc_diary_text",children:String(((fe=C.entry)==null?void 0:fe.text)||"(entry carries no text)")})]})}):null,s.jsx("div",{className:"mc_board",children:Object.keys(vv).map(W=>{const O=W==="done"?g.visible:n[W],$=W==="done"&&!c?O.slice(0,8):O;return s.jsxs(OL,{col:W,title:vv[W],head:s.jsxs(s.Fragment,{children:[W==="done"?s.jsx("select",{className:"mc_window_select",value:m,title:"Show terminal runs from this time window",onClick:z=>z.stopPropagation(),onChange:z=>{const A=z.target.value;_(A),f(!1);try{localStorage.setItem("abstractobserver_done_window_v1",A)}catch{}},children:Object.keys(ig).map(z=>s.jsx("option",{value:z,children:op[z]},z))}):null,s.jsx("span",{className:"mc_column_count",title:W==="done"&&g.hidden_count?`${g.hidden_count} older run(s) outside this window`:void 0,children:O.length})]}),children:[s.jsx("div",{className:"mc_column_hint muted",children:yL[W]}),s.jsxs("div",{className:"mc_column_cards",children:[$.map(z=>K(z)),O.length?null:s.jsx("div",{className:"mc_empty muted",children:e.runs_refreshed_at===null?"loading…":W==="done"&&g.hidden_count?`none in the ${op[m]} — ${g.hidden_count} older`:gL[W]}),W==="done"&&O.length>8&&!c?s.jsxs("button",{className:"btn mc_more",onClick:()=>f(!0),children:["show all ",O.length]}):null,W==="done"&&g.hidden_count&&O.length?s.jsxs("div",{className:"mc_window_note muted",title:"Widen the window above to see older terminal runs",children:["+",g.hidden_count," older outside ",op[m]]}):null]})]},W)})})]})}function DL(){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 FL(){if(typeof window>"u")return!1;const e=window;return!!(e!=null&&e.AudioContext||e!=null&&e.webkitAudioContext)}function zL(){const e=window.MediaRecorder,t=r=>{var o;try{return!!((o=e==null?void 0:e.isTypeSupported)!=null&&o.call(e,r))}catch{return!1}},n=["audio/webm;codecs=opus","audio/webm","audio/mp4","audio/ogg;codecs=opus","audio/ogg"];for(const r of n)if(t(r))return r;return""}async function BL(e,t){var o;const n=t.slice(0),r=(o=e.decodeAudioData)==null?void 0:o.bind(e);if(typeof r!="function")throw new Error("decodeAudioData not available");try{const l=r(n);if(l&&typeof l.then=="function")return await l}catch{}return await new Promise((l,u)=>{try{r(n,l,u)}catch(c){u(c)}})}function UL(e){const t=z=>{var A;return(A=e.on_error)==null?void 0:A.call(e,z)},n=p.useMemo(()=>FL(),[]),r=p.useMemo(()=>DL(),[]),[o,l]=p.useState({key:"",status:"idle"}),u=p.useRef(""),c=p.useRef(""),f=p.useRef(null),m=p.useRef(null),_=p.useRef(null),g=p.useRef(null),w=p.useRef(0),x=p.useRef(0),j=()=>{try{const z=globalThis,A=(z==null?void 0:z.AudioContext)||(z==null?void 0:z.webkitAudioContext);if(!A)return null;if(!f.current){const F=new A,G=F.createGain();G.gain.value=1,G.connect(F.destination),f.current=F,m.current=G}const ee=f.current,P=m.current;if(!ee||!P)return null;try{ee.state==="suspended"&&ee.resume()}catch{}return{ctx:ee,gain:P}}catch{return null}},b=()=>{const z=_.current;if(_.current=null,!!z){try{z.onended=null}catch{}try{z.stop()}catch{}try{z.disconnect()}catch{}}},N=()=>{b(),c.current="",u.current="",g.current=null,w.current=0,x.current=0,l({key:"",status:"idle"})};p.useEffect(()=>()=>{var z,A;N();try{(z=m.current)==null||z.disconnect()}catch{}try{(A=f.current)==null||A.close()}catch{}f.current=null,m.current=null,g.current=null},[]);const C=async(z,A,ee)=>{const P=j();if(!P)throw new Error("TTS playback is not supported in this browser");const{ctx:F,gain:G}=P;try{F.state==="suspended"&&await F.resume()}catch{}b();const R=F.createBufferSource();R.buffer=A,R.connect(G);const Z=Number.isFinite(Number(A.duration))?Number(A.duration):0,X=Math.max(0,Math.min(Number(ee||0),Z>0?Math.max(0,Z-.01):0));x.current=F.currentTime-X,w.current=X,_.current=R,u.current=z,R.onended=()=>{_.current===R&&(_.current=null,w.current=0,x.current=0,u.current="",l({key:"",status:"idle"}))},R.start(0,X),l({key:z,status:"playing"})},E=async(z,A)=>{const ee=String(z||"").trim(),P=String(A||"").trim();if(!ee||!P)return;const F=e.gateway,G=String(e.run_id||"").trim();if(!F){t==null||t("Connect to the gateway first.");return}if(!G){t==null||t("Voice store not available (missing run_id).");return}const R=j();if(!R){t==null||t("TTS playback is not supported in this browser.");return}const Z=o.key===ee;if(Z&&o.status==="playing"){const X=Math.max(0,R.ctx.currentTime-Number(x.current||0));w.current=X,b(),l({key:ee,status:"paused"});return}if(Z&&o.status==="paused"){const X=g.current;if(X){t==null||t("");try{await C(ee,X,w.current)}catch(ie){t==null||t(String((ie==null?void 0:ie.message)||ie||"TTS play failed")),l({key:"",status:"idle"})}return}}if(!(Z&&o.status==="loading")){b(),g.current=null,w.current=0,x.current=0,u.current=ee,c.current=ee,l({key:ee,status:"loading"}),t==null||t("");try{const X=await F.voice_tts(G,{text:P,request_id:xs()}),ie=X==null?void 0:X.audio_artifact,ne=ie&&typeof ie=="object"&&!Array.isArray(ie)?String(ie.$artifact||"").trim():"";if(!ne)throw new Error("TTS failed: missing audio artifact");const he=await(await F.download_run_artifact_content(G,ne)).arrayBuffer();if(c.current!==ee)return;const pe=await BL(R.ctx,he);if(c.current!==ee)return;g.current=pe,w.current=0,await C(ee,pe,0)}catch(X){c.current===ee&&(c.current="",u.current="",l({key:"",status:"idle"})),t==null||t(String((X==null?void 0:X.message)||X||"TTS failed"))}}},[T,I]=p.useState(!1),[K,U]=p.useState(!1),J=p.useRef(null),Y=p.useRef(null),re=p.useRef([]),ce=p.useRef("");function fe(){var z,A;try{(A=(z=J.current)==null?void 0:z.getTracks)==null||A.call(z).forEach(ee=>{try{ee.stop()}catch{}})}catch{}J.current=null}p.useEffect(()=>()=>{var z,A;try{(A=(z=Y.current)==null?void 0:z.stop)==null||A.call(z)}catch{}Y.current=null,fe()},[]);async function W(z,A){var G;if(t==null||t(""),!z||!z.size||K)return;const ee=e.gateway,P=String(e.session_id||"").trim(),F=String(e.run_id||"").trim();if(!ee){t==null||t("Connect to the gateway first.");return}if(!P){t==null||t("Voice input unavailable (missing session_id).");return}if(!F){t==null||t("Voice input unavailable (missing run_id).");return}U(!0);try{const R=String(A||z.type||"").toLowerCase(),Z=R.includes("mp4")?"m4a":R.includes("ogg")?"ogg":R.includes("wav")?"wav":"webm",X=new File([z],`recording.${Z}`,{type:R||"audio/webm"}),ie=await ee.attachments_upload(P,X,{filename:X.name,content_type:X.type}),ne=await ee.audio_transcribe(F,{audio_artifact:ie,request_id:xs()}),ye=String((ne==null?void 0:ne.text)||"").trim();ye&&((G=e.on_transcript)==null||G.call(e,ye))}catch(R){t==null||t(String((R==null?void 0:R.message)||R||"Transcription failed"))}finally{U(!1)}}async function O(){if(t==null||t(""),!r){t==null||t(Pp()?"Voice recording is not supported in this browser (MediaRecorder unavailable).":Op);return}if(!K&&!(T||Y.current)){re.current=[];try{const z=await navigator.mediaDevices.getUserMedia({audio:!0});J.current=z;const A=zL();ce.current=A;const ee=A?new MediaRecorder(z,{mimeType:A}):new MediaRecorder(z);Y.current=ee,ee.ondataavailable=P=>{try{P!=null&&P.data&&re.current.push(P.data)}catch{}},ee.onerror=()=>{t==null||t("Recording failed.")},ee.onstop=()=>{I(!1),fe(),Y.current=null;try{const P=new Blob(re.current,{type:ce.current||""});W(P,ce.current)}catch(P){t==null||t(String((P==null?void 0:P.message)||P||"Failed to build recording"))}},ee.start(),I(!0)}catch(z){fe(),Y.current=null,I(!1);const A=String((z==null?void 0:z.message)||z||"Failed to access microphone");t==null||t(A.toLowerCase().includes("permission")?`Microphone permission denied: ${A}`:A)}}}function $(){const z=Y.current;if(!(!T||!z)){Y.current=null,I(!1);try{z.stop()}catch(A){t==null||t(String((A==null?void 0:A.message)||A||"Failed to stop recording"))}}}return p.useEffect(()=>{if(!T)return;const z=()=>$();return window.addEventListener("pointerup",z),window.addEventListener("pointercancel",z),()=>{window.removeEventListener("pointerup",z),window.removeEventListener("pointercancel",z)}},[T]),{tts_supported:n,tts_playback:o,toggle_tts:E,stop_tts:N,voice_ptt_supported:r,voice_ptt_recording:T,voice_ptt_busy:K,start_voice_ptt_recording:O,stop_voice_ptt_recording:$}}const Yh=500,Sm="http://127.0.0.1:8080";function kv(e){const t=String(e||"").trim(),n=t.indexOf(":");return n<=0||n>=t.length-1?null:{bundle_id:t.slice(0,n),flow_id:t.slice(n+1)}}function sf(e){const t=String(e||"").trim();return t.startsWith("abstractcode.")?`abstract.${t.slice(13)}`:t}function lp(e){const t=e&&typeof e=="object"?e:{},n=typeof(t==null?void 0:t.count)=="number"&&Number.isFinite(t.count)?Number(t.count):null,r=typeof(t==null?void 0:t.node_id)=="string"&&t.node_id.trim()?` before ${t.node_id.trim()}`:"";return`${n===null?"steering":`${n} steer message${n===1?"":"s"}`} folded into the run${r} — the loop sees it at this boundary`}function cp(e){const t=String(e||"").trim();return t.startsWith("abstract.")||t.startsWith("abstractcode.")}function WL(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 qL(e){if(!e||typeof e!="object")return[];const t=Array.isArray(e.nodes)?e.nodes:[];if(!t.length)return[];let n=null;for(const c of t){if(!c||typeof c!="object")continue;const f=c.data&&typeof c.data=="object"?c.data:{};if(String(f.nodeType||c.type||"").trim()==="on_flow_start"){n=c;break}}if(!n)return[];const r=n.data&&typeof n.data=="object"?n.data:{},o=Array.isArray(r.outputs)?r.outputs:[],l=r.pinDefaults&&typeof r.pinDefaults=="object"?r.pinDefaults:{},u=[];for(const c of o){if(!c||typeof c!="object")continue;const f=String(c.id||"").trim();if(!f)continue;const m=String(c.type||"").trim();if(m==="execution"||f==="exec-out"||f==="exec")continue;const _=String(c.label||f).trim()||f,g={id:f,label:_,type:m||"unknown"};l&&Object.prototype.hasOwnProperty.call(l,f)&&(g.default=l[f]),u.push(g)}return u}function up(e,t){const n=String((e==null?void 0:e.message)||e||"Discovery failed");if(/\b401\b/.test(n)){const r=String(t.gateway_user||"").trim();return r?`Gateway authentication failed for user '${r}'. Sign in again through the connection dialog. (${n})`:`Gateway authentication failed. Sign in through the connection dialog (or check the dev bearer token under Settings → Advanced). (${n})`}return n}const HL=/^[a-zA-Z0-9_-]+$/;function jv(e){return HL.test(String(e||"").trim())}async function VL(e){const t=String(e||"");return TE(t)}async function GL(e){const t=String(e||"").trim();if(!t)throw new Error("session_id is required");if(jv(t)){const r=`session_memory_${t}`;if(jv(r))return r}return`session_memory_sha_${(await VL(t)).slice(0,32)}`}function KL(){try{const e=localStorage.getItem("abstractobserver_settings");if(!e)throw new Error("missing");const t=JSON.parse(e);return{gateway_url:String((t==null?void 0:t.gateway_url)||Sm),auth_token:"",gateway_user:String((t==null?void 0:t.gateway_user)||""),gateway_auth_mode:(t==null?void 0:t.gateway_auth_mode)==="direct"?"direct":"session",worker_url:String((t==null?void 0:t.worker_url)||""),worker_token:String((t==null?void 0:t.worker_token)||""),theme:String((t==null?void 0:t.theme)||"dark"),font_scale:String((t==null?void 0:t.font_scale)||(t==null?void 0:t.fontScale)||"md").trim()||"md",header_density:String((t==null?void 0:t.header_density)||(t==null?void 0:t.headerDensity)||"standard").trim()||"standard",auto_connect_gateway:(t==null?void 0:t.auto_connect_gateway)!==!1,maintenance_ai_provider:String((t==null?void 0:t.maintenance_ai_provider)||""),assistant_skill_names:Array.isArray(t==null?void 0:t.assistant_skill_names)?t.assistant_skill_names.map(n=>String(n||"").trim()).filter(Boolean):[],maintenance_ai_model:String((t==null?void 0:t.maintenance_ai_model)||"")}}catch{return{gateway_url:Sm,auth_token:"",gateway_user:"",gateway_auth_mode:"session",worker_url:"",worker_token:"",theme:"dark",font_scale:"md",header_density:"standard",auto_connect_gateway:!0,maintenance_ai_provider:"",assistant_skill_names:[],maintenance_ai_model:""}}}function YL(e){localStorage.setItem("abstractobserver_settings",JSON.stringify({...e,auth_token:""}))}function JL(e){if(!e||typeof e!="object"||Array.isArray(e))return[];const t=[],n=(o,l)=>{const u=String(l??"").trim();u&&(t.some(c=>c.label===o&&c.value===u)||t.push({label:o,value:u}))},r=String(e.display??"").trim().replace(/^\[/,"").replace(/\]$/,"");return n("time",r||e.local_datetime),n("tz",e.timezone),n("country",e.country),n("user",e.user),t}function Sv(e){const t=JL(e.metadata);return t.length?s.jsx("div",{className:"runtime_metadata_chips","aria-label":"Runtime metadata",children:t.map(n=>s.jsxs("span",{className:"chip mono muted",children:[n.label,": ",n.value]},`${n.label}:${n.value}`))}):null}function XL(){return typeof window>"u"?"":TN(window.location)}function ZL(){try{const e="abstractobserver_session_id_v1",t=window.sessionStorage.getItem(e);if(t&&t.trim())return t.trim();const n=`obs_${xs()}`;return window.sessionStorage.setItem(e,n),n}catch{return""}}function QL(){var es,Gn,us,ar,Qo,Yn,Ga,wo,Bl,Qc,Ka,Hs,eu,ea,xi;const[e,t]=p.useState("board"),[n,r]=p.useState(()=>KL()),o=typeof window<"u"&&((es=window.__ABSTRACT_UI_CONFIG__)==null?void 0:es.monitor_gpu)===!0,l=typeof window<"u"&&(((Gn=window.__ABSTRACT_UI_CONFIG__)==null?void 0:Gn.entity_app_url)||"").trim().replace(/\/+$/,"")||"http://127.0.0.1:3007",u=p.useRef(null),[c,f]=p.useState(""),[m,_]=p.useState(""),[g,w]=p.useState(()=>XL()),[x,j]=p.useState(""),[b,N]=p.useState(""),[C,E]=p.useState(""),[T,I]=p.useState("{}"),[K]=p.useState(()=>ZL()),[U,J]=p.useState(null),[Y,re]=p.useState(!1),[ce,fe]=p.useState(""),[W,O]=p.useState(!1),[$,z]=p.useState(""),[A,ee]=p.useState(!1),P=Ok({appName:"AbstractObserver",variant:"dismissable",defaultGatewayUrl:typeof window<"u"&&((us=window.__ABSTRACT_UI_CONFIG__)==null?void 0:us.gateway_url)||Sm,onStatusChange:y=>dd(y)}),[F,G]=p.useState(null),[R,Z]=p.useState(null),[X,ie]=p.useState(!1),[ne,ye]=p.useState(null),[he,pe]=p.useState("once"),[Ne,Ue]=p.useState(""),[We,pt]=p.useState($p),[Fe,tt]=p.useState([]),[lt,Ke]=p.useState(null),[je,Re]=p.useState(!1),[ht,xe]=p.useState([]),Ie=p.useRef(new C2(xs)),[qe,zt]=p.useState({available:!1,reason:"Sign in to a gateway to use automations."}),[en,bn]=oj("abstractobserver",{legacyKey:"abstractobserver_settings"}),[Wt,It]=p.useState(!1),[Sn,ns]=p.useState(!1),[Ot,pn]=p.useState([]),[Bn,An]=p.useState([]),[gn,In]=p.useState([]),[wn,ks]=p.useState(!1),[Kn,js]=p.useState(null),[Nr,On]=p.useState([]),[le,ke]=p.useState(0),[Ye,Ge]=p.useState(""),rt=p.useRef(!1),ct=p.useRef(0),Et=p.useRef(0),[kt,Kt]=p.useState(!1),[xt,Yt]=p.useState([]),[qt,Pt]=p.useState([]),[At,$t]=p.useState({}),[De,on]=p.useState(!1),[ut,tn]=p.useState(!1),[dt,Un]=p.useState(!1),[an,Ys]=p.useState([]),[ss,Wr]=p.useState([]),dr=p.useRef(0),ii=p.useRef(null);ii.current||(ii.current=new _w(y=>window.setTimeout(y,40),y=>Ys(S=>S.concat(y))));const oi=p.useRef(null);oi.current||(oi.current=new _w(y=>window.setTimeout(y,40),y=>Wr(S=>S.concat(y))));const Ps=p.useRef({scanned:0,found:null}),[ue,fr]=p.useState(null),[Gi,hr]=p.useState(""),[Cr,qr]=p.useState(!1),it=p.useRef(null),[cn,Ds]=p.useState({}),[Hr,rs]=p.useState({}),[Eo,Ao]=p.useState(!1),[$o,Pn]=p.useState(""),[mr,Hn]=p.useState(!0),[Ki,ai]=p.useState(""),[$n,Fs]=p.useState(!1),[hs,Js]=p.useState(!1),[ms,da]=p.useState(6),[Yi,ln]=p.useState("standard"),[fa,dc]=p.useState(""),[To,_s]=p.useState(""),[Er,Ar]=p.useState(!1),[Ji,_r]=p.useState(!1),[Ss,pr]=p.useState("pause"),[$r,Xs]=p.useState(""),[Ni,is]=p.useState(""),[Tr,ha]=p.useState(""),gr=p.useRef(null),Xi=p.useRef(null),[fc,Ci]=p.useState(!1),Zs=p.useRef(null),[$u,Qs]=p.useState(""),[Zi,er]=p.useState(""),[Mo,li]=p.useState(""),[ll,ci]=p.useState(""),[B,oe]=p.useState(""),[be,Se]=p.useState(!1),[Ee,He]=p.useState("idle"),[Qe,ot]=p.useState([]),[mt,Dt]=p.useState(null),Xt=p.useRef(null),[Xn,Bt]=p.useState(!1),[un,vn]=p.useState(""),[kn,ps]=p.useState(""),[Ns,yr]=p.useState(""),[Ro,Lo]=p.useState([]),[cl,hc]=p.useState(!1),[mc,_c]=p.useState(""),[Tu,pc]=p.useState(""),[gc,yc]=p.useState(!1),[Mu,Io]=p.useState(""),If=p.useMemo(()=>{if(!Qe.length)return"";try{return JSON.stringify(Qe.map(y=>({role:y.role,content:y.content,ts:y.ts})))}catch{return"1"}},[Qe]),Ru=p.useMemo(()=>Qe.length?Ns?If!==Ns:!0:!1,[If,Qe.length,Ns]),Lu=p.useMemo(()=>Ro.map(y=>{const S=String(y.title||"").trim()||`Chat ${String(y.thread_id||"").slice(0,8)}`,M=String(y.created_at||"").trim(),D=M?M.replace("T"," ").slice(0,19):"",q=String(y.run_id||"").trim()?String(y.run_id).slice(0,8):"",H=[S,D&&`(${D})`,q&&`run ${q}`].filter(Boolean).join(" • ");return{value:String(y.thread_id||""),label:H}}),[Ro]);p.useEffect(()=>{o&&MC()},[o]),p.useEffect(()=>{if(!o)return;const y=u.current;y&&(y.token=n.gateway_auth_mode==="direct"&&n.auth_token||"")},[o,n.auth_token,n.gateway_auth_mode]);const[Iu,Ou]=p.useState([]),[Pu,nn]=p.useState(""),[wc,zm]=p.useState(""),[Du,Bm]=p.useState("all"),[Fu,Um]=p.useState("status"),[tr,Qi]=p.useState("ledger"),vc=my(w_.md),ul=my(`${w_.sm}, ${w_.short}`),ma=NN({is_drawer:vc,page:e}),xc=ma.open,_a=ma.set_open,[zu,Of]=hf("observe_runs"),Pf=ma.toggle_ref,pa=ma.sidebar_ref,Df=p.useRef(null),[Wm,Ff]=p.useState(()=>Uy(typeof window<"u"?window.location.hash:"")),[zf,Bu]=p.useState(""),[ga,Oo]=p.useState(""),[ya,eo]=p.useState(""),[wa,va]=p.useState(null),[xa,dl]=p.useState({}),[Uu,ba]=p.useState(!1),[Wu,fl]=p.useState(""),[hl,qm]=p.useState(!1),[qu,Hm]=p.useState(!1),[Vr,to]=p.useState(()=>Date.now()),[ui,Po]=p.useState(""),[Bf,ml]=p.useState({}),[Hu,Vu]=p.useState({}),_l=p.useRef([]),gs=p.useRef(null),di=p.useRef(""),no=p.useRef({}),so=p.useRef({}),bc=p.useRef({}),ro=p.useRef(new Set),[wr,ka]=p.useState([]),ja=p.useRef(""),Ei=p.useRef({}),Ai=p.useRef(null),zs=p.useRef(null),io=p.useRef(0),Do=p.useRef({}),pl=p.useRef(!1),oo=p.useRef(new Set),[fi,Sa]=p.useState(""),[Mr,ao]=p.useState(""),hi=p.useRef(""),Na=()=>({artifact_id:"",kind:"binary",render_kind:"",text:"",url:"",loading:!1,error:""}),[gl,Gu]=p.useState("activity"),[kc,Nn]=p.useState([]),[jc,yl]=p.useState(0),[wl,Ku]=p.useState(0),[Yu,Ca]=p.useState({}),[Sc,Fo]=p.useState({}),[Uf,Wf]=p.useState(!1),[Vm,Ju]=p.useState(""),[lo,Nc]=p.useState(""),[zo,vl]=p.useState("all"),[Ea,Cc]=p.useState(""),[Aa,qf]=p.useState([]),[Ec,Gm]=p.useState("all"),[co,uo]=p.useState("type"),[xl,$a]=p.useState("newest"),[ys,Ta]=p.useState(""),[vr,Bo]=p.useState(""),[Hf,Xu]=p.useState(""),[Gr,Uo]=p.useState(0),[Kr,Ma]=p.useState(()=>Na()),[Zu,fo]=p.useState(!1),[$i,En]=p.useState(""),[Cn,xr]=p.useState(""),[fn,ws]=p.useState(""),[Ti,Ra]=p.useState("text"),[nr,La]=p.useState(null),[Vf,bl]=p.useState(!1),[kl,jl]=p.useState(""),[mi,Sl]=p.useState(""),[Qu,ed]=p.useState(""),[Gf,Mi]=p.useState(!1),[Ia,Wo]=p.useState(""),[qo,Ac]=p.useState("run_ledger"),[Rr,Lr]=p.useState(""),[Ho,Yr]=p.useState([]),[Ri,Li]=p.useState(""),[Kf,$c]=p.useState(!1),[td,Bs]=p.useState(""),Te=p.useMemo(()=>new F_({base_url:n.gateway_auth_mode==="session"?"":n.gateway_url,auth_token:n.gateway_auth_mode==="session"?"":n.auth_token}),[n.gateway_auth_mode,n.gateway_url,n.auth_token]),Tt=p.useMemo(()=>new B2(Te.automations_client(),D2(Te,xs,Ct)),[Te]),br=p.useSyncExternalStore(y=>Tt.subscribe(y),()=>Tt.state),nd=x2(n.gateway_url),Tc=nd?()=>{window.open(nd,"_blank","noopener,noreferrer")}:void 0;p.useEffect(()=>{e==="launch"&&he==="automate"&&A&&Tt.load_email_status()},[e,he,A,Tt]),p.useEffect(()=>{const y=()=>{const S=k2(window.location.hash);if(S){if(S.page==="run"){w(S.run_id),Ff(Uy(window.location.hash));return}S.page==="launch"&&pe(S.mode),t(S.page)}};return y(),window.addEventListener("hashchange",y),()=>window.removeEventListener("hashchange",y)},[]);const sd=p.useMemo(()=>{const y={};for(const S of br.items)y[S.automation_id]=S.title;return y},[br.items]),rd=p.useMemo(()=>xC(),[]),[Yf,Nl]=p.useState([]),id=p.useRef(0);function Oa(){const y=++id.current;Nl([["Gateway","checking…"]]),bC(Te).then(S=>{y===id.current&&Nl(S)})}const Pa=p.useMemo(()=>n.worker_url.trim()?new RE({url:n.worker_url.trim(),auth_token:n.worker_token}):null,[n.worker_url,n.worker_token]),Us=an.length?an[an.length-1].record:null,Ft=p.useMemo(()=>ra(Us),[Us]),Zn=p.useMemo(()=>{const y=C.trim();if(!U||!y||String(U.bundle_id||"").trim()&&String(U.bundle_id||"").trim()!==y)return null;const S=Array.isArray(U.entrypoints)?U.entrypoints:[];if(!S.length)return null;const M=b.trim();if(M)return S.find(q=>String(q.flow_id||"").trim()===M)||null;if(S.length===1)return S[0];const D=String(U.default_entrypoint||"").trim();return D&&S.find(q=>String(q.flow_id||"").trim()===D)||null},[U,C,b]),Mc=p.useMemo(()=>{const y=Zn==null?void 0:Zn.inputs;return Array.isArray(y)?y:[]},[Zn]),od=p.useMemo(()=>qL(wa),[wa]),_i=p.useMemo(()=>Mc.length?Mc:od,[Mc,od]),Vo=p.useMemo(()=>{const y=typeof(ue==null?void 0:ue.workflow_id)=="string"?String(ue.workflow_id):"",S=kv(y);if(S&&U&&String(U.bundle_id||"").trim()===S.bundle_id){const q=(Array.isArray(U.entrypoints)?U.entrypoints:[]).find(H=>String((H==null?void 0:H.flow_id)||"").trim()===S.flow_id);if(q&&q.node_index&&typeof q.node_index=="object")return q.node_index}const M=Zn==null?void 0:Zn.node_index;return M&&typeof M=="object"?M:{}},[ue,U,Zn]);p.useEffect(()=>{YL(n)},[n]),p.useEffect(()=>()=>{Ai.current&&Ai.current.abort(),zs.current&&zs.current.abort(),gr.current&&window.clearTimeout(gr.current),Xi.current&&window.clearTimeout(Xi.current),gs.current&&window.clearTimeout(gs.current),Zs.current&&window.clearTimeout(Zs.current)},[]);const ft=p.useMemo(()=>{const y=T.trim();if(!y)return{};try{const S=JSON.parse(y);return typeof S!="object"||S===null||Array.isArray(S)?null:S}catch{return null}},[T]),Rc=typeof(ft==null?void 0:ft.prompt)=="string"?String(ft.prompt):"",ho=typeof(ft==null?void 0:ft.provider)=="string"?String(ft.provider):"",ad=typeof(ft==null?void 0:ft.model)=="string"?String(ft.model):"",ld=typeof(ft==null?void 0:ft.workspace_root)=="string"?String(ft.workspace_root):"",Lc=typeof(ft==null?void 0:ft.workspace_access_mode)=="string"?String(ft.workspace_access_mode):"",cd=p.useMemo(()=>{const y=ft==null?void 0:ft.workspace_allowed_paths;return Array.isArray(y)?y.map(S=>String(S||"").trim()).filter(Boolean).join(`
141
- `):typeof y=="string"?String(y):""},[ft]),Da=p.useMemo(()=>{const y=ft==null?void 0:ft.workspace_ignored_paths;return Array.isArray(y)?y.map(S=>String(S||"").trim()).filter(Boolean).join(`
142
- `):typeof y=="string"?String(y):""},[ft]),Ir=_i.length>0&&!!C.trim(),Ii=y=>{const S=String(y||"").trim().toLowerCase();return S==="object"||S==="memory"||S==="assertion"||S==="assertions"||S==="any"};p.useEffect(()=>{rs({})},[C,b]),p.useEffect(()=>{ft!==null&&Ds(y=>{const S={};for(const M of _i){if(!M||typeof M!="object")continue;const D=String(M.id||"").trim();if(!D)continue;const q=String(M.type||"").trim();if(!Ii(q))continue;if(String(Hr[D]||"").trim()){S[D]=typeof y[D]=="string"?y[D]:"";continue}const V=ft==null?void 0:ft[D];V===void 0?S[D]="":S[D]=n2(V)}return S})},[_i,ft,Hr]);const Jr=Ne?{kind:"default",interface:Ne}:C.trim()&&b.trim()?{kind:"bundle",bundle_id:C.trim(),flow_id:b.trim()}:null,ud=g2(Jr),os=Array.isArray(ft==null?void 0:ft.skills)?ft.skills.map(y=>String(y||"").trim()).filter(Boolean):[],as=p.useMemo(()=>{const y={};for(const S of Ot){const M=String(S.workflow_id||"").trim(),D=String(S.label||"").trim();M&&D&&(y[M]=D)}return y},[Ot]),Fa=rx({interfaceId:null,defaultInterface:tc,request:(y,S)=>Te.get_gateway_json(y,S.signal),enabled:A,reloadKey:Ot}),Jf=p.useMemo(()=>{const y=new Set;for(const S of Array.isArray(qt)?qt:[]){const M=String((S==null?void 0:S.name)||"").trim();M&&y.add(M)}return Array.from(y).sort()},[qt]),Oi=p.useMemo(()=>{const y=[];for(const S of Array.isArray(qt)?qt:[]){const M=String((S==null?void 0:S.name)||"").trim();if(!M)continue;const D=String((S==null?void 0:S.display_name)||"").trim();y.push({name:M,display_name:D||void 0})}return y},[qt]),pi=p.useMemo(()=>{const y=new Set;for(const S of xt||[]){if(!S||typeof S!="object")continue;const M=String(S.name||"").trim();M&&y.add(M)}return Array.from(y).sort()},[xt]),Cl=p.useMemo(()=>{const y=n.maintenance_ai_provider.trim();if(!y)return{models:[],error:""};const S=At[y];return S?{models:(Array.isArray(S.models)?S.models:[]).map(D=>String(D||"").trim()).filter(Boolean),error:String(S.error||"")}:{models:[],error:""}},[At,n.maintenance_ai_provider]),Ic=n.maintenance_ai_provider.trim(),Oc=!!(Ic&&A&&!Object.prototype.hasOwnProperty.call(At,Ic));p.useEffect(()=>{const y=ho.trim();if(!y||At[y]||Ei.current[y])return;Ei.current[y]=!0;let S=!1;return(async()=>{try{const D=await Te.discovery_provider_models(y);if(S)return;const q=Array.isArray(D==null?void 0:D.models)?D.models:[],H=typeof(D==null?void 0:D.error)=="string"?String(D.error):"";$t(V=>({...V,[y]:{models:q,error:H||void 0}}))}catch(D){if(S)return;$t(q=>({...q,[y]:{models:[],error:String((D==null?void 0:D.message)||D||"Failed to load models")}}))}finally{delete Ei.current[y]}})(),()=>{S=!0}},[ho,At,Te]),p.useEffect(()=>{const y=n.maintenance_ai_provider.trim();if(!y||!A||At[y]||Ei.current[y])return;Ei.current[y]=!0;let S=!1;return(async()=>{try{const D=await Te.discovery_provider_models(y);if(S)return;const q=Array.isArray(D==null?void 0:D.models)?D.models:[],H=typeof(D==null?void 0:D.error)=="string"?String(D.error):"";$t(V=>({...V,[y]:{models:q,error:H||void 0}}))}catch(D){if(S)return;$t(q=>({...q,[y]:{models:[],error:String((D==null?void 0:D.message)||D||"Failed to load models")}}))}finally{delete Ei.current[y]}})(),()=>{S=!0}},[n.maintenance_ai_provider,At,Te,A]);function Tn(y,S){const M=String(y||"").trim();if(!M)return;let D={};try{const q=JSON.parse(T||"{}");typeof q=="object"&&q!==null&&!Array.isArray(q)&&(D=q)}catch{D={}}if(S==null){delete D[M],I(JSON.stringify(D,null,2));return}if(typeof S=="string")S?D[M]=S:delete D[M];else if(Array.isArray(S)){const q=S.map(H=>H).filter(H=>H!=null);q.length?D[M]=q:delete D[M]}else D[M]=S;I(JSON.stringify(D,null,2))}async function za(y){const S=String(y||"").trim();if(!S)return fe("Missing bundle_id"),null;fe(""),re(!0);try{const M=await Te.get_bundle(S);return J(M),Jt({ts:Ct(),kind:"info",title:`Loaded bundle ${S}`}),M}catch(M){return J(null),fe(String((M==null?void 0:M.message)||M||"Failed to load bundle")),null}finally{re(!1)}}function Or(y){const S=[],M=Array.isArray(y==null?void 0:y.items)?y.items:[];for(const D of M){const q=String((D==null?void 0:D.bundle_id)||"").trim();if(!q)continue;const H=Array.isArray(D==null?void 0:D.entrypoints)?D.entrypoints:[];if(H.length)for(const V of H){const te=String((V==null?void 0:V.flow_id)||"").trim();if(!te||(V==null?void 0:V.deprecated)===!0)continue;const Le=`${q}:${te}`,ge=String((V==null?void 0:V.name)||"").trim(),me=ge?`${q} · ${ge}`:`${q} · ${te}`,Ae=String((V==null?void 0:V.description)||"").trim(),ze=(Array.isArray(V==null?void 0:V.interfaces)?V.interfaces:[]).some(Ve=>String(Ve||"").trim().length>0),Ze=Array.isArray(V==null?void 0:V.agent_default_interfaces)?V.agent_default_interfaces.map(Ve=>String(Ve||"").trim()).filter(Boolean):[];S.push({workflow_id:Le,bundle_id:q,bundle_ref:String((D==null?void 0:D.bundle_ref)||"").trim(),flow_id:te,label:me,description:Ae||void 0,has_interface:ze,agent_default_interfaces:Ze})}}return S.sort((D,q)=>D.label.localeCompare(q.label)),S}async function ls(y=Te,S){if(rt.current&&!(S!=null&&S.force))return;rt.current=!0;const M=gi.current;ks(!0);try{const D=ge=>ge.map(A2).filter(me=>!!me.run_id),[q,H]=await Promise.all([y.list_runs({limit:200,root_only:!0,include_metrics:!0}),y.list_runs({limit:500,root_only:!1,include_metrics:!0})]);if(M!==gi.current)return;const V=Array.isArray(q==null?void 0:q.items)?q.items:[],te=Array.isArray(H==null?void 0:H.items)?H.items:[],Le=D(V).filter(ge=>!String(ge.parent_run_id||"").trim()||ge.role==="occurrence");An(Le),In(D(te).filter(ge=>!!ge.run_id)),js(Date.now()),Et.current=0,ct.current=0}catch(D){const q=String((D==null?void 0:D.message)||D||"");if(Jt({ts:Ct(),kind:"error",title:"Refresh runs failed",preview:jt(q)}),(/\b40[13]\b/.test(q)||/unauthorized|forbidden/i.test(q))&&P.refresh().catch(()=>{}),/\b429\b/.test(q)||/too many requests/i.test(q)){const H=Math.min(12e4,Math.max(15e3,Et.current*2||15e3));Et.current=H,ct.current=Date.now()+H,Jt({ts:Ct(),kind:"info",title:`Gateway rate-limited — pausing polls ${Math.round(H/1e3)}s`})}}finally{rt.current=!1,ks(!1)}}async function Ba(y){var te,Le,ge;const S=gi.current;ee(!0),$t({});const[M,,D,q,H]=await Promise.allSettled([y.list_bundles(),ls(y),y.discovery_tools(),y.discovery_providers({include_models:!1}),y.discovery_capabilities()]);if(S!==gi.current)return;if(M.status==="rejected"&&D.status==="rejected"&&q.status==="rejected"){ee(!1),z(up(M.reason,n)),Jt({ts:Ct(),kind:"error",title:"Discovery failed",preview:jt(String(M.reason||""))});return}zt(H.status==="fulfilled"?$2(H.value):{available:!1,reason:`Could not read the gateway capabilities: ${String(((te=H.reason)==null?void 0:te.message)||H.reason)}`});let V=0;if(M.status==="fulfilled"){const me=Or(M.value);V=me.length,pn(me)}else pn([]),Jt({ts:Ct(),kind:"error",title:"Discovery bundles failed",preview:jt(String(M.reason||""))});if(D.status==="fulfilled"){const me=Array.isArray((Le=D.value)==null?void 0:Le.items)?D.value.items:[];Yt(me)}else Yt([]),Jt({ts:Ct(),kind:"error",title:"Discovery tools failed",preview:jt(String(D.reason||""))});if(q.status==="fulfilled"){const me=Array.isArray((ge=q.value)==null?void 0:ge.items)?q.value.items:[];Pt(me)}else Pt([]),Jt({ts:Ct(),kind:"error",title:"Discovery providers failed",preview:jt(String(q.reason||""))});Jt({ts:Ct(),kind:"info",title:"Gateway discovery loaded",preview:jt(`workflows: ${V}`)})}async function Xr(y){var S,M;z(""),ee(!1),O(!0);try{if(!(y!=null&&y.prefer_direct)&&(await P.refresh(),El.current))return;const D=String(n.auth_token||"").trim();if(!D){y!=null&&y.open_modal_if_needed&&P.openModal();return}const q=String(n.gateway_url||"").trim();if(q){const V=q.toLowerCase();if(!V.startsWith("http://")&&!V.startsWith("https://"))throw new Error("Gateway URL must start with http:// or https:// (or leave it blank to use same origin / dev proxy).");try{if(String(((S=window==null?void 0:window.location)==null?void 0:S.protocol)||"")==="https:"&&V.startsWith("http://"))throw new Error("Gateway URL is http:// but this page is https:// (mixed content is blocked). Use https:// or leave Gateway URL blank to use same origin /api proxy.");const Le=new URL(q),ge=String(((M=window==null?void 0:window.location)==null?void 0:M.hostname)||"").trim().toLowerCase(),me=String(Le.hostname||"").trim().toLowerCase(),Ae=Oe=>Oe==="localhost"||Oe==="127.0.0.1"||Oe==="::1";if(Ae(me)&&ge&&!Ae(ge))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 H=new F_({base_url:q,auth_token:D});await H.list_bundles(),r(V=>({...V,gateway_auth_mode:"direct"})),await Ba(H)}catch(D){z(up(D,n))}finally{O(!1)}}const El=p.useRef(!1),gi=p.useRef(0),Pc=p.useRef(!1);function dd(y){var M,D,q;G(y);const S=!!(y&&y.has_session&&((M=y.gateway)!=null&&M.ok));if(El.current=S,S){if(Pc.current=!1,A&&n.gateway_auth_mode==="direct")return;const H=String(((q=(D=y==null?void 0:y.gateway)==null?void 0:D.principal)==null?void 0:q.user_id)||"").trim();if(r(V=>({...V,gateway_auth_mode:"session",auth_token:"",gateway_user:H||V.gateway_user})),A&&n.gateway_auth_mode==="session")return;z(""),O(!0),Ba(new F_({base_url:"",auth_token:""})).catch(V=>z(up(V,n))).finally(()=>O(!1));return}y&&!y.has_session&&(n.gateway_auth_mode==="session"&&Al({keep_session:!0}),String(n.auth_token||"").trim()&&!A&&!Pc.current&&(Pc.current=!0,Xr({prefer_direct:!0})))}async function Dn(){if(!(kt||W)){Kt(!0);try{await Te.reload_bundles();const y=await Te.list_bundles(),S=Or(y);pn(S),Jt({ts:Ct(),kind:"info",title:"Bundles reloaded",preview:jt(`workflows: ${S.length}`)})}catch(y){const S=String((y==null?void 0:y.message)||y||"Bundle reload failed");Jt({ts:Ct(),kind:"error",title:"Bundle reload failed",preview:jt(S),data:{error:S}})}finally{Kt(!1)}}}async function Dc(y){if(Cr||W||!A)return;const S=y;if(S){qr(!0),nn("");try{const M=await Te.upload_bundle(S,{overwrite:!1,reload:!0});Jt({ts:Ct(),kind:"info",title:"Bundle uploaded",preview:jt(String((M==null?void 0:M.bundle_ref)||""))});const D=await Te.list_bundles(),q=Or(D);pn(q)}catch(M){const D=String((M==null?void 0:M.message)||M||"Upload failed");nn(D),Jt({ts:Ct(),kind:"error",title:"Upload .flow failed",preview:jt(D),data:{error:D}})}finally{qr(!1);try{it.current&&(it.current.value="")}catch{}}}}function Al(y){gi.current+=1,y!=null&&y.keep_session||(P.signOut().catch(()=>{}),El.current=!1),Wc(),E(""),N(""),eo(""),J(null),fe(""),re(!1),pn([]),An([]),In([]),js(null),On([]),Yt([]),Pt([]),$t({}),z(""),ee(!1),G(null),r(S=>({...S,auth_token:""})),Jt({ts:Ct(),kind:"info",title:"Gateway disconnected"})}async function Fc(y){const S=String(y??"");S&&Qn(await EE(S)?"Copied to clipboard":NE,2)}p.useEffect(()=>{const y=c.trim();if(!De||!y)return;let S=!1;const M=async()=>{if(!(ct.current>Date.now()))try{const q=await Te.get_run(y);S||fr(q)}catch{}};M();const D=window.setInterval(M,2e3);return()=>{S=!0,window.clearInterval(D)}},[De,c,Te]),p.useEffect(()=>{if(!A)return;let y=null,S=!1,M=!1;const D=V=>{S||(y!==null&&window.clearTimeout(y),y=window.setTimeout(()=>void q(),V))},q=async()=>{if(M)return;const V=ct.current-Date.now();if(V>0){D(V+500);return}M=!0;const te=Date.now();try{await ls(Te)}finally{M=!1;const Le=Date.now()-te,ge=document.visibilityState==="hidden"?3e4:5e3;D(Math.max(ge,Le*3))}},H=()=>{document.visibilityState==="visible"&&q()};return q(),document.addEventListener("visibilitychange",H),()=>{S=!0,y!==null&&window.clearTimeout(y),document.removeEventListener("visibilitychange",H)}},[A,Te]);const[zc,$l]=p.useState(null);p.useEffect(()=>{if(!A){$l(null);return}let y=!1;return(async()=>{try{const S=await Te.get_entity_phases_spec();if(y)return;const M=EL(S);if($l(M),M)try{const D=localStorage.getItem("abstractobserver_phase_graph_id_v1"),q=D?JSON.parse(D):null;q&&q.sha256&&M.sha256&&q.sha256!==M.sha256&&q.version===M.version&&Jt({ts:Ct(),kind:"error",title:"Phase-graph drift: served bytes changed without a version bump",preview:jt(`v${M.version}: ${String(q.sha256).slice(0,12)}… -> ${String(M.sha256).slice(0,12)}…`),data:{prev:q,now:{sha256:M.sha256,version:M.version}}}),localStorage.setItem("abstractobserver_phase_graph_id_v1",JSON.stringify({sha256:M.sha256,version:M.version}))}catch{}}catch(S){if(!y){$l(null);const M=String((S==null?void 0:S.message)||S||"");/404|not found/i.test(M)||Jt({ts:Ct(),kind:"info",title:"Phase-graph fetch failed — pre-wire fallback vocabulary in use (#FALLBACK)",preview:jt(M),data:{error:M}})}}})(),()=>{y=!0}},[A]),p.useEffect(()=>{if(!A){On([]),Ge("");return}let y=!1,S=null;const M=async()=>{if(!(ct.current>Date.now())){try{const D=await Te.list_entities(),q=D.entities.map(V=>String((V==null?void 0:V.name)||(V==null?void 0:V.slug)||"").trim()).filter(Boolean).slice(0,12),H=await Promise.all(q.map(async V=>{var te,Le;try{const[ge,me]=await Promise.all([Te.get_entity_card(V),Te.get_entity_cognition(V).catch(()=>null)]),Ae=ge!=null&&ge.state&&typeof ge.state=="object"?ge.state:null,Oe=Array.isArray(ge==null?void 0:ge.moments)?ge.moments:[],ze=Oe.length?Oe[Oe.length-1]:null,Ze=(te=me==null?void 0:me.spend)==null?void 0:te.lifetime,Ve=(Le=me==null?void 0:me.spend)==null?void 0:Le.live_visit,rn=Array.isArray(me==null?void 0:me.warnings)?me.warnings.map(Be=>String(Be||"")).filter(Boolean):[],Rt=pL(ge);return{name:V,state:String((Ae==null?void 0:Ae.state)??(typeof(ge==null?void 0:ge.state)=="string"?ge.state:"")).trim(),age_days:typeof(ge==null?void 0:ge.age_days)=="number"?ge.age_days:null,last_moment:String((ze==null?void 0:ze.kind)||"").trim(),last_moment_at:String((ze==null?void 0:ze.at)||"").trim(),working:typeof(me==null?void 0:me.working)=="boolean"?me.working:null,tokens_total:typeof(Ze==null?void 0:Ze.tokens_total)=="number"?Ze.tokens_total:null,live_visit_tokens:typeof(Ve==null?void 0:Ve.tokens_total)=="number"?Ve.tokens_total:null,spend_warning:rn.join(" | "),live_phase:typeof(me==null?void 0:me.phase)=="string"?me.phase:"",open_questions:Rt.questions,open_questions_total:Rt.questions_total,open_problems:Rt.problems,open_problems_total:Rt.problems_total,lessons:Rt.lessons,lessons_total:Rt.lessons_total,dreams_brief:_L(ge),error:""}}catch(ge){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((ge==null?void 0:ge.message)||ge||"card failed")}}}));y||(On(H),ke(D.entities.length),Ge(""))}catch(D){if(!y){On([]);const q=String((D==null?void 0:D.message)||D||"");Ge(/404|not found/i.test(q)?"":q)}}y||(S=window.setTimeout(()=>void M(),3e4))}};return M(),()=>{y=!0,S!==null&&window.clearTimeout(S)}},[A,Te]);async function Go(y,S,M){const D=String(S||"").trim();if(!y||!D)throw new Error("This wait has no wait_key yet — open the run to inspect.");await Te.submit_command({command_id:xs(),run_id:y,type:"resume",payload:{wait_key:D,payload:M||{}},client_id:"web_pwa"}),Jt({ts:Ct(),kind:"info",title:"Board resume submitted",preview:jt(`run ${y} · wait ${D}`),data:{run_id:y,wait_key:D}}),ls(Te,{force:!0}),window.setTimeout(()=>void ls(Te,{force:!0}),1200)}const yn=p.useMemo(()=>{const y=ue==null?void 0:ue.session_id;return typeof y=="string"?y.trim():y==null?"":String(y||"").trim()},[ue]),Mn=p.useMemo(()=>{const y=String(yn||"").trim();return y||String(K||"").trim()},[yn,K]);p.useEffect(()=>{if(!A||!Mn){oe(""),ci("");return}(async()=>{try{const y=await GL(Mn);oe(y)}catch{oe("")}})()},[A,Mn]);const Ht=UL({gateway:A?Te:null,session_id:Mn,run_id:B,on_error:ci,on_transcript:y=>{const S=String(y||"").trim();S&&(er(M=>{const D=String(M||"");return D.trim()?`${D.trimEnd()}
143
- ${S}`:S}),window.setTimeout(()=>{var M;return(M=Xt.current)==null?void 0:M.focus()},0))}});function Bc(y,S){try{const M=URL.createObjectURL(y),D=document.createElement("a");D.href=M,D.download=S||"download",D.rel="noreferrer",document.body.appendChild(D),D.click(),document.body.removeChild(D),window.setTimeout(()=>URL.revokeObjectURL(M),5e3)}catch{}}async function Tl(){const y=ga.trim();if(!y){Qn("This run recorded no workspace folder",2);return}try{const S=await fetch(CN,{method:"POST",headers:{"Content-Type":"application/json",...lb()},body:JSON.stringify({path:y})}),M=await S.json().catch(()=>({}));S.ok&&(M!=null&&M.ok)?Qn(`Opened ${String(M.path||y)}`,2):Qn(String((M==null?void 0:M.error)||`Folder reveal failed (${S.status})`),3)}catch(S){Qn(String((S==null?void 0:S.message)||S||"Folder reveal failed"),3)}}async function Ml(y){const S=String((y==null?void 0:y.run_id)||"").trim(),M=String((y==null?void 0:y.artifact_id)||"").trim();if(!S||!M){Qn("Artifact download needs a run id",3);return}const D=Rp(y)||M;try{const q=await Te.download_run_artifact_content(S,M,{access:"preview"});Bc(q,Hy(D)),Qn("Downloaded artifact",2)}catch(q){Qn(String((q==null?void 0:q.message)||q||"Download failed"),3)}}async function Km(y){const S=String((y==null?void 0:y.run_id)||"").trim(),M=String((y==null?void 0:y.artifact_id)||"").trim();if(!S||!M){Qn("Artifact preview needs a run id",3);return}const D=Rp(y),q=String((y==null?void 0:y.content_type)||"").trim().toLowerCase(),H=uf(y);if(En(D||M),xr(""),jl(""),Ra(H),La(y),fo(!0),fn&&(URL.revokeObjectURL(fn),ws("")),H==="binary"){xr(`(Binary artifact: ${q||"unknown"}; download to view.)`);return}if(H==="text"&&typeof y.size_bytes=="number"&&y.size_bytes>15e5){xr(`(Text artifact is ${y.size_bytes.toLocaleString()} bytes; download to view.)`);return}bl(!0);try{const V=await Te.download_run_artifact_content(S,M,{access:"preview"});if(H==="text"){const te=await V.text(),Le=fm(y,te),ge=Le==="json"?15e5:Le==="markdown"?25e4:Le==="html"?3e5:22e3;xr(te.length>ge&&Le!=="text"?`${Yl(y.size_bytes??te.length)} ${Le.toUpperCase()} artifact. Download to inspect it.`:te.length>ge?`${te.slice(0,Math.max(0,ge-1))}…`:te)}else ws(URL.createObjectURL(V))}catch(V){jl(String((V==null?void 0:V.message)||V||"Preview failed"))}finally{bl(!1)}}p.useEffect(()=>()=>{fn&&URL.revokeObjectURL(fn)},[fn]);async function Cs(y){const S=String(y.artifact_id||"").trim(),M=String(y.run_id||"").trim(),D=uf(y);if(!M||!S)return{artifact_id:S,kind:D,render_kind:"",text:"Preview needs artifact run metadata.",url:"",loading:!1,error:""};if(D==="binary")return{artifact_id:S,kind:D,render_kind:"",text:`Preview unavailable for ${y.content_type||y.modality||"this artifact"}. Download to inspect it.`,url:"",loading:!1,error:""};if(D==="text"&&typeof y.size_bytes=="number"&&y.size_bytes>5e5)return{artifact_id:S,kind:D,render_kind:"",text:`${Yl(y.size_bytes)} text artifact. Use Preview for a larger view or Download to inspect locally.`,url:"",loading:!1,error:""};try{const q=await Te.download_run_artifact_content(M,S,{access:"preview"});if(D==="text"){const H=await q.text(),V=fm(y,H),te=V==="json"?5e5:V==="markdown"?12e4:V==="html"?3e5:8e3;return{artifact_id:S,kind:D,render_kind:V,text:H.length>te&&V!=="text"?`${Yl(y.size_bytes??H.length)} ${V.toUpperCase()} artifact. Use Larger preview or Download to inspect it.`:H.length>te?`${H.slice(0,Math.max(0,te-1))}…`:H,url:"",loading:!1,error:""}}return{artifact_id:S,kind:D,render_kind:"",text:"",url:URL.createObjectURL(q),loading:!1,error:""}}catch(q){return{artifact_id:S,kind:D,render_kind:"",text:"",url:"",loading:!1,error:String((q==null?void 0:q.message)||q||"Preview failed")}}}async function fd(y){if(Kr.url&&URL.revokeObjectURL(Kr.url),!y){Ma(Na());return}const S=String(y.artifact_id||"").trim(),M=uf(y);Ma({artifact_id:S,kind:M,render_kind:"",text:"",url:"",loading:!0,error:""}),Ma(await Cs(y))}function Jt(y){const S=String(y.id||"").trim()||xs();Ou(M=>[{...y,id:S},...M].slice(0,800))}function Qn(y,S){ha(y),Xi.current&&window.clearTimeout(Xi.current),Ci(!1),window.requestAnimationFrame(()=>Ci(!0)),Xi.current=window.setTimeout(()=>{Ci(!1),Xi.current=null},1500),gr.current&&(window.clearTimeout(gr.current),gr.current=null),S>0&&(gr.current=window.setTimeout(()=>{ha(""),gr.current=null},Math.max(1,S)*1e3))}function Fn(y,S){const M=String(y||"").trim(),D=String(S||"").trim();if(!D)return"";const q=M?String(no.current[M]||"").trim():"";return q?`${q}::${D}`:D}function sr(y,S,M){const D=String(y||"").trim(),q=String(S||"").trim(),H=String(M||"").trim();if(!D||!q||!H)return;const V=Fn(D,q);V&&(no.current[H]=V,so.current[H]=D,bc.current[H]={parent_run_id:D,parent_node_id:q},ro.current.has(H)||(ro.current.add(H),ka(te=>te.includes(H)?te:[...te,H])))}function mo(y){const S=String(y||"").trim();if(!S)return;const M=Date.now(),D=di.current;di.current=S,to(M),ml(q=>{const H={};for(const[ge,me]of Object.entries(q))typeof me=="number"&&me>M&&(H[ge]=me);H[S]=Math.max(H[S]||0,M+2e3),D&&D!==S&&(H[D]=Math.max(H[D]||0,M+2e3));const V=Object.keys(H);if(V.length<=200)return H;const te=V.sort((ge,me)=>(H[me]||0)-(H[ge]||0)).slice(0,200),Le={};for(const ge of te)Le[ge]=H[ge]||0;return Le}),Vu(q=>{if(typeof q[S]=="number")return q;const H={...q,[S]:M};if(_l.current.push(S),_l.current.length>8e3){const V=_l.current.splice(0,1500);for(const te of V)delete H[te]}return H}),gs.current&&window.clearTimeout(gs.current),gs.current=window.setTimeout(()=>{const q=Date.now();ml(H=>{const V={};for(const[te,Le]of Object.entries(H))typeof Le=="number"&&Le>q&&(V[te]=Le);return V}),to(q),gs.current=null},2200)}function Uc(y,S){var Ve,rn,Rt;const M=String(S||"").trim()||c.trim();dr.current=y.cursor,(Ve=ii.current)==null||Ve.push({cursor:y.cursor,record:y.record}),M&&oo.current.add(`${M}:${y.cursor}`);const D=Ih(y.record),q=D&&D.name?sf(D.name):"",H=y.record,V=typeof(H==null?void 0:H.node_id)=="string"?H.node_id:"",te=typeof(H==null?void 0:H.status)=="string"?H.status:"",Le=typeof((rn=H==null?void 0:H.effect)==null?void 0:rn.type)=="string"?H.effect.type:"",ge=typeof(H==null?void 0:H.run_id)=="string"?H.run_id:"",me=ge||M;if(q==="abstract.status"&&me===M){const{text:Be,duration:bt}=iu(D==null?void 0:D.payload);Qn(Be,bt)}const Ae=V?Fn(me,V):"";if(te==="waiting"){const Be=ra(H);if(String((Be==null?void 0:Be.reason)||"").trim()==="subworkflow"){const xn=typeof((Rt=Be==null?void 0:Be.details)==null?void 0:Rt.sub_run_id)=="string"?String(Be.details.sub_run_id):"";xn&&V&&sr(me,V,xn)}}if(V&&(mo(Fn(me,V)),te==="waiting"||te==="running")){const Be=Fn(me,V);Be&&(di.current=Be,Po(Be))}let Oe="step",ze=Ae||V||"(node?)",Ze="";if(D&&D.name&&cp(D.name))Oe=q==="abstract.message"?"message":"event",ze=q||D.name,Ze=jt(q==="abstract.steer_seen"?lp(D==null?void 0:D.payload):iu(D==null?void 0:D.payload).text);else if(H!=null&&H.error)Oe="error",ze="error",Ze=jt(cr(H.error,360));else if(te==="waiting"){const Be=ra(H),bt=String((Be==null?void 0:Be.reason)||"").trim();Ze=jt(bt?`waiting • ${bt}`:"waiting")}else H!=null&&H.result?Ze=jt(cr(H.result,360)):Le?Ze=jt(Le):Ze=jt(Qh(H));Jt({id:`step:${ge||M||"?"}:${y.cursor}`,ts:String((H==null?void 0:H.ended_at)||(H==null?void 0:H.started_at)||Ct()),kind:Oe,title:ze,preview:Ze,data:H,cursor:y.cursor,run_id:ge||M||void 0,node_id:Ae||V,status:te,effect_type:Le,emit_name:q||(D==null?void 0:D.name)||void 0})}function hd(y,S){var Ze,Ve,rn;io.current=Math.max(io.current,S.cursor);const M=`${y}:${S.cursor}`;if(!!oo.current.has(M))return;oo.current.add(M),(Ze=oi.current)==null||Ze.push({run_id:y,cursor:S.cursor,record:S.record});const q=Ih(S.record),H=q&&q.name?sf(q.name):"",V=S.record,te=typeof(V==null?void 0:V.node_id)=="string"?V.node_id:"",Le=te?Fn(y,te):"",ge=typeof(V==null?void 0:V.status)=="string"?V.status:"",me=typeof((Ve=V==null?void 0:V.effect)==null?void 0:Ve.type)=="string"?V.effect.type:"";if(ge==="waiting"){const Rt=ra(V);if(String((Rt==null?void 0:Rt.reason)||"").trim()==="subworkflow"){const bt=typeof((rn=Rt==null?void 0:Rt.details)==null?void 0:rn.sub_run_id)=="string"?String(Rt.details.sub_run_id):"";bt&&te&&sr(y,te,bt),bt&&hi.current.trim()===String(y||"").trim()&&(hi.current=bt,ao(bt))}}if(te&&(mo(Fn(y,te)),ge==="waiting"||ge==="running")){const Rt=Fn(y,te);Rt&&(di.current=Rt,Po(Rt))}if((ge==="completed"||ge==="failed")&&hi.current.trim()===String(y||"").trim()){const Rt=String(so.current[String(y||"").trim()]||"").trim();Rt&&Rt!==c.trim()?(hi.current=Rt,ao(Rt)):(hi.current="",ao(""))}if(H==="abstract.status"&&y===c.trim()){const{text:Rt,duration:Be}=iu(q==null?void 0:q.payload);Qn(Rt,Be)}let Ae="step",Oe=Le||te||"(node?)",ze="";if(q&&q.name&&cp(q.name))Ae=H==="abstract.message"?"message":"event",Oe=`subrun • ${H||q.name}`,ze=jt(H==="abstract.steer_seen"?lp(q==null?void 0:q.payload):iu(q==null?void 0:q.payload).text);else if(V!=null&&V.error)Ae="error",Oe="error",ze=jt(cr(V.error,360));else if(ge==="waiting"){const Rt=ra(V),Be=String((Rt==null?void 0:Rt.reason)||"").trim();ze=jt(Be?`waiting • ${Be}`:"waiting")}else V!=null&&V.result?ze=jt(cr(V.result,360)):me?ze=jt(me):ze=jt(Qh(V));Jt({id:`step:${y}:${S.cursor}`,ts:String((V==null?void 0:V.ended_at)||(V==null?void 0:V.started_at)||Ct()),kind:Ae,title:Oe,preview:ze,data:V,cursor:S.cursor,run_id:y,node_id:Le||te,status:ge,effect_type:me,emit_name:H||(q==null?void 0:q.name)||""})}function Xf(y,S){var Ve,rn,Rt;const M=String(y||"").trim();if(!M)return;const D=`${M}:${S.cursor}`;if(!!oo.current.has(D))return;oo.current.add(D),(Ve=oi.current)==null||Ve.push({run_id:M,cursor:S.cursor,record:S.record});const H=Ih(S.record),V=H&&H.name?sf(H.name):"",te=S.record,Le=typeof(te==null?void 0:te.node_id)=="string"?te.node_id:"",ge=Le?Fn(M,Le):"",me=typeof(te==null?void 0:te.status)=="string"?te.status:"",Ae=typeof((rn=te==null?void 0:te.effect)==null?void 0:rn.type)=="string"?te.effect.type:"";if(me==="waiting"){const Be=ra(te);if(String((Be==null?void 0:Be.reason)||"").trim()==="subworkflow"){const xn=typeof((Rt=Be==null?void 0:Be.details)==null?void 0:Rt.sub_run_id)=="string"?String(Be.details.sub_run_id):"";xn&&Le&&sr(M,Le,xn)}}if(Le&&(mo(Fn(M,Le)),me==="waiting"||me==="running")){const Be=Fn(M,Le);Be&&(di.current=Be,Po(Be))}if(V==="abstract.status"&&M===c.trim()){const{text:Be,duration:bt}=iu(H==null?void 0:H.payload);Qn(Be,bt)}let Oe="step",ze=ge||Le||"(node?)",Ze="";if(H&&H.name&&cp(H.name))Oe=V==="abstract.message"?"message":"event",ze=`subrun • ${V||H.name}`,Ze=jt(V==="abstract.steer_seen"?lp(H==null?void 0:H.payload):iu(H==null?void 0:H.payload).text);else if(te!=null&&te.error)Oe="error",ze="error",Ze=jt(cr(te.error,360));else if(me==="waiting"){const Be=ra(te),bt=String((Be==null?void 0:Be.reason)||"").trim();Ze=jt(bt?`waiting • ${bt}`:"waiting")}else te!=null&&te.result?Ze=jt(cr(te.result,360)):Ae?Ze=jt(Ae):Ze=jt(Qh(te));Jt({id:`step:${M}:${S.cursor}`,ts:String((te==null?void 0:te.ended_at)||(te==null?void 0:te.started_at)||Ct()),kind:Oe,title:ze,preview:Ze,data:te,cursor:S.cursor,run_id:M,node_id:ge||Le,status:me,effect_type:Ae,emit_name:V||(H==null?void 0:H.name)||""})}async function md(y,S){var D,q;let M=S.after;for(;;){if((D=S.signal)!=null&&D.aborted)return M;const H=await Te.get_ledger(y,{after:M,limit:200,signal:S.signal});if((q=S.signal)!=null&&q.aborted)return M;const V=Array.isArray(H.items)?H.items:[];if(!V.length)return dr.current=M,M;const te=M;for(let Le=0;Le<V.length;Le++){const ge=V[Le];Uc({cursor:te+Le+1,record:ge},y)}M=typeof H.next_after=="number"?H.next_after:M}}async function Rl(y){var H,V,te,Le;const S=String(y||"").trim();nn(""),tn(!0),on(!1),(H=ii.current)==null||H.reset(),(V=oi.current)==null||V.reset(),Ps.current={scanned:0,found:null},Ys([]),dr.current=0,Wr([]),oo.current=new Set,Ou([]),Bu(""),ha(""),fr(null),Qs(""),Oo(""),Po(""),di.current="",ml({}),Vu({}),_l.current=[],to(Date.now()),no.current=S?{[S]:""}:{},so.current={},bc.current={},ro.current=new Set,ka([]),ja.current="",hi.current="",ao(""),Do.current={},gs.current&&window.clearTimeout(gs.current),gs.current=null,Zs.current&&window.clearTimeout(Zs.current),Zs.current=null,Ai.current&&Ai.current.abort(),zs.current&&zs.current.abort(),zs.current=null,io.current=0,Sa("");const M=new AbortController;Ai.current=M;let D=!1;try{let ge="",me="";try{const Ae=await Te.get_run(S);fr(Ae);const Oe=typeof(Ae==null?void 0:Ae.workflow_id)=="string"?String(Ae.workflow_id):"",ze=kv(Oe);ze&&(ge=ze.bundle_id,me=ze.flow_id)}catch{}try{const Ae=await Te.get_run_input_data(S);typeof(Ae==null?void 0:Ae.bundle_id)=="string"&&(ge=String(Ae.bundle_id||"").trim()||ge),typeof(Ae==null?void 0:Ae.flow_id)=="string"&&(me=String(Ae.flow_id||"").trim()||me);const Oe=Ae&&typeof Ae.input_data=="object"&&Ae.input_data&&!Array.isArray(Ae.input_data)?Ae.input_data:null;Oe&&I(JSON.stringify(Oe,null,2));const ze=Ae==null?void 0:Ae.workspace,Ze=typeof(ze==null?void 0:ze.workspace_root)=="string"?String(ze.workspace_root).trim():"";Oo(Ze)}catch{Oo("")}ge&&me&&(E(ge),N(me),eo(me),await za(ge)),await md(S,{after:0,signal:M.signal});try{const Ae=await Te.get_run_history_bundle(S,{include_subruns:!0,include_session:!1,ledger_mode:"tail",ledger_max_items:1}),Oe=Ae&&typeof Ae=="object"?Ae.ledgers:null,Ze=(Oe&&typeof Oe=="object"?Object.keys(Oe):[]).map(Ve=>String(Ve||"").trim()).filter(Boolean).filter(Ve=>Ve!==S);if(Ze.length){for(const Ve of Ze)ro.current.add(Ve);ka(Ve=>Array.from(new Set([...Ve,...Ze])));try{const Ve=typeof((te=Oe==null?void 0:Oe[S])==null?void 0:te.total)=="number"?Number(Oe[S].total):0;let rn="",Rt=-1;for(const Be of Ze){const bt=typeof((Le=Oe==null?void 0:Oe[Be])==null?void 0:Le.total)=="number"?Number(Oe[Be].total):0;bt>Rt&&(rn=Be,Rt=bt)}rn&&Rt>Math.max(Ve*3,Ve+20)&&(hi.current=rn,ao(rn))}catch{}}}catch{}on(!0),Jt({ts:Ct(),kind:"info",title:`Attached to run ${S}`,data:{run_id:S}}),D=!0}catch(ge){const me=String((ge==null?void 0:ge.message)||ge||"unknown error");nn(me),Jt({ts:Ct(),kind:"error",title:"Connection error",preview:jt(me),data:{error:me}}),on(!1)}finally{tn(!1)}if(!D||M.signal.aborted)return;(async()=>{let ge=250;for(;!M.signal.aborted;){try{const me=await md(S,{after:dr.current,signal:M.signal});await Te.stream_ledger(S,{after:me,on_step:Ae=>Uc(Ae,S),signal:M.signal})}catch(me){if(M.signal.aborted)break;const Ae=String((me==null?void 0:me.message)||me||"stream error");Jt({ts:Ct(),kind:"error",title:"Ledger stream error (will retry)",preview:jt(Ae),data:{error:Ae}})}if(M.signal.aborted)break;await new Promise(me=>setTimeout(me,ge)),ge=Math.min(5e3,Math.floor(ge*1.6))}})()}async function Zf(){const y=Jr,S=(y==null?void 0:y.kind)==="bundle"?y.flow_id:(y==null?void 0:y.kind)==="default"?"@default":"",M=(y==null?void 0:y.kind)==="bundle"?y.bundle_id:"";if(!y){const D="Select a workflow first (Launch → pick a workflow).";return nn(D),D}nn(""),tn(!0);try{let D={};const q=T.trim();if(q)try{if(D=JSON.parse(q),typeof D!="object"||D===null||Array.isArray(D))throw new Error("input_data must be a JSON object")}catch(me){const Ae=`Invalid input_data JSON: ${String((me==null?void 0:me.message)||me)}`;return nn(Ae),Ae}for(const[me,Ae]of Object.entries(D)){if(typeof Ae!="string")continue;const Oe=Ae.trim();Oe?D[me]=Oe:delete D[me]}const H=(_i||[]).find(me=>me&&typeof me=="object"&&me.id==="prompt"),V=H&&typeof H=="object"&&Object.prototype.hasOwnProperty.call(H,"default"),te=D==null?void 0:D.prompt,Le=typeof te=="string"?te.trim():"";if(H&&!V&&!Le){const me="Missing required input_data.prompt";return nn(me),me}const ge=await Te.start_run(S,D,{...M?{bundle_id:M}:{},...y.kind==="default"?{interface:y.interface}:{},session_id:String(K||"").trim()||null});return _(ge),f(ge),hr(""),await Rl(ge),ls(),null}catch(D){const q=String((D==null?void 0:D.message)||D||"start failed");return nn(q),q}finally{tn(!1)}}async function Qf(){if(tt([]),Ke(null),!qe.available){tt([qe.reason]);return}const y=E2(We,{choice:Jr,bundle_ref_for:S=>{var M;return((M=Ot.find(D=>D.bundle_id===S))==null?void 0:M.bundle_ref)||""},input_data:ft,email_usable:Tt.email_usable},Ie.current);if(!y.ok){tt(y.errors);return}Re(!0);try{const S=await Te.automations_client().createAutomation(y.body);Ie.current.reset(),xe([]),pt($p),Jt({ts:Ct(),kind:"info",title:"Automation created",preview:jt(`${y.body.title} · ${S.automation_id}`)}),t("automations"),await Tt.refresh(),await Tt.select(S.automation_id)}catch(S){const M=(S&&typeof S=="object"&&typeof S.code=="string"?S:null)||{status:0,code:"client_error",message:String((S==null?void 0:S.message)||S||"Create failed")};Ke(M)}finally{Re(!1)}}async function eh(){if(hr(""),he==="automate"){await Qf();return}const y=await Zf();if(y){hr(y);return}Qi("ledger"),t("observe")}async function _d(y){if(Tn("skills",void 0),!!y){if(y.kind==="default"){Ue(y.interface),E(""),N(""),J(null);return}Ue(""),E(y.bundle_id),N(y.flow_id),eo(y.flow_id),await za(y.bundle_id)}}async function pd(y){const[S,M]=await Promise.all([Te.get_run(y),Te.get_run_input_data(y)]),D=O2(S,M);await _d(D.choice),I(JSON.stringify(D.input_data,null,2)),pt(D.form),xe([`Recreating the legacy schedule ${Qt(y,14)} as an automation. The legacy schedule keeps running until you suspend it.`,...D.notes]),Ie.current.reset(),pe("automate"),t("launch")}async function Zr(y,S){const M=String(y||"").trim();if(!M)return;if(ut){Qn(`Still attaching — retry in a moment (${Qt(M,14)})`,2500);return}nn(""),j("");const D=String((S==null?void 0:S.root_run_id)||M).trim()||M;_(D),f(M),await Rl(M)}p.useEffect(()=>{const y=String(g||"").trim();if(!y)return;let S=!1;return(async()=>{try{if(A||await Xr({open_modal_if_needed:!0}),S)return;Qi("ledger"),t("observe");const M=await Te.find_run(y);if(S)return;if(M===null){Wc(),j(y);return}await Zr(y),zl()}catch(M){S||nn(String((M==null?void 0:M.message)||M||"Failed to attach run from URL"))}finally{S||w("")}})(),()=>{S=!0}},[g]);function Wc(){var y,S;Ai.current&&Ai.current.abort(),Ai.current=null,zs.current&&zs.current.abort(),zs.current=null,io.current=0,Sa(""),f(""),_(""),no.current={},so.current={},bc.current={},ro.current=new Set,ka([]),ja.current="",hi.current="",ao(""),Do.current={},Qs(""),gs.current&&window.clearTimeout(gs.current),gs.current=null,Zs.current&&window.clearTimeout(Zs.current),Zs.current=null,on(!1),tn(!1),Un(!1),dr.current=0,(y=ii.current)==null||y.reset(),(S=oi.current)==null||S.reset(),Ps.current={scanned:0,found:null},Ys([]),Wr([]),oo.current=new Set,fr(null),Ou([]),Po(""),di.current="",ml({}),Vu({}),_l.current=[],to(Date.now()),Qn("",-1),nn(""),ot([]),Dt(null),er(""),li(""),Se(!1),Bt(!1),vn(""),ps(""),yr(""),Lo([]),hc(!1),_c(""),pc(""),yc(!1),Io("")}p.useEffect(()=>{ot([]),Dt(null),er(""),li(""),Se(!1),Bt(!1),vn(""),ps(""),yr(""),Lo([]),hc(!1),_c(""),pc(""),yc(!1),Io("")},[c]),p.useEffect(()=>{tr==="chat"&&c.trim()&&A&&qc()},[tr,c,A,ue==null?void 0:ue.workflow_id]);async function Ll(y,S,M){const D=String(y||"").trim();if(!D)return nn("Missing run_id"),"Missing run_id";nn("");try{const q={},H=String((M==null?void 0:M.reason)||"").trim();H&&(q.reason=H),await Te.submit_command({command_id:xs(),run_id:D,type:S,payload:q,client_id:"web_pwa"}),Jt({ts:Ct(),kind:"info",title:`${S} submitted`,preview:H?`reason: ${H}`:"",data:{run_id:D,type:S,reason:H}});try{if(D===c.trim()){const V=await Te.get_run(D);fr(V)}}catch{}return ls(Te,{force:!0}),window.setTimeout(()=>void ls(Te,{force:!0}),900),window.setTimeout(()=>void ls(Te,{force:!0}),2400),null}catch(q){const H=String((q==null?void 0:q.message)||q||`${S} failed`);return nn(H),H}}async function Ua(y,S){return Ll(c.trim(),y,S)}async function gd(y,S="Stopped from AbstractObserver"){const M=String(y||"").trim();if(!M||!window.confirm(`Cancel run ${Qt(M,24)}?`))return;await Ll(M,"cancel",{reason:S})||Qn("Cancel submitted",2)}async function yd(){var M;const y=c.trim();if(!y){nn("Select a run first.");return}if(!A){nn("Connect to the gateway first.");return}if(dt)return;const S=String(((M=ue==null?void 0:ue.waiting)==null?void 0:M.reason)||"").trim().toLowerCase()||String(cs||"").trim().toLowerCase();if(!or||ti||_o||ei.toLowerCase()!=="waiting"||S!=="until"){nn("This run is not a scheduled wait that can be triggered now.");return}nn(""),Un(!0);try{const D={payload:{mode:"run_now",requested_at:Ct()}},q=String(Es||"").trim();q&&(D.wait_key=q),await Te.submit_command({command_id:xs(),run_id:y,type:"resume",payload:D,client_id:"web_pwa"}),Jt({ts:Ct(),kind:"info",title:"Scheduled run triggered",preview:jt(`run ${y}`),data:{run_id:y,until:Qr||null}});try{const H=await Te.get_run(y);fr(H)}catch{}}catch(D){nn(String((D==null?void 0:D.message)||D||"Failed to trigger scheduled run"))}finally{Un(!1)}}async function th(y){const S=c.trim();if(!S)return nn("Missing run_id"),"Missing run_id";if($n)return"Schedule update already in progress";const M=String(y.interval||"").trim();if(!/^\s*(\d+(?:\.\d+)?)\s*(ms|s|m|h|d)\s*$/i.test(M)){const q="Invalid interval (expected like '20m', '1h', '0.5s', '250ms')";return ai(q),q}ai(""),nn(""),Fs(!0),tn(!0);try{await Te.submit_command({command_id:xs(),run_id:S,type:"update_schedule",payload:{interval:M,apply_immediately:y.apply_immediately!==!1},client_id:"web_pwa"}),Jt({ts:Ct(),kind:"info",title:"Schedule updated",preview:jt(`interval: ${M}`),data:{interval:M},run_id:S});try{const q=await Te.get_run(S);fr(q)}catch{}return null}catch(q){const H=String((q==null?void 0:q.message)||q||"update_schedule failed");return ai(H),nn(H),H}finally{tn(!1),Fs(!1)}}async function nh(y){const S=c.trim();if(!S)return nn("Missing run_id"),"Missing run_id";if(Er)return"Compaction already in progress";const M=typeof(y==null?void 0:y.preserve_recent)=="number"?y.preserve_recent:ms,D=Math.max(0,Math.min(500,Math.floor(Number.isFinite(M)?M:6))),q=(y==null?void 0:y.compression_mode)||Yi,H=String((y==null?void 0:y.focus)??fa??"").trim();_s(""),nn(""),Ar(!0),tn(!0);try{const V={preserve_recent:D,compression_mode:q};return H&&(V.focus=H),await Te.submit_command({command_id:xs(),run_id:S,type:"compact_memory",payload:V,client_id:"web_pwa"}),Jt({ts:Ct(),kind:"info",title:"Compaction requested",preview:jt(`mode: ${q} • preserve_recent: ${D}`),data:V,run_id:S}),null}catch(V){const te=String((V==null?void 0:V.message)||V||"compact_memory failed");return _s(te),nn(te),te}finally{tn(!1),Ar(!1)}}async function sh(){const y=c.trim();if(!y){li("Select a run first.");return}if(!A){li("Connect to the gateway first.");return}const S=Zi.trim();if(!S||be)return;if(Ht.voice_ptt_busy){ci("Wait for transcription to finish.");return}li(""),ci(""),Se(!0);const D={id:`local:${xs()}`,role:"user",content:S,ts:Ct()};ot(q=>[...q,D]),er("");try{const q=uN(Qe,D),H=n.maintenance_ai_provider.trim(),V=n.maintenance_ai_model.trim(),te=await Te.run_chat(y,{provider:H||void 0,model:V||void 0,include_subruns:!0,messages:q}),Le=String((te==null?void 0:te.answer)||"").trim()||"(empty response)",ge=String((te==null?void 0:te.generated_at)||"").trim()||Ct();Dt((te==null?void 0:te.history)??null),ot(me=>[...me,{id:`local:${xs()}`,role:"assistant",content:Le,ts:ge}])}catch(q){const H=o2(q);li(H),ot(V=>[...V,{id:`local:${xs()}`,role:"assistant",content:`(error: ${H})`,ts:Ct(),local_error:!0}])}finally{Se(!1)}}function rh(y){const S=String(y.id||y.ts||"").trim(),M=String(y.content||"").trim();!S||!M||(ci(""),Ht.toggle_tts(S,M))}function wd(y){const S=String(y.id||y.ts||"").trim(),M=Ht.tts_playback;return!S||!M.key||M.key!==S?"idle":M.status}function vd(y){if(!Qe.length)return;const S=c.trim(),M=S?`Run ${S}`:"Chat",D=DS(Qe.map(q=>({role:q.role,content:q.content,ts:q.ts})),{heading:M});if(y==="download"){const q=new Date().toISOString().slice(0,19).replace(/[:T]/g,"-"),H=`abstractobserver-chat-${Hy(S||"run")}-${q}.md`;FS({filename:H,text:D,mime:"text/markdown;charset=utf-8"});return}(async()=>{const q=await ic(D);He(q?"copied":"failed"),window.setTimeout(()=>He("idle"),900)})()}async function qc(){const y=typeof(ue==null?void 0:ue.workflow_id)=="string"?String(ue.workflow_id).trim():"";if(!y){Lo([]);return}if(A&&!cl){_c(""),hc(!0);try{const S=await Te.list_runs({limit:200,workflow_id:y,root_only:!0}),M=Array.isArray(S==null?void 0:S.items)?S.items:[],D=[];for(const ge of M){const me=typeof(ge==null?void 0:ge.run_id)=="string"?String(ge.run_id).trim():"";if(!me)continue;const Ae=typeof(ge==null?void 0:ge.ledger_len)=="number"?Number(ge.ledger_len):0;D.push({run_id:me,ledger_len:Number.isFinite(Ae)?Ae:0})}if(!D.length){Lo([]);return}const q=400,H=D.map(ge=>({run_id:ge.run_id,after:Math.max(0,(ge.ledger_len||0)-q)})),V=await Te.get_ledger_batch({runs:H,limit:q}),te=[],Le=new Set;for(const ge of D){const me=V!=null&&V.runs&&typeof V.runs=="object"?V.runs[ge.run_id]:null,Ae=Array.isArray(me==null?void 0:me.items)?me.items:[];for(const Oe of Ae){const ze=Oe==null?void 0:Oe.effect;if(!ze||typeof ze!="object"||String(ze.type||"")!=="emit_event")continue;const Ze=ze.payload;if(!Ze||typeof Ze!="object"||String(Ze.name||"")!=="abstract.chat.thread")continue;const Ve=Ze.payload;if(!Ve||typeof Ve!="object")continue;const rn=typeof Ve.thread_id=="string"?String(Ve.thread_id).trim():"";if(!rn||Le.has(rn))continue;Le.add(rn);const Rt=typeof Ve.created_at=="string"?String(Ve.created_at):"",Be=typeof Ve.title=="string"?String(Ve.title):"",bt=typeof Ve.workflow_id=="string"?String(Ve.workflow_id):y,xn=typeof Ve.run_id=="string"?String(Ve.run_id):ge.run_id,hn=typeof Ve.provider=="string"?String(Ve.provider):"",Ms=typeof Ve.model=="string"?String(Ve.model):"",ds=typeof Ve.message_count=="number"?Number(Ve.message_count):null,Dr=Ve.chat_artifact,Ya=Dr&&typeof Dr=="object"&&typeof Dr.$artifact=="string"?String(Dr.$artifact):"";Ya&&te.push({thread_id:rn,created_at:Rt,title:Be||`Chat ${rn.slice(0,8)}`,run_id:xn,workflow_id:bt,message_count:ds,provider:hn,model:Ms,artifact_id:Ya})}}te.sort((ge,me)=>String(me.created_at||"").localeCompare(String(ge.created_at||""))),Lo(te)}catch(S){_c(String((S==null?void 0:S.message)||S||"Failed to load saved discussions"))}finally{hc(!1)}}}async function ih(){const y=c.trim();if(!y){vn("Select a run first.");return}if(!A){vn("Connect to the gateway first.");return}if(Qe.length&&!Xn){vn(""),Bt(!0);try{const S=n.maintenance_ai_provider.trim(),M=n.maintenance_ai_model.trim(),D=await Te.save_chat_thread(y,{provider:S||void 0,model:M||void 0,include_subruns:!0,messages:Qe.map(V=>({role:V.role,content:V.content,ts:V.ts}))}),q=typeof(D==null?void 0:D.created_at)=="string"?String(D.created_at):Ct();ps(q);try{const V=JSON.stringify(Qe.map(te=>({role:te.role,content:te.content,ts:te.ts})));yr(V)}catch{yr("1")}typeof(D==null?void 0:D.thread_id)=="string"&&String(D.thread_id).trim()&&pc(String(D.thread_id).trim());const H=!!(D!=null&&D.duplicate);Qn(H?"Already saved":"Saved discussion",2),await qc()}catch(S){vn(String((S==null?void 0:S.message)||S||"Failed to save discussion"))}finally{Bt(!1)}}}async function Ym(){const y=String(Tu||"").trim();if(!y)return;const S=Ro.find(q=>String(q.thread_id||"").trim()===y)||null;if(!S){Io("Saved discussion not found (refresh list).");return}if(!A){Io("Connect to the gateway first.");return}if(gc)return;const M=Qe.length>0,D=(()=>{if(!M)return!1;if(!Ns)return!0;try{return JSON.stringify(Qe.map(H=>({role:H.role,content:H.content,ts:H.ts})))!==Ns}catch{return!0}})();if(!(M&&D&&!window.confirm("Replace the current chat with the selected saved discussion? Unsaved changes will be lost."))){Io(""),yc(!0);try{const H=await(await Te.download_run_artifact_content(S.run_id,S.artifact_id)).text(),V=JSON.parse(H),te=Array.isArray(V==null?void 0:V.messages)?V.messages:[],Le=typeof(V==null?void 0:V.created_at)=="string"?String(V.created_at):String(S.created_at||""),ge=[];for(let me=0;me<te.length;me++){const Ae=te[me];if(!Ae||typeof Ae!="object")continue;const Oe=String(Ae.role||"").trim()==="assistant"?"assistant":"user",ze=typeof Ae.content=="string"?String(Ae.content):"";if(!ze.trim())continue;const Ze=typeof Ae.ts=="string"?String(Ae.ts):Le||Ct();ge.push({id:`thread:${y}:${me}`,role:Oe,content:ze.trim(),ts:Ze})}ot(ge),Dt(null),er(""),li(""),vn(""),ps(Le||"");try{const me=JSON.stringify(ge.map(Ae=>({role:Ae.role,content:Ae.content,ts:Ae.ts})));yr(me)}catch{yr("1")}Qn("Loaded discussion",2)}catch(q){Io(String((q==null?void 0:q.message)||q||"Failed to load saved discussion"))}finally{yc(!1)}}}async function Il(y){const S=c.trim(),M=String((Ft==null?void 0:Ft.wait_key)||"").trim();if(!S||!M){nn("No active wait to resume");return}if(String((Ft==null?void 0:Ft.reason)||"").trim()==="subworkflow"){nn("This run is waiting on a subworkflow; attach to the child run instead of resuming manually.");return}nn(""),Un(!0);try{await Te.submit_command({command_id:xs(),run_id:S,type:"resume",payload:{wait_key:M,payload:y||{}},client_id:"web_pwa"}),Jt({ts:Ct(),kind:"info",title:"Resume submitted",preview:jt(`wait_key: ${M}`),data:{wait_key:M,payload:y||{}}}),Qs(M);try{const D=await Te.get_run(S);fr(D)}catch{}ls(Te,{force:!0}),window.setTimeout(()=>void ls(Te,{force:!0}),900),window.setTimeout(()=>void ls(Te,{force:!0}),2400),Zs.current&&window.clearTimeout(Zs.current),Zs.current=window.setTimeout(()=>{Qs(D=>D===M?"":D)},2e3)}catch(D){nn(String((D==null?void 0:D.message)||D||"resume failed"))}finally{Un(!1)}}async function Jm(y){if(!Pa){nn("No worker configured");return}if(!dt){nn(""),Un(!0);try{const S=[];for(const M of y){const D=await Pa.call_tool(M);S.push(D)}await Il({mode:"executed",results:S})}finally{Un(!1)}}}const Ko=p.useMemo(()=>Tf(Ft),[Ft]),Es=String((Ft==null?void 0:Ft.wait_key)||"").trim(),cs=String((Ft==null?void 0:Ft.reason)||"").trim(),Qr=typeof(Ft==null?void 0:Ft.until)=="string"?String(Ft.until):"",ei=typeof(ue==null?void 0:ue.status)=="string"?String(ue.status):"",_o=!!(ue!=null&&ue.paused),ti=ei==="completed"||ei==="failed"||ei==="cancelled",Xm=cs==="until"&&!!Qr,rr=!ti&&rE(Us)&&(!!Es||Xm),xd=cs==="user",Wa=cs==="event"?sf(WL(Es)):"",oh=cs==="event"&&Wa==="abstract.ask",ah=Ko.length>0,bd=rr&&Es&&(xd||oh||ah)&&$u!==Es&&e!=="board",Pi=typeof((ar=Ft==null?void 0:Ft.details)==null?void 0:ar.sub_run_id)=="string"?String(Ft.details.sub_run_id):"",yi={run_id:c.trim(),workflow_id:typeof(ue==null?void 0:ue.workflow_id)=="string"?String(ue.workflow_id):null,status:ei,created_at:typeof(ue==null?void 0:ue.created_at)=="string"?String(ue.created_at):null,updated_at:typeof(ue==null?void 0:ue.updated_at)=="string"?String(ue.updated_at):null,session_id:typeof(ue==null?void 0:ue.session_id)=="string"?String(ue.session_id):null,current_node:typeof(ue==null?void 0:ue.current_node)=="string"?String(ue.current_node):null},Hc=an.slice(-10).map(y=>{var S,M,D,q,H,V;return{cursor:y.cursor,node_id:String(((S=y.record)==null?void 0:S.node_id)||"").trim(),status:String(((M=y.record)==null?void 0:M.status)||"").trim(),effect_type:String(((q=(D=y.record)==null?void 0:D.effect)==null?void 0:q.type)||"").trim(),ts:String(((H=y.record)==null?void 0:H.ended_at)||((V=y.record)==null?void 0:V.started_at)||"").trim(),summary:nb(y.record)}}),Vc=jg(Ft,Ko),Zm=Zx(Ft,Ko),kd=Qx(Ft,ft),Yo=kd.text,lh=kd.runtime_metadata,Ol=String((Ft==null?void 0:Ft.prompt)||"").trim(),jd=WC(ft,6),Qm=!!(Ol&&Yx(Ol)),As=!!(Ol&&!Qm),Ws=As?"Question from workflow":Yo&&Yo!==Ol?"Closest prior user request":"Request context",ch=VC(ft,T),uh=!!T.trim(),ir=ue!=null&&ue.schedule&&typeof ue.schedule=="object"?ue.schedule:null,Jo=typeof(ir==null?void 0:ir.interval)=="string"?String(ir.interval).trim():"",dh=typeof(ir==null?void 0:ir.share_context)=="boolean"?!!ir.share_context:null,Gc=typeof(ir==null?void 0:ir.repeat_count)=="number"?Number(ir.repeat_count):null,or=!!(ue!=null&&ue.is_scheduled)||!!ir,Pl=or&&!!Jo,Sd=ei==="running"&&!_o?"Pause":"Resume",Nd=or?_o?"resume":"pause":Sd==="Pause"?"pause":"resume",Cd=or?!c.trim()||ut||dt||ti:!c.trim()||ut||dt||ti||Nd==="resume"&&!_o,Ed=c.trim()?ti?"The schedule has ended.":null:"No run selected.",fh=or&&!_o&&!ti&&!ut&&!dt&&ei.toLowerCase()==="waiting"&&(String(((Qo=ue==null?void 0:ue.waiting)==null?void 0:Qo.reason)||"").trim().toLowerCase()==="until"||cs==="until")&&!!String(Qr||"").trim(),qs=(Yn=ue==null?void 0:ue.limits)==null?void 0:Yn.tokens,po=typeof(qs==null?void 0:qs.pct)=="number"?Number(qs.pct):null,hh=qs==null?void 0:qs.estimated_used,Ad=(qs==null?void 0:qs.max_input_tokens)??(qs==null?void 0:qs.max_tokens),Dl=p.useMemo(()=>{const y=Ps.current;an.length<y.scanned&&(y.scanned=0,y.found=null);for(let S=y.scanned;S<an.length;S++){const M=an[S],D=M==null?void 0:M.record;if(!D)continue;const q=Ih(D);if((q&&q.name?sf(q.name):"")!=="abstract.summary")continue;const V=q!=null&&q.payload&&typeof q.payload=="object"?q.payload:{},te=typeof(V==null?void 0:V.text)=="string"?String(V.text):"";te.trim()&&(y.found={cursor:M.cursor,ts:String((D==null?void 0:D.ended_at)||(D==null?void 0:D.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 y.scanned=an.length,y.found},[an]);p.useEffect(()=>{hi.current=Mr.trim()},[Mr]),p.useEffect(()=>{const y=c.trim(),S=Pi.trim();if(!(De&&cs==="subworkflow"&&!!S&&S!==y)){ja.current="",Mr.trim()&&ao("");return}ja.current!==S&&(ja.current=S,hi.current=S,ao(S))},[De,c,cs,Pi,Mr]),p.useEffect(()=>{dl({})},[C]);const $d=p.useMemo(()=>((Array.isArray(U==null?void 0:U.entrypoints)?U==null?void 0:U.entrypoints:[])||[]).map(S=>String((S==null?void 0:S.flow_id)||"").trim()).filter(Boolean),[U]),Pr=p.useMemo(()=>{const y=String((ue==null?void 0:ue.workflow_id)||"").trim();return De&&or?y:""},[De,or,ue==null?void 0:ue.workflow_id]),Di=p.useMemo(()=>{var V;if(!De||!c.trim()||!Pr.trim())return ui;const y=String((ue==null?void 0:ue.status)||"").trim().toLowerCase(),S=String((ue==null?void 0:ue.current_node)||"").trim();if(y!=="waiting"&&y!=="running"||!S)return ui;const M=Fn(c.trim(),S);if(!M)return ui;const D=String(cs||((V=ue==null?void 0:ue.waiting)==null?void 0:V.reason)||"").trim().toLowerCase(),q=typeof(Us==null?void 0:Us.node_id)=="string"?String(Us.node_id).trim():"",H=typeof(Us==null?void 0:Us.status)=="string"?String(Us.status).trim().toLowerCase():"";return y==="waiting"&&D==="until"||!ui.trim()||(H==="waiting"||H==="running")&&!q?M:ui},[De,c,Pr,ue==null?void 0:ue.status,ue==null?void 0:ue.current_node,(Ga=ue==null?void 0:ue.waiting)==null?void 0:Ga.reason,cs,ui,Us]),e_=p.useMemo(()=>{const y={},S=c.trim(),M=(D,q)=>{if(!q)return;const H=typeof(q==null?void 0:q.node_id)=="string"?String(q.node_id).trim():"";if(!H)return;const V=Fn(D,H);if(!V)return;const te=String((q==null?void 0:q.ended_at)||(q==null?void 0:q.started_at)||"").trim(),Le=qn(te);Le!==null&&(y[V]=Math.max(y[V]||0,Le))};for(const D of an)D&&D.record&&M(S,D.record);for(const D of ss)D&&D.record&&M(String(D.run_id||"").trim(),D.record);return y},[an,ss,c,wr]);p.useEffect(()=>{var M;if(!De||!c.trim()||!Pr.trim())return;const y=String((ue==null?void 0:ue.current_node)||"").trim();!y||String(((M=ue==null?void 0:ue.waiting)==null?void 0:M.reason)||"").trim()==="subworkflow"||mo(Fn(c.trim(),y))},[De,c,Pr,ue==null?void 0:ue.current_node,(wo=ue==null?void 0:ue.waiting)==null?void 0:wo.reason]),p.useEffect(()=>{const y=String((Zn==null?void 0:Zn.flow_id)||"").trim();y&&(ya.trim()||eo(y))},[Zn,ya]),p.useEffect(()=>{const y=Pr.trim(),S=C.trim(),M=ya.trim();if(y){let q=!1;return ba(!0),fl(""),Te.get_workflow_flow(y).then(H=>{if(q)return;const V=H==null?void 0:H.flow;va(V&&typeof V=="object"?V:null)}).catch(H=>{q||(va(null),fl(String((H==null?void 0:H.message)||H||"Failed to load workflow flow")))}).finally(()=>{q||ba(!1)}),()=>{q=!0}}if(!S||!M){va(null),fl(""),ba(!1);return}let D=!1;return ba(!0),fl(""),Te.get_bundle_flow(S,M).then(q=>{if(D)return;const H=q==null?void 0:q.flow,V=H&&typeof H=="object"?H:null;va(V),V&&dl(te=>({...te,[M]:V}))}).catch(q=>{D||(va(null),fl(String((q==null?void 0:q.message)||q||"Failed to load flow")))}).finally(()=>{D||ba(!1)}),()=>{D=!0}},[Pr,C,ya,Te]),p.useEffect(()=>{const y=C.trim();if(!hl||!y||!wa)return;let S=!1;const M=3,D=ge=>{const me=Array.isArray(ge==null?void 0:ge.nodes)?ge.nodes:[],Ae=[];for(const Oe of me){const ze=Oe!=null&&Oe.data&&typeof Oe.data=="object"?Oe.data:{};if(String((ze==null?void 0:ze.nodeType)||(Oe==null?void 0:Oe.type)||"").trim()!=="subflow")continue;const Ve=(ze==null?void 0:ze.subflowId)||(ze==null?void 0:ze.flowId),rn=typeof Ve=="string"?Ve.trim():"";rn&&Ae.push(rn.includes(":")?rn.split(":",2)[1]:rn)}return Ae},q=new Set,H=new Set,V=(ge,me)=>{if(!(!ge||me>=M))for(const Ae of D(ge)){const Oe=String(Ae||"").trim();if(!Oe||q.has(Oe))continue;q.add(Oe),H.add(Oe);const ze=xa[Oe];ze&&V(ze,me+1)}};V(wa,0);const te=Array.from(H).filter(ge=>!xa[ge]).slice(0,20);return te.length?((async()=>{for(const ge of te){if(S)return;try{const me=await Te.get_bundle_flow(y,ge),Ae=me==null?void 0:me.flow,Oe=Ae&&typeof Ae=="object"?Ae:null;if(!Oe)continue;dl(ze=>ze[ge]?ze:{...ze,[ge]:Oe})}catch{}}})(),()=>{S=!0}):void 0},[hl,C,wa,xa,Te]);const Td=p.useMemo(()=>{const S=(Array.isArray(U==null?void 0:U.flows)?U==null?void 0:U.flows:[]).map(M=>String(M||"").trim()).filter(Boolean);return S.length?Array.from(new Set(S)).sort():Array.from(new Set($d)).sort()},[U,$d]);p.useEffect(()=>{ti&&ui.trim()&&(Po(""),di.current="")},[ti,c,ui]),p.useEffect(()=>{const y=Mr.trim(),S=c.trim();if(!(De&&!!y&&y!==S)){zs.current&&zs.current.abort(),zs.current=null,io.current=0,fi&&Sa("");return}if(fi===y)return;zs.current&&zs.current.abort();const D=new AbortController;zs.current=D,io.current=0,Sa(y),Jt({ts:Ct(),kind:"info",title:`Following run ${y} (status/events)`});let q=250;return(async()=>{for(;!D.signal.aborted;){try{await Te.stream_ledger(y,{after:io.current,on_step:V=>hd(y,V),signal:D.signal});return}catch(V){if(D.signal.aborted)break;const te=String((V==null?void 0:V.message)||V||"stream error");Jt({ts:Ct(),kind:"error",title:"Child ledger stream error (will retry)",preview:jt(te),data:{child_run_id:y,error:te}})}if(D.signal.aborted)break;await new Promise(V=>setTimeout(V,q)),q=Math.min(5e3,Math.floor(q*1.6))}})(),()=>{D.abort()}},[De,Mr,c,Te,fi]),p.useEffect(()=>{if(!De||!c.trim())return;let y=!1;const S=async()=>{if(!y&&!pl.current&&wr.length&&!(ct.current>Date.now())){pl.current=!0;try{const D=wr.map(te=>String(te||"").trim()).filter(Boolean);if(!D.length)return;const q=D.map(te=>({run_id:te,after:Number(Do.current[te]||0)})),H=await Te.get_ledger_batch({runs:q,limit:200}),V=H&&typeof H=="object"?H.runs:{};for(const te of D){if(y)return;const Le=V&&typeof V=="object"?V[te]:null,ge=Array.isArray(Le==null?void 0:Le.items)?Le.items:[],me=typeof(Le==null?void 0:Le.next_after)=="number"?Le.next_after:Number(Do.current[te]||0),Ae=Number(Do.current[te]||0);for(let Oe=0;Oe<ge.length;Oe++){const ze=ge[Oe];Xf(te,{cursor:Ae+Oe+1,record:ze})}Do.current[te]=me}}catch(D){if(y)return;Jt({ts:Ct(),kind:"error",title:"Subrun digest poll failed",preview:jt(String((D==null?void 0:D.message)||D||""))})}finally{pl.current=!1}}};S();const M=window.setInterval(()=>void S(),2e3);return()=>{y=!0,window.clearInterval(M),pl.current=!1}},[De,c,wr,Te]);const go=p.useMemo(()=>{const y=c.trim(),S=[];for(const M of an)!M||!M.record||S.push({run_id:y,cursor:M.cursor,record:M.record});for(const M of ss)!M||!M.record||S.push({run_id:String(M.run_id||"").trim(),cursor:M.cursor,record:M.record});return S},[an,ss,c]),Kc=p.useMemo(()=>{var S,M,D,q;const y={};for(const H of go){const V=String(H.run_id||((S=H.record)==null?void 0:S.run_id)||"").trim();!V||String(((D=(M=H.record)==null?void 0:M.effect)==null?void 0:D.type)||"").trim()!=="llm_call"||String(((q=H.record)==null?void 0:q.status)||"")!=="started"&&(y[V]=(y[V]||0)+1)}return y},[go]),mh=p.useMemo(()=>{const y=Mr.trim();if(y)return y;let S="",M=-1;for(const[D,q]of Object.entries(Kc))q>M&&(S=D,M=q);return S||c.trim()},[Kc,Mr,c]),Fl=(zf.trim()||mh).trim(),$s=p.useMemo(()=>{var q;const y=new Set,S=c.trim(),M=Mr.trim();S&&y.add(S),M&&y.add(M);for(const H of wr){const V=String(H||"").trim();V&&y.add(V)}for(const H of go){const V=String(H.run_id||((q=H.record)==null?void 0:q.run_id)||"").trim();V&&y.add(V)}const D=Array.from(y);return D.sort((H,V)=>S&&H===S&&V!==S?-1:S&&V===S&&H!==S?1:M&&H===M&&V!==M?-1:M&&V===M&&H!==M?1:H<V?-1:H>V?1:0),D},[c,Mr,wr,go]),t_=p.useMemo(()=>{var y;for(let S=an.length-1;S>=0;S--){const M=sb((y=an[S])==null?void 0:y.record);if(M)return M}return""},[an]);function n_(y){Ff(y);const S=c.trim();if(!(!S||typeof window>"u"))try{window.history.replaceState(null,"",JN(AN(S),y))}catch{}}const Rn=p.useMemo(()=>{const y=c.trim();return y&&(gn.find(S=>String(S.run_id||"").trim()===y)||Bn.find(S=>String(S.run_id||"").trim()===y))||null},[gn,Bn,c]),Vn=String((ue==null?void 0:ue.status)||(Rn==null?void 0:Rn.status)||"").trim(),s_=String(cs||((Bl=ue==null?void 0:ue.waiting)==null?void 0:Bl.reason)||(Rn==null?void 0:Rn.waiting_reason)||"").trim().toLowerCase(),Xe=!!(ue!=null&&ue.is_scheduled||Rn!=null&&Rn.is_scheduled),Xo=!!(ue!=null&&ue.paused||Rn!=null&&Rn.paused),Yc=Xe&&Vn.toLowerCase()==="waiting",Md=Yc&&s_==="until",_h=qn(Qr),Zo=Md&&_h!==null?Vy(_h-Date.now()):"",yo=a2(ue),qa=Xe&&Xo?"Suspended":Yc?"Scheduled":um({status:Vn,paused:Xo,stop_reason:yo});async function Rd(){if(A){Wf(!0),Ju("");try{const y=zo,S=y==="session"?String(Ea||yn||K||"").trim():"",M=y==="run"?String(ys||c||"").trim():"",D=QC(Ec),q=Aa.length?Aa.join(","):"",H=eE(xl),V=Math.max(0,Gr)*Yh,te=await Te.search_artifacts({scope:y,session_id:S||void 0,run_id:M||void 0,query:lo||void 0,artifact_kind:q||void 0,created_after:D||void 0,include_stats:!0,limit:Yh,offset:V,order_by:H.order_by,order:H.order}),Le=[],ge=new Set;for(const Ze of Array.isArray(te==null?void 0:te.items)?te.items:[]){const Ve=JC(Ze,"search");!Ve||ge.has(Ve.artifact_id)||(ge.add(Ve.artifact_id),Le.push(Ve))}const me=te!=null&&te.stats&&typeof te.stats=="object"?te.stats:{},Ae=Number((me==null?void 0:me.total)??(te==null?void 0:te.total)??Le.length),Oe=iw(te);let ze=Oe;if(Aa.length)try{const Ze=await Te.search_artifacts({scope:y,session_id:S||void 0,run_id:M||void 0,query:lo||void 0,created_after:D||void 0,include_stats:!0,limit:1,offset:0,order_by:H.order_by,order:H.order});ze=iw(Ze)}catch{ze=Oe}yl(Number.isFinite(Ae)?Math.max(0,Ae):Le.length),Ku(Number((me==null?void 0:me.total_bytes)??(me==null?void 0:me.byte_total)??0)||0),Ca(Oe),Fo(ze),Nn(Le),Xu(Ze=>{var Ve;return Ze&&Le.some(rn=>rn.artifact_id===Ze)?Ze:((Ve=Le[0])==null?void 0:Ve.artifact_id)||""})}catch(y){Ju(String((y==null?void 0:y.message)||y||"Failed to load artifacts")),Nn([]),yl(0),Ku(0),Ca({}),Fo({}),Xu("")}finally{Wf(!1)}}}async function Ld(){if(A){Mi(!0),Wo("");try{const y=await Te.audit_log_tail({max_bytes:16e4}),S=typeof(y==null?void 0:y.bytes)=="number"?Number(y.bytes):0,M=!!(y!=null&&y.truncated);Sl(String((y==null?void 0:y.content)||"")),ed(`${S.toLocaleString()} bytes${M?" (tail)":""}`)}catch(y){Wo(String((y==null?void 0:y.message)||y||"Failed to load audit log")),Sl(""),ed("")}finally{Mi(!1)}}}async function Id(y){if(!A)return;const S=String(y||vr||ys||c||"").trim();if(!S){Yr([]),Li(""),Bs("Select a run in Activity or Artifacts to load its runtime ledger.");return}$c(!0),Bs("");try{const M=await Te.get_ledger(S,{after:0,limit:2e3}),D=Array.isArray(M.items)?M.items:[];Yr(D.map((H,V)=>({cursor:V+1,record:H})));const q=typeof M.next_after=="number"?Number(M.next_after):D.length;Li(`${D.length.toLocaleString()} record${D.length===1?"":"s"}${q>=2e3?" (first 2,000)":""}`)}catch(M){Bs(String((M==null?void 0:M.message)||M||"Failed to load run ledger")),Yr([]),Li("")}finally{$c(!1)}}p.useEffect(()=>{A&&e==="runtime"&&Rd()},[A,e,zo,Ea,ys,lo,Aa,Ec,xl,Gr]),p.useEffect(()=>{A&&(Gf||mi||e==="runtime"&&Ld())},[A,e,tr]),p.useEffect(()=>{if(!A||e!=="runtime"||gl!=="logs"||qo!=="run_ledger"&&qo!=="provider_calls")return;const y=String(vr||ys||c||"").trim();y&&Id(y)},[A,e,gl,qo,vr,ys,c]);const wi=p.useMemo(()=>{const y=new Map;for(const S of[...Bn,...gn]){const M=String(S.run_id||"").trim();M&&y.set(M,S)}for(const S of wr){const M=String(S||"").trim();!M||y.has(M)||y.set(M,{run_id:M,workflow_id:null,status:"",created_at:null,updated_at:null,ledger_len:null,parent_run_id:so.current[M]||null,session_id:yn||null})}return c.trim()&&!y.has(c.trim())&&y.set(c.trim(),{run_id:c.trim(),workflow_id:typeof(ue==null?void 0:ue.workflow_id)=="string"?String(ue.workflow_id):null,status:typeof(ue==null?void 0:ue.status)=="string"?String(ue.status):"",created_at:typeof(ue==null?void 0:ue.created_at)=="string"?String(ue.created_at):null,updated_at:typeof(ue==null?void 0:ue.updated_at)=="string"?String(ue.updated_at):null,ledger_len:an.length||null,parent_run_id:typeof(ue==null?void 0:ue.parent_run_id)=="string"?String(ue.parent_run_id):null,session_id:typeof(ue==null?void 0:ue.session_id)=="string"?String(ue.session_id):yn||null}),Array.from(y.values()).sort((S,M)=>{const D=qn(S.updated_at||S.created_at)??0;return(qn(M.updated_at||M.created_at)??0)-D})},[gn,Bn,c,ue,an.length,wr,yn]),Od=p.useMemo(()=>IE(wi,{query:wc,filter:Du,group_by:Fu,workflow_label_by_id:as,parent_hint:y=>so.current[y]||""}),[wi,wc,Du,Fu,as]),zn=p.useMemo(()=>{const y={};for(const S of wi){const M=String(S.run_id||"").trim();M&&(y[M]=S)}return y},[wi]),kr=String(vr||ys||c||"").trim(),vi=kr&&zn[kr]||null,Pd=String(Ea||(vi==null?void 0:vi.session_id)||yn||K||"").trim(),Dd=p.useMemo(()=>kc.map(y=>mm(y,zn,as)),[kc,zn,as]);p.useEffect(()=>{Uo(0)},[lo,Aa,Ec,ys,xl,co,zo,Ea]);const ni=Math.max(1,Math.ceil(jc/Yh)),Ha=Math.min(Math.max(0,Gr),ni-1);p.useEffect(()=>{Gr!==Ha&&Uo(Ha)},[Gr,Ha]);const Ts=p.useMemo(()=>Dd,[Dd,Ha]),r_=p.useMemo(()=>{const y={};for(const S of Ts){const M=co==="type"?Ip(S,zn,as):XC(S,co);y[M]||(y[M]=[]),y[M].push(S)}return Object.entries(y).map(([S,M])=>({key:S,items:M})).sort((S,M)=>{var D,q;if(co==="time"){const H=qn((D=S.items[0])==null?void 0:D.created_at)??0,V=qn((q=M.items[0])==null?void 0:q.created_at)??0;if(H!==V)return V-H}return S.key.localeCompare(M.key)})},[Ts,co,zn,as]),Va=p.useMemo(()=>{const y=Hf.trim();return y?Ts.find(S=>S.artifact_id===y)||Ts[0]||null:Ts[0]||null},[Ts,Hf]);p.useEffect(()=>{e!=="runtime"||gl!=="artifacts"||fd(Va)},[e,gl,Va==null?void 0:Va.artifact_id]),p.useEffect(()=>()=>{Kr.url&&URL.revokeObjectURL(Kr.url)},[Kr.url]);const ph=p.useMemo(()=>wi.filter(y=>ju(y.status)),[wi]);p.useEffect(()=>{if(e!=="settings"&&e!=="launch"||!A||X)return;let y=!1;return(async()=>{const[S,M]=await Promise.all([Te.list_skills(),Te.list_mcp_servers()]);y||(Z(S),ye(M),ie(!0))})(),()=>{y=!0}},[e,A,X]);function zl(){ul&&window.setTimeout(()=>{var y;return(y=Df.current)==null?void 0:y.scrollIntoView({block:"start"})},60)}function Jc(y){Qi(y),zl()}const i_=[{id:"board",label:"Board",icon:s.jsx(et,{name:"board",size:16})},{id:"observe",label:"Observe",icon:s.jsx(et,{name:"history",size:16})},{id:"runtime",label:"System",icon:s.jsx(et,{name:"server",size:16})},{id:"launch",label:"Launch",icon:s.jsx(et,{name:"send",size:16})},{id:"automations",label:"Automations",icon:s.jsx(et,{name:"refresh",size:16})}],Xc={board:"Board",observe:"Observe",runtime:"System",launch:"Launch",automations:"Automations",settings:"Settings"},Zc=s.jsxs(s.Fragment,{children:[Jr?s.jsxs("details",{className:"launch_capabilities",style:{marginTop:"10px"},children:[s.jsxs("summary",{className:"help_text muted",style:{cursor:"pointer"},children:["Capabilities",os.length?` · ${os.length} skill${os.length===1?"":"s"}`:""]}),s.jsx("div",{className:"help_text muted",style:{marginTop:"8px"},children:"Skills attach knowledge procedures to this run. The gateway resolves selections through the trust gate at start: validated skills activate, unverified ones are held for review, blocked ones never ride."}),R===null?s.jsx("div",{className:"help_text muted",style:{marginTop:"8px"},children:"This gateway does not serve a skills inventory yet — the shelf lights up here when it ships."}):R.length?s.jsx("div",{className:"launch_skill_list",children:R.map(y=>{var q;const S=os.includes(y.name),M=y.blocked===!0,D=y.requires_review===!0&&!M;return s.jsxs("label",{className:`launch_skill_row ${M?"is_blocked":""} ${S?"is_on":""}`,title:[y.description||"",y.tree_hash?`tree ${y.tree_hash.slice(0,16)}…`:"",M&&((q=y.reasons)!=null&&q.length)?`blocked: ${y.reasons.join("; ")}`:""].filter(Boolean).join(`
144
- `),children:[s.jsx("input",{type:"checkbox",checked:S,disabled:M||ut||dt||je,onChange:H=>{const V=H.target.checked?Array.from(new Set([...os,y.name])):os.filter(te=>te!==y.name);Tn("skills",V.length?V:void 0)}}),s.jsx("span",{className:"launch_skill_name",children:y.name}),y.trust_level?s.jsx("span",{className:`chip ${M?"danger":D?"warn":"muted"}`,children:M?"blocked":D?"review":y.trust_level}):null,y.description?s.jsx("span",{className:"launch_skill_desc",children:y.description}):null]},y.name)})}):s.jsx("div",{className:"help_text muted",style:{marginTop:"8px"},children:"The gateway's skills shelf is empty."}),os.length?s.jsx("div",{className:"help_text muted",style:{fontSize:"var(--font-size-xxs)",marginTop:"6px"},children:"Selected skills ride the run as input_data.skills; the resolved verdicts land in the run's record."}):null]}):null,s.jsxs("details",{style:{marginTop:"10px"},children:[s.jsx("summary",{className:"help_text muted",style:{cursor:"pointer"},children:"Workspace"}),s.jsx("div",{className:"help_text muted",style:{marginTop:"8px"},children:"Controls what the agent can access via filesystem tools."}),s.jsxs("div",{className:"launch_grid",style:{marginTop:"8px"},children:[s.jsxs("div",{className:"launch_grid_cell",style:{gridColumn:"1 / -1"},children:[s.jsx("label",{className:"launch_label",children:"Workspace Root"}),s.jsx("input",{className:"mono",value:ld,onChange:y=>Tn("workspace_root",y.target.value),placeholder:"/path/to/workspace",disabled:ut||dt}),s.jsx("div",{className:"help_text muted",style:{fontSize:"var(--font-size-xxs)"},children:"Empty = gateway default (isolated per-run workspace)"})]}),s.jsxs("div",{className:"launch_grid_cell",children:[s.jsx("label",{className:"launch_label",children:"Access Mode"}),s.jsxs("select",{className:"mono",value:(Lc||"workspace_only").trim()||"workspace_only",onChange:y=>Tn("workspace_access_mode",y.target.value),disabled:ut||dt,children:[s.jsx("option",{value:"workspace_only",children:"workspace_only"}),s.jsx("option",{value:"workspace_or_allowed",children:"workspace_or_allowed"}),s.jsx("option",{value:"all_except_ignored",children:"all_except_ignored"})]}),s.jsx("div",{className:"help_text muted",style:{fontSize:"var(--font-size-xxs)"},children:"workspace_only: absolute paths must stay under root. workspace_or_allowed: allow additional roots."})]})]}),(Lc||"").trim()==="workspace_or_allowed"?s.jsxs("div",{className:"field",style:{marginTop:"8px"},children:[s.jsx("label",{className:"launch_label",children:"Allowed Paths"}),s.jsx("textarea",{className:"mono",rows:3,value:cd,onChange:y=>Tn("workspace_allowed_paths",y.target.value),placeholder:`/path/to/project
145
- /path/to/workspace`,disabled:ut||dt,spellCheck:!1,autoCorrect:"off",autoCapitalize:"off",autoComplete:"off"}),s.jsx("div",{className:"help_text muted",style:{fontSize:"var(--font-size-xxs)"},children:"Newline-separated directories (absolute or relative to workspace_root)"})]}):null,s.jsxs("div",{className:"field",style:{marginTop:"8px"},children:[s.jsx("label",{className:"launch_label",children:"Ignored Paths"}),s.jsx("textarea",{className:"mono",rows:3,value:Da,onChange:y=>Tn("workspace_ignored_paths",y.target.value),placeholder:`node_modules
146
- runtime
147
- secret`,disabled:ut||dt,spellCheck:!1,autoCorrect:"off",autoCapitalize:"off",autoComplete:"off"}),s.jsx("div",{className:"help_text muted",style:{fontSize:"var(--font-size-xxs)"},children:"Newline-separated paths to block (absolute or relative to workspace_root)"})]})]}),s.jsxs("details",{className:"launch_bundles",style:{marginTop:"10px"},children:[s.jsx("summary",{className:"help_text muted",style:{cursor:"pointer"},children:"Workflow bundles"}),s.jsxs("div",{className:"launch_workflow_bar",style:{marginTop:"8px"},children:[s.jsx("input",{ref:it,type:"file",accept:".flow",style:{display:"none"},onChange:y=>{const S=y.target.files&&y.target.files.length?y.target.files[0]:null;S&&Dc(S)}}),s.jsx("button",{type:"button",className:"btn launch_btn_upload",onClick:()=>{var y;return(y=it.current)==null?void 0:y.click()},disabled:!A||W||Cr||ut||dt,title:"Upload a .flow bundle",children:Cr?"…":"Upload .flow"}),s.jsxs("button",{type:"button",className:"btn launch_btn_reload",onClick:()=>void Dn(),disabled:!A||W||kt||ut||dt,title:"Reload picks up server-side edits",children:[s.jsx(et,{name:"refresh",size:14}),kt?"…":"Reload bundles"]})]})]})]});function jr(y){t("observe"),Qi("ledger"),Zr(y)}const sn={on_select:y=>void Tt.select(y),on_row_action:(y,S)=>{if(S==="discuss"||S==="edit")throw new Error(`${S} is routed by AutomationsPage (route_row_action), not the app handlers.`);if(S==="archive"){Tt.ask_archive(y.automation_id);return}Tt.row_action(y,S)},on_legacy_action:(y,S)=>{if(S==="open_run"){jr(y.automation_id);return}if(S==="recreate"){pd(y.automation_id).catch(M=>Tt.report_error(M));return}Tt.legacy_action(y,S)},on_confirm_archive:y=>void Tt.row_action(y,"archive"),on_cancel_archive:()=>Tt.ask_archive(""),on_status_filter:y=>void Tt.set_status_filter(y),on_refresh:()=>void Tt.refresh(),on_new:()=>{pe("automate"),t("launch")},on_show_archived:y=>Tt.set_show_archived(y)};return s.jsxs("div",{className:`app-shell shell${xc?" nav_open":""}`,children:[vc&&xc?s.jsx("div",{className:"shell_nav_backdrop","aria-hidden":"true",onClick:()=>_a(!1)}):null,s.jsxs("aside",{className:"shell_sidebar",id:"shell_nav",ref:pa,...ma.attrs.aside,children:[s.jsxs("div",{className:"shell_brand",title:"AbstractObserver (Web/PWA)",children:[s.jsx("span",{className:"logo-icon shell_brand_mark","aria-hidden":"true",children:s.jsxs("svg",{viewBox:"0 0 24 24",width:"20",height:"20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[s.jsx("ellipse",{cx:"12",cy:"12",rx:"9",ry:"4.2",transform:"rotate(-18 12 12)",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",opacity:"0.75"}),s.jsx("circle",{cx:"12",cy:"12",r:"4.7",fill:"currentColor",opacity:"0.95"}),s.jsx("circle",{cx:"10.3",cy:"10.7",r:"1.6",fill:"#ffffff",opacity:"0.18"}),s.jsx("circle",{cx:"19",cy:"13.6",r:"1.2",fill:"currentColor"})]})}),s.jsx("span",{className:"shell_brand_name",children:"Observer"}),s.jsx("button",{type:"button",className:"shell_nav_close","aria-label":"Close navigation",title:"Close navigation",onClick:()=>_a(!1),children:s.jsx(et,{name:"x",size:16})})]}),s.jsxs("nav",{className:"shell_nav",children:[i_.map(y=>s.jsxs("button",{className:`shell_nav_item ${e===y.id?"active":""}`,onClick:()=>{t(y.id),_a(!1)},type:"button",children:[s.jsx("span",{className:"shell_nav_icon",children:y.icon}),s.jsx("span",{className:"shell_nav_label",children:y.label})]},y.id)),s.jsxs("a",{className:"shell_nav_item",href:l,target:"_blank",rel:"noreferrer",title:"Open the entity app (memory graph + visits)",children:[s.jsx("span",{className:"shell_nav_icon",children:s.jsx(et,{name:"bot",size:16})}),s.jsx("span",{className:"shell_nav_label",children:"Entities ↗"})]}),s.jsxs("button",{className:`shell_nav_item ${e==="settings"?"active":""}`,onClick:()=>{t("settings"),_a(!1)},type:"button",children:[s.jsx("span",{className:"shell_nav_icon",children:s.jsx(et,{name:"settings",size:16})}),s.jsx("span",{className:"shell_nav_label",children:"Settings"})]})]}),s.jsx("div",{className:"shell_sidebar_footer",children:s.jsxs("div",{className:"shell_connection shell_connection_passive",title:A?"Gateway connected":W?"Gateway: connecting…":"Gateway: signed out",children:[s.jsx("span",{className:`gateway_led ${A?"ok":W?"warn":"err"}`,"aria-hidden":"true"}),s.jsx("span",{className:`shell_connection_label ${A&&((Ka=(Qc=F==null?void 0:F.gateway)==null?void 0:Qc.principal)!=null&&Ka.user_id)?"mono":""}`,children:A?((eu=(Hs=F==null?void 0:F.gateway)==null?void 0:Hs.principal)==null?void 0:eu.user_id)||(n.gateway_auth_mode==="direct"?"direct dev":"connected"):W?"connecting…":"signed out"})]})})]}),s.jsxs("div",{className:"shell_main",...ma.attrs.main,children:[s.jsxs("header",{className:"shell_header",children:[s.jsx("button",{ref:Pf,type:"button",className:"shell_nav_toggle","data-nav-toggle":!0,"aria-label":"Open navigation","aria-controls":"shell_nav","aria-expanded":xc,title:"Navigation",onClick:()=>_a(!0),children:s.jsx(et,{name:"list",size:18})}),s.jsx("div",{className:"shell_header_title",children:Xc[e]||"Observer"}),s.jsxs("div",{className:"shell_header_actions",children:[o?s.jsx("monitor-gpu",{ref:u,mode:"icon","history-size":"5","tick-ms":"1500","base-url":n.gateway_auth_mode==="session"?"":n.gateway_url,title:"GPU usage (host)",style:{"--monitor-gpu-width":"34px","--monitor-gpu-bars-height":"22px","--monitor-gpu-padding":"2px 4px","--monitor-gpu-radius":"999px","--monitor-gpu-bg":"rgba(0,0,0,0.22)","--monitor-gpu-border":"rgba(255,255,255,0.16)",flexShrink:0}}):null,s.jsx(sj,{assistant:{open:Sn,onToggle:()=>ns(y=>!y),label:"Observer assistant (docs-grounded)"},appearance:{onOpen:()=>It(!0)},about:{identity:rd,extraRows:Yf,onOpen:Oa},connection:{phase:P.phase,signingOut:P.signingOut,onConnect:()=>P.openModal(),onDisconnect:()=>Al()}})]})]}),s.jsx(Lk,{...P.modalProps}),s.jsx(aj,{open:Wt,onClose:()=>It(!1),value:en,onChange:bn}),s.jsx(vN,{open:Sn,onClose:()=>ns(!1),connected:A,topOffset:44,gateway:Te}),s.jsxs("div",{className:"app-body shell_content",children:[e==="board"?A?s.jsx(PL,{gateway_connected:A,runs:Bn,all_runs:gn,runs_refreshed_at:Kn,entities:Nr,entities_total:le,entities_error:Ye,refreshing:wn,on_refresh:()=>void ls(Te,{force:!0}),on_open_run:y=>{t("observe"),Qi("ledger"),Zr(y)},on_resume_wait:Go,on_open_automation:y=>{t("automations"),Tt.refresh().then(()=>Tt.select(y))},entity_app_href:l,on_read_diary:(y,S)=>Te.read_entity_diary_entry(y,S),phase_graph:zc}):s.jsx("div",{className:"page page_scroll",children:s.jsx("div",{className:"page_inner constrained",children:s.jsxs("div",{className:"card mc_hero",children:[s.jsx("div",{className:"title",children:s.jsx("h1",{children:"Connect to your gateway"})}),s.jsxs("p",{className:"muted",children:["Mission Control shows every run and entity on one board — but nothing is connected yet.",$?` Last attempt: ${$}`:""]}),s.jsxs("div",{className:"row",style:{gap:"8px",alignItems:"center"},children:[s.jsx("button",{className:"btn primary",onClick:()=>P.openModal(),disabled:W,children:W?"Connecting…":"Sign in"}),s.jsx("button",{className:"btn",onClick:()=>void Xr({open_modal_if_needed:!0}),disabled:W,title:"Retry with an existing browser session or a direct dev token",children:"Retry connection"})]})]})})}):null,e==="settings"?s.jsx("div",{className:"page page_scroll",children:s.jsxs("div",{className:"page_inner settings_col",children:[s.jsxs("section",{className:"pane",children:[s.jsxs("div",{className:"pane_header",children:[s.jsx("span",{className:"pane_title",children:"Gateway"}),s.jsx("span",{className:"pane_spacer"}),s.jsx("span",{className:`chip ${A?"ok":"warn"}`,children:$v(F).label})]}),s.jsxs("div",{className:"pane_body settings_body",children:[s.jsxs("div",{className:"settings_row",children:[s.jsxs("div",{className:"settings_row_main",children:[s.jsx("div",{className:"settings_row_title",children:"Connection"}),s.jsx("div",{className:"settings_row_help",children:"The shared AbstractFramework sign-in: a gateway user token exchanges for an HTTP-only browser session. Raw tokens are never stored."})]}),s.jsxs("div",{className:"settings_row_actions",children:[s.jsx("button",{className:"btn",onClick:()=>P.openModal(),children:"Manage connection…"}),A?s.jsx("button",{className:"btn",onClick:()=>Al(),title:"Sign this browser out of the gateway (this app's session only)",children:"Sign out"}):null]})]}),$?s.jsx("div",{className:"warn_callout",children:$}):null,s.jsx("div",{className:"settings_row",children:s.jsx(mC,{checked:n.auto_connect_gateway,onChange:y=>r(S=>({...S,auto_connect_gateway:y}))})}),s.jsxs("details",{className:"settings_advanced",children:[s.jsx("summary",{children:"Advanced: direct dev connection (bearer token, cross-origin)"}),s.jsxs("div",{className:"field",style:{marginTop:"8px"},children:[s.jsx("label",{children:"Gateway URL"}),s.jsx("input",{value:n.gateway_url,onChange:y=>r(S=>({...S,gateway_url:y.target.value})),placeholder:Sm})]}),s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Dev bearer token"}),s.jsx("input",{type:"password",value:n.auth_token,onChange:y=>r(S=>({...S,auth_token:y.target.value,gateway_auth_mode:"direct"})),placeholder:"development only — prefer the sign-in dialog"})]}),s.jsx("button",{className:"btn",onClick:()=>void Xr({prefer_direct:!0}),disabled:W,children:W?"Connecting…":"Connect directly"})]})]})]}),s.jsxs("section",{className:"pane",children:[s.jsxs("div",{className:"pane_header",children:[s.jsx("span",{className:"pane_title",children:"Assistant"}),s.jsx("span",{className:"pane_spacer"}),s.jsx("span",{className:"chip muted",children:"docs Q&A + run Ask"})]}),s.jsxs("div",{className:"pane_body settings_body",children:[s.jsx("div",{className:"settings_row_help",style:{marginTop:0},children:"The model answering the header assistant and the run page's Ask tab. Blank fields follow the gateway defaults."}),s.jsx(vk,{className:"field",providerLabel:"Provider",modelLabel:"Model",providerPlaceholder:"(gateway default)",modelPlaceholder:"(gateway default)",provider:n.maintenance_ai_provider,model:n.maintenance_ai_model,providers:Oi,models:Cl.models,loadingProviders:W,loadingModels:Oc,modelError:Ic?Cl.error:"",allowCustomProvider:!0,allowCustomModel:!0,allowGatewayDefault:!0,gatewayDefaultLabel:"(gateway default)",onChange:y=>r(S=>({...S,maintenance_ai_provider:y.provider,maintenance_ai_model:y.model}))}),s.jsx("div",{className:"settings_subhead",children:"Skills"}),R===null?s.jsx("div",{className:"settings_row_help",children:A?X?"The gateway does not serve a skills inventory yet — the abstractskill shelf list lights up here the day it ships.":"Probing the gateway for the skills inventory…":"Connect to the gateway to list installable skills (abstractskill shelf)."}):R.length?s.jsx("div",{className:"settings_choice_list",children:R.map(y=>{const S=n.assistant_skill_names.includes(y.name);return s.jsx(_C,{name:y.name,version:y.version,description:y.description,checked:S,onChange:M=>r(D=>({...D,assistant_skill_names:M?Array.from(new Set([...D.assistant_skill_names,y.name])):D.assistant_skill_names.filter(q=>q!==y.name)}))},y.name)})}):s.jsx("div",{className:"settings_row_help",children:"The gateway serves an empty skills inventory."}),s.jsx("div",{className:"settings_row_help",children:"Selected skills ride the assistant's runs once the gateway's skills-attachment lane serves them; the selection persists here meanwhile."}),s.jsx("div",{className:"settings_subhead",children:"MCP servers"}),s.jsx("div",{className:"settings_row_help",style:{marginTop:0},children:"Remote tool endpoints the assistant may call. The gateway does not serve an MCP inventory yet — one manual endpoint is supported (advanced / potentially dangerous: it executes tool waits from this browser)."}),s.jsxs("div",{className:"settings_mcp_row",children:[s.jsx("input",{className:"mono",value:n.worker_url,onChange:y=>r(S=>({...S,worker_url:y.target.value})),placeholder:"https://your-mcp-worker-endpoint"}),s.jsx("input",{className:"mono",type:"password",value:n.worker_token,onChange:y=>r(S=>({...S,worker_token:y.target.value})),placeholder:"Bearer token (optional)"}),s.jsx("span",{className:`chip ${n.worker_url.trim()?"ok":"muted"}`,children:n.worker_url.trim()?"configured":"none"})]})]})]})]})}):null,e==="launch"?s.jsx("div",{className:"page page_scroll",children:s.jsx("div",{className:"page_inner constrained",children:s.jsxs("div",{className:"card",children:[s.jsx(W2,{mode:he,automate_available:qe.available,automate_reason:qe.reason,on_change:pe}),he==="automate"&&!qe.available&&A?s.jsx("div",{className:"warn_callout",role:"note",children:qe.reason}):null,he==="automate"&&ht.length?s.jsx("div",{className:"help_text",role:"note",children:ht.map(y=>s.jsx("div",{children:y},y))}):null,A?null:s.jsxs("div",{className:"warn_callout",children:["Not connected."," ",s.jsx("button",{className:"btn primary",onClick:()=>P.openModal(),children:"Sign in"})," ","to launch workflows on this gateway."]}),he==="automate"?s.jsx("div",{className:"section_title",children:"What"}):null,s.jsx("div",{className:"launch_workflow_bar",children:s.jsx(ox,{id:"launch-workflow-picker",className:"launch_workflow_picker",interfaceId:null,defaultInterface:tc,ariaLabel:"Workflow",workflows:Fa,value:Ky(Jr,((ea=Fa.data)==null?void 0:ea.entries)??[]),currentLabel:Jr&&!Ky(Jr,((xi=Fa.data)==null?void 0:xi.entries)??[])?{name:as[ud]||ud}:null,unavailableReason:A?W?"Loading workflows…":null:"Sign in to load workflows.",onChange:(y,S)=>{const M=p2(y,S);M&&_d(M)}})}),s.jsxs("div",{className:"field",children:[Zn!=null&&Zn.description?s.jsx("div",{className:"help_text muted",style:{fontSize:"var(--font-size-sm)",marginTop:"6px"},children:String(Zn.description)}):null,Y?s.jsx("div",{className:"help_text muted",style:{fontSize:"var(--font-size-sm)"},children:"Loading workflow…"}):null,ce?s.jsx("div",{className:"mono",style:{color:"rgba(239, 68, 68, 0.9)",fontSize:"var(--font-size-sm)"},children:ce}):null]}),s.jsx("div",{className:"section_divider"}),s.jsx("div",{className:"section_title",children:"Inputs"}),Jr?ft===null?s.jsxs("div",{className:"log_item",style:{borderColor:"rgba(239, 68, 68, 0.35)",marginTop:"10px"},children:[s.jsxs("div",{className:"meta",children:[s.jsx("span",{className:"mono",children:"input error"}),s.jsx("span",{className:"mono",children:Ct()})]}),s.jsx("div",{className:"body mono",children:"Invalid input JSON — reselect the workflow to reset its inputs."})]}):Ir?s.jsx("div",{className:"launch_inputs",children:(()=>{const y=ut||dt,S=[],M=[];for(const H of _i){if(!H||typeof H!="object")continue;const V=String(H.id||"").trim();if(!V||he==="automate"&&Fx.includes(V))continue;const te=String(H.type||"").trim().toLowerCase();te==="tools"||te==="skills"||te==="mcp"||te==="mcp_servers"||V==="skills"||V==="mcp"||V==="mcp_servers"||te==="array"||Ii(te)||V==="prompt"||V==="system"?S.push(H):M.push(H)}const D=H=>String(H||"").trim().replace(/_/g," ").replace(/\b\w/g,V=>V.toUpperCase()),q=(H,V)=>{const te=String(H.id||"").trim();if(!te)return null;const Le=String(H.label||te).trim()||te,ge=Le===te?D(te):Le,me=String(H.type||"").trim().toLowerCase(),Ae=Object.prototype.hasOwnProperty.call(H,"default"),Oe=Ae?H.default:void 0,ze=Ae?typeof Oe=="string"?Oe:cr(Oe,80):"",Ze=ft==null?void 0:ft[te],Ve=Ae?`${ze}`:"";if(me==="tools"){if(he==="automate"&&te==="tools")return null;const Be=Array.isArray(Ze)?Ze.map(hn=>String(hn||"").trim()).filter(Boolean):[],bt=Array.isArray(Oe)?Oe.map(hn=>String(hn||"").trim()).filter(Boolean):[],xn=Array.from(new Set([...pi,...Be,...bt])).sort();return s.jsxs("div",{className:"launch_field_wide",children:[s.jsx("label",{className:"launch_label",children:ge}),s.jsx(vp,{options:xn,value:Be,disabled:y,placeholder:"(no tools selected)",onChange:hn=>Tn(te,hn)})]},te)}if(me==="skills"||te==="skills")return null;if(me==="mcp"||me==="mcp_servers"||te==="mcp"||te==="mcp_servers"){const Be=Array.isArray(Ze)?Ze.map(hn=>String(hn||"").trim()).filter(Boolean):[];if(ne===null&&!Be.length)return s.jsxs("div",{className:"launch_field_wide",children:[s.jsx("label",{className:"launch_label",children:ge}),s.jsx("div",{className:"help_text muted",children:"This gateway does not serve an MCP server inventory yet — MCP selection lights up here when it ships."})]},te);const bt=(ne||[]).map(hn=>hn.name),xn=Array.from(new Set([...bt,...Be])).sort();return s.jsxs("div",{className:"launch_field_wide",children:[s.jsx("label",{className:"launch_label",children:ge}),s.jsx(vp,{options:xn,value:Be,disabled:y,placeholder:"(no MCP servers selected)",onChange:hn=>Tn(te,hn)})]},te)}if(me==="provider"||me==="provider_text"){const Be=typeof Ze=="string"?String(Ze):"";return s.jsxs("div",{className:V||"launch_field",children:[s.jsx("label",{className:"launch_label",children:ge}),s.jsxs("select",{value:Be,onChange:bt=>Tn(te,bt.target.value),disabled:y,children:[s.jsx("option",{value:"",children:Ve||"(select)"}),Jf.map(bt=>s.jsx("option",{value:bt,children:bt},bt))]})]},te)}if(me==="model"||me==="model_text"){const Be=typeof Ze=="string"?String(Ze):"",bt=String((ft==null?void 0:ft.provider)||"").trim(),xn=bt?At[bt]:void 0,hn=xn&&Array.isArray(xn.models)?xn.models.map(Ms=>String(Ms||"").trim()).filter(Boolean):[];return s.jsxs("div",{className:V||"launch_field",children:[s.jsx("label",{className:"launch_label",children:ge}),hn.length?s.jsxs("select",{value:Be,onChange:Ms=>Tn(te,Ms.target.value),disabled:y,children:[s.jsx("option",{value:"",children:Ve||"(select)"}),hn.map(Ms=>s.jsx("option",{value:Ms,children:Ms},Ms))]}):s.jsx("input",{value:Be,onChange:Ms=>Tn(te,Ms.target.value),placeholder:Ve||"model id",disabled:y})]},te)}if(me==="boolean"){const Be=typeof Ze=="boolean"?Ze?"true":"false":"";return s.jsxs("div",{className:V||"launch_field",children:[s.jsx("label",{className:"launch_label",children:ge}),s.jsxs("select",{value:Be,onChange:bt=>{const xn=String(bt.target.value||"").trim();xn?Tn(te,xn==="true"):Tn(te,void 0)},disabled:y,children:[s.jsx("option",{value:"",children:Ve||"(default)"}),s.jsx("option",{value:"true",children:"Yes"}),s.jsx("option",{value:"false",children:"No"})]})]},te)}if(me==="number"){const Be=typeof Ze=="number"&&Number.isFinite(Ze)?String(Ze):"";return s.jsxs("div",{className:V||"launch_field",children:[s.jsx("label",{className:"launch_label",children:ge}),s.jsx("input",{type:"number",value:Be,onChange:bt=>{const xn=String(bt.target.value||"").trim();if(!xn){Tn(te,void 0);return}const hn=Number(xn);Number.isFinite(hn)&&Tn(te,hn)},placeholder:Ve,disabled:y})]},te)}if(me==="array"){const Be=Array.isArray(Ze)?Ze.map(bt=>String(bt||"").trim()).filter(Boolean).join(`
148
- `):"";return s.jsxs("div",{className:"launch_field_wide",children:[s.jsx("label",{className:"launch_label",children:ge}),s.jsx("textarea",{className:"mono",value:Be,onChange:bt=>{const xn=String(bt.target.value||"").split(/\r?\n/g).map(hn=>String(hn||"").trim()).filter(Boolean);Tn(te,xn.length?xn:void 0)},placeholder:Ve||"(one item per line)",rows:2,disabled:y})]},te)}if(Ii(me)){const Be=typeof cn[te]=="string"?cn[te]:"",bt=String(Hr[te]||"").trim();return s.jsxs("div",{className:"launch_field_wide",children:[s.jsxs("label",{className:"launch_label",children:[ge," ",s.jsx("span",{className:"launch_label_type",children:me})]}),s.jsx("textarea",{className:"mono",value:Be,onChange:xn=>{const hn=String(xn.target.value??"");Ds(ds=>({...ds,[te]:hn}));const Ms=hn.trim();if(!Ms){rs(ds=>{const Dr={...ds};return delete Dr[te],Dr}),Tn(te,void 0);return}try{const ds=JSON.parse(Ms);rs(Dr=>{const Ya={...Dr};return delete Ya[te],Ya}),Tn(te,ds)}catch(ds){rs(Dr=>({...Dr,[te]:String((ds==null?void 0:ds.message)||ds||"Invalid JSON")}))}},placeholder:Ve||"{...}",rows:3,disabled:y}),bt?s.jsx("div",{className:"launch_field_error",children:bt}):null]},te)}const rn=typeof Ze=="string"?String(Ze):"";return te==="prompt"||te==="system"?s.jsxs("div",{className:"launch_field_wide",children:[s.jsx("label",{className:"launch_label",children:ge}),s.jsx("textarea",{value:rn,onChange:Be=>Tn(te,Be.target.value),placeholder:Ve||(te==="prompt"?"What should the agent do?":"System instructions (optional)"),rows:3,disabled:y})]},te):s.jsxs("div",{className:V||"launch_field",children:[s.jsx("label",{className:"launch_label",children:ge}),s.jsx("input",{value:rn,onChange:Be=>Tn(te,Be.target.value),placeholder:Ve,disabled:y})]},te)};return S.sort((H,V)=>{const te={system:0,prompt:1,tools:2};return(te[String(H.id||"")]??10)-(te[String(V.id||"")]??10)}),s.jsxs(s.Fragment,{children:[S.map(H=>q(H)),M.length>0?s.jsx("div",{className:"launch_grid",children:M.map(H=>q(H,"launch_grid_cell"))}):null]})})()}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"field",style:{marginTop:"10px"},children:[s.jsx("label",{children:"Prompt (common)"}),s.jsx("textarea",{value:Rc,onChange:y=>Tn("prompt",y.target.value),placeholder:"What do you want the workflow/agent to do?",rows:3,disabled:ut||dt})]}),s.jsxs("div",{className:"row",children:[s.jsx("div",{className:"col",children:s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Provider (common)"}),s.jsx("input",{value:ho,onChange:y=>Tn("provider",y.target.value),placeholder:"lmstudio / ollama / openai / ...",disabled:ut||dt})]})}),s.jsx("div",{className:"col",children:s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Model (common)"}),s.jsx("input",{value:ad,onChange:y=>Tn("model",y.target.value),placeholder:"qwen/qwen3-next-80b / gpt-4.1 / ...",disabled:ut||dt})]})})]})]}):s.jsx("div",{className:"help_text muted",style:{marginTop:"8px"},children:"Select a workflow above to configure inputs."}),he==="automate"?s.jsxs(s.Fragment,{children:[s.jsx(q2,{form:We,email_status:br.email_status,on_open_my_email:Tc,tools:Tv(ft||{})??void 0,available_tools:pi,on_tools_change:y=>I(JSON.stringify(Mv(ft||{},y),null,2)),disabled:je,on_change:y=>pt(S=>({...S,...y}))}),s.jsxs("details",{className:"launch_advanced",style:{marginTop:"10px"},children:[s.jsxs("summary",{className:"help_text muted",style:{cursor:"pointer"},children:["Advanced",os.length?` · ${os.length} skill${os.length===1?"":"s"}`:""]}),s.jsx(H2,{form:We,disabled:je,on_change:y=>pt(S=>({...S,...y}))}),Zc]})]}):Zc,s.jsx("div",{className:"section_divider"}),Gi?s.jsxs("div",{className:"observe_context_card error",style:{marginBottom:"10px"},children:[s.jsx("span",{className:"chip mono danger",children:"error"}),s.jsx("span",{className:"mono",children:Gi})]}):null,he==="automate"&&Fe.length?s.jsx("ul",{className:"automate_errors",role:"alert",children:Fe.map(y=>s.jsx("li",{children:y},y))}):null,he==="automate"&&lt?s.jsxs("div",{className:"observe_context_card error",role:"alert","data-code":lt.code,style:{marginBottom:"10px"},children:[s.jsx("span",{className:"chip mono danger",children:lt.code}),s.jsxs("span",{children:[s.jsx("strong",{children:am(lt).title})," ",am(lt).detail,lt.field?s.jsxs("span",{className:"mono",children:[" (",lt.field,")"]}):null]})]}):null,s.jsx("div",{className:"launch_actions_bar launch_actions_stack",children:(()=>{const y=he==="automate",S=A?Jr?ft===null?"Inputs contain invalid JSON":y&&!qe.available?"Automations unavailable on this gateway":ut||dt?"Attaching to a run…":W||Y?"Loading…":je?"Submitting…":"":"Select a workflow":"Sign in first";return s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"launch_submit_btn",onClick:()=>void eh(),disabled:!!S,title:S,children:y?je?"Creating…":"Create automation":ut?"Launching…":"Launch now"}),S&&!je&&!ut?s.jsx("span",{className:"mono muted launch_disabled_reason",children:S}):null]})})()})]})})}):null,e==="automations"?s.jsx(hC,{workflowPickerOptions:{interfaceId:null,defaultInterface:tc,workflows:Fa,request:(y,S)=>Te.get_gateway_json(y,S.signal)},availableTools:pi,ctl:Tt,gateway:Te,active:e==="automations"&&A,available:qe,h:sn,host:{on_open_run:y=>jr(y),...Tc?{on_open_my_email:Tc}:{},on_open_session:(y,S)=>{Jt({ts:Ct(),kind:"info",title:"Discussion started",preview:jt(S),data:y})}}}):null,e==="runtime"?s.jsx(xE,{gateway_connected:A,tab:gl,runs:wi,active_runs:ph,all_artifacts:kc,artifacts:Ts,artifact_total_count:jc,artifact_total_bytes:wl,artifact_facets:Yu,artifact_type_facets:Sc,artifact_page:Ha,artifact_page_size:Yh,artifact_groups:r_,selected_artifact:Va,embedded_preview:Kr,loading:Uf,error:Vm,query:lo,scope:zo,type_filters:Aa,date_filter:Ec,group_by:co,sort_by:xl,artifact_run_filter:ys,audit_log_text:mi,audit_log_meta:Qu,audit_log_loading:Gf,audit_log_error:Ia,workflow_label_by_id:as,run_by_id:zn,selected_run_id:kr,session_id:Pd,runtime_log_source:qo,runtime_log_query:Rr,runtime_ledger_log_items:Ho,runtime_ledger_log_meta:Ri,runtime_ledger_log_loading:Kf,runtime_ledger_log_error:td,on_tab_change:Gu,on_query_change:Nc,on_scope_change:vl,on_session_filter_change:Cc,on_type_filters_change:qf,on_date_filter_change:Gm,on_group_by_change:uo,on_sort_by_change:$a,on_artifact_page_change:Uo,on_artifact_run_filter_change:y=>{const S=String(y||"").trim();Ta(S),S&&Bo(S),S&&zo!=="run"&&vl("run")},on_refresh_artifacts:()=>void Rd(),on_refresh_audit:()=>void Ld(),on_refresh_runtime_ledger:y=>void Id(y),on_runtime_log_source_change:Ac,on_runtime_log_query_change:Lr,on_select_run:y=>{const S=String(y||"").trim();Bo(S);const M=S&&zn[S]||null,D=String((M==null?void 0:M.session_id)||"").trim();D&&Cc(D)},on_select_artifact:Xu,on_preview_artifact:y=>void Km(y),on_download_artifact:y=>void Ml(y),on_open_run:y=>{Bo(String(y||"").trim()),t("observe"),Qi("ledger"),Zr(y)},on_open_ledger:y=>{Bo(String(y||"").trim()),t("observe"),Qi("ledger"),Zr(y)},on_refresh_runs:()=>void ls(Te,{force:!0}),on_reconnect:()=>void Xr({open_modal_if_needed:!0}),on_open_settings:()=>t("settings"),memory_panel:A?s.jsx(mL,{gateway:Te,selected_run_id:vr,selected_session_id:Pd}):null}):null,e==="observe"?s.jsx("div",{className:"page observe_page",children:s.jsxs("div",{className:`observatory_layout${zu?"":" list_collapsed"}`,children:[s.jsx(kE,{sections:Od,selected_run_id:c,root_run_id:m,search:wc,filter:Du,group_by:Fu,loading:wn,connected:A,on_sign_in:()=>P.openModal(),total_runs:wi.length,workflow_label_by_id:as,automation_titles:sd,on_search:zm,on_filter:Bm,on_group_by:Um,on_refresh:()=>void ls(),on_select:(y,S)=>{Zr(y,{root_run_id:S||y}),zl()},list:{open:zu,on_toggle:Of}}),s.jsxs("div",{className:"observatory_main",children:[s.jsxs("div",{className:"observe_toolbar",children:[s.jsxs("div",{className:"observe_toolbar_row",children:[c.trim()?s.jsxs("div",{className:"observe_run_identity",title:c.trim(),children:[s.jsx("span",{className:"observe_run_name",children:as[String((Rn==null?void 0:Rn.workflow_id)||"")]||String((Rn==null?void 0:Rn.workflow_id)||"").trim()||Qt(c.trim(),22)}),s.jsx("span",{className:"chip mono muted",children:Qt(c.trim(),14)}),s.jsx("span",{className:`chip ${ac(qa||Vn,yo)}`,title:String((yo==null?void 0:yo.headline)||""),children:qa||Vn||"unknown"})]}):x?s.jsx("span",{className:"observe_run_identity_empty observe_run_link_missing",role:"alert",children:$N(x)}):s.jsx("span",{className:"observe_run_identity_empty",children:"No run selected"}),s.jsx("span",{className:"observe_toolbar_spacer"}),c.trim()?s.jsxs(s.Fragment,{children:[or?s.jsx(gC,{active:!_o,unavailableReason:Ed,busy:ut||dt,onChange:y=>{if(!y){pr("pause"),Xs(""),is(""),_r(!0);return}Ua("resume")}}):s.jsx("button",{className:"btn",onClick:()=>{if(Nd==="pause"){pr("pause"),Xs(""),is(""),_r(!0);return}Ua("resume")},disabled:Cd,children:Sd}),fh?s.jsx("button",{className:"btn primary",onClick:()=>void yd(),disabled:ut||dt||ti||_o,children:"Run now"}):null,s.jsx("button",{className:"btn danger",onClick:()=>{pr("cancel"),Xs(""),is(""),_r(!0)},disabled:ut||dt||ti,children:"Cancel"}),s.jsx("button",{className:"btn btn_icon",onClick:Wc,title:"Clear the run view",children:s.jsx(et,{name:"x",size:14})})]}):null]}),c.trim()&&!ti?s.jsx("div",{className:"observe_steer_row",children:s.jsx(Wk,{runId:c.trim(),parked:rr,submit:(y,S)=>Te.submit_command({command_id:`steer-${xs()}`,run_id:y,type:"inject_guidance",payload:{guidance:S},client_id:"web_pwa"}).then(M=>({accepted:!!(M!=null&&M.accepted),duplicate:!!(M!=null&&M.duplicate),seq:Number((M==null?void 0:M.seq)??0)})),onSent:()=>Jt({ts:Ct(),kind:"info",title:"Steer queued",preview:"inject_guidance submitted — delivery shows as abstract.steer_seen in the ledger"})})}):null,rr||or||Pu?s.jsxs("div",{className:"observe_toolbar_context",children:[rr?s.jsxs("div",{className:"observe_context_card info",children:[s.jsxs("div",{className:"observe_context_label",children:[(()=>{const y=or?_o?"suspended":"scheduled":"waiting";return s.jsx("span",{className:`chip ${ac(y)}`,children:y})})(),s.jsx("span",{className:"muted",children:cs||"unknown"})]}),s.jsxs("div",{className:"observe_context_body",children:[Es?s.jsxs("span",{className:"mono",title:Es,children:[s.jsx("span",{className:"muted",children:"wait_key"}),": ",Qt(Es,46)]}):null,cs==="event"&&Wa?s.jsxs("span",{className:"mono",children:[s.jsx("span",{className:"muted",children:"event"}),": ",Wa]}):null,cs==="subworkflow"&&Pi?s.jsxs("span",{className:"mono",children:[s.jsx("span",{className:"muted",children:"child"}),": ",Qt(Pi,18)]}):null,cs==="until"&&Qr?s.jsxs("span",{className:"mono",title:Qr,children:[s.jsx("span",{className:"muted",children:"until"}),": ",Qt(Qr,46)]}):null,cs==="until"&&Qr?s.jsx("span",{className:"mono muted",children:(()=>{const y=qn(Qr),S=y!==null?new Date(y).toLocaleString():Qr,M=y!==null?Vy(y-Date.now()):"";return`Next at ${S}${M?` (in ${M})`:""}`})()}):null]}),cs==="subworkflow"&&Pi?s.jsxs("div",{className:"observe_context_actions",children:[s.jsx("button",{className:"btn primary",onClick:async()=>{f(Pi),await Rl(Pi)},disabled:ut,children:"Attach to child"}),m.trim()&&m.trim()!==c.trim()?s.jsx("button",{className:"btn",onClick:async()=>{f(m.trim()),await Rl(m.trim())},disabled:ut,children:"Back to root"}):null]}):null]}):null,or?s.jsxs("div",{className:"observe_context_card muted",children:[s.jsxs("div",{className:"observe_context_label",children:[s.jsx("span",{className:"chip muted",children:"schedule"}),s.jsx("span",{className:"muted",children:Pl?`every ${Jo}`:"once"})]}),s.jsxs("div",{className:"observe_context_body",children:[Jo?s.jsxs("span",{className:"mono",children:[s.jsx("span",{className:"muted",children:"interval"}),": ",Jo]}):null,s.jsxs("span",{className:"mono",children:[s.jsx("span",{className:"muted",children:"share ctx"}),": ",dh?"yes":"no"]}),typeof Gc=="number"?s.jsxs("span",{className:"mono",children:[s.jsx("span",{className:"muted",children:"repeats"}),": ",Gc]}):null]}),po!==null?s.jsxs("div",{className:"observe_context_budget",children:[s.jsxs("span",{className:"mono muted",children:[typeof hh=="number"&&typeof Ad=="number"?`${hh.toLocaleString()} / ${Ad.toLocaleString()}`:"",` • ${Math.round(Math.max(0,Math.min(1,po))*100)}%`]}),s.jsx("div",{className:"observe_budget_bar",children:s.jsx("div",{className:`observe_budget_fill ${po>=.9?"danger":po>=.75?"warn":"ok"}`,style:{width:`${Math.round(Math.max(0,Math.min(1,po))*100)}%`}})})]}):null,s.jsxs("div",{className:"observe_context_actions",children:[Pl?s.jsx("button",{className:"btn",onClick:()=>{Pn(Jo||""),Hn(!0),ai(""),Ao(!0)},disabled:ut||$n,children:"Edit schedule"}):null,Pl?s.jsx("button",{className:"btn",onClick:()=>{_s(""),Js(!0)},disabled:ut||Er,children:"Compact context"}):null,s.jsx("button",{className:"btn",onClick:()=>void pd(c.trim()).catch(y=>nn(String((y==null?void 0:y.message)||y))),disabled:ut||!c.trim(),title:"Open Launch → Automate prefilled from this schedule (this schedule is not changed)",children:"Recreate as automation"})]})]}):null,Pu?s.jsxs("div",{className:"observe_context_card error",children:[s.jsx("span",{className:"chip danger",children:"error"}),s.jsx("span",{className:"mono",children:Pu})]}):null]}):null]}),s.jsxs("div",{className:"card panel_card card_scroll observe_viewer observe_viewer_full",ref:Df,children:[s.jsxs("div",{className:"tab_bar",children:[s.jsxs("div",{role:"tablist","aria-label":"Run views",className:"observe_tablist",children:[s.jsx("button",{role:"tab","aria-selected":tr==="ledger",className:`tab ${tr==="ledger"?"active":""}`,onClick:()=>Jc("ledger"),children:"Ledger"}),s.jsx("button",{role:"tab","aria-selected":tr==="graph",className:`tab ${tr==="graph"?"active":""}`,onClick:()=>Jc("graph"),children:"Flow"}),s.jsx("button",{role:"tab","aria-selected":tr==="chat",className:`tab ${tr==="chat"?"active":""}`,onClick:()=>Jc("chat"),children:"Ask"})]}),tr==="ledger"&&(an.length>0||ss.length>0)?s.jsx("div",{className:"tab_bar_controls",children:s.jsx("button",{className:"seg_action",disabled:!an.length&&!ss.length,title:"Copy full ledger as JSONL",onClick:()=>{const M=[...an.map(H=>({run_id:c.trim()||H.record.run_id||"",cursor:H.cursor,record:H.record})),...ss.map(H=>({run_id:H.run_id,cursor:H.cursor,record:H.record}))].map(H=>{var Le,ge;const V=String(((Le=H.record)==null?void 0:Le.ended_at)||((ge=H.record)==null?void 0:ge.started_at)||"").trim(),te=qn(V);return{...H,_ms:te??0}});M.sort((H,V)=>(H._ms||0)-(V._ms||0));const q=(M.length>5e3?M.slice(M.length-5e3):M).map(({_ms:H,...V})=>JSON.stringify(V)).join(`
149
- `);Fc(q)},children:"Copy JSONL"})}):null,tr==="graph"?s.jsxs("div",{className:"tab_bar_controls",children:[s.jsx("button",{className:`seg_action ${hl?"active":""}`,"aria-pressed":hl,onClick:()=>qm(y=>!y),children:"Subflows"}),s.jsx("button",{className:`seg_action ${qu?"active":""}`,"aria-pressed":qu,onClick:()=>Hm(y=>!y),children:"Path"}),Td.length?s.jsx("select",{className:"mono seg_select",value:ya,onChange:y=>eo(String(y.target.value||"")),disabled:!!Pr.trim()||!C.trim()||Uu,children:Td.map(y=>s.jsx("option",{value:y,children:y},y))}):null]}):null]}),tr==="ledger"?c.trim()?s.jsxs("div",{className:"rs_page",children:[s.jsx(m2,{status:qa||Vn||"unknown",duration:Rn?oc(Rn):"",facts:t2(e2(go)),error:hm(Rn)||String((ue==null?void 0:ue.error)||"").trim(),answer:t_||String((Dl==null?void 0:Dl.text)||"").trim(),waiting_for_user:!!(Ft!=null&&Ft.wait_key)&&String((Ft==null?void 0:Ft.reason)||"")==="user",on_answer_wait:()=>Qs(""),workspace_root:ga,on_reveal_workspace:()=>void Tl(),on_open_artifacts:()=>{const y=String(c||"").trim();y&&(Bo(y),Ta(y),vl("run")),Gu("artifacts"),t("runtime")}}),Iu.filter(y=>y.kind==="error"&&!y.data).slice(0,3).map(y=>s.jsxs("p",{className:"rs_notice",children:[y.title,": ",y.preview]},y.id)),s.jsx(h2,{items:go,run_id:Fl,run_options:$s,run_llm_counts:Kc,on_select_run:y=>Bu(y),state:Wm,on_state:n_,node_label:(y,S)=>{const M=S?(Vo==null?void 0:Vo[Fn(y,S)])||(Vo==null?void 0:Vo[S]):null;return String((M==null?void 0:M.label)||S||"").trim()},on_copy:y=>void Fc(y),on_open_run:y=>void Zr(y,{root_run_id:m||c||y})})]}):s.jsx("div",{className:"empty_state_inline",children:"Select a run on the left to inspect it — or start one from Launch."}):null,tr==="graph"?s.jsxs(s.Fragment,{children:[Wu?s.jsxs("div",{className:"log_item log_item_danger",children:[s.jsxs("div",{className:"meta",children:[s.jsx("span",{children:"graph error"}),s.jsx("span",{className:"mono",children:Ct()})]}),s.jsx("div",{className:"body mono",children:Wu})]}):null,Uu?s.jsxs("div",{className:"log_item log_item_info",children:[s.jsxs("div",{className:"meta",children:[s.jsx("span",{children:"loading"}),s.jsx("span",{className:"mono",children:Pr.trim()?Pr.trim():ya})]}),s.jsx("div",{className:"body mono",children:"Loading graph…"})]}):null,s.jsx("div",{className:"graph_panel",children:s.jsx(WE,{flow:wa,flow_by_id:xa,expand_subflows:hl,simplify:!0,prefer_vertical:!0,vertical_compact:.78,schedule_next_in:Zo,schedule_interval:Jo,node_last_ms:e_,active_node_id:Di,recent_nodes:Bf,visited_nodes:Hu,highlight_path:qu,now_ms:Vr})})]}):null,tr==="chat"?s.jsxs("div",{className:"ask_tab log_scroll",style:{marginTop:"6px"},children:[s.jsxs("div",{className:"ask_header",children:[s.jsx("span",{className:"ask_title",children:"Ask about this run"}),s.jsx("span",{className:"chip muted",title:"Model comes from Settings → Assistant (blank = gateway default)",children:(n.maintenance_ai_provider.trim()||"gateway")+" / "+(n.maintenance_ai_model.trim()||"default")}),s.jsx("span",{className:"pane_spacer"}),s.jsx("span",{className:"ask_hint",children:"Read-only · grounded in this run + subflows"})]}),s.jsxs("details",{className:"ask_manage",children:[s.jsx("summary",{children:"History & export"}),s.jsxs("div",{className:"field",style:{marginTop:"10px"},children:[s.jsxs("div",{className:"actions",style:{justifyContent:"space-between",alignItems:"center",gap:"10px",flexWrap:"wrap",marginTop:0},children:[s.jsx("div",{style:{flex:1,minWidth:260},children:s.jsx(bu,{value:Tu,options:Lu,placeholder:cl?"Loading…":Lu.length?"Select a saved discussion…":"(none saved)",disabled:!c.trim()||!A||!Lu.length,loading:cl,searchable:!0,clearable:!0,onChange:y=>{pc(y),Io("")}})}),s.jsxs("div",{className:"actions",style:{justifyContent:"flex-end",marginTop:0},children:[s.jsx("button",{className:"btn",type:"button",disabled:!Tu.trim()||!A||gc,onClick:()=>void Ym(),children:gc?"Loading…":"Load"}),s.jsx("button",{className:"btn",type:"button",disabled:!Qe.length||be||Xn||gc,onClick:()=>{ot([]),Dt(null),er(""),li(""),vn(""),ps(""),yr("")},children:"Clear"}),s.jsx("button",{className:"btn",type:"button",onClick:()=>void qc(),disabled:!c.trim()||!A||cl,children:cl?"Refreshing…":"Refresh"})]})]}),s.jsxs("div",{className:"actions",style:{justifyContent:"flex-end",marginTop:"8px",flexWrap:"wrap"},children:[s.jsx("button",{className:"btn",type:"button",disabled:!Qe.length||!c.trim()||!A||Xn||!Ru,onClick:()=>void ih(),title:Ru?"":"No changes since last save",children:Xn?"Saving…":!Ru&&kn?"Saved":"Save discussion"}),s.jsx("button",{className:"btn",type:"button",disabled:!Qe.length,onClick:()=>vd("download"),children:"Export Markdown"}),s.jsx("button",{className:"btn",type:"button",disabled:!Qe.length,onClick:()=>vd("copy"),children:Ee==="copied"?"Copied":Ee==="failed"?"Copy failed":"Copy Markdown"})]}),kn?s.jsxs("div",{className:"chat_hint",children:["Last saved: ",ec(kn)]}):null,un?s.jsx("div",{className:"chat_hint chat_hint_danger",children:un}):null,Mu?s.jsx("div",{className:"chat_hint chat_hint_danger",children:Mu}):null,mc?s.jsx("div",{className:"chat_hint chat_hint_danger",children:mc}):null]})]}),Mo?s.jsxs("div",{className:"log_item log_item_danger",children:[s.jsxs("div",{className:"meta",children:[s.jsx("span",{children:"error"}),s.jsx("span",{className:"mono",children:Ct()})]}),s.jsx("div",{className:"body mono",children:Mo})]}):null,ll?s.jsxs("div",{className:"log_item log_item_danger",children:[s.jsxs("div",{className:"meta",children:[s.jsx("span",{children:"voice"}),s.jsx("span",{className:"mono",children:Ct()})]}),s.jsx("div",{className:"body mono",children:ll})]}):null,s.jsx("div",{className:"chat_messages",style:{marginTop:"10px"},children:s.jsx(hg,{messages:Qe,className:"log_scroll",after:s.jsx($x,{history:mt}),afterKey:mt?`${mt.replayed_messages}:${mt.dropped_messages}`:null,messageProps:Ht.tts_supported&&A&&B.trim()?{onSpeakToggle:rh,getSpeakState:wd,jsonCollapseAfterDepth:4}:{jsonCollapseAfterDepth:4},empty:s.jsx("div",{className:"chat_empty_hint",children:"Ask about this run (why failed, which tools, what happened in subflows)."})})}),s.jsxs("div",{className:"chat_composer",style:{marginTop:"10px"},children:[s.jsx(mg,{ref:Xt,value:Zi,onChange:er,onSubmit:()=>void sh(),placeholder:"Ask about this run…",disabled:!c.trim()||!A||be,busy:be||Ht.voice_ptt_busy,busyLabel:Ht.voice_ptt_busy?"Transcribing…":"Thinking…",rows:3,sendButtonClassName:"btn primary",actions:s.jsxs("button",{className:`btn btn_icon voice_btn${Ht.voice_ptt_recording?" danger":""}`,type:"button",disabled:!A||!Mn.trim()||!B.trim()||be||Ht.voice_ptt_busy||!Ht.voice_ptt_supported,title:Ht.voice_ptt_supported?Ht.voice_ptt_busy?"Transcribing…":Ht.voice_ptt_recording?"Recording… release to transcribe":"Hold to talk (record + transcribe)":Pp()?"Voice recording is not supported in this browser":Op,"aria-label":"Voice input",onPointerDown:y=>{var S,M;if(!(!A||!Mn.trim()||!B.trim()||be||Ht.voice_ptt_busy||!Ht.voice_ptt_supported)){y.preventDefault();try{(M=(S=y.currentTarget)==null?void 0:S.setPointerCapture)==null||M.call(S,y.pointerId)}catch{}Ht.start_voice_ptt_recording()}},onPointerUp:y=>{y.preventDefault(),Ht.stop_voice_ptt_recording()},onPointerCancel:y=>{y.preventDefault(),Ht.stop_voice_ptt_recording()},children:[s.jsx(et,{name:Ht.voice_ptt_recording?"x":"mic",size:16}),Ht.voice_ptt_busy?"Transcribing…":Ht.voice_ptt_recording?"Recording…":"Voice"]})}),Pp()?null:s.jsx("div",{className:"mono muted","data-testid":"voice-https-hint",style:{fontSize:"var(--font-size-sm)",marginTop:"6px"},children:Op})]})]}):null,c.trim()?s.jsxs("div",{className:`status_bar ${fc?"pulse":""}`,children:[s.jsx("strong",{children:"Run"}),":"," ",s.jsx("span",{className:"mono",children:qa||Vn||"unknown"}),Md&&Zo?s.jsxs("span",{className:"mono muted",children:[" • next in ",Zo]}):null,Tr?s.jsxs("span",{className:"mono muted",children:[" • ",Tr]}):null]}):null]})]})]})}):null,s.jsxs(Kl,{open:Zu,title:$i||"Artifact",onClose:()=>{fo(!1),xr(""),jl(""),bl(!1),La(null),fn&&(URL.revokeObjectURL(fn),ws(""))},actions:s.jsx("button",{className:"btn",onClick:()=>{fo(!1),xr(""),jl(""),bl(!1),La(null),fn&&(URL.revokeObjectURL(fn),ws(""))},children:"Close"}),children:[Vf?s.jsx("div",{className:"mono muted",style:{fontSize:"var(--font-size-sm)",marginBottom:"8px"},children:"Loading…"}):null,kl?s.jsx("div",{className:"mono",style:{color:"rgba(239, 68, 68, 0.9)",fontSize:"var(--font-size-sm)",marginBottom:"8px"},children:kl}):null,Ti==="image"&&fn?s.jsx("img",{className:"runtime_preview_media",src:fn,alt:$i||"Artifact preview"}):Ti==="audio"&&fn?s.jsx("audio",{className:"runtime_preview_media",controls:!0,src:fn}):Ti==="video"&&fn?s.jsx("video",{className:"runtime_preview_media",controls:!0,src:fn}):s.jsx(ib,{artifact:nr,text:Cn||"(empty)",className:"runtime_preview_text"})]}),Eo?s.jsxs(Kl,{open:Eo,title:"Edit schedule",onClose:()=>{Ao(!1),Pn(""),Hn(!0),ai(""),Fs(!1)},actions:s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"btn",onClick:()=>{Ao(!1),Pn(""),Hn(!0),ai(""),Fs(!1)},disabled:ut||$n,children:"Back"}),s.jsx("button",{className:"btn primary",onClick:async()=>{await th({interval:$o,apply_immediately:mr})||(Ao(!1),ai(""),Fs(!1))},disabled:ut||$n||!$o.trim(),children:"Save"})]}),children:[Ki?s.jsxs("div",{className:"log_item",style:{borderColor:"rgba(239, 68, 68, 0.35)",marginBottom:"10px"},children:[s.jsxs("div",{className:"meta",children:[s.jsx("span",{className:"mono",children:"error"}),s.jsx("span",{className:"mono",children:Ct()})]}),s.jsx("div",{className:"body mono",children:Ki})]}):null,s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Interval"}),s.jsx("input",{className:"mono",value:$o,onChange:y=>Pn(String(y.target.value||"")),placeholder:"20m / 1h / 0.5s / 250ms",disabled:ut||$n}),s.jsxs("div",{className:"mono muted",style:{fontSize:"var(--font-size-sm)"},children:["Accepted units: ",s.jsx("span",{className:"mono",children:"ms"}),", ",s.jsx("span",{className:"mono",children:"s"}),", ",s.jsx("span",{className:"mono",children:"m"}),","," ",s.jsx("span",{className:"mono",children:"h"}),", ",s.jsx("span",{className:"mono",children:"d"}),". This updates the existing scheduled run in place (no context loss)."]})]}),s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Quick picks"}),s.jsx("div",{className:"actions",style:{gap:"8px",flexWrap:"wrap"},children:["15m","30m","1h","2h","6h","1d"].map(y=>s.jsx("button",{className:"btn",onClick:()=>Pn(y),disabled:ut||$n,children:y},y))})]}),s.jsx("div",{className:"field",children:s.jsx(wC,{checked:mr,busy:ut||$n,onChange:Hn})})]}):null,hs?s.jsxs(Kl,{open:hs,title:"Compact scheduled context",onClose:()=>{Js(!1),_s(""),Ar(!1)},actions:s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"btn",onClick:()=>{Js(!1),_s(""),Ar(!1)},disabled:ut||Er,children:"Cancel"}),s.jsx("button",{className:"btn primary",onClick:async()=>{await nh({preserve_recent:ms,compression_mode:Yi,focus:fa})||(Js(!1),_s(""),Ar(!1))},disabled:ut||Er,children:Er?"Compacting…":"Compact"})]}),children:[To?s.jsxs("div",{className:"log_item",style:{borderColor:"rgba(239, 68, 68, 0.35)",marginBottom:"10px"},children:[s.jsxs("div",{className:"meta",children:[s.jsx("span",{className:"mono",children:"error"}),s.jsx("span",{className:"mono",children:Ct()})]}),s.jsx("div",{className:"body mono",children:To})]}):null,s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Preserve recent turns"}),s.jsx("input",{type:"number",min:1,value:String(ms),onChange:y=>da(Math.max(1,parseInt(y.target.value||"6",10)||6)),disabled:ut||Er})]}),s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Mode"}),s.jsxs("select",{value:Yi,onChange:y=>ln(y.target.value),disabled:ut||Er,children:[s.jsx("option",{value:"light",children:"light"}),s.jsx("option",{value:"standard",children:"standard"}),s.jsx("option",{value:"heavy",children:"heavy"})]})]}),s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Focus (optional)"}),s.jsx("input",{className:"mono",value:fa,onChange:y=>dc(String(y.target.value||"")),placeholder:"e.g. important decisions, next steps…",disabled:ut||Er})]})]}):null,Ji?s.jsxs(Kl,{open:Ji,title:Ss==="cancel"?"Cancel run":or?"Suspend schedule":"Pause run",onClose:()=>{_r(!1),Xs(""),is("")},actions:s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"btn",onClick:()=>{_r(!1),Xs(""),is("")},disabled:ut||dt,children:"Back"}),s.jsx("button",{className:`btn ${Ss==="cancel"?"danger":"primary"}`,onClick:async()=>{is("");const y=await Ua(Ss,{reason:$r});if(y){is(y);return}_r(!1),Xs(""),is("")},disabled:ut||dt,children:Ss==="pause"?or?"Suspend":"Pause":"Cancel"})]}),children:[Ni?s.jsxs("div",{className:"log_item",style:{borderColor:"rgba(239, 68, 68, 0.35)",marginBottom:"10px"},children:[s.jsxs("div",{className:"meta",children:[s.jsx("span",{className:"mono",children:"error"}),s.jsx("span",{className:"mono",children:Ct()})]}),s.jsx("div",{className:"body mono",children:Ni})]}):null,s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Reason (optional)"}),s.jsx("input",{className:"mono",value:$r,onChange:y=>Xs(y.target.value),placeholder:"reason…"})]})]}):null,bd?s.jsxs(Kl,{open:bd,title:Vc,onClose:()=>{Es&&Qs(Es)},actions:s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"btn",onClick:()=>{Qi("ledger"),t("observe"),zl(),Es&&Qs(Es)},disabled:!c.trim(),children:"Open ledger"}),s.jsx("button",{className:"btn",onClick:()=>Es&&Qs(Es),disabled:dt,children:"Dismiss"}),Ko.length?s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"btn danger",disabled:dt,onClick:()=>Il({approved:!1}),children:"Reject"}),s.jsx("button",{className:"btn",disabled:dt,onClick:()=>Il({approved:!0}),children:"Approve only"}),s.jsx("button",{className:"btn primary",disabled:!Pa||dt,onClick:()=>Jm(Ko),children:"Approve and execute"})]}):null]}),children:[s.jsxs("div",{className:"wait_context_panel",children:[s.jsxs("div",{className:"wait_context_header",children:[s.jsxs("div",{children:[s.jsx("div",{className:"run_hero_eyebrow",children:"What you need to do"}),s.jsx("strong",{children:Vc}),s.jsx("p",{children:Zm})]}),s.jsx(lc,{status:ei||"waiting"})]}),Yo?s.jsxs("div",{className:`wait_request_card ${As?"":"inferred"}`,children:[s.jsx("span",{children:Ws}),s.jsx(Sv,{metadata:lh}),s.jsx(qi,{text:Yo}),As?null:s.jsx("p",{className:"wait_context_note",children:"The runtime did not attach a specific question to this wait. This is inferred from the run input; verify the session turns and workflow steps before answering."})]}):s.jsx("div",{className:"warn_callout",children:"This wait did not provide a clear prompt or recoverable prior user request. Review the full run input and recent workflow steps before submitting a response."}),jd.length?s.jsxs("section",{className:"wait_context_block wait_conversation_context",children:[s.jsx("span",{children:"Recent session turns"}),s.jsx("div",{className:"wait_turn_list",children:jd.map((y,S)=>s.jsxs("div",{className:`wait_turn_row role_${y.role.replace(/[^a-z0-9_-]+/g,"_")}`,children:[s.jsxs("div",{className:"wait_turn_meta",children:[s.jsx("strong",{children:y.role==="assistant"?"Assistant":y.role==="user"||y.role==="human"?"User":y.role}),y.ts?s.jsx("span",{className:"mono muted",children:ec(y.ts)}):null]}),s.jsx(Sv,{metadata:y.runtime_metadata}),s.jsx(qi,{text:jt(y.text,{max_chars:1200,max_lines:10})})]},`${y.role}:${S}`))})]}):null,s.jsxs("div",{className:"artifact_detail_grid",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Workflow"}),s.jsx("strong",{children:Ui(yi,as)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Run"}),s.jsx("strong",{className:"mono",children:Qt(c.trim(),24)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Node"}),s.jsx("strong",{className:"mono",children:yi.current_node||String((Us==null?void 0:Us.node_id)||"—")})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Elapsed"}),s.jsx("strong",{children:oc(yi)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Session"}),s.jsx("strong",{className:"mono",children:yi.session_id?Qt(String(yi.session_id),18):"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Wait key"}),s.jsx("strong",{className:"mono",children:Qt(Es,28)})]})]}),uh?s.jsxs("details",{className:"runtime_raw_details wait_full_input_details",open:!Yo,children:[s.jsx("summary",{className:"mono muted",children:"Full run input JSON"}),s.jsx("div",{className:"wait_shared_json",children:s.jsx(Is,{value:ch,collapseAfterDepth:4,showCopy:!0})})]}):null,s.jsxs("section",{className:"wait_context_block",children:[s.jsx("span",{children:"Recent workflow steps leading to this wait"}),s.jsxs("div",{className:"wait_event_list",children:[Hc.map(y=>s.jsxs("div",{className:"wait_event_row",children:[s.jsxs("span",{className:"mono",children:["#",y.cursor]}),s.jsx("strong",{children:y.summary||y.effect_type||y.status||"event"}),s.jsx("span",{className:"mono muted",children:[y.node_id,y.status,ec(y.ts)].filter(Boolean).join(" · ")})]},`${y.cursor}:${y.node_id}:${y.status}`)),Hc.length?null:s.jsx("div",{className:"empty_state_inline",children:"No ledger context is loaded. Open the ledger before deciding."})]})]})]}),Ko.length?s.jsxs("div",{className:"wait_action_panel",children:[s.jsx("div",{className:"wait_action_intro",children:"Approve and execute runs the listed tool request through your configured worker. Approve only sends approval without local execution. Reject returns a denial. Cancel run stops the whole workflow run."}),s.jsx("div",{className:"wait_tool_list",children:Ko.map((y,S)=>s.jsxs("div",{className:"wait_tool_card",children:[s.jsxs("div",{className:"wait_tool_header",children:[s.jsx("strong",{children:String((y==null?void 0:y.name)||"tool")}),s.jsxs("div",{className:"wait_tool_badges",children:[s.jsx("span",{className:"chip mono warn",children:"approval"}),Xx(y).map(M=>s.jsxs("span",{className:"chip mono muted",title:Jx,children:[M,"~"]},M))]})]}),s.jsx("div",{className:"wait_tool_args",children:s.jsx(Is,{value:(y==null?void 0:y.arguments)||{},collapseAfterDepth:3,showCopy:!0})})]},`${String((y==null?void 0:y.name)||"tool")}:${S}`))}),Pa?null:s.jsx("div",{className:"warn_callout",children:"No tool worker is configured, so Observer cannot execute these calls directly."}),s.jsx("div",{className:"actions",children:s.jsx("button",{className:"btn danger",onClick:()=>void gd(c.trim(),"Cancelled from wait prompt"),disabled:!c.trim()||dt,children:"Cancel whole run"})}),s.jsxs("details",{className:"runtime_raw_details",children:[s.jsx("summary",{className:"mono muted",children:"Diagnostics"}),s.jsx("div",{className:"wait_shared_json",children:s.jsx(Is,{value:Ft||{},collapseAfterDepth:3,showCopy:!0})})]})]}):s.jsxs("div",{className:"wait_action_panel",children:[s.jsx("div",{className:"wait_action_intro",children:"Submit only when the request above is clear. The response resumes this wait only; Cancel run attempts to stop the whole workflow and prevent further work."}),s.jsx("div",{className:"wait_prompt_text",children:Yo||"No explicit prompt was provided. Open the ledger for context before responding."}),s.jsx(bE,{wait:Ft,disabled:dt,on_submit:y=>Il({response:y})}),s.jsx("div",{className:"actions",children:s.jsx("button",{className:"btn danger",onClick:()=>void gd(c.trim(),"Cancelled from wait prompt"),disabled:!c.trim()||dt,children:"Cancel whole run"})}),s.jsxs("details",{className:"runtime_raw_details",children:[s.jsx("summary",{className:"mono muted",children:"Diagnostics"}),s.jsx("div",{className:"wait_shared_json",children:s.jsx(Is,{value:Ft||{},collapseAfterDepth:3,showCopy:!0})})]})]})]}):null]})]})]})}if("serviceWorker"in navigator){window.addEventListener("load",()=>{navigator.serviceWorker.register(EN).then(t=>t.update()).catch(()=>{})});let e=!1;navigator.serviceWorker.addEventListener("controllerchange",()=>{e||(e=!0,window.location.reload())})}gk();dk.createRoot(document.getElementById("root")).render(s.jsx(ve.StrictMode,{children:s.jsx(QL,{})}));
150
- //# sourceMappingURL=index-mOSIboQ8.js.map