@abstractframework/observer 0.4.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -3
- package/dist/assets/index-C--XTi5_.js +150 -0
- package/dist/assets/index-C--XTi5_.js.map +1 -0
- package/dist/assets/index-DlDs-R7p.css +1 -0
- package/dist/index.html +3 -3
- package/package.json +3 -3
- package/dist/assets/index-BHcQcOeZ.css +0 -1
- package/dist/assets/index-DGir8JbI.js +0 -150
- package/dist/assets/index-DGir8JbI.js.map +0 -1
|
@@ -1,150 +0,0 @@
|
|
|
1
|
-
var z0=Object.defineProperty;var B0=(e,t,n)=>t in e?z0(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var Hs=(e,t,n)=>B0(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 vg(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var E_={exports:{}},of={},$_={exports:{}},Yt={};/**
|
|
2
|
-
* @license React
|
|
3
|
-
* react.production.min.js
|
|
4
|
-
*
|
|
5
|
-
* Copyright (c) Facebook, Inc. and its affiliates.
|
|
6
|
-
*
|
|
7
|
-
* This source code is licensed under the MIT license found in the
|
|
8
|
-
* LICENSE file in the root directory of this source tree.
|
|
9
|
-
*/var oy;function U0(){if(oy)return Yt;oy=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"),_=Symbol.for("react.memo"),p=Symbol.for("react.lazy"),y=Symbol.iterator;function w(T){return T===null||typeof T!="object"?null:(T=y&&T[y]||T["@@iterator"],typeof T=="function"?T:null)}var x={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},k=Object.assign,j={};function E(T,Q,K){this.props=T,this.context=Q,this.refs=j,this.updater=K||x}E.prototype.isReactComponent={},E.prototype.setState=function(T,Q){if(typeof T!="object"&&typeof T!="function"&&T!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,T,Q,"setState")},E.prototype.forceUpdate=function(T){this.updater.enqueueForceUpdate(this,T,"forceUpdate")};function A(){}A.prototype=E.prototype;function L(T,Q,K){this.props=T,this.context=Q,this.refs=j,this.updater=K||x}var O=L.prototype=new A;O.constructor=L,k(O,E.prototype),O.isPureReactComponent=!0;var M=Array.isArray,H=Object.prototype.hasOwnProperty,X={current:null},Y={key:!0,ref:!0,__self:!0,__source:!0};function Z(T,Q,K){var J,oe={},he=null,_e=null;if(Q!=null)for(J in Q.ref!==void 0&&(_e=Q.ref),Q.key!==void 0&&(he=""+Q.key),Q)H.call(Q,J)&&!Y.hasOwnProperty(J)&&(oe[J]=Q[J]);var we=arguments.length-2;if(we===1)oe.children=K;else if(1<we){for(var Ee=Array(we),ze=0;ze<we;ze++)Ee[ze]=arguments[ze+2];oe.children=Ee}if(T&&T.defaultProps)for(J in we=T.defaultProps,we)oe[J]===void 0&&(oe[J]=we[J]);return{$$typeof:e,type:T,key:he,ref:_e,props:oe,_owner:X.current}}function re(T,Q){return{$$typeof:e,type:T.type,key:Q,ref:T.ref,props:T.props,_owner:T._owner}}function ie(T){return typeof T=="object"&&T!==null&&T.$$typeof===e}function ue(T){var Q={"=":"=0",":":"=2"};return"$"+T.replace(/[=:]/g,function(K){return Q[K]})}var F=/\/+/g;function C(T,Q){return typeof T=="object"&&T!==null&&T.key!=null?ue(""+T.key):Q.toString(36)}function N(T,Q,K,J,oe){var he=typeof T;(he==="undefined"||he==="boolean")&&(T=null);var _e=!1;if(T===null)_e=!0;else switch(he){case"string":case"number":_e=!0;break;case"object":switch(T.$$typeof){case e:case t:_e=!0}}if(_e)return _e=T,oe=oe(_e),T=J===""?"."+C(_e,0):J,M(oe)?(K="",T!=null&&(K=T.replace(F,"$&/")+"/"),N(oe,Q,K,"",function(ze){return ze})):oe!=null&&(ie(oe)&&(oe=re(oe,K+(!oe.key||_e&&_e.key===oe.key?"":(""+oe.key).replace(F,"$&/")+"/")+T)),Q.push(oe)),1;if(_e=0,J=J===""?".":J+":",M(T))for(var we=0;we<T.length;we++){he=T[we];var Ee=J+C(he,we);_e+=N(he,Q,K,Ee,oe)}else if(Ee=w(T),typeof Ee=="function")for(T=Ee.call(T),we=0;!(he=T.next()).done;)he=he.value,Ee=J+C(he,we++),_e+=N(he,Q,K,Ee,oe);else if(he==="object")throw Q=String(T),Error("Objects are not valid as a React child (found: "+(Q==="[object Object]"?"object with keys {"+Object.keys(T).join(", ")+"}":Q)+"). If you meant to render a collection of children, use an array instead.");return _e}function P(T,Q,K){if(T==null)return T;var J=[],oe=0;return N(T,J,"","",function(he){return Q.call(K,he,oe++)}),J}function D(T){if(T._status===-1){var Q=T._result;Q=Q(),Q.then(function(K){(T._status===0||T._status===-1)&&(T._status=1,T._result=K)},function(K){(T._status===0||T._status===-1)&&(T._status=2,T._result=K)}),T._status===-1&&(T._status=0,T._result=Q)}if(T._status===1)return T._result.default;throw T._result}var ne={current:null},B={transition:null},z={ReactCurrentDispatcher:ne,ReactCurrentBatchConfig:B,ReactCurrentOwner:X};function G(){throw Error("act(...) is not supported in production builds of React.")}return Yt.Children={map:P,forEach:function(T,Q,K){P(T,function(){Q.apply(this,arguments)},K)},count:function(T){var Q=0;return P(T,function(){Q++}),Q},toArray:function(T){return P(T,function(Q){return Q})||[]},only:function(T){if(!ie(T))throw Error("React.Children.only expected to receive a single React element child.");return T}},Yt.Component=E,Yt.Fragment=n,Yt.Profiler=o,Yt.PureComponent=L,Yt.StrictMode=r,Yt.Suspense=f,Yt.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=z,Yt.act=G,Yt.cloneElement=function(T,Q,K){if(T==null)throw Error("React.cloneElement(...): The argument must be a React element, but you passed "+T+".");var J=k({},T.props),oe=T.key,he=T.ref,_e=T._owner;if(Q!=null){if(Q.ref!==void 0&&(he=Q.ref,_e=X.current),Q.key!==void 0&&(oe=""+Q.key),T.type&&T.type.defaultProps)var we=T.type.defaultProps;for(Ee in Q)H.call(Q,Ee)&&!Y.hasOwnProperty(Ee)&&(J[Ee]=Q[Ee]===void 0&&we!==void 0?we[Ee]:Q[Ee])}var Ee=arguments.length-2;if(Ee===1)J.children=K;else if(1<Ee){we=Array(Ee);for(var ze=0;ze<Ee;ze++)we[ze]=arguments[ze+2];J.children=we}return{$$typeof:e,type:T.type,key:oe,ref:he,props:J,_owner:_e}},Yt.createContext=function(T){return T={$$typeof:u,_currentValue:T,_currentValue2:T,_threadCount:0,Provider:null,Consumer:null,_defaultValue:null,_globalName:null},T.Provider={$$typeof:l,_context:T},T.Consumer=T},Yt.createElement=Z,Yt.createFactory=function(T){var Q=Z.bind(null,T);return Q.type=T,Q},Yt.createRef=function(){return{current:null}},Yt.forwardRef=function(T){return{$$typeof:c,render:T}},Yt.isValidElement=ie,Yt.lazy=function(T){return{$$typeof:p,_payload:{_status:-1,_result:T},_init:D}},Yt.memo=function(T,Q){return{$$typeof:_,type:T,compare:Q===void 0?null:Q}},Yt.startTransition=function(T){var Q=B.transition;B.transition={};try{T()}finally{B.transition=Q}},Yt.unstable_act=G,Yt.useCallback=function(T,Q){return ne.current.useCallback(T,Q)},Yt.useContext=function(T){return ne.current.useContext(T)},Yt.useDebugValue=function(){},Yt.useDeferredValue=function(T){return ne.current.useDeferredValue(T)},Yt.useEffect=function(T,Q){return ne.current.useEffect(T,Q)},Yt.useId=function(){return ne.current.useId()},Yt.useImperativeHandle=function(T,Q,K){return ne.current.useImperativeHandle(T,Q,K)},Yt.useInsertionEffect=function(T,Q){return ne.current.useInsertionEffect(T,Q)},Yt.useLayoutEffect=function(T,Q){return ne.current.useLayoutEffect(T,Q)},Yt.useMemo=function(T,Q){return ne.current.useMemo(T,Q)},Yt.useReducer=function(T,Q,K){return ne.current.useReducer(T,Q,K)},Yt.useRef=function(T){return ne.current.useRef(T)},Yt.useState=function(T){return ne.current.useState(T)},Yt.useSyncExternalStore=function(T,Q,K){return ne.current.useSyncExternalStore(T,Q,K)},Yt.useTransition=function(){return ne.current.useTransition()},Yt.version="18.3.1",Yt}var ay;function Uf(){return ay||(ay=1,$_.exports=U0()),$_.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 ly;function W0(){if(ly)return of;ly=1;var e=Uf(),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,_){var p,y={},w=null,x=null;_!==void 0&&(w=""+_),f.key!==void 0&&(w=""+f.key),f.ref!==void 0&&(x=f.ref);for(p in f)r.call(f,p)&&!l.hasOwnProperty(p)&&(y[p]=f[p]);if(c&&c.defaultProps)for(p in f=c.defaultProps,f)y[p]===void 0&&(y[p]=f[p]);return{$$typeof:t,type:c,key:w,ref:x,props:y,_owner:o.current}}return of.Fragment=n,of.jsx=u,of.jsxs=u,of}var cy;function q0(){return cy||(cy=1,E_.exports=W0()),E_.exports}var s=q0(),m=Uf();const ve=vg(m);var Gh={},A_={exports:{}},Br={},T_={exports:{}},M_={};/**
|
|
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 uy;function H0(){return uy||(uy=1,(function(e){function t(B,z){var G=B.length;B.push(z);e:for(;0<G;){var T=G-1>>>1,Q=B[T];if(0<o(Q,z))B[T]=z,B[G]=Q,G=T;else break e}}function n(B){return B.length===0?null:B[0]}function r(B){if(B.length===0)return null;var z=B[0],G=B.pop();if(G!==z){B[0]=G;e:for(var T=0,Q=B.length,K=Q>>>1;T<K;){var J=2*(T+1)-1,oe=B[J],he=J+1,_e=B[he];if(0>o(oe,G))he<Q&&0>o(_e,oe)?(B[T]=_e,B[he]=G,T=he):(B[T]=oe,B[J]=G,T=J);else if(he<Q&&0>o(_e,G))B[T]=_e,B[he]=G,T=he;else break e}}return z}function o(B,z){var G=B.sortIndex-z.sortIndex;return G!==0?G:B.id-z.id}if(typeof performance=="object"&&typeof performance.now=="function"){var l=performance;e.unstable_now=function(){return l.now()}}else{var u=Date,c=u.now();e.unstable_now=function(){return u.now()-c}}var f=[],_=[],p=1,y=null,w=3,x=!1,k=!1,j=!1,E=typeof setTimeout=="function"?setTimeout:null,A=typeof clearTimeout=="function"?clearTimeout:null,L=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function O(B){for(var z=n(_);z!==null;){if(z.callback===null)r(_);else if(z.startTime<=B)r(_),z.sortIndex=z.expirationTime,t(f,z);else break;z=n(_)}}function M(B){if(j=!1,O(B),!k)if(n(f)!==null)k=!0,D(H);else{var z=n(_);z!==null&&ne(M,z.startTime-B)}}function H(B,z){k=!1,j&&(j=!1,A(Z),Z=-1),x=!0;var G=w;try{for(O(z),y=n(f);y!==null&&(!(y.expirationTime>z)||B&&!ue());){var T=y.callback;if(typeof T=="function"){y.callback=null,w=y.priorityLevel;var Q=T(y.expirationTime<=z);z=e.unstable_now(),typeof Q=="function"?y.callback=Q:y===n(f)&&r(f),O(z)}else r(f);y=n(f)}if(y!==null)var K=!0;else{var J=n(_);J!==null&&ne(M,J.startTime-z),K=!1}return K}finally{y=null,w=G,x=!1}}var X=!1,Y=null,Z=-1,re=5,ie=-1;function ue(){return!(e.unstable_now()-ie<re)}function F(){if(Y!==null){var B=e.unstable_now();ie=B;var z=!0;try{z=Y(!0,B)}finally{z?C():(X=!1,Y=null)}}else X=!1}var C;if(typeof L=="function")C=function(){L(F)};else if(typeof MessageChannel<"u"){var N=new MessageChannel,P=N.port2;N.port1.onmessage=F,C=function(){P.postMessage(null)}}else C=function(){E(F,0)};function D(B){Y=B,X||(X=!0,C())}function ne(B,z){Z=E(function(){B(e.unstable_now())},z)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(B){B.callback=null},e.unstable_continueExecution=function(){k||x||(k=!0,D(H))},e.unstable_forceFrameRate=function(B){0>B||125<B?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):re=0<B?Math.floor(1e3/B):5},e.unstable_getCurrentPriorityLevel=function(){return w},e.unstable_getFirstCallbackNode=function(){return n(f)},e.unstable_next=function(B){switch(w){case 1:case 2:case 3:var z=3;break;default:z=w}var G=w;w=z;try{return B()}finally{w=G}},e.unstable_pauseExecution=function(){},e.unstable_requestPaint=function(){},e.unstable_runWithPriority=function(B,z){switch(B){case 1:case 2:case 3:case 4:case 5:break;default:B=3}var G=w;w=B;try{return z()}finally{w=G}},e.unstable_scheduleCallback=function(B,z,G){var T=e.unstable_now();switch(typeof G=="object"&&G!==null?(G=G.delay,G=typeof G=="number"&&0<G?T+G:T):G=T,B){case 1:var Q=-1;break;case 2:Q=250;break;case 5:Q=1073741823;break;case 4:Q=1e4;break;default:Q=5e3}return Q=G+Q,B={id:p++,callback:z,priorityLevel:B,startTime:G,expirationTime:Q,sortIndex:-1},G>T?(B.sortIndex=G,t(_,B),n(f)===null&&B===n(_)&&(j?(A(Z),Z=-1):j=!0,ne(M,G-T))):(B.sortIndex=Q,t(f,B),k||x||(k=!0,D(H))),B},e.unstable_shouldYield=ue,e.unstable_wrapCallback=function(B){var z=w;return function(){var G=w;w=z;try{return B.apply(this,arguments)}finally{w=G}}}})(M_)),M_}var dy;function V0(){return dy||(dy=1,T_.exports=H0()),T_.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 fy;function G0(){if(fy)return Br;fy=1;var e=Uf(),t=V0();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,_=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,p={},y={};function w(i){return f.call(y,i)?!0:f.call(p,i)?!1:_.test(i)?y[i]=!0:(p[i]=!0,!1)}function x(i,a,d,h){if(d!==null&&d.type===0)return!1;switch(typeof a){case"function":case"symbol":return!0;case"boolean":return h?!1:d!==null?!d.acceptsBooleans:(i=i.toLowerCase().slice(0,5),i!=="data-"&&i!=="aria-");default:return!1}}function k(i,a,d,h){if(a===null||typeof a>"u"||x(i,a,d,h))return!0;if(h)return!1;if(d!==null)switch(d.type){case 3:return!a;case 4:return a===!1;case 5:return isNaN(a);case 6:return isNaN(a)||1>a}return!1}function j(i,a,d,h,v,b,R){this.acceptsBooleans=a===2||a===3||a===4,this.attributeName=h,this.attributeNamespace=v,this.mustUseProperty=d,this.propertyName=i,this.type=a,this.sanitizeURL=b,this.removeEmptyString=R}var E={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(i){E[i]=new j(i,0,!1,i,null,!1,!1)}),[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(i){var a=i[0];E[a]=new j(a,1,!1,i[1],null,!1,!1)}),["contentEditable","draggable","spellCheck","value"].forEach(function(i){E[i]=new j(i,2,!1,i.toLowerCase(),null,!1,!1)}),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(i){E[i]=new j(i,2,!1,i,null,!1,!1)}),"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(i){E[i]=new j(i,3,!1,i.toLowerCase(),null,!1,!1)}),["checked","multiple","muted","selected"].forEach(function(i){E[i]=new j(i,3,!0,i,null,!1,!1)}),["capture","download"].forEach(function(i){E[i]=new j(i,4,!1,i,null,!1,!1)}),["cols","rows","size","span"].forEach(function(i){E[i]=new j(i,6,!1,i,null,!1,!1)}),["rowSpan","start"].forEach(function(i){E[i]=new j(i,5,!1,i.toLowerCase(),null,!1,!1)});var A=/[\-:]([a-z])/g;function L(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(A,L);E[a]=new j(a,1,!1,i,null,!1,!1)}),"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(i){var a=i.replace(A,L);E[a]=new j(a,1,!1,i,"http://www.w3.org/1999/xlink",!1,!1)}),["xml:base","xml:lang","xml:space"].forEach(function(i){var a=i.replace(A,L);E[a]=new j(a,1,!1,i,"http://www.w3.org/XML/1998/namespace",!1,!1)}),["tabIndex","crossOrigin"].forEach(function(i){E[i]=new j(i,1,!1,i.toLowerCase(),null,!1,!1)}),E.xlinkHref=new j("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1),["src","href","action","formAction"].forEach(function(i){E[i]=new j(i,1,!1,i.toLowerCase(),null,!0,!0)});function O(i,a,d,h){var v=E.hasOwnProperty(a)?E[a]:null;(v!==null?v.type!==0:h||!(2<a.length)||a[0]!=="o"&&a[0]!=="O"||a[1]!=="n"&&a[1]!=="N")&&(k(a,d,v,h)&&(d=null),h||v===null?w(a)&&(d===null?i.removeAttribute(a):i.setAttribute(a,""+d)):v.mustUseProperty?i[v.propertyName]=d===null?v.type===3?!1:"":d:(a=v.attributeName,h=v.attributeNamespace,d===null?i.removeAttribute(a):(v=v.type,d=v===3||v===4&&d===!0?"":""+d,h?i.setAttributeNS(h,a,d):i.setAttribute(a,d))))}var M=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,H=Symbol.for("react.element"),X=Symbol.for("react.portal"),Y=Symbol.for("react.fragment"),Z=Symbol.for("react.strict_mode"),re=Symbol.for("react.profiler"),ie=Symbol.for("react.provider"),ue=Symbol.for("react.context"),F=Symbol.for("react.forward_ref"),C=Symbol.for("react.suspense"),N=Symbol.for("react.suspense_list"),P=Symbol.for("react.memo"),D=Symbol.for("react.lazy"),ne=Symbol.for("react.offscreen"),B=Symbol.iterator;function z(i){return i===null||typeof i!="object"?null:(i=B&&i[B]||i["@@iterator"],typeof i=="function"?i:null)}var G=Object.assign,T;function Q(i){if(T===void 0)try{throw Error()}catch(d){var a=d.stack.trim().match(/\n( *(at )?)/);T=a&&a[1]||""}return`
|
|
34
|
-
`+T+i}var K=!1;function J(i,a){if(!i||K)return"";K=!0;var d=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{if(a)if(a=function(){throw Error()},Object.defineProperty(a.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(a,[])}catch(ye){var h=ye}Reflect.construct(i,[],a)}else{try{a.call()}catch(ye){h=ye}i.call(a.prototype)}else{try{throw Error()}catch(ye){h=ye}i()}}catch(ye){if(ye&&h&&typeof ye.stack=="string"){for(var v=ye.stack.split(`
|
|
35
|
-
`),b=h.stack.split(`
|
|
36
|
-
`),R=v.length-1,ee=b.length-1;1<=R&&0<=ee&&v[R]!==b[ee];)ee--;for(;1<=R&&0<=ee;R--,ee--)if(v[R]!==b[ee]){if(R!==1||ee!==1)do if(R--,ee--,0>ee||v[R]!==b[ee]){var se=`
|
|
37
|
-
`+v[R].replace(" at new "," at ");return i.displayName&&se.includes("<anonymous>")&&(se=se.replace("<anonymous>",i.displayName)),se}while(1<=R&&0<=ee);break}}}finally{K=!1,Error.prepareStackTrace=d}return(i=i?i.displayName||i.name:"")?Q(i):""}function oe(i){switch(i.tag){case 5:return Q(i.type);case 16:return Q("Lazy");case 13:return Q("Suspense");case 19:return Q("SuspenseList");case 0:case 2:case 15:return i=J(i.type,!1),i;case 11:return i=J(i.type.render,!1),i;case 1:return i=J(i.type,!0),i;default:return""}}function he(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 Y:return"Fragment";case X:return"Portal";case re:return"Profiler";case Z:return"StrictMode";case C:return"Suspense";case N:return"SuspenseList"}if(typeof i=="object")switch(i.$$typeof){case ue:return(i.displayName||"Context")+".Consumer";case ie:return(i._context.displayName||"Context")+".Provider";case F:var a=i.render;return i=i.displayName,i||(i=a.displayName||a.name||"",i=i!==""?"ForwardRef("+i+")":"ForwardRef"),i;case P:return a=i.displayName||null,a!==null?a:he(i.type)||"Memo";case D:a=i._payload,i=i._init;try{return he(i(a))}catch{}}return null}function _e(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 he(a);case 8:return a===Z?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof a=="function")return a.displayName||a.name||null;if(typeof a=="string")return a}return null}function we(i){switch(typeof i){case"boolean":case"number":case"string":case"undefined":return i;case"object":return i;default:return""}}function Ee(i){var a=i.type;return(i=i.nodeName)&&i.toLowerCase()==="input"&&(a==="checkbox"||a==="radio")}function ze(i){var a=Ee(i)?"checked":"value",d=Object.getOwnPropertyDescriptor(i.constructor.prototype,a),h=""+i[a];if(!i.hasOwnProperty(a)&&typeof d<"u"&&typeof d.get=="function"&&typeof d.set=="function"){var v=d.get,b=d.set;return Object.defineProperty(i,a,{configurable:!0,get:function(){return v.call(this)},set:function(R){h=""+R,b.call(this,R)}}),Object.defineProperty(i,a,{enumerable:d.enumerable}),{getValue:function(){return h},setValue:function(R){h=""+R},stopTracking:function(){i._valueTracker=null,delete i[a]}}}}function Ue(i){i._valueTracker||(i._valueTracker=ze(i))}function _t(i){if(!i)return!1;var a=i._valueTracker;if(!a)return!0;var d=a.getValue(),h="";return i&&(h=Ee(i)?i.checked?"true":"false":i.value),i=h,i!==d?(a.setValue(i),!0):!1}function Pe(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 et(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=we(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 Je(i,a){a=a.checked,a!=null&&O(i,"checked",a,!1)}function Se(i,a){Je(i,a);var d=we(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")?ct(i,a.type,d):a.hasOwnProperty("defaultValue")&&ct(i,a.type,we(a.defaultValue)),a.checked==null&&a.defaultChecked!=null&&(i.defaultChecked=!!a.defaultChecked)}function Ie(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 ct(i,a,d){(a!=="number"||Pe(i.ownerDocument)!==i)&&(d==null?i.defaultValue=""+i._wrapperState.initialValue:i.defaultValue!==""+d&&(i.defaultValue=""+d))}var ge=Array.isArray;function De(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=""+we(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 Ye(i,a){if(a.dangerouslySetInnerHTML!=null)throw Error(n(91));return G({},a,{value:void 0,defaultValue:void 0,children:""+i._wrapperState.initialValue})}function Dt(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(ge(d)){if(1<d.length)throw Error(n(93));d=d[0]}a=d}a==null&&(a=""),d=a}i._wrapperState={initialValue:we(d)}}function tn(i,a){var d=we(a.value),h=we(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 pn(i){var a=i.textContent;a===i._wrapperState.initialValue&&a!==""&&a!==null&&(i.value=a)}function Ut(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"?Ut(a):i==="http://www.w3.org/2000/svg"&&a==="foreignObject"?"http://www.w3.org/1999/xhtml":i}var un,Wn=(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(un=un||document.createElement("div"),un.innerHTML="<svg>"+a.valueOf().toString()+"</svg>",a=un.firstChild;i.firstChild;)i.removeChild(i.firstChild);for(;a.firstChild;)i.appendChild(a.firstChild)}});function Mt(i,a){if(a){var d=i.firstChild;if(d&&d===i.lastChild&&d.nodeType===3){d.nodeValue=a;return}}i.textContent=a}var wn={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},Dn=["Webkit","ms","Moz","O"];Object.keys(wn).forEach(function(i){Dn.forEach(function(a){a=a+i.charAt(0).toUpperCase()+i.substring(1),wn[a]=wn[i]})});function Mn(i,a,d){return a==null||typeof a=="boolean"||a===""?"":d||typeof a!="number"||a===0||wn.hasOwnProperty(i)&&wn[i]?(""+a).trim():a+"px"}function vn(i,a){i=i.style;for(var d in a)if(a.hasOwnProperty(d)){var h=d.indexOf("--")===0,v=Mn(d,a[d],h);d==="float"&&(d="cssFloat"),h?i.setProperty(d,v):i[d]=v}}var On=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 gn(i,a){if(a){if(On[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 Es(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 Hn=null;function as(i){return i=i.target||i.srcElement||window,i.correspondingUseElement&&(i=i.correspondingUseElement),i.nodeType===3?i.parentNode:i}var Tr=null,Vn=null,ce=null;function be(i){if(i=Ba(i)){if(typeof Tr!="function")throw Error(n(280));var a=i.stateNode;a&&(a=Dl(a),Tr(i.stateNode,i.type,a))}}function Ke(i){Vn?ce?ce.push(i):ce=[i]:Vn=i}function qe(){if(Vn){var i=Vn,a=ce;if(ce=Vn=null,be(i),a)for(i=0;i<a.length;i++)be(a[i])}}function st(i,a){return i(a)}function ut(){}var Tt=!1;function kt(i,a,d){if(Tt)return i(a,d);Tt=!0;try{return st(i,a,d)}finally{Tt=!1,(Vn!==null||ce!==null)&&(ut(),qe())}}function Gt(i,a){var d=i.stateNode;if(d===null)return null;var h=Dl(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 dt=!1;if(c)try{var Xt={};Object.defineProperty(Xt,"passive",{get:function(){dt=!0}}),window.addEventListener("test",Xt,Xt),window.removeEventListener("test",Xt,Xt)}catch{dt=!1}function Bt(i,a,d,h,v,b,R,ee,se){var ye=Array.prototype.slice.call(arguments,3);try{a.apply(d,ye)}catch(Me){this.onError(Me)}}var Ct=!1,pt=null,Ot=!1,Ce=null,Vt={onError:function(i){Ct=!0,pt=i}};function Et(i,a,d,h,v,b,R,ee,se){Ct=!1,pt=null,Bt.apply(Vt,arguments)}function ln(i,a,d,h,v,b,R,ee,se){if(Et.apply(this,arguments),Ct){if(Ct){var ye=pt;Ct=!1,pt=null}else throw Error(n(198));Ot||(Ot=!0,Ce=ye)}}function $t(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 ls(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 cs(i){if($t(i)!==i)throw Error(n(188))}function Ks(i){var a=i.alternate;if(!a){if(a=$t(i),a===null)throw Error(n(188));return a!==i?null:i}for(var d=i,h=a;;){var v=d.return;if(v===null)break;var b=v.alternate;if(b===null){if(h=v.return,h!==null){d=h;continue}break}if(v.child===b.child){for(b=v.child;b;){if(b===d)return cs(v),i;if(b===h)return cs(v),a;b=b.sibling}throw Error(n(188))}if(d.return!==h.return)d=v,h=b;else{for(var R=!1,ee=v.child;ee;){if(ee===d){R=!0,d=v,h=b;break}if(ee===h){R=!0,h=v,d=b;break}ee=ee.sibling}if(!R){for(ee=b.child;ee;){if(ee===d){R=!0,d=b,h=v;break}if(ee===h){R=!0,h=b,d=v;break}ee=ee.sibling}if(!R)throw Error(n(189))}}if(d.alternate!==h)throw Error(n(190))}if(d.tag!==3)throw Error(n(188));return d.stateNode.current===d?i:a}function $s(i){return i=Ks(i),i!==null?fr(i):null}function fr(i){if(i.tag===5||i.tag===6)return i;for(i=i.child;i!==null;){var a=fr(i);if(a!==null)return a;i=i.sibling}return null}var Ys=t.unstable_scheduleCallback,ao=t.unstable_cancelCallback,xe=t.unstable_shouldYield,Gn=t.unstable_requestPaint,hn=t.unstable_now,lo=t.unstable_getCurrentPriorityLevel,Mi=t.unstable_ImmediatePriority,Mr=t.unstable_UserBlockingPriority,hr=t.unstable_NormalPriority,Hr=t.unstable_LowPriority,it=t.unstable_IdlePriority,rn=null,gs=null;function ci(i){if(gs&&typeof gs.onCommitFiberRoot=="function")try{gs.onCommitFiberRoot(rn,i,void 0,(i.current.flags&128)===128)}catch{}}var us=Math.clz32?Math.clz32:Sa,co=Math.log,uo=Math.LN2;function Sa(i){return i>>>=0,i===0?32:31-(co(i)/uo|0)|0}var Fn=64,mr=4194304;function Rn(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 _r(i,a){var d=i.pendingLanes;if(d===0)return 0;var h=0,v=i.suspendedLanes,b=i.pingedLanes,R=d&268435455;if(R!==0){var ee=R&~v;ee!==0?h=Rn(ee):(b&=R,b!==0&&(h=Rn(b)))}else R=d&~v,R!==0?h=Rn(R):b!==0&&(h=Rn(b));if(h===0)return 0;if(a!==0&&a!==h&&(a&v)===0&&(v=h&-h,b=a&-a,v>=b||v===16&&(b&4194240)!==0))return a;if((h&4)!==0&&(h|=d&16),a=i.entangledLanes,a!==0)for(i=i.entanglements,a&=h;0<a;)d=31-us(a),v=1<<d,h|=i[d],a&=~v;return h}function fo(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 Xn(i,a){for(var d=i.suspendedLanes,h=i.pingedLanes,v=i.expirationTimes,b=i.pendingLanes;0<b;){var R=31-us(b),ee=1<<R,se=v[R];se===-1?((ee&d)===0||(ee&h)!==0)&&(v[R]=fo(ee,a)):se<=a&&(i.expiredLanes|=ee),b&=~ee}}function Js(i){return i=i.pendingLanes&-1073741825,i!==0?i:i&1073741824?1073741824:0}function ds(){var i=Fn;return Fn<<=1,(Fn&4194240)===0&&(Fn=64),i}function Vr(i){for(var a=[],d=0;31>d;d++)a.push(i);return a}function ys(i,a,d){i.pendingLanes|=a,a!==536870912&&(i.suspendedLanes=0,i.pingedLanes=0),i=i.eventTimes,a=31-us(a),i[a]=d}function ka(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-us(d),b=1<<v;a[v]=0,h[v]=-1,i[v]=-1,d&=~b}}function ho(i,a){var d=i.entangledLanes|=a;for(i=i.entanglements;d;){var h=31-us(d),v=1<<h;v&a|i[h]&a&&(i[h]|=a),d&=~v}}var on=0;function El(i){return i&=-i,1<i?4<i?(i&268435455)!==0?16:536870912:4:1}var Ri,pr,As,Na,Rr,ui=!1,Li=[],Xs=null,Ts=null,Lr=null,Zs=new Map,Ii=new Map,gr=[],ws="mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput copy cut paste click change contextmenu reset submit".split(" ");function Oi(i,a){switch(i){case"focusin":case"focusout":Xs=null;break;case"dragenter":case"dragleave":Ts=null;break;case"mouseover":case"mouseout":Lr=null;break;case"pointerover":case"pointerout":Zs.delete(a.pointerId);break;case"gotpointercapture":case"lostpointercapture":Ii.delete(a.pointerId)}}function Uo(i,a,d,h,v,b){return i===null||i.nativeEvent!==b?(i={blockedOn:a,domEventName:d,eventSystemFlags:h,nativeEvent:b,targetContainers:[v]},a!==null&&(a=Ba(a),a!==null&&pr(a)),i):(i.eventSystemFlags|=h,a=i.targetContainers,v!==null&&a.indexOf(v)===-1&&a.push(v),i)}function $l(i,a,d,h,v){switch(a){case"focusin":return Xs=Uo(Xs,i,a,d,h,v),!0;case"dragenter":return Ts=Uo(Ts,i,a,d,h,v),!0;case"mouseover":return Lr=Uo(Lr,i,a,d,h,v),!0;case"pointerover":var b=v.pointerId;return Zs.set(b,Uo(Zs.get(b)||null,i,a,d,h,v)),!0;case"gotpointercapture":return b=v.pointerId,Ii.set(b,Uo(Ii.get(b)||null,i,a,d,h,v)),!0}return!1}function Qs(i){var a=bo(i.target);if(a!==null){var d=$t(a);if(d!==null){if(a=d.tag,a===13){if(a=ls(d),a!==null){i.blockedOn=a,Rr(i.priority,function(){As(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 Wo(i){if(i.blockedOn!==null)return!1;for(var a=i.targetContainers;0<a.length;){var d=ae(i.domEventName,i.eventSystemFlags,a[0],i.nativeEvent);if(d===null){d=i.nativeEvent;var h=new d.constructor(d.type,d);Hn=h,d.target.dispatchEvent(h),Hn=null}else return a=Ba(d),a!==null&&pr(a),i.blockedOn=d,!1;a.shift()}return!0}function Gr(i,a,d){Wo(i)&&d.delete(a)}function _c(){ui=!1,Xs!==null&&Wo(Xs)&&(Xs=null),Ts!==null&&Wo(Ts)&&(Ts=null),Lr!==null&&Wo(Lr)&&(Lr=null),Zs.forEach(Gr),Ii.forEach(Gr)}function yr(i,a){i.blockedOn===a&&(i.blockedOn=null,ui||(ui=!0,t.unstable_scheduleCallback(t.unstable_NormalPriority,_c)))}function mo(i){function a(v){return yr(v,i)}if(0<Li.length){yr(Li[0],i);for(var d=1;d<Li.length;d++){var h=Li[d];h.blockedOn===i&&(h.blockedOn=null)}}for(Xs!==null&&yr(Xs,i),Ts!==null&&yr(Ts,i),Lr!==null&&yr(Lr,i),Zs.forEach(a),Ii.forEach(a),d=0;d<gr.length;d++)h=gr[d],h.blockedOn===i&&(h.blockedOn=null);for(;0<gr.length&&(d=gr[0],d.blockedOn===null);)Qs(d),d.blockedOn===null&&gr.shift()}var Fs=M.ReactCurrentBatchConfig,qo=!0;function Ho(i,a,d,h){var v=on,b=Fs.transition;Fs.transition=null;try{on=1,_o(i,a,d,h)}finally{on=v,Fs.transition=b}}function Vo(i,a,d,h){var v=on,b=Fs.transition;Fs.transition=null;try{on=4,_o(i,a,d,h)}finally{on=v,Fs.transition=b}}function _o(i,a,d,h){if(qo){var v=ae(i,a,d,h);if(v===null)Oa(i,a,h,U,d),Oi(i,h);else if($l(v,i,a,d,h))h.stopPropagation();else if(Oi(i,h),a&4&&-1<ws.indexOf(i)){for(;v!==null;){var b=Ba(v);if(b!==null&&Ri(b),b=ae(i,a,d,h),b===null&&Oa(i,a,h,U,d),b===v)break;v=b}v!==null&&h.stopPropagation()}else Oa(i,a,h,null,d)}}var U=null;function ae(i,a,d,h){if(U=null,i=as(h),i=bo(i),i!==null)if(a=$t(i),a===null)i=null;else if(d=a.tag,d===13){if(i=ls(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 U=i,null}function je(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(lo()){case Mi:return 1;case Mr:return 4;case hr:case Hr:return 16;case it:return 536870912;default:return 16}default:return 16}}var Ne=null,ke=null,Be=null;function ft(){if(Be)return Be;var i,a=ke,d=a.length,h,v="value"in Ne?Ne.value:Ne.textContent,b=v.length;for(i=0;i<d&&a[i]===v[i];i++);var R=d-i;for(h=1;h<=R&&a[d-h]===v[b-h];h++);return Be=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 gt(){return!0}function Ft(){return!1}function Kt(i){function a(d,h,v,b,R){this._reactName=d,this._targetInst=v,this.type=h,this.nativeEvent=b,this.target=R,this.currentTarget=null;for(var ee in i)i.hasOwnProperty(ee)&&(d=i[ee],this[ee]=d?d(b):b[ee]);return this.isDefaultPrevented=(b.defaultPrevented!=null?b.defaultPrevented:b.returnValue===!1)?gt:Ft,this.isPropagationStopped=Ft,this}return G(a.prototype,{preventDefault:function(){this.defaultPrevented=!0;var d=this.nativeEvent;d&&(d.preventDefault?d.preventDefault():typeof d.returnValue!="unknown"&&(d.returnValue=!1),this.isDefaultPrevented=gt)},stopPropagation:function(){var d=this.nativeEvent;d&&(d.stopPropagation?d.stopPropagation():typeof d.cancelBubble!="unknown"&&(d.cancelBubble=!0),this.isPropagationStopped=gt)},persist:function(){},isPersistent:gt}),a}var vs={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(i){return i.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},Rt=Kt(vs),an=G({},vs,{view:0,detail:0}),Nn=Kt(an),mn,Zn,er,Kr=G({},an,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:Ju,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!==er&&(er&&i.type==="mousemove"?(mn=i.screenX-er.screenX,Zn=i.screenY-er.screenY):Zn=mn=0,er=i),mn)},movementY:function(i){return"movementY"in i?i.movementY:Zn}}),Pi=Kt(Kr),Ca=G({},Kr,{dataTransfer:0}),Jf=Kt(Ca),pc=G({},an,{relatedTarget:0}),Al=Kt(pc),gc=G({},vs,{animationName:0,elapsedTime:0,pseudoElement:0}),yc=Kt(gc),wc=G({},vs,{clipboardData:function(i){return"clipboardData"in i?i.clipboardData:window.clipboardData}}),Xf=Kt(wc),Go=G({},vs,{data:0}),Hu=Kt(Go),Vu={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},Gu={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"},Ku={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function Yu(i){var a=this.nativeEvent;return a.getModifierState?a.getModifierState(i):(i=Ku[i])?!!a[i]:!1}function Ju(){return Yu}var Xu=G({},an,{key:function(i){if(i.key){var a=Vu[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"?Gu[i.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:Ju,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}}),c_=Kt(Xu),Zf=G({},Kr,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),vc=Kt(Zf),nn=G({},an,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:Ju}),Zu=Kt(nn),u_=G({},vs,{propertyName:0,elapsedTime:0,pseudoElement:0}),Qu=Kt(u_),d_=G({},Kr,{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}),ed=Kt(d_),f_=[9,13,27,32],Qn=c&&"CompositionEvent"in window,Ir=null;c&&"documentMode"in document&&(Ir=document.documentMode);var Qf=c&&"TextEvent"in window&&!Ir,xc=c&&(!Qn||Ir&&8<Ir&&11>=Ir),Ko=" ",bc=!1;function Ea(i,a){switch(i){case"keyup":return f_.indexOf(a.keyCode)!==-1;case"keydown":return a.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function eh(i){return i=i.detail,typeof i=="object"&&"data"in i?i.data:null}var Di=!1;function h_(i,a){switch(i){case"compositionend":return eh(a);case"keypress":return a.which!==32?null:(bc=!0,Ko);case"textInput":return i=a.data,i===Ko&&bc?null:i;default:return null}}function m_(i,a){if(Di)return i==="compositionend"||!Qn&&Ea(i,a)?(i=ft(),Be=ke=Ne=null,Di=!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 th={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 $a(i){var a=i&&i.nodeName&&i.nodeName.toLowerCase();return a==="input"?!!th[i.type]:a==="textarea"}function nh(i,a,d,h){Ke(h),a=Pa(a,"onChange"),0<a.length&&(d=new Rt("onChange","change",null,d,h),i.push({event:d,listeners:a}))}var Fi=null,Yo=null;function __(i){Ll(i,0)}function Tl(i){var a=Ua(i);if(_t(a))return i}function td(i,a){if(i==="change")return a}var jc=!1;if(c){var Sc;if(c){var Aa="oninput"in document;if(!Aa){var nd=document.createElement("div");nd.setAttribute("oninput","return;"),Aa=typeof nd.oninput=="function"}Sc=Aa}else Sc=!1;jc=Sc&&(!document.documentMode||9<document.documentMode)}function sd(){Fi&&(Fi.detachEvent("onpropertychange",sh),Yo=Fi=null)}function sh(i){if(i.propertyName==="value"&&Tl(Yo)){var a=[];nh(a,Yo,i,as(i)),kt(__,a)}}function kc(i,a,d){i==="focusin"?(sd(),Fi=a,Yo=d,Fi.attachEvent("onpropertychange",sh)):i==="focusout"&&sd()}function rh(i){if(i==="selectionchange"||i==="keyup"||i==="keydown")return Tl(Yo)}function rd(i,a){if(i==="click")return Tl(a)}function p_(i,a){if(i==="input"||i==="change")return Tl(a)}function id(i,a){return i===a&&(i!==0||1/i===1/a)||i!==i&&a!==a}var Yr=typeof Object.is=="function"?Object.is:id;function Ta(i,a){if(Yr(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)||!Yr(i[v],a[v]))return!1}return!0}function ih(i){for(;i&&i.firstChild;)i=i.firstChild;return i}function Nc(i,a){var d=ih(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=ih(d)}}function oh(i,a){return i&&a?i===a?!0:i&&i.nodeType===3?!1:a&&a.nodeType===3?oh(i,a.parentNode):"contains"in i?i.contains(a):i.compareDocumentPosition?!!(i.compareDocumentPosition(a)&16):!1:!1}function Cc(){for(var i=window,a=Pe();a instanceof i.HTMLIFrameElement;){try{var d=typeof a.contentWindow.location.href=="string"}catch{d=!1}if(d)i=a.contentWindow;else break;a=Pe(i.document)}return a}function od(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 g_(i){var a=Cc(),d=i.focusedElem,h=i.selectionRange;if(a!==d&&d&&d.ownerDocument&&oh(d.ownerDocument.documentElement,d)){if(h!==null&&od(d)){if(a=h.start,i=h.end,i===void 0&&(i=a),"selectionStart"in d)d.selectionStart=a,d.selectionEnd=Math.min(i,d.value.length);else if(i=(a=d.ownerDocument||document)&&a.defaultView||window,i.getSelection){i=i.getSelection();var v=d.textContent.length,b=Math.min(h.start,v);h=h.end===void 0?b:Math.min(h.end,v),!i.extend&&b>h&&(v=h,h=b,b=v),v=Nc(d,b);var R=Nc(d,h);v&&R&&(i.rangeCount!==1||i.anchorNode!==v.node||i.anchorOffset!==v.offset||i.focusNode!==R.node||i.focusOffset!==R.offset)&&(a=a.createRange(),a.setStart(v.node,v.offset),i.removeAllRanges(),b>h?(i.addRange(a),i.extend(R.node,R.offset)):(a.setEnd(R.node,R.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 y_=c&&"documentMode"in document&&11>=document.documentMode,Jr=null,Ec=null,po=null,ad=!1;function Ml(i,a,d){var h=d.window===d?d.document:d.nodeType===9?d:d.ownerDocument;ad||Jr==null||Jr!==Pe(h)||(h=Jr,"selectionStart"in h&&od(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}),po&&Ta(po,h)||(po=h,h=Pa(Ec,"onSelect"),0<h.length&&(a=new Rt("onSelect","select",null,a,d),i.push({event:a,listeners:h}),a.target=Jr)))}function zi(i,a){var d={};return d[i.toLowerCase()]=a.toLowerCase(),d["Webkit"+i]="webkit"+a,d["Moz"+i]="moz"+a,d}var di={animationend:zi("Animation","AnimationEnd"),animationiteration:zi("Animation","AnimationIteration"),animationstart:zi("Animation","AnimationStart"),transitionend:zi("Transition","TransitionEnd")},go={},Ma={};c&&(Ma=document.createElement("div").style,"AnimationEvent"in window||(delete di.animationend.animation,delete di.animationiteration.animation,delete di.animationstart.animation),"TransitionEvent"in window||delete di.transitionend.transition);function Jo(i){if(go[i])return go[i];if(!di[i])return i;var a=di[i],d;for(d in a)if(a.hasOwnProperty(d)&&d in Ma)return go[i]=a[d];return i}var $c=Jo("animationend"),ld=Jo("animationiteration"),Ra=Jo("animationstart"),cd=Jo("transitionend"),La=new Map,Rl="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 yo(i,a){La.set(i,a),l(a,[i])}for(var Ac=0;Ac<Rl.length;Ac++){var ud=Rl[Ac],w_=ud.toLowerCase(),Tc=ud[0].toUpperCase()+ud.slice(1);yo(w_,"on"+Tc)}yo($c,"onAnimationEnd"),yo(ld,"onAnimationIteration"),yo(Ra,"onAnimationStart"),yo("dblclick","onDoubleClick"),yo("focusin","onFocus"),yo("focusout","onBlur"),yo(cd,"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 wr="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(" "),Ia=new Set("cancel close invalid load scroll toggle".split(" ").concat(wr));function ah(i,a,d){var h=i.type||"unknown-event";i.currentTarget=d,ln(h,a,void 0,i),i.currentTarget=null}function Ll(i,a){a=(a&4)!==0;for(var d=0;d<i.length;d++){var h=i[d],v=h.event;h=h.listeners;e:{var b=void 0;if(a)for(var R=h.length-1;0<=R;R--){var ee=h[R],se=ee.instance,ye=ee.currentTarget;if(ee=ee.listener,se!==b&&v.isPropagationStopped())break e;ah(v,ee,ye),b=se}else for(R=0;R<h.length;R++){if(ee=h[R],se=ee.instance,ye=ee.currentTarget,ee=ee.listener,se!==b&&v.isPropagationStopped())break e;ah(v,ee,ye),b=se}}}if(Ot)throw i=Ce,Ot=!1,Ce=null,i}function Cn(i,a){var d=a[Lc];d===void 0&&(d=a[Lc]=new Set);var h=i+"__bubble";d.has(h)||(Bi(a,i,2,!1),d.add(h))}function Il(i,a,d){var h=0;a&&(h|=4),Bi(d,i,h,a)}var wo="_reactListening"+Math.random().toString(36).slice(2);function Ms(i){if(!i[wo]){i[wo]=!0,r.forEach(function(d){d!=="selectionchange"&&(Ia.has(d)||Il(d,!1,i),Il(d,!0,i))});var a=i.nodeType===9?i:i.ownerDocument;a===null||a[wo]||(a[wo]=!0,Il("selectionchange",!1,a))}}function Bi(i,a,d,h){switch(je(a)){case 1:var v=Ho;break;case 4:v=Vo;break;default:v=_o}d=v.bind(null,a,d,i),v=void 0,!dt||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 Oa(i,a,d,h,v){var b=h;if((a&1)===0&&(a&2)===0&&h!==null)e:for(;;){if(h===null)return;var R=h.tag;if(R===3||R===4){var ee=h.stateNode.containerInfo;if(ee===v||ee.nodeType===8&&ee.parentNode===v)break;if(R===4)for(R=h.return;R!==null;){var se=R.tag;if((se===3||se===4)&&(se=R.stateNode.containerInfo,se===v||se.nodeType===8&&se.parentNode===v))return;R=R.return}for(;ee!==null;){if(R=bo(ee),R===null)return;if(se=R.tag,se===5||se===6){h=b=R;continue e}ee=ee.parentNode}}h=h.return}kt(function(){var ye=b,Me=as(d),Le=[];e:{var Te=La.get(i);if(Te!==void 0){var Xe=Rt,tt=i;switch(i){case"keypress":if(ot(d)===0)break e;case"keydown":case"keyup":Xe=c_;break;case"focusin":tt="focus",Xe=Al;break;case"focusout":tt="blur",Xe=Al;break;case"beforeblur":case"afterblur":Xe=Al;break;case"click":if(d.button===2)break e;case"auxclick":case"dblclick":case"mousedown":case"mousemove":case"mouseup":case"mouseout":case"mouseover":case"contextmenu":Xe=Pi;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":Xe=Jf;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":Xe=Zu;break;case $c:case ld:case Ra:Xe=yc;break;case cd:Xe=Qu;break;case"scroll":Xe=Nn;break;case"wheel":Xe=ed;break;case"copy":case"cut":case"paste":Xe=Xf;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":Xe=vc}var nt=(a&4)!==0,os=!nt&&i==="scroll",de=nt?Te!==null?Te+"Capture":null:Te;nt=[];for(var le=ye,me;le!==null;){me=le;var Fe=me.stateNode;if(me.tag===5&&Fe!==null&&(me=Fe,de!==null&&(Fe=Gt(le,de),Fe!=null&&nt.push(fi(le,Fe,me)))),os)break;le=le.return}0<nt.length&&(Te=new Xe(Te,tt,null,d,Me),Le.push({event:Te,listeners:nt}))}}if((a&7)===0){e:{if(Te=i==="mouseover"||i==="pointerover",Xe=i==="mouseout"||i==="pointerout",Te&&d!==Hn&&(tt=d.relatedTarget||d.fromElement)&&(bo(tt)||tt[xr]))break e;if((Xe||Te)&&(Te=Me.window===Me?Me:(Te=Me.ownerDocument)?Te.defaultView||Te.parentWindow:window,Xe?(tt=d.relatedTarget||d.toElement,Xe=ye,tt=tt?bo(tt):null,tt!==null&&(os=$t(tt),tt!==os||tt.tag!==5&&tt.tag!==6)&&(tt=null)):(Xe=null,tt=ye),Xe!==tt)){if(nt=Pi,Fe="onMouseLeave",de="onMouseEnter",le="mouse",(i==="pointerout"||i==="pointerover")&&(nt=vc,Fe="onPointerLeave",de="onPointerEnter",le="pointer"),os=Xe==null?Te:Ua(Xe),me=tt==null?Te:Ua(tt),Te=new nt(Fe,le+"leave",Xe,d,Me),Te.target=os,Te.relatedTarget=me,Fe=null,bo(Me)===ye&&(nt=new nt(de,le+"enter",tt,d,Me),nt.target=me,nt.relatedTarget=os,Fe=nt),os=Fe,Xe&&tt)t:{for(nt=Xe,de=tt,le=0,me=nt;me;me=hi(me))le++;for(me=0,Fe=de;Fe;Fe=hi(Fe))me++;for(;0<le-me;)nt=hi(nt),le--;for(;0<me-le;)de=hi(de),me--;for(;le--;){if(nt===de||de!==null&&nt===de.alternate)break t;nt=hi(nt),de=hi(de)}nt=null}else nt=null;Xe!==null&&mi(Le,Te,Xe,nt,!1),tt!==null&&os!==null&&mi(Le,os,tt,nt,!0)}}e:{if(Te=ye?Ua(ye):window,Xe=Te.nodeName&&Te.nodeName.toLowerCase(),Xe==="select"||Xe==="input"&&Te.type==="file")var rt=td;else if($a(Te))if(jc)rt=p_;else{rt=rh;var yt=kc}else(Xe=Te.nodeName)&&Xe.toLowerCase()==="input"&&(Te.type==="checkbox"||Te.type==="radio")&&(rt=rd);if(rt&&(rt=rt(i,ye))){nh(Le,rt,d,Me);break e}yt&&yt(i,Te,ye),i==="focusout"&&(yt=Te._wrapperState)&&yt.controlled&&Te.type==="number"&&ct(Te,"number",Te.value)}switch(yt=ye?Ua(ye):window,i){case"focusin":($a(yt)||yt.contentEditable==="true")&&(Jr=yt,Ec=ye,po=null);break;case"focusout":po=Ec=Jr=null;break;case"mousedown":ad=!0;break;case"contextmenu":case"mouseup":case"dragend":ad=!1,Ml(Le,d,Me);break;case"selectionchange":if(y_)break;case"keydown":case"keyup":Ml(Le,d,Me)}var wt;if(Qn)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 Di?Ea(i,d)&&(Nt="onCompositionEnd"):i==="keydown"&&d.keyCode===229&&(Nt="onCompositionStart");Nt&&(xc&&d.locale!=="ko"&&(Di||Nt!=="onCompositionStart"?Nt==="onCompositionEnd"&&Di&&(wt=ft()):(Ne=Me,ke="value"in Ne?Ne.value:Ne.textContent,Di=!0)),yt=Pa(ye,Nt),0<yt.length&&(Nt=new Hu(Nt,i,null,d,Me),Le.push({event:Nt,listeners:yt}),wt?Nt.data=wt:(wt=eh(d),wt!==null&&(Nt.data=wt)))),(wt=Qf?h_(i,d):m_(i,d))&&(ye=Pa(ye,"onBeforeInput"),0<ye.length&&(Me=new Hu("onBeforeInput","beforeinput",null,d,Me),Le.push({event:Me,listeners:ye}),Me.data=wt))}Ll(Le,a)})}function fi(i,a,d){return{instance:i,listener:a,currentTarget:d}}function Pa(i,a){for(var d=a+"Capture",h=[];i!==null;){var v=i,b=v.stateNode;v.tag===5&&b!==null&&(v=b,b=Gt(i,d),b!=null&&h.unshift(fi(i,b,v)),b=Gt(i,a),b!=null&&h.push(fi(i,b,v))),i=i.return}return h}function hi(i){if(i===null)return null;do i=i.return;while(i&&i.tag!==5);return i||null}function mi(i,a,d,h,v){for(var b=a._reactName,R=[];d!==null&&d!==h;){var ee=d,se=ee.alternate,ye=ee.stateNode;if(se!==null&&se===h)break;ee.tag===5&&ye!==null&&(ee=ye,v?(se=Gt(d,b),se!=null&&R.unshift(fi(d,se,ee))):v||(se=Gt(d,b),se!=null&&R.push(fi(d,se,ee)))),d=d.return}R.length!==0&&i.push({event:a,listeners:R})}var Mc=/\r\n?/g,Ol=/\u0000|\uFFFD/g;function Xo(i){return(typeof i=="string"?i:""+i).replace(Mc,`
|
|
38
|
-
`).replace(Ol,"")}function Xr(i,a,d){if(a=Xo(a),Xo(i)!==a&&d)throw Error(n(425))}function xs(){}var Ui=null,vo=null;function Da(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 Wi=typeof setTimeout=="function"?setTimeout:void 0,dd=typeof clearTimeout=="function"?clearTimeout:void 0,Pl=typeof Promise=="function"?Promise:void 0,_i=typeof queueMicrotask=="function"?queueMicrotask:typeof Pl<"u"?function(i){return Pl.resolve(null).then(i).catch(xo)}:Wi;function xo(i){setTimeout(function(){throw i})}function Or(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),mo(a);return}h--}else d!=="$"&&d!=="$?"&&d!=="$!"||h++;d=v}while(d);mo(a)}function qi(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 Rc(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 Fa=Math.random().toString(36).slice(2),vr="__reactFiber$"+Fa,za="__reactProps$"+Fa,xr="__reactContainer$"+Fa,Lc="__reactEvents$"+Fa,fd="__reactListeners$"+Fa,lh="__reactHandles$"+Fa;function bo(i){var a=i[vr];if(a)return a;for(var d=i.parentNode;d;){if(a=d[xr]||d[vr]){if(d=a.alternate,a.child!==null||d!==null&&d.child!==null)for(i=Rc(i);i!==null;){if(d=i[vr])return d;i=Rc(i)}return a}i=d,d=i.parentNode}return null}function Ba(i){return i=i[vr]||i[xr],!i||i.tag!==5&&i.tag!==6&&i.tag!==13&&i.tag!==3?null:i}function Ua(i){if(i.tag===5||i.tag===6)return i.stateNode;throw Error(n(33))}function Dl(i){return i[za]||null}var hd=[],Zo=-1;function jo(i){return{current:i}}function xn(i){0>Zo||(i.current=hd[Zo],hd[Zo]=null,Zo--)}function bn(i,a){Zo++,hd[Zo]=i.current,i.current=a}var Hi={},Rs=jo(Hi),zs=jo(!1),Zr=Hi;function Wa(i,a){var d=i.type.contextTypes;if(!d)return Hi;var h=i.stateNode;if(h&&h.__reactInternalMemoizedUnmaskedChildContext===a)return h.__reactInternalMemoizedMaskedChildContext;var v={},b;for(b in d)v[b]=a[b];return h&&(i=i.stateNode,i.__reactInternalMemoizedUnmaskedChildContext=a,i.__reactInternalMemoizedMaskedChildContext=v),v}function fs(i){return i=i.childContextTypes,i!=null}function qa(){xn(zs),xn(Rs)}function Fl(i,a,d){if(Rs.current!==Hi)throw Error(n(168));bn(Rs,a),bn(zs,d)}function md(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,_e(i)||"Unknown",v));return G({},d,h)}function Vi(i){return i=(i=i.stateNode)&&i.__reactInternalMemoizedMergedChildContext||Hi,Zr=Rs.current,bn(Rs,i),bn(zs,zs.current),!0}function ch(i,a,d){var h=i.stateNode;if(!h)throw Error(n(169));d?(i=md(i,a,Zr),h.__reactInternalMemoizedMergedChildContext=i,xn(zs),xn(Rs),bn(Rs,i)):xn(zs),bn(zs,d)}var Pr=null,Ic=!1,So=!1;function uh(i){Pr===null?Pr=[i]:Pr.push(i)}function Oc(i){Ic=!0,uh(i)}function ko(){if(!So&&Pr!==null){So=!0;var i=0,a=on;try{var d=Pr;for(on=1;i<d.length;i++){var h=d[i];do h=h(!0);while(h!==null)}Pr=null,Ic=!1}catch(v){throw Pr!==null&&(Pr=Pr.slice(i+1)),Ys(Mi,ko),v}finally{on=a,So=!1}}return null}var br=[],Qo=0,No=null,Co=0,jr=[],tr=0,Qr=null,ei=1,nr="";function Gi(i,a){br[Qo++]=Co,br[Qo++]=No,No=i,Co=a}function dh(i,a,d){jr[tr++]=ei,jr[tr++]=nr,jr[tr++]=Qr,Qr=i;var h=ei;i=nr;var v=32-us(h)-1;h&=~(1<<v),d+=1;var b=32-us(a)+v;if(30<b){var R=v-v%5;b=(h&(1<<R)-1).toString(32),h>>=R,v-=R,ei=1<<32-us(a)+v|d<<v|h,nr=b+i}else ei=1<<b|d<<v|h,nr=i}function zl(i){i.return!==null&&(Gi(i,1),dh(i,1,0))}function Pc(i){for(;i===No;)No=br[--Qo],br[Qo]=null,Co=br[--Qo],br[Qo]=null;for(;i===Qr;)Qr=jr[--tr],jr[tr]=null,nr=jr[--tr],jr[tr]=null,ei=jr[--tr],jr[tr]=null}var Sr=null,kr=null,_n=!1,En=null;function Bl(i,a){var d=fe(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 Dc(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,Sr=i,kr=qi(a.firstChild),!0):!1;case 6:return a=i.pendingProps===""||a.nodeType!==3?null:a,a!==null?(i.stateNode=a,Sr=i,kr=null,!0):!1;case 13:return a=a.nodeType!==8?null:a,a!==null?(d=Qr!==null?{id:ei,overflow:nr}:null,i.memoizedState={dehydrated:a,treeContext:d,retryLane:1073741824},d=fe(18,null,null,0),d.stateNode=a,d.return=i,i.child=d,Sr=i,kr=null,!0):!1;default:return!1}}function _d(i){return(i.mode&1)!==0&&(i.flags&128)===0}function pd(i){if(_n){var a=kr;if(a){var d=a;if(!Dc(i,a)){if(_d(i))throw Error(n(418));a=qi(d.nextSibling);var h=Sr;a&&Dc(i,a)?Bl(h,d):(i.flags=i.flags&-4097|2,_n=!1,Sr=i)}}else{if(_d(i))throw Error(n(418));i.flags=i.flags&-4097|2,_n=!1,Sr=i}}}function Fc(i){for(i=i.return;i!==null&&i.tag!==5&&i.tag!==3&&i.tag!==13;)i=i.return;Sr=i}function zc(i){if(i!==Sr)return!1;if(!_n)return Fc(i),_n=!0,!1;var a;if((a=i.tag!==3)&&!(a=i.tag!==5)&&(a=i.type,a=a!=="head"&&a!=="body"&&!Da(i.type,i.memoizedProps)),a&&(a=kr)){if(_d(i))throw Ul(),Error(n(418));for(;a;)Bl(i,a),a=qi(a.nextSibling)}if(Fc(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){kr=qi(i.nextSibling);break e}a--}else d!=="$"&&d!=="$!"&&d!=="$?"||a++}i=i.nextSibling}kr=null}}else kr=Sr?qi(i.stateNode.nextSibling):null;return!0}function Ul(){for(var i=kr;i;)i=qi(i.nextSibling)}function ea(){kr=Sr=null,_n=!1}function Ha(i){En===null?En=[i]:En.push(i)}var fh=M.ReactCurrentBatchConfig;function Va(i,a,d){if(i=d.ref,i!==null&&typeof i!="function"&&typeof i!="object"){if(d._owner){if(d=d._owner,d){if(d.tag!==1)throw Error(n(309));var h=d.stateNode}if(!h)throw Error(n(147,i));var v=h,b=""+i;return a!==null&&a.ref!==null&&typeof a.ref=="function"&&a.ref._stringRef===b?a.ref:(a=function(R){var ee=v.refs;R===null?delete ee[b]:ee[b]=R},a._stringRef=b,a)}if(typeof i!="string")throw Error(n(284));if(!d._owner)throw Error(n(290,i))}return i}function Bc(i,a){throw i=Object.prototype.toString.call(a),Error(n(31,i==="[object Object]"?"object with keys {"+Object.keys(a).join(", ")+"}":i))}function gd(i){var a=i._init;return a(i._payload)}function yd(i){function a(de,le){if(i){var me=de.deletions;me===null?(de.deletions=[le],de.flags|=16):me.push(le)}}function d(de,le){if(!i)return null;for(;le!==null;)a(de,le),le=le.sibling;return null}function h(de,le){for(de=new Map;le!==null;)le.key!==null?de.set(le.key,le):de.set(le.index,le),le=le.sibling;return de}function v(de,le){return de=Oe(de,le),de.index=0,de.sibling=null,de}function b(de,le,me){return de.index=me,i?(me=de.alternate,me!==null?(me=me.index,me<le?(de.flags|=2,le):me):(de.flags|=2,le)):(de.flags|=1048576,le)}function R(de){return i&&de.alternate===null&&(de.flags|=2),de}function ee(de,le,me,Fe){return le===null||le.tag!==6?(le=sn(me,de.mode,Fe),le.return=de,le):(le=v(le,me),le.return=de,le)}function se(de,le,me,Fe){var rt=me.type;return rt===Y?Me(de,le,me.props.children,Fe,me.key):le!==null&&(le.elementType===rt||typeof rt=="object"&&rt!==null&&rt.$$typeof===D&&gd(rt)===le.type)?(Fe=v(le,me.props),Fe.ref=Va(de,le,me),Fe.return=de,Fe):(Fe=He(me.type,me.key,me.props,null,de.mode,Fe),Fe.ref=Va(de,le,me),Fe.return=de,Fe)}function ye(de,le,me,Fe){return le===null||le.tag!==4||le.stateNode.containerInfo!==me.containerInfo||le.stateNode.implementation!==me.implementation?(le=At(me,de.mode,Fe),le.return=de,le):(le=v(le,me.children||[]),le.return=de,le)}function Me(de,le,me,Fe,rt){return le===null||le.tag!==7?(le=Ve(me,de.mode,Fe,rt),le.return=de,le):(le=v(le,me),le.return=de,le)}function Le(de,le,me){if(typeof le=="string"&&le!==""||typeof le=="number")return le=sn(""+le,de.mode,me),le.return=de,le;if(typeof le=="object"&&le!==null){switch(le.$$typeof){case H:return me=He(le.type,le.key,le.props,null,de.mode,me),me.ref=Va(de,null,le),me.return=de,me;case X:return le=At(le,de.mode,me),le.return=de,le;case D:var Fe=le._init;return Le(de,Fe(le._payload),me)}if(ge(le)||z(le))return le=Ve(le,de.mode,me,null),le.return=de,le;Bc(de,le)}return null}function Te(de,le,me,Fe){var rt=le!==null?le.key:null;if(typeof me=="string"&&me!==""||typeof me=="number")return rt!==null?null:ee(de,le,""+me,Fe);if(typeof me=="object"&&me!==null){switch(me.$$typeof){case H:return me.key===rt?se(de,le,me,Fe):null;case X:return me.key===rt?ye(de,le,me,Fe):null;case D:return rt=me._init,Te(de,le,rt(me._payload),Fe)}if(ge(me)||z(me))return rt!==null?null:Me(de,le,me,Fe,null);Bc(de,me)}return null}function Xe(de,le,me,Fe,rt){if(typeof Fe=="string"&&Fe!==""||typeof Fe=="number")return de=de.get(me)||null,ee(le,de,""+Fe,rt);if(typeof Fe=="object"&&Fe!==null){switch(Fe.$$typeof){case H:return de=de.get(Fe.key===null?me:Fe.key)||null,se(le,de,Fe,rt);case X:return de=de.get(Fe.key===null?me:Fe.key)||null,ye(le,de,Fe,rt);case D:var yt=Fe._init;return Xe(de,le,me,yt(Fe._payload),rt)}if(ge(Fe)||z(Fe))return de=de.get(me)||null,Me(le,de,Fe,rt,null);Bc(le,Fe)}return null}function tt(de,le,me,Fe){for(var rt=null,yt=null,wt=le,Nt=le=0,Is=null;wt!==null&&Nt<me.length;Nt++){wt.index>Nt?(Is=wt,wt=null):Is=wt.sibling;var dn=Te(de,wt,me[Nt],Fe);if(dn===null){wt===null&&(wt=Is);break}i&&wt&&dn.alternate===null&&a(de,wt),le=b(dn,le,Nt),yt===null?rt=dn:yt.sibling=dn,yt=dn,wt=Is}if(Nt===me.length)return d(de,wt),_n&&Gi(de,Nt),rt;if(wt===null){for(;Nt<me.length;Nt++)wt=Le(de,me[Nt],Fe),wt!==null&&(le=b(wt,le,Nt),yt===null?rt=wt:yt.sibling=wt,yt=wt);return _n&&Gi(de,Nt),rt}for(wt=h(de,wt);Nt<me.length;Nt++)Is=Xe(wt,de,Nt,me[Nt],Fe),Is!==null&&(i&&Is.alternate!==null&&wt.delete(Is.key===null?Nt:Is.key),le=b(Is,le,Nt),yt===null?rt=Is:yt.sibling=Is,yt=Is);return i&&wt.forEach(function(hl){return a(de,hl)}),_n&&Gi(de,Nt),rt}function nt(de,le,me,Fe){var rt=z(me);if(typeof rt!="function")throw Error(n(150));if(me=rt.call(me),me==null)throw Error(n(151));for(var yt=rt=null,wt=le,Nt=le=0,Is=null,dn=me.next();wt!==null&&!dn.done;Nt++,dn=me.next()){wt.index>Nt?(Is=wt,wt=null):Is=wt.sibling;var hl=Te(de,wt,dn.value,Fe);if(hl===null){wt===null&&(wt=Is);break}i&&wt&&hl.alternate===null&&a(de,wt),le=b(hl,le,Nt),yt===null?rt=hl:yt.sibling=hl,yt=hl,wt=Is}if(dn.done)return d(de,wt),_n&&Gi(de,Nt),rt;if(wt===null){for(;!dn.done;Nt++,dn=me.next())dn=Le(de,dn.value,Fe),dn!==null&&(le=b(dn,le,Nt),yt===null?rt=dn:yt.sibling=dn,yt=dn);return _n&&Gi(de,Nt),rt}for(wt=h(de,wt);!dn.done;Nt++,dn=me.next())dn=Xe(wt,de,Nt,dn.value,Fe),dn!==null&&(i&&dn.alternate!==null&&wt.delete(dn.key===null?Nt:dn.key),le=b(dn,le,Nt),yt===null?rt=dn:yt.sibling=dn,yt=dn);return i&&wt.forEach(function(F0){return a(de,F0)}),_n&&Gi(de,Nt),rt}function os(de,le,me,Fe){if(typeof me=="object"&&me!==null&&me.type===Y&&me.key===null&&(me=me.props.children),typeof me=="object"&&me!==null){switch(me.$$typeof){case H:e:{for(var rt=me.key,yt=le;yt!==null;){if(yt.key===rt){if(rt=me.type,rt===Y){if(yt.tag===7){d(de,yt.sibling),le=v(yt,me.props.children),le.return=de,de=le;break e}}else if(yt.elementType===rt||typeof rt=="object"&&rt!==null&&rt.$$typeof===D&&gd(rt)===yt.type){d(de,yt.sibling),le=v(yt,me.props),le.ref=Va(de,yt,me),le.return=de,de=le;break e}d(de,yt);break}else a(de,yt);yt=yt.sibling}me.type===Y?(le=Ve(me.props.children,de.mode,Fe,me.key),le.return=de,de=le):(Fe=He(me.type,me.key,me.props,null,de.mode,Fe),Fe.ref=Va(de,le,me),Fe.return=de,de=Fe)}return R(de);case X:e:{for(yt=me.key;le!==null;){if(le.key===yt)if(le.tag===4&&le.stateNode.containerInfo===me.containerInfo&&le.stateNode.implementation===me.implementation){d(de,le.sibling),le=v(le,me.children||[]),le.return=de,de=le;break e}else{d(de,le);break}else a(de,le);le=le.sibling}le=At(me,de.mode,Fe),le.return=de,de=le}return R(de);case D:return yt=me._init,os(de,le,yt(me._payload),Fe)}if(ge(me))return tt(de,le,me,Fe);if(z(me))return nt(de,le,me,Fe);Bc(de,me)}return typeof me=="string"&&me!==""||typeof me=="number"?(me=""+me,le!==null&&le.tag===6?(d(de,le.sibling),le=v(le,me),le.return=de,de=le):(d(de,le),le=sn(me,de.mode,Fe),le.return=de,de=le),R(de)):d(de,le)}return os}var ta=yd(!0),hh=yd(!1),Wl=jo(null),na=null,Ga=null,wd=null;function vd(){wd=Ga=na=null}function xd(i){var a=Wl.current;xn(Wl),i._currentValue=a}function ql(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 Ka(i,a){na=i,wd=Ga=null,i=i.dependencies,i!==null&&i.firstContext!==null&&((i.lanes&a)!==0&&(rr=!0),i.firstContext=null)}function sr(i){var a=i._currentValue;if(wd!==i)if(i={context:i,memoizedValue:a,next:null},Ga===null){if(na===null)throw Error(n(308));Ga=i,na.dependencies={lanes:0,firstContext:i}}else Ga=Ga.next=i;return a}var sa=null;function Uc(i){sa===null?sa=[i]:sa.push(i)}function mh(i,a,d,h){var v=a.interleaved;return v===null?(d.next=d,Uc(a)):(d.next=v.next,v.next=d),a.interleaved=d,ti(i,h)}function ti(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 Re=!1;function zn(i){i.updateQueue={baseState:i.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function Wc(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 pi(i,a){return{eventTime:i,lane:a,tag:0,payload:null,callback:null,next:null}}function gi(i,a,d){var h=i.updateQueue;if(h===null)return null;if(h=h.shared,(Qt&2)!==0){var v=h.pending;return v===null?a.next=a:(a.next=v.next,v.next=a),h.pending=a,ti(i,d)}return v=h.interleaved,v===null?(a.next=a,Uc(h)):(a.next=v.next,v.next=a),h.interleaved=a,ti(i,d)}function qc(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,ho(i,d)}}function _h(i,a){var d=i.updateQueue,h=i.alternate;if(h!==null&&(h=h.updateQueue,d===h)){var v=null,b=null;if(d=d.firstBaseUpdate,d!==null){do{var R={eventTime:d.eventTime,lane:d.lane,tag:d.tag,payload:d.payload,callback:d.callback,next:null};b===null?v=b=R:b=b.next=R,d=d.next}while(d!==null);b===null?v=b=a:b=b.next=a}else v=b=a;d={baseState:h.baseState,firstBaseUpdate:v,lastBaseUpdate:b,shared:h.shared,effects:h.effects},i.updateQueue=d;return}i=d.lastBaseUpdate,i===null?d.firstBaseUpdate=a:i.next=a,d.lastBaseUpdate=a}function Hc(i,a,d,h){var v=i.updateQueue;Re=!1;var b=v.firstBaseUpdate,R=v.lastBaseUpdate,ee=v.shared.pending;if(ee!==null){v.shared.pending=null;var se=ee,ye=se.next;se.next=null,R===null?b=ye:R.next=ye,R=se;var Me=i.alternate;Me!==null&&(Me=Me.updateQueue,ee=Me.lastBaseUpdate,ee!==R&&(ee===null?Me.firstBaseUpdate=ye:ee.next=ye,Me.lastBaseUpdate=se))}if(b!==null){var Le=v.baseState;R=0,Me=ye=se=null,ee=b;do{var Te=ee.lane,Xe=ee.eventTime;if((h&Te)===Te){Me!==null&&(Me=Me.next={eventTime:Xe,lane:0,tag:ee.tag,payload:ee.payload,callback:ee.callback,next:null});e:{var tt=i,nt=ee;switch(Te=a,Xe=d,nt.tag){case 1:if(tt=nt.payload,typeof tt=="function"){Le=tt.call(Xe,Le,Te);break e}Le=tt;break e;case 3:tt.flags=tt.flags&-65537|128;case 0:if(tt=nt.payload,Te=typeof tt=="function"?tt.call(Xe,Le,Te):tt,Te==null)break e;Le=G({},Le,Te);break e;case 2:Re=!0}}ee.callback!==null&&ee.lane!==0&&(i.flags|=64,Te=v.effects,Te===null?v.effects=[ee]:Te.push(ee))}else Xe={eventTime:Xe,lane:Te,tag:ee.tag,payload:ee.payload,callback:ee.callback,next:null},Me===null?(ye=Me=Xe,se=Le):Me=Me.next=Xe,R|=Te;if(ee=ee.next,ee===null){if(ee=v.shared.pending,ee===null)break;Te=ee,ee=Te.next,Te.next=null,v.lastBaseUpdate=Te,v.shared.pending=null}}while(!0);if(Me===null&&(se=Le),v.baseState=se,v.firstBaseUpdate=ye,v.lastBaseUpdate=Me,a=v.shared.interleaved,a!==null){v=a;do R|=v.lane,v=v.next;while(v!==a)}else b===null&&(v.shared.lanes=0);Ro|=R,i.lanes=R,i.memoizedState=Le}}function bd(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 Ya={},yi=jo(Ya),Eo=jo(Ya),es=jo(Ya);function Wt(i){if(i===Ya)throw Error(n(174));return i}function hs(i,a){switch(bn(es,a),bn(Eo,i),bn(yi,Ya),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)}xn(yi),bn(yi,a)}function $o(){xn(yi),xn(Eo),xn(es)}function jd(i){Wt(es.current);var a=Wt(yi.current),d=It(a,i.type);a!==d&&(bn(Eo,i),bn(yi,d))}function ra(i){Eo.current===i&&(xn(yi),xn(Eo))}var Ln=jo(0);function at(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 Sd=[];function Hl(){for(var i=0;i<Sd.length;i++)Sd[i]._workInProgressVersionPrimary=null;Sd.length=0}var Vc=M.ReactCurrentDispatcher,kd=M.ReactCurrentBatchConfig,Ao=0,Pn=null,ts=null,ms=null,Ja=!1,wi=!1,Vl=0,vi=0;function jn(){throw Error(n(321))}function Gc(i,a){if(a===null)return!1;for(var d=0;d<a.length&&d<i.length;d++)if(!Yr(i[d],a[d]))return!1;return!0}function Nd(i,a,d,h,v,b){if(Ao=b,Pn=a,a.memoizedState=null,a.updateQueue=null,a.lanes=0,Vc.current=i===null||i.memoizedState===null?Cr:Ld,i=d(h,v),wi){b=0;do{if(wi=!1,Vl=0,25<=b)throw Error(n(301));b+=1,ms=ts=null,a.updateQueue=null,Vc.current=eu,i=d(h,v)}while(wi)}if(Vc.current=An,a=ts!==null&&ts.next!==null,Ao=0,ms=ts=Pn=null,Ja=!1,a)throw Error(n(300));return i}function Cd(){var i=Vl!==0;return Vl=0,i}function xi(){var i={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return ms===null?Pn.memoizedState=ms=i:ms=ms.next=i,ms}function Nr(){if(ts===null){var i=Pn.alternate;i=i!==null?i.memoizedState:null}else i=ts.next;var a=ms===null?Pn.memoizedState:ms.next;if(a!==null)ms=a,ts=i;else{if(i===null)throw Error(n(310));ts=i,i={memoizedState:ts.memoizedState,baseState:ts.baseState,baseQueue:ts.baseQueue,queue:ts.queue,next:null},ms===null?Pn.memoizedState=ms=i:ms=ms.next=i}return ms}function ia(i,a){return typeof a=="function"?a(i):a}function Ed(i){var a=Nr(),d=a.queue;if(d===null)throw Error(n(311));d.lastRenderedReducer=i;var h=ts,v=h.baseQueue,b=d.pending;if(b!==null){if(v!==null){var R=v.next;v.next=b.next,b.next=R}h.baseQueue=v=b,d.pending=null}if(v!==null){b=v.next,h=h.baseState;var ee=R=null,se=null,ye=b;do{var Me=ye.lane;if((Ao&Me)===Me)se!==null&&(se=se.next={lane:0,action:ye.action,hasEagerState:ye.hasEagerState,eagerState:ye.eagerState,next:null}),h=ye.hasEagerState?ye.eagerState:i(h,ye.action);else{var Le={lane:Me,action:ye.action,hasEagerState:ye.hasEagerState,eagerState:ye.eagerState,next:null};se===null?(ee=se=Le,R=h):se=se.next=Le,Pn.lanes|=Me,Ro|=Me}ye=ye.next}while(ye!==null&&ye!==b);se===null?R=h:se.next=ee,Yr(h,a.memoizedState)||(rr=!0),a.memoizedState=h,a.baseState=R,a.baseQueue=se,d.lastRenderedState=h}if(i=d.interleaved,i!==null){v=i;do b=v.lane,Pn.lanes|=b,Ro|=b,v=v.next;while(v!==i)}else v===null&&(d.lanes=0);return[a.memoizedState,d.dispatch]}function $n(i){var a=Nr(),d=a.queue;if(d===null)throw Error(n(311));d.lastRenderedReducer=i;var h=d.dispatch,v=d.pending,b=a.memoizedState;if(v!==null){d.pending=null;var R=v=v.next;do b=i(b,R.action),R=R.next;while(R!==v);Yr(b,a.memoizedState)||(rr=!0),a.memoizedState=b,a.baseQueue===null&&(a.baseState=b),d.lastRenderedState=b}return[b,h]}function $d(){}function Kc(i,a){var d=Pn,h=Nr(),v=a(),b=!Yr(h.memoizedState,v);if(b&&(h.memoizedState=v,rr=!0),h=h.queue,Td(Xa.bind(null,d,h,i),[i]),h.getSnapshot!==a||b||ms!==null&&ms.memoizedState.tag&1){if(d.flags|=2048,Gl(9,Ad.bind(null,d,h,v,a),void 0,null),Yn===null)throw Error(n(349));(Ao&30)!==0||Bs(d,a,v)}return v}function Bs(i,a,d){i.flags|=16384,i={getSnapshot:a,value:d},a=Pn.updateQueue,a===null?(a={lastEffect:null,stores:null},Pn.updateQueue=a,a.stores=[i]):(d=a.stores,d===null?a.stores=[i]:d.push(i))}function Ad(i,a,d,h){a.value=d,a.getSnapshot=h,Yc(a)&&Za(i)}function Xa(i,a,d){return d(function(){Yc(a)&&Za(i)})}function Yc(i){var a=i.getSnapshot;i=i.value;try{var d=a();return!Yr(i,d)}catch{return!0}}function Za(i){var a=ti(i,1);a!==null&&ai(a,i,1,-1)}function Jc(i){var a=xi();return typeof i=="function"&&(i=i()),a.memoizedState=a.baseState=i,i={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:ia,lastRenderedState:i},a.queue=i,i=i.dispatch=xh.bind(null,Pn,i),[a.memoizedState,i]}function Gl(i,a,d,h){return i={tag:i,create:a,destroy:d,deps:h,next:null},a=Pn.updateQueue,a===null?(a={lastEffect:null,stores:null},Pn.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 ph(){return Nr().memoizedState}function Xc(i,a,d,h){var v=xi();Pn.flags|=i,v.memoizedState=Gl(1|a,d,void 0,h===void 0?null:h)}function Qa(i,a,d,h){var v=Nr();h=h===void 0?null:h;var b=void 0;if(ts!==null){var R=ts.memoizedState;if(b=R.destroy,h!==null&&Gc(h,R.deps)){v.memoizedState=Gl(a,d,b,h);return}}Pn.flags|=i,v.memoizedState=Gl(1|a,d,b,h)}function Zc(i,a){return Xc(8390656,8,i,a)}function Td(i,a){return Qa(2048,8,i,a)}function Qc(i,a){return Qa(4,2,i,a)}function gh(i,a){return Qa(4,4,i,a)}function Dr(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 oa(i,a,d){return d=d!=null?d.concat([i]):null,Qa(4,4,Dr.bind(null,a,i),d)}function Bn(){}function Md(i,a){var d=Nr();a=a===void 0?null:a;var h=d.memoizedState;return h!==null&&a!==null&&Gc(a,h[1])?h[0]:(d.memoizedState=[i,a],i)}function Rd(i,a){var d=Nr();a=a===void 0?null:a;var h=d.memoizedState;return h!==null&&a!==null&&Gc(a,h[1])?h[0]:(i=i(),d.memoizedState=[i,a],i)}function yh(i,a,d){return(Ao&21)===0?(i.baseState&&(i.baseState=!1,rr=!0),i.memoizedState=d):(Yr(d,a)||(d=ds(),Pn.lanes|=d,Ro|=d,i.baseState=!0),a)}function v_(i,a){var d=on;on=d!==0&&4>d?d:4,i(!0);var h=kd.transition;kd.transition={};try{i(!1),a()}finally{on=d,kd.transition=h}}function wh(){return Nr().memoizedState}function vh(i,a,d){var h=ar(i);if(d={lane:h,action:d,hasEagerState:!1,eagerState:null,next:null},bh(i))jh(a,d);else if(d=mh(i,a,d,h),d!==null){var v=is();ai(d,i,h,v),Zt(d,a,h)}}function xh(i,a,d){var h=ar(i),v={lane:h,action:d,hasEagerState:!1,eagerState:null,next:null};if(bh(i))jh(a,v);else{var b=i.alternate;if(i.lanes===0&&(b===null||b.lanes===0)&&(b=a.lastRenderedReducer,b!==null))try{var R=a.lastRenderedState,ee=b(R,d);if(v.hasEagerState=!0,v.eagerState=ee,Yr(ee,R)){var se=a.interleaved;se===null?(v.next=v,Uc(a)):(v.next=se.next,se.next=v),a.interleaved=v;return}}catch{}finally{}d=mh(i,a,v,h),d!==null&&(v=is(),ai(d,i,h,v),Zt(d,a,h))}}function bh(i){var a=i.alternate;return i===Pn||a!==null&&a===Pn}function jh(i,a){wi=Ja=!0;var d=i.pending;d===null?a.next=a:(a.next=d.next,d.next=a),i.pending=a}function Zt(i,a,d){if((d&4194240)!==0){var h=a.lanes;h&=i.pendingLanes,d|=h,a.lanes=d,ho(i,d)}}var An={readContext:sr,useCallback:jn,useContext:jn,useEffect:jn,useImperativeHandle:jn,useInsertionEffect:jn,useLayoutEffect:jn,useMemo:jn,useReducer:jn,useRef:jn,useState:jn,useDebugValue:jn,useDeferredValue:jn,useTransition:jn,useMutableSource:jn,useSyncExternalStore:jn,useId:jn,unstable_isNewReconciler:!1},Cr={readContext:sr,useCallback:function(i,a){return xi().memoizedState=[i,a===void 0?null:a],i},useContext:sr,useEffect:Zc,useImperativeHandle:function(i,a,d){return d=d!=null?d.concat([i]):null,Xc(4194308,4,Dr.bind(null,a,i),d)},useLayoutEffect:function(i,a){return Xc(4194308,4,i,a)},useInsertionEffect:function(i,a){return Xc(4,2,i,a)},useMemo:function(i,a){var d=xi();return a=a===void 0?null:a,i=i(),d.memoizedState=[i,a],i},useReducer:function(i,a,d){var h=xi();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=vh.bind(null,Pn,i),[h.memoizedState,i]},useRef:function(i){var a=xi();return i={current:i},a.memoizedState=i},useState:Jc,useDebugValue:Bn,useDeferredValue:function(i){return xi().memoizedState=i},useTransition:function(){var i=Jc(!1),a=i[0];return i=v_.bind(null,i[1]),xi().memoizedState=i,[a,i]},useMutableSource:function(){},useSyncExternalStore:function(i,a,d){var h=Pn,v=xi();if(_n){if(d===void 0)throw Error(n(407));d=d()}else{if(d=a(),Yn===null)throw Error(n(349));(Ao&30)!==0||Bs(h,a,d)}v.memoizedState=d;var b={value:d,getSnapshot:a};return v.queue=b,Zc(Xa.bind(null,h,b,i),[i]),h.flags|=2048,Gl(9,Ad.bind(null,h,b,d,a),void 0,null),d},useId:function(){var i=xi(),a=Yn.identifierPrefix;if(_n){var d=nr,h=ei;d=(h&~(1<<32-us(h)-1)).toString(32)+d,a=":"+a+"R"+d,d=Vl++,0<d&&(a+="H"+d.toString(32)),a+=":"}else d=vi++,a=":"+a+"r"+d.toString(32)+":";return i.memoizedState=a},unstable_isNewReconciler:!1},Ld={readContext:sr,useCallback:Md,useContext:sr,useEffect:Td,useImperativeHandle:oa,useInsertionEffect:Qc,useLayoutEffect:gh,useMemo:Rd,useReducer:Ed,useRef:ph,useState:function(){return Ed(ia)},useDebugValue:Bn,useDeferredValue:function(i){var a=Nr();return yh(a,ts.memoizedState,i)},useTransition:function(){var i=Ed(ia)[0],a=Nr().memoizedState;return[i,a]},useMutableSource:$d,useSyncExternalStore:Kc,useId:wh,unstable_isNewReconciler:!1},eu={readContext:sr,useCallback:Md,useContext:sr,useEffect:Td,useImperativeHandle:oa,useInsertionEffect:Qc,useLayoutEffect:gh,useMemo:Rd,useReducer:$n,useRef:ph,useState:function(){return $n(ia)},useDebugValue:Bn,useDeferredValue:function(i){var a=Nr();return ts===null?a.memoizedState=i:yh(a,ts.memoizedState,i)},useTransition:function(){var i=$n(ia)[0],a=Nr().memoizedState;return[i,a]},useMutableSource:$d,useSyncExternalStore:Kc,useId:wh,unstable_isNewReconciler:!1};function Fr(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 Id(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 tu={isMounted:function(i){return(i=i._reactInternals)?$t(i)===i:!1},enqueueSetState:function(i,a,d){i=i._reactInternals;var h=is(),v=ar(i),b=pi(h,v);b.payload=a,d!=null&&(b.callback=d),a=gi(i,b,v),a!==null&&(ai(a,i,v,h),qc(a,i,v))},enqueueReplaceState:function(i,a,d){i=i._reactInternals;var h=is(),v=ar(i),b=pi(h,v);b.tag=1,b.payload=a,d!=null&&(b.callback=d),a=gi(i,b,v),a!==null&&(ai(a,i,v,h),qc(a,i,v))},enqueueForceUpdate:function(i,a){i=i._reactInternals;var d=is(),h=ar(i),v=pi(d,h);v.tag=2,a!=null&&(v.callback=a),a=gi(i,v,h),a!==null&&(ai(a,i,h,d),qc(a,i,h))}};function Od(i,a,d,h,v,b,R){return i=i.stateNode,typeof i.shouldComponentUpdate=="function"?i.shouldComponentUpdate(h,b,R):a.prototype&&a.prototype.isPureReactComponent?!Ta(d,h)||!Ta(v,b):!0}function el(i,a,d){var h=!1,v=Hi,b=a.contextType;return typeof b=="object"&&b!==null?b=sr(b):(v=fs(a)?Zr:Rs.current,h=a.contextTypes,b=(h=h!=null)?Wa(i,v):Hi),a=new a(d,b),i.memoizedState=a.state!==null&&a.state!==void 0?a.state:null,a.updater=tu,i.stateNode=a,a._reactInternals=i,h&&(i=i.stateNode,i.__reactInternalMemoizedUnmaskedChildContext=v,i.__reactInternalMemoizedMaskedChildContext=b),a}function Sh(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&&tu.enqueueReplaceState(a,a.state,null)}function Pd(i,a,d,h){var v=i.stateNode;v.props=d,v.state=i.memoizedState,v.refs={},zn(i);var b=a.contextType;typeof b=="object"&&b!==null?v.context=sr(b):(b=fs(a)?Zr:Rs.current,v.context=Wa(i,b)),v.state=i.memoizedState,b=a.getDerivedStateFromProps,typeof b=="function"&&(Id(i,a,b,d),v.state=i.memoizedState),typeof a.getDerivedStateFromProps=="function"||typeof v.getSnapshotBeforeUpdate=="function"||typeof v.UNSAFE_componentWillMount!="function"&&typeof v.componentWillMount!="function"||(a=v.state,typeof v.componentWillMount=="function"&&v.componentWillMount(),typeof v.UNSAFE_componentWillMount=="function"&&v.UNSAFE_componentWillMount(),a!==v.state&&tu.enqueueReplaceState(v,v.state,null),Hc(i,d,v,h),v.state=i.memoizedState),typeof v.componentDidMount=="function"&&(i.flags|=4194308)}function tl(i,a){try{var d="",h=a;do d+=oe(h),h=h.return;while(h);var v=d}catch(b){v=`
|
|
39
|
-
Error generating stack: `+b.message+`
|
|
40
|
-
`+b.stack}return{value:i,source:a,stack:v,digest:null}}function nu(i,a,d){return{value:i,source:null,stack:d??null,digest:a??null}}function su(i,a){try{console.error(a.value)}catch(d){setTimeout(function(){throw d})}}var aa=typeof WeakMap=="function"?WeakMap:Map;function Dd(i,a,d){d=pi(-1,d),d.tag=3,d.payload={element:null};var h=a.value;return d.callback=function(){oi||(oi=!0,Zd=h),su(i,a)},d}function Fd(i,a,d){d=pi(-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(){su(i,a)}}var b=i.stateNode;return b!==null&&typeof b.componentDidCatch=="function"&&(d.callback=function(){su(i,a),typeof h!="function"&&(Lo===null?Lo=new Set([this]):Lo.add(this));var R=a.stack;this.componentDidCatch(a.value,{componentStack:R!==null?R:""})}),d}function zd(i,a,d){var h=i.pingCache;if(h===null){h=i.pingCache=new aa;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=$.bind(null,i,a,d),a.then(i,i))}function Bd(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 kh(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=pi(-1,1),a.tag=2,gi(d,a,1))),d.lanes|=1),i):(i.flags|=65536,i.lanes=v,i)}var x_=M.ReactCurrentOwner,rr=!1;function Us(i,a,d,h){a.child=i===null?hh(a,null,d,h):ta(a,i.child,d,h)}function Nh(i,a,d,h,v){d=d.render;var b=a.ref;return Ka(a,v),h=Nd(i,a,d,h,b,v),d=Cd(),i!==null&&!rr?(a.updateQueue=i.updateQueue,a.flags&=-2053,i.lanes&=~v,Ki(i,a,v)):(_n&&d&&zl(a),a.flags|=1,Us(i,a,h,v),a.child)}function Ch(i,a,d,h,v){if(i===null){var b=d.type;return typeof b=="function"&&!pe(b)&&b.defaultProps===void 0&&d.compare===null&&d.defaultProps===void 0?(a.tag=15,a.type=b,Eh(i,a,b,h,v)):(i=He(d.type,null,h,a,a.mode,v),i.ref=a.ref,i.return=a,a.child=i)}if(b=i.child,(i.lanes&v)===0){var R=b.memoizedProps;if(d=d.compare,d=d!==null?d:Ta,d(R,h)&&i.ref===a.ref)return Ki(i,a,v)}return a.flags|=1,i=Oe(b,h),i.ref=a.ref,i.return=a,a.child=i}function Eh(i,a,d,h,v){if(i!==null){var b=i.memoizedProps;if(Ta(b,h)&&i.ref===a.ref)if(rr=!1,a.pendingProps=h=b,(i.lanes&v)!==0)(i.flags&131072)!==0&&(rr=!0);else return a.lanes=i.lanes,Ki(i,a,v)}return Wd(i,a,d,h,v)}function Ud(i,a,d){var h=a.pendingProps,v=h.children,b=i!==null?i.memoizedState:null;if(h.mode==="hidden")if((a.mode&1)===0)a.memoizedState={baseLanes:0,cachePool:null,transitions:null},bn(ca,Er),Er|=d;else{if((d&1073741824)===0)return i=b!==null?b.baseLanes|d:d,a.lanes=a.childLanes=1073741824,a.memoizedState={baseLanes:i,cachePool:null,transitions:null},a.updateQueue=null,bn(ca,Er),Er|=i,null;a.memoizedState={baseLanes:0,cachePool:null,transitions:null},h=b!==null?b.baseLanes:d,bn(ca,Er),Er|=h}else b!==null?(h=b.baseLanes|d,a.memoizedState=null):h=d,bn(ca,Er),Er|=h;return Us(i,a,v,d),a.child}function ru(i,a){var d=a.ref;(i===null&&d!==null||i!==null&&i.ref!==d)&&(a.flags|=512,a.flags|=2097152)}function Wd(i,a,d,h,v){var b=fs(d)?Zr:Rs.current;return b=Wa(a,b),Ka(a,v),d=Nd(i,a,d,h,b,v),h=Cd(),i!==null&&!rr?(a.updateQueue=i.updateQueue,a.flags&=-2053,i.lanes&=~v,Ki(i,a,v)):(_n&&h&&zl(a),a.flags|=1,Us(i,a,d,v),a.child)}function $h(i,a,d,h,v){if(fs(d)){var b=!0;Vi(a)}else b=!1;if(Ka(a,v),a.stateNode===null)rl(i,a),el(a,d,h),Pd(a,d,h,v),h=!0;else if(i===null){var R=a.stateNode,ee=a.memoizedProps;R.props=ee;var se=R.context,ye=d.contextType;typeof ye=="object"&&ye!==null?ye=sr(ye):(ye=fs(d)?Zr:Rs.current,ye=Wa(a,ye));var Me=d.getDerivedStateFromProps,Le=typeof Me=="function"||typeof R.getSnapshotBeforeUpdate=="function";Le||typeof R.UNSAFE_componentWillReceiveProps!="function"&&typeof R.componentWillReceiveProps!="function"||(ee!==h||se!==ye)&&Sh(a,R,h,ye),Re=!1;var Te=a.memoizedState;R.state=Te,Hc(a,h,R,v),se=a.memoizedState,ee!==h||Te!==se||zs.current||Re?(typeof Me=="function"&&(Id(a,d,Me,h),se=a.memoizedState),(ee=Re||Od(a,d,ee,h,Te,se,ye))?(Le||typeof R.UNSAFE_componentWillMount!="function"&&typeof R.componentWillMount!="function"||(typeof R.componentWillMount=="function"&&R.componentWillMount(),typeof R.UNSAFE_componentWillMount=="function"&&R.UNSAFE_componentWillMount()),typeof R.componentDidMount=="function"&&(a.flags|=4194308)):(typeof R.componentDidMount=="function"&&(a.flags|=4194308),a.memoizedProps=h,a.memoizedState=se),R.props=h,R.state=se,R.context=ye,h=ee):(typeof R.componentDidMount=="function"&&(a.flags|=4194308),h=!1)}else{R=a.stateNode,Wc(i,a),ee=a.memoizedProps,ye=a.type===a.elementType?ee:Fr(a.type,ee),R.props=ye,Le=a.pendingProps,Te=R.context,se=d.contextType,typeof se=="object"&&se!==null?se=sr(se):(se=fs(d)?Zr:Rs.current,se=Wa(a,se));var Xe=d.getDerivedStateFromProps;(Me=typeof Xe=="function"||typeof R.getSnapshotBeforeUpdate=="function")||typeof R.UNSAFE_componentWillReceiveProps!="function"&&typeof R.componentWillReceiveProps!="function"||(ee!==Le||Te!==se)&&Sh(a,R,h,se),Re=!1,Te=a.memoizedState,R.state=Te,Hc(a,h,R,v);var tt=a.memoizedState;ee!==Le||Te!==tt||zs.current||Re?(typeof Xe=="function"&&(Id(a,d,Xe,h),tt=a.memoizedState),(ye=Re||Od(a,d,ye,h,Te,tt,se)||!1)?(Me||typeof R.UNSAFE_componentWillUpdate!="function"&&typeof R.componentWillUpdate!="function"||(typeof R.componentWillUpdate=="function"&&R.componentWillUpdate(h,tt,se),typeof R.UNSAFE_componentWillUpdate=="function"&&R.UNSAFE_componentWillUpdate(h,tt,se)),typeof R.componentDidUpdate=="function"&&(a.flags|=4),typeof R.getSnapshotBeforeUpdate=="function"&&(a.flags|=1024)):(typeof R.componentDidUpdate!="function"||ee===i.memoizedProps&&Te===i.memoizedState||(a.flags|=4),typeof R.getSnapshotBeforeUpdate!="function"||ee===i.memoizedProps&&Te===i.memoizedState||(a.flags|=1024),a.memoizedProps=h,a.memoizedState=tt),R.props=h,R.state=tt,R.context=se,h=ye):(typeof R.componentDidUpdate!="function"||ee===i.memoizedProps&&Te===i.memoizedState||(a.flags|=4),typeof R.getSnapshotBeforeUpdate!="function"||ee===i.memoizedProps&&Te===i.memoizedState||(a.flags|=1024),h=!1)}return nl(i,a,d,h,b,v)}function nl(i,a,d,h,v,b){ru(i,a);var R=(a.flags&128)!==0;if(!h&&!R)return v&&ch(a,d,!1),Ki(i,a,b);h=a.stateNode,x_.current=a;var ee=R&&typeof d.getDerivedStateFromError!="function"?null:h.render();return a.flags|=1,i!==null&&R?(a.child=ta(a,i.child,null,b),a.child=ta(a,null,ee,b)):Us(i,a,ee,b),a.memoizedState=h.state,v&&ch(a,d,!0),a.child}function Ah(i){var a=i.stateNode;a.pendingContext?Fl(i,a.pendingContext,a.pendingContext!==a.context):a.context&&Fl(i,a.context,!1),hs(i,a.containerInfo)}function To(i,a,d,h,v){return ea(),Ha(v),a.flags|=256,Us(i,a,d,h),a.child}var bs={dehydrated:null,treeContext:null,retryLane:0};function ns(i){return{baseLanes:i,cachePool:null,transitions:null}}function ni(i,a,d){var h=a.pendingProps,v=Ln.current,b=!1,R=(a.flags&128)!==0,ee;if((ee=R)||(ee=i!==null&&i.memoizedState===null?!1:(v&2)!==0),ee?(b=!0,a.flags&=-129):(i===null||i.memoizedState!==null)&&(v|=1),bn(Ln,v&1),i===null)return pd(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):(R=h.children,i=h.fallback,b?(h=a.mode,b=a.child,R={mode:"hidden",children:R},(h&1)===0&&b!==null?(b.childLanes=0,b.pendingProps=R):b=Ge(R,h,0,null),i=Ve(i,h,d,null),b.return=a,i.return=a,b.sibling=i,a.child=b,a.child.memoizedState=ns(d),a.memoizedState=bs,i):bi(a,R));if(v=i.memoizedState,v!==null&&(ee=v.dehydrated,ee!==null))return ji(i,a,R,h,ee,v,d);if(b){b=h.fallback,R=a.mode,v=i.child,ee=v.sibling;var se={mode:"hidden",children:h.children};return(R&1)===0&&a.child!==v?(h=a.child,h.childLanes=0,h.pendingProps=se,a.deletions=null):(h=Oe(v,se),h.subtreeFlags=v.subtreeFlags&14680064),ee!==null?b=Oe(ee,b):(b=Ve(b,R,d,null),b.flags|=2),b.return=a,h.return=a,h.sibling=b,a.child=h,h=b,b=a.child,R=i.child.memoizedState,R=R===null?ns(d):{baseLanes:R.baseLanes|d,cachePool:null,transitions:R.transitions},b.memoizedState=R,b.childLanes=i.childLanes&~d,a.memoizedState=bs,h}return b=i.child,i=b.sibling,h=Oe(b,{mode:"visible",children:h.children}),(a.mode&1)===0&&(h.lanes=d),h.return=a,h.sibling=null,i!==null&&(d=a.deletions,d===null?(a.deletions=[i],a.flags|=16):d.push(i)),a.child=h,a.memoizedState=null,h}function bi(i,a){return a=Ge({mode:"visible",children:a},i.mode,0,null),a.return=i,i.child=a}function si(i,a,d,h){return h!==null&&Ha(h),ta(a,i.child,null,d),i=bi(a,a.pendingProps.children),i.flags|=2,a.memoizedState=null,i}function ji(i,a,d,h,v,b,R){if(d)return a.flags&256?(a.flags&=-257,h=nu(Error(n(422))),si(i,a,R,h)):a.memoizedState!==null?(a.child=i.child,a.flags|=128,null):(b=h.fallback,v=a.mode,h=Ge({mode:"visible",children:h.children},v,0,null),b=Ve(b,v,R,null),b.flags|=2,h.return=a,b.return=a,h.sibling=b,a.child=h,(a.mode&1)!==0&&ta(a,i.child,null,R),a.child.memoizedState=ns(R),a.memoizedState=bs,b);if((a.mode&1)===0)return si(i,a,R,null);if(v.data==="$!"){if(h=v.nextSibling&&v.nextSibling.dataset,h)var ee=h.dgst;return h=ee,b=Error(n(419)),h=nu(b,h,void 0),si(i,a,R,h)}if(ee=(R&i.childLanes)!==0,rr||ee){if(h=Yn,h!==null){switch(R&-R){case 4:v=2;break;case 16:v=8;break;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:v=32;break;case 536870912:v=268435456;break;default:v=0}v=(v&(h.suspendedLanes|R))!==0?0:v,v!==0&&v!==b.retryLane&&(b.retryLane=v,ti(i,v),ai(h,i,v,-1))}return gu(),h=nu(Error(n(421))),si(i,a,R,h)}return v.data==="$?"?(a.flags|=128,a.child=i.child,a=q.bind(null,i),v._reactRetry=a,null):(i=b.treeContext,kr=qi(v.nextSibling),Sr=a,_n=!0,En=null,i!==null&&(jr[tr++]=ei,jr[tr++]=nr,jr[tr++]=Qr,ei=i.id,nr=i.overflow,Qr=a),a=bi(a,h.children),a.flags|=4096,a)}function Th(i,a,d){i.lanes|=a;var h=i.alternate;h!==null&&(h.lanes|=a),ql(i.return,a,d)}function sl(i,a,d,h,v){var b=i.memoizedState;b===null?i.memoizedState={isBackwards:a,rendering:null,renderingStartTime:0,last:h,tail:d,tailMode:v}:(b.isBackwards=a,b.rendering=null,b.renderingStartTime=0,b.last=h,b.tail=d,b.tailMode=v)}function Mh(i,a,d){var h=a.pendingProps,v=h.revealOrder,b=h.tail;if(Us(i,a,h.children,d),h=Ln.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&&Th(i,d,a);else if(i.tag===19)Th(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(bn(Ln,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&&at(i)===null&&(v=d),d=d.sibling;d=v,d===null?(v=a.child,a.child=null):(v=d.sibling,d.sibling=null),sl(a,!1,v,d,b);break;case"backwards":for(d=null,v=a.child,a.child=null;v!==null;){if(i=v.alternate,i!==null&&at(i)===null){a.child=v;break}i=v.sibling,v.sibling=d,d=v,v=i}sl(a,!0,d,null,b);break;case"together":sl(a,!1,null,null,void 0);break;default:a.memoizedState=null}return a.child}function rl(i,a){(a.mode&1)===0&&i!==null&&(i.alternate=null,a.alternate=null,a.flags|=2)}function Ki(i,a,d){if(i!==null&&(a.dependencies=i.dependencies),Ro|=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=Oe(i,i.pendingProps),a.child=d,d.return=a;i.sibling!==null;)i=i.sibling,d=d.sibling=Oe(i,i.pendingProps),d.return=a;d.sibling=null}return a.child}function b_(i,a,d){switch(a.tag){case 3:Ah(a),ea();break;case 5:jd(a);break;case 1:fs(a.type)&&Vi(a);break;case 4:hs(a,a.stateNode.containerInfo);break;case 10:var h=a.type._context,v=a.memoizedProps.value;bn(Wl,h._currentValue),h._currentValue=v;break;case 13:if(h=a.memoizedState,h!==null)return h.dehydrated!==null?(bn(Ln,Ln.current&1),a.flags|=128,null):(d&a.child.childLanes)!==0?ni(i,a,d):(bn(Ln,Ln.current&1),i=Ki(i,a,d),i!==null?i.sibling:null);bn(Ln,Ln.current&1);break;case 19:if(h=(d&a.childLanes)!==0,(i.flags&128)!==0){if(h)return Mh(i,a,d);a.flags|=128}if(v=a.memoizedState,v!==null&&(v.rendering=null,v.tail=null,v.lastEffect=null),bn(Ln,Ln.current),h)break;return null;case 22:case 23:return a.lanes=0,Ud(i,a,d)}return Ki(i,a,d)}var qd,Yi,il,Hd;qd=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}},Yi=function(){},il=function(i,a,d,h){var v=i.memoizedProps;if(v!==h){i=a.stateNode,Wt(yi.current);var b=null;switch(d){case"input":v=et(i,v),h=et(i,h),b=[];break;case"select":v=G({},v,{value:void 0}),h=G({},h,{value:void 0}),b=[];break;case"textarea":v=Ye(i,v),h=Ye(i,h),b=[];break;default:typeof v.onClick!="function"&&typeof h.onClick=="function"&&(i.onclick=xs)}gn(d,h);var R;d=null;for(ye in v)if(!h.hasOwnProperty(ye)&&v.hasOwnProperty(ye)&&v[ye]!=null)if(ye==="style"){var ee=v[ye];for(R in ee)ee.hasOwnProperty(R)&&(d||(d={}),d[R]="")}else ye!=="dangerouslySetInnerHTML"&&ye!=="children"&&ye!=="suppressContentEditableWarning"&&ye!=="suppressHydrationWarning"&&ye!=="autoFocus"&&(o.hasOwnProperty(ye)?b||(b=[]):(b=b||[]).push(ye,null));for(ye in h){var se=h[ye];if(ee=v!=null?v[ye]:void 0,h.hasOwnProperty(ye)&&se!==ee&&(se!=null||ee!=null))if(ye==="style")if(ee){for(R in ee)!ee.hasOwnProperty(R)||se&&se.hasOwnProperty(R)||(d||(d={}),d[R]="");for(R in se)se.hasOwnProperty(R)&&ee[R]!==se[R]&&(d||(d={}),d[R]=se[R])}else d||(b||(b=[]),b.push(ye,d)),d=se;else ye==="dangerouslySetInnerHTML"?(se=se?se.__html:void 0,ee=ee?ee.__html:void 0,se!=null&&ee!==se&&(b=b||[]).push(ye,se)):ye==="children"?typeof se!="string"&&typeof se!="number"||(b=b||[]).push(ye,""+se):ye!=="suppressContentEditableWarning"&&ye!=="suppressHydrationWarning"&&(o.hasOwnProperty(ye)?(se!=null&&ye==="onScroll"&&Cn("scroll",i),b||ee===se||(b=[])):(b=b||[]).push(ye,se))}d&&(b=b||[]).push("style",d);var ye=b;(a.updateQueue=ye)&&(a.flags|=4)}},Hd=function(i,a,d,h){d!==h&&(a.flags|=4)};function ol(i,a){if(!_n)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 Ls(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 Rh(i,a,d){var h=a.pendingProps;switch(Pc(a),a.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return Ls(a),null;case 1:return fs(a.type)&&qa(),Ls(a),null;case 3:return h=a.stateNode,$o(),xn(zs),xn(Rs),Hl(),h.pendingContext&&(h.context=h.pendingContext,h.pendingContext=null),(i===null||i.child===null)&&(zc(a)?a.flags|=4:i===null||i.memoizedState.isDehydrated&&(a.flags&256)===0||(a.flags|=1024,En!==null&&(dl(En),En=null))),Yi(i,a),Ls(a),null;case 5:ra(a);var v=Wt(es.current);if(d=a.type,i!==null&&a.stateNode!=null)il(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 Ls(a),null}if(i=Wt(yi.current),zc(a)){h=a.stateNode,d=a.type;var b=a.memoizedProps;switch(h[vr]=a,h[za]=b,i=(a.mode&1)!==0,d){case"dialog":Cn("cancel",h),Cn("close",h);break;case"iframe":case"object":case"embed":Cn("load",h);break;case"video":case"audio":for(v=0;v<wr.length;v++)Cn(wr[v],h);break;case"source":Cn("error",h);break;case"img":case"image":case"link":Cn("error",h),Cn("load",h);break;case"details":Cn("toggle",h);break;case"input":lt(h,b),Cn("invalid",h);break;case"select":h._wrapperState={wasMultiple:!!b.multiple},Cn("invalid",h);break;case"textarea":Dt(h,b),Cn("invalid",h)}gn(d,b),v=null;for(var R in b)if(b.hasOwnProperty(R)){var ee=b[R];R==="children"?typeof ee=="string"?h.textContent!==ee&&(b.suppressHydrationWarning!==!0&&Xr(h.textContent,ee,i),v=["children",ee]):typeof ee=="number"&&h.textContent!==""+ee&&(b.suppressHydrationWarning!==!0&&Xr(h.textContent,ee,i),v=["children",""+ee]):o.hasOwnProperty(R)&&ee!=null&&R==="onScroll"&&Cn("scroll",h)}switch(d){case"input":Ue(h),Ie(h,b,!0);break;case"textarea":Ue(h),pn(h);break;case"select":case"option":break;default:typeof b.onClick=="function"&&(h.onclick=xs)}h=v,a.updateQueue=h,h!==null&&(a.flags|=4)}else{R=v.nodeType===9?v:v.ownerDocument,i==="http://www.w3.org/1999/xhtml"&&(i=Ut(d)),i==="http://www.w3.org/1999/xhtml"?d==="script"?(i=R.createElement("div"),i.innerHTML="<script><\/script>",i=i.removeChild(i.firstChild)):typeof h.is=="string"?i=R.createElement(d,{is:h.is}):(i=R.createElement(d),d==="select"&&(R=i,h.multiple?R.multiple=!0:h.size&&(R.size=h.size))):i=R.createElementNS(i,d),i[vr]=a,i[za]=h,qd(i,a,!1,!1),a.stateNode=i;e:{switch(R=Es(d,h),d){case"dialog":Cn("cancel",i),Cn("close",i),v=h;break;case"iframe":case"object":case"embed":Cn("load",i),v=h;break;case"video":case"audio":for(v=0;v<wr.length;v++)Cn(wr[v],i);v=h;break;case"source":Cn("error",i),v=h;break;case"img":case"image":case"link":Cn("error",i),Cn("load",i),v=h;break;case"details":Cn("toggle",i),v=h;break;case"input":lt(i,h),v=et(i,h),Cn("invalid",i);break;case"option":v=h;break;case"select":i._wrapperState={wasMultiple:!!h.multiple},v=G({},h,{value:void 0}),Cn("invalid",i);break;case"textarea":Dt(i,h),v=Ye(i,h),Cn("invalid",i);break;default:v=h}gn(d,v),ee=v;for(b in ee)if(ee.hasOwnProperty(b)){var se=ee[b];b==="style"?vn(i,se):b==="dangerouslySetInnerHTML"?(se=se?se.__html:void 0,se!=null&&Wn(i,se)):b==="children"?typeof se=="string"?(d!=="textarea"||se!=="")&&Mt(i,se):typeof se=="number"&&Mt(i,""+se):b!=="suppressContentEditableWarning"&&b!=="suppressHydrationWarning"&&b!=="autoFocus"&&(o.hasOwnProperty(b)?se!=null&&b==="onScroll"&&Cn("scroll",i):se!=null&&O(i,b,se,R))}switch(d){case"input":Ue(i),Ie(i,h,!1);break;case"textarea":Ue(i),pn(i);break;case"option":h.value!=null&&i.setAttribute("value",""+we(h.value));break;case"select":i.multiple=!!h.multiple,b=h.value,b!=null?De(i,!!h.multiple,b,!1):h.defaultValue!=null&&De(i,!!h.multiple,h.defaultValue,!0);break;default:typeof v.onClick=="function"&&(i.onclick=xs)}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 Ls(a),null;case 6:if(i&&a.stateNode!=null)Hd(i,a,i.memoizedProps,h);else{if(typeof h!="string"&&a.stateNode===null)throw Error(n(166));if(d=Wt(es.current),Wt(yi.current),zc(a)){if(h=a.stateNode,d=a.memoizedProps,h[vr]=a,(b=h.nodeValue!==d)&&(i=Sr,i!==null))switch(i.tag){case 3:Xr(h.nodeValue,d,(i.mode&1)!==0);break;case 5:i.memoizedProps.suppressHydrationWarning!==!0&&Xr(h.nodeValue,d,(i.mode&1)!==0)}b&&(a.flags|=4)}else h=(d.nodeType===9?d:d.ownerDocument).createTextNode(h),h[vr]=a,a.stateNode=h}return Ls(a),null;case 13:if(xn(Ln),h=a.memoizedState,i===null||i.memoizedState!==null&&i.memoizedState.dehydrated!==null){if(_n&&kr!==null&&(a.mode&1)!==0&&(a.flags&128)===0)Ul(),ea(),a.flags|=98560,b=!1;else if(b=zc(a),h!==null&&h.dehydrated!==null){if(i===null){if(!b)throw Error(n(318));if(b=a.memoizedState,b=b!==null?b.dehydrated:null,!b)throw Error(n(317));b[vr]=a}else ea(),(a.flags&128)===0&&(a.memoizedState=null),a.flags|=4;Ls(a),b=!1}else En!==null&&(dl(En),En=null),b=!0;if(!b)return a.flags&65536?a:null}return(a.flags&128)!==0?(a.lanes=d,a):(h=h!==null,h!==(i!==null&&i.memoizedState!==null)&&h&&(a.child.flags|=8192,(a.mode&1)!==0&&(i===null||(Ln.current&1)!==0?Jn===0&&(Jn=3):gu())),a.updateQueue!==null&&(a.flags|=4),Ls(a),null);case 4:return $o(),Yi(i,a),i===null&&Ms(a.stateNode.containerInfo),Ls(a),null;case 10:return xd(a.type._context),Ls(a),null;case 17:return fs(a.type)&&qa(),Ls(a),null;case 19:if(xn(Ln),b=a.memoizedState,b===null)return Ls(a),null;if(h=(a.flags&128)!==0,R=b.rendering,R===null)if(h)ol(b,!1);else{if(Jn!==0||i!==null&&(i.flags&128)!==0)for(i=a.child;i!==null;){if(R=at(i),R!==null){for(a.flags|=128,ol(b,!1),h=R.updateQueue,h!==null&&(a.updateQueue=h,a.flags|=4),a.subtreeFlags=0,h=d,d=a.child;d!==null;)b=d,i=h,b.flags&=14680066,R=b.alternate,R===null?(b.childLanes=0,b.lanes=i,b.child=null,b.subtreeFlags=0,b.memoizedProps=null,b.memoizedState=null,b.updateQueue=null,b.dependencies=null,b.stateNode=null):(b.childLanes=R.childLanes,b.lanes=R.lanes,b.child=R.child,b.subtreeFlags=0,b.deletions=null,b.memoizedProps=R.memoizedProps,b.memoizedState=R.memoizedState,b.updateQueue=R.updateQueue,b.type=R.type,i=R.dependencies,b.dependencies=i===null?null:{lanes:i.lanes,firstContext:i.firstContext}),d=d.sibling;return bn(Ln,Ln.current&1|2),a.child}i=i.sibling}b.tail!==null&&hn()>ua&&(a.flags|=128,h=!0,ol(b,!1),a.lanes=4194304)}else{if(!h)if(i=at(R),i!==null){if(a.flags|=128,h=!0,d=i.updateQueue,d!==null&&(a.updateQueue=d,a.flags|=4),ol(b,!0),b.tail===null&&b.tailMode==="hidden"&&!R.alternate&&!_n)return Ls(a),null}else 2*hn()-b.renderingStartTime>ua&&d!==1073741824&&(a.flags|=128,h=!0,ol(b,!1),a.lanes=4194304);b.isBackwards?(R.sibling=a.child,a.child=R):(d=b.last,d!==null?d.sibling=R:a.child=R,b.last=R)}return b.tail!==null?(a=b.tail,b.rendering=a,b.tail=a.sibling,b.renderingStartTime=hn(),a.sibling=null,d=Ln.current,bn(Ln,h?d&1|2:d&1),a):(Ls(a),null);case 22:case 23:return pu(),h=a.memoizedState!==null,i!==null&&i.memoizedState!==null!==h&&(a.flags|=8192),h&&(a.mode&1)!==0?(Er&1073741824)!==0&&(Ls(a),a.subtreeFlags&6&&(a.flags|=8192)):Ls(a),null;case 24:return null;case 25:return null}throw Error(n(156,a.tag))}function al(i,a){switch(Pc(a),a.tag){case 1:return fs(a.type)&&qa(),i=a.flags,i&65536?(a.flags=i&-65537|128,a):null;case 3:return $o(),xn(zs),xn(Rs),Hl(),i=a.flags,(i&65536)!==0&&(i&128)===0?(a.flags=i&-65537|128,a):null;case 5:return ra(a),null;case 13:if(xn(Ln),i=a.memoizedState,i!==null&&i.dehydrated!==null){if(a.alternate===null)throw Error(n(340));ea()}return i=a.flags,i&65536?(a.flags=i&-65537|128,a):null;case 19:return xn(Ln),null;case 4:return $o(),null;case 10:return xd(a.type._context),null;case 22:case 23:return pu(),null;case 24:return null;default:return null}}var iu=!1,ss=!1,Lh=typeof WeakSet=="function"?WeakSet:Set,Qe=null;function Mo(i,a){var d=i.ref;if(d!==null)if(typeof d=="function")try{d(null)}catch(h){S(i,a,h)}else d.current=null}function Vd(i,a,d){try{d()}catch(h){S(i,a,h)}}var Ih=!1;function j_(i,a){if(Ui=qo,i=Cc(),od(i)){if("selectionStart"in i)var d={start:i.selectionStart,end:i.selectionEnd};else e:{d=(d=i.ownerDocument)&&d.defaultView||window;var h=d.getSelection&&d.getSelection();if(h&&h.rangeCount!==0){d=h.anchorNode;var v=h.anchorOffset,b=h.focusNode;h=h.focusOffset;try{d.nodeType,b.nodeType}catch{d=null;break e}var R=0,ee=-1,se=-1,ye=0,Me=0,Le=i,Te=null;t:for(;;){for(var Xe;Le!==d||v!==0&&Le.nodeType!==3||(ee=R+v),Le!==b||h!==0&&Le.nodeType!==3||(se=R+h),Le.nodeType===3&&(R+=Le.nodeValue.length),(Xe=Le.firstChild)!==null;)Te=Le,Le=Xe;for(;;){if(Le===i)break t;if(Te===d&&++ye===v&&(ee=R),Te===b&&++Me===h&&(se=R),(Xe=Le.nextSibling)!==null)break;Le=Te,Te=Le.parentNode}Le=Xe}d=ee===-1||se===-1?null:{start:ee,end:se}}else d=null}d=d||{start:0,end:0}}else d=null;for(vo={focusedElem:i,selectionRange:d},qo=!1,Qe=a;Qe!==null;)if(a=Qe,i=a.child,(a.subtreeFlags&1028)!==0&&i!==null)i.return=a,Qe=i;else for(;Qe!==null;){a=Qe;try{var tt=a.alternate;if((a.flags&1024)!==0)switch(a.tag){case 0:case 11:case 15:break;case 1:if(tt!==null){var nt=tt.memoizedProps,os=tt.memoizedState,de=a.stateNode,le=de.getSnapshotBeforeUpdate(a.elementType===a.type?nt:Fr(a.type,nt),os);de.__reactInternalSnapshotBeforeUpdate=le}break;case 3:var me=a.stateNode.containerInfo;me.nodeType===1?me.textContent="":me.nodeType===9&&me.documentElement&&me.removeChild(me.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(n(163))}}catch(Fe){S(a,a.return,Fe)}if(i=a.sibling,i!==null){i.return=a.return,Qe=i;break}Qe=a.return}return tt=Ih,Ih=!1,tt}function js(i,a,d){var h=a.updateQueue;if(h=h!==null?h.lastEffect:null,h!==null){var v=h=h.next;do{if((v.tag&i)===i){var b=v.destroy;v.destroy=void 0,b!==void 0&&Vd(a,d,b)}v=v.next}while(v!==h)}}function Ji(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 Gd(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 Kd(i){var a=i.alternate;a!==null&&(i.alternate=null,Kd(a)),i.child=null,i.deletions=null,i.sibling=null,i.tag===5&&(a=i.stateNode,a!==null&&(delete a[vr],delete a[za],delete a[Lc],delete a[fd],delete a[lh])),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 ir(i){return i.tag===5||i.tag===3||i.tag===4}function ou(i){e:for(;;){for(;i.sibling===null;){if(i.return===null||ir(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 au(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=xs));else if(h!==4&&(i=i.child,i!==null))for(au(i,a,d),i=i.sibling;i!==null;)au(i,a,d),i=i.sibling}function lu(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(lu(i,a,d),i=i.sibling;i!==null;)lu(i,a,d),i=i.sibling}var Ss=null,ri=!1;function Kn(i,a,d){for(d=d.child;d!==null;)ll(i,a,d),d=d.sibling}function ll(i,a,d){if(gs&&typeof gs.onCommitFiberUnmount=="function")try{gs.onCommitFiberUnmount(rn,d)}catch{}switch(d.tag){case 5:ss||Mo(d,a);case 6:var h=Ss,v=ri;Ss=null,Kn(i,a,d),Ss=h,ri=v,Ss!==null&&(ri?(i=Ss,d=d.stateNode,i.nodeType===8?i.parentNode.removeChild(d):i.removeChild(d)):Ss.removeChild(d.stateNode));break;case 18:Ss!==null&&(ri?(i=Ss,d=d.stateNode,i.nodeType===8?Or(i.parentNode,d):i.nodeType===1&&Or(i,d),mo(i)):Or(Ss,d.stateNode));break;case 4:h=Ss,v=ri,Ss=d.stateNode.containerInfo,ri=!0,Kn(i,a,d),Ss=h,ri=v;break;case 0:case 11:case 14:case 15:if(!ss&&(h=d.updateQueue,h!==null&&(h=h.lastEffect,h!==null))){v=h=h.next;do{var b=v,R=b.destroy;b=b.tag,R!==void 0&&((b&2)!==0||(b&4)!==0)&&Vd(d,a,R),v=v.next}while(v!==h)}Kn(i,a,d);break;case 1:if(!ss&&(Mo(d,a),h=d.stateNode,typeof h.componentWillUnmount=="function"))try{h.props=d.memoizedProps,h.state=d.memoizedState,h.componentWillUnmount()}catch(ee){S(d,a,ee)}Kn(i,a,d);break;case 21:Kn(i,a,d);break;case 22:d.mode&1?(ss=(h=ss)||d.memoizedState!==null,Kn(i,a,d),ss=h):Kn(i,a,d);break;default:Kn(i,a,d)}}function Yd(i){var a=i.updateQueue;if(a!==null){i.updateQueue=null;var d=i.stateNode;d===null&&(d=i.stateNode=new Lh),a.forEach(function(h){var v=W.bind(null,i,h);d.has(h)||(d.add(h),h.then(v,v))})}}function zr(i,a){var d=a.deletions;if(d!==null)for(var h=0;h<d.length;h++){var v=d[h];try{var b=i,R=a,ee=R;e:for(;ee!==null;){switch(ee.tag){case 5:Ss=ee.stateNode,ri=!1;break e;case 3:Ss=ee.stateNode.containerInfo,ri=!0;break e;case 4:Ss=ee.stateNode.containerInfo,ri=!0;break e}ee=ee.return}if(Ss===null)throw Error(n(160));ll(b,R,v),Ss=null,ri=!1;var se=v.alternate;se!==null&&(se.return=null),v.return=null}catch(ye){S(v,a,ye)}}if(a.subtreeFlags&12854)for(a=a.child;a!==null;)Oh(a,i),a=a.sibling}function Oh(i,a){var d=i.alternate,h=i.flags;switch(i.tag){case 0:case 11:case 14:case 15:if(zr(a,i),ii(i),h&4){try{js(3,i,i.return),Ji(3,i)}catch(nt){S(i,i.return,nt)}try{js(5,i,i.return)}catch(nt){S(i,i.return,nt)}}break;case 1:zr(a,i),ii(i),h&512&&d!==null&&Mo(d,d.return);break;case 5:if(zr(a,i),ii(i),h&512&&d!==null&&Mo(d,d.return),i.flags&32){var v=i.stateNode;try{Mt(v,"")}catch(nt){S(i,i.return,nt)}}if(h&4&&(v=i.stateNode,v!=null)){var b=i.memoizedProps,R=d!==null?d.memoizedProps:b,ee=i.type,se=i.updateQueue;if(i.updateQueue=null,se!==null)try{ee==="input"&&b.type==="radio"&&b.name!=null&&Je(v,b),Es(ee,R);var ye=Es(ee,b);for(R=0;R<se.length;R+=2){var Me=se[R],Le=se[R+1];Me==="style"?vn(v,Le):Me==="dangerouslySetInnerHTML"?Wn(v,Le):Me==="children"?Mt(v,Le):O(v,Me,Le,ye)}switch(ee){case"input":Se(v,b);break;case"textarea":tn(v,b);break;case"select":var Te=v._wrapperState.wasMultiple;v._wrapperState.wasMultiple=!!b.multiple;var Xe=b.value;Xe!=null?De(v,!!b.multiple,Xe,!1):Te!==!!b.multiple&&(b.defaultValue!=null?De(v,!!b.multiple,b.defaultValue,!0):De(v,!!b.multiple,b.multiple?[]:"",!1))}v[za]=b}catch(nt){S(i,i.return,nt)}}break;case 6:if(zr(a,i),ii(i),h&4){if(i.stateNode===null)throw Error(n(162));v=i.stateNode,b=i.memoizedProps;try{v.nodeValue=b}catch(nt){S(i,i.return,nt)}}break;case 3:if(zr(a,i),ii(i),h&4&&d!==null&&d.memoizedState.isDehydrated)try{mo(a.containerInfo)}catch(nt){S(i,i.return,nt)}break;case 4:zr(a,i),ii(i);break;case 13:zr(a,i),ii(i),v=i.child,v.flags&8192&&(b=v.memoizedState!==null,v.stateNode.isHidden=b,!b||v.alternate!==null&&v.alternate.memoizedState!==null||(uu=hn())),h&4&&Yd(i);break;case 22:if(Me=d!==null&&d.memoizedState!==null,i.mode&1?(ss=(ye=ss)||Me,zr(a,i),ss=ye):zr(a,i),ii(i),h&8192){if(ye=i.memoizedState!==null,(i.stateNode.isHidden=ye)&&!Me&&(i.mode&1)!==0)for(Qe=i,Me=i.child;Me!==null;){for(Le=Qe=Me;Qe!==null;){switch(Te=Qe,Xe=Te.child,Te.tag){case 0:case 11:case 14:case 15:js(4,Te,Te.return);break;case 1:Mo(Te,Te.return);var tt=Te.stateNode;if(typeof tt.componentWillUnmount=="function"){h=Te,d=Te.return;try{a=h,tt.props=a.memoizedProps,tt.state=a.memoizedState,tt.componentWillUnmount()}catch(nt){S(h,d,nt)}}break;case 5:Mo(Te,Te.return);break;case 22:if(Te.memoizedState!==null){Jd(Le);continue}}Xe!==null?(Xe.return=Te,Qe=Xe):Jd(Le)}Me=Me.sibling}e:for(Me=null,Le=i;;){if(Le.tag===5){if(Me===null){Me=Le;try{v=Le.stateNode,ye?(b=v.style,typeof b.setProperty=="function"?b.setProperty("display","none","important"):b.display="none"):(ee=Le.stateNode,se=Le.memoizedProps.style,R=se!=null&&se.hasOwnProperty("display")?se.display:null,ee.style.display=Mn("display",R))}catch(nt){S(i,i.return,nt)}}}else if(Le.tag===6){if(Me===null)try{Le.stateNode.nodeValue=ye?"":Le.memoizedProps}catch(nt){S(i,i.return,nt)}}else if((Le.tag!==22&&Le.tag!==23||Le.memoizedState===null||Le===i)&&Le.child!==null){Le.child.return=Le,Le=Le.child;continue}if(Le===i)break e;for(;Le.sibling===null;){if(Le.return===null||Le.return===i)break e;Me===Le&&(Me=null),Le=Le.return}Me===Le&&(Me=null),Le.sibling.return=Le.return,Le=Le.sibling}}break;case 19:zr(a,i),ii(i),h&4&&Yd(i);break;case 21:break;default:zr(a,i),ii(i)}}function ii(i){var a=i.flags;if(a&2){try{e:{for(var d=i.return;d!==null;){if(ir(d)){var h=d;break e}d=d.return}throw Error(n(160))}switch(h.tag){case 5:var v=h.stateNode;h.flags&32&&(Mt(v,""),h.flags&=-33);var b=ou(i);lu(i,b,v);break;case 3:case 4:var R=h.stateNode.containerInfo,ee=ou(i);au(i,ee,R);break;default:throw Error(n(161))}}catch(se){S(i,i.return,se)}i.flags&=-3}a&4096&&(i.flags&=-4097)}function Xi(i,a,d){Qe=i,Ph(i)}function Ph(i,a,d){for(var h=(i.mode&1)!==0;Qe!==null;){var v=Qe,b=v.child;if(v.tag===22&&h){var R=v.memoizedState!==null||iu;if(!R){var ee=v.alternate,se=ee!==null&&ee.memoizedState!==null||ss;ee=iu;var ye=ss;if(iu=R,(ss=se)&&!ye)for(Qe=v;Qe!==null;)R=Qe,se=R.child,R.tag===22&&R.memoizedState!==null?cu(v):se!==null?(se.return=R,Qe=se):cu(v);for(;b!==null;)Qe=b,Ph(b),b=b.sibling;Qe=v,iu=ee,ss=ye}Dh(i)}else(v.subtreeFlags&8772)!==0&&b!==null?(b.return=v,Qe=b):Dh(i)}}function Dh(i){for(;Qe!==null;){var a=Qe;if((a.flags&8772)!==0){var d=a.alternate;try{if((a.flags&8772)!==0)switch(a.tag){case 0:case 11:case 15:ss||Ji(5,a);break;case 1:var h=a.stateNode;if(a.flags&4&&!ss)if(d===null)h.componentDidMount();else{var v=a.elementType===a.type?d.memoizedProps:Fr(a.type,d.memoizedProps);h.componentDidUpdate(v,d.memoizedState,h.__reactInternalSnapshotBeforeUpdate)}var b=a.updateQueue;b!==null&&bd(a,b,h);break;case 3:var R=a.updateQueue;if(R!==null){if(d=null,a.child!==null)switch(a.child.tag){case 5:d=a.child.stateNode;break;case 1:d=a.child.stateNode}bd(a,R,d)}break;case 5:var ee=a.stateNode;if(d===null&&a.flags&4){d=ee;var se=a.memoizedProps;switch(a.type){case"button":case"input":case"select":case"textarea":se.autoFocus&&d.focus();break;case"img":se.src&&(d.src=se.src)}}break;case 6:break;case 4:break;case 12:break;case 13:if(a.memoizedState===null){var ye=a.alternate;if(ye!==null){var Me=ye.memoizedState;if(Me!==null){var Le=Me.dehydrated;Le!==null&&mo(Le)}}}break;case 19:case 17:case 21:case 22:case 23:case 25:break;default:throw Error(n(163))}ss||a.flags&512&&Gd(a)}catch(Te){S(a,a.return,Te)}}if(a===i){Qe=null;break}if(d=a.sibling,d!==null){d.return=a.return,Qe=d;break}Qe=a.return}}function Jd(i){for(;Qe!==null;){var a=Qe;if(a===i){Qe=null;break}var d=a.sibling;if(d!==null){d.return=a.return,Qe=d;break}Qe=a.return}}function cu(i){for(;Qe!==null;){var a=Qe;try{switch(a.tag){case 0:case 11:case 15:var d=a.return;try{Ji(4,a)}catch(se){S(a,d,se)}break;case 1:var h=a.stateNode;if(typeof h.componentDidMount=="function"){var v=a.return;try{h.componentDidMount()}catch(se){S(a,v,se)}}var b=a.return;try{Gd(a)}catch(se){S(a,b,se)}break;case 5:var R=a.return;try{Gd(a)}catch(se){S(a,R,se)}}}catch(se){S(a,a.return,se)}if(a===i){Qe=null;break}var ee=a.sibling;if(ee!==null){ee.return=a.return,Qe=ee;break}Qe=a.return}}var Si=Math.ceil,la=M.ReactCurrentDispatcher,Xd=M.ReactCurrentOwner,rs=M.ReactCurrentBatchConfig,Qt=0,Yn=null,qt=null,Un=0,Er=0,ca=jo(0),Jn=0,cl=null,Ro=0,Kl=0,Yl=0,Zi=null,ks=null,uu=0,ua=1/0,ki=null,oi=!1,Zd=null,Lo=null,du=!1,or=null,ul=0,da=0,fu=null,Jl=-1,hu=0;function is(){return(Qt&6)!==0?hn():Jl!==-1?Jl:Jl=hn()}function ar(i){return(i.mode&1)===0?1:(Qt&2)!==0&&Un!==0?Un&-Un:fh.transition!==null?(hu===0&&(hu=ds()),hu):(i=on,i!==0||(i=window.event,i=i===void 0?16:je(i.type)),i)}function ai(i,a,d,h){if(50<da)throw da=0,fu=null,Error(n(185));ys(i,d,h),((Qt&2)===0||i!==Yn)&&(i===Yn&&((Qt&2)===0&&(Kl|=d),Jn===4&&Io(i,Un)),_s(i,h),d===1&&Qt===0&&(a.mode&1)===0&&(ua=hn()+500,Ic&&ko()))}function _s(i,a){var d=i.callbackNode;Xn(i,a);var h=_r(i,i===Yn?Un:0);if(h===0)d!==null&&ao(d),i.callbackNode=null,i.callbackPriority=0;else if(a=h&-h,i.callbackPriority!==a){if(d!=null&&ao(d),a===1)i.tag===0?Oc(Qd.bind(null,i)):uh(Qd.bind(null,i)),_i(function(){(Qt&6)===0&&ko()}),d=null;else{switch(El(h)){case 1:d=Mi;break;case 4:d=Mr;break;case 16:d=hr;break;case 536870912:d=it;break;default:d=hr}d=te(d,Fh.bind(null,i))}i.callbackPriority=a,i.callbackNode=d}}function Fh(i,a){if(Jl=-1,hu=0,(Qt&6)!==0)throw Error(n(327));var d=i.callbackNode;if(ha()&&i.callbackNode!==d)return null;var h=_r(i,i===Yn?Un:0);if(h===0)return null;if((h&30)!==0||(h&i.expiredLanes)!==0||a)a=Xl(i,h);else{a=h;var v=Qt;Qt|=2;var b=tf();(Yn!==i||Un!==a)&&(ki=null,ua=hn()+500,Oo(i,a));do try{Bh();break}catch(ee){ef(i,ee)}while(!0);vd(),la.current=b,Qt=v,qt!==null?a=0:(Yn=null,Un=0,a=Jn)}if(a!==0){if(a===2&&(v=Js(i),v!==0&&(h=v,a=mu(i,v))),a===1)throw d=cl,Oo(i,0),Io(i,h),_s(i,hn()),d;if(a===6)Io(i,h);else{if(v=i.current.alternate,(h&30)===0&&!S_(v)&&(a=Xl(i,h),a===2&&(b=Js(i),b!==0&&(h=b,a=mu(i,b))),a===1))throw d=cl,Oo(i,0),Io(i,h),_s(i,hn()),d;switch(i.finishedWork=v,i.finishedLanes=h,a){case 0:case 1:throw Error(n(345));case 2:Po(i,ks,ki);break;case 3:if(Io(i,h),(h&130023424)===h&&(a=uu+500-hn(),10<a)){if(_r(i,0)!==0)break;if(v=i.suspendedLanes,(v&h)!==h){is(),i.pingedLanes|=i.suspendedLanes&v;break}i.timeoutHandle=Wi(Po.bind(null,i,ks,ki),a);break}Po(i,ks,ki);break;case 4:if(Io(i,h),(h&4194240)===h)break;for(a=i.eventTimes,v=-1;0<h;){var R=31-us(h);b=1<<R,R=a[R],R>v&&(v=R),h&=~b}if(h=v,h=hn()-h,h=(120>h?120:480>h?480:1080>h?1080:1920>h?1920:3e3>h?3e3:4320>h?4320:1960*Si(h/1960))-h,10<h){i.timeoutHandle=Wi(Po.bind(null,i,ks,ki),h);break}Po(i,ks,ki);break;case 5:Po(i,ks,ki);break;default:throw Error(n(329))}}}return _s(i,hn()),i.callbackNode===d?Fh.bind(null,i):null}function mu(i,a){var d=Zi;return i.current.memoizedState.isDehydrated&&(Oo(i,a).flags|=256),i=Xl(i,a),i!==2&&(a=ks,ks=d,a!==null&&dl(a)),i}function dl(i){ks===null?ks=i:ks.push.apply(ks,i)}function S_(i){for(var a=i;;){if(a.flags&16384){var d=a.updateQueue;if(d!==null&&(d=d.stores,d!==null))for(var h=0;h<d.length;h++){var v=d[h],b=v.getSnapshot;v=v.value;try{if(!Yr(b(),v))return!1}catch{return!1}}}if(d=a.child,a.subtreeFlags&16384&&d!==null)d.return=a,a=d;else{if(a===i)break;for(;a.sibling===null;){if(a.return===null||a.return===i)return!0;a=a.return}a.sibling.return=a.return,a=a.sibling}}return!0}function Io(i,a){for(a&=~Yl,a&=~Kl,i.suspendedLanes|=a,i.pingedLanes&=~a,i=i.expirationTimes;0<a;){var d=31-us(a),h=1<<d;i[d]=-1,a&=~h}}function Qd(i){if((Qt&6)!==0)throw Error(n(327));ha();var a=_r(i,0);if((a&1)===0)return _s(i,hn()),null;var d=Xl(i,a);if(i.tag!==0&&d===2){var h=Js(i);h!==0&&(a=h,d=mu(i,h))}if(d===1)throw d=cl,Oo(i,0),Io(i,a),_s(i,hn()),d;if(d===6)throw Error(n(345));return i.finishedWork=i.current.alternate,i.finishedLanes=a,Po(i,ks,ki),_s(i,hn()),null}function _u(i,a){var d=Qt;Qt|=1;try{return i(a)}finally{Qt=d,Qt===0&&(ua=hn()+500,Ic&&ko())}}function fa(i){or!==null&&or.tag===0&&(Qt&6)===0&&ha();var a=Qt;Qt|=1;var d=rs.transition,h=on;try{if(rs.transition=null,on=1,i)return i()}finally{on=h,rs.transition=d,Qt=a,(Qt&6)===0&&ko()}}function pu(){Er=ca.current,xn(ca)}function Oo(i,a){i.finishedWork=null,i.finishedLanes=0;var d=i.timeoutHandle;if(d!==-1&&(i.timeoutHandle=-1,dd(d)),qt!==null)for(d=qt.return;d!==null;){var h=d;switch(Pc(h),h.tag){case 1:h=h.type.childContextTypes,h!=null&&qa();break;case 3:$o(),xn(zs),xn(Rs),Hl();break;case 5:ra(h);break;case 4:$o();break;case 13:xn(Ln);break;case 19:xn(Ln);break;case 10:xd(h.type._context);break;case 22:case 23:pu()}d=d.return}if(Yn=i,qt=i=Oe(i.current,null),Un=Er=a,Jn=0,cl=null,Yl=Kl=Ro=0,ks=Zi=null,sa!==null){for(a=0;a<sa.length;a++)if(d=sa[a],h=d.interleaved,h!==null){d.interleaved=null;var v=h.next,b=d.pending;if(b!==null){var R=b.next;b.next=v,h.next=R}d.pending=h}sa=null}return i}function ef(i,a){do{var d=qt;try{if(vd(),Vc.current=An,Ja){for(var h=Pn.memoizedState;h!==null;){var v=h.queue;v!==null&&(v.pending=null),h=h.next}Ja=!1}if(Ao=0,ms=ts=Pn=null,wi=!1,Vl=0,Xd.current=null,d===null||d.return===null){Jn=1,cl=a,qt=null;break}e:{var b=i,R=d.return,ee=d,se=a;if(a=Un,ee.flags|=32768,se!==null&&typeof se=="object"&&typeof se.then=="function"){var ye=se,Me=ee,Le=Me.tag;if((Me.mode&1)===0&&(Le===0||Le===11||Le===15)){var Te=Me.alternate;Te?(Me.updateQueue=Te.updateQueue,Me.memoizedState=Te.memoizedState,Me.lanes=Te.lanes):(Me.updateQueue=null,Me.memoizedState=null)}var Xe=Bd(R);if(Xe!==null){Xe.flags&=-257,kh(Xe,R,ee,b,a),Xe.mode&1&&zd(b,ye,a),a=Xe,se=ye;var tt=a.updateQueue;if(tt===null){var nt=new Set;nt.add(se),a.updateQueue=nt}else tt.add(se);break e}else{if((a&1)===0){zd(b,ye,a),gu();break e}se=Error(n(426))}}else if(_n&&ee.mode&1){var os=Bd(R);if(os!==null){(os.flags&65536)===0&&(os.flags|=256),kh(os,R,ee,b,a),Ha(tl(se,ee));break e}}b=se=tl(se,ee),Jn!==4&&(Jn=2),Zi===null?Zi=[b]:Zi.push(b),b=R;do{switch(b.tag){case 3:b.flags|=65536,a&=-a,b.lanes|=a;var de=Dd(b,se,a);_h(b,de);break e;case 1:ee=se;var le=b.type,me=b.stateNode;if((b.flags&128)===0&&(typeof le.getDerivedStateFromError=="function"||me!==null&&typeof me.componentDidCatch=="function"&&(Lo===null||!Lo.has(me)))){b.flags|=65536,a&=-a,b.lanes|=a;var Fe=Fd(b,ee,a);_h(b,Fe);break e}}b=b.return}while(b!==null)}sf(d)}catch(rt){a=rt,qt===d&&d!==null&&(qt=d=d.return);continue}break}while(!0)}function tf(){var i=la.current;return la.current=An,i===null?An:i}function gu(){(Jn===0||Jn===3||Jn===2)&&(Jn=4),Yn===null||(Ro&268435455)===0&&(Kl&268435455)===0||Io(Yn,Un)}function Xl(i,a){var d=Qt;Qt|=2;var h=tf();(Yn!==i||Un!==a)&&(ki=null,Oo(i,a));do try{zh();break}catch(v){ef(i,v)}while(!0);if(vd(),Qt=d,la.current=h,qt!==null)throw Error(n(261));return Yn=null,Un=0,Jn}function zh(){for(;qt!==null;)nf(qt)}function Bh(){for(;qt!==null&&!xe();)nf(qt)}function nf(i){var a=V(i.alternate,i,Er);i.memoizedProps=i.pendingProps,a===null?sf(i):qt=a,Xd.current=null}function sf(i){var a=i;do{var d=a.alternate;if(i=a.return,(a.flags&32768)===0){if(d=Rh(d,a,Er),d!==null){qt=d;return}}else{if(d=al(d,a),d!==null){d.flags&=32767,qt=d;return}if(i!==null)i.flags|=32768,i.subtreeFlags=0,i.deletions=null;else{Jn=6,qt=null;return}}if(a=a.sibling,a!==null){qt=a;return}qt=a=i}while(a!==null);Jn===0&&(Jn=5)}function Po(i,a,d){var h=on,v=rs.transition;try{rs.transition=null,on=1,Uh(i,a,d,h)}finally{rs.transition=v,on=h}return null}function Uh(i,a,d,h){do ha();while(or!==null);if((Qt&6)!==0)throw Error(n(327));d=i.finishedWork;var v=i.finishedLanes;if(d===null)return null;if(i.finishedWork=null,i.finishedLanes=0,d===i.current)throw Error(n(177));i.callbackNode=null,i.callbackPriority=0;var b=d.lanes|d.childLanes;if(ka(i,b),i===Yn&&(qt=Yn=null,Un=0),(d.subtreeFlags&2064)===0&&(d.flags&2064)===0||du||(du=!0,te(hr,function(){return ha(),null})),b=(d.flags&15990)!==0,(d.subtreeFlags&15990)!==0||b){b=rs.transition,rs.transition=null;var R=on;on=1;var ee=Qt;Qt|=4,Xd.current=null,j_(i,d),Oh(d,i),g_(vo),qo=!!Ui,vo=Ui=null,i.current=d,Xi(d),Gn(),Qt=ee,on=R,rs.transition=b}else i.current=d;if(du&&(du=!1,or=i,ul=v),b=i.pendingLanes,b===0&&(Lo=null),ci(d.stateNode),_s(i,hn()),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(oi)throw oi=!1,i=Zd,Zd=null,i;return(ul&1)!==0&&i.tag!==0&&ha(),b=i.pendingLanes,(b&1)!==0?i===fu?da++:(da=0,fu=i):da=0,ko(),null}function ha(){if(or!==null){var i=El(ul),a=rs.transition,d=on;try{if(rs.transition=null,on=16>i?16:i,or===null)var h=!1;else{if(i=or,or=null,ul=0,(Qt&6)!==0)throw Error(n(331));var v=Qt;for(Qt|=4,Qe=i.current;Qe!==null;){var b=Qe,R=b.child;if((Qe.flags&16)!==0){var ee=b.deletions;if(ee!==null){for(var se=0;se<ee.length;se++){var ye=ee[se];for(Qe=ye;Qe!==null;){var Me=Qe;switch(Me.tag){case 0:case 11:case 15:js(8,Me,b)}var Le=Me.child;if(Le!==null)Le.return=Me,Qe=Le;else for(;Qe!==null;){Me=Qe;var Te=Me.sibling,Xe=Me.return;if(Kd(Me),Me===ye){Qe=null;break}if(Te!==null){Te.return=Xe,Qe=Te;break}Qe=Xe}}}var tt=b.alternate;if(tt!==null){var nt=tt.child;if(nt!==null){tt.child=null;do{var os=nt.sibling;nt.sibling=null,nt=os}while(nt!==null)}}Qe=b}}if((b.subtreeFlags&2064)!==0&&R!==null)R.return=b,Qe=R;else e:for(;Qe!==null;){if(b=Qe,(b.flags&2048)!==0)switch(b.tag){case 0:case 11:case 15:js(9,b,b.return)}var de=b.sibling;if(de!==null){de.return=b.return,Qe=de;break e}Qe=b.return}}var le=i.current;for(Qe=le;Qe!==null;){R=Qe;var me=R.child;if((R.subtreeFlags&2064)!==0&&me!==null)me.return=R,Qe=me;else e:for(R=le;Qe!==null;){if(ee=Qe,(ee.flags&2048)!==0)try{switch(ee.tag){case 0:case 11:case 15:Ji(9,ee)}}catch(rt){S(ee,ee.return,rt)}if(ee===R){Qe=null;break e}var Fe=ee.sibling;if(Fe!==null){Fe.return=ee.return,Qe=Fe;break e}Qe=ee.return}}if(Qt=v,ko(),gs&&typeof gs.onPostCommitFiberRoot=="function")try{gs.onPostCommitFiberRoot(rn,i)}catch{}h=!0}return h}finally{on=d,rs.transition=a}}return!1}function g(i,a,d){a=tl(d,a),a=Dd(i,a,1),i=gi(i,a,1),a=is(),i!==null&&(ys(i,1,a),_s(i,a))}function S(i,a,d){if(i.tag===3)g(i,i,d);else for(;a!==null;){if(a.tag===3){g(a,i,d);break}else if(a.tag===1){var h=a.stateNode;if(typeof a.type.getDerivedStateFromError=="function"||typeof h.componentDidCatch=="function"&&(Lo===null||!Lo.has(h))){i=tl(d,i),i=Fd(a,i,1),a=gi(a,i,1),i=is(),a!==null&&(ys(a,1,i),_s(a,i));break}}a=a.return}}function $(i,a,d){var h=i.pingCache;h!==null&&h.delete(a),a=is(),i.pingedLanes|=i.suspendedLanes&d,Yn===i&&(Un&d)===d&&(Jn===4||Jn===3&&(Un&130023424)===Un&&500>hn()-uu?Oo(i,0):Yl|=d),_s(i,a)}function I(i,a){a===0&&((i.mode&1)===0?a=1:(a=mr,mr<<=1,(mr&130023424)===0&&(mr=4194304)));var d=is();i=ti(i,a),i!==null&&(ys(i,a,d),_s(i,d))}function q(i){var a=i.memoizedState,d=0;a!==null&&(d=a.retryLane),I(i,d)}function W(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),I(i,d)}var V;V=function(i,a,d){if(i!==null)if(i.memoizedProps!==a.pendingProps||zs.current)rr=!0;else{if((i.lanes&d)===0&&(a.flags&128)===0)return rr=!1,b_(i,a,d);rr=(i.flags&131072)!==0}else rr=!1,_n&&(a.flags&1048576)!==0&&dh(a,Co,a.index);switch(a.lanes=0,a.tag){case 2:var h=a.type;rl(i,a),i=a.pendingProps;var v=Wa(a,Rs.current);Ka(a,d),v=Nd(null,a,h,i,v,d);var b=Cd();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,fs(h)?(b=!0,Vi(a)):b=!1,a.memoizedState=v.state!==null&&v.state!==void 0?v.state:null,zn(a),v.updater=tu,a.stateNode=v,v._reactInternals=a,Pd(a,h,i,d),a=nl(null,a,h,!0,b,d)):(a.tag=0,_n&&b&&zl(a),Us(null,a,v,d),a=a.child),a;case 16:h=a.elementType;e:{switch(rl(i,a),i=a.pendingProps,v=h._init,h=v(h._payload),a.type=h,v=a.tag=Ae(h),i=Fr(h,i),v){case 0:a=Wd(null,a,h,i,d);break e;case 1:a=$h(null,a,h,i,d);break e;case 11:a=Nh(null,a,h,i,d);break e;case 14:a=Ch(null,a,h,Fr(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:Fr(h,v),Wd(i,a,h,v,d);case 1:return h=a.type,v=a.pendingProps,v=a.elementType===h?v:Fr(h,v),$h(i,a,h,v,d);case 3:e:{if(Ah(a),i===null)throw Error(n(387));h=a.pendingProps,b=a.memoizedState,v=b.element,Wc(i,a),Hc(a,h,null,d);var R=a.memoizedState;if(h=R.element,b.isDehydrated)if(b={element:h,isDehydrated:!1,cache:R.cache,pendingSuspenseBoundaries:R.pendingSuspenseBoundaries,transitions:R.transitions},a.updateQueue.baseState=b,a.memoizedState=b,a.flags&256){v=tl(Error(n(423)),a),a=To(i,a,h,d,v);break e}else if(h!==v){v=tl(Error(n(424)),a),a=To(i,a,h,d,v);break e}else for(kr=qi(a.stateNode.containerInfo.firstChild),Sr=a,_n=!0,En=null,d=hh(a,null,h,d),a.child=d;d;)d.flags=d.flags&-3|4096,d=d.sibling;else{if(ea(),h===v){a=Ki(i,a,d);break e}Us(i,a,h,d)}a=a.child}return a;case 5:return jd(a),i===null&&pd(a),h=a.type,v=a.pendingProps,b=i!==null?i.memoizedProps:null,R=v.children,Da(h,v)?R=null:b!==null&&Da(h,b)&&(a.flags|=32),ru(i,a),Us(i,a,R,d),a.child;case 6:return i===null&&pd(a),null;case 13:return ni(i,a,d);case 4:return hs(a,a.stateNode.containerInfo),h=a.pendingProps,i===null?a.child=ta(a,null,h,d):Us(i,a,h,d),a.child;case 11:return h=a.type,v=a.pendingProps,v=a.elementType===h?v:Fr(h,v),Nh(i,a,h,v,d);case 7:return Us(i,a,a.pendingProps,d),a.child;case 8:return Us(i,a,a.pendingProps.children,d),a.child;case 12:return Us(i,a,a.pendingProps.children,d),a.child;case 10:e:{if(h=a.type._context,v=a.pendingProps,b=a.memoizedProps,R=v.value,bn(Wl,h._currentValue),h._currentValue=R,b!==null)if(Yr(b.value,R)){if(b.children===v.children&&!zs.current){a=Ki(i,a,d);break e}}else for(b=a.child,b!==null&&(b.return=a);b!==null;){var ee=b.dependencies;if(ee!==null){R=b.child;for(var se=ee.firstContext;se!==null;){if(se.context===h){if(b.tag===1){se=pi(-1,d&-d),se.tag=2;var ye=b.updateQueue;if(ye!==null){ye=ye.shared;var Me=ye.pending;Me===null?se.next=se:(se.next=Me.next,Me.next=se),ye.pending=se}}b.lanes|=d,se=b.alternate,se!==null&&(se.lanes|=d),ql(b.return,d,a),ee.lanes|=d;break}se=se.next}}else if(b.tag===10)R=b.type===a.type?null:b.child;else if(b.tag===18){if(R=b.return,R===null)throw Error(n(341));R.lanes|=d,ee=R.alternate,ee!==null&&(ee.lanes|=d),ql(R,d,a),R=b.sibling}else R=b.child;if(R!==null)R.return=b;else for(R=b;R!==null;){if(R===a){R=null;break}if(b=R.sibling,b!==null){b.return=R.return,R=b;break}R=R.return}b=R}Us(i,a,v.children,d),a=a.child}return a;case 9:return v=a.type,h=a.pendingProps.children,Ka(a,d),v=sr(v),h=h(v),a.flags|=1,Us(i,a,h,d),a.child;case 14:return h=a.type,v=Fr(h,a.pendingProps),v=Fr(h.type,v),Ch(i,a,h,v,d);case 15:return Eh(i,a,a.type,a.pendingProps,d);case 17:return h=a.type,v=a.pendingProps,v=a.elementType===h?v:Fr(h,v),rl(i,a),a.tag=1,fs(h)?(i=!0,Vi(a)):i=!1,Ka(a,d),el(a,h,v),Pd(a,h,v,d),nl(null,a,h,!0,i,d);case 19:return Mh(i,a,d);case 22:return Ud(i,a,d)}throw Error(n(156,a.tag))};function te(i,a){return Ys(i,a)}function $e(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 fe(i,a,d,h){return new $e(i,a,d,h)}function pe(i){return i=i.prototype,!(!i||!i.isReactComponent)}function Ae(i){if(typeof i=="function")return pe(i)?1:0;if(i!=null){if(i=i.$$typeof,i===F)return 11;if(i===P)return 14}return 2}function Oe(i,a){var d=i.alternate;return d===null?(d=fe(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 He(i,a,d,h,v,b){var R=2;if(h=i,typeof i=="function")pe(i)&&(R=1);else if(typeof i=="string")R=5;else e:switch(i){case Y:return Ve(d.children,v,b,a);case Z:R=8,v|=8;break;case re:return i=fe(12,d,a,v|2),i.elementType=re,i.lanes=b,i;case C:return i=fe(13,d,a,v),i.elementType=C,i.lanes=b,i;case N:return i=fe(19,d,a,v),i.elementType=N,i.lanes=b,i;case ne:return Ge(d,v,b,a);default:if(typeof i=="object"&&i!==null)switch(i.$$typeof){case ie:R=10;break e;case ue:R=9;break e;case F:R=11;break e;case P:R=14;break e;case D:R=16,h=null;break e}throw Error(n(130,i==null?i:typeof i,""))}return a=fe(R,d,a,v),a.elementType=i,a.type=h,a.lanes=b,a}function Ve(i,a,d,h){return i=fe(7,i,h,a),i.lanes=d,i}function Ge(i,a,d,h){return i=fe(22,i,h,a),i.elementType=ne,i.lanes=d,i.stateNode={isHidden:!1},i}function sn(i,a,d){return i=fe(6,i,null,a),i.lanes=d,i}function At(i,a,d){return a=fe(4,i.children!==null?i.children:[],i.key,a),a.lanes=d,a.stateNode={containerInfo:i.containerInfo,pendingChildren:null,implementation:i.implementation},a}function We(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=Vr(0),this.expirationTimes=Vr(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Vr(0),this.identifierPrefix=h,this.onRecoverableError=v,this.mutableSourceEagerHydrationData=null}function xt(i,a,d,h,v,b,R,ee,se){return i=new We(i,a,d,ee,se),a===1?(a=1,b===!0&&(a|=8)):a=0,b=fe(3,null,null,a),i.current=b,b.stateNode=i,b.memoizedState={element:h,isDehydrated:d,cache:null,transitions:null,pendingSuspenseBoundaries:null},zn(b),i}function Sn(i,a,d){var h=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:X,key:h==null?null:""+h,children:i,containerInfo:a,implementation:d}}function Tn(i){if(!i)return Hi;i=i._reactInternals;e:{if($t(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(fs(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(fs(d))return md(i,d,a)}return a}function Ws(i,a,d,h,v,b,R,ee,se){return i=xt(d,h,!0,i,v,b,R,ee,se),i.context=Tn(null),d=i.current,h=is(),v=ar(d),b=pi(h,v),b.callback=a??null,gi(d,b,v),i.current.lanes=v,ys(i,v,h),_s(i,h),i}function qs(i,a,d,h){var v=a.current,b=is(),R=ar(v);return d=Tn(d),a.context===null?a.context=d:a.pendingContext=d,a=pi(b,R),a.payload={element:i},h=h===void 0?null:h,h!==null&&(a.callback=h),i=gi(v,a,R),i!==null&&(ai(i,v,R,b),qc(i,v,R)),R}function lr(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 fl(i,a){if(i=i.memoizedState,i!==null&&i.dehydrated!==null){var d=i.retryLane;i.retryLane=d!==0&&d<a?d:a}}function k_(i,a){fl(i,a),(i=i.alternate)&&fl(i,a)}function I0(){return null}var ry=typeof reportError=="function"?reportError:function(i){console.error(i)};function N_(i){this._internalRoot=i}Wh.prototype.render=N_.prototype.render=function(i){var a=this._internalRoot;if(a===null)throw Error(n(409));qs(i,a,null,null)},Wh.prototype.unmount=N_.prototype.unmount=function(){var i=this._internalRoot;if(i!==null){this._internalRoot=null;var a=i.containerInfo;fa(function(){qs(null,i,null,null)}),a[xr]=null}};function Wh(i){this._internalRoot=i}Wh.prototype.unstable_scheduleHydration=function(i){if(i){var a=Na();i={blockedOn:null,target:i,priority:a};for(var d=0;d<gr.length&&a!==0&&a<gr[d].priority;d++);gr.splice(d,0,i),d===0&&Qs(i)}};function C_(i){return!(!i||i.nodeType!==1&&i.nodeType!==9&&i.nodeType!==11)}function qh(i){return!(!i||i.nodeType!==1&&i.nodeType!==9&&i.nodeType!==11&&(i.nodeType!==8||i.nodeValue!==" react-mount-point-unstable "))}function iy(){}function O0(i,a,d,h,v){if(v){if(typeof h=="function"){var b=h;h=function(){var ye=lr(R);b.call(ye)}}var R=Ws(a,h,i,0,null,!1,!1,"",iy);return i._reactRootContainer=R,i[xr]=R.current,Ms(i.nodeType===8?i.parentNode:i),fa(),R}for(;v=i.lastChild;)i.removeChild(v);if(typeof h=="function"){var ee=h;h=function(){var ye=lr(se);ee.call(ye)}}var se=xt(i,0,!1,null,null,!1,!1,"",iy);return i._reactRootContainer=se,i[xr]=se.current,Ms(i.nodeType===8?i.parentNode:i),fa(function(){qs(a,se,d,h)}),se}function Hh(i,a,d,h,v){var b=d._reactRootContainer;if(b){var R=b;if(typeof v=="function"){var ee=v;v=function(){var se=lr(R);ee.call(se)}}qs(a,R,i,v)}else R=O0(d,a,i,v,h);return lr(R)}Ri=function(i){switch(i.tag){case 3:var a=i.stateNode;if(a.current.memoizedState.isDehydrated){var d=Rn(a.pendingLanes);d!==0&&(ho(a,d|1),_s(a,hn()),(Qt&6)===0&&(ua=hn()+500,ko()))}break;case 13:fa(function(){var h=ti(i,1);if(h!==null){var v=is();ai(h,i,1,v)}}),k_(i,1)}},pr=function(i){if(i.tag===13){var a=ti(i,134217728);if(a!==null){var d=is();ai(a,i,134217728,d)}k_(i,134217728)}},As=function(i){if(i.tag===13){var a=ar(i),d=ti(i,a);if(d!==null){var h=is();ai(d,i,a,h)}k_(i,a)}},Na=function(){return on},Rr=function(i,a){var d=on;try{return on=i,a()}finally{on=d}},Tr=function(i,a,d){switch(a){case"input":if(Se(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=Dl(h);if(!v)throw Error(n(90));_t(h),Se(h,v)}}}break;case"textarea":tn(i,d);break;case"select":a=d.value,a!=null&&De(i,!!d.multiple,a,!1)}},st=_u,ut=fa;var P0={usingClientEntryPoint:!1,Events:[Ba,Ua,Dl,Ke,qe,_u]},rf={findFiberByHostInstance:bo,bundleType:0,version:"18.3.1",rendererPackageName:"react-dom"},D0={bundleType:rf.bundleType,version:rf.version,rendererPackageName:rf.rendererPackageName,rendererConfig:rf.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:M.ReactCurrentDispatcher,findHostInstanceByFiber:function(i){return i=$s(i),i===null?null:i.stateNode},findFiberByHostInstance:rf.findFiberByHostInstance||I0,findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null,reconcilerVersion:"18.3.1-next-f1338f8080-20240426"};if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"){var Vh=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!Vh.isDisabled&&Vh.supportsFiber)try{rn=Vh.inject(D0),gs=Vh}catch{}}return Br.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=P0,Br.createPortal=function(i,a){var d=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!C_(a))throw Error(n(200));return Sn(i,a,null,d)},Br.createRoot=function(i,a){if(!C_(i))throw Error(n(299));var d=!1,h="",v=ry;return a!=null&&(a.unstable_strictMode===!0&&(d=!0),a.identifierPrefix!==void 0&&(h=a.identifierPrefix),a.onRecoverableError!==void 0&&(v=a.onRecoverableError)),a=xt(i,1,!1,null,null,d,!1,h,v),i[xr]=a.current,Ms(i.nodeType===8?i.parentNode:i),new N_(a)},Br.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=$s(a),i=i===null?null:i.stateNode,i},Br.flushSync=function(i){return fa(i)},Br.hydrate=function(i,a,d){if(!qh(a))throw Error(n(200));return Hh(null,i,a,!0,d)},Br.hydrateRoot=function(i,a,d){if(!C_(i))throw Error(n(405));var h=d!=null&&d.hydratedSources||null,v=!1,b="",R=ry;if(d!=null&&(d.unstable_strictMode===!0&&(v=!0),d.identifierPrefix!==void 0&&(b=d.identifierPrefix),d.onRecoverableError!==void 0&&(R=d.onRecoverableError)),a=Ws(a,null,i,1,d??null,v,!1,b,R),i[xr]=a.current,Ms(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 Wh(a)},Br.render=function(i,a,d){if(!qh(a))throw Error(n(200));return Hh(null,i,a,!1,d)},Br.unmountComponentAtNode=function(i){if(!qh(i))throw Error(n(40));return i._reactRootContainer?(fa(function(){Hh(null,null,i,!1,function(){i._reactRootContainer=null,i[xr]=null})}),!0):!1},Br.unstable_batchedUpdates=_u,Br.unstable_renderSubtreeIntoContainer=function(i,a,d,h){if(!qh(d))throw Error(n(200));if(i==null||i._reactInternals===void 0)throw Error(n(38));return Hh(i,a,d,!1,h)},Br.version="18.3.1-next-f1338f8080-20240426",Br}var hy;function Ev(){if(hy)return A_.exports;hy=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(),A_.exports=G0(),A_.exports}var my;function K0(){if(my)return Gh;my=1;var e=Ev();return Gh.createRoot=e.createRoot,Gh.hydrateRoot=e.hydrateRoot,Gh}var Y0=K0();const J0=vg(Y0),$v=[{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"]}];$v.map(e=>({id:e.id,label:e.label}));function X0(e){return`theme-${String(e||"").trim()||"dark"}`}function _y(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(X0(e))}catch{}}const Ep=[{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}],$p=[{id:"compact",label:"Compact",density:.85},{id:"standard",label:"Standard",density:1},{id:"spacious",label:"Spacious",density:1.2}];function Z0(e){const t=String(e).trim();return Ep.find(n=>n.id===t)||Ep[1]}function Q0(e){const t=String(e).trim();return $p.find(n=>n.id===t)||$p[1]}function py(e){try{const t=document.documentElement,n=Z0(e.font_scale||"md"),r=Q0(e.header_density||"standard");t.style.setProperty("--font-scale",String(n.scale)),t.style.setProperty("--header-density",String(r.density))}catch{}}const R_={sm:"(max-width: 767.98px)",md:"(max-width: 1023.98px)",short:"(max-height: 500px)"};function ej(e){try{return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia(e).matches}catch{return!1}}function gy(e){const[t,n]=m.useState(()=>ej(e));return m.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 af=null;function tj(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 nj(){if(af)return af;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}=tj(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),af=()=>{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"),af=null},af}var Av=Ev();function yu(...e){return e.filter(Boolean).join(" ")}function Pu({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:_=240,variant:p="panel",className:y,triggerClassName:w,ariaLabel:x,id:k,includeValueOption:j=!1,onOpen:E,customOptionLabel:A,validateCustomValue:L,onChange:O,renderOption:M,renderValue:H}){const X=m.useRef(null),Y=m.useRef(null),Z=m.useRef(null),re=m.useRef(E),ie=m.useId(),ue=k||`af-select-${ie.replace(/[^a-zA-Z0-9_-]/g,"")}`,F=`${ue}-listbox`,[C,N]=m.useState(!1),[P,D]=m.useState(""),[ne,B]=m.useState(0),[z,G]=m.useState("bottom"),[T,Q]=m.useState({left:0,top:0,width:0});m.useEffect(()=>{re.current=E},[E]);const K=m.useMemo(()=>{if(!j)return t;const ge=String(e??"").trim();return!ge||t.some(De=>De.value===ge)?t:[...t,{value:ge,label:ge}]},[j,t,e]),J=m.useMemo(()=>{const ge=String(e??"");return K.find(De=>De.value===ge)||null},[K,e]),oe=m.useMemo(()=>(J==null?void 0:J.label)||String(e||"").trim()||"",[J,e]),he=m.useMemo(()=>{const ge=P.trim().toLowerCase();return ge?K.filter(De=>De.label.toLowerCase().includes(ge)||De.value.toLowerCase().includes(ge)):K},[K,P]),_e=m.useMemo(()=>{if(!c)return null;const ge=P.trim();if(!ge||K.some(Dt=>Dt.value===ge))return null;const Ye=(L==null?void 0:L(ge,{options:K}))||"";return{value:ge,label:A?A(ge):`Use "${ge}"`,disabled:!!Ye,reason:Ye}},[c,A,K,P,L]),we=m.useMemo(()=>{const ge=_e?[_e,...he]:he;if(ge.length>0)return ge;const De=String(e??"").trim();return o&&De?[{value:De,label:oe||De}]:ge},[_e,he,o,oe,e]),Ee=m.useCallback(()=>{const ge=X.current;if(!ge)return;const De=ge.getBoundingClientRect(),Ye=Math.max(De.width,_),Dt=Math.max(8,Math.min(De.left,window.innerWidth-Ye-8)),tn=window.innerHeight-De.bottom,pn=De.top,Ut=tn>=220||tn>=pn?"bottom":"top";G(Ut);const It=Ut==="bottom"?De.bottom+6:De.top-6;Q({left:Dt,top:It,width:Ye})},[_]),ze=m.useCallback(()=>{N(!1),D("")},[]);m.useEffect(()=>{var ge;C&&((ge=re.current)==null||ge.call(re))},[C]),m.useEffect(()=>{if(!C)return;Ee();const ge=()=>Ee();return window.addEventListener("resize",ge),window.addEventListener("scroll",ge,!0),()=>{window.removeEventListener("resize",ge),window.removeEventListener("scroll",ge,!0)}},[C,Ee]),m.useEffect(()=>{if(!C)return;const ge=De=>{var Dt,tn;const Ye=De.target;Ye&&((Dt=X.current)!=null&&Dt.contains(Ye)||(tn=Y.current)!=null&&tn.contains(Ye)||ze())};return document.addEventListener("mousedown",ge,!0),()=>document.removeEventListener("mousedown",ge,!0)},[C,ze]),m.useEffect(()=>{if(!C)return;const ge=Math.max(0,we.findIndex(De=>De.value===e));B(ge===-1?0:ge),l&&setTimeout(()=>{var De;return(De=Z.current)==null?void 0:De.focus()},0)},[C,l,e,we]);const Ue=ge=>{var Ye;const De=we.find(Dt=>Dt.value===ge);De!=null&&De.disabled||(O(ge),ze(),(Ye=X.current)==null||Ye.focus())},_t=ge=>{var De,Ye;if(ge.key==="Escape")return ge.preventDefault(),ze(),(De=X.current)==null||De.focus(),!0;if(ge.key==="Tab")return ze(),(Ye=X.current)==null||Ye.focus(),!1;if(ge.key==="ArrowDown")return ge.preventDefault(),B(Dt=>Math.min(Dt+1,Math.max(0,we.length-1))),!0;if(ge.key==="ArrowUp")return ge.preventDefault(),B(Dt=>Math.max(Dt-1,0)),!0;if(ge.key==="Home")return ge.preventDefault(),B(0),!0;if(ge.key==="End")return ge.preventDefault(),B(Math.max(0,we.length-1)),!0;if(ge.key==="Enter"){ge.preventDefault();const Dt=we[ne];return Dt&&Ue(Dt.value),!0}return!1},Pe=ge=>{if(!r){if(C){if(_t(ge))return;if(ge.key===" "&&!l){ge.preventDefault();const De=we[ne];De&&Ue(De.value)}return}(ge.key==="Enter"||ge.key===" "||ge.key==="ArrowDown"||ge.key==="ArrowUp")&&(ge.preventDefault(),N(!0))}},et=!!String(e||"").trim(),lt=et?oe:n,Je=_e!=null&&_e.disabled?_e.reason||"Unavailable":"",Se=C&&we.length>0?`${ue}-opt-${ne}`:void 0,Ie=s.jsx("span",{className:yu("af-select-value",!et&&"af-select-value--placeholder"),children:o&&!et?"Loading…":lt}),ct=H?H(J,String(e||"")):Ie;return s.jsxs("span",{className:yu("af-select",p==="pin"?"af-select--pin":"af-select--panel",y),children:[s.jsxs("button",{ref:X,id:ue,type:"button",className:yu("af-select-trigger",f&&et&&"af-select-trigger--clearable",w),disabled:r,onMouseDown:ge=>ge.stopPropagation(),onClick:ge=>{ge.stopPropagation(),!r&&N(De=>!De)},onKeyDown:Pe,role:l?void 0:"combobox","aria-haspopup":"listbox","aria-expanded":C,"aria-controls":C?F:void 0,"aria-activedescendant":l?void 0:Se,"aria-label":x,children:[ct,s.jsx("span",{className:yu("af-select-caret",C&&"af-select-caret--open"),children:"▾"})]}),f&&et?s.jsx("button",{type:"button",className:"af-select-clear-btn","aria-label":"Clear selection",disabled:r,onMouseDown:ge=>{ge.preventDefault(),ge.stopPropagation()},onClick:ge=>{var De;ge.preventDefault(),ge.stopPropagation(),O(""),ze(),(De=X.current)==null||De.focus()},title:"Clear",children:"×"}):null,C?Av.createPortal(s.jsxs("div",{ref:Y,className:yu("af-select-popover",z==="top"&&"af-select-popover--top"),style:{position:"fixed",left:`${T.left}px`,top:`${T.top}px`,width:`${T.width}px`},onMouseDown:ge=>ge.stopPropagation(),onClick:ge=>ge.stopPropagation(),onWheel:ge=>ge.stopPropagation(),onKeyDown:_t,tabIndex:-1,children:[l?s.jsxs("div",{className:"af-select-search",children:[s.jsx("input",{ref:Z,className:"af-select-search-input",value:P,onChange:ge=>D(ge.target.value),placeholder:u,onKeyDown:_t,role:"combobox","aria-expanded":!0,"aria-controls":F,"aria-activedescendant":Se,"aria-invalid":!!Je,"aria-describedby":Je?`${ue}-custom-error`:void 0}),Je?s.jsx("div",{id:`${ue}-custom-error`,className:"af-select-custom-error",role:"alert",children:Je}):null]}):null,s.jsx("div",{className:"af-select-options",role:"listbox",id:F,"aria-label":x,children:o&&we.length===0?s.jsx("div",{className:"af-select-empty",children:"Loading…"}):we.length===0?s.jsx("div",{className:"af-select-empty",children:"No results"}):we.map((ge,De)=>{var It;const Ye=ge.value===e,Dt=De===ne,tn=String(ge.group||"").trim(),pn=De>0?String(((It=we[De-1])==null?void 0:It.group)||"").trim():"",Ut=!!tn&&tn!==pn;return s.jsxs(ve.Fragment,{children:[Ut?s.jsx("div",{className:"af-select-group",role:"presentation",children:tn}):null,s.jsx("div",{id:`${ue}-opt-${De}`,role:"option","aria-selected":Ye,className:yu("af-select-option",Ye&&"af-select-option--selected",Dt&&"af-select-option--highlighted",ge.disabled&&"af-select-option--disabled"),title:ge.disabled?ge.reason||"Unavailable":void 0,onMouseEnter:()=>B(De),onMouseDown:un=>{un.preventDefault(),un.stopPropagation()},onClick:()=>Ue(ge.value),"aria-disabled":ge.disabled?!0:void 0,children:M?M(ge,{selected:Ye,highlighted:Dt}):s.jsxs(s.Fragment,{children:[s.jsxs("span",{className:"af-select-option-label",children:[s.jsx("span",{children:ge.label}),ge.reason?s.jsx("small",{className:"af-select-option-reason",children:ge.reason}):null]}),Ye?s.jsx("span",{className:"af-select-check",children:"✓"}):null]})})]},ge.value)})})]}),document.body):null]})}function sj(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 rj(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 ij(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)"),_=String(e.provider||"").trim(),p=String(e.model||"").trim(),y=sj(e.providers),w=rj(e.models),x=t||!!e.loadingProviders,k=t||!!e.loadingModels,j=[...r?[{value:"",label:o}]:[],...y.map(A=>({value:A.name,label:A.display_name?`${A.display_name} (${A.name})`:A.name}))],E=[...r?[{value:"",label:o}]:[],...w.map(A=>({value:A,label:A}))];return s.jsxs("div",{className:e.className,style:n==="row"?{display:"flex",gap:"10px",flexWrap:"wrap",alignItems:"flex-start"}:{display:"flex",flexDirection:"column",gap:"10px"},children:[s.jsxs("div",{style:n==="row"?{flex:"1 1 260px",minWidth:240}:void 0,children:[s.jsx("label",{children:l}),s.jsx(Pu,{value:_,options:j,placeholder:r?o:c,disabled:x,loading:!!e.loadingProviders,searchable:!0,allowCustom:e.allowCustomProvider===!0,clearable:r,variant:"panel",triggerClassName:e.selectClassName,ariaLabel:l,onChange:A=>e.onChange({provider:String(A||"").trim(),model:""})}),e.loadingProviders?s.jsx("div",{className:"mono muted",style:{fontSize:"12px",marginTop:"6px"},children:"Loading providers…"}):null,e.providerError?s.jsx("div",{className:"mono",style:{color:"var(--error)",fontSize:"12px",marginTop:"6px"},children:e.providerError}):null]}),s.jsxs("div",{style:n==="row"?{flex:"1 1 260px",minWidth:240}:void 0,children:[s.jsx("label",{children:u}),s.jsx(Pu,{value:p,options:E,placeholder:r?o:f,disabled:k,loading:!!e.loadingModels,searchable:!0,allowCustom:e.allowCustomModel===!0,clearable:r,variant:"panel",triggerClassName:e.selectClassName,ariaLabel:u,onChange:A=>e.onChange({provider:_,model:String(A||"").trim()})}),e.loadingModels?s.jsx("div",{className:"mono muted",style:{fontSize:"12px",marginTop:"6px"},children:"Loading models…"}):null,e.modelError?s.jsx("div",{className:"mono",style:{color:"var(--error)",fontSize:"12px",marginTop:"6px"},children:e.modelError}):null]})]})}function yy(...e){return e.filter(Boolean).join(" ")}function oj({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="Gateway token missing",statusTone:o="warn",tokenSourceLabel:l="token: missing",showGatewayUrl:u=!1,gatewayUrl:c="",gatewayUrlPlaceholder:f="http://127.0.0.1:8080",onGatewayUrlChange:_,userId:p,userPlaceholder:y="admin",onUserIdChange:w,token:x,tokenPlaceholder:k="Paste Gateway user token",showToken:j=!1,onTokenChange:E,onShowTokenChange:A,remember:L=!1,rememberLabel:O="Remember this browser",onRememberChange:M,loading:H=!1,submitting:X=!1,submitDisabled:Y=!1,submitLabel:Z="Sign in",submittingLabel:re="Signing in...",closeLabel:ie="Close",signOutLabel:ue="Sign out",showClose:F=!1,showSignOut:C=!1,error:N,message:P,className:D,onSubmit:ne,onClose:B,onSignOut:z}){const G=H||X,T=G||Y||!String(p||"").trim()||!String(x||"").trim(),Q=K=>{K.preventDefault(),!T&&ne()};return s.jsxs("form",{className:yy("af-gateway-signin",D),onSubmit:Q,children:[s.jsxs("div",{className:"af-gateway-signin__hero",children:[s.jsxs("div",{children:[s.jsx("div",{className:"af-gateway-signin__kicker",children:e}),s.jsx("h2",{children:t}),n?s.jsx("p",{children:n}):null]}),s.jsx("div",{className:"af-gateway-signin__mark","aria-hidden":"true",children:"↔"})]}),s.jsxs("div",{className:"af-gateway-signin__status-row",children:[s.jsx("span",{className:yy("af-gateway-signin__status",`af-gateway-signin__status--${o}`),children:r}),l?s.jsx("span",{className:"af-gateway-signin__source",children:l}):null]}),s.jsxs("div",{className:"af-gateway-signin__form",children:[u?s.jsxs(s.Fragment,{children:[s.jsx("label",{className:"af-gateway-signin__label",htmlFor:"gateway-session-url",children:"Gateway URL"}),s.jsx("input",{id:"gateway-session-url",value:c,onChange:K=>_==null?void 0:_(K.target.value),placeholder:f,autoComplete:"url",disabled:G})]}):null,s.jsx("label",{className:"af-gateway-signin__label",htmlFor:"gateway-session-user",children:"Gateway user"}),s.jsx("input",{id:"gateway-session-user",value:p,onChange:K=>w(K.target.value),placeholder:y,autoComplete:"username",disabled:G}),s.jsx("label",{className:"af-gateway-signin__label",htmlFor:"gateway-session-token",children:"Gateway token"}),s.jsxs("div",{className:"af-gateway-signin__token-input",children:[s.jsx("input",{id:"gateway-session-token",type:j?"text":"password",value:x,onChange:K=>E(K.target.value),placeholder:k,autoComplete:"current-password",disabled:G}),s.jsx("button",{className:"af-gateway-signin__secondary",type:"button",onClick:()=>A==null?void 0:A(!j),disabled:G,children:j?"Hide":"Show"})]}),s.jsx("label",{className:"af-gateway-signin__label",children:"Browser session"}),s.jsxs("label",{className:"af-gateway-signin__checkbox",children:[s.jsx("input",{type:"checkbox",checked:!!L,onChange:K=>M==null?void 0:M(K.target.checked),disabled:G}),O]})]}),N?s.jsx("div",{className:"af-gateway-signin__message af-gateway-signin__message--error",children:N}):null,!N&&P?s.jsx("div",{className:"af-gateway-signin__message af-gateway-signin__message--ok",children:P}):null,s.jsxs("div",{className:"af-gateway-signin__actions",children:[F?s.jsx("button",{className:"af-gateway-signin__secondary",type:"button",onClick:B,disabled:G,children:ie}):null,C?s.jsx("button",{className:"af-gateway-signin__secondary",type:"button",onClick:()=>void(z==null?void 0:z()),disabled:G,children:ue}):null,s.jsx("button",{className:"af-gateway-signin__primary",type:"submit",disabled:T,children:X?re:Z})]})]})}function aj(e){return e==="light"?"Light":"Dark"}function lj(e){const t=e.themes&&e.themes.length?e.themes:$v,n=e.showSwatches!==!1,r=e.variant||"panel",o=m.useMemo(()=>{const u={};for(const c of t)u[c.id]=c;return u},[t]),l=m.useMemo(()=>t.map(u=>({value:u.id,label:u.label,group:aj(u.group)})),[t]);return s.jsx(Pu,{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(),_=o[f],p=(_==null?void 0:_.label)||f||e.placeholder||"Select theme…",y=(_==null?void 0:_.swatches)||null,w=!f;return s.jsxs("span",{className:"af-theme-value",children:[s.jsx("span",{className:`af-theme-label ${w?"af-theme-label--placeholder":""}`.trim(),children:p}),n&&y?s.jsx("span",{className:"af-theme-swatches","aria-hidden":"true",children:y.map((x,k)=>s.jsx("span",{className:"af-theme-swatch",style:{background:x}},`${f}:${k}`))}):null]})},renderOption:(u,c)=>{const f=String(u.value||"").trim(),_=o[f],p=(_==null?void 0:_.swatches)||null;return s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"af-theme-option-label",children:u.label}),s.jsxs("span",{className:"af-theme-option-right",children:[n&&p?s.jsx("span",{className:"af-theme-swatches","aria-hidden":"true",children:p.map((y,w)=>s.jsx("span",{className:"af-theme-swatch",style:{background:y}},`${f}:${w}`))}):null,c.selected?s.jsx("span",{className:"af-select-check",children:"✓"}):null]})]})}})}function cj(e){const t=e.scales&&e.scales.length?e.scales:Ep,n=e.variant||"panel",r=m.useMemo(()=>t.map(o=>({value:o.id,label:o.label})),[t]);return s.jsx(Pu,{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 uj(e){const t=e.densities&&e.densities.length?e.densities:$p,n=e.variant||"panel",r=m.useMemo(()=>t.map(o=>({value:o.id,label:o.label})),[t]);return s.jsx(Pu,{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 dj=new Set(["board","inbox","server","agent","playCircle","list","gear"]);function fj(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 Ze({name:e,size:t=16,className:n,title:r,...o}){const l=r?void 0:!0,u=dj.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,fj(e)]})}const Ap="api/gateway",Wf="api/connection/gateway";function bt(e){const t=String(e||"");if(t.startsWith("/"))throw new Error(`gatewayApiPath takes a route relative to the gateway API, got ${JSON.stringify(t)}.`);return t?`${Ap}/${t}`:Ap}function Tv(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 hj(e){const t=String(e||""),n=`/${Ap}/`;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)}async function Tp(e=Wf){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 mj(e,t=Wf){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 Mv(e=Wf){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 L_(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 Rv(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 _j(e){const t=e.connectionPath||Wf,[n,r]=m.useState(!1),[o,l]=m.useState(!1),[u,c]=m.useState(null),[f,_]=m.useState(!1);m.useEffect(()=>{e.isOpen||_(!1)},[e.isOpen]);const[p,y]=m.useState(e.defaultGatewayUrl||"http://127.0.0.1:8080"),[w,x]=m.useState("admin"),[k,j]=m.useState(""),[E,A]=m.useState(!1),[L,O]=m.useState(!0),[M,H]=m.useState(""),[X,Y]=m.useState(""),Z=m.useMemo(()=>Rv(u),[u]),re=C=>{var N;c(C),(N=e.onStatusChange)==null||N.call(e,C)},ie=m.useRef(!1);if(m.useEffect(()=>{var N;if(!e.isOpen)return;const C=!ie.current;if(ie.current=!0,C&&e.initialStatus!==void 0&&e.initialStatus!==null){const P=e.initialStatus;re(P),typeof P.gateway_url=="string"&&P.gateway_url.trim()&&y(L_(P.gateway_url));const D=(N=P.gateway)==null?void 0:N.principal;D!=null&&D.user_id&&x(D.user_id);return}r(!0),H(""),Tp(t).then(P=>{var ne;re(P),typeof P.gateway_url=="string"&&P.gateway_url.trim()&&y(L_(P.gateway_url));const D=(ne=P.gateway)==null?void 0:ne.principal;D!=null&&D.user_id&&x(D.user_id)}).catch(P=>H(`Failed to load connection status: ${String((P==null?void 0:P.message)||P)}`)).finally(()=>r(!1))},[e.isOpen]),m.useEffect(()=>{if(!e.isOpen)return;const C=N=>{N.key==="Escape"&&!N.defaultPrevented&&!e.blocking&&(N.preventDefault(),e.onClose())};return window.addEventListener("keydown",C),()=>window.removeEventListener("keydown",C)},[e.isOpen,e.blocking,e.onClose]),!e.isOpen||f)return null;const ue=async()=>{l(!0),H(""),Y("");try{const C=L_(p);y(C);const N=await mj({gateway_url:C,gateway_user_id:w,gateway_token:k,persist:L},t);re(N),j(""),_(!0),e.onClose()}catch(C){H(String((C==null?void 0:C.message)||C))}finally{l(!1)}},F=async()=>{l(!0),H(""),Y("");try{await Mv(t),j("");const C=await Tp(t).catch(()=>null);re(C),Y("Signed out. This browser no longer holds a gateway session.")}catch(C){H(String((C==null?void 0:C.message)||C))}finally{l(!1)}};return s.jsx("div",{className:"af-connect-overlay",role:"presentation",onMouseDown:C=>{!e.blocking&&C.target===C.currentTarget&&e.onClose()},children:s.jsx("div",{className:"af-connect-modal",role:"dialog","aria-modal":"true","aria-label":"Gateway connection",children:s.jsx(oj,{kicker:`${e.appName||"AbstractFramework"} connection`,title:"Connect this browser to AbstractGateway",description:"Sign in with a Gateway user token. The app exchanges it for an HTTP-only browser session and never stores the raw token.",statusLabel:Z.label,statusTone:Z.tone,tokenSourceLabel:u!=null&&u.has_session?"token: browser session":"token: missing",showGatewayUrl:!0,gatewayUrl:p,onGatewayUrlChange:C=>y(C),userId:w,onUserIdChange:x,token:k,tokenPlaceholder:u!=null&&u.has_session?"(browser session already signed in)":"Paste Gateway user token",showToken:E,onTokenChange:j,onShowTokenChange:A,remember:L,rememberLabel:"Keep this browser signed in",onRememberChange:O,loading:n,submitting:o,submittingLabel:"Signing in...",showClose:!e.blocking,onClose:e.onClose,showSignOut:!e.blocking&&!!(u!=null&&u.has_session),onSignOut:F,error:M,message:X,onSubmit:ue})})})}function pj(e){return!!(e&&e.ok===!0&&e.has_session===!0)}function gj(e){const t=e||{},n=t.connectionPath||Wf,r=t.variant||"dismissable",o=m.useRef(t.onStatusChange);o.current=t.onStatusChange;const l=m.useRef(r);l.current=r;const u=m.useRef(!!t.autoOpenMidSession);u.current=!!t.autoOpenMidSession;const[c,f]=m.useState(null),[_,p]=m.useState("loading"),[y,w]=m.useState(!1),x=m.useRef(!1),k=m.useRef(!1),j=m.useRef("loading"),E=m.useRef("none"),A=m.useRef(!1),L=m.useRef(0),O=m.useCallback(N=>{var D;L.current+=1,f(N),(D=o.current)==null||D.call(o,N);const P=pj(N);if(P)p("connected"),j.current="connected",x.current=!1,E.current="none",k.current||w(!1);else if(N!==null){const ne=j.current;p("disconnected"),j.current="disconnected",ne!=="disconnected"&&(E.current=A.current?"signout":ne==="connected"?"mid":"boot");const B=l.current==="blocking"||E.current!=="mid"||u.current;!x.current&&B&&w(!0)}N!==null&&(k.current=P)},[]),M=m.useCallback(async()=>{const N=L.current;try{const P=await Tp(n);if(L.current!==N)return;O(P)}catch{if(L.current!==N)return;O(null)}},[n,O]),[H,X]=m.useState(!1),[Y,Z]=m.useState(null),re=m.useCallback(async()=>{X(!0),Z(null),L.current+=1;let N=null;try{await Mv(n)}catch(P){N=String((P==null?void 0:P.message)||P||"Sign-out request failed")}A.current=!0;try{await M()}finally{A.current=!1}Z(N),X(!1)},[n,M]),ie=m.useRef(!1);m.useEffect(()=>{ie.current||(ie.current=!0,M())},[M]);const ue=m.useCallback(()=>{w(!0)},[]),F=m.useCallback(()=>{const N=j.current;r==="blocking"&&N==="disconnected"||(N==="disconnected"&&(x.current=!0),w(!1))},[r]),C=m.useMemo(()=>({isOpen:y,onClose:F,blocking:r==="blocking"&&_!=="connected",appName:t.appName,connectionPath:n,defaultGatewayUrl:t.defaultGatewayUrl,initialStatus:c,onStatusChange:O}),[y,F,r,_,t.appName,n,t.defaultGatewayUrl,c,O]);return{status:c,phase:_,connected:_==="connected",modalOpen:y,signingOut:H,signOutError:Y,openModal:ue,refresh:M,signOut:re,modalProps:C}}function yj(){try{if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID()}catch{}return`steer-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function wj(){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 vj(e){const t=e.commandsPath||bt("commands"),n=yj(),r=JSON.stringify({command_id:n,run_id:e.runId,type:"inject_guidance",payload:{guidance:e.guidance}}),o=e.csrfToken!==void 0?[e.csrfToken]:wj();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 _=f&&typeof f=="object"&&f.detail?String(f.detail):`HTTP ${c.status}`;if(l=new Error(_),c.status===403&&f&&typeof f=="object"&&f.reason_code==="csrf_required")continue;throw l}return{accepted:!!(f!=null&&f.accepted),duplicate:!!(f!=null&&f.duplicate),seq:Number((f==null?void 0:f.seq)??0)}}throw l||new Error("Steer submit failed")}function xj(e){const[t,n]=m.useState(""),[r,o]=m.useState({kind:"idle"}),l=m.useRef(!1),u=m.useRef(0);m.useEffect(()=>{u.current+=1,o({kind:"idle"})},[e.runId]);const c=!e.disabled&&t.trim().length>0&&r.kind!=="sending",f=m.useMemo(()=>e.parked?"Run is waiting — your guidance delivers at its next wake (steers do not wake runs).":"Delivers at the run's next loop boundary.",[e.parked]),_=async()=>{var x;const y=t.trim();if(!y||l.current||e.disabled)return;l.current=!0;const w=u.current;o({kind:"sending"});try{const k=e.submit?await e.submit(e.runId,y):await vj({runId:e.runId,guidance:y,commandsPath:e.commandsPath});if(u.current!==w)return;if(!k.accepted&&!k.duplicate){o({kind:"error",detail:"The gateway did not accept this steer (accepted=false)."});return}o({kind:"queued",seq:k.seq,duplicate:k.duplicate}),n(""),(x=e.onSent)==null||x.call(e,{...k,guidance:y})}catch(k){u.current===w&&o({kind:"error",detail:String((k==null?void 0:k.message)||k)})}finally{l.current=!1}},p=y=>{y.key==="Enter"&&(y.metaKey||y.ctrlKey)&&(y.preventDefault(),_())};return s.jsxs("div",{className:`af-steer${e.className?` ${e.className}`:""}`,children:[s.jsxs("div",{className:"af-steer__row",children:[s.jsx("textarea",{className:"af-steer__input",value:t,rows:2,placeholder:e.placeholder||"Steer this run…","aria-label":e.ariaLabel||"Steer message",disabled:e.disabled||r.kind==="sending",onChange:y=>{n(y.target.value),(r.kind==="error"||r.kind==="queued")&&o({kind:"idle"})},onKeyDown:p}),s.jsx("button",{type:"button",className:"af-steer__send",disabled:!c,onClick:()=>void _(),title:"Send guidance (Cmd/Ctrl+Enter)",children: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 bj(e){const t=e.closeOnEscape!==!1,n=m.useRef(null);return m.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]),m.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 jj={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"},Sj={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"}},kj={framework:jj,apps:Sj},km=kj;function Nj(){return Object.keys(km.apps).sort()}function Cj(e,t){const n=Object.prototype.hasOwnProperty.call(km.apps,e)?km.apps[e]:void 0;if(!n)throw new Error(`appIdentity: unknown application id "${e}" (known: ${Nj().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 Ej(e,t){const n=km.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 I_(e){return typeof e=="string"?e.trim():""}function wy(e,t){if(t!=null)return[["Gateway",`unavailable (${String(t).trim()||"unknown error"})`]];const n=e&&typeof e=="object"&&!Array.isArray(e)?e:{},r=I_(n.abstractgateway);if(!r)return[["Gateway","unavailable (the gateway did not report its version)"]];const o=I_(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,_)=>f<_?-1:f>_?1:0);for(const f of c){const _=I_(u[f]);_&&l.push([`Gateway package ${f}`,_])}return l}const $j='a[href], button:not(:disabled), input:not(:disabled), select:not(:disabled), textarea:not(:disabled), [tabindex]:not([tabindex="-1"])';function Aj(e,t,n){if(e.key!=="Tab"||!t)return;const r=Array.from(t.querySelectorAll($j));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 Tj=/https?:\/\/[^\s<>"]+/g;function Mj(e,t){if(e==="Contact")return[{text:t,href:`mailto:${t}`}];const n=[];let r=0;for(const o of t.matchAll(Tj)){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 Rj({label:e,value:t}){return s.jsx("span",{children:Mj(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 Lj(e){const t=m.useRef(null),n=m.useRef(null),r=m.useId(),o=m.useRef(e.onClose);if(o.current=e.onClose,m.useEffect(()=>{var _;if(!e.open)return;const c=document.activeElement;(_=t.current)==null||_.focus();const f=p=>{if(!p.defaultPrevented){if(p.key==="Escape"){p.preventDefault(),o.current();return}Aj(p,n.current,document.activeElement)}};return window.addEventListener("keydown",f),()=>{window.removeEventListener("keydown",f),c&&typeof c.focus=="function"&&c.focus()}},[e.open]),!e.open)return null;const l=e.title||`About ${e.identity.name}`,u=Ej(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],_)=>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(Rj,{label:c,value:f})})]},`${_}:${c}`))}),s.jsx("div",{className:"af-appearance__actions",children:s.jsx("button",{ref:t,type:"button",className:"af-appearance__close",onClick:e.onClose,children:"Close"})})]})})}function Ij(e){const{connection:t}=e,n=t.phase,r=t.signingOut===!0,[o,l]=m.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(Ze,{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(Ze,{name:"contrast",size:16})}):null,u?s.jsx("button",{type:"button",className:"af-topbar__btn af-topbar__btn--about","aria-label":u.label||`About ${u.identity.name}`,title:u.label||"About","aria-haspopup":"dialog",onClick:()=>{var _;l(!0),(_=u.onOpen)==null||_.call(u)},children:s.jsx(Ze,{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(Lj,{open:o,onClose:()=>l(!1),identity:u.identity,extraRows:u.extraRows}):null]})}const pm={theme:"dark",font_scale:"md",header_density:"standard"};function Oj(e){const t=e&&typeof e=="object"?e:{};return{theme:typeof t.theme=="string"&&t.theme?t.theme:pm.theme,font_scale:typeof t.font_scale=="string"&&t.font_scale?t.font_scale:pm.font_scale,header_density:typeof t.header_density=="string"&&t.header_density?t.header_density:pm.header_density}}function Pj(e){return`af_appearance_${e}_v1`}function Dj(e,t){const n=Pj(e),r=m.useMemo(()=>({...pm,...(t==null?void 0:t.defaults)||{}}),[JSON.stringify((t==null?void 0:t.defaults)||{})]),[o,l]=m.useState(()=>{let u=r;try{const c=localStorage.getItem(n)??(t!=null&&t.legacyKey?localStorage.getItem(t.legacyKey):null);c&&(u=Oj({...r,...JSON.parse(c)}))}catch{}try{_y(u.theme),py({font_scale:u.font_scale,header_density:u.header_density})}catch{}return u});return m.useEffect(()=>{_y(o.theme),py({font_scale:o.font_scale,header_density:o.header_density});try{localStorage.setItem(n,JSON.stringify(o))}catch{}},[n,o]),[o,l]}function Fj(e){return m.useEffect(()=>{if(!e.open)return;const t=n=>{n.key!=="Escape"||n.defaultPrevented||(n.preventDefault(),e.onClose())};return window.addEventListener("keydown",t),()=>window.removeEventListener("keydown",t)},[e.open,e.onClose]),e.open?s.jsx("div",{className:"af-appearance-overlay",onClick:e.onClose,role:"presentation",children:s.jsxs("div",{className:"af-appearance",role:"dialog","aria-modal":"true","aria-label":e.title||"Appearance",onClick:t=>t.stopPropagation(),children:[s.jsx("div",{className:"af-appearance__title",children:e.title||"Appearance"}),s.jsx("div",{className:"af-appearance__note",children:e.note||"Stored locally in this browser, per app."}),s.jsxs("div",{className:"af-appearance__grid",children:[s.jsx("label",{className:"af-appearance__label",children:"Theme"}),s.jsx(lj,{value:e.value.theme,onChange:t=>e.onChange({...e.value,theme:t})}),s.jsx("label",{className:"af-appearance__label",children:"Font size"}),s.jsx(cj,{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(uj,{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 zj={diary:"var(--accent)",question:"#e7b45a",dream:"#c084dd",interest:"#7bd88a",lesson:"#6ea8d8",world_model:"#5eead4"};function vy(e){const t=String(e||"");return t.length>14?`${t.slice(0,10)}…${t.slice(-4)}`:t}function O_(e){const[t,n]=m.useState(!1),[r,o]=m.useState(null),l=m.useRef(!1),u=typeof e.entryId=="string"&&e.entryId.trim()?e.entryId.trim():null,c=e.kind&&zj[e.kind]||"var(--text-muted)",f=m.useCallback(async()=>{if(!(!u||!e.onOpen||l.current)){l.current=!0,n(!0),o(null);try{await e.onOpen(u)}catch(_){o(String((_==null?void 0:_.message)||_||"could not open"))}finally{l.current=!1,n(!1)}}},[u,e.onOpen]);return!u||!e.onOpen?s.jsxs("span",{className:["af-memory-hint","af-memory-hint--text",e.className||""].filter(Boolean).join(" "),title:e.title,children:[s.jsx("span",{className:"af-memory-hint__dot",style:{background:c},"aria-hidden":"true"}),s.jsx("span",{className:"af-memory-hint__label",children:e.label}),u&&e.showId!==!1?s.jsx("code",{className:"af-memory-hint__id",children:vy(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:vy(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 P_=bt("automations"),Bj=bt("trigger-sources"),Uj=bt("me/email");class xy 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 Wj(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 D_(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 qj(){const e=globalThis.crypto;if(!e||typeof e.randomUUID!="function")throw new Error("automations client: crypto.randomUUID is unavailable; pass options.newId");return e.randomUUID()}function Hj(e){const t=e.newId??qj,n=o=>`${P_}/${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 _=await e.fetch(Tv(e.baseUrl,l),f),p=await _.text();let y,w=!1;if(p)try{y=JSON.parse(p),w=!0}catch{w=!1}if(!_.ok)throw new xy(Wj(_.status,y));if(!w||y===null||typeof y!="object")throw new xy({status:_.status,code:"invalid_response",message:`The gateway answered ${o} ${l} with a body that is not a JSON object.`});return y}return{listAutomations:(o={})=>r("GET",`${P_}${D_({status:o.status,cursor:o.cursor,limit:o.limit})}`),getAutomation:o=>r("GET",n(o)),createAutomation:o=>r("POST",P_,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${D_({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${D_({cursor:l.cursor,limit:l.limit})}`),listTriggerSources:()=>r("GET",Bj),getMyEmail:()=>r("GET",Uj)}}const Vj={pause:"Pause",resume:"Resume",run_now:"Run now",stop_current:"Stop current",revise:"Edit",archive:"Archive",discuss:"Discuss"},Gj={pause:`Stop scheduled runs until you resume.
|
|
41
|
-
A run in progress, with its retries, finishes. Run now still works.`,resume:`Restart the schedule at its next time after now.
|
|
42
|
-
Times missed while paused are skipped; resuming does not run it now.`,run_now:`Run it once now, without waiting for the schedule.
|
|
43
|
-
The schedule does not move: the next scheduled run keeps its time, or starts right after this run if its time comes first.
|
|
44
|
-
Does not count toward a run limit. Works while paused; it stays paused.
|
|
45
|
-
Not available while a run is in progress.`,stop_current:`Cancel the run in progress, or its pending retry.
|
|
46
|
-
It ends as cancelled, with no failure notice. The schedule continues.`,revise:`Change the task, schedule or settings.
|
|
47
|
-
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.
|
|
48
|
-
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.
|
|
49
|
-
It has its own workspace (the automation's files are read-only) and never changes the automation.`},Kj="Next scheduled run: {time}.",Yj="Growing context: later runs see this run in their history.",Jj={run_now:{name:"playCircle"}},Xj={trigger_label:"When an email arrives",not_set_up:"Email isn't set up — open My email",open_my_email:"open My email",filters_legend:"Only mail that matches (all optional)",from_in:"From these addresses",from_domain_in:"From these domains",to_in:"Sent to these addresses",subject_contains:"Subject contains",has_attachment:"Attachments",has_attachment_any:"any",has_attachment_yes:"only with attachments",has_attachment_no:"only without attachments",list_hint:"Separate entries with commas or new lines. Exact addresses and domains only (no patterns).",every_label:"Check for new mail every",interval_rule:"An automation that runs a model on new mail checks once an hour by default; one that needs no model checks every 60 s. The shortest interval is 60 s.",max_batch_label:"At most this many emails per run",max_batch_hint:"The rest wait for the next run. Each email is read once by this automation; mail that arrived before it was created, or while it is paused, is not processed.",untrusted_hint:"Incoming mail is data, never instructions: the automation acts only on its task. Link-opening tools (fetch_url, browser_probe) always ask for your approval.",notify_label:"Email me the result",notify_hint:"When a run notifies you, or fails for good, the notice is also emailed to you.",recipients_legend:"May send email without asking to",recipients_self:"Only me (default)",recipients_list:"Me and these addresses",recipients_hint:"Sending to anyone else waits for your approval. Your recipient policy in My email still applies."},Lv={labels:Vj,hints:Gj,run_now_next_run_line:Kj,run_now_growing_line:Yj,icons:Jj,email:Xj},Zj=/^([1-9][0-9]*)([smhd])$/,Qj={s:["second","seconds"],m:["minute","minutes"],h:["hour","hours"],d:["day","days"]};function qf(e){if(typeof e!="string")return null;const t=Zj.exec(e);return t?{amount:Number(t[1]),unit:t[2]}:null}function Iv(e){const t=qf(e);if(!t)return`every ${e}`;const[n,r]=Qj[t.unit];return t.amount===1?`every ${n}`:`every ${t.amount} ${r}`}function va(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 Ov(e){const t=e;if(typeof t.every!="string")return t.start_at?`once at ${va(t.start_at)}`:"once, now";const n=[`${Iv(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 ${va(t.until)}`),n.join(" · ")}function xg(e){return e.source_id==="schedule"&&e.source_version===1?Ov(e.config):e.source_id==="manual"&&e.source_version===1?"manual runs only":Km(e)?qv(e.config):`${e.source_id}@${e.source_version}`}function Pv(e){return e==="growing"?"Growing — each run sees the previous runs":"Independent — each run starts fresh"}const eS={active:"Active",paused:"Paused",completed:"Completed",failed:"Failed",archived:"Archived"},Ht=Lv.email,Dv="email.received",Fv=1,tS="1h",nS="60s",zv=60,bg=100,Mp=1e3,by=200,jy=200,Sy=50;function Km(e){return!!e&&e.source_id===Dv&&e.source_version===Fv}function Ym(e){return!!e&&e.effective_enabled===!0}function Bv(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 sS=/[\s<>,;:"()[\]]/;function Rp(e){const t=e.trim().toLowerCase(),n=t.indexOf("@");return n<=0||n===t.length-1?!1:!t.slice(n+1).includes("@")&&!sS.test(t)}function rS(e){const t=e.trim().toLowerCase();return!!t&&!t.includes("@")&&t.includes(".")&&!t.startsWith(".")&&!t.endsWith(".")&&!/[\s<>,;:"()[\]/*]/.test(t)}const Uv={usesModel:!0,every:null,maxBatch:null,fromIn:"",fromDomainIn:"",toIn:"",subjectContains:"",hasAttachment:"any"};function jg(e){return e?tS:nS}function Wv(e){const t=qf(e);return t?t.amount*{s:1,m:60,h:3600,d:86400}[t.unit]:null}function F_(e,t,n,r,o){const l=Bv(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>by&&o.push(`${t}: at most ${by} entries.`),l}function iS(e){const t=[],n={uses_model:e.usesModel};e.every===null?n.every=jg(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&&(Wv(n.every)??0)<zv&&t.push("The check interval is at least 60 seconds."),e.maxBatch===null?n.max_batch=bg:!Number.isInteger(e.maxBatch)||e.maxBatch<1||e.maxBatch>Mp?t.push(`At most this many emails per run: a whole number from 1 to ${Mp}.`):n.max_batch=e.maxBatch;const r={},o=F_(e.fromIn,Ht.from_in,Rp,"an email address",t);o&&(r.from_in=o);const l=F_(e.fromDomainIn,Ht.from_domain_in,rS,"a domain like example.com",t);l&&(r.from_domain_in=l);const u=F_(e.toIn,Ht.to_in,Rp,"an email address",t);u&&(r.to_in=u);const c=e.subjectContains.trim();return c&&(c.length>jy||/[\r\n]/.test(c)?t.push(`${Ht.subject_contains}: one line of at most ${jy} 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 qv(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:jg(t.uses_model!==!1);r.push(`checked ${Iv(l)}`);const u=typeof t.max_batch=="number"?t.max_batch:bg;return r.push(`up to ${u} per run`),r.join(" · ")}const Sg={mode:"self",addresses:""};function Lp(e){if(e.mode==="self")return{recipients:["self"],errors:[]};const t=[],n=Bv(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=>!Rp(o));return r.length&&t.push(`${Ht.recipients_list}: ${r.join(", ")} ${r.length===1?"is not an email address":"are not email addresses"}.`),n.length+1>Sy&&t.push(`At most ${Sy-1} addresses.`),{recipients:["self",...n],errors:t}}function oS(e){const t=(e??[]).filter(n=>n!=="self");return t.length?{mode:"list",addresses:t.join(", ")}:{mode:"self",addresses:""}}function aS(e){const t=(e??["self"]).filter(n=>n!=="self");return t.length?`Me and ${t.join(", ")}`:"Only me"}function Hv(e){return{channels:e?["console","email"]:["console"]}}function Vv(e){return!!e&&Array.isArray(e.channels)&&e.channels.includes("email")}function lS(e){return Vv(e)?"In the console and by email":"In the console"}const Fo={pause:"automation.pause",resume:"automation.resume",run_now:"automation.run_now",stop_current:"automation.stop_current",archive:"automation.archive"},cS=new Set(["running","waiting","backoff"]);function uS(e,t=[]){return e.current_occurrence!=null}function Gv(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 Kv(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 Nm(e,t=[],n=!1){const r=new Set(e.capabilities),o=e.status,l=uS(e,t),u=(f,_,p)=>n?{enabled:!1,reason:"Working…"}:e.legacy?{enabled:!1,reason:"Legacy schedule: managed with its existing controls."}:r.has(f)?o==="archived"?{enabled:!1,reason:"Archived: history is kept, nothing runs."}:_?{enabled:!0}:{enabled:!1,reason:p}:{enabled:!1,reason:"Not permitted for this automation."},c=o==="active"||o==="paused";return{pause:u("pause",o==="active",o==="paused"?"Already paused.":"The automation has ended."),resume:u("resume",o==="paused",o==="active"?"Already running on schedule.":"The automation has ended."),run_now:u("run_now",c&&!l,l?"An occurrence is in progress.":"The automation has ended."),stop_current:u("stop_current",l,"Nothing is running."),revise:u("revise",!0,""),archive:u("archive",!0,""),discuss:n?{enabled:!1,reason:"Working…"}:e.legacy?{enabled:!1,reason:"Legacy schedule: discussion is not available."}:r.has("discuss")?{enabled:!0}:{enabled:!1,reason:"Discussion is not permitted for this automation."}}}function dS(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 fS(e){return[...e].sort((t,n)=>t.index-n.index).map(t=>{const n=dS(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:!cS.has(t.status)}})}function hS(e){const t=e.attention.items;return t.length?t[t.length-1].cursor:null}function Yv(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 mS={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 Cm(e){return{title:mS[e.code]??`The gateway refused the request (${e.code}).`,detail:e.message}}function kg(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 Jv(e,t){const n=e.trigger,r=n.source_id==="schedule"||Km(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,prompt:typeof o=="string"?o:null,toolApproval:t?t.policy.tool_approval:null,notifyEmail:t?Vv(t.notify):null,emailRecipients:t?oS(t.policy.email_allowed_recipients):null}}function _S(e,t,n){const r=[],o={},l=t.title.trim();l?l.length>120?r.push("Title is at most 120 characters."):l!==e.title&&(o.title=l):r.push("Title is required.");const u=Jv(e,n);if(t.every!==u.every&&t.every!==null){const c=Km(e.trigger);if(!qf(t.every))r.push("Interval must be a whole number of minutes, hours or days.");else if(c&&(Wv(t.every)??0)<zv)r.push("The check interval is at least 60 seconds.");else{const f={...e.trigger.config,every:t.every};c&&delete f.start_at,o.trigger={source_id:e.trigger.source_id,source_version:e.trigger.source_version,config:f}}}if(t.context!==e.context_mode&&(o.context={mode:t.context}),n&&typeof u.prompt=="string"&&typeof t.prompt=="string"&&t.prompt.trim()!==u.prompt.trim()){const c=t.prompt.trim();c?o.target={bundle_ref:n.target.bundle_ref,flow_id:n.target.flow_id,input_data:{...n.target.input_data,prompt:c}}:r.push("Task is required.")}if(n&&t.toolApproval&&t.toolApproval!==u.toolApproval&&(o.policy={tool_approval:t.toolApproval}),n&&typeof t.notifyEmail=="boolean"&&t.notifyEmail!==u.notifyEmail&&(o.notify=Hv(t.notifyEmail)),n&&t.emailRecipients){const c=Lp(t.emailRecipients),f=Lp(u.emailRecipients??Sg).recipients;c.errors.length?r.push(...c.errors):JSON.stringify(c.recipients)!==JSON.stringify(f)&&(o.policy={...o.policy??{},email_allowed_recipients:c.recipients})}return r.length?{errors:r}:Object.keys(o).length?o:null}const pS=[{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 z_(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 gS(e){const t=e.trim().split(`
|
|
50
|
-
`)[0].trim();return t.length>120?`${t.slice(0,119)}…`:t}function yS(e){const t=[],n={};if(e.when.kind==="once"){const o=z_(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=z_(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=z_(e.until);o?n.until=o:t.push("Stop at must be a date and time (UTC).")}return{config:n,errors:t}}function Ip(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()||gS(r);o.length>120&&n.push("Title is at most 120 characters.");const l=e.trigger==="email",u=l?iS(e.email??Uv):yS(e);n.push(...u.errors);const c=e.emailRecipients&&e.emailRecipients.mode==="list"?Lp(e.emailRecipients):null;if(c&&n.push(...c.errors),n.length||!t.target)return{ok:!1,errors:n};const f={...t.target,input_data:{...t.target.input_data??{},prompt:r}},_={request_id:t.requestId,title:o,target:f,trigger:l?{source_id:Dv,source_version:Fv,config:u.config}:{source_id:"schedule",source_version:1,config:u.config},context:{mode:e.context},policy:{tool_approval:e.toolApproval??"auto",...c?{email_allowed_recipients:c.recipients}:{}}};return e.notifyEmail===!0&&(_.notify=Hv(!0)),{ok:!0,body:_}}const wS="Tools run without asking (you approve them now by creating this automation)";function vS(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 xS(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 Xv={ask_user:"Question for you",tool_approval:"Approval needed",event:"Waiting for an event"};class bS{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||jS(n.error))&&this.open.delete(t)}}function jS(e){return kg(e)&&e.status>0&&e.code!=="invalid_response"}function SS(){const e=globalThis.crypto;if(!e||typeof e.randomUUID!="function")throw new Error("crypto.randomUUID is unavailable; pass newId");return e.randomUUID()}class kS{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 ky(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 Op(e){if(Ym(e.status))return null;const t=Ht.not_set_up,n=Ht.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 NS(e){const t=e.value,n=c=>e.onChange({...t,...c}),r=c=>`${e.idBase}-email-${c}`,o=qf(jg(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:Ht.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:Ht.interval_rule}),s.jsxs("label",{className:"af-auto__field",htmlFor:r("batch"),children:[s.jsx("span",{children:Ht.max_batch_label}),s.jsx("input",{id:r("batch"),name:"email_max_batch",type:"number",min:1,max:Mp,step:1,disabled:u,value:String(t.maxBatch??bg),onChange:c=>n({maxBatch:c.target.value.trim()===""?null:Number(c.target.value)})})]}),s.jsx("p",{className:"af-auto__hint",children:Ht.max_batch_hint}),s.jsxs("fieldset",{className:"af-auto__field af-email__filters",disabled:u,children:[s.jsx("legend",{children:Ht.filters_legend}),s.jsxs("label",{className:"af-auto__field",htmlFor:r("from"),children:[s.jsx("span",{children:Ht.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:Ht.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:Ht.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:Ht.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:Ht.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:Ht.has_attachment_any}),s.jsx("option",{value:"yes",children:Ht.has_attachment_yes}),s.jsx("option",{value:"no",children:Ht.has_attachment_no})]})]}),s.jsx("p",{className:"af-auto__hint",children:Ht.list_hint})]})]})}function CS(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.jsxs("label",{className:"af-email__check",children:[s.jsx("input",{type:"checkbox",name:"notify_email",checked:e.notifyEmail,disabled:n,onChange:r=>e.onNotifyEmailChange(r.target.checked)})," ",Ht.notify_label]}),s.jsx("p",{className:"af-auto__hint",children:Ht.notify_hint}),s.jsxs("fieldset",{className:"af-auto__field",disabled:n,"data-field":"email-recipients",children:[s.jsx("legend",{children:Ht.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"})})," ",Ht.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"})})," ",Ht.recipients_list]}),e.recipients.mode==="list"?s.jsx("textarea",{name:"email_recipient_list","aria-label":Ht.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:Ht.recipients_hint})]})]})}const ES={active:"play",paused:"pause",completed:"check",failed:"error",archived:"archive"};function Zv(e){const t=String(e.status),n=ES[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:eS[t]??t}),n?s.jsx(Ze,{name:n,size:e.iconSize??11,className:"af-auto__status-icon"}):null]})}const Pp="Discuss — fork at this occurrence (own workspace, automation files read-only)",Jm=e=>s.jsx("div",{className:"af-auto-text","data-unformatted":"true",children:e});function $S(e){return kg(e)?e:{status:0,code:"client_error",message:e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}}function Ny(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 AS(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 TS(e){const t=e.summary,n=Gv(t),r=AS(t,e.triggerSources),o=t.next_fire_at?`${va(t.next_fire_at)} (${Kv(t.next_fire_at,e.nowMs??Date.now())})`:t.status==="paused"?"none while paused":"none scheduled";return s.jsxs("header",{className:"af-auto__head",children:[s.jsxs("div",{className:"af-auto__titlebar",children:[s.jsx("h2",{className:"af-auto__title",id:e.titleId,tabIndex:-1,children:t.title}),s.jsx(Zv,{status:t.status}),t.legacy?s.jsx("span",{className:"af-auto__legacy",children:"Legacy schedule"}):null]}),s.jsxs("dl",{className:"af-auto__facts",children:[s.jsx("dt",{children:"When"}),s.jsxs("dd",{"data-fact":"trigger",children:[xg(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:Pv(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
|
|
51
|
-
${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(Ze,{name:"folder",size:14,className:"af-auto__path-icon"}),s.jsx(Ny,{path:t.workspace_root})]}):s.jsxs("span",{className:"af-auto__path af-auto__path--static",children:[s.jsx(Ze,{name:"folder",size:14,className:"af-auto__path-icon"}),s.jsx(Ny,{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:Yv(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 MS(e){const t=e.definition,n=e.renderText??Jm,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(Ze,{name:"chevronRight",size:14,className:"af-auto__definition-chevron"}),s.jsx(Ze,{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," · ",xg(t.trigger),s.jsx("pre",{className:"af-auto__json",children:JSON.stringify(t.trigger.config,null,2)})]}),s.jsx("dt",{children:"Context"}),s.jsx("dd",{"data-def":"context",children:Pv(t.context.mode)}),s.jsx("dt",{children:"Tools"}),s.jsx("dd",{"data-def":"tool_approval",children:l==="ask"?"Ask before each tool call (ask)":l==="auto"?"Run without asking (auto)":String(l)}),s.jsx("dt",{children:"Notify"}),s.jsx("dd",{"data-def":"notify",children:lS(t.notify)}),s.jsx("dt",{children:"May email"}),s.jsx("dd",{"data-def":"email_allowed_recipients",children:aS(t.policy.email_allowed_recipients)}),s.jsx("dt",{children:"Retries"}),s.jsxs("dd",{"data-def":"retry",children:[o.max_attempts," ",o.max_attempts===1?"attempt":"attempts",", backoff ",o.backoff.initial," ×",o.backoff.factor," up to ",o.backoff.max]}),s.jsx("dt",{children:"Revision"}),s.jsx("dd",{"data-def":"revision",children:t.revision})]})]})}const Hf=Lv,yl=Hf.labels,no={pause:"pause",resume:"play",run_now:Hf.icons.run_now.name,stop_current:"stop",revise:"edit",archive:"archive",discuss:"chat"},Dp=Hf.hints,RS=Hf.run_now_next_run_line,LS=Hf.run_now_growing_line;function Qv(e,t){const n=[Dp[e]];return e==="run_now"&&t&&(t.next_fire_at&&n.push(RS.replace("{time}",va(t.next_fire_at))),t.context_mode==="growing"&&n.push(LS)),n.join(`
|
|
52
|
-
`)}function IS(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 _=`${n}-why-${f}`;o.push({id:_,text:`${c.map(p=>yl[p]).join(", ")}: ${u}`});for(const p of c)l[p]=_}),{lines:o,describedBy:l}}function ur(e){return s.jsxs(s.Fragment,{children:[s.jsx(Ze,{name:e.icon,size:14,className:"af-auto__btn-icon"}),s.jsx("span",{children:e.label})]})}function OS(e){const t=Nm(e.summary,e.occurrences,e.busy),n=[e.summary.status==="paused"?"resume":"pause","run_now","stop_current","revise","archive"],r=IS(t,n,e.idBase??`af-auto-${e.summary.automation_id}`),o=(l,u,c)=>{const f=Qv(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}
|
|
53
|
-
${f}`,"aria-description":f,"aria-describedby":r.describedBy[l],"aria-pressed":c==null?void 0:c.pressed,onClick:u,children:s.jsx(ur,{icon:no[l],label:(c==null?void 0:c.label)??yl[l]})},l)};return s.jsxs("div",{className:"af-auto__controls-wrap",children:[s.jsxs("div",{className:"af-auto__actionbar",children:[s.jsxs("div",{className:"af-auto__controls",role:"toolbar","aria-label":"Automation controls",children:[e.summary.status==="paused"?o("resume",()=>e.onCommand(Fo.resume)):o("pause",()=>e.onCommand(Fo.pause)),o("run_now",()=>e.onCommand(Fo.run_now)),o("stop_current",()=>e.onCommand(Fo.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(Ze,{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(Ze,{name:"x",size:12})}):null]}):null})]}),r.lines.length?s.jsxs("p",{className:"af-auto__reasons",children:[s.jsx(Ze,{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(Fo.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 Cy=[["m","minutes"],["h","hours"],["d","days"]];function PS(e,t){const n=E=>{const A=e.elements.namedItem(E);return A&&typeof A.value=="string"?A.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"),_=e.elements.namedItem("tool_approval"),p=_&&(_.value==="auto"||_.value==="ask")?_.value:t.toolApproval??null,y=e.elements.namedItem("notify_email"),w=y&&typeof y.checked=="boolean"?y.checked:t.notifyEmail??null,x=e.elements.namedItem("email_recipients"),k=n("email_recipient_list"),j=x&&(x.value==="self"||x.value==="list")?{mode:x.value,addresses:k??""}:t.emailRecipients??null;return{title:n("title")??t.title,every:l,context:c,prompt:f??t.prompt??null,toolApproval:p,notifyEmail:w,emailRecipients:j}}function DS(e){const t=Jv(e.summary,e.definition),n=t.every?qf(t.every):null,r=n&&n.unit==="s"?[["s","seconds"],...Cy]:Cy,o=`af-auto-revise-${e.summary.automation_id}`,l=Ym(e.emailStatus),u=Km(e.summary.trigger);return s.jsxs("form",{className:"af-auto__revise","aria-labelledby":`${o}-heading`,onSubmit:c=>{c.preventDefault(),e.onSubmit(PS(c.currentTarget,t))},onKeyDown:c=>{c.key==="Escape"&&(c.preventDefault(),e.onCancel())},children:[s.jsxs("h3",{className:"af-auto__form-title",id:`${o}-heading`,children:[s.jsx(Ze,{name:"edit",size:14})," Edit automation"]}),s.jsxs("label",{className:"af-auto__field",htmlFor:`${o}-title`,children:[s.jsx("span",{children:"Title"}),s.jsx("input",{id:`${o}-title`,name:"title",defaultValue:t.title,maxLength:120,required:!0})]}),t.prompt!==null&&t.prompt!==void 0?s.jsxs("label",{className:"af-auto__field",htmlFor:`${o}-prompt`,children:[s.jsx("span",{children:"Task"}),s.jsx("textarea",{id:`${o}-prompt`,name:"prompt",defaultValue:t.prompt,rows:Math.min(10,Math.max(3,t.prompt.split(`
|
|
54
|
-
`).length+1)),required:!0})]}):null,n?s.jsxs("fieldset",{className:"af-auto__field",children:[s.jsx("legend",{children:u?Ht.every_label:"Repeat every (UTC)"}),s.jsxs("div",{className:"af-auto__row",children:[s.jsx("input",{name:"every_amount",type:"number",min:1,step:1,defaultValue:n.amount,"aria-label":"Interval amount"}),s.jsx("select",{name:"every_unit",defaultValue:n.unit,"aria-label":"Interval unit",children:r.map(([c,f])=>s.jsx("option",{value:c,children:f},c))})]}),u?s.jsx("p",{className:"af-auto__hint","data-email-rule":"interval",children:Ht.interval_rule}):null]}):s.jsx("p",{className:"af-auto__hint",children:"This trigger has no interval to change."}),s.jsxs("fieldset",{className:"af-auto__field",children:[s.jsx("legend",{children:"Context"}),s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:"context",value:"independent",defaultChecked:t.context==="independent"})," Independent — each run starts fresh"]}),s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:"context",value:"growing",defaultChecked:t.context==="growing"})," Growing — each run sees the previous runs"]})]}),t.toolApproval?s.jsxs("fieldset",{className:"af-auto__field",children:[s.jsx("legend",{children:"Tools"}),s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:"tool_approval",value:"auto",defaultChecked:t.toolApproval==="auto"})," Run without asking"]}),s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:"tool_approval",value:"ask",defaultChecked:t.toolApproval==="ask"})," Ask before each tool call"]})]}):null,t.notifyEmail!==null&&t.notifyEmail!==void 0&&t.emailRecipients?s.jsxs("fieldset",{className:"af-auto__field","data-field":"email",children:[s.jsx("legend",{children:"Email"}),l?null:s.jsx(Op,{status:e.emailStatus,onOpenMyEmail:e.onOpenMyEmail}),s.jsxs("label",{className:"af-email__check",children:[s.jsx("input",{type:"checkbox",name:"notify_email",defaultChecked:t.notifyEmail,disabled:!l&&!t.notifyEmail})," ",Ht.notify_label]}),s.jsx("p",{className:"af-auto__hint",children:Ht.notify_hint}),s.jsxs("fieldset",{className:"af-auto__field","data-field":"email-recipients",children:[s.jsx("legend",{children:Ht.recipients_legend}),s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:"email_recipients",value:"self",defaultChecked:t.emailRecipients.mode==="self"})," ",Ht.recipients_self]}),s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:"email_recipients",value:"list",defaultChecked:t.emailRecipients.mode==="list",disabled:!l&&t.emailRecipients.mode!=="list"})," ",Ht.recipients_list]}),s.jsx("textarea",{name:"email_recipient_list","aria-label":Ht.recipients_list,rows:2,spellCheck:!1,defaultValue:t.emailRecipients.addresses,disabled:!l&&t.emailRecipients.mode!=="list"}),s.jsx("p",{className:"af-auto__hint",children:Ht.recipients_hint})]})]}):null,s.jsx("p",{className:"af-auto__hint",children:"Changes apply from the next run; a new interval never fires past ticks."}),e.errors.length?s.jsx("ul",{className:"af-auto__form-errors",role:"alert",children:e.errors.map(c=>s.jsx("li",{children:c},c))}):null,s.jsxs("div",{className:"af-auto__row",children:[s.jsx("button",{type:"submit",className:"af-auto__btn af-auto__btn--primary","data-action":"edit-save",disabled:e.busy,children:s.jsx(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 Fp(e,t){const n=e.elements.namedItem(t);return n&&typeof n.value=="string"?n.value.trim():""}function FS(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??Jm,l=u=>s.jsxs("div",{className:"af-auto-wait__prompt",id:n,children:[s.jsx("span",{className:"af-auto-wait__kind",children:Xv[t.kind]??"Waiting"}),t.prompt?o(t.prompt):s.jsxs("span",{children:[" ",u]})]});if(t.kind==="tool_approval"){const u=vS(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=xS(Fp(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=Fp(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 zS(e){const{row:t,tone:n,badge:r,statusText:o}=e.view,l=`af-auto-occ-${t.run_id}`,u=e.renderText??Jm,c=e.discuss.enabled&&e.view.canDiscuss&&!e.busy,f=e.discuss.enabled?e.view.canDiscuss?null:"Available once this occurrence finishes.":e.discuss.reason??"Not available.",_=(w,x)=>e.renderTurn?e.renderTurn({kind:w,role:w==="trigger"?"user":"assistant",text:x,index:t.index,runId:t.run_id}):u(x),p=e.renderTurn?" af-auto-turn--card":"",y=n==="failed"?t.failure?"No answer.":"No answer: the run failed.":n==="waiting"?"Waiting for your answer.":n==="running"?"Running…":"No answer.";return s.jsxs("li",{className:`af-auto-occ af-auto-occ--${n}`,"data-index":t.index,"data-tone":n,"aria-labelledby":`${l}-h`,children:[s.jsxs("div",{className:`af-auto-turn af-auto-turn--trigger${p}`,"data-turn":"trigger",children:[s.jsxs("div",{className:"af-auto-turn__meta",id:`${l}-h`,children:[s.jsxs("span",{className:"af-auto-turn__index",children:["#",t.index]})," · ",t.trigger.summary," · fired ",va(t.fired_at)]}),s.jsx("div",{className:"af-auto-turn__text",children:_("trigger",t.user_turn)})]}),s.jsxs("div",{className:`af-auto-turn af-auto-turn--answer${p}`,"data-turn":"answer",children:[s.jsxs("div",{className:"af-auto-turn__meta",children:[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:[" · ",va(t.finished_at)]}):null]}),t.notify?s.jsxs("div",{className:"af-auto-notify","data-notify":"true",children:[s.jsx("strong",{children:t.notify.title}),t.notify.body?s.jsx("div",{className:"af-auto-notify__body",children:u(t.notify.body)}):null]}):null,t.failure?s.jsxs("div",{className:"af-auto-failure","data-failure":t.failure.reason_code,children:[s.jsx("strong",{children:t.failure.reason_code}),": ",t.failure.message," ",s.jsxs("span",{className:"af-auto-turn__muted",children:["(after ",t.failure.attempts," ",t.failure.attempts===1?"attempt":"attempts",")"]})]}):null,t.answer?s.jsx("div",{className:"af-auto-turn__text",children:_("answer",t.answer)}):s.jsx("div",{className:"af-auto-turn__empty",children:y}),t.artifacts.length?s.jsx("ul",{className:"af-auto-artifacts","aria-label":"Artifacts",children:t.artifacts.map(w=>s.jsxs("li",{children:[e.onOpenResource?s.jsxs("button",{type:"button",className:"af-auto__linkbtn","data-action":"open-artifact",onClick:()=>{var x;return(x=e.onOpenResource)==null?void 0:x.call(e,{kind:"artifact",url:w.url,name:w.name,mimeType:w.mime_type,runId:t.run_id})},children:[s.jsx(Ze,{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(FS,{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":`${Pp}, from occurrence ${t.index}`,onSubmit:w=>{w.preventDefault();const x=Fp(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:Dp.discuss,"aria-description":Dp.discuss,"aria-describedby":f?`${l}-discuss-why`:void 0,onClick:()=>e.onDiscussOpen(t.index),children:s.jsx(ur,{icon:no.discuss,label:Pp})}),f?s.jsx("span",{className:"af-auto__reasons",id:`${l}-discuss-why`,children:f}):null]})]})]})}const BS=5e3,US={[Fo.pause]:"Pause sent.",[Fo.resume]:"Resume sent.",[Fo.run_now]:"Run requested.",[Fo.stop_current]:"Stop sent."};function WS(e){const{summary:t,busy:n}=e,r=e.renderText??Jm,o=m.useId(),l=m.useRef(null),[u,c]=m.useState(!1),f=e.editOpen!==void 0,p=Nm(t,e.occurrences,!1).revise.enabled&&(f?e.editOpen===!0:u),y=m.useRef(null);p?(!y.current||y.current.summary.automation_id!==t.automation_id)&&(y.current={summary:t,definition:e.definition}):y.current=null;const w=y.current,x=m.useRef(e.onEditOpenChange);x.current=e.onEditOpenChange;const k=J=>{var oe;f||c(J),(oe=x.current)==null||oe.call(x,J)},[j,E]=m.useState([]),[A,L]=m.useState(!1),[O,M]=m.useState(null),[H,X]=m.useState(null),[Y,Z]=m.useState(null);m.useEffect(()=>{if(!Y)return;const J=setTimeout(()=>Z(null),BS);return()=>clearTimeout(J)},[Y]),m.useEffect(()=>{var oe;if(!p)return;E([]);const J=ky(l.current,['.af-auto__revise [name="title"]']);J==null||J.focus(),(oe=J==null?void 0:J.scrollIntoView)==null||oe.call(J,{block:"nearest"})},[p,t.automation_id]);const[re,ie]=m.useState(null);m.useEffect(()=>{var J;re&&((J=ky(l.current,[...re,".af-auto__notice",".af-auto__title"]))==null||J.focus(),ie(null))},[re]);const ue=m.useRef(null);ue.current||(ue.current=new bS(e.newId??SS));const F=ue.current,C=J=>X($S(J)),N=(J,oe,he)=>{X(null),Z(null),oe(F.idFor(J)).then(_e=>{F.settle(J,{ok:!0}),he(_e)},_e=>{F.settle(J,{ok:!1,error:_e}),C(_e)})},P=hS(t),D=m.useRef(e.onSeen);D.current=e.onSeen;const ne=m.useRef(null);ne.current||(ne.current=new kS),m.useEffect(()=>{const J=ne.current,oe=P?`${t.automation_id}|${P}`:null;if(!P||!J.next(oe,t))return;const he=t;D.current(P).then(()=>J.succeeded(oe),_e=>{J.failed(oe,he),C(_e)})});const B=Nm(t,e.occurrences,n),z=fS(e.occurrences),G=t.occurrence_count-e.occurrences.length,T=H??e.error??null,Q=T?Cm(T):null,K=t.attention;return s.jsxs("section",{ref:l,className:`af-auto${e.className?` ${e.className}`:""}`,"aria-labelledby":o,"aria-busy":n,"data-text-rendering":e.renderText?"rich":"unformatted",children:[s.jsx(TS,{summary:t,triggerSources:e.triggerSources,titleId:o,nowMs:e.nowMs,onOpenWorkspace:e.onOpenWorkspace}),s.jsx(OS,{summary:t,occurrences:e.occurrences,busy:n,confirmingArchive:A,reviseOpen:p,notice:Y,onDismissNotice:()=>Z(null),idBase:`${o}-ctl`,onCommand:J=>N(`command:${J}`,oe=>e.onCommand(J,void 0,{command_id:oe}),()=>{J===Fo.archive?(L(!1),Z("Archive requested."),ie(['[data-action="archive"]'])):Z(US[J]??"Command sent.")}),onToggleRevise:()=>{E([]),k(!p)},onAskArchive:()=>L(!0),onCancelArchive:()=>{L(!1),ie(['[data-action="archive"]'])}}),p&&w?s.jsx(DS,{summary:w.summary,definition:w.definition,busy:n,errors:j,emailStatus:e.emailStatus,onOpenMyEmail:e.onOpenMyEmail,onCancel:()=>{k(!1),ie(['[data-action="edit"]'])},onSubmit:J=>{const oe=w.summary,he=_S(oe,J,w.definition);if(he===null){E(["Nothing changed."]);return}if("errors"in he){E(he.errors);return}E([]),N(`revise:${oe.revision}:${JSON.stringify(he)}`,_e=>e.onRevise(he,oe.revision,{command_id:_e}),()=>{Z("Saved; applies from the next run."),k(!1),ie(['[data-action="edit"]'])})}}):e.definition?s.jsx(MS,{definition:e.definition,renderText:r}):null,Q?s.jsxs("div",{className:"af-auto__error",role:"alert","data-code":T==null?void 0:T.code,children:[s.jsx(Ze,{name:"error",size:14,className:"af-auto__btn-icon"}),s.jsxs("span",{className:"af-auto__error-text",children:[s.jsx("strong",{children:Q.title})," ",s.jsx("span",{children:Q.detail})]}),H?s.jsx("button",{type:"button",className:"af-auto__icon-btn af-auto__icon-btn--bare","data-action":"dismiss-error","aria-label":"Dismiss",title:"Dismiss",onClick:()=>X(null),children:s.jsx(Ze,{name:"x",size:12})}):null]}):null,K.items.length||K.waits.length?s.jsx("section",{className:"af-auto__attention","aria-label":"Needs attention",children:s.jsxs("ul",{children:[K.items.map(J=>s.jsxs("li",{className:`af-auto__attention-item af-auto__attention-item--${J.kind}`,"data-cursor":J.cursor,children:[s.jsx("span",{className:`af-auto-badge af-auto-badge--${J.kind==="failure"?"failed":"notified"}`,children:J.kind==="failure"?"Failed":"Notified"})," ",s.jsx("strong",{children:J.title})," ",s.jsxs("span",{className:"af-auto-turn__muted",children:["#",J.index," · ",va(J.at)]}),J.body?s.jsx("div",{className:"af-auto__attention-body",children:r(J.body)}):null]},J.cursor)),K.waits.map(J=>s.jsxs("li",{className:"af-auto__attention-item af-auto__attention-item--wait",children:[s.jsx("span",{className:"af-auto-badge af-auto-badge--waiting","data-wait-kind":J.kind,children:Xv[J.kind]??"Waiting for you"})," ",s.jsxs("span",{className:"af-auto-turn__muted",children:["#",J.index]}),J.prompt?s.jsx("div",{className:"af-auto__attention-body",children:r(J.prompt)}):null]},`${J.run_id}:${J.wait_key}`))]})}):null,G>0?s.jsx("button",{type:"button",className:"af-auto__btn af-auto__more","data-action":"load-more",disabled:n,onClick:e.onLoadMore,children:s.jsx(ur,{icon:"history",label:`Load earlier occurrences (${G} more)`})}):null,z.length?s.jsx("ol",{className:"af-auto__timeline","aria-label":"Occurrences",children:z.map(J=>{const oe=`[data-index="${J.row.index}"]`;return s.jsx(zS,{view:J,busy:n,discuss:B.discuss,renderText:r,renderTurn:e.renderTurn,onOpenWorkspace:e.onOpenWorkspace,onOpenResource:e.onOpenResource?he=>{var _e;X(null);try{Promise.resolve((_e=e.onOpenResource)==null?void 0:_e.call(e,he)).catch(C)}catch(we){C(we)}}:void 0,discussOpen:O===J.row.index,onOpenRun:e.onOpenRun,onAnswerWait:(he,_e,we)=>{X(null),e.onAnswerWait(he,_e,we).then(()=>Z("Answer sent."),C)},onWaitError:he=>X({status:0,code:"invalid_payload",message:he}),onDiscussOpen:M,onDiscussCancel:()=>{M(null),ie([`${oe} [data-action="discuss"]`])},onDiscussSubmit:(he,_e)=>N(`discuss:${he}:${_e}`,we=>e.onDiscuss(he,_e,{request_id:we}),we=>{M(null),Z(`Discussion started (session ${we.session_id}).`),ie([`${oe} [data-action="discuss"]`])})},J.row.run_id)})}):s.jsx("p",{className:"af-auto__empty",children:"No occurrences yet."})]})}async function ex(e){const t=String(e||"");if(!t)return!1;try{return await navigator.clipboard.writeText(t),!0}catch{try{const n=document.createElement("textarea");return n.value=t,n.style.position="fixed",n.style.left="-9999px",document.body.appendChild(n),n.select(),document.execCommand("copy"),document.body.removeChild(n),!0}catch{return!1}}}const qS=3,HS=Number.MAX_SAFE_INTEGER;function tx(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function nx(e){return Array.isArray(e)}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 GS(e){if(e==null)return"";if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}}function Eu({kind:e,children:t}){return s.jsx("span",{className:`json-token ${e}`,children:t})}function KS(e){const t=JSON.stringify(e.value),n=t.length>96||t.includes("\\n")||t.includes("\\r")||t.includes("\\t"),[r,o]=m.useState(!n||e.expansion_mode==="unfolded");return m.useEffect(()=>{n&&o(e.expansion_mode==="unfolded")},[n,e.expansion_mode,e.expansion_version]),n?s.jsxs("span",{className:`json-string ${r?"open":"collapsed"}`,children:[s.jsx("button",{type:"button",className:"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:"json-token string json-string__value",children:t}):s.jsxs("button",{type:"button",className:"json-string__preview",onClick:()=>o(!0),"aria-label":"Expand string value",children:[s.jsx("span",{className:"json-token string json-string__preview_text",children:t}),s.jsx("span",{className:"json-string__suffix",children:"(...)"})]})]}):s.jsx(Eu,{kind:"string",children:t})}function YS(e,t,n){return e===null?s.jsx(Eu,{kind:"null",children:"null"}):typeof e=="string"?s.jsx(KS,{value:e,expansion_mode:t,expansion_version:n}):typeof e=="number"?s.jsx(Eu,{kind:"number",children:String(e)}):typeof e=="boolean"?s.jsx(Eu,{kind:"boolean",children:e?"true":"false"}):s.jsx(Eu,{kind:"string",children:JSON.stringify(String(e))})}function JS(e){return nx(e)?e.length===1?"1 item":`${e.length} items`:tx(e)?Object.keys(e).length===1?"1 key":`${Object.keys(e).length} keys`:""}function sx(e){const{label:t,value:n,depth:r,collapse_after_depth:o,expansion_mode:l,expansion_version:u,trailing_comma:c}=e,f=r*14,_=tx(n),p=nx(n),y=_||p,w=r<o,[x,k]=m.useState(w);m.useEffect(()=>{k(w)},[w,u]);const j=t?s.jsxs(s.Fragment,{children:[s.jsx(Eu,{kind:"key",children:JSON.stringify(t)}),": "]}):null;if(!y)return s.jsxs("div",{className:"json-viewer__line",style:{paddingLeft:f},children:[j,YS(n,l,u),c?",":""]});const E=p?"[":"{",A=p?"]":"}",L=JS(n),O=x?`${E}`:`${E}…${A}${L?` (${L})`:""}`,M=p?n.map((H,X)=>({key:String(X),label:void 0,value:H})):Object.entries(n).map(([H,X])=>({key:H,label:H,value:X}));return s.jsxs("details",{className:"json-viewer__details",open:x,onToggle:H=>k(H.currentTarget.open),children:[s.jsxs("summary",{className:"json-viewer__summary",style:{paddingLeft:f},children:[j,s.jsx("span",{className:"json-viewer__caret","aria-hidden":"true",children:x?"▾":"▸"}),s.jsx("span",{className:"json-viewer__punct",children:O}),!x&&c?s.jsx("span",{className:"json-viewer__punct",children:","}):null]}),x?s.jsx("div",{className:"json-viewer__children",children:M.length===0?s.jsxs("div",{className:"json-viewer__line",style:{paddingLeft:f},children:[s.jsx("span",{className:"json-viewer__punct",children:A}),c?",":""]}):s.jsxs(s.Fragment,{children:[M.map((H,X)=>{const Y=X===M.length-1;return s.jsx(sx,{label:H.label,value:H.value,depth:r+1,collapse_after_depth:o,expansion_mode:l,expansion_version:u,trailing_comma:!Y},`${r}:${t||"root"}:${H.key}`)}),s.jsxs("div",{className:"json-viewer__line",style:{paddingLeft:f},children:[s.jsx("span",{className:"json-viewer__punct",children:A}),c?",":""]})]})}):null]})}function rx(e){const{value:t,className:n,showCopy:r=!0}=e,[o,l]=m.useState({mode:"folded",version:0}),u=typeof e.collapseAfterDepth=="number"&&(Number.isFinite(e.collapseAfterDepth)||e.collapseAfterDepth===1/0)&&e.collapseAfterDepth>=0?e.collapseAfterDepth===1/0?Number.MAX_SAFE_INTEGER:Math.trunc(e.collapseAfterDepth):qS,c=o.mode==="unfolded"?HS:u,f=m.useMemo(()=>typeof t=="string"?VS(t):t,[t]),_=m.useMemo(()=>GS(t),[t]),p=["json-viewer",n].filter(Boolean).join(" ");m.useEffect(()=>{l(w=>({mode:"folded",version:w.version+1}))},[f]);const y=()=>{l(w=>({mode:w.mode==="unfolded"?"folded":"unfolded",version:w.version+1}))};return s.jsxs("div",{className:p,children:[s.jsxs("div",{className:"json-viewer__toolbar",children:[s.jsx("button",{type:"button",className:"json-viewer__btn json-viewer__toggle-all",onClick:y,"aria-expanded":o.mode==="unfolded",children:o.mode==="unfolded"?"Fold all":"Unfold all"}),r?s.jsx("button",{type:"button",className:"json-viewer__btn json-viewer__copy",onClick:()=>void ex(_),children:"Copy"}):null]}),s.jsx("div",{className:"json-viewer__tree",role:"tree","aria-label":"JSON viewer",children:s.jsx(sx,{value:f,depth:0,collapse_after_depth:c,expansion_mode:o.mode,expansion_version:o.version,trailing_comma:!1})})]})}function B_(e){const t=[],n=String(e??"");let r=0,o="";const l=()=>{o&&(t.push(o),o="")};for(;r<n.length;){const u=n[r];if(u==="`"){const c=n.indexOf("`",r+1);if(c!==-1){l(),t.push(s.jsx("code",{children:n.slice(r+1,c)},`code:${r}`)),r=c+1;continue}}if(u==="*"&&n[r+1]==="*"){const c=n.indexOf("**",r+2);if(c!==-1){l(),t.push(s.jsx("strong",{children:n.slice(r+2,c)},`bold:${r}`)),r=c+2;continue}}o+=u,r+=1}return l(),t}function XS(e){return String(e??"").replace(/\r\n/g,`
|
|
55
|
-
`).replace(/\r/g,`
|
|
56
|
-
`).split(`
|
|
57
|
-
`)}function ZS({text:e,className:t}){const n=XS(e),r=[];let o=0;for(;o<n.length;){const u=n[o],c=String(u??"");if(!c.trim()){o+=1;continue}if(c.trim().startsWith("```")){const w=c.trim().replace(/```/g,"").trim(),x=[];for(o+=1;o<n.length&&!String(n[o]??"").trim().startsWith("```");)x.push(String(n[o]??"")),o+=1;o<n.length&&(o+=1);const k=x.join(`
|
|
58
|
-
`);r.push(s.jsx("pre",{className:"mf-md_pre",children:s.jsx("code",{className:w?`language-${w}`:void 0,children:k})},`pre:${o}`));continue}const f=c.match(/^(#{1,3})\s+(.*)$/);if(f){const y=f[1].length,w=f[2]||"",x=B_(w);y===1?r.push(s.jsx("h1",{children:x},`h1:${o}`)):y===2?r.push(s.jsx("h2",{children:x},`h2:${o}`)):r.push(s.jsx("h3",{children:x},`h3:${o}`)),o+=1;continue}const _=y=>{const w=y.trimStart();return w.startsWith("- ")||w.startsWith("* ")};if(_(c)){const y=[];for(;o<n.length&&_(String(n[o]??""));){const w=String(n[o]??"").trimStart();y.push(w.slice(2)),o+=1}r.push(s.jsx("ul",{className:"mf-md_ul",children:y.map((w,x)=>s.jsx("li",{children:B_(w)},`li:${o}:${x}`))},`ul:${o}`));continue}const p=[];for(;o<n.length&&String(n[o]??"").trim();)p.push(String(n[o]??"")),o+=1;r.push(s.jsx("p",{className:"mf-md_p",children:p.map((y,w)=>s.jsxs(ve.Fragment,{children:[B_(y),w<p.length-1?s.jsx("br",{}):null]},`pl:${o}:${w}`))},`p:${o}`))}const l=["mf-md",t].filter(Boolean).join(" ");return s.jsx("div",{className:l,children:r})}const Ey="observe";function Ar(e){return!e||typeof e!="object"?null:e}function zp(e,t){const n=String(e||"").replace(/\s+/g," ").trim();return n?n.length<=t?n:`${n.slice(0,Math.max(0,t-1)).trimEnd()}…`:""}function $y(e){const t=Ar(e);if(!t)return null;const n=typeof t.role=="string"?String(t.role).trim():"",r=typeof t.content=="string"?String(t.content):"";if(!n||r==="")return null;const o=typeof t.name=="string"?String(t.name).trim():"";return{role:n,content:r,name:o||void 0}}function QS(e){if(Array.isArray(e)){if(e.length===0)return null;const n=[];for(const r of e){const o=$y(r);if(!o)return null;n.push(o)}return n}const t=$y(e);return t?[t]:null}function ek(e){const t=String(e||"").trim();if(!t)return null;const n=t[0],r=t[t.length-1];if(!(n==="{"&&r==="}"||n==="["&&r==="]"))return null;try{const l=JSON.parse(t);return l&&typeof l=="object"||Array.isArray(l)?l:null}catch{return null}}function tk(e){const t=String(e||"");return t.trim()?!!(t.includes("```")||/\n\s*#{1,3}\s+/.test(t)||/\n\s*[-*]\s+/.test(t)||/\n\s*\d+[\.\)]\s+/.test(t)||t.includes("**")||t.includes("`")):!1}function Ay({text:e}){const t=String(e||""),n=ek(t);if(n!==null)return s.jsx(rx,{value:n});const r=t.trim();return r.startsWith("{")||r.startsWith("[")?s.jsx("pre",{className:"run-details-output",children:t||"(none)"}):t.includes(`
|
|
59
|
-
`)||tk(t)?s.jsx("div",{className:"run-details-output",children:s.jsx(ZS,{text:t})}):s.jsx("pre",{className:"run-details-output",children:t||"(none)"})}function ix({value:e}){if(e==null)return s.jsx("pre",{className:"run-details-output",children:"(none)"});const t=QS(e);return t?s.jsx("div",{className:"mf-msg-list",children:t.map((n,r)=>s.jsxs("div",{className:"mf-msg",children:[s.jsxs("div",{className:"mf-msg-meta",children:[s.jsx("span",{className:`mf-msg-role ${n.role}`,children:n.role}),n.name?s.jsx("span",{className:"mf-msg-name",children:n.name}):null]}),s.jsx("div",{className:"mf-msg-content",children:s.jsx(Ay,{text:n.content})})]},`${n.role}:${r}`))}):typeof e=="string"?s.jsx(Ay,{text:e}):s.jsx(rx,{value:e})}function ox(e){const t=e.effect;return!t||typeof t!="object"?null:t}function kl(e){const t=ox(e);return(t&&typeof t.type=="string"?t.type:"")||"effect"}function Xm(e){const t=ox(e),n=t==null?void 0:t.payload;return!n||typeof n!="object"?null:n}function Ng(e){const t=e.result;return!t||typeof t!="object"?null:t}function ax(e){if(kl(e)!=="tool_calls")return[];const n=Ng(e),r=n&&Array.isArray(n.results)?n.results:null;if(!r)return[];const o=[];for(const l of r){const u=Ar(l);if(!u)continue;const c=typeof u.name=="string"?u.name.trim():"";c&&o.push({call_id:typeof u.call_id=="string"?u.call_id:void 0,name:c,success:!!u.success,output:u.output,error:u.error})}return o}function lx(e){if(kl(e)!=="tool_calls")return[];const n=Xm(e),r=n&&Array.isArray(n.tool_calls)?n.tool_calls:null;if(!r)return[];const o=[];for(const l of r){const u=Ar(l);if(!u)continue;const c=typeof u.name=="string"?u.name.trim():"";if(!c)continue;const f=Ar(u.args)||Ar(u.arguments)||{};o.push({call_id:typeof u.call_id=="string"?u.call_id:void 0,name:c,args:f})}return o}function Zm(e){const t=e.error;if(typeof t=="string")return t.trim();const n=Ar(t);if(n){const r=typeof n.message=="string"?n.message.trim():"",o=typeof n.stack=="string"?n.stack.trim():"";return r||o||""}return""}function cx(e){if(!e)return"";const t=e.reasoning;if(typeof t=="string")return t.trim();const n=Ar(t);return n&&typeof n.text=="string"?n.text.trim():""}function ux(e){const t=kl(e),n=Xm(e),r=Ng(e),o=(l,u)=>{const c=String(l||"").replace(/\s+/g," ").trim();return c?c.length<=u?c:`${c.slice(0,Math.max(0,u-1)).trimEnd()}…`:""};if(t==="llm_call"){const l=r==null?void 0:r.content,u=typeof l=="string"?l.replace(/\s+/g," ").trim():"",c=cx(r),f=Array.isArray(r==null?void 0:r.tool_calls)?r.tool_calls:null,p=!!(f&&f.length>0)?c||u:u||c;return o(p,220)}if(t==="tool_calls"){const l=r&&Array.isArray(r.results)?r.results:null;if(!l)return"";const u=l.filter(c=>{var f;return((f=Ar(c))==null?void 0:f.success)===!1});return u.length>0?`${u.length} tool call(s) failed`:`${l.length} tool call(s) executed`}return t==="ask_user"&&n&&typeof n.prompt=="string"?String(n.prompt).trim():""}function Em(e){const t=typeof e.status=="string"?e.status:"unknown";return t==="failed"||Zm(e.step)?"failed":t}function nk(e){const t=e.map(n=>Em(n));return t.some(n=>n==="failed")?"failed":t.some(n=>n==="waiting")?"waiting":t.some(n=>n==="running")?"running":"completed"}function U_(e){return e.filter(t=>!t.hidden)}function sk(e){const t=kl(e),n=Zm(e);return U_(t==="llm_call"?[{id:"system",label:"System"},{id:"user",label:"User"},{id:"tools",label:"Tools"},{id:"response",label:"Response"},{id:"reasoning",label:"Reasoning"},{id:"errors",label:"Errors",hidden:!n},{id:"raw",label:"Raw"}]:t==="tool_calls"?[{id:"tools",label:"Tools"},{id:"errors",label:"Errors",hidden:!n},{id:"raw",label:"Raw"}]:[{id:"errors",label:"Errors",hidden:!n},{id:"raw",label:"Raw"}])}function rk(e){const t=kl(e);return t==="llm_call"?"user":t==="tool_calls"?"tools":Zm(e)?"errors":"raw"}function ik(e){const t=new Map,n=Xm(e),r=n&&Array.isArray(n.tools)?n.tools:null;if(!r)return t;for(const o of r){const l=Ar(o);if(!l)continue;const u=typeof l.name=="string"?l.name.trim():"";if(!u)continue;const f=(Array.isArray(l.parameters)?l.parameters:[]).map(_=>{const p=Ar(_);return(p&&typeof p.id=="string"?p.id.trim():"")||""}).filter(Boolean);t.set(u,f)}return t}function dx(e,t,n){const r=Object.keys(t||{}),o=n&&n.length?n.filter(f=>r.includes(f)):[],l=r.filter(f=>!o.includes(f)).sort(),u=[...o,...l],c=u.slice(0,5).map(f=>{const _=t[f];return typeof _=="string"?`${f}=${JSON.stringify(zp(_,42))}`:typeof _=="number"||typeof _=="boolean"?`${f}=${String(_)}`:_==null?`${f}=null`:`${f}=${zp(JSON.stringify(_),42)}`});return`${e}(${c.join(", ")}${u.length>5?", …":""})`}function ok(e){const t=e.ts?String(e.ts):"";if(!t)return"";try{const n=new Date(t);return Number.isFinite(n.getTime())?n.toLocaleTimeString():""}catch{return""}}function W_({item:e,label:t,toolDefs:n,defaultOpen:r=!1}){const o=e.step,l=kl(o),u=sk(o),c=rk(o),[f,_]=m.useState(c),[p,y]=m.useState(!!r),w=Xm(o),x=Ng(o),k=Zm(o),j=ok(e),E=e.nodeId?String(e.nodeId):"",A=e.runId?String(e.runId):"",L=l==="tool_calls"?lx(o):[],O=l==="tool_calls"?ax(o):[],M=L.map(ie=>dx(ie.name,ie.args,n.get(ie.name)||null)),X=(()=>{if(f==="raw")return o;if(f==="errors")return k||null;if(l==="llm_call"){const ie=w||{},ue=typeof ie.system_prompt=="string"?String(ie.system_prompt):"",F=typeof ie.prompt=="string"?String(ie.prompt):"",C=Ar(x==null?void 0:x.metadata),N=C?Ar(C._runtime_observability):null,P=N?Ar(N.llm_generate_kwargs):null,D=P&&Array.isArray(P.messages)?P.messages:null,ne=C?Ar(C._provider_request):null,B=ne?Ar(ne.payload):null,z=B&&Array.isArray(B.messages)?B.messages:null,G=Array.isArray(ie.messages)?ie.messages:[],T=D||z||G,Q=T.filter(J=>String((J==null?void 0:J.role)||"").trim()==="system"),K=T.filter(J=>String((J==null?void 0:J.role)||"").trim()==="user");if(f==="system"){const J=[],oe=ue.trim(),he=!!oe&&Q.some(_e=>typeof(_e==null?void 0:_e.content)=="string"&&String(_e.content).trim()===oe);return oe&&!he&&J.push({role:"system",name:"system_prompt",content:ue}),J.push(...Q),J}if(f==="user"){const J=[],oe=F.trim(),he=!!oe&&K.some(_e=>typeof(_e==null?void 0:_e.content)=="string"&&String(_e.content).trim()===oe);return oe&&!he&&J.push({role:"user",name:"prompt",content:F}),J.push(...K),J}if(f==="tools")return ie.tools||[];if(f==="response"){const J=x==null?void 0:x.content;if(typeof J=="string"&&J.trim())return J;const oe=x==null?void 0:x.output;if(oe!==void 0)return oe;const he=Array.isArray(x==null?void 0:x.tool_calls)?x.tool_calls:null;return he&&he.length?{tool_calls:he}:x}if(f==="reasoning")return cx(x)||null}return l==="tool_calls"&&f==="tools"?{tool_calls:L,tool_signatures:M,results:O}:o})(),Y=ux(o),Z=Em(e),re=Z==="completed"?"OK":Z==="failed"?"ERROR":Z==="waiting"?"WAITING":Z.toUpperCase();return s.jsxs("details",{className:`agent-trace-entry ${Z}`,open:p,onToggle:ie=>y(ie.currentTarget.open),children:[s.jsxs("summary",{className:"agent-trace-summary",children:[s.jsx("span",{className:`agent-trace-status ${Z}`,children:re}),s.jsx("span",{className:"agent-cycle-stage","data-stage":t,children:t}),s.jsx("span",{className:"agent-trace-kind",children:l}),j?s.jsx("span",{className:"agent-trace-node",children:j}):null,E?s.jsx("span",{className:"agent-trace-node",children:E}):null,A?s.jsx("span",{className:"agent-trace-run",children:A}):null]}),Y?s.jsx("div",{className:"agent-trace-preview",children:Y}):null,s.jsxs("div",{className:"agent-trace-body",children:[s.jsx("div",{className:"agent-trace-tabs",children:u.map(ie=>s.jsx("button",{type:"button",className:`agent-trace-tab ${ie.id===f?"active":""}`,onClick:()=>_(ie.id),children:ie.label},ie.id))}),s.jsx(ix,{value:X})]})]})}function ak({acts:e}){const t=e.flatMap(l=>ax(l.step)),n=t.filter(l=>l.success===!1),r=n.length?`${n.length} error(s)`:t.length?`${t.length} tool result(s)`:"(none)",o=n.length?"failed":"completed";return s.jsxs("details",{className:`agent-trace-entry ${o}`,open:!1,children:[s.jsxs("summary",{className:"agent-trace-summary",children:[s.jsx("span",{className:`agent-trace-status ${o}`,children:n.length?"ERROR":"OK"}),s.jsx("span",{className:"agent-cycle-stage","data-stage":Ey,children:Ey}),s.jsx("span",{className:"agent-trace-kind",children:"OBSERVATIONS"}),s.jsx("span",{className:"agent-trace-preview-inline",children:r})]}),s.jsx("div",{className:"agent-observe-body",children:t.length===0?s.jsx("div",{className:"agent-observe-empty",children:"(no tool results)"}):s.jsx("div",{className:"agent-observe-results",children:t.map((l,u)=>{const c=l.success?"completed":"failed",f=l.success?"OK":"ERROR",_=l.success?l.output:l.error??l.output;return s.jsxs("details",{className:`agent-observe-result ${c}`,open:!1,children:[s.jsxs("summary",{className:"agent-observe-summary",children:[s.jsx("span",{className:`agent-trace-status ${c}`,children:f}),s.jsx("span",{className:"agent-observe-name",children:l.name}),l.call_id?s.jsx("span",{className:"agent-observe-callid",children:l.call_id}):null]}),s.jsx(ix,{value:_})]},`${l.name}:${l.call_id||""}:${u}`)})})})]})}function lk({items:e,subRunId:t,title:n,subtitle:r,onOpenSubRun:o,defaultOpenLatest:l=!0}){const u=m.useMemo(()=>{const y=Array.isArray(e)?e.slice():[];return y.sort((w,x)=>{const k=w.ts?new Date(w.ts).getTime():NaN,j=x.ts?new Date(x.ts).getTime():NaN;return Number.isFinite(k)&&Number.isFinite(j)?k-j:0}),y},[e]),c=m.useMemo(()=>{const y=[];let w=null,x=0;for(const k of u){const j=kl(k.step);if(j==="llm_call"){x+=1,w={id:`cycle:${k.runId}:${x}:${k.ts||""}`,index:x,items:[k],think:k,acts:[],others:[],status:Em(k),ts:k.ts},y.push(w);continue}w||(x+=1,w={id:`cycle:${k.runId}:${x}:${k.ts||""}`,index:x,items:[],think:null,acts:[],others:[],status:Em(k),ts:k.ts},y.push(w)),w.items.push(k),j==="tool_calls"?w.acts.push(k):w.others.push(k),w.status=nk(w.items)}return y},[u]),f=typeof n=="string"&&n.trim()?n.trim():"Agent calls",_=typeof r=="string"&&r.trim()?r.trim():"Live per-effect trace (LLM/tool calls).",p=typeof t=="string"?t.trim():"";return s.jsxs("div",{className:"agent-trace-panel",children:[s.jsxs("div",{className:"agent-trace-header",children:[s.jsx("div",{className:"agent-trace-title",children:f}),s.jsxs("div",{className:"agent-trace-subtitle",children:[_,p?s.jsxs("span",{className:"agent-trace-subrun",children:[" ","sub_run_id: ",p,s.jsx("button",{type:"button",className:"agent-trace-copy",onClick:y=>{y.stopPropagation(),ex(p)},title:`Copy sub_run_id: ${p}`,"aria-label":"Copy sub run id",children:"⧉"}),o?s.jsx("button",{type:"button",className:"agent-trace-open",onClick:y=>{y.stopPropagation(),o()},title:"Open sub-run",children:"Open"}):null]}):null]})]}),u.length===0?s.jsx("div",{className:"agent-trace-empty",children:"No trace entries yet."}):s.jsxs("div",{className:"agent-cycle-list",children:[s.jsxs("div",{className:"agent-cycle-meta",children:[c.length," cycle(s)"]}),c.map(y=>{const w=y.status,x=w==="completed"?"OK":w==="failed"?"ERROR":w==="waiting"?"WAITING":w.toUpperCase(),k=w==="completed"?"✓":w==="failed"?"✗":"",j=k?`${k} ${x}`:x,E=y.think?ux(y.think.step):"",A=y.think?ik(y.think.step):new Map,O=y.acts.flatMap(H=>lx(H.step)).map(H=>dx(H.name,H.args,A.get(H.name)||null)),M=l&&y.index===c.length;return s.jsxs("details",{className:`agent-cycle ${w}`,open:M,children:[s.jsxs("summary",{className:"agent-cycle-summary",children:[s.jsx("span",{className:`agent-trace-status ${w}`,children:j}),s.jsx("span",{className:"agent-cycle-label",children:"cycle"}),s.jsxs("span",{className:"agent-cycle-index",children:["#",y.index]}),O.length?s.jsxs("span",{className:"agent-trace-badges",children:[O.slice(0,3).map(H=>s.jsx("span",{className:"run-metric-badge metric-tool",title:H,children:zp(H,62)},H)),O.length>3?s.jsxs("span",{className:"run-metric-badge metric-tool",children:["+",O.length-3]}):null]}):null,s.jsx("span",{className:"agent-cycle-spacer"}),E?s.jsx("span",{className:"agent-cycle-preview",children:E}):null]}),s.jsxs("div",{className:"agent-cycle-body",children:[y.think?s.jsx(W_,{item:y.think,label:"think",toolDefs:A,defaultOpen:M}):null,y.acts.map(H=>s.jsx(W_,{item:H,label:"act",toolDefs:A},H.id)),s.jsx(ak,{acts:y.acts}),y.others.length?s.jsxs("div",{className:"agent-cycle-others",children:[s.jsx("div",{className:"agent-cycle-others-title",children:"other"}),y.others.map(H=>{const X=M&&kl(H.step)==="answer_user";return s.jsx(W_,{item:H,label:"other",toolDefs:A,defaultOpen:X},H.id)})]}):null]})]},y.id)})]})]})}function io(e){return typeof e=="string"?e.trim():""}function ck(e){var t;return io(e.run_id)||io((t=e.record)==null?void 0:t.run_id)}function Bp(e){return io(e==null?void 0:e.node_id)}const uk=new Set(["reason","act","observe","thought","think"]);function Up(e){const t=io(e);if(!t.includes("::"))return t;const n=t.split("::");if(n.length<2)return t;const r=String(n[n.length-1]||"").trim().toLowerCase();return uk.has(r)?n.slice(0,-1).join("::"):t}function fx(e){var t;return io((t=e==null?void 0:e.effect)==null?void 0:t.type)}function dk(e){return io(e==null?void 0:e.status)||"unknown"}function Ty(e){return io(e==null?void 0:e.step_id)}function fk(e){return io(e==null?void 0:e.ended_at)||io(e==null?void 0:e.started_at)}function hk(e){const t=new Map,n=new Map;for(const o of e){const l=Up(Bp(o));if(!l)continue;const u=fx(o);u==="llm_call"?t.set(l,(t.get(l)||0)+1):u==="tool_calls"&&n.set(l,(n.get(l)||0)+1)}const r=o=>{let l="",u=-1;for(const[c,f]of o)f>u&&(l=c,u=f);return l};return r(t)||r(n)||""}function mk(e,t){const n=io(t.run_id);if(!n)return{run_id:"",node_id:"",items:[]};const r=(Array.isArray(e)?e:[]).filter(x=>x&&x.record&&ck(x)===n).map(x=>({cursor:x.cursor,record:x.record})).sort((x,k)=>(x.cursor||0)-(k.cursor||0)),o=r.map(x=>x.record),l=Up(io(t.node_id)),u=l||hk(o),c=new Set(["llm_call","tool_calls","ask_user","answer_user"]);let f=r.filter(x=>c.has(fx(x.record)));l&&(f=f.filter(x=>Up(Bp(x.record))===l));const _=new Map,p=[];for(const x of f){const k=Ty(x.record);if(!k){p.push(x);continue}const j=_.get(k);(!j||(x.cursor||0)>(j.cursor||0))&&_.set(k,x)}const w=[...p,...Array.from(_.values())].sort((x,k)=>(x.cursor||0)-(k.cursor||0)).map(x=>{const k=x.record,j=Bp(k)||"(node?)",E=fk(k),A=Ty(k);return{id:`ledger:${n}:${x.cursor}:${A||""}`,runId:n,nodeId:j,ts:E||void 0,status:dk(k),step:k}});return{run_id:n,node_id:u,items:w}}function Qm(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 _k(e){if(e==null)return"";if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}}function pk(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 gk(e){return e.endsWith(`
|
|
60
|
-
`)?e:`${e}
|
|
61
|
-
`}function yk(e){return String(e||"").trimStart().startsWith("```")}function wk(e,t){const r=[`# ${String((t==null?void 0:t.heading)||"Chat").trim()||"Chat"}`,""];for(const o of e){const l=pk(o);r.push(`## ${l}`,"");const u=String(o.content||""),c=Qm(u);c!==null&&!yk(u)?r.push("```json",_k(c).trimEnd(),"```",""):r.push(gk(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(`
|
|
62
|
-
`).trimEnd()}
|
|
63
|
-
`}async function dc(e){const t=String(e||"");if(!t)return!1;try{return await navigator.clipboard.writeText(t),!0}catch{try{const n=document.createElement("textarea");return n.value=t,n.style.position="fixed",n.style.left="-9999px",document.body.appendChild(n),n.select(),document.execCommand("copy"),document.body.removeChild(n),!0}catch{return!1}}}function vk(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 xk=3,bk=Number.MAX_SAFE_INTEGER;function hx(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function mx(e){return Array.isArray(e)}function jk(e){if(e==null)return"";if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}}function $u({kind:e,children:t}){return s.jsx("span",{className:`pc-json-token ${e}`,children:t})}function Sk(e){const t=JSON.stringify(e.value),n=t.length>96||t.includes("\\n")||t.includes("\\r")||t.includes("\\t"),[r,o]=m.useState(!n||e.expansionMode==="unfolded");return m.useEffect(()=>{n&&o(e.expansionMode==="unfolded")},[n,e.expansionMode,e.expansionVersion]),n?s.jsxs("span",{className:`pc-json-string ${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($u,{kind:"string",children:t})}function kk(e,t,n){return e===null?s.jsx($u,{kind:"null",children:"null"}):typeof e=="string"?s.jsx(Sk,{value:e,expansionMode:t,expansionVersion:n}):typeof e=="number"?s.jsx($u,{kind:"number",children:String(e)}):typeof e=="boolean"?s.jsx($u,{kind:"boolean",children:e?"true":"false"}):s.jsx($u,{kind:"string",children:JSON.stringify(String(e))})}function Nk(e){return mx(e)?e.length===1?"1 item":`${e.length} items`:hx(e)?Object.keys(e).length===1?"1 key":`${Object.keys(e).length} keys`:""}function _x(e){const{label:t,value:n,depth:r,collapseAfterDepth:o,expansionMode:l,expansionVersion:u,trailingComma:c}=e,f=r*14,_=hx(n),p=mx(n),y=_||p,w=r<o,[x,k]=m.useState(w);m.useEffect(()=>{k(w)},[w,u]);const j=t?s.jsxs(s.Fragment,{children:[s.jsx($u,{kind:"key",children:JSON.stringify(t)}),": "]}):null;if(!y)return s.jsxs("div",{className:"pc-json-viewer__line",style:{paddingLeft:f},children:[j,kk(n,l,u),c?",":""]});const E=p?"[":"{",A=p?"]":"}",L=Nk(n),O=x?`${E}`:`${E}…${A}${L?` (${L})`:""}`,M=p?n.map((H,X)=>({key:String(X),label:void 0,value:H})):Object.entries(n).map(([H,X])=>({key:H,label:H,value:X}));return s.jsxs("details",{className:"pc-json-viewer__details",open:x,onToggle:H=>k(H.currentTarget.open),children:[s.jsxs("summary",{className:"pc-json-viewer__summary",style:{paddingLeft:f},children:[j,s.jsx("span",{className:"pc-json-viewer__caret","aria-hidden":"true",children:x?"▾":"▸"}),s.jsx("span",{className:"pc-json-viewer__punct",children:O}),!x&&c?s.jsx("span",{className:"pc-json-viewer__punct",children:","}):null]}),x?s.jsx("div",{className:"pc-json-viewer__children",children:M.length===0?s.jsxs("div",{className:"pc-json-viewer__line",style:{paddingLeft:f},children:[s.jsx("span",{className:"pc-json-viewer__punct",children:A}),c?",":""]}):s.jsxs(s.Fragment,{children:[M.map((H,X)=>{const Y=X===M.length-1;return s.jsx(_x,{label:H.label,value:H.value,depth:r+1,collapseAfterDepth:o,expansionMode:l,expansionVersion:u,trailingComma:!Y},`${r}:${t||"root"}:${H.key}`)}),s.jsxs("div",{className:"pc-json-viewer__line",style:{paddingLeft:f},children:[s.jsx("span",{className:"pc-json-viewer__punct",children:A}),c?",":""]})]})}):null]})}function Ck(e){const t=e.trim();if(!t)return e;if(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))try{return JSON.parse(t)}catch{return e}return e}function dr(e){const{value:t,className:n,showCopy:r=!0}=e,[o,l]=m.useState({mode:"folded",version:0}),u=typeof e.collapseAfterDepth=="number"&&(Number.isFinite(e.collapseAfterDepth)||e.collapseAfterDepth===1/0)&&e.collapseAfterDepth>=0?e.collapseAfterDepth===1/0?Number.MAX_SAFE_INTEGER:Math.trunc(e.collapseAfterDepth):xk,c=o.mode==="unfolded"?bk:u,f=m.useMemo(()=>typeof t=="string"?Ck(t):t,[t]),_=m.useMemo(()=>jk(t),[t]),p=["pc-json-viewer",n].filter(Boolean).join(" ");m.useEffect(()=>{l(w=>({mode:"folded",version:w.version+1}))},[f]);const y=()=>{l(w=>({mode:w.mode==="unfolded"?"folded":"unfolded",version:w.version+1}))};return s.jsxs("div",{className:p,children:[s.jsxs("div",{className:"pc-json-viewer__toolbar",children:[s.jsx("button",{type:"button",className:"pc-btn pc-json-viewer__toggle-all",onClick:y,"aria-expanded":o.mode==="unfolded",children:o.mode==="unfolded"?"Fold all":"Unfold all"}),r?s.jsx("button",{type:"button",className:"pc-btn pc-json-viewer__copy",onClick:()=>void dc(_),children:"Copy JSON"}):null]}),s.jsx("div",{className:"pc-json-viewer__tree",role:"tree","aria-label":"JSON viewer",children:s.jsx(_x,{value:f,depth:0,collapseAfterDepth:c,expansionMode:o.mode,expansionVersion:o.version,trailingComma:!1})})]})}function lf(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 p=0;p<t.needlesLower.length;p++){const y=t.needlesLower[p];if(!y)continue;const w=o.indexOf(y,l);if(w===-1)continue;const x=t.needles[p]||"";x&&(u===-1||w<u||w===u&&x.length>c.length)&&(u=w,c=x)}if(u===-1||!c){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,_=n.slice(u,u+c.length);r.push(s.jsx("span",{id:f,className:t.className,children:_},`hl:${t.hits}`)),t.hits+=1,l=u+c.length}return r}function px(e){const t=String(e||"").trim();if(t&&/^(https?:|mailto:|tel:|#|\/)/i.test(t))return t}const Wp="http://same-origin.invalid/";function Ek(e){try{const t=new URL(e,Wp);return t.protocol==="http:"&&t.origin===new URL(Wp).origin}catch{return!1}}function gx(e){const t=String(e||"").trim();return px(t)??(t&&Ek(t)?t:void 0)}let oc=null;function $k(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??Wp;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 yx(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 wl(e,t){const n=[],r=String(e??"");let o=0,l="";const u=()=>{if(l){for(const c of lf(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 _=r.indexOf(")",f+2);if(_!==-1){const p=r.slice(o+2,f),y=gx(r.slice(f+2,_));if(y&&oc&&!oc(y)){u(),n.push(yx(`img:${o}`,y,p)),o=_+1;continue}if(y){u(),n.push(s.jsxs("span",{className:"pc-md_image_inline",children:[s.jsx("img",{className:"pc-md_img",src:y,alt:p,loading:"lazy"}),p?s.jsx("span",{className:"pc-md_img_caption",children:t?lf(p,t):p}):null]},`img:${o}`)),o=_+1;continue}}}}if(c==="["){const f=r.indexOf("]",o+1);if(f!==-1&&r[f+1]==="("){const _=r.indexOf(")",f+2);if(_!==-1){const p=r.slice(o+1,f),y=px(r.slice(f+2,_));if(y){u(),n.push(s.jsx("a",{className:"pc-md_link",href:y,target:y.startsWith("#")?void 0:"_blank",rel:"noreferrer",children:wl(p,t)},`link:${o}`)),o=_+1;continue}}}}if(c==="`"){const f=r.indexOf("`",o+1);if(f!==-1){u();const _=r.slice(o+1,f);n.push(s.jsx("code",{children:t?lf(_,t):_},`code:${o}`)),o=f+1;continue}}if(c==="*"&&r[o+1]==="*"){const f=r.indexOf("**",o+2);if(f!==-1){u();const _=r.slice(o+2,f);n.push(s.jsx("strong",{children:t?lf(_,t):_},`bold:${o}`)),o=f+2;continue}}if(c==="*"&&r[o+1]!=="*"){const f=r.indexOf("*",o+1);if(f!==-1){u();const _=r.slice(o+1,f);n.push(s.jsx("em",{children:t?lf(_,t):_},`em:${o}`)),o=f+1;continue}}l+=c,o+=1}return u(),n}function Ak(e){return String(e??"").replace(/\r\n/g,`
|
|
64
|
-
`).replace(/\r/g,`
|
|
65
|
-
`).split(`
|
|
66
|
-
`)}function gm(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 Tk(e){const t=[];for(const o of e){const l=gm(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,_=f[f.length-1];_?_.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 wx(e,t,n){const r=e.items.map((o,l)=>s.jsxs("li",{children:[wl(o.content,t),o.children.map((u,c)=>wx(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 Mk(e,t,n){return Tk(e).map((r,o)=>wx(r,t,`${n}:${o}`))}function My(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 Ry(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 Ly=/^(#{1,5})\s+(.*)$/;function Iy(e){return e.trim().startsWith("```")}function Oy(e){return e.trimStart().startsWith(">")}function Ai(e){const t=oc;oc=e.images==="link"?e.inlineImage||$k:null;try{return Rk(e)}finally{oc=t}}function Rk({text:e,className:t,highlight:n,highlights:r,highlightClassName:o,highlightId:l}){const u=Ak(e),c=[],f=[];Array.isArray(r)&&f.push(...r),typeof n=="string"&&n.trim()&&f.push(n);const _=Array.from(new Set(f.map(x=>String(x??"").trim()).filter(Boolean))).filter(x=>x.length>=4),p=_.length?{needles:_,needlesLower:_.map(x=>x.toLowerCase()),className:o||"pc-md_hl",id:l,hits:0}:null;let y=0;for(;y<u.length;){const x=String(u[y]??"");if(!x.trim()){y+=1;continue}const k=x.trim();if(/^([-_*])(\s*\1){2,}$/.test(k)){c.push(s.jsx("hr",{className:"pc-md_hr"},`hr:${y}`)),y+=1;continue}const j=x.match(/^\s*!\[([^\]]*)\]\(([^)]+)\)\s*$/);if(j){const L=gx(j[2]||"");if(L&&oc&&!oc(L)){c.push(s.jsx("p",{className:"pc-md_p",children:yx(`img:${y}`,L,j[1]||"")},`p:${y}`)),y+=1;continue}if(L){const O=j[1]||"";c.push(s.jsxs("figure",{className:"pc-md_figure",children:[s.jsx("img",{className:"pc-md_img",src:L,alt:O,loading:"lazy"}),O?s.jsx("figcaption",{children:wl(O,p)}):null]},`figure:${y}`)),y+=1;continue}}if(Iy(x)){const O=x.trim().replace(/```/g,"").trim(),M=[];for(y+=1;y<u.length&&!String(u[y]??"").trim().startsWith("```");)M.push(String(u[y]??"")),y+=1;y<u.length&&(y+=1);const H=M.join(`
|
|
67
|
-
`);c.push(s.jsx("pre",{className:"pc-md_pre",children:s.jsx("code",{className:O?`language-${O}`:void 0,children:H})},`pre:${y}`));continue}const E=x.match(Ly);if(E){const L=E[1].length,O=E[2]||"",M=wl(O,p);L===1?c.push(s.jsx("h1",{children:M},`h1:${y}`)):L===2?c.push(s.jsx("h2",{children:M},`h2:${y}`)):L===3?c.push(s.jsx("h3",{children:M},`h3:${y}`)):L===4?c.push(s.jsx("h4",{children:M},`h4:${y}`)):c.push(s.jsx("h5",{children:M},`h5:${y}`)),y+=1;continue}if(Oy(x)){const L=[];for(;y<u.length&&String(u[y]??"").trimStart().startsWith(">");){const M=String(u[y]??"").trimStart();L.push(M.replace(/^>\s?/,"")),y+=1}c.push(s.jsx("blockquote",{className:"pc-md_quote",children:L.map((O,M)=>s.jsxs(ve.Fragment,{children:[wl(O,p),M<L.length-1?s.jsx("br",{}):null]},`q:${y}:${M}`))},`quote:${y}`));continue}if(x.includes("|")&&y+1<u.length&&Ry(String(u[y+1]??""))){const L=My(x),O=Math.max(1,L.length),M=[];for(y+=2;y<u.length;){const H=String(u[y]??"");if(!H.trim()||!H.includes("|"))break;const X=My(H),Y=[];for(let Z=0;Z<O;Z++)Y.push(X[Z]??"");M.push(Y),y+=1}c.push(s.jsx("div",{className:"pc-md_table_wrap",children:s.jsxs("table",{className:"pc-md_table",children:[s.jsx("thead",{children:s.jsx("tr",{children:L.slice(0,O).map((H,X)=>s.jsx("th",{children:wl(H,p)},`th:${y}:${X}`))})}),s.jsx("tbody",{children:M.map((H,X)=>s.jsx("tr",{children:H.map((Y,Z)=>s.jsx("td",{children:wl(Y,p)},`td:${y}:${X}:${Z}`))},`tr:${y}:${X}`))})]})},`table:${y}`));continue}if(gm(x)){const L=[];for(;y<u.length;){const O=String(u[y]??"");if(!O.trim()||O.trimStart().startsWith("```"))break;if(gm(O)||/^\s{2,}\S/.test(O)){L.push(O),y+=1;continue}break}c.push(s.jsx(ve.Fragment,{children:Mk(L,p,`list:${y}`)},`list:${y}`));continue}const A=[];for(;y<u.length&&String(u[y]??"").trim()&&!(A.length>0&&gm(String(u[y]??"")));){const L=String(u[y]??"");if(A.length>0&&(Ly.test(L)||Iy(L)||Oy(L))||A.length>0&&L.includes("|")&&y+1<u.length&&Ry(String(u[y+1]??"")))break;A.push(L),y+=1}c.push(s.jsx("p",{className:"pc-md_p",children:A.map((L,O)=>s.jsxs(ve.Fragment,{children:[wl(L,p),O<A.length-1?s.jsx("br",{}):null]},`pl:${y}:${O}`))},`p:${y}`))}const w=["pc-md",t].filter(Boolean).join(" ");return s.jsx("div",{className:w,children:c})}function vx(e){const t=String(e.text??""),n=m.useMemo(()=>Qm(t),[t]),r=["pc-chat-content",e.className].filter(Boolean).join(" ");return n!==null?s.jsx("div",{className:r,children:s.jsx(dr,{value:n,collapseAfterDepth:e.jsonCollapseAfterDepth})}):e.renderMarkdown?s.jsx("div",{className:r,children:e.renderMarkdown(t)}):s.jsx("div",{className:r,children:s.jsx(Ai,{text:t,images:e.images,inlineImage:e.inlineImage})})}function xx(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}}function Lk(e){const t=xx(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 bx({tool:e,showCopy:t=!0}){const[n,r]=m.useState(!1),o=xx(e.arguments),l=Lk(e.arguments),u=["file path","path"].includes(l.label)&&l.value.length>60?`${l.value.split(/[\\/]/).pop()} · ${l.value.slice(0,24)}…`:l.value,c=e.error&&/^File ['"].+['"] does not exist\.?$/.test(e.error)?"File not found. Expand for the exact path.":e.error&&e.error.length>180?`${e.error.slice(0,100)}…${e.error.slice(-70)}`:e.error,f={running:"Running",waiting:"Approval needed",completed:"Done",failed:"Failed"},_=e.startedAt&&e.endedAt?Date.parse(e.endedAt)-Date.parse(e.startedAt):NaN,p=o&&typeof o=="object"&&!Array.isArray(o)?Object.entries(o):null;return s.jsxs("details",{className:`pc-tool-activity pc-tool-activity--${e.status}`,children:[s.jsxs("summary",{className:"pc-tool-activity__summary",children:[s.jsx("span",{className:"pc-tool-activity__state-icon","aria-hidden":"true",children:s.jsx(Ze,{name:e.status==="completed"?"check":e.status==="failed"?"x":e.status==="waiting"?"warning":"loader",size:15})}),s.jsx("strong",{children:e.name}),s.jsx("span",{className:"pc-tool-activity__preview",title:l.value,children:l.value?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"pc-tool-activity__key",children:l.label}),u]}):"No parameters"}),s.jsx("span",{className:"pc-tool-activity__status",children:f[e.status]}),Number.isFinite(_)&&_>=0?s.jsxs("span",{className:"pc-tool-activity__duration",children:[(_/1e3).toFixed(1),"s"]}):null,s.jsx("span",{className:"pc-tool-activity__chevron","aria-hidden":"true",children:s.jsx(Ze,{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 dc(JSON.stringify(e,null,2))),children:[s.jsx(Ze,{name:"copy",size:13}),n?"Copied":"Copy details"]}):null]}),p?s.jsx("dl",{className:"pc-tool-activity__parameters",children:p.map(([y,w])=>s.jsxs(ve.Fragment,{children:[s.jsx("dt",{children:y}),s.jsx("dd",{children:w&&typeof w=="object"?s.jsx(dr,{value:w}):s.jsx("code",{children:typeof w=="string"?w:JSON.stringify(w)})})]},y))}):e.arguments===void 0?s.jsx("p",{children:"Arguments are unavailable in this ledger."}):s.jsx(dr,{value:o}),e.output!==void 0?s.jsxs(s.Fragment,{children:[s.jsx("h4",{children:"Result"}),typeof e.output=="string"?s.jsx("pre",{className:"pc-tool-activity__output",children:e.output}):s.jsx("div",{className:"pc-tool-activity__output",children:s.jsx(dr,{value:e.output})})]}):null]})]})}function jx({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(Ze,{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(bx,{tool:r,showCopy:t},r.id))]})}const Vs="not reported",$r=e=>e===void 0?Vs:Math.round(e).toLocaleString(),Wr=e=>{if(e===void 0)return Vs;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`},Sx=e=>e===void 0?Vs:`${Math.round(e).toLocaleString()} tok/s`,Ik=(e,t)=>t>0?`${Math.round(e/t*100)}%`:"",ac=(e,t,n=`${t}s`)=>`${e.toLocaleString()} ${e===1?t:n}`,Ok=e=>{const t=e.split("#")[0].replace(/\/+$/,"");return t.slice(t.lastIndexOf("/")+1)||e};function Pk(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 $m(e){const t=[],n=(e.models||[]).map(Ok),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 Dk(e){const t=e.modelCalls||[],n=[],r=[{label:"Input",value:$r(e.inputTokens)},{label:"Output",value:$r(e.outputTokens)}];if(e.reasoningTokens!==void 0&&r.push({label:"Reasoning",value:$r(e.reasoningTokens),hint:"part of output"}),r.push({label:"Total",value:$r(e.totalTokens)}),n.push({heading:`Usage · ${ac(e.llmCalls,"model call")}`,rows:r}),e.measuredCacheCalls){const l=e.cachedTokens||0,u=e.fedTokens||0,c=[{label:"Reused from cache",value:`${$r(l)}${l+u?` (${Ik(l,l+u)})`:""}`},{label:"Newly processed",value:$r(e.fedTokens)},{label:"Outcome",value:Pk(t.map(f=>f.cacheOutcome))||(e.cacheOutcomes||[]).join(" · ")||Vs},{label:"Backend",value:(e.cacheBackends||[]).join(", ")||Vs}];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:Vs}]});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:`${$r(o[0].inputTokens)} tokens`}]}):o.length>1&&n.push({heading:"Context",rows:[{label:"First → last call",value:`${$r(o[0].inputTokens)} → ${$r(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),$r(l.inputTokens),l.cachedTokens===void 0?"—":$r(l.cachedTokens),l.fedTokens===void 0?"—":$r(l.fedTokens),$r(l.outputTokens),l.cacheOutcome||"—"])}}),{kind:"tokens",title:"Tokens",headline:e.totalTokens===void 0?Vs:`${e.totalTokens.toLocaleString()} total`,sections:n,footer:$m(e)}}function Kh(e,t,n,r){if(e===void 0)return Vs;const o=[Wr(e)];return t!==void 0&&o.push(`${t.toLocaleString()} ${r}${n!==void 0?` at ${Sx(n)}`:""}`),o.join(" · ")}function Fk(e){var _,p,y;const t=e.modelCalls||[],n=[],r=e.durationMs,o=[{label:"Wall clock",value:Wr(r)}];if(o.push({label:"Model",value:e.genTimeMs===void 0?Vs:`${Wr(e.genTimeMs)} · ${ac(e.timedCalls||0,"call")}${e.timedCalls!==e.llmCalls?` (of ${e.llmCalls})`:""}`}),o.push({label:"Tools",value:e.toolTimeMs!==void 0?`${Wr(e.toolTimeMs)} · ${ac(e.toolBatches||0,"batch","batches")}`:e.toolCalls?Vs:"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?Wr(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:Kh(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:Kh(e.prefillMs,e.prefillNewTokens,e.prefillNewTokensPerSecond,"new tok"),hint:"derived: prompt ÷ provider rate"}):e.prefillMs!==void 0?l.push({label:"Prefill",value:`${Wr(e.prefillMs)}${e.promptTokensPerSecond!==void 0?` at ${Sx(e.promptTokensPerSecond)}`:""}`,hint:"provider rate over all prompt tokens, restored included"}):l.push({label:"Prefill",value:Vs}),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?Kh(e.generationPhaseMs,e.generationPhaseTokens,e.generationPhaseTokensPerSecond,"tok"):Kh(e.decodeMs,e.outputTokens,e.generationTokensPerSecond,"tok")}),e.measuredSpeedCalls&&e.measuredSpeedCalls!==e.llmCalls&&l.push({label:"Speeds from",value:`${e.measuredSpeedCalls} of ${e.llmCalls} calls`}),n.push({heading:"Model",rows:l});const f=e.speculation;if(f){const w=(f.draftKinds||[]).map(k=>k.toUpperCase()).join(", "),x=[{label:"Mode",value:`${f.used?"on":"off"}${w?` · ${w}`:""}${(_=f.modes)!=null&&_.length?` (${f.modes.join(", ")})`:""}`,hint:f.calls!==e.llmCalls||f.used!==f.calls?`used on ${f.used} of ${e.llmCalls} calls`:void 0},{label:"Acceptance",value:f.acceptanceRate===void 0?Vs:`${Math.round(f.acceptanceRate*100)}% · ${$r(f.acceptedTokens)} of ${$r(f.draftedTokens)} drafted`}];((p=f.draftLengths)!=null&&p.length||f.rounds!==void 0)&&x.push({label:"Draft length",value:`${(y=f.draftLengths)!=null&&y.length?`${f.draftLengths.join("/")} tok/round`:Vs}${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:`${Wr(e.toolTimeMs)} · ${ac(e.toolBatches||0,"batch","batches")}`},{label:"Slowest",value:`${Wr(e.slowestToolBatch.ms)} · ${kx(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?"—":`${Wr(w.promptMs)}${w.promptSource==="rate"?"*":""}`,w.promptNewTokensPerSecond===void 0?"—":Math.round(w.promptNewTokensPerSecond).toLocaleString(),w.generationMs===void 0?"—":Wr(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?Vs:`${Wr(r)} wall clock`,sections:n,footer:$m(e)}}function kx(e){return e.tools.length===1?`${e.tools[0]} ×${e.calls}`:`${ac(e.calls,"call")} (${e.tools.join(", ")})`}function zk(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:$m(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?`${Wr(f.ms)}${f.sharedBatches?" +shared":""}`:f.sharedBatches?"shared":Vs])},note:o.some(([,c])=>c.sharedBatches)?"A batch that mixed tools ran them together; its time is not split between them.":void 0});const l=o.filter(([,c])=>c.errors&&Object.keys(c.errors).length);l.length&&t.push({heading:"Failures",rows:l.map(([c,f])=>({label:c,value:Object.entries(f.errors).sort((_,p)=>p[1]-_[1]).map(([_,p])=>p>1?`${_} ×${p}`:_).join(" · ")}))});const u=[{label:"Tool time",value:e.toolTimeMs===void 0?Vs:`${Wr(e.toolTimeMs)} · ${ac(e.toolBatches||0,"batch","batches")}`}];return e.slowestToolBatch&&u.push({label:"Slowest batch",value:`${Wr(e.slowestToolBatch.ms)} · ${kx(e.slowestToolBatch)}`}),t.push({heading:"Timing",rows:u,note:e.toolTimeIncludesApproval?"Gated calls are timed from request to result, so this includes waiting for your approval.":void 0}),{kind:"tools",title:"Tools",headline:`${ac(e.toolCalls,"call")}${e.toolsFailed?` · ${e.toolsFailed} failed`:""}`,sections:t,footer:$m(e)}}function q_(e,t){return e==="tokens"?Dk(t):e==="time"?Fk(t):zk(t)}function Bk(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===Vs?"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 ma=8;function Uk(e){const[t,n]=m.useState(!!e.defaultOpen),[r,o]=m.useState(null),l=m.useRef(null),u=m.useRef(null),c=m.useRef(null),f=`pc-stat-${m.useId().replace(/[^a-zA-Z0-9_-]/g,"")}`,_=m.useCallback(()=>{c.current!==null&&window.clearTimeout(c.current),c.current=null},[]),p=m.useCallback(()=>{_(),n(!0)},[_]),y=m.useCallback(()=>{_(),c.current=window.setTimeout(()=>n(!1),120)},[_]);m.useEffect(()=>_,[_]),m.useLayoutEffect(()=>{if(!t){o(null);return}const j=()=>{const E=l.current,A=u.current;if(!E||!A)return;const L=E.getBoundingClientRect(),O=A.offsetWidth,M=A.offsetHeight,H=window.innerWidth,X=window.innerHeight,Y=L.top-ma-M,Z=L.bottom+ma,re=Y>=ma?Y:Z+M<=X-ma?Z:Math.max(ma,X-ma-M),ie=Math.min(Math.max(ma,L.left),Math.max(ma,H-ma-O));o({top:re,left:ie})};return j(),window.addEventListener("resize",j),window.addEventListener("scroll",j,!0),()=>{window.removeEventListener("resize",j),window.removeEventListener("scroll",j,!0)}},[t]),m.useEffect(()=>{if(!t)return;const j=E=>{E.key==="Escape"&&n(!1)};return document.addEventListener("keydown",j),()=>document.removeEventListener("keydown",j)},[t]);const w=typeof e.onClick=="function",x=w?"button":"span",k=t?s.jsx(Bk,{detail:e.detail,id:f,panelRef:u,onMouseEnter:_,onMouseLeave:y,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:p,onMouseLeave:y,onFocus:p,onBlur:()=>n(!1),onKeyDown:j=>{j.key==="Escape"&&n(!1)},onClick:w?()=>{var j;return(j=e.onClick)==null?void 0:j.call(e)}:void 0,children:[e.icon?s.jsx("span",{className:"pc-chat-stat-icon","aria-hidden":"true",children:e.icon}):null,s.jsx("span",{className:"pc-chat-stat-label",children:e.label})]}),k&&typeof document<"u"?Av.createPortal(k,document.body):k]})}function Wk(e){const t=e.totalTokens!==void 0?q_("tokens",e):null,n=q_("tools",e),r=e.durationMs!==void 0?q_("time",e):null;return[...t?[{label:`${e.totalTokens.toLocaleString()} tokens`,detail:t}]:[],{label:`${e.toolCalls} ${e.toolCalls===1?"tool":"tools"}`,detail:n},...e.changedFiles.length?[{label:`${e.changedFiles.length} ${e.changedFiles.length===1?"file":"files"} changed`,title:e.changedFiles.join(`
|
|
68
|
-
`)}]:[],...r?[{label:`${(e.durationMs/1e3).toFixed(e.durationMs<1e4?1:0)}s`,detail:r}]:[]]}function qk(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"}}function Cg(e){var A;const t=e.message,n=m.useMemo(()=>qk(t),[t.kind,t.level,t.role,t.title]),r=String(t.ts||"").trim(),o=m.useMemo(()=>{if(!r)return"";const L=new Date(r);return Number.isFinite(L.getTime())?L.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):""},[r]),[l,u]=m.useState("idle"),c=m.useRef(null);m.useEffect(()=>()=>{c.current!==null&&window.clearTimeout(c.current)},[]);const f=t.live,_=!f&&typeof e.onSpeakToggle=="function"&&n.variant==="assistant"&&!!String(t.content||"").trim(),p=_&&((A=e.getSpeakState)==null?void 0:A.call(e,t))||"idle",y=p==="loading"?"loader":p==="playing"?"pause":"speaker",w=p==="loading"?"Generating audio…":p==="playing"?"Pause":p==="paused"?"Resume":"Speak (TTS)",x=e.showCopy!==!1,k=Array.isArray(e.attachments)?e.attachments:[],j=t.statistics,E=m.useMemo(()=>Array.isArray(e.stats)?e.stats:j?Wk(j):[],[e.stats,j]);return t.toolActivity?s.jsx(bx,{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(Ze,{name:n.icon,size:14})}),s.jsx("span",{className:"pc-chat-role",children:n.label}),f?s.jsxs("span",{className:"pc-chat-live-indicator",title:"The reply is still being written",children:[s.jsx("span",{className:"pc-chat-live-dot","aria-hidden":"true"}),"streaming"]}):null,f!=null&&f.caption?s.jsx("span",{className:"pc-chat-live-caption",children:f.caption}):null,s.jsx("span",{className:"pc-chat-header-spacer"}),o?s.jsx("span",{className:"pc-chat-time",children:o}):null,s.jsxs("div",{className:"pc-chat-header-actions",children:[_?s.jsx("button",{className:"pc-chat-icon-btn",type:"button","aria-label":w,title:w,onClick:()=>{var L;return(L=e.onSpeakToggle)==null?void 0:L.call(e,t)},children:s.jsx(Ze,{name:y,size:22})}):null,x?s.jsx("button",{className:`pc-chat-icon-btn ${l!=="idle"?`pc-chat-icon-btn--${l}`:""}`.trim(),type:"button","aria-label":"Copy message",title:l==="idle"?"Copy":l==="copied"?"Copied":"Copy failed",onClick:async()=>{const L=await dc(String(t.content||""));u(L?"copied":"failed"),c.current!==null&&window.clearTimeout(c.current),c.current=window.setTimeout(()=>u("idle"),900)},children:s.jsx(Ze,{name:"copy",size:22})}):null]})]}),f!=null&&f.reasoning?s.jsxs("details",{className:"pc-chat-thinking",children:[s.jsx("summary",{children:"Thinking"}),s.jsx("div",{className:"pc-chat-thinking-body",children:f.reasoning})]}):null,!f||String(t.content||"").trim()?s.jsx("div",{className:"pc-chat-body",children:s.jsx(vx,{text:String(t.content||""),renderMarkdown:e.renderMarkdown,jsonCollapseAfterDepth:e.jsonCollapseAfterDepth,images:e.images||(n.variant==="user"?"inline":"link"),inlineImage:e.inlineImage})}):null,k.length?s.jsx("div",{className:"pc-chat-attachments","aria-label":"Attachments",children:k.slice(0,24).map((L,O)=>{const M=String(L.label||"").trim()||"attachment",H=String(L.target||"").trim(),X=String(L.title||"").trim(),Y=!!L.disabled||typeof L.onClick!="function";return s.jsxs("button",{type:"button",className:"pc-chat-attachment-chip",title:X||M,onClick:Y?void 0:L.onClick,disabled:Y,children:[s.jsx(Ze,{name:"paperclip",size:14}),H?s.jsx("span",{className:`pc-chat-attachment-target pc-chat-attachment-target--${H}`,children:H}):null,s.jsx("span",{className:"pc-chat-attachment-name",children:M})]},L.id||`${M}:${O}`)})}):null,E.length?s.jsx("div",{className:"pc-chat-stats","aria-label":"Stats",children:E.slice(0,12).map((L,O)=>{const M=String(L.label||"").trim();if(!M)return null;if(L.detail)return s.jsx(Uk,{label:M,detail:L.detail,icon:L.icon,onClick:L.onClick},L.id||`${M}:${O}`);const H=String(L.title||"").trim(),X=typeof L.onClick=="function",Y=X?"button":"span";return s.jsxs(Y,{...X?{type:"button"}:{},className:["pc-chat-stat",X?"pc-chat-stat--clickable":""].filter(Boolean).join(" "),title:H||void 0,onClick:X?()=>{var Z;return(Z=L.onClick)==null?void 0:Z.call(L)}:void 0,children:[L.icon?s.jsx("span",{className:"pc-chat-stat-icon","aria-hidden":"true",children:L.icon}):null,s.jsx("span",{className:"pc-chat-stat-label",children:M})]},L.id||`${M}:${O}`)})}):null]})}function Hk(e,t){const n=Math.max(0,Math.trunc(t));return e.scrollHeight-e.scrollTop-e.clientHeight<=n}function Eg(e){const t=typeof e.autoScrollThresholdPx=="number"&&Number.isFinite(e.autoScrollThresholdPx)?e.autoScrollThresholdPx:120,n=e.autoScroll!==!1,r=m.useRef(null),o=m.useRef(null),[l,u]=m.useState(!0),c=m.useMemo(()=>Array.isArray(e.messages)?e.messages:[],[e.messages]),f=m.useMemo(()=>{var y;const p=[];for(const w of c){const x=p[p.length-1];w.toolActivity&&((y=x==null?void 0:x[0])!=null&&y.toolActivity)&&x[0].runId===w.runId?x.push(w):p.push([w])}return p},[c]);m.useEffect(()=>{if(!n)return;const p=r.current;if(!p)return;const y=()=>{u(Hk(p,t))};return p.addEventListener("scroll",y,{passive:!0}),y(),()=>p.removeEventListener("scroll",y)},[n,t]);const _=m.useMemo(()=>{let p=0;for(const y of c)p+=String(y.content??"").length;return`${c.length}:${p}:${String(e.afterKey??"")}`},[c,e.afterKey]);return m.useEffect(()=>{if(!n||!l)return;const p=r.current;p&&(p.scrollTop=p.scrollHeight)},[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((p,y)=>{var k;const w=p[0],x=String(w.id||"")||String(w.ts||"")+":"+String(w.role||"")+":"+y;return w.toolActivity?s.jsx(jx,{tools:p.map(j=>j.toolActivity),showCopy:(k=e.messageProps)==null?void 0:k.showCopy},x):s.jsx(Cg,{message:w,...e.messageProps||{}},x)}),e.after,s.jsx("div",{ref:o})]})}const $g=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 Vk(e){return!!(e&&typeof e[Symbol.asyncIterator]=="function")}function Gk(e){const[t,n]=m.useState([]),r=e.messages??t,o=j=>{e.onMessagesChange&&e.onMessagesChange(j),e.messages===void 0&&n(j)},l=m.useRef(r);l.current=r;const[u,c]=m.useState(""),[f,_]=m.useState(!1),p=m.useRef(null),y=e.assistantName||"Assistant",w=!!e.blockedNotice,x=async j=>{const E=String(j||"").trim();if(!E||f||w)return;c("");const A=l.current,L=[...A,{role:"user",content:E,ts:new Date().toISOString()}];o(L),_(!0);const O=new AbortController;p.current=O;try{const M=e.ask(E,{signal:O.signal,history:A});if(Vk(M)){let H="";const X=[...L,{role:"assistant",title:y,content:"",ts:new Date().toISOString()}];o(X);for await(const Y of M){if(O.signal.aborted)break;H+=String(Y??""),o([...L,{role:"assistant",title:y,content:H,ts:new Date().toISOString()}])}!H.trim()&&!O.signal.aborted&&o([...L,{role:"assistant",title:y,content:"#FALLBACK the assistant returned no answer.",level:"warn",ts:new Date().toISOString()}])}else{const H=String(await M??"").trim();o([...L,H?{role:"assistant",title:y,content:H,ts:new Date().toISOString()}:{role:"assistant",title:y,content:"#FALLBACK the assistant returned no answer.",level:"warn",ts:new Date().toISOString()}])}}catch(M){O.signal.aborted||o([...l.current,{role:"assistant",title:y,content:`#FALLBACK assistant request failed: ${String((M==null?void 0:M.message)||M||"unknown error")}`,level:"error",ts:new Date().toISOString()}])}finally{p.current===O&&(p.current=null),_(!1)}},k=m.useMemo(()=>r.length>0?null:s.jsxs("div",{className:"pc-assistant__empty",children:[s.jsx("div",{className:"pc-assistant__empty-text",children:e.emptyState||"Ask about this app — answers are grounded in its documentation."}),e.suggestions&&e.suggestions.length>0?s.jsx("div",{className:"pc-assistant__suggestions",children:e.suggestions.map(j=>s.jsx("button",{type:"button",className:"pc-assistant__suggestion",onClick:()=>void x(j),disabled:f||w,children:j},j))}):null]}),[r.length,e.emptyState,e.suggestions,f,w]);return s.jsxs("div",{className:`pc-assistant${e.className?` ${e.className}`:""}`,children:[s.jsxs("div",{className:"pc-assistant__thread",children:[k,s.jsx(Eg,{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($g,{value:u,onChange:c,onSubmit:()=>void x(u),placeholder:e.placeholder||"Ask about this app…",disabled:w,busy:f,rows:2,actions:f?s.jsx("button",{type:"button",className:"pc-btn",onClick:()=>{var j;(j=p.current)==null||j.abort()},children:"Stop"}):null})})]})}const yn=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},ym=e=>Array.isArray(e)?e.map(yn):[],en=e=>typeof e=="string"?e:"",cf=e=>en(e.runtime_call_id||e.call_uid),uf=e=>en(e.call_id||e.id);function Nx(e,t){const n=t.record,r=yn(n.effect);if(r.type!=="tool_calls")return[];const o=yn(n.result),l=ym(yn(r.payload).tool_calls),u=l.length||n.status!=="waiting"?l:ym(yn(yn(o.wait).details).tool_calls),c=ym(o.results),f=u.length?u:c,_=[];return f.forEach((p,y)=>{let w=cf(p)?c.filter(X=>cf(X)===cf(p)):[];!w.length&&uf(p)&&u.filter(X=>uf(X)===uf(p)).length===1&&(w=c.filter(X=>uf(X)===uf(p)));const x=u.length?w.length===1?w[0]:u.length===c.length?c[y]:{}:p,k=cf(p)||cf(x)||`${en(n.idempotency_key)||en(n.step_id)||t.cursor}:${y}`,j=`${t.runId}:${k}`,E=e.get(j),A=en(p.name||x.name)||(E==null?void 0:E.name);if(!A)return;const L=n.status==="completed"||n.status==="failed",O=n.status==="failed"||x.success===!1||!!x.error,M=p.arguments??x.arguments??(E==null?void 0:E.arguments),H={...E,id:j,runId:t.runId,name:A,arguments:M,status:L?O?"failed":"completed":n.status==="waiting"?"waiting":"running",...typeof x.success=="boolean"?{success:x.success}:{},...x.output!==void 0||x.result!==void 0?{output:x.output??x.result}:{},...x.error?{error:String(x.error)}:{},startedAt:(E==null?void 0:E.startedAt)||en(n.started_at)||void 0,endedAt:L&&en(n.ended_at)||(E==null?void 0:E.endedAt)};E&&["completed","failed"].includes(E.status)&&!L||(e.set(j,H),_.push(H))}),_}function Nu(e){if(e==null||e===""||typeof e=="boolean")return;const t=Number(e);return Number.isFinite(t)&&t>=0?t:void 0}function Do(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 Cx(e){if(typeof e=="string")try{return yn(JSON.parse(e))}catch{return{}}return yn(e)}function wu(e,t){if(t===void 0||t==="")return e;const n=e||[];return n.includes(t)||n.push(t),n}function Kk(e){return Do(e,["reasoning_tokens","thinking_tokens"])??Do(yn(e.completion_tokens_details),["reasoning_tokens"])??Do(yn(e.output_tokens_details),["reasoning_tokens"])}function Yk(e){const t=yn(typeof e=="string"&&e.trim().startsWith("{")?Cx(e):e);return en(t.error_class)}function Jk(e){const t=new Map;for(const n of e){const r=n.record;if(yn(r.effect).type!=="emit_event")continue;const o=yn(r.result);if(en(o.name)!=="abstract.progress")continue;const l=yn(o.payload);if(en(l.kind)!=="llm"||!en(l.step_id))continue;const u=`${en(l.run_id)||n.runId}:${en(l.step_id)}`,c=t.get(u)||{},f=Nu(l.ttft_s);f!==void 0&&(c.ttftS=f),c.provider=c.provider||en(l.provider)||void 0,c.model=c.model||en(l.model)||void 0,t.set(u,c)}return t}function H_(e){var j,E,A,L;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,_=0,p=0;const y=Jk(e),w=[],x=new Set;for(const O of e){const M=O.record,H=`${O.runId}:${M.step_id||O.cursor}:${M.status}`;if(n.has(H))continue;n.add(H);for(const we of[M.started_at,M.ended_at]){const Ee=Date.parse(en(we));Number.isFinite(Ee)&&(l=Math.min(l,Ee),u=Math.max(u,Ee))}for(const we of Nx(t,O))we.status==="waiting"&&x.add(we.id);if(yn(M.effect).type!=="llm_call"||M.status!=="completed")continue;o.llmCalls+=1;const X=yn(M.result),Y=yn(X.output),Z=yn(X.usage||X.token_usage||X.tokens||Y.usage||Y.token_usage||Y.tokens),re=Do(Z,["input_tokens","prompt_tokens","prompt","input","in"]),ie=Do(Z,["output_tokens","completion_tokens","completion","output","out"]),ue=Do(Z,["total_tokens","total"])??(re!==void 0||ie!==void 0?(re||0)+(ie||0):void 0);ue!==void 0&&(re===void 0||ie===void 0||re+ie!==ue)&&(c=!0),re!==void 0&&(o.inputTokens=(o.inputTokens||0)+re),ie!==void 0&&(o.outputTokens=(o.outputTokens||0)+ie),ue!==void 0&&(o.totalTokens=(o.totalTokens||0)+ue);const F=Nu(X.gen_time??Y.gen_time);F!==void 0&&(o.genTimeMs=(o.genTimeMs||0)+F,o.timedCalls=(o.timedCalls||0)+1);const C=yn(X.metadata||Y.metadata),N=yn(C.performance),P=Nu(N.prompt_tokens_per_second),D=Nu(N.generation_tokens_per_second),ne=yn(C.prompt_cache),B=Nu(ne.cached_tokens),z=Nu(ne.fed_tokens);if(P!==void 0||D!==void 0){if(o.measuredSpeedCalls=(o.measuredSpeedCalls||0)+1,P!==void 0&&P>0&&(o.promptTokensPerSecond=(o.promptTokensPerSecond||0)+P,re!==void 0)){const we=re/P*1e3;o.prefillMs=(o.prefillMs||0)+we,z!==void 0&&(f+=z,_+=we)}D!==void 0&&D>0&&(o.generationTokensPerSecond=(o.generationTokensPerSecond||0)+D,ie!==void 0&&(o.decodeMs=(o.decodeMs||0)+ie/D*1e3))}if(B!==void 0||z!==void 0){o.measuredCacheCalls=(o.measuredCacheCalls||0)+1,o.cachedTokens=(o.cachedTokens||0)+(B||0),o.fedTokens=(o.fedTokens||0)+(z||0);const we=en(ne.outcome);if(we){const Ee=o.cacheOutcomes||[];Ee.includes(we)||Ee.push(we),o.cacheOutcomes=Ee}}const G=en(M.step_id)||void 0,T=G&&y.get(`${O.runId}:${G}`)||{},Q=yn(X.route),K={runId:O.runId};G&&(K.stepId=G),en(M.started_at)&&(K.startedAt=en(M.started_at));const J=en(X.model||Y.model)||en(Q.model)||T.model,oe=en(Q.provider)||en(yn(C._provider_request).provider)||T.provider||en(X.provider);J&&(K.model=J),oe&&(K.provider=oe),J&&(o.models=wu(o.models,J)),oe&&(o.providers=wu(o.providers,oe)),(ue===void 0||re!==void 0&&ie!==void 0&&re+ie===ue)&&(re!==void 0&&(K.inputTokens=re),ie!==void 0&&(K.outputTokens=ie)),ue!==void 0&&(K.totalTokens=ue);const he=Kk(Z);he!==void 0&&(K.reasoningTokens=he,o.reasoningTokens=(o.reasoningTokens||0)+he),B!==void 0&&(K.cachedTokens=B),z!==void 0&&(K.fedTokens=z),en(ne.outcome)&&(K.cacheOutcome=en(ne.outcome)),en(ne.backend)&&(K.cacheBackend=en(ne.backend),o.cacheBackends=wu(o.cacheBackends,K.cacheBackend)),F!==void 0&&(K.genTimeMs=F),P!==void 0&&P>0&&(K.promptTokensPerSecond=P),D!==void 0&&D>0&&(K.generationTokensPerSecond=D),T.ttftS!==void 0?(K.ttftMs=T.ttftS*1e3,K.promptMs=K.ttftMs,K.promptSource="ttft",o.ttftMs=(o.ttftMs||0)+K.ttftMs,o.ttftCalls=(o.ttftCalls||0)+1):K.promptTokensPerSecond!==void 0&&re!==void 0&&(K.promptMs=re/K.promptTokensPerSecond*1e3,K.promptSource="rate"),K.promptMs!==void 0&&(o.promptPhaseMs=(o.promptPhaseMs||0)+K.promptMs,o.promptPhaseCalls=(o.promptPhaseCalls||0)+1,z!==void 0&&K.promptMs>0&&(K.promptNewTokensPerSecond=z/(K.promptMs/1e3),o.promptPhaseNewTokens=(o.promptPhaseNewTokens||0)+z,p+=K.promptMs)),K.ttftMs!==void 0&&F!==void 0&&F>=K.ttftMs?K.generationMs=F-K.ttftMs:K.generationTokensPerSecond!==void 0&&ie!==void 0&&(K.generationMs=ie/K.generationTokensPerSecond*1e3),K.generationMs!==void 0&&ie!==void 0&&(o.generationPhaseMs=(o.generationPhaseMs||0)+K.generationMs,o.generationPhaseTokens=(o.generationPhaseTokens||0)+ie);const _e=yn(C.speculation);if(Object.keys(_e).length){const we={};en(_e.mode)&&(we.mode=en(_e.mode)),typeof _e.used=="boolean"&&(we.used=_e.used),en(_e.draft_kind)&&(we.draftKind=en(_e.draft_kind));const Ee=Do(_e,["accepted_tokens"]),ze=Do(_e,["drafted_tokens"]),Ue=Do(_e,["rounds"]),_t=Do(_e,["num_draft_tokens"]);Ee!==void 0&&(we.acceptedTokens=Ee),ze!==void 0&&(we.draftedTokens=ze),Ee!==void 0&&ze&&(we.acceptanceRate=Ee/ze),Ue!==void 0&&(we.rounds=Ue),_t!==void 0&&(we.draftLength=_t),K.speculation=we;const Pe=o.speculation||(o.speculation={calls:0,used:0});Pe.calls+=1,we.used&&(Pe.used+=1),we.mode&&(Pe.modes=wu(Pe.modes,we.mode)),we.draftKind&&(Pe.draftKinds=wu(Pe.draftKinds,we.draftKind)),Ee!==void 0&&ze!==void 0&&(Pe.acceptedTokens=(Pe.acceptedTokens||0)+Ee,Pe.draftedTokens=(Pe.draftedTokens||0)+ze),Ue!==void 0&&(Pe.rounds=(Pe.rounds||0)+Ue),_t!==void 0&&(Pe.draftLengths=wu(Pe.draftLengths,_t))}w.push(K)}w.length&&(w.every(O=>O.startedAt)&&w.sort((O,M)=>Date.parse(O.startedAt)-Date.parse(M.startedAt)),o.modelCalls=w),p>0&&o.promptPhaseNewTokens!==void 0&&(o.promptPhaseTokensPerSecond=o.promptPhaseNewTokens/(p/1e3)),o.generationPhaseMs&&o.generationPhaseTokens!==void 0&&(o.generationPhaseTokensPerSecond=o.generationPhaseTokens/(o.generationPhaseMs/1e3)),(j=o.speculation)!=null&&j.draftedTokens&&(o.speculation.acceptanceRate=(o.speculation.acceptedTokens||0)/o.speculation.draftedTokens),o.measuredSpeedCalls&&(o.promptTokensPerSecond!==void 0&&(o.promptTokensPerSecond/=o.measuredSpeedCalls),o.generationTokensPerSecond!==void 0&&(o.generationTokensPerSecond/=o.measuredSpeedCalls)),_>0&&(o.prefillNewTokens=f,o.prefillNewTokensPerSecond=f/(_/1e3));const k=new Map;for(const O of t.values()){if(O.status==="waiting"){o.toolsWaiting=(o.toolsWaiting||0)+1;continue}if(O.status==="running"){o.toolsRunning=(o.toolsRunning||0)+1;continue}if(!["completed","failed"].includes(O.status))continue;o.toolCalls+=1;const M=O.status==="failed";M&&(o.toolsFailed=(o.toolsFailed||0)+1);const H=o.toolBreakdown||(o.toolBreakdown={}),X=H[O.name]||(H[O.name]={calls:0,failed:0});if(X.calls+=1,M){X.failed+=1;const ue=Yk(O.output);ue&&((X.errors||(X.errors={}))[ue]=(((E=X.errors)==null?void 0:E[ue])||0)+1)}const Y=Date.parse(en(O.startedAt)),Z=Date.parse(en(O.endedAt));if(Number.isFinite(Y)&&Number.isFinite(Z)&&Z>=Y){const ue=`${O.runId}|${O.startedAt}|${O.endedAt}`,F=k.get(ue)||{ms:Z-Y,calls:0,names:new Map,waited:!1};F.calls+=1,F.names.set(O.name,(F.names.get(O.name)||0)+1),x.has(O.id)&&(F.waited=!0),k.set(ue,F)}if(O.success!==!0||!["write_file","create_file","save_file","edit_file","update_file","replace_in_file","delete_file","remove_file","move_file","rename_file","copy_file"].includes(O.name))continue;const re=Cx(O.arguments),ie=en(re.destination||re.destination_path||re.file_path||re.path||re.filename);ie&&r.add(ie)}for(const O of k.values()){o.toolBatches=(o.toolBatches||0)+1,o.toolTimeMs=(o.toolTimeMs||0)+O.ms,O.waited&&(o.toolTimeIncludesApproval=!0);const M=[...O.names.keys()].sort();(!o.slowestToolBatch||O.ms>o.slowestToolBatch.ms)&&(o.slowestToolBatch={ms:O.ms,calls:O.calls,tools:M});const H=(A=o.toolBreakdown)==null?void 0:A[M[0]];if(M.length===1&&H)H.ms=(H.ms||0)+O.ms;else for(const X of M){const Y=(L=o.toolBreakdown)==null?void 0:L[X];Y&&(Y.sharedBatches=(Y.sharedBatches||0)+1)}}return o.changedFiles=[...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 Xk(e){const t=yn(yn(e).ledgers);return Object.entries(t).flatMap(([n,r])=>ym(yn(r).items).map((o,l)=>({runId:n,cursor:Number(o.cursor)||l+1,record:Object.keys(yn(o.record)).length?yn(o.record):o})))}function Yh(e){if(!e)return!1;for(let t=0;t<e.length;t+=1)if(e[t]==="Files")return!0;return!1}function Py(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 Dy(e){return e===1?"Drop file to attach":typeof e=="number"&&e>1?`Drop ${e} files to attach`:"Drop files to attach"}function Ex(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 Zk(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 Qk={"image/png":"png","image/jpeg":"jpg","image/gif":"gif","image/webp":"webp","image/heic":"heic","image/tiff":"tiff","image/bmp":"bmp"};function df(e){return String(e).padStart(2,"0")}function eN(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=Qk[String(t||"").toLowerCase()]||r.split(".").pop()||"bin",l=`${n.getFullYear()}-${df(n.getMonth()+1)}-${df(n.getDate())} at ${df(n.getHours())}.${df(n.getMinutes())}.${df(n.getSeconds())}`;return`${String(t||"").startsWith("image/")||!r?"Pasted image":"Pasted file"} ${l}.${o}`}function tN(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}=Ex(e);return r.map(o=>{const l=eN(o.name,o.type,t);return l===o.name?o:new File([o],l,{type:o.type,lastModified:o.lastModified})})}class nN{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 sN(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 rN(e){return(e instanceof Error?e.message:String(e||"Unknown error")).trim()||"Unknown error"}function iN(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 oN(e){var Y;const t=e.interaction,[n,r]=m.useState(""),[o,l]=m.useState(()=>t.kind==="event-wait"&&t.initialPayload||""),[u,c]=m.useState(null),[f,_]=m.useState(!1),[p,y]=m.useState(""),[w,x]=m.useState(null),k=`${t.kind}:${t.id}`,j=m.useRef(k),E=m.useRef(!1),A=m.useRef(!1),L=m.useRef(!0),O=m.useRef(0);j.current!==k&&(j.current=k,E.current=!1,A.current=!1,O.current+=1);const M=!!e.disabled||u!==null||f||E.current||A.current,H=async(Z,re)=>{var F;if(e.disabled||E.current||A.current)return;const ie=k,ue=++O.current;E.current=!0,x(null),y(""),c(Z);try{if(await re(),!L.current||j.current!==ie||O.current!==ue)return;A.current=!0,_(!0),y("Response sent. Waiting for the workflow to continue.")}catch(C){if(!L.current||j.current!==ie||O.current!==ue)return;x({submission:Z,message:rN(C)}),y("The action failed. You can try again."),(F=e.onError)==null||F.call(e,C)}finally{if(!L.current||j.current!==ie||O.current!==ue)return;E.current=!1,c(null)}};m.useEffect(()=>{r(""),l(t.kind==="event-wait"&&t.initialPayload||""),x(null),c(null),_(!1),y("")},[k]),m.useEffect(()=>(L.current=!0,()=>{L.current=!1,O.current+=1,E.current=!1}),[]);const X=()=>{w&&H(w.submission,()=>sN(t,w.submission))};return s.jsxs("section",{className:"pc-workflow-interaction","aria-labelledby":`pc-workflow-interaction-${k}`,children:[s.jsxs("div",{className:"pc-workflow-interaction__heading",children:[s.jsx(Ze,{name:t.kind==="tool-approval"?"warning":t.kind==="event-wait"?"history":"info",size:16}),s.jsxs("div",{children:[s.jsx("h3",{tabIndex:-1,id:`pc-workflow-interaction-${k}`,children:t.title||(t.kind==="tool-approval"?"Tool approval required":"Input required")}),t.description?s.jsx("div",{className:"pc-workflow-interaction__description",children:t.description}):null]})]}),t.kind==="ask-user"?s.jsxs("div",{className:"pc-workflow-interaction__body",children:[s.jsx("div",{className:"pc-workflow-interaction__prompt",children:t.prompt}),(Y=t.choices)!=null&&Y.length?s.jsx("div",{className:"pc-workflow-interaction__choices","aria-label":"Choices",children:t.choices.map(Z=>s.jsxs("button",{type:"button",className:"pc-workflow-interaction__choice",disabled:M||Z.disabled,onClick:()=>void H({kind:"choice",answer:Z.id},()=>t.onSubmit(Z.id)),children:[s.jsx("span",{children:Z.label}),Z.description?s.jsx("small",{children:Z.description}):null]},Z.id))}):null,t.allowFreeText!==!1?s.jsxs("div",{className:"pc-workflow-interaction__entry",children:[s.jsx("textarea",{"aria-label":"Response",value:n,onChange:Z=>r(Z.target.value),placeholder:t.freeTextPlaceholder||"Type a response",rows:2,disabled:M,onKeyDown:Z=>{Z.key!=="Enter"||Z.shiftKey||Z.nativeEvent.isComposing||Z.keyCode===229||(Z.preventDefault(),n.trim()&&H({kind:"free-text",answer:n},()=>t.onSubmit(n)))}},`${k}:text`),s.jsx("button",{type:"button",className:"pc-btn",disabled:M||!n.trim(),onClick:()=>void H({kind:"free-text",answer:n},()=>t.onSubmit(n)),children:(u==null?void 0:u.kind)==="free-text"?"Sending…":t.submitLabel||"Submit"})]}):null]}):t.kind==="tool-approval"?s.jsxs("div",{className:"pc-workflow-interaction__body",children:[s.jsxs("div",{className:"pc-workflow-interaction__prompt",children:["Allow ",s.jsx("strong",{children:t.toolName})," to run?"]}),t.detail?s.jsx("div",{className:"pc-workflow-interaction__detail",children:t.detail}):null,s.jsxs("div",{className:"pc-workflow-interaction__buttons",children:[s.jsx("button",{type:"button",className:"pc-workflow-interaction__deny",disabled:M,onClick:()=>void H({kind:"deny"},t.onDeny),children:(u==null?void 0:u.kind)==="deny"?"Denying…":t.denyLabel||"Deny"}),s.jsx("button",{type:"button",className:"pc-btn",disabled:M,onClick:()=>void H({kind:"approve"},t.onApprove),children:(u==null?void 0:u.kind)==="approve"?"Approving…":t.approveLabel||"Approve"}),t.onApproveAll?s.jsx("button",{type:"button",className:"pc-workflow-interaction__allow-all",disabled:M,onClick:()=>void H({kind:"approve-all"},t.onApproveAll),children:(u==null?void 0:u.kind)==="approve-all"?"Approving…":t.approveAllLabel||"Allow all"}):null]}),t.onApproveAll&&t.approveAllDescription?s.jsx("p",{className:"pc-workflow-interaction__scope",children:t.approveAllDescription}):null]}):s.jsxs("div",{className:"pc-workflow-interaction__body",children:[s.jsx("div",{className:"pc-workflow-interaction__prompt",children:t.prompt}),s.jsxs("label",{className:"pc-workflow-interaction__entry",children:[s.jsx("span",{children:t.payloadLabel||(t.eventName?`Payload for ${t.eventName}`:"Event payload")}),s.jsx("textarea",{value:o,onChange:Z=>l(Z.target.value),placeholder:t.payloadPlaceholder||"Enter payload",rows:2,"aria-label":t.payloadLabel||(t.eventName?`Payload for ${t.eventName}`:"Event payload"),disabled:M},`${k}:payload`)]}),s.jsx("div",{className:"pc-workflow-interaction__buttons",children:s.jsx("button",{type:"button",className:"pc-btn",disabled:M,onClick:()=>void H({kind:"event",payload:o},()=>t.onSend(o)),children:(u==null?void 0:u.kind)==="event"?"Sending…":t.sendLabel||"Send event"})})]}),w?s.jsx(iN,{message:w.message,onRetry:X,disabled:M}):null,s.jsx("div",{className:"pc-workflow-interaction__outcome","aria-live":"polite",children:p})]})}function Jh(e){return(e instanceof Error?e.message:String(e||"Unknown error")).trim()||"Unknown error"}function aN(e){const[t,n]=m.useState(!1),[r,o]=m.useState(!1),[l,u]=m.useState(!1),[c,f]=m.useState(null),_=m.useRef(!0),p=m.useRef(!1),y=m.useRef(!1),w=m.useRef(!1),x=m.useRef(0),k=m.useRef(0),j=m.useRef(0);m.useEffect(()=>(_.current=!0,()=>{_.current=!1,x.current+=1,k.current+=1,j.current+=1,p.current=!1,y.current=!1,w.current=!1}),[]);const E=!!e.blockedNotice,A=!!e.disabled||E,L=!!e.busy||t,O=t||!!e.busy&&!e.sendWhileBusy,M=e.stopState||null,H=(M==null?void 0:M.phase)==="stopping",X=typeof e.onFiles=="function",Y=m.useRef(null),[Z,re]=m.useState(null),[ie,ue]=m.useState(""),F=m.useRef(e.onFiles);F.current=e.onFiles;const C=m.useRef(A);C.current=A;const N=async(K,J)=>{const oe=F.current;if(oe){if(C.current){f({action:"attach",message:"attachments are unavailable right now."});return}if(J.length)f({action:"attach",message:Zk(J)});else if(K.length)f(null);else{f({action:"attach",message:"the drop contained no files."});return}if(K.length){ue(`Attaching ${K.length} ${K.length===1?"file":"files"}…`);try{await oe(K)}catch(he){_.current&&f({action:"attach",message:Jh(he)})}}}},P=m.useRef(N);P.current=N,m.useEffect(()=>{if(!X||typeof window>"u")return;const K=new nN;let J=0;const oe=Pe=>!!(Y.current&&Pe instanceof Node&&Y.current.contains(Pe)),he=()=>{K.reset(),J&&window.clearInterval(J),J=0,re(null)},_e=()=>{J||(J=window.setInterval(()=>{K.active(Date.now())||he()},250))},we=Pe=>{var Je;if(!Yh((Je=Pe.dataTransfer)==null?void 0:Je.types))return;K.enter(Date.now());const et=oe(Pe.target),lt=Py(Pe.dataTransfer);re(Se=>Se&&Se.over===et&&Se.count===(lt??Se.count)?Se:{count:lt??(Se==null?void 0:Se.count)??null,over:et}),_e()},Ee=Pe=>{var lt;if(!Yh((lt=Pe.dataTransfer)==null?void 0:lt.types))return;Pe.preventDefault(),K.over(Date.now());const et=oe(Pe.target);Pe.dataTransfer&&(Pe.dataTransfer.dropEffect=et&&!C.current?"copy":"none"),re(Je=>Je&&Je.over===et?Je:{count:(Je==null?void 0:Je.count)??Py(Pe.dataTransfer),over:et}),_e()},ze=Pe=>{var et;Yh((et=Pe.dataTransfer)==null?void 0:et.types)&&(K.leave(Date.now())||he())},Ue=Pe=>{var Ie;if(!Yh((Ie=Pe.dataTransfer)==null?void 0:Ie.types))return;const et=oe(Pe.target),lt=Pe.defaultPrevented&&!et;if(Pe.preventDefault(),he(),lt)return;if(!et){f({action:"attach",message:"drop files on the conversation to attach them."});return}const{files:Je,folders:Se}=Ex(Pe.dataTransfer);P.current(Je,Se)},_t=Pe=>{Pe.key==="Escape"&&K.depth>0&&he()};return window.addEventListener("dragenter",we),window.addEventListener("dragover",Ee),window.addEventListener("dragleave",ze),window.addEventListener("drop",Ue),window.addEventListener("dragend",he),window.addEventListener("blur",he),window.addEventListener("keydown",_t),()=>{window.removeEventListener("dragenter",we),window.removeEventListener("dragover",Ee),window.removeEventListener("dragleave",ze),window.removeEventListener("drop",Ue),window.removeEventListener("dragend",he),window.removeEventListener("blur",he),window.removeEventListener("keydown",_t),J&&window.clearInterval(J)}},[X]);const D=K=>{if(!X||A)return;const J=tN(K.clipboardData);J.length&&(K.preventDefault(),N(J,[]))},ne=Z?s.jsxs("div",{className:["pc-workflow-chat__dropzone",Z.over?"is-over":"",A?"is-disabled":""].filter(Boolean).join(" "),"aria-hidden":"true",children:[s.jsx("span",{className:"pc-workflow-chat__dropzone-icon",children:s.jsx(Ze,{name:"paperclip",size:18})}),s.jsxs("span",{className:"pc-workflow-chat__dropzone-text",children:[s.jsx("strong",{children:A?"Attachments are unavailable right now":Dy(Z.count)}),A?null:s.jsx("span",{children:Z.over?"Release to upload to this conversation":"Drop anywhere on the conversation"})]})]}):null,B=Z?A?"Attachments are unavailable right now":Dy(Z.count):ie,z=async()=>{const K=String(e.draft||"");if(A||p.current||!e.sendWhileBusy&&e.busy||!K.trim())return;const J=++x.current;p.current=!0,f(null),n(!0);try{await e.onSend(K)}catch(oe){_.current&&x.current===J&&f({action:"send",message:Jh(oe)})}finally{_.current&&x.current===J&&(p.current=!1,n(!1))}},G=async()=>{if(A||y.current||!e.onCancel)return;const K=++k.current;y.current=!0,f(null),o(!0);try{await e.onCancel()}catch(J){_.current&&k.current===K&&f({action:"cancel",message:Jh(J)})}finally{_.current&&k.current===K&&(y.current=!1,o(!1))}},T=async()=>{if(A||w.current||!e.onAttach)return;const K=++j.current;w.current=!0,f(null),u(!0);try{await e.onAttach()}catch(J){_.current&&j.current===K&&f({action:"attach",message:Jh(J)})}finally{_.current&&j.current===K&&(w.current=!1,u(!1))}},Q=()=>{c&&(c.action==="send"&&z(),c.action==="cancel"&&G(),c.action==="attach"&&T())};return s.jsxs("section",{ref:Y,className:["pc-workflow-chat",Z?"pc-workflow-chat--dragging":"",Z!=null&&Z.over?"pc-workflow-chat--drag-over":"",e.className].filter(Boolean).join(" "),"aria-label":"Workflow chat","data-stream-replies":e.streamReplies||"gateway_default",children:[e.header?s.jsx("header",{className:"pc-workflow-chat__header",children:e.header}):null,s.jsx("div",{className:"pc-workflow-chat__transcript",children:s.jsx(Eg,{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(oN,{interaction:e.interaction,disabled:A}):null,E?s.jsx("div",{className:"pc-workflow-chat__blocked",role:"status",children:e.blockedNotice}):null]}),afterKey:`${e.interaction?`${e.interaction.kind}:${e.interaction.id}`:""}:${E?"blocked":""}`})}),c?s.jsxs("div",{className:"pc-workflow-chat__error",role:"alert",children:[s.jsxs("span",{children:["Could not ",c.action==="send"?"send this message":c.action==="attach"?"attach a file":"stop the run",": ",c.message]}),s.jsx("button",{type:"button",onClick:Q,disabled:A,children:"Try again"})]}):null,s.jsxs("div",{className:"pc-workflow-chat__composer",children:[s.jsx($g,{value:e.draft,onChange:e.onDraftChange,onSubmit:()=>void z(),placeholder:e.placeholder||"Send a message",ariaLabel:"Message",disabled:A,busy:O,sendLabel:e.sendLabel,busyLabel:e.busyLabel,rows:2,leading:e.attachments?s.jsx("div",{className:"pc-workflow-chat__attachments",children:e.attachments}):null,overlay:ne,onPaste:X?D:void 0,actions:s.jsxs(s.Fragment,{children:[e.onAttach?s.jsxs("button",{type:"button",className:"pc-workflow-chat__icon-button","aria-label":"Attach file",title:"Attach file",disabled:A||l,onClick:()=>void T(),children:[s.jsx(Ze,{name:"paperclip",size:16}),s.jsx("span",{children:l?"Attaching…":"Attach"})]}):null,e.composerExtras,L&&e.onCancel?s.jsxs("button",{type:"button",className:"pc-workflow-chat__stop",disabled:A||r||H,onClick:()=>void G(),children:[s.jsx(Ze,{name:"x",size:14}),s.jsx("span",{children:r||H?"Stopping…":"Stop"})]}):M?s.jsx("span",{className:`pc-workflow-chat__stop-state pc-workflow-chat__stop-state--${M.phase}`,role:"status","aria-live":"polite",children:M.label}):null]})}),X?s.jsx("div",{className:"pc-sr-only",role:"status","aria-live":"polite",children:B}):null]}),e.footer?s.jsx("footer",{className:"pc-workflow-chat__footer",children:e.footer}):null]})}const V_="llm.delta",Xh="llm.delta_end";function lN(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Zl(e){return typeof e=="string"&&e.trim()!==""}function cN(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0}function uN(e){return"reason"in e}function dN(e,t){const n=lN(e),r=n==null?void 0:n.kind,o=typeof r=="string"&&r?r:n&&"reason"in n?Xh:V_,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!==V_&&r!==Xh&&l(`unknown kind ${JSON.stringify(r)}`),Zl(n.run_id)||l("run_id is missing"),Zl(n.call_id)||l("call_id is missing"),cN(n.seq)||l("seq is not a non-negative integer");const u=r?r===Xh:"reason"in n;n.root_run_id!==void 0&&!Zl(n.root_run_id)&&l("root_run_id is not a run id"),n.parent_run_id!==void 0&&n.parent_run_id!==null&&!Zl(n.parent_run_id)&&l("parent_run_id is neither a run id nor null");const c={run_id:n.run_id,...Zl(n.root_run_id)?{root_run_id:n.root_run_id}:{},...n.parent_run_id!==void 0?{parent_run_id:n.parent_run_id}:{},...Zl(n.node_id)?{node_id:n.node_id}:{},call_id:n.call_id,seq:n.seq};return u?(["completed","failed","cancelled","unavailable"].includes(String(n.reason))||l(`unknown reason ${JSON.stringify(n.reason)}`),n.detail!==void 0&&n.detail!==null&&typeof n.detail!="string"&&l("detail is not a string"),{kind:Xh,...c,reason:n.reason,...Zl(n.detail)?{detail:n.detail}:{}}):(typeof n.text!="string"&&l("text is not a string"),n.channel!=="content"&&n.channel!=="reasoning"&&l(`unknown channel ${JSON.stringify(n.channel)}`),typeof n.snapshot!="boolean"&&l("snapshot is not a boolean"),{kind:V_,...c,text:n.text,channel:n.channel,snapshot:n.snapshot})}const fN={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 hN(e){return`This reply is not streamed: ${e?fN[e]||`the gateway reported "${e}"`:"the gateway gave no reason"}. It appears when it is complete.`}function mN(e){return e.toolApprovalGranted?null:e.interaction}const Fy={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 Sf(e){return Array.isArray(e)?e:[]}function Ur(e){return vt(e==null?void 0:e.status).toLowerCase()||"unknown"}function Ns(e){return["completed","failed","cancelled"].includes(e.toLowerCase())}function ml(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 _N(e){const t=St(e);return Number((t==null?void 0:t.status)??(t==null?void 0:t.statusCode))}function G_(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 qp(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 vu(e){const t=qp(e);if(t)return t;if(!St(e)&&!Array.isArray(e))return"";try{return JSON.stringify(e,null,2)}catch{return""}}function zy(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=Sf(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 $x(e){const t=St(e.result);return St(t==null?void 0:t.wait)}function K_(e){return e?vt(e.reason)==="subworkflow"||vt(e.wait_key).startsWith("subworkflow:"):!1}function By(e,t){return!!(e&&e.runId===t.runId&&vt(e.wait.wait_key)===vt(t.wait.wait_key))}function Hp(e){return St(e.effect)||{}}function pN(e,t){return vt(e.run_id)||t}function Uy(e){return vt(e.ended_at)||vt(e.started_at)||void 0}function Wy(e){const t=new Set,n=_=>{const p=vt(_);p&&t.add(p)},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=Hp(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=$x(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 gN{constructor(t,n={}){this.transport=t,this.options=n,this.snapshot={...Fy},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({...Fy})}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),_=Ur(c);if(await this.ingestHistory(u,n,r),!this.live(r))return;if(this.set({...this.snapshot,run:c,status:_,loading:!1,...f&&!Ns(_)?{interaction:this.interactionWith({runId:n,wait:f})}:{}}),c&&this.updateRunState(n,c),f)for(const p of Wy({result:{wait:f}}))p!==n&&this.catchUpAndWatch(p,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 p,y;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&&((p=this.snapshot.interaction)==null?void 0:p.stepId)||"",u=`${o}\0${t}\0${l}\0${G_(n)}`;let c=this.commandIds.get(u);c||(c=this.newCommandId(),this.commandIds.set(u,c));const f=this.generation,_=(y=this.controller)==null?void 0:y.signal;try{const w=await this.transport.submitCommand({command_id:c,run_id:o,type:t,payload:n,...this.options.clientId?{client_id:this.options.clientId}:{}},_);if(!this.live(f))return w;const x=St(w);if(x&&x.accepted===!1)throw t==="cancel"&&(this.stopRequested=!1,this.recomputeStop()),new Error(vt(x.detail)||"Gateway did not accept the command");return this.commandIds.delete(u),o===this.rootRunId&&["pause","resume","cancel"].includes(t)&&this.refreshRunState(o,f),w}catch(w){throw this.live(f)&&this.fail(w,!1),w}}resume(t){const n=this.requireInteraction();return this.sendCommand("resume",{wait_key:vt(n.wait.wait_key),payload:{response:t}})}approve(t,n){const r=this.requireInteraction();if(Ns(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||Ns(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||Ns(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){G_(t)!==G_(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&&K_(t.wait)&&!K_(n.wait)?n:n&&By(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||Ur(n)!=="waiting"||K_(r)||Ns(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&&By(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||Ns(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 p;const f=c.toolActivity;if(!f||((p=this.toolActivities.get(f.id))==null?void 0:p.status)!=="waiting")return c;const _=o&&f.runId===(n==null?void 0:n.runId)?"running":"waiting";return f.status===_?c:(l=!0,this.toolMessage({...f,status:_}))});return{...t,toolApprovalGranted:o,...l?{messages:u}:{}}}toolCallsMatch(t,n){var o;const r=Sf((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(ml(o))throw o;this.fail(o,!1)}if(await this.catchUp(t,n),!this.live(n)||Ns(Ur(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(ml(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:Sf(c==null?void 0:c.items);for(const p of f)this.ingestItem(t,p);const _=Number(c==null?void 0:c.next_after);if(!f.length||!Number.isFinite(_)||_<=l)break;this.cursors.set(t,_)}}async watch(t,n){try{await this.followStream(t,n)}finally{this.live(n)&&this.closeLiveRepliesVia(t)}}async followStream(t,n){var o;let r=0;for(;this.live(n)&&!Ns(Ur(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,_=>{this.live(n)&&(c(),this.ingestItem(t,_))},this.controller.signal,c,_=>{this.live(n)&&(c(),this.ingestDelta(t,_))}),!this.live(n)||(await this.catchUp(t,n),!this.live(n)))return;const f=St(await this.transport.getRun(t,(o=this.controller)==null?void 0:o.signal));if(!this.live(n))return;f&&this.updateRunState(t,f),r+=1}catch(u){if(!this.live(n))return;if(r+=1,this.fail(u,!1),ml(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(Ns(Ur(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=Sf(l==null?void 0:l.turns).map(St).filter(_=>!!_);if(await this.hydrateHistoricalSessionRuns(u,n,r),!this.live(r))return;for(const _ of u){const p=vt(_==null?void 0:_.run_id)||n;this.ingestSessionTurn(_,n,p!==n&&this.historicalRuns.get(p)||null)}const c=`turn:${n}:user`;if(!this.seenMessages.has(c)){const _=zy(St(o.input_data));_&&this.addMessage({id:c,role:"user",content:_})}const f=St(o.ledgers);if(f)for(const[_,p]of Object.entries(f)){const y=St(p);for(const w of Sf(y==null?void 0:y.items))this.ingestItem(_,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)||zy(l);u&&this.addMessage({id:`turn:${o}:user`,role:"user",content:u,ts:vt(t.created_at)||void 0});const c=this.historicalRunFailures.get(o);if(c){const y=vt(t.answer)||qp(t.output),w=c.missing?"is unavailable because the run no longer exists":"could not be restored",x=y?` Saved reply (not verified as the final result): ${y}`:"";this.addMessage({id:`history:${o}:unavailable`,role:"system",level:"warn",title:"History",content:`The final output for an earlier turn ${w}.${x}`});return}const _=(r&&Ns(Ur(r))?vu(r.output):"")||(r?vt(t.answer)||qp(t.output):""),p=this.historicalEvidence.get(o);for(const y of(p==null?void 0:p.tools)||[])this.upsertTool(y);_&&this.addRunAssistantMessage(o,{id:`final:${o}`,role:"assistant",content:_,runId:o,statistics:p==null?void 0:p.statistics,ts:vt(t.updated_at)||void 0})}async hydrateHistoricalSessionRuns(t,n,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,_,p;for(;!u&&this.live(r);){const y=o[l++];if(!y)return;try{const w=St(await this.transport.getRun(y,(f=this.controller)==null?void 0:f.signal));if(!this.live(r))return;if(w){this.historicalRuns.set(y,w);try{const x=await this.transport.getHistory(y,(_=this.controller)==null?void 0:_.signal);if(!this.live(r))return;this.historicalEvidence.set(y,H_(Xk(x)))}catch(x){if(!this.live(r))return;if(ml(x))throw x;this.fail(new Error(`Earlier turn activity could not be restored: ${x instanceof Error?x.message:String(x)}`),!1)}}else this.historicalRuns.set(y,null),this.historicalRunFailures.set(y,{missing:!1,detail:"gateway returned an invalid historical run snapshot"})}catch(w){if(!this.live(r))return;const x=_N(w)===404;this.historicalRuns.set(y,null),this.historicalRunFailures.set(y,{missing:x,detail:w instanceof Error?w.message:vt((p=St(w))==null?void 0:p.detail)||"request failed"}),ml(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=pN(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(_=>_.id===`final:${this.rootRunId}`)){const _=H_(this.snapshot.records).statistics;this.set({...this.snapshot,messages:this.snapshot.messages.map(p=>p.id===`final:${this.rootRunId}`?{...p,statistics:_}:p)})}for(const _ of Wy(o))_!==l&&this.catchUpAndWatch(_,this.generation)}}foldRecord(t,n,r){var p,y,w;const o=Hp(n),l=vt(o.type).toLowerCase(),u=St(n.result),c=vt(n.status).toLowerCase(),f=Uy(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=vu(u)||vu(St(o.payload));x&&this.addRunAssistantMessage(t,{id:`answer:${t}:${r}`,role:"assistant",content:x,ts:f})}if(l==="emit_event"&&c==="completed"){const x=St(o.payload)||{},k=St(u),j=vt(x.name)||vt(k==null?void 0:k.name),E=x.payload!==void 0?x.payload:k==null?void 0:k.payload;if(["abstract.message","abstractcode.message"].includes(j)){const A=vu(E);if(A){const L=vt((p=St(E))==null?void 0:p.level).toLowerCase(),O=L==="error"?"error":["warn","warning"].includes(L)?"warn":"info";this.addMessage({id:`event:${t}:${r}`,role:"system",title:"Workflow",content:A,level:O,ts:f})}}if(["abstract.status","abstractcode.status"].includes(j)){const A=St(E),L=A?A.status??A.text??A.value:E,O=Date.parse(f||"");!Ns(this.snapshot.status)&&typeof L=="string"&&(!Number.isFinite(O)||O>=this.displayStatusAt)&&(Number.isFinite(O)&&(this.displayStatusAt=O),this.set({...this.snapshot,displayStatus:L.trim()}))}if(["abstract.tool_execution","abstractcode.tool_execution","abstract.tool_result","abstractcode.tool_result"].includes(j)){const A=vu(E);A&&this.addMessage({id:`event:${t}:${r}`,role:"system",title:"Tool activity",content:A,ts:f})}}const _=$x(n);if(c==="waiting"&&_&&!Ns(this.snapshot.status)&&!Ns(Ur(this.runStates.get(t)||null))&&(this.resolvedWaits.delete(`${t}:${vt(_.wait_key)}`),this.set({...this.snapshot,interaction:this.interactionWith({runId:t,wait:_,...vt(n.step_id)?{stepId:vt(n.step_id)}:{}})})),l==="tool_calls")for(const x of Nx(this.toolActivities,{runId:t,cursor:this.cursors.get(t)||0,record:n}))this.upsertTool(x);if(l==="resume"&&(u==null?void 0:u.resumed)===!0){const x=vt((y=St(o.payload))==null?void 0:y.wait_key);x&&this.resolvedWaits.add(`${t}:${x}`),((w=this.snapshot.interaction)==null?void 0:w.runId)===t&&(this.set({...this.snapshot,interaction:null}),this.refreshRunState(t,this.generation))}}foldStopEvidence(t,n,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(Hp(n).payload)||{},c=St(n.result),f=vt(u.name)||vt(c==null?void 0:c.name),_=St(u.payload!==void 0?u.payload:c==null?void 0:c.payload);f==="abstract.status"&&vt(_==null?void 0:_.killed_by)==="kill_switch"&&(this.forcedStop=_,l=!0)}l&&this.recomputeStop()}recomputeStop(){let t=null;this.forcedStop?t={phase:"forced",label:vt(this.forcedStop.text)||"Stop forced: inference killed",record:this.forcedStop}:this.stopRequested&&(t=this.snapshot.status==="cancelled"&&this.openLlmSteps.size===0?{phase:"stopped",label:"Stopped"}:{phase:"stopping",label:"Stopping…"});const n=this.snapshot.stop||null;((n==null?void 0:n.phase)!==(t==null?void 0:t.phase)||(n==null?void 0:n.label)!==(t==null?void 0:t.label))&&this.set({...this.snapshot,stop:t}),(t==null?void 0:t.phase)==="stopping"&&this.snapshot.status==="cancelled"&&this.followStop(this.generation)}async followStop(t){var n;if(!this.stopFollowing){this.stopFollowing=!0;try{let 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=dN(n)}catch(f){this.fail(f,!1);return}const o=`${r.run_id}:${r.call_id}`;if(uN(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 Ns(Ur(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:hN(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;ml(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),...ml(t)?{autoApproveTools:!1}:{},...n?{connection:"disconnected"}:{}})}newCommandId(){const t=globalThis.crypto;return t&&typeof t.randomUUID=="function"?t.randomUUID():`workflow-${Date.now()}-${Math.random().toString(36).slice(2)}`}updateRunState(t,n){var l;if(this.runStates.set(t,n),Ns(Ur(n))&&this.endLiveRepliesOfRun(t,Ur(n)),t!==this.rootRunId){Ns(Ur(n))&&((l=this.snapshot.interaction)==null?void 0:l.runId)===t?this.set({...this.snapshot,interaction:null}):this.adoptDurableWait(t,n);return}const r=Ur(n),o=Ns(r);if(o){const u=vu(n.output);u&&this.upsertFinal(t,u,Uy(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:H_(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&&!Ns(Ur(this.runStates.get(t)||null));){if(await this.waitForRetry(2e3),!this.live(n)||this.rootRunId!==t||Ns(Ur(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(ml(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 yN(e){const t=m.useMemo(()=>new gN(e.transport,{onAuthError:e.onAuthError,clientId:e.clientId,...e.liveRenderIntervalMs!==void 0?{liveRenderIntervalMs:e.liveRenderIntervalMs}:{}}),[e.transport,e.onAuthError,e.clientId,e.authScopeKey,e.liveRenderIntervalMs]),n=m.useSyncExternalStore(o=>t.subscribe(o),()=>t.getSnapshot(),()=>t.getSnapshot()),r=String(e.runId||"").trim();return m.useEffect(()=>{t.setToolApprovalPolicy(e.enabled===!1?{enabledTools:[],autoApproveTools:[]}:e.toolApprovalPolicy??null)},[t,e.toolApprovalPolicy,e.enabled]),m.useEffect(()=>{if(e.enabled===!1||!r){t.reset();return}return t.load(r),()=>t.reset()},[t,r,e.enabled]),{controller:t,snapshot:n}}function Ql(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function cr(e){return typeof e=="string"?e.trim():e==null?"":typeof e=="number"||typeof e=="boolean"?String(e):""}function qy(e){return["session","workflow","run","global"].includes(e)?e:null}function pl(e){return{scope:cr(e==null?void 0:e.scope).toLowerCase(),name:cr(e==null?void 0:e.name)||cr(e==null?void 0:e.event_name),scopeId:cr(e==null?void 0:e.scope_id)||cr(e==null?void 0:e.scopeId),sessionId:cr(e==null?void 0:e.session_id)||cr(e==null?void 0:e.sessionId),workflowId:cr(e==null?void 0:e.workflow_id)||cr(e==null?void 0:e.workflowId),runId:cr(e==null?void 0:e.run_id)||cr(e==null?void 0:e.runId)}}function wN(e,t){const n=e.wait,r=cr(n.wait_key),o=[pl(n),pl(Ql(n.details))];for(const l of t){if(l.runId!==e.runId)continue;const u=l.record,c=Ql(u.result),f=Ql(c==null?void 0:c.wait),_=Ql(u.effect),p=Ql(_==null?void 0:_.payload);cr(f==null?void 0:f.wait_key)!==r&&cr(p==null?void 0:p.wait_key)!==r||o.push(pl(u),pl(p),pl(Ql(p==null?void 0:p.details)),pl(f),pl(Ql(f==null?void 0:f.details)))}return o}function Y_(e,t){return t.scopeId?t.scopeId:e==="session"?t.sessionId:e==="workflow"?t.workflowId:e==="run"?t.runId:"global"}function Ax(e,t,n){return{scope:e,scopeId:t,name:n,...e==="session"?{sessionId:t}:{},...e==="workflow"?{workflowId:t}:{},...e==="run"?{runId:t}:{}}}function vN(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?Ax(t,n,o):null}function xN(e,t=[],n){if(!e)return{target:null,error:"No event wait is available."};const r=cr(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=qy(o[1]);if(!l)return{target:null,error:"The event wait uses an unsupported scope."};const u=wN(e,Array.isArray(t)?t:[]),c=new Map;for(const w of u){const x=qy(w.scope);if(!x||!w.name)continue;if(x!==l)return{target:null,error:"Event metadata conflicts with the canonical wait scope."};const k=`evt:${x}:`,j=`:${w.name}`;if(!r.startsWith(k)||!r.endsWith(j)||r.length<=k.length+j.length)return{target:null,error:"Event metadata does not exactly match the canonical wait key."};const E=r.slice(k.length,-j.length),A=Y_(x,w);if(A&&A!==E)return{target:null,error:"Event metadata conflicts with the canonical wait target."};const L=Ax(x,E,w.name);c.set(`${L.scope}\0${L.scopeId}\0${L.name}`,L)}if(c.size>1)return{target:null,error:"Multiple event targets match this wait; routing is unavailable."};if(c.size===1)return{target:[...c.values()][0]};const f=new Set;l==="run"&&f.add(e.runId),l==="global"&&f.add("global");for(const w of u){const x=Y_(l,w);x&&f.add(x)}if(cr(n==null?void 0:n.run_id)===e.runId){const w=pl(n||null),x=Y_(l,w);x&&f.add(x)}const p=[...f].map(w=>vN(r,l,w)).filter(w=>!!w),y=new Map(p.map(w=>[`${w.scope}\0${w.scopeId}\0${w.name}`,w]));return y.size===1?{target:[...y.values()][0]}:y.size>1?{target:null,error:"The event key is ambiguous for the available scope metadata."}:{target:null,error:"The gateway did not provide enough canonical event routing metadata."}}const Ag=e=>bt(`runs/${encodeURIComponent(e)}/workspace`);function bN(e){return Ag(e)}function jN(e,t){return`${Ag(e)}/files?${new URLSearchParams({path:t,recursive:"false"})}`}function SN(e,t){return`${Ag(e)}/content?${new URLSearchParams({path:t})}`}async function e_(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 kN(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 NN(e,t,n){const r=await e(bN(t),{signal:n});if(!r.ok)throw await e_(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 CN(e,t,n,r){const o=await e(jN(t,n),{signal:r});if(!o.ok)throw await e_(o,"The folder could not be listed");return kN(await o.json(),n)}async function EN(e,t,n,r){const o=await e(SN(t,n),{signal:r});if(!o.ok)throw await e_(o,"The file could not be read");return await o.blob()}async function $N(e,t,n,r){const o=await NN(e,t,r);return{where:o,listing:o.exists?await CN(e,t,n,r):null}}function AN(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 TN(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 MN(e){return[...e].sort((t,n)=>t.type===n.type?t.name.localeCompare(n.name):t.type==="dir"?-1:1)}function RN(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 LN=new Set(["image/png","image/jpeg","image/gif","image/webp","image/avif","image/bmp","application/pdf","text/plain","application/json"]);function IN(e){const t=String(e||"").split(";",1)[0].trim().toLowerCase();return LN.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 Tx(e,t,n){const r=n==="open"?IN(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 ON(e,t,n){const r=await e(hj(t),{signal:n.signal});if(!r.ok)throw await e_(r,`${n.name} could not be read`);Tx(await r.blob(),n.name,n.mode??"open")}function Mx(e){const{fetchGateway:t,runId:n}=e,[r,o]=m.useState({runId:n,path:""}),l=r.runId===n?r.path:"",[u,c]=m.useState(null),[f,_]=m.useState(""),[p,y]=m.useState(!!n),[w,x]=m.useState(""),[k,j]=m.useState(0);m.useEffect(()=>{if(!n)return;const L=new AbortController;return y(!0),_(""),(async()=>{try{const O=await $N(t,n,l,L.signal);L.signal.aborted||c({runId:n,...O})}catch(O){L.signal.aborted||_(String((O==null?void 0:O.message)||O))}finally{L.signal.aborted||y(!1)}})(),()=>L.abort()},[t,n,l,k,e.refreshKey]);const E=u&&u.runId===n?u:null,A=m.useCallback(async(L,O)=>{x(L.path),_("");try{Tx(await EN(t,n,L.path),L.name,O)}catch(M){_(String((M==null?void 0:M.message)||M))}finally{x("")}},[t,n]);return s.jsx(PN,{title:e.title,note:e.note,where:(E==null?void 0:E.where)??null,path:l,listing:(E==null?void 0:E.listing)??null,error:f,loading:p,fileBusy:w,selectedPath:e.selectedPath,className:e.className,onNavigate:L=>o({runId:n,path:L}),onRefresh:()=>j(L=>L+1),onFile:e.onSelectFile?void 0:(L,O)=>void A(L,O),onSelectFile:e.onSelectFile,onClose:e.onClose})}function PN(e){var r,o,l,u;const t=e.listing?RN(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(Ze,{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(Ze,{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(Ze,{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:AN(e.path).map((c,f,_)=>f===_.length-1?s.jsx("span",{"aria-current":"page",children:c.label},c.path):s.jsxs(ve.Fragment,{children:[s.jsx("button",{type:"button",className:"pc-ws__crumb",onClick:()=>e.onNavigate(c.path),children:c.label}),s.jsx("span",{className:"pc-ws__muted",children:" / "})]},c.path))}),e.error?s.jsx("div",{className:"pc-ws__error",role:"alert",children:e.error}):null,e.loading&&!e.listing?s.jsx("div",{className:"pc-ws__muted",role:"status",children:"Loading…"}):null,e.where&&!e.where.exists?s.jsx("div",{className:"pc-ws__muted",children:"The folder does not exist yet: nothing has been written."}):null,e.listing?e.listing.entries.length?s.jsx("ul",{className:"pc-ws__entries",children:MN(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(Ze,{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(Ze,{name:"file",size:14})," ",c.name]}):s.jsxs("span",{className:"pc-ws__name",children:[s.jsx(Ze,{name:"file",size:14})," ",c.name]}),s.jsx("span",{className:"pc-ws__size",children:TN(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(Ze,{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 Rx(e){return s.jsx(vx,{text:e,images:"link"})}const DN={trigger:"Trigger",answer:"Automation"};function FN(e){return s.jsx(Cg,{message:{id:`${e.runId}:${e.kind}`,role:e.role,content:e.text,title:DN[e.kind],runId:e.runId},images:"link"})}const zN={renderText:Rx,renderTurn:FN};function BN(e){const{fetchGateway:t,...n}=e,r=n.onOpenResource??(t?o=>ON(t,o.url,{name:o.name}):void 0);return s.jsx(WS,{...n,onOpenResource:r,...zN})}function UN(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},_=[...new Set(c.map(y=>String((y==null?void 0:y.name)||"tool")))],p=n.onPermissionsAll;return{id:o,kind:"tool-approval",title:`${c.length||"Requested"} ${c.length===1?"action needs":"actions need"} permission`,toolName:_.join(", ")||"the requested tools",description:"Review the targets below. Allow once approves this batch only.",detail:s.jsxs("div",{className:"pc-approval-summary",children:[s.jsx(jx,{tools:c.map((y,w)=>({id:String((y==null?void 0:y.call_id)||(y==null?void 0:y.id)||w),runId:e.runId,name:(y==null?void 0:y.name)||"Tool",arguments:y==null?void 0:y.arguments,status:"waiting"}))}),s.jsxs("details",{children:[s.jsx("summary",{children:"Review full tool arguments (JSON)"}),s.jsx(dr,{value:c.length?c:l})]})]}),approveLabel:"Allow once",denyLabel:"Deny",approveAllLabel:p?"Allow all enabled tools":void 0,approveAllDescription:p?"Sets permissions: all for this Gateway account, including future turns. Unchecked tools stay unavailable; explicit Ask overrides and Gateway restrictions remain enforced. Questions still need your answer.":void 0,onApproveAll:p?async()=>{await t.approveWithPolicyChange(f,()=>{p()})}:void 0,onApprove:async()=>{await t.approve(!0,f)},onDeny:async()=>{await t.approve(!1,f)}}}if(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=xN(e,n.records||[],n.currentRun??null),f=c.target,_=(f==null?void 0:f.name)||"";return{id:o,kind:"event-wait",title:f?"Waiting for an event":"Event routing unavailable",eventName:_,prompt:String(r.prompt||`This workflow will continue when “${_||"its trigger"}” arrives.`),description:f?"You can also send the expected event here.":`This event cannot be sent safely. ${c.error}`,initialPayload:"{}",payloadLabel:"Event data (JSON)",sendLabel:"Send event",onSend:async p=>{if(!f)throw new Error(c.error);const y=JSON.parse(p||"{}"),w={name:f.name,scope:f.scope,payload:y};f.scope==="session"?w.session_id=f.scopeId:f.scope==="workflow"?w.workflow_id=f.scopeId:f.scope==="run"&&(w.run_id=f.scopeId),await t.emitEvent(w)}}}return null}const WN="# 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- `llms.txt` format reference: https://llmstxt.org/\n\n## Documentation (start here)\n- [README](README.md): Install and quickstart\n- [Getting started](docs/getting-started.md): Run the UI and connect to a gateway; Ask about a run (whole conversation, History note when the 50k-token window drops older messages, error cards never sent back) vs the top-bar Assistant (one gateway session per conversation, New conversation, no tools)\n- [FAQ](docs/faq.md): Common questions (grounded in code), including the CLI `/api` session proxy, the About dialog, chat history windows and the tool-less Assistant\n- [Docs index](docs/README.md): What to read next\n- [Architecture](docs/architecture.md): Components, data flow, diagrams\n- [Configuration](docs/configuration.md): launch flags, serving under the gateway at /apps/observer/, UI settings, deployment patterns\n- [API](docs/api.md): Gateway endpoints used by the UI, including Runtime Activity run pages and canonical artifact envelope search/stats for Runtime Artifact Explorer\n- [Automations](docs/automations.md): Launch → Automate (what, when in UTC intervals, independent/growing context, tool approval), the Automations page (icon controls, Edit: the row's Edit opens the form — title, task, interval, context, tools —, 409 conflicts), runs as a conversation, answering waits by kind, the automation's files (browse, open, download through the gateway), Discuss as an in-page chat with a fork, automation tags on Board/Observe/System, legacy schedules and Recreate, the stub gateway\n- [Development](docs/development.md): Local dev, workspace deps, tests, build\n- [Security](docs/security.md): Trust boundaries and operational guidance\n- [Troubleshooting](docs/troubleshooting.md): Common issues and fixes (CORS, mixed content, 401 under `/api`, About shows the gateway unavailable, stale service worker, automations)\n\n## Key entrypoints (code)\n- [CLI](bin/cli.js) and [app server](bin/server.js): launch flags (`--gateway-url`, `--port`, `--host`, `--monitor-gpu`, `--entity-app-url`, `--gateway-dir`), mount-capable handler, session proxy, folder reveal (browsers on this machine only)\n- [App shell + pages](src/ui/app.tsx): settings, page routing, observe/launch flows, durable commands\n- [Gateway client](src/lib/gateway_client.ts): HTTP client + SSE ledger streaming (API source of truth)\n- [Automations rules + controller](src/ui/automations.ts): workflow choice (`@default`), create body, run tags, capability gate, legacy prefill, typed wait answers, page controller\n- [Automations page](src/ui/automations_page.tsx) and [Automate fields](src/ui/automate_form.tsx): the page, rows and the ui-kit `AutomationPanel` wiring; the When/Context/Tools fields\n- [Discussion chat](src/ui/automation_discussion.tsx): panel-chat `WorkflowChat` + `presentInteraction` over the gateway client; folders through panel-chat `WorkspaceBrowser` (`/runs/{id}/workspace*`)\n- [Automations stub gateway](scripts/automations_stub_server.mjs): dev/test stub serving the ui-kit fixtures\n- [Vite config](vite.config.ts): workspace aliases + dev session proxy and `/api` fallback proxy\n- [Package metadata](package.json): npm name/version, scripts, Node engine\n- [llms-full generator](scripts/generate-llms-full.mjs): defines which files are embedded into `llms-full.txt`\n\n## Ecosystem context\n- [AbstractFramework](https://github.com/lpalbou/AbstractFramework): ecosystem entrypoint and component map\n- [AbstractRuntime](https://github.com/lpalbou/abstractruntime): durable workflow runtime behind the gateway ledger\n- [AbstractCore](https://github.com/lpalbou/abstractcore): unified LLM + tools layer commonly used by workflows\n\n## Common tasks\n- Add/change a gateway capability: update `src/lib/gateway_client.ts` (source of truth) → update `docs/api.md` → run `npm test` + `npm run build`.\n- Change CLI behavior/config: update `bin/cli.js` / `bin/server.js` → update `docs/configuration.md` → run `npm run build`.\n- Update docs for agents: edit docs → regenerate `llms-full.txt` with `npm run llms:full`.\n\n## Optional (project meta)\n- [Changelog](CHANGELOG.md): Release notes\n- [Contributing](CONTRIBUTING.md): How to develop and submit changes\n- [Security policy](SECURITY.md): Responsible vulnerability reporting\n- [Acknowledgments](ACKNOWLEDGMENTS.md): Credits\n- [Code of conduct](CODE_OF_CONDUCT.md): Conduct expectations and reporting\n- [License](LICENSE): MIT license\n";function Os(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`id_${Date.now()}_${Math.random().toString(16).slice(2)}`}function qN(e,t){return[...e.filter(n=>!n.local_error),t].map(n=>({role:n.role,content:n.content}))}function Zh(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?Math.trunc(e):0}function HN(e){const t=Zh(e==null?void 0:e.dropped_messages);if(!e||t<=0)return null;const n=Zh(e.replayed_messages),r=Zh(e.dropped_tokens),o=Zh(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 Lx(e){const t=HN(e.history);return t?s.jsx(Cg,{message:{role:"system",level:"info",title:"History",content:t}}):null}const VN=1500,GN=12e4;function KN(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 YN=["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) ===",WN,"=== END DOCUMENTATION ==="].join(`
|
|
69
|
-
`),JN="observer-docs-assistant";function Hy(){return`${JN}:${Os()}`}function XN(e){return{prompt:e,system:YN,tools:[],use_session_history:!0,use_context:!0}}function ZN(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 QN(e,t,n=()=>{}){return async(r,o)=>{var f;const l=e(),u=await l.start_run(null,XN(r),{bundle_id:"basic-agent",session_id:t()}),c=Date.now();for(;;){if(await KN(VN,o.signal),Date.now()-c>GN)throw new Error("The assistant run timed out (120s). The run is still visible on the Observe page.");const _=await l.get_run(u),p=String((_==null?void 0:_.status)||"").trim().toLowerCase();if(p==="failed"||p==="cancelled"){const y=String(((f=_==null?void 0:_.error)==null?void 0:f.message)||(_==null?void 0:_.error)||"run "+p).slice(0,400);throw new Error(`The assistant run ${p}: ${y}`)}if(p==="completed"){n((_==null?void 0:_.session_history)??null);const y=await l.get_ledger(u,{after:0,limit:500,signal:o.signal});return ZN(y.items)||"(the run completed but produced no readable answer — inspect it on the Observe page)"}}}}function e1(e){const t=m.useRef(e.gateway);t.current=e.gateway;const n=m.useRef(Hy()),[r,o]=m.useState([]),[l,u]=m.useState(null),c=m.useMemo(()=>QN(()=>t.current,()=>n.current,u),[]),[f]=m.useState(void 0),_=()=>{n.current=Hy(),o([]),u(null)};return s.jsxs(bj,{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:_,title:"Start a new conversation (nothing earlier is replayed)",children:"New conversation"}),children:[s.jsx(Lx,{history:l}),s.jsx(Gk,{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 t1(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 n1(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 s1(e,t,n){return e<=0?-1:t<0?n?e-1:0:(t+(n?e-1:1))%e}const r1='a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';function i1(e){return typeof document>"u"?!1:Array.from(document.querySelectorAll('[role="dialog"][aria-modal="true"]')).some(t=>t!==e)}function o1(e){const[t,n]=m.useReducer(t1,!1),r=m.useRef(null),o=m.useRef(null),l=m.useRef(!1);return m.useEffect(()=>{n({type:"page_change"})},[e.page]),m.useEffect(()=>{n({type:"layout_change"})},[e.is_drawer]),m.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 _=p=>{if(p.key==="Escape"){n({type:"escape",default_prevented:p.defaultPrevented,other_modal_open:i1(o.current)});return}if(p.key!=="Tab"||!o.current)return;const y=Array.from(o.current.querySelectorAll(r1)).filter(x=>x.offsetParent!==null||x===document.activeElement),w=s1(y.length,y.indexOf(document.activeElement),p.shiftKey);w>=0&&(p.preventDefault(),y[w].focus())};return window.addEventListener("keydown",_),()=>window.removeEventListener("keydown",_)}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:n1(e.is_drawer,t)}}const a1="api/local/reveal",l1="sw.js";function c1(e){const t=l=>/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(l),n=l=>{const u=l.split("/").filter(Boolean);return u.length?u[u.length-1].trim():""},r=n(String(e.hash||"").replace(/^#/,""));if(t(r))return r;const o=n(String(e.pathname||""));return t(o)?o:""}const Am="@default:",Tm="abstractcode.agent.v1";function u1(e){const t=String(e||"").trim();if(t.startsWith(Am)){const r=t.slice(Am.length).trim();return r?{kind:"default",interface:r}:null}const n=t.indexOf(":");return n<=0||n>=t.length-1?null:{kind:"bundle",bundle_id:t.slice(0,n),flow_id:t.slice(n+1)}}function d1(e){return e?e.kind==="default"?`${Am}${e.interface}`:`${e.bundle_id}:${e.flow_id}`:""}function f1(e){const t={};for(const r of e)for(const o of r.agent_default_interfaces||[])o&&!t[o]&&(t[o]=r.label);return[Tm,...Object.keys(t).filter(r=>r!==Tm).sort()].map(r=>({interface:r,value:`${Am}${r}`,label:`Gateway default agent · ${r}${t[r]?` (now: ${t[r]})`:""}`}))}function h1(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 m1(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 _1={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 p1(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 g1="#launch/automate";function y1(e){const t=String(e||"").replace(/^#\/?/,"");if(t==="automations")return{page:"automations"};const n=/^launch(?:\/(once|automate))?$/.exec(t);return n?{page:"launch",mode:n[1]||"once"}:null}const Vp={when:"every",email:Uv,notify_email:!1,email_recipients:Sg,amount:"24",unit:"h",once_at:"",context:"independent",tool_approval:"auto",title:"",start_at:"",count:"",until:""},Vy={independent:"Each run starts fresh in its own session. Runs never see each other.",growing:"Each run is a new turn of one conversation and sees the previous runs. The history is bounded: the most recent 50,000 tokens of whole turns are replayed; older runs drop out."},Ix=["use_context"],w1="This choice also sets the workflow's Use Context input: the workflow always reads the history the automation gives it.";function Gp(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,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 v1(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:[Ht.not_set_up]};const n=m1(t.input_data),r=typeof n.prompt=="string"?n.prompt:"";delete n.prompt;for(const l of Ix)delete n[l];let o;try{o=h1(t.choice,t.bundle_ref_for,n)}catch(l){return{ok:!1,errors:[String((l==null?void 0:l.message)||l)]}}return Ip(Gp(e,r,t.email_usable===!0),{target:o,requestId:t.request_id})}function x1(e,t=!1){if(e.when==="email"){if(!t)return"";const l=Ip(Gp(e,"preview",!0),{target:{flow_id:"@default",interface:Tm},requestId:"preview"});return l.ok?`Runs ${qv(l.body.trigger.config)}.`:""}const n=Ip(Gp(e,"preview"),{target:{flow_id:"@default",interface:Tm},requestId:"preview"});if(!n.ok)return"";const r=n.body.trigger.config,o=Ov(r);return e.when==="once"?`Runs ${o}.`:`Runs ${o}, first run ${r.start_at?`at ${va(r.start_at)}`:"now"}.`}class b1{constructor(t){Hs(this,"key","");Hs(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 j1(e,t,n){const r=v1(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 _a(e){return typeof e=="string"?e:e??null}function S1(e){var t,n,r,o,l,u;return{run_id:String((e==null?void 0:e.run_id)||"").trim(),workflow_id:_a(e==null?void 0:e.workflow_id),status:typeof(e==null?void 0:e.status)=="string"?String(e.status):"",created_at:_a(e==null?void 0:e.created_at),updated_at:_a(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:_a(e==null?void 0:e.parent_run_id),session_id:_a(e==null?void 0:e.session_id),actor_id:_a(e==null?void 0:e.actor_id),session_kind:_a(e==null?void 0:e.session_kind),automation_id:_a(e==null?void 0:e.automation_id),role:_a(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 $f(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 Ox(e){const t=$f(e);return t==="occurrence"?typeof e.occurrence_index=="number"?`occurrence #${e.occurrence_index}`:"occurrence":t==="legacy"?"legacy schedule":t||""}function Gy(e){return String((e==null?void 0:e.role)||"").trim()==="controller"}function k1(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 lc(e){return e.legacy===!0||e.capabilities.includes("legacy")}function Px(e,t=Date.now()){const n=lc(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:xg(e.trigger),next_run:e.next_fire_at?`${va(e.next_fire_at)} (${Kv(e.next_fire_at,t)})`:e.status==="paused"?"none while paused":"none scheduled",current:Gv(e),state:e.status,last:r?r.excerpt:"",last_status:r?`#${r.index} ${r.status}${o}`:"no runs yet",attention:l?Yv(e):null,legacy:n}}function Dx(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 N1(e,t){const n=Nm(e,[],t),r=Dx(e),o=t?{enabled:!1,reason:"Working…"}:lc(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{pause:n.pause,resume:n.resume,run_now:n.run_now,edit:n.revise,archive:n.archive,discuss:o}}function C1(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?"Resume the schedule first.":"The schedule has ended."),open_run:{enabled:!0},recreate:{enabled:!0}}}function E1(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 $1=/^([1-9][0-9]*)([smhd])$/;function A1(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 T1(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={...Vp},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=$1.exec(f);let x=w?Number(w[1]):0,k=w?w[2]:"";k==="s"&&x%60===0&&(x=x/60,k="m"),k==="m"||k==="h"||k==="d"?(c.amount=String(x),c.unit=k):u.push(`The legacy interval "${f}" is not a whole number of minutes, hours or days; choose an interval.`)}typeof n.repeat_count=="number"&&n.repeat_count>=1&&(c.count=String(n.repeat_count));const _=A1(n.repeat_until);_&&(c.until=_),c.context=n.share_context===!1?"independent":"growing";const p=t&&typeof t.input_data=="object"&&t.input_data&&!Array.isArray(t.input_data)?t.input_data:{},y={};for(const[w,x]of Object.entries(p))w==="workflow_selection"||w.startsWith("_")||(y[w]=x);return{choice:{kind:"bundle",bundle_id:o,flow_id:l},input_data:y,form:c,notes:u}}const M1={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 R1(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 L1(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 Ky(e){return e.show_archived||e.status_filter==="archived"?e.items:e.items.filter(t=>t.status!=="archived")}function Yy(e){return e.items.filter(t=>t.status==="archived").length}function Tg(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 I1=3e4,Qh=50;function Qi(e){return kg(e)?e:{status:0,code:"client_error",message:e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}}function J_(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 O1{constructor(t,n,r=[1500,4e3]){Hs(this,"state",{...M1});Hs(this,"listeners",new Set);Hs(this,"list_seq",0);Hs(this,"detail_seq",0);Hs(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:Qh});if(t.push(...o.items),!o.next_cursor)return t;n=o.next_cursor}throw new Error("GET /api/gateway/automations kept returning next_cursor after 200 pages.")}async 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 Ym(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:Qi(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&&lc(l)){this.set({detail:{automation_id:n,summary:l,definition:null,occurrences:[],next_cursor:null,error:null}});return}const[u,c]=await Promise.all([this.client.getAutomation(n),this.client.listOccurrences(n,{limit:Qh})]);if(r!==this.detail_seq)return;this.set({detail:{automation_id:n,summary:l??u.summary,definition:u.definition,occurrences:J_([],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:Qi(l)})}}async reload_occurrences(t){const n=this.state.detail;if(!n||n.automation_id!==t||lc(n.summary))return;const[r,o]=await Promise.all([this.client.getAutomation(t),this.client.listOccurrences(t,{limit:Qh})]),l=this.state.detail;if(!l||l.automation_id!==t)return;const u=this.state.items.find(c=>c.automation_id===t);this.set({detail:{...l,summary:u??r.summary,definition:r.definition,occurrences:J_(l.occurrences,o.items),next_cursor:l.occurrences.length>o.items.length?l.next_cursor:o.next_cursor}})}async load_more(){const t=this.state.detail;if(!(!t||!t.next_cursor))try{const n=await this.client.listOccurrences(t.automation_id,{cursor:t.next_cursor,limit:Qh}),r=this.state.detail;if(!r||r.automation_id!==t.automation_id)return;this.set({detail:{...r,occurrences:J_(r.occurrences,n.items),next_cursor:n.next_cursor}})}catch(n){this.set({error:Qi(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 Qi(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 Qi(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:Tg(n,l)}),l}catch(l){throw Qi(l)}finally{this.set({busy:!1})}}async seen(t,n){try{await this.client.markSeen(t,n)}catch(r){throw Qi(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,L1(u.kind,o)),await this.after_change(t)}catch(u){throw Qi(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.`:`${P1[n]} sent to “${t.title}”.`,confirm_archive_id:""})}catch(o){this.set({error:Qi(o)})}}set_show_archived(t){this.set({show_archived:t})}ask_archive(t){this.set({confirm_archive_id:t})}async legacy_action(t,n){if(!lc(t))throw new Error("legacy_action on a non-legacy automation");const r=E1(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:`${r.type==="pause"?"Suspend":n==="legacy_run_now"?"Run now":"Resume"} sent to “${t.title}”.`}),await this.refresh()}catch(o){this.set({error:Qi(o)})}finally{this.set({busy:!1})}}report_error(t){this.set({error:Qi(t)})}clear_notice(){this.set({notice:"",error:null})}dismiss_notice(){this.state.notice&&this.set({notice:""})}dismiss_error(){this.state.error&&this.set({error:null})}}const P1={pause:"Pause",resume:"Resume",run_now:"Run now",archive:"Archive"};function D1(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:_1[e.mode]})]})}function F1(e){const t=e.form,n=Ym(e.email_status),r=t.when==="email"&&!n?"every":t.when,o=x1(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"})})," ",Ht.trigger_label]})]}),n?null:s.jsx(Op,{status:e.email_status,onOpenMyEmail:e.on_open_my_email}),r==="email"?s.jsx(NS,{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:pS.map(l=>l.when.kind==="every"?s.jsx("button",{type:"button",className:"btn btn_sm","data-preset":l.label,"aria-pressed":Number(t.amount)===l.when.amount&&t.unit===l.when.unit,disabled:e.disabled,onClick:()=>{l.when.kind==="every"&&e.on_change({amount:String(l.when.amount),unit:l.when.unit})},children:l.label},l.label):null)}),s.jsxs("div",{className:"automate_row",children:[s.jsx("span",{children:"Every"}),s.jsx("input",{type:"number",min:1,step:1,value:t.amount,disabled:e.disabled,"aria-label":"Interval amount",onChange:l=>e.on_change({amount:l.target.value})}),s.jsxs("select",{value:t.unit,disabled:e.disabled,"aria-label":"Interval unit",onChange:l=>e.on_change({unit:l.target.value}),children:[s.jsx("option",{value:"m",children:"minutes"}),s.jsx("option",{value:"h",children:"hours"}),s.jsx("option",{value:"d",children:"days"})]})]})]}):s.jsxs("label",{className:"automate_row",children:[s.jsx("span",{children:"Run once at (UTC)"}),s.jsx("input",{type:"datetime-local",value:t.once_at,disabled:e.disabled,onChange:l=>e.on_change({once_at:l.target.value})})]}),s.jsx("div",{className:"automate_preview","aria-live":"polite","data-preview":"true",children:o||(r==="email"?"Incomplete email trigger.":"Incomplete schedule.")})]}),s.jsxs("fieldset",{"data-section":"context",children:[s.jsx("legend",{children:"Context"}),s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:"automate_context",value:"independent",checked:t.context==="independent",disabled:e.disabled,onChange:()=>e.on_change({context:"independent"})})," ",s.jsx("strong",{children:"Independent"})," (default) — ",Vy.independent]}),s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:"automate_context",value:"growing",checked:t.context==="growing",disabled:e.disabled,onChange:()=>e.on_change({context:"growing"})})," ",s.jsx("strong",{children:"Growing"})," — ",Vy.growing]}),s.jsx("p",{className:"help_text muted","data-context-owns":"use_context",children:w1})]}),s.jsxs("fieldset",{"data-section":"tools",children:[s.jsx("legend",{children:"Tools"}),r==="email"?s.jsx("p",{className:"help_text muted","data-email-rule":"untrusted",children:Ht.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"})})," ",wS,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(Op,{status:e.email_status,onOpenMyEmail:e.on_open_my_email}),s.jsx(CS,{notifyEmail:n&&t.notify_email,onNotifyEmailChange:l=>e.on_change({notify_email:l}),recipients:n?t.email_recipients:Sg,onRecipientsChange:l=>e.on_change({email_recipients:l}),disabled:e.disabled||!n,idBase:"automate"})]})]})}function z1(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 B1="abstractobserver";function U1(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 W1(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 q1=new Set(["completed","failed","cancelled"]);function H1(e){var O;const{gateway:t,discussion:n}=e,r=m.useMemo(()=>U1(t),[t]),[o,l]=m.useState(((O=n.session)==null?void 0:O.run_id)||""),[u,c]=m.useState(""),[f,_]=m.useState(!1),[p,y]=m.useState(""),{controller:w,snapshot:x}=yN({transport:r,runId:o,enabled:e.connected,clientId:B1}),k=n.session,j=!!o&&!q1.has(x.status)&&x.status!=="idle",E=mN(x),A=async M=>{var X;const H=M.trim();if(H){_(!0);try{if(k){const Y=String(((X=x.run)==null?void 0:X.workflow_id)||""),Z=W1(Y),re=await t.start_run(Z.flow_id,{prompt:H},{bundle_id:Z.bundle_id,session_id:k.session_id});l(re)}else{const Y=await e.on_fork(n.automation_id,n.occurrence_index,H);l(Y.run_id)}c("")}finally{_(!1)}}},L=s.jsxs("div",{className:"discussion_head",children:[s.jsxs("button",{type:"button",className:"btn btn_sm","data-action":"discussion-back",onClick:e.on_close,title:`Back to ${n.automation_title}`,children:[s.jsx(Ze,{name:"chevronRight",size:13,className:"flip_x"})," ",n.automation_title]}),s.jsxs("span",{className:"discussion_title",children:[s.jsx(Ze,{name:"chat",size:15})," Discussion — fork at #",n.occurrence_index]}),s.jsx("span",{className:"pane_spacer"}),k?s.jsxs(s.Fragment,{children:[s.jsxs("button",{type:"button",className:`btn btn_sm${p==="own"?" active":""}`,"data-action":"discussion-files",onClick:()=>y(p==="own"?"":"own"),title:k.workspace_root,children:[s.jsx(Ze,{name:"folder",size:14})," Its files"]}),s.jsxs("button",{type:"button",className:`btn btn_sm${p==="mounted"?" active":""}`,"data-action":"automation-files",onClick:()=>y(p==="mounted"?"":"mounted"),title:k.mounted_workspace,children:[s.jsx(Ze,{name:"folder",size:14})," Automation files"]})]}):null]});return s.jsxs("section",{className:"pane auto_detail auto_discussion","data-discussion-session":(k==null?void 0:k.session_id)||void 0,children:[p&&k?s.jsx(Mx,{fetchGateway:t.fetch_gateway,runId:p==="own"?k.run_id:n.automation_id,title:p==="own"?"Discussion files":"Automation files",note:p==="own"?"The discussion's own writable folder.":"Mounted read-only for the discussion's file tools; nothing is written back.",onClose:()=>y(""),refreshKey:x.status}):null,s.jsx(aN,{header:L,messages:x.messages,draft:u,onDraftChange:c,onSend:A,busy:j||f,busyLabel:f?k?"Starting…":"Forking the automation…":E?"Waiting for you":"Working…",onCancel:j?()=>w.cancel():void 0,stopState:x.stop??null,disabled:!e.connected,interaction:UN(E,w,{records:x.records,currentRun:x.run}),placeholder:k?"Ask a follow-up…":`Ask about run #${n.occurrence_index}…`,emptyState:s.jsxs("div",{className:"help_text muted discussion_intro",children:["A new session that forks this automation at #",n.occurrence_index," with its history (runs 1–",n.occurrence_index,"). It works in its own writable workspace; the automation's files are mounted read-only for the file tools (shell commands are not sandboxed), and nothing is written back into the automation."]}),footer:x.error?s.jsx("div",{className:"observe_context_card error",role:"alert",children:x.error}):null})]})}const V1=5e3,G1=[["","All"],["active","Active"],["paused","Paused"],["completed","Completed"],["failed","Failed"],["archived","Archived"]],K1={pause:yl.pause,resume:yl.resume,run_now:yl.run_now,edit:yl.revise,archive:`${yl.archive}…`,discuss:yl.discuss},Y1={pause:no.pause,resume:no.resume,run_now:no.run_now,edit:no.revise,archive:no.archive,discuss:no.discuss},J1={pause:"pause",resume:"resume",run_now:"run_now",edit:"revise",archive:"archive",discuss:"discuss"},X1={legacy_pause:no.pause,legacy_resume:no.resume,legacy_run_now:no.run_now,open_run:"list",recreate:"refresh"};function Z1(e){return s.jsx("span",{className:"auto_state","data-field":"state",children:s.jsx(Zv,{status:e.status})})}function em(e){return s.jsxs("span",{className:`auto_fact${e.className?` ${e.className}`:""}`,"data-field":e.field,title:e.label,children:[s.jsx(Ze,{name:e.icon,size:12}),s.jsx("span",{children:e.children})]})}const Q1={legacy_pause:"Suspend",legacy_resume:"Resume",legacy_run_now:"Run now",open_run:"Open run",recreate:"Recreate as automation"};function eC(e){const t=e.summary,n=Px(t),r=e.state.selected_id===t.automation_id,o=e.state.busy,l=(f,_,p,y,w,x,k,j)=>s.jsxs("button",{type:"button",className:`btn btn_sm auto_action${k?" auto_action_icon":""}${w?` ${w}`:""}`,"data-action":f,disabled:!p.enabled,title:[k?_:null,p.enabled?null:p.reason,j].filter(Boolean).join(`
|
|
70
|
-
`)||void 0,"aria-label":k?_:void 0,"aria-description":j,onClick:y,children:[x?s.jsx(Ze,{name:x,size:13}):null,k?null:s.jsx("span",{children:_})]},f);let u;if(n.legacy){const f=C1(t,o);u=[t.status==="paused"?"legacy_resume":"legacy_pause","legacy_run_now","open_run","recreate"].map(p=>l(p,Q1[p],f[p],()=>e.h.on_legacy_action(t,p),void 0,X1[p]))}else{const f=N1(t,o);u=[t.status==="paused"?"resume":"pause","run_now","edit","discuss","archive"].map(p=>l(p,K1[p],f[p],()=>e.h.on_row_action(t,p),p==="archive"?"danger auto_action_end":void 0,Y1[p],p==="archive",Qv(J1[p],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(Z1,{status:n.state}),n.attention?s.jsxs("span",{className:"chip warn auto_row_attention","data-field":"attention",children:[s.jsx(Ze,{name:"warning",size:12})," ",n.attention]}):null]}),s.jsxs("span",{className:"auto_row_facts",children:[s.jsx(em,{icon:"refresh",field:"cadence",label:"When it runs",children:n.cadence}),n.current?s.jsx(em,{icon:"loader",field:"current",label:"Running now",className:"auto_row_current",children:n.current}):null,s.jsxs(em,{icon:"clock",field:"next",label:"Next run",children:["next: ",n.next_run]}),s.jsx(em,{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:Rx(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(Ze,{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(Ze,{name:"x",size:13}),s.jsx("span",{children:"Keep it"})]})]}):null]})}function tC(e){const t=e.state,n=t.error??t.list_error,r=n?Cm(n):null;return s.jsxs("section",{className:"pane auto_list","aria-label":"Automations",children:[s.jsxs("div",{className:"pane_header",children:[s.jsx("span",{className:"pane_title",children:"Automations"}),s.jsx("span",{className:"pane_count",children:Ky(t).length}),s.jsx("span",{className:"pane_spacer"}),s.jsx("select",{className:"seg_select",value:t.status_filter,onChange:o=>e.h.on_status_filter(o.target.value),"aria-label":"Filter by status",children:G1.map(([o,l])=>s.jsx("option",{value:o,children:l},o||"all"))}),s.jsx("button",{type:"button",className:"btn btn_sm auto_icon_btn","data-action":"refresh",onClick:e.h.on_refresh,disabled:t.loading||!e.available.available,title:"Refresh","aria-label":"Refresh",children:s.jsx(Ze,{name:t.loading?"loader":"refresh",size:14})}),s.jsxs("a",{className:`btn btn_sm auto_new${e.available.available?"":" disabled"}`,"data-action":"new",href:g1,"aria-disabled":!e.available.available,title:"New automation: opens Launch in Automate mode","aria-label":"New automation",onClick:o=>{o.preventDefault(),e.available.available&&e.h.on_new()},children:[s.jsx(Ze,{name:"plus",size:14}),s.jsx("span",{className:"auto_new_label",children:"New automation"})]})]}),s.jsxs("div",{className:"pane_body scroll",children:[e.available.available?null:s.jsx("div",{className:"warn_callout",role:"note","data-unavailable":"true",children:e.available.reason}),r?s.jsxs("div",{className:"observe_context_card error auto_list_error",role:"alert","data-code":n==null?void 0:n.code,children:[s.jsx(Ze,{name:"error",size:14}),s.jsxs("span",{className:"auto_list_msg",children:[s.jsx("strong",{children:r.title})," ",s.jsx("span",{children:r.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(Ze,{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(Ze,{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(Ze,{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,Yy(t)>0&&t.status_filter!=="archived"?s.jsxs("label",{className:"auto_show_archived help_text muted",children:[s.jsx("input",{type:"checkbox","data-action":"show-archived",checked:t.show_archived,onChange:o=>e.h.on_show_archived(o.target.checked)})," Show archived (",Yy(t),")"]}):null,s.jsx("ul",{className:"auto_rows",children:Ky(t).map(o=>s.jsx(eC,{summary:o,state:t,h:e.h},o.automation_id))})]})]})}function nC(e,t,n){const r=e.state,o=r.detail;if(!o||lc(o.summary))return null;const l=o.automation_id;return{summary:o.summary,...o.definition?{definition:o.definition}:{},occurrences:o.occurrences,triggerSources: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 _=await e.discuss(l,u,c,f==null?void 0:f.request_id);return t.on_open_session(_,Tg(u,_),u),_},onSeen:u=>e.seen(l,u),onLoadMore:()=>void e.load_more(),onOpenRun:u=>t.on_open_run(u),...t.on_open_workspace?{onOpenWorkspace:t.on_open_workspace}:{},...t.fetch_gateway?{fetchGateway:t.fetch_gateway}:{},onAnswerWait:(u,c,f)=>e.answer_wait(l,u,c,f),...n?{editOpen:n.open,onEditOpenChange:n.on_change}:{},emailStatus: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 sC(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 (",Pp.toLowerCase(),")."]})});if(lc(t.summary)){const r=Px(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=nC(e.ctl,e.host,e.edit);return s.jsxs("section",{className:"pane auto_detail",children:[e.browser??null,n?s.jsx(BN,{...n}):null]})}function rC(e,t){if(t==="edit")return{kind:"edit"};if(t!=="discuss")return{kind:"forward"};const n=Dx(e);return n===null?{kind:"none"}:{kind:"discuss",index:n}}function iC(e){const t=e.ctl,[n,r]=m.useState(null),o=j=>r(E=>({...j,opened:((E==null?void 0:E.opened)||0)+1})),[l,u]=m.useState(""),[c,f]=m.useState("");m.useSyncExternalStore(j=>t.subscribe(j),()=>t.state,()=>t.state);const[_,p]=m.useState(()=>typeof document>"u"||document.visibilityState!=="hidden");m.useEffect(()=>{const j=()=>p(document.visibilityState!=="hidden");return document.addEventListener("visibilitychange",j),()=>document.removeEventListener("visibilitychange",j)},[]),m.useEffect(()=>{if(!e.active||!_||!e.available.available)return;t.refresh();const j=window.setInterval(()=>void t.refresh(),I1);return()=>window.clearInterval(j)},[t,e.active,_,e.available.available]);const y=t.state.detail,w=t.state.notice;m.useEffect(()=>{if(!w)return;const j=window.setTimeout(()=>t.dismiss_notice(),V1);return()=>window.clearTimeout(j)},[t,w]);const x={...e.host,on_open_workspace:j=>u(E=>E===j?"":j),fetch_gateway:e.gateway.fetch_gateway,on_open_session:(j,E,A)=>{e.host.on_open_session(j,E,A),y&&o({automation_id:y.automation_id,automation_title:y.summary.title,occurrence_index:A,session:j})}},k={...e.h,on_select:j=>{r(null),u(""),j!==c&&f(""),e.h.on_select(j)},on_dismiss_notice:()=>t.dismiss_notice(),on_dismiss_error:()=>t.dismiss_error(),on_row_action:(j,E)=>{const A=rC(j,E);A.kind==="forward"?e.h.on_row_action(j,E):A.kind==="edit"?(r(null),u(""),f(j.automation_id),e.h.on_select(j.automation_id)):A.kind==="discuss"&&(e.h.on_select(j.automation_id),o({automation_id:j.automation_id,automation_title:j.title,occurrence_index:A.index}))}};return s.jsxs("div",{className:"page auto_page",children:[s.jsx(tC,{state:t.state,available:e.available,h:k}),n?s.jsx(H1,{gateway:e.gateway,discussion:n,connected:e.active,on_fork:async(j,E,A)=>{const L=await t.discuss(j,E,A);return e.host.on_open_session(L,Tg(E,L),E),r(O=>O&&{...O,session:L}),L},on_close:()=>r(null)},n.opened):s.jsx(sC,{ctl:t,host:x,h:k,edit:{open:!!y&&c===y.automation_id,on_change:j=>f(j&&y?y.automation_id:"")},browser:l?s.jsx(Mx,{fetchGateway:e.gateway.fetch_gateway,runId:l,title:l===(y==null?void 0:y.automation_id)?"Automation files":"Run files",onClose:()=>u("")}):void 0})]})}function oC(){const e="0.4.0".trim();if(!e)throw new Error("AbstractObserver: __APP_VERSION__ is not defined; the vite/vitest config must inject it from package.json");return e}function aC(){return Cj("abstractobserver",oC())}async function lC(e){let t;try{t=await e.gateway_about()}catch(n){return wy(null,n instanceof Error?n.message||n.name:String(n))}return wy(t)}class Mm{constructor(t){this._maxSize=Mm._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=Mm._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 cC(e){try{return new URL(String(e)),!0}catch{return!1}}function uC({baseUrl:e,endpoint:t}){const n=String(t||"api/gateway/host/metrics/gpu");return cC(n)?n:e&&String(e).trim()?new URL(n,String(e)).toString():n}async function dC({token:e,getToken:t}){if(typeof t=="function"){const n=await t();return n==null?"":String(n)}return e==null?"":String(e)}function fC({token:e}){const t=String(e||"").trim();return t?{Authorization:`Bearer ${t}`}:{}}function hC(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 mC({baseUrl:e,endpoint:t,token:n,getToken:r,signal:o,fetchImpl:l}={}){const u=uC({baseUrl:e,endpoint:t}),c=await dC({token:n,getToken:r}),f=l||globalThis.fetch;if(typeof f!="function")return{ok:!1,status:0,error:"fetch_unavailable",payload:null};let _;try{_=await f(u,{method:"GET",headers:{Accept:"application/json",...fC({token:c})},signal:o})}catch(y){return{ok:!1,status:0,error:"network_error",detail:y instanceof Error?y.message:String(y),payload:null}}let p=null;try{p=await _.json()}catch{p=null}return{ok:_.ok,status:_.status,error:_.ok?null:"http_error",payload:p}}const ff=Object.freeze({tickMs:1500,historySize:20,endpoint:"api/gateway/host/metrics/gpu",baseUrl:"",mode:"full"});function _C(e){return Number.isFinite(e)?Math.min(1,Math.max(0,e)):0}function Jy(e,t,n){return Number.isFinite(e)?Math.min(n,Math.max(t,e)):t}function Xy(e,t){const n=Number(e);return Number.isFinite(n)?Math.floor(n):t}function X_(e,t=1){const n=Jy(Number(e)/100,0,1),r=Math.round(140-140*n),o=Jy(Number(t),0,1);return o>=1?`hsl(${r} 85% 55%)`:`hsl(${r} 85% 55% / ${o})`}function Zy(e){const t={...ff,...e||{}};return t.tickMs=Math.max(250,Xy(t.tickMs,ff.tickMs)),t.historySize=Math.max(1,Math.min(200,Xy(t.historySize,ff.historySize))),t.endpoint=String(t.endpoint||ff.endpoint),t.baseUrl=String(t.baseUrl||""),t.mode=String(t.mode||ff.mode).trim().toLowerCase(),t.mode!=="icon"&&(t.mode="full"),t}function pC(){return`
|
|
71
|
-
:host{display:inline-block;font-family:ui-sans-serif,system-ui,-apple-system,Segoe UI,Roboto,Helvetica,Arial,"Apple Color Emoji","Segoe UI Emoji";line-height:1}
|
|
72
|
-
.wrap{box-sizing:border-box;display:flex;flex-direction:column;gap:6px;padding:var(--monitor-gpu-padding,8px 10px);border:1px solid var(--monitor-gpu-border,#2a2f3a);border-radius:var(--monitor-gpu-radius,10px);background:var(--monitor-gpu-bg,#0b1020);color:var(--monitor-gpu-fg,#e7eaf0);width:var(--monitor-gpu-width,180px)}
|
|
73
|
-
.wrap.icon{gap:var(--monitor-gpu-gap,4px);padding:var(--monitor-gpu-padding,4px);border-radius:var(--monitor-gpu-radius,999px);width:var(--monitor-gpu-width,30px);background:linear-gradient(180deg,rgba(255,255,255,0.08),rgba(255,255,255,0.02)),var(--monitor-gpu-bg,#0b1020);box-shadow:0 0 14px var(--monitor-gpu-accent-glow, rgba(76,195,255,0.18))}
|
|
74
|
-
.wrap.icon .top{display:none}
|
|
75
|
-
.wrap.icon .bars{height:var(--monitor-gpu-bars-height,18px)}
|
|
76
|
-
.top{display:flex;align-items:baseline;justify-content:space-between;gap:10px}
|
|
77
|
-
.label{font-size:var(--monitor-gpu-font-size,var(--font-size-sm,12px));opacity:.9}
|
|
78
|
-
.value{font-variant-numeric:tabular-nums;font-size:var(--monitor-gpu-font-size,var(--font-size-sm,12px));opacity:.95}
|
|
79
|
-
.bars{display:flex;align-items:flex-end;gap:2px;height:var(--monitor-gpu-bars-height,34px);overflow:hidden}
|
|
80
|
-
.bar{flex:1;min-width:0;border-radius:2px;background:var(--monitor-gpu-bar,#4cc3ff);height:2px;opacity:.9;transition:height .25s ease, background .25s ease, opacity .25s ease}
|
|
81
|
-
.bar.missing{background:var(--monitor-gpu-bar-missing,#62708a);opacity:.35}
|
|
82
|
-
.bar.error{background:var(--monitor-gpu-bar-error,#ff6b6b);opacity:.7}
|
|
83
|
-
.muted{opacity:.6}
|
|
84
|
-
`}class gC{constructor(t,n={}){if(!t||typeof t!="object")throw new TypeError("target element is required");this._target=t,this._opts=Zy(n),this._buffer=new Mm(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=pC();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=Zy({...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",X_(c,.95)),n.style.setProperty("--monitor-gpu-accent-glow",X_(c,.35))));const f=Array.from(o.children),_=Math.max(0,f.length-l.length),p=Math.max(2,o&&typeof o.clientHeight=="number"&&o.clientHeight>0?o.clientHeight:34);for(let y=0;y<f.length;y+=1){const w=f[y],x=y-_,k=x>=0?l[x]:null,j=Number.isFinite(k)?k:null,E=j==null?0:_C(j/100),A=Math.max(2,Math.min(p,Math.round(E*p)));w.style.height=`${A}px`,w.style.background=j==null?"":X_(j),w.className="bar",j==null&&w.classList.add("missing"),t&&w.classList.add("error")}}async _tick(){const t=String(this._token||"").trim(),n=this._getToken,r=!!t||typeof n=="function";this._abort&&this._abort.abort(),this._abort=new AbortController;const o=await mC({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=hC(l);if(!o.ok){if(this._buffer.push(null),this._render({error:!0}),o.status===401||o.status===403){const f=String(this._token||"").trim(),_=typeof this._getToken=="function";if(!r&&(!!f||_))return;this._stoppedForAuth=!0,this.stop()}else o.status===429&&(this.stop(),this._resumeTimer=setTimeout(()=>{this._resumeTimer=null,this._mounted&&this.start()},3e4));return}if(!u||c==null){this._buffer.push(null),this._render();return}this._buffer.push(c),this._render()}async _poll_loop(t){!this._running||t!==this._timer_gen||(await this._tick(),!(!this._running||t!==this._timer_gen)&&(this._timer=setTimeout(()=>{this._timer=null,this._poll_loop(t)},this._opts.tickMs)))}}function yC(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 gC(o,{}),this._upgradeProperty("token"),this._upgradeProperty("getToken"),this._upgradeProperty("mode")}_upgradeProperty(o){if(!Object.prototype.hasOwnProperty.call(this,o))return;const l=this[o];try{delete this[o]}catch{}this[o]=l}connectedCallback(){this._controller.setOptions(this._readAttrs());const o=()=>{this.isConnected&&this._controller.start()};typeof queueMicrotask=="function"?queueMicrotask(o):Promise.resolve().then(o)}disconnectedCallback(){this._controller.destroy()}attributeChangedCallback(){this._controller.setOptions(this._readAttrs())}_readAttrs(){const o=this.getAttribute("tick-ms"),l=this.getAttribute("history-size"),u=this.getAttribute("endpoint"),c=this.getAttribute("base-url"),f=this.getAttribute("mode");return{...o!=null?{tickMs:o}:{},...l!=null?{historySize:l}:{},...u!=null?{endpoint:u}:{},...c!=null?{baseUrl:c}:{},...f!=null?{mode:f}:{}}}set token(o){this._controller.token=o}get token(){return this._controller.token}set getToken(o){this._controller.getToken=o}get getToken(){return this._controller.getToken}set tickMs(o){this._controller.setOptions({tickMs:o})}get tickMs(){return this._controller.options.tickMs}set historySize(o){this._controller.setOptions({historySize:o})}get historySize(){return this._controller.options.historySize}set endpoint(o){this._controller.setOptions({endpoint:o})}get endpoint(){return this._controller.options.endpoint}set baseUrl(o){this._controller.setOptions({baseUrl:o})}get baseUrl(){return this._controller.options.baseUrl}set mode(o){this._controller.setOptions({mode:o})}get mode(){return this._controller.options.mode}}globalThis.customElements.define(e,n)}function jt(){return new Date().toISOString()}function wC(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}function Ps(e,t){try{const n=JSON.stringify(e);return typeof n!="string"?String(e):n.length<=t?n:`${n.slice(0,Math.max(0,t-1))}…`}catch{const n=String(e);return n.length<=t?n:`${n.slice(0,Math.max(0,t-1))}…`}}function ht(e,t){const n=typeof(t==null?void 0:t.max_chars)=="number"?t.max_chars:360,r=typeof(t==null?void 0:t.max_lines)=="number"?t.max_lines:2,l=String(e||"").replace(/\r\n/g,`
|
|
85
|
-
`).replace(/\r/g,`
|
|
86
|
-
`).split(`
|
|
87
|
-
`),u=l.slice(0,Math.max(1,r)).join(`
|
|
88
|
-
`),c=l.length>r,f=u.length>n?`${u.slice(0,Math.max(0,n-1))}…`:u;return c&&f===u?`${u}…`:f}function Lt(e,t){const n=String(e||"");return n.length<=t?n:`${n.slice(0,Math.max(0,t-1))}…`}function Z_(e){const t=String(e||"").trim();return t&&t.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")||"untitled"}function kn(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 vC(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 ya(e){const t=kn(e);return t===null?"—":vC(t)}function Qy(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 Mg(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 xa(e){const t=kn(e);return t===null?"—":new Date(t).toLocaleString()}function fn(...e){for(const t of e){const n=String(t??"").trim();if(n)return n}return""}function xC(...e){for(const t of e){const n=Number(t);if(Number.isFinite(n))return n}return null}function Ti(e){const t=String(e||"").trim().toLowerCase();return t==="completed"||t==="failed"||t==="cancelled"}function Du(e){const t=String(e||"").trim().toLowerCase();return t==="running"||t==="waiting"}function nc(e){return String((e==null?void 0:e.started_at)||(e==null?void 0:e.created_at)||"").trim()}function Fx(e){const t=String((e==null?void 0:e.status)||"").trim();return Ti(t)?String((e==null?void 0:e.finished_at)||(e==null?void 0:e.updated_at)||"").trim():""}function Rg(e,t=Date.now()){const n=kn(nc(e));if(n===null)return-1;const r=kn(Fx(e));return Math.max(0,(r!==null?r:t)-n)}function fc(e,t=Date.now()){return Mg(Rg(e,t))}function bC(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 Fu(e){return String(e||"").trim().toLowerCase()}function t_(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 jC(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 SC(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 kC(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 zx(e,t){var u,c,f,_,p;const n=Fu(e==null?void 0:e.content_type),r=t_(e),o=[e==null?void 0:e.semantic_kind,e==null?void 0:e.render_kind,e==null?void 0:e.task,(u=e==null?void 0:e.tags)==null?void 0:u.semantic_kind,(c=e==null?void 0:e.tags)==null?void 0:c.render_kind,(f=e==null?void 0:e.tags)==null?void 0:f.task,(_=e==null?void 0:e.tags)==null?void 0:_.kind,(p=e==null?void 0:e.tags)==null?void 0:p.type].map(y=>String(y||"").trim().toLowerCase()).filter(Boolean).join(" ");if(/(^|[^a-z0-9])(code|source_code|script|program|executable)([^a-z0-9]|$)/i.test(o)||n.includes("javascript")||n.includes("typescript")||n.includes("x-python")||n.includes("x-shellscript")||n.includes("x-rust")||n.includes("x-go")||n.includes("x-java")||n.includes("x-csrc")||n.includes("x-c++src")||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,`
|
|
89
|
-
`).replace(/\r/g,`
|
|
90
|
-
`).split(`
|
|
91
|
-
`);return Bx(l)}function NC(e){const n=String(e||"").replace(/\r\n/g,`
|
|
92
|
-
`).replace(/\r/g,`
|
|
93
|
-
`).split(`
|
|
94
|
-
`),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(`
|
|
95
|
-
`).trim();return!o.length&&!l?null:{metadata:o,body:l}}function CC(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 EC(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:Bx(e)}function Bx(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 $C(e){const t=String(e||"");if(!t.trim())return!1;const n=t.match(/\\[A-Za-z]{2,}\b/g)||[];if(n.length>=1&&/\\(?:setcctype|sectctype|documentclass|begin|end|maketitle|geq|leq|cite|ref|label)\b/.test(t)||n.length>=4)return!0;const o=t.replace(/\r\n/g,`
|
|
96
|
-
`).replace(/\r/g,`
|
|
97
|
-
`).split(`
|
|
98
|
-
`).map(f=>f.trim()).filter(Boolean).slice(0,80);if(o.length<12)return!1;const l=o.filter(f=>f.length<=28).length,u=o.filter(f=>/^[,.;:()†]+$/.test(f)).length;return o.filter(f=>/^(abstract\.?|introduction|references|appendix|figure\s+\d+|table\s+\d+)\b/i.test(f)).length>=2&&(l/o.length>=.45||u>=2)}function AC(e,t){var _;const n=String(t||""),r=jC(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,`
|
|
99
|
-
`).replace(/\r/g,`
|
|
100
|
-
`).split(`
|
|
101
|
-
`),l=o.map(p=>p.trim()).filter(Boolean);if(l.length<2||$C(n)||CC(o)||EC(o))return!1;const u=((_=n.match(/[A-Za-z][A-Za-z'-]+/g))==null?void 0:_.length)||0,c=o.filter(p=>!p.trim()).length,f=l.filter(p=>/[A-Za-z]{3,}/.test(p)&&p.length>=12).length;return u>=24&&f>=2&&(c>=1||l[0].length<=140)}function Ef(e){const t=Fu(e==null?void 0:e.modality),n=Fu(e==null?void 0:e.content_type),r=t_(e),o=SC(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")||zx(e,"")?"text":"binary"}function Rm(e,t){const n=Fu(e==null?void 0:e.content_type),r=t_(e),o=String(t||"").trim();return n.includes("html")||r.endsWith(".html")||r.endsWith(".htm")||kC(t)?"html":zx(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("["))&&Qm(o)!==null?"json":AC(e,t)?"markdown":"text"}function Lg(e,t=""){const n=Ef(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=Fu(e==null?void 0:e.modality),o=Fu(e==null?void 0:e.content_type),l=t_(e);return r==="document"||o.includes("pdf")||Cf(l,[".pdf",".doc",".docx",".ppt",".pptx",".xls",".xlsx"])?"document":"other"}return Rm(e,t)}function Q_(e){var _,p;const t=String(e||"").replace(/\r\n/g,`
|
|
102
|
-
`).replace(/\r/g,`
|
|
103
|
-
`).trim();if(!t)return"";const n=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]),r=t.match(/<!--[\s\S]*?-->|<!doctype\b[^>]*>|<!\[CDATA\[[\s\S]*?\]\]>|<\/?[A-Za-z][^>]*>|[^<]+/gi)||[t],o=[];let l=0,u="";const c=y=>" ".repeat(Math.max(0,y)),f=(y,w)=>{const x=y.match(/^(<\/?|<!)([^\s/>]+)([\s\S]*?)(\/?>)$/);if(!x||y.length<=120||y.startsWith("</")||y.startsWith("<!"))return[`${c(w)}${y.trim()}`];const k=(x[3]||"").trim();if(!k)return[`${c(w)}${y.trim()}`];const j=k.match(/[^\s="'<>`]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'<>`]+))?/g)||[k];return[`${c(w)}${x[1]}${x[2]}`,...j.map(E=>`${c(w+1)}${E.trim()}`),`${c(w)}${x[4]}`]};for(const y of r){const w=String(y||"");if(!w.trim())continue;const x=w.trim().toLowerCase();if(x.startsWith("</")){const j=((_=x.match(/^<\/\s*([a-z0-9:-]+)/))==null?void 0:_[1])||"";u&&j===u&&(u=""),l=Math.max(0,l-1),o.push(`${c(l)}${w.trim()}`);continue}if(w.trimStart().startsWith("<")){o.push(...f(w,l));const j=((p=x.match(/^<\s*([a-z0-9:-]+)/))==null?void 0:p[1])||"";/\/>\s*$/.test(w)||x.startsWith("<!")||n.has(j)||(l+=1,(j==="script"||j==="style")&&(u=j));continue}if(u){const j=w.trim();j&&o.push(...j.split(`
|
|
104
|
-
`).map(E=>`${c(l)}${E.trimEnd()}`));continue}const k=w.replace(/\s+/g," ").trim();k&&o.push(`${c(l)}${k}`)}return o.join(`
|
|
105
|
-
`)}function TC(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 Lm(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 Nl(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 MC=/^\s*<runtime_metadata>\s*([\s\S]*?)\s*<\/runtime_metadata>\s*/i;function Ig(e){const t=typeof e=="string"?e:String(e??""),n=MC.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 Ux(...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 Kp(e){if(e==null)return"";if(typeof e=="string")return e.trim();if(Array.isArray(e))return e.map(t=>Kp(t)).filter(Boolean).join(`
|
|
106
|
-
`).trim();if(typeof e=="object"){const t=e.text??e.content??e.message??e.value;if(t!==e){const n=Kp(t);if(n)return n}}return""}function Wx(e){const t=Ig(Kp(e));return{text:t.text,runtime_metadata:t.metadata}}function RC(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=Ig(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 _=Wx((c==null?void 0:c.content)??(c==null?void 0:c.text)??c);if(_.text)return{text:_.text,runtime_metadata:Ux(_.runtime_metadata,c!=null&&c.runtime_metadata&&typeof c.runtime_metadata=="object"?c.runtime_metadata:null,(o=c==null?void 0:c.metadata)!=null&&o.runtime_metadata&&typeof c.metadata.runtime_metadata=="object"?c.metadata.runtime_metadata:null)}}return{text:"",runtime_metadata:null}}function LC(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",_=Wx((c==null?void 0:c.content)??(c==null?void 0:c.text)??(c==null?void 0:c.message)??c),p=_.text;if(!p)continue;const y=String((c==null?void 0:c.ts)||(c==null?void 0:c.timestamp)||(c==null?void 0:c.created_at)||(c==null?void 0:c.time)||"").trim(),w=Ux(_.runtime_metadata,c!=null&&c.runtime_metadata&&typeof c.runtime_metadata=="object"?c.runtime_metadata:null,(u=c==null?void 0:c.metadata)!=null&&u.runtime_metadata&&typeof c.metadata.runtime_metadata=="object"?c.metadata.runtime_metadata:null);o.push({role:f,text:p,ts:y,runtime_metadata:w})}return o.slice(Math.max(0,o.length-Math.max(1,t)))}function qx(e){const t=String(e||"").trim().toLowerCase().replace(/\s+/g," ");return t==="please respond:"||t==="please respond"||t==="type response..."||t==="type response"}function IC(e){const t=e.map(n=>String((n==null?void 0:n.name)||"tool").trim()).filter(Boolean);return t.length?`${t.slice(0,3).join(", ")}${t.length>3?` +${t.length-3}`:""}`:""}const Hx="inferred from the call's arguments (regex heuristic) — not a declared risk tier; declared tiers replace this when the grant API ships";function Vx(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 Og(e,t){const n=String((e==null?void 0:e.reason)||"").trim().toLowerCase(),r=IC(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 Gx(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 Kx(e,t){const n=String((e==null?void 0:e.prompt)||"").trim(),r=Ig(n),o=RC(t);return r.text&&!qx(r.text)?{text:r.text,runtime_metadata:r.metadata}:o.text?o:{text:r.text||n,runtime_metadata:r.metadata}}function OC(e,t){return Kx(e,t).text}function PC(e,t){return e||String(t||"").trim()||{}}function Ci(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 Cl(e){const t=String(e.status||"unknown").trim()||"unknown";return s.jsx("span",{className:`run_status_pill ${Nl(t)}`,children:t})}function DC(e){var l;const t=String((e==null?void 0:e.status)||"").trim().toLowerCase();if(Ti(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?Og(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 Im(e){const t=e==null?void 0:e.error;return t?typeof t=="string"?ht(t,{max_chars:220,max_lines:2}):ht(Ps(t,400),{max_chars:220,max_lines:2}):""}function FC(e){const t=DC(e);if(t)return t;const n=Im(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":Ti(o)?"Terminal":"No current activity reported"}function Yx(e){return e!=null&&e.ref&&typeof e.ref=="object"?e.ref:e!=null&&e.artifact_ref&&typeof e.artifact_ref=="object"?e.artifact_ref:e!=null&&e.artifact&&typeof e.artifact=="object"?e.artifact:{}}function ew(e){const t=Yx(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=fn(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=fn(e==null?void 0:e.content_type,e==null?void 0:e.mime_type,e==null?void 0:e.mime,t==null?void 0:t.content_type,t==null?void 0:t.mime_type,t==null?void 0:t.mime,n==null?void 0:n.content_type,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 zC(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 BC(e,t){if(!e||typeof e!="object")return null;const n=zC(e),r=Yx(e),o=e!=null&&e.metadata&&typeof e.metadata=="object"?e.metadata:e!=null&&e.meta&&typeof e.meta=="object"?e.meta:{},l=n!=null&&n.descriptor&&typeof n.descriptor=="object"?n.descriptor:e!=null&&e.descriptor&&typeof e.descriptor=="object"?e.descriptor:{},u=fn(n.artifact_id,e.artifact_id,e.$artifact,e.id,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[M,H]of Object.entries(c)){const X=String(M||"").trim();X&&(f[X]=String(H??""))}const _=fn(n.filename,e.filename,r.filename,o.filename,f.filename,f.name,e.name,r.name),p=fn(n.source_path,e.source_path,r.source_path,o.source_path,e.path,r.path,f.path,f.source_path,f.file_path),y=fn(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=fn(n.render_kind,l.render_kind,e.render_kind,f.render_kind),x=fn(n.semantic_kind,l.semantic_kind,e.semantic_kind,f.semantic_kind,f.artifact_type),k=n.access&&typeof n.access=="object"?n.access:e.access&&typeof e.access=="object"?e.access:{},j=n.producer&&typeof n.producer=="object"?n.producer:e.producer&&typeof e.producer=="object"?e.producer:l.producer&&typeof l.producer=="object"?l.producer:{},E=n.provenance&&typeof n.provenance=="object"?n.provenance:e.provenance&&typeof e.provenance=="object"?e.provenance:l.provenance&&typeof l.provenance=="object"?l.provenance:{},A=n.generation&&typeof n.generation=="object"?n.generation:e.generation&&typeof e.generation=="object"?e.generation:l.generation&&typeof l.generation=="object"?l.generation:{},L=n.media&&typeof n.media=="object"?n.media:e.media&&typeof e.media=="object"?e.media:l.media&&typeof l.media=="object"?l.media:{},O=n.links&&typeof n.links=="object"?n.links:e.links&&typeof e.links=="object"?e.links:l.links&&typeof l.links=="object"?l.links:{};return{artifact_id:u,run_id:fn(n.run_id,e.run_id,r.run_id,o.run_id,f.run_id,E.run_id),content_type:y,modality:fn(n.modality,e.modality,l.modality,f.modality)||ew({...e,ref:r,metadata:o,tags:f}),semantic_kind:x||ew({...e,ref:r,metadata:o,tags:f}),render_kind:w||Lg({content_type:y,filename:_,source_path:p,modality:fn(n.modality,e.modality,f.modality),tags:f}),task:fn(n.task,l.task,e.task,f.task,f.provider_task),classification_source:fn(n.classification_source,l.classification_source,e.classification_source),session_id:fn(n.session_id,l.session_id,e.session_id,f.session_id),workflow_id:fn(n.workflow_id,l.workflow_id,e.workflow_id,f.workflow_id,f.workflow),node_id:fn(n.node_id,l.node_id,e.node_id,f.node_id,f.node),step_id:fn(n.step_id,l.step_id,e.step_id,f.step_id),effect_id:fn(n.effect_id,l.effect_id,e.effect_id,f.effect_id,f.effect_idempotency_key),turn_id:fn(n.turn_id,l.turn_id,e.turn_id,f.turn_id,f.turn),ledger_cursor:fn(n.ledger_cursor,l.ledger_cursor,e.ledger_cursor,f.ledger_cursor,f.step_cursor),parent_run_id:fn(n.parent_run_id,l.parent_run_id,e.parent_run_id,f.parent_run_id),actor_id:fn(n.actor_id,l.actor_id,e.actor_id,f.actor_id),title:fn(n.title,e.title,f.title,f.label,f.name),created_at:fn(n.created_at,e.created_at,r.created_at,o.created_at,f.created_at),size_bytes:xC(n.size_bytes,e.size_bytes,r.size_bytes,o.size_bytes,f.size_bytes),filename:_,source_path:p,sha256:fn(n.sha256,e.sha256,r.sha256,o.sha256,f.sha256),tags:f,producer:j,provenance:E,generation:A,media:L,source_refs:Array.isArray(n.source_refs)?n.source_refs:Array.isArray(e.source_refs)?e.source_refs:[],access:k,links:O,available_actions:Array.isArray(n.available_actions)?n.available_actions.map(String):Array.isArray(e.available_actions)?e.available_actions.map(String):[],provider_trace_available:!!(n.provider_trace_available??e.provider_trace_available),audit_available:!!(n.audit_available??e.audit_available),legacy_inferred:!!((n.legacy_inferred??e.legacy_inferred)||/(?:legacy|inferred|runtime_tags|runtime_mime)/i.test(fn(n.classification_source,l.classification_source,e.classification_source))),descriptor:l,source:t,raw:e}}function Yp(e){return e.filename||e.title||(e.source_path?e.source_path.split("/").filter(Boolean).slice(-1)[0]:"")||Lt(e.artifact_id,16)}function UC(e,t){if(t==="type")return Ru(e);if(t==="run")return e.run_id||"(no run)";if(t==="turn")return Jp(e);if(t==="node")return Mu(e)||"(node unknown)";if(t==="workflow")return Pg(e)||"(workflow unknown)";if(t==="location"){const o=(e.source_path||e.filename||"").split("/").filter(Boolean);return o.length>1?o.slice(0,-1).join("/"):"(root)"}if(t==="source")return Af(e)||e.source||"artifact";const n=kn(e.created_at);return n===null?"(unknown time)":new Date(n).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}function Pg(e){const t=(e==null?void 0:e.tags)||{};return String((e==null?void 0:e.workflow_id)||t.workflow_id||t.workflow||"").trim()}function Mu(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 Jp(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=Mu(e),o=kn(e==null?void 0:e.created_at),l=o===null?"unknown time":new Date(o).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}),u=e!=null&&e.run_id?Lt(String(e.run_id),10):"unknown run";return r?`${u} · ${r} · ${l}`:`${u} · ${l}`}function tw(e){if(!e)return"provenance unavailable";const t=[],n=Pg(e),r=Mu(e),o=Af(e),l=Jx(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 sc(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 Ru(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 WC(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 HC(e){return e==="oldest"?{order_by:"created_at",order:"asc"}:e==="size_desc"?{order_by:"size_bytes",order:"desc"}:e==="size_asc"?{order_by:"size_bytes",order:"asc"}:e==="last_access"?{order_by:"last_accessed_at",order:"desc"}:e==="turn"?{order_by:"turn",order:"asc"}:e==="type"?{order_by:"semantic_kind",order:"asc"}:{order_by:"created_at",order:"desc"}}function nw(e){const t=e!=null&&e.stats&&typeof e.stats=="object"?e.stats:{},n=t!=null&&t.facets&&typeof t.facets=="object"?t.facets:e!=null&&e.facets&&typeof e.facets=="object"?e.facets:{};return n&&typeof n=="object"?n:{}}function VC(e){const t=xa(e.created_at),n=ya(e.created_at);return t==="—"?"Created —":`${t}${n&&n!=="—"?` (${n})`:""}`}function sw(e){var o;const t=e.tags||{},n=String(((o=e.access)==null?void 0:o.last_accessed_at)||t.last_accessed_at||t.accessed_at||t.updated_at||e.created_at||"").trim(),r=xa(n);return r==="—"?"—":r}function rw(e){const t=e.tags||{},n=String(e.title||t.title||t.name||t.label||e.filename||"").trim();if(n)return n;const r=String(e.source_path||t.path||"").trim();if(r)return r.split("/").filter(Boolean).slice(-1)[0]||r;const o=Af(e),l=Ru(e);return o?`${l} ${o}`:`${l} artifact`}function Af(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 Jx(e){var r,o,l,u,c,f,_,p;if(!e)return"";const t=fn((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=fn((c=e.producer)==null?void 0:c.model,(f=e.producer)==null?void 0:f.model_id,(_=e.provenance)==null?void 0:_.model,(p=e.generation)==null?void 0:p.model);return t&&n?`${t} / ${n}`:t||n}function GC(e){var t,n,r,o;return e?fn((t=e.generation)==null?void 0:t.prompt,(n=e.generation)==null?void 0:n.input,(r=e.generation)==null?void 0:r.text,(o=e.provenance)==null?void 0:o.prompt):""}function iw(e){if(!e)return"";const t=e.media||{},n=Number(t.duration_s??t.duration_seconds??t.duration),r=Number(t.width??t.image_width??t.video_width),o=Number(t.height??t.image_height??t.video_height),l=Number(t.sample_rate??t.sample_rate_hz),u=Number(t.channels);if(Number.isFinite(n)&&n>0){const f=[`${n>=60?`${Math.floor(n/60)}m ${Math.round(n%60)}s`:`${n.toFixed(n>=10?1:2)}s`}`];return Number.isFinite(l)&&l>0&&f.push(`${Math.round(l/1e3)} kHz`),Number.isFinite(u)&&u>0&&f.push(`${u} ch`),f.join(" · ")}if(Number.isFinite(r)&&Number.isFinite(o)&&r>0&&o>0)return`${Math.round(r)} x ${Math.round(o)}`;const c=Number(t.page_count??t.pages);return Number.isFinite(c)&&c>0?`${Math.round(c)} pages`:""}function ow(e){return e.source_path||e.filename||""}function Om(e,t,n){const r=e.run_id&&t[e.run_id]||null;if(!r)return e;const o=Ci(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 Xp(e,t,n,r=""){const o=Om(e,t,n),l=Lg(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]||Ru(o)}function eo(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 tm(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 Wu(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 KC(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 Xx(e){if(!e||typeof e!="object")return"Ledger record";const t=String(e.node_id||"").trim(),n=String(e.status||"").trim(),r=KC(e),o=eo(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 xu(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):Ps(e,320),n=typeof e.duration=="number"?Number(e.duration):-1;return{text:t,duration:n}}return{text:Ps(e,320),duration:-1}}function Vf(e){var u,c,f,_,p,y,w,x,k;if(!e||typeof e!="object")return"";const t=String(((u=e==null?void 0:e.effect)==null?void 0:u.type)||"").trim(),n=e==null?void 0:e.result,r=j=>typeof j=="string"?j.trim():j==null?"":typeof j=="number"||typeof j=="boolean"?String(j):"",o=j=>{if(!j||typeof j!="object")return"";const E=j,A=[E.response,E.answer,E.message,E.text,E.content];for(const L of A){const O=r(L);if(O)return O}return""};if(t==="answer_user"){const j=r(n==null?void 0:n.message)||r((c=n==null?void 0:n.output)==null?void 0:c.message)||r((f=n==null?void 0:n.output)==null?void 0:f.response)||r((p=(_=e==null?void 0:e.effect)==null?void 0:_.payload)==null?void 0:p.message)||r((w=(y=e==null?void 0:e.effect)==null?void 0:y.payload)==null?void 0:w.text)||r((k=(x=e==null?void 0:e.effect)==null?void 0:x.payload)==null?void 0:k.content);if(j)return j}if(t==="llm_call"){const j=o(n)||r(n==null?void 0:n.output)||o(n==null?void 0:n.output)||r(n==null?void 0:n.response);if(j)return j}return r(n==null?void 0:n.output)||o(n==null?void 0:n.output)||o(n)||r(n==null?void 0:n.response)}function wm(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 YC(e){return!!(e&&String(e.status||"")==="waiting")}function Zx(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:{},_=(f==null?void 0:f.usage)||(f==null?void 0:f.token_usage)||{},p=typeof c.prompt=="string"?c.prompt:Array.isArray(c.messages)?Ps(c.messages,1800):"",y=typeof f.content=="string"?f.content:typeof f.response=="string"?f.response:typeof l.result=="string"?String(l.result):"",w=kn(l.started_at),x=kn(l.ended_at),k=Number(_.prompt_tokens??_.input_tokens??0)||0,j=Number(_.completion_tokens??_.output_tokens??0)||0;t.push({id:`${String(o.run_id||l.run_id||"")}:${o.cursor}`,cursor:Number(o.cursor||0),ts:String(l.ended_at||l.started_at||""),run_id:String(o.run_id||l.run_id||"").trim(),node_id:String(l.node_id||"").trim(),provider:String(c.provider||f.provider||f.runtime_provider||"").trim(),model:String(c.model||f.model||f.runtime_model||"").trim(),prompt_preview:ht(p,{max_chars:1200,max_lines:10}),response_preview:ht(y,{max_chars:1200,max_lines:10}),missing_response:!String(y||"").trim(),tokens:{prompt:k,completion:j,total:Number(_.total_tokens??k+j)||0},duration_ms:w!==null&&x!==null?Math.max(0,x-w):typeof f.gen_time=="number"?Number(f.gen_time)*1e3:null,status:String(l.status||"").trim(),error:l.error?Ps(l.error,500):"",raw:l})}return t.sort((o,l)=>(kn(l.ts)??0)-(kn(o.ts)??0))}function aw(e){const t=e.size||18,n=Ef(e.artifact),r=Lg(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 JC=2,XC=Number.MAX_SAFE_INTEGER;function ZC(e,t=120){const n=String(e||"").replace(/\s+/g," ").trim();return n.length<=t?n:`${n.slice(0,Math.max(0,t-1)).trimEnd()}…`}function QC(e){const t=String(e||"");if(typeof DOMParser>"u")return[{kind:"text",text:Q_(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(_=>({name:_.name,value:_.value})),f=Array.from(u.childNodes||[]).map(o).filter(Boolean);return{kind:"element",tag:u.tagName.toLowerCase(),attrs:c,children:f}}return null};if(n.documentElement){const l=o(n.documentElement);l&&r.push(l)}return r.length?r:[{kind:"text",text:Q_(t)||t}]}catch{return[{kind:"text",text:Q_(t)||t}]}}function ep(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 Qx(e){const t=e.node,n=e.depth*14,r=e.depth<e.collapseAfterDepth,[o,l]=m.useState(r);if(m.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(ep,{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(ep,{tag:t.tag,attrs:t.attrs}),!o&&u?s.jsxs("span",{className:"html-tree__summary_text",children:[" ",ZC(u.text)]}):null]}),o?s.jsxs("div",{className:"html-tree__children",children:[t.children.map((c,f)=>s.jsx(Qx,{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(ep,{tag:t.tag,attrs:[],closing:!0})})]}):null]})}function e2(e){const t=m.useMemo(()=>QC(e.text),[e.text]),[n,r]=m.useState({mode:"folded",version:0}),o=n.mode==="unfolded"?XC:JC;m.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(Qx,{node:u,depth:0,collapseAfterDepth:o,expansionMode:n.mode,expansionVersion:n.version},`root:${c}`))})]})}function t2(e){var r;const t=NC(e.text);if(!t)return s.jsx("div",{className:`${e.className} structured markdown_preview`,children:s.jsx(Ai,{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(Ai,{text:t.body||e.text})]})}function eb(e){const t=String(e.text||""),n=Rm(e.artifact,t);if(n==="json"){const r=Qm(t);if(r!==null)return s.jsx("div",{className:`${e.className} structured`,children:s.jsx(dr,{value:r,collapseAfterDepth:4,showCopy:!1})})}return n==="markdown"?s.jsx(t2,{text:t,className:e.className}):n==="html"?s.jsx(e2,{text:t,className:e.className}):s.jsx("pre",{className:`mono ${e.className}`,children:t})}function n2(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:Yp(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(eb,{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 Dg(e){const t=e==null?void 0:e.waiting;return t&&typeof t=="object"?t:null}function tb(e){const t=Dg(e);return String((t==null?void 0:t.reason)||(e==null?void 0:e.waiting_reason)||"").trim().toLowerCase()}function lw(e){return e?String(e.prompt||"").trim()||Array.isArray(e.choices)&&e.choices.length>0?!0:e.allow_free_text!==!1&&String(e.reason||"").trim().toLowerCase()==="user":!1}function s2(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 qu(e){const t=String((e==null?void 0:e.status)||"").trim().toLowerCase();if(Ti(t)||t!=="waiting")return"none";const n=Dg(e),r=tb(e);return Wu(n).length?"tool_approval":r==="until"||String((e==null?void 0:e.role)||"").trim()==="controller"?"scheduled":r==="subworkflow"?"subworkflow":r==="event"?lw(n)?"user_response":"external_event":r==="user"||lw(n)?"user_response":"unknown_wait"}function nb(e){const t=Dg(e),n=Wu(t),r=qu(e);return r==="tool_approval"?`Tool approval: ${s2(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 r2(e){const t=qu(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.":Ti(n)?"Open the ledger and artifacts for the final outcome.":"Open the run to inspect current activity."}function cw(e){const t=e==null?void 0:e.error;if(!t)return"";if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return String(t)}}function i2(e,t={}){const n=t.now_ms??Date.now(),r=t.workflow_label??"",o=String(e.status||"unknown").trim().toLowerCase()||"unknown",l=qu(e),u=Ti(o),c=Rg(e,n),f=kn(e.updated_at||e.created_at)??0,_=o==="running"&&c>=14400*1e3,p=nb(e)||cw(e)||(e.current_node?`Current node: ${e.current_node}`:o==="running"?"Running":u?"Terminal":"No current activity reported");let y="all";l==="tool_approval"?y="tool_approval":l==="user_response"?y="user_wait":l==="scheduled"?y="scheduled":l==="subworkflow"||l==="external_event"?y="subflows":o==="failed"?y="failed":o==="running"?y="running":u&&(y="finished");const w=l==="tool_approval"?0:l==="user_response"?1:l==="unknown_wait"?2:o==="failed"?3:_?4:o==="running"?5:l!=="none"?6:u?8:7,x=l==="tool_approval"||l==="user_response",k=l==="tool_approval"?"Open approval":l==="user_response"?"Open wait":"Open Observe",j=[e.run_id,e.workflow_id,r,e.session_id,e.parent_run_id,e.status,e.current_node,tb(e),p,cw(e)].join(" ").toLowerCase();return{run:e,run_id:String(e.run_id||"").trim(),status:o,wait_kind:l,queue:y,attention_rank:w,reason:p,expected_action:r2(e),action_label:k,search_text:j,is_terminal:u,needs_user_action:x,is_stale:_,duration_ms:c,updated_ms:f}}function o2(e,t={}){const n=t.now_ms??Date.now(),r=t.workflow_label_by_id??{};return e.map(o=>i2(o,{now_ms:n,workflow_label:r[String(o.workflow_id||"")]||String(o.workflow_id||"")}))}function a2(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 l2(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 c2(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 u2(e){const[t,n]=m.useState("attention"),[r,o]=m.useState(""),[l,u]=m.useState("attention"),[c,f]=m.useState(""),_=m.useMemo(()=>{const F={};for(const C of e.artifacts){const N=String(C.run_id||"").trim();N&&(F[N]=(F[N]||0)+1)}return F},[e.artifacts]),p=m.useMemo(()=>o2(e.runs,{workflow_label_by_id:e.workflow_label_by_id}),[e.runs,e.workflow_label_by_id]),y=m.useMemo(()=>a2(p),[p]),w=m.useMemo(()=>{const F=l2(p,{queue:t,query:r});return c2(F,l)},[p,t,r,l]),x=w.find(F=>String(F.run_id||"")===c)||w.find(F=>String(F.run_id||"")===e.selected_run_id)||w[0]||null,k=(x==null?void 0:x.run)||null,j=String((k==null?void 0:k.run_id)||"").trim(),E=String((k==null?void 0:k.session_id)||"").trim(),A=m.useMemo(()=>E?new Set(e.runs.filter(F=>String(F.session_id||"").trim()===E).map(F=>String(F.run_id||"").trim()).filter(Boolean)):new Set,[e.runs,E]),L=E?A.size:0,O=m.useMemo(()=>E?e.artifacts.filter(F=>String(F.session_id||"").trim()===E||A.has(String(F.run_id||"").trim())).length:0,[e.artifacts,E,A]),M=k!=null&&k.waiting&&typeof k.waiting=="object"?k.waiting:null,H=M?Wu(M):[],X=(x==null?void 0:x.reason)||(M?Og(M,H):""),Y=(x==null?void 0:x.expected_action)||(M?Gx(M,H):""),Z=M?OC(M,null):"",re=j&&_[j]||0,ie=Ti(k==null?void 0:k.status),ue=[{key:"attention",label:"Needs attention",count:y.attention},{key:"user_wait",label:"Needs my response",count:y.user_wait},{key:"tool_approval",label:"Tool approvals",count:y.tool_approval},{key:"running",label:"Running",count:y.running},{key:"failed",label:"Failed",count:y.failed},{key:"scheduled",label:"Scheduled",count:y.scheduled},{key:"subflows",label:"Subflows / external events",count:y.subflows},{key:"finished",label:"Finished",count:y.finished},{key:"all",label:"All loaded",count:y.all}];return s.jsxs("div",{className:"runtime_ops_layout",children:[s.jsxs("aside",{className:"pane runtime_ops_filters",children:[s.jsxs("div",{className:"pane_header runtime_ops_filter_header",children:[s.jsx("span",{className:"pane_title",children:"Queues"}),s.jsx("div",{className:"pane_spacer"}),s.jsxs("button",{className:"btn btn_icon",onClick:e.gateway_connected?e.on_refresh_runs:e.on_reconnect,children:[s.jsx(Ze,{name:"refresh",size:14}),e.gateway_connected?"Refresh":"Reconnect"]})]}),s.jsxs("div",{className:"pane_body scroll runtime_ops_queue_list",children:[ue.map(F=>s.jsxs("button",{className:`runtime_ops_filter ${t===F.key?"selected":""}`,"aria-pressed":t===F.key,onClick:()=>n(F.key),children:[s.jsx("span",{children:F.label}),s.jsx("strong",{children:F.count.toLocaleString()})]},F.key)),s.jsx("div",{className:"runtime_ops_hint",children:"Counts are for the loaded runtime page. Refine search or refresh when supervising large runtimes."})]})]}),s.jsxs("section",{className:"pane runtime_ops_table_panel",children:[s.jsxs("div",{className:"pane_header runtime_ops_list_header",children:[s.jsx("span",{className:"pane_title",children:"Runs"}),s.jsx("span",{className:"pane_count",children:w.length.toLocaleString()}),s.jsx("div",{className:"pane_spacer"}),s.jsx("input",{value:r,onChange:F=>o(F.target.value),placeholder:"Search workflow, run, node, status, error"}),s.jsxs("select",{className:"seg_select",value:l,onChange:F=>u(F.target.value),children:[s.jsx("option",{value:"attention",children:"Attention order"}),s.jsx("option",{value:"recent",children:"Latest event"}),s.jsx("option",{value:"oldest",children:"Oldest event"}),s.jsx("option",{value:"duration",children:"Longest duration"}),s.jsx("option",{value:"tokens",children:"Most tokens"}),s.jsx("option",{value:"workflow",children:"Workflow"})]})]}),s.jsxs("div",{className:"pane_body scroll runtime_ops_rows",children:[w.length?null:s.jsx("div",{className:"runtime_ops_empty",children:e.gateway_connected?"No runs match this queue.":"Gateway offline. Runtime activity cannot be loaded until the connection is restored."}),w.map(F=>{const C=F.run,N=String(C.run_id||"").trim(),P=_[N]||0;return s.jsxs("div",{className:`raised runtime_ops_row ${N===j?"selected":""}`,"aria-current":N===j?"true":void 0,tabIndex:0,onClick:()=>{f(N),e.on_select_run(N)},onKeyDown:D=>{(D.key==="Enter"||D.key===" ")&&(D.preventDefault(),f(N),e.on_select_run(N))},children:[s.jsxs("div",{className:"runtime_ops_row_top",children:[s.jsx("strong",{className:"runtime_ops_row_name",children:Ci(C,e.workflow_label_by_id)}),F.is_stale?s.jsx("span",{className:"chip warn",children:"stale"}):null,s.jsx(Cl,{status:C.status})]}),s.jsxs("div",{className:"runtime_ops_row_sub",children:[s.jsx("span",{className:"mono",children:Lt(N,18)}),s.jsx("span",{children:ya(C.updated_at||C.created_at)}),s.jsx("span",{children:fc(C)}),s.jsx("span",{className:"runtime_ops_row_reason",title:F.reason,children:F.reason})]}),s.jsxs("div",{className:"runtime_ops_row_foot",children:[s.jsxs("span",{className:"runtime_ops_row_facts",children:[s.jsxs("span",{children:[Number(C.llm_calls||0).toLocaleString()," llm"]}),s.jsxs("span",{children:[Number(C.tool_calls||0).toLocaleString()," tools"]}),s.jsxs("span",{children:[Number(C.tokens_total||0).toLocaleString()," tok"]}),s.jsxs("span",{children:[P.toLocaleString()," artifacts"]})]}),s.jsxs("div",{className:"runtime_ops_actions",children:[F.needs_user_action?s.jsx("button",{className:"btn primary",onClick:D=>{D.stopPropagation(),e.on_open_run(N)},children:F.action_label}):s.jsx("button",{className:"btn",onClick:D=>{D.stopPropagation(),e.on_open_run(N)},children:"Open"}),s.jsx("button",{className:"btn",onClick:D=>{D.stopPropagation(),e.on_open_ledger(N)},children:"Ledger"}),s.jsx("button",{className:"btn",onClick:D=>{D.stopPropagation(),e.on_select_run(N),e.on_open_logs()},children:"Logs"}),s.jsx("button",{className:"btn",onClick:D=>{D.stopPropagation(),e.on_filter_artifacts(N)},children:"Artifacts"})]})]})]},N)})]})]}),s.jsxs("aside",{className:"pane runtime_ops_inspector",children:[s.jsxs("div",{className:"pane_header",children:[s.jsx("span",{className:"pane_title",children:"Run inspector"}),k?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"pane_spacer"}),s.jsx(Cl,{status:k.status})]}):null]}),s.jsx("div",{className:"pane_body scroll runtime_ops_inspector_body",children:k?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"runtime_ops_inspector_head",children:[s.jsx("h3",{children:Ci(k,e.workflow_label_by_id)}),s.jsx("span",{className:"mono",children:Lt(j,28)})]}),s.jsxs("div",{className:"runtime_ops_decision",children:[s.jsx("strong",{children:(x==null?void 0:x.reason)||FC(k)}),s.jsx("span",{children:(x==null?void 0:x.expected_action)||(String(k.status||"").toLowerCase()==="waiting"?"This run is paused until the pending wait is resolved or the run is cancelled.":ie?"This run is terminal. Open the ledger for the narrative and final error/output.":"This run is active or recently updated. Use ledger/provider logs to inspect live work.")})]}),s.jsxs("div",{className:"artifact_detail_grid",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Started"}),s.jsx("strong",{children:xa(nc(k))})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Elapsed"}),s.jsx("strong",{children:fc(k)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Last event"}),s.jsx("strong",{children:xa(k.updated_at||k.created_at)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Session"}),s.jsx("strong",{className:"mono",children:k.session_id?Lt(String(k.session_id),18):"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Node"}),s.jsx("strong",{className:"mono",children:k.current_node||"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Visible artifacts"}),s.jsx("strong",{children:re.toLocaleString()})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Provider calls"}),s.jsx("strong",{children:Number(k.llm_calls||0).toLocaleString()})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Tokens"}),s.jsx("strong",{children:Number(k.tokens_total||0).toLocaleString()})]})]}),E?s.jsxs("section",{className:"runtime_ops_session_context",children:[s.jsxs("div",{children:[s.jsx("span",{className:"run_hero_eyebrow",children:"Session context"}),s.jsx("strong",{className:"mono",children:Lt(E,30)})]}),s.jsxs("div",{className:"runtime_ops_session_facts",children:[s.jsxs("span",{children:[L.toLocaleString()," loaded run",L===1?"":"s"]}),s.jsxs("span",{children:[O.toLocaleString()," visible artifact",O===1?"":"s"]})]}),s.jsxs("div",{className:"runtime_detail_actions compact",children:[s.jsx("button",{className:"btn",onClick:()=>e.on_filter_session_artifacts(E),children:"Open session artifacts"}),s.jsx("button",{className:"btn",onClick:()=>void dc(E),children:"Copy session id"})]})]}):null,M?s.jsxs("div",{className:"runtime_ops_wait_summary",children:[s.jsxs("div",{className:"runtime_ops_wait_header",children:[s.jsx("span",{className:"run_hero_eyebrow",children:"Blocked on"}),s.jsx("strong",{children:X})]}),s.jsx("p",{children:Y}),Z?s.jsxs("div",{className:"runtime_ops_wait_request",children:[s.jsx("span",{children:"Request"}),s.jsx(Ai,{text:Z})]}):s.jsx("div",{className:"runtime_ops_wait_request muted",children:"No explicit prompt is attached to this wait. Open Observe or the ledger for full run context before responding."}),H.length?s.jsx("div",{className:"runtime_ops_wait_tools",children:H.map((F,C)=>s.jsxs(ve.Fragment,{children:[s.jsx("span",{className:"chip mono warn",children:String((F==null?void 0:F.name)||"tool")}),Vx(F).map(N=>s.jsxs("span",{className:"chip muted",title:Hx,children:[N,"~"]},`${C}:${N}`))]},`${String((F==null?void 0:F.name)||"tool")}:${C}`))}):null,s.jsxs("details",{className:"runtime_raw_details",children:[s.jsx("summary",{className:"muted",children:"Raw wait payload"}),s.jsx(dr,{value:M,collapseAfterDepth:3,showCopy:!0})]})]}):null,Im(k)?s.jsx("div",{className:"warn_callout",children:Im(k)}):null,s.jsxs("div",{className:"runtime_detail_actions",children:[s.jsx("button",{className:"btn primary",onClick:()=>e.on_open_run(j),children:"Open Observe"}),s.jsx("button",{className:"btn",onClick:()=>e.on_open_ledger(j),children:"Open ledger"}),s.jsx("button",{className:"btn",onClick:()=>e.on_filter_artifacts(j),children:"Open artifacts"}),s.jsx("button",{className:"btn",onClick:e.on_open_logs,children:"Open logs"}),s.jsx("button",{className:"btn",onClick:()=>void dc(j),children:"Copy run id"})]})]}):s.jsx("div",{className:"empty_state_inline",children:"Select a run to inspect why it is active or blocked."})})]})]})}function d2(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=m.useMemo(()=>new Set(e.type_filters),[e.type_filters]),l=Math.max(0,Number(e.artifact_total_count||0)),u=!!e.query.trim()||e.type_filters.length>0||e.date_filter!=="all"||e.scope!=="all"||!!e.artifact_run_filter.trim(),c=Math.max(1,Number(e.artifact_page_size||500)),f=Math.max(1,Math.ceil(l/c)),_=Math.min(Math.max(0,Number(e.artifact_page||0)),f-1),p=l?_*c+1:0,y=Math.min(l,_*c+e.artifacts.length),w=m.useMemo(()=>{const C={},N=e.artifact_type_facets&&Object.keys(e.artifact_type_facets).length?e.artifact_type_facets:e.artifact_facets,P=(N==null?void 0:N.semantic_kind)||{},D=(N==null?void 0:N.render_kind)||{};for(const ne of n)C[ne]=Number(P[ne]||D[ne]||0);return C.audio=Number(P.audio||0),C.other=Number(P.other||0)+Number(P.artifact||0)+Number(P.binary||0)+Number(P["(none)"]||0),C},[e.artifact_facets,e.artifact_type_facets]),x=C=>{const N=new Set(o);N.has(C)?N.delete(C):N.add(C),e.on_type_filters_change(Array.from(N.values()))},k=m.useMemo(()=>{const C={waiting:[],running:[],failed:[],cancelled:[],completed:[],other:[]};for(const N of e.runs){const P=String(N.status||"").trim().toLowerCase();P==="waiting"?C.waiting.push(N):P==="running"?C.running.push(N):P==="failed"?C.failed.push(N):P==="cancelled"?C.cancelled.push(N):P==="completed"?C.completed.push(N):C.other.push(N)}return C},[e.runs]),j=t!=null&&t.run_id&&e.run_by_id[t.run_id]||null,E=e.artifact_run_filter?Ci(e.run_by_id[e.artifact_run_filter],e.workflow_label_by_id):"",A=m.useMemo(()=>{var P;const C=new Set,N=((P=e.artifact_facets)==null?void 0:P.run_id)||{};for(const D of Object.keys(N))D&&D!=="(none)"&&C.add(D);for(const D of e.artifacts)D.run_id&&C.add(D.run_id);for(const D of e.active_runs)D.run_id&&C.add(String(D.run_id));return Array.from(C).map(D=>e.run_by_id[D]||{run_id:D,workflow_id:null,status:"",created_at:null,updated_at:null}).sort((D,ne)=>{const B=Du(D.status)?0:1,z=Du(ne.status)?0:1;if(B!==z)return B-z;const G=kn(D.updated_at||D.created_at)??0;return(kn(ne.updated_at||ne.created_at)??0)-G}).slice(0,160)},[e.artifacts,e.active_runs,e.run_by_id,e.artifact_facets]),L=C=>{e.on_artifact_run_filter_change(C),e.on_session_filter_change(""),e.on_scope_change(C?"run":"all")},O=C=>e.gateway_connected?Math.max(0,Number(C||0)).toLocaleString():"—",M=e.selected_run_id&&e.run_by_id[e.selected_run_id]||null,H=m.useMemo(()=>{const C=e.runtime_log_query.trim().toLowerCase(),N=e.runtime_ledger_log_items||[];return C?N.filter(P=>{var B,z;const D=P.record||{};return[P.cursor,D.run_id,D.node_id,D.status,(B=D.effect)==null?void 0:B.type,D.started_at,D.ended_at,Ps(((z=D.effect)==null?void 0:z.payload)??{},900),Ps(D.result??{},900)].join(" ").toLowerCase().includes(C)}):N},[e.runtime_ledger_log_items,e.runtime_log_query]),X=m.useMemo(()=>{const C=e.runtime_log_query.trim().toLowerCase(),N=Zx(e.runtime_ledger_log_items);return C?N.filter(P=>[P.provider,P.model,P.run_id,P.node_id,P.status,P.error,P.prompt_preview,P.response_preview,P.tokens.prompt,P.tokens.completion,P.tokens.total].join(" ").toLowerCase().includes(C)):N},[e.runtime_ledger_log_items,e.runtime_log_query]),Y=X.reduce((C,N)=>C+(Number(N.tokens.total)||0),0),Z=X.filter(C=>C.missing_response||C.error).length,re=m.useMemo(()=>{const C=e.runtime_log_query.trim().toLowerCase(),N=String(e.audit_log_text||"").replace(/\r\n/g,`
|
|
107
|
-
`).replace(/\r/g,`
|
|
108
|
-
`).split(`
|
|
109
|
-
`).filter(Boolean);return C?N.filter(P=>P.toLowerCase().includes(C)):N},[e.audit_log_text,e.runtime_log_query]),ie=e.runtime_log_source==="run_ledger"||e.runtime_log_source==="provider_calls",ue=e.runtime_log_source==="run_ledger"?"Selected Run Ledger":e.runtime_log_source==="provider_calls"?"Provider Calls":"Gateway HTTP Audit",F=e.runtime_log_source==="run_ledger"?"Runtime execution records for the selected workflow run.":e.runtime_log_source==="provider_calls"?"Model/provider call records extracted from the selected run ledger.":"Global Gateway HTTP/audit tail. This is system activity, not artifact provenance.";return s.jsxs("div",{className:"page runtime_page",children:[s.jsxs("section",{className:"runtime_header",children:[s.jsxs("div",{children:[s.jsx("div",{className:"run_hero_eyebrow",children:"System"}),s.jsx("h2",{children:e.tab==="activity"?"Activity monitor":e.tab==="artifacts"?"Artifact explorer":e.tab==="memory"?"Active memory":"Logs"}),s.jsxs("div",{className:"run_hero_meta",children:[s.jsx("span",{className:`status_pill ${e.gateway_connected?"ok":"warn"}`,children:e.gateway_connected?"gateway connected":"gateway offline"}),e.tab==="artifacts"&&e.artifact_run_filter?s.jsxs("span",{className:"chip muted",children:["filtered run ",s.jsx("span",{className:"mono",children:Lt(e.artifact_run_filter,18)})]}):null,e.session_id?s.jsxs("span",{className:"chip muted",children:["session ",s.jsx("span",{className:"mono",children:Lt(e.session_id,18)})]}):null]})]}),s.jsxs("div",{className:"metric_grid compact runtime_header_metrics",children:[s.jsxs("div",{className:"metric_tile",children:[s.jsx("span",{children:"Waiting"}),s.jsx("strong",{children:O(k.waiting.length)})]}),s.jsxs("div",{className:"metric_tile",children:[s.jsx("span",{children:"Running"}),s.jsx("strong",{children:O(k.running.length)})]}),s.jsxs("div",{className:"metric_tile",children:[s.jsx("span",{children:"Failed"}),s.jsx("strong",{children:O(k.failed.length)})]}),s.jsxs("div",{className:"metric_tile",children:[s.jsxs("span",{children:["Artifacts",u?" (filtered)":""]}),s.jsx("strong",{children:O(l)})]})]})]}),s.jsx("nav",{className:"runtime_mode_tabs",role:"tablist","aria-label":"System sections",children:["activity","artifacts","memory","logs"].map(C=>s.jsxs("button",{role:"tab","aria-selected":e.tab===C,className:`runtime_mode_tab ${e.tab===C?"active":""}`,onClick:()=>e.on_tab_change(C),children:[s.jsx(Ze,{name:C==="activity"?"history":C==="artifacts"?"download":C==="memory"?"agent":"terminal",size:14}),s.jsx("span",{children:C==="activity"?"Activity":C==="artifacts"?"Artifacts":C==="memory"?"Memory":"Logs"})]},C))}),e.gateway_connected?null:s.jsxs("div",{className:"runtime_offline_banner",role:"status",children:[s.jsxs("div",{children:[s.jsx("strong",{children:"Gateway offline"}),s.jsx("span",{children:"Activity, artifacts, memory, and logs are unavailable until the gateway reconnects."})]}),s.jsxs("div",{children:[s.jsx("button",{className:"btn primary",onClick:e.on_reconnect,children:"Reconnect"}),s.jsx("button",{className:"btn",onClick:e.on_open_settings,children:"Settings"})]})]}),e.error?s.jsx("div",{className:"warn_callout",children:e.error}):null,e.tab==="activity"?s.jsx(u2,{gateway_connected:e.gateway_connected,runs:e.runs,artifacts:e.artifacts,selected_run_id:e.selected_run_id,workflow_label_by_id:e.workflow_label_by_id,on_select_run:e.on_select_run,on_open_run:e.on_open_run,on_open_ledger:e.on_open_ledger,on_refresh_runs:e.on_refresh_runs,on_reconnect:e.on_reconnect,on_open_logs:()=>e.on_tab_change("logs"),on_filter_artifacts:C=>{L(C),e.on_select_run(C),e.on_tab_change("artifacts")},on_filter_session_artifacts:C=>{C&&(e.on_artifact_run_filter_change(""),e.on_session_filter_change(C),e.on_scope_change("session"),e.on_tab_change("artifacts"))}}):null,e.tab==="memory"?e.memory_panel?s.jsx("div",{className:"runtime_memory_panel",children:e.memory_panel}):s.jsx("div",{className:"empty_state_inline",children:"The memory explorer needs a gateway connection — sign in to browse knowledge-graph assertions."}):null,e.tab==="artifacts"?s.jsxs(s.Fragment,{children:[s.jsxs("section",{className:"pane runtime_artifact_toolbar","aria-label":"Find artifacts",children:[s.jsxs("div",{className:"runtime_artifact_toolbar_top",children:[s.jsxs("label",{className:"artifact_filter_field artifact_filter_search",children:[s.jsx("span",{children:"Search"}),s.jsx("input",{value:e.query,onChange:C=>e.on_query_change(C.target.value),placeholder:"title, path, hash, run, workflow, tag"})]}),s.jsxs("label",{className:"artifact_filter_field",children:[s.jsx("span",{children:"Scope"}),s.jsxs("select",{className:"seg_select",value:e.scope,onChange:C=>{const N=C.target.value;N!=="run"&&e.on_artifact_run_filter_change(""),N==="session"?e.on_session_filter_change(e.session_id):e.on_session_filter_change(""),e.on_scope_change(N)},children:[s.jsx("option",{value:"all",children:"All runtime"}),s.jsx("option",{value:"session",children:"This session"}),s.jsx("option",{value:"run",children:"Selected run"})]})]}),s.jsxs("label",{className:"artifact_filter_field",children:[s.jsx("span",{children:"Group"}),s.jsxs("select",{className:"seg_select",value:e.group_by,onChange:C=>e.on_group_by_change(C.target.value),children:[s.jsx("option",{value:"type",children:"Type"}),s.jsx("option",{value:"time",children:"Date"}),s.jsx("option",{value:"turn",children:"Turn"}),s.jsx("option",{value:"node",children:"Node"}),s.jsx("option",{value:"workflow",children:"Workflow"}),s.jsx("option",{value:"run",children:"Run"}),s.jsx("option",{value:"location",children:"Location"}),s.jsx("option",{value:"source",children:"Source"})]})]}),s.jsxs("label",{className:"artifact_filter_field",children:[s.jsx("span",{children:"Sort"}),s.jsxs("select",{className:"seg_select",value:e.sort_by,onChange:C=>e.on_sort_by_change(C.target.value),children:[s.jsx("option",{value:"newest",children:"Newest"}),s.jsx("option",{value:"oldest",children:"Oldest"}),s.jsx("option",{value:"last_access",children:"Last accessed"}),s.jsx("option",{value:"turn",children:"Turn order"}),s.jsx("option",{value:"type",children:"Type"}),s.jsx("option",{value:"size_desc",children:"Largest"}),s.jsx("option",{value:"size_asc",children:"Smallest"})]})]}),s.jsxs("button",{className:"btn btn_icon",onClick:e.on_refresh_artifacts,disabled:!e.gateway_connected||e.loading,children:[s.jsx(Ze,{name:"refresh",size:14}),e.loading?"Loading…":"Refresh"]})]}),s.jsxs("div",{className:"artifact_filter_section",children:[s.jsxs("div",{className:"artifact_filter_label",children:["Type ",s.jsx("span",{className:"muted",children:"OR"})]}),s.jsxs("div",{className:"artifact_filter_chips",role:"group","aria-label":"Artifact type filters combine with OR",children:[n.map(C=>{const N=o.has(C),P=w[C]||0,D=WC(C);return s.jsxs("button",{type:"button","aria-pressed":N,"aria-label":`${N?"Remove":"Add"} ${D} artifact type filter. Type filters combine with OR.`,title:`${N?"Remove":"Add"} ${D}. Type filters combine with OR.`,className:`artifact_filter_chip ${N?"active":""}`,onClick:()=>x(C),children:[s.jsx("span",{children:D}),s.jsx("span",{className:"artifact_chip_count",children:e.gateway_connected?P.toLocaleString():"—"})]},C)}),e.type_filters.length?s.jsx("button",{type:"button",className:"artifact_filter_chip clear",onClick:()=>e.on_type_filters_change([]),children:"Clear types"}):null]})]}),s.jsxs("div",{className:"artifact_filter_section",children:[s.jsx("div",{className:"artifact_filter_label",children:"Date"}),s.jsx("div",{className:"artifact_filter_chips",role:"group","aria-label":"Artifact date filters",children:r.map(C=>s.jsx("button",{type:"button","aria-pressed":e.date_filter===C.value,className:`artifact_filter_chip ${e.date_filter===C.value?"active":""}`,onClick:()=>e.on_date_filter_change(C.value),children:C.label},C.value))})]})]}),s.jsx("div",{className:"artifact_scope_banner",children:e.artifact_run_filter?s.jsxs(s.Fragment,{children:["Showing artifacts for ",s.jsx("strong",{children:E||Lt(e.artifact_run_filter,18)}),".",s.jsx("button",{className:"btn",onClick:()=>L(""),children:"Show all"})]}):s.jsxs(s.Fragment,{children:["Showing artifacts across the selected runtime scope. Select a run to filter the inventory. ",e.artifact_total_bytes?s.jsxs("span",{className:"mono muted",children:["Total size ",sc(e.artifact_total_bytes)]}):null]})}),s.jsxs("div",{className:"runtime_artifacts_layout",children:[s.jsxs("aside",{className:"pane artifact_filter_rail",children:[s.jsxs("div",{className:"pane_header",children:[s.jsx("span",{className:"pane_title",children:"Runs"}),s.jsx("span",{className:"pane_count",children:A.length.toLocaleString()})]}),s.jsxs("div",{className:"pane_body scroll artifact_filter_rail_list",children:[s.jsxs("button",{className:`artifact_filter_run ${e.artifact_run_filter?"":"selected"}`,onClick:()=>L(""),children:[s.jsx("strong",{children:"All artifacts"}),s.jsx("span",{children:e.gateway_connected?`${l.toLocaleString()} match${l===1?"":"es"}`:"counts unavailable"})]}),A.map(C=>{const N=String(C.run_id||"").trim(),P=N===e.artifact_run_filter||N===(t==null?void 0:t.run_id);return s.jsxs("button",{className:`artifact_filter_run ${P?"selected":""}`,onClick:()=>L(N),title:N,children:[s.jsx("strong",{children:Ci(C,e.workflow_label_by_id)}),s.jsx("span",{className:"mono",children:Lt(N,15)}),s.jsx("span",{children:fc(C)})]},N)})]})]}),s.jsxs("section",{className:"pane runtime_artifact_browser",children:[s.jsxs("div",{className:"pane_header artifact_browser_header",children:[s.jsx("span",{className:"pane_title",children:"Artifacts"}),s.jsx("span",{className:"pane_count",children:l?`${p.toLocaleString()}-${y.toLocaleString()} of ${l.toLocaleString()}`:"0 items"}),s.jsx("div",{className:"pane_spacer"}),f>1?s.jsxs("div",{className:"artifact_pagination","aria-label":"Artifact pages",children:[s.jsx("button",{className:"btn",onClick:()=>e.on_artifact_page_change(0),disabled:_<=0,children:"First"}),s.jsx("button",{className:"btn",onClick:()=>e.on_artifact_page_change(_-1),disabled:_<=0,children:"Prev"}),s.jsxs("span",{className:"muted artifact_page_label",children:["Page ",(_+1).toLocaleString()," / ",f.toLocaleString()]}),s.jsx("button",{className:"btn",onClick:()=>e.on_artifact_page_change(_+1),disabled:_>=f-1,children:"Next"}),s.jsx("button",{className:"btn",onClick:()=>e.on_artifact_page_change(f-1),disabled:_>=f-1,children:"Last"})]}):null]}),s.jsxs("div",{className:"pane_body scroll artifact_browser_body",children:[e.artifact_groups.length?null:s.jsx("div",{className:"empty_state_inline",children:e.gateway_connected?"No artifacts match the current filters.":"Gateway offline. Artifact inventory cannot be loaded until the connection is restored."}),s.jsx("div",{className:"artifact_group_list",children:e.artifact_groups.map(C=>s.jsxs("section",{className:"artifact_group",children:[s.jsxs("div",{className:"artifact_group_header",children:[s.jsx("span",{children:C.key}),s.jsx("span",{className:"artifact_group_count",children:C.items.length})]}),C.items.map(N=>{var z;const P=N.run_id&&e.run_by_id[N.run_id]||null,D=P?Ci(P,e.workflow_label_by_id):Pg(N),ne=iw(N),B=Number(((z=N.access)==null?void 0:z.access_count)||0)||0;return s.jsxs("button",{className:`artifact_row ${(t==null?void 0:t.artifact_id)===N.artifact_id?"selected":""}`,onClick:()=>{e.on_select_artifact(N.artifact_id),N.run_id&&e.on_select_run(N.run_id)},title:N.artifact_id,children:[s.jsx(aw,{artifact:N,size:18}),s.jsxs("div",{className:"artifact_row_main",children:[s.jsxs("div",{className:"artifact_row_title",children:[s.jsx("strong",{children:rw(Om(N,e.run_by_id,e.workflow_label_by_id))}),s.jsx("span",{className:"artifact_type_badge",children:Ru(N)}),N.render_kind&&N.render_kind!==N.semantic_kind?s.jsx("span",{className:"artifact_type_badge muted",children:N.render_kind}):null,N.legacy_inferred?s.jsx("span",{className:"artifact_type_badge inferred",children:"legacy inferred"}):null]}),s.jsxs("div",{className:"artifact_row_facts",children:[s.jsxs("span",{children:[s.jsx("b",{children:"Created"})," ",VC(N)]}),s.jsxs("span",{children:[s.jsx("b",{children:"Size"})," ",sc(N.size_bytes)]}),s.jsxs("span",{children:[s.jsx("b",{children:"Last seen"})," ",sw(N)]}),B?s.jsxs("span",{children:[s.jsx("b",{children:"Accesses"})," ",B.toLocaleString()]}):null,ne?s.jsxs("span",{children:[s.jsx("b",{children:"Media"})," ",ne]}):null,N.content_type?s.jsxs("span",{children:[s.jsx("b",{children:"MIME"})," ",N.content_type]}):null]}),s.jsxs("div",{className:"artifact_row_facts secondary",children:[D?s.jsxs("span",{children:[s.jsx("b",{children:"Workflow"})," ",D]}):null,N.run_id?s.jsxs("span",{className:"mono",children:[s.jsx("b",{children:"Run"})," ",Lt(N.run_id,13)]}):null,s.jsxs("span",{children:[s.jsx("b",{children:"Turn"})," ",Jp(N)]}),Mu(N)?s.jsxs("span",{className:"mono",children:[s.jsx("b",{children:"Node"})," ",Mu(N)]}):null,Af(N)?s.jsxs("span",{children:[s.jsx("b",{children:"Source"})," ",Af(N)]}):null]}),s.jsxs("div",{className:"artifact_row_facts tertiary",children:[s.jsxs("span",{className:"mono",children:[s.jsx("b",{children:"ID"})," ",Lt(N.artifact_id,22)]}),s.jsxs("span",{children:[s.jsx("b",{children:"Provenance"})," ",tw(N)]})]}),ow(N)?s.jsx("div",{className:"artifact_row_path mono",children:ow(N)}):null]})]},N.artifact_id)})]},C.key))})]})]}),s.jsx("aside",{className:"runtime_detail",children:s.jsxs("section",{className:"overview_panel runtime_artifact_detail",children:[s.jsxs("div",{className:"overview_panel_header",children:[s.jsx("h3",{children:"Artifact Detail"}),t?s.jsx("span",{className:"chip mono muted",children:e.embedded_preview.render_kind?Xp(t,e.run_by_id,e.workflow_label_by_id,e.embedded_preview.text):Xp(t,e.run_by_id,e.workflow_label_by_id)}):null]}),t?s.jsxs(s.Fragment,{children:[(()=>{var z,G,T,Q,K,J,oe;const C=GC(t),N=Jx(t),P=iw(t),D=Number(((z=t.access)==null?void 0:z.access_count)||0)||0,ne=fn((G=t.links)==null?void 0:G.provider_trace,(T=t.links)==null?void 0:T.provider_trace_url,(Q=t.links)==null?void 0:Q.provider_trace_id),B=fn((K=t.links)==null?void 0:K.audit,(J=t.links)==null?void 0:J.audit_tail,(oe=t.links)==null?void 0:oe.audit_url);return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"artifact_detail_header",children:[s.jsx(aw,{artifact:t,size:22}),s.jsxs("div",{children:[s.jsx("div",{className:"artifact_detail_title",children:rw(Om(t,e.run_by_id,e.workflow_label_by_id))}),s.jsxs("div",{className:"artifact_detail_subtitle",children:[Ru(t)," • ",t.render_kind||e.embedded_preview.render_kind||t.modality||"artifact"," • ",t.content_type||"unknown MIME"," • ",sc(t.size_bytes),t.legacy_inferred?" • legacy inferred":""]})]})]}),s.jsx(n2,{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:Ru(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:xa(t.created_at)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Size"}),s.jsx("strong",{children:sc(t.size_bytes)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Last seen"}),s.jsx("strong",{children:sw(t)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Accesses"}),s.jsx("strong",{children:D?D.toLocaleString():"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Run"}),s.jsx("strong",{className:"mono",children:t.run_id?Lt(t.run_id,24):"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Workflow"}),s.jsx("strong",{children:j?Ci(j,e.workflow_label_by_id):"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Turn"}),s.jsx("strong",{children:Jp(t)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Node"}),s.jsx("strong",{className:"mono",children:Mu(t)||"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Provider/model"}),s.jsx("strong",{children:N||"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Media facts"}),s.jsx("strong",{children:P||"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Trace"}),s.jsx("strong",{children:t.provider_trace_available?"available":"not recorded"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Provenance"}),s.jsx("strong",{children:tw(t)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Artifact id"}),s.jsx("strong",{className:"mono",children:Lt(t.artifact_id,30)})]}),t.sha256?s.jsxs("div",{children:[s.jsx("span",{children:"sha256"}),s.jsx("strong",{className:"mono",children:Lt(t.sha256,30)})]}):null]}),C?s.jsxs("div",{className:"artifact_provenance_panel",children:[s.jsx("div",{className:"artifact_filter_label",children:"Generation prompt / input"}),s.jsx("div",{className:"artifact_prompt_text",children:C})]}):s.jsxs("div",{className:"artifact_provenance_panel muted",children:[s.jsx("div",{className:"artifact_filter_label",children:"Generation prompt / input"}),s.jsx("div",{className:"artifact_prompt_text",children:"Generation prompt not recorded by the runtime artifact descriptor."})]}),Object.keys(t.generation||{}).length||Object.keys(t.producer||{}).length?s.jsxs("details",{className:"runtime_raw_details",children:[s.jsx("summary",{className:"mono muted",children:"Generation and producer metadata"}),s.jsx(dr,{value:{generation:t.generation,producer:t.producer,source_refs:t.source_refs},collapseAfterDepth:3,showCopy:!0})]}):null,t.source_path?s.jsx("div",{className:"artifact_detail_path mono",children:t.source_path}):null,s.jsxs("div",{className:"runtime_detail_actions",children:[s.jsx("button",{className:"btn primary",onClick:()=>e.on_preview_artifact(t),disabled:!t.run_id,children:e.embedded_preview.render_kind==="html"?"Open as web page":"Open full preview"}),s.jsx("button",{className:"btn",onClick:()=>e.on_download_artifact(t),disabled:!t.run_id,children:"Download"}),s.jsx("button",{className:"btn",onClick:()=>L(t.run_id),disabled:!t.run_id,children:"Show run artifacts"}),s.jsx("button",{className:"btn",onClick:()=>e.on_open_run(t.run_id),disabled:!t.run_id,children:"Open in Observe"}),s.jsx("button",{className:"btn",onClick:()=>e.on_open_ledger(t.run_id),disabled:!t.run_id,children:"Open run ledger"}),s.jsx("button",{className:"btn",onClick:()=>{ne&&window.open(ne,"_blank","noopener,noreferrer")},disabled:!ne,children:"Open provider trace"}),s.jsx("button",{className:"btn",onClick:()=>{B?window.open(B,"_blank","noopener,noreferrer"):e.on_tab_change("logs")},disabled:!B&&!t.audit_available,children:"Open audit trail"}),s.jsx("button",{className:"btn",onClick:()=>void dc(t.artifact_id),disabled:!t.artifact_id,children:"Copy artifact id"})]})]})})(),s.jsxs("details",{className:"runtime_raw_details",children:[s.jsx("summary",{className:"mono muted",children:"Raw metadata"}),s.jsx(dr,{value:t.raw,collapseAfterDepth:3,showCopy:!0})]})]}):s.jsx("div",{className:"empty_state_inline",children:"Select an artifact to inspect metadata, preview, or download content."})]})})]})]}):null,e.tab==="logs"?s.jsxs("section",{className:"overview_panel runtime_logs_panel",children:[s.jsxs("div",{className:"overview_panel_header",children:[s.jsxs("div",{children:[s.jsx("h3",{children:ue}),s.jsx("div",{className:"mono muted",children:F})]}),s.jsxs("div",{className:"actions",style:{marginTop:0},children:[ie&&e.runtime_ledger_log_meta?s.jsx("span",{className:"mono muted",children:e.runtime_ledger_log_meta}):null,e.runtime_log_source==="gateway_audit"&&e.audit_log_meta?s.jsx("span",{className:"mono muted",children:e.audit_log_meta}):null,s.jsxs("button",{className:"btn btn_icon",onClick:()=>{ie?e.on_refresh_runtime_ledger(e.selected_run_id):e.on_refresh_audit()},disabled:ie?e.runtime_ledger_log_loading:e.audit_log_loading,children:[s.jsx(Ze,{name:"refresh",size:14}),ie?e.runtime_ledger_log_loading?"Loading…":"Refresh":e.audit_log_loading?"Loading…":"Refresh"]})]})]}),s.jsxs("div",{className:"runtime_log_toolbar",children:[s.jsxs("div",{className:"seg_toggle mono",children:[s.jsx("button",{className:`seg_btn ${e.runtime_log_source==="run_ledger"?"active":""}`,onClick:()=>e.on_runtime_log_source_change("run_ledger"),children:"Run ledger"}),s.jsx("button",{className:`seg_btn ${e.runtime_log_source==="provider_calls"?"active":""}`,onClick:()=>e.on_runtime_log_source_change("provider_calls"),children:"Provider calls"}),s.jsx("button",{className:`seg_btn ${e.runtime_log_source==="gateway_audit"?"active":""}`,onClick:()=>e.on_runtime_log_source_change("gateway_audit"),children:"Gateway audit"})]}),s.jsx("input",{className:"mono",value:e.runtime_log_query,onChange:C=>e.on_runtime_log_query_change(C.target.value),placeholder:"Search node, status, effect, payload, error"})]}),e.runtime_log_source==="run_ledger"?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"runtime_log_context",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Selected run"}),s.jsx("strong",{children:M?Ci(M,e.workflow_label_by_id):e.selected_run_id?Lt(e.selected_run_id,24):"No run selected"}),e.selected_run_id?s.jsx("em",{className:"mono",children:Lt(e.selected_run_id,34)}):null]}),s.jsxs("div",{children:[s.jsx("span",{children:"Session"}),s.jsx("strong",{className:"mono",children:M!=null&&M.session_id?Lt(String(M.session_id),28):e.session_id?Lt(e.session_id,28):"—"})]}),s.jsxs("div",{className:"runtime_log_context_actions",children:[s.jsx("button",{className:"btn",onClick:()=>e.on_open_run(e.selected_run_id),disabled:!e.selected_run_id,children:"Open Observe"}),s.jsx("button",{className:"btn",onClick:()=>L(e.selected_run_id),disabled:!e.selected_run_id,children:"Run artifacts"})]})]}),e.runtime_ledger_log_error?s.jsx("div",{className:"warn_callout",children:e.runtime_ledger_log_error}):null,e.selected_run_id?null:s.jsx("div",{className:"empty_state_inline",children:"Select a run in Activity or Artifact Explorer to inspect its runtime ledger."}),e.selected_run_id&&!H.length&&!e.runtime_ledger_log_loading?s.jsx("div",{className:"empty_state_inline",children:"No ledger records match the current search."}):null,s.jsx("div",{className:"runtime_log_event_list","aria-label":"Selected run ledger records",children:H.map(C=>{var K,J;const N=C.record||{},P=String(((K=N==null?void 0:N.effect)==null?void 0:K.type)||"").trim(),D=String((N==null?void 0:N.status)||"").trim(),ne=String((N==null?void 0:N.node_id)||"").trim(),B=fn(N==null?void 0:N.ended_at,N==null?void 0:N.started_at,N==null?void 0:N.ts),z=eo(N),G=Xx(N),T=P?ht(Ps(((J=N==null?void 0:N.effect)==null?void 0:J.payload)??{},1200),{max_chars:1200,max_lines:6}):"",Q=Vf(N)||(z?`Waiting for ${String(z.reason||"input")}`:"")||((N==null?void 0:N.result)!==void 0?Ps(N.result,700):"");return s.jsxs("article",{className:`runtime_log_event ${Nl(D)}`,children:[s.jsxs("div",{className:"runtime_log_event_header",children:[s.jsxs("span",{className:"mono",children:["#",C.cursor]}),s.jsx(Cl,{status:D||"record"}),P?s.jsx("span",{className:"chip mono muted",children:P}):null,ne?s.jsx("strong",{className:"mono",children:ne}):null,B?s.jsx("span",{className:"mono muted",children:xa(B)}):null]}),s.jsxs("div",{className:"runtime_log_event_body",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Request / activity"}),s.jsx("p",{children:[G||wm(N),T&&T!=="{}"?T:""].filter(Boolean).join(`
|
|
110
|
-
`)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Outcome"}),s.jsx("p",{children:ht(Q||"—",{max_chars:1200,max_lines:6})})]})]}),s.jsxs("details",{className:"runtime_raw_details",children:[s.jsx("summary",{className:"mono muted",children:"Raw ledger record"}),s.jsx(dr,{value:N,collapseAfterDepth:3,showCopy:!0})]})]},`${e.selected_run_id}:${C.cursor}`)})})]}):e.runtime_log_source==="provider_calls"?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"runtime_log_context",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Selected run"}),s.jsx("strong",{children:M?Ci(M,e.workflow_label_by_id):e.selected_run_id?Lt(e.selected_run_id,24):"No run selected"}),e.selected_run_id?s.jsx("em",{className:"mono",children:Lt(e.selected_run_id,34)}):null]}),s.jsxs("div",{children:[s.jsx("span",{children:"Provider calls"}),s.jsx("strong",{children:X.length.toLocaleString()}),s.jsx("em",{className:"mono",children:Y?`${Y.toLocaleString()} tokens`:"tokens not recorded"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Issues"}),s.jsx("strong",{children:Z.toLocaleString()})]}),s.jsxs("div",{className:"runtime_log_context_actions",children:[s.jsx("button",{className:"btn",onClick:()=>e.on_open_run(e.selected_run_id),disabled:!e.selected_run_id,children:"Open Observe"}),s.jsx("button",{className:"btn",onClick:()=>e.on_runtime_log_source_change("run_ledger"),disabled:!e.selected_run_id,children:"Run ledger"})]})]}),e.runtime_ledger_log_error?s.jsx("div",{className:"warn_callout",children:e.runtime_ledger_log_error}):null,e.selected_run_id?null:s.jsx("div",{className:"empty_state_inline",children:"Select a run in Activity or Artifact Explorer to inspect provider calls."}),e.selected_run_id&&!X.length&&!e.runtime_ledger_log_loading?s.jsx("div",{className:"empty_state_inline",children:"No provider calls are present in the selected run ledger, or none match the current search."}):null,s.jsx("div",{className:"provider_activity_list runtime_provider_log_list",children:X.map(C=>s.jsxs("article",{className:`provider_activity ${C.error||C.missing_response?"danger":""}`,children:[s.jsxs("div",{className:"provider_activity_header",children:[s.jsxs("div",{children:[s.jsx("h4",{children:[C.provider||"provider unknown",C.model||"model unknown"].join(" / ")}),s.jsxs("div",{className:"timeline_subtitle",children:[C.node_id?s.jsx("span",{className:"mono",children:C.node_id}):null,C.run_id?s.jsx("span",{className:"mono",children:Lt(C.run_id,16)}):null,s.jsx("span",{children:Mg(C.duration_ms)}),C.status?s.jsx(Cl,{status:C.status}):null]})]}),s.jsxs("div",{className:"provider_tokens mono",children:[C.tokens.total?C.tokens.total.toLocaleString():"—"," tokens"]})]}),s.jsxs("div",{className:"provider_preview_grid",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Prompt / messages"}),s.jsx("p",{children:C.prompt_preview||"No prompt payload captured"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Response / error"}),s.jsx("p",{children:C.response_preview||C.error||"No response captured"})]})]}),s.jsxs("details",{className:"runtime_raw_details",children:[s.jsx("summary",{className:"mono muted",children:"Raw provider ledger record"}),s.jsx(dr,{value:C.raw,collapseAfterDepth:3,showCopy:!0})]})]},C.id))})]}):s.jsxs(s.Fragment,{children:[e.audit_log_error?s.jsx("div",{className:"warn_callout",children:e.audit_log_error}):null,s.jsx("pre",{className:"mono audit_log_tail",children:re.length?re.join(`
|
|
111
|
-
`):"(audit tail not loaded or no lines match search)"})]})]}):null]})}const nm=30;function f2(e){const[t,n]=m.useState(""),r=Array.isArray(e.wait.choices)?e.wait.choices:[],o=e.wait.allow_free_text!==!1,l=e.disabled===!0,u=String(e.wait.prompt||"").trim();return s.jsxs(s.Fragment,{children:[r.length?s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Expected response"}),s.jsxs("select",{className:"mono",value:t,onChange:c=>n(c.target.value),children:[s.jsx("option",{value:"",children:"(select)"}),r.map((c,f)=>s.jsx("option",{value:String(c),children:String(c)},f))]})]}):null,o?s.jsxs("div",{className:"field",children:[s.jsx("label",{children:r.length?"Or type a response":u?"Your answer":"Response to resume this wait"}),s.jsx("textarea",{className:"mono wait_response_input",value:t,onChange:c=>n(c.target.value),placeholder:u?"Type your answer to the request above…":"Type the response the workflow is waiting for…",rows:4})]}):null,s.jsx("div",{className:"actions",children:s.jsx("button",{className:"btn primary",disabled:l||!t.trim(),onClick:()=>e.on_submit(t.trim()),children:"Submit response"})})]})}function uw(e,t,n){if($f(e)==="automation"){const r=String(e.automation_id||e.run_id||"").trim();return n[r]||"Automation"}return Ci(e,t)}function dw(e){const t=$f(e.run);return t?s.jsx("span",{className:"chip scheduled run_tree_tag","data-tag":t,children:Ox(e.run)}):null}function h2(e){const t=e.selected_run_id.trim(),n=e.root_run_id.trim()||t,r=e.sections.reduce((o,l)=>o+l.rows.reduce((u,c)=>{const f=[c.run,...c.children];return u+f.filter(_=>Du(_.status)).length},0),0);return s.jsxs("aside",{className:"observatory_sidebar pane",children:[s.jsxs("div",{className:"run_nav_header pane_header",children:[s.jsx("span",{className:"pane_title",children:"Runs"}),s.jsxs("span",{className:"pane_count",children:[e.total_runs.toLocaleString()," runs • ",r.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(Ze,{name:"refresh",size:14}),e.loading?"…":""]})]}),s.jsxs("div",{className:"run_nav_controls",children:[s.jsx("input",{value:e.search,onChange:o=>e.on_search(o.target.value),placeholder:"Search runs, sessions, workflows"}),s.jsxs("div",{className:"run_nav_filter_row",children:[s.jsx("div",{className:"seg_toggle run_nav_segments",children:["active","waiting","terminal","failed","all"].map(o=>s.jsx("button",{className:`seg_btn ${e.filter===o?"active":""}`,onClick:()=>e.on_filter(o),children:o},o))}),s.jsxs("select",{className:"seg_select",value:e.group_by,onChange:o=>e.on_group_by(o.target.value),title:"Group workflow runs",children:[s.jsx("option",{value:"status",children:"Group by status"}),s.jsx("option",{value:"workflow",children:"Group by workflow"}),s.jsx("option",{value:"session",children:"Group by session"})]})]})]}),s.jsxs("div",{className:"run_tree",children:[e.sections.length?null:e.connected?s.jsx("div",{className:"run_tree_empty",children:"No runs match the current filters."}):s.jsxs("div",{className:"run_tree_empty",children:["Gateway offline — runs are unavailable."," ",s.jsx("button",{className:"btn btn_sm",onClick:e.on_sign_in,children:"Sign in"})]}),e.sections.map(o=>s.jsxs("section",{className:"run_tree_section",children:[s.jsxs("div",{className:"run_tree_section_header",children:[s.jsx("span",{children:o.label}),s.jsx("span",{className:"mono",children:o.rows.length})]}),o.rows.map(l=>{const u=l.run,c=String(u.run_id||"").trim(),f=c===t;return s.jsxs("div",{className:"run_tree_group",children:[s.jsxs("button",{className:`run_tree_item ${f?"selected":""} ${c===n?"root_context":""}`,onClick:()=>e.on_select(c,c),title:c,children:[s.jsxs("div",{className:"run_tree_item_top",children:[s.jsx("span",{className:"run_tree_label",children:uw(u,e.workflow_label_by_id,e.automation_titles)}),s.jsx(dw,{run:u}),u.status?s.jsx(Cl,{status:Lm(u)}):null]}),s.jsxs("div",{className:"run_tree_meta",children:[s.jsx("span",{className:"mono",children:Lt(c,13)}),s.jsx("span",{children:nc(u)?ya(nc(u)):"no start"}),s.jsx("span",{children:fc(u)})]})]}),l.children.length?s.jsx("div",{className:"run_tree_children",children:l.children.map(_=>{const p=String(_.run_id||"").trim();return s.jsxs("button",{className:`run_tree_item run_tree_child ${p===t?"selected":""}`,onClick:()=>e.on_select(p,c),title:p,children:[s.jsxs("div",{className:"run_tree_item_top",children:[s.jsx("span",{className:"run_tree_label",children:uw(_,e.workflow_label_by_id,e.automation_titles)}),s.jsx(dw,{run:_}),s.jsx(Cl,{status:Lm(_)})]}),s.jsxs("div",{className:"run_tree_meta",children:[s.jsx("span",{className:"mono",children:Lt(p,13)}),s.jsx("span",{children:nc(_)?ya(nc(_)):"child"}),s.jsx("span",{children:fc(_)})]})]},p)})}):null]},c)})]},o.key))]})]})}function fw(){return s.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:s.jsx("path",{d:"M4 20h16a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.7-.9L9.2 3.9A2 2 0 0 0 7.5 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z"})})}function m2(e){var E,A,L,O,M,H,X;const t=e.run_id.trim(),[n,r]=m.useState(!1);if(!t)return s.jsx("div",{className:"run_overview",children:s.jsx("div",{className:"empty_state_inline",style:{padding:"48px 24px",textAlign:"center"},children:"Select a run on the left to inspect it — or start one from Launch."})});const o=Ci(e.run,e.workflow_label_by_id),l=nc(e.run)||String(((E=e.run_state)==null?void 0:E.started_at)||((A=e.run_state)==null?void 0:A.created_at)||"").trim(),u=Fx(e.run)||(Ti(e.status_label)?String(((L=e.run_state)==null?void 0:L.updated_at)||"").trim():""),c=e.run?fc(e.run):l?Mg((kn(u)??Date.now())-(kn(l)??Date.now())):"—",f=e.provider_activities.length,_=e.provider_activities.reduce((Y,Z)=>Y+(Number(Z.tokens.total)||0),0),p=e.provider_activities.filter(Y=>Y.missing_response||Y.error).length,y=String(((O=e.latest_summary)==null?void 0:O.text)||"").trim(),w=e.wait_state,x=Ti(e.status_label),k=Im(e.run)||String(((M=e.run_state)==null?void 0:M.error)||"").trim();let j="";for(let Y=e.records.length-1;Y>=0;Y--){const Z=Vf((H=e.records[Y])==null?void 0:H.record);if(Z){j=Z;break}}return s.jsxs("div",{className:"run_overview",children:[s.jsxs("section",{className:"run_hero run_hero_line",children:[s.jsx("h2",{className:"run_hero_title",title:o,children:o}),s.jsx(Cl,{status:e.status_label}),t?s.jsx("span",{className:"chip mono muted",title:t,children:Lt(t,18)}):null,e.root_run_id&&e.root_run_id!==t?s.jsxs("span",{className:"chip mono muted",title:e.root_run_id,children:["root ",Lt(e.root_run_id,12)]}):null,s.jsx("span",{className:"run_hero_spacer"}),e.workspace_root?s.jsxs("button",{className:"btn btn_icon",onClick:e.on_reveal_workspace,title:`Open the run's workspace folder
|
|
112
|
-
${e.workspace_root}`,children:[s.jsx(fw,{}),"Folder"]}):null,s.jsx("button",{className:"btn",onClick:e.on_generate_summary,disabled:!t||e.summary_generating,children:e.summary_generating?"Summarizing…":y?"Refresh summary":"Summarize"}),s.jsx("button",{className:"btn",onClick:e.on_open_runtime,title:"Open this run's artifacts in the System explorer",children:"Run artifacts"})]}),x?s.jsxs("section",{className:"overview_panel",children:[s.jsxs("div",{className:"overview_panel_header",children:[s.jsx("h3",{children:"Outcome"}),s.jsx("span",{className:`chip mono ${Nl(e.status_label)}`,children:e.status_label||(k?"failed":"completed")})]}),k?s.jsx("div",{className:"error_callout",children:k}):null,j?s.jsx(Ai,{text:ht(j,{max_chars:4e3,max_lines:60})}):null,!k&&!j?s.jsx("div",{className:"empty_state_inline",children:"No final text output was recorded for this run — produced files, if any, live under Run artifacts (above)."}):null]}):null,(()=>{const Y=Array.isArray(e.run_artifacts)?e.run_artifacts:[],Z=C=>{const N=String((C!=null&&C.tags&&typeof C.tags=="object"?C.tags.source:"")||"").trim();return N==="run_store_offload"||N==="node_trace_offload"},re=C=>{const N=C!=null&&C.tags&&typeof C.tags=="object"?C.tags:{},P=String((C==null?void 0:C.filename)||N.filename||"").trim();if(P)return P;const D=String(N.path||(C==null?void 0:C.source_path)||"").trim();return D?D.split("/").pop()||D:String((C==null?void 0:C.title)||"").trim()||String((C==null?void 0:C.artifact_id)||"").slice(0,14)},ie=C=>{var N;return s.jsxs("div",{className:"run_artifact_row",children:[s.jsx("span",{className:"run_artifact_name",title:String(((N=C==null?void 0:C.tags)==null?void 0:N.path)||(C==null?void 0:C.source_path)||(C==null?void 0:C.artifact_id)||""),children:re(C)}),s.jsx("span",{className:"chip mono muted",children:String((C==null?void 0:C.content_type)||"?").replace(/^application\//,"").replace(/^text\//,"")}),s.jsx("span",{className:"run_artifact_size",children:typeof(C==null?void 0:C.size_bytes)=="number"?`${(C.size_bytes/1024).toFixed(C.size_bytes>1e5?0:1)} kB`:""}),s.jsxs("span",{className:"run_artifact_actions",children:[s.jsx("button",{className:"btn",onClick:()=>e.on_preview_run_artifact(C),children:"Preview"}),s.jsx("button",{className:"btn",onClick:()=>e.on_download_run_artifact(C),children:"Download"})]})]},String((C==null?void 0:C.artifact_id)||Math.random()))},ue=Y.filter(C=>!Z(C)),F=Y.filter(Z);return s.jsxs("section",{className:"overview_panel",children:[s.jsxs("div",{className:"overview_panel_header",children:[s.jsx("h3",{children:"Artifacts"}),s.jsx("span",{className:"mono muted",children:Y.length?Y.length.toLocaleString():""}),e.workspace_root?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"pane_spacer"}),s.jsxs("button",{className:"btn btn_icon",onClick:e.on_reveal_workspace,title:`Open the run's workspace folder
|
|
113
|
-
${e.workspace_root}`,children:[s.jsx(fw,{}),"Workspace"]})]}):null]}),e.run_artifacts_error?s.jsx("div",{className:"warn_callout",children:e.run_artifacts_error}):null,e.run_artifacts_loading&&!Y.length?s.jsx("div",{className:"empty_state_inline",children:"Loading artifacts…"}):null,!e.run_artifacts_loading&&!Y.length&&!e.run_artifacts_error?s.jsxs("div",{className:"empty_state_inline",children:["The runtime recorded no durable artifacts for this run.",e.workspace_root?" Files written to the workspace folder (if any) are reachable via the Folder button.":""]}):null,ue.length?s.jsx("div",{className:"run_artifact_list",children:ue.map(ie)}):null,!ue.length&&Y.length?s.jsxs("div",{className:"empty_state_inline",children:["No file products — this run's durable artifacts are internal state offloads (below).",e.workspace_root?" Report files written to the workspace are reachable via the Folder button.":""]}):null,F.length?s.jsxs("details",{className:"runtime_raw_details",children:[s.jsxs("summary",{className:"muted",children:["Internal state offloads (",F.length,")"]}),s.jsx("div",{className:"run_artifact_list",children:F.map(ie)})]}):null]})})(),s.jsxs("div",{className:"metric_grid",children:[s.jsxs("div",{className:"metric_tile",children:[s.jsx("span",{children:"Started"}),s.jsx("strong",{children:xa(l)})]}),s.jsxs("div",{className:"metric_tile",children:[s.jsx("span",{children:u?"Finished":"Running for"}),s.jsx("strong",{children:u?xa(u):c})]}),s.jsxs("div",{className:"metric_tile",children:[s.jsx("span",{children:"Total duration"}),s.jsx("strong",{children:c})]}),s.jsxs("div",{className:"metric_tile",children:[s.jsx("span",{children:"Ledger"}),s.jsx("strong",{children:(e.records_count+e.child_records_count).toLocaleString()})]}),s.jsxs("div",{className:"metric_tile",children:[s.jsx("span",{children:"Subworkflows"}),s.jsx("strong",{children:e.subrun_ids.length.toLocaleString()})]}),s.jsxs("div",{className:"metric_tile",children:[s.jsx("span",{children:"Provider calls"}),s.jsx("strong",{children:f.toLocaleString()})]}),s.jsxs("div",{className:"metric_tile",children:[s.jsx("span",{children:"Tokens"}),s.jsx("strong",{children:_?_.toLocaleString():"—"})]}),s.jsxs("div",{className:"metric_tile",children:[s.jsx("span",{children:"Assets"}),s.jsx("strong",{children:e.attachments_count.toLocaleString()})]})]}),s.jsxs("div",{className:"overview_columns",children:[s.jsxs("section",{className:"overview_panel",children:[s.jsxs("div",{className:"overview_panel_header",children:[s.jsx("h3",{children:x?"What happened":"What is happening"}),w?s.jsx("span",{className:"chip mono info",children:"waiting"}):null]}),w?s.jsxs("div",{className:"overview_fact_list",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Reason"}),s.jsx("strong",{children:String(w.reason||"unknown")})]}),w.wait_key?s.jsxs("div",{children:[s.jsx("span",{children:"Wait key"}),s.jsx("strong",{className:"mono",children:Lt(String(w.wait_key),34)})]}):null,(X=w==null?void 0:w.details)!=null&&X.sub_run_id?s.jsxs("div",{children:[s.jsx("span",{children:"Subworkflow"}),s.jsx("strong",{className:"mono",children:Lt(String(w.details.sub_run_id),24)})]}):null,w.prompt?s.jsxs("div",{children:[s.jsx("span",{children:"Prompt"}),s.jsx("strong",{children:ht(String(w.prompt),{max_chars:260,max_lines:3})})]}):null,e.on_answer_wait&&w.wait_key&&String(w.reason||"")==="user"?s.jsx("div",{className:"overview_fact_actions",children:s.jsx("button",{className:"btn primary",onClick:e.on_answer_wait,children:"Review & answer…"})}):null]}):(()=>{var C;const Y=e.timeline_items.length?e.timeline_items[e.timeline_items.length-1]:null,Z=(Y==null?void 0:Y.record)||null,re=String((Z==null?void 0:Z.node_id)||"").trim(),ie=re&&e.node_index?e.node_index[re]:null,ue=String((ie==null?void 0:ie.label)||re||"").trim(),F=String(((C=Z==null?void 0:Z.effect)==null?void 0:C.type)||"").trim();return ue||F?s.jsxs("div",{className:"overview_fact_list",children:[ue?s.jsxs("div",{children:[s.jsx("span",{children:x?"Ended at":"Last step"}),s.jsx("strong",{children:ue})]}):null,F?s.jsxs("div",{children:[s.jsx("span",{children:"Effect"}),s.jsx("strong",{className:"mono",children:F})]}):null]}):s.jsx("div",{className:"empty_state_inline",children:x?"Nothing in flight — the run is finished.":"No active wait is reported for this run."})})(),p?s.jsxs("div",{className:"warn_callout",children:[p," provider call(s) have missing responses or errors."]}):null]}),s.jsxs("section",{className:"overview_panel",children:[s.jsxs("div",{className:"overview_panel_header",children:[s.jsx("h3",{children:"Summary"}),e.latest_summary?s.jsx("span",{className:"chip mono ok",children:"saved"}):s.jsx("span",{className:"chip mono muted",children:"none"})]}),e.summary_error?s.jsx("div",{className:"warn_callout",children:e.summary_error}):null,y?s.jsx(Ai,{text:y}):s.jsx("div",{className:"empty_state_inline",children:"Generate a grounded summary from the root run and its subflows."})]})]}),e.subrun_ids.length?s.jsxs("section",{className:"overview_panel",children:[s.jsxs("div",{className:"overview_panel_header",children:[s.jsx("h3",{children:"Subworkflows"}),s.jsx("span",{className:"mono muted",children:e.subrun_ids.length})]}),s.jsx("div",{className:"subrun_chip_list",children:e.subrun_ids.map(Y=>s.jsx("button",{className:"subrun_chip mono",onClick:()=>e.on_open_subrun(Y),title:Y,children:Lt(Y,22)},Y))})]}):null,e.attachments.length||e.session_id?s.jsxs("section",{className:"overview_panel",children:[s.jsxs("div",{className:"overview_panel_header",children:[s.jsx("h3",{children:"Session files"}),s.jsx("span",{className:"mono muted",children:e.attachments.length?`${e.attachments.length} file${e.attachments.length===1?"":"s"}`:""}),s.jsx("button",{className:"btn btn_sm",onClick:e.on_refresh_attachments,disabled:e.attachments_loading||!e.session_id,children:e.attachments_loading?"Refreshing…":"Refresh"})]}),e.attachments_error?s.jsx("div",{className:"warn_callout",children:e.attachments_error}):null,e.attachments.length?s.jsx("div",{className:"produced_list",children:e.attachments.map(Y=>{const Z=String((Y==null?void 0:Y.artifact_id)||"").trim();if(!Z)return null;const re=Y!=null&&Y.tags&&typeof Y.tags=="object"?Y.tags:{},ie=String((re==null?void 0:re.path)||"").trim()?`@${String(re.path).trim()}`:String((re==null?void 0:re.filename)||"").trim()||Z,ue=typeof(Y==null?void 0:Y.size_bytes)=="number"?Number(Y.size_bytes):null,F=e.attachments_loading||!e.attachments_ready;return s.jsxs("div",{className:"produced_row",children:[s.jsx("span",{className:"produced_name mono",title:Z,children:ie}),s.jsx("span",{className:"mono muted",children:ue!==null?`${ue.toLocaleString()} B`:""}),s.jsxs("span",{className:"produced_actions",children:[s.jsx("button",{className:"btn btn_sm",onClick:()=>e.on_preview_attachment(Y),disabled:F,children:"Preview"}),s.jsx("button",{className:"btn btn_sm",onClick:()=>e.on_download_attachment(Y),disabled:F,children:"Download"})]})]},Z)})}):s.jsx("div",{className:"empty_state_inline",children:x?"No files were attached to this run's session.":"No files in this run's session yet."})]}):null,e.timeline_items.length?s.jsxs("section",{className:"overview_panel",children:[s.jsxs("div",{className:"overview_panel_header",children:[s.jsx("h3",{children:"Chronology"}),s.jsx("span",{className:"mono muted",children:n||e.timeline_items.length<=nm?`${e.timeline_items.length} steps`:`last ${nm} of ${e.timeline_items.length} steps`}),e.timeline_items.length>nm?s.jsx("button",{className:"btn btn_sm",onClick:()=>r(Y=>!Y),children:n?"Show fewer":"Show all"}):null]}),s.jsx(_2,{items:n?e.timeline_items:e.timeline_items.slice(-nm),node_index:e.node_index,workflow_label_by_id:e.workflow_label_by_id,on_copy:e.on_copy})]}):null]})}function _2(e){const t=n=>{var A,L;const r=n,o=n.record||{},l=String(((A=o==null?void 0:o.effect)==null?void 0:A.type)||r.effect_type||"").trim(),u=String((o==null?void 0:o.status)||r.status||"").trim(),c=String((o==null?void 0:o.node_id)||r.node_id||"").trim(),f=c&&e.node_index?e.node_index[c]:null,_=String((f==null?void 0:f.label)||c||r.title||"Step").trim(),p=eo(o),y=(L=o==null?void 0:o.effect)==null?void 0:L.payload,w=o==null?void 0:o.result,x=Vf(o),k=l?Ps(y??{},900):ht(String(r.preview||""),{max_chars:900,max_lines:8}),j=x||(p?`Waiting for ${String(p.reason||"input")}${p.wait_key?` (${Lt(String(p.wait_key),18)})`:""}`:"")||(w!==void 0?Ps(w,900):"");return{title:l==="llm_call"?"Model call":l==="tool_calls"?"Tool execution":l==="answer_user"?"User-facing response":l==="start_subworkflow"?"Subworkflow launched":l==="ask_user"?"User input requested":l||r.title||"Ledger event",subtitle:_,request:ht(k,{max_chars:900,max_lines:7}),outcome:ht(j,{max_chars:1100,max_lines:9}),cls:Nl(u)}};return s.jsxs("div",{className:"human_timeline",children:[e.items.length?null:s.jsx("div",{className:"empty_state_inline",children:"No ledger records yet."}),e.items.map(n=>{const r=n.record||{},o=t(n),l=String(r.ended_at||r.started_at||n.ts||"").trim();return s.jsxs("article",{className:`timeline_event ${o.cls}`,children:[s.jsx("div",{className:"timeline_marker"}),s.jsxs("div",{className:"timeline_event_body",children:[s.jsxs("div",{className:"timeline_event_header",children:[s.jsxs("div",{children:[s.jsx("h3",{children:o.title}),s.jsxs("div",{className:"timeline_subtitle",children:[s.jsx("span",{children:o.subtitle}),n.run_id?s.jsx("span",{className:"mono",children:Lt(String(n.run_id),13)}):null]})]}),s.jsxs("div",{className:"timeline_time",children:[s.jsx("span",{children:ya(l)}),s.jsx("span",{className:"mono",title:l,children:xa(l)})]})]}),s.jsxs("div",{className:"timeline_payload_grid",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Requested"}),s.jsx("p",{className:"mono",children:o.request||"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Outcome"}),s.jsx("p",{children:o.outcome||"—"})]})]}),s.jsx("div",{className:"timeline_actions",children:s.jsxs("button",{className:"btn btn_icon",onClick:()=>e.on_copy(JSON.stringify(r,null,2)),children:[s.jsx(Ze,{name:"copy",size:14}),"JSON"]})})]})]},`${String(n.run_id||r.run_id||"")}:${n.cursor}`)})]})}function p2(e){const t=e.item,n=String(t.node_id||"").trim(),r=n&&e.node_index&&typeof e.node_index=="object"?e.node_index[n]:null,o=typeof(r==null?void 0:r.label)=="string"&&r.label.trim()?r.label.trim():n||t.title,l=typeof(r==null?void 0:r.type)=="string"&&r.type.trim()?r.type.trim():"",u=typeof(r==null?void 0:r.headerColor)=="string"&&r.headerColor.trim()?r.headerColor.trim():"",c=t.kind==="step"?o:t.title,f=u||(t.kind==="error"?"rgba(239, 68, 68, 0.85)":t.kind==="message"?"rgba(167, 139, 250, 0.85)":t.kind==="event"?"rgba(96, 165, 250, 0.85)":t.status==="waiting"?"rgba(96, 165, 250, 0.65)":t.status==="completed"?"rgba(34, 197, 94, 0.65)":"rgba(255, 255, 255, 0.14)"),_=String(t.status||"").trim(),p=_.toLowerCase(),y=Nl(p),w=Vf(t.data),x=!!(w&&w.trim()),k=ya(t.ts);return s.jsxs("div",{className:`lc ${y}`,style:{"--lc-accent":f},children:[s.jsxs("div",{className:"lc_header",children:[s.jsx("span",{className:"lc_title",children:c}),s.jsxs("div",{className:"lc_header_right",children:[_?s.jsx("span",{className:`lc_status ${y}`,children:_}):null,s.jsx("span",{className:"lc_time",title:t.ts,children:k})]})]}),s.jsxs("div",{className:"lc_meta",children:[l?s.jsx("span",{className:"lc_chip",children:l}):null,t.effect_type?s.jsx("span",{className:"lc_chip",children:String(t.effect_type)}):null,t.cursor?s.jsxs("span",{className:"lc_chip",children:["#",t.cursor]}):null,t.run_id?s.jsx("span",{className:"lc_chip",children:Lt(String(t.run_id),10)}):null,t.kind!=="step"&&n?s.jsx("span",{className:"lc_chip",children:n}):null]}),t.preview?s.jsx("div",{className:"lc_preview",children:t.preview}):null,t.data?s.jsxs("div",{className:"lc_actions",children:[x?s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"lc_btn",onClick:e.on_toggle_response,children:e.response_open?"Fold Response":"Unfold Response"}),s.jsx("button",{className:"lc_btn",onClick:()=>e.on_copy(String(w||"")),children:"Copy Response"})]}):null,s.jsx("button",{className:"lc_btn",onClick:e.on_toggle,children:e.open?"Fold JSON":"Unfold JSON"}),s.jsx("button",{className:"lc_btn",onClick:()=>{try{e.on_copy(JSON.stringify(t.data,null,2))}catch{e.on_copy(String(t.data))}},children:"Copy JSON"})]}):null,e.response_open&&x?s.jsx("div",{className:"lc_body",children:s.jsx(Ai,{text:String(w||"")})}):null,e.open&&t.data?s.jsx("div",{className:"lc_body lc_body_json mono",children:s.jsx(dr,{value:t.data,collapseAfterDepth:3,showCopy:!1})}):null]})}class g2{constructor(){Hs(this,"_buffer","");Hs(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 _={id:this._current.id,event:this._current.event,data:this._current.data_lines.join(`
|
|
115
|
-
`)};n(_)}this._current={data_lines:[]};continue}const u=l.indexOf(":"),c=u===-1?l:l.slice(0,u),f=u===-1?"":l.slice(u+1).trimStart();if(c==="id"){this._current.id=f;continue}if(c==="event"){this._current.event=f;continue}if(c==="data"){this._current.data_lines.push(f);continue}}}}const zt=Tv;function Ni(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 sb(){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 Pt(e){const t=(e||"").trim(),n={};return t&&(n.Authorization=`Bearer ${t}`),{...n,...sb()}}async function qn(e){try{const t=await e.text();return t!=null&&t.trim()?t.trim():`${e.status}`}catch{return`${e.status}`}}class y2 extends Error{constructor(n,r){super(r);Hs(this,"status");this.name="GatewayRequestError",this.status=n}}async function tp(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 y2(e.status,`${t} (HTTP ${e.status}): ${r||e.statusText||"no reason given"}`)}class np{constructor(t){Hs(this,"_cfg");Hs(this,"fetch_gateway",(t,n)=>fetch(zt(this._cfg.base_url,t),{...n,headers:{...n==null?void 0:n.headers,...Pt(this._cfg.auth_token)}}));this._cfg={...t,base_url:(t.base_url||"").trim()}}async start_run(t,n,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 _=await fetch(zt(this._cfg.base_url,bt("runs/start")),{method:"POST",headers:{"Content-Type":"application/json",...Pt(this._cfg.auth_token)},body:JSON.stringify(f)});if(!_.ok)throw new Error(`start_run failed: ${_.status}`);const p=await _.json(),y=p==null?void 0:p.run_id;if(typeof y!="string"||!y)throw new Error("start_run: missing run_id");return y}async list_mcp_servers(){for(const t of[bt("mcp/servers"),bt("mcp"),bt("discovery/mcp")])try{const n=await fetch(zt(this._cfg.base_url,t),{headers:{...Pt(this._cfg.auth_token)},signal:Ni()});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[bt("skills"),bt("skills/registry")])try{const n=await fetch(zt(this._cfg.base_url,t),{headers:{...Pt(this._cfg.auth_token)},signal:Ni()});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(zt(this._cfg.base_url,bt(`runs/${encodeURIComponent(t)}`)),{headers:{...Pt(this._cfg.auth_token)}});if(!n.ok)throw new Error(`get_run failed: ${await qn(n)}`);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=zt(this._cfg.base_url,bt(`runs/${encodeURIComponent(r)}/history_bundle?${o.toString()}`)),u=await fetch(l,{headers:{...Pt(this._cfg.auth_token)}});if(!u.ok)throw new Error(`get_run_history_bundle failed: ${await qn(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=zt(this._cfg.base_url,bt(`runs?${c.toString()}`)),_=await fetch(f,{headers:{...Pt(this._cfg.auth_token)},signal:AbortSignal.timeout(3e4)});if(!_.ok)throw new Error(`list_runs failed: ${await qn(_)}`);return await _.json()}async audit_log_tail(t){const n=typeof(t==null?void 0:t.max_bytes)=="number"?Math.max(1024,Math.min(4e5,Math.floor(t.max_bytes))):8e4,r=zt(this._cfg.base_url,bt(`audit/tail?max_bytes=${encodeURIComponent(String(n))}`)),o=await fetch(r,{headers:{...Pt(this._cfg.auth_token)}});if(!o.ok)throw new Error(`audit_log_tail failed: ${await qn(o)}`);return await o.json()}async gateway_about(){const t=await fetch(zt(this._cfg.base_url,bt("about")),{headers:{...Pt(this._cfg.auth_token)},signal:Ni(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(zt(this._cfg.base_url,bt(`runs/${encodeURIComponent(n)}/input_data`)),{headers:{...Pt(this._cfg.auth_token)}});if(!r.ok)throw new Error(`get_run_input_data failed: ${await qn(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=zt(this._cfg.base_url,bt(`runs/${encodeURIComponent(r)}/artifacts?limit=${encodeURIComponent(String(o))}&offset=${encodeURIComponent(String(l))}`)),c=await fetch(u,{headers:{...Pt(this._cfg.auth_token)}});if(!c.ok)throw new Error(`list_run_artifacts failed: ${await qn(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=zt(this._cfg.base_url,bt(`sessions/${encodeURIComponent(r)}/artifacts?limit=${encodeURIComponent(String(o))}&offset=${encodeURIComponent(String(l))}`)),c=await fetch(u,{headers:{...Pt(this._cfg.auth_token)}});if(!c.ok)throw new Error(`list_session_artifacts failed: ${await qn(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(),_=String((t==null?void 0:t.workflow_id)||"").trim(),p=String((t==null?void 0:t.node_id)||"").trim(),y=String((t==null?void 0:t.content_type)||"").trim(),w=String((t==null?void 0:t.query)||"").trim(),x=String((t==null?void 0:t.tags)||"").trim(),k=String((t==null?void 0:t.cursor)||"").trim(),j=String((t==null?void 0:t.order_by)||"").trim(),E=String((t==null?void 0:t.order)||"").trim(),A=String((t==null?void 0:t.created_after)||"").trim(),L=String((t==null?void 0:t.created_before)||"").trim(),O=typeof(t==null?void 0:t.limit)=="number"?t.limit:500,M=typeof(t==null?void 0:t.offset)=="number"?Math.max(0,Math.floor(t.offset)):0;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),_&&n.set("workflow_id",_),p&&n.set("node_id",p),y&&n.set("content_type",y),w&&n.set("query",w),x&&n.set("tags",x),k&&n.set("cursor",k),j&&n.set("order_by",j),E&&n.set("order",E),A&&n.set("created_after",A),L&&n.set("created_before",L),t!=null&&t.include_stats&&n.set("include_stats","true"),n.set("limit",String(O)),n.set("offset",String(M));const H=await fetch(zt(this._cfg.base_url,bt(`artifacts/search?${n.toString()}`)),{headers:{...Pt(this._cfg.auth_token)}});if(!H.ok)throw new Error(`search_artifacts failed: ${await qn(H)}`);return await H.json()}async artifact_stats(t){const n=new URLSearchParams;n.set("scope",String((t==null?void 0:t.scope)||"all").trim()||"all");for(const o of["session_id","run_id","modality","semantic_kind","render_kind","workflow_id","node_id","content_type","query","tags","created_after","created_before"]){const l=String((t==null?void 0:t[o])||"").trim();l&&n.set(o,l)}const r=await fetch(zt(this._cfg.base_url,bt(`artifacts/stats?${n.toString()}`)),{headers:{...Pt(this._cfg.auth_token)}});if(!r.ok)throw new Error(`artifact_stats failed: ${await qn(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=zt(this._cfg.base_url,bt(`runs/${encodeURIComponent(o)}/artifacts/${encodeURIComponent(l)}/content${c}`)),_=await fetch(f,{headers:{...Pt(this._cfg.auth_token)}});if(!_.ok)throw new Error(`download_run_artifact_content failed: ${await qn(_)}`);return await _.blob()}async list_entities(){const t=await fetch(zt(this._cfg.base_url,bt("entities")),{headers:{...Pt(this._cfg.auth_token)},signal:Ni()});if(!t.ok)throw new Error(`list_entities failed: ${await qn(t)}`);const n=await t.json();return{entities:Array.isArray(n==null?void 0:n.entities)?n.entities:[]}}async get_entity_phases_spec(){const t=await fetch(zt(this._cfg.base_url,bt("entities/spec/phases")),{headers:{...Pt(this._cfg.auth_token)},signal:Ni()});if(!t.ok)throw new Error(`get_entity_phases_spec failed: ${await qn(t)}`);return await t.json()}async get_entity_cognition(t){const n=await fetch(zt(this._cfg.base_url,bt(`entities/${encodeURIComponent(t)}/cognition`)),{headers:{...Pt(this._cfg.auth_token)},signal:Ni()});if(!n.ok)throw new Error(`get_entity_cognition failed: ${await qn(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(zt(this._cfg.base_url,bt(`entities/${encodeURIComponent(n)}/card`)),{headers:{...Pt(this._cfg.auth_token)},signal:Ni()});if(!r.ok)throw new Error(`get_entity_card failed: ${await qn(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=zt(this._cfg.base_url,bt(`entities/${encodeURIComponent(r)}/diary/${encodeURIComponent(o)}?reason=${encodeURIComponent("observer board hint chip")}`)),u=await fetch(l,{headers:{...Pt(this._cfg.auth_token)},signal:Ni()});if(!u.ok)throw new Error(`read_entity_diary_entry failed: ${await qn(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=zt(this._cfg.base_url,bt(`runs/${encodeURIComponent(t)}/ledger?after=${encodeURIComponent(String(r))}&limit=${encodeURIComponent(String(o))}`)),u=await fetch(l,{headers:{...Pt(this._cfg.auth_token)},signal:Ni(n==null?void 0:n.signal)});if(!u.ok)throw new Error(`get_ledger failed: ${u.status}`);const c=await u.json(),f=Array.isArray(c==null?void 0:c.items)?c.items:[],_=typeof(c==null?void 0:c.next_after)=="number"?c.next_after:r;return{items:f,next_after:_}}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(zt(this._cfg.base_url,bt("runs/ledger/batch")),{method:"POST",headers:{"Content-Type":"application/json",...Pt(this._cfg.auth_token)},body:JSON.stringify({runs:n,limit:r}),signal:Ni()});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(zt(this._cfg.base_url,bt(`runs/${encodeURIComponent(r)}/summary`)),{method:"POST",headers:{"Content-Type":"application/json",...Pt(this._cfg.auth_token)},body:JSON.stringify(o)});if(!c.ok)throw await tp(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(zt(this._cfg.base_url,bt(`runs/${encodeURIComponent(r)}/chat`)),{method:"POST",headers:{"Content-Type":"application/json",...Pt(this._cfg.auth_token)},body:JSON.stringify(o)});if(!c.ok)throw await tp(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 _=await fetch(zt(this._cfg.base_url,bt(`runs/${encodeURIComponent(r)}/audio/transcribe`)),{method:"POST",headers:{"Content-Type":"application/json",...Pt(this._cfg.auth_token)},body:JSON.stringify(u)});if(!_.ok)throw new Error(`audio_transcribe failed: ${await qn(_)}`);const p=await _.json(),y=String((p==null?void 0:p.text)||"");return{ok:!!(p!=null&&p.ok),run_id:String((p==null?void 0:p.run_id)||""),request_id:String((p==null?void 0:p.request_id)||""),text:y,transcript_artifact:p==null?void 0:p.transcript_artifact}}async voice_tts(t,n){const 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 _=await fetch(zt(this._cfg.base_url,bt(`runs/${encodeURIComponent(r)}/voice/tts`)),{method:"POST",headers:{"Content-Type":"application/json",...Pt(this._cfg.auth_token)},body:JSON.stringify(l)});if(!_.ok)throw new Error(`voice_tts failed: ${await qn(_)}`);const p=await _.json();return{ok:!!(p!=null&&p.ok),run_id:String((p==null?void 0:p.run_id)||""),request_id:String((p==null?void 0:p.request_id)||""),audio_artifact:p==null?void 0:p.audio_artifact}}async save_chat_thread(t,n){const 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(zt(this._cfg.base_url,bt(`runs/${encodeURIComponent(r)}/chat_threads`)),{method:"POST",headers:{"Content-Type":"application/json",...Pt(this._cfg.auth_token)},body:JSON.stringify(o)});if(!f.ok)throw new Error(`save_chat_thread failed: ${await qn(f)}`);return await f.json()}async list_bundles(){const t=await fetch(zt(this._cfg.base_url,bt("bundles")),{headers:{...Pt(this._cfg.auth_token)},signal:Ni()});if(!t.ok)throw new Error(`list_bundles failed: ${t.status}`);return await t.json()}async reload_bundles(){const t=await fetch(zt(this._cfg.base_url,bt("bundles/reload")),{method:"POST",headers:{...Pt(this._cfg.auth_token)}});if(!t.ok)throw new Error(`reload_bundles failed: ${t.status}`);return await t.json()}async upload_bundle(t,n){const 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(zt(this._cfg.base_url,bt("bundles/upload")),{method:"POST",headers:{...Pt(this._cfg.auth_token)},body:l});if(!u.ok)throw new Error(`upload_bundle failed: ${await qn(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(zt(this._cfg.base_url,bt("attachments/upload")),{method:"POST",headers:{...Pt(this._cfg.auth_token)},body:c});if(!f.ok)throw new Error(`attachments_upload failed: ${await qn(f)}`);const _=await f.json(),p=_==null?void 0:_.attachment;if(!p||typeof p!="object")throw new Error("attachments_upload: missing attachment");if(!String(p.$artifact||"").trim())throw new Error("attachments_upload: missing attachment.$artifact");return p}async remove_bundle(t,n){const 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=zt(this._cfg.base_url,bt(`bundles/${encodeURIComponent(r)}?${o.toString()}`)),c=await fetch(u,{method:"DELETE",headers:{...Pt(this._cfg.auth_token)}});if(!c.ok)throw new Error(`remove_bundle failed: ${await qn(c)}`);return await c.json()}async discovery_tools(){const t=await fetch(zt(this._cfg.base_url,bt("discovery/tools")),{headers:{...Pt(this._cfg.auth_token)}});if(!t.ok)throw new Error(`discovery_tools failed: ${t.status}`);return await t.json()}async discovery_providers(t){const n=(t==null?void 0:t.include_models)===!0,r=zt(this._cfg.base_url,bt(`discovery/providers?include_models=${encodeURIComponent(String(n))}`)),o=await fetch(r,{headers:{...Pt(this._cfg.auth_token)}});if(!o.ok)throw new Error(`discovery_providers failed: ${o.status}`);return await o.json()}async discovery_provider_models(t){const n=String(t||"").trim();if(!n)throw new Error("discovery_provider_models: provider_name is required");const r=await fetch(zt(this._cfg.base_url,bt(`discovery/providers/${encodeURIComponent(n)}/models`)),{headers:{...Pt(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(zt(this._cfg.base_url,bt(`bundles/${encodeURIComponent(n)}`)),{headers:{...Pt(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(zt(this._cfg.base_url,bt(`bundles/${encodeURIComponent(r)}/flows/${encodeURIComponent(o)}`)),{headers:{...Pt(this._cfg.auth_token)}});if(!l.ok)throw new Error(`get_bundle_flow failed: ${l.status}`);return await l.json()}async get_workflow_flow(t){const n=String(t||"").trim();if(!n)throw new Error("get_workflow_flow: workflow_id is required");const r=await fetch(zt(this._cfg.base_url,bt(`workflows/${encodeURIComponent(n)}/flow`)),{headers:{...Pt(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(zt(this._cfg.base_url,bt("discovery/capabilities")),{headers:{...Pt(this._cfg.auth_token)},signal:Ni()});if(!t.ok)throw new Error(`discovery_capabilities failed: ${await qn(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:()=>Pt(t)})}async submit_command(t){const n=await fetch(zt(this._cfg.base_url,bt("commands")),{method:"POST",headers:{"Content-Type":"application/json",...Pt(this._cfg.auth_token)},body:JSON.stringify(t)});if(!n.ok)throw new Error(`submit_command failed: ${n.status}`);return await n.json()}async kg_query(t){const n=String((t==null?void 0:t.scope)||"session").trim().toLowerCase(),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 _=String((t==null?void 0:t.subject)||"").trim();_&&(l.subject=_);const p=String((t==null?void 0:t.predicate)||"").trim();p&&(l.predicate=p);const y=String((t==null?void 0:t.object)||"").trim();y&&(l.object=y);const w=String((t==null?void 0:t.since)||"").trim();w&&(l.since=w);const x=String((t==null?void 0:t.until)||"").trim();x&&(l.until=x);const k=String((t==null?void 0:t.active_at)||"").trim();k&&(l.active_at=k);const j=String((t==null?void 0:t.query_text)||"").trim();j&&(l.query_text=j),typeof(t==null?void 0:t.min_score)=="number"&&Number.isFinite(t.min_score)&&(l.min_score=Number(t.min_score));const E=await fetch(zt(this._cfg.base_url,bt("kg/query")),{method:"POST",headers:{"Content-Type":"application/json",...Pt(this._cfg.auth_token)},body:JSON.stringify(l)});if(!E.ok)throw new Error(`kg_query failed: ${await qn(E)}`);return await E.json()}async stream_ledger(t,n){var y;const r=Number((n==null?void 0:n.after)||0),o=n.on_step,l=n.signal,u=zt(this._cfg.base_url,bt(`runs/${encodeURIComponent(t)}/ledger/stream?after=${encodeURIComponent(String(r))}`)),c=await fetch(u,{headers:{Accept:"text/event-stream",...Pt(this._cfg.auth_token)},signal:l});if(!c.ok)throw await tp(c,"The ledger stream was refused");if(!c.body)throw new Error("stream_ledger: response body is missing");(y=n.on_open)==null||y.call(n);const f=c.body.getReader(),_=new TextDecoder("utf-8"),p=new g2;for(;;){const{value:w,done:x}=await f.read();if(x)return;const k=_.decode(w,{stream:!0});p.push(k,j=>{if(!(j.event!=="step"||!j.data))try{const E=JSON.parse(j.data);E&&typeof E.cursor=="number"&&E.record&&o(E)}catch{}})}}}function w2(e){const t=(e||"").trim();return t?{Authorization:`Bearer ${t}`}:{}}class v2{constructor(t){Hs(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)||Os()),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:Os(),method:"tools/call",params:{name:n,arguments:o}},u=await fetch(this._cfg.url,{method:"POST",headers:{"Content-Type":"application/json",...w2(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,_=!!(f!=null&&f.isError),y=(Array.isArray(f==null?void 0:f.content)?f.content:[]).find(x=>x&&x.type==="text"&&typeof x.text=="string"),w=(y==null?void 0:y.text)??"";return _?{call_id:r,name:n,success:!1,output:null,error:w||"Tool failed"}:{call_id:r,name:n,success:!0,output:w,error:null}}}class hw{constructor(t,n){Hs(this,"pending",[]);Hs(this,"scheduled",!1);Hs(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 mw(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 x2(e,t){const n=kn(e.updated_at||e.created_at)??0;return(kn(t.updated_at||t.created_at)??0)-n}function b2(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=mw(w);if(String(w.role||"")==="occurrence"&&x&&!o[x]){const k={run_id:x,workflow_id:null,status:"",role:"controller",session_kind:"automation",automation_id:x,updated_at:w.updated_at??null,created_at:w.created_at??null};o[x]=k,r.push(k)}}const l={},u={};for(const w of r){const x=String(w.run_id||"").trim();if(!x)continue;const k=mw(w,t.parent_hint?t.parent_hint(x):"");u[x]=k,k&&(l[k]||(l[k]=[])).push(w)}const c=w=>{const x=String(w.status||"").trim().toLowerCase();return t.filter==="all"?!0:t.filter==="active"?Du(x):t.filter==="waiting"?x==="waiting":t.filter==="terminal"?Ti(x):t.filter==="failed"?x==="failed":!0},f=w=>{if(!n)return!0;const x=String(w.workflow_id||w.schedule_target_workflow_id||"").trim(),k=x?t.workflow_label_by_id[x]||x:"";return[w.run_id,x,k,w.session_id,w.status,w.session_kind,w.automation_id].join(" ").toLowerCase().includes(n)},_=[];for(const w of r){const x=String(w.run_id||"").trim();if(!x)continue;const k=u[x];(!k||!o[k])&&_.push(x)}const p={},y=w=>{if(t.group_by==="workflow"){const k=String(w.schedule_target_workflow_id||w.workflow_id||"").trim()||"(unknown workflow)";return{key:k,label:t.workflow_label_by_id[k]||k}}if(t.group_by==="session"){const k=String(w.session_id||"").trim()||"(no session)";return{key:k,label:k}}const x=String(w.status||"").trim().toLowerCase()||"unknown";return Du(x)?{key:"active",label:"Active"}:x==="failed"?{key:"failed",label:"Failed"}:Ti(x)?{key:"finished",label:"Finished"}:{key:x,label:x}};for(const w of _){const x=o[w];if(!x)continue;const k=[...l[w]||[]].sort(x2),j=k.some(A=>c(A)&&f(A));if(!(c(x)&&f(x))&&!j)continue;const E=y(x);p[E.key]||(p[E.key]={key:E.key,label:E.label,rows:[]}),p[E.key].rows.push({run:x,children:k})}return Object.values(p).sort((w,x)=>{const k={active:0,waiting:1,failed:2,finished:3},j=k[w.key]??10,E=k[x.key]??10;return j!==E?j-E:w.label.localeCompare(x.label)})}const j2={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"},S2=[{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 k2(){const[e,t]=m.useState(!0);return s.jsxs("div",{className:"pin-legend",children:[s.jsxs("button",{className:"pin-legend-toggle mono",type:"button",onClick:()=>t(n=>!n),title:"Pin Type Legend",children:[e?"?":"×"," Pin Types"]}),e?null:s.jsxs("div",{className:"pin-legend-content",children:[S2.map(n=>s.jsxs("div",{className:"pin-legend-row",children:[s.jsx("span",{className:"pin-legend-shape",style:{color:j2[n.type]},children:n.shape}),s.jsx("span",{className:"pin-legend-label mono",children:n.label}),s.jsx("span",{className:"pin-legend-desc mono",children:n.description})]},n.type)),s.jsxs("div",{className:"pin-legend-rules mono",children:[s.jsx("strong",{children:"Connection Rules:"}),s.jsxs("ul",{children:[s.jsx("li",{children:"Execution connects to Execution only"}),s.jsx("li",{children:'"Any" type accepts all data types'}),s.jsx("li",{children:"Same types always compatible"}),s.jsx("li",{children:"Array and Object are interchangeable"}),s.jsx("li",{children:'"Tools" is compatible with Array (specialized string[])'})]})]})]})]})}function cn(e){return typeof e=="string"?e:e==null?"":String(e)}function _w(e,t){const n=cn(e).trim();return n.length<=t?n:`${n.slice(0,Math.max(0,t-1))}…`}function rb(e){const t=cn(e==null?void 0:e.targetHandle),n=cn(e==null?void 0:e.sourceHandle);return!!(t==="exec-in"||n==="exec-out"||t.includes("exec")||n.includes("exec"))}function ib(e){if(!e||typeof e!="object")return"";const t=e!=null&&e.data&&typeof e.data=="object"?e.data:{};return cn((t==null?void 0:t.nodeType)||(e==null?void 0:e.type)||"").trim()}function ob(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=cn(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 N2(e){const t=cn(e==null?void 0:e.entryNode).trim();if(t)return t;const n=Array.isArray(e==null?void 0:e.nodes)?e.nodes:[];for(const r of n)if(ib(r)==="on_flow_start"){const o=cn(r==null?void 0:r.id).trim();if(o)return o}return""}function sp(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 hf(e,t){const n=cn(e).trim(),r=cn(t).trim();return r?n?`${n}::${r}`:r:""}function C2(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,_)=>{if(!u||typeof u!="object"||n.length>=e.max_nodes||r.length>=e.max_edges)return;const p=Array.isArray(u.nodes)?u.nodes:[],y=Array.isArray(u.edges)?u.edges:[];for(const w of p){const x=cn(w==null?void 0:w.id).trim();if(!x)continue;const k=hf(c,x);if(!k||o.has(k))continue;const j=sp(w),E={...w,id:k,position:{x:j.x+f.x,y:j.y+f.y}};if(n.push(E),o.add(k),n.length>=e.max_nodes)break}for(const w of y){if(!rb(w))continue;const x=cn(w==null?void 0:w.source).trim(),k=cn(w==null?void 0:w.target).trim();if(!x||!k)continue;const j=hf(c,x),E=hf(c,k);if(!j||!E)continue;const A=cn(w==null?void 0:w.id).trim(),L=A?`${j}->${E}::${A}`:`${j}->${E}`;if(r.push({...w,id:L,source:j,target:E}),r.length>=e.max_edges)break}if(!(_>=e.max_depth))for(const w of p){if(n.length>=e.max_nodes||r.length>=e.max_edges)return;if(ib(w)!=="subflow")continue;const x=ob(w);if(!x)continue;const k=e.flow_by_id[x];if(!k||typeof k!="object")continue;const j=hf(c,cn(w==null?void 0:w.id));if(!j)continue;const E=N2(k);if(!E)continue;const L=(Array.isArray(k.nodes)?k.nodes:[]).find(re=>cn(re==null?void 0:re.id).trim()===E)||null;if(!L)continue;const O=sp(w),M=sp(L),Y={x:O.x+f.x+240-M.x,y:O.y+f.y+0-M.y},Z=hf(j,E);r.push({id:`${j}=>${Z}`,source:j,target:Z,sourceHandle:"exec-out",targetHandle:"exec-in"}),l(k,j,Y,_+1)}};return l(t,"",{x:0,y:0},0),{...t,id:cn(t.id),nodes:n,edges:r}}function E2(e){const t=cn(e).trim().toLowerCase();return t?!!(t.startsWith("literal")||t.includes("literal")||t==="concat"||t==="join"||t==="cast"||t==="parse_json"||t==="stringify_json"||t==="break_object"||t==="get_property"||t==="set_property"||t.includes("get_property")||t.includes("set_property")||t==="get_variable"||t==="set_variable"||t.includes("get_variable")||t.includes("set_variable")||t==="json_schema"):!1}function $2(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 p=`${l.id}->${f}`;o.has(p)||o.set(p,{id:p,source:l.id,target:f});continue}const _=r[f]||[];for(const p of _)u.has(p)||c.push(p);if(o.size>=e.max_edges)break}if(o.size>=e.max_edges)break}return{nodes:t,edges:Array.from(o.values())}}function pw(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 A2(e){const t=typeof e.now_ms=="number"?e.now_ms:Date.now(),n=e.flow,r=cn(e.active_node_id),o=e.recent_nodes||{},l=e.visited_nodes||{},u=e.highlight_path===!0,c=typeof e.vertical_compact=="number"?Math.max(.4,Math.min(1,e.vertical_compact)):.78,{nodes:f,edges:_,bounds:p}=m.useMemo(()=>{const B=C2({root:n||{},flow_by_id:e.flow_by_id||{},expand_subflows:e.expand_subflows===!0,max_depth:3,max_nodes:700,max_edges:900}),z=Array.isArray(B.nodes)?B.nodes:[],G=Array.isArray(B.edges)?B.edges:[];let T=[];for(const Se of z){const Ie=cn(Se==null?void 0:Se.id).trim();if(!Ie)continue;const ct=Se!=null&&Se.position&&typeof Se.position=="object"?Se.position:{},ge=typeof ct.x=="number"?ct.x:0,De=typeof ct.y=="number"?ct.y:0,Ye=Se!=null&&Se.data&&typeof Se.data=="object"?Se.data:{},Dt=cn((Ye==null?void 0:Ye.label)||(Se==null?void 0:Se.label)||Ie)||Ie,tn=cn((Ye==null?void 0:Ye.nodeType)||(Se==null?void 0:Se.type)||"unknown")||"unknown",pn=cn((Ye==null?void 0:Ye.headerColor)||(Se==null?void 0:Se.headerColor)||"")||"",Ut=Ye!=null&&Ye.eventConfig&&typeof Ye.eventConfig=="object"?Ye.eventConfig:null,It=Ut&&typeof Ut.schedule=="string"?cn(Ut.schedule).trim():"",un=Ut&&typeof Ut.recurrent=="boolean"?!!Ut.recurrent:void 0,Wn=tn==="subflow"?ob(Se):"",Mt=It||un!==void 0||Wn?{schedule:It||void 0,recurrent:un,subflow_id:Wn||void 0}:void 0;T.push({id:Ie,x:ge,y:De,label:Dt,type:tn,color:pn,meta:Mt})}const Q={};for(const Se of T)Q[Se.id]=Se;let K=[];for(const Se of G){if(!rb(Se))continue;const Ie=cn(Se==null?void 0:Se.source).trim(),ct=cn(Se==null?void 0:Se.target).trim();!Ie||!ct||K.push({id:cn((Se==null?void 0:Se.id)||`${Ie}->${ct}`),source:Ie,target:ct})}const J=new Set(T.map(Se=>Se.id));if(K=K.filter(Se=>J.has(Se.source)&&J.has(Se.target)),e.simplify===!0){const Ie=$2({nodes:T,edges:K,keep_id:ct=>{if(r&&ct===r)return!0;const ge=Q[ct];if(!ge)return!1;const De=cn(ge.type).trim().toLowerCase();return De==="on_flow_start"||De==="on_flow_end"||De==="subflow"?!0:!E2(De)},max_edges:900});T=Ie.nodes,K=Ie.edges}if(e.prefer_vertical===!0&&T.length>=2){const Se=T.map(Ye=>Ye.x),Ie=T.map(Ye=>Ye.y),ct=Math.max(...Se)-Math.min(...Se),ge=Math.max(...Ie)-Math.min(...Ie);ct>=ge&&(T=T.map(Ye=>({...Ye,x:Ye.y,y:Ye.x})));const De=Math.min(...T.map(Ye=>Ye.y));T=T.map(Ye=>({...Ye,y:De+(Ye.y-De)*c}))}const oe={};for(const Se of T)oe[Se.id]=Se;const he=160,_e=56,we=he/2,Ee=_e/2;let ze=0,Ue=0,_t=0,Pe=0;T.length&&(ze=Math.min(...T.map(Se=>Se.x)),Ue=Math.min(...T.map(Se=>Se.y)),_t=Math.max(...T.map(Se=>Se.x+he)),Pe=Math.max(...T.map(Se=>Se.y+_e)));let et=0;if(K.length){const Se=new Set(K.map(Ie=>`${Ie.source}->${Ie.target}`));for(const Ie of K){if(!Se.has(`${Ie.target}->${Ie.source}`))continue;const ct=oe[Ie.source],ge=oe[Ie.target];if(!ct||!ge)continue;const De=ct.x+we,Ye=ct.y+Ee,Dt=ge.x+we,tn=ge.y+Ee,pn=Math.max(1,Math.hypot(Dt-De,tn-Ye)),Ut=Math.max(28,Math.min(72,pn*.14)),It=Math.min(200,Ut*3.5);It>et&&(et=It)}}const lt=60+et,Je={x:ze-lt,y:Ue-lt,w:_t-ze+lt*2,h:Pe-Ue+lt*2,node_w:he,node_h:_e};return{nodes:T,edges:K,bounds:Je}},[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 y=m.useRef(null),[w,x]=m.useState(()=>({x:p.x,y:p.y,w:p.w,h:p.h})),k=m.useRef(w);k.current=w,m.useEffect(()=>{x({x:p.x,y:p.y,w:p.w,h:p.h})},[p.x,p.y,p.w,p.h]);const j=m.useRef(new Map),E=m.useRef(null),A=`${w.x} ${w.y} ${w.w} ${w.h}`,L={};for(const B of f)L[B.id]=B;const O=B=>{let z=cn(B).trim();if(!z)return"";if(L[z])return z;for(;z.includes("::");)if(z=z.slice(0,Math.max(0,z.lastIndexOf("::"))),L[z])return z;return""},M=O(r),H={};for(const[B,z]of Object.entries(o)){if(typeof z!="number")continue;const G=O(B);G&&(H[G]=Math.max(H[G]||0,z))}const X={};if(u)for(const[B,z]of Object.entries(l)){if(typeof z!="number")continue;const G=O(B);G&&(X[G]=typeof X[G]=="number"?Math.min(X[G],z):z)}const Y=cn(e.schedule_next_in).trim(),Z=cn(e.schedule_interval).trim(),re=e.node_last_ms&&typeof e.node_last_ms=="object"?e.node_last_ms:{},ie=B=>{try{const z=new Date(B),G=String(z.getHours()).padStart(2,"0"),T=String(z.getMinutes()).padStart(2,"0");return`${G}:${T}`}catch{return""}},ue=(B,z)=>{var K,J;const G=cn((K=B.meta)==null?void 0:K.schedule).trim();if(!(((J=B.meta)==null?void 0:J.recurrent)===!0))return z&&Y?`next ${Y}`:G&&G.length<=12&&!G.includes("T")?`in ${G}`:"scheduled";const Q=G||Z;return Q?z&&Y?`${Q} • next ${Y}`:`every ${Q}`:z&&Y?`next ${Y}`:"scheduled"},F=B=>{var he;const z=cn((he=B.meta)==null?void 0:he.subflow_id).trim(),G=z&&e.flow_by_id?e.flow_by_id[z]:null,Q=cn(G==null?void 0:G.name).trim()||z||B.label||B.id,K=typeof re[B.id]=="number"?Number(re[B.id]):null,J=K!==null?ie(K):"",oe=J?`last ${J}`:"subflow";return{label:Q,sub:oe}},C=(B,z,G)=>{const T=G||k.current,Q=y.current;if(!Q)return{x:B,y:z};const K=Q.getBoundingClientRect(),J=K.width>0?(B-K.left)/K.width:0,oe=K.height>0?(z-K.top)/K.height:0;return{x:T.x+J*T.w,y:T.y+oe*T.h}},N=(B,z,G)=>{const T=G||k.current,Q=Math.max(.12,Math.min(8,z)),K=T.w*Q,J=T.h*Q,oe=T.w>0?(B.x-T.x)/T.w:.5,he=T.h>0?(B.y-T.y)/T.h:.5,_e=B.x-oe*K,we=B.y-he*J;x(pw({x:_e,y:we,w:K,h:J},p))},P=(B,z,G)=>{const T=G||k.current,Q=y.current;if(!Q)return;const K=Q.getBoundingClientRect(),J=.88,oe=K.width>0?B/K.width*T.w*J:0,he=K.height>0?z/K.height*T.h*J:0;x(_e=>pw({x:(G||_e).x-oe,y:(G||_e).y-he,w:(G||_e).w,h:(G||_e).h},p))},D=m.useMemo(()=>{const B=new Set;for(const z of _)B.add(`${z.source}->${z.target}`);return B},[_]),ne=(B,z,G,T)=>{const Q=p.node_w,K=p.node_h,J=Math.abs(G),oe=Math.abs(T);if(J<1e-6&&oe<1e-6)return{x:B,y:z};const he=J>1e-6?Q/2/J:Number.POSITIVE_INFINITY,_e=oe>1e-6?K/2/oe:Number.POSITIVE_INFINITY,we=Math.min(he,_e);return{x:B+G*we,y:z+T*we}};return s.jsxs("div",{className:"graph_wrap",children:[s.jsxs("div",{className:"graph_corner",children:[s.jsxs("div",{className:"graph_corner_buttons",children:[s.jsx("button",{className:"btn graph_corner_btn",type:"button",onClick:()=>x({x:p.x,y:p.y,w:p.w,h:p.h}),title:"Recenter",children:"⤢"}),s.jsx("button",{className:"btn graph_corner_btn",type:"button",onClick:()=>{const B=y.current;if(!B)return;const z=B.getBoundingClientRect(),G=C(z.left+z.width/2,z.top+z.height/2);N(G,.84)},title:"Zoom in",children:"+"}),s.jsx("button",{className:"btn graph_corner_btn",type:"button",onClick:()=>{const B=y.current;if(!B)return;const z=B.getBoundingClientRect(),G=C(z.left+z.width/2,z.top+z.height/2);N(G,1.18)},title:"Zoom out",children:"−"})]}),s.jsx(k2,{})]}),s.jsxs("svg",{ref:y,className:"graph_svg",viewBox:A,role:"img","aria-label":"Workflow execution graph",onWheel:B=>{B.preventDefault();const z=C(B.clientX,B.clientY),G=typeof B.deltaY=="number"?B.deltaY:0,T=typeof B.deltaMode=="number"?Number(B.deltaMode):0,Q=T===1?G*24:T===2?G*800:G,K=45e-5*1.15*1.1;let J=Math.exp(Q*K);J=Math.max(.86,Math.min(1.16,J)),N(z,J)},onPointerDown:B=>{var G,T;(T=(G=B.currentTarget).setPointerCapture)==null||T.call(G,B.pointerId),j.current.set(B.pointerId,{x:B.clientX,y:B.clientY});const z=Array.from(j.current.values());if(z.length===1)E.current={mode:"pan",start_view:k.current,start_client:{x:B.clientX,y:B.clientY},start_dist:0,anchor_svg:{x:0,y:0}};else if(z.length>=2){const Q=z[0],K=z[1],J=Q.x-K.x,oe=Q.y-K.y,he=Math.max(1,Math.hypot(J,oe)),_e={x:(Q.x+K.x)/2,y:(Q.y+K.y)/2},we=k.current;E.current={mode:"pinch",start_view:we,start_client:_e,start_dist:he,anchor_svg:C(_e.x,_e.y,we)}}},onPointerMove:B=>{if(!j.current.has(B.pointerId))return;j.current.set(B.pointerId,{x:B.clientX,y:B.clientY});const z=E.current;if(!z)return;const G=Array.from(j.current.values());if(z.mode==="pan"&&G.length===1){const T=B.clientX-z.start_client.x,Q=B.clientY-z.start_client.y;P(T,Q,z.start_view)}else if(z.mode==="pinch"&&G.length>=2){const T=G[0],Q=G[1],K=T.x-Q.x,J=T.y-Q.y,oe=Math.max(1,Math.hypot(K,J)),he=z.start_dist/oe;N(z.anchor_svg,he,z.start_view)}},onPointerUp:B=>{j.current.delete(B.pointerId),j.current.size===0&&(E.current=null)},onPointerCancel:B=>{j.current.delete(B.pointerId),j.current.size===0&&(E.current=null)},children:[s.jsxs("defs",{children:[s.jsx("marker",{id:"arrow",viewBox:"0 0 10 10",refX:"9",refY:"5",markerWidth:"8",markerHeight:"8",orient:"auto-start-reverse",children:s.jsx("path",{d:"M 0 0 L 10 5 L 0 10 z",fill:"rgba(148,163,184,0.55)"})}),s.jsxs("filter",{id:"glow",children:[s.jsx("feGaussianBlur",{stdDeviation:"3",result:"coloredBlur"}),s.jsxs("feMerge",{children:[s.jsx("feMergeNode",{in:"coloredBlur"}),s.jsx("feMergeNode",{in:"SourceGraphic"})]})]})]}),_.map(B=>{const z=L[B.source],G=L[B.target];if(!z||!G)return null;const T=z.x+p.node_w/2,Q=z.y+p.node_h/2,K=G.x+p.node_w/2,J=G.y+p.node_h/2,oe=K-T,he=J-Q,_e=ne(T,Q,oe,he),we=ne(K,J,-oe,-he),Ee=B.source!==B.target&&D.has(`${B.target}->${B.source}`),ze=Math.max(1,Math.hypot(oe,he)),Ue=-he/ze,_t=oe/ze,Pe=String(B.source)<String(B.target)?1:-1,lt=Math.abs(oe)>=Math.abs(he)?oe>=0:he>=0,Je=!Ee||lt,Se=Math.max(28,Math.min(72,ze*.14)),Ie=Math.min(200,Se*3.5),ct=Ee&&!Je?Ie*Pe:0,ge=(_e.x+we.x)/2+Ue*ct,De=(_e.y+we.y)/2+_t*ct,Ye=Ee&&!Je?`M ${_e.x} ${_e.y} Q ${ge} ${De} ${we.x} ${we.y}`:`M ${_e.x} ${_e.y} L ${we.x} ${we.y}`,Dt=u&&X&&X[B.source]!==void 0&&X[B.target]!==void 0;return s.jsx("path",{d:Ye,className:`graph_edge ${Dt?"visited":""}`,markerEnd:"url(#arrow)",fill:"none"},B.id)}),f.map(B=>{const G=(typeof H[B.id]=="number"?H[B.id]:0)>t,T=M&&B.id===M,Q=u&&X&&X[B.id]!==void 0,K=`graph_node ${T?"active":G?"recent":""} ${Q?"visited":""}`,J=B.color||"rgba(255,255,255,0.16)";let oe=B.label||B.id,he=B.type;if(B.type==="on_schedule")he=ue(B,!!T);else if(B.type==="subflow"){const Ee=F(B);oe=Ee.label,he=Ee.sub}const _e=_w(oe,22),we=_w(he,22);return s.jsxs("g",{className:K,transform:`translate(${B.x}, ${B.y})`,children:[s.jsx("rect",{className:"graph_node_bg",width:p.node_w,height:p.node_h,rx:12,ry:12}),s.jsx("rect",{className:"graph_node_bar",width:p.node_w,height:6,rx:12,ry:12,fill:J}),s.jsx("text",{className:"graph_node_label",x:12,y:28,children:_e}),s.jsx("text",{className:"graph_node_type",x:12,y:46,children:we}),B.type==="on_schedule"?s.jsx("text",{className:"graph_node_icon",x:p.node_w-18,y:18,children:"⏰"}):null]},B.id)})]})]})}function Gs(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=Gs(e[n]))!==""&&(t+=(t&&" ")+r);else for(let n in e)e[n]&&(t+=(t&&" ")+n);return t}var rp={exports:{}},ip={},op={exports:{}},ap={};/**
|
|
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 gw;function T2(){if(gw)return ap;gw=1;var e=Uf();function t(y,w){return y===w&&(y!==0||1/y===1/w)||y!==y&&w!==w}var n=typeof Object.is=="function"?Object.is:t,r=e.useState,o=e.useEffect,l=e.useLayoutEffect,u=e.useDebugValue;function c(y,w){var x=w(),k=r({inst:{value:x,getSnapshot:w}}),j=k[0].inst,E=k[1];return l(function(){j.value=x,j.getSnapshot=w,f(j)&&E({inst:j})},[y,x,w]),o(function(){return f(j)&&E({inst:j}),y(function(){f(j)&&E({inst:j})})},[y]),u(x),x}function f(y){var w=y.getSnapshot;y=y.value;try{var x=w();return!n(y,x)}catch{return!0}}function _(y,w){return w()}var p=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?_:c;return ap.useSyncExternalStore=e.useSyncExternalStore!==void 0?e.useSyncExternalStore:p,ap}var yw;function M2(){return yw||(yw=1,op.exports=T2()),op.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 ww;function R2(){if(ww)return ip;ww=1;var e=Uf(),t=M2();function n(_,p){return _===p&&(_!==0||1/_===1/p)||_!==_&&p!==p}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 ip.useSyncExternalStoreWithSelector=function(_,p,y,w,x){var k=l(null);if(k.current===null){var j={hasValue:!1,value:null};k.current=j}else j=k.current;k=c(function(){function A(X){if(!L){if(L=!0,O=X,X=w(X),x!==void 0&&j.hasValue){var Y=j.value;if(x(Y,X))return M=Y}return M=X}if(Y=M,r(O,X))return Y;var Z=w(X);return x!==void 0&&x(Y,Z)?(O=X,Y):(O=X,M=Z)}var L=!1,O,M,H=y===void 0?null:y;return[function(){return A(p())},H===null?void 0:function(){return A(H())}]},[p,y,w,x]);var E=o(_,k[0],k[1]);return u(function(){j.hasValue=!0,j.value=E},[E]),f(E),E},ip}var vw;function L2(){return vw||(vw=1,rp.exports=R2()),rp.exports}var I2=L2();const O2=vg(I2),P2={},xw=e=>{let t;const n=new Set,r=(p,y)=>{const w=typeof p=="function"?p(t):p;if(!Object.is(w,t)){const x=t;t=y??(typeof w!="object"||w===null)?w:Object.assign({},t,w),n.forEach(k=>k(t,x))}},o=()=>t,f={setState:r,getState:o,getInitialState:()=>_,subscribe:p=>(n.add(p),()=>n.delete(p)),destroy:()=>{(P2?"production":void 0)!=="production"&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),n.clear()}},_=t=e(r,o,f);return f},D2=e=>e?xw(e):xw,{useDebugValue:F2}=ve,{useSyncExternalStoreWithSelector:z2}=O2,B2=e=>e;function ab(e,t=B2,n){const r=z2(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return F2(r),r}const bw=(e,t)=>{const n=D2(e),r=(o,l=t)=>ab(n,o,l);return Object.assign(r,n),r},U2=(e,t)=>e?bw(e,t):bw;function Ds(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 W2={value:()=>{}};function n_(){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 vm(n)}function vm(e){this._=e}function q2(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}})}vm.prototype=n_.prototype={constructor:vm,on:function(e,t){var n=this._,r=q2(e+"",n),o,l=-1,u=r.length;if(arguments.length<2){for(;++l<u;)if((o=(e=r[l]).type)&&(o=H2(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]=jw(n[o],e.name,t);else if(t==null)for(o in n)n[o]=jw(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 vm(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 H2(e,t){for(var n=0,r=e.length,o;n<r;++n)if((o=e[n]).name===t)return o.value}function jw(e,t,n){for(var r=0,o=e.length;r<o;++r)if(e[r].name===t){e[r]=W2,e=e.slice(0,r).concat(e.slice(r+1));break}return n!=null&&e.push({name:t,value:n}),e}var Zp="http://www.w3.org/1999/xhtml";const Sw={svg:"http://www.w3.org/2000/svg",xhtml:Zp,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function s_(e){var t=e+="",n=t.indexOf(":");return n>=0&&(t=e.slice(0,n))!=="xmlns"&&(e=e.slice(n+1)),Sw.hasOwnProperty(t)?{space:Sw[t],local:e}:e}function V2(e){return function(){var t=this.ownerDocument,n=this.namespaceURI;return n===Zp&&t.documentElement.namespaceURI===Zp?t.createElement(e):t.createElementNS(n,e)}}function G2(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function lb(e){var t=s_(e);return(t.local?G2:V2)(t)}function K2(){}function Fg(e){return e==null?K2:function(){return this.querySelector(e)}}function Y2(e){typeof e!="function"&&(e=Fg(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,_,p=0;p<u;++p)(f=l[p])&&(_=e.call(f,f.__data__,p,l))&&("__data__"in f&&(_.__data__=f.__data__),c[p]=_);return new li(r,this._parents)}function J2(e){return e==null?[]:Array.isArray(e)?e:Array.from(e)}function X2(){return[]}function cb(e){return e==null?X2:function(){return this.querySelectorAll(e)}}function Z2(e){return function(){return J2(e.apply(this,arguments))}}function Q2(e){typeof e=="function"?e=Z2(e):e=cb(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,_=0;_<c;++_)(f=u[_])&&(r.push(e.call(f,f.__data__,_,u)),o.push(f));return new li(r,o)}function ub(e){return function(){return this.matches(e)}}function db(e){return function(t){return t.matches(e)}}var eE=Array.prototype.find;function tE(e){return function(){return eE.call(this.children,e)}}function nE(){return this.firstElementChild}function sE(e){return this.select(e==null?nE:tE(typeof e=="function"?e:db(e)))}var rE=Array.prototype.filter;function iE(){return Array.from(this.children)}function oE(e){return function(){return rE.call(this.children,e)}}function aE(e){return this.selectAll(e==null?iE:oE(typeof e=="function"?e:db(e)))}function lE(e){typeof e!="function"&&(e=ub(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,_=0;_<u;++_)(f=l[_])&&e.call(f,f.__data__,_,l)&&c.push(f);return new li(r,this._parents)}function fb(e){return new Array(e.length)}function cE(){return new li(this._enter||this._groups.map(fb),this._parents)}function Pm(e,t){this.ownerDocument=e.ownerDocument,this.namespaceURI=e.namespaceURI,this._next=null,this._parent=e,this.__data__=t}Pm.prototype={constructor:Pm,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 uE(e){return function(){return e}}function dE(e,t,n,r,o,l){for(var u=0,c,f=t.length,_=l.length;u<_;++u)(c=t[u])?(c.__data__=l[u],r[u]=c):n[u]=new Pm(e,l[u]);for(;u<f;++u)(c=t[u])&&(o[u]=c)}function fE(e,t,n,r,o,l,u){var c,f,_=new Map,p=t.length,y=l.length,w=new Array(p),x;for(c=0;c<p;++c)(f=t[c])&&(w[c]=x=u.call(f,f.__data__,c,t)+"",_.has(x)?o[c]=f:_.set(x,f));for(c=0;c<y;++c)x=u.call(e,l[c],c,l)+"",(f=_.get(x))?(r[c]=f,f.__data__=l[c],_.delete(x)):n[c]=new Pm(e,l[c]);for(c=0;c<p;++c)(f=t[c])&&_.get(w[c])===f&&(o[c]=f)}function hE(e){return e.__data__}function mE(e,t){if(!arguments.length)return Array.from(this,hE);var n=t?fE:dE,r=this._parents,o=this._groups;typeof e!="function"&&(e=uE(e));for(var l=o.length,u=new Array(l),c=new Array(l),f=new Array(l),_=0;_<l;++_){var p=r[_],y=o[_],w=y.length,x=_E(e.call(p,p&&p.__data__,_,r)),k=x.length,j=c[_]=new Array(k),E=u[_]=new Array(k),A=f[_]=new Array(w);n(p,y,j,E,A,x,t);for(var L=0,O=0,M,H;L<k;++L)if(M=j[L]){for(L>=O&&(O=L+1);!(H=E[O])&&++O<k;);M._next=H||null}}return u=new li(u,r),u._enter=c,u._exit=f,u}function _E(e){return typeof e=="object"&&"length"in e?e:Array.from(e)}function pE(){return new li(this._exit||this._groups.map(fb),this._parents)}function gE(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 yE(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 _=n[f],p=r[f],y=_.length,w=c[f]=new Array(y),x,k=0;k<y;++k)(x=_[k]||p[k])&&(w[k]=x);for(;f<o;++f)c[f]=n[f];return new li(c,this._parents)}function wE(){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 vE(e){e||(e=xE);function t(y,w){return y&&w?e(y.__data__,w.__data__):!y-!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),_,p=0;p<c;++p)(_=u[p])&&(f[p]=_);f.sort(t)}return new li(o,this._parents).order()}function xE(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}function bE(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this}function jE(){return Array.from(this)}function SE(){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 kE(){let e=0;for(const t of this)++e;return e}function NE(){return!this.node()}function CE(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 EE(e){return function(){this.removeAttribute(e)}}function $E(e){return function(){this.removeAttributeNS(e.space,e.local)}}function AE(e,t){return function(){this.setAttribute(e,t)}}function TE(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function ME(e,t){return function(){var n=t.apply(this,arguments);n==null?this.removeAttribute(e):this.setAttribute(e,n)}}function RE(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 LE(e,t){var n=s_(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?$E:EE:typeof t=="function"?n.local?RE:ME:n.local?TE:AE)(n,t))}function hb(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function IE(e){return function(){this.style.removeProperty(e)}}function OE(e,t,n){return function(){this.style.setProperty(e,t,n)}}function PE(e,t,n){return function(){var r=t.apply(this,arguments);r==null?this.style.removeProperty(e):this.style.setProperty(e,r,n)}}function DE(e,t,n){return arguments.length>1?this.each((t==null?IE:typeof t=="function"?PE:OE)(e,t,n??"")):zu(this.node(),e)}function zu(e,t){return e.style.getPropertyValue(t)||hb(e).getComputedStyle(e,null).getPropertyValue(t)}function FE(e){return function(){delete this[e]}}function zE(e,t){return function(){this[e]=t}}function BE(e,t){return function(){var n=t.apply(this,arguments);n==null?delete this[e]:this[e]=n}}function UE(e,t){return arguments.length>1?this.each((t==null?FE:typeof t=="function"?BE:zE)(e,t)):this.node()[e]}function mb(e){return e.trim().split(/^|\s+/)}function zg(e){return e.classList||new _b(e)}function _b(e){this._node=e,this._names=mb(e.getAttribute("class")||"")}_b.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 pb(e,t){for(var n=zg(e),r=-1,o=t.length;++r<o;)n.add(t[r])}function gb(e,t){for(var n=zg(e),r=-1,o=t.length;++r<o;)n.remove(t[r])}function WE(e){return function(){pb(this,e)}}function qE(e){return function(){gb(this,e)}}function HE(e,t){return function(){(t.apply(this,arguments)?pb:gb)(this,e)}}function VE(e,t){var n=mb(e+"");if(arguments.length<2){for(var r=zg(this.node()),o=-1,l=n.length;++o<l;)if(!r.contains(n[o]))return!1;return!0}return this.each((typeof t=="function"?HE:t?WE:qE)(n,t))}function GE(){this.textContent=""}function KE(e){return function(){this.textContent=e}}function YE(e){return function(){var t=e.apply(this,arguments);this.textContent=t??""}}function JE(e){return arguments.length?this.each(e==null?GE:(typeof e=="function"?YE:KE)(e)):this.node().textContent}function XE(){this.innerHTML=""}function ZE(e){return function(){this.innerHTML=e}}function QE(e){return function(){var t=e.apply(this,arguments);this.innerHTML=t??""}}function e$(e){return arguments.length?this.each(e==null?XE:(typeof e=="function"?QE:ZE)(e)):this.node().innerHTML}function t$(){this.nextSibling&&this.parentNode.appendChild(this)}function n$(){return this.each(t$)}function s$(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function r$(){return this.each(s$)}function i$(e){var t=typeof e=="function"?e:lb(e);return this.select(function(){return this.appendChild(t.apply(this,arguments))})}function o$(){return null}function a$(e,t){var n=typeof e=="function"?e:lb(e),r=t==null?o$:typeof t=="function"?t:Fg(t);return this.select(function(){return this.insertBefore(n.apply(this,arguments),r.apply(this,arguments)||null)})}function l$(){var e=this.parentNode;e&&e.removeChild(this)}function c$(){return this.each(l$)}function u$(){var e=this.cloneNode(!1),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function d$(){var e=this.cloneNode(!0),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function f$(e){return this.select(e?d$:u$)}function h$(e){return arguments.length?this.property("__data__",e):this.node().__data__}function m$(e){return function(t){e.call(this,t,this.__data__)}}function _$(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 p$(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 g$(e,t,n){return function(){var r=this.__on,o,l=m$(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 y$(e,t,n){var r=_$(e+""),o,l=r.length,u;if(arguments.length<2){var c=this.node().__on;if(c){for(var f=0,_=c.length,p;f<_;++f)for(o=0,p=c[f];o<l;++o)if((u=r[o]).type===p.type&&u.name===p.name)return p.value}return}for(c=t?g$:p$,o=0;o<l;++o)this.each(c(r[o],t,n));return this}function yb(e,t,n){var r=hb(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 w$(e,t){return function(){return yb(this,e,t)}}function v$(e,t){return function(){return yb(this,e,t.apply(this,arguments))}}function x$(e,t){return this.each((typeof t=="function"?v$:w$)(e,t))}function*b$(){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 wb=[null];function li(e,t){this._groups=e,this._parents=t}function Gf(){return new li([[document.documentElement]],wb)}function j$(){return this}li.prototype=Gf.prototype={constructor:li,select:Y2,selectAll:Q2,selectChild:sE,selectChildren:aE,filter:lE,data:mE,enter:cE,exit:pE,join:gE,merge:yE,selection:j$,order:wE,sort:vE,call:bE,nodes:jE,node:SE,size:kE,empty:NE,each:CE,attr:LE,style:DE,property:UE,classed:VE,text:JE,html:e$,raise:n$,lower:r$,append:i$,insert:a$,remove:c$,clone:f$,datum:h$,on:y$,dispatch:x$,[Symbol.iterator]:b$};function Ei(e){return typeof e=="string"?new li([[document.querySelector(e)]],[document.documentElement]):new li([[e]],wb)}function S$(e){let t;for(;t=e.sourceEvent;)e=t;return e}function to(e,t){if(e=S$(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 k$={passive:!1},Tf={capture:!0,passive:!1};function lp(e){e.stopImmediatePropagation()}function Lu(e){e.preventDefault(),e.stopImmediatePropagation()}function vb(e){var t=e.document.documentElement,n=Ei(e).on("dragstart.drag",Lu,Tf);"onselectstart"in t?n.on("selectstart.drag",Lu,Tf):(t.__noselect=t.style.MozUserSelect,t.style.MozUserSelect="none")}function xb(e,t){var n=e.document.documentElement,r=Ei(e).on("dragstart.drag",null);t&&(r.on("click.drag",Lu,Tf),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 sm=e=>()=>e;function Qp(e,{sourceEvent:t,subject:n,target:r,identifier:o,active:l,x:u,y:c,dx:f,dy:_,dispatch:p}){Object.defineProperties(this,{type:{value:e,enumerable:!0,configurable:!0},sourceEvent:{value:t,enumerable:!0,configurable:!0},subject:{value:n,enumerable:!0,configurable:!0},target:{value: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:_,enumerable:!0,configurable:!0},_:{value:p}})}Qp.prototype.on=function(){var e=this._.on.apply(this._,arguments);return e===this._?this:e};function N$(e){return!e.ctrlKey&&!e.button}function C$(){return this.parentNode}function E$(e,t){return t??{x:e.x,y:e.y}}function $$(){return navigator.maxTouchPoints||"ontouchstart"in this}function A$(){var e=N$,t=C$,n=E$,r=$$,o={},l=n_("start","drag","end"),u=0,c,f,_,p,y=0;function w(M){M.on("mousedown.drag",x).filter(r).on("touchstart.drag",E).on("touchmove.drag",A,k$).on("touchend.drag touchcancel.drag",L).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function x(M,H){if(!(p||!e.call(this,M,H))){var X=O(this,t.call(this,M,H),M,H,"mouse");X&&(Ei(M.view).on("mousemove.drag",k,Tf).on("mouseup.drag",j,Tf),vb(M.view),lp(M),_=!1,c=M.clientX,f=M.clientY,X("start",M))}}function k(M){if(Lu(M),!_){var H=M.clientX-c,X=M.clientY-f;_=H*H+X*X>y}o.mouse("drag",M)}function j(M){Ei(M.view).on("mousemove.drag mouseup.drag",null),xb(M.view,_),Lu(M),o.mouse("end",M)}function E(M,H){if(e.call(this,M,H)){var X=M.changedTouches,Y=t.call(this,M,H),Z=X.length,re,ie;for(re=0;re<Z;++re)(ie=O(this,Y,M,H,X[re].identifier,X[re]))&&(lp(M),ie("start",M,X[re]))}}function A(M){var H=M.changedTouches,X=H.length,Y,Z;for(Y=0;Y<X;++Y)(Z=o[H[Y].identifier])&&(Lu(M),Z("drag",M,H[Y]))}function L(M){var H=M.changedTouches,X=H.length,Y,Z;for(p&&clearTimeout(p),p=setTimeout(function(){p=null},500),Y=0;Y<X;++Y)(Z=o[H[Y].identifier])&&(lp(M),Z("end",M,H[Y]))}function O(M,H,X,Y,Z,re){var ie=l.copy(),ue=to(re||X,H),F,C,N;if((N=n.call(M,new Qp("beforestart",{sourceEvent:X,target:w,identifier:Z,active:u,x:ue[0],y:ue[1],dx:0,dy:0,dispatch:ie}),Y))!=null)return F=N.x-ue[0]||0,C=N.y-ue[1]||0,function P(D,ne,B){var z=ue,G;switch(D){case"start":o[Z]=P,G=u++;break;case"end":delete o[Z],--u;case"drag":ue=to(B||ne,H),G=u;break}ie.call(D,M,new Qp(D,{sourceEvent:ne,subject:N,target:w,identifier:Z,active:G,x:ue[0]+F,y:ue[1]+C,dx:ue[0]-z[0],dy:ue[1]-z[1],dispatch:ie}),Y)}}return w.filter=function(M){return arguments.length?(e=typeof M=="function"?M:sm(!!M),w):e},w.container=function(M){return arguments.length?(t=typeof M=="function"?M:sm(M),w):t},w.subject=function(M){return arguments.length?(n=typeof M=="function"?M:sm(M),w):n},w.touchable=function(M){return arguments.length?(r=typeof M=="function"?M:sm(!!M),w):r},w.on=function(){var M=l.on.apply(l,arguments);return M===l?w:M},w.clickDistance=function(M){return arguments.length?(y=(M=+M)*M,w):Math.sqrt(y)},w}function Bg(e,t,n){e.prototype=t.prototype=n,n.constructor=e}function bb(e,t){var n=Object.create(e.prototype);for(var r in t)n[r]=t[r];return n}function Kf(){}var Mf=.7,Dm=1/Mf,Iu="\\s*([+-]?\\d+)\\s*",Rf="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",zo="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",T$=/^#([0-9a-f]{3,8})$/,M$=new RegExp(`^rgb\\(${Iu},${Iu},${Iu}\\)$`),R$=new RegExp(`^rgb\\(${zo},${zo},${zo}\\)$`),L$=new RegExp(`^rgba\\(${Iu},${Iu},${Iu},${Rf}\\)$`),I$=new RegExp(`^rgba\\(${zo},${zo},${zo},${Rf}\\)$`),O$=new RegExp(`^hsl\\(${Rf},${zo},${zo}\\)$`),P$=new RegExp(`^hsla\\(${Rf},${zo},${zo},${Rf}\\)$`),kw={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074};Bg(Kf,Lf,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:Nw,formatHex:Nw,formatHex8:D$,formatHsl:F$,formatRgb:Cw,toString:Cw});function Nw(){return this.rgb().formatHex()}function D$(){return this.rgb().formatHex8()}function F$(){return jb(this).formatHsl()}function Cw(){return this.rgb().formatRgb()}function Lf(e){var t,n;return e=(e+"").trim().toLowerCase(),(t=T$.exec(e))?(n=t[1].length,t=parseInt(t[1],16),n===6?Ew(t):n===3?new qr(t>>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):n===8?rm(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?rm(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=M$.exec(e))?new qr(t[1],t[2],t[3],1):(t=R$.exec(e))?new qr(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=L$.exec(e))?rm(t[1],t[2],t[3],t[4]):(t=I$.exec(e))?rm(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=O$.exec(e))?Tw(t[1],t[2]/100,t[3]/100,1):(t=P$.exec(e))?Tw(t[1],t[2]/100,t[3]/100,t[4]):kw.hasOwnProperty(e)?Ew(kw[e]):e==="transparent"?new qr(NaN,NaN,NaN,0):null}function Ew(e){return new qr(e>>16&255,e>>8&255,e&255,1)}function rm(e,t,n,r){return r<=0&&(e=t=n=NaN),new qr(e,t,n,r)}function z$(e){return e instanceof Kf||(e=Lf(e)),e?(e=e.rgb(),new qr(e.r,e.g,e.b,e.opacity)):new qr}function eg(e,t,n,r){return arguments.length===1?z$(e):new qr(e,t,n,r??1)}function qr(e,t,n,r){this.r=+e,this.g=+t,this.b=+n,this.opacity=+r}Bg(qr,eg,bb(Kf,{brighter(e){return e=e==null?Dm:Math.pow(Dm,e),new qr(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=e==null?Mf:Math.pow(Mf,e),new qr(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new qr(cc(this.r),cc(this.g),cc(this.b),Fm(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:$w,formatHex:$w,formatHex8:B$,formatRgb:Aw,toString:Aw}));function $w(){return`#${rc(this.r)}${rc(this.g)}${rc(this.b)}`}function B$(){return`#${rc(this.r)}${rc(this.g)}${rc(this.b)}${rc((isNaN(this.opacity)?1:this.opacity)*255)}`}function Aw(){const e=Fm(this.opacity);return`${e===1?"rgb(":"rgba("}${cc(this.r)}, ${cc(this.g)}, ${cc(this.b)}${e===1?")":`, ${e})`}`}function Fm(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function cc(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function rc(e){return e=cc(e),(e<16?"0":"")+e.toString(16)}function Tw(e,t,n,r){return r<=0?e=t=n=NaN:n<=0||n>=1?e=t=NaN:t<=0&&(e=NaN),new so(e,t,n,r)}function jb(e){if(e instanceof so)return new so(e.h,e.s,e.l,e.opacity);if(e instanceof Kf||(e=Lf(e)),!e)return new so;if(e instanceof so)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 so(u,c,f,e.opacity)}function U$(e,t,n,r){return arguments.length===1?jb(e):new so(e,t,n,r??1)}function so(e,t,n,r){this.h=+e,this.s=+t,this.l=+n,this.opacity=+r}Bg(so,U$,bb(Kf,{brighter(e){return e=e==null?Dm:Math.pow(Dm,e),new so(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?Mf:Math.pow(Mf,e),new so(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 qr(cp(e>=240?e-240:e+120,o,r),cp(e,o,r),cp(e<120?e+240:e-120,o,r),this.opacity)},clamp(){return new so(Mw(this.h),im(this.s),im(this.l),Fm(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=Fm(this.opacity);return`${e===1?"hsl(":"hsla("}${Mw(this.h)}, ${im(this.s)*100}%, ${im(this.l)*100}%${e===1?")":`, ${e})`}`}}));function Mw(e){return e=(e||0)%360,e<0?e+360:e}function im(e){return Math.max(0,Math.min(1,e||0))}function cp(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 Sb=e=>()=>e;function W$(e,t){return function(n){return e+n*t}}function q$(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 H$(e){return(e=+e)==1?kb:function(t,n){return n-t?q$(t,n,e):Sb(isNaN(t)?n:t)}}function kb(e,t){var n=t-e;return n?W$(e,n):Sb(isNaN(e)?t:e)}const Rw=(function e(t){var n=H$(t);function r(o,l){var u=n((o=eg(o)).r,(l=eg(l)).r),c=n(o.g,l.g),f=n(o.b,l.b),_=kb(o.opacity,l.opacity);return function(p){return o.r=u(p),o.g=c(p),o.b=f(p),o.opacity=_(p),o+""}}return r.gamma=e,r})(1);function vl(e,t){return e=+e,t=+t,function(n){return e*(1-n)+t*n}}var tg=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,up=new RegExp(tg.source,"g");function V$(e){return function(){return e}}function G$(e){return function(t){return e(t)+""}}function K$(e,t){var n=tg.lastIndex=up.lastIndex=0,r,o,l,u=-1,c=[],f=[];for(e=e+"",t=t+"";(r=tg.exec(e))&&(o=up.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:vl(r,o)})),n=up.lastIndex;return n<t.length&&(l=t.slice(n),c[u]?c[u]+=l:c[++u]=l),c.length<2?f[0]?G$(f[0].x):V$(t):(t=f.length,function(_){for(var p=0,y;p<t;++p)c[(y=f[p]).i]=y.x(_);return c.join("")})}var Lw=180/Math.PI,ng={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function Nb(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)*Lw,skewX:Math.atan(f)*Lw,scaleX:u,scaleY:c}}var om;function Y$(e){const t=new(typeof DOMMatrix=="function"?DOMMatrix:WebKitCSSMatrix)(e+"");return t.isIdentity?ng:Nb(t.a,t.b,t.c,t.d,t.e,t.f)}function J$(e){return e==null||(om||(om=document.createElementNS("http://www.w3.org/2000/svg","g")),om.setAttribute("transform",e),!(e=om.transform.baseVal.consolidate()))?ng:(e=e.matrix,Nb(e.a,e.b,e.c,e.d,e.e,e.f))}function Cb(e,t,n,r){function o(_){return _.length?_.pop()+" ":""}function l(_,p,y,w,x,k){if(_!==y||p!==w){var j=x.push("translate(",null,t,null,n);k.push({i:j-4,x:vl(_,y)},{i:j-2,x:vl(p,w)})}else(y||w)&&x.push("translate("+y+t+w+n)}function u(_,p,y,w){_!==p?(_-p>180?p+=360:p-_>180&&(_+=360),w.push({i:y.push(o(y)+"rotate(",null,r)-2,x:vl(_,p)})):p&&y.push(o(y)+"rotate("+p+r)}function c(_,p,y,w){_!==p?w.push({i:y.push(o(y)+"skewX(",null,r)-2,x:vl(_,p)}):p&&y.push(o(y)+"skewX("+p+r)}function f(_,p,y,w,x,k){if(_!==y||p!==w){var j=x.push(o(x)+"scale(",null,",",null,")");k.push({i:j-4,x:vl(_,y)},{i:j-2,x:vl(p,w)})}else(y!==1||w!==1)&&x.push(o(x)+"scale("+y+","+w+")")}return function(_,p){var y=[],w=[];return _=e(_),p=e(p),l(_.translateX,_.translateY,p.translateX,p.translateY,y,w),u(_.rotate,p.rotate,y,w),c(_.skewX,p.skewX,y,w),f(_.scaleX,_.scaleY,p.scaleX,p.scaleY,y,w),_=p=null,function(x){for(var k=-1,j=w.length,E;++k<j;)y[(E=w[k]).i]=E.x(x);return y.join("")}}}var X$=Cb(Y$,"px, ","px)","deg)"),Z$=Cb(J$,", ",")",")"),Q$=1e-12;function Iw(e){return((e=Math.exp(e))+1/e)/2}function eA(e){return((e=Math.exp(e))-1/e)/2}function tA(e){return((e=Math.exp(2*e))-1)/(e+1)}const nA=(function e(t,n,r){function o(l,u){var c=l[0],f=l[1],_=l[2],p=u[0],y=u[1],w=u[2],x=p-c,k=y-f,j=x*x+k*k,E,A;if(j<Q$)A=Math.log(w/_)/t,E=function(Y){return[c+Y*x,f+Y*k,_*Math.exp(t*Y*A)]};else{var L=Math.sqrt(j),O=(w*w-_*_+r*j)/(2*_*n*L),M=(w*w-_*_-r*j)/(2*w*n*L),H=Math.log(Math.sqrt(O*O+1)-O),X=Math.log(Math.sqrt(M*M+1)-M);A=(X-H)/t,E=function(Y){var Z=Y*A,re=Iw(H),ie=_/(n*L)*(re*tA(t*Z+H)-eA(H));return[c+ie*x,f+ie*k,_*re/Iw(t*Z+H)]}}return E.duration=A*1e3*t/Math.SQRT2,E}return o.rho=function(l){var u=Math.max(.001,+l),c=u*u,f=c*c;return e(u,c,f)},o})(Math.SQRT2,2,4);var Bu=0,kf=0,mf=0,Eb=1e3,zm,Nf,Bm=0,hc=0,r_=0,If=typeof performance=="object"&&performance.now?performance:Date,$b=typeof window=="object"&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(e){setTimeout(e,17)};function Ug(){return hc||($b(sA),hc=If.now()+r_)}function sA(){hc=0}function Um(){this._call=this._time=this._next=null}Um.prototype=Ab.prototype={constructor:Um,restart:function(e,t,n){if(typeof e!="function")throw new TypeError("callback is not a function");n=(n==null?Ug():+n)+(t==null?0:+t),!this._next&&Nf!==this&&(Nf?Nf._next=this:zm=this,Nf=this),this._call=e,this._time=n,sg()},stop:function(){this._call&&(this._call=null,this._time=1/0,sg())}};function Ab(e,t,n){var r=new Um;return r.restart(e,t,n),r}function rA(){Ug(),++Bu;for(var e=zm,t;e;)(t=hc-e._time)>=0&&e._call.call(void 0,t),e=e._next;--Bu}function Ow(){hc=(Bm=If.now())+r_,Bu=kf=0;try{rA()}finally{Bu=0,oA(),hc=0}}function iA(){var e=If.now(),t=e-Bm;t>Eb&&(r_-=t,Bm=e)}function oA(){for(var e,t=zm,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:zm=n);Nf=e,sg(r)}function sg(e){if(!Bu){kf&&(kf=clearTimeout(kf));var t=e-hc;t>24?(e<1/0&&(kf=setTimeout(Ow,e-If.now()-r_)),mf&&(mf=clearInterval(mf))):(mf||(Bm=If.now(),mf=setInterval(iA,Eb)),Bu=1,$b(Ow))}}function Pw(e,t,n){var r=new Um;return t=t==null?0:+t,r.restart(o=>{r.stop(),e(o+t)},t,n),r}var aA=n_("start","end","cancel","interrupt"),lA=[],Tb=0,Dw=1,rg=2,xm=3,Fw=4,ig=5,bm=6;function i_(e,t,n,r,o,l){var u=e.__transition;if(!u)e.__transition={};else if(n in u)return;cA(e,n,{name:t,index:r,group:o,on:aA,tween:lA,time:l.time,delay:l.delay,duration:l.duration,ease:l.ease,timer:null,state:Tb})}function Wg(e,t){var n=oo(e,t);if(n.state>Tb)throw new Error("too late; already scheduled");return n}function Bo(e,t){var n=oo(e,t);if(n.state>xm)throw new Error("too late; already running");return n}function oo(e,t){var n=e.__transition;if(!n||!(n=n[t]))throw new Error("transition not found");return n}function cA(e,t,n){var r=e.__transition,o;r[t]=n,n.timer=Ab(l,0,n.time);function l(_){n.state=Dw,n.timer.restart(u,n.delay,n.time),n.delay<=_&&u(_-n.delay)}function u(_){var p,y,w,x;if(n.state!==Dw)return f();for(p in r)if(x=r[p],x.name===n.name){if(x.state===xm)return Pw(u);x.state===Fw?(x.state=bm,x.timer.stop(),x.on.call("interrupt",e,e.__data__,x.index,x.group),delete r[p]):+p<t&&(x.state=bm,x.timer.stop(),x.on.call("cancel",e,e.__data__,x.index,x.group),delete r[p])}if(Pw(function(){n.state===xm&&(n.state=Fw,n.timer.restart(c,n.delay,n.time),c(_))}),n.state=rg,n.on.call("start",e,e.__data__,n.index,n.group),n.state===rg){for(n.state=xm,o=new Array(w=n.tween.length),p=0,y=-1;p<w;++p)(x=n.tween[p].value.call(e,e.__data__,n.index,n.group))&&(o[++y]=x);o.length=y+1}}function c(_){for(var p=_<n.duration?n.ease.call(null,_/n.duration):(n.timer.restart(f),n.state=ig,1),y=-1,w=o.length;++y<w;)o[y].call(e,p);n.state===ig&&(n.on.call("end",e,e.__data__,n.index,n.group),f())}function f(){n.state=bm,n.timer.stop(),delete r[t];for(var _ in r)return;delete e.__transition}}function jm(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>rg&&r.state<ig,r.state=bm,r.timer.stop(),r.on.call(o?"interrupt":"cancel",e,e.__data__,r.index,r.group),delete n[u]}l&&delete e.__transition}}function uA(e){return this.each(function(){jm(this,e)})}function dA(e,t){var n,r;return function(){var o=Bo(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 fA(e,t,n){var r,o;if(typeof n!="function")throw new Error;return function(){var l=Bo(this,e),u=l.tween;if(u!==r){o=(r=u).slice();for(var c={name:t,value:n},f=0,_=o.length;f<_;++f)if(o[f].name===t){o[f]=c;break}f===_&&o.push(c)}l.tween=o}}function hA(e,t){var n=this._id;if(e+="",arguments.length<2){for(var r=oo(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?dA:fA)(n,e,t))}function qg(e,t,n){var r=e._id;return e.each(function(){var o=Bo(this,r);(o.value||(o.value={}))[t]=n.apply(this,arguments)}),function(o){return oo(o,r).value[t]}}function Mb(e,t){var n;return(typeof t=="number"?vl:t instanceof Lf?Rw:(n=Lf(t))?(t=n,Rw):K$)(e,t)}function mA(e){return function(){this.removeAttribute(e)}}function _A(e){return function(){this.removeAttributeNS(e.space,e.local)}}function pA(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 gA(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 yA(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 wA(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 vA(e,t){var n=s_(e),r=n==="transform"?Z$:Mb;return this.attrTween(e,typeof t=="function"?(n.local?wA:yA)(n,r,qg(this,"attr."+e,t)):t==null?(n.local?_A:mA)(n):(n.local?gA:pA)(n,r,t))}function xA(e,t){return function(n){this.setAttribute(e,t.call(this,n))}}function bA(e,t){return function(n){this.setAttributeNS(e.space,e.local,t.call(this,n))}}function jA(e,t){var n,r;function o(){var l=t.apply(this,arguments);return l!==r&&(n=(r=l)&&bA(e,l)),n}return o._value=t,o}function SA(e,t){var n,r;function o(){var l=t.apply(this,arguments);return l!==r&&(n=(r=l)&&xA(e,l)),n}return o._value=t,o}function kA(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=s_(e);return this.tween(n,(r.local?jA:SA)(r,t))}function NA(e,t){return function(){Wg(this,e).delay=+t.apply(this,arguments)}}function CA(e,t){return t=+t,function(){Wg(this,e).delay=t}}function EA(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?NA:CA)(t,e)):oo(this.node(),t).delay}function $A(e,t){return function(){Bo(this,e).duration=+t.apply(this,arguments)}}function AA(e,t){return t=+t,function(){Bo(this,e).duration=t}}function TA(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?$A:AA)(t,e)):oo(this.node(),t).duration}function MA(e,t){if(typeof t!="function")throw new Error;return function(){Bo(this,e).ease=t}}function RA(e){var t=this._id;return arguments.length?this.each(MA(t,e)):oo(this.node(),t).ease}function LA(e,t){return function(){var n=t.apply(this,arguments);if(typeof n!="function")throw new Error;Bo(this,e).ease=n}}function IA(e){if(typeof e!="function")throw new Error;return this.each(LA(this._id,e))}function OA(e){typeof e!="function"&&(e=ub(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,_=0;_<u;++_)(f=l[_])&&e.call(f,f.__data__,_,l)&&c.push(f);return new ba(r,this._parents,this._name,this._id)}function PA(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],_=n[c],p=f.length,y=u[c]=new Array(p),w,x=0;x<p;++x)(w=f[x]||_[x])&&(y[x]=w);for(;c<r;++c)u[c]=t[c];return new ba(u,this._parents,this._name,this._id)}function DA(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 FA(e,t,n){var r,o,l=DA(t)?Wg:Bo;return function(){var u=l(this,e),c=u.on;c!==r&&(o=(r=c).copy()).on(t,n),u.on=o}}function zA(e,t){var n=this._id;return arguments.length<2?oo(this.node(),n).on.on(e):this.each(FA(n,e,t))}function BA(e){return function(){var t=this.parentNode;for(var n in this.__transition)if(+n!==e)return;t&&t.removeChild(this)}}function UA(){return this.on("end.remove",BA(this._id))}function WA(e){var t=this._name,n=this._id;typeof e!="function"&&(e=Fg(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,_=l[u]=new Array(f),p,y,w=0;w<f;++w)(p=c[w])&&(y=e.call(p,p.__data__,w,c))&&("__data__"in p&&(y.__data__=p.__data__),_[w]=y,i_(_[w],t,n,w,_,oo(p,n)));return new ba(l,this._parents,t,n)}function qA(e){var t=this._name,n=this._id;typeof e!="function"&&(e=cb(e));for(var r=this._groups,o=r.length,l=[],u=[],c=0;c<o;++c)for(var f=r[c],_=f.length,p,y=0;y<_;++y)if(p=f[y]){for(var w=e.call(p,p.__data__,y,f),x,k=oo(p,n),j=0,E=w.length;j<E;++j)(x=w[j])&&i_(x,t,n,j,w,k);l.push(w),u.push(p)}return new ba(l,u,t,n)}var HA=Gf.prototype.constructor;function VA(){return new HA(this._groups,this._parents)}function GA(e,t){var n,r,o;return function(){var l=zu(this,e),u=(this.style.removeProperty(e),zu(this,e));return l===u?null:l===n&&u===r?o:o=t(n=l,r=u)}}function Rb(e){return function(){this.style.removeProperty(e)}}function KA(e,t,n){var r,o=n+"",l;return function(){var u=zu(this,e);return u===o?null:u===r?l:l=t(r=u,n)}}function YA(e,t,n){var r,o,l;return function(){var u=zu(this,e),c=n(this),f=c+"";return c==null&&(f=c=(this.style.removeProperty(e),zu(this,e))),u===f?null:u===r&&f===o?l:(o=f,l=t(r=u,c))}}function JA(e,t){var n,r,o,l="style."+t,u="end."+l,c;return function(){var f=Bo(this,e),_=f.on,p=f.value[l]==null?c||(c=Rb(t)):void 0;(_!==n||o!==p)&&(r=(n=_).copy()).on(u,o=p),f.on=r}}function XA(e,t,n){var r=(e+="")=="transform"?X$:Mb;return t==null?this.styleTween(e,GA(e,r)).on("end.style."+e,Rb(e)):typeof t=="function"?this.styleTween(e,YA(e,r,qg(this,"style."+e,t))).each(JA(this._id,e)):this.styleTween(e,KA(e,r,t),n).on("end.style."+e,null)}function ZA(e,t,n){return function(r){this.style.setProperty(e,t.call(this,r),n)}}function QA(e,t,n){var r,o;function l(){var u=t.apply(this,arguments);return u!==o&&(r=(o=u)&&ZA(e,u,n)),r}return l._value=t,l}function eT(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,QA(e,t,n??""))}function tT(e){return function(){this.textContent=e}}function nT(e){return function(){var t=e(this);this.textContent=t??""}}function sT(e){return this.tween("text",typeof e=="function"?nT(qg(this,"text",e)):tT(e==null?"":e+""))}function rT(e){return function(t){this.textContent=e.call(this,t)}}function iT(e){var t,n;function r(){var o=e.apply(this,arguments);return o!==n&&(t=(n=o)&&rT(o)),t}return r._value=e,r}function oT(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,iT(e))}function aT(){for(var e=this._name,t=this._id,n=Lb(),r=this._groups,o=r.length,l=0;l<o;++l)for(var u=r[l],c=u.length,f,_=0;_<c;++_)if(f=u[_]){var p=oo(f,t);i_(f,e,n,_,u,{time:p.time+p.delay+p.duration,delay:0,duration:p.duration,ease:p.ease})}return new ba(r,this._parents,e,n)}function lT(){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 _=Bo(this,r),p=_.on;p!==e&&(t=(e=p).copy(),t._.cancel.push(c),t._.interrupt.push(c),t._.end.push(f)),_.on=t}),o===0&&l()})}var cT=0;function ba(e,t,n,r){this._groups=e,this._parents=t,this._name=n,this._id=r}function Lb(){return++cT}var pa=Gf.prototype;ba.prototype={constructor:ba,select:WA,selectAll:qA,selectChild:pa.selectChild,selectChildren:pa.selectChildren,filter:OA,merge:PA,selection:VA,transition:aT,call:pa.call,nodes:pa.nodes,node:pa.node,size:pa.size,empty:pa.empty,each:pa.each,on:zA,attr:vA,attrTween:kA,style:XA,styleTween:eT,text:sT,textTween:oT,remove:UA,tween:hA,delay:EA,duration:TA,ease:RA,easeVarying:IA,end:lT,[Symbol.iterator]:pa[Symbol.iterator]};function uT(e){return((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2}var dT={time:null,delay:0,duration:250,ease:uT};function fT(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 hT(e){var t,n;e instanceof ba?(t=e._id,e=e._name):(t=Lb(),(n=dT).time=Ug(),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,_=0;_<c;++_)(f=u[_])&&i_(f,e,t,_,u,n||fT(f,t));return new ba(r,this._parents,e,t)}Gf.prototype.interrupt=uA;Gf.prototype.transition=hT;const am=e=>()=>e;function mT(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 ga(e,t,n){this.k=e,this.x=t,this.y=n}ga.prototype={constructor:ga,scale:function(e){return e===1?this:new ga(this.k*e,this.x,this.y)},translate:function(e,t){return e===0&t===0?this:new ga(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 wa=new ga(1,0,0);ga.prototype;function dp(e){e.stopImmediatePropagation()}function _f(e){e.preventDefault(),e.stopImmediatePropagation()}function _T(e){return(!e.ctrlKey||e.type==="wheel")&&!e.button}function pT(){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 zw(){return this.__zoom||wa}function gT(e){return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*(e.ctrlKey?10:1)}function yT(){return navigator.maxTouchPoints||"ontouchstart"in this}function wT(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 Ib(){var e=_T,t=pT,n=wT,r=gT,o=yT,l=[0,1/0],u=[[-1/0,-1/0],[1/0,1/0]],c=250,f=nA,_=n_("start","zoom","end"),p,y,w,x=500,k=150,j=0,E=10;function A(N){N.property("__zoom",zw).on("wheel.zoom",Z,{passive:!1}).on("mousedown.zoom",re).on("dblclick.zoom",ie).filter(o).on("touchstart.zoom",ue).on("touchmove.zoom",F).on("touchend.zoom touchcancel.zoom",C).style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}A.transform=function(N,P,D,ne){var B=N.selection?N.selection():N;B.property("__zoom",zw),N!==B?H(N,P,D,ne):B.interrupt().each(function(){X(this,arguments).event(ne).start().zoom(null,typeof P=="function"?P.apply(this,arguments):P).end()})},A.scaleBy=function(N,P,D,ne){A.scaleTo(N,function(){var B=this.__zoom.k,z=typeof P=="function"?P.apply(this,arguments):P;return B*z},D,ne)},A.scaleTo=function(N,P,D,ne){A.transform(N,function(){var B=t.apply(this,arguments),z=this.__zoom,G=D==null?M(B):typeof D=="function"?D.apply(this,arguments):D,T=z.invert(G),Q=typeof P=="function"?P.apply(this,arguments):P;return n(O(L(z,Q),G,T),B,u)},D,ne)},A.translateBy=function(N,P,D,ne){A.transform(N,function(){return n(this.__zoom.translate(typeof P=="function"?P.apply(this,arguments):P,typeof D=="function"?D.apply(this,arguments):D),t.apply(this,arguments),u)},null,ne)},A.translateTo=function(N,P,D,ne,B){A.transform(N,function(){var z=t.apply(this,arguments),G=this.__zoom,T=ne==null?M(z):typeof ne=="function"?ne.apply(this,arguments):ne;return n(wa.translate(T[0],T[1]).scale(G.k).translate(typeof P=="function"?-P.apply(this,arguments):-P,typeof D=="function"?-D.apply(this,arguments):-D),z,u)},ne,B)};function L(N,P){return P=Math.max(l[0],Math.min(l[1],P)),P===N.k?N:new ga(P,N.x,N.y)}function O(N,P,D){var ne=P[0]-D[0]*N.k,B=P[1]-D[1]*N.k;return ne===N.x&&B===N.y?N:new ga(N.k,ne,B)}function M(N){return[(+N[0][0]+ +N[1][0])/2,(+N[0][1]+ +N[1][1])/2]}function H(N,P,D,ne){N.on("start.zoom",function(){X(this,arguments).event(ne).start()}).on("interrupt.zoom end.zoom",function(){X(this,arguments).event(ne).end()}).tween("zoom",function(){var B=this,z=arguments,G=X(B,z).event(ne),T=t.apply(B,z),Q=D==null?M(T):typeof D=="function"?D.apply(B,z):D,K=Math.max(T[1][0]-T[0][0],T[1][1]-T[0][1]),J=B.__zoom,oe=typeof P=="function"?P.apply(B,z):P,he=f(J.invert(Q).concat(K/J.k),oe.invert(Q).concat(K/oe.k));return function(_e){if(_e===1)_e=oe;else{var we=he(_e),Ee=K/we[2];_e=new ga(Ee,Q[0]-we[0]*Ee,Q[1]-we[1]*Ee)}G.zoom(null,_e)}})}function X(N,P,D){return!D&&N.__zooming||new Y(N,P)}function Y(N,P){this.that=N,this.args=P,this.active=0,this.sourceEvent=null,this.extent=t.apply(N,P),this.taps=0}Y.prototype={event:function(N){return N&&(this.sourceEvent=N),this},start:function(){return++this.active===1&&(this.that.__zooming=this,this.emit("start")),this},zoom:function(N,P){return this.mouse&&N!=="mouse"&&(this.mouse[1]=P.invert(this.mouse[0])),this.touch0&&N!=="touch"&&(this.touch0[1]=P.invert(this.touch0[0])),this.touch1&&N!=="touch"&&(this.touch1[1]=P.invert(this.touch1[0])),this.that.__zoom=P,this.emit("zoom"),this},end:function(){return--this.active===0&&(delete this.that.__zooming,this.emit("end")),this},emit:function(N){var P=Ei(this.that).datum();_.call(N,this.that,new mT(N,{sourceEvent:this.sourceEvent,target:A,transform:this.that.__zoom,dispatch:_}),P)}};function Z(N,...P){if(!e.apply(this,arguments))return;var D=X(this,P).event(N),ne=this.__zoom,B=Math.max(l[0],Math.min(l[1],ne.k*Math.pow(2,r.apply(this,arguments)))),z=to(N);if(D.wheel)(D.mouse[0][0]!==z[0]||D.mouse[0][1]!==z[1])&&(D.mouse[1]=ne.invert(D.mouse[0]=z)),clearTimeout(D.wheel);else{if(ne.k===B)return;D.mouse=[z,ne.invert(z)],jm(this),D.start()}_f(N),D.wheel=setTimeout(G,k),D.zoom("mouse",n(O(L(ne,B),D.mouse[0],D.mouse[1]),D.extent,u));function G(){D.wheel=null,D.end()}}function re(N,...P){if(w||!e.apply(this,arguments))return;var D=N.currentTarget,ne=X(this,P,!0).event(N),B=Ei(N.view).on("mousemove.zoom",Q,!0).on("mouseup.zoom",K,!0),z=to(N,D),G=N.clientX,T=N.clientY;vb(N.view),dp(N),ne.mouse=[z,this.__zoom.invert(z)],jm(this),ne.start();function Q(J){if(_f(J),!ne.moved){var oe=J.clientX-G,he=J.clientY-T;ne.moved=oe*oe+he*he>j}ne.event(J).zoom("mouse",n(O(ne.that.__zoom,ne.mouse[0]=to(J,D),ne.mouse[1]),ne.extent,u))}function K(J){B.on("mousemove.zoom mouseup.zoom",null),xb(J.view,ne.moved),_f(J),ne.event(J).end()}}function ie(N,...P){if(e.apply(this,arguments)){var D=this.__zoom,ne=to(N.changedTouches?N.changedTouches[0]:N,this),B=D.invert(ne),z=D.k*(N.shiftKey?.5:2),G=n(O(L(D,z),ne,B),t.apply(this,P),u);_f(N),c>0?Ei(this).transition().duration(c).call(H,G,ne,N):Ei(this).call(A.transform,G,ne,N)}}function ue(N,...P){if(e.apply(this,arguments)){var D=N.touches,ne=D.length,B=X(this,P,N.changedTouches.length===ne).event(N),z,G,T,Q;for(dp(N),G=0;G<ne;++G)T=D[G],Q=to(T,this),Q=[Q,this.__zoom.invert(Q),T.identifier],B.touch0?!B.touch1&&B.touch0[2]!==Q[2]&&(B.touch1=Q,B.taps=0):(B.touch0=Q,z=!0,B.taps=1+!!p);p&&(p=clearTimeout(p)),z&&(B.taps<2&&(y=Q[0],p=setTimeout(function(){p=null},x)),jm(this),B.start())}}function F(N,...P){if(this.__zooming){var D=X(this,P).event(N),ne=N.changedTouches,B=ne.length,z,G,T,Q;for(_f(N),z=0;z<B;++z)G=ne[z],T=to(G,this),D.touch0&&D.touch0[2]===G.identifier?D.touch0[0]=T:D.touch1&&D.touch1[2]===G.identifier&&(D.touch1[0]=T);if(G=D.that.__zoom,D.touch1){var K=D.touch0[0],J=D.touch0[1],oe=D.touch1[0],he=D.touch1[1],_e=(_e=oe[0]-K[0])*_e+(_e=oe[1]-K[1])*_e,we=(we=he[0]-J[0])*we+(we=he[1]-J[1])*we;G=L(G,Math.sqrt(_e/we)),T=[(K[0]+oe[0])/2,(K[1]+oe[1])/2],Q=[(J[0]+he[0])/2,(J[1]+he[1])/2]}else if(D.touch0)T=D.touch0[0],Q=D.touch0[1];else return;D.zoom("touch",n(O(G,T,Q),D.extent,u))}}function C(N,...P){if(this.__zooming){var D=X(this,P).event(N),ne=N.changedTouches,B=ne.length,z,G;for(dp(N),w&&clearTimeout(w),w=setTimeout(function(){w=null},x),z=0;z<B;++z)G=ne[z],D.touch0&&D.touch0[2]===G.identifier?delete D.touch0:D.touch1&&D.touch1[2]===G.identifier&&delete D.touch1;if(D.touch1&&!D.touch0&&(D.touch0=D.touch1,delete D.touch1),D.touch0)D.touch0[1]=this.__zoom.invert(D.touch0[0]);else if(D.end(),D.taps===2&&(G=to(G,this),Math.hypot(y[0]-G[0],y[1]-G[1])<E)){var T=Ei(this).on("dblclick.zoom");T&&T.apply(this,arguments)}}}return A.wheelDelta=function(N){return arguments.length?(r=typeof N=="function"?N:am(+N),A):r},A.filter=function(N){return arguments.length?(e=typeof N=="function"?N:am(!!N),A):e},A.touchable=function(N){return arguments.length?(o=typeof N=="function"?N:am(!!N),A):o},A.extent=function(N){return arguments.length?(t=typeof N=="function"?N:am([[+N[0][0],+N[0][1]],[+N[1][0],+N[1][1]]]),A):t},A.scaleExtent=function(N){return arguments.length?(l[0]=+N[0],l[1]=+N[1],A):[l[0],l[1]]},A.translateExtent=function(N){return arguments.length?(u[0][0]=+N[0][0],u[1][0]=+N[1][0],u[0][1]=+N[0][1],u[1][1]=+N[1][1],A):[[u[0][0],u[0][1]],[u[1][0],u[1][1]]]},A.constrain=function(N){return arguments.length?(n=N,A):n},A.duration=function(N){return arguments.length?(c=+N,A):c},A.interpolate=function(N){return arguments.length?(f=N,A):f},A.on=function(){var N=_.on.apply(_,arguments);return N===_?A:N},A.clickDistance=function(N){return arguments.length?(j=(N=+N)*N,A):Math.sqrt(j)},A.tapDistance=function(N){return arguments.length?(E=+N,A):E},A}const o_=m.createContext(null),vT=o_.Provider,ja={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.`},Ob=ja.error001();function In(e,t){const n=m.useContext(o_);if(n===null)throw new Error(Ob);return ab(n,e,t)}const Cs=()=>{const e=m.useContext(o_);if(e===null)throw new Error(Ob);return m.useMemo(()=>({getState:e.getState,setState:e.setState,subscribe:e.subscribe,destroy:e.destroy}),[e])},xT=e=>e.userSelectionActive?"none":"all";function Of({position:e,children:t,className:n,style:r,...o}){const l=In(xT),u=`${e}`.split("-");return ve.createElement("div",{className:Gs(["react-flow__panel",n,...u]),style:{...r,pointerEvents:l},...o},t)}function bT({proOptions:e,position:t="bottom-right"}){return e!=null&&e.hideAttribution?null:ve.createElement(Of,{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 jT=({x:e,y:t,label:n,labelStyle:r={},labelShowBg:o=!0,labelBgStyle:l={},labelBgPadding:u=[2,4],labelBgBorderRadius:c=2,children:f,className:_,...p})=>{const y=m.useRef(null),[w,x]=m.useState({x:0,y:0,width:0,height:0}),k=Gs(["react-flow__edge-textwrapper",_]);return m.useEffect(()=>{if(y.current){const j=y.current.getBBox();x({x:j.x,y:j.y,width:j.width,height:j.height})}},[n]),typeof n>"u"||!n?null:ve.createElement("g",{transform:`translate(${e-w.width/2} ${t-w.height/2})`,className:k,visibility:w.width?"visible":"hidden",...p},o&&ve.createElement("rect",{width:w.width+2*u[0],x:-u[0],y:-u[1],height:w.height+2*u[1],className:"react-flow__edge-textbg",style:l,rx:c,ry:c}),ve.createElement("text",{className:"react-flow__edge-text",y:w.height/2,dy:"0.3em",ref:y,style:r},n),f)};var ST=m.memo(jT);const Hg=e=>({width:e.offsetWidth,height:e.offsetHeight}),Uu=(e,t=0,n=1)=>Math.min(Math.max(e,t),n),Vg=(e={x:0,y:0},t)=>({x:Uu(e.x,t[0][0],t[1][0]),y:Uu(e.y,t[0][1],t[1][1])}),Bw=(e,t,n)=>e<t?Uu(Math.abs(e-t),1,50)/50:e>n?-Uu(Math.abs(e-n),1,50)/50:0,Pb=(e,t)=>{const n=Bw(e.x,35,t.width-35)*20,r=Bw(e.y,35,t.height-35)*20;return[n,r]},Db=e=>{var t;return((t=e.getRootNode)==null?void 0:t.call(e))||(window==null?void 0:window.document)},Fb=(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)}),Pf=({x:e,y:t,width:n,height:r})=>({x:e,y:t,x2:e+n,y2:t+r}),zb=({x:e,y:t,x2:n,y2:r})=>({x:e,y:t,width:n-e,height:r-t}),Uw=e=>({...e.positionAbsolute||{x:0,y:0},width:e.width||0,height:e.height||0}),kT=(e,t)=>zb(Fb(Pf(e),Pf(t))),og=(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)},NT=e=>$i(e.width)&&$i(e.height)&&$i(e.x)&&$i(e.y),$i=e=>!isNaN(e)&&isFinite(e),ps=Symbol.for("internals"),Bb=["Enter"," ","Escape"],CT=(e,t)=>{},ET=e=>"nativeEvent"in e;function ag(e){var o,l;const t=ET(e)?e.nativeEvent:e,n=((l=(o=t.composedPath)==null?void 0:o.call(t))==null?void 0:l[0])||e.target;return["INPUT","SELECT","TEXTAREA"].includes(n==null?void 0:n.nodeName)||(n==null?void 0:n.hasAttribute("contenteditable"))||!!(n!=null&&n.closest(".nokey"))}const Ub=e=>"clientX"in e,Sl=(e,t)=>{var l,u;const n=Ub(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)}},Wm=()=>{var e;return typeof navigator<"u"&&((e=navigator==null?void 0:navigator.userAgent)==null?void 0:e.indexOf("Mac"))>=0},Yf=({id:e,path:t,labelX:n,labelY:r,label:o,labelStyle:l,labelShowBg:u,labelBgStyle:c,labelBgPadding:f,labelBgBorderRadius:_,style:p,markerEnd:y,markerStart:w,interactionWidth:x=20})=>ve.createElement(ve.Fragment,null,ve.createElement("path",{id:e,style:p,d:t,fill:"none",className:"react-flow__edge-path",markerEnd:y,markerStart:w}),x&&ve.createElement("path",{d:t,fill:"none",strokeOpacity:0,strokeWidth:x,className:"react-flow__edge-interaction"}),o&&$i(n)&&$i(r)?ve.createElement(ST,{x:n,y:r,label:o,labelStyle:l,labelShowBg:u,labelBgStyle:c,labelBgPadding:f,labelBgBorderRadius:_}):null);Yf.displayName="BaseEdge";function pf(e,t,n){return n===void 0?n:r=>{const o=t().edges.find(l=>l.id===e);o&&n(r,{...o})}}function Wb({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 qb({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,_=t*.125+l*.375+c*.375+r*.125,p=Math.abs(f-e),y=Math.abs(_-t);return[f,_,p,y]}var mc;(function(e){e.Strict="strict",e.Loose="loose"})(mc||(mc={}));var ic;(function(e){e.Free="free",e.Vertical="vertical",e.Horizontal="horizontal"})(ic||(ic={}));var Df;(function(e){e.Partial="partial",e.Full="full"})(Df||(Df={}));var jl;(function(e){e.Bezier="default",e.Straight="straight",e.Step="step",e.SmoothStep="smoothstep",e.SimpleBezier="simplebezier"})(jl||(jl={}));var Ff;(function(e){e.Arrow="arrow",e.ArrowClosed="arrowclosed"})(Ff||(Ff={}));var mt;(function(e){e.Left="left",e.Top="top",e.Right="right",e.Bottom="bottom"})(mt||(mt={}));function Ww({pos:e,x1:t,y1:n,x2:r,y2:o}){return e===mt.Left||e===mt.Right?[.5*(t+r),n]:[t,.5*(n+o)]}function Hb({sourceX:e,sourceY:t,sourcePosition:n=mt.Bottom,targetX:r,targetY:o,targetPosition:l=mt.Top}){const[u,c]=Ww({pos:n,x1:e,y1:t,x2:r,y2:o}),[f,_]=Ww({pos:l,x1:r,y1:o,x2:e,y2:t}),[p,y,w,x]=qb({sourceX:e,sourceY:t,targetX:r,targetY:o,sourceControlX:u,sourceControlY:c,targetControlX:f,targetControlY:_});return[`M${e},${t} C${u},${c} ${f},${_} ${r},${o}`,p,y,w,x]}const Gg=m.memo(({sourceX:e,sourceY:t,targetX:n,targetY:r,sourcePosition:o=mt.Bottom,targetPosition:l=mt.Top,label:u,labelStyle:c,labelShowBg:f,labelBgStyle:_,labelBgPadding:p,labelBgBorderRadius:y,style:w,markerEnd:x,markerStart:k,interactionWidth:j})=>{const[E,A,L]=Hb({sourceX:e,sourceY:t,sourcePosition:o,targetX:n,targetY:r,targetPosition:l});return ve.createElement(Yf,{path:E,labelX:A,labelY:L,label:u,labelStyle:c,labelShowBg:f,labelBgStyle:_,labelBgPadding:p,labelBgBorderRadius:y,style:w,markerEnd:x,markerStart:k,interactionWidth:j})});Gg.displayName="SimpleBezierEdge";const qw={[mt.Left]:{x:-1,y:0},[mt.Right]:{x:1,y:0},[mt.Top]:{x:0,y:-1},[mt.Bottom]:{x:0,y:1}},$T=({source:e,sourcePosition:t=mt.Bottom,target:n})=>t===mt.Left||t===mt.Right?e.x<n.x?{x:1,y:0}:{x:-1,y:0}:e.y<n.y?{x:0,y:1}:{x:0,y:-1},Hw=(e,t)=>Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2));function AT({source:e,sourcePosition:t=mt.Bottom,target:n,targetPosition:r=mt.Top,center:o,offset:l}){const u=qw[t],c=qw[r],f={x:e.x+u.x*l,y:e.y+u.y*l},_={x:n.x+c.x*l,y:n.y+c.y*l},p=$T({source:f,sourcePosition:t,target:_}),y=p.x!==0?"x":"y",w=p[y];let x=[],k,j;const E={x:0,y:0},A={x:0,y:0},[L,O,M,H]=Wb({sourceX:e.x,sourceY:e.y,targetX:n.x,targetY:n.y});if(u[y]*c[y]===-1){k=o.x||L,j=o.y||O;const Y=[{x:k,y:f.y},{x:k,y:_.y}],Z=[{x:f.x,y:j},{x:_.x,y:j}];u[y]===w?x=y==="x"?Y:Z:x=y==="x"?Z:Y}else{const Y=[{x:f.x,y:_.y}],Z=[{x:_.x,y:f.y}];if(y==="x"?x=u.x===w?Z:Y:x=u.y===w?Y:Z,t===r){const C=Math.abs(e[y]-n[y]);if(C<=l){const N=Math.min(l-1,l-C);u[y]===w?E[y]=(f[y]>e[y]?-1:1)*N:A[y]=(_[y]>n[y]?-1:1)*N}}if(t!==r){const C=y==="x"?"y":"x",N=u[y]===c[C],P=f[C]>_[C],D=f[C]<_[C];(u[y]===1&&(!N&&P||N&&D)||u[y]!==1&&(!N&&D||N&&P))&&(x=y==="x"?Y:Z)}const re={x:f.x+E.x,y:f.y+E.y},ie={x:_.x+A.x,y:_.y+A.y},ue=Math.max(Math.abs(re.x-x[0].x),Math.abs(ie.x-x[0].x)),F=Math.max(Math.abs(re.y-x[0].y),Math.abs(ie.y-x[0].y));ue>=F?(k=(re.x+ie.x)/2,j=x[0].y):(k=x[0].x,j=(re.y+ie.y)/2)}return[[e,{x:f.x+E.x,y:f.y+E.y},...x,{x:_.x+A.x,y:_.y+A.y},n],k,j,M,H]}function TT(e,t,n,r){const o=Math.min(Hw(e,t)/2,Hw(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 _=e.x<n.x?-1:1,p=e.y<n.y?1:-1;return`L ${l+o*_},${u}Q ${l},${u} ${l},${u+o*p}`}const c=e.x<n.x?1:-1,f=e.y<n.y?-1:1;return`L ${l},${u+o*f}Q ${l},${u} ${l+o*c},${u}`}function lg({sourceX:e,sourceY:t,sourcePosition:n=mt.Bottom,targetX:r,targetY:o,targetPosition:l=mt.Top,borderRadius:u=5,centerX:c,centerY:f,offset:_=20}){const[p,y,w,x,k]=AT({source:{x:e,y:t},sourcePosition:n,target:{x:r,y:o},targetPosition:l,center:{x:c,y:f},offset:_});return[p.reduce((E,A,L)=>{let O="";return L>0&&L<p.length-1?O=TT(p[L-1],A,p[L+1],u):O=`${L===0?"M":"L"}${A.x} ${A.y}`,E+=O,E},""),y,w,x,k]}const a_=m.memo(({sourceX:e,sourceY:t,targetX:n,targetY:r,label:o,labelStyle:l,labelShowBg:u,labelBgStyle:c,labelBgPadding:f,labelBgBorderRadius:_,style:p,sourcePosition:y=mt.Bottom,targetPosition:w=mt.Top,markerEnd:x,markerStart:k,pathOptions:j,interactionWidth:E})=>{const[A,L,O]=lg({sourceX:e,sourceY:t,sourcePosition:y,targetX:n,targetY:r,targetPosition:w,borderRadius:j==null?void 0:j.borderRadius,offset:j==null?void 0:j.offset});return ve.createElement(Yf,{path:A,labelX:L,labelY:O,label:o,labelStyle:l,labelShowBg:u,labelBgStyle:c,labelBgPadding:f,labelBgBorderRadius:_,style:p,markerEnd:x,markerStart:k,interactionWidth:E})});a_.displayName="SmoothStepEdge";const Kg=m.memo(e=>{var t;return ve.createElement(a_,{...e,pathOptions:m.useMemo(()=>{var n;return{borderRadius:0,offset:(n=e.pathOptions)==null?void 0:n.offset}},[(t=e.pathOptions)==null?void 0:t.offset])})});Kg.displayName="StepEdge";function MT({sourceX:e,sourceY:t,targetX:n,targetY:r}){const[o,l,u,c]=Wb({sourceX:e,sourceY:t,targetX:n,targetY:r});return[`M ${e},${t}L ${n},${r}`,o,l,u,c]}const Yg=m.memo(({sourceX:e,sourceY:t,targetX:n,targetY:r,label:o,labelStyle:l,labelShowBg:u,labelBgStyle:c,labelBgPadding:f,labelBgBorderRadius:_,style:p,markerEnd:y,markerStart:w,interactionWidth:x})=>{const[k,j,E]=MT({sourceX:e,sourceY:t,targetX:n,targetY:r});return ve.createElement(Yf,{path:k,labelX:j,labelY:E,label:o,labelStyle:l,labelShowBg:u,labelBgStyle:c,labelBgPadding:f,labelBgBorderRadius:_,style:p,markerEnd:y,markerStart:w,interactionWidth:x})});Yg.displayName="StraightEdge";function lm(e,t){return e>=0?.5*e:t*25*Math.sqrt(-e)}function Vw({pos:e,x1:t,y1:n,x2:r,y2:o,c:l}){switch(e){case mt.Left:return[t-lm(t-r,l),n];case mt.Right:return[t+lm(r-t,l),n];case mt.Top:return[t,n-lm(n-o,l)];case mt.Bottom:return[t,n+lm(o-n,l)]}}function Vb({sourceX:e,sourceY:t,sourcePosition:n=mt.Bottom,targetX:r,targetY:o,targetPosition:l=mt.Top,curvature:u=.25}){const[c,f]=Vw({pos:n,x1:e,y1:t,x2:r,y2:o,c:u}),[_,p]=Vw({pos:l,x1:r,y1:o,x2:e,y2:t,c:u}),[y,w,x,k]=qb({sourceX:e,sourceY:t,targetX:r,targetY:o,sourceControlX:c,sourceControlY:f,targetControlX:_,targetControlY:p});return[`M${e},${t} C${c},${f} ${_},${p} ${r},${o}`,y,w,x,k]}const qm=m.memo(({sourceX:e,sourceY:t,targetX:n,targetY:r,sourcePosition:o=mt.Bottom,targetPosition:l=mt.Top,label:u,labelStyle:c,labelShowBg:f,labelBgStyle:_,labelBgPadding:p,labelBgBorderRadius:y,style:w,markerEnd:x,markerStart:k,pathOptions:j,interactionWidth:E})=>{const[A,L,O]=Vb({sourceX:e,sourceY:t,sourcePosition:o,targetX:n,targetY:r,targetPosition:l,curvature:j==null?void 0:j.curvature});return ve.createElement(Yf,{path:A,labelX:L,labelY:O,label:u,labelStyle:c,labelShowBg:f,labelBgStyle:_,labelBgPadding:p,labelBgBorderRadius:y,style:w,markerEnd:x,markerStart:k,interactionWidth:E})});qm.displayName="BezierEdge";const Jg=m.createContext(null),RT=Jg.Provider;Jg.Consumer;const LT=()=>m.useContext(Jg),IT=e=>"id"in e&&"source"in e&&"target"in e,OT=({source:e,sourceHandle:t,target:n,targetHandle:r})=>`reactflow__edge-${e}${t||""}-${n}${r||""}`,cg=(e,t)=>typeof e>"u"?"":typeof e=="string"?e:`${t?`${t}__`:""}${Object.keys(e).sort().map(r=>`${r}=${e[r]}`).join("&")}`,PT=(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)),DT=(e,t)=>{if(!e.source||!e.target)return t;let n;return IT(e)?n={...e}:n={...e,id:OT(e)},PT(n,t)?t:t.concat(n)},ug=({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},Gb=({x:e,y:t},[n,r,o])=>({x:e*o+n,y:t*o+r}),uc=(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}},l_=(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}=uc(o,t).positionAbsolute;return Fb(r,Pf({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 zb(n)},Kb=(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},_=[];return e.forEach(p=>{const{width:y,height:w,selectable:x=!0,hidden:k=!1}=p;if(u&&!x||k)return!1;const{positionAbsolute:j}=uc(p,c),E={x:j.x,y:j.y,width:y||0,height:w||0},A=og(f,E),L=typeof y>"u"||typeof w>"u"||y===null||w===null,O=l&&A>0,M=(y||0)*(w||0);(L||O||A>=M||p.dragging)&&_.push(p)}),_},Yb=(e,t)=>{const n=e.map(r=>r.id);return t.filter(r=>n.includes(r.source)||n.includes(r.target))},Jb=(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),_=Uu(f,r,o),p=e.x+e.width/2,y=e.y+e.height/2,w=t/2-p*_,x=n/2-y*_;return{x:w,y:x,zoom:_}},ec=(e,t=0)=>e.transition().duration(t);function Gw(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 FT(e,t,n,r,o,l){const{x:u,y:c}=Sl(e),_=t.elementsFromPoint(u,c).find(k=>k.classList.contains("react-flow__handle"));if(_){const k=_.getAttribute("data-nodeid");if(k){const j=Xg(void 0,_),E=_.getAttribute("data-handleid"),A=l({nodeId:k,id:E,type:j});if(A){const L=o.find(O=>O.nodeId===k&&O.type===j&&O.id===E);return{handle:{id:E,type:j,nodeId:k,x:(L==null?void 0:L.x)||n.x,y:(L==null?void 0:L.y)||n.y},validHandleResult:A}}}}let p=[],y=1/0;if(o.forEach(k=>{const j=Math.sqrt((k.x-n.x)**2+(k.y-n.y)**2);if(j<=r){const E=l(k);j<=y&&(j<y?p=[{handle:k,validHandleResult:E}]:j===y&&p.push({handle:k,validHandleResult:E}),y=j)}}),!p.length)return{handle:null,validHandleResult:Xb()};if(p.length===1)return p[0];const w=p.some(({validHandleResult:k})=>k.isValid),x=p.some(({handle:k})=>k.type==="target");return p.find(({handle:k,validHandleResult:j})=>x?k.type==="target":w?j.isValid:!0)||p[0]}const zT={source:null,target:null,sourceHandle:null,targetHandle:null},Xb=()=>({handleDomNode:null,isValid:!1,connection:zT,endHandle:null});function Zb(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}"]`),_={...Xb(),handleDomNode:f};if(f){const p=Xg(void 0,f),y=f.getAttribute("data-nodeid"),w=f.getAttribute("data-handleid"),x=f.classList.contains("connectable"),k=f.classList.contains("connectableend"),j={source:c?y:n,sourceHandle:c?w:r,target:c?n:y,targetHandle:c?r:w};_.connection=j,x&&k&&(t===mc.Strict?c&&p==="source"||!c&&p==="target":y!==n||w!==r)&&(_.endHandle={nodeId:y,handleId:w,type:p},_.isValid=l(j))}return _}function BT({nodes:e,nodeId:t,handleId:n,handleType:r}){return e.reduce((o,l)=>{if(l[ps]){const{handleBounds:u}=l[ps];let c=[],f=[];u&&(c=Gw(l,u,"source",`${t}-${n}-${r}`),f=Gw(l,u,"target",`${t}-${n}-${r}`)),o.push(...c,...f)}return o},[])}function Xg(e,t){return e||(t!=null&&t.classList.contains("target")?"target":t!=null&&t.classList.contains("source")?"source":null)}function fp(e){e==null||e.classList.remove("valid","connecting","react-flow__handle-valid","react-flow__handle-connecting")}function UT(e,t){let n=null;return t?n="valid":e&&!t&&(n="invalid"),n}function Qb({event:e,handleId:t,nodeId:n,onConnect:r,isTarget:o,getState:l,setState:u,isValidConnection:c,edgeUpdaterType:f,onEdgeUpdateEnd:_}){const p=Db(e.target),{connectionMode:y,domNode:w,autoPanOnConnect:x,connectionRadius:k,onConnectStart:j,panBy:E,getNodes:A,cancelConnection:L}=l();let O=0,M;const{x:H,y:X}=Sl(e),Y=p==null?void 0:p.elementFromPoint(H,X),Z=Xg(f,Y),re=w==null?void 0:w.getBoundingClientRect();if(!re||!Z)return;let ie,ue=Sl(e,re),F=!1,C=null,N=!1,P=null;const D=BT({nodes:A(),nodeId:n,handleId:t,handleType:Z}),ne=()=>{if(!x)return;const[G,T]=Pb(ue,re);E({x:G,y:T}),O=requestAnimationFrame(ne)};u({connectionPosition:ue,connectionStatus:null,connectionNodeId:n,connectionHandleId:t,connectionHandleType:Z,connectionStartHandle:{nodeId:n,handleId:t,type:Z},connectionEndHandle:null}),j==null||j(e,{nodeId:n,handleId:t,handleType:Z});function B(G){const{transform:T}=l();ue=Sl(G,re);const{handle:Q,validHandleResult:K}=FT(G,p,ug(ue,T,!1,[1,1]),k,D,J=>Zb(J,y,n,t,o?"target":"source",c,p));if(M=Q,F||(ne(),F=!0),P=K.handleDomNode,C=K.connection,N=K.isValid,u({connectionPosition:M&&N?Gb({x:M.x,y:M.y},T):ue,connectionStatus:UT(!!M,N),connectionEndHandle:K.endHandle}),!M&&!N&&!P)return fp(ie);C.source!==C.target&&P&&(fp(ie),ie=P,P.classList.add("connecting","react-flow__handle-connecting"),P.classList.toggle("valid",N),P.classList.toggle("react-flow__handle-valid",N))}function z(G){var T,Q;(M||P)&&C&&N&&(r==null||r(C)),(Q=(T=l()).onConnectEnd)==null||Q.call(T,G),f&&(_==null||_(G)),fp(ie),L(),cancelAnimationFrame(O),F=!1,N=!1,C=null,P=null,p.removeEventListener("mousemove",B),p.removeEventListener("mouseup",z),p.removeEventListener("touchmove",B),p.removeEventListener("touchend",z)}p.addEventListener("mousemove",B),p.addEventListener("mouseup",z),p.addEventListener("touchmove",B),p.addEventListener("touchend",z)}const Kw=()=>!0,WT=e=>({connectionStartHandle:e.connectionStartHandle,connectOnClick:e.connectOnClick,noPanClassName:e.noPanClassName}),qT=(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}},e0=m.forwardRef(({type:e="source",position:t=mt.Top,isValidConnection:n,isConnectable:r=!0,isConnectableStart:o=!0,isConnectableEnd:l=!0,id:u,onConnect:c,children:f,className:_,onMouseDown:p,onTouchStart:y,...w},x)=>{var re,ie;const k=u||null,j=e==="target",E=Cs(),A=LT(),{connectOnClick:L,noPanClassName:O}=In(WT,Ds),{connecting:M,clickConnecting:H}=In(qT(A,k,e),Ds);A||(ie=(re=E.getState()).onError)==null||ie.call(re,"010",ja.error010());const X=ue=>{const{defaultEdgeOptions:F,onConnect:C,hasDefaultEdges:N}=E.getState(),P={...F,...ue};if(N){const{edges:D,setEdges:ne}=E.getState();ne(DT(P,D))}C==null||C(P),c==null||c(P)},Y=ue=>{if(!A)return;const F=Ub(ue);o&&(F&&ue.button===0||!F)&&Qb({event:ue,handleId:k,nodeId:A,onConnect:X,isTarget:j,getState:E.getState,setState:E.setState,isValidConnection:n||E.getState().isValidConnection||Kw}),F?p==null||p(ue):y==null||y(ue)},Z=ue=>{const{onClickConnectStart:F,onClickConnectEnd:C,connectionClickStartHandle:N,connectionMode:P,isValidConnection:D}=E.getState();if(!A||!N&&!o)return;if(!N){F==null||F(ue,{nodeId:A,handleId:k,handleType:e}),E.setState({connectionClickStartHandle:{nodeId:A,type:e,handleId:k}});return}const ne=Db(ue.target),B=n||D||Kw,{connection:z,isValid:G}=Zb({nodeId:A,id:k,type:e},P,N.nodeId,N.handleId||null,N.type,B,ne);G&&X(z),C==null||C(ue),E.setState({connectionClickStartHandle:null})};return ve.createElement("div",{"data-handleid":k,"data-nodeid":A,"data-handlepos":t,"data-id":`${A}-${k}-${e}`,className:Gs(["react-flow__handle",`react-flow__handle-${t}`,"nodrag",O,_,{source:!j,target:j,connectable:r,connectablestart:o,connectableend:l,connecting:H,connectionindicator:r&&(o&&!M||l&&M)}]),onMouseDown:Y,onTouchStart:Y,onClick:L?Z:void 0,ref:x,...w},f)});e0.displayName="Handle";var Hm=m.memo(e0);const t0=({data:e,isConnectable:t,targetPosition:n=mt.Top,sourcePosition:r=mt.Bottom})=>ve.createElement(ve.Fragment,null,ve.createElement(Hm,{type:"target",position:n,isConnectable:t}),e==null?void 0:e.label,ve.createElement(Hm,{type:"source",position:r,isConnectable:t}));t0.displayName="DefaultNode";var dg=m.memo(t0);const n0=({data:e,isConnectable:t,sourcePosition:n=mt.Bottom})=>ve.createElement(ve.Fragment,null,e==null?void 0:e.label,ve.createElement(Hm,{type:"source",position:n,isConnectable:t}));n0.displayName="InputNode";var s0=m.memo(n0);const r0=({data:e,isConnectable:t,targetPosition:n=mt.Top})=>ve.createElement(ve.Fragment,null,ve.createElement(Hm,{type:"target",position:n,isConnectable:t}),e==null?void 0:e.label);r0.displayName="OutputNode";var i0=m.memo(r0);const Zg=()=>null;Zg.displayName="GroupNode";const HT=e=>({selectedNodes:e.getNodes().filter(t=>t.selected),selectedEdges:e.edges.filter(t=>t.selected)}),cm=e=>e.id;function VT(e,t){return Ds(e.selectedNodes.map(cm),t.selectedNodes.map(cm))&&Ds(e.selectedEdges.map(cm),t.selectedEdges.map(cm))}const o0=m.memo(({onSelectionChange:e})=>{const t=Cs(),{selectedNodes:n,selectedEdges:r}=In(HT,VT);return m.useEffect(()=>{const o={nodes:n,edges:r};e==null||e(o),t.getState().onSelectionChange.forEach(l=>l(o))},[n,r,e]),null});o0.displayName="SelectionListener";const GT=e=>!!e.onSelectionChange;function KT({onSelectionChange:e}){const t=In(GT);return e||t?ve.createElement(o0,{onSelectionChange:e}):null}const YT=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 bu(e,t){m.useEffect(()=>{typeof e<"u"&&t(e)},[e])}function Jt(e,t,n){m.useEffect(()=>{typeof t<"u"&&n({[e]:t})},[t])}const JT=({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,onConnect:o,onConnectStart:l,onConnectEnd:u,onClickConnectStart:c,onClickConnectEnd:f,nodesDraggable:_,nodesConnectable:p,nodesFocusable:y,edgesFocusable:w,edgesUpdatable:x,elevateNodesOnSelect:k,minZoom:j,maxZoom:E,nodeExtent:A,onNodesChange:L,onEdgesChange:O,elementsSelectable:M,connectionMode:H,snapGrid:X,snapToGrid:Y,translateExtent:Z,connectOnClick:re,defaultEdgeOptions:ie,fitView:ue,fitViewOptions:F,onNodesDelete:C,onEdgesDelete:N,onNodeDrag:P,onNodeDragStart:D,onNodeDragStop:ne,onSelectionDrag:B,onSelectionDragStart:z,onSelectionDragStop:G,noPanClassName:T,nodeOrigin:Q,rfId:K,autoPanOnConnect:J,autoPanOnNodeDrag:oe,onError:he,connectionRadius:_e,isValidConnection:we,nodeDragThreshold:Ee})=>{const{setNodes:ze,setEdges:Ue,setDefaultNodesAndEdges:_t,setMinZoom:Pe,setMaxZoom:et,setTranslateExtent:lt,setNodeExtent:Je,reset:Se}=In(YT,Ds),Ie=Cs();return m.useEffect(()=>{const ct=r==null?void 0:r.map(ge=>({...ge,...ie}));return _t(n,ct),()=>{Se()}},[]),Jt("defaultEdgeOptions",ie,Ie.setState),Jt("connectionMode",H,Ie.setState),Jt("onConnect",o,Ie.setState),Jt("onConnectStart",l,Ie.setState),Jt("onConnectEnd",u,Ie.setState),Jt("onClickConnectStart",c,Ie.setState),Jt("onClickConnectEnd",f,Ie.setState),Jt("nodesDraggable",_,Ie.setState),Jt("nodesConnectable",p,Ie.setState),Jt("nodesFocusable",y,Ie.setState),Jt("edgesFocusable",w,Ie.setState),Jt("edgesUpdatable",x,Ie.setState),Jt("elementsSelectable",M,Ie.setState),Jt("elevateNodesOnSelect",k,Ie.setState),Jt("snapToGrid",Y,Ie.setState),Jt("snapGrid",X,Ie.setState),Jt("onNodesChange",L,Ie.setState),Jt("onEdgesChange",O,Ie.setState),Jt("connectOnClick",re,Ie.setState),Jt("fitViewOnInit",ue,Ie.setState),Jt("fitViewOnInitOptions",F,Ie.setState),Jt("onNodesDelete",C,Ie.setState),Jt("onEdgesDelete",N,Ie.setState),Jt("onNodeDrag",P,Ie.setState),Jt("onNodeDragStart",D,Ie.setState),Jt("onNodeDragStop",ne,Ie.setState),Jt("onSelectionDrag",B,Ie.setState),Jt("onSelectionDragStart",z,Ie.setState),Jt("onSelectionDragStop",G,Ie.setState),Jt("noPanClassName",T,Ie.setState),Jt("nodeOrigin",Q,Ie.setState),Jt("rfId",K,Ie.setState),Jt("autoPanOnConnect",J,Ie.setState),Jt("autoPanOnNodeDrag",oe,Ie.setState),Jt("onError",he,Ie.setState),Jt("connectionRadius",_e,Ie.setState),Jt("isValidConnection",we,Ie.setState),Jt("nodeDragThreshold",Ee,Ie.setState),bu(e,ze),bu(t,Ue),bu(j,Pe),bu(E,et),bu(Z,lt),bu(A,Je),null},Yw={display:"none"},XT={position:"absolute",width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0px, 0px, 0px, 0px)",clipPath:"inset(100%)"},a0="react-flow__node-desc",l0="react-flow__edge-desc",ZT="react-flow__aria-live",QT=e=>e.ariaLiveMessage;function eM({rfId:e}){const t=In(QT);return ve.createElement("div",{id:`${ZT}-${e}`,"aria-live":"assertive","aria-atomic":"true",style:XT},t)}function tM({rfId:e,disableKeyboardA11y:t}){return ve.createElement(ve.Fragment,null,ve.createElement("div",{id:`${a0}-${e}`,style:Yw},"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:`${l0}-${e}`,style:Yw},"Press enter or space to select an edge. You can then press delete to remove it or escape to cancel."),!t&&ve.createElement(eM,{rfId:e}))}var zf=(e=null,t={actInsideInputWithModifier:!0})=>{const[n,r]=m.useState(!1),o=m.useRef(!1),l=m.useRef(new Set([])),[u,c]=m.useMemo(()=>{if(e!==null){const _=(Array.isArray(e)?e:[e]).filter(y=>typeof y=="string").map(y=>y.split("+")),p=_.reduce((y,w)=>y.concat(...w),[]);return[_,p]}return[[],[]]},[e]);return m.useEffect(()=>{const f=typeof document<"u"?document:null,_=(t==null?void 0:t.target)||f;if(e!==null){const p=x=>{if(o.current=x.ctrlKey||x.metaKey||x.shiftKey,(!o.current||o.current&&!t.actInsideInputWithModifier)&&ag(x))return!1;const j=Xw(x.code,c);l.current.add(x[j]),Jw(u,l.current,!1)&&(x.preventDefault(),r(!0))},y=x=>{if((!o.current||o.current&&!t.actInsideInputWithModifier)&&ag(x))return!1;const j=Xw(x.code,c);Jw(u,l.current,!0)?(r(!1),l.current.clear()):l.current.delete(x[j]),x.key==="Meta"&&l.current.clear(),o.current=!1},w=()=>{l.current.clear(),r(!1)};return _==null||_.addEventListener("keydown",p),_==null||_.addEventListener("keyup",y),window.addEventListener("blur",w),()=>{_==null||_.removeEventListener("keydown",p),_==null||_.removeEventListener("keyup",y),window.removeEventListener("blur",w)}}},[e,r]),n};function Jw(e,t,n){return e.filter(r=>n||r.length===t.size).some(r=>r.every(o=>t.has(o)))}function Xw(e,t){return t.includes(e)?"code":"key"}function c0(e,t,n,r){var u,c;if(!e.parentNode)return n;const o=t.get(e.parentNode),l=uc(o,r);return c0(o,t,{x:(n.x??0)+l.x,y:(n.y??0)+l.y,z:(((u=o[ps])==null?void 0:u.z)??0)>(n.z??0)?((c=o[ps])==null?void 0:c.z)??0:n.z??0},r)}function u0(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}=c0(r,e,{...r.position,z:((o=r[ps])==null?void 0:o.z)??0},t);r.positionAbsolute={x:l,y:u},r[ps].z=c,n!=null&&n[r.id]&&(r[ps].isParent=!0)}})}function hp(e,t,n,r){const o=new Map,l={},u=r?1e3:0;return e.forEach(c=>{var w;const f=($i(c.zIndex)?c.zIndex:0)+(c.selected?u:0),_=t.get(c.id),p={...c,positionAbsolute:{x:c.position.x,y:c.position.y}};c.parentNode&&(l[c.parentNode]=!0);const y=(_==null?void 0:_.type)&&(_==null?void 0:_.type)!==c.type;Object.defineProperty(p,ps,{enumerable:!1,value:{handleBounds:y||(w=_==null?void 0:_[ps])==null?void 0:w.handleBounds,z:f}}),o.set(c.id,p)}),u0(o,n,l),o}function d0(e,t={}){const{getNodes:n,width:r,height:o,minZoom:l,maxZoom:u,d3Zoom:c,d3Selection:f,fitViewOnInitDone:_,fitViewOnInit:p,nodeOrigin:y}=e(),w=t.initial&&!_&&p;if(c&&f&&(w||!t.initial)){const k=n().filter(E=>{var L;const A=t.includeHiddenNodes?E.width&&E.height:!E.hidden;return(L=t.nodes)!=null&&L.length?A&&t.nodes.some(O=>O.id===E.id):A}),j=k.every(E=>E.width&&E.height);if(k.length>0&&j){const E=l_(k,y),{x:A,y:L,zoom:O}=Jb(E,r,o,t.minZoom??l,t.maxZoom??u,t.padding??.1),M=wa.translate(A,L).scale(O);return typeof t.duration=="number"&&t.duration>0?c.transform(ec(f,t.duration),M):c.transform(f,M),!0}}return!1}function nM(e,t){return e.forEach(n=>{const r=t.get(n.id);r&&t.set(r.id,{...r,[ps]:r[ps],selected:n.selected})}),new Map(t)}function sM(e,t){return t.map(n=>{const r=e.find(o=>o.id===n.id);return r&&(n.selected=r.selected),n})}function um({changedNodes:e,changedEdges:t,get:n,set:r}){const{nodeInternals:o,edges:l,onNodesChange:u,onEdgesChange:c,hasDefaultNodes:f,hasDefaultEdges:_}=n();e!=null&&e.length&&(f&&r({nodeInternals:nM(e,o)}),u==null||u(e)),t!=null&&t.length&&(_&&r({edges:sM(t,l)}),c==null||c(t))}const ju=()=>{},rM={zoomIn:ju,zoomOut:ju,zoomTo:ju,getZoom:()=>1,setViewport:ju,getViewport:()=>({x:0,y:0,zoom:1}),fitView:()=>!1,setCenter:ju,fitBounds:ju,project:e=>e,screenToFlowPosition:e=>e,flowToScreenPosition:e=>e,viewportInitialized:!1},iM=e=>({d3Zoom:e.d3Zoom,d3Selection:e.d3Selection}),oM=()=>{const e=Cs(),{d3Zoom:t,d3Selection:n}=In(iM,Ds);return m.useMemo(()=>n&&t?{zoomIn:o=>t.scaleBy(ec(n,o==null?void 0:o.duration),1.2),zoomOut:o=>t.scaleBy(ec(n,o==null?void 0:o.duration),1/1.2),zoomTo:(o,l)=>t.scaleTo(ec(n,l==null?void 0:l.duration),o),getZoom:()=>e.getState().transform[2],setViewport:(o,l)=>{const[u,c,f]=e.getState().transform,_=wa.translate(o.x??u,o.y??c).scale(o.zoom??f);t.transform(ec(n,l==null?void 0:l.duration),_)},getViewport:()=>{const[o,l,u]=e.getState().transform;return{x:o,y:l,zoom:u}},fitView:o=>d0(e.getState,o),setCenter:(o,l,u)=>{const{width:c,height:f,maxZoom:_}=e.getState(),p=typeof(u==null?void 0:u.zoom)<"u"?u.zoom:_,y=c/2-o*p,w=f/2-l*p,x=wa.translate(y,w).scale(p);t.transform(ec(n,u==null?void 0:u.duration),x)},fitBounds:(o,l)=>{const{width:u,height:c,minZoom:f,maxZoom:_}=e.getState(),{x:p,y,zoom:w}=Jb(o,u,c,f,_,(l==null?void 0:l.padding)??.1),x=wa.translate(p,y).scale(w);t.transform(ec(n,l==null?void 0:l.duration),x)},project:o=>{const{transform:l,snapToGrid:u,snapGrid:c}=e.getState();return console.warn("[DEPRECATED] `project` is deprecated. Instead use `screenToFlowPosition`. There is no need to subtract the react flow bounds anymore! https://reactflow.dev/api-reference/types/react-flow-instance#screen-to-flow-position"),ug(o,l,u,c)},screenToFlowPosition:o=>{const{transform:l,snapToGrid:u,snapGrid:c,domNode:f}=e.getState();if(!f)return o;const{x:_,y:p}=f.getBoundingClientRect(),y={x:o.x-_,y:o.y-p};return ug(y,l,u,c)},flowToScreenPosition:o=>{const{transform:l,domNode:u}=e.getState();if(!u)return o;const{x:c,y:f}=u.getBoundingClientRect(),_=Gb(o,l);return{x:_.x+c,y:_.y+f}},viewportInitialized:!0}:rM,[t,n])};function Qg(){const e=oM(),t=Cs(),n=m.useCallback(()=>t.getState().getNodes().map(j=>({...j})),[]),r=m.useCallback(j=>t.getState().nodeInternals.get(j),[]),o=m.useCallback(()=>{const{edges:j=[]}=t.getState();return j.map(E=>({...E}))},[]),l=m.useCallback(j=>{const{edges:E=[]}=t.getState();return E.find(A=>A.id===j)},[]),u=m.useCallback(j=>{const{getNodes:E,setNodes:A,hasDefaultNodes:L,onNodesChange:O}=t.getState(),M=E(),H=typeof j=="function"?j(M):j;if(L)A(H);else if(O){const X=H.length===0?M.map(Y=>({type:"remove",id:Y.id})):H.map(Y=>({item:Y,type:"reset"}));O(X)}},[]),c=m.useCallback(j=>{const{edges:E=[],setEdges:A,hasDefaultEdges:L,onEdgesChange:O}=t.getState(),M=typeof j=="function"?j(E):j;if(L)A(M);else if(O){const H=M.length===0?E.map(X=>({type:"remove",id:X.id})):M.map(X=>({item:X,type:"reset"}));O(H)}},[]),f=m.useCallback(j=>{const E=Array.isArray(j)?j:[j],{getNodes:A,setNodes:L,hasDefaultNodes:O,onNodesChange:M}=t.getState();if(O){const X=[...A(),...E];L(X)}else if(M){const H=E.map(X=>({item:X,type:"add"}));M(H)}},[]),_=m.useCallback(j=>{const E=Array.isArray(j)?j:[j],{edges:A=[],setEdges:L,hasDefaultEdges:O,onEdgesChange:M}=t.getState();if(O)L([...A,...E]);else if(M){const H=E.map(X=>({item:X,type:"add"}));M(H)}},[]),p=m.useCallback(()=>{const{getNodes:j,edges:E=[],transform:A}=t.getState(),[L,O,M]=A;return{nodes:j().map(H=>({...H})),edges:E.map(H=>({...H})),viewport:{x:L,y:O,zoom:M}}},[]),y=m.useCallback(({nodes:j,edges:E})=>{const{nodeInternals:A,getNodes:L,edges:O,hasDefaultNodes:M,hasDefaultEdges:H,onNodesDelete:X,onEdgesDelete:Y,onNodesChange:Z,onEdgesChange:re}=t.getState(),ie=(j||[]).map(P=>P.id),ue=(E||[]).map(P=>P.id),F=L().reduce((P,D)=>{const ne=!ie.includes(D.id)&&D.parentNode&&P.find(z=>z.id===D.parentNode);return(typeof D.deletable=="boolean"?D.deletable:!0)&&(ie.includes(D.id)||ne)&&P.push(D),P},[]),C=O.filter(P=>typeof P.deletable=="boolean"?P.deletable:!0),N=C.filter(P=>ue.includes(P.id));if(F||N){const P=Yb(F,C),D=[...N,...P],ne=D.reduce((B,z)=>(B.includes(z.id)||B.push(z.id),B),[]);if((H||M)&&(H&&t.setState({edges:O.filter(B=>!ne.includes(B.id))}),M&&(F.forEach(B=>{A.delete(B.id)}),t.setState({nodeInternals:new Map(A)}))),ne.length>0&&(Y==null||Y(D),re&&re(ne.map(B=>({id:B,type:"remove"})))),F.length>0&&(X==null||X(F),Z)){const B=F.map(z=>({id:z.id,type:"remove"}));Z(B)}}},[]),w=m.useCallback(j=>{const E=NT(j),A=E?null:t.getState().nodeInternals.get(j.id);return!E&&!A?[null,null,E]:[E?j:Uw(A),A,E]},[]),x=m.useCallback((j,E=!0,A)=>{const[L,O,M]=w(j);return L?(A||t.getState().getNodes()).filter(H=>{if(!M&&(H.id===O.id||!H.positionAbsolute))return!1;const X=Uw(H),Y=og(X,L);return E&&Y>0||Y>=L.width*L.height}):[]},[]),k=m.useCallback((j,E,A=!0)=>{const[L]=w(j);if(!L)return!1;const O=og(L,E);return A&&O>0||O>=L.width*L.height},[]);return m.useMemo(()=>({...e,getNodes:n,getNode:r,getEdges:o,getEdge:l,setNodes:u,setEdges:c,addNodes:f,addEdges:_,toObject:p,deleteElements:y,getIntersectingNodes:x,isNodeIntersecting:k}),[e,n,r,o,l,u,c,f,_,p,y,x,k])}const aM={actInsideInputWithModifier:!1};var lM=({deleteKeyCode:e,multiSelectionKeyCode:t})=>{const n=Cs(),{deleteElements:r}=Qg(),o=zf(e,aM),l=zf(t);m.useEffect(()=>{if(o){const{edges:u,getNodes:c}=n.getState(),f=c().filter(p=>p.selected),_=u.filter(p=>p.selected);r({nodes:f,edges:_}),n.setState({nodesSelectionActive:!1})}},[o]),m.useEffect(()=>{n.setState({multiSelectionActive:l})},[l])};function cM(e){const t=Cs();m.useEffect(()=>{let n;const r=()=>{var l,u;if(!e.current)return;const o=Hg(e.current);(o.height===0||o.width===0)&&((u=(l=t.getState()).onError)==null||u.call(l,"004",ja.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 ey={position:"absolute",width:"100%",height:"100%",top:0,left:0},uM=(e,t)=>e.x!==t.x||e.y!==t.y||e.zoom!==t.k,dm=e=>({x:e.x,y:e.y,zoom:e.k}),Su=(e,t)=>e.target.closest(`.${t}`),Zw=(e,t)=>t===2&&Array.isArray(e)&&e.includes(2),Qw=e=>{const t=e.ctrlKey&&Wm()?10:1;return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*t},dM=e=>({d3Zoom:e.d3Zoom,d3Selection:e.d3Selection,d3ZoomHandler:e.d3ZoomHandler,userSelectionActive:e.userSelectionActive}),fM=({onMove:e,onMoveStart:t,onMoveEnd:n,onPaneContextMenu:r,zoomOnScroll:o=!0,zoomOnPinch:l=!0,panOnScroll:u=!1,panOnScrollSpeed:c=.5,panOnScrollMode:f=ic.Free,zoomOnDoubleClick:_=!0,elementsSelectable:p,panOnDrag:y=!0,defaultViewport:w,translateExtent:x,minZoom:k,maxZoom:j,zoomActivationKeyCode:E,preventScrolling:A=!0,children:L,noWheelClassName:O,noPanClassName:M})=>{const H=m.useRef(),X=Cs(),Y=m.useRef(!1),Z=m.useRef(!1),re=m.useRef(null),ie=m.useRef({x:0,y:0,zoom:0}),{d3Zoom:ue,d3Selection:F,d3ZoomHandler:C,userSelectionActive:N}=In(dM,Ds),P=zf(E),D=m.useRef(0),ne=m.useRef(!1),B=m.useRef();return cM(re),m.useEffect(()=>{if(re.current){const z=re.current.getBoundingClientRect(),G=Ib().scaleExtent([k,j]).translateExtent(x),T=Ei(re.current).call(G),Q=wa.translate(w.x,w.y).scale(Uu(w.zoom,k,j)),K=[[0,0],[z.width,z.height]],J=G.constrain()(Q,K,x);G.transform(T,J),G.wheelDelta(Qw),X.setState({d3Zoom:G,d3Selection:T,d3ZoomHandler:T.on("wheel.zoom"),transform:[J.x,J.y,J.k],domNode:re.current.closest(".react-flow")})}},[]),m.useEffect(()=>{F&&ue&&(u&&!P&&!N?F.on("wheel.zoom",z=>{if(Su(z,O))return!1;z.preventDefault(),z.stopImmediatePropagation();const G=F.property("__zoom").k||1,T=Wm();if(z.ctrlKey&&l&&T){const Ee=to(z),ze=Qw(z),Ue=G*Math.pow(2,ze);ue.scaleTo(F,Ue,Ee,z);return}const Q=z.deltaMode===1?20:1;let K=f===ic.Vertical?0:z.deltaX*Q,J=f===ic.Horizontal?0:z.deltaY*Q;!T&&z.shiftKey&&f!==ic.Vertical&&(K=z.deltaY*Q,J=0),ue.translateBy(F,-(K/G)*c,-(J/G)*c,{internal:!0});const oe=dm(F.property("__zoom")),{onViewportChangeStart:he,onViewportChange:_e,onViewportChangeEnd:we}=X.getState();clearTimeout(B.current),ne.current||(ne.current=!0,t==null||t(z,oe),he==null||he(oe)),ne.current&&(e==null||e(z,oe),_e==null||_e(oe),B.current=setTimeout(()=>{n==null||n(z,oe),we==null||we(oe),ne.current=!1},150))},{passive:!1}):typeof C<"u"&&F.on("wheel.zoom",function(z,G){if(!A||Su(z,O))return null;z.preventDefault(),C.call(this,z,G)},{passive:!1}))},[N,u,f,F,ue,C,P,l,A,O,t,e,n]),m.useEffect(()=>{ue&&ue.on("start",z=>{var Q,K;if(!z.sourceEvent||z.sourceEvent.internal)return null;D.current=(Q=z.sourceEvent)==null?void 0:Q.button;const{onViewportChangeStart:G}=X.getState(),T=dm(z.transform);Y.current=!0,ie.current=T,((K=z.sourceEvent)==null?void 0:K.type)==="mousedown"&&X.setState({paneDragging:!0}),G==null||G(T),t==null||t(z.sourceEvent,T)})},[ue,t]),m.useEffect(()=>{ue&&(N&&!Y.current?ue.on("zoom",null):N||ue.on("zoom",z=>{var T;const{onViewportChange:G}=X.getState();if(X.setState({transform:[z.transform.x,z.transform.y,z.transform.k]}),Z.current=!!(r&&Zw(y,D.current??0)),(e||G)&&!((T=z.sourceEvent)!=null&&T.internal)){const Q=dm(z.transform);G==null||G(Q),e==null||e(z.sourceEvent,Q)}}))},[N,ue,e,y,r]),m.useEffect(()=>{ue&&ue.on("end",z=>{if(!z.sourceEvent||z.sourceEvent.internal)return null;const{onViewportChangeEnd:G}=X.getState();if(Y.current=!1,X.setState({paneDragging:!1}),r&&Zw(y,D.current??0)&&!Z.current&&r(z.sourceEvent),Z.current=!1,(n||G)&&uM(ie.current,z.transform)){const T=dm(z.transform);ie.current=T,clearTimeout(H.current),H.current=setTimeout(()=>{G==null||G(T),n==null||n(z.sourceEvent,T)},u?150:0)}})},[ue,u,y,n,r]),m.useEffect(()=>{ue&&ue.filter(z=>{const G=P||o,T=l&&z.ctrlKey;if((y===!0||Array.isArray(y)&&y.includes(1))&&z.button===1&&z.type==="mousedown"&&(Su(z,"react-flow__node")||Su(z,"react-flow__edge")))return!0;if(!y&&!G&&!u&&!_&&!l||N||!_&&z.type==="dblclick"||Su(z,O)&&z.type==="wheel"||Su(z,M)&&(z.type!=="wheel"||u&&z.type==="wheel"&&!P)||!l&&z.ctrlKey&&z.type==="wheel"||!G&&!u&&!T&&z.type==="wheel"||!y&&(z.type==="mousedown"||z.type==="touchstart")||Array.isArray(y)&&!y.includes(z.button)&&(z.type==="mousedown"||z.type==="touchstart"))return!1;const Q=Array.isArray(y)&&y.includes(z.button)||!z.button||z.button<=1;return(!z.ctrlKey||z.type==="wheel")&&Q})},[N,ue,o,l,u,_,y,p,P]),ve.createElement("div",{className:"react-flow__renderer",ref:re,style:ey},L)},hM=e=>({userSelectionActive:e.userSelectionActive,userSelectionRect:e.userSelectionRect});function mM(){const{userSelectionActive:e,userSelectionRect:t}=In(hM,Ds);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 ev(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 _M(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&&ev(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&&ev(r,u);break}case"remove":return r}return r.push(u),r},n)}function pM(e,t){return _M(e,t)}const xl=(e,t)=>({id:e,type:"select",selected:t});function Au(e,t){return e.reduce((n,r)=>{const o=t.includes(r.id);return!r.selected&&o?(r.selected=!0,n.push(xl(r.id,!0))):r.selected&&!o&&(r.selected=!1,n.push(xl(r.id,!1))),n},[])}const mp=(e,t)=>n=>{n.target===t.current&&(e==null||e(n))},gM=e=>({userSelectionActive:e.userSelectionActive,elementsSelectable:e.elementsSelectable,dragging:e.paneDragging}),f0=m.memo(({isSelecting:e,selectionMode:t=Df.Full,panOnDrag:n,onSelectionStart:r,onSelectionEnd:o,onPaneClick:l,onPaneContextMenu:u,onPaneScroll:c,onPaneMouseEnter:f,onPaneMouseMove:_,onPaneMouseLeave:p,children:y})=>{const w=m.useRef(null),x=Cs(),k=m.useRef(0),j=m.useRef(0),E=m.useRef(),{userSelectionActive:A,elementsSelectable:L,dragging:O}=In(gM,Ds),M=()=>{x.setState({userSelectionActive:!1,userSelectionRect:null}),k.current=0,j.current=0},H=C=>{l==null||l(C),x.getState().resetSelectedElements(),x.setState({nodesSelectionActive:!1})},X=C=>{if(Array.isArray(n)&&(n!=null&&n.includes(2))){C.preventDefault();return}u==null||u(C)},Y=c?C=>c(C):void 0,Z=C=>{const{resetSelectedElements:N,domNode:P}=x.getState();if(E.current=P==null?void 0:P.getBoundingClientRect(),!L||!e||C.button!==0||C.target!==w.current||!E.current)return;const{x:D,y:ne}=Sl(C,E.current);N(),x.setState({userSelectionRect:{width:0,height:0,startX:D,startY:ne,x:D,y:ne}}),r==null||r(C)},re=C=>{const{userSelectionRect:N,nodeInternals:P,edges:D,transform:ne,onNodesChange:B,onEdgesChange:z,nodeOrigin:G,getNodes:T}=x.getState();if(!e||!E.current||!N)return;x.setState({userSelectionActive:!0,nodesSelectionActive:!1});const Q=Sl(C,E.current),K=N.startX??0,J=N.startY??0,oe={...N,x:Q.x<K?Q.x:K,y:Q.y<J?Q.y:J,width:Math.abs(Q.x-K),height:Math.abs(Q.y-J)},he=T(),_e=Kb(P,oe,ne,t===Df.Partial,!0,G),we=Yb(_e,D).map(ze=>ze.id),Ee=_e.map(ze=>ze.id);if(k.current!==Ee.length){k.current=Ee.length;const ze=Au(he,Ee);ze.length&&(B==null||B(ze))}if(j.current!==we.length){j.current=we.length;const ze=Au(D,we);ze.length&&(z==null||z(ze))}x.setState({userSelectionRect:oe})},ie=C=>{if(C.button!==0)return;const{userSelectionRect:N}=x.getState();!A&&N&&C.target===w.current&&(H==null||H(C)),x.setState({nodesSelectionActive:k.current>0}),M(),o==null||o(C)},ue=C=>{A&&(x.setState({nodesSelectionActive:k.current>0}),o==null||o(C)),M()},F=L&&(e||A);return ve.createElement("div",{className:Gs(["react-flow__pane",{dragging:O,selection:e}]),onClick:F?void 0:mp(H,w),onContextMenu:mp(X,w),onWheel:mp(Y,w),onMouseEnter:F?void 0:f,onMouseDown:F?Z:void 0,onMouseMove:F?re:_,onMouseUp:F?ie:void 0,onMouseLeave:F?ue:p,ref:w,style:ey},y,ve.createElement(mM,null))});f0.displayName="Pane";function h0(e,t){if(!e.parentNode)return!1;const n=t.get(e.parentNode);return n?n.selected?!0:h0(n,t):!1}function tv(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 yM(e,t,n,r){return Array.from(e.values()).filter(o=>(o.selected||o.id===r)&&(!o.parentNode||!h0(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 wM(e,t){return!t||t==="parent"?t:[t[0],[t[1][0]-(e.width||0),t[1][1]-(e.height||0)]]}function m0(e,t,n,r,o=[0,0],l){const u=wM(e,e.extent||r);let c=u;if(e.extent==="parent"&&!e.expandParent)if(e.parentNode&&e.width&&e.height){const p=n.get(e.parentNode),{x:y,y:w}=uc(p,o).positionAbsolute;c=p&&$i(y)&&$i(w)&&$i(p.width)&&$i(p.height)?[[y+e.width*o[0],w+e.height*o[1]],[y+p.width-e.width+e.width*o[0],w+p.height-e.height+e.height*o[1]]]:c}else l==null||l("005",ja.error005()),c=u;else if(e.extent&&e.parentNode&&e.extent!=="parent"){const p=n.get(e.parentNode),{x:y,y:w}=uc(p,o).positionAbsolute;c=[[e.extent[0][0]+y,e.extent[0][1]+w],[e.extent[1][0]+y,e.extent[1][1]+w]]}let f={x:0,y:0};if(e.parentNode){const p=n.get(e.parentNode);f=uc(p,o).positionAbsolute}const _=c&&c!=="parent"?Vg(t,c):t;return{position:{x:_.x-f.x,y:_.y-f.y},positionAbsolute:_}}function _p({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 nv=(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 _=f.getBoundingClientRect();return{id:f.getAttribute("data-handleid"),position:f.getAttribute("data-handlepos"),x:(_.left-u.left-c.x)/n,y:(_.top-u.top-c.y)/n,...Hg(f)}})};function gf(e,t,n){return n===void 0?n:r=>{const o=t().nodeInternals.get(e);o&&n(r,{...o})}}function fg({id:e,store:t,unselect:n=!1,nodeRef:r}){const{addSelectedNodes:o,unselectNodesAndEdges:l,multiSelectionActive:u,nodeInternals:c,onError:f}=t.getState(),_=c.get(e);if(!_){f==null||f("012",ja.error012(e));return}t.setState({nodesSelectionActive:!1}),_.selected?(n||_.selected&&u)&&(l({nodes:[_],edges:[]}),requestAnimationFrame(()=>{var p;return(p=r==null?void 0:r.current)==null?void 0:p.blur()})):o([e])}function vM(){const e=Cs();return m.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 pp(e){return(t,n,r)=>e==null?void 0:e(t,r)}function _0({nodeRef:e,disabled:t=!1,noDragClassName:n,handleSelector:r,nodeId:o,isSelectable:l,selectNodesOnDrag:u}){const c=Cs(),[f,_]=m.useState(!1),p=m.useRef([]),y=m.useRef({x:null,y:null}),w=m.useRef(0),x=m.useRef(null),k=m.useRef({x:0,y:0}),j=m.useRef(null),E=m.useRef(!1),A=m.useRef(!1),L=vM();return m.useEffect(()=>{if(e!=null&&e.current){const O=Ei(e.current),M=({x:Y,y:Z})=>{const{nodeInternals:re,onNodeDrag:ie,onSelectionDrag:ue,updateNodePositions:F,nodeExtent:C,snapGrid:N,snapToGrid:P,nodeOrigin:D,onError:ne}=c.getState();y.current={x:Y,y:Z};let B=!1,z={x:0,y:0,x2:0,y2:0};if(p.current.length>1&&C){const T=l_(p.current,D);z=Pf(T)}if(p.current=p.current.map(T=>{const Q={x:Y-T.distance.x,y:Z-T.distance.y};P&&(Q.x=N[0]*Math.round(Q.x/N[0]),Q.y=N[1]*Math.round(Q.y/N[1]));const K=[[C[0][0],C[0][1]],[C[1][0],C[1][1]]];p.current.length>1&&C&&!T.extent&&(K[0][0]=T.positionAbsolute.x-z.x+C[0][0],K[1][0]=T.positionAbsolute.x+(T.width??0)-z.x2+C[1][0],K[0][1]=T.positionAbsolute.y-z.y+C[0][1],K[1][1]=T.positionAbsolute.y+(T.height??0)-z.y2+C[1][1]);const J=m0(T,Q,re,K,D,ne);return B=B||T.position.x!==J.position.x||T.position.y!==J.position.y,T.position=J.position,T.positionAbsolute=J.positionAbsolute,T}),!B)return;F(p.current,!0,!0),_(!0);const G=o?ie:pp(ue);if(G&&j.current){const[T,Q]=_p({nodeId:o,dragItems:p.current,nodeInternals:re});G(j.current,T,Q)}},H=()=>{if(!x.current)return;const[Y,Z]=Pb(k.current,x.current);if(Y!==0||Z!==0){const{transform:re,panBy:ie}=c.getState();y.current.x=(y.current.x??0)-Y/re[2],y.current.y=(y.current.y??0)-Z/re[2],ie({x:Y,y:Z})&&M(y.current)}w.current=requestAnimationFrame(H)},X=Y=>{var D;const{nodeInternals:Z,multiSelectionActive:re,nodesDraggable:ie,unselectNodesAndEdges:ue,onNodeDragStart:F,onSelectionDragStart:C}=c.getState();A.current=!0;const N=o?F:pp(C);(!u||!l)&&!re&&o&&((D=Z.get(o))!=null&&D.selected||ue()),o&&l&&u&&fg({id:o,store:c,nodeRef:e});const P=L(Y);if(y.current=P,p.current=yM(Z,ie,P,o),N&&p.current){const[ne,B]=_p({nodeId:o,dragItems:p.current,nodeInternals:Z});N(Y.sourceEvent,ne,B)}};if(t)O.on(".drag",null);else{const Y=A$().on("start",Z=>{const{domNode:re,nodeDragThreshold:ie}=c.getState();ie===0&&X(Z);const ue=L(Z);y.current=ue,x.current=(re==null?void 0:re.getBoundingClientRect())||null,k.current=Sl(Z.sourceEvent,x.current)}).on("drag",Z=>{var F,C;const re=L(Z),{autoPanOnNodeDrag:ie,nodeDragThreshold:ue}=c.getState();if(!E.current&&A.current&&ie&&(E.current=!0,H()),!A.current){const N=re.xSnapped-(((F=y==null?void 0:y.current)==null?void 0:F.x)??0),P=re.ySnapped-(((C=y==null?void 0:y.current)==null?void 0:C.y)??0);Math.sqrt(N*N+P*P)>ue&&X(Z)}(y.current.x!==re.xSnapped||y.current.y!==re.ySnapped)&&p.current&&A.current&&(j.current=Z.sourceEvent,k.current=Sl(Z.sourceEvent,x.current),M(re))}).on("end",Z=>{if(A.current&&(_(!1),E.current=!1,A.current=!1,cancelAnimationFrame(w.current),p.current)){const{updateNodePositions:re,nodeInternals:ie,onNodeDragStop:ue,onSelectionDragStop:F}=c.getState(),C=o?ue:pp(F);if(re(p.current,!1,!1),C){const[N,P]=_p({nodeId:o,dragItems:p.current,nodeInternals:ie});C(Z.sourceEvent,N,P)}}}).filter(Z=>{const re=Z.target;return!Z.button&&(!n||!tv(re,`.${n}`,e))&&(!r||tv(re,r,e))});return O.call(Y),()=>{O.on(".drag",null)}}}},[e,t,n,r,l,c,o,u,L]),f}function p0(){const e=Cs();return m.useCallback(n=>{const{nodeInternals:r,nodeExtent:o,updateNodePositions:l,getNodes:u,snapToGrid:c,snapGrid:f,onError:_,nodesDraggable:p}=e.getState(),y=u().filter(L=>L.selected&&(L.draggable||p&&typeof L.draggable>"u")),w=c?f[0]:5,x=c?f[1]:5,k=n.isShiftPressed?4:1,j=n.x*w*k,E=n.y*x*k,A=y.map(L=>{if(L.positionAbsolute){const O={x:L.positionAbsolute.x+j,y:L.positionAbsolute.y+E};c&&(O.x=f[0]*Math.round(O.x/f[0]),O.y=f[1]*Math.round(O.y/f[1]));const{positionAbsolute:M,position:H}=m0(L,O,r,o,void 0,_);L.position=H,L.positionAbsolute=M}return L});l(A,!0,!1)},[])}const Ou={ArrowUp:{x:0,y:-1},ArrowDown:{x:0,y:1},ArrowLeft:{x:-1,y:0},ArrowRight:{x:1,y:0}};var yf=e=>{const t=({id:n,type:r,data:o,xPos:l,yPos:u,xPosOrigin:c,yPosOrigin:f,selected:_,onClick:p,onMouseEnter:y,onMouseMove:w,onMouseLeave:x,onContextMenu:k,onDoubleClick:j,style:E,className:A,isDraggable:L,isSelectable:O,isConnectable:M,isFocusable:H,selectNodesOnDrag:X,sourcePosition:Y,targetPosition:Z,hidden:re,resizeObserver:ie,dragHandle:ue,zIndex:F,isParent:C,noDragClassName:N,noPanClassName:P,initialized:D,disableKeyboardA11y:ne,ariaLabel:B,rfId:z,hasHandleBounds:G})=>{const T=Cs(),Q=m.useRef(null),K=m.useRef(Y),J=m.useRef(Z),oe=m.useRef(r),he=O||L||p||y||w||x,_e=p0(),we=gf(n,T.getState,y),Ee=gf(n,T.getState,w),ze=gf(n,T.getState,x),Ue=gf(n,T.getState,k),_t=gf(n,T.getState,j),Pe=Je=>{const{nodeDragThreshold:Se}=T.getState();if(O&&(!X||!L||Se>0)&&fg({id:n,store:T,nodeRef:Q}),p){const Ie=T.getState().nodeInternals.get(n);Ie&&p(Je,{...Ie})}},et=Je=>{if(!ag(Je))if(Bb.includes(Je.key)&&O){const Se=Je.key==="Escape";fg({id:n,store:T,unselect:Se,nodeRef:Q})}else!ne&&L&&_&&Object.prototype.hasOwnProperty.call(Ou,Je.key)&&(T.setState({ariaLiveMessage:`Moved selected node ${Je.key.replace("Arrow","").toLowerCase()}. New position, x: ${~~l}, y: ${~~u}`}),_e({x:Ou[Je.key].x,y:Ou[Je.key].y,isShiftPressed:Je.shiftKey}))};m.useEffect(()=>()=>{Q.current&&(ie==null||ie.unobserve(Q.current))},[]),m.useEffect(()=>{if(Q.current&&!re){const Je=Q.current;(!D||!G)&&(ie==null||ie.unobserve(Je),ie==null||ie.observe(Je))}},[re,D,G]),m.useEffect(()=>{const Je=oe.current!==r,Se=K.current!==Y,Ie=J.current!==Z;Q.current&&(Je||Se||Ie)&&(Je&&(oe.current=r),Se&&(K.current=Y),Ie&&(J.current=Z),T.getState().updateNodeDimensions([{id:n,nodeElement:Q.current,forceUpdate:!0}]))},[n,r,Y,Z]);const lt=_0({nodeRef:Q,disabled:re||!L,noDragClassName:N,handleSelector:ue,nodeId:n,isSelectable:O,selectNodesOnDrag:X});return re?null:ve.createElement("div",{className:Gs(["react-flow__node",`react-flow__node-${r}`,{[P]:L},A,{selected:_,selectable:O,parent:C,dragging:lt}]),ref:Q,style:{zIndex:F,transform:`translate(${c}px,${f}px)`,pointerEvents:he?"all":"none",visibility:D?"visible":"hidden",...E},"data-id":n,"data-testid":`rf__node-${n}`,onMouseEnter:we,onMouseMove:Ee,onMouseLeave:ze,onContextMenu:Ue,onClick:Pe,onDoubleClick:_t,onKeyDown:H?et:void 0,tabIndex:H?0:void 0,role:H?"button":void 0,"aria-describedby":ne?void 0:`${a0}-${z}`,"aria-label":B},ve.createElement(RT,{value:n},ve.createElement(e,{id:n,data:o,type:r,xPos:l,yPos:u,selected:_,isConnectable:M,sourcePosition:Y,targetPosition:Z,dragging:lt,dragHandle:ue,zIndex:F})))};return t.displayName="NodeWrapper",m.memo(t)};const xM=e=>{const t=e.getNodes().filter(n=>n.selected);return{...l_(t,e.nodeOrigin),transformString:`translate(${e.transform[0]}px,${e.transform[1]}px) scale(${e.transform[2]})`,userSelectionActive:e.userSelectionActive}};function bM({onSelectionContextMenu:e,noPanClassName:t,disableKeyboardA11y:n}){const r=Cs(),{width:o,height:l,x:u,y:c,transformString:f,userSelectionActive:_}=In(xM,Ds),p=p0(),y=m.useRef(null);if(m.useEffect(()=>{var k;n||(k=y.current)==null||k.focus({preventScroll:!0})},[n]),_0({nodeRef:y}),_||!o||!l)return null;const w=e?k=>{const j=r.getState().getNodes().filter(E=>E.selected);e(k,j)}:void 0,x=k=>{Object.prototype.hasOwnProperty.call(Ou,k.key)&&p({x:Ou[k.key].x,y:Ou[k.key].y,isShiftPressed:k.shiftKey})};return ve.createElement("div",{className:Gs(["react-flow__nodesselection","react-flow__container",t]),style:{transform:f}},ve.createElement("div",{ref:y,className:"react-flow__nodesselection-rect",onContextMenu:w,tabIndex:n?void 0:-1,onKeyDown:n?void 0:x,style:{width:o,height:l,top:c,left:u}}))}var jM=m.memo(bM);const SM=e=>e.nodesSelectionActive,g0=({children:e,onPaneClick:t,onPaneMouseEnter:n,onPaneMouseMove:r,onPaneMouseLeave:o,onPaneContextMenu:l,onPaneScroll:u,deleteKeyCode:c,onMove:f,onMoveStart:_,onMoveEnd:p,selectionKeyCode:y,selectionOnDrag:w,selectionMode:x,onSelectionStart:k,onSelectionEnd:j,multiSelectionKeyCode:E,panActivationKeyCode:A,zoomActivationKeyCode:L,elementsSelectable:O,zoomOnScroll:M,zoomOnPinch:H,panOnScroll:X,panOnScrollSpeed:Y,panOnScrollMode:Z,zoomOnDoubleClick:re,panOnDrag:ie,defaultViewport:ue,translateExtent:F,minZoom:C,maxZoom:N,preventScrolling:P,onSelectionContextMenu:D,noWheelClassName:ne,noPanClassName:B,disableKeyboardA11y:z})=>{const G=In(SM),T=zf(y),Q=zf(A),K=Q||ie,J=Q||X,oe=T||w&&K!==!0;return lM({deleteKeyCode:c,multiSelectionKeyCode:E}),ve.createElement(fM,{onMove:f,onMoveStart:_,onMoveEnd:p,onPaneContextMenu:l,elementsSelectable:O,zoomOnScroll:M,zoomOnPinch:H,panOnScroll:J,panOnScrollSpeed:Y,panOnScrollMode:Z,zoomOnDoubleClick:re,panOnDrag:!T&&K,defaultViewport:ue,translateExtent:F,minZoom:C,maxZoom:N,zoomActivationKeyCode:L,preventScrolling:P,noWheelClassName:ne,noPanClassName:B},ve.createElement(f0,{onSelectionStart:k,onSelectionEnd:j,onPaneClick:t,onPaneMouseEnter:n,onPaneMouseMove:r,onPaneMouseLeave:o,onPaneContextMenu:l,onPaneScroll:u,panOnDrag:K,isSelecting:!!oe,selectionMode:x},e,G&&ve.createElement(jM,{onSelectionContextMenu:D,noPanClassName:B,disableKeyboardA11y:z})))};g0.displayName="FlowRenderer";var kM=m.memo(g0);function NM(e){return In(m.useCallback(n=>e?Kb(n.nodeInternals,{x:0,y:0,width:n.width,height:n.height},n.transform,!0):n.getNodes(),[e]))}function CM(e){const t={input:yf(e.input||s0),default:yf(e.default||dg),output:yf(e.output||i0),group:yf(e.group||Zg)},n={},r=Object.keys(e).filter(o=>!["input","default","output","group"].includes(o)).reduce((o,l)=>(o[l]=yf(e[l]||dg),o),n);return{...t,...r}}const EM=({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]},$M=e=>({nodesDraggable:e.nodesDraggable,nodesConnectable:e.nodesConnectable,nodesFocusable:e.nodesFocusable,elementsSelectable:e.elementsSelectable,updateNodeDimensions:e.updateNodeDimensions,onError:e.onError}),y0=e=>{const{nodesDraggable:t,nodesConnectable:n,nodesFocusable:r,elementsSelectable:o,updateNodeDimensions:l,onError:u}=In($M,Ds),c=NM(e.onlyRenderVisibleElements),f=m.useRef(),_=m.useMemo(()=>{if(typeof ResizeObserver>"u")return null;const p=new ResizeObserver(y=>{const w=y.map(x=>({id:x.target.getAttribute("data-id"),nodeElement:x.target,forceUpdate:!0}));l(w)});return f.current=p,p},[]);return m.useEffect(()=>()=>{var p;(p=f==null?void 0:f.current)==null||p.disconnect()},[]),ve.createElement("div",{className:"react-flow__nodes",style:ey},c.map(p=>{var H,X,Y;let y=p.type||"default";e.nodeTypes[y]||(u==null||u("003",ja.error003(y)),y="default");const w=e.nodeTypes[y]||e.nodeTypes.default,x=!!(p.draggable||t&&typeof p.draggable>"u"),k=!!(p.selectable||o&&typeof p.selectable>"u"),j=!!(p.connectable||n&&typeof p.connectable>"u"),E=!!(p.focusable||r&&typeof p.focusable>"u"),A=e.nodeExtent?Vg(p.positionAbsolute,e.nodeExtent):p.positionAbsolute,L=(A==null?void 0:A.x)??0,O=(A==null?void 0:A.y)??0,M=EM({x:L,y:O,width:p.width??0,height:p.height??0,origin:e.nodeOrigin});return ve.createElement(w,{key:p.id,id:p.id,className:p.className,style:p.style,type:y,data:p.data,sourcePosition:p.sourcePosition||mt.Bottom,targetPosition:p.targetPosition||mt.Top,hidden:p.hidden,xPos:L,yPos:O,xPosOrigin:M.x,yPosOrigin:M.y,selectNodesOnDrag:e.selectNodesOnDrag,onClick:e.onNodeClick,onMouseEnter:e.onNodeMouseEnter,onMouseMove:e.onNodeMouseMove,onMouseLeave:e.onNodeMouseLeave,onContextMenu:e.onNodeContextMenu,onDoubleClick:e.onNodeDoubleClick,selected:!!p.selected,isDraggable:x,isSelectable:k,isConnectable:j,isFocusable:E,resizeObserver:_,dragHandle:p.dragHandle,zIndex:((H=p[ps])==null?void 0:H.z)??0,isParent:!!((X=p[ps])!=null&&X.isParent),noDragClassName:e.noDragClassName,noPanClassName:e.noPanClassName,initialized:!!p.width&&!!p.height,rfId:e.rfId,disableKeyboardA11y:e.disableKeyboardA11y,ariaLabel:p.ariaLabel,hasHandleBounds:!!((Y=p[ps])!=null&&Y.handleBounds)})}))};y0.displayName="NodeRenderer";var AM=m.memo(y0);const TM=(e,t,n)=>n===mt.Left?e-t:n===mt.Right?e+t:e,MM=(e,t,n)=>n===mt.Top?e-t:n===mt.Bottom?e+t:e,sv="react-flow__edgeupdater",rv=({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:Gs([sv,`${sv}-${c}`]),cx:TM(t,r,e),cy:MM(n,r,e),r,stroke:"transparent",fill:"transparent"}),RM=()=>!0;var ku=e=>{const t=({id:n,className:r,type:o,data:l,onClick:u,onEdgeDoubleClick:c,selected:f,animated:_,label:p,labelStyle:y,labelShowBg:w,labelBgStyle:x,labelBgPadding:k,labelBgBorderRadius:j,style:E,source:A,target:L,sourceX:O,sourceY:M,targetX:H,targetY:X,sourcePosition:Y,targetPosition:Z,elementsSelectable:re,hidden:ie,sourceHandleId:ue,targetHandleId:F,onContextMenu:C,onMouseEnter:N,onMouseMove:P,onMouseLeave:D,edgeUpdaterRadius:ne,onEdgeUpdate:B,onEdgeUpdateStart:z,onEdgeUpdateEnd:G,markerEnd:T,markerStart:Q,rfId:K,ariaLabel:J,isFocusable:oe,isUpdatable:he,pathOptions:_e,interactionWidth:we})=>{const Ee=m.useRef(null),[ze,Ue]=m.useState(!1),[_t,Pe]=m.useState(!1),et=Cs(),lt=m.useMemo(()=>`url('#${cg(Q,K)}')`,[Q,K]),Je=m.useMemo(()=>`url('#${cg(T,K)}')`,[T,K]);if(ie)return null;const Se=Mt=>{var gn;const{edges:wn,addSelectedEdges:Dn,unselectNodesAndEdges:Mn,multiSelectionActive:vn}=et.getState(),On=wn.find(Es=>Es.id===n);On&&(re&&(et.setState({nodesSelectionActive:!1}),On.selected&&vn?(Mn({nodes:[],edges:[On]}),(gn=Ee.current)==null||gn.blur()):Dn([n])),u&&u(Mt,On))},Ie=pf(n,et.getState,c),ct=pf(n,et.getState,C),ge=pf(n,et.getState,N),De=pf(n,et.getState,P),Ye=pf(n,et.getState,D),Dt=(Mt,wn)=>{if(Mt.button!==0)return;const{edges:Dn,isValidConnection:Mn}=et.getState(),vn=wn?L:A,On=(wn?F:ue)||null,gn=wn?"target":"source",Es=Mn||RM,Hn=wn,as=Dn.find(ce=>ce.id===n);Pe(!0),z==null||z(Mt,as,gn);const Tr=ce=>{Pe(!1),G==null||G(ce,as,gn)};Qb({event:Mt,handleId:On,nodeId:vn,onConnect:ce=>B==null?void 0:B(as,ce),isTarget:Hn,getState:et.getState,setState:et.setState,isValidConnection:Es,edgeUpdaterType:gn,onEdgeUpdateEnd:Tr})},tn=Mt=>Dt(Mt,!0),pn=Mt=>Dt(Mt,!1),Ut=()=>Ue(!0),It=()=>Ue(!1),un=!re&&!u,Wn=Mt=>{var wn;if(Bb.includes(Mt.key)&&re){const{unselectNodesAndEdges:Dn,addSelectedEdges:Mn,edges:vn}=et.getState();Mt.key==="Escape"?((wn=Ee.current)==null||wn.blur(),Dn({edges:[vn.find(gn=>gn.id===n)]})):Mn([n])}};return ve.createElement("g",{className:Gs(["react-flow__edge",`react-flow__edge-${o}`,r,{selected:f,animated:_,inactive:un,updating:ze}]),onClick:Se,onDoubleClick:Ie,onContextMenu:ct,onMouseEnter:ge,onMouseMove:De,onMouseLeave:Ye,onKeyDown:oe?Wn:void 0,tabIndex:oe?0:void 0,role:oe?"button":"img","data-testid":`rf__edge-${n}`,"aria-label":J===null?void 0:J||`Edge from ${A} to ${L}`,"aria-describedby":oe?`${l0}-${K}`:void 0,ref:Ee},!_t&&ve.createElement(e,{id:n,source:A,target:L,selected:f,animated:_,label:p,labelStyle:y,labelShowBg:w,labelBgStyle:x,labelBgPadding:k,labelBgBorderRadius:j,data:l,style:E,sourceX:O,sourceY:M,targetX:H,targetY:X,sourcePosition:Y,targetPosition:Z,sourceHandleId:ue,targetHandleId:F,markerStart:lt,markerEnd:Je,pathOptions:_e,interactionWidth:we}),he&&ve.createElement(ve.Fragment,null,(he==="source"||he===!0)&&ve.createElement(rv,{position:Y,centerX:O,centerY:M,radius:ne,onMouseDown:tn,onMouseEnter:Ut,onMouseOut:It,type:"source"}),(he==="target"||he===!0)&&ve.createElement(rv,{position:Z,centerX:H,centerY:X,radius:ne,onMouseDown:pn,onMouseEnter:Ut,onMouseOut:It,type:"target"})))};return t.displayName="EdgeWrapper",m.memo(t)};function LM(e){const t={default:ku(e.default||qm),straight:ku(e.bezier||Yg),step:ku(e.step||Kg),smoothstep:ku(e.step||a_),simplebezier:ku(e.simplebezier||Gg)},n={},r=Object.keys(e).filter(o=>!["default","bezier"].includes(o)).reduce((o,l)=>(o[l]=ku(e[l]||qm),o),n);return{...t,...r}}function iv(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 mt.Top:return{x:r+l/2,y:o};case mt.Right:return{x:r+l,y:o+u/2};case mt.Bottom:return{x:r+l/2,y:o+u};case mt.Left:return{x:r,y:o+u/2}}}function ov(e,t){return e?e.length===1||!t?e[0]:t&&e.find(n=>n.id===t)||null:null}const IM=(e,t,n,r,o,l)=>{const u=iv(n,e,t),c=iv(l,r,o);return{sourceX:u.x,sourceY:u.y,targetX:c.x,targetY:c.y}};function OM({sourcePos:e,targetPos:t,sourceWidth:n,sourceHeight:r,targetWidth:o,targetHeight:l,width:u,height:c,transform:f}){const _={x:Math.min(e.x,t.x),y:Math.min(e.y,t.y),x2:Math.max(e.x+n,t.x+o),y2:Math.max(e.y+r,t.y+l)};_.x===_.x2&&(_.x2+=1),_.y===_.y2&&(_.y2+=1);const p=Pf({x:(0-f[0])/f[2],y:(0-f[1])/f[2],width:u/f[2],height:c/f[2]}),y=Math.max(0,Math.min(p.x2,_.x2)-Math.max(p.x,_.x)),w=Math.max(0,Math.min(p.y2,_.y2)-Math.max(p.y,_.y));return Math.ceil(y*w)>0}function av(e){var r,o,l,u,c;const t=((r=e==null?void 0:e[ps])==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 PM=[{level:0,isMaxLevel:!0,edges:[]}];function DM(e,t,n=!1){let r=-1;const o=e.reduce((u,c)=>{var p,y;const f=$i(c.zIndex);let _=f?c.zIndex:0;if(n){const w=t.get(c.target),x=t.get(c.source),k=c.selected||(w==null?void 0:w.selected)||(x==null?void 0:x.selected),j=Math.max(((p=x==null?void 0:x[ps])==null?void 0:p.z)||0,((y=w==null?void 0:w[ps])==null?void 0:y.z)||0,1e3);_=(f?c.zIndex:0)+(k?j:0)}return u[_]?u[_].push(c):u[_]=[c],r=_>r?_:r,u},{}),l=Object.entries(o).map(([u,c])=>{const f=+u;return{edges:c,level:f,isMaxLevel:f===r}});return l.length===0?PM:l}function FM(e,t,n){const r=In(m.useCallback(o=>e?o.edges.filter(l=>{const u=t.get(l.source),c=t.get(l.target);return(u==null?void 0:u.width)&&(u==null?void 0:u.height)&&(c==null?void 0:c.width)&&(c==null?void 0:c.height)&&OM({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 DM(r,t,n)}const zM=({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"}),BM=({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"}),lv={[Ff.Arrow]:zM,[Ff.ArrowClosed]:BM};function UM(e){const t=Cs();return m.useMemo(()=>{var o,l;return Object.prototype.hasOwnProperty.call(lv,e)?lv[e]:((l=(o=t.getState()).onError)==null||l.call(o,"009",ja.error009(e)),null)},[e])}const WM=({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=UM(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},qM=({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=cg(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))},w0=({defaultColor:e,rfId:t})=>{const n=In(m.useCallback(qM({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(WM,{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})))};w0.displayName="MarkerDefinitions";var HM=m.memo(w0);const VM=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}),v0=({defaultMarkerColor:e,onlyRenderVisibleElements:t,elevateEdgesOnSelect:n,rfId:r,edgeTypes:o,noPanClassName:l,onEdgeUpdate:u,onEdgeContextMenu:c,onEdgeMouseEnter:f,onEdgeMouseMove:_,onEdgeMouseLeave:p,onEdgeClick:y,edgeUpdaterRadius:w,onEdgeDoubleClick:x,onEdgeUpdateStart:k,onEdgeUpdateEnd:j,children:E})=>{const{edgesFocusable:A,edgesUpdatable:L,elementsSelectable:O,width:M,height:H,connectionMode:X,nodeInternals:Y,onError:Z}=In(VM,Ds),re=FM(t,Y,n);return M?ve.createElement(ve.Fragment,null,re.map(({level:ie,edges:ue,isMaxLevel:F})=>ve.createElement("svg",{key:ie,style:{zIndex:ie},width:M,height:H,className:"react-flow__edges react-flow__container"},F&&ve.createElement(HM,{defaultColor:e,rfId:r}),ve.createElement("g",null,ue.map(C=>{const[N,P,D]=av(Y.get(C.source)),[ne,B,z]=av(Y.get(C.target));if(!D||!z)return null;let G=C.type||"default";o[G]||(Z==null||Z("011",ja.error011(G)),G="default");const T=o[G]||o.default,Q=X===mc.Strict?B.target:(B.target??[]).concat(B.source??[]),K=ov(P.source,C.sourceHandle),J=ov(Q,C.targetHandle),oe=(K==null?void 0:K.position)||mt.Bottom,he=(J==null?void 0:J.position)||mt.Top,_e=!!(C.focusable||A&&typeof C.focusable>"u"),we=typeof u<"u"&&(C.updatable||L&&typeof C.updatable>"u");if(!K||!J)return Z==null||Z("008",ja.error008(K,C)),null;const{sourceX:Ee,sourceY:ze,targetX:Ue,targetY:_t}=IM(N,K,oe,ne,J,he);return ve.createElement(T,{key:C.id,id:C.id,className:Gs([C.className,l]),type:G,data:C.data,selected:!!C.selected,animated:!!C.animated,hidden:!!C.hidden,label:C.label,labelStyle:C.labelStyle,labelShowBg:C.labelShowBg,labelBgStyle:C.labelBgStyle,labelBgPadding:C.labelBgPadding,labelBgBorderRadius:C.labelBgBorderRadius,style:C.style,source:C.source,target:C.target,sourceHandleId:C.sourceHandle,targetHandleId:C.targetHandle,markerEnd:C.markerEnd,markerStart:C.markerStart,sourceX:Ee,sourceY:ze,targetX:Ue,targetY:_t,sourcePosition:oe,targetPosition:he,elementsSelectable:O,onEdgeUpdate:u,onContextMenu:c,onMouseEnter:f,onMouseMove:_,onMouseLeave:p,onClick:y,edgeUpdaterRadius:w,onEdgeDoubleClick:x,onEdgeUpdateStart:k,onEdgeUpdateEnd:j,rfId:r,ariaLabel:C.ariaLabel,isFocusable:_e,isUpdatable:we,pathOptions:"pathOptions"in C?C.pathOptions:void 0,interactionWidth:C.interactionWidth})})))),E):null};v0.displayName="EdgeRenderer";var GM=m.memo(v0);const KM=e=>`translate(${e.transform[0]}px,${e.transform[1]}px) scale(${e.transform[2]})`;function YM({children:e}){const t=In(KM);return ve.createElement("div",{className:"react-flow__viewport react-flow__container",style:{transform:t}},e)}function JM(e){const t=Qg(),n=m.useRef(!1);m.useEffect(()=>{!n.current&&t.viewportInitialized&&e&&(setTimeout(()=>e(t),1),n.current=!0)},[e,t.viewportInitialized])}const XM={[mt.Left]:mt.Right,[mt.Right]:mt.Left,[mt.Top]:mt.Bottom,[mt.Bottom]:mt.Top},x0=({nodeId:e,handleType:t,style:n,type:r=jl.Bezier,CustomComponent:o,connectionStatus:l})=>{var X,Y,Z;const{fromNode:u,handleId:c,toX:f,toY:_,connectionMode:p}=In(m.useCallback(re=>({fromNode:re.nodeInternals.get(e),handleId:re.connectionHandleId,toX:(re.connectionPosition.x-re.transform[0])/re.transform[2],toY:(re.connectionPosition.y-re.transform[1])/re.transform[2],connectionMode:re.connectionMode}),[e]),Ds),y=(X=u==null?void 0:u[ps])==null?void 0:X.handleBounds;let w=y==null?void 0:y[t];if(p===mc.Loose&&(w=w||(y==null?void 0:y[t==="source"?"target":"source"])),!u||!w)return null;const x=c?w.find(re=>re.id===c):w[0],k=x?x.x+x.width/2:(u.width??0)/2,j=x?x.y+x.height/2:u.height??0,E=(((Y=u.positionAbsolute)==null?void 0:Y.x)??0)+k,A=(((Z=u.positionAbsolute)==null?void 0:Z.y)??0)+j,L=x==null?void 0:x.position,O=L?XM[L]:null;if(!L||!O)return null;if(o)return ve.createElement(o,{connectionLineType:r,connectionLineStyle:n,fromNode:u,fromHandle:x,fromX:E,fromY:A,toX:f,toY:_,fromPosition:L,toPosition:O,connectionStatus:l});let M="";const H={sourceX:E,sourceY:A,sourcePosition:L,targetX:f,targetY:_,targetPosition:O};return r===jl.Bezier?[M]=Vb(H):r===jl.Step?[M]=lg({...H,borderRadius:0}):r===jl.SmoothStep?[M]=lg(H):r===jl.SimpleBezier?[M]=Hb(H):M=`M${E},${A} ${f},${_}`,ve.createElement("path",{d:M,fill:"none",className:"react-flow__connection-path",style:n})};x0.displayName="ConnectionLine";const ZM=e=>({nodeId:e.connectionNodeId,handleType:e.connectionHandleType,nodesConnectable:e.nodesConnectable,connectionStatus:e.connectionStatus,width:e.width,height:e.height});function QM({containerStyle:e,style:t,type:n,component:r}){const{nodeId:o,handleType:l,nodesConnectable:u,width:c,height:f,connectionStatus:_}=In(ZM,Ds);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:Gs(["react-flow__connection",_])},ve.createElement(x0,{nodeId:o,handleType:l,style:t,type:n,CustomComponent:r,connectionStatus:_})))}function cv(e,t){return m.useRef(null),Cs(),m.useMemo(()=>t(e),[e])}const b0=({nodeTypes:e,edgeTypes:t,onMove:n,onMoveStart:r,onMoveEnd:o,onInit:l,onNodeClick:u,onEdgeClick:c,onNodeDoubleClick:f,onEdgeDoubleClick:_,onNodeMouseEnter:p,onNodeMouseMove:y,onNodeMouseLeave:w,onNodeContextMenu:x,onSelectionContextMenu:k,onSelectionStart:j,onSelectionEnd:E,connectionLineType:A,connectionLineStyle:L,connectionLineComponent:O,connectionLineContainerStyle:M,selectionKeyCode:H,selectionOnDrag:X,selectionMode:Y,multiSelectionKeyCode:Z,panActivationKeyCode:re,zoomActivationKeyCode:ie,deleteKeyCode:ue,onlyRenderVisibleElements:F,elementsSelectable:C,selectNodesOnDrag:N,defaultViewport:P,translateExtent:D,minZoom:ne,maxZoom:B,preventScrolling:z,defaultMarkerColor:G,zoomOnScroll:T,zoomOnPinch:Q,panOnScroll:K,panOnScrollSpeed:J,panOnScrollMode:oe,zoomOnDoubleClick:he,panOnDrag:_e,onPaneClick:we,onPaneMouseEnter:Ee,onPaneMouseMove:ze,onPaneMouseLeave:Ue,onPaneScroll:_t,onPaneContextMenu:Pe,onEdgeUpdate:et,onEdgeContextMenu:lt,onEdgeMouseEnter:Je,onEdgeMouseMove:Se,onEdgeMouseLeave:Ie,edgeUpdaterRadius:ct,onEdgeUpdateStart:ge,onEdgeUpdateEnd:De,noDragClassName:Ye,noWheelClassName:Dt,noPanClassName:tn,elevateEdgesOnSelect:pn,disableKeyboardA11y:Ut,nodeOrigin:It,nodeExtent:un,rfId:Wn})=>{const Mt=cv(e,CM),wn=cv(t,LM);return JM(l),ve.createElement(kM,{onPaneClick:we,onPaneMouseEnter:Ee,onPaneMouseMove:ze,onPaneMouseLeave:Ue,onPaneContextMenu:Pe,onPaneScroll:_t,deleteKeyCode:ue,selectionKeyCode:H,selectionOnDrag:X,selectionMode:Y,onSelectionStart:j,onSelectionEnd:E,multiSelectionKeyCode:Z,panActivationKeyCode:re,zoomActivationKeyCode:ie,elementsSelectable:C,onMove:n,onMoveStart:r,onMoveEnd:o,zoomOnScroll:T,zoomOnPinch:Q,zoomOnDoubleClick:he,panOnScroll:K,panOnScrollSpeed:J,panOnScrollMode:oe,panOnDrag:_e,defaultViewport:P,translateExtent:D,minZoom:ne,maxZoom:B,onSelectionContextMenu:k,preventScrolling:z,noDragClassName:Ye,noWheelClassName:Dt,noPanClassName:tn,disableKeyboardA11y:Ut},ve.createElement(YM,null,ve.createElement(GM,{edgeTypes:wn,onEdgeClick:c,onEdgeDoubleClick:_,onEdgeUpdate:et,onlyRenderVisibleElements:F,onEdgeContextMenu:lt,onEdgeMouseEnter:Je,onEdgeMouseMove:Se,onEdgeMouseLeave:Ie,onEdgeUpdateStart:ge,onEdgeUpdateEnd:De,edgeUpdaterRadius:ct,defaultMarkerColor:G,noPanClassName:tn,elevateEdgesOnSelect:!!pn,disableKeyboardA11y:Ut,rfId:Wn},ve.createElement(QM,{style:L,type:A,component:O,containerStyle:M})),ve.createElement("div",{className:"react-flow__edgelabel-renderer"}),ve.createElement(AM,{nodeTypes:Mt,onNodeClick:u,onNodeDoubleClick:f,onNodeMouseEnter:p,onNodeMouseMove:y,onNodeMouseLeave:w,onNodeContextMenu:x,selectNodesOnDrag:N,onlyRenderVisibleElements:F,noPanClassName:tn,noDragClassName:Ye,disableKeyboardA11y:Ut,nodeOrigin:It,nodeExtent:un,rfId:Wn})))};b0.displayName="GraphView";var eR=m.memo(b0);const hg=[[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY],[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY]],_l={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:hg,nodeExtent:hg,nodesSelectionActive:!1,userSelectionActive:!1,userSelectionRect:null,connectionNodeId:null,connectionHandleId:null,connectionHandleType:"source",connectionPosition:{x:0,y:0},connectionStatus:null,connectionMode:mc.Strict,domNode:null,paneDragging:!1,noPanClassName:"nopan",nodeOrigin:[0,0],nodeDragThreshold:0,snapGrid:[15,15],snapToGrid:!1,nodesDraggable:!0,nodesConnectable:!0,nodesFocusable:!0,edgesFocusable:!0,edgesUpdatable:!0,elementsSelectable:!0,elevateNodesOnSelect:!0,fitViewOnInit:!1,fitViewOnInitDone:!1,fitViewOnInitOptions:void 0,onSelectionChange:[],multiSelectionActive:!1,connectionStartHandle:null,connectionEndHandle:null,connectionClickStartHandle:null,connectOnClick:!0,ariaLiveMessage:"",autoPanOnConnect:!0,autoPanOnNodeDrag:!0,connectionRadius:20,onError:CT,isValidConnection:void 0},tR=()=>U2((e,t)=>({..._l,setNodes:n=>{const{nodeInternals:r,nodeOrigin:o,elevateNodesOnSelect:l}=t();e({nodeInternals:hp(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?hp(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:_}=t(),p=f==null?void 0:f.querySelector(".react-flow__viewport");if(!p)return;const y=window.getComputedStyle(p),{m22:w}=new window.DOMMatrixReadOnly(y.transform),x=n.reduce((j,E)=>{const A=o.get(E.id);if(A){const L=Hg(E.nodeElement);!!(L.width&&L.height&&(A.width!==L.width||A.height!==L.height||E.forceUpdate))&&(o.set(A.id,{...A,[ps]:{...A[ps],handleBounds:{source:nv(".source",E.nodeElement,w,_),target:nv(".target",E.nodeElement,w,_)}},...L}),j.push({id:A.id,type:"dimensions",dimensions:L}))}return j},[]);u0(o,_);const k=u||l&&!u&&d0(t,{initial:!0,...c});e({nodeInternals:new Map(o),fitViewOnInitDone:k}),(x==null?void 0:x.length)>0&&(r==null||r(x))},updateNodePositions:(n,r=!0,o=!1)=>{const{triggerNodeChanges:l}=t(),u=n.map(c=>{const f={id:c.id,type:"position",dragging:o};return r&&(f.positionAbsolute=c.positionAbsolute,f.position=c.position),f});l(u)},triggerNodeChanges:n=>{const{onNodesChange:r,nodeInternals:o,hasDefaultNodes:l,nodeOrigin:u,getNodes:c,elevateNodesOnSelect:f}=t();if(n!=null&&n.length){if(l){const _=pM(n,c()),p=hp(_,o,u,f);e({nodeInternals:p})}r==null||r(n)}},addSelectedNodes:n=>{const{multiSelectionActive:r,edges:o,getNodes:l}=t();let u,c=null;r?u=n.map(f=>xl(f,!0)):(u=Au(l(),n),c=Au(o,[])),um({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=>xl(f,!0)):(u=Au(o,n),c=Au(l(),[])),um({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(p=>(p.selected=!1,xl(p.id,!1))),_=c.map(p=>xl(p.id,!1));um({changedNodes:f,changedEdges:_,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=>xl(c.id,!1)),u=n.filter(c=>c.selected).map(c=>xl(c.id,!1));um({changedNodes:l,changedEdges:u,get:t,set:e})},setNodeExtent:n=>{const{nodeInternals:r}=t();r.forEach(o=>{o.positionAbsolute=Vg(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 _=wa.translate(r[0]+n.x,r[1]+n.y).scale(r[2]),p=[[0,0],[o,l]],y=u==null?void 0:u.constrain()(_,p,f);return u.transform(c,y),r[0]!==y.x||r[1]!==y.y||r[2]!==y.k},cancelConnection:()=>e({connectionNodeId:_l.connectionNodeId,connectionHandleId:_l.connectionHandleId,connectionHandleType:_l.connectionHandleType,connectionStatus:_l.connectionStatus,connectionStartHandle:_l.connectionStartHandle,connectionEndHandle:_l.connectionEndHandle}),reset:()=>e({..._l})}),Object.is),ty=({children:e})=>{const t=m.useRef(null);return t.current||(t.current=tR()),ve.createElement(vT,{value:t.current},e)};ty.displayName="ReactFlowProvider";const j0=({children:e})=>m.useContext(o_)?ve.createElement(ve.Fragment,null,e):ve.createElement(ty,null,e);j0.displayName="ReactFlowWrapper";const nR={input:s0,default:dg,output:i0,group:Zg},sR={default:qm,straight:Yg,step:Kg,smoothstep:a_,simplebezier:Gg},rR=[0,0],iR=[15,15],oR={x:0,y:0,zoom:1},aR={width:"100%",height:"100%",overflow:"hidden",position:"relative",zIndex:0},S0=m.forwardRef(({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,className:o,nodeTypes:l=nR,edgeTypes:u=sR,onNodeClick:c,onEdgeClick:f,onInit:_,onMove:p,onMoveStart:y,onMoveEnd:w,onConnect:x,onConnectStart:k,onConnectEnd:j,onClickConnectStart:E,onClickConnectEnd:A,onNodeMouseEnter:L,onNodeMouseMove:O,onNodeMouseLeave:M,onNodeContextMenu:H,onNodeDoubleClick:X,onNodeDragStart:Y,onNodeDrag:Z,onNodeDragStop:re,onNodesDelete:ie,onEdgesDelete:ue,onSelectionChange:F,onSelectionDragStart:C,onSelectionDrag:N,onSelectionDragStop:P,onSelectionContextMenu:D,onSelectionStart:ne,onSelectionEnd:B,connectionMode:z=mc.Strict,connectionLineType:G=jl.Bezier,connectionLineStyle:T,connectionLineComponent:Q,connectionLineContainerStyle:K,deleteKeyCode:J="Backspace",selectionKeyCode:oe="Shift",selectionOnDrag:he=!1,selectionMode:_e=Df.Full,panActivationKeyCode:we="Space",multiSelectionKeyCode:Ee=Wm()?"Meta":"Control",zoomActivationKeyCode:ze=Wm()?"Meta":"Control",snapToGrid:Ue=!1,snapGrid:_t=iR,onlyRenderVisibleElements:Pe=!1,selectNodesOnDrag:et=!0,nodesDraggable:lt,nodesConnectable:Je,nodesFocusable:Se,nodeOrigin:Ie=rR,edgesFocusable:ct,edgesUpdatable:ge,elementsSelectable:De,defaultViewport:Ye=oR,minZoom:Dt=.5,maxZoom:tn=2,translateExtent:pn=hg,preventScrolling:Ut=!0,nodeExtent:It,defaultMarkerColor:un="#b1b1b7",zoomOnScroll:Wn=!0,zoomOnPinch:Mt=!0,panOnScroll:wn=!1,panOnScrollSpeed:Dn=.5,panOnScrollMode:Mn=ic.Free,zoomOnDoubleClick:vn=!0,panOnDrag:On=!0,onPaneClick:gn,onPaneMouseEnter:Es,onPaneMouseMove:Hn,onPaneMouseLeave:as,onPaneScroll:Tr,onPaneContextMenu:Vn,children:ce,onEdgeUpdate:be,onEdgeContextMenu:Ke,onEdgeDoubleClick:qe,onEdgeMouseEnter:st,onEdgeMouseMove:ut,onEdgeMouseLeave:Tt,onEdgeUpdateStart:kt,onEdgeUpdateEnd:Gt,edgeUpdaterRadius:dt=10,onNodesChange:Xt,onEdgesChange:Bt,noDragClassName:Ct="nodrag",noWheelClassName:pt="nowheel",noPanClassName:Ot="nopan",fitView:Ce=!1,fitViewOptions:Vt,connectOnClick:Et=!0,attributionPosition:ln,proOptions:$t,defaultEdgeOptions:ls,elevateNodesOnSelect:cs=!0,elevateEdgesOnSelect:Ks=!1,disableKeyboardA11y:$s=!1,autoPanOnConnect:fr=!0,autoPanOnNodeDrag:Ys=!0,connectionRadius:ao=20,isValidConnection:xe,onError:Gn,style:hn,id:lo,nodeDragThreshold:Mi,...Mr},hr)=>{const Hr=lo||"1";return ve.createElement("div",{...Mr,style:{...hn,...aR},ref:hr,className:Gs(["react-flow",o]),"data-testid":"rf__wrapper",id:lo},ve.createElement(j0,null,ve.createElement(eR,{onInit:_,onMove:p,onMoveStart:y,onMoveEnd:w,onNodeClick:c,onEdgeClick:f,onNodeMouseEnter:L,onNodeMouseMove:O,onNodeMouseLeave:M,onNodeContextMenu:H,onNodeDoubleClick:X,nodeTypes:l,edgeTypes:u,connectionLineType:G,connectionLineStyle:T,connectionLineComponent:Q,connectionLineContainerStyle:K,selectionKeyCode:oe,selectionOnDrag:he,selectionMode:_e,deleteKeyCode:J,multiSelectionKeyCode:Ee,panActivationKeyCode:we,zoomActivationKeyCode:ze,onlyRenderVisibleElements:Pe,selectNodesOnDrag:et,defaultViewport:Ye,translateExtent:pn,minZoom:Dt,maxZoom:tn,preventScrolling:Ut,zoomOnScroll:Wn,zoomOnPinch:Mt,zoomOnDoubleClick:vn,panOnScroll:wn,panOnScrollSpeed:Dn,panOnScrollMode:Mn,panOnDrag:On,onPaneClick:gn,onPaneMouseEnter:Es,onPaneMouseMove:Hn,onPaneMouseLeave:as,onPaneScroll:Tr,onPaneContextMenu:Vn,onSelectionContextMenu:D,onSelectionStart:ne,onSelectionEnd:B,onEdgeUpdate:be,onEdgeContextMenu:Ke,onEdgeDoubleClick:qe,onEdgeMouseEnter:st,onEdgeMouseMove:ut,onEdgeMouseLeave:Tt,onEdgeUpdateStart:kt,onEdgeUpdateEnd:Gt,edgeUpdaterRadius:dt,defaultMarkerColor:un,noDragClassName:Ct,noWheelClassName:pt,noPanClassName:Ot,elevateEdgesOnSelect:Ks,rfId:Hr,disableKeyboardA11y:$s,nodeOrigin:Ie,nodeExtent:It}),ve.createElement(JT,{nodes:e,edges:t,defaultNodes:n,defaultEdges:r,onConnect:x,onConnectStart:k,onConnectEnd:j,onClickConnectStart:E,onClickConnectEnd:A,nodesDraggable:lt,nodesConnectable:Je,nodesFocusable:Se,edgesFocusable:ct,edgesUpdatable:ge,elementsSelectable:De,elevateNodesOnSelect:cs,minZoom:Dt,maxZoom:tn,nodeExtent:It,onNodesChange:Xt,onEdgesChange:Bt,snapToGrid:Ue,snapGrid:_t,connectionMode:z,translateExtent:pn,connectOnClick:Et,defaultEdgeOptions:ls,fitView:Ce,fitViewOptions:Vt,onNodesDelete:ie,onEdgesDelete:ue,onNodeDragStart:Y,onNodeDrag:Z,onNodeDragStop:re,onSelectionDrag:N,onSelectionDragStart:C,onSelectionDragStop:P,noPanClassName:Ot,nodeOrigin:Ie,rfId:Hr,autoPanOnConnect:fr,autoPanOnNodeDrag:Ys,onError:Gn,connectionRadius:ao,isValidConnection:xe,nodeDragThreshold:Mi}),ve.createElement(KT,{onSelectionChange:F}),ce,ve.createElement(bT,{proOptions:$t,position:ln}),ve.createElement(tM,{rfId:Hr,disableKeyboardA11y:$s})))});S0.displayName="ReactFlow";const k0=({id:e,x:t,y:n,width:r,height:o,style:l,color:u,strokeColor:c,strokeWidth:f,className:_,borderRadius:p,shapeRendering:y,onClick:w,selected:x})=>{const{background:k,backgroundColor:j}=l||{},E=u||k||j;return ve.createElement("rect",{className:Gs(["react-flow__minimap-node",{selected:x},_]),x:t,y:n,rx:p,ry:p,width:r,height:o,fill:E,stroke:c,strokeWidth:f,shapeRendering:y,onClick:w?A=>w(A,e):void 0})};k0.displayName="MiniMapNode";var lR=m.memo(k0);const cR=e=>e.nodeOrigin,uR=e=>e.getNodes().filter(t=>!t.hidden&&t.width&&t.height),gp=e=>e instanceof Function?e:()=>e;function dR({nodeStrokeColor:e="transparent",nodeColor:t="#e2e2e2",nodeClassName:n="",nodeBorderRadius:r=5,nodeStrokeWidth:o=2,nodeComponent:l=lR,onClick:u}){const c=In(uR,Ds),f=In(cR),_=gp(t),p=gp(e),y=gp(n),w=typeof window>"u"||window.chrome?"crispEdges":"geometricPrecision";return ve.createElement(ve.Fragment,null,c.map(x=>{const{x:k,y:j}=uc(x,f).positionAbsolute;return ve.createElement(l,{key:x.id,x:k,y:j,width:x.width,height:x.height,style:x.style,selected:x.selected,className:y(x),color:_(x),borderRadius:r,strokeColor:p(x),strokeWidth:o,shapeRendering:w,onClick:u,id:x.id})}))}var fR=m.memo(dR);const hR=200,mR=150,_R=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?kT(l_(t,e.nodeOrigin),n):n,rfId:e.rfId}},pR="react-flow__minimap-desc";function N0({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:_="none",maskStrokeWidth:p=1,position:y="bottom-right",onClick:w,onNodeClick:x,pannable:k=!1,zoomable:j=!1,ariaLabel:E="React Flow mini map",inversePan:A=!1,zoomStep:L=10,offsetScale:O=5}){const M=Cs(),H=m.useRef(null),{boundingRect:X,viewBB:Y,rfId:Z}=In(_R,Ds),re=(e==null?void 0:e.width)??hR,ie=(e==null?void 0:e.height)??mR,ue=X.width/re,F=X.height/ie,C=Math.max(ue,F),N=C*re,P=C*ie,D=O*C,ne=X.x-(N-X.width)/2-D,B=X.y-(P-X.height)/2-D,z=N+D*2,G=P+D*2,T=`${pR}-${Z}`,Q=m.useRef(0);Q.current=C,m.useEffect(()=>{if(H.current){const oe=Ei(H.current),he=Ee=>{const{transform:ze,d3Selection:Ue,d3Zoom:_t}=M.getState();if(Ee.sourceEvent.type!=="wheel"||!Ue||!_t)return;const Pe=-Ee.sourceEvent.deltaY*(Ee.sourceEvent.deltaMode===1?.05:Ee.sourceEvent.deltaMode?1:.002)*L,et=ze[2]*Math.pow(2,Pe);_t.scaleTo(Ue,et)},_e=Ee=>{const{transform:ze,d3Selection:Ue,d3Zoom:_t,translateExtent:Pe,width:et,height:lt}=M.getState();if(Ee.sourceEvent.type!=="mousemove"||!Ue||!_t)return;const Je=Q.current*Math.max(1,ze[2])*(A?-1:1),Se={x:ze[0]-Ee.sourceEvent.movementX*Je,y:ze[1]-Ee.sourceEvent.movementY*Je},Ie=[[0,0],[et,lt]],ct=wa.translate(Se.x,Se.y).scale(ze[2]),ge=_t.constrain()(ct,Ie,Pe);_t.transform(Ue,ge)},we=Ib().on("zoom",k?_e:null).on("zoom.wheel",j?he:null);return oe.call(we),()=>{oe.on("zoom",null)}}},[k,j,A,L]);const K=w?oe=>{const he=to(oe);w(oe,{x:he[0],y:he[1]})}:void 0,J=x?(oe,he)=>{const _e=M.getState().nodeInternals.get(he);x(oe,_e)}:void 0;return ve.createElement(Of,{position:y,style:e,className:Gs(["react-flow__minimap",t]),"data-testid":"rf__minimap"},ve.createElement("svg",{width:re,height:ie,viewBox:`${ne} ${B} ${z} ${G}`,role:"img","aria-labelledby":T,ref:H,onClick:K},E&&ve.createElement("title",{id:T},E),ve.createElement(fR,{onClick:J,nodeColor:r,nodeStrokeColor:n,nodeBorderRadius:l,nodeClassName:o,nodeStrokeWidth:u,nodeComponent:c}),ve.createElement("path",{className:"react-flow__minimap-mask",d:`M${ne-D},${B-D}h${z+D*2}v${G+D*2}h${-z-D*2}z
|
|
132
|
-
M${Y.x},${Y.y}h${Y.width}v${Y.height}h${-Y.width}z`,fill:f,fillRule:"evenodd",stroke:_,strokeWidth:p,pointerEvents:"none"})))}N0.displayName="MiniMap";var gR=m.memo(N0);function yR(){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 wR(){return ve.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 5"},ve.createElement("path",{d:"M0 0h32v4.2H0z"}))}function vR(){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 xR(){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 bR(){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 Tu=({children:e,className:t,...n})=>ve.createElement("button",{type:"button",className:Gs(["react-flow__controls-button",t]),...n},e);Tu.displayName="ControlButton";const jR=e=>({isInteractive:e.nodesDraggable||e.nodesConnectable||e.elementsSelectable,minZoomReached:e.transform[2]<=e.minZoom,maxZoomReached:e.transform[2]>=e.maxZoom}),C0=({style:e,showZoom:t=!0,showFitView:n=!0,showInteractive:r=!0,fitViewOptions:o,onZoomIn:l,onZoomOut:u,onFitView:c,onInteractiveChange:f,className:_,children:p,position:y="bottom-left"})=>{const w=Cs(),[x,k]=m.useState(!1),{isInteractive:j,minZoomReached:E,maxZoomReached:A}=In(jR,Ds),{zoomIn:L,zoomOut:O,fitView:M}=Qg();if(m.useEffect(()=>{k(!0)},[]),!x)return null;const H=()=>{L(),l==null||l()},X=()=>{O(),u==null||u()},Y=()=>{M(o),c==null||c()},Z=()=>{w.setState({nodesDraggable:!j,nodesConnectable:!j,elementsSelectable:!j}),f==null||f(!j)};return ve.createElement(Of,{className:Gs(["react-flow__controls",_]),position:y,style:e,"data-testid":"rf__controls"},t&&ve.createElement(ve.Fragment,null,ve.createElement(Tu,{onClick:H,className:"react-flow__controls-zoomin",title:"zoom in","aria-label":"zoom in",disabled:A},ve.createElement(yR,null)),ve.createElement(Tu,{onClick:X,className:"react-flow__controls-zoomout",title:"zoom out","aria-label":"zoom out",disabled:E},ve.createElement(wR,null))),n&&ve.createElement(Tu,{className:"react-flow__controls-fitview",onClick:Y,title:"fit view","aria-label":"fit view"},ve.createElement(vR,null)),r&&ve.createElement(Tu,{className:"react-flow__controls-interactive",onClick:Z,title:"toggle interactivity","aria-label":"toggle interactivity"},j?ve.createElement(bR,null):ve.createElement(xR,null)),p)};C0.displayName="Controls";var SR=m.memo(C0),ro;(function(e){e.Lines="lines",e.Dots="dots",e.Cross="cross"})(ro||(ro={}));function kR({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 NR({color:e,radius:t}){return ve.createElement("circle",{cx:t,cy:t,r:t,fill:e})}const CR={[ro.Dots]:"#91919a",[ro.Lines]:"#eee",[ro.Cross]:"#e2e2e2"},ER={[ro.Dots]:1,[ro.Lines]:1,[ro.Cross]:6},$R=e=>({transform:e.transform,patternId:`pattern-${e.rfId}`});function E0({id:e,variant:t=ro.Dots,gap:n=20,size:r,lineWidth:o=1,offset:l=2,color:u,style:c,className:f}){const _=m.useRef(null),{transform:p,patternId:y}=In($R,Ds),w=u||CR[t],x=r||ER[t],k=t===ro.Dots,j=t===ro.Cross,E=Array.isArray(n)?n:[n,n],A=[E[0]*p[2]||1,E[1]*p[2]||1],L=x*p[2],O=j?[L,L]:A,M=k?[L/l,L/l]:[O[0]/l,O[1]/l];return ve.createElement("svg",{className:Gs(["react-flow__background",f]),style:{...c,position:"absolute",width:"100%",height:"100%",top:0,left:0},ref:_,"data-testid":"rf__background"},ve.createElement("pattern",{id:y+e,x:p[0]%A[0],y:p[1]%A[1],width:A[0],height:A[1],patternUnits:"userSpaceOnUse",patternTransform:`translate(-${M[0]},-${M[1]})`},k?ve.createElement(NR,{color:w,radius:L/l}):ve.createElement(kR,{dimensions:O,color:w,lineWidth:o})),ve.createElement("rect",{x:"0",y:"0",width:"100%",height:"100%",fill:`url(#${y+e})`}))}E0.displayName="Background";var AR=m.memo(E0);function $0(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,_=Math.min(c,f),p=Math.max(c,f);return{x:r,y:o,zoom:Math.min(p,Math.max(_,l))}}function Vm(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 TR(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 MR(e){const t=String(e||"").trim();if(!t)return"";const n=t.indexOf(":");if(n<=0||n>=t.length-1)return Vm(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 Vm(t)}function mg(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 _g(e){const t=String(e??"");let n=2166136261;for(let r=0;r<t.length;r++)n^=t.charCodeAt(r),n=Math.imul(n,16777619);return n>>>0}function A0(e){let t=e>>>0;return()=>{t+=1831565813;let n=Math.imul(t^t>>>15,1|t);return n^=n+Math.imul(n^n>>>7,61|n),((n^n>>>14)>>>0)/4294967296}}function RR(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 uv(e,t,n){var k;const r={};if(!e.length)return r;const o=new Map;for(const j of e)o.set(j,new Set);for(const j of t){const E=String((j==null?void 0:j.source)||"").trim(),A=String((j==null?void 0:j.target)||"").trim();if(!E||!A||E===A)continue;const L=o.get(E),O=o.get(A);L&&L.add(A),O&&O.add(E)}let l=e[0],u=-1;for(const j of e){const E=((k=o.get(j))==null?void 0:k.size)??0;(E>u||E===u&&j.localeCompare(l)<0)&&(l=j,u=E)}const c=new Map,f=[];for(c.set(l,0),f.push(l);f.length;){const j=f.shift(),E=c.get(j)??0,A=Array.from(o.get(j)??[]);A.sort((L,O)=>L.localeCompare(O));for(const L of A)c.has(L)||(c.set(L,E+1),f.push(L))}let _=0;for(const j of c.values())_=Math.max(_,j);for(const j of e)c.has(j)||c.set(j,_+1);const p=new Map;for(const j of e){const E=c.get(j)??0,A=p.get(E);A?A.push(j):p.set(E,[j])}const y=Array.from(p.keys()).sort((j,E)=>j-E),w=260,x=n%360*Math.PI/180;for(const j of y){const E=p.get(j)||[];if(E.sort((M,H)=>M.localeCompare(H)),j===0){if(E.length===1)r[E[0]]={x:0,y:0};else for(let H=0;H<E.length;H++){const X=x+2*Math.PI*H/E.length;r[E[H]]={x:80*Math.cos(X),y:80*Math.sin(X)}}continue}const A=w*j,L=E.length;if(L===1){r[E[0]]={x:A,y:0};continue}const O=x+j*.35;for(let M=0;M<L;M++){const H=O+2*Math.PI*M/L;r[E[M]]={x:A*Math.cos(H),y:A*Math.sin(H)}}}return r}function Cu(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 mg(o);if(n==="circle")return RR(o,r);if(n==="radial")return uv(o,e.edges,r);if(n==="force"){const l=uv(o,e.edges,r),u=A0(r||1),c=Math.max(10,Math.min(42,Math.sqrt(o.length)*2.75)),f={};for(const _ of o){const p=l[_]||{x:0,y:0};f[_]={x:p.x+(u()-.5)*c,y:p.y+(u()-.5)*c}}return f}return mg(o)}function LR(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 IR(e,t={}){const n=!!(t.groupEdges??!0),r=Math.max(1,t.maxEdgeLabelPredicates??3),o=LR(e),l=new Set;for(const w of o){const x=String(w.subject||"").trim(),k=String(w.object||"").trim();x&&l.add(x),k&&l.add(k)}const u=Array.from(l);u.sort((w,x)=>w.localeCompare(x));const c=mg(u),f=u.map(w=>({id:w,type:"default",data:{label:MR(w),kind:TR(w)},position:c[w]||{x:0,y:0}})),_=new Map,p=(w,x)=>{const k=String(w.subject||"").trim(),j=String(w.object||"").trim(),E=String(w.predicate||"").trim();return n?`edge:${k}:${j}`:`edge:${x}:${k}:${E}:${j}`};for(let w=0;w<o.length;w++){const x=o[w],k=p(x,w),j=_.get(k);j?j.push(x):_.set(k,[x])}const y=[];for(const[w,x]of _.entries()){const k=x[0],j=String(k.subject||"").trim(),E=String(k.object||"").trim();if(!j||!E)continue;const A=new Map;for(const Y of x){const Z=String(Y.predicate||"").trim();Z&&A.set(Z,(A.get(Z)||0)+1)}const L=Array.from(A.entries());L.sort((Y,Z)=>Z[1]-Y[1]||Y[0].localeCompare(Z[0]));const M=L.slice(0,r).map(([Y,Z])=>Z>1?`${Vm(Y)}×${Z}`:Vm(Y)).join(" | "),H=L.length>r?` +${L.length-r}`:"",X=`${M}${H}`.trim();y.push({id:w,source:j,target:E,label:X,animated:!1,data:{assertions:x,predicateSummary:X}})}return{nodes:f,edges:y}}function OR(e,t,n,r={}){const o=r.directed!==!1,l=String(t||"").trim(),u=String(n||"").trim();if(!l||!u)return null;if(l===u)return{nodeIds:[l],edgeIds:[]};const c=new Map,f=(j,E,A)=>{const L=c.get(j);L?L.push({to:E,edgeId:A}):c.set(j,[{to:E,edgeId:A}])};for(const j of e.edges)f(j.source,j.target,j.id),o||f(j.target,j.source,j.id);const _=[l],p=new Map,y=new Map;for(p.set(l,null),y.set(l,null);_.length;){const j=_.shift(),E=c.get(j)||[];for(const A of E)if(!p.has(A.to)){if(p.set(A.to,j),y.set(A.to,A.edgeId),A.to===u){_.length=0;break}_.push(A.to)}}if(!p.has(u))return null;const w=[],x=[];let k=u;for(;k;){w.push(k);const j=y.get(k);j&&x.push(j),k=p.get(k)||null}return w.reverse(),x.reverse(),{nodeIds:w,edgeIds:x}}const dv={seed:1,dt:1,springLength:240,springStrength:.03,repulsionStrength:9e3,centeringStrength:.003,damping:.85,maxSpeed:90,maxRepulsionNodes:320};function fm(e,t={}){const n={...dv,...t,seed:typeof t.seed=="number"&&Number.isFinite(t.seed)?Math.trunc(t.seed):dv.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 _=t.positions??Cu(e,{kind:"force",seed:n.seed}),p=A0(n.seed||1),y=Math.max(8,Math.min(38,Math.sqrt(o)*2.25));for(let x=0;x<o;x++){const k=r[x],j=_[k],E=typeof(j==null?void 0:j.x)=="number"&&Number.isFinite(j.x)?j.x:(p()-.5)*500,A=typeof(j==null?void 0:j.y)=="number"&&Number.isFinite(j.y)?j.y:(p()-.5)*500;l[2*x]=E+(p()-.5)*y,l[2*x+1]=A+(p()-.5)*y,u[2*x]=0,u[2*x+1]=0}const w=[];for(const x of e.edges){const k=f.get(String((x==null?void 0:x.source)||"").trim()),j=f.get(String((x==null?void 0:x.target)||"").trim());typeof k!="number"||typeof j!="number"||k===j||w.push(k,j)}return{nodeIds:r,pos:l,vel:u,acc:c,edges:new Uint32Array(w),options:n,tick:0}}function PR(e,t=1){const n=e.nodeIds.length;if(!n)return;const r=e.options,o=r.dt;for(let l=0;l<Math.max(1,Math.trunc(t));l++){if(e.acc.fill(0),n<=r.maxRepulsionNodes){const x=r.repulsionStrength;for(let k=0;k<n;k++){const j=e.pos[2*k],E=e.pos[2*k+1];for(let A=k+1;A<n;A++){const L=e.pos[2*A]-j,O=e.pos[2*A+1]-E,M=L*L+O*O+1e-6,H=1/Math.sqrt(M),X=x/M,Y=X*L*H,Z=X*O*H;e.acc[2*k]-=Y,e.acc[2*k+1]-=Z,e.acc[2*A]+=Y,e.acc[2*A+1]+=Z}}}const c=r.springLength,f=r.springStrength,_=e.edges;for(let x=0;x<_.length;x+=2){const k=_[x],j=_[x+1],E=e.pos[2*k],A=e.pos[2*k+1],L=e.pos[2*j],O=e.pos[2*j+1],M=L-E,H=O-A,X=M*M+H*H+1e-6,Y=Math.sqrt(X),Z=f*(Y-c),re=Z*M/Y,ie=Z*H/Y;e.acc[2*k]+=re,e.acc[2*k+1]+=ie,e.acc[2*j]-=re,e.acc[2*j+1]-=ie}const p=r.centeringStrength;for(let x=0;x<n;x++)e.acc[2*x]+=-p*e.pos[2*x],e.acc[2*x+1]+=-p*e.pos[2*x+1];const y=r.damping,w=r.maxSpeed;for(let x=0;x<n;x++){let k=(e.vel[2*x]+e.acc[2*x]*o)*y,j=(e.vel[2*x+1]+e.acc[2*x+1]*o)*y;const E=Math.sqrt(k*k+j*j);if(E>w){const A=w/E;k*=A,j*=A}e.vel[2*x]=k,e.vel[2*x+1]=j,e.pos[2*x]+=k*o,e.pos[2*x+1]+=j*o}e.tick+=1}}function DR(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 FR(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 fv(e,t="session"){const n=String(e??"").trim().toLowerCase();return n==="run"||n==="session"||n==="global"||n==="all"?n:t}function zR(){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 BR(){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 T0(e,t,n,r){const o=typeof e=="number"&&Number.isFinite(e)?e:r;return Math.min(n,Math.max(t,o))}function wf(e){const t=T0(e,.6,2.4,1),n=240*t,r=9e3*t*t;return{springLength:n,repulsionStrength:r}}const Bf="abstractuic_amx_saved_layouts_v1",pg=.025,gg=6,M0=1e6;function ny(){if(typeof window>"u")return null;try{return window.localStorage}catch{return null}}function yg(e,t="grid"){const n=String(e??"").trim().toLowerCase();return n==="grid"||n==="circle"||n==="radial"||n==="force"?n:t}function UR(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 hv(e){const t=ny();if(!t)return null;const n=String(e??"").trim();if(!n)return null;try{const r=t.getItem(Bf);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 _=yg(c.kind,"grid"),p=typeof c.seed=="number"&&Number.isFinite(c.seed)?Math.trunc(c.seed):_g(n),y=c.positions&&typeof c.positions=="object"&&!Array.isArray(c.positions)?c.positions:null,w={};if(y)for(const[j,E]of Object.entries(y)){const A=UR(E);A&&(w[String(j)]=A)}const x=$0(c.viewport,{minZoom:pg,maxZoom:gg,maxAbsTranslate:M0})??void 0,k=typeof c.saved_at=="string"&&c.saved_at.trim()?c.saved_at.trim():"";return{version:f,kind:_,seed:p,positions:w,viewport:x,saved_at:k}}catch{return null}}function WR(e,t){const n=ny();if(!n)return;const r=String(e??"").trim();if(r)try{const o=n.getItem(Bf),l=o?JSON.parse(o):null,u=l&&typeof l=="object"&&!Array.isArray(l)?{...l}:{};u[r]=t,n.setItem(Bf,JSON.stringify(u))}catch{}}function qR(e){const t=ny();if(!t)return;const n=String(e??"").trim();if(n)try{const r=t.getItem(Bf);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(Bf,JSON.stringify(l))}catch{}}function HR(e){const t=String(e??"").trim();if(!t)return;const n=Number(t);if(Number.isFinite(n))return n}function yp(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 VR(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 GR(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 _=typeof l.writer_run_id=="string"?l.writer_run_id.trim():"",p=typeof l.writer_workflow_id=="string"?l.writer_workflow_id.trim():"";_&&t.push(`writer_run_id=${_}`),p&&t.push(`writer_workflow_id=${p}`)}const u=e.attributes&&typeof e.attributes=="object"&&!Array.isArray(e.attributes)?e.attributes:null,c=u&&u._retrieval&&typeof u._retrieval=="object"&&!Array.isArray(u._retrieval)?u._retrieval:null,f=c&&typeof c.score=="number"&&Number.isFinite(c.score)?c.score:null;return f!==null&&t.push(`score=${f.toFixed(3)}`),t.length?t.join(" · "):null}function KR(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 vf(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 YR(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 xf(e){const t=YR(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 R0(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 wp(e,t){const n=String(e??"").trim().toLowerCase();return!!(n&&t.has(n))}function JR(e,t={}){const n=Math.max(1,t.maxPredicates??3),r=new Map;for(const f of e){const _=String((f==null?void 0:f.predicate)||"").trim();_&&r.set(_,(r.get(_)||0)+1)}const o=Array.from(r.entries());o.sort((f,_)=>_[1]-f[1]||f[0].localeCompare(_[0]));const u=o.slice(0,n).map(([f,_])=>{const p=R0(f);return _>1?`${p}×${_}`:p}).join(" | "),c=o.length>n?` +${o.length-n}`:"";return`${u}${c}`.trim()}function XR({resetKey:e,queryMode:t,items:n,activeMemoryText:r,packets:o,packetsVersion:l,packedCount:u,dropped:c,estimatedTokens:f,effort:_,warnings:p,onQuery:y,onItemsReplace:w,onOpenSpan:x,onOpenTranscript:k}){var _o;const j=m.useRef(null),E=m.useMemo(()=>{const U=n==null?void 0:n[0],ae=n==null?void 0:n[n.length-1],je=U?`${U.subject}|${U.predicate}|${U.object}`:"",Ne=ae?`${ae.subject}|${ae.predicate}|${ae.object}`:"";return`${(n==null?void 0:n.length)||0}:${je}:${Ne}`},[n]),A=String(e??E),L=t==="replace"?"replace":"override",[O,M]=m.useState(null),[H,X]=m.useState(null),[Y,Z]=m.useState(!1),[re,ie]=m.useState(""),[ue,F]=m.useState(!1),[C,N]=m.useState("");m.useEffect(()=>{M(null),X(null),ie(""),Z(!1),N(""),F(!1)},[A]);const[P,D]=m.useState(""),[ne,B]=m.useState(!0),[z,G]=m.useState(!1),[T,Q]=m.useState(!0),[K]=m.useState(()=>({compact:zR(),show:!1})),J=K.compact,[oe,he]=m.useState(K.show),[_e,we]=m.useState(!1),Ee=A,ze=m.useMemo(()=>_g(Ee),[Ee]),[Ue,_t]=m.useState("grid"),[Pe,et]=m.useState(ze),[lt,Je]=m.useState(!1),[Se,Ie]=m.useState(1),ct=m.useRef(null),ge=m.useRef(null),De=m.useRef(!1),[Ye,Dt]=m.useState(0),tn=m.useRef(null),pn=m.useRef(0),Ut=m.useRef(0),It=m.useRef(0),un=m.useRef(0),[Wn,Mt]=m.useState(!1),[wn,Dn]=m.useState(""),[Mn,vn]=m.useState({}),On=m.useRef({});m.useEffect(()=>{On.current=Mn},[Mn]);const[gn,Es]=m.useState(""),[Hn,as]=m.useState(""),Tr=m.useMemo(()=>{var ae;const U=(ae=n==null?void 0:n[0])==null?void 0:ae.scope;return fv(U,"session")},[n]),[Vn,ce]=m.useState(Tr),[be,Ke]=m.useState("standard"),[qe,st]=m.useState(""),[ut,Tt]=m.useState(""),[kt,Gt]=m.useState(""),[dt,Xt]=m.useState(""),[Bt,Ct]=m.useState(""),[pt,Ot]=m.useState(""),[Ce,Vt]=m.useState(""),[Et,ln]=m.useState("qwen/qwen3-next-80b");m.useEffect(()=>{ce(Tr)},[A]);const $t=Array.isArray(n)?n:[],ls=typeof r=="string"?r:"",cs=Array.isArray(o)?o:[],Ks=typeof l=="number"?l:void 0,$s=typeof u=="number"?u:void 0,fr=typeof c=="number"?c:void 0,Ys=typeof f=="number"?f:void 0,ao=_,xe=p,Gn=L==="override"&&(O!=null&&O.items)&&Array.isArray(O.items)?O.items:$t,hn=typeof(O==null?void 0:O.active_memory_text)=="string"&&O.active_memory_text.trim()?O.active_memory_text:ls,lo=(O==null?void 0:O.effort)??ao,Mi=(O==null?void 0:O.warnings)??xe,Mr=m.useMemo(()=>new Set(["rdf:type","schema:name","skos:preflabel","skos:altlabel","dcterms:title","dcterms:identifier"]),[]),hr=m.useMemo(()=>T?Gn:(Gn||[]).filter(U=>!wp(U==null?void 0:U.predicate,Mr)),[Gn,T,Mr]),Hr=m.useMemo(()=>IR(Gn,{groupEdges:ne}),[Gn,ne]),it=m.useMemo(()=>{if(T)return Hr;const U=[];for(const ae of Hr.edges){const Ne=(ae&&ae.data&&Array.isArray(ae.data.assertions)?ae.data.assertions:[]).filter(Be=>!wp(Be==null?void 0:Be.predicate,Mr));if(!Ne.length)continue;const ke=JR(Ne);U.push({...ae,label:ke,data:{...ae.data,assertions:Ne,predicateSummary:ke}})}return{nodes:Hr.nodes,edges:U}},[Hr,T,Mr]),rn=m.useMemo(()=>it.nodes.map(U=>U.id),[it.nodes]),gs=m.useMemo(()=>{const U=rn[0]||"",ae=rn[rn.length-1]||"";return`${rn.length}:${U}:${ae}`},[rn]),ci=m.useMemo(()=>{var ae;const U=new Map;for(const je of it.nodes)U.set(je.id,String(((ae=je.data)==null?void 0:ae.label)||je.id));return U},[it.nodes]),us=m.useMemo(()=>{var ae;const U=new Map;for(const je of it.nodes)U.set(je.id,String(((ae=je.data)==null?void 0:ae.kind)||""));return U},[it.nodes]),co=P.trim().toLowerCase(),uo=m.useMemo(()=>{var ae;if(!co)return new Set;const U=new Set;for(const je of it.nodes){const Ne=String(je.id||"").toLowerCase(),ke=String(((ae=je.data)==null?void 0:ae.label)||"").toLowerCase();(Ne.includes(co)||ke.includes(co))&&U.add(je.id)}return U},[it.nodes,co]),Sa=m.useCallback((U,ae)=>{const je={};for(const Ne of rn){const ke=U[Ne]||ae[Ne];je[Ne]=ke?{x:ke.x,y:ke.y}:{x:0,y:0}}return je},[rn]);m.useEffect(()=>{vn(U=>{const ae=Cu(it,{kind:Ue,seed:Pe}),je={};for(const Ne of rn){const ke=U[Ne]||ae[Ne];je[Ne]=ke?{x:ke.x,y:ke.y}:{x:0,y:0}}return je})},[it,Ue,Pe,rn,gs]),m.useEffect(()=>{if(!De.current)return;const U=j.current;if(!(!U||typeof U.fitView!="function")&&rn.length){De.current=!1;try{U.fitView({padding:.2,duration:0})}catch{try{U.fitView({padding:.2})}catch{}}}},[rn.length,gs,Mn]),m.useEffect(()=>{Je(!1),ct.current=null,ge.current=null,De.current=!1,pn.current=0,Ut.current=0,It.current=0;const U=hv(Ee);if(U&&Object.keys(U.positions||{}).length){if(_t(U.kind),et(U.seed),Mt(!0),Dn(U.saved_at||""),U.viewport){ge.current=U.viewport;const ke=j.current;if(ke&&typeof ke.setViewport=="function"){try{ke.setViewport(U.viewport,{duration:0})}catch{try{ke.setViewport(U.viewport)}catch{}}ge.current=null}}else De.current=!0;const Ne=Cu(it,{kind:U.kind,seed:U.seed});vn(Sa(U.positions,Ne));return}Mt(!1),Dn("");const ae=_g(Ee);et(ae);const je=Cu(it,{kind:Ue,seed:ae});vn(je),Ue==="force"&&it.nodes.length>0&&it.nodes.length<=320&&(ct.current=fm(it,{seed:ae,positions:je,...wf(Se)}),Je(!0))},[Ee]);const Fn=m.useMemo(()=>{const U=String(gn||"").trim(),ae=String(Hn||"").trim();return!U||!ae?null:OR(it,U,ae,{directed:z})},[it,gn,Hn,z]),mr=!!(Fn&&String(gn||"").trim()&&String(Hn||"").trim()),Rn=m.useMemo(()=>{const U=String(gn||"").trim(),ae=String(Hn||"").trim();if(!U||!ae)return null;const je=z,Ne=new Map,ke=(ot,gt)=>{const Ft=Ne.get(ot);Ft?Ft.push(gt):Ne.set(ot,[gt])};for(const ot of it.edges)ke(ot.source,ot.target),je||ke(ot.target,ot.source);const Be=new Set,ft=[];for(Be.add(U),ft.push(U);ft.length;){const ot=ft.shift(),gt=Ne.get(ot)||[];for(const Ft of gt)Be.has(Ft)||(Be.add(Ft),ft.push(Ft))}return{reachableFromStart:Be.size,endReachable:Be.has(ae),nodes:it.nodes.length,edges:it.edges.length,assertions:hr.length}},[z,it.edges,it.nodes.length,Hn,gn,hr.length]),_r=m.useMemo(()=>new Set((Fn==null?void 0:Fn.nodeIds)||[]),[Fn]),fo=m.useMemo(()=>new Set((Fn==null?void 0:Fn.edgeIds)||[]),[Fn]),[Xn,Js]=m.useState(""),[ds,Vr]=m.useState(""),ys=!!(String(Xn||"").trim()||String(ds||"").trim()),ka=m.useMemo(()=>{const U=new Set,ae=new Set,je=String(Xn||"").trim(),Ne=String(ds||"").trim();if(je){U.add(je);for(const ke of it.edges)(ke.source===je||ke.target===je)&&(ae.add(ke.id),U.add(ke.source),U.add(ke.target));return{nodes:U,edges:ae}}if(Ne){const ke=it.edges.find(Be=>Be.id===Ne);ke&&(ae.add(ke.id),U.add(ke.source),U.add(ke.target))}return{nodes:U,edges:ae}},[it.edges,ds,Xn]);m.useEffect(()=>{Js(""),Vr(""),Es(""),as("")},[A]);const[ho,on]=m.useState(!1);m.useEffect(()=>{on(!1)},[A]),m.useEffect(()=>{lt||(ct.current=null)},[lt]),m.useEffect(()=>{if(Ue!=="force")return;const U=ct.current;if(!U)return;const ae=wf(Se);U.options.springLength=ae.springLength,U.options.repulsionStrength=ae.repulsionStrength},[Ue,Se]),m.useEffect(()=>{Ue!=="force"&<&&Je(!1)},[Ue,lt]),m.useEffect(()=>{if(!lt||Ue!=="force"||it.nodes.length===0||typeof window>"u"||typeof window.requestAnimationFrame!="function")return;ct.current||(ct.current=fm(it,{seed:Pe,positions:On.current,...wf(Se)}));let U=0,ae=0,je=0;const Ne=it.nodes.length<=140?2:1,ke=1600,Be=.08,ft=ot=>{if(U=window.requestAnimationFrame(ft),ot-ae<33)return;ae=ot;const gt=ct.current;if(!gt){Je(!1);return}PR(gt,Ne),je+=Ne,vn(FR(gt)),(DR(gt)<=Be||je>=ke)&&Je(!1)};return U=window.requestAnimationFrame(ft),()=>{window.cancelAnimationFrame(U)}},[it,Ue,lt,Pe]);const El=m.useMemo(()=>it.nodes.map(U=>{var an;const ae=_r.has(U.id),je=uo.has(U.id),Ne=Xn===U.id,ke=ys&&ka.nodes.has(U.id),Be=vf((an=U.data)==null?void 0:an.kind),ft="rgba(34, 211, 238, 0.88)",ot=je?"0 0 0 1px rgba(34, 211, 238, 0.34), 0 0 16px rgba(34, 211, 238, 0.26), 0 0 44px rgba(34, 211, 238, 0.14)":"",gt=ae?"rgba(168, 85, 247, 0.9)":je?ft:Be.stroke,Ft=Ne?"0 0 0 2px rgba(255,255,255,0.20), 0 18px 46px rgba(0,0,0,0.55)":ke?"0 0 0 1px rgba(96, 165, 250, 0.28), 0 12px 34px rgba(0,0,0,0.45)":void 0,Kt=ot&&Ft?`${ot}, ${Ft}`:Ft||ot||void 0,vs=ae?"rgba(168, 85, 247, 0.10)":je?"rgba(34, 211, 238, 0.08)":Be.bg,Rt=mr?ae||Ne?1:.16:ys?ke||Ne?1:.1:1;return{...U,position:Mn[U.id]?{x:Mn[U.id].x,y:Mn[U.id].y}:U.position,style:{...U.style||{},border:`1px solid ${gt}`,borderRadius:10,background:vs,color:"rgba(255,255,255,0.92)",opacity:Rt,padding:8,fontSize:12,boxShadow:Kt,width:180,cursor:"pointer"}}}),[it.nodes,mr,uo,Mn,Xn,_r,ys,ka.nodes]),Ri=m.useMemo(()=>it.edges.map(U=>{const ae=fo.has(U.id),je=ds===U.id,Ne=ys&&ka.edges.has(U.id),ke=ae?"rgba(168, 85, 247, 0.9)":ys?Ne||je?"rgba(96, 165, 250, 0.55)":"rgba(255,255,255,0.14)":"rgba(255,255,255,0.18)",Be=ae?2.75:ys?Ne||je?2.25:1.25:1.5,ft=je?"drop-shadow(0 0 10px rgba(168, 85, 247, 0.25))":void 0,ot=ae?"rgba(168, 85, 247, 0.9)":mr?"rgba(255,255,255,0.10)":"rgba(255,255,255,0.28)",gt=mr?ae||je?1:.1:ys?Ne||je?1:.08:1,Ft=mr?ae||je?1:0:ys?Ne||je?1:0:1,Kt=mr?ae||je?String(U.label||""):"":String(U.label||"");return{...U,label:Kt,style:{...U.style||{},stroke:ke,strokeWidth:Be,filter:ft,opacity:gt},animated:!1,markerEnd:{type:Ff.ArrowClosed,color:ot,width:20,height:20},labelShowBg:!0,labelBgPadding:[6,3],labelBgBorderRadius:10,labelBgStyle:{fill:`rgba(0, 0, 0, ${.38*Ft})`,stroke:`rgba(255, 255, 255, ${.14*Ft})`,strokeWidth:1},labelStyle:{fill:`rgba(255, 255, 255, ${.92*Ft})`,fontSize:10,fontWeight:600,letterSpacing:.2,textTransform:"lowercase"}}}),[it.edges,mr,ds,fo,ys,ka.edges]),pr=m.useMemo(()=>{if(!ds)return[];const U=it.edges.find(je=>je.id===ds),ae=U&&U.data&&Array.isArray(U.data.assertions)?U.data.assertions:[];return Array.isArray(ae)?ae:[]},[it.edges,ds]),As=m.useMemo(()=>ds&&it.edges.find(U=>U.id===ds)||null,[it.edges,ds]),Na=m.useMemo(()=>{const U=String(Xn||"").trim();return U?Gn.filter(ae=>!ae||typeof ae!="object"||!(ae.subject===U||ae.object===U)?!1:T?!0:!wp(ae.predicate,Mr)):[]},[Gn,Xn,T,Mr]),Rr=m.useMemo(()=>ds?pr:Na,[pr,ds,Na]),ui=m.useMemo(()=>{const U=new Map;for(const ae of Rr){if(!ae||typeof ae!="object")continue;const je=ae.provenance&&typeof ae.provenance=="object"&&!Array.isArray(ae.provenance)?ae.provenance:null,Ne=je&&typeof je.span_id=="string"?je.span_id.trim():"",ke=je&&typeof je.writer_run_id=="string"?je.writer_run_id.trim():"",Be=typeof ae.owner_id=="string"?ae.owner_id.trim():"",ft=ke||Be;if(!ft||!Ne)continue;const ot=`${ft}|${Ne}`,gt=U.get(ot),Ft=typeof ae.observed_at=="string"?ae.observed_at.trim():"";gt?(gt.count+=1,Ft&&(!gt.last_observed_at||Ft>gt.last_observed_at)&&(gt.last_observed_at=Ft,gt.last_observed_at_fmt=xf(Ft),gt.assertion=ae)):U.set(ot,{span_run_id:ft,span_id:Ne,writer_run_id:ke,count:1,last_observed_at:Ft,last_observed_at_fmt:xf(Ft),assertion:ae})}return Array.from(U.values()).sort((ae,je)=>String(je.last_observed_at||"").localeCompare(String(ae.last_observed_at||"")))},[Rr]),Li=m.useMemo(()=>{const U=new Map;for(const ae of Rr){if(!ae||typeof ae!="object")continue;const je=ae.provenance&&typeof ae.provenance=="object"&&!Array.isArray(ae.provenance)?ae.provenance:null,Ne=je&&typeof je.span_id=="string"?je.span_id.trim():"",ke=je&&typeof je.writer_run_id=="string"?je.writer_run_id.trim():"";if(!ke||Ne)continue;const Be=U.get(ke),ft=typeof ae.observed_at=="string"?ae.observed_at.trim():"";Be?(Be.count+=1,ft&&(!Be.last_observed_at||ft>Be.last_observed_at)&&(Be.last_observed_at=ft,Be.last_observed_at_fmt=xf(ft),Be.assertion=ae)):U.set(ke,{run_id:ke,count:1,last_observed_at:ft,last_observed_at_fmt:xf(ft),assertion:ae})}return Array.from(U.values()).sort((ae,je)=>String(je.last_observed_at||"").localeCompare(String(ae.last_observed_at||"")))},[Rr]),Xs=m.useCallback(U=>{const ae=String(U.run_id||"").trim(),je=typeof U.span_id=="string"?String(U.span_id).trim():"";if(ae){if(k){try{k({run_id:ae,span_id:je||void 0,assertion:U.assertion})}catch{}return}if(x&&je)try{x({run_id:ae,span_id:je,assertion:U.assertion})}catch{}}},[x,k]),Ts=m.useCallback(async U=>{const ae=String(U??"");if(ae)try{await navigator.clipboard.writeText(ae)}catch{}},[]),Lr=m.useCallback(()=>{const U=j.current;if(!(!U||typeof U.fitView!="function")){if(Xn&&typeof U.getNode=="function"){const ae=U.getNode(Xn);if(ae){U.fitView({nodes:[ae],padding:.55,duration:350});return}}U.fitView({padding:.2,duration:350})}},[Xn]),Zs=m.useCallback(U=>{const ae=U.kind,je=Math.trunc(U.seed);Je(!1),ct.current=null,ge.current=null,_t(ae),et(je);const Ne=Cu(it,{kind:ae,seed:je});vn(Ne),ae==="force"&&(U.autoPlay??!0)&&it.nodes.length>0&&it.nodes.length<=320&&(ct.current=fm(it,{seed:je,positions:Ne,...wf(Se)}),Je(!0))},[it,Se]),Ii=m.useCallback(()=>{if(Ue==="force"){if(lt){Je(!1);return}ct.current=fm(it,{seed:Pe,positions:On.current,...wf(Se)}),Je(!0)}},[it,Ue,lt,Pe,Se]);m.useEffect(()=>()=>{typeof window>"u"||typeof window.cancelAnimationFrame=="function"&&un.current&&window.cancelAnimationFrame(un.current)},[]);const gr=m.useCallback(()=>{const U=j.current;if(!U||typeof U.getViewport!="function"||!rn.length)return null;const ae=tn.current;if(!ae)return null;const je=ae.getBoundingClientRect();if(!Number.isFinite(je.width)||!Number.isFinite(je.height)||je.width<64||je.height<64)return null;const Ne=U.getViewport(),ke=typeof(Ne==null?void 0:Ne.zoom)=="number"&&Number.isFinite(Ne.zoom)?Ne.zoom:null,Be=typeof(Ne==null?void 0:Ne.x)=="number"&&Number.isFinite(Ne.x)?Ne.x:null,ft=typeof(Ne==null?void 0:Ne.y)=="number"&&Number.isFinite(Ne.y)?Ne.y:null;if(ke===null||Be===null||ft===null||ke<=0)return null;const ot=140,gt=Math.min(rn.length,180),Ft=On.current;let Kt=0,vs=0;for(const Rt of rn){const an=Ft[Rt];if(!an||!Number.isFinite(an.x)||!Number.isFinite(an.y))continue;vs+=1;const Nn=[{x:an.x,y:an.y},{x:an.x+90,y:an.y+24}];for(const mn of Nn){const Zn=mn.x*ke+Be,er=mn.y*ke+ft;if(Zn>-ot&&Zn<je.width+ot&&er>-ot&&er<je.height+ot)return!1}if(Kt++,Kt>=gt)break}return vs?!0:null},[rn]),ws=m.useCallback(U=>{typeof window>"u"||typeof window.requestAnimationFrame!="function"||un.current||(un.current=window.requestAnimationFrame(()=>{un.current=0;const ae=gr();if(ae===null){if(It.current>=12)return;It.current+=1,window.setTimeout(()=>ws(`${U}:probe`),120);return}if(ae!==!0){It.current=0,Ut.current=0;return}It.current=0;const je=j.current;if(je&&typeof je.fitView=="function")try{je.fitView({padding:.2,duration:0})}catch{try{je.fitView({padding:.2})}catch{}}if(Ut.current+=1,Ut.current>=4&&pn.current<1){Ut.current=0,pn.current+=1,Dt(Ne=>Ne+1);return}Ut.current<8&&window.setTimeout(()=>ws(`${U}:retry`),220)}))},[gr]);m.useEffect(()=>{Ut.current=0,pn.current=0,It.current=0,ws("mount")},[A,ws]),m.useEffect(()=>{ws("graph change")},[gs,ws]),m.useEffect(()=>{const U=tn.current;if(!U||typeof window>"u"||typeof ResizeObserver!="function")return;const ae=new ResizeObserver(()=>ws("resize"));return ae.observe(U),()=>ae.disconnect()},[ws]);const Oi=m.useCallback(()=>{const U=new Date().toISOString(),ae={};for(const ft of rn){const ot=On.current[ft];ot&&typeof ot.x=="number"&&typeof ot.y=="number"&&(ae[ft]={x:ot.x,y:ot.y})}const je=j.current,Ne=je&&typeof je.toObject=="function"?je.toObject():null,ke=Ne&&Ne.viewport?Ne.viewport:je&&typeof je.getViewport=="function"?je.getViewport():null,Be=$0(ke,{minZoom:pg,maxZoom:gg,maxAbsTranslate:M0})??void 0;WR(Ee,{version:1,kind:Ue,seed:Pe,positions:ae,viewport:Be,saved_at:U}),Mt(!0),Dn(U),Je(!1)},[Ee,Ue,Pe,rn]),Uo=m.useCallback(()=>{const U=hv(Ee);if(!U)return;Je(!1),ct.current=null,_t(U.kind),et(U.seed),Mt(!0),Dn(U.saved_at||""),ge.current=U.viewport||null,De.current=!U.viewport;const ae=Cu(it,{kind:U.kind,seed:U.seed});if(vn(Sa(U.positions,ae)),U.viewport){const je=j.current;if(je&&typeof je.setViewport=="function"){try{je.setViewport(U.viewport,{duration:0})}catch{try{je.setViewport(U.viewport)}catch{}}ge.current=null}}},[Sa,it,Ee]),$l=m.useCallback(()=>{qR(Ee),Mt(!1),Dn("")},[Ee]),Qs=m.useCallback(U=>{if(!Array.isArray(U)||U.length===0)return;let ae=!1;vn(je=>{let Ne=je,ke=!1;for(const Be of U){const ft=Be&&typeof Be=="object"&&"id"in Be&&typeof Be.id=="string"?String(Be.id):"",ot=(Be==null?void 0:Be.type)==="position"?Be==null?void 0:Be.position:null;ft&&ot&&typeof ot.x=="number"&&typeof ot.y=="number"&&(ke||(Ne={...je},ke=!0),Ne[ft]={x:ot.x,y:ot.y},Be!=null&&Be.dragging&&(ae=!0))}return ke?Ne:je}),ae&<&&Je(!1)},[lt]),Wo=m.useMemo(()=>{const U=new Map;for(const ae of it.edges)U.set(ae.id,ae);return U},[it.edges]),Gr=m.useMemo(()=>{var Ne;if(!Fn)return[];const U=Fn.nodeIds||[],ae=Fn.edgeIds||[],je=[];for(let ke=0;ke<Math.min(U.length-1,ae.length);ke++){const Be=U[ke],ft=U[ke+1],ot=ae[ke],gt=Wo.get(ot),Ft=String(((Ne=gt==null?void 0:gt.data)==null?void 0:Ne.predicateSummary)||(gt==null?void 0:gt.label)||"").trim(),Kt=gt&>.source===Be&>.target===ft?"forward":gt&>.source===ft&>.target===Be?"reverse":"unknown";je.push({from:Be,to:ft,edgeId:ot,predicate:Ft,dir:Kt})}return je},[Wo,Fn]),_c=m.useCallback(async()=>{if(y){ie(""),N(""),Z(!0);try{const U=HR(Bt),ae=yp(pt,{allowZero:!0,allowNegativeOne:!0}),je=yp(Ce,{allowZero:!0}),Ne=await y({scope:Vn,owner_id:void 0,recall_level:be,query_text:qe||void 0,subject:ut||void 0,predicate:kt||void 0,object:dt||void 0,min_score:U,limit:ae,max_input_tokens:je,model:Et||void 0});M(Ne),X("live query"),L==="replace"&&w&&Ne&&Array.isArray(Ne.items)&&w(Ne.items,{kind:"live query",result:Ne})}catch(U){const ae=U instanceof Error?U.message:String(U);ie(ae||"Query failed")}finally{Z(!1)}}},[pt,Ce,Bt,Et,dt,w,y,kt,L,qe,be,Vn,ut]),yr=m.useCallback(async()=>{if(!y)return;const U=String(gn||"").trim(),ae=String(Hn||"").trim();if(!U||!ae)return;const je=Math.max(200,yp(pt)??80),Ne=60;N(""),ie(""),F(!0);try{const ke=[],Be=new Set,ft=Rt=>{if(!Rt||typeof Rt!="object"||typeof Rt.subject!="string"||typeof Rt.predicate!="string"||typeof Rt.object!="string")return;const an=`${Rt.subject}|${Rt.predicate}|${Rt.object}|${String(Rt.observed_at||"")}|${String(Rt.scope||"")}|${String(Rt.owner_id||"")}`;Be.has(an)||(Be.add(an),ke.push(Rt))};for(const Rt of Gn)ft(Rt);const ot=z,gt=new Set,Ft=[U],Kt=new Set([U]),vs=async Rt=>{const an=await y({scope:Vn,recall_level:be,min_score:0,limit:je,subject:Rt,query_text:void 0,max_input_tokens:0,model:void 0});if(an&&Array.isArray(an.items)){for(const Nn of an.items)if(ft(Nn),typeof Nn.subject=="string"&&Nn.subject.trim()===Rt&&typeof Nn.object=="string"){const mn=Nn.object.trim();mn&&!Kt.has(mn)&&(Kt.add(mn),Ft.push(mn))}}if(!ot){const Nn=await y({scope:Vn,recall_level:be,min_score:0,limit:je,object:Rt,query_text:void 0,max_input_tokens:0,model:void 0});if(Nn&&Array.isArray(Nn.items)){for(const mn of Nn.items)if(ft(mn),typeof mn.object=="string"&&mn.object.trim()===Rt&&typeof mn.subject=="string"){const Zn=mn.subject.trim();Zn&&!Kt.has(Zn)&&(Kt.add(Zn),Ft.push(Zn))}}}};for(;Ft.length&>.size<Ne&&!Kt.has(ae);){const Rt=Ft.shift();!Rt||gt.has(Rt)||(gt.add(Rt),await vs(Rt))}M({ok:!0,count:ke.length,items:ke,active_memory_text:hn,raw:{expanded_for_path:!0,expanded_nodes:gt.size,discovered_nodes:Kt.size,merged:ke.length,directed:ot}}),X("expanded neighborhood"),L==="replace"&&w&&w(ke,{kind:"expanded neighborhood",result:{ok:!0,count:ke.length,items:ke,active_memory_text:hn,raw:{expanded_for_path:!0,expanded_nodes:gt.size,discovered_nodes:Kt.size,merged:ke.length,directed:ot}}})}catch(ke){const Be=ke instanceof Error?ke.message:String(ke);N(Be||"Expand neighborhood failed")}finally{F(!1)}},[z,hn,Gn,pt,w,y,Hn,gn,L,be,Vn]),mo=m.useCallback(()=>{M(null),X(null),ie(""),Z(!1),N(""),F(!1),Es(""),as(""),Js(""),Vr("")},[]),Fs="Search KG",qo=it.nodes.length,Ho=it.edges.length,Vo=hr.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:Ue,onChange:U=>_t(yg(U.target.value,Ue)),disabled:!rn.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)"})]}),Ue==="force"?s.jsxs("label",{className:"amx-graphbar-spread",children:[s.jsx("span",{className:"amx-graphbar-title",children:"spread"}),s.jsx("input",{type:"range",min:"0.7",max:"2.2",step:"0.1",value:Se,onChange:U=>Ie(T0(Number(U.target.value),.7,2.2,1))}),s.jsxs("span",{className:"amx-small",children:[Se.toFixed(1),"×"]})]}):null,s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>Zs({kind:Ue,seed:Pe}),disabled:!rn.length,children:"Apply"}),s.jsx("button",{type:"button",className:"amx-btn",onClick:Ii,disabled:!rn.length||Ue!=="force",children:lt?"Pause simulation":"Play simulation"})]})}),s.jsxs("div",{className:"amx-graph","aria-label":"Knowledge graph",ref:tn,children:[s.jsx(ty,{children:s.jsxs(S0,{nodes:El,edges:Ri,defaultViewport:{x:0,y:0,zoom:1},minZoom:pg,maxZoom:gg,onInit:U=>{j.current=U;const ae=ge.current;if(ae&&typeof U.setViewport=="function")try{U.setViewport(ae,{duration:0})}catch{try{U.setViewport(ae)}catch{}}if(De.current&&typeof U.fitView=="function")try{U.fitView({padding:.2,duration:0})}catch{try{U.fitView({padding:.2})}catch{}}ge.current=null,De.current=!1,ws("init")},nodesDraggable:!0,nodesConnectable:!1,elementsSelectable:!0,onNodesChange:Qs,onNodeClick:(U,ae)=>{Vr(""),Js(ae.id)},onEdgeClick:(U,ae)=>{Js(""),Vr(ae.id)},onPaneClick:()=>{Js(""),Vr("")},children:[s.jsx(SR,{className:"amx-flow-controls",children:s.jsx(Tu,{type:"button",className:`amx-control-legend ${_e?"amx-control-legend-active":""}`,onClick:()=>we(U=>!U),title:_e?"Hide node color legend":"Show node color legend","aria-label":_e?"Hide node color legend":"Show node color legend",children:s.jsx(BR,{})})}),s.jsx(Of,{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:()=>he(U=>!U),title:oe?"Hide minimap preview":"Show minimap preview","aria-label":oe?"Hide minimap preview":"Show minimap preview",children:oe?"minimap on":"minimap off"})})}),oe?s.jsx(gR,{position:"bottom-right",pannable:!0,zoomable:!0,maskColor:"rgba(0,0,0,0.45)",style:{background:"rgba(12, 18, 34, 0.88)",border:"1px solid rgba(255,255,255,0.12)",borderRadius:10,width:J?120:160,height:J?80:110,marginBottom:56},nodeColor:U=>{var ae;return vf((ae=U.data)==null?void 0:ae.kind).minimap}}):null,_e?s.jsxs(Of,{position:"bottom-left",className:"amx-legend-panel",children:[s.jsx("div",{className:"amx-legend-title",children:"node colors"}),s.jsx("div",{className:"amx-legend",children:[{k:"person",label:"person"},{k:"org",label:"org"},{k:"concept",label:"concept"},{k:"claim",label:"claim"},{k:"event",label:"event"},{k:"doc",label:"doc"},{k:"vocab",label:"vocab"}].map(({k:U,label:ae})=>s.jsx("span",{className:"amx-legend-item",style:{borderColor:vf(U).stroke},children:ae},U))})]}):null,s.jsx(AR,{gap:20,size:1,color:"rgba(255,255,255,0.06)"})]})},Ye),s.jsxs("details",{className:"amx-panel amx-controls",children:[s.jsxs("summary",{children:[s.jsx("span",{className:"amx-controls-title",children:Fs}),s.jsxs("span",{className:"amx-small",children:[Vo," assertions · ",qo," nodes · ",Ho," edges"]})]}),s.jsxs("div",{className:"amx-toolbar",style:{marginTop:10},children:[s.jsxs("div",{className:"amx-toolbar-grid",children:[s.jsxs("label",{children:["search / highlight",s.jsx("input",{value:P,onChange:U=>D(U.target.value),placeholder:"filter nodes by id/label"})]}),s.jsxs("label",{children:["group edges",s.jsxs("select",{value:String(ne),onChange:U=>B(U.target.value==="true"),children:[s.jsx("option",{value:"true",children:"group (subject→object)"}),s.jsx("option",{value:"false",children:"no grouping"})]})]}),s.jsxs("label",{children:["view",s.jsxs("select",{value:String(T),onChange:U=>Q(U.target.value==="true"),children:[s.jsx("option",{value:"true",children:"all assertions"}),s.jsx("option",{value:"false",children:"hide rdf:type / labels"})]})]}),s.jsxs("label",{children:["path mode",s.jsxs("select",{value:String(z),onChange:U=>G(U.target.value==="true"),children:[s.jsx("option",{value:"false",children:"undirected"}),s.jsx("option",{value:"true",children:"directed"})]})]})]}),s.jsxs("details",{className:"amx-details",children:[s.jsx("summary",{children:"layout"}),s.jsxs("div",{className:"amx-toolbar-grid",style:{marginTop:10},children:[s.jsxs("label",{children:["layout",s.jsxs("select",{value:Ue,onChange:U=>_t(yg(U.target.value,Ue)),children:[s.jsx("option",{value:"grid",children:"grid (deterministic)"}),s.jsx("option",{value:"radial",children:"radial (bfs)"}),s.jsx("option",{value:"circle",children:"circle"}),s.jsx("option",{value:"force",children:"force (simulation)"})]})]}),s.jsxs("label",{children:["seed",s.jsx("input",{type:"number",step:"1",value:Pe,onChange:U=>et(Math.trunc(Number(U.target.value||0)||0))})]})]}),s.jsxs("div",{className:"amx-actions",style:{marginTop:10},children:[s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>Zs({kind:Ue,seed:Pe}),disabled:!rn.length,children:"Apply layout"}),Ue==="force"?s.jsx("button",{type:"button",className:"amx-btn",onClick:Ii,disabled:!rn.length,children:lt?"Pause simulation":"Play simulation"}):null,s.jsx("button",{type:"button",className:"amx-btn",onClick:Oi,disabled:!rn.length,children:"Save layout"}),Wn?s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"amx-btn",onClick:Uo,children:"Load saved"}),s.jsx("button",{type:"button",className:"amx-btn",onClick:$l,children:"Clear saved"})]}):null]}),s.jsxs("div",{className:"amx-small",style:{marginTop:10,opacity:.9},children:["Drag nodes to adjust manually; use ",s.jsx("span",{className:"amx-mono",children:"Save layout"})," for a stable, replayable view.",Wn?s.jsxs("span",{children:[" ","(saved",wn?`: ${wn}`:"",")"]}):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:gn,onChange:U=>Es(U.target.value),children:[s.jsx("option",{value:"",children:"(none)"}),rn.map(U=>s.jsx("option",{value:U,children:(()=>{const ae=ci.get(U)||U;return ae===U?ae:`${ae} (${U})`})()},U))]})]}),s.jsxs("label",{children:["path end",s.jsxs("select",{value:Hn,onChange:U=>as(U.target.value),children:[s.jsx("option",{value:"",children:"(none)"}),rn.map(U=>s.jsx("option",{value:U,children:(()=>{const ae=ci.get(U)||U;return ae===U?ae:`${ae} (${U})`})()},U))]})]})]}),Fn?s.jsx("div",{className:"amx-small",style:{marginTop:10},children:Gr.map((U,ae)=>{const je=ci.get(U.from)||U.from,Ne=ci.get(U.to)||U.to,ke=U.dir==="reverse"?" ← ":" → ",Be=U.predicate?` (${U.predicate})`:"";return s.jsxs("div",{children:[ae===0?s.jsx("span",{children:je}):null,ke,s.jsxs("span",{children:[Ne,Be]})]},`${U.edgeId}:${ae}`)})}):gn&&Hn?s.jsxs("div",{className:"amx-small",style:{marginTop:10,opacity:.9},children:["No path found in the current subgraph (",(Rn==null?void 0:Rn.assertions)??Vo," assertions · ",(Rn==null?void 0:Rn.nodes)??it.nodes.length," nodes ·"," ",(Rn==null?void 0:Rn.edges)??it.edges.length," edges). Start reaches ",(Rn==null?void 0:Rn.reachableFromStart)??0," nodes.",y?s.jsx("div",{style:{marginTop:10},children:s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>void yr(),disabled:ue,children:ue?"Expanding…":"Expand neighborhood"})}):null]}):s.jsx("div",{className:"amx-small",style:{marginTop:10},children:"(no path)"})]}),s.jsxs("details",{className:"amx-details",children:[s.jsx("summary",{children:"query"}),s.jsxs("div",{className:"amx-toolbar-grid",style:{marginTop:10},children:[s.jsxs("label",{children:["query_text (semantic)",s.jsx("input",{value:qe,onChange:U=>st(U.target.value),placeholder:"e.g. emotion chip"})]}),s.jsxs("label",{children:["subject (exact)",s.jsx("input",{value:ut,onChange:U=>Tt(U.target.value),placeholder:"e.g. ex:person-data"})]}),s.jsxs("label",{children:["predicate (exact)",s.jsx("input",{value:kt,onChange:U=>Gt(U.target.value),placeholder:"e.g. schema:about"})]}),s.jsxs("label",{children:["object (exact)",s.jsx("input",{value:dt,onChange:U=>Xt(U.target.value),placeholder:"e.g. ex:concept-emotion-chip"})]}),s.jsxs("label",{children:["min_score",s.jsx("input",{type:"number",step:"any",value:Bt,onChange:U=>Ct(U.target.value),placeholder:"(auto)"})]}),s.jsxs("label",{children:["limit",s.jsx("input",{type:"number",min:"-1",step:"1",value:pt,onChange:U=>Ot(U.target.value),placeholder:"0/-1 = unlimited (if supported)"})]})]})]}),s.jsxs("details",{className:"amx-details",children:[s.jsx("summary",{children:"advanced"}),s.jsxs("div",{className:"amx-toolbar-grid",style:{marginTop:10},children:[s.jsxs("label",{children:["scope",s.jsxs("select",{value:Vn,onChange:U=>ce(fv(U.target.value,Vn)),children:[s.jsx("option",{value:"run",children:"run"}),s.jsx("option",{value:"session",children:"session"}),s.jsx("option",{value:"global",children:"global"}),s.jsx("option",{value:"all",children:"all"})]})]}),s.jsxs("label",{children:["recall level",s.jsxs("select",{value:be,onChange:U=>Ke(U.target.value||"standard"),children:[s.jsx("option",{value:"urgent",children:"urgent"}),s.jsx("option",{value:"standard",children:"standard"}),s.jsx("option",{value:"deep",children:"deep"})]})]}),s.jsxs("label",{children:["max_input_tokens",s.jsx("input",{type:"number",min:"0",step:"1",value:Ce,onChange:U=>Vt(U.target.value),placeholder:"(auto)"})]}),s.jsxs("label",{children:["model (budgeting)",s.jsx("input",{value:Et,onChange:U=>ln(U.target.value),placeholder:"qwen/qwen3-next-80b"})]})]})]}),s.jsxs("div",{className:"amx-actions",children:[s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>void _c(),disabled:!y||Y,children:Y?"Querying…":"Query store"}),s.jsx("button",{type:"button",className:"amx-btn",onClick:mo,disabled:!O&&!re&&!Y,children:"Reset to step output"}),O?s.jsxs("span",{className:"amx-small",children:["showing: ",H||"live query"]}):s.jsx("span",{className:"amx-small",children:"showing: step output"}),re?s.jsx("span",{className:"amx-small",style:{color:"var(--error, rgba(255, 80, 80, 0.95))"},children:re}):null,C?s.jsx("span",{className:"amx-small",style:{color:"var(--error, rgba(255, 80, 80, 0.95))"},children:C}):null]})]})]})]})]}),s.jsxs("div",{className:"amx-right",children:[s.jsxs("div",{className:"amx-panel",children:[s.jsx("h3",{children:"Details"}),s.jsx("div",{className:"amx-small",style:{marginBottom:8},children:"Derived from `memory_kg_query` packetization (max_input_tokens); safe to inject into an LLM system prompt."}),(()=>{const U=VR(lo);return U?s.jsx("div",{className:"amx-small",style:{marginBottom:8,opacity:.9},children:U}):null})(),(()=>{const U=Mi;if(!U)return null;const ae=typeof U=="string"?U:Array.isArray(U)?U.map(je=>String(je)).join(" · "):JSON.stringify(U);return!ae||!ae.trim()?null:s.jsx("div",{className:"amx-small",style:{marginBottom:8,color:"var(--warning, rgba(255, 180, 90, 0.95))"},children:ae})})(),s.jsx("div",{className:"amx-small",style:{marginBottom:8,opacity:.9},children:(()=>{const U=(O==null?void 0:O.packets_version)??Ks,ae=(O==null?void 0:O.packed_count)??$s,je=(O==null?void 0:O.dropped)??fr,Ne=(O==null?void 0:O.estimated_tokens)??Ys,ke=[];return typeof U=="number"&&ke.push(`packets_v${U}`),typeof ae=="number"&&ke.push(`packed=${ae}`),typeof je=="number"&&ke.push(`dropped=${je}`),typeof Ne=="number"&&ke.push(`est_tokens=${Ne}`),ke.length?ke.join(" · "):"No packetization stats (set max_input_tokens > 0)."})()}),s.jsx("div",{className:"amx-active-memory",children:KR(hn||"(empty)",P)}),(()=>{const U=O!=null&&O.packets&&Array.isArray(O.packets)?O.packets:cs;return!Array.isArray(U)||U.length===0?null:s.jsxs("div",{style:{marginTop:10},children:[s.jsxs("button",{type:"button",className:"amx-btn",onClick:()=>on(ae=>!ae),children:[ho?"Hide":"Show"," packets (",U.length,")"]}),ho?s.jsx("div",{className:"amx-list",style:{marginTop:10},children:U.slice(0,120).map((ae,je)=>{const Ne=ae&&typeof ae=="object"&&!Array.isArray(ae)?ae:null,ke=Ne&&typeof Ne.statement=="string"?Ne.statement:typeof ae=="string"?ae:"",Be=Ne&&(typeof Ne.retrieval_score=="number"||typeof Ne.retrieval_score=="string")?Ne.retrieval_score:null,ft=Ne&&typeof Ne.observed_at=="string"?Ne.observed_at:null;return s.jsxs("div",{className:"amx-item",children:[s.jsx("div",{className:"amx-mono",children:ke||"(packet)"}),ft||Be!==null?s.jsxs("div",{className:"amx-small",children:[ft?`[${ft}]`:null,ft&&Be!==null?" ":null,Be!==null?`score:${Be}`:null]}):null]},je)})}):null]})})(),s.jsx("div",{style:{marginTop:14,marginBottom:12,borderTop:"1px solid var(--ui-border-1, rgba(255,255,255,0.08))"}}),s.jsx("div",{className:"amx-small",style:{marginBottom:8,fontWeight:700,opacity:.9},children:"Inspect"}),s.jsx("div",{className:"amx-small",style:{marginBottom:8},children:"Click a node or edge to inspect its assertions."}),Xn?s.jsxs("div",{className:"amx-item",style:{marginBottom:10,display:"flex",justifyContent:"space-between",gap:10,alignItems:"center"},children:[s.jsxs("div",{style:{minWidth:0},children:[s.jsx("div",{className:"amx-mono",style:{fontSize:11,opacity:.95},children:ci.get(Xn)||Xn}),s.jsxs("div",{className:"amx-small",children:["kind=",us.get(Xn)||"entity"," · id=",Xn]})]}),s.jsxs("div",{className:"amx-actions",children:[s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>void Ts(Xn),children:"Copy id"}),s.jsx("button",{type:"button",className:"amx-btn",onClick:Lr,children:"Focus"})]})]}):As&&As.source&&As.target?s.jsxs("div",{className:"amx-item",style:{marginBottom:10,display:"flex",justifyContent:"space-between",gap:10,alignItems:"center"},children:[s.jsxs("div",{style:{minWidth:0},children:[s.jsxs("div",{className:"amx-mono",style:{fontSize:11,opacity:.95},children:[As.source," —",String(As.label||((_o=As.data)==null?void 0:_o.predicateSummary)||"").trim()||"?","→ ",As.target]}),s.jsxs("div",{className:"amx-small",children:["edge_id=",As.id]})]}),s.jsxs("div",{className:"amx-actions",children:[s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>void Ts(As.id),children:"Copy id"}),s.jsx("button",{type:"button",className:"amx-btn",onClick:Lr,children:"Fit"})]})]}):s.jsx("div",{className:"amx-small",style:{marginBottom:10,opacity:.9},children:"(no selection)"}),s.jsx("div",{className:"amx-list",children:Rr.slice(0,80).map((U,ae)=>{const je=String(U.subject||"").trim(),Ne=String(U.predicate||"").trim(),ke=String(U.object||"").trim(),Be=ci.get(je)||je,ft=ci.get(ke)||ke,ot=us.get(je)||"entity",gt=us.get(ke)||"entity",Ft=vf(ot),Kt=vf(gt),vs=xf(U.observed_at),Rt=GR(U),an=U.provenance&&typeof U.provenance=="object"&&!Array.isArray(U.provenance)?U.provenance:null,Nn=an&&typeof an.span_id=="string"?an.span_id.trim():"",mn=an&&typeof an.writer_run_id=="string"?an.writer_run_id.trim():"",Zn=typeof U.owner_id=="string"?U.owner_id.trim():"",er=mn||Zn,Kr=!!((k||x)&&Nn&&er),Pi=!!(k&&mn&&!Nn),Ca=Kr||Pi;return s.jsxs("div",{className:"amx-item amx-triple-card",children:[s.jsxs("div",{className:"amx-triple-row",children:[s.jsx("button",{type:"button",className:"amx-term",style:{borderColor:Ft.stroke,background:Ft.bg},title:je,onClick:()=>{je&&(Vr(""),Js(je))},children:Be||je||"(subject)"}),s.jsx("span",{className:"amx-arrow",children:"—"}),s.jsx("span",{className:"amx-predicate",title:Ne,children:R0(Ne)||"(predicate)"}),s.jsx("span",{className:"amx-arrow",children:"→"}),s.jsx("button",{type:"button",className:"amx-term",style:{borderColor:Kt.stroke,background:Kt.bg},title:ke,onClick:()=>{ke&&(Vr(""),Js(ke))},children:ft||ke||"(object)"})]}),s.jsxs("div",{className:"amx-triple-meta",children:[vs?s.jsxs("span",{className:"amx-small",title:String(U.observed_at||""),children:["[",vs,"]"]}):null,Rt?s.jsx("span",{className:"amx-small",children:Rt}):null]}),Nn||mn?s.jsxs("div",{className:"amx-triple-actions",children:[Nn?s.jsxs("span",{className:"amx-small",children:["span:",Nn]}):null,mn?s.jsxs("span",{className:"amx-small",children:["run:",mn]}):null,Ca?s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>{if(Kr&&Nn&&er){Xs({run_id:er,span_id:Nn,assertion:U});return}Pi&&mn&&Xs({run_id:mn,assertion:U})},children:"Open transcript"}):null]}):null]},ae)})})]}),s.jsxs("div",{className:"amx-panel",children:[s.jsx("h3",{children:"Transcript"}),s.jsx("div",{className:"amx-small",style:{marginBottom:8},children:"Pivot from a triple to its provenance transcript (span/note artifact, or run input fallback)."}),ui.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:ui.slice(0,60).map(U=>s.jsxs("div",{className:"amx-item",style:{display:"flex",justifyContent:"space-between",gap:10,alignItems:"center"},children:[s.jsxs("div",{style:{minWidth:0},children:[s.jsxs("div",{className:"amx-mono",style:{fontSize:11,opacity:.95},children:["span:",U.span_id]}),s.jsxs("div",{className:"amx-small",children:["run_id=",U.span_run_id," · assertions=",U.count,U.last_observed_at_fmt?` · last=[${U.last_observed_at_fmt}]`:""]})]}),x||k?s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>Xs({run_id:U.span_run_id,span_id:U.span_id,assertion:U.assertion}),children:"Open transcript"}):null]},`${U.span_run_id}|${U.span_id}`))})]}):null,k&&Li.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:Li.slice(0,40).map(U=>s.jsxs("div",{className:"amx-item",style:{display:"flex",justifyContent:"space-between",gap:10,alignItems:"center"},children:[s.jsxs("div",{style:{minWidth:0},children:[s.jsxs("div",{className:"amx-mono",style:{fontSize:11,opacity:.95},children:["run:",U.run_id]}),s.jsxs("div",{className:"amx-small",children:["assertions=",U.count,U.last_observed_at_fmt?` · last=[${U.last_observed_at_fmt}]`:""]})]}),s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>Xs({run_id:U.run_id,assertion:U.assertion}),children:"Open transcript"})]},U.run_id))})]}):null,!ui.length&&!(k&&Li.length)?s.jsx("div",{className:"amx-small",children:"(no provenance)"}):null]})]})]})})}function bl({open:e,title:t,children:n,actions:r,variant:o="default",onClose:l}){const u=m.useId();if(m.useEffect(()=>{if(!e)return;const f=_=>{_.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 vp(e,t="session"){const n=String(e||"").trim().toLowerCase();return n==="run"||n==="session"||n==="global"||n==="all"?n:t}function gl(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 tc(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 ZR(e){const t=String(e??"").trim();if(!t)return"";if(/^\d{4}\/\d{2}\/\d{2} \d{2}:\d{2}$/.test(t))return t;const n=gl(t);return n!==null?tc(n):t}function sy(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 L0(e){return String(e??"").replace(/[*_`~]/g,"")}function hm(e,t){const n=!!(t!=null&&t.strip_punct),r=sy(e);let o=L0(r).replace(/\s+/g," ").trim().toLowerCase();return n&&(o=o.replace(/[^\p{L}\p{N}\s]+/gu,"").replace(/\s+/g," ").trim()),o}function mm(e,t){const n=String(t??"").trim();if(!n)return!1;const r=hm(n,{strip_punct:!1});if(!r)return!1;if(hm(String(e??""),{strip_punct:!1}).includes(r))return!0;const l=hm(n,{strip_punct:!0});return l?hm(String(e??""),{strip_punct:!0}).includes(l):!1}function mv(e){const t=sy(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(L0(t)),n}function QR(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 _=()=>{if(!u)return;const w=c.join(`
|
|
138
|
-
`).trim();w&&l.push({role:u,lines:[w]}),u=null,c=[]};for(const w of n){const x=r?null:w.match(/^\s*created_at\s*=\s*(.+)\s*$/i);if(x&&x[1]){r=x[1].trim();continue}const k=w.match(/^\s*(USER|ASSISTANT|SYSTEM)\s*:\s*(.*)$/i);if(k){f=!0,_();const j=String(k[1]||"").trim().toLowerCase();u=j==="user"?"user":j==="assistant"?"assistant":"system";const E=String(k[2]??"");c=E?[E]:[];continue}u?c.push(w):o.push(w)}if(_(),!f||!l.length)return null;const p=o.join(`
|
|
139
|
-
`).trim(),y={messages:[]};r&&(y.created_at=r),p&&y.messages.push({role:"system",content:p});for(const w of l)y.messages.push({role:w.role,content:w.lines.join(`
|
|
140
|
-
`)});return y.messages.length?y:null}function _v(e,t){const n=String(e||""),r=String(t||"");return r>n?r:n}function pv(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 eL(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 tL({gateway:e,selected_run_id:t,selected_session_id:n}){const[r,o]=m.useState(String(t||"").trim()),[l,u]=m.useState(String(n||"").trim()),[c,f]=m.useState("all"),_=c==="all",[p,y]=m.useState(!0),[w,x]=m.useState(750),[k,j]=m.useState(5e3),[E,A]=m.useState([]),[L,O]=m.useState(void 0),[M,H]=m.useState(""),[X,Y]=m.useState(!1),[Z,re]=m.useState([]),[ie,ue]=m.useState(!1),[F,C]=m.useState(!1),[N,P]=m.useState(""),[D,ne]=m.useState(""),[B,z]=m.useState(""),[G,T]=m.useState(""),[Q,K]=m.useState("artifact"),[J,oe]=m.useState(null),[he,_e]=m.useState(""),[we,Ee]=m.useState(null),ze=m.useRef(!1),Ue=m.useMemo(()=>{const ce=we,be=ce!=null&&ce.attributes&&typeof ce.attributes=="object"&&!Array.isArray(ce.attributes)?ce.attributes:null;return(be&&typeof be.evidence_quote=="string"?String(be.evidence_quote):"").trim()},[we]),_t=m.useMemo(()=>{const ce=J,be=ce&&typeof ce=="object"&&!Array.isArray(ce)?ce:null,Ke=be&&typeof be.note=="string"?String(be.note):"";return sy(Ke).trim()},[J]),Pe=m.useMemo(()=>{const ce=J&&typeof J=="object"&&!Array.isArray(J)?J:null,be=ce&&Array.isArray(ce.messages)?ce.messages:null;return Array.isArray(be)?be:null},[J]),et=m.useMemo(()=>{const ce=_t,be=Ue;return!ce||!be?!1:mm(ce,be)},[Ue,_t]),lt=m.useMemo(()=>{const ce=Pe,be=Ue;if(!ce||!be)return[];const Ke=[];for(let qe=0;qe<Math.min(ce.length,500);qe++){const st=ce[qe],ut=(st==null?void 0:st.content)==null?"":String(st.content);mm(ut,be)&&Ke.push(qe)}return Ke},[Ue,Pe]),Je=m.useMemo(()=>new Set(lt),[lt]),Se=lt.length?lt[0]:null,Ie=m.useCallback(ce=>{const be=document.getElementById(`source_msg_${ce}`);be&&typeof be.scrollIntoView=="function"&&be.scrollIntoView({block:"center",behavior:"smooth"})},[]),ct=m.useCallback(()=>{const ce=document.getElementById("source_note_hit_0")||document.getElementById("source_note_msg_hit_0");ce&&typeof ce.scrollIntoView=="function"&&ce.scrollIntoView({block:"center",behavior:"smooth"})},[]);m.useEffect(()=>{if(ie&&!(F||N)&&!ze.current){if(Se!==null){ze.current=!0,window.setTimeout(()=>Ie(Se),0);return}if(et){ze.current=!0,window.setTimeout(()=>ct(),0);return}}},[Ie,ct,N,Se,F,et,ie]);const ge=m.useRef(new Set),De=m.useRef(""),Ye=m.useRef(null),Dt=m.useRef(null);m.useEffect(()=>{o(String(t||"").trim())},[t]),m.useEffect(()=>{u(String(n||"").trim())},[n]);const tn=m.useMemo(()=>{const ce=String(r||"").trim(),be=String(l||"").trim();return`mindmap:${c}:${ce}:${be}`},[r,l,c]),pn=m.useMemo(()=>{let ce=null,be=null;for(const Ke of E){const qe=gl(Ke==null?void 0:Ke.observed_at);qe!==null&&(ce=ce===null?qe:Math.min(ce,qe),be=be===null?qe:Math.max(be,qe))}return{min_ms:ce,max_ms:be}},[E]),Ut=1e3,It=m.useMemo(()=>{const ce=pn.min_ms,be=pn.max_ms;if(typeof ce!="number"||typeof be!="number"||!Number.isFinite(ce)||!Number.isFinite(be))return null;if(be<=ce)return{min_ms:ce,max_ms:ce,real_max_ms:be};const Ke=ce+Math.ceil((be-ce)/Ut)*Ut;return{min_ms:ce,max_ms:Ke,real_max_ms:be}},[pn.max_ms,pn.min_ms]),[un,Wn]=m.useState(!0),[Mt,wn]=m.useState(null);m.useEffect(()=>{un&&It&&wn(It.max_ms)},[un,It]);const Dn=m.useMemo(()=>{const ce=typeof Mt=="number"?Mt:null;return ce===null?E:E.filter(be=>{const Ke=gl(be==null?void 0:be.observed_at);return Ke===null?!0:Ke<=ce})},[E,Mt]),Mn=m.useCallback((ce,be)=>{const Ke=Array.isArray(ce)?ce:[],qe=String(De.current||"").trim(),st=new Set,ut=[];let Tt="";for(const kt of Ke){if(!kt||typeof kt!="object"||typeof kt.subject!="string"||typeof kt.predicate!="string"||typeof kt.object!="string")continue;const Gt=pv(kt);if(st.has(Gt))continue;st.add(Gt),ut.push(kt);const dt=String(kt.observed_at||"").trim();dt&&(Tt=_v(Tt,dt))}A(ut),O(be==null?void 0:be.warnings),ge.current=st,De.current=Tt||qe},[]),vn=m.useCallback(async ce=>{const be=vp(ce.scope,"session"),Ke=String(ce.subject||"").trim(),qe=String(ce.predicate||"").trim(),st=String(ce.object||"").trim(),ut=String(ce.since||"").trim(),Tt=String(ce.until||"").trim(),kt=String(ce.active_at||"").trim(),Gt=String(ce.query_text||"").trim(),dt=typeof ce.min_score=="number"&&Number.isFinite(ce.min_score)?Number(ce.min_score):void 0,Xt=ce.order==="asc"?"asc":"desc",Bt=typeof ce.limit=="number"&&Number.isFinite(ce.limit)?Number(ce.limit):0,Ct=String(r||"").trim(),pt=String(l||"").trim(),Ot={scope:be,all_owners:_,limit:Bt,order:Xt};Ke&&(Ot.subject=Ke),qe&&(Ot.predicate=qe),st&&(Ot.object=st),ut&&(Ot.since=ut),Tt&&(Ot.until=Tt),kt&&(Ot.active_at=kt),Gt&&(Ot.query_text=Gt),typeof dt=="number"&&(Ot.min_score=dt),_||(be==="run"?Ct&&(Ot.run_id=Ct):be==="session"?pt?Ot.session_id=pt:Ct&&(Ot.run_id=Ct):be==="all"&&(Ct?Ot.run_id=Ct:pt&&(Ot.session_id=pt)));try{const Ce=await e.kg_query(Ot),Vt=Array.isArray(Ce==null?void 0:Ce.items)?Ce.items:[],Et=Ce==null?void 0:Ce.warnings;return{ok:(Ce==null?void 0:Ce.ok)!==!1,count:Number((Ce==null?void 0:Ce.count)||Vt.length),items:Vt,warnings:Et,raw:Ce}}catch(Ce){const Vt=Ce instanceof Error?Ce.message:String(Ce);if(Vt.includes("Run '")&&Vt.includes("not found")&&!pt&&(be==="session"||be==="all")&&Ct){const ln=await e.kg_query({...Ot,run_id:void 0,session_id:Ct}),$t=Array.isArray(ln==null?void 0:ln.items)?ln.items:[],ls=ln==null?void 0:ln.warnings;return{ok:(ln==null?void 0:ln.ok)!==!1,count:Number((ln==null?void 0:ln.count)||$t.length),items:$t,warnings:ls,raw:ln}}throw new Error(Vt||"KG query failed")}},[_,e,r,l]),On=m.useCallback(async ce=>{var qe;const be=String(ce.run_id||"").trim(),Ke=String(ce.span_id||"").trim();if(!(!be||!Ke)){ue(!0),C(!0),P(""),z(be),T(Ke),K("artifact"),ne(`source span:${Ke}`),oe(null),_e(""),Ee(ce.assertion&&typeof ce.assertion=="object"?ce.assertion:null),ze.current=!1;try{const st=[be],ut=typeof((qe=ce.assertion)==null?void 0:qe.owner_id)=="string"?String(ce.assertion.owner_id).trim():"";ut&&ut!==be&&st.push(ut);let Tt=null,kt=null;for(const Gt of st)try{kt=await(await e.download_run_artifact_content(Gt,Ke)).text(),Gt!==be&&z(Gt);break}catch(dt){Tt=dt instanceof Error?dt.message:String(dt)}if(kt==null)throw new Error(Tt||"Failed to load source span");_e(kt);try{const Gt=JSON.parse(kt);oe(Gt)}catch{oe(null)}}catch(st){const ut=st instanceof Error?st.message:String(st);P(ut||"Failed to load source span")}finally{C(!1)}}},[e]),gn=m.useCallback(async ce=>{const be=String(ce.run_id||"").trim();if(!be)return null;try{const Ke=await e.list_run_artifacts(be,{limit:200}),st=(Array.isArray(Ke==null?void 0:Ke.items)?Ke.items:[]).map(dt=>{const Xt=typeof(dt==null?void 0:dt.artifact_id)=="string"?String(dt.artifact_id).trim():"",Bt=dt!=null&&dt.tags&&typeof dt.tags=="object"&&!Array.isArray(dt.tags)?dt.tags:null,Ct=Bt&&typeof Bt.kind=="string"?String(Bt.kind).trim():"";return{artifact_id:Xt,kind:Ct}}).filter(dt=>!!(dt.artifact_id&&(dt.kind==="conversation_span"||dt.kind==="memory_note")));if(!st.length)return null;if(st.length===1)return st[0].artifact_id;const ut=ce.assertion,Tt=ut!=null&&ut.attributes&&typeof ut.attributes=="object"&&!Array.isArray(ut.attributes)?ut.attributes:null,Gt=(Tt&&typeof Tt.evidence_quote=="string"?String(Tt.evidence_quote):"").trim();if(!Gt)return null;for(const dt of st.slice(0,10))try{const Bt=await(await e.download_run_artifact_content(be,dt.artifact_id)).text(),Ct=JSON.parse(Bt);if(Ct&&typeof Ct=="object"){const pt=typeof Ct.note=="string"?String(Ct.note):"";if(pt&&pt.includes(Gt))return dt.artifact_id;const Ot=Array.isArray(Ct.messages)?Ct.messages:null;if(Ot){for(const Ce of Ot.slice(0,200))if(((Ce==null?void 0:Ce.content)==null?"":String(Ce.content)).includes(Gt))return dt.artifact_id}}}catch{}}catch{}return null},[e]),Es=m.useCallback(async ce=>{const be=String(ce.run_id||"").trim();if(be){ue(!0),C(!0),P(""),z(be),T(""),K("run_input"),ne(`transcript run:${be}`),oe(null),_e(""),Ee(ce.assertion&&typeof ce.assertion=="object"?ce.assertion:null),ze.current=!1;try{const Ke=await gn({run_id:be,assertion:ce.assertion});if(Ke){await On({run_id:be,span_id:Ke,assertion:ce.assertion});return}const qe=await e.get_run_input_data(be),st=qe&&typeof qe=="object"&&!Array.isArray(qe)?qe.input_data:null,ut={kind:"run_input_data",run_id:be};if(qe&&typeof(qe==null?void 0:qe.workflow_id)=="string"&&(ut.workflow_id=String(qe.workflow_id)),st&&typeof st=="object"&&!Array.isArray(st)){const Tt=st.context,Gt=(Tt&&typeof Tt=="object"&&Array.isArray(Tt.messages)?Tt.messages:null)||(Array.isArray(st.messages)?st.messages:null);Array.isArray(Gt)&&(ut.messages=Gt);const dt=["text","prompt","task","message"];for(const Xt of dt){const Bt=st[Xt];if(typeof Bt=="string"&&Bt.trim()){ut.note=Bt.trim();break}}ut.input_data=st}!ut.messages&&!ut.note&&(ut.note=JSON.stringify(st??qe??{},null,2));try{const Tt=await e.get_run(be),kt=Tt&&typeof(Tt==null?void 0:Tt.created_at)=="string"?String(Tt.created_at):"";kt&&(ut.created_at=kt)}catch{}oe(ut),_e(JSON.stringify(qe,null,2))}catch(Ke){const qe=Ke instanceof Error?Ke.message:String(Ke);P(qe||"Failed to load run input transcript")}finally{C(!1)}}},[e,On,gn]),Hn=m.useCallback(async()=>{H(""),Y(!0);try{const ce=c==="all"?"all":c,be=await vn({scope:ce,limit:0,order:"desc"});Mn(be.items||[],{warnings:be.warnings}),Ye.current={scope:ce}}catch(ce){const be=ce instanceof Error?ce.message:String(ce);H(be||"Load failed")}finally{Y(!1)}},[vn,Mn,c]);m.useEffect(()=>{E.length||Hn()},[]);const as=m.useCallback(async ce=>{const be=vp(ce.scope,"session");return Dt.current=ce,await vn({scope:be,subject:ce.subject,predicate:ce.predicate,object:ce.object,query_text:ce.query_text,min_score:ce.min_score,since:ce.since,until:ce.until,active_at:ce.active_at,limit:typeof ce.limit=="number"?ce.limit:0,order:"desc"})},[vn]),Tr=m.useCallback((ce,be)=>{var Ke;if((be==null?void 0:be.kind)==="live query"){const qe=Dt.current;qe&&(Ye.current={scope:vp(qe.scope,"session"),subject:typeof qe.subject=="string"?qe.subject:void 0,predicate:typeof qe.predicate=="string"?qe.predicate:void 0,object:typeof qe.object=="string"?qe.object:void 0})}Mn(ce,{warnings:(Ke=be==null?void 0:be.result)==null?void 0:Ke.warnings})},[Mn]),Vn=m.useCallback(async()=>{const ce=Ye.current;if(!ce)return;const be=String(De.current||"").trim(),Ke=await vn({scope:ce.scope,subject:ce.subject,predicate:ce.predicate,object:ce.object,since:be||void 0,order:"asc",limit:0}),qe=Array.isArray(Ke.items)?Ke.items:[];if(!qe.length)return;const ut=Date.now()+Math.max(250,Math.min(2e4,k)),Tt=ge.current,kt=[],Gt=[];let dt=String(De.current||"").trim();for(const Xt of qe){if(!Xt||typeof Xt!="object"||typeof Xt.subject!="string"||typeof Xt.predicate!="string"||typeof Xt.object!="string")continue;const Bt=pv(Xt);if(Tt.has(Bt))continue;Tt.add(Bt),kt.push(Xt),Gt.push({id:Bt,assertion:Xt,expires_at_ms:ut});const Ct=String(Xt.observed_at||"").trim();Ct&&(dt=_v(dt,Ct))}kt.length&&(De.current=dt,A(Xt=>{const Bt=Xt.concat(kt);return Bt.sort((Ct,pt)=>String((pt==null?void 0:pt.observed_at)||"").localeCompare(String((Ct==null?void 0:Ct.observed_at)||""))),Bt}),re(Xt=>{const Bt=Xt.concat(Gt);return Bt.sort((Ct,pt)=>pt.expires_at_ms-Ct.expires_at_ms),Bt.slice(0,30)}))},[k,vn]);return m.useEffect(()=>{if(!p)return;let ce=!1,be=null;const Ke=async()=>{if(!ce){try{await Vn()}catch{}ce||(be=window.setTimeout(()=>void Ke(),Math.max(250,Math.min(6e4,w))))}};return Ke(),()=>{ce=!0,be!==null&&window.clearTimeout(be)}},[p,w,Vn]),m.useEffect(()=>{if(!Z.length)return;const ce=window.setInterval(()=>{const be=Date.now();re(Ke=>Ke.filter(qe=>qe.expires_at_ms>be))},250);return()=>window.clearInterval(ce)},[Z.length]),s.jsxs("div",{className:"mindmap_root",children:[s.jsxs("div",{className:"mindmap_bar",children:[s.jsx("button",{className:"btn",onClick:()=>void Hn(),disabled:X,children:X?"Loading…":"Load snapshot"}),s.jsxs("label",{className:"field_inline",children:[s.jsx("span",{className:"mono muted",children:"source"}),s.jsxs("select",{value:c,onChange:ce=>{const be=String(ce.target.value||"").trim();(be==="all"||be==="global"||be==="session"||be==="run")&&f(be)},children:[s.jsx("option",{value:"all",children:"all memory"}),s.jsx("option",{value:"global",children:"global"}),s.jsx("option",{value:"session",children:"session"}),s.jsx("option",{value:"run",children:"run"})]})]}),s.jsxs("label",{className:"field_inline",children:[s.jsx("span",{className:"mono muted",children:"live"}),s.jsx("input",{type:"checkbox",checked:p,onChange:ce=>y(!!ce.target.checked)})]}),c==="session"?s.jsxs("label",{className:"field_inline",children:[s.jsx("span",{className:"mono muted",children:"session_id"}),s.jsx("input",{className:"mono",value:l,onChange:ce=>u(String(ce.target.value||"")),placeholder:"(required)"})]}):null,c==="run"?s.jsxs("label",{className:"field_inline",children:[s.jsx("span",{className:"mono muted",children:"run_id"}),s.jsx("input",{className:"mono",value:r,onChange:ce=>o(String(ce.target.value||"")),placeholder:"(required)"})]}):null,s.jsxs("details",{className:"mindmap_details",children:[s.jsx("summary",{className:"mono muted",children:"advanced"}),s.jsx("div",{className:"mindmap_advanced",children:s.jsxs("div",{className:"field_inline",children:[s.jsx("span",{className:"mono muted",style:{width:84},children:"poll_ms"}),s.jsx("input",{type:"number",min:250,max:6e4,step:50,value:w,onChange:ce=>x(Math.max(250,Number(ce.target.value||0)||750))}),s.jsx("span",{className:"mono muted",children:"highlight_ms"}),s.jsx("input",{type:"number",min:250,max:2e4,step:250,value:k,onChange:ce=>j(Math.max(250,Number(ce.target.value||0)||5e3))})]})})]})]}),M?s.jsx("div",{className:"mindmap_error mono",children:M}):null,s.jsxs("div",{className:"mindmap_explorer",children:[s.jsx(XR,{title:"mindmap",resetKey:tn,queryMode:"replace",items:Dn,warnings:L,onQuery:as,onItemsReplace:Tr,onOpenSpan:({run_id:ce,span_id:be,assertion:Ke})=>{On({run_id:ce,span_id:be,assertion:Ke})},onOpenTranscript:({run_id:ce,span_id:be,assertion:Ke})=>{const qe=String(ce||"").trim(),st=typeof be=="string"?String(be).trim():"";qe&&(st?On({run_id:qe,span_id:st,assertion:Ke}):Es({run_id:qe,assertion:Ke}))}},tn),Z.length?s.jsxs("div",{className:"mindmap_recent mindmap_overlay mindmap_overlay_recent",children:[s.jsx("div",{className:"mindmap_recent_title mono muted",children:"new assertions"}),s.jsx("div",{className:"mindmap_recent_list",children:Z.slice().sort((ce,be)=>be.expires_at_ms-ce.expires_at_ms).slice(0,12).map(ce=>s.jsx("div",{className:"mindmap_recent_item mono",children:eL(ce.assertion)},ce.id))})]}):null,It?s.jsx("div",{className:"mindmap_timeline mindmap_overlay mindmap_overlay_timeline",children:s.jsxs("div",{className:"mindmap_timeline_row",children:[s.jsx("div",{className:"mindmap_timeline_label mono muted",children:tc(Math.min(typeof Mt=="number"?Mt:It.max_ms,It.real_max_ms))}),s.jsx("input",{className:"mindmap_slider",type:"range",min:It.min_ms,max:It.max_ms,step:Ut,value:typeof Mt=="number"?Mt:It.max_ms,onChange:ce=>{const be=Number(ce.target.value||0);wn(be),Wn(be>=It.max_ms)}}),s.jsxs("div",{className:"mindmap_timeline_counts mono muted",children:[Dn.length.toLocaleString(),"/",E.length.toLocaleString()]})]})}):null]}),s.jsxs(bl,{open:ie,title:D||"source",onClose:()=>{ue(!1)},children:[F?s.jsx("div",{className:"mono muted",children:"Loading…"}):null,N?s.jsx("div",{className:"mindmap_error mono",children:N}):null,!F&&!N?s.jsxs("div",{className:"source_span",children:[(()=>{const ce=we;if(!ce)return null;const be=String(ce.subject||"").trim(),Ke=String(ce.predicate||"").trim(),qe=String(ce.object||"").trim(),st=tc(gl(ce.observed_at)),ut=ce.attributes&&typeof ce.attributes=="object"&&!Array.isArray(ce.attributes)?ce.attributes:null,Tt=ut&&typeof ut.evidence_quote=="string"?String(ut.evidence_quote):"",kt=ut&&typeof ut.original_context=="string"?String(ut.original_context):"";return s.jsxs("div",{className:"source_header",children:[s.jsxs("div",{className:"mono source_triple",title:`${be} --${Ke}--> ${qe}`,children:[be," ",s.jsxs("span",{className:"muted",children:["—",Ke,"→"]})," ",qe," ",st?s.jsxs("span",{className:"muted",children:["[",st,"]"]}):null]}),Tt?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:Tt}),kt?s.jsxs("details",{className:"source_evidence_more",children:[s.jsx("summary",{className:"mono muted",children:"original_context"}),s.jsx("pre",{className:"mono source_evidence_quote",children:kt})]}):null]}):null]})})(),s.jsxs("div",{className:"mono muted",style:{marginBottom:10},children:["run_id=",B," · ",Q==="artifact"?`span_id=${G}`:"source=input_data"]}),s.jsxs("div",{className:"source_actions",children:[Se!==null?s.jsx("button",{className:"btn",onClick:()=>Ie(Se),children:"Jump to evidence"}):null,Se===null&&et?s.jsx("button",{className:"btn",onClick:()=>ct(),children:"Jump to evidence"}):null]}),(()=>{const ce=J,be=ce&&typeof ce=="object"&&!Array.isArray(ce)?ce:null,Ke=Pe,qe=_t,st=be&&typeof be.created_at=="string"?String(be.created_at):"",ut=st?gl(st):null,Tt=ut!==null?tc(ut):st,kt=be&&be.span&&typeof be.span=="object"&&!Array.isArray(be.span)?be.span:null,Gt=kt&&typeof kt.from_timestamp=="string"?String(kt.from_timestamp):"",dt=kt&&typeof kt.to_timestamp=="string"?String(kt.to_timestamp):"",Xt=Gt?gl(Gt):null,Bt=dt?gl(dt):null,Ct=Xt!==null&&Bt!==null?`${tc(Xt)} → ${tc(Bt)}`:"";if(qe){const pt=QR(qe);if(pt){const Ot=Ue,Ce=Ot?pt.messages.findIndex($t=>mm($t.content,Ot)):-1,Vt=Ot?mv(Ot):[],Et=pt.created_at||st,ln=Et?ZR(Et):st?Tt:"";return s.jsx("div",{className:"source_chat",children:pt.messages.map(($t,ls)=>{const cs=$t.role,Ks=!!(Ot&&mm($t.content,Ot)),$s=cs==="user"?"USER":cs==="assistant"?"ASSISTANT":"SYSTEM";return s.jsxs("div",{id:ls===Ce?"source_note_msg_hit_0":void 0,className:`source_msg source_${cs} ${Ks?"source_match":""}`,children:[s.jsxs("div",{className:"source_msg_meta mono muted",children:[s.jsxs("span",{children:["#",ls+1," · ",$s,Ks?s.jsx("span",{className:"source_match_badge",children:"evidence"}):null]}),ln?s.jsx("span",{title:Et||"",children:ln}):null]}),s.jsx("div",{className:"source_msg_body",children:s.jsx(Ai,{text:$t.content,highlights:Ks&&Vt.length?Vt:void 0,highlightClassName:"source_note_hit",highlightId:ls===Ce?"source_note_hit_0":void 0})})]},`note_msg:${ls}`)})})}return s.jsxs("div",{className:"source_note",children:[st?s.jsx("div",{className:"mono muted",style:{marginBottom:10},children:s.jsxs("span",{title:st,children:["created_at=",Tt]})}):null,s.jsx(Ai,{text:qe,highlights:Ue?mv(Ue):void 0,highlightClassName:"source_note_hit",highlightId:"source_note_hit_0"})]})}if(Ke){const pt=new Map;for(const Ce of Ke){const Vt=typeof(Ce==null?void 0:Ce.role)=="string"?String(Ce.role):"unknown";pt.set(Vt,(pt.get(Vt)||0)+1)}const Ot=Array.from(pt.entries()).sort((Ce,Vt)=>Vt[1]-Ce[1]||Ce[0].localeCompare(Vt[0])).map(([Ce,Vt])=>`${Ce}×${Vt}`).join(" · ");return s.jsxs("div",{className:"source_chat",children:[st?s.jsxs("div",{className:"mono muted",style:{marginBottom:10},children:[s.jsxs("span",{title:st,children:["created_at=",Tt]})," · messages=",Ke.length]}):null,Ct?s.jsxs("div",{className:"mono muted",style:{marginBottom:10},children:["span=",Ct]}):null,Ot?s.jsxs("div",{className:"mono muted",style:{marginBottom:10},children:["participants: ",Ot]}):null,Ke.slice(0,200).map((Ce,Vt)=>{var fr,Ys;const Et=typeof(Ce==null?void 0:Ce.role)=="string"?String(Ce.role):"unknown",ln=(Ce==null?void 0:Ce.content)==null?"":String(Ce.content),$t=typeof(Ce==null?void 0:Ce.timestamp)=="string"?String(Ce.timestamp):"",ls=$t?gl($t):null,cs=ls!==null?tc(ls):$t,Ks=typeof(Ce==null?void 0:Ce.message_id)=="string"?String(Ce.message_id):typeof((fr=Ce==null?void 0:Ce.metadata)==null?void 0:fr.message_id)=="string"?String(Ce.metadata.message_id):typeof((Ys=Ce==null?void 0:Ce.metadata)==null?void 0:Ys.id)=="string"?String(Ce.metadata.id):"",$s=Je.has(Vt);return s.jsxs("div",{id:`source_msg_${Vt}`,className:`source_msg source_${Et} ${$s?"source_match":""}`,children:[s.jsxs("div",{className:"source_msg_meta mono muted",children:[s.jsxs("span",{children:["#",Vt+1," · ",Et,$s?s.jsx("span",{className:"source_match_badge",children:"evidence"}):null,Ks?s.jsx("span",{className:"source_msg_id",children:Ks}):null]}),$t?s.jsx("span",{title:$t,children:cs}):null]}),s.jsx("div",{className:"source_msg_body",children:s.jsx(Ai,{text:ln})})]},Vt)})]})}return s.jsx("pre",{className:"mono source_raw",style:{whiteSpace:"pre-wrap",wordBreak:"break-word"},children:(typeof ce=="string"?ce:he)||"(empty)"})})()]}):null]})]})}const xp=4;function nL(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 gv(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 sL(e){var c,f;const t=_=>{var y;const p=(y=e==null?void 0:e[_])==null?void 0:y.open;return Array.isArray(p)?p.map(gv).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(gv).filter(_=>_!==null):[],u=typeof((f=e==null?void 0:e.lessons)==null?void 0:f.total)=="number"?e.lessons.total:l.length;return{questions:n.slice(0,xp),questions_total:n.length,problems:r.slice(0,xp),problems_total:r.length,lessons:l.slice(0,xp),lessons_total:u}}function bp(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 yv={review:"Review",working:"Working",pending:"Pending",done:"Done"},rL={review:"nothing needs you",working:"idle",pending:"nothing scheduled",done:"no recent runs"},iL={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 oL(e){const t=String((e==null?void 0:e.status)||"").trim().toLowerCase();if(Ti(t))return"done";const n=qu(e);return n==="tool_approval"||n==="user_response"?"review":n==="scheduled"||t==="pending"||t==="queued"||t==="created"?"pending":"working"}function aL(e){const t=qu(e);return t==="tool_approval"||t==="user_response"}function wv(e,t=Date.now()){const n=oL(e),r=e!=null&&e.waiting&&typeof e.waiting=="object"?e.waiting:null,o=Wu(r),l=kn((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:qu(e),reason:nb(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:Rg(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:$f(e),tag_label:Ox(e),automation_id:$f(e)==="occurrence"?String((e==null?void 0:e.automation_id)||"").trim():""}}function lL(e,t,n=Date.now()){const r={pending:[],working:[],review:[],done:[]},o=t&&t.length?t:e,l=new Set;for(const u of o||[]){const c=String((u==null?void 0:u.run_id)||"").trim();!u||!c||l.has(c)||Gy(u)||aL(u)&&(l.add(c),r.review.push(wv(u,n)))}for(const u of e||[]){const c=String((u==null?void 0:u.run_id)||"").trim();if(!u||!c||l.has(c)||Gy(u))continue;const f=wv(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 wg={"12h":12*36e5,"24h":24*36e5,"48h":48*36e5,"72h":72*36e5,"7d":7*864e5,"14d":14*864e5,"1m":30*864e5,all:null},jp={"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"},vv="48h";function cL(e,t,n=Date.now()){const r=wg[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 uL(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 dL=6e4;function bf(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 fL(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 hL(e){const t=String(e||"");return t.length>14?`${t.slice(0,6)}…${t.slice(-6)}`:t}function Sp(e){const t=String(e||"").trim();return t.length>72?`${t.slice(0,70)}…`:t}function mL(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 Sm(e){return e.toLowerCase().replace(/[_-]+/g," ")}function _L(e){var _,p;const t=e!=null&&e.spec&&typeof e.spec=="object"?e.spec:null,n=t!=null&&t.phases&&typeof t.phases=="object"&&!Array.isArray(t.phases)?t.phases:null;if(!n)return null;const r=Object.keys(n).filter(y=>y&&typeof y=="string");if(!r.length)return null;const o=[];for(const y of r){o.push({needle:Sm(y),phase:y});const w=(_=n[y])==null?void 0:_.spoken_synonyms;if(Array.isArray(w))for(const x of w){const k=Sm(String(x||"").trim());k&&o.push({needle:k,phase:y})}}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=(p=t==null?void 0:t.state_mode_axis)==null?void 0:p.words;if(f&&typeof f=="object"&&!Array.isArray(f))for(const[y,w]of Object.entries(f)){const x=String((w==null?void 0:w.phase)||"").trim(),k=Sm(String(y||"").trim());k&&r.includes(x)&&c.push({needle:k,phase:x})}return{phases:r,synonyms:o,modes:c,initial:u,version:typeof t.version=="number"?t.version:null,sha256:String((e==null?void 0:e.sha256)||"").trim()}}const pL=["asleep","sleep","dream"],gL=["rest"],yL=["awake","idle"];function wL(e,t){const n=String(e||"").trim().toLowerCase();if(!n)return"unknown";if(t){const r=Sm(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":pL.some(u=>n.includes(u))?t.initial:gL.some(u=>n.includes(u))&&t.phases.includes("personal")?"personal":yL.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 vL=new Set(["visit","work","personal","sleep","paused","resting","stopped","unknown"]),xL=new Set(["visit","work","personal","sleep","paused","resting","stopped","unknown"]);function bL(e){if(!e)return vL;const t=e.phases.filter(n=>xL.has(n));return new Set([...t,"paused","stopped","unknown"])}function jL(e){var X,Y,Z,re,ie,ue;const t=Date.now(),n=m.useMemo(()=>lL(e.runs,e.all_runs,Date.now()),[e.runs,e.all_runs]),[r,o]=m.useState(""),[l,u]=m.useState(""),[c,f]=m.useState(!1),[_,p]=m.useState(()=>{try{const F=localStorage.getItem("abstractobserver_done_window_v1");return F&&F in wg?F:vv}catch{return vv}}),y=m.useMemo(()=>cL(n.done,_,t),[n.done,_]),w=bf(e.runs_refreshed_at,t),x=n.review.length,k=y.visible.filter(F=>F.failed).length,[j,E]=m.useState(""),[A,L]=m.useState(null),O=F=>`${F.run_id}:${F.wait_key}:${F.since_ms??""}`;m.useEffect(()=>{r&&(n.review.some(F=>O(F)===r)||o(""))},[n,r]);async function M(F,C){o(O(F)),u("");try{await e.on_resume_wait(F.run_id,F.wait_key,C)}catch(N){u(`${F.run_id}: ${String((N==null?void 0:N.message)||N||"resume failed")}`),o("")}}function H(F){const C=r===O(F),N=F.column==="review",P=N&&!F.wait_key;return s.jsxs("div",{className:`mc_card ${N?"mc_card_review":""} ${F.failed?"mc_card_failed":""}`,onClick:()=>e.on_open_run(F.run_id),role:"button",tabIndex:0,onKeyDown:D=>{D.key==="Enter"&&D.target===D.currentTarget&&e.on_open_run(F.run_id)},children:[s.jsxs("div",{className:"mc_card_head",children:[s.jsx("span",{className:"mc_card_title",title:F.workflow,children:mL(F.workflow)}),(()=>{const D=F.failed?"failed":Lm({status:F.status,paused:F.paused});return s.jsx("span",{className:`mc_status ${Nl(D)}`,children:D==="unknown"?"?":D})})()]}),s.jsxs("div",{className:"mc_card_meta",children:[s.jsx("span",{className:"mono",title:F.run_id,children:hL(F.run_id)}),F.is_subrun?s.jsx("span",{title:"This wait lives in a child run of an agent workflow",children:"subrun"}):null,F.tag?s.jsx("span",{className:"mc_pill","data-tag":F.tag,children:F.tag_label}):null,F.automation_id?s.jsx("button",{type:"button",className:"btn btn_sm",title:"Open this occurrence's automation",onClick:D=>{D.stopPropagation(),e.on_open_automation(F.automation_id)},onKeyDown:D=>D.stopPropagation(),children:"Automation"}):null,F.duration_ms>=0?s.jsx("span",{children:fL(F.duration_ms)}):null,F.tokens_total!==null?s.jsxs("span",{children:[F.tokens_total.toLocaleString()," tk"]}):null,F.tool_calls!==null&&F.tool_calls>0?s.jsxs("span",{children:[F.tool_calls," tools"]}):null]}),F.is_scheduled&&F.schedule_interval?s.jsxs("div",{className:"mc_card_line",children:["every ",F.schedule_interval]}):null,F.failed&&F.error?s.jsx("div",{className:"mc_card_error",title:F.error,children:F.error.length>120?`${F.error.slice(0,118)}…`:F.error}):null,N?s.jsxs("div",{className:"mc_card_review_body",onClick:D=>D.stopPropagation(),onKeyDown:D=>D.stopPropagation(),children:[s.jsx("div",{className:"mc_card_reason",children:F.reason||"Needs a decision"}),F.prompt?s.jsx("div",{className:"mc_card_prompt",title:F.prompt,children:F.prompt.length>240?`${F.prompt.slice(0,238)}…`:F.prompt}):null,F.tool_names.length?s.jsxs("div",{className:"mc_card_tools",title:"Tool calls awaiting your approval",children:[F.tool_names.slice(0,4).map((D,ne)=>s.jsx("span",{className:"mc_tool_chip mono",children:D},`${D}_${ne}`)),F.tool_names.length>4?s.jsxs("span",{className:"mc_tool_chip",children:["+",F.tool_names.length-4," more"]}):null]}):null,F.since_ms!==null?s.jsxs("div",{className:"mc_card_waiting",children:["waiting ",bf(F.since_ms,t)]}):null,P?s.jsx("div",{className:"mc_card_line",title:"The wait has not registered a wait_key yet — open the run to inspect.",children:"wait key not published yet — open the run"}):null,P?s.jsx("div",{className:"mc_card_actions",children:s.jsx("button",{className:"btn",onClick:()=>e.on_open_run(F.run_id),children:"Open the run →"})}):F.wait_kind==="tool_approval"?s.jsxs("div",{className:"mc_card_actions",children:[s.jsx("button",{className:"btn success",disabled:C,onClick:()=>void M(F,{approved:!0}),children:C?"Resuming…":"Approve"}),s.jsx("button",{className:"btn danger",disabled:C,onClick:()=>void M(F,{approved:!1}),children:"Reject"})]}):s.jsx("div",{className:"mc_card_actions",children:s.jsx("button",{className:"btn primary",onClick:()=>e.on_open_run(F.run_id),children:"Review & answer →"})})]}):null]},F.run_id)}return s.jsxs("div",{className:"page page_scroll mc_page",children:[s.jsxs("div",{className:"mc_health",children:[s.jsx("span",{className:`mc_led ${e.gateway_connected?"ok":"bad"}`,title:e.gateway_connected?"Gateway connected":"Gateway unreachable"}),e.gateway_connected?null:s.jsx("span",{className:"mc_health_text",children:"gateway unreachable"}),e.runs_refreshed_at===null?s.jsx("span",{className:"mc_health_text muted mc_loading",children:"loading runs…"}):s.jsxs("div",{className:"mc_stats",children:[s.jsxs("div",{className:`mc_stat ${x?"is_hot":""}`,title:"runs blocked on a human decision (Review column)",children:[s.jsx("span",{className:"mc_stat_value",children:x}),s.jsx("span",{className:"mc_stat_label",children:"need you"})]}),s.jsxs("div",{className:`mc_stat ${k?"is_bad":""}`,title:"failed runs in the Done column",children:[s.jsx("span",{className:"mc_stat_value",children:k}),s.jsx("span",{className:"mc_stat_label",children:"failed"})]}),s.jsxs("div",{className:"mc_stat",title:"runs executing or parked listening",children:[s.jsx("span",{className:"mc_stat_value",children:n.working.length}),s.jsx("span",{className:"mc_stat_label",children:"working"})]})]}),s.jsx("span",{className:"mc_spacer"}),s.jsxs("div",{className:"mc_health_side",children:[w?s.jsxs("span",{className:"mc_health_text muted",title:"age of the last runs poll — the board is only as live as this",children:["data ",w," old"]}):null,s.jsx("button",{className:"btn",onClick:e.on_refresh,disabled:e.refreshing,children:e.refreshing?"Refreshing…":"Refresh"})]})]}),l?s.jsx("div",{className:"mc_error",children:l}):null,e.entities.length||e.entities_error?s.jsxs("div",{className:"mc_entities",children:[s.jsxs("div",{className:"mc_entities_head",children:[s.jsxs("span",{children:["Entities",e.entities_total>e.entities.length?` (${e.entities.length} of ${e.entities_total} — open the entity app for all)`:""]}),s.jsx("a",{className:"mc_entity_link",href:e.entity_app_href,target:"_blank",rel:"noreferrer",children:"open the entity app →"})]}),e.entities_error?s.jsx("div",{className:"muted",children:e.entities_error}):null,s.jsx("div",{className:"mc_entities_row",children:e.entities.map(F=>s.jsxs("div",{className:"mc_entity_cell",children:[s.jsxs("a",{className:"mc_entity",href:`${e.entity_app_href}${e.entity_app_href.includes("?")?"&":"?"}entity=${encodeURIComponent(F.name)}&live=1`,target:"_blank",rel:"noreferrer",title:[F.error,F.age_days!==null?`${F.age_days.toFixed(0)} days old`:"",F.last_moment].filter(Boolean).join(" — ")||F.name,children:[s.jsx("span",{className:"mc_entity_name",children:F.name}),(()=>{var z;const C=String(F.live_phase||F.state||"").trim(),N=wL(C,e.phase_graph),P=bL(e.phase_graph).has(N)?N:"other",D=((z=e.phase_graph)==null?void 0:z.initial)??"sleep",ne=/awake|idle/i.test(C)&&N===D,B=C&&C.toLowerCase()!==N?` — wire word: ${C}${ne?" (settling)":""}`:"";return s.jsx("span",{className:`mc_entity_phase mc_phase_${P}`,title:(F.live_phase?"phase (cognition wire)":"phase from card state — cognition wire unavailable")+B,children:N})})(),F.last_moment?s.jsx("span",{className:"mc_entity_moment",title:F.last_moment,children:F.last_moment.replace(/_/g," ")}):null,(()=>{if(F.working===!0)return s.jsx("span",{className:"mc_entity_live",title:"busy now (loop mid-day or live visit — store-read, never fabricated)",children:"● busy"});const C=uL(F.last_moment_at,t);return F.working===!1?s.jsxs("span",{className:"mc_entity_live muted",title:"idle (cognition wire)",children:["idle",C!==null?` · ${bf(t-C,t)} ago`:""]}):C===null?null:C<=dL?s.jsx("span",{className:"mc_entity_live",title:`last moment ${bf(t-C,t)} ago`,children:"● active"}):s.jsxs("span",{className:"mc_entity_live muted",title:"time since the last recorded moment",children:[bf(t-C,t)," ago"]})})(),F.tokens_total!==null?s.jsxs("span",{className:"muted mc_entity_spend",title:`lifetime billed tokens (home run ledger)${F.live_visit_tokens!==null?`; open visit: ${bp(F.live_visit_tokens)} tk`:""}${F.spend_warning?`; ${F.spend_warning}`:""}`,children:[bp(F.tokens_total)," tk",F.live_visit_tokens!==null?` (+${bp(F.live_visit_tokens)})`:"",F.spend_warning?"*":""]}):null]}),F.open_questions_total||F.open_problems_total||F.lessons_total||F.dreams_brief?s.jsx("button",{type:"button",className:"mc_entity_hints_btn","aria-expanded":j===F.name,title:"open questions / problems + distilled lessons + night signals from the entity card — click to expand",onClick:()=>E(j===F.name?"":F.name),children:[F.open_questions_total?`${F.open_questions_total} question${F.open_questions_total>1?"s":""}`:"",F.open_problems_total?`${F.open_problems_total} problem${F.open_problems_total>1?"s":""}`:"",F.lessons_total?`${F.lessons_total} lesson${F.lessons_total>1?"s":""}`:"",F.dreams_brief?`night: ${F.dreams_brief.count} signal${F.dreams_brief.count>1?"s":""}`:""].filter(Boolean).join(" · ")}):null]},F.name))}),(()=>{if(!j)return null;const F=e.entities.find(P=>P.name===j);if(!F||!F.open_questions.length&&!F.open_problems.length&&!F.lessons.length&&!F.dreams_brief)return null;const C=e.on_read_diary?async P=>{const D=await e.on_read_diary(F.name,P);L({entity:F.name,entry:(D==null?void 0:D.entry)??D,seq:typeof(D==null?void 0:D.read_recorded_at_seq)=="number"?D.read_recorded_at_seq:null})}:void 0,N=F.open_questions_total-F.open_questions.length+(F.open_problems_total-F.open_problems.length)+(F.lessons_total-F.lessons.length);return s.jsxs("div",{className:"mc_entity_hints_panel",children:[F.open_questions.map((P,D)=>s.jsx(O_,{kind:"question",label:P.title||Sp(P.statement),entryId:P.entry_id,onOpen:C,title:P.statement||P.title},`q_${P.record_id||D}`)),F.open_problems.map((P,D)=>s.jsx(O_,{kind:"problem",label:P.title||Sp(P.statement),entryId:P.entry_id,onOpen:C,title:P.statement||P.title},`p_${P.record_id||D}`)),F.lessons.map((P,D)=>s.jsx(O_,{kind:"lesson",label:P.title||Sp(P.statement),entryId:P.entry_id,onOpen:C,title:P.statement||P.title},`l_${P.record_id||D}`)),F.dreams_brief?s.jsxs("span",{className:"mc_entity_dreams muted",title:"night signals carried by STANDING dreams (the sleep pass's maintenance stream; count = signals, not dreams); felt tones color the content, they never rank it — the entity app renders the full stream",children:["night signals: ",F.dreams_brief.count,F.dreams_brief.dreams?` across ${F.dreams_brief.dreams} dream${F.dreams_brief.dreams>1?"s":""}`:"",F.dreams_brief.kinds.length?` — ${F.dreams_brief.kinds.slice(0,6).join(", ")}${F.dreams_brief.kinds.length>6?` +${F.dreams_brief.kinds.length-6} more`:""}`:"",F.dreams_brief.felt_tones.length?` · felt: ${F.dreams_brief.felt_tones.slice(0,6).join(", ")}`:""]}):null,N>0?s.jsxs("span",{className:"muted mc_entity_hints_more",children:["+",N," more — open the entity app"]}):null]})})()]}):null,A?s.jsx(bl,{open:!0,title:`${A.entity} — diary entry`,onClose:()=>L(null),children:s.jsxs("div",{className:"mc_diary_entry",children:[s.jsx("div",{className:"mc_diary_meta muted",children:[(X=A.entry)!=null&&X.kind?`kind: ${A.entry.kind}`:"",(Y=A.entry)!=null&&Y.visibility?`visibility: ${A.entry.visibility}`:"",(Z=A.entry)!=null&&Z.written_at?`written: ${A.entry.written_at}`:"",(re=A.entry)!=null&&re.entry_id?`id: ${A.entry.entry_id}`:""].filter(Boolean).join(" · ")}),s.jsxs("div",{className:"mc_diary_recorded muted",children:["this read was recorded in ",A.entity,"’s stream",A.seq!==null?` (seq ${A.seq})`:""]}),(ie=A.entry)!=null&&ie.gist?s.jsx("div",{className:"mc_diary_gist",children:String(A.entry.gist)}):null,s.jsx("pre",{className:"mc_diary_text",children:String(((ue=A.entry)==null?void 0:ue.text)||"(entry carries no text)")})]})}):null,s.jsx("div",{className:"mc_board",children:Object.keys(yv).map(F=>{const C=F==="done"?y.visible:n[F],N=F==="done"&&!c?C.slice(0,8):C;return s.jsxs("div",{className:`mc_column mc_column_${F}`,children:[s.jsxs("div",{className:"mc_column_head",children:[s.jsx("span",{className:"mc_column_title",children:yv[F]}),F==="done"?s.jsx("select",{className:"mc_window_select",value:_,title:"Show terminal runs from this time window",onClick:P=>P.stopPropagation(),onChange:P=>{const D=P.target.value;p(D),f(!1);try{localStorage.setItem("abstractobserver_done_window_v1",D)}catch{}},children:Object.keys(wg).map(P=>s.jsx("option",{value:P,children:jp[P]},P))}):null,s.jsx("span",{className:"mc_column_count",title:F==="done"&&y.hidden_count?`${y.hidden_count} older run(s) outside this window`:void 0,children:C.length})]}),s.jsx("div",{className:"mc_column_hint muted",children:iL[F]}),s.jsxs("div",{className:"mc_column_cards",children:[N.map(P=>H(P)),C.length?null:s.jsx("div",{className:"mc_empty muted",children:e.runs_refreshed_at===null?"loading…":F==="done"&&y.hidden_count?`none in the ${jp[_]} — ${y.hidden_count} older`:rL[F]}),F==="done"&&C.length>8&&!c?s.jsxs("button",{className:"btn mc_more",onClick:()=>f(!0),children:["show all ",C.length]}):null,F==="done"&&y.hidden_count&&C.length?s.jsxs("div",{className:"mc_window_note muted",title:"Widen the window above to see older terminal runs",children:["+",y.hidden_count," older outside ",jp[_]]}):null]})]},F)})})]})}function xv(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 bv(e){const t=e.disabled===!0,n=m.useMemo(()=>xv(e.options||[]),[e.options]),r=m.useMemo(()=>xv(e.value||[]),[e.value]),[o,l]=m.useState(!1),[u,c]=m.useState(""),f=m.useMemo(()=>{const y=u.trim().toLowerCase();return y?n.filter(w=>w.toLowerCase().includes(y)):n},[n,u]),_=m.useMemo(()=>new Set(r),[r]),p=typeof e.max_list_height_px=="number"?e.max_list_height_px:220;return s.jsxs("div",{className:"multi_select",children:[s.jsxs("div",{className:"multi_select_row",children:[s.jsxs("button",{className:"btn",type:"button",onClick:()=>l(y=>!y),disabled:t||!n.length,"aria-expanded":o,children:[o?"Hide":"Select"," • ",r.length>0?`${r.length} of ${n.length}`:e.placeholder||"(none)"]}),s.jsx("button",{className:"btn",type:"button",onClick:()=>e.onChange(n.slice()),disabled:t||!n.length||r.length===n.length,title:"Select all",children:"All"}),s.jsx("button",{className:"btn",type:"button",onClick:()=>e.onChange([]),disabled:t||r.length===0,title:"Clear selection",children:"Clear"})]}),r.length>0?s.jsx("div",{className:"multi_select_chips",children:r.map(y=>s.jsxs("span",{className:"multi_select_chip",title:y,onClick:()=>{if(t)return;const w=new Set(_);w.delete(y),e.onChange(Array.from(w.values()))},children:[y,t?null:s.jsx("span",{className:"multi_select_chip_x",children:"×"})]},y))}):null,o?s.jsxs("div",{className:"multi_select_panel",children:[s.jsx("input",{className:"mono",value:u,onChange:y=>c(String(y.target.value||"")),placeholder:"filter…",disabled:t}),s.jsxs("div",{className:"multi_select_list",style:{maxHeight:`${p}px`},children:[f.map(y=>{const w=_.has(y);return s.jsxs("label",{className:`multi_select_item mono ${w?"checked":""}`,children:[s.jsx("input",{type:"checkbox",checked:w,disabled:t,onChange:x=>{const k=new Set(_);x.target.checked?k.add(y):k.delete(y),e.onChange(Array.from(k.values()))}}),s.jsx("span",{children:y})]},y)}),f.length?null:s.jsx("div",{className:"mono muted",children:"(no matches)"})]})]}):null]})}function SL(){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 kL(){if(typeof window>"u")return!1;const e=window;return!!(e!=null&&e.AudioContext||e!=null&&e.webkitAudioContext)}function NL(){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 CL(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 EL(e){const t=P=>{var D;return(D=e.on_error)==null?void 0:D.call(e,P)},n=m.useMemo(()=>kL(),[]),r=m.useMemo(()=>SL(),[]),[o,l]=m.useState({key:"",status:"idle"}),u=m.useRef(""),c=m.useRef(""),f=m.useRef(null),_=m.useRef(null),p=m.useRef(null),y=m.useRef(null),w=m.useRef(0),x=m.useRef(0),k=()=>{try{const P=globalThis,D=(P==null?void 0:P.AudioContext)||(P==null?void 0:P.webkitAudioContext);if(!D)return null;if(!f.current){const z=new D,G=z.createGain();G.gain.value=1,G.connect(z.destination),f.current=z,_.current=G}const ne=f.current,B=_.current;if(!ne||!B)return null;try{ne.state==="suspended"&&ne.resume()}catch{}return{ctx:ne,gain:B}}catch{return null}},j=()=>{const P=p.current;if(p.current=null,!!P){try{P.onended=null}catch{}try{P.stop()}catch{}try{P.disconnect()}catch{}}},E=()=>{j(),c.current="",u.current="",y.current=null,w.current=0,x.current=0,l({key:"",status:"idle"})};m.useEffect(()=>()=>{var P,D;E();try{(P=_.current)==null||P.disconnect()}catch{}try{(D=f.current)==null||D.close()}catch{}f.current=null,_.current=null,y.current=null},[]);const A=async(P,D,ne)=>{const B=k();if(!B)throw new Error("TTS playback is not supported in this browser");const{ctx:z,gain:G}=B;try{z.state==="suspended"&&await z.resume()}catch{}j();const T=z.createBufferSource();T.buffer=D,T.connect(G);const Q=Number.isFinite(Number(D.duration))?Number(D.duration):0,K=Math.max(0,Math.min(Number(ne||0),Q>0?Math.max(0,Q-.01):0));x.current=z.currentTime-K,w.current=K,p.current=T,u.current=P,T.onended=()=>{p.current===T&&(p.current=null,w.current=0,x.current=0,u.current="",l({key:"",status:"idle"}))},T.start(0,K),l({key:P,status:"playing"})},L=async(P,D)=>{const ne=String(P||"").trim(),B=String(D||"").trim();if(!ne||!B)return;const z=e.gateway,G=String(e.run_id||"").trim();if(!z){t==null||t("Connect to the gateway first.");return}if(!G){t==null||t("Voice store not available (missing run_id).");return}const T=k();if(!T){t==null||t("TTS playback is not supported in this browser.");return}const Q=o.key===ne;if(Q&&o.status==="playing"){const K=Math.max(0,T.ctx.currentTime-Number(x.current||0));w.current=K,j(),l({key:ne,status:"paused"});return}if(Q&&o.status==="paused"){const K=y.current;if(K){t==null||t("");try{await A(ne,K,w.current)}catch(J){t==null||t(String((J==null?void 0:J.message)||J||"TTS play failed")),l({key:"",status:"idle"})}return}}if(!(Q&&o.status==="loading")){j(),y.current=null,w.current=0,x.current=0,u.current=ne,c.current=ne,l({key:ne,status:"loading"}),t==null||t("");try{const K=await z.voice_tts(G,{text:B,request_id:Os()}),J=K==null?void 0:K.audio_artifact,oe=J&&typeof J=="object"&&!Array.isArray(J)?String(J.$artifact||"").trim():"";if(!oe)throw new Error("TTS failed: missing audio artifact");const _e=await(await z.download_run_artifact_content(G,oe)).arrayBuffer();if(c.current!==ne)return;const we=await CL(T.ctx,_e);if(c.current!==ne)return;y.current=we,w.current=0,await A(ne,we,0)}catch(K){c.current===ne&&(c.current="",u.current="",l({key:"",status:"idle"})),t==null||t(String((K==null?void 0:K.message)||K||"TTS failed"))}}},[O,M]=m.useState(!1),[H,X]=m.useState(!1),Y=m.useRef(null),Z=m.useRef(null),re=m.useRef([]),ie=m.useRef("");function ue(){var P,D;try{(D=(P=Y.current)==null?void 0:P.getTracks)==null||D.call(P).forEach(ne=>{try{ne.stop()}catch{}})}catch{}Y.current=null}m.useEffect(()=>()=>{var P,D;try{(D=(P=Z.current)==null?void 0:P.stop)==null||D.call(P)}catch{}Z.current=null,ue()},[]);async function F(P,D){var G;if(t==null||t(""),!P||!P.size||H)return;const ne=e.gateway,B=String(e.session_id||"").trim(),z=String(e.run_id||"").trim();if(!ne){t==null||t("Connect to the gateway first.");return}if(!B){t==null||t("Voice input unavailable (missing session_id).");return}if(!z){t==null||t("Voice input unavailable (missing run_id).");return}X(!0);try{const T=String(D||P.type||"").toLowerCase(),Q=T.includes("mp4")?"m4a":T.includes("ogg")?"ogg":T.includes("wav")?"wav":"webm",K=new File([P],`recording.${Q}`,{type:T||"audio/webm"}),J=await ne.attachments_upload(B,K,{filename:K.name,content_type:K.type}),oe=await ne.audio_transcribe(z,{audio_artifact:J,request_id:Os()}),he=String((oe==null?void 0:oe.text)||"").trim();he&&((G=e.on_transcript)==null||G.call(e,he))}catch(T){t==null||t(String((T==null?void 0:T.message)||T||"Transcription failed"))}finally{X(!1)}}async function C(){if(t==null||t(""),!r){t==null||t("Voice recording is not supported in this browser (MediaRecorder/getUserMedia unavailable).");return}if(!H&&!(O||Z.current)){re.current=[];try{const P=await navigator.mediaDevices.getUserMedia({audio:!0});Y.current=P;const D=NL();ie.current=D;const ne=D?new MediaRecorder(P,{mimeType:D}):new MediaRecorder(P);Z.current=ne,ne.ondataavailable=B=>{try{B!=null&&B.data&&re.current.push(B.data)}catch{}},ne.onerror=()=>{t==null||t("Recording failed.")},ne.onstop=()=>{M(!1),ue(),Z.current=null;try{const B=new Blob(re.current,{type:ie.current||""});F(B,ie.current)}catch(B){t==null||t(String((B==null?void 0:B.message)||B||"Failed to build recording"))}},ne.start(),M(!0)}catch(P){ue(),Z.current=null,M(!1);const D=String((P==null?void 0:P.message)||P||"Failed to access microphone");t==null||t(D.toLowerCase().includes("permission")?`Microphone permission denied: ${D}`:D)}}}function N(){const P=Z.current;if(!(!O||!P)){Z.current=null,M(!1);try{P.stop()}catch(D){t==null||t(String((D==null?void 0:D.message)||D||"Failed to stop recording"))}}}return m.useEffect(()=>{if(!O)return;const P=()=>N();return window.addEventListener("pointerup",P),window.addEventListener("pointercancel",P),()=>{window.removeEventListener("pointerup",P),window.removeEventListener("pointercancel",P)}},[O]),{tts_supported:n,tts_playback:o,toggle_tts:L,stop_tts:E,voice_ptt_supported:r,voice_ptt_recording:O,voice_ptt_busy:H,start_voice_ptt_recording:C,stop_voice_ptt_recording:N}}const _m=500,Gm="http://127.0.0.1:8080";function jv(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 jf(e){const t=String(e||"").trim();return t.startsWith("abstractcode.")?`abstract.${t.slice(13)}`:t}function kp(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 Np(e){const t=String(e||"").trim();return t.startsWith("abstract.")||t.startsWith("abstractcode.")}function $L(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 AL(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 _=String(c.type||"").trim();if(_==="execution"||f==="exec-out"||f==="exec")continue;const p=String(c.label||f).trim()||f,y={id:f,label:p,type:_||"unknown"};l&&Object.prototype.hasOwnProperty.call(l,f)&&(y.default=l[f]),u.push(y)}return u}function Cp(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 TL=/^[a-zA-Z0-9_-]+$/;function Sv(e){return TL.test(String(e||"").trim())}async function ML(e){const t=String(e||""),n=new TextEncoder().encode(t),r=globalThis.crypto;if(!r||!r.subtle||typeof r.subtle.digest!="function")throw new Error("crypto.subtle.digest not available");const o=await r.subtle.digest("SHA-256",n);return Array.from(new Uint8Array(o)).map(l=>l.toString(16).padStart(2,"0")).join("")}async function kv(e){const t=String(e||"").trim();if(!t)throw new Error("session_id is required");if(Sv(t)){const r=`session_memory_${t}`;if(Sv(r))return r}return`session_memory_sha_${(await ML(t)).slice(0,32)}`}const Nv=new Set(["abstract.status","abstract.summary","abstract.chat"]);function RL(e){if(!e)return!1;if(e.kind==="error")return!0;if(e.kind==="info")return!1;const t=String(e.emit_name||"").trim();if((e.kind==="event"||e.kind==="message")&&t)return!Nv.has(t);const n=String(e.effect_type||"").trim();if(n){if(n==="tool_calls"||n==="llm_call"||n==="ask_user"||n==="answer_user"||n==="memory_compact"||n==="start_subworkflow")return!0;if(n==="emit_event")return!(t&&Nv.has(t))}if(String(e.status||"").trim()==="waiting"){const l=eo(e.data),u=String((l==null?void 0:l.reason)||"").trim();return!!(u==="user"||u==="event"||Wu(l).length)}return!!Vf(e.data)}function LL(){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)||Gm),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:Gm,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 IL(e){localStorage.setItem("abstractobserver_settings",JSON.stringify({...e,auth_token:""}))}function OL(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 Cv(e){const t=OL(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 PL(){return typeof window>"u"?"":c1(window.location)}function DL(){try{const e="abstractobserver_session_id_v1",t=window.sessionStorage.getItem(e);if(t&&t.trim())return t.trim();const n=globalThis.crypto,o=`obs_${n&&typeof n.randomUUID=="function"?n.randomUUID():`${Math.random().toString(16).slice(2)}_${Date.now().toString(16)}`}`;return window.sessionStorage.setItem(e,o),o}catch{return""}}function FL(){var pu,Oo,ef,tf,gu,Xl,zh,Bh,nf,sf,Po,Uh,ha;const[e,t]=m.useState("board"),[n,r]=m.useState(()=>LL()),o=typeof window<"u"&&((pu=window.__ABSTRACT_UI_CONFIG__)==null?void 0:pu.monitor_gpu)===!0,l=typeof window<"u"&&(((Oo=window.__ABSTRACT_UI_CONFIG__)==null?void 0:Oo.entity_app_url)||"").trim().replace(/\/+$/,"")||"http://127.0.0.1:3007",u=m.useRef(null),[c,f]=m.useState(""),[_,p]=m.useState(""),[y,w]=m.useState(()=>PL()),[x,k]=m.useState(""),[j,E]=m.useState(""),[A,L]=m.useState("{}"),[O]=m.useState(()=>DL()),[M,H]=m.useState(null),[X,Y]=m.useState(!1),[Z,re]=m.useState(""),[ie,ue]=m.useState(!1),[F,C]=m.useState(""),[N,P]=m.useState(!1),D=gj({appName:"AbstractObserver",variant:"dismissable",defaultGatewayUrl:typeof window<"u"&&((ef=window.__ABSTRACT_UI_CONFIG__)==null?void 0:ef.gateway_url)||Gm,onStatusChange:g=>Gl(g)}),[ne,B]=m.useState(null),[z,G]=m.useState(null),[T,Q]=m.useState(!1),[K,J]=m.useState(null),[oe,he]=m.useState("once"),[_e,we]=m.useState(""),[Ee,ze]=m.useState(Vp),[Ue,_t]=m.useState([]),[Pe,et]=m.useState(null),[lt,Je]=m.useState(!1),[Se,Ie]=m.useState([]),ct=m.useRef(new b1(Os)),[ge,De]=m.useState({available:!1,reason:"Sign in to a gateway to use automations."}),[Ye,Dt]=Dj("abstractobserver",{legacyKey:"abstractobserver_settings"}),[tn,pn]=m.useState(!1),[Ut,It]=m.useState(!1),[un,Wn]=m.useState([]),[Mt,wn]=m.useState([]),[Dn,Mn]=m.useState([]),[vn,On]=m.useState(!1),[gn,Es]=m.useState(null),[Hn,as]=m.useState([]),[Tr,Vn]=m.useState(0),[ce,be]=m.useState(""),Ke=m.useRef(!1),qe=m.useRef(0),st=m.useRef(0),[ut,Tt]=m.useState(!1),[kt,Gt]=m.useState([]),[dt,Xt]=m.useState([]),[Bt,Ct]=m.useState({}),[pt,Ot]=m.useState(!1),[Ce,Vt]=m.useState(!1),[Et,ln]=m.useState(!1),[$t,ls]=m.useState([]),[cs,Ks]=m.useState([]),$s=m.useRef(0),fr=m.useRef(null);fr.current||(fr.current=new hw(g=>window.setTimeout(g,40),g=>ls(S=>S.concat(g))));const Ys=m.useRef(null);Ys.current||(Ys.current=new hw(g=>window.setTimeout(g,40),g=>Ks(S=>S.concat(g))));const ao=m.useRef({scanned:0,found:null}),[xe,Gn]=m.useState(null),[hn,lo]=m.useState(""),[Mi,Mr]=m.useState(!1),hr=m.useRef(null),[Hr,it]=m.useState({}),[rn,gs]=m.useState({}),[ci,us]=m.useState(!1),[co,uo]=m.useState(""),[Sa,Fn]=m.useState(!0),[mr,Rn]=m.useState(""),[_r,fo]=m.useState(!1),[Xn,Js]=m.useState(!1),[ds,Vr]=m.useState(6),[ys,ka]=m.useState("standard"),[ho,on]=m.useState(""),[El,Ri]=m.useState(""),[pr,As]=m.useState(!1),[Na,Rr]=m.useState(!1),[ui,Li]=m.useState("pause"),[Xs,Ts]=m.useState(""),[Lr,Zs]=m.useState(""),[Ii,gr]=m.useState(""),ws=m.useRef(null),Oi=m.useRef(null),[Uo,$l]=m.useState(!1),Qs=m.useRef(null),[Wo,Gr]=m.useState(""),[_c,yr]=m.useState(""),[mo,Fs]=m.useState(""),[qo,Ho]=m.useState(""),[Vo,_o]=m.useState(""),[U,ae]=m.useState(!1),[je,Ne]=m.useState("idle"),[ke,Be]=m.useState([]),[ft,ot]=m.useState(null),gt=m.useRef(null),[Ft,Kt]=m.useState(!1),[vs,Rt]=m.useState(""),[an,Nn]=m.useState(""),[mn,Zn]=m.useState(""),[er,Kr]=m.useState([]),[Pi,Ca]=m.useState(!1),[Jf,pc]=m.useState(""),[Al,gc]=m.useState(""),[yc,wc]=m.useState(!1),[Xf,Go]=m.useState(""),Hu=m.useMemo(()=>{if(!ke.length)return"";try{return JSON.stringify(ke.map(g=>({role:g.role,content:g.content,ts:g.ts})))}catch{return"1"}},[ke]),Vu=m.useMemo(()=>ke.length?mn?Hu!==mn:!0:!1,[Hu,ke.length,mn]),Gu=m.useMemo(()=>er.map(g=>{const S=String(g.title||"").trim()||`Chat ${String(g.thread_id||"").slice(0,8)}`,$=String(g.created_at||"").trim(),I=$?$.replace("T"," ").slice(0,19):"",q=String(g.run_id||"").trim()?String(g.run_id).slice(0,8):"",W=[S,I&&`(${I})`,q&&`run ${q}`].filter(Boolean).join(" • ");return{value:String(g.thread_id||""),label:W}}),[er]);m.useEffect(()=>{o&&yC()},[o]),m.useEffect(()=>{if(!o)return;const g=u.current;g&&(g.token=n.gateway_auth_mode==="direct"&&n.auth_token||"")},[o,n.auth_token,n.gateway_auth_mode]);const[Ku,Yu]=m.useState([]),[Ju,Xu]=m.useState({}),[c_,Zf]=m.useState({}),[vc,nn]=m.useState(""),[Zu,u_]=m.useState(""),[Qu,d_]=m.useState("all"),[ed,f_]=m.useState("status"),[Qn,Ir]=m.useState("overview"),Qf=gy(R_.md),xc=gy(`${R_.sm}, ${R_.short}`),Ko=o1({is_drawer:Qf,page:e}),bc=Ko.open,Ea=Ko.set_open,[eh,Di]=m.useState("runs"),h_=Ko.toggle_ref,m_=Ko.sidebar_ref,th=m.useRef(null),[$a,nh]=m.useState(!0),[Fi,Yo]=m.useState("steps"),[__,Tl]=m.useState(""),[td,jc]=m.useState(""),[Sc,Aa]=m.useState([]),[nd,sd]=m.useState(!1),[sh,kc]=m.useState(""),[rh,rd]=m.useState(""),[p_,id]=m.useState([]),[Yr,Ta]=m.useState(!1),[ih,Nc]=m.useState(""),[oh,Cc]=m.useState(!1),[od,g_]=m.useState(""),[y_,Jr]=m.useState(""),[Ec,po]=m.useState(""),[ad,Ml]=m.useState(!1),[zi,di]=m.useState(""),[go,Ma]=m.useState(null),[Jo,$c]=m.useState({}),[ld,Ra]=m.useState(!1),[cd,La]=m.useState(""),[Rl,yo]=m.useState(!1),[Ac,ud]=m.useState(!1),[w_,Tc]=m.useState(()=>Date.now()),[wr,Ia]=m.useState(""),[ah,Ll]=m.useState({}),[Cn,Il]=m.useState({}),wo=m.useRef([]),Ms=m.useRef(null),Bi=m.useRef(""),Oa=m.useRef({}),fi=m.useRef({}),Pa=m.useRef({}),hi=m.useRef(new Set),[mi,Mc]=m.useState([]),Ol=m.useRef(""),Xo=m.useRef({}),Xr=m.useRef(null),xs=m.useRef(null),Ui=m.useRef(0),vo=m.useRef({}),Da=m.useRef(!1),Wi=m.useRef(new Set),[dd,Pl]=m.useState(""),[_i,xo]=m.useState(""),Or=m.useRef(""),[qi,Rc]=m.useState(!1),[Fa,vr]=m.useState(""),za=()=>({artifact_id:"",kind:"binary",render_kind:"",text:"",url:"",loading:!1,error:""}),[xr,Lc]=m.useState("activity"),[fd,lh]=m.useState([]),[bo,Ba]=m.useState(0),[Ua,Dl]=m.useState(0),[hd,Zo]=m.useState({}),[jo,xn]=m.useState({}),[bn,Hi]=m.useState(!1),[Rs,zs]=m.useState(""),[Zr,Wa]=m.useState(""),[fs,qa]=m.useState("all"),[Fl,md]=m.useState(""),[Vi,ch]=m.useState([]),[Pr,Ic]=m.useState("all"),[So,uh]=m.useState("type"),[Oc,ko]=m.useState("newest"),[br,Qo]=m.useState(""),[No,Co]=m.useState(""),[jr,tr]=m.useState(""),[Qr,ei]=m.useState(0),[nr,Gi]=m.useState(()=>za()),[dh,zl]=m.useState(!1),[Pc,Sr]=m.useState(""),[kr,_n]=m.useState(""),[En,Bl]=m.useState(""),[Dc,_d]=m.useState("text"),[pd,Fc]=m.useState(null),[zc,Ul]=m.useState(!1),[ea,Ha]=m.useState(""),[fh,Va]=m.useState(""),[Bc,gd]=m.useState(""),[yd,ta]=m.useState(!1),[hh,Wl]=m.useState(""),[na,Ga]=m.useState("run_ledger"),[wd,vd]=m.useState(""),[xd,ql]=m.useState([]),[Ka,sr]=m.useState(""),[sa,Uc]=m.useState(!1),[mh,ti]=m.useState(""),Re=m.useMemo(()=>new np({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]),zn=m.useMemo(()=>new O1(Re.automations_client(),R1(Re,Os,jt)),[Re]),Wc=m.useSyncExternalStore(g=>zn.subscribe(g),()=>zn.state),pi=p1(n.gateway_url),gi=pi?()=>{window.open(pi,"_blank","noopener,noreferrer")}:void 0;m.useEffect(()=>{e==="launch"&&oe==="automate"&&N&&zn.load_email_status()},[e,oe,N,zn]),m.useEffect(()=>{const g=()=>{const S=y1(window.location.hash);S&&(S.page==="launch"&&he(S.mode),t(S.page))};return g(),window.addEventListener("hashchange",g),()=>window.removeEventListener("hashchange",g)},[]);const qc=m.useMemo(()=>{const g={};for(const S of Wc.items)g[S.automation_id]=S.title;return g},[Wc.items]),_h=m.useMemo(()=>aC(),[]),[Hc,bd]=m.useState([]),Ya=m.useRef(0);function yi(){const g=++Ya.current;bd([["Gateway","checking…"]]),lC(Re).then(S=>{g===Ya.current&&bd(S)})}const Eo=m.useMemo(()=>n.worker_url.trim()?new v2({url:n.worker_url.trim(),auth_token:n.worker_token}):null,[n.worker_url,n.worker_token]),es=$t.length?$t[$t.length-1].record:null,Wt=m.useMemo(()=>eo(es),[es]),hs=m.useMemo(()=>{const g=j.trim();if(!M||!g||String(M.bundle_id||"").trim()&&String(M.bundle_id||"").trim()!==g)return null;const S=Array.isArray(M.entrypoints)?M.entrypoints:[];if(!S.length)return null;const $=x.trim();if($)return S.find(q=>String(q.flow_id||"").trim()===$)||null;if(S.length===1)return S[0];const I=String(M.default_entrypoint||"").trim();return I&&S.find(q=>String(q.flow_id||"").trim()===I)||null},[M,j,x]),$o=m.useMemo(()=>{const g=hs==null?void 0:hs.inputs;return Array.isArray(g)?g:[]},[hs]),jd=m.useMemo(()=>AL(go),[go]),ra=m.useMemo(()=>$o.length?$o:jd,[$o,jd]),Ln=m.useMemo(()=>{const g=typeof(xe==null?void 0:xe.workflow_id)=="string"?String(xe.workflow_id):"",S=jv(g);if(S&&M&&String(M.bundle_id||"").trim()===S.bundle_id){const q=(Array.isArray(M.entrypoints)?M.entrypoints:[]).find(W=>String((W==null?void 0:W.flow_id)||"").trim()===S.flow_id);if(q&&q.node_index&&typeof q.node_index=="object")return q.node_index}const $=hs==null?void 0:hs.node_index;return $&&typeof $=="object"?$:{}},[xe,M,hs]);m.useEffect(()=>{IL(n)},[n]),m.useEffect(()=>()=>{Xr.current&&Xr.current.abort(),xs.current&&xs.current.abort(),ws.current&&window.clearTimeout(ws.current),Oi.current&&window.clearTimeout(Oi.current),Ms.current&&window.clearTimeout(Ms.current),Qs.current&&window.clearTimeout(Qs.current)},[]);const at=m.useMemo(()=>{const g=A.trim();if(!g)return{};try{const S=JSON.parse(g);return typeof S!="object"||S===null||Array.isArray(S)?null:S}catch{return null}},[A]),Sd=typeof(at==null?void 0:at.prompt)=="string"?String(at.prompt):"",Hl=typeof(at==null?void 0:at.provider)=="string"?String(at.provider):"",Vc=typeof(at==null?void 0:at.model)=="string"?String(at.model):"",kd=typeof(at==null?void 0:at.workspace_root)=="string"?String(at.workspace_root):"",Ao=typeof(at==null?void 0:at.workspace_access_mode)=="string"?String(at.workspace_access_mode):"",Pn=m.useMemo(()=>{const g=at==null?void 0:at.workspace_allowed_paths;return Array.isArray(g)?g.map(S=>String(S||"").trim()).filter(Boolean).join(`
|
|
141
|
-
`):typeof g=="string"?String(g):""},[at]),ts=m.useMemo(()=>{const g=at==null?void 0:at.workspace_ignored_paths;return Array.isArray(g)?g.map(S=>String(S||"").trim()).filter(Boolean).join(`
|
|
142
|
-
`):typeof g=="string"?String(g):""},[at]),ms=ra.length>0&&!!j.trim(),Ja=g=>{const S=String(g||"").trim().toLowerCase();return S==="object"||S==="memory"||S==="assertion"||S==="assertions"||S==="any"};m.useEffect(()=>{gs({})},[j,x]),m.useEffect(()=>{at!==null&&it(g=>{const S={};for(const $ of ra){if(!$||typeof $!="object")continue;const I=String($.id||"").trim();if(!I)continue;const q=String($.type||"").trim();if(!Ja(q))continue;if(String(rn[I]||"").trim()){S[I]=typeof g[I]=="string"?g[I]:"";continue}const V=at==null?void 0:at[I];V===void 0?S[I]="":S[I]=wC(V)}return S})},[ra,at,rn]);const wi=_e?{kind:"default",interface:_e}:j.trim()&&x.trim()?{kind:"bundle",bundle_id:j.trim(),flow_id:x.trim()}:null,Vl=d1(wi),vi=Array.isArray(at==null?void 0:at.skills)?at.skills.map(g=>String(g||"").trim()).filter(Boolean):[],jn=m.useMemo(()=>{const g={};for(const S of un){const $=String(S.workflow_id||"").trim(),I=String(S.label||"").trim();$&&I&&(g[$]=I)}return g},[un]),Gc=m.useMemo(()=>un.filter(g=>g.has_interface),[un]),Nd=m.useMemo(()=>{const g=new Set;for(const S of Array.isArray(dt)?dt:[]){const $=String((S==null?void 0:S.name)||"").trim();$&&g.add($)}return Array.from(g).sort()},[dt]),Cd=m.useMemo(()=>{const g=[];for(const S of Array.isArray(dt)?dt:[]){const $=String((S==null?void 0:S.name)||"").trim();if(!$)continue;const I=String((S==null?void 0:S.display_name)||"").trim();g.push({name:$,display_name:I||void 0})}return g},[dt]),xi=m.useMemo(()=>{const g=new Set;for(const S of kt||[]){if(!S||typeof S!="object")continue;const $=String(S.name||"").trim();$&&g.add($)}return Array.from(g).sort()},[kt]),Nr=m.useMemo(()=>{const g=n.maintenance_ai_provider.trim();if(!g)return{models:[],error:""};const S=Bt[g];return S?{models:(Array.isArray(S.models)?S.models:[]).map(I=>String(I||"").trim()).filter(Boolean),error:String(S.error||"")}:{models:[],error:""}},[Bt,n.maintenance_ai_provider]),ia=n.maintenance_ai_provider.trim(),Ed=!!(ia&&N&&!Object.prototype.hasOwnProperty.call(Bt,ia));m.useEffect(()=>{const g=Hl.trim();if(!g||Bt[g]||Xo.current[g])return;Xo.current[g]=!0;let S=!1;return(async()=>{try{const I=await Re.discovery_provider_models(g);if(S)return;const q=Array.isArray(I==null?void 0:I.models)?I.models:[],W=typeof(I==null?void 0:I.error)=="string"?String(I.error):"";Ct(V=>({...V,[g]:{models:q,error:W||void 0}}))}catch(I){if(S)return;Ct(q=>({...q,[g]:{models:[],error:String((I==null?void 0:I.message)||I||"Failed to load models")}}))}finally{delete Xo.current[g]}})(),()=>{S=!0}},[Hl,Bt,Re]),m.useEffect(()=>{const g=n.maintenance_ai_provider.trim();if(!g||!N||Bt[g]||Xo.current[g])return;Xo.current[g]=!0;let S=!1;return(async()=>{try{const I=await Re.discovery_provider_models(g);if(S)return;const q=Array.isArray(I==null?void 0:I.models)?I.models:[],W=typeof(I==null?void 0:I.error)=="string"?String(I.error):"";Ct(V=>({...V,[g]:{models:q,error:W||void 0}}))}catch(I){if(S)return;Ct(q=>({...q,[g]:{models:[],error:String((I==null?void 0:I.message)||I||"Failed to load models")}}))}finally{delete Xo.current[g]}})(),()=>{S=!0}},[n.maintenance_ai_provider,Bt,Re,N]);function $n(g,S){const $=String(g||"").trim();if(!$)return;let I={};try{const q=JSON.parse(A||"{}");typeof q=="object"&&q!==null&&!Array.isArray(q)&&(I=q)}catch{I={}}if(S==null){delete I[$],L(JSON.stringify(I,null,2));return}if(typeof S=="string")S?I[$]=S:delete I[$];else if(Array.isArray(S)){const q=S.map(W=>W).filter(W=>W!=null);q.length?I[$]=q:delete I[$]}else I[$]=S;L(JSON.stringify(I,null,2))}async function $d(g){const S=String(g||"").trim();if(!S)return re("Missing bundle_id"),null;re(""),Y(!0);try{const $=await Re.get_bundle(S);return H($),Zt({ts:jt(),kind:"info",title:`Loaded bundle ${S}`}),$}catch($){return H(null),re(String(($==null?void 0:$.message)||$||"Failed to load bundle")),null}finally{Y(!1)}}function Kc(g){const S=[],$=Array.isArray(g==null?void 0:g.items)?g.items:[];for(const I of $){const q=String((I==null?void 0:I.bundle_id)||"").trim();if(!q)continue;const W=Array.isArray(I==null?void 0:I.entrypoints)?I.entrypoints:[];if(W.length)for(const V of W){const te=String((V==null?void 0:V.flow_id)||"").trim();if(!te||(V==null?void 0:V.deprecated)===!0)continue;const $e=`${q}:${te}`,fe=String((V==null?void 0:V.name)||"").trim(),pe=fe?`${q} · ${fe}`:`${q} · ${te}`,Ae=String((V==null?void 0:V.description)||"").trim(),He=(Array.isArray(V==null?void 0:V.interfaces)?V.interfaces:[]).some(Ge=>String(Ge||"").trim().length>0),Ve=Array.isArray(V==null?void 0:V.agent_default_interfaces)?V.agent_default_interfaces.map(Ge=>String(Ge||"").trim()).filter(Boolean):[];S.push({workflow_id:$e,bundle_id:q,bundle_ref:String((I==null?void 0:I.bundle_ref)||"").trim(),flow_id:te,label:pe,description:Ae||void 0,has_interface:He,agent_default_interfaces:Ve})}}return S.sort((I,q)=>I.label.localeCompare(q.label)),S}async function Bs(g=Re,S){if(Ke.current&&!(S!=null&&S.force))return;Ke.current=!0;const $=Za.current;On(!0);try{const I=fe=>fe.map(S1).filter(pe=>!!pe.run_id),[q,W]=await Promise.all([g.list_runs({limit:200,root_only:!0,include_metrics:!0}),g.list_runs({limit:500,root_only:!1,include_metrics:!0})]);if($!==Za.current)return;const V=Array.isArray(q==null?void 0:q.items)?q.items:[],te=Array.isArray(W==null?void 0:W.items)?W.items:[],$e=I(V).filter(fe=>!String(fe.parent_run_id||"").trim()||fe.role==="occurrence");wn($e),Mn(I(te).filter(fe=>!!fe.run_id)),Es(Date.now()),st.current=0,qe.current=0}catch(I){const q=String((I==null?void 0:I.message)||I||"");if(Zt({ts:jt(),kind:"error",title:"Refresh runs failed",preview:ht(q)}),(/\b40[13]\b/.test(q)||/unauthorized|forbidden/i.test(q))&&D.refresh().catch(()=>{}),/\b429\b/.test(q)||/too many requests/i.test(q)){const W=Math.min(12e4,Math.max(15e3,st.current*2||15e3));st.current=W,qe.current=Date.now()+W,Zt({ts:jt(),kind:"info",title:`Gateway rate-limited — pausing polls ${Math.round(W/1e3)}s`})}}finally{Ke.current=!1,On(!1)}}async function Ad(g){var te,$e,fe;const S=Za.current;P(!0),Ct({});const[$,,I,q,W]=await Promise.allSettled([g.list_bundles(),Bs(g),g.discovery_tools(),g.discovery_providers({include_models:!1}),g.discovery_capabilities()]);if(S!==Za.current)return;if($.status==="rejected"&&I.status==="rejected"&&q.status==="rejected"){P(!1),C(Cp($.reason,n)),Zt({ts:jt(),kind:"error",title:"Discovery failed",preview:ht(String($.reason||""))});return}De(W.status==="fulfilled"?k1(W.value):{available:!1,reason:`Could not read the gateway capabilities: ${String(((te=W.reason)==null?void 0:te.message)||W.reason)}`});let V=0;if($.status==="fulfilled"){const pe=Kc($.value);V=pe.length,Wn(pe)}else Wn([]),Zt({ts:jt(),kind:"error",title:"Discovery bundles failed",preview:ht(String($.reason||""))});if(I.status==="fulfilled"){const pe=Array.isArray(($e=I.value)==null?void 0:$e.items)?I.value.items:[];Gt(pe)}else Gt([]),Zt({ts:jt(),kind:"error",title:"Discovery tools failed",preview:ht(String(I.reason||""))});if(q.status==="fulfilled"){const pe=Array.isArray((fe=q.value)==null?void 0:fe.items)?q.value.items:[];Xt(pe)}else Xt([]),Zt({ts:jt(),kind:"error",title:"Discovery providers failed",preview:ht(String(q.reason||""))});Zt({ts:jt(),kind:"info",title:"Gateway discovery loaded",preview:ht(`workflows: ${V}`)})}async function Xa(g){var S,$;C(""),P(!1),ue(!0);try{if(!(g!=null&&g.prefer_direct)&&(await D.refresh(),Yc.current))return;const I=String(n.auth_token||"").trim();if(!I){g!=null&&g.open_modal_if_needed&&D.openModal();return}const q=String(n.gateway_url||"").trim();if(q){const V=q.toLowerCase();if(!V.startsWith("http://")&&!V.startsWith("https://"))throw new Error("Gateway URL must start with http:// or https:// (or leave it blank to use same origin / dev proxy).");try{if(String(((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 $e=new URL(q),fe=String((($=window==null?void 0:window.location)==null?void 0:$.hostname)||"").trim().toLowerCase(),pe=String($e.hostname||"").trim().toLowerCase(),Ae=Oe=>Oe==="localhost"||Oe==="127.0.0.1"||Oe==="::1";if(Ae(pe)&&fe&&!Ae(fe))throw new Error("Gateway URL points to localhost, which from this device is not your machine. Use the gateway's public URL (e.g. an ngrok https URL) or leave Gateway URL blank to use same origin /api proxy.")}catch(te){throw new Error(String((te==null?void 0:te.message)||te||"Invalid Gateway URL"))}}const W=new np({base_url:q,auth_token:I});await W.list_bundles(),r(V=>({...V,gateway_auth_mode:"direct"})),await Ad(W)}catch(I){C(Cp(I,n))}finally{ue(!1)}}const Yc=m.useRef(!1),Za=m.useRef(0),Jc=m.useRef(!1);function Gl(g){var $,I,q;B(g);const S=!!(g&&g.has_session&&(($=g.gateway)!=null&&$.ok));if(Yc.current=S,S){if(Jc.current=!1,N&&n.gateway_auth_mode==="direct")return;const W=String(((q=(I=g==null?void 0:g.gateway)==null?void 0:I.principal)==null?void 0:q.user_id)||"").trim();if(r(V=>({...V,gateway_auth_mode:"session",auth_token:"",gateway_user:W||V.gateway_user})),N&&n.gateway_auth_mode==="session")return;C(""),ue(!0),Ad(new np({base_url:"",auth_token:""})).catch(V=>C(Cp(V,n))).finally(()=>ue(!1));return}g&&!g.has_session&&(n.gateway_auth_mode==="session"&&Qa({keep_session:!0}),String(n.auth_token||"").trim()&&!N&&!Jc.current&&(Jc.current=!0,Xa({prefer_direct:!0})))}async function ph(){if(!(ut||ie)){Tt(!0);try{await Re.reload_bundles();const g=await Re.list_bundles(),S=Kc(g);Wn(S),Zt({ts:jt(),kind:"info",title:"Bundles reloaded",preview:ht(`workflows: ${S.length}`)})}catch(g){const S=String((g==null?void 0:g.message)||g||"Bundle reload failed");Zt({ts:jt(),kind:"error",title:"Bundle reload failed",preview:ht(S),data:{error:S}})}finally{Tt(!1)}}}async function Xc(g){if(Mi||ie||!N)return;const S=g;if(S){Mr(!0),nn("");try{const $=await Re.upload_bundle(S,{overwrite:!1,reload:!0});Zt({ts:jt(),kind:"info",title:"Bundle uploaded",preview:ht(String(($==null?void 0:$.bundle_ref)||""))});const I=await Re.list_bundles(),q=Kc(I);Wn(q)}catch($){const I=String(($==null?void 0:$.message)||$||"Upload failed");nn(I),Zt({ts:jt(),kind:"error",title:"Upload .flow failed",preview:ht(I),data:{error:I}})}finally{Mr(!1);try{hr.current&&(hr.current.value="")}catch{}}}}function Qa(g){Za.current+=1,g!=null&&g.keep_session||(D.signOut().catch(()=>{}),Yc.current=!1),Dd(),E(""),k(""),di(""),H(null),re(""),Y(!1),Wn([]),wn([]),Mn([]),Es(null),as([]),Gt([]),Xt([]),Ct({}),C(""),P(!1),B(null),r(S=>({...S,auth_token:""})),Zt({ts:jt(),kind:"info",title:"Gateway disconnected"})}async function Zc(g){const S=String(g??"");if(S){try{await navigator.clipboard.writeText(S),An("Copied to clipboard",2);return}catch{}try{const $=document.createElement("textarea");$.value=S,$.style.position="fixed",$.style.left="-9999px",$.style.top="0",$.style.opacity="0",document.body.appendChild($),$.focus(),$.select(),document.execCommand("copy"),document.body.removeChild($),An("Copied to clipboard",2)}catch{An("Copy failed",2)}}}m.useEffect(()=>{const g=c.trim();if(!pt||!g)return;let S=!1;const $=async()=>{if(!(qe.current>Date.now()))try{const q=await Re.get_run(g);S||Gn(q)}catch{}};$();const I=window.setInterval($,2e3);return()=>{S=!0,window.clearInterval(I)}},[pt,c,Re]),m.useEffect(()=>{if(!N)return;let g=null,S=!1,$=!1;const I=V=>{S||(g!==null&&window.clearTimeout(g),g=window.setTimeout(()=>void q(),V))},q=async()=>{if($)return;const V=qe.current-Date.now();if(V>0){I(V+500);return}$=!0;const te=Date.now();try{await Bs(Re)}finally{$=!1;const $e=Date.now()-te,fe=document.visibilityState==="hidden"?3e4:5e3;I(Math.max(fe,$e*3))}},W=()=>{document.visibilityState==="visible"&&q()};return q(),document.addEventListener("visibilitychange",W),()=>{S=!0,g!==null&&window.clearTimeout(g),document.removeEventListener("visibilitychange",W)}},[N,Re]);const[Td,Qc]=m.useState(null);m.useEffect(()=>{if(!N){Qc(null);return}let g=!1;return(async()=>{try{const S=await Re.get_entity_phases_spec();if(g)return;const $=_L(S);if(Qc($),$)try{const I=localStorage.getItem("abstractobserver_phase_graph_id_v1"),q=I?JSON.parse(I):null;q&&q.sha256&&$.sha256&&q.sha256!==$.sha256&&q.version===$.version&&Zt({ts:jt(),kind:"error",title:"Phase-graph drift: served bytes changed without a version bump",preview:ht(`v${$.version}: ${String(q.sha256).slice(0,12)}… -> ${String($.sha256).slice(0,12)}…`),data:{prev:q,now:{sha256:$.sha256,version:$.version}}}),localStorage.setItem("abstractobserver_phase_graph_id_v1",JSON.stringify({sha256:$.sha256,version:$.version}))}catch{}}catch(S){if(!g){Qc(null);const $=String((S==null?void 0:S.message)||S||"");/404|not found/i.test($)||Zt({ts:jt(),kind:"info",title:"Phase-graph fetch failed — pre-wire fallback vocabulary in use (#FALLBACK)",preview:ht($),data:{error:$}})}}})(),()=>{g=!0}},[N]),m.useEffect(()=>{if(!N){as([]),be("");return}let g=!1,S=null;const $=async()=>{if(!(qe.current>Date.now())){try{const I=await Re.list_entities(),q=I.entities.map(V=>String((V==null?void 0:V.name)||(V==null?void 0:V.slug)||"").trim()).filter(Boolean).slice(0,12),W=await Promise.all(q.map(async V=>{var te,$e;try{const[fe,pe]=await Promise.all([Re.get_entity_card(V),Re.get_entity_cognition(V).catch(()=>null)]),Ae=fe!=null&&fe.state&&typeof fe.state=="object"?fe.state:null,Oe=Array.isArray(fe==null?void 0:fe.moments)?fe.moments:[],He=Oe.length?Oe[Oe.length-1]:null,Ve=(te=pe==null?void 0:pe.spend)==null?void 0:te.lifetime,Ge=($e=pe==null?void 0:pe.spend)==null?void 0:$e.live_visit,sn=Array.isArray(pe==null?void 0:pe.warnings)?pe.warnings.map(We=>String(We||"")).filter(Boolean):[],At=sL(fe);return{name:V,state:String((Ae==null?void 0:Ae.state)??(typeof(fe==null?void 0:fe.state)=="string"?fe.state:"")).trim(),age_days:typeof(fe==null?void 0:fe.age_days)=="number"?fe.age_days:null,last_moment:String((He==null?void 0:He.kind)||"").trim(),last_moment_at:String((He==null?void 0:He.at)||"").trim(),working:typeof(pe==null?void 0:pe.working)=="boolean"?pe.working:null,tokens_total:typeof(Ve==null?void 0:Ve.tokens_total)=="number"?Ve.tokens_total:null,live_visit_tokens:typeof(Ge==null?void 0:Ge.tokens_total)=="number"?Ge.tokens_total:null,spend_warning:sn.join(" | "),live_phase:typeof(pe==null?void 0:pe.phase)=="string"?pe.phase:"",open_questions:At.questions,open_questions_total:At.questions_total,open_problems:At.problems,open_problems_total:At.problems_total,lessons:At.lessons,lessons_total:At.lessons_total,dreams_brief:nL(fe),error:""}}catch(fe){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((fe==null?void 0:fe.message)||fe||"card failed")}}}));g||(as(W),Vn(I.entities.length),be(""))}catch(I){if(!g){as([]);const q=String((I==null?void 0:I.message)||I||"");be(/404|not found/i.test(q)?"":q)}}g||(S=window.setTimeout(()=>void $(),3e4))}};return $(),()=>{g=!0,S!==null&&window.clearTimeout(S)}},[N,Re]);async function gh(g,S,$){const I=String(S||"").trim();if(!g||!I)throw new Error("This wait has no wait_key yet — open the run to inspect.");await Re.submit_command({command_id:Os(),run_id:g,type:"resume",payload:{wait_key:I,payload:$||{}},client_id:"web_pwa"}),Zt({ts:jt(),kind:"info",title:"Board resume submitted",preview:ht(`run ${g} · wait ${I}`),data:{run_id:g,wait_key:I}}),Bs(Re,{force:!0}),window.setTimeout(()=>void Bs(Re,{force:!0}),1200)}const Dr=m.useMemo(()=>{const g=xe==null?void 0:xe.session_id;return typeof g=="string"?g.trim():g==null?"":String(g||"").trim()},[xe]),oa=m.useMemo(()=>{const g=String(Dr||"").trim();return g||String(O||"").trim()},[Dr,O]);m.useEffect(()=>{if(!N||!oa){_o(""),Ho("");return}(async()=>{try{const g=await kv(oa);_o(g)}catch{_o("")}})()},[N,oa]);const Bn=EL({gateway:N?Re:null,session_id:oa,run_id:Vo,on_error:Ho,on_transcript:g=>{const S=String(g||"").trim();S&&(yr($=>{const I=String($||"");return I.trim()?`${I.trimEnd()}
|
|
143
|
-
${S}`:S}),window.setTimeout(()=>{var $;return($=gt.current)==null?void 0:$.focus()},0))}});function Md(g,S){try{const $=URL.createObjectURL(g),I=document.createElement("a");I.href=$,I.download=S||"download",I.rel="noreferrer",document.body.appendChild(I),I.click(),document.body.removeChild(I),window.setTimeout(()=>URL.revokeObjectURL($),5e3)}catch{}}async function Rd(){if(!nd){if(!N||!Dr){jc(""),Aa([]),kc("");return}sd(!0),kc("");try{const g=await kv(Dr);jc(g);const S=await Re.list_run_artifacts(g,{limit:800}),I=(Array.isArray(S==null?void 0:S.items)?S.items:[]).filter(q=>{const W=q==null?void 0:q.tags;return W&&typeof W=="object"&&String(W.kind||"").trim()==="attachment"});Aa(I)}catch(g){const S=String((g==null?void 0:g.message)||g||"Failed to load session attachments"),$=S.toLowerCase();S.includes("404")||$.includes("session_memory_")&&$.includes("not found")||$.includes('"detail"')&&$.includes("not found")&&$.includes("session_memory_")?(Aa([]),kc("")):(Aa([]),kc(S)),jc("")}finally{sd(!1)}}}async function yh(){const g=rh.trim();if(!g){An("This run recorded no workspace folder",2);return}try{const S=await fetch(a1,{method:"POST",headers:{"Content-Type":"application/json",...sb()},body:JSON.stringify({path:g})}),$=await S.json().catch(()=>({}));S.ok&&($!=null&&$.ok)?An(`Opened ${String($.path||g)}`,2):An(String(($==null?void 0:$.error)||`Folder reveal failed (${S.status})`),3)}catch(S){An(String((S==null?void 0:S.message)||S||"Folder reveal failed"),3)}}async function v_(g){const S=String(td||"").trim();if(!S){An("No session attachment store yet",2);return}const $=String((g==null?void 0:g.artifact_id)||"").trim();if(!$)return;const I=g!=null&&g.tags&&typeof g.tags=="object"?g.tags:{},q=String(I.filename||"").trim(),W=String(I.path||"").trim(),V=q||(W?W.split("/").pop():"")||$,te=Z_(V);try{const $e=await Re.download_run_artifact_content(S,$,{access:"download"});Md($e,te),An("Downloaded attachment",2)}catch($e){An(String(($e==null?void 0:$e.message)||$e||"Download failed"),3)}}async function wh(g){const S=String(td||"").trim(),$=String((g==null?void 0:g.artifact_id)||"").trim();if(!S||!$)return;const I=g!=null&&g.tags&&typeof g.tags=="object"?g.tags:{},q=String(I.filename||"").trim(),W=String(I.path||"").trim(),V=W?`@${W}`:q||$,te=typeof(g==null?void 0:g.size_bytes)=="number"?Number(g.size_bytes):null,$e=String((g==null?void 0:g.content_type)||I.content_type||"").trim().toLowerCase();if(g_(V),Jr(""),po(""),Cc(!0),typeof te=="number"&&te>1e6){Jr(`(Attachment is ${te.toLocaleString()} bytes; download to view.)`);return}if(!(!$e||$e.startsWith("text/")||$e.includes("json")||$e.includes("yaml")||$e.includes("toml")||$e.includes("xml"))){Jr(`(Binary attachment: ${$e||"unknown"}; download to view.)`);return}Ml(!0);try{const Ae=await(await Re.download_run_artifact_content(S,$,{access:"download"})).text(),Oe=14e3,He=Ae.length>Oe?`${Ae.slice(0,Math.max(0,Oe-1))}…`:Ae;Jr(He)}catch(pe){po(String((pe==null?void 0:pe.message)||pe||"Preview failed"))}finally{Ml(!1)}}async function vh(g){const S=String((g==null?void 0:g.run_id)||"").trim(),$=String((g==null?void 0:g.artifact_id)||"").trim();if(!S||!$){An("Artifact download needs a run id",3);return}const I=Yp(g)||$;try{const q=await Re.download_run_artifact_content(S,$,{access:"preview"});Md(q,Z_(I)),An("Downloaded artifact",2)}catch(q){An(String((q==null?void 0:q.message)||q||"Download failed"),3)}}async function xh(g){const S=String((g==null?void 0:g.run_id)||"").trim(),$=String((g==null?void 0:g.artifact_id)||"").trim();if(!S||!$){An("Artifact preview needs a run id",3);return}const I=Yp(g),q=String((g==null?void 0:g.content_type)||"").trim().toLowerCase(),W=Ef(g);if(Sr(I||$),_n(""),Ha(""),_d(W),Fc(g),zl(!0),En&&(URL.revokeObjectURL(En),Bl("")),W==="binary"){_n(`(Binary artifact: ${q||"unknown"}; download to view.)`);return}if(W==="text"&&typeof g.size_bytes=="number"&&g.size_bytes>15e5){_n(`(Text artifact is ${g.size_bytes.toLocaleString()} bytes; download to view.)`);return}Ul(!0);try{const V=await Re.download_run_artifact_content(S,$,{access:"preview"});if(W==="text"){const te=await V.text(),$e=Rm(g,te),fe=$e==="json"?15e5:$e==="markdown"?25e4:$e==="html"?3e5:22e3;_n(te.length>fe&&$e!=="text"?`${sc(g.size_bytes??te.length)} ${$e.toUpperCase()} artifact. Download to inspect it.`:te.length>fe?`${te.slice(0,Math.max(0,fe-1))}…`:te)}else Bl(URL.createObjectURL(V))}catch(V){Ha(String((V==null?void 0:V.message)||V||"Preview failed"))}finally{Ul(!1)}}m.useEffect(()=>()=>{En&&URL.revokeObjectURL(En)},[En]);async function bh(g){const S=String(g.artifact_id||"").trim(),$=String(g.run_id||"").trim(),I=Ef(g);if(!$||!S)return{artifact_id:S,kind:I,render_kind:"",text:"Preview needs artifact run metadata.",url:"",loading:!1,error:""};if(I==="binary")return{artifact_id:S,kind:I,render_kind:"",text:`Preview unavailable for ${g.content_type||g.modality||"this artifact"}. Download to inspect it.`,url:"",loading:!1,error:""};if(I==="text"&&typeof g.size_bytes=="number"&&g.size_bytes>5e5)return{artifact_id:S,kind:I,render_kind:"",text:`${sc(g.size_bytes)} text artifact. Use Preview for a larger view or Download to inspect locally.`,url:"",loading:!1,error:""};try{const q=await Re.download_run_artifact_content($,S,{access:"preview"});if(I==="text"){const W=await q.text(),V=Rm(g,W),te=V==="json"?5e5:V==="markdown"?12e4:V==="html"?3e5:8e3;return{artifact_id:S,kind:I,render_kind:V,text:W.length>te&&V!=="text"?`${sc(g.size_bytes??W.length)} ${V.toUpperCase()} artifact. Use Larger preview or Download to inspect it.`:W.length>te?`${W.slice(0,Math.max(0,te-1))}…`:W,url:"",loading:!1,error:""}}return{artifact_id:S,kind:I,render_kind:"",text:"",url:URL.createObjectURL(q),loading:!1,error:""}}catch(q){return{artifact_id:S,kind:I,render_kind:"",text:"",url:"",loading:!1,error:String((q==null?void 0:q.message)||q||"Preview failed")}}}async function jh(g){if(nr.url&&URL.revokeObjectURL(nr.url),!g){Gi(za());return}const S=String(g.artifact_id||"").trim(),$=Ef(g);Gi({artifact_id:S,kind:$,render_kind:"",text:"",url:"",loading:!0,error:""}),Gi(await bh(g))}m.useEffect(()=>{Rd()},[Re,N,Dr]);function Zt(g){const S=String(g.id||"").trim()||Os();Yu($=>[{...g,id:S},...$].slice(0,800))}function An(g,S){gr(g),Oi.current&&window.clearTimeout(Oi.current),$l(!1),window.requestAnimationFrame(()=>$l(!0)),Oi.current=window.setTimeout(()=>{$l(!1),Oi.current=null},1500),ws.current&&(window.clearTimeout(ws.current),ws.current=null),S>0&&(ws.current=window.setTimeout(()=>{gr(""),ws.current=null},Math.max(1,S)*1e3))}function Cr(g,S){const $=String(g||"").trim(),I=String(S||"").trim();if(!I)return"";const q=$?String(Oa.current[$]||"").trim():"";return q?`${q}::${I}`:I}function Ld(g,S,$){const I=String(g||"").trim(),q=String(S||"").trim(),W=String($||"").trim();if(!I||!q||!W)return;const V=Cr(I,q);V&&(Oa.current[W]=V,fi.current[W]=I,Pa.current[W]={parent_run_id:I,parent_node_id:q},hi.current.has(W)||(hi.current.add(W),Mc(te=>te.includes(W)?te:[...te,W])))}function eu(g){const S=String(g||"").trim();if(!S)return;const $=Date.now(),I=Bi.current;Bi.current=S,Tc($),Ll(q=>{const W={};for(const[fe,pe]of Object.entries(q))typeof pe=="number"&&pe>$&&(W[fe]=pe);W[S]=Math.max(W[S]||0,$+2e3),I&&I!==S&&(W[I]=Math.max(W[I]||0,$+2e3));const V=Object.keys(W);if(V.length<=200)return W;const te=V.sort((fe,pe)=>(W[pe]||0)-(W[fe]||0)).slice(0,200),$e={};for(const fe of te)$e[fe]=W[fe]||0;return $e}),Il(q=>{if(typeof q[S]=="number")return q;const W={...q,[S]:$};if(wo.current.push(S),wo.current.length>8e3){const V=wo.current.splice(0,1500);for(const te of V)delete W[te]}return W}),Ms.current&&window.clearTimeout(Ms.current),Ms.current=window.setTimeout(()=>{const q=Date.now();Ll(W=>{const V={};for(const[te,$e]of Object.entries(W))typeof $e=="number"&&$e>q&&(V[te]=$e);return V}),Tc(q),Ms.current=null},2200)}function Fr(g,S){var Ge,sn,At;const $=String(S||"").trim()||c.trim();$s.current=g.cursor,(Ge=fr.current)==null||Ge.push({cursor:g.cursor,record:g.record}),$&&Wi.current.add(`${$}:${g.cursor}`);const I=tm(g.record),q=I&&I.name?jf(I.name):"",W=g.record,V=typeof(W==null?void 0:W.node_id)=="string"?W.node_id:"",te=typeof(W==null?void 0:W.status)=="string"?W.status:"",$e=typeof((sn=W==null?void 0:W.effect)==null?void 0:sn.type)=="string"?W.effect.type:"",fe=typeof(W==null?void 0:W.run_id)=="string"?W.run_id:"",pe=fe||$;if(q==="abstract.status"&&pe===$){const{text:We,duration:xt}=xu(I==null?void 0:I.payload);An(We,xt)}const Ae=V?Cr(pe,V):"";if(te==="waiting"){const We=eo(W);if(String((We==null?void 0:We.reason)||"").trim()==="subworkflow"){const Sn=typeof((At=We==null?void 0:We.details)==null?void 0:At.sub_run_id)=="string"?String(We.details.sub_run_id):"";Sn&&V&&Ld(pe,V,Sn)}}if(V&&(eu(Cr(pe,V)),te==="waiting"||te==="running")){const We=Cr(pe,V);We&&(Bi.current=We,Ia(We))}let Oe="step",He=Ae||V||"(node?)",Ve="";if(I&&I.name&&Np(I.name))Oe=q==="abstract.message"?"message":"event",He=q||I.name,Ve=ht(q==="abstract.steer_seen"?kp(I==null?void 0:I.payload):xu(I==null?void 0:I.payload).text);else if(W!=null&&W.error)Oe="error",He="error",Ve=ht(Ps(W.error,360));else if(te==="waiting"){const We=eo(W),xt=String((We==null?void 0:We.reason)||"").trim();Ve=ht(xt?`waiting • ${xt}`:"waiting")}else W!=null&&W.result?Ve=ht(Ps(W.result,360)):$e?Ve=ht($e):Ve=ht(wm(W));Zt({id:`step:${fe||$||"?"}:${g.cursor}`,ts:String((W==null?void 0:W.ended_at)||(W==null?void 0:W.started_at)||jt()),kind:Oe,title:He,preview:Ve,data:W,cursor:g.cursor,run_id:fe||$||void 0,node_id:Ae||V,status:te,effect_type:$e,emit_name:q||(I==null?void 0:I.name)||void 0})}function Id(g,S){var Ve,Ge,sn;Ui.current=Math.max(Ui.current,S.cursor);const $=`${g}:${S.cursor}`;if(!!Wi.current.has($))return;Wi.current.add($),(Ve=Ys.current)==null||Ve.push({run_id:g,cursor:S.cursor,record:S.record});const q=tm(S.record),W=q&&q.name?jf(q.name):"",V=S.record,te=typeof(V==null?void 0:V.node_id)=="string"?V.node_id:"",$e=te?Cr(g,te):"",fe=typeof(V==null?void 0:V.status)=="string"?V.status:"",pe=typeof((Ge=V==null?void 0:V.effect)==null?void 0:Ge.type)=="string"?V.effect.type:"";if(fe==="waiting"){const At=eo(V);if(String((At==null?void 0:At.reason)||"").trim()==="subworkflow"){const xt=typeof((sn=At==null?void 0:At.details)==null?void 0:sn.sub_run_id)=="string"?String(At.details.sub_run_id):"";xt&&te&&Ld(g,te,xt),xt&&Or.current.trim()===String(g||"").trim()&&(Or.current=xt,xo(xt))}}if(te&&(eu(Cr(g,te)),fe==="waiting"||fe==="running")){const At=Cr(g,te);At&&(Bi.current=At,Ia(At))}if((fe==="completed"||fe==="failed")&&Or.current.trim()===String(g||"").trim()){const At=String(fi.current[String(g||"").trim()]||"").trim();At&&At!==c.trim()?(Or.current=At,xo(At)):(Or.current="",xo(""))}if(W==="abstract.status"&&g===c.trim()){const{text:At,duration:We}=xu(q==null?void 0:q.payload);An(At,We)}let Ae="step",Oe=$e||te||"(node?)",He="";if(q&&q.name&&Np(q.name))Ae=W==="abstract.message"?"message":"event",Oe=`subrun • ${W||q.name}`,He=ht(W==="abstract.steer_seen"?kp(q==null?void 0:q.payload):xu(q==null?void 0:q.payload).text);else if(V!=null&&V.error)Ae="error",Oe="error",He=ht(Ps(V.error,360));else if(fe==="waiting"){const At=eo(V),We=String((At==null?void 0:At.reason)||"").trim();He=ht(We?`waiting • ${We}`:"waiting")}else V!=null&&V.result?He=ht(Ps(V.result,360)):pe?He=ht(pe):He=ht(wm(V));Zt({id:`step:${g}:${S.cursor}`,ts:String((V==null?void 0:V.ended_at)||(V==null?void 0:V.started_at)||jt()),kind:Ae,title:Oe,preview:He,data:V,cursor:S.cursor,run_id:g,node_id:$e||te,status:fe,effect_type:pe,emit_name:W||(q==null?void 0:q.name)||""})}function tu(g,S){var Ge,sn,At;const $=String(g||"").trim();if(!$)return;const I=`${$}:${S.cursor}`;if(!!Wi.current.has(I))return;Wi.current.add(I),(Ge=Ys.current)==null||Ge.push({run_id:$,cursor:S.cursor,record:S.record});const W=tm(S.record),V=W&&W.name?jf(W.name):"",te=S.record,$e=typeof(te==null?void 0:te.node_id)=="string"?te.node_id:"",fe=$e?Cr($,$e):"",pe=typeof(te==null?void 0:te.status)=="string"?te.status:"",Ae=typeof((sn=te==null?void 0:te.effect)==null?void 0:sn.type)=="string"?te.effect.type:"";if(pe==="waiting"){const We=eo(te);if(String((We==null?void 0:We.reason)||"").trim()==="subworkflow"){const Sn=typeof((At=We==null?void 0:We.details)==null?void 0:At.sub_run_id)=="string"?String(We.details.sub_run_id):"";Sn&&$e&&Ld($,$e,Sn)}}if($e&&(eu(Cr($,$e)),pe==="waiting"||pe==="running")){const We=Cr($,$e);We&&(Bi.current=We,Ia(We))}if(V==="abstract.status"&&$===c.trim()){const{text:We,duration:xt}=xu(W==null?void 0:W.payload);An(We,xt)}let Oe="step",He=fe||$e||"(node?)",Ve="";if(W&&W.name&&Np(W.name))Oe=V==="abstract.message"?"message":"event",He=`subrun • ${V||W.name}`,Ve=ht(V==="abstract.steer_seen"?kp(W==null?void 0:W.payload):xu(W==null?void 0:W.payload).text);else if(te!=null&&te.error)Oe="error",He="error",Ve=ht(Ps(te.error,360));else if(pe==="waiting"){const We=eo(te),xt=String((We==null?void 0:We.reason)||"").trim();Ve=ht(xt?`waiting • ${xt}`:"waiting")}else te!=null&&te.result?Ve=ht(Ps(te.result,360)):Ae?Ve=ht(Ae):Ve=ht(wm(te));Zt({id:`step:${$}:${S.cursor}`,ts:String((te==null?void 0:te.ended_at)||(te==null?void 0:te.started_at)||jt()),kind:Oe,title:He,preview:Ve,data:te,cursor:S.cursor,run_id:$,node_id:fe||$e,status:pe,effect_type:Ae,emit_name:V||(W==null?void 0:W.name)||""})}async function Od(g,S){var I,q;let $=S.after;for(;;){if((I=S.signal)!=null&&I.aborted)return $;const W=await Re.get_ledger(g,{after:$,limit:200,signal:S.signal});if((q=S.signal)!=null&&q.aborted)return $;const V=Array.isArray(W.items)?W.items:[];if(!V.length)return $s.current=$,$;const te=$;for(let $e=0;$e<V.length;$e++){const fe=V[$e];Fr({cursor:te+$e+1,record:fe},g)}$=typeof W.next_after=="number"?W.next_after:$}}async function el(g){var W,V,te,$e;const S=String(g||"").trim();nn(""),Vt(!0),Ot(!1),(W=fr.current)==null||W.reset(),(V=Ys.current)==null||V.reset(),ao.current={scanned:0,found:null},ls([]),$s.current=0,Ks([]),Wi.current=new Set,Yu([]),Xu({}),Zf({}),Yo("steps"),Tl(""),gr(""),Gn(null),Gr(""),rd(""),id([]),Nc(""),Ia(""),Bi.current="",Ll({}),Il({}),wo.current=[],Tc(Date.now()),Oa.current=S?{[S]:""}:{},fi.current={},Pa.current={},hi.current=new Set,Mc([]),Ol.current="",Or.current="",xo(""),vo.current={},Ms.current&&window.clearTimeout(Ms.current),Ms.current=null,Qs.current&&window.clearTimeout(Qs.current),Qs.current=null,Xr.current&&Xr.current.abort(),xs.current&&xs.current.abort(),xs.current=null,Ui.current=0,Pl("");const $=new AbortController;Xr.current=$;let I=!1;try{let fe="",pe="";try{const Ae=await Re.get_run(S);Gn(Ae);const Oe=typeof(Ae==null?void 0:Ae.workflow_id)=="string"?String(Ae.workflow_id):"",He=jv(Oe);He&&(fe=He.bundle_id,pe=He.flow_id)}catch{}try{const Ae=await Re.get_run_input_data(S);typeof(Ae==null?void 0:Ae.bundle_id)=="string"&&(fe=String(Ae.bundle_id||"").trim()||fe),typeof(Ae==null?void 0:Ae.flow_id)=="string"&&(pe=String(Ae.flow_id||"").trim()||pe);const Oe=Ae&&typeof Ae.input_data=="object"&&Ae.input_data&&!Array.isArray(Ae.input_data)?Ae.input_data:null;Oe&&L(JSON.stringify(Oe,null,2));const He=Ae==null?void 0:Ae.workspace,Ve=typeof(He==null?void 0:He.workspace_root)=="string"?String(He.workspace_root).trim():"";rd(Ve)}catch{rd("")}(async()=>{Ta(!0),Nc("");try{const Ae=await Re.list_run_artifacts(S,{limit:200}),Oe=Array.isArray(Ae==null?void 0:Ae.items)?Ae.items:[];$.signal.aborted||id(Oe)}catch(Ae){$.signal.aborted||(id([]),Nc(String((Ae==null?void 0:Ae.message)||Ae||"artifact listing failed")))}finally{$.signal.aborted||Ta(!1)}})(),fe&&pe&&(E(fe),k(pe),di(pe),await $d(fe)),await Od(S,{after:0,signal:$.signal});try{const Ae=await Re.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,Ve=(Oe&&typeof Oe=="object"?Object.keys(Oe):[]).map(Ge=>String(Ge||"").trim()).filter(Boolean).filter(Ge=>Ge!==S);if(Ve.length){for(const Ge of Ve)hi.current.add(Ge);Mc(Ge=>Array.from(new Set([...Ge,...Ve])));try{const Ge=typeof((te=Oe==null?void 0:Oe[S])==null?void 0:te.total)=="number"?Number(Oe[S].total):0;let sn="",At=-1;for(const We of Ve){const xt=typeof(($e=Oe==null?void 0:Oe[We])==null?void 0:$e.total)=="number"?Number(Oe[We].total):0;xt>At&&(sn=We,At=xt)}sn&&At>Math.max(Ge*3,Ge+20)&&(Or.current=sn,xo(sn))}catch{}}}catch{}Ot(!0),Zt({ts:jt(),kind:"info",title:`Attached to run ${S}`,data:{run_id:S}}),I=!0}catch(fe){const pe=String((fe==null?void 0:fe.message)||fe||"unknown error");nn(pe),Zt({ts:jt(),kind:"error",title:"Connection error",preview:ht(pe),data:{error:pe}}),Ot(!1)}finally{Vt(!1)}if(!I||$.signal.aborted)return;(async()=>{let fe=250;for(;!$.signal.aborted;){try{const pe=await Od(S,{after:$s.current,signal:$.signal});await Re.stream_ledger(S,{after:pe,on_step:Ae=>Fr(Ae,S),signal:$.signal})}catch(pe){if($.signal.aborted)break;const Ae=String((pe==null?void 0:pe.message)||pe||"stream error");Zt({ts:jt(),kind:"error",title:"Ledger stream error (will retry)",preview:ht(Ae),data:{error:Ae}})}if($.signal.aborted)break;await new Promise(pe=>setTimeout(pe,fe)),fe=Math.min(5e3,Math.floor(fe*1.6))}})()}async function Sh(){const g=wi,S=(g==null?void 0:g.kind)==="bundle"?g.flow_id:(g==null?void 0:g.kind)==="default"?"@default":"",$=(g==null?void 0:g.kind)==="bundle"?g.bundle_id:"";if(!g){const I="Select a workflow first (Launch → pick a workflow).";return nn(I),I}nn(""),Vt(!0);try{let I={};const q=A.trim();if(q)try{if(I=JSON.parse(q),typeof I!="object"||I===null||Array.isArray(I))throw new Error("input_data must be a JSON object")}catch(pe){const Ae=`Invalid input_data JSON: ${String((pe==null?void 0:pe.message)||pe)}`;return nn(Ae),Ae}for(const[pe,Ae]of Object.entries(I)){if(typeof Ae!="string")continue;const Oe=Ae.trim();Oe?I[pe]=Oe:delete I[pe]}const W=(ra||[]).find(pe=>pe&&typeof pe=="object"&&pe.id==="prompt"),V=W&&typeof W=="object"&&Object.prototype.hasOwnProperty.call(W,"default"),te=I==null?void 0:I.prompt,$e=typeof te=="string"?te.trim():"";if(W&&!V&&!$e){const pe="Missing required input_data.prompt";return nn(pe),pe}const fe=await Re.start_run(S,I,{...$?{bundle_id:$}:{},...g.kind==="default"?{interface:g.interface}:{},session_id:String(O||"").trim()||null});return p(fe),f(fe),lo(""),await el(fe),Bs(),null}catch(I){const q=String((I==null?void 0:I.message)||I||"start failed");return nn(q),q}finally{Vt(!1)}}async function Pd(){if(_t([]),et(null),!ge.available){_t([ge.reason]);return}const g=j1(Ee,{choice:wi,bundle_ref_for:S=>{var $;return(($=un.find(I=>I.bundle_id===S))==null?void 0:$.bundle_ref)||""},input_data:at,email_usable:zn.email_usable},ct.current);if(!g.ok){_t(g.errors);return}Je(!0);try{const S=await Re.automations_client().createAutomation(g.body);ct.current.reset(),Ie([]),ze(Vp),Zt({ts:jt(),kind:"info",title:"Automation created",preview:ht(`${g.body.title} · ${S.automation_id}`)}),t("automations"),await zn.refresh(),await zn.select(S.automation_id)}catch(S){const $=(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")};et($)}finally{Je(!1)}}async function tl(){if(lo(""),oe==="automate"){await Pd();return}const g=await Sh();if(g){lo(g);return}Ir("overview"),t("observe")}async function nu(g){if($n("skills",void 0),!!g){if(g.kind==="default"){we(g.interface),E(""),k(""),H(null);return}we(""),E(g.bundle_id),k(g.flow_id),di(g.flow_id),await $d(g.bundle_id)}}async function su(g){const[S,$]=await Promise.all([Re.get_run(g),Re.get_run_input_data(g)]),I=T1(S,$);await nu(I.choice),L(JSON.stringify(I.input_data,null,2)),ze(I.form),Ie([`Recreating the legacy schedule ${Lt(g,14)} as an automation. The legacy schedule keeps running until you suspend it.`,...I.notes]),ct.current.reset(),he("automate"),t("launch")}async function aa(g,S){const $=String(g||"").trim();if(!$)return;if(Ce){An(`Still attaching — retry in a moment (${Lt($,14)})`,2500);return}nn("");const I=String((S==null?void 0:S.root_run_id)||$).trim()||$;p(I),f($),await el($)}m.useEffect(()=>{const g=String(y||"").trim();if(!g)return;let S=!1;return(async()=>{try{if(N||await Xa({open_modal_if_needed:!0}),S)return;Ir("overview"),t("observe"),await aa(g)}catch($){S||nn(String(($==null?void 0:$.message)||$||"Failed to attach run from URL"))}finally{S||w("")}})(),()=>{S=!0}},[y]);function Dd(){var g,S;Xr.current&&Xr.current.abort(),Xr.current=null,xs.current&&xs.current.abort(),xs.current=null,Ui.current=0,Pl(""),f(""),p(""),Oa.current={},fi.current={},Pa.current={},hi.current=new Set,Mc([]),Ol.current="",Or.current="",xo(""),vo.current={},Gr(""),Ms.current&&window.clearTimeout(Ms.current),Ms.current=null,Qs.current&&window.clearTimeout(Qs.current),Qs.current=null,Ot(!1),Vt(!1),ln(!1),$s.current=0,(g=fr.current)==null||g.reset(),(S=Ys.current)==null||S.reset(),ao.current={scanned:0,found:null},ls([]),Ks([]),Wi.current=new Set,Gn(null),Yu([]),Xu({}),Ia(""),Bi.current="",Ll({}),Il({}),wo.current=[],Tc(Date.now()),An("",-1),nn(""),Rc(!1),vr(""),Be([]),ot(null),yr(""),Fs(""),ae(!1),Kt(!1),Rt(""),Nn(""),Zn(""),Kr([]),Ca(!1),pc(""),gc(""),wc(!1),Go("")}m.useEffect(()=>{Be([]),ot(null),yr(""),Fs(""),ae(!1),Kt(!1),Rt(""),Nn(""),Zn(""),Kr([]),Ca(!1),pc(""),gc(""),wc(!1),Go("")},[c]),m.useEffect(()=>{Qn==="chat"&&c.trim()&&N&&ru()},[Qn,c,N,xe==null?void 0:xe.workflow_id]);async function Fd(g,S,$){const I=String(g||"").trim();if(!I)return nn("Missing run_id"),"Missing run_id";nn("");try{const q={},W=String(($==null?void 0:$.reason)||"").trim();W&&(q.reason=W),await Re.submit_command({command_id:Os(),run_id:I,type:S,payload:q,client_id:"web_pwa"}),Zt({ts:jt(),kind:"info",title:`${S} submitted`,preview:W?`reason: ${W}`:"",data:{run_id:I,type:S,reason:W}});try{if(I===c.trim()){const V=await Re.get_run(I);Gn(V)}}catch{}return Bs(Re,{force:!0}),window.setTimeout(()=>void Bs(Re,{force:!0}),900),window.setTimeout(()=>void Bs(Re,{force:!0}),2400),null}catch(q){const W=String((q==null?void 0:q.message)||q||`${S} failed`);return nn(W),W}}async function zd(g,S){return Fd(c.trim(),g,S)}async function Bd(g,S="Stopped from AbstractObserver"){const $=String(g||"").trim();if(!$||!window.confirm(`Cancel run ${Lt($,24)}?`))return;await Fd($,"cancel",{reason:S})||An("Cancel submitted",2)}async function kh(){var $;const g=c.trim();if(!g){nn("Select a run first.");return}if(!N){nn("Connect to the gateway first.");return}if(Et)return;const S=String((($=xe==null?void 0:xe.waiting)==null?void 0:$.reason)||"").trim().toLowerCase()||String(ns||"").trim().toLowerCase();if(!ir||ji||si||bi.toLowerCase()!=="waiting"||S!=="until"){nn("This run is not a scheduled wait that can be triggered now.");return}nn(""),ln(!0);try{const I={payload:{mode:"run_now",requested_at:jt()}},q=String(bs||"").trim();q&&(I.wait_key=q),await Re.submit_command({command_id:Os(),run_id:g,type:"resume",payload:I,client_id:"web_pwa"}),Zt({ts:jt(),kind:"info",title:"Scheduled run triggered",preview:ht(`run ${g}`),data:{run_id:g,until:ni||null}});try{const W=await Re.get_run(g);Gn(W)}catch{}}catch(I){nn(String((I==null?void 0:I.message)||I||"Failed to trigger scheduled run"))}finally{ln(!1)}}async function x_(g){const S=c.trim();if(!S)return nn("Missing run_id"),"Missing run_id";if(_r)return"Schedule update already in progress";const $=String(g.interval||"").trim();if(!/^\s*(\d+(?:\.\d+)?)\s*(ms|s|m|h|d)\s*$/i.test($)){const q="Invalid interval (expected like '20m', '1h', '0.5s', '250ms')";return Rn(q),q}Rn(""),nn(""),fo(!0),Vt(!0);try{await Re.submit_command({command_id:Os(),run_id:S,type:"update_schedule",payload:{interval:$,apply_immediately:g.apply_immediately!==!1},client_id:"web_pwa"}),Zt({ts:jt(),kind:"info",title:"Schedule updated",preview:ht(`interval: ${$}`),data:{interval:$},run_id:S});try{const q=await Re.get_run(S);Gn(q)}catch{}return null}catch(q){const W=String((q==null?void 0:q.message)||q||"update_schedule failed");return Rn(W),nn(W),W}finally{Vt(!1),fo(!1)}}async function rr(g){const S=c.trim();if(!S)return nn("Missing run_id"),"Missing run_id";if(pr)return"Compaction already in progress";const $=typeof(g==null?void 0:g.preserve_recent)=="number"?g.preserve_recent:ds,I=Math.max(0,Math.min(500,Math.floor(Number.isFinite($)?$:6))),q=(g==null?void 0:g.compression_mode)||ys,W=String((g==null?void 0:g.focus)??ho??"").trim();Ri(""),nn(""),As(!0),Vt(!0);try{const V={preserve_recent:I,compression_mode:q};return W&&(V.focus=W),await Re.submit_command({command_id:Os(),run_id:S,type:"compact_memory",payload:V,client_id:"web_pwa"}),Zt({ts:jt(),kind:"info",title:"Compaction requested",preview:ht(`mode: ${q} • preserve_recent: ${I}`),data:V,run_id:S}),null}catch(V){const te=String((V==null?void 0:V.message)||V||"compact_memory failed");return Ri(te),nn(te),te}finally{Vt(!1),As(!1)}}async function Us(){const g=c.trim();if(!g){vr("Missing run_id");return}if(!qi){vr(""),Rc(!0);try{const S=n.maintenance_ai_provider.trim(),$=n.maintenance_ai_model.trim();await Re.generate_run_summary(g,{provider:S||void 0,model:$||void 0,include_subruns:!0}),Zt({ts:jt(),kind:"info",title:"Summary generation requested",preview:ht(`run ${g}`)})}catch(S){vr(String((S==null?void 0:S.message)||S||"Failed to generate summary"))}finally{Rc(!1)}}}async function Nh(){const g=c.trim();if(!g){Fs("Select a run first.");return}if(!N){Fs("Connect to the gateway first.");return}const S=_c.trim();if(!S||U)return;if(Bn.voice_ptt_busy){Ho("Wait for transcription to finish.");return}Fs(""),Ho(""),ae(!0);const I={id:`local:${Os()}`,role:"user",content:S,ts:jt()};Be(q=>[...q,I]),yr("");try{const q=qN(ke,I),W=n.maintenance_ai_provider.trim(),V=n.maintenance_ai_model.trim(),te=await Re.run_chat(g,{provider:W||void 0,model:V||void 0,include_subruns:!0,messages:q}),$e=String((te==null?void 0:te.answer)||"").trim()||"(empty response)",fe=String((te==null?void 0:te.generated_at)||"").trim()||jt();ot((te==null?void 0:te.history)??null),Be(pe=>[...pe,{id:`local:${Os()}`,role:"assistant",content:$e,ts:fe}])}catch(q){const W=bC(q);Fs(W),Be(V=>[...V,{id:`local:${Os()}`,role:"assistant",content:`(error: ${W})`,ts:jt(),local_error:!0}])}finally{ae(!1)}}function Ch(g){const S=String(g.id||g.ts||"").trim(),$=String(g.content||"").trim();!S||!$||(Ho(""),Bn.toggle_tts(S,$))}function Eh(g){const S=String(g.id||g.ts||"").trim(),$=Bn.tts_playback;return!S||!$.key||$.key!==S?"idle":$.status}function Ud(g){if(!ke.length)return;const S=c.trim(),$=S?`Run ${S}`:"Chat",I=wk(ke.map(q=>({role:q.role,content:q.content,ts:q.ts})),{heading:$});if(g==="download"){const q=new Date().toISOString().slice(0,19).replace(/[:T]/g,"-"),W=`abstractobserver-chat-${Z_(S||"run")}-${q}.md`;vk({filename:W,text:I,mime:"text/markdown;charset=utf-8"});return}(async()=>{const q=await dc(I);Ne(q?"copied":"failed"),window.setTimeout(()=>Ne("idle"),900)})()}async function ru(){const g=typeof(xe==null?void 0:xe.workflow_id)=="string"?String(xe.workflow_id).trim():"";if(!g){Kr([]);return}if(N&&!Pi){pc(""),Ca(!0);try{const S=await Re.list_runs({limit:200,workflow_id:g,root_only:!0}),$=Array.isArray(S==null?void 0:S.items)?S.items:[],I=[];for(const fe of $){const pe=typeof(fe==null?void 0:fe.run_id)=="string"?String(fe.run_id).trim():"";if(!pe)continue;const Ae=typeof(fe==null?void 0:fe.ledger_len)=="number"?Number(fe.ledger_len):0;I.push({run_id:pe,ledger_len:Number.isFinite(Ae)?Ae:0})}if(!I.length){Kr([]);return}const q=400,W=I.map(fe=>({run_id:fe.run_id,after:Math.max(0,(fe.ledger_len||0)-q)})),V=await Re.get_ledger_batch({runs:W,limit:q}),te=[],$e=new Set;for(const fe of I){const pe=V!=null&&V.runs&&typeof V.runs=="object"?V.runs[fe.run_id]:null,Ae=Array.isArray(pe==null?void 0:pe.items)?pe.items:[];for(const Oe of Ae){const He=Oe==null?void 0:Oe.effect;if(!He||typeof He!="object"||String(He.type||"")!=="emit_event")continue;const Ve=He.payload;if(!Ve||typeof Ve!="object"||String(Ve.name||"")!=="abstract.chat.thread")continue;const Ge=Ve.payload;if(!Ge||typeof Ge!="object")continue;const sn=typeof Ge.thread_id=="string"?String(Ge.thread_id).trim():"";if(!sn||$e.has(sn))continue;$e.add(sn);const At=typeof Ge.created_at=="string"?String(Ge.created_at):"",We=typeof Ge.title=="string"?String(Ge.title):"",xt=typeof Ge.workflow_id=="string"?String(Ge.workflow_id):g,Sn=typeof Ge.run_id=="string"?String(Ge.run_id):fe.run_id,Tn=typeof Ge.provider=="string"?String(Ge.provider):"",Ws=typeof Ge.model=="string"?String(Ge.model):"",qs=typeof Ge.message_count=="number"?Number(Ge.message_count):null,lr=Ge.chat_artifact,fl=lr&&typeof lr=="object"&&typeof lr.$artifact=="string"?String(lr.$artifact):"";fl&&te.push({thread_id:sn,created_at:At,title:We||`Chat ${sn.slice(0,8)}`,run_id:Sn,workflow_id:xt,message_count:qs,provider:Tn,model:Ws,artifact_id:fl})}}te.sort((fe,pe)=>String(pe.created_at||"").localeCompare(String(fe.created_at||""))),Kr(te)}catch(S){pc(String((S==null?void 0:S.message)||S||"Failed to load saved discussions"))}finally{Ca(!1)}}}async function Wd(){const g=c.trim();if(!g){Rt("Select a run first.");return}if(!N){Rt("Connect to the gateway first.");return}if(ke.length&&!Ft){Rt(""),Kt(!0);try{const S=n.maintenance_ai_provider.trim(),$=n.maintenance_ai_model.trim(),I=await Re.save_chat_thread(g,{provider:S||void 0,model:$||void 0,include_subruns:!0,messages:ke.map(V=>({role:V.role,content:V.content,ts:V.ts}))}),q=typeof(I==null?void 0:I.created_at)=="string"?String(I.created_at):jt();Nn(q);try{const V=JSON.stringify(ke.map(te=>({role:te.role,content:te.content,ts:te.ts})));Zn(V)}catch{Zn("1")}typeof(I==null?void 0:I.thread_id)=="string"&&String(I.thread_id).trim()&&gc(String(I.thread_id).trim());const W=!!(I!=null&&I.duplicate);An(W?"Already saved":"Saved discussion",2),await ru()}catch(S){Rt(String((S==null?void 0:S.message)||S||"Failed to save discussion"))}finally{Kt(!1)}}}async function $h(){const g=String(Al||"").trim();if(!g)return;const S=er.find(q=>String(q.thread_id||"").trim()===g)||null;if(!S){Go("Saved discussion not found (refresh list).");return}if(!N){Go("Connect to the gateway first.");return}if(yc)return;const $=ke.length>0,I=(()=>{if(!$)return!1;if(!mn)return!0;try{return JSON.stringify(ke.map(W=>({role:W.role,content:W.content,ts:W.ts})))!==mn}catch{return!0}})();if(!($&&I&&!window.confirm("Replace the current chat with the selected saved discussion? Unsaved changes will be lost."))){Go(""),wc(!0);try{const W=await(await Re.download_run_artifact_content(S.run_id,S.artifact_id)).text(),V=JSON.parse(W),te=Array.isArray(V==null?void 0:V.messages)?V.messages:[],$e=typeof(V==null?void 0:V.created_at)=="string"?String(V.created_at):String(S.created_at||""),fe=[];for(let pe=0;pe<te.length;pe++){const Ae=te[pe];if(!Ae||typeof Ae!="object")continue;const Oe=String(Ae.role||"").trim()==="assistant"?"assistant":"user",He=typeof Ae.content=="string"?String(Ae.content):"";if(!He.trim())continue;const Ve=typeof Ae.ts=="string"?String(Ae.ts):$e||jt();fe.push({id:`thread:${g}:${pe}`,role:Oe,content:He.trim(),ts:Ve})}Be(fe),ot(null),yr(""),Fs(""),Rt(""),Nn($e||"");try{const pe=JSON.stringify(fe.map(Ae=>({role:Ae.role,content:Ae.content,ts:Ae.ts})));Zn(pe)}catch{Zn("1")}An("Loaded discussion",2)}catch(q){Go(String((q==null?void 0:q.message)||q||"Failed to load saved discussion"))}finally{wc(!1)}}}async function nl(g){const S=c.trim(),$=String((Wt==null?void 0:Wt.wait_key)||"").trim();if(!S||!$){nn("No active wait to resume");return}if(String((Wt==null?void 0:Wt.reason)||"").trim()==="subworkflow"){nn("This run is waiting on a subworkflow; attach to the child run instead of resuming manually.");return}nn(""),ln(!0);try{await Re.submit_command({command_id:Os(),run_id:S,type:"resume",payload:{wait_key:$,payload:g||{}},client_id:"web_pwa"}),Zt({ts:jt(),kind:"info",title:"Resume submitted",preview:ht(`wait_key: ${$}`),data:{wait_key:$,payload:g||{}}}),Gr($);try{const I=await Re.get_run(S);Gn(I)}catch{}Bs(Re,{force:!0}),window.setTimeout(()=>void Bs(Re,{force:!0}),900),window.setTimeout(()=>void Bs(Re,{force:!0}),2400),Qs.current&&window.clearTimeout(Qs.current),Qs.current=window.setTimeout(()=>{Gr(I=>I===$?"":I)},2e3)}catch(I){nn(String((I==null?void 0:I.message)||I||"resume failed"))}finally{ln(!1)}}async function Ah(g){if(!Eo){nn("No worker configured");return}if(!Et){nn(""),ln(!0);try{const S=[];for(const $ of g){const I=await Eo.call_tool($);S.push(I)}await nl({mode:"executed",results:S})}finally{ln(!1)}}}const To=m.useMemo(()=>Wu(Wt),[Wt]),bs=String((Wt==null?void 0:Wt.wait_key)||"").trim(),ns=String((Wt==null?void 0:Wt.reason)||"").trim(),ni=typeof(Wt==null?void 0:Wt.until)=="string"?String(Wt.until):"",bi=typeof(xe==null?void 0:xe.status)=="string"?String(xe.status):"",si=!!(xe!=null&&xe.paused),ji=bi==="completed"||bi==="failed"||bi==="cancelled",Th=ns==="until"&&!!ni,sl=!ji&&YC(es)&&(!!bs||Th),Mh=ns==="user",rl=ns==="event"?jf($L(bs)):"",Ki=ns==="event"&&rl==="abstract.ask",b_=To.length>0,qd=sl&&bs&&(Mh||Ki||b_)&&Wo!==bs&&e!=="board",Yi=typeof((tf=Wt==null?void 0:Wt.details)==null?void 0:tf.sub_run_id)=="string"?String(Wt.details.sub_run_id):"",il={run_id:c.trim(),workflow_id:typeof(xe==null?void 0:xe.workflow_id)=="string"?String(xe.workflow_id):null,status:bi,created_at:typeof(xe==null?void 0:xe.created_at)=="string"?String(xe.created_at):null,updated_at:typeof(xe==null?void 0:xe.updated_at)=="string"?String(xe.updated_at):null,session_id:typeof(xe==null?void 0:xe.session_id)=="string"?String(xe.session_id):null,current_node:typeof(xe==null?void 0:xe.current_node)=="string"?String(xe.current_node):null},Hd=$t.slice(-10).map(g=>{var S,$,I,q,W,V;return{cursor:g.cursor,node_id:String(((S=g.record)==null?void 0:S.node_id)||"").trim(),status:String((($=g.record)==null?void 0:$.status)||"").trim(),effect_type:String(((q=(I=g.record)==null?void 0:I.effect)==null?void 0:q.type)||"").trim(),ts:String(((W=g.record)==null?void 0:W.ended_at)||((V=g.record)==null?void 0:V.started_at)||"").trim(),summary:Xx(g.record)}}),ol=Og(Wt,To),Ls=Gx(Wt,To),Rh=Kx(Wt,at),al=Rh.text,iu=Rh.runtime_metadata,ss=String((Wt==null?void 0:Wt.prompt)||"").trim(),Lh=LC(at,6),Qe=!!(ss&&qx(ss)),Mo=!!(ss&&!Qe),Vd=Mo?"Question from workflow":al&&al!==ss?"Closest prior user request":"Request context",Ih=PC(at,A),j_=!!A.trim(),js=xe!=null&&xe.schedule&&typeof xe.schedule=="object"?xe.schedule:null,Ji=typeof(js==null?void 0:js.interval)=="string"?String(js.interval).trim():"",Gd=typeof(js==null?void 0:js.share_context)=="boolean"?!!js.share_context:null,Kd=typeof(js==null?void 0:js.repeat_count)=="number"?Number(js.repeat_count):null,ir=!!(xe!=null&&xe.is_scheduled)||!!js,ou=ir&&!!Ji,au=ir?si?"Resume schedule":"Suspend schedule":bi==="running"&&!si?"Pause":"Resume",lu=ir?si?"resume":"pause":au==="Pause"?"pause":"resume",Ss=ir?!c.trim()||Ce||Et||ji:!c.trim()||Ce||Et||ji||lu==="resume"&&!si,ri=ir&&!si&&!ji&&!Ce&&!Et&&bi.toLowerCase()==="waiting"&&(String(((gu=xe==null?void 0:xe.waiting)==null?void 0:gu.reason)||"").trim().toLowerCase()==="until"||ns==="until")&&!!String(ni||"").trim(),Kn=(Xl=xe==null?void 0:xe.limits)==null?void 0:Xl.tokens,ll=typeof(Kn==null?void 0:Kn.pct)=="number"?Number(Kn.pct):null,Yd=Kn==null?void 0:Kn.estimated_used,zr=(Kn==null?void 0:Kn.max_input_tokens)??(Kn==null?void 0:Kn.max_tokens),Oh=m.useMemo(()=>{const g=ao.current;$t.length<g.scanned&&(g.scanned=0,g.found=null);for(let S=g.scanned;S<$t.length;S++){const $=$t[S],I=$==null?void 0:$.record;if(!I)continue;const q=tm(I);if((q&&q.name?jf(q.name):"")!=="abstract.summary")continue;const V=q!=null&&q.payload&&typeof q.payload=="object"?q.payload:{},te=typeof(V==null?void 0:V.text)=="string"?String(V.text):"";te.trim()&&(g.found={cursor:$.cursor,ts:String((I==null?void 0:I.ended_at)||(I==null?void 0:I.started_at)||""),text:te,provider:typeof(V==null?void 0:V.provider)=="string"?String(V.provider):void 0,model:typeof(V==null?void 0:V.model)=="string"?String(V.model):void 0,generated_at:typeof(V==null?void 0:V.generated_at)=="string"?String(V.generated_at):void 0,source:V==null?void 0:V.source})}return g.scanned=$t.length,g.found},[$t]);m.useEffect(()=>{Or.current=_i.trim()},[_i]),m.useEffect(()=>{const g=c.trim(),S=Yi.trim();if(!(pt&&ns==="subworkflow"&&!!S&&S!==g)){Ol.current="",_i.trim()&&xo("");return}Ol.current!==S&&(Ol.current=S,Or.current=S,xo(S))},[pt,c,ns,Yi,_i]),m.useEffect(()=>{$c({})},[j]);const ii=m.useMemo(()=>((Array.isArray(M==null?void 0:M.entrypoints)?M==null?void 0:M.entrypoints:[])||[]).map(S=>String((S==null?void 0:S.flow_id)||"").trim()).filter(Boolean),[M]),Xi=m.useMemo(()=>{const g=String((xe==null?void 0:xe.workflow_id)||"").trim();return pt&&ir?g:""},[pt,ir,xe==null?void 0:xe.workflow_id]),Ph=m.useMemo(()=>{var V;if(!pt||!c.trim()||!Xi.trim())return wr;const g=String((xe==null?void 0:xe.status)||"").trim().toLowerCase(),S=String((xe==null?void 0:xe.current_node)||"").trim();if(g!=="waiting"&&g!=="running"||!S)return wr;const $=Cr(c.trim(),S);if(!$)return wr;const I=String(ns||((V=xe==null?void 0:xe.waiting)==null?void 0:V.reason)||"").trim().toLowerCase(),q=typeof(es==null?void 0:es.node_id)=="string"?String(es.node_id).trim():"",W=typeof(es==null?void 0:es.status)=="string"?String(es.status).trim().toLowerCase():"";return g==="waiting"&&I==="until"||!wr.trim()||(W==="waiting"||W==="running")&&!q?$:wr},[pt,c,Xi,xe==null?void 0:xe.status,xe==null?void 0:xe.current_node,(zh=xe==null?void 0:xe.waiting)==null?void 0:zh.reason,ns,wr,es]),Dh=m.useMemo(()=>{const g={},S=c.trim(),$=(I,q)=>{if(!q)return;const W=typeof(q==null?void 0:q.node_id)=="string"?String(q.node_id).trim():"";if(!W)return;const V=Cr(I,W);if(!V)return;const te=String((q==null?void 0:q.ended_at)||(q==null?void 0:q.started_at)||"").trim(),$e=kn(te);$e!==null&&(g[V]=Math.max(g[V]||0,$e))};for(const I of $t)I&&I.record&&$(S,I.record);for(const I of cs)I&&I.record&&$(String(I.run_id||"").trim(),I.record);return g},[$t,cs,c,mi]);m.useEffect(()=>{var $;if(!pt||!c.trim()||!Xi.trim())return;const g=String((xe==null?void 0:xe.current_node)||"").trim();!g||String((($=xe==null?void 0:xe.waiting)==null?void 0:$.reason)||"").trim()==="subworkflow"||eu(Cr(c.trim(),g))},[pt,c,Xi,xe==null?void 0:xe.current_node,(Bh=xe==null?void 0:xe.waiting)==null?void 0:Bh.reason]),m.useEffect(()=>{const g=String((hs==null?void 0:hs.flow_id)||"").trim();g&&(zi.trim()||di(g))},[hs,zi]),m.useEffect(()=>{const g=Xi.trim(),S=j.trim(),$=zi.trim();if(g){let q=!1;return Ra(!0),La(""),Re.get_workflow_flow(g).then(W=>{if(q)return;const V=W==null?void 0:W.flow;Ma(V&&typeof V=="object"?V:null)}).catch(W=>{q||(Ma(null),La(String((W==null?void 0:W.message)||W||"Failed to load workflow flow")))}).finally(()=>{q||Ra(!1)}),()=>{q=!0}}if(!S||!$){Ma(null),La(""),Ra(!1);return}let I=!1;return Ra(!0),La(""),Re.get_bundle_flow(S,$).then(q=>{if(I)return;const W=q==null?void 0:q.flow,V=W&&typeof W=="object"?W:null;Ma(V),V&&$c(te=>({...te,[$]:V}))}).catch(q=>{I||(Ma(null),La(String((q==null?void 0:q.message)||q||"Failed to load flow")))}).finally(()=>{I||Ra(!1)}),()=>{I=!0}},[Xi,j,zi,Re]),m.useEffect(()=>{const g=j.trim();if(!Rl||!g||!go)return;let S=!1;const $=3,I=fe=>{const pe=Array.isArray(fe==null?void 0:fe.nodes)?fe.nodes:[],Ae=[];for(const Oe of pe){const He=Oe!=null&&Oe.data&&typeof Oe.data=="object"?Oe.data:{};if(String((He==null?void 0:He.nodeType)||(Oe==null?void 0:Oe.type)||"").trim()!=="subflow")continue;const Ge=(He==null?void 0:He.subflowId)||(He==null?void 0:He.flowId),sn=typeof Ge=="string"?Ge.trim():"";sn&&Ae.push(sn.includes(":")?sn.split(":",2)[1]:sn)}return Ae},q=new Set,W=new Set,V=(fe,pe)=>{if(!(!fe||pe>=$))for(const Ae of I(fe)){const Oe=String(Ae||"").trim();if(!Oe||q.has(Oe))continue;q.add(Oe),W.add(Oe);const He=Jo[Oe];He&&V(He,pe+1)}};V(go,0);const te=Array.from(W).filter(fe=>!Jo[fe]).slice(0,20);return te.length?((async()=>{for(const fe of te){if(S)return;try{const pe=await Re.get_bundle_flow(g,fe),Ae=pe==null?void 0:pe.flow,Oe=Ae&&typeof Ae=="object"?Ae:null;if(!Oe)continue;$c(He=>He[fe]?He:{...He,[fe]:Oe})}catch{}}})(),()=>{S=!0}):void 0},[Rl,j,go,Jo,Re]);const Jd=m.useMemo(()=>{const S=(Array.isArray(M==null?void 0:M.flows)?M==null?void 0:M.flows:[]).map($=>String($||"").trim()).filter(Boolean);return S.length?Array.from(new Set(S)).sort():Array.from(new Set(ii)).sort()},[M,ii]);m.useEffect(()=>{ji&&wr.trim()&&(Ia(""),Bi.current="")},[ji,c,wr]),m.useEffect(()=>{const g=_i.trim(),S=c.trim();if(!(pt&&!!g&&g!==S)){xs.current&&xs.current.abort(),xs.current=null,Ui.current=0,dd&&Pl("");return}if(dd===g)return;xs.current&&xs.current.abort();const I=new AbortController;xs.current=I,Ui.current=0,Pl(g),Zt({ts:jt(),kind:"info",title:`Following run ${g} (status/events)`});let q=250;return(async()=>{for(;!I.signal.aborted;){try{await Re.stream_ledger(g,{after:Ui.current,on_step:V=>Id(g,V),signal:I.signal});return}catch(V){if(I.signal.aborted)break;const te=String((V==null?void 0:V.message)||V||"stream error");Zt({ts:jt(),kind:"error",title:"Child ledger stream error (will retry)",preview:ht(te),data:{child_run_id:g,error:te}})}if(I.signal.aborted)break;await new Promise(V=>setTimeout(V,q)),q=Math.min(5e3,Math.floor(q*1.6))}})(),()=>{I.abort()}},[pt,_i,c,Re,dd]),m.useEffect(()=>{if(!pt||!c.trim())return;let g=!1;const S=async()=>{if(!g&&!Da.current&&mi.length&&!(qe.current>Date.now())){Da.current=!0;try{const I=mi.map(te=>String(te||"").trim()).filter(Boolean);if(!I.length)return;const q=I.map(te=>({run_id:te,after:Number(vo.current[te]||0)})),W=await Re.get_ledger_batch({runs:q,limit:200}),V=W&&typeof W=="object"?W.runs:{};for(const te of I){if(g)return;const $e=V&&typeof V=="object"?V[te]:null,fe=Array.isArray($e==null?void 0:$e.items)?$e.items:[],pe=typeof($e==null?void 0:$e.next_after)=="number"?$e.next_after:Number(vo.current[te]||0),Ae=Number(vo.current[te]||0);for(let Oe=0;Oe<fe.length;Oe++){const He=fe[Oe];tu(te,{cursor:Ae+Oe+1,record:He})}vo.current[te]=pe}}catch(I){if(g)return;Zt({ts:jt(),kind:"error",title:"Subrun digest poll failed",preview:ht(String((I==null?void 0:I.message)||I||""))})}finally{Da.current=!1}}};S();const $=window.setInterval(()=>void S(),2e3);return()=>{g=!0,window.clearInterval($),Da.current=!1}},[pt,c,mi,Re]);const cu=m.useMemo(()=>$a?Ku.filter(RL):Ku,[$a,Ku]),Si=m.useMemo(()=>{const g=c.trim(),S=[];for(const $ of $t)!$||!$.record||S.push({run_id:g,cursor:$.cursor,record:$.record});for(const $ of cs)!$||!$.record||S.push({run_id:String($.run_id||"").trim(),cursor:$.cursor,record:$.record});return S},[$t,cs,c]),la=m.useMemo(()=>{var S,$,I;const g={};for(const q of Si){const W=String(q.run_id||((S=q.record)==null?void 0:S.run_id)||"").trim();!W||String(((I=($=q.record)==null?void 0:$.effect)==null?void 0:I.type)||"").trim()!=="llm_call"||(g[W]=(g[W]||0)+1)}return g},[Si]),Xd=m.useMemo(()=>{const g=_i.trim();if(g)return g;let S="",$=-1;for(const[I,q]of Object.entries(la))q>$&&(S=I,$=q);return S||c.trim()},[la,_i,c]),rs=(__.trim()||Xd).trim(),Qt=m.useMemo(()=>{var q;const g=new Set,S=c.trim(),$=_i.trim();S&&g.add(S),$&&g.add($);for(const W of mi){const V=String(W||"").trim();V&&g.add(V)}for(const W of Si){const V=String(W.run_id||((q=W.record)==null?void 0:q.run_id)||"").trim();V&&g.add(V)}const I=Array.from(g);return I.sort((W,V)=>S&&W===S&&V!==S?-1:S&&V===S&&W!==S?1:$&&W===$&&V!==$?-1:$&&V===$&&W!==$?1:W<V?-1:W>V?1:0),I},[c,_i,mi,Si]),Yn=m.useMemo(()=>mk(Si,{run_id:rs}),[Si,rs]),qt=m.useMemo(()=>{const g=c.trim();return g&&(Dn.find(S=>String(S.run_id||"").trim()===g)||Mt.find(S=>String(S.run_id||"").trim()===g))||null},[Dn,Mt,c]),Un=String((xe==null?void 0:xe.status)||(qt==null?void 0:qt.status)||"").trim(),Er=String(ns||((nf=xe==null?void 0:xe.waiting)==null?void 0:nf.reason)||(qt==null?void 0:qt.waiting_reason)||"").trim().toLowerCase(),ca=!!(xe!=null&&xe.is_scheduled||qt!=null&&qt.is_scheduled),Jn=!!(xe!=null&&xe.paused||qt!=null&&qt.paused),cl=ca&&Un.toLowerCase()==="waiting",Ro=cl&&Er==="until",Kl=kn(ni),Yl=Ro&&Kl!==null?Qy(Kl-Date.now()):"",Zi=TC(xe),ks=ca&&Jn?"Suspended":cl?"Scheduled":Lm({status:Un,paused:Jn,stop_reason:Zi});async function uu(){if(N){Hi(!0),zs("");try{const g=fs,S=g==="session"?String(Fl||Dr||O||"").trim():"",$=g==="run"?String(br||c||"").trim():"",I=qC(Pr),q=Vi.length?Vi.join(","):"",W=HC(Oc),V=Math.max(0,Qr)*_m,te=await Re.search_artifacts({scope:g,session_id:S||void 0,run_id:$||void 0,query:Zr||void 0,artifact_kind:q||void 0,created_after:I||void 0,include_stats:!0,limit:_m,offset:V,order_by:W.order_by,order:W.order}),$e=[],fe=new Set;for(const Ve of Array.isArray(te==null?void 0:te.items)?te.items:[]){const Ge=BC(Ve,"search");!Ge||fe.has(Ge.artifact_id)||(fe.add(Ge.artifact_id),$e.push(Ge))}const pe=te!=null&&te.stats&&typeof te.stats=="object"?te.stats:{},Ae=Number((pe==null?void 0:pe.total)??(te==null?void 0:te.total)??$e.length),Oe=nw(te);let He=Oe;if(Vi.length)try{const Ve=await Re.search_artifacts({scope:g,session_id:S||void 0,run_id:$||void 0,query:Zr||void 0,created_after:I||void 0,include_stats:!0,limit:1,offset:0,order_by:W.order_by,order:W.order});He=nw(Ve)}catch{He=Oe}Ba(Number.isFinite(Ae)?Math.max(0,Ae):$e.length),Dl(Number((pe==null?void 0:pe.total_bytes)??(pe==null?void 0:pe.byte_total)??0)||0),Zo(Oe),xn(He),lh($e),tr(Ve=>{var Ge;return Ve&&$e.some(sn=>sn.artifact_id===Ve)?Ve:((Ge=$e[0])==null?void 0:Ge.artifact_id)||""})}catch(g){zs(String((g==null?void 0:g.message)||g||"Failed to load artifacts")),lh([]),Ba(0),Dl(0),Zo({}),xn({}),tr("")}finally{Hi(!1)}}}async function ua(){if(N){ta(!0),Wl("");try{const g=await Re.audit_log_tail({max_bytes:16e4}),S=typeof(g==null?void 0:g.bytes)=="number"?Number(g.bytes):0,$=!!(g!=null&&g.truncated);Va(String((g==null?void 0:g.content)||"")),gd(`${S.toLocaleString()} bytes${$?" (tail)":""}`)}catch(g){Wl(String((g==null?void 0:g.message)||g||"Failed to load audit log")),Va(""),gd("")}finally{ta(!1)}}}async function ki(g){if(!N)return;const S=String(g||No||br||c||"").trim();if(!S){ql([]),sr(""),ti("Select a run in Activity or Artifacts to load its runtime ledger.");return}Uc(!0),ti("");try{const $=await Re.get_ledger(S,{after:0,limit:2e3}),I=Array.isArray($.items)?$.items:[];ql(I.map((W,V)=>({cursor:V+1,record:W})));const q=typeof $.next_after=="number"?Number($.next_after):I.length;sr(`${I.length.toLocaleString()} record${I.length===1?"":"s"}${q>=2e3?" (first 2,000)":""}`)}catch($){ti(String(($==null?void 0:$.message)||$||"Failed to load run ledger")),ql([]),sr("")}finally{Uc(!1)}}m.useEffect(()=>{N&&e==="runtime"&&uu()},[N,e,fs,Fl,br,Zr,Vi,Pr,Oc,Qr]),m.useEffect(()=>{N&&(yd||fh||e==="runtime"&&ua())},[N,e,Qn]),m.useEffect(()=>{if(!N||e!=="runtime"||xr!=="logs"||na!=="run_ledger"&&na!=="provider_calls")return;const g=String(No||br||c||"").trim();g&&ki(g)},[N,e,xr,na,No,br,c]);const oi=m.useMemo(()=>{const g=new Map;for(const S of[...Mt,...Dn]){const $=String(S.run_id||"").trim();$&&g.set($,S)}for(const S of mi){const $=String(S||"").trim();!$||g.has($)||g.set($,{run_id:$,workflow_id:null,status:"",created_at:null,updated_at:null,ledger_len:null,parent_run_id:fi.current[$]||null,session_id:Dr||null})}return c.trim()&&!g.has(c.trim())&&g.set(c.trim(),{run_id:c.trim(),workflow_id:typeof(xe==null?void 0:xe.workflow_id)=="string"?String(xe.workflow_id):null,status:typeof(xe==null?void 0:xe.status)=="string"?String(xe.status):"",created_at:typeof(xe==null?void 0:xe.created_at)=="string"?String(xe.created_at):null,updated_at:typeof(xe==null?void 0:xe.updated_at)=="string"?String(xe.updated_at):null,ledger_len:$t.length||null,parent_run_id:typeof(xe==null?void 0:xe.parent_run_id)=="string"?String(xe.parent_run_id):null,session_id:typeof(xe==null?void 0:xe.session_id)=="string"?String(xe.session_id):Dr||null}),Array.from(g.values()).sort((S,$)=>{const I=kn(S.updated_at||S.created_at)??0;return(kn($.updated_at||$.created_at)??0)-I})},[Dn,Mt,c,xe,$t.length,mi,Dr]),Zd=m.useMemo(()=>b2(oi,{query:Zu,filter:Qu,group_by:ed,workflow_label_by_id:jn,parent_hint:g=>fi.current[g]||""}),[oi,Zu,Qu,ed,jn]),Lo=m.useMemo(()=>Zx(Si),[Si]),du=m.useMemo(()=>{const g=[...Si];return g.sort((S,$)=>{var W,V,te,$e;const I=kn(((W=S.record)==null?void 0:W.ended_at)||((V=S.record)==null?void 0:V.started_at))??0,q=kn(((te=$.record)==null?void 0:te.ended_at)||(($e=$.record)==null?void 0:$e.started_at))??0;return I-q}),g.slice(-240)},[Si]),or=m.useMemo(()=>{const g={};for(const S of oi){const $=String(S.run_id||"").trim();$&&(g[$]=S)}return g},[oi]),ul=String(No||br||c||"").trim(),da=ul&&or[ul]||null,fu=String(Fl||(da==null?void 0:da.session_id)||Dr||O||"").trim(),Jl=m.useMemo(()=>fd.map(g=>Om(g,or,jn)),[fd,or,jn]);m.useEffect(()=>{ei(0)},[Zr,Vi,Pr,br,Oc,So,fs,Fl]);const hu=Math.max(1,Math.ceil(bo/_m)),is=Math.min(Math.max(0,Qr),hu-1);m.useEffect(()=>{Qr!==is&&ei(is)},[Qr,is]);const ar=m.useMemo(()=>Jl,[Jl,is]),ai=m.useMemo(()=>{const g={};for(const S of ar){const $=So==="type"?Xp(S,or,jn):UC(S,So);g[$]||(g[$]=[]),g[$].push(S)}return Object.entries(g).map(([S,$])=>({key:S,items:$})).sort((S,$)=>{var I,q;if(So==="time"){const W=kn((I=S.items[0])==null?void 0:I.created_at)??0,V=kn((q=$.items[0])==null?void 0:q.created_at)??0;if(W!==V)return V-W}return S.key.localeCompare($.key)})},[ar,So,or,jn]),_s=m.useMemo(()=>{const g=jr.trim();return g?ar.find(S=>S.artifact_id===g)||ar[0]||null:ar[0]||null},[ar,jr]);m.useEffect(()=>{e!=="runtime"||xr!=="artifacts"||jh(_s)},[e,xr,_s==null?void 0:_s.artifact_id]),m.useEffect(()=>()=>{nr.url&&URL.revokeObjectURL(nr.url)},[nr.url]);const Fh=m.useMemo(()=>oi.filter(g=>Du(g.status)),[oi]);m.useEffect(()=>{if(e!=="settings"&&e!=="launch"||!N||T)return;let g=!1;return(async()=>{const[S,$]=await Promise.all([Re.list_skills(),Re.list_mcp_servers()]);g||(G(S),J($),Q(!0))})(),()=>{g=!0}},[e,N,T]),m.useEffect(()=>{Di(c.trim()?"run":"runs")},[c]);function mu(){xc&&window.setTimeout(()=>{var g;return(g=th.current)==null?void 0:g.scrollIntoView({block:"start"})},60)}function dl(g){Ir(g),mu()}const S_=[{id:"board",label:"Board",icon:s.jsx(Ze,{name:"board",size:16})},{id:"observe",label:"Observe",icon:s.jsx(Ze,{name:"history",size:16})},{id:"runtime",label:"System",icon:s.jsx(Ze,{name:"server",size:16})},{id:"launch",label:"Launch",icon:s.jsx(Ze,{name:"send",size:16})},{id:"automations",label:"Automations",icon:s.jsx(Ze,{name:"refresh",size:16})}],Io={board:"Board",observe:"Observe",runtime:"System",launch:"Launch",automations:"Automations",settings:"Settings"},Qd=s.jsxs(s.Fragment,{children:[wi?s.jsxs("details",{className:"launch_capabilities",style:{marginTop:"10px"},children:[s.jsxs("summary",{className:"help_text muted",style:{cursor:"pointer"},children:["Capabilities",vi.length?` · ${vi.length} skill${vi.length===1?"":"s"}`:""]}),s.jsx("div",{className:"help_text muted",style:{fontSize:"var(--font-size-sm)",marginTop:"8px"},children:"Skills attach knowledge procedures to this run. The gateway resolves selections through the trust gate at start: validated skills activate, unverified ones are held for review, blocked ones never ride."}),z===null?s.jsx("div",{className:"help_text muted",style:{marginTop:"8px"},children:"This gateway does not serve a skills inventory yet — the shelf lights up here when it ships."}):z.length?s.jsx("div",{className:"launch_skill_list",children:z.map(g=>{var q;const S=vi.includes(g.name),$=g.blocked===!0,I=g.requires_review===!0&&!$;return s.jsxs("label",{className:`launch_skill_row ${$?"is_blocked":""} ${S?"is_on":""}`,title:[g.description||"",g.tree_hash?`tree ${g.tree_hash.slice(0,16)}…`:"",$&&((q=g.reasons)!=null&&q.length)?`blocked: ${g.reasons.join("; ")}`:""].filter(Boolean).join(`
|
|
144
|
-
`),children:[s.jsx("input",{type:"checkbox",checked:S,disabled:$||Ce||Et||lt,onChange:W=>{const V=W.target.checked?Array.from(new Set([...vi,g.name])):vi.filter(te=>te!==g.name);$n("skills",V.length?V:void 0)}}),s.jsx("span",{className:"launch_skill_name",children:g.name}),g.trust_level?s.jsx("span",{className:`chip ${$?"danger":I?"warn":"muted"}`,children:$?"blocked":I?"review":g.trust_level}):null,g.description?s.jsx("span",{className:"launch_skill_desc",children:g.description}):null]},g.name)})}):s.jsx("div",{className:"help_text muted",style:{marginTop:"8px"},children:"The gateway's skills shelf is empty."}),vi.length?s.jsx("div",{className:"help_text muted",style:{fontSize:"var(--font-size-xxs)",marginTop:"6px"},children:"Selected skills ride the run as input_data.skills; the resolved verdicts land in the run's record."}):null]}):null,s.jsxs("details",{style:{marginTop:"10px"},children:[s.jsx("summary",{className:"help_text muted",style:{cursor:"pointer"},children:"Workspace"}),s.jsx("div",{className:"help_text muted",style:{fontSize:"var(--font-size-sm)",marginTop:"8px"},children:"Controls what the agent can access via filesystem tools."}),s.jsxs("div",{className:"launch_grid",style:{marginTop:"8px"},children:[s.jsxs("div",{className:"launch_grid_cell",style:{gridColumn:"1 / -1"},children:[s.jsx("label",{className:"launch_label",children:"Workspace Root"}),s.jsx("input",{className:"mono",value:kd,onChange:g=>$n("workspace_root",g.target.value),placeholder:"/path/to/workspace",disabled:Ce||Et}),s.jsx("div",{className:"help_text muted",style:{fontSize:"var(--font-size-xxs)"},children:"Empty = gateway default (isolated per-run workspace)"})]}),s.jsxs("div",{className:"launch_grid_cell",children:[s.jsx("label",{className:"launch_label",children:"Access Mode"}),s.jsxs("select",{className:"mono",value:(Ao||"workspace_only").trim()||"workspace_only",onChange:g=>$n("workspace_access_mode",g.target.value),disabled:Ce||Et,children:[s.jsx("option",{value:"workspace_only",children:"workspace_only"}),s.jsx("option",{value:"workspace_or_allowed",children:"workspace_or_allowed"}),s.jsx("option",{value:"all_except_ignored",children:"all_except_ignored"})]}),s.jsx("div",{className:"help_text muted",style:{fontSize:"var(--font-size-xxs)"},children:"workspace_only: absolute paths must stay under root. workspace_or_allowed: allow additional roots."})]})]}),(Ao||"").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:Pn,onChange:g=>$n("workspace_allowed_paths",g.target.value),placeholder:`/path/to/project
|
|
145
|
-
/path/to/workspace`,disabled:Ce||Et,spellCheck:!1,autoCorrect:"off",autoCapitalize:"off",autoComplete:"off"}),s.jsx("div",{className:"help_text muted",style:{fontSize:"var(--font-size-xxs)"},children:"Newline-separated directories (absolute or relative to workspace_root)"})]}):null,s.jsxs("div",{className:"field",style:{marginTop:"8px"},children:[s.jsx("label",{className:"launch_label",children:"Ignored Paths"}),s.jsx("textarea",{className:"mono",rows:3,value:ts,onChange:g=>$n("workspace_ignored_paths",g.target.value),placeholder:`node_modules
|
|
146
|
-
runtime
|
|
147
|
-
secret`,disabled:Ce||Et,spellCheck:!1,autoCorrect:"off",autoCapitalize:"off",autoComplete:"off"}),s.jsx("div",{className:"help_text muted",style:{fontSize:"var(--font-size-xxs)"},children:"Newline-separated paths to block (absolute or relative to workspace_root)"})]})]}),s.jsxs("details",{className:"launch_bundles",style:{marginTop:"10px"},children:[s.jsx("summary",{className:"help_text muted",style:{cursor:"pointer"},children:"Workflow bundles"}),s.jsxs("div",{className:"launch_workflow_bar",style:{marginTop:"8px"},children:[s.jsx("input",{ref:hr,type:"file",accept:".flow",style:{display:"none"},onChange:g=>{const S=g.target.files&&g.target.files.length?g.target.files[0]:null;S&&Xc(S)}}),s.jsx("button",{type:"button",className:"btn launch_btn_upload",onClick:()=>{var g;return(g=hr.current)==null?void 0:g.click()},disabled:!N||ie||Mi||Ce||Et,title:"Upload a .flow bundle",children:Mi?"…":"Upload .flow"}),s.jsxs("button",{type:"button",className:"btn launch_btn_reload",onClick:()=>void ph(),disabled:!N||ie||ut||Ce||Et,title:"Reload picks up server-side edits",children:[s.jsx(Ze,{name:"refresh",size:14}),ut?"…":"Reload bundles"]})]})]})]});function _u(g){t("observe"),Ir("overview"),aa(g)}const fa={on_select:g=>void zn.select(g),on_row_action:(g,S)=>{if(S==="discuss"||S==="edit")throw new Error(`${S} is routed by AutomationsPage (route_row_action), not the app handlers.`);if(S==="archive"){zn.ask_archive(g.automation_id);return}zn.row_action(g,S)},on_legacy_action:(g,S)=>{if(S==="open_run"){_u(g.automation_id);return}if(S==="recreate"){su(g.automation_id).catch($=>zn.report_error($));return}zn.legacy_action(g,S)},on_confirm_archive:g=>void zn.row_action(g,"archive"),on_cancel_archive:()=>zn.ask_archive(""),on_status_filter:g=>void zn.set_status_filter(g),on_refresh:()=>void zn.refresh(),on_new:()=>{he("automate"),t("launch")},on_show_archived:g=>zn.set_show_archived(g)};return s.jsxs("div",{className:`app-shell shell${bc?" nav_open":""}`,children:[Qf&&bc?s.jsx("div",{className:"shell_nav_backdrop","aria-hidden":"true",onClick:()=>Ea(!1)}):null,s.jsxs("aside",{className:"shell_sidebar",id:"shell_nav",ref:m_,...Ko.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:()=>Ea(!1),children:s.jsx(Ze,{name:"x",size:16})})]}),s.jsxs("nav",{className:"shell_nav",children:[S_.map(g=>s.jsxs("button",{className:`shell_nav_item ${e===g.id?"active":""}`,onClick:()=>{t(g.id),Ea(!1)},type:"button",children:[s.jsx("span",{className:"shell_nav_icon",children:g.icon}),s.jsx("span",{className:"shell_nav_label",children:g.label})]},g.id)),s.jsxs("a",{className:"shell_nav_item",href:l,target:"_blank",rel:"noreferrer",title:"Open the entity app (memory graph + visits)",children:[s.jsx("span",{className:"shell_nav_icon",children:s.jsx(Ze,{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"),Ea(!1)},type:"button",children:[s.jsx("span",{className:"shell_nav_icon",children:s.jsx(Ze,{name:"settings",size:16})}),s.jsx("span",{className:"shell_nav_label",children:"Settings"})]})]}),s.jsx("div",{className:"shell_sidebar_footer",children:s.jsxs("div",{className:"shell_connection shell_connection_passive",title:N?"Gateway connected":ie?"Gateway: connecting…":"Gateway: signed out",children:[s.jsx("span",{className:`gateway_led ${N?"ok":ie?"warn":"err"}`,"aria-hidden":"true"}),s.jsx("span",{className:`shell_connection_label ${N&&((Po=(sf=ne==null?void 0:ne.gateway)==null?void 0:sf.principal)!=null&&Po.user_id)?"mono":""}`,children:N?((ha=(Uh=ne==null?void 0:ne.gateway)==null?void 0:Uh.principal)==null?void 0:ha.user_id)||(n.gateway_auth_mode==="direct"?"direct dev":"connected"):ie?"connecting…":"signed out"})]})})]}),s.jsxs("div",{className:"shell_main",...Ko.attrs.main,children:[s.jsxs("header",{className:"shell_header",children:[s.jsx("button",{ref:h_,type:"button",className:"shell_nav_toggle","data-nav-toggle":!0,"aria-label":"Open navigation","aria-controls":"shell_nav","aria-expanded":bc,title:"Navigation",onClick:()=>Ea(!0),children:s.jsx(Ze,{name:"list",size:18})}),s.jsx("div",{className:"shell_header_title",children:Io[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(Ij,{assistant:{open:Ut,onToggle:()=>It(g=>!g),label:"Observer assistant (docs-grounded)"},appearance:{onOpen:()=>pn(!0)},about:{identity:_h,extraRows:Hc,onOpen:yi},connection:{phase:D.phase,signingOut:D.signingOut,onConnect:()=>D.openModal(),onDisconnect:()=>Qa()}})]})]}),s.jsx(_j,{...D.modalProps}),s.jsx(Fj,{open:tn,onClose:()=>pn(!1),value:Ye,onChange:Dt}),s.jsx(e1,{open:Ut,onClose:()=>It(!1),connected:N,topOffset:44,gateway:Re}),s.jsxs("div",{className:"app-body shell_content",children:[e==="board"?N?s.jsx(jL,{gateway_connected:N,runs:Mt,all_runs:Dn,runs_refreshed_at:gn,entities:Hn,entities_total:Tr,entities_error:ce,refreshing:vn,on_refresh:()=>void Bs(Re,{force:!0}),on_open_run:g=>{t("observe"),Ir("overview"),aa(g)},on_resume_wait:gh,on_open_automation:g=>{t("automations"),zn.refresh().then(()=>zn.select(g))},entity_app_href:l,on_read_diary:(g,S)=>Re.read_entity_diary_entry(g,S),phase_graph:Td}):s.jsx("div",{className:"page page_scroll",children:s.jsx("div",{className:"page_inner constrained",children:s.jsxs("div",{className:"card mc_hero",children:[s.jsx("div",{className:"title",children:s.jsx("h1",{children:"Connect to your gateway"})}),s.jsxs("p",{className:"muted",children:["Mission Control shows every run and entity on one board — but nothing is connected yet.",F?` Last attempt: ${F}`:""]}),s.jsxs("div",{className:"row",style:{gap:"8px",alignItems:"center"},children:[s.jsx("button",{className:"btn primary",onClick:()=>D.openModal(),disabled:ie,children:ie?"Connecting…":"Sign in"}),s.jsx("button",{className:"btn",onClick:()=>void Xa({open_modal_if_needed:!0}),disabled:ie,title:"Retry with an existing browser session or a direct dev token",children:"Retry connection"})]})]})})}):null,e==="settings"?s.jsx("div",{className:"page page_scroll",children:s.jsxs("div",{className:"page_inner settings_col",children:[s.jsxs("section",{className:"pane",children:[s.jsxs("div",{className:"pane_header",children:[s.jsx("span",{className:"pane_title",children:"Gateway"}),s.jsx("span",{className:"pane_spacer"}),s.jsx("span",{className:`chip ${N?"ok":"warn"}`,children:Rv(ne).label})]}),s.jsxs("div",{className:"pane_body settings_body",children:[s.jsxs("div",{className:"settings_row",children:[s.jsxs("div",{className:"settings_row_main",children:[s.jsx("div",{className:"settings_row_title",children:"Connection"}),s.jsx("div",{className:"settings_row_help",children:"The shared AbstractFramework sign-in: a gateway user token exchanges for an HTTP-only browser session. Raw tokens are never stored."})]}),s.jsxs("div",{className:"settings_row_actions",children:[s.jsx("button",{className:"btn",onClick:()=>D.openModal(),children:"Manage connection…"}),N?s.jsx("button",{className:"btn",onClick:()=>Qa(),title:"Sign this browser out of the gateway (this app's session only)",children:"Sign out"}):null]})]}),F?s.jsx("div",{className:"warn_callout",children:F}):null,s.jsxs("div",{className:"settings_row",children:[s.jsxs("div",{className:"settings_row_main",children:[s.jsx("div",{className:"settings_row_title",children:"Auto-connect on load"}),s.jsx("div",{className:"settings_row_help",children:"Reuse the browser session automatically when the app opens."})]}),s.jsx("div",{className:"settings_row_actions",children:s.jsxs("select",{value:n.auto_connect_gateway?"on":"off",onChange:g=>r(S=>({...S,auto_connect_gateway:g.target.value==="on"})),children:[s.jsx("option",{value:"on",children:"On"}),s.jsx("option",{value:"off",children:"Off"})]})})]}),s.jsxs("details",{className:"settings_advanced",children:[s.jsx("summary",{children:"Advanced: direct dev connection (bearer token, cross-origin)"}),s.jsxs("div",{className:"field",style:{marginTop:"8px"},children:[s.jsx("label",{children:"Gateway URL"}),s.jsx("input",{value:n.gateway_url,onChange:g=>r(S=>({...S,gateway_url:g.target.value})),placeholder:Gm})]}),s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Dev bearer token"}),s.jsx("input",{type:"password",value:n.auth_token,onChange:g=>r(S=>({...S,auth_token:g.target.value,gateway_auth_mode:"direct"})),placeholder:"development only — prefer the sign-in dialog"})]}),s.jsx("button",{className:"btn",onClick:()=>void Xa({prefer_direct:!0}),disabled:ie,children:ie?"Connecting…":"Connect directly"})]})]})]}),s.jsxs("section",{className:"pane",children:[s.jsxs("div",{className:"pane_header",children:[s.jsx("span",{className:"pane_title",children:"Assistant"}),s.jsx("span",{className:"pane_spacer"}),s.jsx("span",{className:"chip muted",children:"docs Q&A + run Ask"})]}),s.jsxs("div",{className:"pane_body settings_body",children:[s.jsx("div",{className:"settings_row_help",style:{marginTop:0},children:"The model answering the header assistant and the run page's Ask tab. Blank fields follow the gateway defaults."}),s.jsx(ij,{className:"field",providerLabel:"Provider",modelLabel:"Model",providerPlaceholder:"(gateway default)",modelPlaceholder:"(gateway default)",provider:n.maintenance_ai_provider,model:n.maintenance_ai_model,providers:Cd,models:Nr.models,loadingProviders:ie,loadingModels:Ed,modelError:ia?Nr.error:"",allowCustomProvider:!0,allowCustomModel:!0,allowGatewayDefault:!0,gatewayDefaultLabel:"(gateway default)",onChange:g=>r(S=>({...S,maintenance_ai_provider:g.provider,maintenance_ai_model:g.model}))}),s.jsx("div",{className:"settings_subhead",children:"Skills"}),z===null?s.jsx("div",{className:"settings_row_help",children:N?T?"The gateway does not serve a skills inventory yet — the abstractskill shelf list lights up here the day it ships.":"Probing the gateway for the skills inventory…":"Connect to the gateway to list installable skills (abstractskill shelf)."}):z.length?s.jsx("div",{className:"settings_choice_list",children:z.map(g=>{const S=n.assistant_skill_names.includes(g.name);return s.jsxs("label",{className:`settings_choice ${S?"on":""}`,title:g.description||g.name,children:[s.jsx("input",{type:"checkbox",checked:S,onChange:$=>r(I=>({...I,assistant_skill_names:$.target.checked?Array.from(new Set([...I.assistant_skill_names,g.name])):I.assistant_skill_names.filter(q=>q!==g.name)}))}),s.jsxs("span",{className:"settings_choice_name",children:[g.name,g.version?s.jsxs("em",{children:[" v",g.version]}):null]}),g.description?s.jsx("span",{className:"settings_choice_desc",children:g.description}):null]},g.name)})}):s.jsx("div",{className:"settings_row_help",children:"The gateway serves an empty skills inventory."}),s.jsx("div",{className:"settings_row_help",children:"Selected skills ride the assistant's runs once the gateway's skills-attachment lane serves them; the selection persists here meanwhile."}),s.jsx("div",{className:"settings_subhead",children:"MCP servers"}),s.jsx("div",{className:"settings_row_help",style:{marginTop:0},children:"Remote tool endpoints the assistant may call. The gateway does not serve an MCP inventory yet — one manual endpoint is supported (advanced / potentially dangerous: it executes tool waits from this browser)."}),s.jsxs("div",{className:"settings_mcp_row",children:[s.jsx("input",{className:"mono",value:n.worker_url,onChange:g=>r(S=>({...S,worker_url:g.target.value})),placeholder:"https://your-mcp-worker-endpoint"}),s.jsx("input",{className:"mono",type:"password",value:n.worker_token,onChange:g=>r(S=>({...S,worker_token:g.target.value})),placeholder:"Bearer token (optional)"}),s.jsx("span",{className:`chip ${n.worker_url.trim()?"ok":"muted"}`,children:n.worker_url.trim()?"configured":"none"})]})]})]})]})}):null,e==="launch"?s.jsx("div",{className:"page page_scroll",children:s.jsx("div",{className:"page_inner constrained",children:s.jsxs("div",{className:"card",children:[s.jsx(D1,{mode:oe,automate_available:ge.available,automate_reason:ge.reason,on_change:he}),oe==="automate"&&!ge.available&&N?s.jsx("div",{className:"warn_callout",role:"note",children:ge.reason}):null,oe==="automate"&&Se.length?s.jsx("div",{className:"help_text",role:"note",children:Se.map(g=>s.jsx("div",{children:g},g))}):null,N?null:s.jsxs("div",{className:"warn_callout",children:["Not connected."," ",s.jsx("button",{className:"btn primary",onClick:()=>D.openModal(),children:"Sign in"})," ","to launch workflows on this gateway."]}),oe==="automate"?s.jsx("div",{className:"section_title",children:"What"}):null,s.jsx("div",{className:"launch_workflow_bar",children:s.jsxs("select",{className:"launch_workflow_select","aria-label":"Workflow",value:Vl,onChange:async g=>{const S=u1(String(g.target.value||""));S&&await nu(S)},disabled:ie||!N,children:[s.jsx("option",{value:"",children:Gc.length?"(select workflow)":pt?ie?"(loading workflows…)":"(no executable workflows published on this gateway)":"(sign in to load workflows)"}),s.jsx("optgroup",{label:"Gateway default",children:f1(un).map(g=>s.jsx("option",{value:g.value,children:g.label},g.value))}),s.jsx("optgroup",{label:"Workflows",children:Gc.map(g=>s.jsx("option",{value:g.workflow_id,children:g.label},g.workflow_id))})]})}),s.jsxs("div",{className:"field",children:[hs!=null&&hs.description?s.jsx("div",{className:"help_text muted",style:{fontSize:"var(--font-size-sm)",marginTop:"6px"},children:String(hs.description)}):null,X?s.jsx("div",{className:"help_text muted",style:{fontSize:"var(--font-size-sm)"},children:"Loading workflow…"}):null,Z?s.jsx("div",{className:"mono",style:{color:"rgba(239, 68, 68, 0.9)",fontSize:"var(--font-size-sm)"},children:Z}):null]}),s.jsx("div",{className:"section_divider"}),s.jsx("div",{className:"section_title",children:"Inputs"}),wi?at===null?s.jsxs("div",{className:"log_item",style:{borderColor:"rgba(239, 68, 68, 0.35)",marginTop:"10px"},children:[s.jsxs("div",{className:"meta",children:[s.jsx("span",{className:"mono",children:"input error"}),s.jsx("span",{className:"mono",children:jt()})]}),s.jsx("div",{className:"body mono",children:"Invalid input JSON — reselect the workflow to reset its inputs."})]}):ms?s.jsx("div",{className:"launch_inputs",children:(()=>{const g=Ce||Et,S=[],$=[];for(const W of ra){if(!W||typeof W!="object")continue;const V=String(W.id||"").trim();if(!V||oe==="automate"&&Ix.includes(V))continue;const te=String(W.type||"").trim().toLowerCase();te==="tools"||te==="skills"||te==="mcp"||te==="mcp_servers"||V==="skills"||V==="mcp"||V==="mcp_servers"||te==="array"||Ja(te)||V==="prompt"||V==="system"?S.push(W):$.push(W)}const I=W=>String(W||"").trim().replace(/_/g," ").replace(/\b\w/g,V=>V.toUpperCase()),q=(W,V)=>{const te=String(W.id||"").trim();if(!te)return null;const $e=String(W.label||te).trim()||te,fe=$e===te?I(te):$e,pe=String(W.type||"").trim().toLowerCase(),Ae=Object.prototype.hasOwnProperty.call(W,"default"),Oe=Ae?W.default:void 0,He=Ae?typeof Oe=="string"?Oe:Ps(Oe,80):"",Ve=at==null?void 0:at[te],Ge=Ae?`${He}`:"";if(pe==="tools"){const We=Array.isArray(Ve)?Ve.map(Tn=>String(Tn||"").trim()).filter(Boolean):[],xt=Array.isArray(Oe)?Oe.map(Tn=>String(Tn||"").trim()).filter(Boolean):[],Sn=Array.from(new Set([...xi,...We,...xt])).sort();return s.jsxs("div",{className:"launch_field_wide",children:[s.jsx("label",{className:"launch_label",children:fe}),s.jsx(bv,{options:Sn,value:We,disabled:g,placeholder:"(no tools selected)",onChange:Tn=>$n(te,Tn)})]},te)}if(pe==="skills"||te==="skills")return null;if(pe==="mcp"||pe==="mcp_servers"||te==="mcp"||te==="mcp_servers"){const We=Array.isArray(Ve)?Ve.map(Tn=>String(Tn||"").trim()).filter(Boolean):[];if(K===null&&!We.length)return s.jsxs("div",{className:"launch_field_wide",children:[s.jsx("label",{className:"launch_label",children:fe}),s.jsx("div",{className:"help_text muted",children:"This gateway does not serve an MCP server inventory yet — MCP selection lights up here when it ships."})]},te);const xt=(K||[]).map(Tn=>Tn.name),Sn=Array.from(new Set([...xt,...We])).sort();return s.jsxs("div",{className:"launch_field_wide",children:[s.jsx("label",{className:"launch_label",children:fe}),s.jsx(bv,{options:Sn,value:We,disabled:g,placeholder:"(no MCP servers selected)",onChange:Tn=>$n(te,Tn)})]},te)}if(pe==="provider"||pe==="provider_text"){const We=typeof Ve=="string"?String(Ve):"";return s.jsxs("div",{className:V||"launch_field",children:[s.jsx("label",{className:"launch_label",children:fe}),s.jsxs("select",{value:We,onChange:xt=>$n(te,xt.target.value),disabled:g,children:[s.jsx("option",{value:"",children:Ge||"(select)"}),Nd.map(xt=>s.jsx("option",{value:xt,children:xt},xt))]})]},te)}if(pe==="model"||pe==="model_text"){const We=typeof Ve=="string"?String(Ve):"",xt=String((at==null?void 0:at.provider)||"").trim(),Sn=xt?Bt[xt]:void 0,Tn=Sn&&Array.isArray(Sn.models)?Sn.models.map(Ws=>String(Ws||"").trim()).filter(Boolean):[];return s.jsxs("div",{className:V||"launch_field",children:[s.jsx("label",{className:"launch_label",children:fe}),Tn.length?s.jsxs("select",{value:We,onChange:Ws=>$n(te,Ws.target.value),disabled:g,children:[s.jsx("option",{value:"",children:Ge||"(select)"}),Tn.map(Ws=>s.jsx("option",{value:Ws,children:Ws},Ws))]}):s.jsx("input",{value:We,onChange:Ws=>$n(te,Ws.target.value),placeholder:Ge||"model id",disabled:g})]},te)}if(pe==="boolean"){const We=typeof Ve=="boolean"?Ve?"true":"false":"";return s.jsxs("div",{className:V||"launch_field",children:[s.jsx("label",{className:"launch_label",children:fe}),s.jsxs("select",{value:We,onChange:xt=>{const Sn=String(xt.target.value||"").trim();Sn?$n(te,Sn==="true"):$n(te,void 0)},disabled:g,children:[s.jsx("option",{value:"",children:Ge||"(default)"}),s.jsx("option",{value:"true",children:"Yes"}),s.jsx("option",{value:"false",children:"No"})]})]},te)}if(pe==="number"){const We=typeof Ve=="number"&&Number.isFinite(Ve)?String(Ve):"";return s.jsxs("div",{className:V||"launch_field",children:[s.jsx("label",{className:"launch_label",children:fe}),s.jsx("input",{type:"number",value:We,onChange:xt=>{const Sn=String(xt.target.value||"").trim();if(!Sn){$n(te,void 0);return}const Tn=Number(Sn);Number.isFinite(Tn)&&$n(te,Tn)},placeholder:Ge,disabled:g})]},te)}if(pe==="array"){const We=Array.isArray(Ve)?Ve.map(xt=>String(xt||"").trim()).filter(Boolean).join(`
|
|
148
|
-
`):"";return s.jsxs("div",{className:"launch_field_wide",children:[s.jsx("label",{className:"launch_label",children:fe}),s.jsx("textarea",{className:"mono",value:We,onChange:xt=>{const Sn=String(xt.target.value||"").split(/\r?\n/g).map(Tn=>String(Tn||"").trim()).filter(Boolean);$n(te,Sn.length?Sn:void 0)},placeholder:Ge||"(one item per line)",rows:2,disabled:g})]},te)}if(Ja(pe)){const We=typeof Hr[te]=="string"?Hr[te]:"",xt=String(rn[te]||"").trim();return s.jsxs("div",{className:"launch_field_wide",children:[s.jsxs("label",{className:"launch_label",children:[fe," ",s.jsx("span",{className:"launch_label_type",children:pe})]}),s.jsx("textarea",{className:"mono",value:We,onChange:Sn=>{const Tn=String(Sn.target.value??"");it(qs=>({...qs,[te]:Tn}));const Ws=Tn.trim();if(!Ws){gs(qs=>{const lr={...qs};return delete lr[te],lr}),$n(te,void 0);return}try{const qs=JSON.parse(Ws);gs(lr=>{const fl={...lr};return delete fl[te],fl}),$n(te,qs)}catch(qs){gs(lr=>({...lr,[te]:String((qs==null?void 0:qs.message)||qs||"Invalid JSON")}))}},placeholder:Ge||"{...}",rows:3,disabled:g}),xt?s.jsx("div",{className:"launch_field_error",children:xt}):null]},te)}const sn=typeof Ve=="string"?String(Ve):"";return te==="prompt"||te==="system"?s.jsxs("div",{className:"launch_field_wide",children:[s.jsx("label",{className:"launch_label",children:fe}),s.jsx("textarea",{value:sn,onChange:We=>$n(te,We.target.value),placeholder:Ge||(te==="prompt"?"What should the agent do?":"System instructions (optional)"),rows:3,disabled:g})]},te):s.jsxs("div",{className:V||"launch_field",children:[s.jsx("label",{className:"launch_label",children:fe}),s.jsx("input",{value:sn,onChange:We=>$n(te,We.target.value),placeholder:Ge,disabled:g})]},te)};return S.sort((W,V)=>{const te={system:0,prompt:1,tools:2};return(te[String(W.id||"")]??10)-(te[String(V.id||"")]??10)}),s.jsxs(s.Fragment,{children:[S.map(W=>q(W)),$.length>0?s.jsx("div",{className:"launch_grid",children:$.map(W=>q(W,"launch_grid_cell"))}):null]})})()}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"field",style:{marginTop:"10px"},children:[s.jsx("label",{children:"Prompt (common)"}),s.jsx("textarea",{value:Sd,onChange:g=>$n("prompt",g.target.value),placeholder:"What do you want the workflow/agent to do?",rows:3,disabled:Ce||Et})]}),s.jsxs("div",{className:"row",children:[s.jsx("div",{className:"col",children:s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Provider (common)"}),s.jsx("input",{value:Hl,onChange:g=>$n("provider",g.target.value),placeholder:"lmstudio / ollama / openai / ...",disabled:Ce||Et})]})}),s.jsx("div",{className:"col",children:s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Model (common)"}),s.jsx("input",{value:Vc,onChange:g=>$n("model",g.target.value),placeholder:"qwen/qwen3-next-80b / gpt-4.1 / ...",disabled:Ce||Et})]})})]})]}):s.jsx("div",{className:"help_text muted",style:{fontSize:"var(--font-size-sm)",marginTop:"8px"},children:"Select a workflow above to configure inputs."}),oe==="automate"?s.jsxs(s.Fragment,{children:[s.jsx(F1,{form:Ee,email_status:Wc.email_status,on_open_my_email:gi,tools:Array.isArray(at==null?void 0:at.tools)?at.tools.map(g=>String(g)):void 0,disabled:lt,on_change:g=>ze(S=>({...S,...g}))}),s.jsxs("details",{className:"launch_advanced",style:{marginTop:"10px"},children:[s.jsxs("summary",{className:"help_text muted",style:{cursor:"pointer"},children:["Advanced",vi.length?` · ${vi.length} skill${vi.length===1?"":"s"}`:""]}),s.jsx(z1,{form:Ee,disabled:lt,on_change:g=>ze(S=>({...S,...g}))}),Qd]})]}):Qd,s.jsx("div",{className:"section_divider"}),hn?s.jsxs("div",{className:"observe_context_card error",style:{marginBottom:"10px"},children:[s.jsx("span",{className:"chip mono danger",children:"error"}),s.jsx("span",{className:"mono",children:hn})]}):null,oe==="automate"&&Ue.length?s.jsx("ul",{className:"automate_errors",role:"alert",children:Ue.map(g=>s.jsx("li",{children:g},g))}):null,oe==="automate"&&Pe?s.jsxs("div",{className:"observe_context_card error",role:"alert","data-code":Pe.code,style:{marginBottom:"10px"},children:[s.jsx("span",{className:"chip mono danger",children:Pe.code}),s.jsxs("span",{children:[s.jsx("strong",{children:Cm(Pe).title})," ",Cm(Pe).detail,Pe.field?s.jsxs("span",{className:"mono",children:[" (",Pe.field,")"]}):null]})]}):null,s.jsx("div",{className:"launch_actions_bar launch_actions_stack",children:(()=>{const g=oe==="automate",S=N?wi?at===null?"Inputs contain invalid JSON":g&&!ge.available?"Automations unavailable on this gateway":Ce||Et?"Attaching to a run…":ie||X?"Loading…":lt?"Submitting…":"":"Select a workflow":"Sign in first";return s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"launch_submit_btn",onClick:()=>void tl(),disabled:!!S,title:S,children:g?lt?"Creating…":"Create automation":Ce?"Launching…":"Launch now"}),S&&!lt&&!Ce?s.jsx("span",{className:"mono muted launch_disabled_reason",children:S}):null]})})()})]})})}):null,e==="automations"?s.jsx(iC,{ctl:zn,gateway:Re,active:e==="automations"&&N,available:ge,h:fa,host:{on_open_run:g=>_u(g),...gi?{on_open_my_email:gi}:{},on_open_session:(g,S)=>{Zt({ts:jt(),kind:"info",title:"Discussion started",preview:ht(S),data:g})}}}):null,e==="runtime"?s.jsx(d2,{gateway_connected:N,tab:xr,runs:oi,active_runs:Fh,all_artifacts:fd,artifacts:ar,artifact_total_count:bo,artifact_total_bytes:Ua,artifact_facets:hd,artifact_type_facets:jo,artifact_page:is,artifact_page_size:_m,artifact_groups:ai,selected_artifact:_s,embedded_preview:nr,loading:bn,error:Rs,query:Zr,scope:fs,type_filters:Vi,date_filter:Pr,group_by:So,sort_by:Oc,artifact_run_filter:br,audit_log_text:fh,audit_log_meta:Bc,audit_log_loading:yd,audit_log_error:hh,workflow_label_by_id:jn,run_by_id:or,selected_run_id:ul,session_id:fu,runtime_log_source:na,runtime_log_query:wd,runtime_ledger_log_items:xd,runtime_ledger_log_meta:Ka,runtime_ledger_log_loading:sa,runtime_ledger_log_error:mh,on_tab_change:Lc,on_query_change:Wa,on_scope_change:qa,on_session_filter_change:md,on_type_filters_change:ch,on_date_filter_change:Ic,on_group_by_change:uh,on_sort_by_change:ko,on_artifact_page_change:ei,on_artifact_run_filter_change:g=>{const S=String(g||"").trim();Qo(S),S&&Co(S),S&&fs!=="run"&&qa("run")},on_refresh_artifacts:()=>void uu(),on_refresh_audit:()=>void ua(),on_refresh_runtime_ledger:g=>void ki(g),on_runtime_log_source_change:Ga,on_runtime_log_query_change:vd,on_select_run:g=>{const S=String(g||"").trim();Co(S);const $=S&&or[S]||null,I=String(($==null?void 0:$.session_id)||"").trim();I&&md(I)},on_select_artifact:tr,on_preview_artifact:g=>void xh(g),on_download_artifact:g=>void vh(g),on_open_run:g=>{Co(String(g||"").trim()),t("observe"),Ir("overview"),aa(g)},on_open_ledger:g=>{Co(String(g||"").trim()),t("observe"),Ir("ledger"),aa(g)},on_refresh_runs:()=>void Bs(Re,{force:!0}),on_reconnect:()=>void Xa({open_modal_if_needed:!0}),on_open_settings:()=>t("settings"),memory_panel:N?s.jsx(tL,{gateway:Re,selected_run_id:No,selected_session_id:fu}):null}):null,e==="observe"?s.jsx("div",{className:"page observe_page",children:s.jsxs("div",{className:`observatory_layout observe_pane_${xc?eh:"both"}`,children:[s.jsx(h2,{sections:Zd,selected_run_id:c,root_run_id:_,search:Zu,filter:Qu,group_by:ed,loading:vn,connected:N,on_sign_in:()=>D.openModal(),total_runs:oi.length,workflow_label_by_id:jn,automation_titles:qc,on_search:u_,on_filter:d_,on_group_by:f_,on_refresh:()=>void Bs(),on_select:(g,S)=>{Di("run"),aa(g,{root_run_id:S||g})}}),s.jsxs("div",{className:"observatory_main",children:[s.jsxs("div",{className:"observe_toolbar",children:[s.jsxs("div",{className:"observe_toolbar_row",children:[xc?s.jsxs("button",{type:"button",className:"btn observe_back_btn",onClick:()=>Di("runs"),"aria-label":"Back to the run list",title:"Back to the run list",children:[s.jsx(Ze,{name:"list",size:14}),s.jsx("span",{children:"Runs"})]}):null,c.trim()?s.jsxs("div",{className:"observe_run_identity",title:c.trim(),children:[s.jsx("span",{className:"observe_run_name",children:jn[String((qt==null?void 0:qt.workflow_id)||"")]||String((qt==null?void 0:qt.workflow_id)||"").trim()||Lt(c.trim(),22)}),s.jsx("span",{className:"chip mono muted",children:Lt(c.trim(),14)}),s.jsx("span",{className:`chip ${Nl(ks||Un,Zi)}`,title:String((Zi==null?void 0:Zi.headline)||""),children:ks||Un||"unknown"})]}):s.jsx("span",{className:"observe_run_identity_empty",children:"No run selected"}),s.jsx("span",{className:"observe_toolbar_spacer"}),c.trim()?s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"btn",onClick:()=>{if(lu==="pause"){Li("pause"),Ts(""),Zs(""),Rr(!0);return}zd("resume")},disabled:Ss,children:au}),ri?s.jsx("button",{className:"btn primary",onClick:()=>void kh(),disabled:Ce||Et||ji||si,children:"Run now"}):null,s.jsx("button",{className:"btn danger",onClick:()=>{Li("cancel"),Ts(""),Zs(""),Rr(!0)},disabled:Ce||Et||ji,children:"Cancel"}),s.jsx("button",{className:"btn btn_icon",onClick:Dd,title:"Clear the run view",children:s.jsx(Ze,{name:"x",size:14})})]}):null]}),c.trim()&&!ji?s.jsx("div",{className:"observe_steer_row",children:s.jsx(xj,{runId:c.trim(),parked:sl,submit:(g,S)=>Re.submit_command({command_id:`steer-${Os()}`,run_id:g,type:"inject_guidance",payload:{guidance:S},client_id:"web_pwa"}).then($=>({accepted:!!($!=null&&$.accepted),duplicate:!!($!=null&&$.duplicate),seq:Number(($==null?void 0:$.seq)??0)})),onSent:()=>Zt({ts:jt(),kind:"info",title:"Steer queued",preview:"inject_guidance submitted — delivery shows as abstract.steer_seen in the ledger"})})}):null,sl||ir||vc?s.jsxs("div",{className:"observe_toolbar_context",children:[sl?s.jsxs("div",{className:"observe_context_card info",children:[s.jsxs("div",{className:"observe_context_label",children:[(()=>{const g=ir?si?"suspended":"scheduled":"waiting";return s.jsx("span",{className:`chip ${Nl(g)}`,children:g})})(),s.jsx("span",{className:"muted",children:ns||"unknown"})]}),s.jsxs("div",{className:"observe_context_body",children:[bs?s.jsxs("span",{className:"mono",title:bs,children:[s.jsx("span",{className:"muted",children:"wait_key"}),": ",Lt(bs,46)]}):null,ns==="event"&&rl?s.jsxs("span",{className:"mono",children:[s.jsx("span",{className:"muted",children:"event"}),": ",rl]}):null,ns==="subworkflow"&&Yi?s.jsxs("span",{className:"mono",children:[s.jsx("span",{className:"muted",children:"child"}),": ",Lt(Yi,18)]}):null,ns==="until"&&ni?s.jsxs("span",{className:"mono",title:ni,children:[s.jsx("span",{className:"muted",children:"until"}),": ",Lt(ni,46)]}):null,ns==="until"&&ni?s.jsx("span",{className:"mono muted",children:(()=>{const g=kn(ni),S=g!==null?new Date(g).toLocaleString():ni,$=g!==null?Qy(g-Date.now()):"";return`Next at ${S}${$?` (in ${$})`:""}`})()}):null]}),ns==="subworkflow"&&Yi?s.jsxs("div",{className:"observe_context_actions",children:[s.jsx("button",{className:"btn primary",onClick:async()=>{f(Yi),await el(Yi)},disabled:Ce,children:"Attach to child"}),_.trim()&&_.trim()!==c.trim()?s.jsx("button",{className:"btn",onClick:async()=>{f(_.trim()),await el(_.trim())},disabled:Ce,children:"Back to root"}):null]}):null]}):null,ir?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:ou?`every ${Ji}`:"once"})]}),s.jsxs("div",{className:"observe_context_body",children:[Ji?s.jsxs("span",{className:"mono",children:[s.jsx("span",{className:"muted",children:"interval"}),": ",Ji]}):null,s.jsxs("span",{className:"mono",children:[s.jsx("span",{className:"muted",children:"share ctx"}),": ",Gd?"yes":"no"]}),typeof Kd=="number"?s.jsxs("span",{className:"mono",children:[s.jsx("span",{className:"muted",children:"repeats"}),": ",Kd]}):null]}),ll!==null?s.jsxs("div",{className:"observe_context_budget",children:[s.jsxs("span",{className:"mono muted",children:[typeof Yd=="number"&&typeof zr=="number"?`${Yd.toLocaleString()} / ${zr.toLocaleString()}`:"",` • ${Math.round(Math.max(0,Math.min(1,ll))*100)}%`]}),s.jsx("div",{className:"observe_budget_bar",children:s.jsx("div",{className:`observe_budget_fill ${ll>=.9?"danger":ll>=.75?"warn":"ok"}`,style:{width:`${Math.round(Math.max(0,Math.min(1,ll))*100)}%`}})})]}):null,s.jsxs("div",{className:"observe_context_actions",children:[ou?s.jsx("button",{className:"btn",onClick:()=>{uo(Ji||""),Fn(!0),Rn(""),us(!0)},disabled:Ce||_r,children:"Edit schedule"}):null,ou?s.jsx("button",{className:"btn",onClick:()=>{Ri(""),Js(!0)},disabled:Ce||pr,children:"Compact context"}):null,s.jsx("button",{className:"btn",onClick:()=>void su(c.trim()).catch(g=>nn(String((g==null?void 0:g.message)||g))),disabled:Ce||!c.trim(),title:"Open Launch → Automate prefilled from this schedule (this schedule is not changed)",children:"Recreate as automation"})]})]}):null,vc?s.jsxs("div",{className:"observe_context_card error",children:[s.jsx("span",{className:"chip danger",children:"error"}),s.jsx("span",{className:"mono",children:vc})]}):null]}):null]}),s.jsxs("div",{className:"card panel_card card_scroll observe_viewer observe_viewer_full",ref:th,children:[s.jsxs("div",{className:"tab_bar",children:[s.jsxs("div",{role:"tablist","aria-label":"Run views",className:"observe_tablist",children:[s.jsx("button",{role:"tab","aria-selected":Qn==="overview",className:`tab ${Qn==="overview"?"active":""}`,onClick:()=>dl("overview"),children:"Story"}),s.jsx("button",{role:"tab","aria-selected":Qn==="ledger",className:`tab ${Qn==="ledger"?"active":""}`,onClick:()=>dl("ledger"),children:"Ledger"}),s.jsx("button",{role:"tab","aria-selected":Qn==="graph",className:`tab ${Qn==="graph"?"active":""}`,onClick:()=>dl("graph"),children:"Flow"}),s.jsx("button",{role:"tab","aria-selected":Qn==="chat",className:`tab ${Qn==="chat"?"active":""}`,onClick:()=>dl("chat"),children:"Ask"})]}),Qn==="ledger"&&(cu.length>0||Fi==="cycles")?s.jsxs("div",{className:"tab_bar_controls",children:[s.jsxs("div",{className:"seg_toggle",children:[s.jsx("button",{className:`seg_btn ${Fi==="steps"?"active":""}`,onClick:()=>Yo("steps"),children:"Steps"}),s.jsx("button",{className:`seg_btn ${Fi==="cycles"?"active":""}`,onClick:()=>Yo("cycles"),children:"Cycles"})]}),Fi==="steps"?s.jsx("button",{className:`seg_action ${$a?"active":""}`,onClick:()=>nh(g=>!g),title:$a?"Showing condensed view":"Showing all steps",children:$a?"Condensed":"All"}):s.jsxs("select",{className:"mono seg_select",value:rs,onChange:g=>Tl(String(g.target.value||"")),disabled:!Qt.length,title:"Select run for cycles view",children:[Qt.length?null:s.jsx("option",{value:"",children:"(no runs)"}),Qt.map(g=>{const S=typeof la[g]=="number"?Number(la[g]):0,$=`${Lt(g,18)}${S?` • ${S} llm`:""}`;return s.jsx("option",{value:g,children:$},g)})]}),s.jsx("button",{className:"seg_action",disabled:!$t.length&&!cs.length,title:"Copy full ledger as JSONL",onClick:()=>{const $=[...$t.map(W=>({run_id:c.trim()||W.record.run_id||"",cursor:W.cursor,record:W.record})),...cs.map(W=>({run_id:W.run_id,cursor:W.cursor,record:W.record}))].map(W=>{var $e,fe;const V=String((($e=W.record)==null?void 0:$e.ended_at)||((fe=W.record)==null?void 0:fe.started_at)||"").trim(),te=kn(V);return{...W,_ms:te??0}});$.sort((W,V)=>(W._ms||0)-(V._ms||0));const q=($.length>5e3?$.slice($.length-5e3):$).map(({_ms:W,...V})=>JSON.stringify(V)).join(`
|
|
149
|
-
`);Zc(q)},children:"Copy JSONL"})]}):null,Qn==="graph"?s.jsxs("div",{className:"tab_bar_controls",children:[s.jsx("button",{className:`seg_action ${Rl?"active":""}`,onClick:()=>yo(g=>!g),children:"Subflows"}),s.jsx("button",{className:`seg_action ${Ac?"active":""}`,onClick:()=>ud(g=>!g),children:"Path"}),Jd.length?s.jsx("select",{className:"mono seg_select",value:zi,onChange:g=>di(String(g.target.value||"")),disabled:!!Xi.trim()||!j.trim()||ld,children:Jd.map(g=>s.jsx("option",{value:g,children:g},g))}):null]}):null]}),Qn==="overview"?s.jsx(m2,{run_id:c,run:qt,run_state:xe,status_label:ks||Un||"unknown",workflow_label_by_id:jn,root_run_id:_,subrun_ids:mi,session_id:Dr,records_count:$t.length,records:$t,child_records_count:cs.length,provider_activities:Lo,attachments_count:Sc.length,latest_summary:Oh,wait_state:Wt,summary_generating:qi,summary_error:Fa,on_generate_summary:()=>void Us(),on_open_runtime:()=>{const g=String(c||"").trim();g&&(Co(g),Qo(g),qa("run")),Lc("artifacts"),t("runtime")},on_open_subrun:g=>void aa(g,{root_run_id:_||c||g}),on_answer_wait:()=>Gr(""),workspace_root:rh,on_reveal_workspace:()=>void yh(),run_artifacts:p_,run_artifacts_loading:Yr,run_artifacts_error:ih,on_preview_run_artifact:g=>void xh(g),on_download_run_artifact:g=>void vh(g),timeline_items:du,node_index:Ln,attachments:Sc,attachments_loading:nd,attachments_error:sh,attachments_ready:!!td.trim(),on_refresh_attachments:()=>void Rd(),on_preview_attachment:g=>void wh(g),on_download_attachment:g=>void v_(g),on_copy:g=>void Zc(g)}):null,Qn==="ledger"?s.jsx(s.Fragment,{children:Fi==="steps"?s.jsxs("div",{className:"log log_scroll",children:[cu.map(g=>s.jsx(p2,{item:g,open:Ju[g.id]===!0,on_toggle:()=>Xu(S=>({...S,[g.id]:!S[g.id]})),response_open:c_[g.id]===!0,on_toggle_response:()=>Zf(S=>({...S,[g.id]:!S[g.id]})),node_index:Ln,on_copy:S=>void Zc(S)},g.id)),cu.length?null:s.jsx("div",{className:"empty_state_inline",children:"(no ledger items)"})]}):s.jsx("div",{className:"log log_scroll",children:s.jsx(lk,{items:Yn.items,title:"Agent",subtitle:Yn.node_id?`node_id: ${Yn.node_id}`:"Live per-effect trace (LLM/tool calls).",subRunId:rs,onOpenSubRun:rs&&rs!==c.trim()?()=>{f(rs),el(rs)}:void 0})})}):null,Qn==="graph"?s.jsxs(s.Fragment,{children:[cd?s.jsxs("div",{className:"log_item log_item_danger",children:[s.jsxs("div",{className:"meta",children:[s.jsx("span",{children:"graph error"}),s.jsx("span",{className:"mono",children:jt()})]}),s.jsx("div",{className:"body mono",children:cd})]}):null,ld?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:Xi.trim()?Xi.trim():zi})]}),s.jsx("div",{className:"body mono",children:"Loading graph…"})]}):null,s.jsx("div",{className:"graph_panel",children:s.jsx(A2,{flow:go,flow_by_id:Jo,expand_subflows:Rl,simplify:!0,prefer_vertical:!0,vertical_compact:.78,schedule_next_in:Yl,schedule_interval:Ji,node_last_ms:Dh,active_node_id:Ph,recent_nodes:ah,visited_nodes:Cn,highlight_path:Ac,now_ms:w_})})]}):null,s.jsxs(bl,{open:oh,title:od||"Attachment",onClose:()=>{Cc(!1),Jr(""),po(""),Ml(!1)},actions:s.jsx(s.Fragment,{children:s.jsx("button",{className:"btn",onClick:()=>{Cc(!1),Jr(""),po(""),Ml(!1)},children:"Close"})}),children:[ad?s.jsx("div",{className:"mono muted",style:{fontSize:"var(--font-size-sm)",marginBottom:"8px"},children:"Loading…"}):null,Ec?s.jsx("div",{className:"mono",style:{color:"rgba(239, 68, 68, 0.9)",fontSize:"var(--font-size-sm)",marginBottom:"8px"},children:Ec}):null,s.jsx("pre",{className:"mono",style:{whiteSpace:"pre-wrap",maxHeight:"62vh",overflow:"auto",margin:0},children:y_||"(empty)"})]}),Qn==="chat"?s.jsxs("div",{className:"ask_tab log_scroll",style:{marginTop:"6px"},children:[s.jsxs("div",{className:"ask_header",children:[s.jsx("span",{className:"ask_title",children:"Ask about this run"}),s.jsx("span",{className:"chip muted",title:"Model comes from Settings → Assistant (blank = gateway default)",children:(n.maintenance_ai_provider.trim()||"gateway")+" / "+(n.maintenance_ai_model.trim()||"default")}),s.jsx("span",{className:"pane_spacer"}),s.jsx("span",{className:"ask_hint",children:"Read-only · grounded in this run + subflows"})]}),s.jsxs("details",{className:"ask_manage",children:[s.jsx("summary",{children:"History & export"}),s.jsxs("div",{className:"field",style:{marginTop:"10px"},children:[s.jsxs("div",{className:"actions",style:{justifyContent:"space-between",alignItems:"center",gap:"10px",flexWrap:"wrap",marginTop:0},children:[s.jsx("div",{style:{flex:1,minWidth:260},children:s.jsx(Pu,{value:Al,options:Gu,placeholder:Pi?"Loading…":Gu.length?"Select a saved discussion…":"(none saved)",disabled:!c.trim()||!N||!Gu.length,loading:Pi,searchable:!0,clearable:!0,onChange:g=>{gc(g),Go("")}})}),s.jsxs("div",{className:"actions",style:{justifyContent:"flex-end",marginTop:0},children:[s.jsx("button",{className:"btn",type:"button",disabled:!Al.trim()||!N||yc,onClick:()=>void $h(),children:yc?"Loading…":"Load"}),s.jsx("button",{className:"btn",type:"button",disabled:!ke.length||U||Ft||yc,onClick:()=>{Be([]),ot(null),yr(""),Fs(""),Rt(""),Nn(""),Zn("")},children:"Clear"}),s.jsx("button",{className:"btn",type:"button",onClick:()=>void ru(),disabled:!c.trim()||!N||Pi,children:Pi?"Refreshing…":"Refresh"})]})]}),s.jsxs("div",{className:"actions",style:{justifyContent:"flex-end",marginTop:"8px",flexWrap:"wrap"},children:[s.jsx("button",{className:"btn",type:"button",disabled:!ke.length||!c.trim()||!N||Ft||!Vu,onClick:()=>void Wd(),title:Vu?"":"No changes since last save",children:Ft?"Saving…":!Vu&&an?"Saved":"Save discussion"}),s.jsx("button",{className:"btn",type:"button",disabled:!ke.length,onClick:()=>Ud("download"),children:"Export Markdown"}),s.jsx("button",{className:"btn",type:"button",disabled:!ke.length,onClick:()=>Ud("copy"),children:je==="copied"?"Copied":je==="failed"?"Copy failed":"Copy Markdown"})]}),an?s.jsxs("div",{className:"chat_hint",children:["Last saved: ",ya(an)]}):null,vs?s.jsx("div",{className:"chat_hint chat_hint_danger",children:vs}):null,Xf?s.jsx("div",{className:"chat_hint chat_hint_danger",children:Xf}):null,Jf?s.jsx("div",{className:"chat_hint chat_hint_danger",children:Jf}):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:jt()})]}),s.jsx("div",{className:"body mono",children:mo})]}):null,qo?s.jsxs("div",{className:"log_item log_item_danger",children:[s.jsxs("div",{className:"meta",children:[s.jsx("span",{children:"voice"}),s.jsx("span",{className:"mono",children:jt()})]}),s.jsx("div",{className:"body mono",children:qo})]}):null,s.jsx("div",{className:"chat_messages",style:{marginTop:"10px"},children:s.jsx(Eg,{messages:ke,className:"log_scroll",after:s.jsx(Lx,{history:ft}),afterKey:ft?`${ft.replayed_messages}:${ft.dropped_messages}`:null,messageProps:Bn.tts_supported&&N&&Vo.trim()?{onSpeakToggle:Ch,getSpeakState:Eh,jsonCollapseAfterDepth:4}:{jsonCollapseAfterDepth:4},empty:s.jsx("div",{className:"chat_empty_hint",children:"Ask about this run (why failed, which tools, what happened in subflows)."})})}),s.jsx("div",{className:"chat_composer",style:{marginTop:"10px"},children:s.jsx($g,{ref:gt,value:_c,onChange:yr,onSubmit:()=>void Nh(),placeholder:"Ask about this run…",disabled:!c.trim()||!N||U,busy:U||Bn.voice_ptt_busy,busyLabel:Bn.voice_ptt_busy?"Transcribing…":"Thinking…",rows:3,sendButtonClassName:"btn primary",actions:s.jsxs("button",{className:`btn btn_icon voice_btn${Bn.voice_ptt_recording?" danger":""}`,type:"button",disabled:!N||!oa.trim()||!Vo.trim()||U||Bn.voice_ptt_busy||!Bn.voice_ptt_supported,title:Bn.voice_ptt_supported?Bn.voice_ptt_busy?"Transcribing…":Bn.voice_ptt_recording?"Recording… release to transcribe":"Hold to talk (record + transcribe)":"Voice recording is not supported in this browser","aria-label":"Voice input",onPointerDown:g=>{var S,$;if(!(!N||!oa.trim()||!Vo.trim()||U||Bn.voice_ptt_busy||!Bn.voice_ptt_supported)){g.preventDefault();try{($=(S=g.currentTarget)==null?void 0:S.setPointerCapture)==null||$.call(S,g.pointerId)}catch{}Bn.start_voice_ptt_recording()}},onPointerUp:g=>{g.preventDefault(),Bn.stop_voice_ptt_recording()},onPointerCancel:g=>{g.preventDefault(),Bn.stop_voice_ptt_recording()},children:[s.jsx(Ze,{name:Bn.voice_ptt_recording?"x":"mic",size:16}),Bn.voice_ptt_busy?"Transcribing…":Bn.voice_ptt_recording?"Recording…":"Voice"]})})})]}):null,c.trim()?s.jsxs("div",{className:`status_bar ${Uo?"pulse":""}`,children:[s.jsx("strong",{children:"Run"}),":"," ",s.jsx("span",{className:"mono",children:ks||Un||"unknown"}),Ro&&Yl?s.jsxs("span",{className:"mono muted",children:[" • next in ",Yl]}):null,Ii?s.jsxs("span",{className:"mono muted",children:[" • ",Ii]}):null]}):null]})]})]})}):null,s.jsxs(bl,{open:dh,title:Pc||"Artifact",onClose:()=>{zl(!1),_n(""),Ha(""),Ul(!1),Fc(null),En&&(URL.revokeObjectURL(En),Bl(""))},actions:s.jsx("button",{className:"btn",onClick:()=>{zl(!1),_n(""),Ha(""),Ul(!1),Fc(null),En&&(URL.revokeObjectURL(En),Bl(""))},children:"Close"}),children:[zc?s.jsx("div",{className:"mono muted",style:{fontSize:"var(--font-size-sm)",marginBottom:"8px"},children:"Loading…"}):null,ea?s.jsx("div",{className:"mono",style:{color:"rgba(239, 68, 68, 0.9)",fontSize:"var(--font-size-sm)",marginBottom:"8px"},children:ea}):null,Dc==="image"&&En?s.jsx("img",{className:"runtime_preview_media",src:En,alt:Pc||"Artifact preview"}):Dc==="audio"&&En?s.jsx("audio",{className:"runtime_preview_media",controls:!0,src:En}):Dc==="video"&&En?s.jsx("video",{className:"runtime_preview_media",controls:!0,src:En}):s.jsx(eb,{artifact:pd,text:kr||"(empty)",className:"runtime_preview_text"})]}),ci?s.jsxs(bl,{open:ci,title:"Edit schedule",onClose:()=>{us(!1),uo(""),Fn(!0),Rn(""),fo(!1)},actions:s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"btn",onClick:()=>{us(!1),uo(""),Fn(!0),Rn(""),fo(!1)},disabled:Ce||_r,children:"Back"}),s.jsx("button",{className:"btn primary",onClick:async()=>{await x_({interval:co,apply_immediately:Sa})||(us(!1),Rn(""),fo(!1))},disabled:Ce||_r||!co.trim(),children:"Save"})]}),children:[mr?s.jsxs("div",{className:"log_item",style:{borderColor:"rgba(239, 68, 68, 0.35)",marginBottom:"10px"},children:[s.jsxs("div",{className:"meta",children:[s.jsx("span",{className:"mono",children:"error"}),s.jsx("span",{className:"mono",children:jt()})]}),s.jsx("div",{className:"body mono",children:mr})]}):null,s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Interval"}),s.jsx("input",{className:"mono",value:co,onChange:g=>uo(String(g.target.value||"")),placeholder:"20m / 1h / 0.5s / 250ms",disabled:Ce||_r}),s.jsxs("div",{className:"mono muted",style:{fontSize:"var(--font-size-sm)"},children:["Accepted units: ",s.jsx("span",{className:"mono",children:"ms"}),", ",s.jsx("span",{className:"mono",children:"s"}),", ",s.jsx("span",{className:"mono",children:"m"}),","," ",s.jsx("span",{className:"mono",children:"h"}),", ",s.jsx("span",{className:"mono",children:"d"}),". This updates the existing scheduled run in place (no context loss)."]})]}),s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Quick picks"}),s.jsx("div",{className:"actions",style:{gap:"8px",flexWrap:"wrap"},children:["15m","30m","1h","2h","6h","1d"].map(g=>s.jsx("button",{className:"btn",onClick:()=>uo(g),disabled:Ce||_r,children:g},g))})]}),s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Apply"}),s.jsxs("label",{style:{display:"flex",gap:"10px",alignItems:"center"},children:[s.jsx("input",{type:"checkbox",checked:Sa,onChange:g=>Fn(!!g.target.checked),disabled:Ce||_r}),"Apply immediately (recompute next run from now if waiting)"]})]})]}):null,Xn?s.jsxs(bl,{open:Xn,title:"Compact scheduled context",onClose:()=>{Js(!1),Ri(""),As(!1)},actions:s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"btn",onClick:()=>{Js(!1),Ri(""),As(!1)},disabled:Ce||pr,children:"Cancel"}),s.jsx("button",{className:"btn primary",onClick:async()=>{await rr({preserve_recent:ds,compression_mode:ys,focus:ho})||(Js(!1),Ri(""),As(!1))},disabled:Ce||pr,children:pr?"Compacting…":"Compact"})]}),children:[El?s.jsxs("div",{className:"log_item",style:{borderColor:"rgba(239, 68, 68, 0.35)",marginBottom:"10px"},children:[s.jsxs("div",{className:"meta",children:[s.jsx("span",{className:"mono",children:"error"}),s.jsx("span",{className:"mono",children:jt()})]}),s.jsx("div",{className:"body mono",children:El})]}):null,s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Preserve recent turns"}),s.jsx("input",{type:"number",min:1,value:String(ds),onChange:g=>Vr(Math.max(1,parseInt(g.target.value||"6",10)||6)),disabled:Ce||pr})]}),s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Mode"}),s.jsxs("select",{value:ys,onChange:g=>ka(g.target.value),disabled:Ce||pr,children:[s.jsx("option",{value:"light",children:"light"}),s.jsx("option",{value:"standard",children:"standard"}),s.jsx("option",{value:"heavy",children:"heavy"})]})]}),s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Focus (optional)"}),s.jsx("input",{className:"mono",value:ho,onChange:g=>on(String(g.target.value||"")),placeholder:"e.g. important decisions, next steps…",disabled:Ce||pr})]})]}):null,Na?s.jsxs(bl,{open:Na,title:ui==="cancel"?"Cancel run":ir?"Suspend schedule":"Pause run",onClose:()=>{Rr(!1),Ts(""),Zs("")},actions:s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"btn",onClick:()=>{Rr(!1),Ts(""),Zs("")},disabled:Ce||Et,children:"Back"}),s.jsx("button",{className:`btn ${ui==="cancel"?"danger":"primary"}`,onClick:async()=>{Zs("");const g=await zd(ui,{reason:Xs});if(g){Zs(g);return}Rr(!1),Ts(""),Zs("")},disabled:Ce||Et,children:ui==="pause"?ir?"Suspend":"Pause":"Cancel"})]}),children:[Lr?s.jsxs("div",{className:"log_item",style:{borderColor:"rgba(239, 68, 68, 0.35)",marginBottom:"10px"},children:[s.jsxs("div",{className:"meta",children:[s.jsx("span",{className:"mono",children:"error"}),s.jsx("span",{className:"mono",children:jt()})]}),s.jsx("div",{className:"body mono",children:Lr})]}):null,s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Reason (optional)"}),s.jsx("input",{className:"mono",value:Xs,onChange:g=>Ts(g.target.value),placeholder:"reason…"})]})]}):null,qd?s.jsxs(bl,{open:qd,title:ol,onClose:()=>{bs&&Gr(bs)},actions:s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"btn",onClick:()=>{Ir("ledger"),t("observe"),Di("run"),mu(),bs&&Gr(bs)},disabled:!c.trim(),children:"Open ledger"}),s.jsx("button",{className:"btn",onClick:()=>bs&&Gr(bs),disabled:Et,children:"Dismiss"}),To.length?s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"btn danger",disabled:Et,onClick:()=>nl({approved:!1}),children:"Reject"}),s.jsx("button",{className:"btn",disabled:Et,onClick:()=>nl({approved:!0}),children:"Approve only"}),s.jsx("button",{className:"btn primary",disabled:!Eo||Et,onClick:()=>Ah(To),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:ol}),s.jsx("p",{children:Ls})]}),s.jsx(Cl,{status:bi||"waiting"})]}),al?s.jsxs("div",{className:`wait_request_card ${Mo?"":"inferred"}`,children:[s.jsx("span",{children:Vd}),s.jsx(Cv,{metadata:iu}),s.jsx(Ai,{text:al}),Mo?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."}),Lh.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:Lh.map((g,S)=>s.jsxs("div",{className:`wait_turn_row role_${g.role.replace(/[^a-z0-9_-]+/g,"_")}`,children:[s.jsxs("div",{className:"wait_turn_meta",children:[s.jsx("strong",{children:g.role==="assistant"?"Assistant":g.role==="user"||g.role==="human"?"User":g.role}),g.ts?s.jsx("span",{className:"mono muted",children:ya(g.ts)}):null]}),s.jsx(Cv,{metadata:g.runtime_metadata}),s.jsx(Ai,{text:ht(g.text,{max_chars:1200,max_lines:10})})]},`${g.role}:${S}`))})]}):null,s.jsxs("div",{className:"artifact_detail_grid",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Workflow"}),s.jsx("strong",{children:Ci(il,jn)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Run"}),s.jsx("strong",{className:"mono",children:Lt(c.trim(),24)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Node"}),s.jsx("strong",{className:"mono",children:il.current_node||String((es==null?void 0:es.node_id)||"—")})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Elapsed"}),s.jsx("strong",{children:fc(il)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Session"}),s.jsx("strong",{className:"mono",children:il.session_id?Lt(String(il.session_id),18):"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Wait key"}),s.jsx("strong",{className:"mono",children:Lt(bs,28)})]})]}),j_?s.jsxs("details",{className:"runtime_raw_details wait_full_input_details",open:!al,children:[s.jsx("summary",{className:"mono muted",children:"Full run input JSON"}),s.jsx("div",{className:"wait_shared_json",children:s.jsx(dr,{value:Ih,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:[Hd.map(g=>s.jsxs("div",{className:"wait_event_row",children:[s.jsxs("span",{className:"mono",children:["#",g.cursor]}),s.jsx("strong",{children:g.summary||g.effect_type||g.status||"event"}),s.jsx("span",{className:"mono muted",children:[g.node_id,g.status,ya(g.ts)].filter(Boolean).join(" · ")})]},`${g.cursor}:${g.node_id}:${g.status}`)),Hd.length?null:s.jsx("div",{className:"empty_state_inline",children:"No ledger context is loaded. Open the ledger before deciding."})]})]})]}),To.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:To.map((g,S)=>s.jsxs("div",{className:"wait_tool_card",children:[s.jsxs("div",{className:"wait_tool_header",children:[s.jsx("strong",{children:String((g==null?void 0:g.name)||"tool")}),s.jsxs("div",{className:"wait_tool_badges",children:[s.jsx("span",{className:"chip mono warn",children:"approval"}),Vx(g).map($=>s.jsxs("span",{className:"chip mono muted",title:Hx,children:[$,"~"]},$))]})]}),s.jsx("div",{className:"wait_tool_args",children:s.jsx(dr,{value:(g==null?void 0:g.arguments)||{},collapseAfterDepth:3,showCopy:!0})})]},`${String((g==null?void 0:g.name)||"tool")}:${S}`))}),Eo?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 Bd(c.trim(),"Cancelled from wait prompt"),disabled:!c.trim()||Et,children:"Cancel whole run"})}),s.jsxs("details",{className:"runtime_raw_details",children:[s.jsx("summary",{className:"mono muted",children:"Diagnostics"}),s.jsx("div",{className:"wait_shared_json",children:s.jsx(dr,{value:Wt||{},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:al||"No explicit prompt was provided. Open the ledger for context before responding."}),s.jsx(f2,{wait:Wt,disabled:Et,on_submit:g=>nl({response:g})}),s.jsx("div",{className:"actions",children:s.jsx("button",{className:"btn danger",onClick:()=>void Bd(c.trim(),"Cancelled from wait prompt"),disabled:!c.trim()||Et,children:"Cancel whole run"})}),s.jsxs("details",{className:"runtime_raw_details",children:[s.jsx("summary",{className:"mono muted",children:"Diagnostics"}),s.jsx("div",{className:"wait_shared_json",children:s.jsx(dr,{value:Wt||{},collapseAfterDepth:3,showCopy:!0})})]})]})]}):null]})]})]})}if("serviceWorker"in navigator){window.addEventListener("load",()=>{navigator.serviceWorker.register(l1).then(t=>t.update()).catch(()=>{})});let e=!1;navigator.serviceWorker.addEventListener("controllerchange",()=>{e||(e=!0,window.location.reload())})}nj();J0.createRoot(document.getElementById("root")).render(s.jsx(ve.StrictMode,{children:s.jsx(FL,{})}));
|
|
150
|
-
//# sourceMappingURL=index-DGir8JbI.js.map
|