@abstractframework/observer 0.6.0 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,150 +0,0 @@
1
- var H0=Object.defineProperty;var V0=(e,t,n)=>t in e?H0(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var Vr=(e,t,n)=>V0(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"]'))s(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"&&s(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 s(o){if(o.ep)return;o.ep=!0;const l=n(o);fetch(o.href,l)}})();function ng(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var f_={exports:{}},zd={},h_={exports:{}},Vt={};/**
2
- * @license React
3
- * react.production.min.js
4
- *
5
- * Copyright (c) Facebook, Inc. and its affiliates.
6
- *
7
- * This source code is licensed under the MIT license found in the
8
- * LICENSE file in the root directory of this source tree.
9
- */var ey;function G0(){if(ey)return Vt;ey=1;var e=Symbol.for("react.element"),t=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),s=Symbol.for("react.strict_mode"),o=Symbol.for("react.profiler"),l=Symbol.for("react.provider"),u=Symbol.for("react.context"),c=Symbol.for("react.forward_ref"),f=Symbol.for("react.suspense"),m=Symbol.for("react.memo"),p=Symbol.for("react.lazy"),g=Symbol.iterator;function w(R){return R===null||typeof R!="object"?null:(R=g&&R[g]||R["@@iterator"],typeof R=="function"?R:null)}var x={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},S=Object.assign,j={};function N(R,Z,X){this.props=R,this.context=Z,this.refs=j,this.updater=X||x}N.prototype.isReactComponent={},N.prototype.setState=function(R,Z){if(typeof R!="object"&&typeof R!="function"&&R!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,R,Z,"setState")},N.prototype.forceUpdate=function(R){this.updater.enqueueForceUpdate(this,R,"forceUpdate")};function C(){}C.prototype=N.prototype;function E(R,Z,X){this.props=R,this.context=Z,this.refs=j,this.updater=X||x}var T=E.prototype=new C;T.constructor=E,S(T,N.prototype),T.isPureReactComponent=!0;var I=Array.isArray,K=Object.prototype.hasOwnProperty,U={current:null},J={key:!0,ref:!0,__self:!0,__source:!0};function Y(R,Z,X){var Q,le={},ge=null,pe=null;if(Z!=null)for(Q in Z.ref!==void 0&&(pe=Z.ref),Z.key!==void 0&&(ge=""+Z.key),Z)K.call(Z,Q)&&!J.hasOwnProperty(Q)&&(le[Q]=Z[Q]);var ye=arguments.length-2;if(ye===1)le.children=X;else if(1<ye){for(var Ne=Array(ye),Ue=0;Ue<ye;Ue++)Ne[Ue]=arguments[Ue+2];le.children=Ne}if(R&&R.defaultProps)for(Q in ye=R.defaultProps,ye)le[Q]===void 0&&(le[Q]=ye[Q]);return{$$typeof:e,type:R,key:ge,ref:pe,props:le,_owner:U.current}}function se(R,Z){return{$$typeof:e,type:R.type,key:Z,ref:R.ref,props:R.props,_owner:R._owner}}function ce(R){return typeof R=="object"&&R!==null&&R.$$typeof===e}function fe(R){var Z={"=":"=0",":":"=2"};return"$"+R.replace(/[=:]/g,function(X){return Z[X]})}var W=/\/+/g;function P(R,Z){return typeof R=="object"&&R!==null&&R.key!=null?fe(""+R.key):Z.toString(36)}function A(R,Z,X,Q,le){var ge=typeof R;(ge==="undefined"||ge==="boolean")&&(R=null);var pe=!1;if(R===null)pe=!0;else switch(ge){case"string":case"number":pe=!0;break;case"object":switch(R.$$typeof){case e:case t:pe=!0}}if(pe)return pe=R,le=le(pe),R=Q===""?"."+P(pe,0):Q,I(le)?(X="",R!=null&&(X=R.replace(W,"$&/")+"/"),A(le,Z,X,"",function(Ue){return Ue})):le!=null&&(ce(le)&&(le=se(le,X+(!le.key||pe&&pe.key===le.key?"":(""+le.key).replace(W,"$&/")+"/")+R)),Z.push(le)),1;if(pe=0,Q=Q===""?".":Q+":",I(R))for(var ye=0;ye<R.length;ye++){ge=R[ye];var Ne=Q+P(ge,ye);pe+=A(ge,Z,X,Ne,le)}else if(Ne=w(R),typeof Ne=="function")for(R=Ne.call(R),ye=0;!(ge=R.next()).done;)ge=ge.value,Ne=Q+P(ge,ye++),pe+=A(ge,Z,X,Ne,le);else if(ge==="object")throw Z=String(R),Error("Objects are not valid as a React child (found: "+(Z==="[object Object]"?"object with keys {"+Object.keys(R).join(", ")+"}":Z)+"). If you meant to render a collection of children, use an array instead.");return pe}function z(R,Z,X){if(R==null)return R;var Q=[],le=0;return A(R,Q,"","",function(ge){return Z.call(X,ge,le++)}),Q}function $(R){if(R._status===-1){var Z=R._result;Z=Z(),Z.then(function(X){(R._status===0||R._status===-1)&&(R._status=1,R._result=X)},function(X){(R._status===0||R._status===-1)&&(R._status=2,R._result=X)}),R._status===-1&&(R._status=0,R._result=Z)}if(R._status===1)return R._result.default;throw R._result}var te={current:null},O={transition:null},F={ReactCurrentDispatcher:te,ReactCurrentBatchConfig:O,ReactCurrentOwner:U};function G(){throw Error("act(...) is not supported in production builds of React.")}return Vt.Children={map:z,forEach:function(R,Z,X){z(R,function(){Z.apply(this,arguments)},X)},count:function(R){var Z=0;return z(R,function(){Z++}),Z},toArray:function(R){return z(R,function(Z){return Z})||[]},only:function(R){if(!ce(R))throw Error("React.Children.only expected to receive a single React element child.");return R}},Vt.Component=N,Vt.Fragment=n,Vt.Profiler=o,Vt.PureComponent=E,Vt.StrictMode=s,Vt.Suspense=f,Vt.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=F,Vt.act=G,Vt.cloneElement=function(R,Z,X){if(R==null)throw Error("React.cloneElement(...): The argument must be a React element, but you passed "+R+".");var Q=S({},R.props),le=R.key,ge=R.ref,pe=R._owner;if(Z!=null){if(Z.ref!==void 0&&(ge=Z.ref,pe=U.current),Z.key!==void 0&&(le=""+Z.key),R.type&&R.type.defaultProps)var ye=R.type.defaultProps;for(Ne in Z)K.call(Z,Ne)&&!J.hasOwnProperty(Ne)&&(Q[Ne]=Z[Ne]===void 0&&ye!==void 0?ye[Ne]:Z[Ne])}var Ne=arguments.length-2;if(Ne===1)Q.children=X;else if(1<Ne){ye=Array(Ne);for(var Ue=0;Ue<Ne;Ue++)ye[Ue]=arguments[Ue+2];Q.children=ye}return{$$typeof:e,type:R.type,key:le,ref:ge,props:Q,_owner:pe}},Vt.createContext=function(R){return R={$$typeof:u,_currentValue:R,_currentValue2:R,_threadCount:0,Provider:null,Consumer:null,_defaultValue:null,_globalName:null},R.Provider={$$typeof:l,_context:R},R.Consumer=R},Vt.createElement=Y,Vt.createFactory=function(R){var Z=Y.bind(null,R);return Z.type=R,Z},Vt.createRef=function(){return{current:null}},Vt.forwardRef=function(R){return{$$typeof:c,render:R}},Vt.isValidElement=ce,Vt.lazy=function(R){return{$$typeof:p,_payload:{_status:-1,_result:R},_init:$}},Vt.memo=function(R,Z){return{$$typeof:m,type:R,compare:Z===void 0?null:Z}},Vt.startTransition=function(R){var Z=O.transition;O.transition={};try{R()}finally{O.transition=Z}},Vt.unstable_act=G,Vt.useCallback=function(R,Z){return te.current.useCallback(R,Z)},Vt.useContext=function(R){return te.current.useContext(R)},Vt.useDebugValue=function(){},Vt.useDeferredValue=function(R){return te.current.useDeferredValue(R)},Vt.useEffect=function(R,Z){return te.current.useEffect(R,Z)},Vt.useId=function(){return te.current.useId()},Vt.useImperativeHandle=function(R,Z,X){return te.current.useImperativeHandle(R,Z,X)},Vt.useInsertionEffect=function(R,Z){return te.current.useInsertionEffect(R,Z)},Vt.useLayoutEffect=function(R,Z){return te.current.useLayoutEffect(R,Z)},Vt.useMemo=function(R,Z){return te.current.useMemo(R,Z)},Vt.useReducer=function(R,Z,X){return te.current.useReducer(R,Z,X)},Vt.useRef=function(R){return te.current.useRef(R)},Vt.useState=function(R){return te.current.useState(R)},Vt.useSyncExternalStore=function(R,Z,X){return te.current.useSyncExternalStore(R,Z,X)},Vt.useTransition=function(){return te.current.useTransition()},Vt.version="18.3.1",Vt}var ty;function kf(){return ty||(ty=1,h_.exports=G0()),h_.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 ny;function K0(){if(ny)return zd;ny=1;var e=kf(),t=Symbol.for("react.element"),n=Symbol.for("react.fragment"),s=Object.prototype.hasOwnProperty,o=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,l={key:!0,ref:!0,__self:!0,__source:!0};function u(c,f,m){var p,g={},w=null,x=null;m!==void 0&&(w=""+m),f.key!==void 0&&(w=""+f.key),f.ref!==void 0&&(x=f.ref);for(p in f)s.call(f,p)&&!l.hasOwnProperty(p)&&(g[p]=f[p]);if(c&&c.defaultProps)for(p in f=c.defaultProps,f)g[p]===void 0&&(g[p]=f[p]);return{$$typeof:t,type:c,key:w,ref:x,props:g,_owner:o.current}}return zd.Fragment=n,zd.jsx=u,zd.jsxs=u,zd}var ry;function Y0(){return ry||(ry=1,f_.exports=K0()),f_.exports}var r=Y0(),_=kf();const ve=ng(_);var Sh={},m_={exports:{}},Fs={},__={exports:{}},p_={};/**
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 sy;function J0(){return sy||(sy=1,(function(e){function t(O,F){var G=O.length;O.push(F);e:for(;0<G;){var R=G-1>>>1,Z=O[R];if(0<o(Z,F))O[R]=F,O[G]=Z,G=R;else break e}}function n(O){return O.length===0?null:O[0]}function s(O){if(O.length===0)return null;var F=O[0],G=O.pop();if(G!==F){O[0]=G;e:for(var R=0,Z=O.length,X=Z>>>1;R<X;){var Q=2*(R+1)-1,le=O[Q],ge=Q+1,pe=O[ge];if(0>o(le,G))ge<Z&&0>o(pe,le)?(O[R]=pe,O[ge]=G,R=ge):(O[R]=le,O[Q]=G,R=Q);else if(ge<Z&&0>o(pe,G))O[R]=pe,O[ge]=G,R=ge;else break e}}return F}function o(O,F){var G=O.sortIndex-F.sortIndex;return G!==0?G:O.id-F.id}if(typeof performance=="object"&&typeof performance.now=="function"){var l=performance;e.unstable_now=function(){return l.now()}}else{var u=Date,c=u.now();e.unstable_now=function(){return u.now()-c}}var f=[],m=[],p=1,g=null,w=3,x=!1,S=!1,j=!1,N=typeof setTimeout=="function"?setTimeout:null,C=typeof clearTimeout=="function"?clearTimeout:null,E=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function T(O){for(var F=n(m);F!==null;){if(F.callback===null)s(m);else if(F.startTime<=O)s(m),F.sortIndex=F.expirationTime,t(f,F);else break;F=n(m)}}function I(O){if(j=!1,T(O),!S)if(n(f)!==null)S=!0,$(K);else{var F=n(m);F!==null&&te(I,F.startTime-O)}}function K(O,F){S=!1,j&&(j=!1,C(Y),Y=-1),x=!0;var G=w;try{for(T(F),g=n(f);g!==null&&(!(g.expirationTime>F)||O&&!fe());){var R=g.callback;if(typeof R=="function"){g.callback=null,w=g.priorityLevel;var Z=R(g.expirationTime<=F);F=e.unstable_now(),typeof Z=="function"?g.callback=Z:g===n(f)&&s(f),T(F)}else s(f);g=n(f)}if(g!==null)var X=!0;else{var Q=n(m);Q!==null&&te(I,Q.startTime-F),X=!1}return X}finally{g=null,w=G,x=!1}}var U=!1,J=null,Y=-1,se=5,ce=-1;function fe(){return!(e.unstable_now()-ce<se)}function W(){if(J!==null){var O=e.unstable_now();ce=O;var F=!0;try{F=J(!0,O)}finally{F?P():(U=!1,J=null)}}else U=!1}var P;if(typeof E=="function")P=function(){E(W)};else if(typeof MessageChannel<"u"){var A=new MessageChannel,z=A.port2;A.port1.onmessage=W,P=function(){z.postMessage(null)}}else P=function(){N(W,0)};function $(O){J=O,U||(U=!0,P())}function te(O,F){Y=N(function(){O(e.unstable_now())},F)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(O){O.callback=null},e.unstable_continueExecution=function(){S||x||(S=!0,$(K))},e.unstable_forceFrameRate=function(O){0>O||125<O?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):se=0<O?Math.floor(1e3/O):5},e.unstable_getCurrentPriorityLevel=function(){return w},e.unstable_getFirstCallbackNode=function(){return n(f)},e.unstable_next=function(O){switch(w){case 1:case 2:case 3:var F=3;break;default:F=w}var G=w;w=F;try{return O()}finally{w=G}},e.unstable_pauseExecution=function(){},e.unstable_requestPaint=function(){},e.unstable_runWithPriority=function(O,F){switch(O){case 1:case 2:case 3:case 4:case 5:break;default:O=3}var G=w;w=O;try{return F()}finally{w=G}},e.unstable_scheduleCallback=function(O,F,G){var R=e.unstable_now();switch(typeof G=="object"&&G!==null?(G=G.delay,G=typeof G=="number"&&0<G?R+G:R):G=R,O){case 1:var Z=-1;break;case 2:Z=250;break;case 5:Z=1073741823;break;case 4:Z=1e4;break;default:Z=5e3}return Z=G+Z,O={id:p++,callback:F,priorityLevel:O,startTime:G,expirationTime:Z,sortIndex:-1},G>R?(O.sortIndex=G,t(m,O),n(f)===null&&O===n(m)&&(j?(C(Y),Y=-1):j=!0,te(I,G-R))):(O.sortIndex=Z,t(f,O),S||x||(S=!0,$(K))),O},e.unstable_shouldYield=fe,e.unstable_wrapCallback=function(O){var F=w;return function(){var G=w;w=F;try{return O.apply(this,arguments)}finally{w=G}}}})(p_)),p_}var iy;function X0(){return iy||(iy=1,__.exports=J0()),__.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 oy;function Z0(){if(oy)return Fs;oy=1;var e=kf(),t=X0();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 s=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++)s.add(a[i])}var c=!(typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),f=Object.prototype.hasOwnProperty,m=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,p={},g={};function w(i){return f.call(g,i)?!0:f.call(p,i)?!1:m.test(i)?g[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 S(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,L){this.acceptsBooleans=a===2||a===3||a===4,this.attributeName=h,this.attributeNamespace=v,this.mustUseProperty=d,this.propertyName=i,this.type=a,this.sanitizeURL=b,this.removeEmptyString=L}var N={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(i){N[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];N[a]=new j(a,1,!1,i[1],null,!1,!1)}),["contentEditable","draggable","spellCheck","value"].forEach(function(i){N[i]=new j(i,2,!1,i.toLowerCase(),null,!1,!1)}),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(i){N[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){N[i]=new j(i,3,!1,i.toLowerCase(),null,!1,!1)}),["checked","multiple","muted","selected"].forEach(function(i){N[i]=new j(i,3,!0,i,null,!1,!1)}),["capture","download"].forEach(function(i){N[i]=new j(i,4,!1,i,null,!1,!1)}),["cols","rows","size","span"].forEach(function(i){N[i]=new j(i,6,!1,i,null,!1,!1)}),["rowSpan","start"].forEach(function(i){N[i]=new j(i,5,!1,i.toLowerCase(),null,!1,!1)});var C=/[\-:]([a-z])/g;function E(i){return i[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(i){var a=i.replace(C,E);N[a]=new 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(C,E);N[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(C,E);N[a]=new j(a,1,!1,i,"http://www.w3.org/XML/1998/namespace",!1,!1)}),["tabIndex","crossOrigin"].forEach(function(i){N[i]=new j(i,1,!1,i.toLowerCase(),null,!1,!1)}),N.xlinkHref=new j("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1),["src","href","action","formAction"].forEach(function(i){N[i]=new j(i,1,!1,i.toLowerCase(),null,!0,!0)});function T(i,a,d,h){var v=N.hasOwnProperty(a)?N[a]:null;(v!==null?v.type!==0:h||!(2<a.length)||a[0]!=="o"&&a[0]!=="O"||a[1]!=="n"&&a[1]!=="N")&&(S(a,d,v,h)&&(d=null),h||v===null?w(a)&&(d===null?i.removeAttribute(a):i.setAttribute(a,""+d)):v.mustUseProperty?i[v.propertyName]=d===null?v.type===3?!1:"":d:(a=v.attributeName,h=v.attributeNamespace,d===null?i.removeAttribute(a):(v=v.type,d=v===3||v===4&&d===!0?"":""+d,h?i.setAttributeNS(h,a,d):i.setAttribute(a,d))))}var I=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,K=Symbol.for("react.element"),U=Symbol.for("react.portal"),J=Symbol.for("react.fragment"),Y=Symbol.for("react.strict_mode"),se=Symbol.for("react.profiler"),ce=Symbol.for("react.provider"),fe=Symbol.for("react.context"),W=Symbol.for("react.forward_ref"),P=Symbol.for("react.suspense"),A=Symbol.for("react.suspense_list"),z=Symbol.for("react.memo"),$=Symbol.for("react.lazy"),te=Symbol.for("react.offscreen"),O=Symbol.iterator;function F(i){return i===null||typeof i!="object"?null:(i=O&&i[O]||i["@@iterator"],typeof i=="function"?i:null)}var G=Object.assign,R;function Z(i){if(R===void 0)try{throw Error()}catch(d){var a=d.stack.trim().match(/\n( *(at )?)/);R=a&&a[1]||""}return`
34
- `+R+i}var X=!1;function Q(i,a){if(!i||X)return"";X=!0;var d=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{if(a)if(a=function(){throw Error()},Object.defineProperty(a.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(a,[])}catch(we){var h=we}Reflect.construct(i,[],a)}else{try{a.call()}catch(we){h=we}i.call(a.prototype)}else{try{throw Error()}catch(we){h=we}i()}}catch(we){if(we&&h&&typeof we.stack=="string"){for(var v=we.stack.split(`
35
- `),b=h.stack.split(`
36
- `),L=v.length-1,ee=b.length-1;1<=L&&0<=ee&&v[L]!==b[ee];)ee--;for(;1<=L&&0<=ee;L--,ee--)if(v[L]!==b[ee]){if(L!==1||ee!==1)do if(L--,ee--,0>ee||v[L]!==b[ee]){var re=`
37
- `+v[L].replace(" at new "," at ");return i.displayName&&re.includes("<anonymous>")&&(re=re.replace("<anonymous>",i.displayName)),re}while(1<=L&&0<=ee);break}}}finally{X=!1,Error.prepareStackTrace=d}return(i=i?i.displayName||i.name:"")?Z(i):""}function le(i){switch(i.tag){case 5:return Z(i.type);case 16:return Z("Lazy");case 13:return Z("Suspense");case 19:return Z("SuspenseList");case 0:case 2:case 15:return i=Q(i.type,!1),i;case 11:return i=Q(i.type.render,!1),i;case 1:return i=Q(i.type,!0),i;default:return""}}function ge(i){if(i==null)return null;if(typeof i=="function")return i.displayName||i.name||null;if(typeof i=="string")return i;switch(i){case J:return"Fragment";case U:return"Portal";case se:return"Profiler";case Y:return"StrictMode";case P:return"Suspense";case A:return"SuspenseList"}if(typeof i=="object")switch(i.$$typeof){case fe:return(i.displayName||"Context")+".Consumer";case ce:return(i._context.displayName||"Context")+".Provider";case W:var a=i.render;return i=i.displayName,i||(i=a.displayName||a.name||"",i=i!==""?"ForwardRef("+i+")":"ForwardRef"),i;case z:return a=i.displayName||null,a!==null?a:ge(i.type)||"Memo";case $:a=i._payload,i=i._init;try{return ge(i(a))}catch{}}return null}function pe(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 ge(a);case 8:return a===Y?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof a=="function")return a.displayName||a.name||null;if(typeof a=="string")return a}return null}function ye(i){switch(typeof i){case"boolean":case"number":case"string":case"undefined":return i;case"object":return i;default:return""}}function Ne(i){var a=i.type;return(i=i.nodeName)&&i.toLowerCase()==="input"&&(a==="checkbox"||a==="radio")}function Ue(i){var a=Ne(i)?"checked":"value",d=Object.getOwnPropertyDescriptor(i.constructor.prototype,a),h=""+i[a];if(!i.hasOwnProperty(a)&&typeof d<"u"&&typeof d.get=="function"&&typeof d.set=="function"){var v=d.get,b=d.set;return Object.defineProperty(i,a,{configurable:!0,get:function(){return v.call(this)},set:function(L){h=""+L,b.call(this,L)}}),Object.defineProperty(i,a,{enumerable:d.enumerable}),{getValue:function(){return h},setValue:function(L){h=""+L},stopTracking:function(){i._valueTracker=null,delete i[a]}}}}function We(i){i._valueTracker||(i._valueTracker=Ue(i))}function pt(i){if(!i)return!1;var a=i._valueTracker;if(!a)return!0;var d=a.getValue(),h="";return i&&(h=Ne(i)?i.checked?"true":"false":i.value),i=h,i!==d?(a.setValue(i),!0):!1}function Fe(i){if(i=i||(typeof document<"u"?document:void 0),typeof i>"u")return null;try{return i.activeElement||i.body}catch{return i.body}}function tt(i,a){var d=a.checked;return G({},a,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:d??i._wrapperState.initialChecked})}function lt(i,a){var d=a.defaultValue==null?"":a.defaultValue,h=a.checked!=null?a.checked:a.defaultChecked;d=ye(a.value!=null?a.value:d),i._wrapperState={initialChecked:h,initialValue:d,controlled:a.type==="checkbox"||a.type==="radio"?a.checked!=null:a.value!=null}}function Ke(i,a){a=a.checked,a!=null&&T(i,"checked",a,!1)}function Se(i,a){Ke(i,a);var d=ye(a.value),h=a.type;if(d!=null)h==="number"?(d===0&&i.value===""||i.value!=d)&&(i.value=""+d):i.value!==""+d&&(i.value=""+d);else if(h==="submit"||h==="reset"){i.removeAttribute("value");return}a.hasOwnProperty("value")?ht(i,a.type,d):a.hasOwnProperty("defaultValue")&&ht(i,a.type,ye(a.defaultValue)),a.checked==null&&a.defaultChecked!=null&&(i.defaultChecked=!!a.defaultChecked)}function Re(i,a,d){if(a.hasOwnProperty("value")||a.hasOwnProperty("defaultValue")){var h=a.type;if(!(h!=="submit"&&h!=="reset"||a.value!==void 0&&a.value!==null))return;a=""+i._wrapperState.initialValue,d||a===i.value||(i.value=a),i.defaultValue=a}d=i.name,d!==""&&(i.name=""),i.defaultChecked=!!i._wrapperState.initialChecked,d!==""&&(i.name=d)}function ht(i,a,d){(a!=="number"||Fe(i.ownerDocument)!==i)&&(d==null?i.defaultValue=""+i._wrapperState.initialValue:i.defaultValue!==""+d&&(i.defaultValue=""+d))}var xe=Array.isArray;function Ie(i,a,d,h){if(i=i.options,a){a={};for(var v=0;v<d.length;v++)a["$"+d[v]]=!0;for(d=0;d<i.length;d++)v=a.hasOwnProperty("$"+i[d].value),i[d].selected!==v&&(i[d].selected=v),v&&h&&(i[d].defaultSelected=!0)}else{for(d=""+ye(d),a=null,v=0;v<i.length;v++){if(i[v].value===d){i[v].selected=!0,h&&(i[v].defaultSelected=!0);return}a!==null||i[v].disabled||(a=i[v])}a!==null&&(a.selected=!0)}}function qe(i,a){if(a.dangerouslySetInnerHTML!=null)throw Error(n(91));return G({},a,{value:void 0,defaultValue:void 0,children:""+i._wrapperState.initialValue})}function zt(i,a){var d=a.value;if(d==null){if(d=a.children,a=a.defaultValue,d!=null){if(a!=null)throw Error(n(92));if(xe(d)){if(1<d.length)throw Error(n(93));d=d[0]}a=d}a==null&&(a=""),d=a}i._wrapperState={initialValue:ye(d)}}function en(i,a){var d=ye(a.value),h=ye(a.defaultValue);d!=null&&(d=""+d,d!==i.value&&(i.value=d),a.defaultValue==null&&i.defaultValue!==d&&(i.defaultValue=d)),h!=null&&(i.defaultValue=""+h)}function bn(i){var a=i.textContent;a===i._wrapperState.initialValue&&a!==""&&a!==null&&(i.value=a)}function Wt(i){switch(i){case"svg":return"http://www.w3.org/2000/svg";case"math":return"http://www.w3.org/1998/Math/MathML";default:return"http://www.w3.org/1999/xhtml"}}function It(i,a){return i==null||i==="http://www.w3.org/1999/xhtml"?Wt(a):i==="http://www.w3.org/2000/svg"&&a==="foreignObject"?"http://www.w3.org/1999/xhtml":i}var kn,nr=(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(kn=kn||document.createElement("div"),kn.innerHTML="<svg>"+a.valueOf().toString()+"</svg>",a=kn.firstChild;i.firstChild;)i.removeChild(i.firstChild);for(;a.firstChild;)i.appendChild(a.firstChild)}});function Pt(i,a){if(a){var d=i.firstChild;if(d&&d===i.lastChild&&d.nodeType===3){d.nodeValue=a;return}}i.textContent=a}var pn={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},Bn=["Webkit","ms","Moz","O"];Object.keys(pn).forEach(function(i){Bn.forEach(function(a){a=a+i.charAt(0).toUpperCase()+i.substring(1),pn[a]=pn[i]})});function $n(i,a,d){return a==null||typeof a=="boolean"||a===""?"":d||typeof a!="number"||a===0||pn.hasOwnProperty(i)&&pn[i]?(""+a).trim():a+"px"}function gn(i,a){i=i.style;for(var d in a)if(a.hasOwnProperty(d)){var h=d.indexOf("--")===0,v=$n(d,a[d],h);d==="float"&&(d="cssFloat"),h?i.setProperty(d,v):i[d]=v}}var In=G({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function wn(i,a){if(a){if(In[i]&&(a.children!=null||a.dangerouslySetInnerHTML!=null))throw Error(n(137,i));if(a.dangerouslySetInnerHTML!=null){if(a.children!=null)throw Error(n(60));if(typeof a.dangerouslySetInnerHTML!="object"||!("__html"in a.dangerouslySetInnerHTML))throw Error(n(61))}if(a.style!=null&&typeof a.style!="object")throw Error(n(62))}}function jr(i,a){if(i.indexOf("-")===-1)return typeof a.is=="string";switch(i){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var Kn=null;function Sr(i){return i=i.target||i.srcElement||window,i.correspondingUseElement&&(i=i.correspondingUseElement),i.nodeType===3?i.parentNode:i}var Ns=null,Pn=null,ae=null;function je(i){if(i=Uo(i)){if(typeof Ns!="function")throw Error(n(280));var a=i.stateNode;a&&(a=Ma(a),Ns(i.stateNode,i.type,a))}}function Ye(i){Pn?ae?ae.push(i):ae=[i]:Pn=i}function Ge(){if(Pn){var i=Pn,a=ae;if(ae=Pn=null,je(i),a)for(i=0;i<a.length;i++)je(a[i])}}function st(i,a){return i(a)}function ct(){}var Et=!1;function jt(i,a,d){if(Et)return i(a,d);Et=!0;try{return st(i,a,d)}finally{Et=!1,(Pn!==null||ae!==null)&&(ct(),Ge())}}function Kt(i,a){var d=i.stateNode;if(d===null)return null;var h=Ma(d);if(h===null)return null;d=h[a];e:switch(a){case"onClick":case"onClickCapture":case"onDoubleClick":case"onDoubleClickCapture":case"onMouseDown":case"onMouseDownCapture":case"onMouseMove":case"onMouseMoveCapture":case"onMouseUp":case"onMouseUpCapture":case"onMouseEnter":(h=!h.disabled)||(i=i.type,h=!(i==="button"||i==="input"||i==="select"||i==="textarea")),i=!h;break e;default:i=!1}if(i)return null;if(d&&typeof d!="function")throw Error(n(231,a,typeof d));return d}var xt=!1;if(c)try{var Yt={};Object.defineProperty(Yt,"passive",{get:function(){xt=!0}}),window.addEventListener("test",Yt,Yt),window.removeEventListener("test",Yt,Yt)}catch{xt=!1}function qt(i,a,d,h,v,b,L,ee,re){var we=Array.prototype.slice.call(arguments,3);try{a.apply(d,we)}catch(Ae){this.onError(Ae)}}var Ot=!1,$t=null,At=!1,De=null,on={onError:function(i){Ot=!0,$t=i}};function dt(i,a,d,h,v,b,L,ee,re){Ot=!1,$t=null,qt.apply(on,arguments)}function tn(i,a,d,h,v,b,L,ee,re){if(dt.apply(this,arguments),Ot){if(Ot){var we=$t;Ot=!1,$t=null}else throw Error(n(198));At||(At=!0,De=we)}}function ft(i){var a=i,d=i;if(i.alternate)for(;a.return;)a=a.return;else{i=a;do a=i,(a.flags&4098)!==0&&(d=a.return),i=a.return;while(i)}return a.tag===3?d:null}function Un(i){if(i.tag===13){var a=i.memoizedState;if(a===null&&(i=i.alternate,i!==null&&(a=i.memoizedState)),a!==null)return a.dehydrated}return null}function an(i){if(ft(i)!==i)throw Error(n(188))}function Yr(i){var a=i.alternate;if(!a){if(a=ft(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 an(v),i;if(b===h)return an(v),a;b=b.sibling}throw Error(n(188))}if(d.return!==h.return)d=v,h=b;else{for(var L=!1,ee=v.child;ee;){if(ee===d){L=!0,d=v,h=b;break}if(ee===h){L=!0,h=v,d=b;break}ee=ee.sibling}if(!L){for(ee=b.child;ee;){if(ee===d){L=!0,d=b,h=v;break}if(ee===h){L=!0,h=b,d=v;break}ee=ee.sibling}if(!L)throw Error(n(189))}}if(d.alternate!==h)throw Error(n(190))}if(d.tag!==3)throw Error(n(188));return d.stateNode.current===d?i:a}function rr(i){return i=Yr(i),i!==null?Ws(i):null}function Ws(i){if(i.tag===5||i.tag===6)return i;for(i=i.child;i!==null;){var a=Ws(i);if(a!==null)return a;i=i.sibling}return null}var ds=t.unstable_scheduleCallback,ii=t.unstable_cancelCallback,oi=t.unstable_shouldYield,Or=t.unstable_requestPaint,ue=t.unstable_now,fs=t.unstable_getCurrentPriorityLevel,Vi=t.unstable_ImmediatePriority,hs=t.unstable_UserBlockingPriority,Cs=t.unstable_NormalPriority,qs=t.unstable_LowPriority,it=t.unstable_IdlePriority,cn=null,Dr=null;function Hs(i){if(Dr&&typeof Dr.onCommitFiberRoot=="function")try{Dr.onCommitFiberRoot(cn,i,void 0,(i.current.flags&128)===128)}catch{}}var sr=Math.clz32?Math.clz32:Ao,Eo=Math.log,$o=Math.LN2;function Ao(i){return i>>>=0,i===0?32:31-(Eo(i)/$o|0)|0}var On=64,ms=4194304;function Hn(i){switch(i&-i){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return i&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return i&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return i}}function Gi(i,a){var d=i.pendingLanes;if(d===0)return 0;var h=0,v=i.suspendedLanes,b=i.pingedLanes,L=d&268435455;if(L!==0){var ee=L&~v;ee!==0?h=Hn(ee):(b&=L,b!==0&&(h=Hn(b)))}else L=d&~v,L!==0?h=Hn(L):b!==0&&(h=Hn(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-sr(a),v=1<<d,h|=i[d],a&=~v;return h}function ai(i,a){switch(i){case 1:case 2:case 4:return a+250;case 8:case 16:case 32:case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return a+5e3;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return-1;case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function An(i,a){for(var d=i.suspendedLanes,h=i.pingedLanes,v=i.expirationTimes,b=i.pendingLanes;0<b;){var L=31-sr(b),ee=1<<L,re=v[L];re===-1?((ee&d)===0||(ee&h)!==0)&&(v[L]=ai(ee,a)):re<=a&&(i.expiredLanes|=ee),b&=~ee}}function Fr(i){return i=i.pendingLanes&-1073741825,i!==0?i:i&1073741824?1073741824:0}function hr(){var i=On;return On<<=1,(On&4194240)===0&&(On=64),i}function Jr(i){for(var a=[],d=0;31>d;d++)a.push(i);return a}function mr(i,a,d){i.pendingLanes|=a,a!==536870912&&(i.suspendedLanes=0,i.pingedLanes=0),i=i.eventTimes,a=31-sr(a),i[a]=d}function da(i,a){var d=i.pendingLanes&~a;i.pendingLanes=a,i.suspendedLanes=0,i.pingedLanes=0,i.expiredLanes&=a,i.mutableReadLanes&=a,i.entangledLanes&=a,a=i.entanglements;var h=i.eventTimes;for(i=i.expirationTimes;0<d;){var v=31-sr(d),b=1<<v;a[v]=0,h[v]=-1,i[v]=-1,d&=~b}}function Ki(i,a){var d=i.entangledLanes|=a;for(i=i.entanglements;d;){var h=31-sr(d),v=1<<h;v&a|i[h]&a&&(i[h]|=a),d&=~v}}var ln=0;function fa(i){return i&=-i,1<i?4<i?(i&268435455)!==0?16:536870912:4:1}var uc,To,_r,Es,$s,Yi=!1,_s=[],kr=null,ps=null,As=null,Xr=new Map,ki=new Map,ir=[],Ts="mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput copy cut paste click change contextmenu reset submit".split(" ");function ha(i,a){switch(i){case"focusin":case"focusout":kr=null;break;case"dragenter":case"dragleave":ps=null;break;case"mouseover":case"mouseout":As=null;break;case"pointerover":case"pointerout":Xr.delete(a.pointerId);break;case"gotpointercapture":case"lostpointercapture":ki.delete(a.pointerId)}}function gs(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=Uo(a),a!==null&&To(a)),i):(i.eventSystemFlags|=h,a=i.targetContainers,v!==null&&a.indexOf(v)===-1&&a.push(v),i)}function Ji(i,a,d,h,v){switch(a){case"focusin":return kr=gs(kr,i,a,d,h,v),!0;case"dragenter":return ps=gs(ps,i,a,d,h,v),!0;case"mouseover":return As=gs(As,i,a,d,h,v),!0;case"pointerover":var b=v.pointerId;return Xr.set(b,gs(Xr.get(b)||null,i,a,d,h,v)),!0;case"gotpointercapture":return b=v.pointerId,ki.set(b,gs(ki.get(b)||null,i,a,d,h,v)),!0}return!1}function dc(i){var a=Gs(i.target);if(a!==null){var d=ft(a);if(d!==null){if(a=d.tag,a===13){if(a=Un(d),a!==null){i.blockedOn=a,$s(i.priority,function(){_r(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 Ni(i){if(i.blockedOn!==null)return!1;for(var a=i.targetContainers;0<a.length;){var d=ie(i.domEventName,i.eventSystemFlags,a[0],i.nativeEvent);if(d===null){d=i.nativeEvent;var h=new d.constructor(d.type,d);Kn=h,d.target.dispatchEvent(h),Kn=null}else return a=Uo(d),a!==null&&To(a),i.blockedOn=d,!1;a.shift()}return!0}function Zr(i,a,d){Ni(i)&&d.delete(a)}function Au(){Yi=!1,kr!==null&&Ni(kr)&&(kr=null),ps!==null&&Ni(ps)&&(ps=null),As!==null&&Ni(As)&&(As=null),Xr.forEach(Zr),ki.forEach(Zr)}function Qr(i,a){i.blockedOn===a&&(i.blockedOn=null,Yi||(Yi=!0,t.unstable_scheduleCallback(t.unstable_NormalPriority,Au)))}function Xi(i){function a(v){return Qr(v,i)}if(0<_s.length){Qr(_s[0],i);for(var d=1;d<_s.length;d++){var h=_s[d];h.blockedOn===i&&(h.blockedOn=null)}}for(kr!==null&&Qr(kr,i),ps!==null&&Qr(ps,i),As!==null&&Qr(As,i),Xr.forEach(a),ki.forEach(a),d=0;d<ir.length;d++)h=ir[d],h.blockedOn===i&&(h.blockedOn=null);for(;0<ir.length&&(d=ir[0],d.blockedOn===null);)dc(d),d.blockedOn===null&&ir.shift()}var es=I.ReactCurrentBatchConfig,Mo=!0;function li(i,a,d,h){var v=ln,b=es.transition;es.transition=null;try{ln=1,ci(i,a,d,h)}finally{ln=v,es.transition=b}}function al(i,a,d,h){var v=ln,b=es.transition;es.transition=null;try{ln=4,ci(i,a,d,h)}finally{ln=v,es.transition=b}}function ci(i,a,d,h){if(Mo){var v=ie(i,a,d,h);if(v===null)Yu(i,a,h,B,d),ha(i,h);else if(Ji(v,i,a,d,h))h.stopPropagation();else if(ha(i,h),a&4&&-1<Ts.indexOf(i)){for(;v!==null;){var b=Uo(v);if(b!==null&&uc(b),b=ie(i,a,d,h),b===null&&Yu(i,a,h,B,d),b===v)break;v=b}v!==null&&h.stopPropagation()}else Yu(i,a,h,null,d)}}var B=null;function ie(i,a,d,h){if(B=null,i=Sr(h),i=Gs(i),i!==null)if(a=ft(i),a===null)i=null;else if(d=a.tag,d===13){if(i=Un(a),i!==null)return i;i=null}else if(d===3){if(a.stateNode.current.memoizedState.isDehydrated)return a.tag===3?a.stateNode.containerInfo:null;i=null}else a!==i&&(i=null);return B=i,null}function be(i){switch(i){case"cancel":case"click":case"close":case"contextmenu":case"copy":case"cut":case"auxclick":case"dblclick":case"dragend":case"dragstart":case"drop":case"focusin":case"focusout":case"input":case"invalid":case"keydown":case"keypress":case"keyup":case"mousedown":case"mouseup":case"paste":case"pause":case"play":case"pointercancel":case"pointerdown":case"pointerup":case"ratechange":case"reset":case"resize":case"seeked":case"submit":case"touchcancel":case"touchend":case"touchstart":case"volumechange":case"change":case"selectionchange":case"textInput":case"compositionstart":case"compositionend":case"compositionupdate":case"beforeblur":case"afterblur":case"beforeinput":case"blur":case"fullscreenchange":case"focus":case"hashchange":case"popstate":case"select":case"selectstart":return 1;case"drag":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"mousemove":case"mouseout":case"mouseover":case"pointermove":case"pointerout":case"pointerover":case"scroll":case"toggle":case"touchmove":case"wheel":case"mouseenter":case"mouseleave":case"pointerenter":case"pointerleave":return 4;case"message":switch(fs()){case Vi:return 1;case hs:return 4;case Cs:case qs:return 16;case it:return 536870912;default:return 16}default:return 16}}var ke=null,Ee=null,He=null;function Qe(){if(He)return He;var i,a=Ee,d=a.length,h,v="value"in ke?ke.value:ke.textContent,b=v.length;for(i=0;i<d&&a[i]===v[i];i++);var L=d-i;for(h=1;h<=L&&a[d-h]===v[b-h];h++);return He=v.slice(i,1<h?1-h:void 0)}function ot(i){var a=i.keyCode;return"charCode"in i?(i=i.charCode,i===0&&a===13&&(i=13)):i=a,i===10&&(i=13),32<=i||i===13?i:0}function mt(){return!0}function Dt(){return!1}function Xt(i){function a(d,h,v,b,L){this._reactName=d,this._targetInst=v,this.type=h,this.nativeEvent=b,this.target=L,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)?mt:Dt,this.isPropagationStopped=Dt,this}return G(a.prototype,{preventDefault:function(){this.defaultPrevented=!0;var d=this.nativeEvent;d&&(d.preventDefault?d.preventDefault():typeof d.returnValue!="unknown"&&(d.returnValue=!1),this.isDefaultPrevented=mt)},stopPropagation:function(){var d=this.nativeEvent;d&&(d.stopPropagation?d.stopPropagation():typeof d.cancelBubble!="unknown"&&(d.cancelBubble=!0),this.isPropagationStopped=mt)},persist:function(){},isPersistent:mt}),a}var Xn={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(i){return i.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},Bt=Xt(Xn),un=G({},Xn,{view:0,detail:0}),vn=Xt(un),jn,pr,Nr,ys=G({},un,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:Iu,button:0,buttons:0,relatedTarget:function(i){return i.relatedTarget===void 0?i.fromElement===i.srcElement?i.toElement:i.fromElement:i.relatedTarget},movementX:function(i){return"movementX"in i?i.movementX:(i!==Nr&&(Nr&&i.type==="mousemove"?(jn=i.screenX-Nr.screenX,pr=i.screenY-Nr.screenY):pr=jn=0,Nr=i),jn)},movementY:function(i){return"movementY"in i?i.movementY:pr}}),Ro=Xt(ys),Lo=G({},ys,{dataTransfer:0}),ll=Xt(Lo),fc=G({},un,{relatedTarget:0}),hc=Xt(fc),mc=G({},Xn,{animationName:0,elapsedTime:0,pseudoElement:0}),Tu=Xt(mc),_c=G({},Xn,{clipboardData:function(i){return"clipboardData"in i?i.clipboardData:window.clipboardData}}),pc=Xt(_c),gc=G({},Xn,{data:0}),Mu=Xt(gc),Io={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},Rf={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"},Ru={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function Lu(i){var a=this.nativeEvent;return a.getModifierState?a.getModifierState(i):(i=Ru[i])?!!a[i]:!1}function Iu(){return Lu}var Pu=G({},un,{key:function(i){if(i.key){var a=Io[i.key]||i.key;if(a!=="Unidentified")return a}return i.type==="keypress"?(i=ot(i),i===13?"Enter":String.fromCharCode(i)):i.type==="keydown"||i.type==="keyup"?Rf[i.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:Iu,charCode:function(i){return i.type==="keypress"?ot(i):0},keyCode:function(i){return i.type==="keydown"||i.type==="keyup"?i.keyCode:0},which:function(i){return i.type==="keypress"?ot(i):i.type==="keydown"||i.type==="keyup"?i.keyCode:0}}),Ou=Xt(Pu),nn=G({},ys,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),yc=Xt(nn),Dm=G({},un,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:Iu}),Du=Xt(Dm),Fm=G({},Xn,{propertyName:0,elapsedTime:0,pseudoElement:0}),Fu=Xt(Fm),zm=G({},ys,{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}),ts=Xt(zm),Zi=[9,13,27,32],wc=c&&"CompositionEvent"in window,cl=null;c&&"documentMode"in document&&(cl=document.documentMode);var ma=c&&"TextEvent"in window&&!cl,vc=c&&(!wc||cl&&8<cl&&11>=cl),_a=" ",zu=!1;function Lf(i,a){switch(i){case"keyup":return Zi.indexOf(a.keyCode)!==-1;case"keydown":return a.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function If(i){return i=i.detail,typeof i=="object"&&"data"in i?i.data:null}var pa=!1;function Pf(i,a){switch(i){case"compositionend":return If(a);case"keypress":return a.which!==32?null:(zu=!0,_a);case"textInput":return i=a.data,i===_a&&zu?null:i;default:return null}}function Bm(i,a){if(pa)return i==="compositionend"||!wc&&Lf(i,a)?(i=Qe(),He=Ee=ke=null,pa=!1,i):null;switch(i){case"paste":return null;case"keypress":if(!(a.ctrlKey||a.altKey||a.metaKey)||a.ctrlKey&&a.altKey){if(a.char&&1<a.char.length)return a.char;if(a.which)return String.fromCharCode(a.which)}return null;case"compositionend":return vc&&a.locale!=="ko"?null:a.data;default:return null}}var Of={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 Df(i){var a=i&&i.nodeName&&i.nodeName.toLowerCase();return a==="input"?!!Of[i.type]:a==="textarea"}function Bu(i,a,d,h){Ye(h),a=Sc(a,"onChange"),0<a.length&&(d=new Bt("onChange","change",null,d,h),i.push({event:d,listeners:a}))}var ga=null,Po=null;function ya(i){bc(i,0)}function Qi(i){var a=Ks(i);if(pt(a))return i}function wa(i,a){if(i==="change")return a}var va=!1;if(c){var xa;if(c){var ul="oninput"in document;if(!ul){var Uu=document.createElement("div");Uu.setAttribute("oninput","return;"),ul=typeof Uu.oninput=="function"}xa=ul}else xa=!1;va=xa&&(!document.documentMode||9<document.documentMode)}function ba(){ga&&(ga.detachEvent("onpropertychange",Wu),Po=ga=null)}function Wu(i){if(i.propertyName==="value"&&Qi(Po)){var a=[];Bu(a,Po,i,Sr(i)),jt(ya,a)}}function dl(i,a,d){i==="focusin"?(ba(),ga=a,Po=d,ga.attachEvent("onpropertychange",Wu)):i==="focusout"&&ba()}function fl(i){if(i==="selectionchange"||i==="keyup"||i==="keydown")return Qi(Po)}function Um(i,a){if(i==="click")return Qi(a)}function qu(i,a){if(i==="input"||i==="change")return Qi(a)}function Wm(i,a){return i===a&&(i!==0||1/i===1/a)||i!==i&&a!==a}var Vs=typeof Object.is=="function"?Object.is:Wm;function eo(i,a){if(Vs(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)||!Vs(i[v],a[v]))return!1}return!0}function ui(i){for(;i&&i.firstChild;)i=i.firstChild;return i}function Oo(i,a){var d=ui(i);i=0;for(var h;d;){if(d.nodeType===3){if(h=i+d.textContent.length,i<=a&&h>=a)return{node:d,offset:a-i};i=h}e:{for(;d;){if(d.nextSibling){d=d.nextSibling;break e}d=d.parentNode}d=void 0}d=ui(d)}}function Ff(i,a){return i&&a?i===a?!0:i&&i.nodeType===3?!1:a&&a.nodeType===3?Ff(i,a.parentNode):"contains"in i?i.contains(a):i.compareDocumentPosition?!!(i.compareDocumentPosition(a)&16):!1:!1}function hl(){for(var i=window,a=Fe();a instanceof i.HTMLIFrameElement;){try{var d=typeof a.contentWindow.location.href=="string"}catch{d=!1}if(d)i=a.contentWindow;else break;a=Fe(i.document)}return a}function Hu(i){var a=i&&i.nodeName&&i.nodeName.toLowerCase();return a&&(a==="input"&&(i.type==="text"||i.type==="search"||i.type==="tel"||i.type==="url"||i.type==="password")||a==="textarea"||i.contentEditable==="true")}function Vu(i){var a=hl(),d=i.focusedElem,h=i.selectionRange;if(a!==d&&d&&d.ownerDocument&&Ff(d.ownerDocument.documentElement,d)){if(h!==null&&Hu(d)){if(a=h.start,i=h.end,i===void 0&&(i=a),"selectionStart"in d)d.selectionStart=a,d.selectionEnd=Math.min(i,d.value.length);else if(i=(a=d.ownerDocument||document)&&a.defaultView||window,i.getSelection){i=i.getSelection();var v=d.textContent.length,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=Oo(d,b);var L=Oo(d,h);v&&L&&(i.rangeCount!==1||i.anchorNode!==v.node||i.anchorOffset!==v.offset||i.focusNode!==L.node||i.focusOffset!==L.offset)&&(a=a.createRange(),a.setStart(v.node,v.offset),i.removeAllRanges(),b>h?(i.addRange(a),i.extend(L.node,L.offset)):(a.setEnd(L.node,L.offset),i.addRange(a)))}}for(a=[],i=d;i=i.parentNode;)i.nodeType===1&&a.push({element:i,left:i.scrollLeft,top:i.scrollTop});for(typeof d.focus=="function"&&d.focus(),d=0;d<a.length;d++)i=a[d],i.element.scrollLeft=i.left,i.element.scrollTop=i.top}}var ml=c&&"documentMode"in document&&11>=document.documentMode,gr=null,di=null,to=null,no=!1;function xc(i,a,d){var h=d.window===d?d.document:d.nodeType===9?d:d.ownerDocument;no||gr==null||gr!==Fe(h)||(h=gr,"selectionStart"in h&&Hu(h)?h={start:h.selectionStart,end:h.selectionEnd}:(h=(h.ownerDocument&&h.ownerDocument.defaultView||window).getSelection(),h={anchorNode:h.anchorNode,anchorOffset:h.anchorOffset,focusNode:h.focusNode,focusOffset:h.focusOffset}),to&&eo(to,h)||(to=h,h=Sc(di,"onSelect"),0<h.length&&(a=new Bt("onSelect","select",null,a,d),i.push({event:a,listeners:h}),a.target=gr)))}function ro(i,a){var d={};return d[i.toLowerCase()]=a.toLowerCase(),d["Webkit"+i]="webkit"+a,d["Moz"+i]="moz"+a,d}var ws={animationend:ro("Animation","AnimationEnd"),animationiteration:ro("Animation","AnimationIteration"),animationstart:ro("Animation","AnimationStart"),transitionend:ro("Transition","TransitionEnd")},ja={},Sa={};c&&(Sa=document.createElement("div").style,"AnimationEvent"in window||(delete ws.animationend.animation,delete ws.animationiteration.animation,delete ws.animationstart.animation),"TransitionEvent"in window||delete ws.transitionend.transition);function Ci(i){if(ja[i])return ja[i];if(!ws[i])return i;var a=ws[i],d;for(d in a)if(a.hasOwnProperty(d)&&d in Sa)return ja[i]=a[d];return i}var Ei=Ci("animationend"),zr=Ci("animationiteration"),so=Ci("animationstart"),Do=Ci("transitionend"),_l=new Map,io="abort auxClick cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll toggle touchMove waiting wheel".split(" ");function fi(i,a){_l.set(i,a),l(a,[i])}for(var ka=0;ka<io.length;ka++){var Ms=io[ka],oo=Ms.toLowerCase(),hi=Ms[0].toUpperCase()+Ms.slice(1);fi(oo,"on"+hi)}fi(Ei,"onAnimationEnd"),fi(zr,"onAnimationIteration"),fi(so,"onAnimationStart"),fi("dblclick","onDoubleClick"),fi("focusin","onFocus"),fi("focusout","onBlur"),fi(Do,"onTransitionEnd"),u("onMouseEnter",["mouseout","mouseover"]),u("onMouseLeave",["mouseout","mouseover"]),u("onPointerEnter",["pointerout","pointerover"]),u("onPointerLeave",["pointerout","pointerover"]),l("onChange","change click focusin focusout input keydown keyup selectionchange".split(" ")),l("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" ")),l("onBeforeInput",["compositionend","keypress","textInput","paste"]),l("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" ")),l("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" ")),l("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var Na="abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange resize seeked seeking stalled suspend timeupdate volumechange waiting".split(" "),pl=new Set("cancel close invalid load scroll toggle".split(" ").concat(Na));function Gu(i,a,d){var h=i.type||"unknown-event";i.currentTarget=d,tn(h,a,void 0,i),i.currentTarget=null}function bc(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 L=h.length-1;0<=L;L--){var ee=h[L],re=ee.instance,we=ee.currentTarget;if(ee=ee.listener,re!==b&&v.isPropagationStopped())break e;Gu(v,ee,we),b=re}else for(L=0;L<h.length;L++){if(ee=h[L],re=ee.instance,we=ee.currentTarget,ee=ee.listener,re!==b&&v.isPropagationStopped())break e;Gu(v,ee,we),b=re}}}if(At)throw i=De,At=!1,De=null,i}function Nn(i,a){var d=a[Bo];d===void 0&&(d=a[Bo]=new Set);var h=i+"__bubble";d.has(h)||(Ku(a,i,2,!1),d.add(h))}function jc(i,a,d){var h=0;a&&(h|=4),Ku(d,i,h,a)}var gl="_reactListening"+Math.random().toString(36).slice(2);function yl(i){if(!i[gl]){i[gl]=!0,s.forEach(function(d){d!=="selectionchange"&&(pl.has(d)||jc(d,!1,i),jc(d,!0,i))});var a=i.nodeType===9?i:i.ownerDocument;a===null||a[gl]||(a[gl]=!0,jc("selectionchange",!1,a))}}function Ku(i,a,d,h){switch(be(a)){case 1:var v=li;break;case 4:v=al;break;default:v=ci}d=v.bind(null,a,d,i),v=void 0,!xt||a!=="touchstart"&&a!=="touchmove"&&a!=="wheel"||(v=!0),h?v!==void 0?i.addEventListener(a,d,{capture:!0,passive:v}):i.addEventListener(a,d,!0):v!==void 0?i.addEventListener(a,d,{passive:v}):i.addEventListener(a,d,!1)}function Yu(i,a,d,h,v){var b=h;if((a&1)===0&&(a&2)===0&&h!==null)e:for(;;){if(h===null)return;var L=h.tag;if(L===3||L===4){var ee=h.stateNode.containerInfo;if(ee===v||ee.nodeType===8&&ee.parentNode===v)break;if(L===4)for(L=h.return;L!==null;){var re=L.tag;if((re===3||re===4)&&(re=L.stateNode.containerInfo,re===v||re.nodeType===8&&re.parentNode===v))return;L=L.return}for(;ee!==null;){if(L=Gs(ee),L===null)return;if(re=L.tag,re===5||re===6){h=b=L;continue e}ee=ee.parentNode}}h=h.return}jt(function(){var we=b,Ae=Sr(d),Me=[];e:{var Ce=_l.get(i);if(Ce!==void 0){var Je=Bt,nt=i;switch(i){case"keypress":if(ot(d)===0)break e;case"keydown":case"keyup":Je=Ou;break;case"focusin":nt="focus",Je=hc;break;case"focusout":nt="blur",Je=hc;break;case"beforeblur":case"afterblur":Je=hc;break;case"click":if(d.button===2)break e;case"auxclick":case"dblclick":case"mousedown":case"mousemove":case"mouseup":case"mouseout":case"mouseover":case"contextmenu":Je=Ro;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":Je=ll;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":Je=Du;break;case Ei:case zr:case so:Je=Tu;break;case Do:Je=Fu;break;case"scroll":Je=vn;break;case"wheel":Je=ts;break;case"copy":case"cut":case"paste":Je=pc;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":Je=yc}var rt=(a&4)!==0,tr=!rt&&i==="scroll",de=rt?Ce!==null?Ce+"Capture":null:Ce;rt=[];for(var oe=we,me;oe!==null;){me=oe;var Oe=me.stateNode;if(me.tag===5&&Oe!==null&&(me=Oe,de!==null&&(Oe=Kt(oe,de),Oe!=null&&rt.push(Ca(oe,Oe,me)))),tr)break;oe=oe.return}0<rt.length&&(Ce=new Je(Ce,nt,null,d,Ae),Me.push({event:Ce,listeners:rt}))}}if((a&7)===0){e:{if(Ce=i==="mouseover"||i==="pointerover",Je=i==="mouseout"||i==="pointerout",Ce&&d!==Kn&&(nt=d.relatedTarget||d.fromElement)&&(Gs(nt)||nt[vs]))break e;if((Je||Ce)&&(Ce=Ae.window===Ae?Ae:(Ce=Ae.ownerDocument)?Ce.defaultView||Ce.parentWindow:window,Je?(nt=d.relatedTarget||d.toElement,Je=we,nt=nt?Gs(nt):null,nt!==null&&(tr=ft(nt),nt!==tr||nt.tag!==5&&nt.tag!==6)&&(nt=null)):(Je=null,nt=we),Je!==nt)){if(rt=Ro,Oe="onMouseLeave",de="onMouseEnter",oe="mouse",(i==="pointerout"||i==="pointerover")&&(rt=yc,Oe="onPointerLeave",de="onPointerEnter",oe="pointer"),tr=Je==null?Ce:Ks(Je),me=nt==null?Ce:Ks(nt),Ce=new rt(Oe,oe+"leave",Je,d,Ae),Ce.target=tr,Ce.relatedTarget=me,Oe=null,Gs(Ae)===we&&(rt=new rt(de,oe+"enter",nt,d,Ae),rt.target=me,rt.relatedTarget=tr,Oe=rt),tr=Oe,Je&&nt)t:{for(rt=Je,de=nt,oe=0,me=rt;me;me=Fo(me))oe++;for(me=0,Oe=de;Oe;Oe=Fo(Oe))me++;for(;0<oe-me;)rt=Fo(rt),oe--;for(;0<me-oe;)de=Fo(de),me--;for(;oe--;){if(rt===de||de!==null&&rt===de.alternate)break t;rt=Fo(rt),de=Fo(de)}rt=null}else rt=null;Je!==null&&zf(Me,Ce,Je,rt,!1),nt!==null&&tr!==null&&zf(Me,tr,nt,rt,!0)}}e:{if(Ce=we?Ks(we):window,Je=Ce.nodeName&&Ce.nodeName.toLowerCase(),Je==="select"||Je==="input"&&Ce.type==="file")var at=wa;else if(Df(Ce))if(va)at=qu;else{at=fl;var gt=dl}else(Je=Ce.nodeName)&&Je.toLowerCase()==="input"&&(Ce.type==="checkbox"||Ce.type==="radio")&&(at=Um);if(at&&(at=at(i,we))){Bu(Me,at,d,Ae);break e}gt&&gt(i,Ce,we),i==="focusout"&&(gt=Ce._wrapperState)&&gt.controlled&&Ce.type==="number"&&ht(Ce,"number",Ce.value)}switch(gt=we?Ks(we):window,i){case"focusin":(Df(gt)||gt.contentEditable==="true")&&(gr=gt,di=we,to=null);break;case"focusout":to=di=gr=null;break;case"mousedown":no=!0;break;case"contextmenu":case"mouseup":case"dragend":no=!1,xc(Me,d,Ae);break;case"selectionchange":if(ml)break;case"keydown":case"keyup":xc(Me,d,Ae)}var yt;if(wc)e:{switch(i){case"compositionstart":var Nt="onCompositionStart";break e;case"compositionend":Nt="onCompositionEnd";break e;case"compositionupdate":Nt="onCompositionUpdate";break e}Nt=void 0}else pa?Lf(i,d)&&(Nt="onCompositionEnd"):i==="keydown"&&d.keyCode===229&&(Nt="onCompositionStart");Nt&&(vc&&d.locale!=="ko"&&(pa||Nt!=="onCompositionStart"?Nt==="onCompositionEnd"&&pa&&(yt=Qe()):(ke=Ae,Ee="value"in ke?ke.value:ke.textContent,pa=!0)),gt=Sc(we,Nt),0<gt.length&&(Nt=new Mu(Nt,i,null,d,Ae),Me.push({event:Nt,listeners:gt}),yt?Nt.data=yt:(yt=If(d),yt!==null&&(Nt.data=yt)))),(yt=ma?Pf(i,d):Bm(i,d))&&(we=Sc(we,"onBeforeInput"),0<we.length&&(Ae=new Mu("onBeforeInput","beforeinput",null,d,Ae),Me.push({event:Ae,listeners:we}),Ae.data=yt))}bc(Me,a)})}function Ca(i,a,d){return{instance:i,listener:a,currentTarget:d}}function Sc(i,a){for(var d=a+"Capture",h=[];i!==null;){var v=i,b=v.stateNode;v.tag===5&&b!==null&&(v=b,b=Kt(i,d),b!=null&&h.unshift(Ca(i,b,v)),b=Kt(i,a),b!=null&&h.push(Ca(i,b,v))),i=i.return}return h}function Fo(i){if(i===null)return null;do i=i.return;while(i&&i.tag!==5);return i||null}function zf(i,a,d,h,v){for(var b=a._reactName,L=[];d!==null&&d!==h;){var ee=d,re=ee.alternate,we=ee.stateNode;if(re!==null&&re===h)break;ee.tag===5&&we!==null&&(ee=we,v?(re=Kt(d,b),re!=null&&L.unshift(Ca(d,re,ee))):v||(re=Kt(d,b),re!=null&&L.push(Ca(d,re,ee)))),d=d.return}L.length!==0&&i.push({event:a,listeners:L})}var Bf=/\r\n?/g,qm=/\u0000|\uFFFD/g;function Ju(i){return(typeof i=="string"?i:""+i).replace(Bf,`
38
- `).replace(qm,"")}function ao(i,a,d){if(a=Ju(a),Ju(i)!==a&&d)throw Error(n(425))}function kc(){}var zo=null,wl=null;function Ea(i,a){return i==="textarea"||i==="noscript"||typeof a.children=="string"||typeof a.children=="number"||typeof a.dangerouslySetInnerHTML=="object"&&a.dangerouslySetInnerHTML!==null&&a.dangerouslySetInnerHTML.__html!=null}var Nc=typeof setTimeout=="function"?setTimeout:void 0,$a=typeof clearTimeout=="function"?clearTimeout:void 0,Uf=typeof Promise=="function"?Promise:void 0,Cc=typeof queueMicrotask=="function"?queueMicrotask:typeof Uf<"u"?function(i){return Uf.resolve(null).then(i).catch(Hm)}:Nc;function Hm(i){setTimeout(function(){throw i})}function lo(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),Xi(a);return}h--}else d!=="$"&&d!=="$?"&&d!=="$!"||h++;d=v}while(d);Xi(a)}function co(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 vl(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 Aa=Math.random().toString(36).slice(2),yr="__reactFiber$"+Aa,Ta="__reactProps$"+Aa,vs="__reactContainer$"+Aa,Bo="__reactEvents$"+Aa,Wf="__reactListeners$"+Aa,Xu="__reactHandles$"+Aa;function Gs(i){var a=i[yr];if(a)return a;for(var d=i.parentNode;d;){if(a=d[vs]||d[yr]){if(d=a.alternate,a.child!==null||d!==null&&d.child!==null)for(i=vl(i);i!==null;){if(d=i[yr])return d;i=vl(i)}return a}i=d,d=i.parentNode}return null}function Uo(i){return i=i[yr]||i[vs],!i||i.tag!==5&&i.tag!==6&&i.tag!==13&&i.tag!==3?null:i}function Ks(i){if(i.tag===5||i.tag===6)return i.stateNode;throw Error(n(33))}function Ma(i){return i[Ta]||null}var Zu=[],uo=-1;function $i(i){return{current:i}}function En(i){0>uo||(i.current=Zu[uo],Zu[uo]=null,uo--)}function Cn(i,a){uo++,Zu[uo]=i.current,i.current=a}var xs={},fn=$i(xs),wr=$i(!1),Ai=xs;function Ra(i,a){var d=i.type.contextTypes;if(!d)return xs;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 ns(i){return i=i.childContextTypes,i!=null}function La(){En(wr),En(fn)}function qf(i,a,d){if(fn.current!==xs)throw Error(n(168));Cn(fn,a),Cn(wr,d)}function xl(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,pe(i)||"Unknown",v));return G({},d,h)}function bl(i){return i=(i=i.stateNode)&&i.__reactInternalMemoizedMergedChildContext||xs,Ai=fn.current,Cn(fn,i),Cn(wr,wr.current),!0}function jl(i,a,d){var h=i.stateNode;if(!h)throw Error(n(169));d?(i=xl(i,a,Ai),h.__reactInternalMemoizedMergedChildContext=i,En(wr),En(fn),Cn(fn,i)):En(wr),Cn(wr,d)}var mi=null,Sl=!1,Qu=!1;function ed(i){mi===null?mi=[i]:mi.push(i)}function Hf(i){Sl=!0,ed(i)}function Ti(){if(!Qu&&mi!==null){Qu=!0;var i=0,a=ln;try{var d=mi;for(ln=1;i<d.length;i++){var h=d[i];do h=h(!0);while(h!==null)}mi=null,Sl=!1}catch(v){throw mi!==null&&(mi=mi.slice(i+1)),ds(Vi,Ti),v}finally{ln=a,Qu=!1}}return null}var Ia=[],Wo=0,qo=null,Ec=0,Rs=[],Ls=0,Ho=null,Ys=1,Mi="";function Ri(i,a){Ia[Wo++]=Ec,Ia[Wo++]=qo,qo=i,Ec=a}function Vf(i,a,d){Rs[Ls++]=Ys,Rs[Ls++]=Mi,Rs[Ls++]=Ho,Ho=i;var h=Ys;i=Mi;var v=32-sr(h)-1;h&=~(1<<v),d+=1;var b=32-sr(a)+v;if(30<b){var L=v-v%5;b=(h&(1<<L)-1).toString(32),h>>=L,v-=L,Ys=1<<32-sr(a)+v|d<<v|h,Mi=b+i}else Ys=1<<b|d<<v|h,Mi=i}function $c(i){i.return!==null&&(Ri(i,1),Vf(i,1,0))}function td(i){for(;i===qo;)qo=Ia[--Wo],Ia[Wo]=null,Ec=Ia[--Wo],Ia[Wo]=null;for(;i===Ho;)Ho=Rs[--Ls],Rs[Ls]=null,Mi=Rs[--Ls],Rs[Ls]=null,Ys=Rs[--Ls],Rs[Ls]=null}var Br=null,Te=null,Tt=!1,bs=null;function nd(i,a){var d=xi(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 Ac(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,Br=i,Te=co(a.firstChild),!0):!1;case 6:return a=i.pendingProps===""||a.nodeType!==3?null:a,a!==null?(i.stateNode=a,Br=i,Te=null,!0):!1;case 13:return a=a.nodeType!==8?null:a,a!==null?(d=Ho!==null?{id:Ys,overflow:Mi}:null,i.memoizedState={dehydrated:a,treeContext:d,retryLane:1073741824},d=xi(18,null,null,0),d.stateNode=a,d.return=i,i.child=d,Br=i,Te=null,!0):!1;default:return!1}}function rd(i){return(i.mode&1)!==0&&(i.flags&128)===0}function sd(i){if(Tt){var a=Te;if(a){var d=a;if(!Ac(i,a)){if(rd(i))throw Error(n(418));a=co(d.nextSibling);var h=Br;a&&Ac(i,a)?nd(h,d):(i.flags=i.flags&-4097|2,Tt=!1,Br=i)}}else{if(rd(i))throw Error(n(418));i.flags=i.flags&-4097|2,Tt=!1,Br=i}}}function Gf(i){for(i=i.return;i!==null&&i.tag!==5&&i.tag!==3&&i.tag!==13;)i=i.return;Br=i}function kl(i){if(i!==Br)return!1;if(!Tt)return Gf(i),Tt=!0,!1;var a;if((a=i.tag!==3)&&!(a=i.tag!==5)&&(a=i.type,a=a!=="head"&&a!=="body"&&!Ea(i.type,i.memoizedProps)),a&&(a=Te)){if(rd(i))throw id(),Error(n(418));for(;a;)nd(i,a),a=co(a.nextSibling)}if(Gf(i),i.tag===13){if(i=i.memoizedState,i=i!==null?i.dehydrated:null,!i)throw Error(n(317));e:{for(i=i.nextSibling,a=0;i;){if(i.nodeType===8){var d=i.data;if(d==="/$"){if(a===0){Te=co(i.nextSibling);break e}a--}else d!=="$"&&d!=="$!"&&d!=="$?"||a++}i=i.nextSibling}Te=null}}else Te=Br?co(i.stateNode.nextSibling):null;return!0}function id(){for(var i=Te;i;)i=co(i.nextSibling)}function Pa(){Te=Br=null,Tt=!1}function Oa(i){bs===null?bs=[i]:bs.push(i)}var Ur=I.ReactCurrentBatchConfig;function Ft(i,a,d){if(i=d.ref,i!==null&&typeof i!="function"&&typeof i!="object"){if(d._owner){if(d=d._owner,d){if(d.tag!==1)throw Error(n(309));var h=d.stateNode}if(!h)throw Error(n(147,i));var v=h,b=""+i;return a!==null&&a.ref!==null&&typeof a.ref=="function"&&a.ref._stringRef===b?a.ref:(a=function(L){var ee=v.refs;L===null?delete ee[b]:ee[b]=L},a._stringRef=b,a)}if(typeof i!="string")throw Error(n(284));if(!d._owner)throw Error(n(290,i))}return i}function Zn(i,a){throw i=Object.prototype.toString.call(a),Error(n(31,i==="[object Object]"?"object with keys {"+Object.keys(a).join(", ")+"}":i))}function Tc(i){var a=i._init;return a(i._payload)}function od(i){function a(de,oe){if(i){var me=de.deletions;me===null?(de.deletions=[oe],de.flags|=16):me.push(oe)}}function d(de,oe){if(!i)return null;for(;oe!==null;)a(de,oe),oe=oe.sibling;return null}function h(de,oe){for(de=new Map;oe!==null;)oe.key!==null?de.set(oe.key,oe):de.set(oe.index,oe),oe=oe.sibling;return de}function v(de,oe){return de=Ya(de,oe),de.index=0,de.sibling=null,de}function b(de,oe,me){return de.index=me,i?(me=de.alternate,me!==null?(me=me.index,me<oe?(de.flags|=2,oe):me):(de.flags|=2,oe)):(de.flags|=1048576,oe)}function L(de){return i&&de.alternate===null&&(de.flags|=2),de}function ee(de,oe,me,Oe){return oe===null||oe.tag!==6?(oe=o_(me,de.mode,Oe),oe.return=de,oe):(oe=v(oe,me),oe.return=de,oe)}function re(de,oe,me,Oe){var at=me.type;return at===J?Ae(de,oe,me.props.children,Oe,me.key):oe!==null&&(oe.elementType===at||typeof at=="object"&&at!==null&&at.$$typeof===$&&Tc(at)===oe.type)?(Oe=v(oe,me.props),Oe.ref=Ft(de,oe,me),Oe.return=de,Oe):(Oe=ph(me.type,me.key,me.props,null,de.mode,Oe),Oe.ref=Ft(de,oe,me),Oe.return=de,Oe)}function we(de,oe,me,Oe){return oe===null||oe.tag!==4||oe.stateNode.containerInfo!==me.containerInfo||oe.stateNode.implementation!==me.implementation?(oe=a_(me,de.mode,Oe),oe.return=de,oe):(oe=v(oe,me.children||[]),oe.return=de,oe)}function Ae(de,oe,me,Oe,at){return oe===null||oe.tag!==7?(oe=Wl(me,de.mode,Oe,at),oe.return=de,oe):(oe=v(oe,me),oe.return=de,oe)}function Me(de,oe,me){if(typeof oe=="string"&&oe!==""||typeof oe=="number")return oe=o_(""+oe,de.mode,me),oe.return=de,oe;if(typeof oe=="object"&&oe!==null){switch(oe.$$typeof){case K:return me=ph(oe.type,oe.key,oe.props,null,de.mode,me),me.ref=Ft(de,null,oe),me.return=de,me;case U:return oe=a_(oe,de.mode,me),oe.return=de,oe;case $:var Oe=oe._init;return Me(de,Oe(oe._payload),me)}if(xe(oe)||F(oe))return oe=Wl(oe,de.mode,me,null),oe.return=de,oe;Zn(de,oe)}return null}function Ce(de,oe,me,Oe){var at=oe!==null?oe.key:null;if(typeof me=="string"&&me!==""||typeof me=="number")return at!==null?null:ee(de,oe,""+me,Oe);if(typeof me=="object"&&me!==null){switch(me.$$typeof){case K:return me.key===at?re(de,oe,me,Oe):null;case U:return me.key===at?we(de,oe,me,Oe):null;case $:return at=me._init,Ce(de,oe,at(me._payload),Oe)}if(xe(me)||F(me))return at!==null?null:Ae(de,oe,me,Oe,null);Zn(de,me)}return null}function Je(de,oe,me,Oe,at){if(typeof Oe=="string"&&Oe!==""||typeof Oe=="number")return de=de.get(me)||null,ee(oe,de,""+Oe,at);if(typeof Oe=="object"&&Oe!==null){switch(Oe.$$typeof){case K:return de=de.get(Oe.key===null?me:Oe.key)||null,re(oe,de,Oe,at);case U:return de=de.get(Oe.key===null?me:Oe.key)||null,we(oe,de,Oe,at);case $:var gt=Oe._init;return Je(de,oe,me,gt(Oe._payload),at)}if(xe(Oe)||F(Oe))return de=de.get(me)||null,Ae(oe,de,Oe,at,null);Zn(oe,Oe)}return null}function nt(de,oe,me,Oe){for(var at=null,gt=null,yt=oe,Nt=oe=0,Rr=null;yt!==null&&Nt<me.length;Nt++){yt.index>Nt?(Rr=yt,yt=null):Rr=yt.sibling;var mn=Ce(de,yt,me[Nt],Oe);if(mn===null){yt===null&&(yt=Rr);break}i&&yt&&mn.alternate===null&&a(de,yt),oe=b(mn,oe,Nt),gt===null?at=mn:gt.sibling=mn,gt=mn,yt=Rr}if(Nt===me.length)return d(de,yt),Tt&&Ri(de,Nt),at;if(yt===null){for(;Nt<me.length;Nt++)yt=Me(de,me[Nt],Oe),yt!==null&&(oe=b(yt,oe,Nt),gt===null?at=yt:gt.sibling=yt,gt=yt);return Tt&&Ri(de,Nt),at}for(yt=h(de,yt);Nt<me.length;Nt++)Rr=Je(yt,de,Nt,me[Nt],Oe),Rr!==null&&(i&&Rr.alternate!==null&&yt.delete(Rr.key===null?Nt:Rr.key),oe=b(Rr,oe,Nt),gt===null?at=Rr:gt.sibling=Rr,gt=Rr);return i&&yt.forEach(function(Ja){return a(de,Ja)}),Tt&&Ri(de,Nt),at}function rt(de,oe,me,Oe){var at=F(me);if(typeof at!="function")throw Error(n(150));if(me=at.call(me),me==null)throw Error(n(151));for(var gt=at=null,yt=oe,Nt=oe=0,Rr=null,mn=me.next();yt!==null&&!mn.done;Nt++,mn=me.next()){yt.index>Nt?(Rr=yt,yt=null):Rr=yt.sibling;var Ja=Ce(de,yt,mn.value,Oe);if(Ja===null){yt===null&&(yt=Rr);break}i&&yt&&Ja.alternate===null&&a(de,yt),oe=b(Ja,oe,Nt),gt===null?at=Ja:gt.sibling=Ja,gt=Ja,yt=Rr}if(mn.done)return d(de,yt),Tt&&Ri(de,Nt),at;if(yt===null){for(;!mn.done;Nt++,mn=me.next())mn=Me(de,mn.value,Oe),mn!==null&&(oe=b(mn,oe,Nt),gt===null?at=mn:gt.sibling=mn,gt=mn);return Tt&&Ri(de,Nt),at}for(yt=h(de,yt);!mn.done;Nt++,mn=me.next())mn=Je(yt,de,Nt,mn.value,Oe),mn!==null&&(i&&mn.alternate!==null&&yt.delete(mn.key===null?Nt:mn.key),oe=b(mn,oe,Nt),gt===null?at=mn:gt.sibling=mn,gt=mn);return i&&yt.forEach(function(q0){return a(de,q0)}),Tt&&Ri(de,Nt),at}function tr(de,oe,me,Oe){if(typeof me=="object"&&me!==null&&me.type===J&&me.key===null&&(me=me.props.children),typeof me=="object"&&me!==null){switch(me.$$typeof){case K:e:{for(var at=me.key,gt=oe;gt!==null;){if(gt.key===at){if(at=me.type,at===J){if(gt.tag===7){d(de,gt.sibling),oe=v(gt,me.props.children),oe.return=de,de=oe;break e}}else if(gt.elementType===at||typeof at=="object"&&at!==null&&at.$$typeof===$&&Tc(at)===gt.type){d(de,gt.sibling),oe=v(gt,me.props),oe.ref=Ft(de,gt,me),oe.return=de,de=oe;break e}d(de,gt);break}else a(de,gt);gt=gt.sibling}me.type===J?(oe=Wl(me.props.children,de.mode,Oe,me.key),oe.return=de,de=oe):(Oe=ph(me.type,me.key,me.props,null,de.mode,Oe),Oe.ref=Ft(de,oe,me),Oe.return=de,de=Oe)}return L(de);case U:e:{for(gt=me.key;oe!==null;){if(oe.key===gt)if(oe.tag===4&&oe.stateNode.containerInfo===me.containerInfo&&oe.stateNode.implementation===me.implementation){d(de,oe.sibling),oe=v(oe,me.children||[]),oe.return=de,de=oe;break e}else{d(de,oe);break}else a(de,oe);oe=oe.sibling}oe=a_(me,de.mode,Oe),oe.return=de,de=oe}return L(de);case $:return gt=me._init,tr(de,oe,gt(me._payload),Oe)}if(xe(me))return nt(de,oe,me,Oe);if(F(me))return rt(de,oe,me,Oe);Zn(de,me)}return typeof me=="string"&&me!==""||typeof me=="number"?(me=""+me,oe!==null&&oe.tag===6?(d(de,oe.sibling),oe=v(oe,me),oe.return=de,de=oe):(d(de,oe),oe=o_(me,de.mode,Oe),oe.return=de,de=oe),L(de)):d(de,oe)}return tr}var _i=od(!0),Vo=od(!1),ut=$i(null),Mc=null,fo=null,ad=null;function ld(){ad=fo=Mc=null}function Rc(i){var a=ut.current;En(ut),i._currentValue=a}function cd(i,a,d){for(;i!==null;){var h=i.alternate;if((i.childLanes&a)!==a?(i.childLanes|=a,h!==null&&(h.childLanes|=a)):h!==null&&(h.childLanes&a)!==a&&(h.childLanes|=a),i===d)break;i=i.return}}function Da(i,a){Mc=i,ad=fo=null,i=i.dependencies,i!==null&&i.firstContext!==null&&((i.lanes&a)!==0&&($r=!0),i.firstContext=null)}function Is(i){var a=i._currentValue;if(ad!==i)if(i={context:i,memoizedValue:a,next:null},fo===null){if(Mc===null)throw Error(n(308));fo=i,Mc.dependencies={lanes:0,firstContext:i}}else fo=fo.next=i;return a}var Li=null;function Js(i){Li===null?Li=[i]:Li.push(i)}function ud(i,a,d,h){var v=a.interleaved;return v===null?(d.next=d,Js(a)):(d.next=v.next,v.next=d),a.interleaved=d,or(i,h)}function or(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 ar=!1;function Nl(i){i.updateQueue={baseState:i.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function Kf(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 Ii(i,a){return{eventTime:i,lane:a,tag:0,payload:null,callback:null,next:null}}function ho(i,a,d){var h=i.updateQueue;if(h===null)return null;if(h=h.shared,(rn&2)!==0){var v=h.pending;return v===null?a.next=a:(a.next=v.next,v.next=a),h.pending=a,or(i,d)}return v=h.interleaved,v===null?(a.next=a,Js(h)):(a.next=v.next,v.next=a),h.interleaved=a,or(i,d)}function Cl(i,a,d){if(a=a.updateQueue,a!==null&&(a=a.shared,(d&4194240)!==0)){var h=a.lanes;h&=i.pendingLanes,d|=h,a.lanes=d,Ki(i,d)}}function Lc(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 L={eventTime:d.eventTime,lane:d.lane,tag:d.tag,payload:d.payload,callback:d.callback,next:null};b===null?v=b=L:b=b.next=L,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 Ic(i,a,d,h){var v=i.updateQueue;ar=!1;var b=v.firstBaseUpdate,L=v.lastBaseUpdate,ee=v.shared.pending;if(ee!==null){v.shared.pending=null;var re=ee,we=re.next;re.next=null,L===null?b=we:L.next=we,L=re;var Ae=i.alternate;Ae!==null&&(Ae=Ae.updateQueue,ee=Ae.lastBaseUpdate,ee!==L&&(ee===null?Ae.firstBaseUpdate=we:ee.next=we,Ae.lastBaseUpdate=re))}if(b!==null){var Me=v.baseState;L=0,Ae=we=re=null,ee=b;do{var Ce=ee.lane,Je=ee.eventTime;if((h&Ce)===Ce){Ae!==null&&(Ae=Ae.next={eventTime:Je,lane:0,tag:ee.tag,payload:ee.payload,callback:ee.callback,next:null});e:{var nt=i,rt=ee;switch(Ce=a,Je=d,rt.tag){case 1:if(nt=rt.payload,typeof nt=="function"){Me=nt.call(Je,Me,Ce);break e}Me=nt;break e;case 3:nt.flags=nt.flags&-65537|128;case 0:if(nt=rt.payload,Ce=typeof nt=="function"?nt.call(Je,Me,Ce):nt,Ce==null)break e;Me=G({},Me,Ce);break e;case 2:ar=!0}}ee.callback!==null&&ee.lane!==0&&(i.flags|=64,Ce=v.effects,Ce===null?v.effects=[ee]:Ce.push(ee))}else Je={eventTime:Je,lane:Ce,tag:ee.tag,payload:ee.payload,callback:ee.callback,next:null},Ae===null?(we=Ae=Je,re=Me):Ae=Ae.next=Je,L|=Ce;if(ee=ee.next,ee===null){if(ee=v.shared.pending,ee===null)break;Ce=ee,ee=Ce.next,Ce.next=null,v.lastBaseUpdate=Ce,v.shared.pending=null}}while(!0);if(Ae===null&&(re=Me),v.baseState=re,v.firstBaseUpdate=we,v.lastBaseUpdate=Ae,a=v.shared.interleaved,a!==null){v=a;do L|=v.lane,v=v.next;while(v!==a)}else b===null&&(v.shared.lanes=0);wo|=L,i.lanes=L,i.memoizedState=Me}}function Tn(i,a,d){if(i=a.effects,a.effects=null,i!==null)for(a=0;a<i.length;a++){var h=i[a],v=h.callback;if(v!==null){if(h.callback=null,h=d,typeof v!="function")throw Error(n(191,v));v.call(h)}}}var Fa={},Ps=$i(Fa),lr=$i(Fa),za=$i(Fa);function Xs(i){if(i===Fa)throw Error(n(174));return i}function El(i,a){switch(Cn(za,a),Cn(lr,i),Cn(Ps,Fa),i=a.nodeType,i){case 9:case 11:a=(a=a.documentElement)?a.namespaceURI:It(null,"");break;default:i=i===8?a.parentNode:a,a=i.namespaceURI||null,i=i.tagName,a=It(a,i)}En(Ps),Cn(Ps,a)}function pi(){En(Ps),En(lr),En(za)}function Pc(i){Xs(za.current);var a=Xs(Ps.current),d=It(a,i.type);a!==d&&(Cn(lr,i),Cn(Ps,d))}function dd(i){lr.current===i&&(En(Ps),En(lr))}var Dn=$i(0);function Oc(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 $l=[];function Dc(){for(var i=0;i<$l.length;i++)$l[i]._workInProgressVersionPrimary=null;$l.length=0}var Fc=I.ReactCurrentDispatcher,Al=I.ReactCurrentBatchConfig,Go=0,yn=null,Mn=null,Ht=null,zc=!1,Tl=!1,Ml=0,Vm=0;function Cr(){throw Error(n(321))}function fd(i,a){if(a===null)return!1;for(var d=0;d<a.length&&d<i.length;d++)if(!Vs(i[d],a[d]))return!1;return!0}function Jt(i,a,d,h,v,b){if(Go=b,yn=a,a.memoizedState=null,a.updateQueue=null,a.lanes=0,Fc.current=i===null||i.memoizedState===null?_o:ti,i=d(h,v),Tl){b=0;do{if(Tl=!1,Ml=0,25<=b)throw Error(n(301));b+=1,Ht=Mn=null,a.updateQueue=null,Fc.current=Ym,i=d(h,v)}while(Tl)}if(Fc.current=ei,a=Mn!==null&&Mn.next!==null,Go=0,Ht=Mn=yn=null,zc=!1,a)throw Error(n(300));return i}function Qn(){var i=Ml!==0;return Ml=0,i}function Fn(){var i={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return Ht===null?yn.memoizedState=Ht=i:Ht=Ht.next=i,Ht}function rs(){if(Mn===null){var i=yn.alternate;i=i!==null?i.memoizedState:null}else i=Mn.next;var a=Ht===null?yn.memoizedState:Ht.next;if(a!==null)Ht=a,Mn=i;else{if(i===null)throw Error(n(310));Mn=i,i={memoizedState:Mn.memoizedState,baseState:Mn.baseState,baseQueue:Mn.baseQueue,queue:Mn.queue,next:null},Ht===null?yn.memoizedState=Ht=i:Ht=Ht.next=i}return Ht}function mo(i,a){return typeof a=="function"?a(i):a}function Bc(i){var a=rs(),d=a.queue;if(d===null)throw Error(n(311));d.lastRenderedReducer=i;var h=Mn,v=h.baseQueue,b=d.pending;if(b!==null){if(v!==null){var L=v.next;v.next=b.next,b.next=L}h.baseQueue=v=b,d.pending=null}if(v!==null){b=v.next,h=h.baseState;var ee=L=null,re=null,we=b;do{var Ae=we.lane;if((Go&Ae)===Ae)re!==null&&(re=re.next={lane:0,action:we.action,hasEagerState:we.hasEagerState,eagerState:we.eagerState,next:null}),h=we.hasEagerState?we.eagerState:i(h,we.action);else{var Me={lane:Ae,action:we.action,hasEagerState:we.hasEagerState,eagerState:we.eagerState,next:null};re===null?(ee=re=Me,L=h):re=re.next=Me,yn.lanes|=Ae,wo|=Ae}we=we.next}while(we!==null&&we!==b);re===null?L=h:re.next=ee,Vs(h,a.memoizedState)||($r=!0),a.memoizedState=h,a.baseState=L,a.baseQueue=re,d.lastRenderedState=h}if(i=d.interleaved,i!==null){v=i;do b=v.lane,yn.lanes|=b,wo|=b,v=v.next;while(v!==i)}else v===null&&(d.lanes=0);return[a.memoizedState,d.dispatch]}function hd(i){var a=rs(),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 L=v=v.next;do b=i(b,L.action),L=L.next;while(L!==v);Vs(b,a.memoizedState)||($r=!0),a.memoizedState=b,a.baseQueue===null&&(a.baseState=b),d.lastRenderedState=b}return[b,h]}function Yf(){}function md(i,a){var d=yn,h=rs(),v=a(),b=!Vs(h.memoizedState,v);if(b&&(h.memoizedState=v,$r=!0),h=h.queue,yd(Xf.bind(null,d,h,i),[i]),h.getSnapshot!==a||b||Ht!==null&&Ht.memoizedState.tag&1){if(d.flags|=2048,Zs(9,Jf.bind(null,d,h,v,a),void 0,null),er===null)throw Error(n(349));(Go&30)!==0||Rl(d,a,v)}return v}function Rl(i,a,d){i.flags|=16384,i={getSnapshot:a,value:d},a=yn.updateQueue,a===null?(a={lastEffect:null,stores:null},yn.updateQueue=a,a.stores=[i]):(d=a.stores,d===null?a.stores=[i]:d.push(i))}function Jf(i,a,d,h){a.value=d,a.getSnapshot=h,Zf(a)&&_d(i)}function Xf(i,a,d){return d(function(){Zf(a)&&_d(i)})}function Zf(i){var a=i.getSnapshot;i=i.value;try{var d=a();return!Vs(i,d)}catch{return!0}}function _d(i){var a=or(i,1);a!==null&&Pe(a,i,1,-1)}function pd(i){var a=Fn();return typeof i=="function"&&(i=i()),a.memoizedState=a.baseState=i,i={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:mo,lastRenderedState:i},a.queue=i,i=i.dispatch=Ko.bind(null,yn,i),[a.memoizedState,i]}function Zs(i,a,d,h){return i={tag:i,create:a,destroy:d,deps:h,next:null},a=yn.updateQueue,a===null?(a={lastEffect:null,stores:null},yn.updateQueue=a,a.lastEffect=i.next=i):(d=a.lastEffect,d===null?a.lastEffect=i.next=i:(h=d.next,d.next=i,i.next=h,a.lastEffect=i)),i}function Uc(){return rs().memoizedState}function Ll(i,a,d,h){var v=Fn();yn.flags|=i,v.memoizedState=Zs(1|a,d,void 0,h===void 0?null:h)}function Ba(i,a,d,h){var v=rs();h=h===void 0?null:h;var b=void 0;if(Mn!==null){var L=Mn.memoizedState;if(b=L.destroy,h!==null&&fd(h,L.deps)){v.memoizedState=Zs(a,d,b,h);return}}yn.flags|=i,v.memoizedState=Zs(1|a,d,b,h)}function gd(i,a){return Ll(8390656,8,i,a)}function yd(i,a){return Ba(2048,8,i,a)}function Qf(i,a){return Ba(4,2,i,a)}function eh(i,a){return Ba(4,4,i,a)}function th(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 nh(i,a,d){return d=d!=null?d.concat([i]):null,Ba(4,4,th.bind(null,a,i),d)}function wd(){}function vd(i,a){var d=rs();a=a===void 0?null:a;var h=d.memoizedState;return h!==null&&a!==null&&fd(a,h[1])?h[0]:(d.memoizedState=[i,a],i)}function Wc(i,a){var d=rs();a=a===void 0?null:a;var h=d.memoizedState;return h!==null&&a!==null&&fd(a,h[1])?h[0]:(i=i(),d.memoizedState=[i,a],i)}function rh(i,a,d){return(Go&21)===0?(i.baseState&&(i.baseState=!1,$r=!0),i.memoizedState=d):(Vs(d,a)||(d=hr(),yn.lanes|=d,wo|=d,i.baseState=!0),a)}function Gm(i,a){var d=ln;ln=d!==0&&4>d?d:4,i(!0);var h=Al.transition;Al.transition={};try{i(!1),a()}finally{ln=d,Al.transition=h}}function Il(){return rs().memoizedState}function Km(i,a,d){var h=$e(i);if(d={lane:h,action:d,hasEagerState:!1,eagerState:null,next:null},Er(i))cr(a,d);else if(d=ud(i,a,d,h),d!==null){var v=he();Pe(d,i,h,v),Qs(d,a,h)}}function Ko(i,a,d){var h=$e(i),v={lane:h,action:d,hasEagerState:!1,eagerState:null,next:null};if(Er(i))cr(a,v);else{var b=i.alternate;if(i.lanes===0&&(b===null||b.lanes===0)&&(b=a.lastRenderedReducer,b!==null))try{var L=a.lastRenderedState,ee=b(L,d);if(v.hasEagerState=!0,v.eagerState=ee,Vs(ee,L)){var re=a.interleaved;re===null?(v.next=v,Js(a)):(v.next=re.next,re.next=v),a.interleaved=v;return}}catch{}finally{}d=ud(i,a,v,h),d!==null&&(v=he(),Pe(d,i,h,v),Qs(d,a,h))}}function Er(i){var a=i.alternate;return i===yn||a!==null&&a===yn}function cr(i,a){Tl=zc=!0;var d=i.pending;d===null?a.next=a:(a.next=d.next,d.next=a),i.pending=a}function Qs(i,a,d){if((d&4194240)!==0){var h=a.lanes;h&=i.pendingLanes,d|=h,a.lanes=d,Ki(i,d)}}var ei={readContext:Is,useCallback:Cr,useContext:Cr,useEffect:Cr,useImperativeHandle:Cr,useInsertionEffect:Cr,useLayoutEffect:Cr,useMemo:Cr,useReducer:Cr,useRef:Cr,useState:Cr,useDebugValue:Cr,useDeferredValue:Cr,useTransition:Cr,useMutableSource:Cr,useSyncExternalStore:Cr,useId:Cr,unstable_isNewReconciler:!1},_o={readContext:Is,useCallback:function(i,a){return Fn().memoizedState=[i,a===void 0?null:a],i},useContext:Is,useEffect:gd,useImperativeHandle:function(i,a,d){return d=d!=null?d.concat([i]):null,Ll(4194308,4,th.bind(null,a,i),d)},useLayoutEffect:function(i,a){return Ll(4194308,4,i,a)},useInsertionEffect:function(i,a){return Ll(4,2,i,a)},useMemo:function(i,a){var d=Fn();return a=a===void 0?null:a,i=i(),d.memoizedState=[i,a],i},useReducer:function(i,a,d){var h=Fn();return a=d!==void 0?d(a):a,h.memoizedState=h.baseState=a,i={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:i,lastRenderedState:a},h.queue=i,i=i.dispatch=Km.bind(null,yn,i),[h.memoizedState,i]},useRef:function(i){var a=Fn();return i={current:i},a.memoizedState=i},useState:pd,useDebugValue:wd,useDeferredValue:function(i){return Fn().memoizedState=i},useTransition:function(){var i=pd(!1),a=i[0];return i=Gm.bind(null,i[1]),Fn().memoizedState=i,[a,i]},useMutableSource:function(){},useSyncExternalStore:function(i,a,d){var h=yn,v=Fn();if(Tt){if(d===void 0)throw Error(n(407));d=d()}else{if(d=a(),er===null)throw Error(n(349));(Go&30)!==0||Rl(h,a,d)}v.memoizedState=d;var b={value:d,getSnapshot:a};return v.queue=b,gd(Xf.bind(null,h,b,i),[i]),h.flags|=2048,Zs(9,Jf.bind(null,h,b,d,a),void 0,null),d},useId:function(){var i=Fn(),a=er.identifierPrefix;if(Tt){var d=Mi,h=Ys;d=(h&~(1<<32-sr(h)-1)).toString(32)+d,a=":"+a+"R"+d,d=Ml++,0<d&&(a+="H"+d.toString(32)),a+=":"}else d=Vm++,a=":"+a+"r"+d.toString(32)+":";return i.memoizedState=a},unstable_isNewReconciler:!1},ti={readContext:Is,useCallback:vd,useContext:Is,useEffect:yd,useImperativeHandle:nh,useInsertionEffect:Qf,useLayoutEffect:eh,useMemo:Wc,useReducer:Bc,useRef:Uc,useState:function(){return Bc(mo)},useDebugValue:wd,useDeferredValue:function(i){var a=rs();return rh(a,Mn.memoizedState,i)},useTransition:function(){var i=Bc(mo)[0],a=rs().memoizedState;return[i,a]},useMutableSource:Yf,useSyncExternalStore:md,useId:Il,unstable_isNewReconciler:!1},Ym={readContext:Is,useCallback:vd,useContext:Is,useEffect:yd,useImperativeHandle:nh,useInsertionEffect:Qf,useLayoutEffect:eh,useMemo:Wc,useReducer:hd,useRef:Uc,useState:function(){return hd(mo)},useDebugValue:wd,useDeferredValue:function(i){var a=rs();return Mn===null?a.memoizedState=i:rh(a,Mn.memoizedState,i)},useTransition:function(){var i=hd(mo)[0],a=rs().memoizedState;return[i,a]},useMutableSource:Yf,useSyncExternalStore:md,useId:Il,unstable_isNewReconciler:!1};function ss(i,a){if(i&&i.defaultProps){a=G({},a),i=i.defaultProps;for(var d in i)a[d]===void 0&&(a[d]=i[d]);return a}return a}function xd(i,a,d,h){a=i.memoizedState,d=d(h,a),d=d==null?a:G({},a,d),i.memoizedState=d,i.lanes===0&&(i.updateQueue.baseState=d)}var Ua={isMounted:function(i){return(i=i._reactInternals)?ft(i)===i:!1},enqueueSetState:function(i,a,d){i=i._reactInternals;var h=he(),v=$e(i),b=Ii(h,v);b.payload=a,d!=null&&(b.callback=d),a=ho(i,b,v),a!==null&&(Pe(a,i,v,h),Cl(a,i,v))},enqueueReplaceState:function(i,a,d){i=i._reactInternals;var h=he(),v=$e(i),b=Ii(h,v);b.tag=1,b.payload=a,d!=null&&(b.callback=d),a=ho(i,b,v),a!==null&&(Pe(a,i,v,h),Cl(a,i,v))},enqueueForceUpdate:function(i,a){i=i._reactInternals;var d=he(),h=$e(i),v=Ii(d,h);v.tag=2,a!=null&&(v.callback=a),a=ho(i,v,h),a!==null&&(Pe(a,i,h,d),Cl(a,i,h))}};function sh(i,a,d,h,v,b,L){return i=i.stateNode,typeof i.shouldComponentUpdate=="function"?i.shouldComponentUpdate(h,b,L):a.prototype&&a.prototype.isPureReactComponent?!eo(d,h)||!eo(v,b):!0}function ih(i,a,d){var h=!1,v=xs,b=a.contextType;return typeof b=="object"&&b!==null?b=Is(b):(v=ns(a)?Ai:fn.current,h=a.contextTypes,b=(h=h!=null)?Ra(i,v):xs),a=new a(d,b),i.memoizedState=a.state!==null&&a.state!==void 0?a.state:null,a.updater=Ua,i.stateNode=a,a._reactInternals=i,h&&(i=i.stateNode,i.__reactInternalMemoizedUnmaskedChildContext=v,i.__reactInternalMemoizedMaskedChildContext=b),a}function bd(i,a,d,h){i=a.state,typeof a.componentWillReceiveProps=="function"&&a.componentWillReceiveProps(d,h),typeof a.UNSAFE_componentWillReceiveProps=="function"&&a.UNSAFE_componentWillReceiveProps(d,h),a.state!==i&&Ua.enqueueReplaceState(a,a.state,null)}function Pi(i,a,d,h){var v=i.stateNode;v.props=d,v.state=i.memoizedState,v.refs={},Nl(i);var b=a.contextType;typeof b=="object"&&b!==null?v.context=Is(b):(b=ns(a)?Ai:fn.current,v.context=Ra(i,b)),v.state=i.memoizedState,b=a.getDerivedStateFromProps,typeof b=="function"&&(xd(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&&Ua.enqueueReplaceState(v,v.state,null),Ic(i,d,v,h),v.state=i.memoizedState),typeof v.componentDidMount=="function"&&(i.flags|=4194308)}function gi(i,a){try{var d="",h=a;do d+=le(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 qc(i,a,d){return{value:i,source:null,stack:d??null,digest:a??null}}function Hc(i,a){try{console.error(a.value)}catch(d){setTimeout(function(){throw d})}}var Jm=typeof WeakMap=="function"?WeakMap:Map;function jd(i,a,d){d=Ii(-1,d),d.tag=3,d.payload={element:null};var h=a.value;return d.callback=function(){y||(y=!0,k=h),Hc(i,a)},d}function Yo(i,a,d){d=Ii(-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(){Hc(i,a)}}var b=i.stateNode;return b!==null&&typeof b.componentDidCatch=="function"&&(d.callback=function(){Hc(i,a),typeof h!="function"&&(M===null?M=new Set([this]):M.add(this));var L=a.stack;this.componentDidCatch(a.value,{componentStack:L!==null?L:""})}),d}function oh(i,a,d){var h=i.pingCache;if(h===null){h=i.pingCache=new Jm;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=R0.bind(null,i,a,d),a.then(i,i))}function Pl(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 Sd(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=Ii(-1,1),a.tag=2,ho(d,a,1))),d.lanes|=1),i):(i.flags|=65536,i.lanes=v,i)}var Xm=I.ReactCurrentOwner,$r=!1;function Wr(i,a,d,h){a.child=i===null?Vo(a,null,d,h):_i(a,i.child,d,h)}function ah(i,a,d,h,v){d=d.render;var b=a.ref;return Da(a,v),h=Jt(i,a,d,h,b,v),d=Qn(),i!==null&&!$r?(a.updateQueue=i.updateQueue,a.flags&=-2053,i.lanes&=~v,Oi(i,a,v)):(Tt&&d&&$c(a),a.flags|=1,Wr(i,a,h,v),a.child)}function lh(i,a,d,h,v){if(i===null){var b=d.type;return typeof b=="function"&&!i_(b)&&b.defaultProps===void 0&&d.compare===null&&d.defaultProps===void 0?(a.tag=15,a.type=b,is(i,a,b,h,v)):(i=ph(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 L=b.memoizedProps;if(d=d.compare,d=d!==null?d:eo,d(L,h)&&i.ref===a.ref)return Oi(i,a,v)}return a.flags|=1,i=Ya(b,h),i.ref=a.ref,i.return=a,a.child=i}function is(i,a,d,h,v){if(i!==null){var b=i.memoizedProps;if(eo(b,h)&&i.ref===a.ref)if($r=!1,a.pendingProps=h=b,(i.lanes&v)!==0)(i.flags&131072)!==0&&($r=!0);else return a.lanes=i.lanes,Oi(i,a,v)}return Vc(i,a,d,h,v)}function Jo(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},Cn(Qo,as),as|=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,Cn(Qo,as),as|=i,null;a.memoizedState={baseLanes:0,cachePool:null,transitions:null},h=b!==null?b.baseLanes:d,Cn(Qo,as),as|=h}else b!==null?(h=b.baseLanes|d,a.memoizedState=null):h=d,Cn(Qo,as),as|=h;return Wr(i,a,v,d),a.child}function ch(i,a){var d=a.ref;(i===null&&d!==null||i!==null&&i.ref!==d)&&(a.flags|=512,a.flags|=2097152)}function Vc(i,a,d,h,v){var b=ns(d)?Ai:fn.current;return b=Ra(a,b),Da(a,v),d=Jt(i,a,d,h,b,v),h=Qn(),i!==null&&!$r?(a.updateQueue=i.updateQueue,a.flags&=-2053,i.lanes&=~v,Oi(i,a,v)):(Tt&&h&&$c(a),a.flags|=1,Wr(i,a,d,v),a.child)}function os(i,a,d,h,v){if(ns(d)){var b=!0;bl(a)}else b=!1;if(Da(a,v),a.stateNode===null)Os(i,a),ih(a,d,h),Pi(a,d,h,v),h=!0;else if(i===null){var L=a.stateNode,ee=a.memoizedProps;L.props=ee;var re=L.context,we=d.contextType;typeof we=="object"&&we!==null?we=Is(we):(we=ns(d)?Ai:fn.current,we=Ra(a,we));var Ae=d.getDerivedStateFromProps,Me=typeof Ae=="function"||typeof L.getSnapshotBeforeUpdate=="function";Me||typeof L.UNSAFE_componentWillReceiveProps!="function"&&typeof L.componentWillReceiveProps!="function"||(ee!==h||re!==we)&&bd(a,L,h,we),ar=!1;var Ce=a.memoizedState;L.state=Ce,Ic(a,h,L,v),re=a.memoizedState,ee!==h||Ce!==re||wr.current||ar?(typeof Ae=="function"&&(xd(a,d,Ae,h),re=a.memoizedState),(ee=ar||sh(a,d,ee,h,Ce,re,we))?(Me||typeof L.UNSAFE_componentWillMount!="function"&&typeof L.componentWillMount!="function"||(typeof L.componentWillMount=="function"&&L.componentWillMount(),typeof L.UNSAFE_componentWillMount=="function"&&L.UNSAFE_componentWillMount()),typeof L.componentDidMount=="function"&&(a.flags|=4194308)):(typeof L.componentDidMount=="function"&&(a.flags|=4194308),a.memoizedProps=h,a.memoizedState=re),L.props=h,L.state=re,L.context=we,h=ee):(typeof L.componentDidMount=="function"&&(a.flags|=4194308),h=!1)}else{L=a.stateNode,Kf(i,a),ee=a.memoizedProps,we=a.type===a.elementType?ee:ss(a.type,ee),L.props=we,Me=a.pendingProps,Ce=L.context,re=d.contextType,typeof re=="object"&&re!==null?re=Is(re):(re=ns(d)?Ai:fn.current,re=Ra(a,re));var Je=d.getDerivedStateFromProps;(Ae=typeof Je=="function"||typeof L.getSnapshotBeforeUpdate=="function")||typeof L.UNSAFE_componentWillReceiveProps!="function"&&typeof L.componentWillReceiveProps!="function"||(ee!==Me||Ce!==re)&&bd(a,L,h,re),ar=!1,Ce=a.memoizedState,L.state=Ce,Ic(a,h,L,v);var nt=a.memoizedState;ee!==Me||Ce!==nt||wr.current||ar?(typeof Je=="function"&&(xd(a,d,Je,h),nt=a.memoizedState),(we=ar||sh(a,d,we,h,Ce,nt,re)||!1)?(Ae||typeof L.UNSAFE_componentWillUpdate!="function"&&typeof L.componentWillUpdate!="function"||(typeof L.componentWillUpdate=="function"&&L.componentWillUpdate(h,nt,re),typeof L.UNSAFE_componentWillUpdate=="function"&&L.UNSAFE_componentWillUpdate(h,nt,re)),typeof L.componentDidUpdate=="function"&&(a.flags|=4),typeof L.getSnapshotBeforeUpdate=="function"&&(a.flags|=1024)):(typeof L.componentDidUpdate!="function"||ee===i.memoizedProps&&Ce===i.memoizedState||(a.flags|=4),typeof L.getSnapshotBeforeUpdate!="function"||ee===i.memoizedProps&&Ce===i.memoizedState||(a.flags|=1024),a.memoizedProps=h,a.memoizedState=nt),L.props=h,L.state=nt,L.context=re,h=we):(typeof L.componentDidUpdate!="function"||ee===i.memoizedProps&&Ce===i.memoizedState||(a.flags|=4),typeof L.getSnapshotBeforeUpdate!="function"||ee===i.memoizedProps&&Ce===i.memoizedState||(a.flags|=1024),h=!1)}return Ol(i,a,d,h,b,v)}function Ol(i,a,d,h,v,b){ch(i,a);var L=(a.flags&128)!==0;if(!h&&!L)return v&&jl(a,d,!1),Oi(i,a,b);h=a.stateNode,Xm.current=a;var ee=L&&typeof d.getDerivedStateFromError!="function"?null:h.render();return a.flags|=1,i!==null&&L?(a.child=_i(a,i.child,null,b),a.child=_i(a,null,ee,b)):Wr(i,a,ee,b),a.memoizedState=h.state,v&&jl(a,d,!0),a.child}function kd(i){var a=i.stateNode;a.pendingContext?qf(i,a.pendingContext,a.pendingContext!==a.context):a.context&&qf(i,a.context,!1),El(i,a.containerInfo)}function Nd(i,a,d,h,v){return Pa(),Oa(v),a.flags|=256,Wr(i,a,d,h),a.child}var Cd={dehydrated:null,treeContext:null,retryLane:0};function Ed(i){return{baseLanes:i,cachePool:null,transitions:null}}function uh(i,a,d){var h=a.pendingProps,v=Dn.current,b=!1,L=(a.flags&128)!==0,ee;if((ee=L)||(ee=i!==null&&i.memoizedState===null?!1:(v&2)!==0),ee?(b=!0,a.flags&=-129):(i===null||i.memoizedState!==null)&&(v|=1),Cn(Dn,v&1),i===null)return sd(a),i=a.memoizedState,i!==null&&(i=i.dehydrated,i!==null)?((a.mode&1)===0?a.lanes=1:i.data==="$!"?a.lanes=8:a.lanes=1073741824,null):(L=h.children,i=h.fallback,b?(h=a.mode,b=a.child,L={mode:"hidden",children:L},(h&1)===0&&b!==null?(b.childLanes=0,b.pendingProps=L):b=gh(L,h,0,null),i=Wl(i,h,d,null),b.return=a,i.return=a,b.sibling=i,a.child=b,a.child.memoizedState=Ed(d),a.memoizedState=Cd,i):qr(a,L));if(v=i.memoizedState,v!==null&&(ee=v.dehydrated,ee!==null))return dh(i,a,L,h,ee,v,d);if(b){b=h.fallback,L=a.mode,v=i.child,ee=v.sibling;var re={mode:"hidden",children:h.children};return(L&1)===0&&a.child!==v?(h=a.child,h.childLanes=0,h.pendingProps=re,a.deletions=null):(h=Ya(v,re),h.subtreeFlags=v.subtreeFlags&14680064),ee!==null?b=Ya(ee,b):(b=Wl(b,L,d,null),b.flags|=2),b.return=a,h.return=a,h.sibling=b,a.child=h,h=b,b=a.child,L=i.child.memoizedState,L=L===null?Ed(d):{baseLanes:L.baseLanes|d,cachePool:null,transitions:L.transitions},b.memoizedState=L,b.childLanes=i.childLanes&~d,a.memoizedState=Cd,h}return b=i.child,i=b.sibling,h=Ya(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 qr(i,a){return a=gh({mode:"visible",children:a},i.mode,0,null),a.return=i,i.child=a}function po(i,a,d,h){return h!==null&&Oa(h),_i(a,i.child,null,d),i=qr(a,a.pendingProps.children),i.flags|=2,a.memoizedState=null,i}function dh(i,a,d,h,v,b,L){if(d)return a.flags&256?(a.flags&=-257,h=qc(Error(n(422))),po(i,a,L,h)):a.memoizedState!==null?(a.child=i.child,a.flags|=128,null):(b=h.fallback,v=a.mode,h=gh({mode:"visible",children:h.children},v,0,null),b=Wl(b,v,L,null),b.flags|=2,h.return=a,b.return=a,h.sibling=b,a.child=h,(a.mode&1)!==0&&_i(a,i.child,null,L),a.child.memoizedState=Ed(L),a.memoizedState=Cd,b);if((a.mode&1)===0)return po(i,a,L,null);if(v.data==="$!"){if(h=v.nextSibling&&v.nextSibling.dataset,h)var ee=h.dgst;return h=ee,b=Error(n(419)),h=qc(b,h,void 0),po(i,a,L,h)}if(ee=(L&i.childLanes)!==0,$r||ee){if(h=er,h!==null){switch(L&-L){case 4:v=2;break;case 16:v=8;break;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:v=32;break;case 536870912:v=268435456;break;default:v=0}v=(v&(h.suspendedLanes|L))!==0?0:v,v!==0&&v!==b.retryLane&&(b.retryLane=v,or(i,v),Pe(h,i,v,-1))}return s_(),h=qc(Error(n(421))),po(i,a,L,h)}return v.data==="$?"?(a.flags|=128,a.child=i.child,a=L0.bind(null,i),v._reactRetry=a,null):(i=b.treeContext,Te=co(v.nextSibling),Br=a,Tt=!0,bs=null,i!==null&&(Rs[Ls++]=Ys,Rs[Ls++]=Mi,Rs[Ls++]=Ho,Ys=i.id,Mi=i.overflow,Ho=a),a=qr(a,h.children),a.flags|=4096,a)}function $d(i,a,d){i.lanes|=a;var h=i.alternate;h!==null&&(h.lanes|=a),cd(i.return,a,d)}function Dl(i,a,d,h,v){var 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 Ad(i,a,d){var h=a.pendingProps,v=h.revealOrder,b=h.tail;if(Wr(i,a,h.children,d),h=Dn.current,(h&2)!==0)h=h&1|2,a.flags|=128;else{if(i!==null&&(i.flags&128)!==0)e:for(i=a.child;i!==null;){if(i.tag===13)i.memoizedState!==null&&$d(i,d,a);else if(i.tag===19)$d(i,d,a);else if(i.child!==null){i.child.return=i,i=i.child;continue}if(i===a)break e;for(;i.sibling===null;){if(i.return===null||i.return===a)break e;i=i.return}i.sibling.return=i.return,i=i.sibling}h&=1}if(Cn(Dn,h),(a.mode&1)===0)a.memoizedState=null;else switch(v){case"forwards":for(d=a.child,v=null;d!==null;)i=d.alternate,i!==null&&Oc(i)===null&&(v=d),d=d.sibling;d=v,d===null?(v=a.child,a.child=null):(v=d.sibling,d.sibling=null),Dl(a,!1,v,d,b);break;case"backwards":for(d=null,v=a.child,a.child=null;v!==null;){if(i=v.alternate,i!==null&&Oc(i)===null){a.child=v;break}i=v.sibling,v.sibling=d,d=v,v=i}Dl(a,!0,d,null,b);break;case"together":Dl(a,!1,null,null,void 0);break;default:a.memoizedState=null}return a.child}function Os(i,a){(a.mode&1)===0&&i!==null&&(i.alternate=null,a.alternate=null,a.flags|=2)}function Oi(i,a,d){if(i!==null&&(a.dependencies=i.dependencies),wo|=a.lanes,(d&a.childLanes)===0)return null;if(i!==null&&a.child!==i.child)throw Error(n(153));if(a.child!==null){for(i=a.child,d=Ya(i,i.pendingProps),a.child=d,d.return=a;i.sibling!==null;)i=i.sibling,d=d.sibling=Ya(i,i.pendingProps),d.return=a;d.sibling=null}return a.child}function Zm(i,a,d){switch(a.tag){case 3:kd(a),Pa();break;case 5:Pc(a);break;case 1:ns(a.type)&&bl(a);break;case 4:El(a,a.stateNode.containerInfo);break;case 10:var h=a.type._context,v=a.memoizedProps.value;Cn(ut,h._currentValue),h._currentValue=v;break;case 13:if(h=a.memoizedState,h!==null)return h.dehydrated!==null?(Cn(Dn,Dn.current&1),a.flags|=128,null):(d&a.child.childLanes)!==0?uh(i,a,d):(Cn(Dn,Dn.current&1),i=Oi(i,a,d),i!==null?i.sibling:null);Cn(Dn,Dn.current&1);break;case 19:if(h=(d&a.childLanes)!==0,(i.flags&128)!==0){if(h)return Ad(i,a,d);a.flags|=128}if(v=a.memoizedState,v!==null&&(v.rendering=null,v.tail=null,v.lastEffect=null),Cn(Dn,Dn.current),h)break;return null;case 22:case 23:return a.lanes=0,Jo(i,a,d)}return Oi(i,a,d)}var Td,go,Gc,fh;Td=function(i,a){for(var d=a.child;d!==null;){if(d.tag===5||d.tag===6)i.appendChild(d.stateNode);else if(d.tag!==4&&d.child!==null){d.child.return=d,d=d.child;continue}if(d===a)break;for(;d.sibling===null;){if(d.return===null||d.return===a)return;d=d.return}d.sibling.return=d.return,d=d.sibling}},go=function(){},Gc=function(i,a,d,h){var v=i.memoizedProps;if(v!==h){i=a.stateNode,Xs(Ps.current);var b=null;switch(d){case"input":v=tt(i,v),h=tt(i,h),b=[];break;case"select":v=G({},v,{value:void 0}),h=G({},h,{value:void 0}),b=[];break;case"textarea":v=qe(i,v),h=qe(i,h),b=[];break;default:typeof v.onClick!="function"&&typeof h.onClick=="function"&&(i.onclick=kc)}wn(d,h);var L;d=null;for(we in v)if(!h.hasOwnProperty(we)&&v.hasOwnProperty(we)&&v[we]!=null)if(we==="style"){var ee=v[we];for(L in ee)ee.hasOwnProperty(L)&&(d||(d={}),d[L]="")}else we!=="dangerouslySetInnerHTML"&&we!=="children"&&we!=="suppressContentEditableWarning"&&we!=="suppressHydrationWarning"&&we!=="autoFocus"&&(o.hasOwnProperty(we)?b||(b=[]):(b=b||[]).push(we,null));for(we in h){var re=h[we];if(ee=v!=null?v[we]:void 0,h.hasOwnProperty(we)&&re!==ee&&(re!=null||ee!=null))if(we==="style")if(ee){for(L in ee)!ee.hasOwnProperty(L)||re&&re.hasOwnProperty(L)||(d||(d={}),d[L]="");for(L in re)re.hasOwnProperty(L)&&ee[L]!==re[L]&&(d||(d={}),d[L]=re[L])}else d||(b||(b=[]),b.push(we,d)),d=re;else we==="dangerouslySetInnerHTML"?(re=re?re.__html:void 0,ee=ee?ee.__html:void 0,re!=null&&ee!==re&&(b=b||[]).push(we,re)):we==="children"?typeof re!="string"&&typeof re!="number"||(b=b||[]).push(we,""+re):we!=="suppressContentEditableWarning"&&we!=="suppressHydrationWarning"&&(o.hasOwnProperty(we)?(re!=null&&we==="onScroll"&&Nn("scroll",i),b||ee===re||(b=[])):(b=b||[]).push(we,re))}d&&(b=b||[]).push("style",d);var we=b;(a.updateQueue=we)&&(a.flags|=4)}},fh=function(i,a,d,h){d!==h&&(a.flags|=4)};function Fl(i,a){if(!Tt)switch(i.tailMode){case"hidden":a=i.tail;for(var d=null;a!==null;)a.alternate!==null&&(d=a),a=a.sibling;d===null?i.tail=null:d.sibling=null;break;case"collapsed":d=i.tail;for(var h=null;d!==null;)d.alternate!==null&&(h=d),d=d.sibling;h===null?a||i.tail===null?i.tail=null:i.tail.sibling=null:h.sibling=null}}function Ar(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 Qm(i,a,d){var h=a.pendingProps;switch(td(a),a.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return Ar(a),null;case 1:return ns(a.type)&&La(),Ar(a),null;case 3:return h=a.stateNode,pi(),En(wr),En(fn),Dc(),h.pendingContext&&(h.context=h.pendingContext,h.pendingContext=null),(i===null||i.child===null)&&(kl(a)?a.flags|=4:i===null||i.memoizedState.isDehydrated&&(a.flags&256)===0||(a.flags|=1024,bs!==null&&(sn(bs),bs=null))),go(i,a),Ar(a),null;case 5:dd(a);var v=Xs(za.current);if(d=a.type,i!==null&&a.stateNode!=null)Gc(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 Ar(a),null}if(i=Xs(Ps.current),kl(a)){h=a.stateNode,d=a.type;var b=a.memoizedProps;switch(h[yr]=a,h[Ta]=b,i=(a.mode&1)!==0,d){case"dialog":Nn("cancel",h),Nn("close",h);break;case"iframe":case"object":case"embed":Nn("load",h);break;case"video":case"audio":for(v=0;v<Na.length;v++)Nn(Na[v],h);break;case"source":Nn("error",h);break;case"img":case"image":case"link":Nn("error",h),Nn("load",h);break;case"details":Nn("toggle",h);break;case"input":lt(h,b),Nn("invalid",h);break;case"select":h._wrapperState={wasMultiple:!!b.multiple},Nn("invalid",h);break;case"textarea":zt(h,b),Nn("invalid",h)}wn(d,b),v=null;for(var L in b)if(b.hasOwnProperty(L)){var ee=b[L];L==="children"?typeof ee=="string"?h.textContent!==ee&&(b.suppressHydrationWarning!==!0&&ao(h.textContent,ee,i),v=["children",ee]):typeof ee=="number"&&h.textContent!==""+ee&&(b.suppressHydrationWarning!==!0&&ao(h.textContent,ee,i),v=["children",""+ee]):o.hasOwnProperty(L)&&ee!=null&&L==="onScroll"&&Nn("scroll",h)}switch(d){case"input":We(h),Re(h,b,!0);break;case"textarea":We(h),bn(h);break;case"select":case"option":break;default:typeof b.onClick=="function"&&(h.onclick=kc)}h=v,a.updateQueue=h,h!==null&&(a.flags|=4)}else{L=v.nodeType===9?v:v.ownerDocument,i==="http://www.w3.org/1999/xhtml"&&(i=Wt(d)),i==="http://www.w3.org/1999/xhtml"?d==="script"?(i=L.createElement("div"),i.innerHTML="<script><\/script>",i=i.removeChild(i.firstChild)):typeof h.is=="string"?i=L.createElement(d,{is:h.is}):(i=L.createElement(d),d==="select"&&(L=i,h.multiple?L.multiple=!0:h.size&&(L.size=h.size))):i=L.createElementNS(i,d),i[yr]=a,i[Ta]=h,Td(i,a,!1,!1),a.stateNode=i;e:{switch(L=jr(d,h),d){case"dialog":Nn("cancel",i),Nn("close",i),v=h;break;case"iframe":case"object":case"embed":Nn("load",i),v=h;break;case"video":case"audio":for(v=0;v<Na.length;v++)Nn(Na[v],i);v=h;break;case"source":Nn("error",i),v=h;break;case"img":case"image":case"link":Nn("error",i),Nn("load",i),v=h;break;case"details":Nn("toggle",i),v=h;break;case"input":lt(i,h),v=tt(i,h),Nn("invalid",i);break;case"option":v=h;break;case"select":i._wrapperState={wasMultiple:!!h.multiple},v=G({},h,{value:void 0}),Nn("invalid",i);break;case"textarea":zt(i,h),v=qe(i,h),Nn("invalid",i);break;default:v=h}wn(d,v),ee=v;for(b in ee)if(ee.hasOwnProperty(b)){var re=ee[b];b==="style"?gn(i,re):b==="dangerouslySetInnerHTML"?(re=re?re.__html:void 0,re!=null&&nr(i,re)):b==="children"?typeof re=="string"?(d!=="textarea"||re!=="")&&Pt(i,re):typeof re=="number"&&Pt(i,""+re):b!=="suppressContentEditableWarning"&&b!=="suppressHydrationWarning"&&b!=="autoFocus"&&(o.hasOwnProperty(b)?re!=null&&b==="onScroll"&&Nn("scroll",i):re!=null&&T(i,b,re,L))}switch(d){case"input":We(i),Re(i,h,!1);break;case"textarea":We(i),bn(i);break;case"option":h.value!=null&&i.setAttribute("value",""+ye(h.value));break;case"select":i.multiple=!!h.multiple,b=h.value,b!=null?Ie(i,!!h.multiple,b,!1):h.defaultValue!=null&&Ie(i,!!h.multiple,h.defaultValue,!0);break;default:typeof v.onClick=="function"&&(i.onclick=kc)}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 Ar(a),null;case 6:if(i&&a.stateNode!=null)fh(i,a,i.memoizedProps,h);else{if(typeof h!="string"&&a.stateNode===null)throw Error(n(166));if(d=Xs(za.current),Xs(Ps.current),kl(a)){if(h=a.stateNode,d=a.memoizedProps,h[yr]=a,(b=h.nodeValue!==d)&&(i=Br,i!==null))switch(i.tag){case 3:ao(h.nodeValue,d,(i.mode&1)!==0);break;case 5:i.memoizedProps.suppressHydrationWarning!==!0&&ao(h.nodeValue,d,(i.mode&1)!==0)}b&&(a.flags|=4)}else h=(d.nodeType===9?d:d.ownerDocument).createTextNode(h),h[yr]=a,a.stateNode=h}return Ar(a),null;case 13:if(En(Dn),h=a.memoizedState,i===null||i.memoizedState!==null&&i.memoizedState.dehydrated!==null){if(Tt&&Te!==null&&(a.mode&1)!==0&&(a.flags&128)===0)id(),Pa(),a.flags|=98560,b=!1;else if(b=kl(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[yr]=a}else Pa(),(a.flags&128)===0&&(a.memoizedState=null),a.flags|=4;Ar(a),b=!1}else bs!==null&&(sn(bs),bs=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||(Dn.current&1)!==0?Yn===0&&(Yn=3):s_())),a.updateQueue!==null&&(a.flags|=4),Ar(a),null);case 4:return pi(),go(i,a),i===null&&yl(a.stateNode.containerInfo),Ar(a),null;case 10:return Rc(a.type._context),Ar(a),null;case 17:return ns(a.type)&&La(),Ar(a),null;case 19:if(En(Dn),b=a.memoizedState,b===null)return Ar(a),null;if(h=(a.flags&128)!==0,L=b.rendering,L===null)if(h)Fl(b,!1);else{if(Yn!==0||i!==null&&(i.flags&128)!==0)for(i=a.child;i!==null;){if(L=Oc(i),L!==null){for(a.flags|=128,Fl(b,!1),h=L.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,L=b.alternate,L===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=L.childLanes,b.lanes=L.lanes,b.child=L.child,b.subtreeFlags=0,b.deletions=null,b.memoizedProps=L.memoizedProps,b.memoizedState=L.memoizedState,b.updateQueue=L.updateQueue,b.type=L.type,i=L.dependencies,b.dependencies=i===null?null:{lanes:i.lanes,firstContext:i.firstContext}),d=d.sibling;return Cn(Dn,Dn.current&1|2),a.child}i=i.sibling}b.tail!==null&&ue()>ea&&(a.flags|=128,h=!0,Fl(b,!1),a.lanes=4194304)}else{if(!h)if(i=Oc(L),i!==null){if(a.flags|=128,h=!0,d=i.updateQueue,d!==null&&(a.updateQueue=d,a.flags|=4),Fl(b,!0),b.tail===null&&b.tailMode==="hidden"&&!L.alternate&&!Tt)return Ar(a),null}else 2*ue()-b.renderingStartTime>ea&&d!==1073741824&&(a.flags|=128,h=!0,Fl(b,!1),a.lanes=4194304);b.isBackwards?(L.sibling=a.child,a.child=L):(d=b.last,d!==null?d.sibling=L:a.child=L,b.last=L)}return b.tail!==null?(a=b.tail,b.rendering=a,b.tail=a.sibling,b.renderingStartTime=ue(),a.sibling=null,d=Dn.current,Cn(Dn,h?d&1|2:d&1),a):(Ar(a),null);case 22:case 23:return Mr(),h=a.memoizedState!==null,i!==null&&i.memoizedState!==null!==h&&(a.flags|=8192),h&&(a.mode&1)!==0?(as&1073741824)!==0&&(Ar(a),a.subtreeFlags&6&&(a.flags|=8192)):Ar(a),null;case 24:return null;case 25:return null}throw Error(n(156,a.tag))}function e_(i,a){switch(td(a),a.tag){case 1:return ns(a.type)&&La(),i=a.flags,i&65536?(a.flags=i&-65537|128,a):null;case 3:return pi(),En(wr),En(fn),Dc(),i=a.flags,(i&65536)!==0&&(i&128)===0?(a.flags=i&-65537|128,a):null;case 5:return dd(a),null;case 13:if(En(Dn),i=a.memoizedState,i!==null&&i.dehydrated!==null){if(a.alternate===null)throw Error(n(340));Pa()}return i=a.flags,i&65536?(a.flags=i&-65537|128,a):null;case 19:return En(Dn),null;case 4:return pi(),null;case 10:return Rc(a.type._context),null;case 22:case 23:return Mr(),null;case 24:return null;default:return null}}var Rn=!1,Vn=!1,t_=typeof WeakSet=="function"?WeakSet:Set,Xe=null;function Xo(i,a){var d=i.ref;if(d!==null)if(typeof d=="function")try{d(null)}catch(h){Jn(i,a,h)}else d.current=null}function Kc(i,a,d){try{d()}catch(h){Jn(i,a,h)}}var Md=!1;function hh(i,a){if(zo=Mo,i=hl(),Hu(i)){if("selectionStart"in i)var d={start:i.selectionStart,end:i.selectionEnd};else e:{d=(d=i.ownerDocument)&&d.defaultView||window;var h=d.getSelection&&d.getSelection();if(h&&h.rangeCount!==0){d=h.anchorNode;var v=h.anchorOffset,b=h.focusNode;h=h.focusOffset;try{d.nodeType,b.nodeType}catch{d=null;break e}var L=0,ee=-1,re=-1,we=0,Ae=0,Me=i,Ce=null;t:for(;;){for(var Je;Me!==d||v!==0&&Me.nodeType!==3||(ee=L+v),Me!==b||h!==0&&Me.nodeType!==3||(re=L+h),Me.nodeType===3&&(L+=Me.nodeValue.length),(Je=Me.firstChild)!==null;)Ce=Me,Me=Je;for(;;){if(Me===i)break t;if(Ce===d&&++we===v&&(ee=L),Ce===b&&++Ae===h&&(re=L),(Je=Me.nextSibling)!==null)break;Me=Ce,Ce=Me.parentNode}Me=Je}d=ee===-1||re===-1?null:{start:ee,end:re}}else d=null}d=d||{start:0,end:0}}else d=null;for(wl={focusedElem:i,selectionRange:d},Mo=!1,Xe=a;Xe!==null;)if(a=Xe,i=a.child,(a.subtreeFlags&1028)!==0&&i!==null)i.return=a,Xe=i;else for(;Xe!==null;){a=Xe;try{var nt=a.alternate;if((a.flags&1024)!==0)switch(a.tag){case 0:case 11:case 15:break;case 1:if(nt!==null){var rt=nt.memoizedProps,tr=nt.memoizedState,de=a.stateNode,oe=de.getSnapshotBeforeUpdate(a.elementType===a.type?rt:ss(a.type,rt),tr);de.__reactInternalSnapshotBeforeUpdate=oe}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(Oe){Jn(a,a.return,Oe)}if(i=a.sibling,i!==null){i.return=a.return,Xe=i;break}Xe=a.return}return nt=Md,Md=!1,nt}function Zo(i,a,d){var h=a.updateQueue;if(h=h!==null?h.lastEffect:null,h!==null){var v=h=h.next;do{if((v.tag&i)===i){var b=v.destroy;v.destroy=void 0,b!==void 0&&Kc(a,d,b)}v=v.next}while(v!==h)}}function yo(i,a){if(a=a.updateQueue,a=a!==null?a.lastEffect:null,a!==null){var d=a=a.next;do{if((d.tag&i)===i){var h=d.create;d.destroy=h()}d=d.next}while(d!==a)}}function Wa(i){var a=i.ref;if(a!==null){var d=i.stateNode;switch(i.tag){case 5:i=d;break;default:i=d}typeof a=="function"?a(i):a.current=i}}function Rd(i){var a=i.alternate;a!==null&&(i.alternate=null,Rd(a)),i.child=null,i.deletions=null,i.sibling=null,i.tag===5&&(a=i.stateNode,a!==null&&(delete a[yr],delete a[Ta],delete a[Bo],delete a[Wf],delete a[Xu])),i.stateNode=null,i.return=null,i.dependencies=null,i.memoizedProps=null,i.memoizedState=null,i.pendingProps=null,i.stateNode=null,i.updateQueue=null}function Ld(i){return i.tag===5||i.tag===3||i.tag===4}function Id(i){e:for(;;){for(;i.sibling===null;){if(i.return===null||Ld(i.return))return null;i=i.return}for(i.sibling.return=i.return,i=i.sibling;i.tag!==5&&i.tag!==6&&i.tag!==18;){if(i.flags&2||i.child===null||i.tag===4)continue e;i.child.return=i,i=i.child}if(!(i.flags&2))return i.stateNode}}function yi(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=kc));else if(h!==4&&(i=i.child,i!==null))for(yi(i,a,d),i=i.sibling;i!==null;)yi(i,a,d),i=i.sibling}function Pd(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(Pd(i,a,d),i=i.sibling;i!==null;)Pd(i,a,d),i=i.sibling}var zn=null,js=!1;function wi(i,a,d){for(d=d.child;d!==null;)Od(i,a,d),d=d.sibling}function Od(i,a,d){if(Dr&&typeof Dr.onCommitFiberUnmount=="function")try{Dr.onCommitFiberUnmount(cn,d)}catch{}switch(d.tag){case 5:Vn||Xo(d,a);case 6:var h=zn,v=js;zn=null,wi(i,a,d),zn=h,js=v,zn!==null&&(js?(i=zn,d=d.stateNode,i.nodeType===8?i.parentNode.removeChild(d):i.removeChild(d)):zn.removeChild(d.stateNode));break;case 18:zn!==null&&(js?(i=zn,d=d.stateNode,i.nodeType===8?lo(i.parentNode,d):i.nodeType===1&&lo(i,d),Xi(i)):lo(zn,d.stateNode));break;case 4:h=zn,v=js,zn=d.stateNode.containerInfo,js=!0,wi(i,a,d),zn=h,js=v;break;case 0:case 11:case 14:case 15:if(!Vn&&(h=d.updateQueue,h!==null&&(h=h.lastEffect,h!==null))){v=h=h.next;do{var b=v,L=b.destroy;b=b.tag,L!==void 0&&((b&2)!==0||(b&4)!==0)&&Kc(d,a,L),v=v.next}while(v!==h)}wi(i,a,d);break;case 1:if(!Vn&&(Xo(d,a),h=d.stateNode,typeof h.componentWillUnmount=="function"))try{h.props=d.memoizedProps,h.state=d.memoizedState,h.componentWillUnmount()}catch(ee){Jn(d,a,ee)}wi(i,a,d);break;case 21:wi(i,a,d);break;case 22:d.mode&1?(Vn=(h=Vn)||d.memoizedState!==null,wi(i,a,d),Vn=h):wi(i,a,d);break;default:wi(i,a,d)}}function Dd(i){var a=i.updateQueue;if(a!==null){i.updateQueue=null;var d=i.stateNode;d===null&&(d=i.stateNode=new t_),a.forEach(function(h){var v=I0.bind(null,i,h);d.has(h)||(d.add(h),h.then(v,v))})}}function ni(i,a){var d=a.deletions;if(d!==null)for(var h=0;h<d.length;h++){var v=d[h];try{var b=i,L=a,ee=L;e:for(;ee!==null;){switch(ee.tag){case 5:zn=ee.stateNode,js=!1;break e;case 3:zn=ee.stateNode.containerInfo,js=!0;break e;case 4:zn=ee.stateNode.containerInfo,js=!0;break e}ee=ee.return}if(zn===null)throw Error(n(160));Od(b,L,v),zn=null,js=!1;var re=v.alternate;re!==null&&(re.return=null),v.return=null}catch(we){Jn(v,a,we)}}if(a.subtreeFlags&12854)for(a=a.child;a!==null;)qa(a,i),a=a.sibling}function qa(i,a){var d=i.alternate,h=i.flags;switch(i.tag){case 0:case 11:case 14:case 15:if(ni(a,i),Tr(i),h&4){try{Zo(3,i,i.return),yo(3,i)}catch(rt){Jn(i,i.return,rt)}try{Zo(5,i,i.return)}catch(rt){Jn(i,i.return,rt)}}break;case 1:ni(a,i),Tr(i),h&512&&d!==null&&Xo(d,d.return);break;case 5:if(ni(a,i),Tr(i),h&512&&d!==null&&Xo(d,d.return),i.flags&32){var v=i.stateNode;try{Pt(v,"")}catch(rt){Jn(i,i.return,rt)}}if(h&4&&(v=i.stateNode,v!=null)){var b=i.memoizedProps,L=d!==null?d.memoizedProps:b,ee=i.type,re=i.updateQueue;if(i.updateQueue=null,re!==null)try{ee==="input"&&b.type==="radio"&&b.name!=null&&Ke(v,b),jr(ee,L);var we=jr(ee,b);for(L=0;L<re.length;L+=2){var Ae=re[L],Me=re[L+1];Ae==="style"?gn(v,Me):Ae==="dangerouslySetInnerHTML"?nr(v,Me):Ae==="children"?Pt(v,Me):T(v,Ae,Me,we)}switch(ee){case"input":Se(v,b);break;case"textarea":en(v,b);break;case"select":var Ce=v._wrapperState.wasMultiple;v._wrapperState.wasMultiple=!!b.multiple;var Je=b.value;Je!=null?Ie(v,!!b.multiple,Je,!1):Ce!==!!b.multiple&&(b.defaultValue!=null?Ie(v,!!b.multiple,b.defaultValue,!0):Ie(v,!!b.multiple,b.multiple?[]:"",!1))}v[Ta]=b}catch(rt){Jn(i,i.return,rt)}}break;case 6:if(ni(a,i),Tr(i),h&4){if(i.stateNode===null)throw Error(n(162));v=i.stateNode,b=i.memoizedProps;try{v.nodeValue=b}catch(rt){Jn(i,i.return,rt)}}break;case 3:if(ni(a,i),Tr(i),h&4&&d!==null&&d.memoizedState.isDehydrated)try{Xi(a.containerInfo)}catch(rt){Jn(i,i.return,rt)}break;case 4:ni(a,i),Tr(i);break;case 13:ni(a,i),Tr(i),v=i.child,v.flags&8192&&(b=v.memoizedState!==null,v.stateNode.isHidden=b,!b||v.alternate!==null&&v.alternate.memoizedState!==null||(Qc=ue())),h&4&&Dd(i);break;case 22:if(Ae=d!==null&&d.memoizedState!==null,i.mode&1?(Vn=(we=Vn)||Ae,ni(a,i),Vn=we):ni(a,i),Tr(i),h&8192){if(we=i.memoizedState!==null,(i.stateNode.isHidden=we)&&!Ae&&(i.mode&1)!==0)for(Xe=i,Ae=i.child;Ae!==null;){for(Me=Xe=Ae;Xe!==null;){switch(Ce=Xe,Je=Ce.child,Ce.tag){case 0:case 11:case 14:case 15:Zo(4,Ce,Ce.return);break;case 1:Xo(Ce,Ce.return);var nt=Ce.stateNode;if(typeof nt.componentWillUnmount=="function"){h=Ce,d=Ce.return;try{a=h,nt.props=a.memoizedProps,nt.state=a.memoizedState,nt.componentWillUnmount()}catch(rt){Jn(h,d,rt)}}break;case 5:Xo(Ce,Ce.return);break;case 22:if(Ce.memoizedState!==null){zl(Me);continue}}Je!==null?(Je.return=Ce,Xe=Je):zl(Me)}Ae=Ae.sibling}e:for(Ae=null,Me=i;;){if(Me.tag===5){if(Ae===null){Ae=Me;try{v=Me.stateNode,we?(b=v.style,typeof b.setProperty=="function"?b.setProperty("display","none","important"):b.display="none"):(ee=Me.stateNode,re=Me.memoizedProps.style,L=re!=null&&re.hasOwnProperty("display")?re.display:null,ee.style.display=$n("display",L))}catch(rt){Jn(i,i.return,rt)}}}else if(Me.tag===6){if(Ae===null)try{Me.stateNode.nodeValue=we?"":Me.memoizedProps}catch(rt){Jn(i,i.return,rt)}}else if((Me.tag!==22&&Me.tag!==23||Me.memoizedState===null||Me===i)&&Me.child!==null){Me.child.return=Me,Me=Me.child;continue}if(Me===i)break e;for(;Me.sibling===null;){if(Me.return===null||Me.return===i)break e;Ae===Me&&(Ae=null),Me=Me.return}Ae===Me&&(Ae=null),Me.sibling.return=Me.return,Me=Me.sibling}}break;case 19:ni(a,i),Tr(i),h&4&&Dd(i);break;case 21:break;default:ni(a,i),Tr(i)}}function Tr(i){var a=i.flags;if(a&2){try{e:{for(var d=i.return;d!==null;){if(Ld(d)){var h=d;break e}d=d.return}throw Error(n(160))}switch(h.tag){case 5:var v=h.stateNode;h.flags&32&&(Pt(v,""),h.flags&=-33);var b=Id(i);Pd(i,b,v);break;case 3:case 4:var L=h.stateNode.containerInfo,ee=Id(i);yi(i,ee,L);break;default:throw Error(n(161))}}catch(re){Jn(i,i.return,re)}i.flags&=-3}a&4096&&(i.flags&=-4097)}function n_(i,a,d){Xe=i,Ha(i)}function Ha(i,a,d){for(var h=(i.mode&1)!==0;Xe!==null;){var v=Xe,b=v.child;if(v.tag===22&&h){var L=v.memoizedState!==null||Rn;if(!L){var ee=v.alternate,re=ee!==null&&ee.memoizedState!==null||Vn;ee=Rn;var we=Vn;if(Rn=L,(Vn=re)&&!we)for(Xe=v;Xe!==null;)L=Xe,re=L.child,L.tag===22&&L.memoizedState!==null?Yc(v):re!==null?(re.return=L,Xe=re):Yc(v);for(;b!==null;)Xe=b,Ha(b),b=b.sibling;Xe=v,Rn=ee,Vn=we}mh(i)}else(v.subtreeFlags&8772)!==0&&b!==null?(b.return=v,Xe=b):mh(i)}}function mh(i){for(;Xe!==null;){var a=Xe;if((a.flags&8772)!==0){var d=a.alternate;try{if((a.flags&8772)!==0)switch(a.tag){case 0:case 11:case 15:Vn||yo(5,a);break;case 1:var h=a.stateNode;if(a.flags&4&&!Vn)if(d===null)h.componentDidMount();else{var v=a.elementType===a.type?d.memoizedProps:ss(a.type,d.memoizedProps);h.componentDidUpdate(v,d.memoizedState,h.__reactInternalSnapshotBeforeUpdate)}var b=a.updateQueue;b!==null&&Tn(a,b,h);break;case 3:var L=a.updateQueue;if(L!==null){if(d=null,a.child!==null)switch(a.child.tag){case 5:d=a.child.stateNode;break;case 1:d=a.child.stateNode}Tn(a,L,d)}break;case 5:var ee=a.stateNode;if(d===null&&a.flags&4){d=ee;var re=a.memoizedProps;switch(a.type){case"button":case"input":case"select":case"textarea":re.autoFocus&&d.focus();break;case"img":re.src&&(d.src=re.src)}}break;case 6:break;case 4:break;case 12:break;case 13:if(a.memoizedState===null){var we=a.alternate;if(we!==null){var Ae=we.memoizedState;if(Ae!==null){var Me=Ae.dehydrated;Me!==null&&Xi(Me)}}}break;case 19:case 17:case 21:case 22:case 23:case 25:break;default:throw Error(n(163))}Vn||a.flags&512&&Wa(a)}catch(Ce){Jn(a,a.return,Ce)}}if(a===i){Xe=null;break}if(d=a.sibling,d!==null){d.return=a.return,Xe=d;break}Xe=a.return}}function zl(i){for(;Xe!==null;){var a=Xe;if(a===i){Xe=null;break}var d=a.sibling;if(d!==null){d.return=a.return,Xe=d;break}Xe=a.return}}function Yc(i){for(;Xe!==null;){var a=Xe;try{switch(a.tag){case 0:case 11:case 15:var d=a.return;try{yo(4,a)}catch(re){Jn(a,d,re)}break;case 1:var h=a.stateNode;if(typeof h.componentDidMount=="function"){var v=a.return;try{h.componentDidMount()}catch(re){Jn(a,v,re)}}var b=a.return;try{Wa(a)}catch(re){Jn(a,b,re)}break;case 5:var L=a.return;try{Wa(a)}catch(re){Jn(a,L,re)}}}catch(re){Jn(a,a.return,re)}if(a===i){Xe=null;break}var ee=a.sibling;if(ee!==null){ee.return=a.return,Xe=ee;break}Xe=a.return}}var r_=Math.ceil,Jc=I.ReactCurrentDispatcher,Xc=I.ReactCurrentOwner,Ss=I.ReactCurrentBatchConfig,rn=0,er=null,Gn=null,ur=0,as=0,Qo=$i(0),Yn=0,Va=null,wo=0,Bl=0,Zc=0,Ga=null,Hr=null,Qc=0,ea=1/0,vi=null,y=!1,k=null,M=null,D=!1,q=null,H=0,V=0,ne=null,Le=-1,_e=0;function he(){return(rn&6)!==0?ue():Le!==-1?Le:Le=ue()}function $e(i){return(i.mode&1)===0?1:(rn&2)!==0&&ur!==0?ur&-ur:Ur.transition!==null?(_e===0&&(_e=hr()),_e):(i=ln,i!==0||(i=window.event,i=i===void 0?16:be(i.type)),i)}function Pe(i,a,d,h){if(50<V)throw V=0,ne=null,Error(n(185));mr(i,d,h),((rn&2)===0||i!==er)&&(i===er&&((rn&2)===0&&(Bl|=d),Yn===4&&Be(i,ur)),ze(i,h),d===1&&rn===0&&(a.mode&1)===0&&(ea=ue()+500,Sl&&Ti()))}function ze(i,a){var d=i.callbackNode;An(i,a);var h=Gi(i,i===er?ur:0);if(h===0)d!==null&&ii(d),i.callbackNode=null,i.callbackPriority=0;else if(a=h&-h,i.callbackPriority!==a){if(d!=null&&ii(d),a===1)i.tag===0?Hf(bt.bind(null,i)):ed(bt.bind(null,i)),Cc(function(){(rn&6)===0&&Ti()}),d=null;else{switch(fa(h)){case 1:d=Vi;break;case 4:d=hs;break;case 16:d=Cs;break;case 536870912:d=it;break;default:d=Cs}d=Kg(d,Ze.bind(null,i))}i.callbackPriority=a,i.callbackNode=d}}function Ze(i,a){if(Le=-1,_e=0,(rn&6)!==0)throw Error(n(327));var d=i.callbackNode;if(eu()&&i.callbackNode!==d)return null;var h=Gi(i,i===er?ur:0);if(h===0)return null;if((h&30)!==0||(h&i.expiredLanes)!==0||a)a=_h(i,h);else{a=h;var v=rn;rn|=2;var b=Ka();(er!==i||ur!==a)&&(vi=null,ea=ue()+500,dr(i,a));do try{T0();break}catch(ee){Ds(i,ee)}while(!0);ld(),Jc.current=b,rn=v,Gn!==null?a=0:(er=null,ur=0,a=Yn)}if(a!==0){if(a===2&&(v=Fr(i),v!==0&&(h=v,a=Ve(i,v))),a===1)throw d=Va,dr(i,0),Be(i,h),ze(i,ue()),d;if(a===6)Be(i,h);else{if(v=i.current.alternate,(h&30)===0&&!Rt(v)&&(a=_h(i,h),a===2&&(b=Fr(i),b!==0&&(h=b,a=Ve(i,b))),a===1))throw d=Va,dr(i,0),Be(i,h),ze(i,ue()),d;switch(i.finishedWork=v,i.finishedLanes=h,a){case 0:case 1:throw Error(n(345));case 2:Ul(i,Hr,vi);break;case 3:if(Be(i,h),(h&130023424)===h&&(a=Qc+500-ue(),10<a)){if(Gi(i,0)!==0)break;if(v=i.suspendedLanes,(v&h)!==h){he(),i.pingedLanes|=i.suspendedLanes&v;break}i.timeoutHandle=Nc(Ul.bind(null,i,Hr,vi),a);break}Ul(i,Hr,vi);break;case 4:if(Be(i,h),(h&4194240)===h)break;for(a=i.eventTimes,v=-1;0<h;){var L=31-sr(h);b=1<<L,L=a[L],L>v&&(v=L),h&=~b}if(h=v,h=ue()-h,h=(120>h?120:480>h?480:1080>h?1080:1920>h?1920:3e3>h?3e3:4320>h?4320:1960*r_(h/1960))-h,10<h){i.timeoutHandle=Nc(Ul.bind(null,i,Hr,vi),h);break}Ul(i,Hr,vi);break;case 5:Ul(i,Hr,vi);break;default:throw Error(n(329))}}}return ze(i,ue()),i.callbackNode===d?Ze.bind(null,i):null}function Ve(i,a){var d=Ga;return i.current.memoizedState.isDehydrated&&(dr(i,a).flags|=256),i=_h(i,a),i!==2&&(a=Hr,Hr=d,a!==null&&sn(a)),i}function sn(i){Hr===null?Hr=i:Hr.push.apply(Hr,i)}function Rt(i){for(var a=i;;){if(a.flags&16384){var d=a.updateQueue;if(d!==null&&(d=d.stores,d!==null))for(var h=0;h<d.length;h++){var v=d[h],b=v.getSnapshot;v=v.value;try{if(!Vs(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 Be(i,a){for(a&=~Zc,a&=~Bl,i.suspendedLanes|=a,i.pingedLanes&=~a,i=i.expirationTimes;0<a;){var d=31-sr(a),h=1<<d;i[d]=-1,a&=~h}}function bt(i){if((rn&6)!==0)throw Error(n(327));eu();var a=Gi(i,0);if((a&1)===0)return ze(i,ue()),null;var d=_h(i,a);if(i.tag!==0&&d===2){var h=Fr(i);h!==0&&(a=h,d=Ve(i,h))}if(d===1)throw d=Va,dr(i,0),Be(i,a),ze(i,ue()),d;if(d===6)throw Error(n(345));return i.finishedWork=i.current.alternate,i.finishedLanes=a,Ul(i,Hr,vi),ze(i,ue()),null}function xn(i,a){var d=rn;rn|=1;try{return i(a)}finally{rn=d,rn===0&&(ea=ue()+500,Sl&&Ti())}}function hn(i){q!==null&&q.tag===0&&(rn&6)===0&&eu();var a=rn;rn|=1;var d=Ss.transition,h=ln;try{if(Ss.transition=null,ln=1,i)return i()}finally{ln=h,Ss.transition=d,rn=a,(rn&6)===0&&Ti()}}function Mr(){as=Qo.current,En(Qo)}function dr(i,a){i.finishedWork=null,i.finishedLanes=0;var d=i.timeoutHandle;if(d!==-1&&(i.timeoutHandle=-1,$a(d)),Gn!==null)for(d=Gn.return;d!==null;){var h=d;switch(td(h),h.tag){case 1:h=h.type.childContextTypes,h!=null&&La();break;case 3:pi(),En(wr),En(fn),Dc();break;case 5:dd(h);break;case 4:pi();break;case 13:En(Dn);break;case 19:En(Dn);break;case 10:Rc(h.type._context);break;case 22:case 23:Mr()}d=d.return}if(er=i,Gn=i=Ya(i.current,null),ur=as=a,Yn=0,Va=null,Zc=Bl=wo=0,Hr=Ga=null,Li!==null){for(a=0;a<Li.length;a++)if(d=Li[a],h=d.interleaved,h!==null){d.interleaved=null;var v=h.next,b=d.pending;if(b!==null){var L=b.next;b.next=v,h.next=L}d.pending=h}Li=null}return i}function Ds(i,a){do{var d=Gn;try{if(ld(),Fc.current=ei,zc){for(var h=yn.memoizedState;h!==null;){var v=h.queue;v!==null&&(v.pending=null),h=h.next}zc=!1}if(Go=0,Ht=Mn=yn=null,Tl=!1,Ml=0,Xc.current=null,d===null||d.return===null){Yn=1,Va=a,Gn=null;break}e:{var b=i,L=d.return,ee=d,re=a;if(a=ur,ee.flags|=32768,re!==null&&typeof re=="object"&&typeof re.then=="function"){var we=re,Ae=ee,Me=Ae.tag;if((Ae.mode&1)===0&&(Me===0||Me===11||Me===15)){var Ce=Ae.alternate;Ce?(Ae.updateQueue=Ce.updateQueue,Ae.memoizedState=Ce.memoizedState,Ae.lanes=Ce.lanes):(Ae.updateQueue=null,Ae.memoizedState=null)}var Je=Pl(L);if(Je!==null){Je.flags&=-257,Sd(Je,L,ee,b,a),Je.mode&1&&oh(b,we,a),a=Je,re=we;var nt=a.updateQueue;if(nt===null){var rt=new Set;rt.add(re),a.updateQueue=rt}else nt.add(re);break e}else{if((a&1)===0){oh(b,we,a),s_();break e}re=Error(n(426))}}else if(Tt&&ee.mode&1){var tr=Pl(L);if(tr!==null){(tr.flags&65536)===0&&(tr.flags|=256),Sd(tr,L,ee,b,a),Oa(gi(re,ee));break e}}b=re=gi(re,ee),Yn!==4&&(Yn=2),Ga===null?Ga=[b]:Ga.push(b),b=L;do{switch(b.tag){case 3:b.flags|=65536,a&=-a,b.lanes|=a;var de=jd(b,re,a);Lc(b,de);break e;case 1:ee=re;var oe=b.type,me=b.stateNode;if((b.flags&128)===0&&(typeof oe.getDerivedStateFromError=="function"||me!==null&&typeof me.componentDidCatch=="function"&&(M===null||!M.has(me)))){b.flags|=65536,a&=-a,b.lanes|=a;var Oe=Yo(b,ee,a);Lc(b,Oe);break e}}b=b.return}while(b!==null)}qg(d)}catch(at){a=at,Gn===d&&d!==null&&(Gn=d=d.return);continue}break}while(!0)}function Ka(){var i=Jc.current;return Jc.current=ei,i===null?ei:i}function s_(){(Yn===0||Yn===3||Yn===2)&&(Yn=4),er===null||(wo&268435455)===0&&(Bl&268435455)===0||Be(er,ur)}function _h(i,a){var d=rn;rn|=2;var h=Ka();(er!==i||ur!==a)&&(vi=null,dr(i,a));do try{A0();break}catch(v){Ds(i,v)}while(!0);if(ld(),rn=d,Jc.current=h,Gn!==null)throw Error(n(261));return er=null,ur=0,Yn}function A0(){for(;Gn!==null;)Wg(Gn)}function T0(){for(;Gn!==null&&!oi();)Wg(Gn)}function Wg(i){var a=Gg(i.alternate,i,as);i.memoizedProps=i.pendingProps,a===null?qg(i):Gn=a,Xc.current=null}function qg(i){var a=i;do{var d=a.alternate;if(i=a.return,(a.flags&32768)===0){if(d=Qm(d,a,as),d!==null){Gn=d;return}}else{if(d=e_(d,a),d!==null){d.flags&=32767,Gn=d;return}if(i!==null)i.flags|=32768,i.subtreeFlags=0,i.deletions=null;else{Yn=6,Gn=null;return}}if(a=a.sibling,a!==null){Gn=a;return}Gn=a=i}while(a!==null);Yn===0&&(Yn=5)}function Ul(i,a,d){var h=ln,v=Ss.transition;try{Ss.transition=null,ln=1,M0(i,a,d,h)}finally{Ss.transition=v,ln=h}return null}function M0(i,a,d,h){do eu();while(q!==null);if((rn&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(da(i,b),i===er&&(Gn=er=null,ur=0),(d.subtreeFlags&2064)===0&&(d.flags&2064)===0||D||(D=!0,Kg(Cs,function(){return eu(),null})),b=(d.flags&15990)!==0,(d.subtreeFlags&15990)!==0||b){b=Ss.transition,Ss.transition=null;var L=ln;ln=1;var ee=rn;rn|=4,Xc.current=null,hh(i,d),qa(d,i),Vu(wl),Mo=!!zo,wl=zo=null,i.current=d,n_(d),Or(),rn=ee,ln=L,Ss.transition=b}else i.current=d;if(D&&(D=!1,q=i,H=v),b=i.pendingLanes,b===0&&(M=null),Hs(d.stateNode),ze(i,ue()),a!==null)for(h=i.onRecoverableError,d=0;d<a.length;d++)v=a[d],h(v.value,{componentStack:v.stack,digest:v.digest});if(y)throw y=!1,i=k,k=null,i;return(H&1)!==0&&i.tag!==0&&eu(),b=i.pendingLanes,(b&1)!==0?i===ne?V++:(V=0,ne=i):V=0,Ti(),null}function eu(){if(q!==null){var i=fa(H),a=Ss.transition,d=ln;try{if(Ss.transition=null,ln=16>i?16:i,q===null)var h=!1;else{if(i=q,q=null,H=0,(rn&6)!==0)throw Error(n(331));var v=rn;for(rn|=4,Xe=i.current;Xe!==null;){var b=Xe,L=b.child;if((Xe.flags&16)!==0){var ee=b.deletions;if(ee!==null){for(var re=0;re<ee.length;re++){var we=ee[re];for(Xe=we;Xe!==null;){var Ae=Xe;switch(Ae.tag){case 0:case 11:case 15:Zo(8,Ae,b)}var Me=Ae.child;if(Me!==null)Me.return=Ae,Xe=Me;else for(;Xe!==null;){Ae=Xe;var Ce=Ae.sibling,Je=Ae.return;if(Rd(Ae),Ae===we){Xe=null;break}if(Ce!==null){Ce.return=Je,Xe=Ce;break}Xe=Je}}}var nt=b.alternate;if(nt!==null){var rt=nt.child;if(rt!==null){nt.child=null;do{var tr=rt.sibling;rt.sibling=null,rt=tr}while(rt!==null)}}Xe=b}}if((b.subtreeFlags&2064)!==0&&L!==null)L.return=b,Xe=L;else e:for(;Xe!==null;){if(b=Xe,(b.flags&2048)!==0)switch(b.tag){case 0:case 11:case 15:Zo(9,b,b.return)}var de=b.sibling;if(de!==null){de.return=b.return,Xe=de;break e}Xe=b.return}}var oe=i.current;for(Xe=oe;Xe!==null;){L=Xe;var me=L.child;if((L.subtreeFlags&2064)!==0&&me!==null)me.return=L,Xe=me;else e:for(L=oe;Xe!==null;){if(ee=Xe,(ee.flags&2048)!==0)try{switch(ee.tag){case 0:case 11:case 15:yo(9,ee)}}catch(at){Jn(ee,ee.return,at)}if(ee===L){Xe=null;break e}var Oe=ee.sibling;if(Oe!==null){Oe.return=ee.return,Xe=Oe;break e}Xe=ee.return}}if(rn=v,Ti(),Dr&&typeof Dr.onPostCommitFiberRoot=="function")try{Dr.onPostCommitFiberRoot(cn,i)}catch{}h=!0}return h}finally{ln=d,Ss.transition=a}}return!1}function Hg(i,a,d){a=gi(d,a),a=jd(i,a,1),i=ho(i,a,1),a=he(),i!==null&&(mr(i,1,a),ze(i,a))}function Jn(i,a,d){if(i.tag===3)Hg(i,i,d);else for(;a!==null;){if(a.tag===3){Hg(a,i,d);break}else if(a.tag===1){var h=a.stateNode;if(typeof a.type.getDerivedStateFromError=="function"||typeof h.componentDidCatch=="function"&&(M===null||!M.has(h))){i=gi(d,i),i=Yo(a,i,1),a=ho(a,i,1),i=he(),a!==null&&(mr(a,1,i),ze(a,i));break}}a=a.return}}function R0(i,a,d){var h=i.pingCache;h!==null&&h.delete(a),a=he(),i.pingedLanes|=i.suspendedLanes&d,er===i&&(ur&d)===d&&(Yn===4||Yn===3&&(ur&130023424)===ur&&500>ue()-Qc?dr(i,0):Zc|=d),ze(i,a)}function Vg(i,a){a===0&&((i.mode&1)===0?a=1:(a=ms,ms<<=1,(ms&130023424)===0&&(ms=4194304)));var d=he();i=or(i,a),i!==null&&(mr(i,a,d),ze(i,d))}function L0(i){var a=i.memoizedState,d=0;a!==null&&(d=a.retryLane),Vg(i,d)}function I0(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),Vg(i,d)}var Gg;Gg=function(i,a,d){if(i!==null)if(i.memoizedProps!==a.pendingProps||wr.current)$r=!0;else{if((i.lanes&d)===0&&(a.flags&128)===0)return $r=!1,Zm(i,a,d);$r=(i.flags&131072)!==0}else $r=!1,Tt&&(a.flags&1048576)!==0&&Vf(a,Ec,a.index);switch(a.lanes=0,a.tag){case 2:var h=a.type;Os(i,a),i=a.pendingProps;var v=Ra(a,fn.current);Da(a,d),v=Jt(null,a,h,i,v,d);var b=Qn();return a.flags|=1,typeof v=="object"&&v!==null&&typeof v.render=="function"&&v.$$typeof===void 0?(a.tag=1,a.memoizedState=null,a.updateQueue=null,ns(h)?(b=!0,bl(a)):b=!1,a.memoizedState=v.state!==null&&v.state!==void 0?v.state:null,Nl(a),v.updater=Ua,a.stateNode=v,v._reactInternals=a,Pi(a,h,i,d),a=Ol(null,a,h,!0,b,d)):(a.tag=0,Tt&&b&&$c(a),Wr(null,a,v,d),a=a.child),a;case 16:h=a.elementType;e:{switch(Os(i,a),i=a.pendingProps,v=h._init,h=v(h._payload),a.type=h,v=a.tag=O0(h),i=ss(h,i),v){case 0:a=Vc(null,a,h,i,d);break e;case 1:a=os(null,a,h,i,d);break e;case 11:a=ah(null,a,h,i,d);break e;case 14:a=lh(null,a,h,ss(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:ss(h,v),Vc(i,a,h,v,d);case 1:return h=a.type,v=a.pendingProps,v=a.elementType===h?v:ss(h,v),os(i,a,h,v,d);case 3:e:{if(kd(a),i===null)throw Error(n(387));h=a.pendingProps,b=a.memoizedState,v=b.element,Kf(i,a),Ic(a,h,null,d);var L=a.memoizedState;if(h=L.element,b.isDehydrated)if(b={element:h,isDehydrated:!1,cache:L.cache,pendingSuspenseBoundaries:L.pendingSuspenseBoundaries,transitions:L.transitions},a.updateQueue.baseState=b,a.memoizedState=b,a.flags&256){v=gi(Error(n(423)),a),a=Nd(i,a,h,d,v);break e}else if(h!==v){v=gi(Error(n(424)),a),a=Nd(i,a,h,d,v);break e}else for(Te=co(a.stateNode.containerInfo.firstChild),Br=a,Tt=!0,bs=null,d=Vo(a,null,h,d),a.child=d;d;)d.flags=d.flags&-3|4096,d=d.sibling;else{if(Pa(),h===v){a=Oi(i,a,d);break e}Wr(i,a,h,d)}a=a.child}return a;case 5:return Pc(a),i===null&&sd(a),h=a.type,v=a.pendingProps,b=i!==null?i.memoizedProps:null,L=v.children,Ea(h,v)?L=null:b!==null&&Ea(h,b)&&(a.flags|=32),ch(i,a),Wr(i,a,L,d),a.child;case 6:return i===null&&sd(a),null;case 13:return uh(i,a,d);case 4:return El(a,a.stateNode.containerInfo),h=a.pendingProps,i===null?a.child=_i(a,null,h,d):Wr(i,a,h,d),a.child;case 11:return h=a.type,v=a.pendingProps,v=a.elementType===h?v:ss(h,v),ah(i,a,h,v,d);case 7:return Wr(i,a,a.pendingProps,d),a.child;case 8:return Wr(i,a,a.pendingProps.children,d),a.child;case 12:return Wr(i,a,a.pendingProps.children,d),a.child;case 10:e:{if(h=a.type._context,v=a.pendingProps,b=a.memoizedProps,L=v.value,Cn(ut,h._currentValue),h._currentValue=L,b!==null)if(Vs(b.value,L)){if(b.children===v.children&&!wr.current){a=Oi(i,a,d);break e}}else for(b=a.child,b!==null&&(b.return=a);b!==null;){var ee=b.dependencies;if(ee!==null){L=b.child;for(var re=ee.firstContext;re!==null;){if(re.context===h){if(b.tag===1){re=Ii(-1,d&-d),re.tag=2;var we=b.updateQueue;if(we!==null){we=we.shared;var Ae=we.pending;Ae===null?re.next=re:(re.next=Ae.next,Ae.next=re),we.pending=re}}b.lanes|=d,re=b.alternate,re!==null&&(re.lanes|=d),cd(b.return,d,a),ee.lanes|=d;break}re=re.next}}else if(b.tag===10)L=b.type===a.type?null:b.child;else if(b.tag===18){if(L=b.return,L===null)throw Error(n(341));L.lanes|=d,ee=L.alternate,ee!==null&&(ee.lanes|=d),cd(L,d,a),L=b.sibling}else L=b.child;if(L!==null)L.return=b;else for(L=b;L!==null;){if(L===a){L=null;break}if(b=L.sibling,b!==null){b.return=L.return,L=b;break}L=L.return}b=L}Wr(i,a,v.children,d),a=a.child}return a;case 9:return v=a.type,h=a.pendingProps.children,Da(a,d),v=Is(v),h=h(v),a.flags|=1,Wr(i,a,h,d),a.child;case 14:return h=a.type,v=ss(h,a.pendingProps),v=ss(h.type,v),lh(i,a,h,v,d);case 15:return is(i,a,a.type,a.pendingProps,d);case 17:return h=a.type,v=a.pendingProps,v=a.elementType===h?v:ss(h,v),Os(i,a),a.tag=1,ns(h)?(i=!0,bl(a)):i=!1,Da(a,d),ih(a,h,v),Pi(a,h,v,d),Ol(null,a,h,!0,i,d);case 19:return Ad(i,a,d);case 22:return Jo(i,a,d)}throw Error(n(156,a.tag))};function Kg(i,a){return ds(i,a)}function P0(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 xi(i,a,d,h){return new P0(i,a,d,h)}function i_(i){return i=i.prototype,!(!i||!i.isReactComponent)}function O0(i){if(typeof i=="function")return i_(i)?1:0;if(i!=null){if(i=i.$$typeof,i===W)return 11;if(i===z)return 14}return 2}function Ya(i,a){var d=i.alternate;return d===null?(d=xi(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 ph(i,a,d,h,v,b){var L=2;if(h=i,typeof i=="function")i_(i)&&(L=1);else if(typeof i=="string")L=5;else e:switch(i){case J:return Wl(d.children,v,b,a);case Y:L=8,v|=8;break;case se:return i=xi(12,d,a,v|2),i.elementType=se,i.lanes=b,i;case P:return i=xi(13,d,a,v),i.elementType=P,i.lanes=b,i;case A:return i=xi(19,d,a,v),i.elementType=A,i.lanes=b,i;case te:return gh(d,v,b,a);default:if(typeof i=="object"&&i!==null)switch(i.$$typeof){case ce:L=10;break e;case fe:L=9;break e;case W:L=11;break e;case z:L=14;break e;case $:L=16,h=null;break e}throw Error(n(130,i==null?i:typeof i,""))}return a=xi(L,d,a,v),a.elementType=i,a.type=h,a.lanes=b,a}function Wl(i,a,d,h){return i=xi(7,i,h,a),i.lanes=d,i}function gh(i,a,d,h){return i=xi(22,i,h,a),i.elementType=te,i.lanes=d,i.stateNode={isHidden:!1},i}function o_(i,a,d){return i=xi(6,i,null,a),i.lanes=d,i}function a_(i,a,d){return a=xi(4,i.children!==null?i.children:[],i.key,a),a.lanes=d,a.stateNode={containerInfo:i.containerInfo,pendingChildren:null,implementation:i.implementation},a}function D0(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=Jr(0),this.expirationTimes=Jr(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Jr(0),this.identifierPrefix=h,this.onRecoverableError=v,this.mutableSourceEagerHydrationData=null}function l_(i,a,d,h,v,b,L,ee,re){return i=new D0(i,a,d,ee,re),a===1?(a=1,b===!0&&(a|=8)):a=0,b=xi(3,null,null,a),i.current=b,b.stateNode=i,b.memoizedState={element:h,isDehydrated:d,cache:null,transitions:null,pendingSuspenseBoundaries:null},Nl(b),i}function F0(i,a,d){var h=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:U,key:h==null?null:""+h,children:i,containerInfo:a,implementation:d}}function Yg(i){if(!i)return xs;i=i._reactInternals;e:{if(ft(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(ns(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(ns(d))return xl(i,d,a)}return a}function Jg(i,a,d,h,v,b,L,ee,re){return i=l_(d,h,!0,i,v,b,L,ee,re),i.context=Yg(null),d=i.current,h=he(),v=$e(d),b=Ii(h,v),b.callback=a??null,ho(d,b,v),i.current.lanes=v,mr(i,v,h),ze(i,h),i}function yh(i,a,d,h){var v=a.current,b=he(),L=$e(v);return d=Yg(d),a.context===null?a.context=d:a.pendingContext=d,a=Ii(b,L),a.payload={element:i},h=h===void 0?null:h,h!==null&&(a.callback=h),i=ho(v,a,L),i!==null&&(Pe(i,v,L,b),Cl(i,v,L)),L}function wh(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 Xg(i,a){if(i=i.memoizedState,i!==null&&i.dehydrated!==null){var d=i.retryLane;i.retryLane=d!==0&&d<a?d:a}}function c_(i,a){Xg(i,a),(i=i.alternate)&&Xg(i,a)}function z0(){return null}var Zg=typeof reportError=="function"?reportError:function(i){console.error(i)};function u_(i){this._internalRoot=i}vh.prototype.render=u_.prototype.render=function(i){var a=this._internalRoot;if(a===null)throw Error(n(409));yh(i,a,null,null)},vh.prototype.unmount=u_.prototype.unmount=function(){var i=this._internalRoot;if(i!==null){this._internalRoot=null;var a=i.containerInfo;hn(function(){yh(null,i,null,null)}),a[vs]=null}};function vh(i){this._internalRoot=i}vh.prototype.unstable_scheduleHydration=function(i){if(i){var a=Es();i={blockedOn:null,target:i,priority:a};for(var d=0;d<ir.length&&a!==0&&a<ir[d].priority;d++);ir.splice(d,0,i),d===0&&dc(i)}};function d_(i){return!(!i||i.nodeType!==1&&i.nodeType!==9&&i.nodeType!==11)}function xh(i){return!(!i||i.nodeType!==1&&i.nodeType!==9&&i.nodeType!==11&&(i.nodeType!==8||i.nodeValue!==" react-mount-point-unstable "))}function Qg(){}function B0(i,a,d,h,v){if(v){if(typeof h=="function"){var b=h;h=function(){var we=wh(L);b.call(we)}}var L=Jg(a,h,i,0,null,!1,!1,"",Qg);return i._reactRootContainer=L,i[vs]=L.current,yl(i.nodeType===8?i.parentNode:i),hn(),L}for(;v=i.lastChild;)i.removeChild(v);if(typeof h=="function"){var ee=h;h=function(){var we=wh(re);ee.call(we)}}var re=l_(i,0,!1,null,null,!1,!1,"",Qg);return i._reactRootContainer=re,i[vs]=re.current,yl(i.nodeType===8?i.parentNode:i),hn(function(){yh(a,re,d,h)}),re}function bh(i,a,d,h,v){var b=d._reactRootContainer;if(b){var L=b;if(typeof v=="function"){var ee=v;v=function(){var re=wh(L);ee.call(re)}}yh(a,L,i,v)}else L=B0(d,a,i,v,h);return wh(L)}uc=function(i){switch(i.tag){case 3:var a=i.stateNode;if(a.current.memoizedState.isDehydrated){var d=Hn(a.pendingLanes);d!==0&&(Ki(a,d|1),ze(a,ue()),(rn&6)===0&&(ea=ue()+500,Ti()))}break;case 13:hn(function(){var h=or(i,1);if(h!==null){var v=he();Pe(h,i,1,v)}}),c_(i,1)}},To=function(i){if(i.tag===13){var a=or(i,134217728);if(a!==null){var d=he();Pe(a,i,134217728,d)}c_(i,134217728)}},_r=function(i){if(i.tag===13){var a=$e(i),d=or(i,a);if(d!==null){var h=he();Pe(d,i,a,h)}c_(i,a)}},Es=function(){return ln},$s=function(i,a){var d=ln;try{return ln=i,a()}finally{ln=d}},Ns=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=Ma(h);if(!v)throw Error(n(90));pt(h),Se(h,v)}}}break;case"textarea":en(i,d);break;case"select":a=d.value,a!=null&&Ie(i,!!d.multiple,a,!1)}},st=xn,ct=hn;var U0={usingClientEntryPoint:!1,Events:[Uo,Ks,Ma,Ye,Ge,xn]},Fd={findFiberByHostInstance:Gs,bundleType:0,version:"18.3.1",rendererPackageName:"react-dom"},W0={bundleType:Fd.bundleType,version:Fd.version,rendererPackageName:Fd.rendererPackageName,rendererConfig:Fd.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:I.ReactCurrentDispatcher,findHostInstanceByFiber:function(i){return i=rr(i),i===null?null:i.stateNode},findFiberByHostInstance:Fd.findFiberByHostInstance||z0,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 jh=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!jh.isDisabled&&jh.supportsFiber)try{cn=jh.inject(W0),Dr=jh}catch{}}return Fs.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=U0,Fs.createPortal=function(i,a){var d=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!d_(a))throw Error(n(200));return F0(i,a,null,d)},Fs.createRoot=function(i,a){if(!d_(i))throw Error(n(299));var d=!1,h="",v=Zg;return a!=null&&(a.unstable_strictMode===!0&&(d=!0),a.identifierPrefix!==void 0&&(h=a.identifierPrefix),a.onRecoverableError!==void 0&&(v=a.onRecoverableError)),a=l_(i,1,!1,null,null,d,!1,h,v),i[vs]=a.current,yl(i.nodeType===8?i.parentNode:i),new u_(a)},Fs.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=rr(a),i=i===null?null:i.stateNode,i},Fs.flushSync=function(i){return hn(i)},Fs.hydrate=function(i,a,d){if(!xh(a))throw Error(n(200));return bh(null,i,a,!0,d)},Fs.hydrateRoot=function(i,a,d){if(!d_(i))throw Error(n(405));var h=d!=null&&d.hydratedSources||null,v=!1,b="",L=Zg;if(d!=null&&(d.unstable_strictMode===!0&&(v=!0),d.identifierPrefix!==void 0&&(b=d.identifierPrefix),d.onRecoverableError!==void 0&&(L=d.onRecoverableError)),a=Jg(a,null,i,1,d??null,v,!1,b,L),i[vs]=a.current,yl(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 vh(a)},Fs.render=function(i,a,d){if(!xh(a))throw Error(n(200));return bh(null,i,a,!1,d)},Fs.unmountComponentAtNode=function(i){if(!xh(i))throw Error(n(40));return i._reactRootContainer?(hn(function(){bh(null,null,i,!1,function(){i._reactRootContainer=null,i[vs]=null})}),!0):!1},Fs.unstable_batchedUpdates=xn,Fs.unstable_renderSubtreeIntoContainer=function(i,a,d,h){if(!xh(d))throw Error(n(200));if(i==null||i._reactInternals===void 0)throw Error(n(38));return bh(i,a,d,!1,h)},Fs.version="18.3.1-next-f1338f8080-20240426",Fs}var ay;function Sv(){if(ay)return m_.exports;ay=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(),m_.exports=Z0(),m_.exports}var ly;function Q0(){if(ly)return Sh;ly=1;var e=Sv();return Sh.createRoot=e.createRoot,Sh.hydrateRoot=e.hydrateRoot,Sh}var ej=Q0();const tj=ng(ej),kv=[{id:"dark",label:"Dark (Abstract)",group:"dark",swatches:["#1a1a2e","#16213e","#0f3460","#e94560","#60a5fa","#27ae60"]},{id:"observer-night",label:"Observer Night",group:"dark",swatches:["#0b0f14","#10161e","#161e28","#e8a54a","#6ea8d8","#7bc98c"]},{id:"catppuccin-mocha",label:"Catppuccin Mocha",group:"dark",swatches:["#1e1e2e","#181825","#313244","#cba6f7","#89b4fa","#a6e3a1"]},{id:"catppuccin-macchiato",label:"Catppuccin Macchiato",group:"dark",swatches:["#24273a","#1e2030","#363a4f","#c6a0f6","#8aadf4","#a6da95"]},{id:"catppuccin-frappe",label:"Catppuccin Frappe",group:"dark",swatches:["#303446","#292c3c","#414559","#ca9ee6","#8caaee","#a6d189"]},{id:"rose-pine",label:"Rose Pine",group:"dark",swatches:["#191724","#1f1d2e","#26233a","#c4a7e7","#31748f","#9ccfd8"]},{id:"rose-pine-moon",label:"Rose Pine Moon",group:"dark",swatches:["#232136","#2a273f","#393552","#c4a7e7","#3e8fb0","#9ccfd8"]},{id:"tokyo-night",label:"Tokyo Night",group:"dark",swatches:["#1a1b26","#24283b","#414868","#7aa2f7","#2ac3de","#9ece6a"]},{id:"nord",label:"Nord",group:"dark",swatches:["#2e3440","#3b4252","#434c5e","#88c0d0","#5e81ac","#a3be8c"]},{id:"one-dark",label:"One Dark",group:"dark",swatches:["#282c34","#21252b","#3a3f4b","#61afef","#c678dd","#98c379"]},{id:"dracula",label:"Dracula",group:"dark",swatches:["#282a36","#343746","#44475a","#ff79c6","#8be9fd","#50fa7b"]},{id:"monokai",label:"Monokai",group:"dark",swatches:["#272822","#2d2e27","#3e3d32","#66d9ef","#a1efe4","#a6e22e"]},{id:"gruvbox",label:"Gruvbox",group:"dark",swatches:["#282828","#3c3836","#504945","#fe8019","#83a598","#b8bb26"]},{id:"solarized-dark",label:"Solarized Dark",group:"dark",swatches:["#002b36","#073642","#0b4b5a","#268bd2","#2aa198","#859900"]},{id:"everforest-dark",label:"Everforest Dark",group:"dark",swatches:["#2b3339","#323c41","#3a464c","#a7c080","#7fbbb3","#a7c080"]},{id:"catppuccin-latte",label:"Catppuccin Latte",group:"light",swatches:["#eff1f5","#e6e9ef","#ccd0da","#8839ef","#1e66f5","#40a02b"]},{id:"rose-pine-dawn",label:"Rose Pine Dawn",group:"light",swatches:["#faf4ed","#fffaf3","#f2e9e1","#907aa9","#56949f","#286983"]},{id:"one-light",label:"One Light",group:"light",swatches:["#fafafa","#ffffff","#e5e5e6","#4078f2","#a626a4","#50a14f"]},{id:"everforest-light",label:"Everforest Light",group:"light",swatches:["#fdf6e3","#fffbef","#e8e0cc","#4f8f5a","#3a94c5","#4f8f5a"]},{id:"solarized-light",label:"Solarized Light",group:"light",swatches:["#fdf6e3","#eee8d5","#e3ddc9","#268bd2","#2aa198","#859900"]},{id:"light",label:"Light",group:"light",swatches:["#f7f7fb","#ffffff","#e6e8f0","#e94560","#2563eb","#16a34a"]}];kv.map(e=>({id:e.id,label:e.label}));function nj(e){return`theme-${String(e||"").trim()||"dark"}`}function cy(e){try{const t=document.documentElement,n=Array.from(t.classList).filter(s=>s.startsWith("theme-"));for(const s of n)t.classList.remove(s);t.classList.add(nj(e))}catch{}}const cp=[{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}],up=[{id:"compact",label:"Compact",density:.85},{id:"standard",label:"Standard",density:1},{id:"spacious",label:"Spacious",density:1.2}];function rj(e){const t=String(e).trim();return cp.find(n=>n.id===t)||cp[1]}function sj(e){const t=String(e).trim();return up.find(n=>n.id===t)||up[1]}function uy(e){try{const t=document.documentElement,n=rj(e.font_scale||"md"),s=sj(e.header_density||"standard");t.style.setProperty("--font-scale",String(n.scale)),t.style.setProperty("--header-density",String(s.density))}catch{}}const g_={sm:"(max-width: 767.98px)",md:"(max-width: 1023.98px)",short:"(max-height: 500px)"};function ij(e){try{return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia(e).matches}catch{return!1}}function dy(e){const[t,n]=_.useState(()=>ij(e));return _.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const s=window.matchMedia(e),o=()=>n(s.matches);return o(),typeof s.addEventListener=="function"?s.addEventListener("change",o):s.addListener(o),()=>{typeof s.removeEventListener=="function"?s.removeEventListener("change",o):s.removeListener(o)}},[e]),t}let Bd=null;function oj(e,t){const n=Math.max(0,Math.round(e));if(!(t.scale<=1.01))return{vvHeight:n,keyboardInset:0};const s=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:s,keyboardInset:o}}function aj(){if(Bd)return Bd;if(typeof window>"u"||typeof document>"u")return()=>{};const e=window.visualViewport;if(!e)return()=>{};const t=document.documentElement;let n=0;const s=()=>{n=0;const{vvHeight:l,keyboardInset:u}=oj(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(s))};return s(),e.addEventListener("resize",o),e.addEventListener("scroll",o),window.addEventListener("orientationchange",o),Bd=()=>{e.removeEventListener("resize",o),e.removeEventListener("scroll",o),window.removeEventListener("orientationchange",o),n&&window.cancelAnimationFrame(n),t.style.removeProperty("--vv-height"),t.style.removeProperty("--keyboard-inset"),Bd=null},Bd}var Nv=Sv();function tu(...e){return e.filter(Boolean).join(" ")}function xu({value:e,options:t,placeholder:n="Select…",disabled:s=!1,loading:o=!1,searchable:l=!0,searchPlaceholder:u="Search…",allowCustom:c=!1,clearable:f=!1,minPopoverWidth:m=240,variant:p="panel",className:g,triggerClassName:w,ariaLabel:x,id:S,includeValueOption:j=!1,onOpen:N,customOptionLabel:C,validateCustomValue:E,onChange:T,renderOption:I,renderValue:K}){const U=_.useRef(null),J=_.useRef(null),Y=_.useRef(null),se=_.useRef(N),ce=_.useId(),fe=S||`af-select-${ce.replace(/[^a-zA-Z0-9_-]/g,"")}`,W=`${fe}-listbox`,[P,A]=_.useState(!1),[z,$]=_.useState(""),[te,O]=_.useState(0),[F,G]=_.useState("bottom"),[R,Z]=_.useState({left:0,top:0,width:0});_.useEffect(()=>{se.current=N},[N]);const X=_.useMemo(()=>{if(!j)return t;const xe=String(e??"").trim();return!xe||t.some(Ie=>Ie.value===xe)?t:[...t,{value:xe,label:xe}]},[j,t,e]),Q=_.useMemo(()=>{const xe=String(e??"");return X.find(Ie=>Ie.value===xe)||null},[X,e]),le=_.useMemo(()=>(Q==null?void 0:Q.label)||String(e||"").trim()||"",[Q,e]),ge=_.useMemo(()=>{const xe=z.trim().toLowerCase();return xe?X.filter(Ie=>Ie.label.toLowerCase().includes(xe)||Ie.value.toLowerCase().includes(xe)):X},[X,z]),pe=_.useMemo(()=>{if(!c)return null;const xe=z.trim();if(!xe||X.some(zt=>zt.value===xe))return null;const qe=(E==null?void 0:E(xe,{options:X}))||"";return{value:xe,label:C?C(xe):`Use "${xe}"`,disabled:!!qe,reason:qe}},[c,C,X,z,E]),ye=_.useMemo(()=>{const xe=pe?[pe,...ge]:ge;if(xe.length>0)return xe;const Ie=String(e??"").trim();return o&&Ie?[{value:Ie,label:le||Ie}]:xe},[pe,ge,o,le,e]),Ne=_.useCallback(()=>{const xe=U.current;if(!xe)return;const Ie=xe.getBoundingClientRect(),qe=Math.max(Ie.width,m),zt=Math.max(8,Math.min(Ie.left,window.innerWidth-qe-8)),en=window.innerHeight-Ie.bottom,bn=Ie.top,Wt=en>=220||en>=bn?"bottom":"top";G(Wt);const It=Wt==="bottom"?Ie.bottom+6:Ie.top-6;Z({left:zt,top:It,width:qe})},[m]),Ue=_.useCallback(()=>{A(!1),$("")},[]);_.useEffect(()=>{var xe;P&&((xe=se.current)==null||xe.call(se))},[P]),_.useEffect(()=>{if(!P)return;Ne();const xe=()=>Ne();return window.addEventListener("resize",xe),window.addEventListener("scroll",xe,!0),()=>{window.removeEventListener("resize",xe),window.removeEventListener("scroll",xe,!0)}},[P,Ne]),_.useEffect(()=>{if(!P)return;const xe=Ie=>{var zt,en;const qe=Ie.target;qe&&((zt=U.current)!=null&&zt.contains(qe)||(en=J.current)!=null&&en.contains(qe)||Ue())};return document.addEventListener("mousedown",xe,!0),()=>document.removeEventListener("mousedown",xe,!0)},[P,Ue]),_.useEffect(()=>{if(!P)return;const xe=Math.max(0,ye.findIndex(Ie=>Ie.value===e));O(xe===-1?0:xe),l&&setTimeout(()=>{var Ie;return(Ie=Y.current)==null?void 0:Ie.focus()},0)},[P,l,e,ye]);const We=xe=>{var qe;const Ie=ye.find(zt=>zt.value===xe);Ie!=null&&Ie.disabled||(T(xe),Ue(),(qe=U.current)==null||qe.focus())},pt=xe=>{var Ie,qe;if(xe.key==="Escape")return xe.preventDefault(),Ue(),(Ie=U.current)==null||Ie.focus(),!0;if(xe.key==="Tab")return Ue(),(qe=U.current)==null||qe.focus(),!1;if(xe.key==="ArrowDown")return xe.preventDefault(),O(zt=>Math.min(zt+1,Math.max(0,ye.length-1))),!0;if(xe.key==="ArrowUp")return xe.preventDefault(),O(zt=>Math.max(zt-1,0)),!0;if(xe.key==="Home")return xe.preventDefault(),O(0),!0;if(xe.key==="End")return xe.preventDefault(),O(Math.max(0,ye.length-1)),!0;if(xe.key==="Enter"){xe.preventDefault();const zt=ye[te];return zt&&We(zt.value),!0}return!1},Fe=xe=>{if(!s){if(P){if(pt(xe))return;if(xe.key===" "&&!l){xe.preventDefault();const Ie=ye[te];Ie&&We(Ie.value)}return}(xe.key==="Enter"||xe.key===" "||xe.key==="ArrowDown"||xe.key==="ArrowUp")&&(xe.preventDefault(),A(!0))}},tt=!!String(e||"").trim(),lt=tt?le:n,Ke=pe!=null&&pe.disabled?pe.reason||"Unavailable":"",Se=P&&ye.length>0?`${fe}-opt-${te}`:void 0,Re=r.jsx("span",{className:tu("af-select-value",!tt&&"af-select-value--placeholder"),children:o&&!tt?"Loading…":lt}),ht=K?K(Q,String(e||"")):Re;return r.jsxs("span",{className:tu("af-select",p==="pin"?"af-select--pin":"af-select--panel",g),children:[r.jsxs("button",{ref:U,id:fe,type:"button",className:tu("af-select-trigger",f&&tt&&"af-select-trigger--clearable",w),disabled:s,onMouseDown:xe=>xe.stopPropagation(),onClick:xe=>{xe.stopPropagation(),!s&&A(Ie=>!Ie)},onKeyDown:Fe,role:l?void 0:"combobox","aria-haspopup":"listbox","aria-expanded":P,"aria-controls":P?W:void 0,"aria-activedescendant":l?void 0:Se,"aria-label":x,children:[ht,r.jsx("span",{className:tu("af-select-caret",P&&"af-select-caret--open"),children:"▾"})]}),f&&tt?r.jsx("button",{type:"button",className:"af-select-clear-btn","aria-label":"Clear selection",disabled:s,onMouseDown:xe=>{xe.preventDefault(),xe.stopPropagation()},onClick:xe=>{var Ie;xe.preventDefault(),xe.stopPropagation(),T(""),Ue(),(Ie=U.current)==null||Ie.focus()},title:"Clear",children:"×"}):null,P?Nv.createPortal(r.jsxs("div",{ref:J,className:tu("af-select-popover",F==="top"&&"af-select-popover--top"),style:{position:"fixed",left:`${R.left}px`,top:`${R.top}px`,width:`${R.width}px`},onMouseDown:xe=>xe.stopPropagation(),onClick:xe=>xe.stopPropagation(),onWheel:xe=>xe.stopPropagation(),onKeyDown:pt,tabIndex:-1,children:[l?r.jsxs("div",{className:"af-select-search",children:[r.jsx("input",{ref:Y,className:"af-select-search-input",value:z,onChange:xe=>$(xe.target.value),placeholder:u,onKeyDown:pt,role:"combobox","aria-expanded":!0,"aria-controls":W,"aria-activedescendant":Se,"aria-invalid":!!Ke,"aria-describedby":Ke?`${fe}-custom-error`:void 0}),Ke?r.jsx("div",{id:`${fe}-custom-error`,className:"af-select-custom-error",role:"alert",children:Ke}):null]}):null,r.jsx("div",{className:"af-select-options",role:"listbox",id:W,"aria-label":x,children:o&&ye.length===0?r.jsx("div",{className:"af-select-empty",children:"Loading…"}):ye.length===0?r.jsx("div",{className:"af-select-empty",children:"No results"}):ye.map((xe,Ie)=>{var It;const qe=xe.value===e,zt=Ie===te,en=String(xe.group||"").trim(),bn=Ie>0?String(((It=ye[Ie-1])==null?void 0:It.group)||"").trim():"",Wt=!!en&&en!==bn;return r.jsxs(ve.Fragment,{children:[Wt?r.jsx("div",{className:"af-select-group",role:"presentation",children:en}):null,r.jsx("div",{id:`${fe}-opt-${Ie}`,role:"option","aria-selected":qe,className:tu("af-select-option",qe&&"af-select-option--selected",zt&&"af-select-option--highlighted",xe.disabled&&"af-select-option--disabled"),title:xe.disabled?xe.reason||"Unavailable":void 0,onMouseEnter:()=>O(Ie),onMouseDown:kn=>{kn.preventDefault(),kn.stopPropagation()},onClick:()=>We(xe.value),"aria-disabled":xe.disabled?!0:void 0,children:I?I(xe,{selected:qe,highlighted:zt}):r.jsxs(r.Fragment,{children:[r.jsxs("span",{className:"af-select-option-label",children:[r.jsx("span",{children:xe.label}),xe.reason?r.jsx("small",{className:"af-select-option-reason",children:xe.reason}):null]}),qe?r.jsx("span",{className:"af-select-check",children:"✓"}):null]})})]},xe.value)})})]}),document.body):null]})}function lj(e){const t=new Set,n=[];for(const s of e||[]){if(!s||typeof s!="object")continue;const o=String(s.name||"").trim();!o||t.has(o)||(t.add(o),n.push({name:o,display_name:typeof s.display_name=="string"?s.display_name:void 0}))}return n.sort((s,o)=>s.name.localeCompare(o.name)),n}function cj(e){const t=new Set,n=[];for(const s of e||[]){const o=String(s||"").trim();!o||t.has(o)||(t.add(o),n.push(o))}return n.sort(),n}function uj(e){const t=e.disabled===!0,n=e.layout||"stack",s=e.allowGatewayDefault!==!1,o=String(e.gatewayDefaultLabel||"(gateway default)"),l=String(e.providerLabel||"Provider"),u=String(e.modelLabel||"Model"),c=String(e.providerPlaceholder||"(select)"),f=String(e.modelPlaceholder||"(select)"),m=String(e.provider||"").trim(),p=String(e.model||"").trim(),g=lj(e.providers),w=cj(e.models),x=t||!!e.loadingProviders,S=t||!!e.loadingModels,j=[...s?[{value:"",label:o}]:[],...g.map(C=>({value:C.name,label:C.display_name?`${C.display_name} (${C.name})`:C.name}))],N=[...s?[{value:"",label:o}]:[],...w.map(C=>({value:C,label:C}))];return r.jsxs("div",{className:e.className,style:n==="row"?{display:"flex",gap:"10px",flexWrap:"wrap",alignItems:"flex-start"}:{display:"flex",flexDirection:"column",gap:"10px"},children:[r.jsxs("div",{style:n==="row"?{flex:"1 1 260px",minWidth:240}:void 0,children:[r.jsx("label",{children:l}),r.jsx(xu,{value:m,options:j,placeholder:s?o:c,disabled:x,loading:!!e.loadingProviders,searchable:!0,allowCustom:e.allowCustomProvider===!0,clearable:s,variant:"panel",triggerClassName:e.selectClassName,ariaLabel:l,onChange:C=>e.onChange({provider:String(C||"").trim(),model:""})}),e.loadingProviders?r.jsx("div",{className:"mono muted",style:{fontSize:"12px",marginTop:"6px"},children:"Loading providers…"}):null,e.providerError?r.jsx("div",{className:"mono",style:{color:"var(--error)",fontSize:"12px",marginTop:"6px"},children:e.providerError}):null]}),r.jsxs("div",{style:n==="row"?{flex:"1 1 260px",minWidth:240}:void 0,children:[r.jsx("label",{children:u}),r.jsx(xu,{value:p,options:N,placeholder:s?o:f,disabled:S,loading:!!e.loadingModels,searchable:!0,allowCustom:e.allowCustomModel===!0,clearable:s,variant:"panel",triggerClassName:e.selectClassName,ariaLabel:u,onChange:C=>e.onChange({provider:m,model:String(C||"").trim()})}),e.loadingModels?r.jsx("div",{className:"mono muted",style:{fontSize:"12px",marginTop:"6px"},children:"Loading models…"}):null,e.modelError?r.jsx("div",{className:"mono",style:{color:"var(--error)",fontSize:"12px",marginTop:"6px"},children:e.modelError}):null]})]})}function fy(...e){return e.filter(Boolean).join(" ")}function dj({kicker:e="AbstractGateway connection",title:t="Connect to AbstractGateway",description:n="Sign in with the Gateway user token assigned by the Gateway admin.",statusLabel:s="Not signed in",statusTone:o="neutral",showGatewayUrl:l=!1,gatewayUrl:u="",gatewayUrlPlaceholder:c="http://127.0.0.1:8080",onGatewayUrlChange:f,userId:m,userPlaceholder:p="admin",onUserIdChange:g,token:w,tokenPlaceholder:x="Paste Gateway user token",showToken:S=!1,onTokenChange:j,onShowTokenChange:N,remember:C=!1,rememberLabel:E="Remember this browser",onRememberChange:T,loading:I=!1,submitting:K=!1,submitDisabled:U=!1,submitLabel:J="Sign in",submittingLabel:Y="Signing in...",closeLabel:se="Close",signOutLabel:ce="Sign out",showClose:fe=!1,showSignOut:W=!1,error:P,message:A,className:z,onSubmit:$,onClose:te,onSignOut:O}){const F=I||K,G=F||U||!String(m||"").trim()||!String(w||"").trim(),R=Z=>{Z.preventDefault(),!G&&$()};return r.jsxs("form",{className:fy("af-gateway-signin",z),onSubmit:R,children:[r.jsxs("div",{className:"af-gateway-signin__hero",children:[r.jsxs("div",{children:[r.jsx("div",{className:"af-gateway-signin__kicker",children:e}),r.jsx("h2",{children:t}),n?r.jsx("p",{children:n}):null]}),r.jsx("div",{className:"af-gateway-signin__mark","aria-hidden":"true",children:"↔"})]}),r.jsx("div",{className:"af-gateway-signin__status-row",children:r.jsx("span",{className:fy("af-gateway-signin__status",`af-gateway-signin__status--${o}`),children:s})}),r.jsxs("div",{className:"af-gateway-signin__form",children:[l?r.jsxs(r.Fragment,{children:[r.jsx("label",{className:"af-gateway-signin__label",htmlFor:"gateway-session-url",children:"Gateway URL"}),r.jsx("input",{id:"gateway-session-url",value:u,onChange:Z=>f==null?void 0:f(Z.target.value),placeholder:c,autoComplete:"url",disabled:F})]}):null,r.jsx("label",{className:"af-gateway-signin__label",htmlFor:"gateway-session-user",children:"Gateway user"}),r.jsx("input",{id:"gateway-session-user",value:m,onChange:Z=>g(Z.target.value),placeholder:p,autoComplete:"username",disabled:F}),r.jsx("label",{className:"af-gateway-signin__label",htmlFor:"gateway-session-token",children:"Gateway token"}),r.jsxs("div",{className:"af-gateway-signin__token-input",children:[r.jsx("input",{id:"gateway-session-token",type:S?"text":"password",value:w,onChange:Z=>j(Z.target.value),placeholder:x,autoComplete:"off","data-1p-ignore":"","data-lpignore":"true","data-bwignore":"",spellCheck:!1,disabled:F}),r.jsx("button",{className:"af-gateway-signin__secondary",type:"button",onClick:()=>N==null?void 0:N(!S),disabled:F,children:S?"Hide":"Show"})]}),r.jsxs("label",{className:"af-gateway-signin__checkbox",children:[r.jsx("input",{type:"checkbox",checked:!!C,onChange:Z=>T==null?void 0:T(Z.target.checked),disabled:F}),E]})]}),P?r.jsx("div",{className:"af-gateway-signin__message af-gateway-signin__message--error",children:P}):null,!P&&A?r.jsx("div",{className:"af-gateway-signin__message af-gateway-signin__message--ok",children:A}):null,r.jsxs("div",{className:"af-gateway-signin__actions",children:[fe?r.jsx("button",{className:"af-gateway-signin__secondary",type:"button",onClick:te,disabled:F,children:se}):null,W?r.jsx("button",{className:"af-gateway-signin__secondary",type:"button",onClick:()=>void(O==null?void 0:O()),disabled:F,children:ce}):null,r.jsx("button",{className:"af-gateway-signin__primary",type:"submit",disabled:G,children:K?Y:J})]})]})}function fj(e){return e==="light"?"Light":"Dark"}function hj(e){const t=e.themes&&e.themes.length?e.themes:kv,n=e.showSwatches!==!1,s=e.variant||"panel",o=_.useMemo(()=>{const u={};for(const c of t)u[c.id]=c;return u},[t]),l=_.useMemo(()=>t.map(u=>({value:u.id,label:u.label,group:fj(u.group)})),[t]);return r.jsx(xu,{value:e.value,options:l,placeholder:e.placeholder||"Select theme…",disabled:e.disabled===!0,searchable:!0,allowCustom:!1,clearable:!1,variant:s,className:e.className,triggerClassName:e.triggerClassName,onChange:u=>e.onChange(String(u||"").trim()),renderValue:(u,c)=>{const f=String(c||"").trim(),m=o[f],p=(m==null?void 0:m.label)||f||e.placeholder||"Select theme…",g=(m==null?void 0:m.swatches)||null,w=!f;return r.jsxs("span",{className:"af-theme-value",children:[r.jsx("span",{className:`af-theme-label ${w?"af-theme-label--placeholder":""}`.trim(),children:p}),n&&g?r.jsx("span",{className:"af-theme-swatches","aria-hidden":"true",children:g.map((x,S)=>r.jsx("span",{className:"af-theme-swatch",style:{background:x}},`${f}:${S}`))}):null]})},renderOption:(u,c)=>{const f=String(u.value||"").trim(),m=o[f],p=(m==null?void 0:m.swatches)||null;return r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"af-theme-option-label",children:u.label}),r.jsxs("span",{className:"af-theme-option-right",children:[n&&p?r.jsx("span",{className:"af-theme-swatches","aria-hidden":"true",children:p.map((g,w)=>r.jsx("span",{className:"af-theme-swatch",style:{background:g}},`${f}:${w}`))}):null,c.selected?r.jsx("span",{className:"af-select-check",children:"✓"}):null]})]})}})}function mj(e){const t=e.scales&&e.scales.length?e.scales:cp,n=e.variant||"panel",s=_.useMemo(()=>t.map(o=>({value:o.id,label:o.label})),[t]);return r.jsx(xu,{value:e.value,options:s,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 _j(e){const t=e.densities&&e.densities.length?e.densities:up,n=e.variant||"panel",s=_.useMemo(()=>t.map(o=>({value:o.id,label:o.label})),[t]);return r.jsx(xu,{value:e.value,options:s,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 pj=new Set(["board","inbox","server","agent","playCircle","list","gear"]);function gj(e){switch(e){case"chat":return r.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H8l-5 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"});case"plus":return r.jsxs(r.Fragment,{children:[r.jsx("path",{d:"M12 5v14"}),r.jsx("path",{d:"M5 12h14"})]});case"history":return r.jsxs(r.Fragment,{children:[r.jsx("circle",{cx:"12",cy:"12",r:"9"}),r.jsx("path",{d:"M12 7v5l3 3"})]});case"refresh":return r.jsxs(r.Fragment,{children:[r.jsx("path",{d:"M21 12a9 9 0 0 0-15.5-6.4L3 8"}),r.jsx("path",{d:"M3 3v5h5"}),r.jsx("path",{d:"M3 12a9 9 0 0 0 15.5 6.4L21 16"}),r.jsx("path",{d:"M21 21v-5h-5"})]});case"settings":return r.jsxs(r.Fragment,{children:[r.jsx("path",{d:"M4 6h16"}),r.jsx("circle",{cx:"8",cy:"6",r:"2"}),r.jsx("path",{d:"M4 12h16"}),r.jsx("circle",{cx:"16",cy:"12",r:"2"}),r.jsx("path",{d:"M4 18h16"}),r.jsx("circle",{cx:"10",cy:"18",r:"2"})]});case"user":return r.jsxs(r.Fragment,{children:[r.jsx("circle",{cx:"12",cy:"8",r:"4"}),r.jsx("path",{d:"M4 21a8 8 0 0 1 16 0"})]});case"bot":return r.jsxs(r.Fragment,{children:[r.jsx("path",{d:"M12 2v3"}),r.jsx("rect",{x:"5",y:"6",width:"14",height:"14",rx:"3"}),r.jsx("circle",{cx:"9",cy:"13",r:"1",fill:"currentColor",stroke:"none"}),r.jsx("circle",{cx:"15",cy:"13",r:"1",fill:"currentColor",stroke:"none"}),r.jsx("path",{d:"M9 17h6"})]});case"paperclip":return r.jsx("path",{d:"M21.44 11.05l-9.19 9.19a5.5 5.5 0 0 1-7.78-7.78l9.19-9.19a3.5 3.5 0 0 1 4.95 4.95l-9.2 9.19a1.5 1.5 0 0 1-2.12-2.12l8.49-8.48"});case"mic":return r.jsxs(r.Fragment,{children:[r.jsx("path",{d:"M12 14a3 3 0 0 0 3-3V5a3 3 0 0 0-6 0v6a3 3 0 0 0 3 3z"}),r.jsx("path",{d:"M19 11a7 7 0 0 1-14 0"}),r.jsx("path",{d:"M12 18v4"}),r.jsx("path",{d:"M8 22h8"})]});case"speaker":return r.jsxs(r.Fragment,{children:[r.jsx("path",{d:"M11 5L6 9H2v6h4l5 4V5z"}),r.jsx("path",{d:"M15.5 8.5a5 5 0 0 1 0 7"}),r.jsx("path",{d:"M18 6a9 9 0 0 1 0 12"})]});case"pause":return r.jsxs(r.Fragment,{children:[r.jsx("rect",{x:"6",y:"4",width:"4",height:"16",rx:"1",fill:"currentColor",stroke:"none"}),r.jsx("rect",{x:"14",y:"4",width:"4",height:"16",rx:"1",fill:"currentColor",stroke:"none"})]});case"terminal":return r.jsxs(r.Fragment,{children:[r.jsx("rect",{x:"3",y:"4",width:"18",height:"16",rx:"2",ry:"2"}),r.jsx("path",{d:"M7 9l3 3-3 3"}),r.jsx("path",{d:"M12 15h5"})]});case"edit":return r.jsxs(r.Fragment,{children:[r.jsx("path",{d:"M12 20h9"}),r.jsx("path",{d:"M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4 12.5-12.5z"})]});case"download":return r.jsxs(r.Fragment,{children:[r.jsx("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),r.jsx("path",{d:"M7 10l5 5 5-5"}),r.jsx("path",{d:"M12 15V3"})]});case"loader":return r.jsx("path",{d:"M21 12a9 9 0 1 1-3.3-6.9"});case"info":return r.jsxs(r.Fragment,{children:[r.jsx("circle",{cx:"12",cy:"12",r:"10"}),r.jsx("path",{d:"M12 16v-4"}),r.jsx("circle",{cx:"12",cy:"8",r:"0.75",fill:"currentColor",stroke:"none"})]});case"warning":return r.jsxs(r.Fragment,{children:[r.jsx("path",{d:"M12 3l10 18H2L12 3z"}),r.jsx("path",{d:"M12 9v4"}),r.jsx("circle",{cx:"12",cy:"17",r:"0.75",fill:"currentColor",stroke:"none"})]});case"error":return r.jsxs(r.Fragment,{children:[r.jsx("circle",{cx:"12",cy:"12",r:"10"}),r.jsx("path",{d:"M15 9l-6 6"}),r.jsx("path",{d:"M9 9l6 6"})]});case"copy":return r.jsxs(r.Fragment,{children:[r.jsx("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2"}),r.jsx("path",{d:"M5 15V5a2 2 0 0 1 2-2h10"})]});case"check":return r.jsx("path",{d:"M20 6L9 17l-5-5"});case"x":return r.jsxs(r.Fragment,{children:[r.jsx("path",{d:"M18 6L6 18"}),r.jsx("path",{d:"M6 6l12 12"})]});case"chevronDown":return r.jsx("path",{d:"M6 9l6 6 6-6"});case"chevronRight":return r.jsx("path",{d:"M9 18l6-6-6-6"});case"trash":return r.jsxs(r.Fragment,{children:[r.jsx("path",{d:"M3 6h18"}),r.jsx("path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"}),r.jsx("path",{d:"M6 6l1 16h10l1-16"}),r.jsx("path",{d:"M10 11v6"}),r.jsx("path",{d:"M14 11v6"})]});case"send":return r.jsxs(r.Fragment,{children:[r.jsx("path",{d:"M22 2L11 13"}),r.jsx("path",{d:"M22 2L15 22l-4-9-9-4 20-7z"})]});case"thumbsUp":return r.jsxs(r.Fragment,{children:[r.jsx("path",{d:"M7 10v11"}),r.jsx("path",{d:"M7 10l4.5-8a2 2 0 0 1 3.6 1.5L14 8h5.2a2 2 0 0 1 2 2.4l-1.6 8a2 2 0 0 1-2 1.6H7"})]});case"thumbsDown":return r.jsxs(r.Fragment,{children:[r.jsx("path",{d:"M17 14V3"}),r.jsx("path",{d:"M17 14l-4.5 8a2 2 0 0 1-3.6-1.5L10 16H4.8a2 2 0 0 1-2-2.4l1.6-8a2 2 0 0 1 2-1.6H17"})]});case"thumbsUpFilled":return r.jsxs(r.Fragment,{children:[r.jsx("path",{d:"M7 10v11"}),r.jsx("path",{d:"M7 10l4.5-8a2 2 0 0 1 3.6 1.5L14 8h5.2a2 2 0 0 1 2 2.4l-1.6 8a2 2 0 0 1-2 1.6H7z",fill:"currentColor",stroke:"none"})]});case"thumbsDownFilled":return r.jsxs(r.Fragment,{children:[r.jsx("path",{d:"M17 14V3"}),r.jsx("path",{d:"M17 14l-4.5 8a2 2 0 0 1-3.6-1.5L10 16H4.8a2 2 0 0 1-2-2.4l1.6-8a2 2 0 0 1 2-1.6H17z",fill:"currentColor",stroke:"none"})]});case"board":return r.jsxs(r.Fragment,{children:[r.jsx("rect",{x:"1.5",y:"2",width:"3.6",height:"12",rx:"1"}),r.jsx("rect",{x:"6.2",y:"2",width:"3.6",height:"8.5",rx:"1"}),r.jsx("rect",{x:"10.9",y:"2",width:"3.6",height:"5.5",rx:"1"})]});case"inbox":return r.jsxs(r.Fragment,{children:[r.jsx("path",{d:"M2 9.5 L4 3.5 h8 l2 6"}),r.jsx("path",{d:"M2 9.5 v3 h12 v-3"}),r.jsx("path",{d:"M2 9.5 h3.4 l1 1.6 h3.2 l1-1.6 H14"})]});case"server":return r.jsxs(r.Fragment,{children:[r.jsx("rect",{x:"2",y:"2.5",width:"12",height:"4.6",rx:"1.2"}),r.jsx("rect",{x:"2",y:"8.9",width:"12",height:"4.6",rx:"1.2"}),r.jsx("circle",{cx:"4.6",cy:"4.8",r:"0.8",fill:"currentColor",stroke:"none"}),r.jsx("circle",{cx:"4.6",cy:"11.2",r:"0.8",fill:"currentColor",stroke:"none"})]});case"agent":return r.jsxs(r.Fragment,{children:[r.jsx("rect",{x:"3",y:"4.5",width:"10",height:"8",rx:"2"}),r.jsx("path",{d:"M8 4.5V2.2"}),r.jsx("circle",{cx:"8",cy:"1.8",r:"0.9",fill:"currentColor",stroke:"none"}),r.jsx("circle",{cx:"5.8",cy:"8.4",r:"0.9",fill:"currentColor",stroke:"none"}),r.jsx("circle",{cx:"10.2",cy:"8.4",r:"0.9",fill:"currentColor",stroke:"none"})]});case"playCircle":return r.jsxs(r.Fragment,{children:[r.jsx("circle",{cx:"8",cy:"8",r:"6.2"}),r.jsx("path",{d:"M6.5 5.6 L11 8 L6.5 10.4 Z",fill:"currentColor",stroke:"none"})]});case"list":return r.jsxs(r.Fragment,{children:[r.jsx("path",{d:"M2.5 4h11"}),r.jsx("path",{d:"M2.5 8h11"}),r.jsx("path",{d:"M2.5 12h7"})]});case"gear":return r.jsxs(r.Fragment,{children:[r.jsx("circle",{cx:"8",cy:"8",r:"2.2"}),r.jsx("path",{d:"M8 1.6v2"}),r.jsx("path",{d:"M8 12.4v2"}),r.jsx("path",{d:"M1.6 8h2"}),r.jsx("path",{d:"M12.4 8h2"}),r.jsx("path",{d:"M3.5 3.5l1.4 1.4"}),r.jsx("path",{d:"M11.1 11.1l1.4 1.4"}),r.jsx("path",{d:"M12.5 3.5l-1.4 1.4"}),r.jsx("path",{d:"M4.9 11.1l-1.4 1.4"})]});case"sparkle":return r.jsxs(r.Fragment,{children:[r.jsx("path",{d:"M12 3l1.9 5.1L19 10l-5.1 1.9L12 17l-1.9-5.1L5 10l5.1-1.9z"}),r.jsx("path",{d:"M18.5 15.5l.8 2.2 2.2.8-2.2.8-.8 2.2-.8-2.2-2.2-.8 2.2-.8z"})]});case"contrast":return r.jsxs(r.Fragment,{children:[r.jsx("circle",{cx:"12",cy:"12",r:"9"}),r.jsx("path",{d:"M12 3a9 9 0 0 1 0 18z",fill:"currentColor",stroke:"none"})]});case"logout":return r.jsxs(r.Fragment,{children:[r.jsx("path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"}),r.jsx("path",{d:"M16 17l5-5-5-5"}),r.jsx("path",{d:"M21 12H9"})]});case"play":return r.jsx("path",{d:"M7 4.5v15a1 1 0 0 0 1.5.86l12-7.5a1 1 0 0 0 0-1.72l-12-7.5A1 1 0 0 0 7 4.5z",fill:"currentColor",stroke:"none"});case"stop":return r.jsx("rect",{x:"5",y:"5",width:"14",height:"14",rx:"2",fill:"currentColor",stroke:"none"});case"folder":return r.jsx("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"});case"file":return r.jsxs(r.Fragment,{children:[r.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),r.jsx("path",{d:"M14 2v6h6"})]});case"archive":return r.jsxs(r.Fragment,{children:[r.jsx("rect",{x:"2",y:"3",width:"20",height:"5",rx:"1"}),r.jsx("path",{d:"M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8"}),r.jsx("path",{d:"M10 12h4"})]});case"clock":return r.jsxs(r.Fragment,{children:[r.jsx("circle",{cx:"12",cy:"12",r:"10"}),r.jsx("path",{d:"M12 6v6h4"})]});default:return null}}function et({name:e,size:t=16,className:n,title:s,...o}){const l=s?void 0:!0,u=pj.has(e);return r.jsxs("svg",{width:t,height:t,viewBox:u?"0 0 16 16":"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:u?1.4:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,"aria-hidden":l,role:s?"img":"presentation",...o,children:[s?r.jsx("title",{children:s}):null,gj(e)]})}const dp="api/gateway",Nf="api/connection/gateway";function wt(e){const t=String(e||"");if(t.startsWith("/"))throw new Error(`gatewayApiPath takes a route relative to the gateway API, got ${JSON.stringify(t)}.`);return t?`${dp}/${t}`:dp}function rg(e,t){const n=String(t||"");if(n.startsWith("/"))throw new Error(`joinBaseUrl takes a relative path, got ${JSON.stringify(n)}.`);let s=String(e??"");for(;s.endsWith("/");)s=s.slice(0,-1);return s?`${s}/${n}`:n}function yj(e){const t=String(e||""),n=`/${dp}/`;if(!t.startsWith(n)||t.length===n.length)throw new Error(`Not a gateway API path: ${JSON.stringify(t)} (expected ${JSON.stringify(n)}…).`);const s=t.slice(n.length).split(/[?#]/,1)[0];if(/\\|%2f|%5c/i.test(s))throw new Error(`Not a gateway API path: ${JSON.stringify(t)} (encoded slash or backslash).`);for(const o of s.split("/")){const l=o.replace(/%2e/gi,".");if(l==="."||l==="..")throw new Error(`Not a gateway API path: ${JSON.stringify(t)} (a "." or ".." segment).`)}return t.slice(1)}function wj(e){return!String(e.unavailableReason||"").trim()&&!e.busy}function vj(e){return wj(e)?!e.checked:null}let xj=0;function No(e){const{label:t,checked:n,onChange:s,description:o,reasonVisible:l=!0,describedBy:u,hint:c,busy:f=!1,variant:m="inline",ariaLabel:p,className:g,id:w,action:x}=e,S=String(e.unavailableReason||"").trim(),j=!!S,N=u||(w?`${w}-reason`:j?`af-switch-reason-${++xj}`:void 0),C=["af-switch",m==="row"?"af-switch--row":m==="sm"?"af-switch--sm":"",j?"af-switch--unavailable":"",g||""].filter(Boolean).join(" "),E=I=>{const K=vj({checked:n,unavailableReason:S,busy:f});if(K===null){I.preventDefault();return}s==null||s(K)},T=r.jsxs("button",{type:"button",role:"switch",id:w,className:C,"data-action":x,"aria-checked":n?"true":"false","aria-disabled":j?"true":void 0,"aria-describedby":j?N:void 0,"aria-busy":f?"true":void 0,"aria-label":p,"aria-description":o?void 0:c,title:j?c?`${S}
41
- ${c}`:S:c,onClick:E,children:[r.jsx("span",{className:"af-switch__track","aria-hidden":"true",children:r.jsx("span",{className:"af-switch__thumb"})}),r.jsxs("span",{className:"af-switch__text",children:[r.jsx("span",{className:"af-switch__label",children:t}),o?r.jsx("span",{className:"af-switch__desc",children:o}):null]})]});return!j||u?T:r.jsxs("span",{className:m==="row"?"af-switch-wrap af-switch-wrap--row":"af-switch-wrap",children:[T,r.jsx("span",{id:N,className:l?"af-switch__reason":"af-switch__reason af-switch__reason--hidden",children:S})]})}function bj(e){const t=String(e.unavailableReason||"").trim(),n=["af-switch","af-switch--native",e.variant==="row"?"af-switch--row":"",t?"af-switch--unavailable":""].filter(Boolean).join(" "),s=t?`${e.id||e.name}-reason`:void 0,o=r.jsxs("label",{className:n,title:t||void 0,"data-action":e.action,children:[r.jsx("input",{type:"checkbox",role:"switch",className:"af-switch__input",id:e.id,name:e.name,defaultChecked:e.defaultChecked,disabled:!!t,"aria-describedby":s}),r.jsx("span",{className:"af-switch__track","aria-hidden":"true",children:r.jsx("span",{className:"af-switch__thumb"})}),r.jsx("span",{className:"af-switch__text",children:r.jsx("span",{className:"af-switch__label",children:e.label})})]});return t?r.jsxs("span",{className:e.variant==="row"?"af-switch-wrap af-switch-wrap--row":"af-switch-wrap",children:[o,r.jsx("span",{id:s,className:"af-switch__reason",children:t})]}):o}async function fp(e=Nf){const t=await fetch(e),n=await t.json().catch(()=>null);if(!t.ok){const s=n&&typeof n=="object"&&n.detail?String(n.detail):`HTTP ${t.status}`;throw new Error(s)}return n}async function jj(e,t=Nf){const n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),s=await n.json().catch(()=>null);if(!n.ok){const o=s&&typeof s=="object"&&s.detail?String(s.detail):`HTTP ${n.status}`;throw new Error(o)}return s}async function Cv(e=Nf){const t=await fetch(e,{method:"DELETE"});if(!t.ok){const n=await t.json().catch(()=>({})),s=n&&typeof n=="object"&&n.detail?String(n.detail):`HTTP ${t.status}`;throw new Error(s)}}function y_(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 s=t[0],o=t[t.length-1];if(s==='"'&&o==='"'||s==="'"&&o==="'"){t=t.slice(1,-1).trim();continue}break}return t.replace(/\/+$/,"")}function Ev(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,s=(u=t.principal)==null?void 0:u.runtime_id;if(t.ok&&n)return{label:`Signed in as ${n}${s?` · runtime ${s}`:""}`,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 Sj(e){const t=e.connectionPath||Nf,[n,s]=_.useState(!1),[o,l]=_.useState(!1),[u,c]=_.useState(null),[f,m]=_.useState(!1);_.useEffect(()=>{e.isOpen||m(!1)},[e.isOpen]);const[p,g]=_.useState(e.defaultGatewayUrl||"http://127.0.0.1:8080"),[w,x]=_.useState("admin"),[S,j]=_.useState(""),[N,C]=_.useState(!1),[E,T]=_.useState(!0),[I,K]=_.useState(""),[U,J]=_.useState(""),Y=_.useMemo(()=>Ev(u),[u]),se=P=>{var A;c(P),(A=e.onStatusChange)==null||A.call(e,P)},ce=_.useRef(!1);if(_.useEffect(()=>{var A;if(!e.isOpen)return;const P=!ce.current;if(ce.current=!0,P&&e.initialStatus!==void 0&&e.initialStatus!==null){const z=e.initialStatus;se(z),typeof z.gateway_url=="string"&&z.gateway_url.trim()&&g(y_(z.gateway_url));const $=(A=z.gateway)==null?void 0:A.principal;$!=null&&$.user_id&&x($.user_id);return}s(!0),K(""),fp(t).then(z=>{var te;se(z),typeof z.gateway_url=="string"&&z.gateway_url.trim()&&g(y_(z.gateway_url));const $=(te=z.gateway)==null?void 0:te.principal;$!=null&&$.user_id&&x($.user_id)}).catch(z=>K(`Failed to load connection status: ${String((z==null?void 0:z.message)||z)}`)).finally(()=>s(!1))},[e.isOpen]),_.useEffect(()=>{if(!e.isOpen)return;const P=A=>{A.key==="Escape"&&!A.defaultPrevented&&!e.blocking&&(A.preventDefault(),e.onClose())};return window.addEventListener("keydown",P),()=>window.removeEventListener("keydown",P)},[e.isOpen,e.blocking,e.onClose]),!e.isOpen||f)return null;const fe=async()=>{l(!0),K(""),J("");try{const P=y_(p);g(P);const A=await jj({gateway_url:P,gateway_user_id:w,gateway_token:S,persist:E},t);se(A),j(""),m(!0),e.onClose()}catch(P){K(String((P==null?void 0:P.message)||P))}finally{l(!1)}},W=async()=>{l(!0),K(""),J("");try{await Cv(t),j("");const P=await fp(t).catch(()=>null);se(P),J("Signed out. This browser no longer holds a gateway session.")}catch(P){K(String((P==null?void 0:P.message)||P))}finally{l(!1)}};return r.jsx("div",{className:"af-connect-overlay",role:"presentation",onMouseDown:P=>{!e.blocking&&P.target===P.currentTarget&&e.onClose()},children:r.jsx("div",{className:"af-connect-modal",role:"dialog","aria-modal":"true","aria-label":"Gateway connection",children:r.jsx(dj,{kicker:`${e.appName||"AbstractFramework"} connection`,title:"Connect this browser to AbstractGateway",description:"Sign in with a Gateway user token. The app exchanges it for an HTTP-only browser session and never stores the raw token.",statusLabel:Y.label,statusTone:Y.tone,showGatewayUrl:!0,gatewayUrl:p,onGatewayUrlChange:P=>g(P),userId:w,onUserIdChange:x,token:S,tokenPlaceholder:u!=null&&u.has_session?"(browser session already signed in)":"Paste Gateway user token",showToken:N,onTokenChange:j,onShowTokenChange:C,remember:E,rememberLabel:"Keep this browser signed in",onRememberChange:T,loading:n,submitting:o,submittingLabel:"Signing in...",showClose:!e.blocking,onClose:e.onClose,showSignOut:!e.blocking&&!!(u!=null&&u.has_session),onSignOut:W,error:I,message:U,onSubmit:fe})})})}function kj(e){return!!(e&&e.ok===!0&&e.has_session===!0)}function Nj(e){const t=e||{},n=t.connectionPath||Nf,s=t.variant||"dismissable",o=_.useRef(t.onStatusChange);o.current=t.onStatusChange;const l=_.useRef(s);l.current=s;const u=_.useRef(!!t.autoOpenMidSession);u.current=!!t.autoOpenMidSession;const[c,f]=_.useState(null),[m,p]=_.useState("loading"),[g,w]=_.useState(!1),x=_.useRef(!1),S=_.useRef(!1),j=_.useRef("loading"),N=_.useRef("none"),C=_.useRef(!1),E=_.useRef(0),T=_.useCallback(A=>{var $;E.current+=1,f(A),($=o.current)==null||$.call(o,A);const z=kj(A);if(z)p("connected"),j.current="connected",x.current=!1,N.current="none",S.current||w(!1);else if(A!==null){const te=j.current;p("disconnected"),j.current="disconnected",te!=="disconnected"&&(N.current=C.current?"signout":te==="connected"?"mid":"boot");const O=l.current==="blocking"||N.current!=="mid"||u.current;!x.current&&O&&w(!0)}A!==null&&(S.current=z)},[]),I=_.useCallback(async()=>{const A=E.current;try{const z=await fp(n);if(E.current!==A)return;T(z)}catch{if(E.current!==A)return;T(null)}},[n,T]),[K,U]=_.useState(!1),[J,Y]=_.useState(null),se=_.useCallback(async()=>{U(!0),Y(null),E.current+=1;let A=null;try{await Cv(n)}catch(z){A=String((z==null?void 0:z.message)||z||"Sign-out request failed")}C.current=!0;try{await I()}finally{C.current=!1}Y(A),U(!1)},[n,I]),ce=_.useRef(!1);_.useEffect(()=>{ce.current||(ce.current=!0,I())},[I]);const fe=_.useCallback(()=>{w(!0)},[]),W=_.useCallback(()=>{const A=j.current;s==="blocking"&&A==="disconnected"||(A==="disconnected"&&(x.current=!0),w(!1))},[s]),P=_.useMemo(()=>({isOpen:g,onClose:W,blocking:s==="blocking"&&m!=="connected",appName:t.appName,connectionPath:n,defaultGatewayUrl:t.defaultGatewayUrl,initialStatus:c,onStatusChange:T}),[g,W,s,m,t.appName,n,t.defaultGatewayUrl,c,T]);return{status:c,phase:m,connected:m==="connected",modalOpen:g,signingOut:K,signOutError:J,openModal:fe,refresh:I,signOut:se,modalProps:P}}function Cj(){return globalThis.crypto}function Ej(e){if(e.length<16)throw new Error("uuidV4FromBytes: needs 16 bytes");const t=Array.from(e.subarray(0,16));t[6]=t[6]&15|64,t[8]=t[8]&63|128;const n=t.map(s=>s.toString(16).padStart(2,"0")).join("");return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}function Sm(){const e=Cj();if(e&&typeof e.randomUUID=="function")try{return e.randomUUID()}catch{}if(e&&typeof e.getRandomValues=="function")return Ej(e.getRandomValues(new Uint8Array(16)));throw new Error("randomId: Web Crypto (crypto.getRandomValues) is unavailable")}function $j(e){return globalThis.isSecureContext!==!1?null:`This page is loaded over http, so ${e} is unavailable — open it over https (for example through tailscale serve; the gateway console's Network page explains how) or on the gateway's own computer.`}function Aj(){return Sm()}function Tj(){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 Mj(e){const t=e.commandsPath||wt("commands"),n=Aj(),s=JSON.stringify({command_id:n,run_id:e.runId,type:"inject_guidance",payload:{guidance:e.guidance}}),o=e.csrfToken!==void 0?[e.csrfToken]:Tj();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:s}),f=await c.json().catch(()=>null);if(!c.ok){const m=f&&typeof f=="object"&&f.detail?String(f.detail):`HTTP ${c.status}`;if(l=new Error(m),c.status===403&&f&&typeof f=="object"&&f.reason_code==="csrf_required")continue;throw l}return{accepted:!!(f!=null&&f.accepted),duplicate:!!(f!=null&&f.duplicate),seq:Number((f==null?void 0:f.seq)??0)}}throw l||new Error("Steer submit failed")}function Rj(e){const[t,n]=_.useState(""),[s,o]=_.useState({kind:"idle"}),l=_.useRef(!1),u=_.useRef(0);_.useEffect(()=>{u.current+=1,o({kind:"idle"})},[e.runId]);const c=!e.disabled&&t.trim().length>0&&s.kind!=="sending",f=_.useMemo(()=>e.parked?"Run is waiting — your guidance delivers at its next wake (steers do not wake runs).":"Delivers at the run's next loop boundary.",[e.parked]),m=async()=>{var x;const g=t.trim();if(!g||l.current||e.disabled)return;l.current=!0;const w=u.current;o({kind:"sending"});try{const S=e.submit?await e.submit(e.runId,g):await Mj({runId:e.runId,guidance:g,commandsPath:e.commandsPath});if(u.current!==w)return;if(!S.accepted&&!S.duplicate){o({kind:"error",detail:"The gateway did not accept this steer (accepted=false)."});return}o({kind:"queued",seq:S.seq,duplicate:S.duplicate}),n(""),(x=e.onSent)==null||x.call(e,{...S,guidance:g})}catch(S){u.current===w&&o({kind:"error",detail:String((S==null?void 0:S.message)||S)})}finally{l.current=!1}},p=g=>{g.key==="Enter"&&(g.metaKey||g.ctrlKey)&&(g.preventDefault(),m())};return r.jsxs("div",{className:`af-steer${e.className?` ${e.className}`:""}`,children:[r.jsxs("div",{className:"af-steer__row",children:[r.jsx("textarea",{className:"af-steer__input",value:t,rows:2,placeholder:e.placeholder||"Steer this run…","aria-label":e.ariaLabel||"Steer message",disabled:e.disabled||s.kind==="sending",onChange:g=>{n(g.target.value),(s.kind==="error"||s.kind==="queued")&&o({kind:"idle"})},onKeyDown:p}),r.jsx("button",{type:"button",className:"af-steer__send",disabled:!c,onClick:()=>void m(),title:"Send guidance (Cmd/Ctrl+Enter)",children:s.kind==="sending"?"Sending…":"Steer"})]}),r.jsx("div",{className:"af-steer__status",role:"status","aria-live":"polite",children:s.kind==="queued"?r.jsxs("span",{className:"af-steer__ok",children:[s.duplicate?`Already queued (seq ${s.seq}).`:`Queued (seq ${s.seq}).`," ",f," ","Watch for the steer_seen ack in the run ledger."]}):s.kind==="error"?r.jsx("span",{className:"af-steer__err",children:s.detail}):r.jsx("span",{className:"af-steer__hint",children:f})})]})}function Lj(e){const t=e.closeOnEscape!==!1,n=_.useRef(null);return _.useEffect(()=>{if(!e.open||!t)return;const s=o=>{o.key!=="Escape"||o.defaultPrevented||(o.preventDefault(),e.onClose())};return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[e.open,t,e.onClose]),_.useEffect(()=>{const s=n.current;s&&(e.open?s.removeAttribute("inert"):s.setAttribute("inert",""))},[e.open]),r.jsxs(r.Fragment,{children:[e.backdrop&&e.open?r.jsx("div",{className:"af-drawer-backdrop","aria-hidden":"true",onClick:e.onClose,style:{top:e.topOffset||0}}):null,r.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?r.jsxs("div",{className:"af-drawer__header",children:[r.jsx("div",{className:"af-drawer__title",children:e.title}),r.jsxs("div",{className:"af-drawer__header-actions",children:[e.headerActions,r.jsx("button",{type:"button",className:"af-drawer__close","aria-label":"Close panel",onClick:e.onClose,children:"×"})]})]}):null,r.jsx("div",{className:"af-drawer__body",children:e.children})]})]})}const Ij={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"},Pj={abstractframework:{name:"AbstractFramework",website:"https://abstractframework.ai",repo:"https://github.com/lpalbou/AbstractFramework",docs:"https://github.com/lpalbou/AbstractFramework/tree/main/docs",issues:"https://github.com/lpalbou/AbstractFramework/issues",feedback:"https://github.com/lpalbou/AbstractFramework/issues/new?labels=feedback"},abstractgateway:{name:"AbstractGateway",website:"https://abstractframework.ai/gateway",repo:"https://github.com/lpalbou/AbstractGateway",docs:"https://www.lpalbou.info/AbstractGateway/",issues:"https://github.com/lpalbou/AbstractGateway/issues",feedback:"https://github.com/lpalbou/AbstractGateway/issues/new?labels=feedback"},abstractcode:{name:"AbstractCode",website:"https://abstractframework.ai/code",repo:"https://github.com/lpalbou/AbstractCode",docs:"https://github.com/lpalbou/AbstractCode/tree/main/docs",issues:"https://github.com/lpalbou/AbstractCode/issues",feedback:"https://github.com/lpalbou/AbstractCode/issues/new?labels=feedback"},abstractassistant:{name:"AbstractAssistant",website:"https://abstractframework.ai/assistant",repo:"https://github.com/lpalbou/AbstractAssistant",docs:"https://github.com/lpalbou/AbstractAssistant/blob/main/docs/README.md",issues:"https://github.com/lpalbou/AbstractAssistant/issues",feedback:"https://github.com/lpalbou/AbstractAssistant/issues/new?labels=feedback"},abstractflow:{name:"AbstractFlow",website:"https://abstractframework.ai/flow",repo:"https://github.com/lpalbou/AbstractFlow",docs:"https://github.com/lpalbou/AbstractFlow#readme",issues:"https://github.com/lpalbou/AbstractFlow/issues",feedback:"https://github.com/lpalbou/AbstractFlow/issues/new?labels=feedback"},abstractcontinuum:{name:"AbstractContinuum",website:"https://abstractframework.ai",repo:"https://github.com/lpalbou/AbstractContinuum",docs:"https://github.com/lpalbou/AbstractContinuum/tree/main/docs",issues:"https://github.com/lpalbou/AbstractContinuum/issues",feedback:"https://github.com/lpalbou/AbstractContinuum/issues/new?labels=feedback"},abstractentity:{name:"AbstractEntity",website:"https://abstractframework.ai",repo:"https://github.com/lpalbou/AbstractEntity",docs:"https://github.com/lpalbou/AbstractEntity/tree/main/docs",issues:"https://github.com/lpalbou/AbstractEntity/issues",feedback:"https://github.com/lpalbou/AbstractEntity/issues/new?labels=feedback"},abstractobserver:{name:"AbstractObserver",website:"https://abstractframework.ai/observer",repo:"https://github.com/lpalbou/AbstractObserver",docs:"https://github.com/lpalbou/AbstractObserver#readme",issues:"https://github.com/lpalbou/AbstractObserver/issues",feedback:"https://github.com/lpalbou/AbstractObserver/issues/new?labels=feedback"},abstractcore:{name:"AbstractCore",website:"https://www.abstractcore.ai",repo:"https://github.com/lpalbou/AbstractCore",docs:"https://github.com/lpalbou/AbstractCore/tree/main/docs",issues:"https://github.com/lpalbou/AbstractCore/issues",feedback:"https://github.com/lpalbou/AbstractCore/issues/new?labels=feedback"},abstractuic:{name:"AbstractUIC",website:"https://abstractframework.ai",repo:"https://github.com/lpalbou/AbstractUIC",docs:"https://github.com/lpalbou/AbstractUIC/tree/main/docs",issues:"https://github.com/lpalbou/AbstractUIC/issues",feedback:"https://github.com/lpalbou/AbstractUIC/issues/new?labels=feedback"}},Oj={framework:Ij,apps:Pj},rm=Oj;function Dj(){return Object.keys(rm.apps).sort()}function Fj(e,t){const n=Object.prototype.hasOwnProperty.call(rm.apps,e)?rm.apps[e]:void 0;if(!n)throw new Error(`appIdentity: unknown application id "${e}" (known: ${Dj().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 zj(e,t){const n=rm.framework,s=[["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||[])s.push([String(o),String(l)]);return s}function w_(e){return typeof e=="string"?e.trim():""}function hy(e,t){if(t!=null)return[["Gateway",`unavailable (${String(t).trim()||"unknown error"})`]];const n=e&&typeof e=="object"&&!Array.isArray(e)?e:{},s=w_(n.abstractgateway);if(!s)return[["Gateway","unavailable (the gateway did not report its version)"]];const o=w_(n.abstractframework),l=[["Gateway",`AbstractGateway ${s}`],["Gateway framework",o?`AbstractFramework ${o}`:"not installed on the gateway host"]],u=n.packages&&typeof n.packages=="object"&&!Array.isArray(n.packages)?n.packages:{},c=Object.keys(u).filter(f=>f!=="abstractgateway"&&f!=="abstractframework").sort((f,m)=>f<m?-1:f>m?1:0);for(const f of c){const m=w_(u[f]);m&&l.push([`Gateway package ${f}`,m])}return l}const Bj='a[href], button:not(:disabled), input:not(:disabled), select:not(:disabled), textarea:not(:disabled), [tabindex]:not([tabindex="-1"])';function Uj(e,t,n){if(e.key!=="Tab"||!t)return;const s=Array.from(t.querySelectorAll(Bj));if(s.length===0){e.preventDefault();return}const o=s[0],l=s[s.length-1],u=!!n&&t.contains(n);e.shiftKey?(n===o||!u)&&(e.preventDefault(),l.focus()):(n===l||!u)&&(e.preventDefault(),o.focus())}const Wj=/https?:\/\/[^\s<>"]+/g;function qj(e,t){if(e==="Contact")return[{text:t,href:`mailto:${t}`}];const n=[];let s=0;for(const o of t.matchAll(Wj)){const l=o.index??0;l>s&&n.push({text:t.slice(s,l)}),n.push({text:o[0],href:o[0]}),s=l+o[0].length}return(s<t.length||n.length===0)&&n.push({text:t.slice(s)}),n}function Hj({label:e,value:t}){return r.jsx("span",{children:qj(e,t).map((n,s)=>n.href===void 0?r.jsx(ve.Fragment,{children:n.text},s):n.href.startsWith("mailto:")?r.jsx("a",{className:"af-about__link",href:n.href,children:n.text},s):r.jsx("a",{className:"af-about__link",href:n.href,target:"_blank",rel:"noopener noreferrer",children:n.text},s))})}function Vj(e){const t=_.useRef(null),n=_.useRef(null),s=_.useId(),o=_.useRef(e.onClose);if(o.current=e.onClose,_.useEffect(()=>{var m;if(!e.open)return;const c=document.activeElement;(m=t.current)==null||m.focus();const f=p=>{if(!p.defaultPrevented){if(p.key==="Escape"){p.preventDefault(),o.current();return}Uj(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=zj(e.identity,e.extraRows);return r.jsx("div",{className:"af-appearance-overlay af-about-overlay",onClick:e.onClose,role:"presentation",children:r.jsxs("div",{ref:n,className:"af-appearance af-about",role:"dialog","aria-modal":"true","aria-labelledby":s,onClick:c=>c.stopPropagation(),children:[r.jsx("div",{className:"af-appearance__title",id:s,children:l}),r.jsx("dl",{className:"af-about__rows",children:u.map(([c,f],m)=>r.jsxs("div",{className:"af-about__row",children:[r.jsx("dt",{className:"af-about__label",children:c}),r.jsx("dd",{className:"af-about__value",children:r.jsx(Hj,{label:c,value:f})})]},`${m}:${c}`))}),r.jsx("div",{className:"af-appearance__actions",children:r.jsx("button",{ref:t,type:"button",className:"af-appearance__close",onClick:e.onClose,children:"Close"})})]})})}function Gj(e){const{connection:t}=e,n=t.phase,s=t.signingOut===!0,[o,l]=_.useState(!1),u=e.about,c=s?"Signing out…":n==="connected"?"Disconnect":n==="loading"?"Connecting…":"Connect",f=n==="connected"?"Disconnect from gateway":n==="loading"?"Checking gateway session…":"Connect to gateway";return r.jsxs("div",{className:`af-topbar${e.className?` ${e.className}`:""}`,role:"group","aria-label":"App actions",children:[e.assistant?r.jsx("button",{type:"button",className:`af-topbar__btn${e.assistant.open?" is-active":""}`,"aria-pressed":e.assistant.open,"aria-label":e.assistant.label||"Open assistant",title:e.assistant.label||"Assistant",onClick:e.assistant.onToggle,children:r.jsx(et,{name:"sparkle",size:16})}):null,e.appearance?r.jsx("button",{type:"button",className:"af-topbar__btn","aria-label":e.appearance.label||"Appearance (theme and typography)",title:e.appearance.label||"Appearance",onClick:e.appearance.onOpen,children:r.jsx(et,{name:"contrast",size:16})}):null,u?r.jsx("button",{type:"button",className:"af-topbar__btn af-topbar__btn--about","aria-label":u.label||`About ${u.identity.name}`,title:u.label||"About","aria-haspopup":"dialog",onClick:()=>{var m;l(!0),(m=u.onOpen)==null||m.call(u)},children:r.jsx(et,{name:"info",size:16})}):null,e.extraActions,r.jsxs("button",{type:"button",className:`af-topbar__pill af-topbar__pill--${n}`,onClick:n==="connected"?t.onDisconnect:t.onConnect,disabled:s,title:f,"aria-label":f,children:[r.jsx("span",{className:`af-topbar__dot af-topbar__dot--${n}`,"aria-hidden":"true"}),r.jsx("span",{className:"af-topbar__pill-label",children:c})]}),u?r.jsx(Vj,{open:o,onClose:()=>l(!1),identity:u.identity,extraRows:u.extraRows}):null]})}const Kh={theme:"dark",font_scale:"md",header_density:"standard"};function Kj(e){const t=e&&typeof e=="object"?e:{};return{theme:typeof t.theme=="string"&&t.theme?t.theme:Kh.theme,font_scale:typeof t.font_scale=="string"&&t.font_scale?t.font_scale:Kh.font_scale,header_density:typeof t.header_density=="string"&&t.header_density?t.header_density:Kh.header_density}}function Yj(e){return`af_appearance_${e}_v1`}function Jj(e,t){const n=Yj(e),s=_.useMemo(()=>({...Kh,...(t==null?void 0:t.defaults)||{}}),[JSON.stringify((t==null?void 0:t.defaults)||{})]),[o,l]=_.useState(()=>{let u=s;try{const c=localStorage.getItem(n)??(t!=null&&t.legacyKey?localStorage.getItem(t.legacyKey):null);c&&(u=Kj({...s,...JSON.parse(c)}))}catch{}try{cy(u.theme),uy({font_scale:u.font_scale,header_density:u.header_density})}catch{}return u});return _.useEffect(()=>{cy(o.theme),uy({font_scale:o.font_scale,header_density:o.header_density});try{localStorage.setItem(n,JSON.stringify(o))}catch{}},[n,o]),[o,l]}function Xj(e){return _.useEffect(()=>{if(!e.open)return;const t=n=>{n.key!=="Escape"||n.defaultPrevented||(n.preventDefault(),e.onClose())};return window.addEventListener("keydown",t),()=>window.removeEventListener("keydown",t)},[e.open,e.onClose]),e.open?r.jsx("div",{className:"af-appearance-overlay",onClick:e.onClose,role:"presentation",children:r.jsxs("div",{className:"af-appearance",role:"dialog","aria-modal":"true","aria-label":e.title||"Appearance",onClick:t=>t.stopPropagation(),children:[r.jsx("div",{className:"af-appearance__title",children:e.title||"Appearance"}),r.jsx("div",{className:"af-appearance__note",children:e.note||"Stored locally in this browser, per app."}),r.jsxs("div",{className:"af-appearance__grid",children:[r.jsx("label",{className:"af-appearance__label",children:"Theme"}),r.jsx(hj,{value:e.value.theme,onChange:t=>e.onChange({...e.value,theme:t})}),r.jsx("label",{className:"af-appearance__label",children:"Font size"}),r.jsx(mj,{value:e.value.font_scale,onChange:t=>e.onChange({...e.value,font_scale:t})}),r.jsx("label",{className:"af-appearance__label",children:"Header size"}),r.jsx(_j,{value:e.value.header_density,onChange:t=>e.onChange({...e.value,header_density:t})})]}),r.jsx("div",{className:"af-appearance__actions",children:r.jsx("button",{type:"button",className:"af-appearance__close",onClick:e.onClose,children:"Close"})})]})}):null}const Zj={diary:"var(--accent)",question:"#e7b45a",dream:"#c084dd",interest:"#7bd88a",lesson:"#6ea8d8",world_model:"#5eead4"};function my(e){const t=String(e||"");return t.length>14?`${t.slice(0,10)}…${t.slice(-4)}`:t}function v_(e){const[t,n]=_.useState(!1),[s,o]=_.useState(null),l=_.useRef(!1),u=typeof e.entryId=="string"&&e.entryId.trim()?e.entryId.trim():null,c=e.kind&&Zj[e.kind]||"var(--text-muted)",f=_.useCallback(async()=>{if(!(!u||!e.onOpen||l.current)){l.current=!0,n(!0),o(null);try{await e.onOpen(u)}catch(m){o(String((m==null?void 0:m.message)||m||"could not open"))}finally{l.current=!1,n(!1)}}},[u,e.onOpen]);return!u||!e.onOpen?r.jsxs("span",{className:["af-memory-hint","af-memory-hint--text",e.className||""].filter(Boolean).join(" "),title:e.title,children:[r.jsx("span",{className:"af-memory-hint__dot",style:{background:c},"aria-hidden":"true"}),r.jsx("span",{className:"af-memory-hint__label",children:e.label}),u&&e.showId!==!1?r.jsx("code",{className:"af-memory-hint__id",children:my(u)}):null]}):r.jsxs("span",{className:["af-memory-hint",e.className||""].filter(Boolean).join(" "),children:[r.jsxs("button",{type:"button",className:"af-memory-hint__btn",onClick:()=>void f(),disabled:t,title:e.title||(e.command?e.command:`open ${u}`),"aria-label":`Open ${e.kind||"memory"} entry: ${e.label}`,children:[r.jsx("span",{className:"af-memory-hint__dot",style:{background:c},"aria-hidden":"true"}),r.jsx("span",{className:"af-memory-hint__label",children:e.label}),e.showId!==!1?r.jsx("code",{className:"af-memory-hint__id",children:my(u)}):null,r.jsx("span",{className:"af-memory-hint__act","aria-hidden":"true",children:t?"…":"↗"})]}),e.command?r.jsx("code",{className:"af-memory-hint__cmd",children:e.command}):null,s?r.jsx("span",{className:"af-memory-hint__err",role:"alert",children:s}):null]})}const x_=wt("automations"),Qj=wt("trigger-sources"),eS=wt("me/email");class _y 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 tS(e,t){const n=t&&typeof t=="object"?t.detail:void 0;if(n&&typeof n=="object"&&!Array.isArray(n)){const s=n;if(typeof s.reason_code=="string"&&s.reason_code&&typeof s.message=="string"){const o={status:e,code:s.reason_code,message:s.message};return typeof s.field=="string"&&(o.field=s.field),typeof s.command_id=="string"&&(o.command_id=s.command_id),o}}return{status:e,code:"invalid_response",message:`The gateway answered HTTP ${e} without an automation error envelope.`}}function b_(e){const t=new URLSearchParams;for(const[s,o]of Object.entries(e))o!==void 0&&t.set(s,String(o));const n=t.toString();return n?`?${n}`:""}function nS(){return Sm()}function rS(e){const t=e.newId??nS,n=o=>`${x_}/${encodeURIComponent(o)}`;async function s(o,l,u){const c={accept:"application/json",...e.headers?e.headers():{}},f={method:o,headers:c};u!==void 0&&(c["content-type"]="application/json",f.body=JSON.stringify(u));const m=await e.fetch(rg(e.baseUrl,l),f),p=await m.text();let g,w=!1;if(p)try{g=JSON.parse(p),w=!0}catch{w=!1}if(!m.ok)throw new _y(tS(m.status,g));if(!w||g===null||typeof g!="object")throw new _y({status:m.status,code:"invalid_response",message:`The gateway answered ${o} ${l} with a body that is not a JSON object.`});return g}return{listAutomations:(o={})=>s("GET",`${x_}${b_({status:o.status,cursor:o.cursor,limit:o.limit})}`),getAutomation:o=>s("GET",n(o)),createAutomation:o=>s("POST",x_,o),reviseAutomation:(o,l)=>s("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)=>s("POST",`${n(o)}/commands`,{command_id:l.command_id??t(),type:l.type,...l.payload!==void 0?{payload:l.payload}:{}}),listOccurrences:(o,l={})=>s("GET",`${n(o)}/occurrences${b_({cursor:l.cursor,limit:l.limit})}`),discuss:(o,l)=>s("POST",`${n(o)}/discuss`,{request_id:l.request_id??t(),occurrence_index:l.occurrence_index,prompt:l.prompt}),markSeen:(o,l)=>s("POST",`${n(o)}/seen`,{attention_cursor:l}),listAttention:(o,l={})=>s("GET",`${n(o)}/attention${b_({cursor:l.cursor,limit:l.limit})}`),listTriggerSources:()=>s("GET",Qj),getMyEmail:()=>s("GET",eS)}}const sS={active:"Active",pause:"Pause",resume:"Resume",run_now:"Run now",stop_current:"Stop current",revise:"Edit",archive:"Archive",discuss:"Discuss"},iS={active:`On: it runs on its schedule. Off: paused, scheduled runs are skipped.
42
- Pausing lets a run in progress finish, without further retries; Run now still works and keeps it paused.
43
- Making it active again restarts the schedule at its next time after now; times missed while paused are skipped.`,pause:`Stop scheduled runs until you resume.
44
- A run in progress finishes; a pending retry is cancelled. Run now still works.`,resume:`Restart the schedule at its next time after now.
45
- Times missed while paused are skipped; resuming does not run it now.`,run_now:`Run it once now, without waiting for the schedule.
46
- The schedule does not move: the next scheduled run keeps its time, or starts right after this run if its time comes first.
47
- Does not count toward a run limit. Works while paused; it stays paused.
48
- Not available while a run is in progress.`,stop_current:`Cancel the run in progress, or its pending retry.
49
- It ends as cancelled, with no failure notice. The schedule continues.`,revise:`Change the task, schedule or settings.
50
- Changes apply from the next run; a run in progress keeps its inputs. A changed schedule restarts from now, so no past time runs.`,archive:`Stop it for good: it will not run again.
51
- A run in progress finishes; the history stays readable.`,discuss:`Talk about the results in a separate conversation, seeded with the runs up to this one.
52
- It has its own workspace (the automation's files are read-only) and never changes the automation.`},oS="Next scheduled run: {time}.",aS="Growing context: later runs see this run in their history.",lS={run_now:{name:"playCircle"}},cS={trigger_label:"When an email arrives",not_set_up:"Connect a mailbox first — open My email",open_my_email:"open My email",filters_legend:"Only mail that matches (all optional)",from_in:"From these addresses",from_domain_in:"From these domains",to_in:"Sent to these addresses",subject_contains:"Subject contains",has_attachment:"Attachments",has_attachment_any:"any",has_attachment_yes:"only with attachments",has_attachment_no:"only without attachments",list_hint:"Separate entries with commas or new lines. Exact addresses and domains only (no patterns).",every_label:"Check for new mail every",interval_rule:"An automation that runs a model on new mail checks once an hour by default; one that needs no model checks every 60 s. The shortest interval is 60 s.",max_batch_label:"At most this many emails per run",max_batch_hint:"The rest wait for the next run. Each email is read once by this automation; mail that arrived before it was created, or while it is paused, is not processed.",untrusted_hint:"Incoming mail is data, never instructions: the automation acts only on its task. Link-opening tools (fetch_url, browser_probe) always ask for your approval.",notify_label:"Email 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."},$v={labels:sS,hints:iS,run_now_next_run_line:oS,run_now_growing_line:aS,icons:lS,email:cS},uS=/^([1-9][0-9]*)([smhd])$/,dS={s:["second","seconds"],m:["minute","minutes"],h:["hour","hours"],d:["day","days"]};function Cf(e){if(typeof e!="string")return null;const t=uS.exec(e);return t?{amount:Number(t[1]),unit:t[2]}:null}function Av(e){const t=Cf(e);if(!t)return`every ${e}`;const[n,s]=dS[t.unit];return t.amount===1?`every ${n}`:`every ${t.amount} ${s}`}function la(e){if(!e)return"";const t=Date.parse(e);if(Number.isNaN(t))return e;const n=new Date(t).toISOString(),s=n.slice(17,19);return`${n.slice(0,10)} ${n.slice(11,16)}${s==="00"?"":`:${s}`} UTC`}function Tv(e){const t=e;if(typeof t.every!="string")return t.start_at?`once at ${la(t.start_at)}`:"once, now";const n=[`${Av(t.every)} (UTC)`];return typeof t.count=="number"&&n.push(`${t.count} ${t.count===1?"run":"runs"} max`),typeof t.until=="string"&&n.push(`until ${la(t.until)}`),n.join(" · ")}function sg(e){return e.source_id==="schedule"&&e.source_version===1?Tv(e.config):e.source_id==="manual"&&e.source_version===1?"manual runs only":km(e)?Fv(e.config):`${e.source_id}@${e.source_version}`}function Mv(e){return e==="growing"?"Growing — each run sees the previous runs":"Independent — each run starts fresh"}const fS={active:"Active",paused:"Paused",completed:"Completed",failed:"Failed",archived:"Archived"},Ut=$v.email,Rv="email.received",Lv=1,hS="1h",mS="60s",Iv=60,ig=100,hp=1e3,py=200,gy=200,yy=50;function km(e){return!!e&&e.source_id===Rv&&e.source_version===Lv}function Nm(e){return!!e&&e.effective_enabled===!0}function Pv(e){const t=[];for(const n of String(e??"").split(/[\s,;]+/)){const s=n.trim().toLowerCase();s&&!t.includes(s)&&t.push(s)}return t}const _S=/[\s<>,;:"()[\]]/;function mp(e){const t=e.trim().toLowerCase(),n=t.indexOf("@");return n<=0||n===t.length-1?!1:!t.slice(n+1).includes("@")&&!_S.test(t)}function pS(e){const t=e.trim().toLowerCase();return!!t&&!t.includes("@")&&t.includes(".")&&!t.startsWith(".")&&!t.endsWith(".")&&!/[\s<>,;:"()[\]/*]/.test(t)}const Ov={usesModel:!0,every:null,maxBatch:null,fromIn:"",fromDomainIn:"",toIn:"",subjectContains:"",hasAttachment:"any"};function og(e){return e?hS:mS}function Dv(e){const t=Cf(e);return t?t.amount*{s:1,m:60,h:3600,d:86400}[t.unit]:null}function j_(e,t,n,s,o){const l=Pv(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"} ${s}.`),l.length>py&&o.push(`${t}: at most ${py} entries.`),l}function gS(e){const t=[],n={uses_model:e.usesModel};e.every===null?n.every=og(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&&(Dv(n.every)??0)<Iv&&t.push("The check interval is at least 60 seconds."),e.maxBatch===null?n.max_batch=ig:!Number.isInteger(e.maxBatch)||e.maxBatch<1||e.maxBatch>hp?t.push(`At most this many emails per run: a whole number from 1 to ${hp}.`):n.max_batch=e.maxBatch;const s={},o=j_(e.fromIn,Ut.from_in,mp,"an email address",t);o&&(s.from_in=o);const l=j_(e.fromDomainIn,Ut.from_domain_in,pS,"a domain like example.com",t);l&&(s.from_domain_in=l);const u=j_(e.toIn,Ut.to_in,mp,"an email address",t);u&&(s.to_in=u);const c=e.subjectContains.trim();return c&&(c.length>gy||/[\r\n]/.test(c)?t.push(`${Ut.subject_contains}: one line of at most ${gy} characters.`):s.subject_contains=c),e.hasAttachment==="yes"?s.has_attachment=!0:e.hasAttachment==="no"&&(s.has_attachment=!1),Object.keys(s).length&&(n.filter=s),{config:n,errors:t}}function Fv(e){const t=e,n=t.filter??{},s=["when an email arrives"],o=[...n.from_in??[],...n.from_domain_in??[]];o.length&&s.push(`from ${o.join(", ")}`),n.to_in&&n.to_in.length&&s.push(`to ${n.to_in.join(", ")}`),typeof n.subject_contains=="string"&&n.subject_contains&&s.push(`subject contains “${n.subject_contains}”`),n.has_attachment===!0&&s.push("with attachments"),n.has_attachment===!1&&s.push("without attachments");const l=typeof t.every=="string"?t.every:og(t.uses_model!==!1);s.push(`checked ${Av(l)}`);const u=typeof t.max_batch=="number"?t.max_batch:ig;return s.push(`up to ${u} per run`),s.join(" · ")}const ag={mode:"self",addresses:""};function _p(e){if(e.mode==="self")return{recipients:["self"],errors:[]};const t=[],n=Pv(e.addresses).filter(o=>o!=="self");n.length||t.push("Name at least one address the automation may email, or choose Only me.");const s=n.filter(o=>!mp(o));return s.length&&t.push(`${Ut.recipients_list}: ${s.join(", ")} ${s.length===1?"is not an email address":"are not email addresses"}.`),n.length+1>yy&&t.push(`At most ${yy-1} addresses.`),{recipients:["self",...n],errors:t}}function yS(e){const t=(e??[]).filter(n=>n!=="self");return t.length?{mode:"list",addresses:t.join(", ")}:{mode:"self",addresses:""}}function wS(e){const t=(e??["self"]).filter(n=>n!=="self");return t.length?`Me and ${t.join(", ")}`:"Only me"}function zv(e){return{channels:e?["console","email"]:["console"]}}function Bv(e){return!!e&&Array.isArray(e.channels)&&e.channels.includes("email")}function vS(e){return Bv(e)?"In the console and by email":"In the console"}const jo={pause:"automation.pause",resume:"automation.resume",run_now:"automation.run_now",stop_current:"automation.stop_current",archive:"automation.archive"},xS=new Set(["running","waiting","backoff"]);function bS(e,t=[]){return e.current_occurrence!=null}function Uv(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 Wv(e,t){const n=Date.parse(e);if(Number.isNaN(n))return"";const s=Math.round((n-t)/6e4);if(s<=0)return"due now";if(s<60)return`in ${s} min`;const o=Math.floor(s/60);return o<24?`in ${o} h${s%60?` ${s%60} min`:""}`:`in ${Math.floor(o/24)} d${o%24?` ${o%24} h`:""}`}function sm(e,t=[],n=!1){const s=new Set(e.capabilities),o=e.status,l=bS(e,t),u=(p,g,w)=>n?{enabled:!1,reason:"Working…"}:e.legacy?{enabled:!1,reason:"Legacy schedule: managed with its existing controls."}:s.has(p)?o==="archived"?{enabled:!1,reason:"Archived: history is kept, nothing runs."}:g?{enabled:!0}:{enabled:!1,reason:w}:{enabled:!1,reason:"Not permitted for this automation."},c=o==="active"||o==="paused",f=o==="active"?"pause":"resume";return{active:n?{enabled:!1,reason:"Working…"}:e.legacy?{enabled:!1,reason:"Legacy schedule: managed with its existing controls."}:o==="archived"?{enabled:!1,reason:"Archived: history is kept, nothing runs."}:c?s.has(f)?{enabled:!0}:{enabled:!1,reason:"Not permitted for this automation."}:{enabled:!1,reason:"The automation has ended."},pause:u("pause",o==="active",o==="paused"?"Already paused.":"The automation has ended."),resume:u("resume",o==="paused",o==="active"?"Already running on schedule.":"The automation has ended."),run_now:u("run_now",c&&!l,l?"An occurrence is in progress.":"The automation has ended."),stop_current:u("stop_current",l,"Nothing is running."),revise:u("revise",!0,""),archive:u("archive",!0,""),discuss:n?{enabled:!1,reason:"Working…"}:e.legacy?{enabled:!1,reason:"Legacy schedule: discussion is not available."}:s.has("discuss")?{enabled:!0}:{enabled:!1,reason:"Discussion is not permitted for this automation."}}}function jS(e){return e.status==="active"?jo.pause:jo.resume}function SS(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 kS(e){return[...e].sort((t,n)=>t.index-n.index).map(t=>{const n=SS(t),s=`${t.attempts} ${t.attempts===1?"attempt":"attempts"}`,o=n==="failed"?`Failed after ${s}`:n==="waiting"?"Waiting for you":n==="notified"?"Notified":n==="running"?"Running":null,l=t.status==="completed"&&t.attempts>1?`completed after ${s}`:t.status;return{row:t,tone:n,notable:n==="failed"||n==="waiting"||n==="notified",badge:o,statusText:l,canDiscuss:!xS.has(t.status)}})}function NS(e){const t=e.attention.items;return t.length?t[t.length-1].cursor:null}function qv(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 CS={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 im(e){return{title:CS[e.code]??`The gateway refused the request (${e.code}).`,detail:e.message}}function lg(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 Hv(e,t){const n=e.trigger,s=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 s=="string"?s:null,context:e.context_mode,prompt:typeof o=="string"?o:null,toolApproval:t?t.policy.tool_approval:null,notifyEmail:t?Bv(t.notify):null,emailRecipients:t?yS(t.policy.email_allowed_recipients):null}}function ES(e,t,n){const s=[],o={},l=t.title.trim();l?l.length>120?s.push("Title is at most 120 characters."):l!==e.title&&(o.title=l):s.push("Title is required.");const u=Hv(e,n);if(t.every!==u.every&&t.every!==null){const c=km(e.trigger);if(!Cf(t.every))s.push("Interval must be a whole number of minutes, hours or days.");else if(c&&(Dv(t.every)??0)<Iv)s.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}}:s.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=zv(t.notifyEmail)),n&&t.emailRecipients){const c=_p(t.emailRecipients),f=_p(u.emailRecipients??ag).recipients;c.errors.length?s.push(...c.errors):JSON.stringify(c.recipients)!==JSON.stringify(f)&&(o.policy={...o.policy??{},email_allowed_recipients:c.recipients})}return s.length?{errors:s}:Object.keys(o).length?o:null}const $S=[{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 S_(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 AS(e){const t=e.trim().split(`
53
- `)[0].trim();return t.length>120?`${t.slice(0,119)}…`:t}function TS(e){const t=[],n={};if(e.when.kind==="once"){const o=S_(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 s=e.when.amount;if(!Number.isInteger(s)||s<1?t.push("The interval must be a whole number of at least 1."):n.every=`${s}${e.when.unit}`,e.startAt){const o=S_(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=S_(e.until);o?n.until=o:t.push("Stop at must be a date and time (UTC).")}return{config:n,errors:t}}function pp(e,t){const n=[];t.target||n.push("Choose what to run.");const s=e.prompt.trim();s||n.push("Write the task to run.");const o=(e.title??"").trim()||AS(s);o.length>120&&n.push("Title is at most 120 characters.");const l=e.trigger==="email",u=l?gS(e.email??Ov):TS(e);n.push(...u.errors);const c=e.emailRecipients&&e.emailRecipients.mode==="list"?_p(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:s}},m={request_id:t.requestId,title:o,target:f,trigger:l?{source_id:Rv,source_version:Lv,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&&(m.notify=zv(!0)),{ok:!0,body:m}}const MS="Tools run without asking (you approve them now by creating this automation)";function RS(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 s=n;if(typeof s.name!="string"||!s.arguments||typeof s.arguments!="object"||Array.isArray(s.arguments)||s.call_id!==void 0&&typeof s.call_id!="string")return null;t.push({name:s.name,arguments:s.arguments,...typeof s.call_id=="string"?{call_id:s.call_id}:{}})}return t}function LS(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 Vv={ask_user:"Question for you",tool_approval:"Approval needed",event:"Waiting for an event"};class IS{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||PS(n.error))&&this.open.delete(t)}}function PS(e){return lg(e)&&e.status>0&&e.code!=="invalid_response"}function OS(){return Sm()}class DS{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 wy(e,t){if(!e)return null;for(const n of t){const s=e.querySelector(n);if(s&&s.disabled!==!0&&typeof s.focus=="function")return s}return null}function gp(e){if(Nm(e.status))return null;const t=Ut.not_set_up,n=Ut.open_my_email,s=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 r.jsxs("p",{className:"af-auto__hint af-email__notice",role:"note","data-email-setup":"missing",children:[s,e.onOpenMyEmail?r.jsx("button",{type:"button",className:"af-auto__linkbtn","data-action":"open-my-email",onClick:e.onOpenMyEmail,children:n}):n,o?r.jsxs("span",{className:"af-email__cause",children:[" (",o,")"]}):null]})}function FS(e){const t=e.value,n=c=>e.onChange({...t,...c}),s=c=>`${e.idBase}-email-${c}`,o=Cf(og(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 r.jsxs("div",{className:"af-email__trigger","data-field":"email-trigger",children:[r.jsxs("div",{className:"af-auto__row",children:[r.jsx("span",{children:Ut.every_label}),r.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}})}),r.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:[r.jsx("option",{value:"m",children:"minutes"}),r.jsx("option",{value:"h",children:"hours"}),r.jsx("option",{value:"d",children:"days"})]})]}),r.jsx("p",{className:"af-auto__hint","data-email-rule":"interval",children:Ut.interval_rule}),r.jsxs("label",{className:"af-auto__field",htmlFor:s("batch"),children:[r.jsx("span",{children:Ut.max_batch_label}),r.jsx("input",{id:s("batch"),name:"email_max_batch",type:"number",min:1,max:hp,step:1,disabled:u,value:String(t.maxBatch??ig),onChange:c=>n({maxBatch:c.target.value.trim()===""?null:Number(c.target.value)})})]}),r.jsx("p",{className:"af-auto__hint",children:Ut.max_batch_hint}),r.jsxs("fieldset",{className:"af-auto__field af-email__filters",disabled:u,children:[r.jsx("legend",{children:Ut.filters_legend}),r.jsxs("label",{className:"af-auto__field",htmlFor:s("from"),children:[r.jsx("span",{children:Ut.from_in}),r.jsx("input",{id:s("from"),name:"email_from_in",value:t.fromIn,spellCheck:!1,placeholder:"alice@example.com, billing@example.org",onChange:c=>n({fromIn:c.target.value})})]}),r.jsxs("label",{className:"af-auto__field",htmlFor:s("domain"),children:[r.jsx("span",{children:Ut.from_domain_in}),r.jsx("input",{id:s("domain"),name:"email_from_domain_in",value:t.fromDomainIn,spellCheck:!1,placeholder:"example.com",onChange:c=>n({fromDomainIn:c.target.value})})]}),r.jsxs("label",{className:"af-auto__field",htmlFor:s("to"),children:[r.jsx("span",{children:Ut.to_in}),r.jsx("input",{id:s("to"),name:"email_to_in",value:t.toIn,spellCheck:!1,onChange:c=>n({toIn:c.target.value})})]}),r.jsxs("label",{className:"af-auto__field",htmlFor:s("subject"),children:[r.jsx("span",{children:Ut.subject_contains}),r.jsx("input",{id:s("subject"),name:"email_subject_contains",value:t.subjectContains,maxLength:200,onChange:c=>n({subjectContains:c.target.value})})]}),r.jsxs("label",{className:"af-auto__field",htmlFor:s("attach"),children:[r.jsx("span",{children:Ut.has_attachment}),r.jsxs("select",{id:s("attach"),name:"email_has_attachment",value:t.hasAttachment,onChange:c=>n({hasAttachment:c.target.value}),children:[r.jsx("option",{value:"any",children:Ut.has_attachment_any}),r.jsx("option",{value:"yes",children:Ut.has_attachment_yes}),r.jsx("option",{value:"no",children:Ut.has_attachment_no})]})]}),r.jsx("p",{className:"af-auto__hint",children:Ut.list_hint})]})]})}function zS(e){const t=s=>`${e.idBase}-email-${s}`,n=e.disabled===!0;return r.jsxs("div",{className:"af-email__options","data-field":"email-options",children:[r.jsx(No,{variant:"row",action:"notify-email",label:Ut.notify_label,checked:e.notifyEmail,unavailableReason:n?"Connect a mailbox first.":null,onChange:s=>e.onNotifyEmailChange(s)}),r.jsx("p",{className:"af-auto__hint",children:Ut.notify_hint}),r.jsxs("fieldset",{className:"af-auto__field",disabled:n,"data-field":"email-recipients",children:[r.jsx("legend",{children:Ut.recipients_legend}),r.jsxs("label",{children:[r.jsx("input",{type:"radio",name:t("rcpt"),value:"self",checked:e.recipients.mode==="self",onChange:()=>e.onRecipientsChange({...e.recipients,mode:"self"})})," ",Ut.recipients_self]}),r.jsxs("label",{children:[r.jsx("input",{type:"radio",name:t("rcpt"),value:"list",checked:e.recipients.mode==="list",onChange:()=>e.onRecipientsChange({...e.recipients,mode:"list"})})," ",Ut.recipients_list]}),e.recipients.mode==="list"?r.jsx("textarea",{name:"email_recipient_list","aria-label":Ut.recipients_list,rows:2,spellCheck:!1,value:e.recipients.addresses,placeholder:"colleague@example.com",onChange:s=>e.onRecipientsChange({mode:"list",addresses:s.target.value})}):null,r.jsx("p",{className:"af-auto__hint",children:Ut.recipients_hint})]})]})}const BS={active:"play",paused:"pause",completed:"check",failed:"error",archived:"archive"};function Gv(e){const t=String(e.status),n=BS[t];return r.jsxs("span",{className:`af-auto__status af-auto__status--${t}${e.className?` ${e.className}`:""}`,"data-state":t,children:[r.jsx("span",{className:"af-auto__status-word",children:fS[t]??t}),n?r.jsx(et,{name:n,size:e.iconSize??11,className:"af-auto__status-icon"}):null]})}const yp="Discuss — fork at this occurrence (own workspace, automation files read-only)",Cm=e=>r.jsx("div",{className:"af-auto-text","data-unformatted":"true",children:e});function US(e){return lg(e)?e:{status:0,code:"client_error",message:e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}}function vy(e){const t=e.path.split(new RegExp("(?<=[/\\\\_-])"));return r.jsx("code",{className:"af-auto__path-text",children:t.map((n,s)=>r.jsxs(ve.Fragment,{children:[n,s<t.length-1?r.jsx("wbr",{}):null]},s))})}function WS(e,t){const n=e.trigger,s=t.find(o=>o.id===n.source_id&&o.version===n.source_version);return s?"available"in s&&s.available===!1?`Trigger source ${n.source_id}@${n.source_version} is unavailable${s.unavailable_reason?`: ${s.unavailable_reason}`:"."}`:null:`This gateway does not list the trigger source ${n.source_id}@${n.source_version}.`}function qS(e){const t=e.summary,n=Uv(t),s=WS(t,e.triggerSources),o=t.next_fire_at?`${la(t.next_fire_at)} (${Wv(t.next_fire_at,e.nowMs??Date.now())})`:t.status==="paused"?"none while paused":"none scheduled";return r.jsxs("header",{className:"af-auto__head",children:[r.jsxs("div",{className:"af-auto__titlebar",children:[r.jsx("h2",{className:"af-auto__title",id:e.titleId,tabIndex:-1,children:t.title}),r.jsx(Gv,{status:t.status}),t.legacy?r.jsx("span",{className:"af-auto__legacy",children:"Legacy schedule"}):null]}),r.jsxs("dl",{className:"af-auto__facts",children:[r.jsx("dt",{children:"When"}),r.jsxs("dd",{"data-fact":"trigger",children:[sg(t.trigger),s?r.jsxs("span",{className:"af-auto__warn",role:"note",children:[" ",s]}):null]}),r.jsx("dt",{children:"Context"}),r.jsx("dd",{"data-fact":"context",children:Mv(t.context_mode)}),n?r.jsxs(r.Fragment,{children:[r.jsx("dt",{children:"Now"}),r.jsx("dd",{"data-fact":"current",className:"is-notable",children:n})]}):null,r.jsx("dt",{children:"Next run"}),r.jsx("dd",{"data-fact":"next",children:o}),r.jsx("dt",{children:"Runs"}),r.jsx("dd",{"data-fact":"count",children:t.occurrence_count}),t.workspace_root?r.jsxs(r.Fragment,{children:[r.jsx("dt",{children:"Workspace"}),r.jsx("dd",{"data-fact":"workspace",className:"af-auto__workspace",children:e.onOpenWorkspace?r.jsxs("button",{type:"button",className:"af-auto__path","data-action":"open-workspace",title:`Browse the automation's folder
54
- ${t.workspace_root}`,"aria-label":`Browse the automation's folder ${t.workspace_root}`,onClick:()=>{var l;return(l=e.onOpenWorkspace)==null?void 0:l.call(e,t.automation_id)},children:[r.jsx(et,{name:"folder",size:14,className:"af-auto__path-icon"}),r.jsx(vy,{path:t.workspace_root})]}):r.jsxs("span",{className:"af-auto__path af-auto__path--static",children:[r.jsx(et,{name:"folder",size:14,className:"af-auto__path-icon"}),r.jsx(vy,{path:t.workspace_root})]})})]}):null,r.jsx("dt",{children:"Attention"}),r.jsx("dd",{"data-fact":"attention",className:t.attention.unread||t.attention.pending_waits?"is-notable":void 0,children:qv(t)}),t.revision!==null?r.jsxs(r.Fragment,{children:[r.jsx("dt",{children:"Revision"}),r.jsx("dd",{"data-fact":"revision",children:t.revision})]}):null]})]})}function HS(e){const t=e.definition,n=e.renderText??Cm,s=t.target.input_data.prompt,o=t.policy.retry,l=t.policy.tool_approval;return r.jsxs("details",{className:"af-auto__definition","data-definition-revision":t.revision,open:e.open,children:[r.jsxs("summary",{children:[r.jsx(et,{name:"chevronRight",size:14,className:"af-auto__definition-chevron"}),r.jsx(et,{name:"file",size:14}),r.jsx("span",{className:"af-auto__definition-title",children:"Definition"}),r.jsxs("span",{className:"af-auto__definition-meta",children:["revision ",t.revision]})]}),r.jsxs("dl",{className:"af-auto__facts",children:[r.jsx("dt",{children:"Target"}),r.jsx("dd",{"data-def":"target",children:r.jsx("code",{children:t.target.workflow_id})}),typeof s=="string"&&s?r.jsxs(r.Fragment,{children:[r.jsx("dt",{children:"Task"}),r.jsx("dd",{"data-def":"prompt",children:n(s)})]}):null,r.jsx("dt",{children:"Trigger"}),r.jsxs("dd",{"data-def":"trigger",children:[t.trigger.source_id,"@",t.trigger.source_version," · ",sg(t.trigger),r.jsx("pre",{className:"af-auto__json",children:JSON.stringify(t.trigger.config,null,2)})]}),r.jsx("dt",{children:"Context"}),r.jsx("dd",{"data-def":"context",children:Mv(t.context.mode)}),r.jsx("dt",{children:"Tools"}),r.jsx("dd",{"data-def":"tool_approval",children:l==="ask"?"Ask before each tool call (ask)":l==="auto"?"Run without asking (auto)":String(l)}),r.jsx("dt",{children:"Notify"}),r.jsx("dd",{"data-def":"notify",children:vS(t.notify)}),r.jsx("dt",{children:"May email"}),r.jsx("dd",{"data-def":"email_allowed_recipients",children:wS(t.policy.email_allowed_recipients)}),r.jsx("dt",{children:"Retries"}),r.jsxs("dd",{"data-def":"retry",children:[o.max_attempts," ",o.max_attempts===1?"attempt":"attempts",", backoff ",o.backoff.initial," ×",o.backoff.factor," up to ",o.backoff.max]}),r.jsx("dt",{children:"Revision"}),r.jsx("dd",{"data-def":"revision",children:t.revision})]})]})}const Ef=$v,xo=Ef.labels,zi={active:"play",pause:"pause",resume:"play",run_now:Ef.icons.run_now.name,stop_current:"stop",revise:"edit",archive:"archive",discuss:"chat"},wp=Ef.hints,VS=Ef.run_now_next_run_line,GS=Ef.run_now_growing_line;function om(e,t){const n=[wp[e]];return e==="run_now"&&t&&(t.next_fire_at&&n.push(VS.replace("{time}",la(t.next_fire_at))),t.context_mode==="growing"&&n.push(GS)),n.join(`
55
- `)}function KS(e,t,n){const s=new Map;for(const u of t){const c=e[u];if(c.enabled)continue;const f=c.reason??"Not available now.";s.set(f,[...s.get(f)??[],u])}const o=[],l={};return[...s.entries()].forEach(([u,c],f)=>{const m=`${n}-why-${f}`;o.push({id:m,text:`${c.map(p=>xo[p]).join(", ")}: ${u}`});for(const p of c)l[p]=m}),{lines:o,describedBy:l}}function us(e){return r.jsxs(r.Fragment,{children:[r.jsx(et,{name:e.icon,size:14,className:"af-auto__btn-icon"}),r.jsx("span",{children:e.label})]})}function YS(e){const t=sm(e.summary,e.occurrences,e.busy),s=KS(t,["active","run_now","stop_current","revise","archive"],e.idBase??`af-auto-${e.summary.automation_id}`),o=(l,u,c)=>{const f=om(l,e.summary);return r.jsx("button",{type:"button",className:`af-auto__btn${c!=null&&c.danger?" af-auto__btn--danger":""}`,"data-action":(c==null?void 0:c.action)??l,disabled:!t[l].enabled,title:t[l].enabled?f:`${t[l].reason}
56
- ${f}`,"aria-description":f,"aria-describedby":s.describedBy[l],"aria-pressed":c==null?void 0:c.pressed,onClick:u,children:r.jsx(us,{icon:zi[l],label:(c==null?void 0:c.label)??xo[l]})},l)};return r.jsxs("div",{className:"af-auto__controls-wrap",children:[r.jsxs("div",{className:"af-auto__actionbar",children:[r.jsxs("div",{className:"af-auto__controls",role:"toolbar","aria-label":"Automation controls",children:[r.jsx(No,{className:"af-auto__switch",action:"active",label:xo.active,checked:e.summary.status==="active",unavailableReason:t.active.enabled?null:t.active.reason??"Not available now.",describedBy:s.describedBy.active,busy:e.busy,hint:om("active",e.summary),onChange:()=>e.onCommand(jS(e.summary))},"active"),o("run_now",()=>e.onCommand(jo.run_now)),o("stop_current",()=>e.onCommand(jo.stop_current)),o("revise",e.onToggleRevise,{pressed:e.reviseOpen,action:"edit"}),o("archive",e.onAskArchive,{danger:!0,label:"Archive…"})]}),r.jsx("span",{className:`af-auto__notice${e.notice?" af-auto__notice--on":""}`,role:"status",tabIndex:-1,children:e.notice?r.jsxs(r.Fragment,{children:[r.jsx(et,{name:"check",size:13}),r.jsx("span",{className:"af-auto__notice-text",children:e.notice}),e.onDismissNotice?r.jsx("button",{type:"button",className:"af-auto__icon-btn af-auto__icon-btn--bare","data-action":"dismiss-notice","aria-label":"Dismiss",title:"Dismiss",onClick:e.onDismissNotice,children:r.jsx(et,{name:"x",size:12})}):null]}):null})]}),s.lines.length?r.jsxs("p",{className:"af-auto__reasons",children:[r.jsx(et,{name:"info",size:12,className:"af-auto__reasons-icon"}),s.lines.map(l=>r.jsx("span",{id:l.id,children:l.text},l.id))]}):null,e.summary.status==="paused"&&t.run_now.enabled?r.jsx("p",{className:"af-auto__hint",children:"Paused: scheduled runs are skipped. Run now works and keeps it paused."}):null,e.confirmingArchive?r.jsxs("div",{className:"af-auto__confirm",role:"group","aria-label":"Confirm archive",children:[r.jsxs("p",{children:["Archive “",e.summary.title,"”? Its history stays readable; it will not run again. The current run, if any, finishes."]}),r.jsxs("div",{className:"af-auto__row",children:[r.jsx("button",{type:"button",className:"af-auto__btn af-auto__btn--danger","data-action":"archive-confirm",disabled:!t.archive.enabled,onClick:()=>e.onCommand(jo.archive),children:r.jsx(us,{icon:"archive",label:"Archive"})}),r.jsx("button",{type:"button",className:"af-auto__btn","data-action":"archive-cancel",onClick:e.onCancelArchive,children:r.jsx(us,{icon:"x",label:"Keep it"})})]})]}):null]})}const xy=[["m","minutes"],["h","hours"],["d","days"]];function JS(e,t){const n=N=>{const C=e.elements.namedItem(N);return C&&typeof C.value=="string"?C.value:null},s=n("every_amount"),o=n("every_unit"),l=s!==null&&o!==null?`${s.trim()}${o}`:t.every,u=e.elements.namedItem("context"),c=u&&(u.value==="growing"||u.value==="independent")?u.value:t.context,f=n("prompt"),m=e.elements.namedItem("tool_approval"),p=m&&(m.value==="auto"||m.value==="ask")?m.value:t.toolApproval??null,g=e.elements.namedItem("notify_email"),w=g&&typeof g.checked=="boolean"?g.checked:t.notifyEmail??null,x=e.elements.namedItem("email_recipients"),S=n("email_recipient_list"),j=x&&(x.value==="self"||x.value==="list")?{mode:x.value,addresses:S??""}:t.emailRecipients??null;return{title:n("title")??t.title,every:l,context:c,prompt:f??t.prompt??null,toolApproval:p,notifyEmail:w,emailRecipients:j}}function XS(e){const t=Hv(e.summary,e.definition),n=t.every?Cf(t.every):null,s=n&&n.unit==="s"?[["s","seconds"],...xy]:xy,o=`af-auto-revise-${e.summary.automation_id}`,l=Nm(e.emailStatus),u=km(e.summary.trigger);return r.jsxs("form",{className:"af-auto__revise","aria-labelledby":`${o}-heading`,onSubmit:c=>{c.preventDefault(),e.onSubmit(JS(c.currentTarget,t))},onKeyDown:c=>{c.key==="Escape"&&(c.preventDefault(),e.onCancel())},children:[r.jsxs("h3",{className:"af-auto__form-title",id:`${o}-heading`,children:[r.jsx(et,{name:"edit",size:14})," Edit automation"]}),r.jsxs("label",{className:"af-auto__field",htmlFor:`${o}-title`,children:[r.jsx("span",{children:"Title"}),r.jsx("input",{id:`${o}-title`,name:"title",defaultValue:t.title,maxLength:120,required:!0})]}),t.prompt!==null&&t.prompt!==void 0?r.jsxs("label",{className:"af-auto__field",htmlFor:`${o}-prompt`,children:[r.jsx("span",{children:"Task"}),r.jsx("textarea",{id:`${o}-prompt`,name:"prompt",defaultValue:t.prompt,rows:Math.min(10,Math.max(3,t.prompt.split(`
57
- `).length+1)),required:!0})]}):null,n?r.jsxs("fieldset",{className:"af-auto__field",children:[r.jsx("legend",{children:u?Ut.every_label:"Repeat every (UTC)"}),r.jsxs("div",{className:"af-auto__row",children:[r.jsx("input",{name:"every_amount",type:"number",min:1,step:1,defaultValue:n.amount,"aria-label":"Interval amount"}),r.jsx("select",{name:"every_unit",defaultValue:n.unit,"aria-label":"Interval unit",children:s.map(([c,f])=>r.jsx("option",{value:c,children:f},c))})]}),u?r.jsx("p",{className:"af-auto__hint","data-email-rule":"interval",children:Ut.interval_rule}):null]}):r.jsx("p",{className:"af-auto__hint",children:"This trigger has no interval to change."}),r.jsxs("fieldset",{className:"af-auto__field",children:[r.jsx("legend",{children:"Context"}),r.jsxs("label",{children:[r.jsx("input",{type:"radio",name:"context",value:"independent",defaultChecked:t.context==="independent"})," Independent — each run starts fresh"]}),r.jsxs("label",{children:[r.jsx("input",{type:"radio",name:"context",value:"growing",defaultChecked:t.context==="growing"})," Growing — each run sees the previous runs"]})]}),t.toolApproval?r.jsxs("fieldset",{className:"af-auto__field",children:[r.jsx("legend",{children:"Tools"}),r.jsxs("label",{children:[r.jsx("input",{type:"radio",name:"tool_approval",value:"auto",defaultChecked:t.toolApproval==="auto"})," Run without asking"]}),r.jsxs("label",{children:[r.jsx("input",{type:"radio",name:"tool_approval",value:"ask",defaultChecked:t.toolApproval==="ask"})," Ask before each tool call"]})]}):null,t.notifyEmail!==null&&t.notifyEmail!==void 0&&t.emailRecipients?r.jsxs("fieldset",{className:"af-auto__field","data-field":"email",children:[r.jsx("legend",{children:"Mailbox"}),l?null:r.jsx(gp,{status:e.emailStatus,onOpenMyEmail:e.onOpenMyEmail}),r.jsx(bj,{variant:"row",action:"notify-email",name:"notify_email",label:Ut.notify_label,defaultChecked:!!t.notifyEmail,unavailableReason:!l&&!t.notifyEmail?"Connect a mailbox first.":null}),r.jsx("p",{className:"af-auto__hint",children:Ut.notify_hint}),r.jsxs("fieldset",{className:"af-auto__field","data-field":"email-recipients",children:[r.jsx("legend",{children:Ut.recipients_legend}),r.jsxs("label",{children:[r.jsx("input",{type:"radio",name:"email_recipients",value:"self",defaultChecked:t.emailRecipients.mode==="self"})," ",Ut.recipients_self]}),r.jsxs("label",{children:[r.jsx("input",{type:"radio",name:"email_recipients",value:"list",defaultChecked:t.emailRecipients.mode==="list",disabled:!l&&t.emailRecipients.mode!=="list"})," ",Ut.recipients_list]}),r.jsx("textarea",{name:"email_recipient_list","aria-label":Ut.recipients_list,rows:2,spellCheck:!1,defaultValue:t.emailRecipients.addresses,disabled:!l&&t.emailRecipients.mode!=="list"}),r.jsx("p",{className:"af-auto__hint",children:Ut.recipients_hint})]})]}):null,r.jsx("p",{className:"af-auto__hint",children:"Changes apply from the next run; a new interval never fires past ticks."}),e.errors.length?r.jsx("ul",{className:"af-auto__form-errors",role:"alert",children:e.errors.map(c=>r.jsx("li",{children:c},c))}):null,r.jsxs("div",{className:"af-auto__row",children:[r.jsx("button",{type:"submit",className:"af-auto__btn af-auto__btn--primary","data-action":"edit-save",disabled:e.busy,children:r.jsx(us,{icon:"check",label:"Save changes"})}),r.jsx("button",{type:"button",className:"af-auto__btn","data-action":"edit-cancel",onClick:e.onCancel,children:r.jsx(us,{icon:"x",label:"Cancel"})})]})]})}function vp(e,t){const n=e.elements.namedItem(t);return n&&typeof n.value=="string"?n.value.trim():""}function ZS(e){const t=e.wait,n=`${e.idBase}-${t.run_id}-${t.wait_key}-prompt`,s=u=>e.onAnswerWait(t.run_id,t.wait_key,u),o=e.renderText??Cm,l=u=>r.jsxs("div",{className:"af-auto-wait__prompt",id:n,children:[r.jsx("span",{className:"af-auto-wait__kind",children:Vv[t.kind]??"Waiting"}),t.prompt?o(t.prompt):r.jsxs("span",{children:[" ",u]})]});if(t.kind==="tool_approval"){const u=RS(t);return r.jsxs("div",{className:"af-auto-wait af-auto-wait--tool_approval",role:"group","data-wait-key":t.wait_key,"data-wait-kind":t.kind,"aria-labelledby":n,children:[l("A tool call needs your approval."),u&&u.length?r.jsx("ul",{className:"af-auto-wait__calls","aria-label":"Tool calls to approve",children:u.map((c,f)=>r.jsxs("li",{"data-tool":c.name,children:[r.jsx("code",{className:"af-auto-wait__tool",children:c.name}),r.jsx("pre",{className:"af-auto-wait__args",children:JSON.stringify(c.arguments,null,2)})]},c.call_id??`${c.name}:${f}`))}):r.jsx("p",{className:"af-auto__hint",children:"The gateway did not list the tool calls; open the run to see them before approving."}),r.jsxs("div",{className:"af-auto__row",children:[r.jsx("button",{type:"button",className:"af-auto__btn af-auto__btn--primary","data-action":"wait-approve",disabled:e.busy,onClick:()=>s({approved:!0}),children:r.jsx(us,{icon:"check",label:"Approve"})}),r.jsx("button",{type:"button",className:"af-auto__btn af-auto__btn--danger","data-action":"wait-deny",disabled:e.busy,onClick:()=>s({approved:!1}),children:r.jsx(us,{icon:"x",label:"Deny"})})]})]})}return t.kind==="event"?r.jsxs("form",{className:"af-auto-wait af-auto-wait--event","data-wait-key":t.wait_key,"data-wait-kind":t.kind,"aria-labelledby":n,onSubmit:u=>{var f;u.preventDefault();const c=LS(vp(u.currentTarget,"payload"));c.ok?s({payload:c.payload}):(f=e.onWaitError)==null||f.call(e,c.error)},children:[l("The run waits for an event."),r.jsx("textarea",{name:"payload",rows:3,"aria-label":"Event payload (JSON)",placeholder:'{"key": "value"}',disabled:e.busy}),r.jsx("div",{className:"af-auto__row",children:r.jsx("button",{type:"submit",className:"af-auto__btn af-auto__btn--primary","data-action":"wait-send-event",disabled:e.busy,children:r.jsx(us,{icon:"send",label:"Send event"})})})]}):t.kind==="ask_user"?r.jsxs("form",{className:"af-auto-wait af-auto-wait--ask_user","data-wait-key":t.wait_key,"data-wait-kind":t.kind,"aria-labelledby":n,onSubmit:u=>{u.preventDefault();const c=vp(u.currentTarget,"response");c&&s({response:c})},children:[l("The run is waiting for your input."),t.choices&&t.choices.length?r.jsx("div",{className:"af-auto__row",role:"group","aria-label":"Choices",children:t.choices.map(u=>r.jsx("button",{type:"button",className:"af-auto__btn","data-action":"wait-choice",disabled:e.busy,onClick:()=>s({response:u}),children:u},u))}):null,r.jsxs("div",{className:"af-auto__row",children:[r.jsx("input",{name:"response","aria-label":"Your answer",placeholder:"Your answer",disabled:e.busy}),r.jsx("button",{type:"submit",className:"af-auto__btn af-auto__btn--primary","data-action":"wait-answer",disabled:e.busy,children:r.jsx(us,{icon:"send",label:"Answer"})})]})]}):r.jsxs("div",{className:"af-auto-wait",role:"group","data-wait-key":t.wait_key,"data-wait-kind":String(t.kind),"aria-labelledby":n,children:[l("The run is waiting."),r.jsxs("p",{className:"af-auto__hint",children:["This kind of wait (",String(t.kind),") cannot be answered here; open the run."]})]})}function QS(e){const{row:t,tone:n,badge:s,statusText:o}=e.view,l=`af-auto-occ-${t.run_id}`,u=e.renderText??Cm,c=e.discuss.enabled&&e.view.canDiscuss&&!e.busy,f=e.discuss.enabled?e.view.canDiscuss?null:"Available once this occurrence finishes.":e.discuss.reason??"Not available.",m=(w,x)=>e.renderTurn?e.renderTurn({kind:w,role:w==="trigger"?"user":"assistant",text:x,index:t.index,runId:t.run_id}):u(x),p=e.renderTurn?" af-auto-turn--card":"",g=n==="failed"?t.failure?"No answer.":"No answer: the run failed.":n==="waiting"?"Waiting for your answer.":n==="running"?"Running…":"No answer.";return r.jsxs("li",{className:`af-auto-occ af-auto-occ--${n}`,"data-index":t.index,"data-tone":n,"aria-labelledby":`${l}-h`,children:[r.jsxs("div",{className:`af-auto-turn af-auto-turn--trigger${p}`,"data-turn":"trigger",children:[r.jsxs("div",{className:"af-auto-turn__meta",id:`${l}-h`,children:[r.jsxs("span",{className:"af-auto-turn__index",children:["#",t.index]})," · ",t.trigger.summary," · fired ",la(t.fired_at)]}),r.jsx("div",{className:"af-auto-turn__text",children:m("trigger",t.user_turn)})]}),r.jsxs("div",{className:`af-auto-turn af-auto-turn--answer${p}`,"data-turn":"answer",children:[r.jsxs("div",{className:"af-auto-turn__meta",children:[s?r.jsx("span",{className:`af-auto-badge af-auto-badge--${n}`,children:s}):null,r.jsx("span",{className:"af-auto-turn__status",children:o}),t.finished_at?r.jsxs("span",{children:[" · ",la(t.finished_at)]}):null]}),t.notify?r.jsxs("div",{className:"af-auto-notify","data-notify":"true",children:[r.jsx("strong",{children:t.notify.title}),t.notify.body?r.jsx("div",{className:"af-auto-notify__body",children:u(t.notify.body)}):null]}):null,t.failure?r.jsxs("div",{className:"af-auto-failure","data-failure":t.failure.reason_code,children:[r.jsx("strong",{children:t.failure.reason_code}),": ",t.failure.message," ",r.jsxs("span",{className:"af-auto-turn__muted",children:["(after ",t.failure.attempts," ",t.failure.attempts===1?"attempt":"attempts",")"]})]}):null,t.answer?r.jsx("div",{className:"af-auto-turn__text",children:m("answer",t.answer)}):r.jsx("div",{className:"af-auto-turn__empty",children:g}),t.artifacts.length?r.jsx("ul",{className:"af-auto-artifacts","aria-label":"Artifacts",children:t.artifacts.map(w=>r.jsxs("li",{children:[e.onOpenResource?r.jsxs("button",{type:"button",className:"af-auto__linkbtn","data-action":"open-artifact",onClick:()=>{var x;return(x=e.onOpenResource)==null?void 0:x.call(e,{kind:"artifact",url:w.url,name:w.name,mimeType:w.mime_type,runId:t.run_id})},children:[r.jsx(et,{name:"file",size:13,className:"af-auto__btn-icon"})," ",w.name]}):r.jsx("span",{className:"af-auto-artifact__name",children:w.name})," ",r.jsx("span",{className:"af-auto-turn__muted",children:w.mime_type})]},w.artifact_id))}):null,t.waits.map(w=>r.jsx(ZS,{wait:w,busy:e.busy,idBase:l,onAnswerWait:e.onAnswerWait,onWaitError:e.onWaitError,renderText:e.renderText},`${w.run_id}:${w.wait_key}`))]}),r.jsxs("div",{className:"af-auto-occ__foot",children:[r.jsxs("details",{className:"af-auto-occ__details",children:[r.jsx("summary",{children:"Run details"}),r.jsxs("dl",{className:"af-auto__facts",children:[r.jsx("dt",{children:"Run"}),r.jsx("dd",{children:r.jsx("code",{children:t.run_id})}),r.jsx("dt",{children:"Attempts"}),r.jsx("dd",{children:t.attempts})]}),r.jsxs("div",{className:"af-auto__row",children:[r.jsx("button",{type:"button",className:"af-auto__btn","data-action":"open-run",onClick:()=>e.onOpenRun(t.run_id),children:r.jsx(us,{icon:"list",label:"Open run ledger"})}),e.onOpenResource?r.jsx("button",{type:"button",className:"af-auto__btn","data-action":"open-ledger-json",onClick:()=>{var 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:r.jsx(us,{icon:"file",label:"Ledger (JSON)"})}):null,t.workspace_url&&e.onOpenWorkspace?r.jsx("button",{type:"button",className:"af-auto__btn","data-action":"open-workspace",title:"Browse this run's folder",onClick:()=>{var w;return(w=e.onOpenWorkspace)==null?void 0:w.call(e,t.run_id)},children:r.jsx(us,{icon:"folder",label:"Workspace"})}):null]})]}),e.discussOpen?r.jsxs("form",{className:"af-auto-discuss","aria-label":`${yp}, from occurrence ${t.index}`,onSubmit:w=>{w.preventDefault();const x=vp(w.currentTarget,"prompt");x&&e.onDiscussSubmit(t.index,x)},children:[r.jsxs("p",{className:"af-auto__hint",children:["Starts a new session that forks this automation at #",t.index," with its full history (runs 1–",t.index,"). It works in its own writable workspace; the automation's files are mounted read-only for the file tools (shell commands are not sandboxed), and nothing is written back into the automation's session."]}),r.jsx("textarea",{name:"prompt",rows:3,"aria-label":"Your message",placeholder:"Ask about this result…",required:!0}),r.jsxs("div",{className:"af-auto__row",children:[r.jsx("button",{type:"submit",className:"af-auto__btn af-auto__btn--primary","data-action":"discuss-submit",disabled:e.busy,children:r.jsx(us,{icon:"send",label:"Start discussion"})}),r.jsx("button",{type:"button",className:"af-auto__btn","data-action":"discuss-cancel",onClick:e.onDiscussCancel,children:r.jsx(us,{icon:"x",label:"Cancel"})})]})]}):r.jsxs(r.Fragment,{children:[r.jsx("button",{type:"button",className:"af-auto__btn af-auto__btn--quiet","data-action":"discuss",disabled:!c,title:wp.discuss,"aria-description":wp.discuss,"aria-describedby":f?`${l}-discuss-why`:void 0,onClick:()=>e.onDiscussOpen(t.index),children:r.jsx(us,{icon:zi.discuss,label:yp})}),f?r.jsx("span",{className:"af-auto__reasons",id:`${l}-discuss-why`,children:f}):null]})]})]})}const ek=5e3,tk={[jo.pause]:"Automation paused.",[jo.resume]:"Automation active.",[jo.run_now]:"Run requested.",[jo.stop_current]:"Stop requested."};function nk(e){const{summary:t,busy:n}=e,s=e.renderText??Cm,o=_.useId(),l=_.useRef(null),[u,c]=_.useState(!1),f=e.editOpen!==void 0,p=sm(t,e.occurrences,!1).revise.enabled&&(f?e.editOpen===!0:u),g=_.useRef(null);p?(!g.current||g.current.summary.automation_id!==t.automation_id)&&(g.current={summary:t,definition:e.definition}):g.current=null;const w=g.current,x=_.useRef(e.onEditOpenChange);x.current=e.onEditOpenChange;const S=Q=>{var le;f||c(Q),(le=x.current)==null||le.call(x,Q)},[j,N]=_.useState([]),[C,E]=_.useState(!1),[T,I]=_.useState(null),[K,U]=_.useState(null),[J,Y]=_.useState(null);_.useEffect(()=>{if(!J)return;const Q=setTimeout(()=>Y(null),ek);return()=>clearTimeout(Q)},[J]),_.useEffect(()=>{var le;if(!p)return;N([]);const Q=wy(l.current,['.af-auto__revise [name="title"]']);Q==null||Q.focus(),(le=Q==null?void 0:Q.scrollIntoView)==null||le.call(Q,{block:"nearest"})},[p,t.automation_id]);const[se,ce]=_.useState(null);_.useEffect(()=>{var Q;se&&((Q=wy(l.current,[...se,".af-auto__notice",".af-auto__title"]))==null||Q.focus(),ce(null))},[se]);const fe=_.useRef(null);fe.current||(fe.current=new IS(e.newId??OS));const W=fe.current,P=Q=>U(US(Q)),A=(Q,le,ge)=>{U(null),Y(null),le(W.idFor(Q)).then(pe=>{W.settle(Q,{ok:!0}),ge(pe)},pe=>{W.settle(Q,{ok:!1,error:pe}),P(pe)})},z=NS(t),$=_.useRef(e.onSeen);$.current=e.onSeen;const te=_.useRef(null);te.current||(te.current=new DS),_.useEffect(()=>{const Q=te.current,le=z?`${t.automation_id}|${z}`:null;if(!z||!Q.next(le,t))return;const ge=t;$.current(z).then(()=>Q.succeeded(le),pe=>{Q.failed(le,ge),P(pe)})});const O=sm(t,e.occurrences,n),F=kS(e.occurrences),G=t.occurrence_count-e.occurrences.length,R=K??e.error??null,Z=R?im(R):null,X=t.attention;return r.jsxs("section",{ref:l,className:`af-auto${e.className?` ${e.className}`:""}`,"aria-labelledby":o,"aria-busy":n,"data-text-rendering":e.renderText?"rich":"unformatted",children:[r.jsx(qS,{summary:t,triggerSources:e.triggerSources,titleId:o,nowMs:e.nowMs,onOpenWorkspace:e.onOpenWorkspace}),r.jsx(YS,{summary:t,occurrences:e.occurrences,busy:n,confirmingArchive:C,reviseOpen:p,notice:J,onDismissNotice:()=>Y(null),idBase:`${o}-ctl`,onCommand:Q=>A(`command:${Q}`,le=>e.onCommand(Q,void 0,{command_id:le}),()=>{Q===jo.archive?(E(!1),Y("Archive requested."),ce(['[data-action="archive"]'])):Y(tk[Q]??"Command sent.")}),onToggleRevise:()=>{N([]),S(!p)},onAskArchive:()=>E(!0),onCancelArchive:()=>{E(!1),ce(['[data-action="archive"]'])}}),p&&w?r.jsx(XS,{summary:w.summary,definition:w.definition,busy:n,errors:j,emailStatus:e.emailStatus,onOpenMyEmail:e.onOpenMyEmail,onCancel:()=>{S(!1),ce(['[data-action="edit"]'])},onSubmit:Q=>{const le=w.summary,ge=ES(le,Q,w.definition);if(ge===null){N(["Nothing changed."]);return}if("errors"in ge){N(ge.errors);return}N([]),A(`revise:${le.revision}:${JSON.stringify(ge)}`,pe=>e.onRevise(ge,le.revision,{command_id:pe}),()=>{Y("Saved; applies from the next run."),S(!1),ce(['[data-action="edit"]'])})}}):e.definition?r.jsx(HS,{definition:e.definition,renderText:s}):null,Z?r.jsxs("div",{className:"af-auto__error",role:"alert","data-code":R==null?void 0:R.code,children:[r.jsx(et,{name:"error",size:14,className:"af-auto__btn-icon"}),r.jsxs("span",{className:"af-auto__error-text",children:[r.jsx("strong",{children:Z.title})," ",r.jsx("span",{children:Z.detail})]}),K?r.jsx("button",{type:"button",className:"af-auto__icon-btn af-auto__icon-btn--bare","data-action":"dismiss-error","aria-label":"Dismiss",title:"Dismiss",onClick:()=>U(null),children:r.jsx(et,{name:"x",size:12})}):null]}):null,X.items.length||X.waits.length?r.jsx("section",{className:"af-auto__attention","aria-label":"Needs attention",children:r.jsxs("ul",{children:[X.items.map(Q=>r.jsxs("li",{className:`af-auto__attention-item af-auto__attention-item--${Q.kind}`,"data-cursor":Q.cursor,children:[r.jsx("span",{className:`af-auto-badge af-auto-badge--${Q.kind==="failure"?"failed":"notified"}`,children:Q.kind==="failure"?"Failed":"Notified"})," ",r.jsx("strong",{children:Q.title})," ",r.jsxs("span",{className:"af-auto-turn__muted",children:["#",Q.index," · ",la(Q.at)]}),Q.body?r.jsx("div",{className:"af-auto__attention-body",children:s(Q.body)}):null]},Q.cursor)),X.waits.map(Q=>r.jsxs("li",{className:"af-auto__attention-item af-auto__attention-item--wait",children:[r.jsx("span",{className:"af-auto-badge af-auto-badge--waiting","data-wait-kind":Q.kind,children:Vv[Q.kind]??"Waiting for you"})," ",r.jsxs("span",{className:"af-auto-turn__muted",children:["#",Q.index]}),Q.prompt?r.jsx("div",{className:"af-auto__attention-body",children:s(Q.prompt)}):null]},`${Q.run_id}:${Q.wait_key}`))]})}):null,G>0?r.jsx("button",{type:"button",className:"af-auto__btn af-auto__more","data-action":"load-more",disabled:n,onClick:e.onLoadMore,children:r.jsx(us,{icon:"history",label:`Load earlier occurrences (${G} more)`})}):null,F.length?r.jsx("ol",{className:"af-auto__timeline","aria-label":"Occurrences",children:F.map(Q=>{const le=`[data-index="${Q.row.index}"]`;return r.jsx(QS,{view:Q,busy:n,discuss:O.discuss,renderText:s,renderTurn:e.renderTurn,onOpenWorkspace:e.onOpenWorkspace,onOpenResource:e.onOpenResource?ge=>{var pe;U(null);try{Promise.resolve((pe=e.onOpenResource)==null?void 0:pe.call(e,ge)).catch(P)}catch(ye){P(ye)}}:void 0,discussOpen:T===Q.row.index,onOpenRun:e.onOpenRun,onAnswerWait:(ge,pe,ye)=>{U(null),e.onAnswerWait(ge,pe,ye).then(()=>Y("Answer sent."),P)},onWaitError:ge=>U({status:0,code:"invalid_payload",message:ge}),onDiscussOpen:I,onDiscussCancel:()=>{I(null),ce([`${le} [data-action="discuss"]`])},onDiscussSubmit:(ge,pe)=>A(`discuss:${ge}:${pe}`,ye=>e.onDiscuss(ge,pe,{request_id:ye}),ye=>{I(null),Y(`Discussion started (session ${ye.session_id}).`),ce([`${le} [data-action="discuss"]`])})},Q.row.run_id)})}):r.jsx("p",{className:"af-auto__empty",children:"No occurrences yet."})]})}const Kv="@default",Yv="No workflows available for this app — ask your admin.",Jv={shared:"Shared",mine:"Mine"};class Xa extends Error{constructor(t){super(t),this.name="WorkflowPickerContractError"}}function rk(e,t={}){const n=String(e||"").trim();if(!n)throw new Error("executableWorkflowsPath needs the interface the app runs (e.g. abstractcode.agent.v1).");return`bundles?executable_for=${encodeURIComponent(n)}${t.allVersions?"&all_versions=true":""}`}function sk(e={}){return e.allVersions?"bundles?all_versions=true":"bundles"}function ik(e,t={}){return e===null?sk(t):rk(e,t)}function ia(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function Lr(e){return typeof e=="string"?e.trim():""}const kh="update the gateway";function ok(e,t){var c,f;const n=ia(e.default_agent_workflows);if(!n)return{status:"unavailable",reason:"the gateway does not report a default workflow"};const s=ia(n[t]);if(!s)return{status:"unavailable",reason:Lr((f=ia((c=ia(e.default_agent_workflows_unavailable))==null?void 0:c[t]))==null?void 0:f.reason)||`no default workflow for ${t}`};const o=Lr(s.bundle_id),l=Lr(s.flow_id);if(!o||!l)return{status:"unavailable",reason:"the gateway's default workflow is missing its bundle or flow"};const u=Lr(s.bundle_version);return{status:"ok",name:Lr(s.name)||l,bundleId:o,bundleVersion:u,flowId:l,workflowId:Lr(s.workflow_id)||`${o}${u?`@${u}`:""}:${l}`}}function ak(e,t,n={}){var c;const s=ia(e);if(!s)throw new Xa("The gateway's workflow list is not a JSON object.");const o=Lr(s.executable_for);if(t===null){if(o)throw new Xa(`Asked for every workflow, the gateway listed only ${o}.`)}else if(o!==t)throw new Xa(o?`The gateway listed workflows for ${o}, not ${t}.`:`This gateway does not filter workflows per app (no executable_for in its answer): ${kh}.`);if(!Array.isArray(s.items))throw new Xa("The gateway's workflow list has no items.");const l=[];for(const f of s.items){const m=ia(f),p=Lr(m==null?void 0:m.bundle_id);if(!m||!p)throw new Xa("The gateway listed a workflow without a bundle id.");const g=ia(m.owner),w=Lr(g==null?void 0:g.kind);if(w!=="gateway"&&w!=="user")throw new Xa(`The gateway did not say who owns ${p} (owner missing): ${kh}.`);if(typeof m.shipped!="boolean")throw new Xa(`The gateway did not say whether ${p} ships with it (shipped missing): ${kh}.`);const x=Lr(m.bundle_version),S=Array.isArray(m.entrypoints)?m.entrypoints:[];for(const j of S){const N=ia(j),C=Lr(N==null?void 0:N.flow_id);if(!N||!C)continue;const E=Array.isArray(N.interfaces)?N.interfaces.map(Lr).filter(Boolean):[];if(t===null){if(!E.length)continue}else if(!E.includes(t))throw new Xa(`The gateway offered ${p}:${C}, which does not declare ${t}: ${kh}.`);l.push({value:Lr(N.workflow_id)||`${p}${x?`@${x}`:""}:${C}`,bundleId:p,bundleVersion:x,flowId:C,name:Lr(N.name)||Lr((c=ia(m.metadata))==null?void 0:c.name)||p,description:Lr(N.description)||Lr(m.description),registryScope:Lr(m.registry_scope)||"private",group:w==="user"?"mine":"shared",shipped:m.shipped,interfaces:E,...t===null?{showInterfaces:!0}:{}})}}const u=n.defaultInterface??t;return{interfaceId:t,entries:l,gatewayDefault:u?ok(s,u):{status:"unavailable",reason:"no interface named for the gateway default"}}}function lk(e){const t=(n,s)=>n.name.localeCompare(s.name)||s.bundleVersion.localeCompare(n.bundleVersion,void 0,{numeric:!0})||n.value.localeCompare(s.value);return["shared","mine"].map(n=>({id:n,label:Jv[n],entries:e.filter(s=>s.group===n).sort(t)})).filter(n=>n.entries.length>0)}const ck={"abstractcode.agent.v1":"Code agent","abstractassistant.agent.v1":"Assistant","abstractcode.coding.v1":"Coding",tools:"tools",event:"event",chat:"chat"};function uk(e){return ck[e]??e}function dk(e,t=[]){const n=e.bundleVersion?`@${e.bundleVersion}`:"";return e.showInterfaces?[[...new Set(e.interfaces.map(uk))].join(", "),n].filter(Boolean).join(" · "):n}function fk(e){return e.value}function hk(e){return e?e.status==="unavailable"?e.reason:`${e.name}${e.bundleVersion?` @${e.bundleVersion}`:""}`:""}function mk(e,t,n){return n<=0?null:e==="ArrowDown"?t<0?0:Math.min(n-1,t+1):e==="ArrowUp"?t<0?n-1:Math.max(0,t-1):e==="Home"?0:e==="End"?n-1:null}function _k(e,t=!0){const n=(e==null?void 0:e.entries)??[],s=[];t&&s.push({key:"default",value:Kv,name:"Gateway default",detail:hk((e==null?void 0:e.gatewayDefault)??null),group:null,entry:null});for(const o of lk(n))for(const l of o.entries)s.push({key:l.value,value:l.value,name:l.name,detail:dk(l,n),title:fk(l),group:o.id,entry:l});return s}async function pk(e,t,n){var l;const s=await fetch(rg(e,wt(t)),{credentials:"include",headers:{Accept:"application/json"},signal:n}),o=await s.json().catch(()=>null);if(!s.ok){const u=((l=o==null?void 0:o.detail)==null?void 0:l.message)||(o==null?void 0:o.message)||(typeof(o==null?void 0:o.detail)=="string"?o.detail:"");throw new Error(u||`The gateway answered ${s.status}.`)}return o}function gk(e){var n;const t=e;return String(((n=t==null?void 0:t.detail)==null?void 0:n.message)||(t==null?void 0:t.message)||t||"The workflow list could not be loaded.")}function Xv(e){const{interfaceId:t,defaultInterface:n,allVersions:s=!1,enabled:o=!0,gatewayBaseUrl:l,reloadKey:u}=e,c=_.useRef(e.request);c.current=e.request;const[f,m]=_.useState(0),[p,g]=_.useState({status:"idle",data:null,error:""});_.useEffect(()=>{if(!o){g({status:"idle",data:null,error:""});return}const x=new AbortController;g(N=>({...N,status:"loading",error:""}));const S=ik(t,{allVersions:s});return(c.current?c.current(S,{signal:x.signal}):pk(l,S,x.signal)).then(N=>{x.signal.aborted||g({status:"ready",data:ak(N,t,{defaultInterface:n}),error:""})}).catch(N=>{x.signal.aborted||g({status:"error",data:null,error:gk(N)})}),()=>x.abort()},[t,n,s,o,l,u,f]);const w=_.useCallback(()=>m(x=>x+1),[]);return{...p,reload:w}}function yk(e){if(!e||typeof window>"u")return{};const t=e.getBoundingClientRect(),n=window.innerWidth,s=window.innerHeight,o=Math.min(Math.max(t.width,300),440,n-32),l=Math.max(16,Math.min(t.left,n-16-o)),u=s-t.bottom-16;return u>=220||u>=t.top?{position:"fixed",left:l,width:o,top:t.bottom+4,maxHeight:Math.max(160,u)}:{position:"fixed",left:l,width:o,bottom:s-t.top+4,maxHeight:Math.max(160,t.top-16)}}function Zv(...e){return e.filter(Boolean).join(" ")}function wk(e){const t=Xv({interfaceId:e.interfaceId,defaultInterface:e.defaultInterface,request:e.request,gatewayBaseUrl:e.gatewayBaseUrl,allVersions:e.allVersions,enabled:e.workflows?!1:e.enabled!==!1}),n=e.workflows??t,s=e.showDefault!==!1&&(e.interfaceId!==null||!!e.defaultInterface),o=_.useId().replace(/:/g,""),l=`${o}-list`,[u,c]=_.useState(!1),[f,m]=_.useState(-1),p=_.useRef(null),g=_.useRef(null),[w,x]=_.useState({}),S=_.useMemo(()=>_k(n.data,s),[n.data,s]),j=S.find(J=>J.value===e.value),N=j?{name:j.name,detail:j.detail}:e.currentLabel?{name:e.currentLabel.name,detail:e.currentLabel.detail||""}:n.status==="loading"?{name:"Loading workflows…",detail:""}:{name:e.value===Kv?"Gateway default":"Choose a workflow",detail:""},C=String(e.unavailableReason||"").trim(),E=!C&&n.status==="ready",T=_.useCallback(()=>{c(!1),m(-1)},[]),I=_.useCallback(()=>{if(!E)return;x(yk(g.current)),c(!0);const J=S.findIndex(Y=>Y.value===e.value);m(J>=0?J:0)},[E,S,e.value]),K=_.useCallback(J=>{var Y;T(),J.value!==e.value&&e.onChange(J.value,J.entry),(Y=g.current)==null||Y.focus()},[T,e]);_.useEffect(()=>{if(!u)return;const J=se=>{p.current&&!p.current.contains(se.target)&&T()},Y=()=>T();return document.addEventListener("mousedown",J),document.addEventListener("touchstart",J),window.addEventListener("resize",Y),()=>{document.removeEventListener("mousedown",J),document.removeEventListener("touchstart",J),window.removeEventListener("resize",Y)}},[u,T]),_.useEffect(()=>{var Y;if(!u||f<0)return;const J=typeof document<"u"?document.getElementById(`${o}-opt-${f}`):null;(Y=J==null?void 0:J.scrollIntoView)==null||Y.call(J,{block:"nearest"})},[u,f,o]);const U=J=>{if(!u){["Enter"," ","ArrowDown","ArrowUp"].includes(J.key)&&(J.preventDefault(),I());return}if(J.key==="Escape"){J.preventDefault(),T();return}if(J.key==="Tab"){T();return}if(J.key==="Enter"||J.key===" "){J.preventDefault(),f>=0&&S[f]&&K(S[f]);return}const Y=mk(J.key,f,S.length);Y!==null&&(J.preventDefault(),m(Y))};return r.jsxs("div",{ref:p,className:Zv("af-workflow-picker",e.className),"data-interface":e.interfaceId??"any",children:[r.jsxs("button",{ref:g,id:e.id,type:"button",role:"combobox",className:"af-workflow-picker__trigger","aria-label":e.ariaLabel||"Workflow","aria-describedby":`${o}-value`,"aria-haspopup":"listbox","aria-expanded":u,"aria-controls":l,"aria-activedescendant":u&&f>=0?`${o}-opt-${f}`:void 0,"aria-disabled":E?void 0:!0,title:C||void 0,onClick:()=>u?T():I(),onKeyDown:U,children:[r.jsxs("span",{className:"af-workflow-picker__value",id:`${o}-value`,children:[r.jsx("span",{className:"af-workflow-picker__name",children:N.name}),N.detail?r.jsx("span",{className:"af-workflow-picker__detail",children:N.detail}):null]}),r.jsx("span",{className:"af-workflow-picker__caret","aria-hidden":"true"})]}),u?r.jsx(vk,{id:l,idBase:o,rows:S,value:e.value,highlight:f,ariaLabel:e.ariaLabel||"Workflow",style:w,onHighlight:m,onChoose:K}):null,n.status==="error"?r.jsx("span",{className:"af-workflow-picker__error",role:"alert",children:n.error}):n.status==="ready"&&S.every(J=>!J.entry)&&!s?r.jsx("span",{className:"af-workflow-picker__empty",role:"status",children:Yv}):null]})}function vk(e){const t=(l,u)=>r.jsxs("div",{id:`${e.idBase}-opt-${u}`,role:"option","aria-selected":l.value===e.value,"data-value":l.value,title:l.title,className:Zv("af-workflow-picker__option",u===e.highlight&&"af-workflow-picker__option--highlighted",l.value===e.value&&"af-workflow-picker__option--selected"),onMouseEnter:()=>e.onHighlight(u),onMouseDown:c=>c.preventDefault(),onClick:()=>e.onChoose(l),children:[r.jsx("span",{className:"af-workflow-picker__name",children:l.name}),l.detail?r.jsx("span",{className:"af-workflow-picker__detail",children:l.detail}):null]},l.key),n=e.rows.map((l,u)=>({row:l,index:u})),s=n.filter(l=>l.row.group===null),o=["shared","mine"].map(l=>({g:l,items:n.filter(u=>u.row.group===l)})).filter(l=>l.items.length>0);return r.jsxs("div",{id:e.id,role:"listbox","aria-label":e.ariaLabel,className:"af-workflow-picker__list",style:e.style,children:[s.map(l=>t(l.row,l.index)),o.map(({g:l,items:u})=>r.jsxs("div",{role:"group","aria-labelledby":`${e.idBase}-g-${l}`,"data-group":l,children:[r.jsx("div",{id:`${e.idBase}-g-${l}`,className:"af-workflow-picker__group",role:"presentation",children:Jv[l]}),u.map(c=>t(c.row,c.index))]},l)),o.length===0?r.jsx("p",{className:"af-workflow-picker__empty",children:Yv}):null]})}function Em(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 xk(e){if(e==null)return"";if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}}function bk(e){const t=String(e.role||"message").trim()||"message",n=String(e.title||"").trim(),s=String(e.ts||"").trim(),o=[t];return n&&o.push(n),s&&o.push(s),o.join(" · ")}function jk(e){return e.endsWith(`
58
- `)?e:`${e}
59
- `}function Sk(e){return String(e||"").trimStart().startsWith("```")}function kk(e,t){const s=[`# ${String((t==null?void 0:t.heading)||"Chat").trim()||"Chat"}`,""];for(const o of e){const l=bk(o);s.push(`## ${l}`,"");const u=String(o.content||""),c=Em(u);c!==null&&!Sk(u)?s.push("```json",xk(c).trimEnd(),"```",""):s.push(jk(u).trimEnd(),""),s.push("---","")}for(;s.length&&!s[s.length-1].trim();)s.pop();return s.length&&s[s.length-1]==="---"&&s.pop(),`${s.join(`
60
- `).trimEnd()}
61
- `}async function sc(e){var n;const t=String(e||"");if(!t)return!1;try{if(typeof navigator<"u"&&typeof((n=navigator.clipboard)==null?void 0:n.writeText)=="function")return await navigator.clipboard.writeText(t),!0}catch{}try{const s=document.createElement("textarea");s.value=t,s.style.position="fixed",s.style.left="-9999px",document.body.appendChild(s),s.select();const o=document.execCommand("copy")===!0;return document.body.removeChild(s),o}catch{return!1}}function Nk(e){const t=String(e.filename||"").trim()||"export.txt",n=String(e.text||""),s=String(e.mime),o=new Blob([n],{type:s}),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 Ck=3,Ek=Number.MAX_SAFE_INTEGER;function Qv(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function ex(e){return Array.isArray(e)}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 du({kind:e,children:t}){return r.jsx("span",{className:`pc-json-token ${e}`,children:t})}function Ak(e){const t=JSON.stringify(e.value),n=t.length>96||t.includes("\\n")||t.includes("\\r")||t.includes("\\t"),[s,o]=_.useState(!n||e.expansionMode==="unfolded");return _.useEffect(()=>{n&&o(e.expansionMode==="unfolded")},[n,e.expansionMode,e.expansionVersion]),n?r.jsxs("span",{className:`pc-json-string ${s?"open":"collapsed"}`,children:[r.jsx("button",{type:"button",className:"pc-json-string__toggle",onClick:()=>o(l=>!l),"aria-label":s?"Collapse string value":"Expand string value","aria-expanded":s,children:s?"▾":"▸"}),s?r.jsx("span",{className:"pc-json-token string pc-json-string__value",children:t}):r.jsxs("button",{type:"button",className:"pc-json-string__preview",onClick:()=>o(!0),"aria-label":"Expand string value",children:[r.jsx("span",{className:"pc-json-token string pc-json-string__preview_text",children:t}),r.jsx("span",{className:"pc-json-string__suffix",children:"(...)"})]})]}):r.jsx(du,{kind:"string",children:t})}function Tk(e,t,n){return e===null?r.jsx(du,{kind:"null",children:"null"}):typeof e=="string"?r.jsx(Ak,{value:e,expansionMode:t,expansionVersion:n}):typeof e=="number"?r.jsx(du,{kind:"number",children:String(e)}):typeof e=="boolean"?r.jsx(du,{kind:"boolean",children:e?"true":"false"}):r.jsx(du,{kind:"string",children:JSON.stringify(String(e))})}function Mk(e){return ex(e)?e.length===1?"1 item":`${e.length} items`:Qv(e)?Object.keys(e).length===1?"1 key":`${Object.keys(e).length} keys`:""}function tx(e){const{label:t,value:n,depth:s,collapseAfterDepth:o,expansionMode:l,expansionVersion:u,trailingComma:c}=e,f=s*14,m=Qv(n),p=ex(n),g=m||p,w=s<o,[x,S]=_.useState(w);_.useEffect(()=>{S(w)},[w,u]);const j=t?r.jsxs(r.Fragment,{children:[r.jsx(du,{kind:"key",children:JSON.stringify(t)}),": "]}):null;if(!g)return r.jsxs("div",{className:"pc-json-viewer__line",style:{paddingLeft:f},children:[j,Tk(n,l,u),c?",":""]});const N=p?"[":"{",C=p?"]":"}",E=Mk(n),T=x?`${N}`:`${N}…${C}${E?` (${E})`:""}`,I=p?n.map((K,U)=>({key:String(U),label:void 0,value:K})):Object.entries(n).map(([K,U])=>({key:K,label:K,value:U}));return r.jsxs("details",{className:"pc-json-viewer__details",open:x,onToggle:K=>S(K.currentTarget.open),children:[r.jsxs("summary",{className:"pc-json-viewer__summary",style:{paddingLeft:f},children:[j,r.jsx("span",{className:"pc-json-viewer__caret","aria-hidden":"true",children:x?"▾":"▸"}),r.jsx("span",{className:"pc-json-viewer__punct",children:T}),!x&&c?r.jsx("span",{className:"pc-json-viewer__punct",children:","}):null]}),x?r.jsx("div",{className:"pc-json-viewer__children",children:I.length===0?r.jsxs("div",{className:"pc-json-viewer__line",style:{paddingLeft:f},children:[r.jsx("span",{className:"pc-json-viewer__punct",children:C}),c?",":""]}):r.jsxs(r.Fragment,{children:[I.map((K,U)=>{const J=U===I.length-1;return r.jsx(tx,{label:K.label,value:K.value,depth:s+1,collapseAfterDepth:o,expansionMode:l,expansionVersion:u,trailingComma:!J},`${s}:${t||"root"}:${K.key}`)}),r.jsxs("div",{className:"pc-json-viewer__line",style:{paddingLeft:f},children:[r.jsx("span",{className:"pc-json-viewer__punct",children:C}),c?",":""]})]})}):null]})}function Rk(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 Ir(e){const{value:t,className:n,showCopy:s=!0}=e,[o,l]=_.useState({mode:"folded",version:0}),[u,c]=_.useState("idle"),f=typeof e.collapseAfterDepth=="number"&&(Number.isFinite(e.collapseAfterDepth)||e.collapseAfterDepth===1/0)&&e.collapseAfterDepth>=0?e.collapseAfterDepth===1/0?Number.MAX_SAFE_INTEGER:Math.trunc(e.collapseAfterDepth):Ck,m=o.mode==="unfolded"?Ek:f,p=_.useMemo(()=>typeof t=="string"?Rk(t):t,[t]),g=_.useMemo(()=>$k(t),[t]),w=["pc-json-viewer",n].filter(Boolean).join(" ");_.useEffect(()=>{l(S=>({mode:"folded",version:S.version+1}))},[p]);const x=()=>{l(S=>({mode:S.mode==="unfolded"?"folded":"unfolded",version:S.version+1}))};return r.jsxs("div",{className:w,children:[r.jsxs("div",{className:"pc-json-viewer__toolbar",children:[r.jsx("button",{type:"button",className:"pc-btn pc-json-viewer__toggle-all",onClick:x,"aria-expanded":o.mode==="unfolded",children:o.mode==="unfolded"?"Fold all":"Unfold all"}),s?r.jsx("button",{type:"button",className:"pc-btn pc-json-viewer__copy",onClick:()=>void sc(g).then(S=>{c(S?"copied":"failed"),window.setTimeout(()=>c("idle"),2e3)}),children:u==="copied"?"Copied":u==="failed"?"Copy failed — select and copy":"Copy JSON"}):null]}),r.jsx("div",{className:"pc-json-viewer__tree",role:"tree","aria-label":"JSON viewer",children:r.jsx(tx,{value:p,depth:0,collapseAfterDepth:m,expansionMode:o.mode,expansionVersion:o.version,trailingComma:!1})})]})}function Ud(e,t){const n=String(e??"");if(!t||!t.needles.length)return[n];const s=[],o=n.toLowerCase();let l=0;for(;l<n.length;){let u=-1,c="";for(let p=0;p<t.needlesLower.length;p++){const g=t.needlesLower[p];if(!g)continue;const w=o.indexOf(g,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){s.push(n.slice(l));break}u>l&&s.push(n.slice(l,u));const f=t.hits===0&&t.id?t.id:void 0,m=n.slice(u,u+c.length);s.push(r.jsx("span",{id:f,className:t.className,children:m},`hl:${t.hits}`)),t.hits+=1,l=u+c.length}return s}function nx(e){const t=String(e||"").trim();if(t&&/^(https?:|mailto:|tel:|#|\/)/i.test(t))return t}const xp="http://same-origin.invalid/";function Lk(e){try{const t=new URL(e,xp);return t.protocol==="http:"&&t.origin===new URL(xp).origin}catch{return!1}}function rx(e){const t=String(e||"").trim();return nx(t)??(t&&Lk(t)?t:void 0)}let Zl=null;function Ik(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 s=n??xp;let o,l;try{o=new URL(s).origin,l=new URL(t,s)}catch{return!1}return l.protocol!=="http:"&&l.protocol!=="https:"?!1:l.origin===o}function sx(e,t,n){return r.jsx("a",{className:"pc-md_link pc-md_image_link",href:t,target:"_blank",rel:"noopener noreferrer",children:`image: ${n||t}`},e)}function nl(e,t){const n=[],s=String(e??"");let o=0,l="";const u=()=>{if(l){for(const c of Ud(l,t))n.push(c);l=""}};for(;o<s.length;){const c=s[o];if(c==="!"&&s[o+1]==="["){const f=s.indexOf("]",o+2);if(f!==-1&&s[f+1]==="("){const m=s.indexOf(")",f+2);if(m!==-1){const p=s.slice(o+2,f),g=rx(s.slice(f+2,m));if(g&&Zl&&!Zl(g)){u(),n.push(sx(`img:${o}`,g,p)),o=m+1;continue}if(g){u(),n.push(r.jsxs("span",{className:"pc-md_image_inline",children:[r.jsx("img",{className:"pc-md_img",src:g,alt:p,loading:"lazy"}),p?r.jsx("span",{className:"pc-md_img_caption",children:t?Ud(p,t):p}):null]},`img:${o}`)),o=m+1;continue}}}}if(c==="["){const f=s.indexOf("]",o+1);if(f!==-1&&s[f+1]==="("){const m=s.indexOf(")",f+2);if(m!==-1){const p=s.slice(o+1,f),g=nx(s.slice(f+2,m));if(g){u(),n.push(r.jsx("a",{className:"pc-md_link",href:g,target:g.startsWith("#")?void 0:"_blank",rel:"noreferrer",children:nl(p,t)},`link:${o}`)),o=m+1;continue}}}}if(c==="`"){const f=s.indexOf("`",o+1);if(f!==-1){u();const m=s.slice(o+1,f);n.push(r.jsx("code",{children:t?Ud(m,t):m},`code:${o}`)),o=f+1;continue}}if(c==="*"&&s[o+1]==="*"){const f=s.indexOf("**",o+2);if(f!==-1){u();const m=s.slice(o+2,f);n.push(r.jsx("strong",{children:t?Ud(m,t):m},`bold:${o}`)),o=f+2;continue}}if(c==="*"&&s[o+1]!=="*"){const f=s.indexOf("*",o+1);if(f!==-1){u();const m=s.slice(o+1,f);n.push(r.jsx("em",{children:t?Ud(m,t):m},`em:${o}`)),o=f+1;continue}}l+=c,o+=1}return u(),n}function Pk(e){return String(e??"").replace(/\r\n/g,`
62
- `).replace(/\r/g,`
63
- `).split(`
64
- `)}function Yh(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 Ok(e){const t=[];for(const o of e){const l=Yh(o);l?t.push(l):t.length>0&&o.trim()&&(t[t.length-1].content+=` ${o.trim()}`)}const n=[],s=[];for(const o of t){for(;s.length>0&&o.indent<s[s.length-1].indent;)s.pop();let l=s.length>0?s[s.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),s.push({indent:o.indent,node:f}),l=s[s.length-1]}}else if(l&&l.node.ordered!==o.ordered){s.pop();const u=s.length>0?s[s.length-1]:null,c={ordered:o.ordered,start:o.start,items:[]};if(u){const f=u.node.items,m=f[f.length-1];m?m.children.push(c):u.node.items.push({content:"",children:[c]})}else n.push(c);s.push({indent:o.indent,node:c}),l=s[s.length-1]}if(!l){const u={ordered:o.ordered,start:o.start,items:[]};n.push(u),s.push({indent:o.indent,node:u}),l=s[s.length-1]}l.node.items.push({content:o.content,children:[]})}return n}function ix(e,t,n){const s=e.items.map((o,l)=>r.jsxs("li",{children:[nl(o.content,t),o.children.map((u,c)=>ix(u,t,`${n}:${l}:${c}`))]},`${n}:li:${l}`));return e.ordered?r.jsx("ol",{className:"pc-md_ol",start:e.start!==1?e.start:void 0,children:s},n):r.jsx("ul",{className:"pc-md_ul",children:s},n)}function Dk(e,t,n){return Ok(e).map((s,o)=>ix(s,t,`${n}:${o}`))}function by(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 jy(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(s=>String(s??"").trim());return n.length<2?!1:n.every(s=>/^:?-{3,}:?$/.test(s))}const Sy=/^(#{1,5})\s+(.*)$/;function ky(e){return e.trim().startsWith("```")}function Ny(e){return e.trimStart().startsWith(">")}function Wi(e){const t=Zl;Zl=e.images==="link"?e.inlineImage||Ik:null;try{return Fk(e)}finally{Zl=t}}function Fk({text:e,className:t,highlight:n,highlights:s,highlightClassName:o,highlightId:l}){const u=Pk(e),c=[],f=[];Array.isArray(s)&&f.push(...s),typeof n=="string"&&n.trim()&&f.push(n);const m=Array.from(new Set(f.map(x=>String(x??"").trim()).filter(Boolean))).filter(x=>x.length>=4),p=m.length?{needles:m,needlesLower:m.map(x=>x.toLowerCase()),className:o||"pc-md_hl",id:l,hits:0}:null;let g=0;for(;g<u.length;){const x=String(u[g]??"");if(!x.trim()){g+=1;continue}const S=x.trim();if(/^([-_*])(\s*\1){2,}$/.test(S)){c.push(r.jsx("hr",{className:"pc-md_hr"},`hr:${g}`)),g+=1;continue}const j=x.match(/^\s*!\[([^\]]*)\]\(([^)]+)\)\s*$/);if(j){const E=rx(j[2]||"");if(E&&Zl&&!Zl(E)){c.push(r.jsx("p",{className:"pc-md_p",children:sx(`img:${g}`,E,j[1]||"")},`p:${g}`)),g+=1;continue}if(E){const T=j[1]||"";c.push(r.jsxs("figure",{className:"pc-md_figure",children:[r.jsx("img",{className:"pc-md_img",src:E,alt:T,loading:"lazy"}),T?r.jsx("figcaption",{children:nl(T,p)}):null]},`figure:${g}`)),g+=1;continue}}if(ky(x)){const T=x.trim().replace(/```/g,"").trim(),I=[];for(g+=1;g<u.length&&!String(u[g]??"").trim().startsWith("```");)I.push(String(u[g]??"")),g+=1;g<u.length&&(g+=1);const K=I.join(`
65
- `);c.push(r.jsx("pre",{className:"pc-md_pre",children:r.jsx("code",{className:T?`language-${T}`:void 0,children:K})},`pre:${g}`));continue}const N=x.match(Sy);if(N){const E=N[1].length,T=N[2]||"",I=nl(T,p);E===1?c.push(r.jsx("h1",{children:I},`h1:${g}`)):E===2?c.push(r.jsx("h2",{children:I},`h2:${g}`)):E===3?c.push(r.jsx("h3",{children:I},`h3:${g}`)):E===4?c.push(r.jsx("h4",{children:I},`h4:${g}`)):c.push(r.jsx("h5",{children:I},`h5:${g}`)),g+=1;continue}if(Ny(x)){const E=[];for(;g<u.length&&String(u[g]??"").trimStart().startsWith(">");){const I=String(u[g]??"").trimStart();E.push(I.replace(/^>\s?/,"")),g+=1}c.push(r.jsx("blockquote",{className:"pc-md_quote",children:E.map((T,I)=>r.jsxs(ve.Fragment,{children:[nl(T,p),I<E.length-1?r.jsx("br",{}):null]},`q:${g}:${I}`))},`quote:${g}`));continue}if(x.includes("|")&&g+1<u.length&&jy(String(u[g+1]??""))){const E=by(x),T=Math.max(1,E.length),I=[];for(g+=2;g<u.length;){const K=String(u[g]??"");if(!K.trim()||!K.includes("|"))break;const U=by(K),J=[];for(let Y=0;Y<T;Y++)J.push(U[Y]??"");I.push(J),g+=1}c.push(r.jsx("div",{className:"pc-md_table_wrap",children:r.jsxs("table",{className:"pc-md_table",children:[r.jsx("thead",{children:r.jsx("tr",{children:E.slice(0,T).map((K,U)=>r.jsx("th",{children:nl(K,p)},`th:${g}:${U}`))})}),r.jsx("tbody",{children:I.map((K,U)=>r.jsx("tr",{children:K.map((J,Y)=>r.jsx("td",{children:nl(J,p)},`td:${g}:${U}:${Y}`))},`tr:${g}:${U}`))})]})},`table:${g}`));continue}if(Yh(x)){const E=[];for(;g<u.length;){const T=String(u[g]??"");if(!T.trim()||T.trimStart().startsWith("```"))break;if(Yh(T)||/^\s{2,}\S/.test(T)){E.push(T),g+=1;continue}break}c.push(r.jsx(ve.Fragment,{children:Dk(E,p,`list:${g}`)},`list:${g}`));continue}const C=[];for(;g<u.length&&String(u[g]??"").trim()&&!(C.length>0&&Yh(String(u[g]??"")));){const E=String(u[g]??"");if(C.length>0&&(Sy.test(E)||ky(E)||Ny(E))||C.length>0&&E.includes("|")&&g+1<u.length&&jy(String(u[g+1]??"")))break;C.push(E),g+=1}c.push(r.jsx("p",{className:"pc-md_p",children:C.map((E,T)=>r.jsxs(ve.Fragment,{children:[nl(E,p),T<C.length-1?r.jsx("br",{}):null]},`pl:${g}:${T}`))},`p:${g}`))}const w=["pc-md",t].filter(Boolean).join(" ");return r.jsx("div",{className:w,children:c})}function ox(e){const t=String(e.text??""),n=_.useMemo(()=>Em(t),[t]),s=["pc-chat-content",e.className].filter(Boolean).join(" ");return n!==null?r.jsx("div",{className:s,children:r.jsx(Ir,{value:n,collapseAfterDepth:e.jsonCollapseAfterDepth})}):e.renderMarkdown?r.jsx("div",{className:s,children:e.renderMarkdown(t)}):r.jsx("div",{className:s,children:r.jsx(Wi,{text:t,images:e.images,inlineImage:e.inlineImage})})}function ax(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}}function zk(e){const t=ax(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 lx({tool:e,showCopy:t=!0}){const[n,s]=_.useState(!1),o=ax(e.arguments),l=zk(e.arguments),u=["file path","path"].includes(l.label)&&l.value.length>60?`${l.value.split(/[\\/]/).pop()} · ${l.value.slice(0,24)}…`:l.value,c=e.error&&/^File ['"].+['"] does not exist\.?$/.test(e.error)?"File not found. Expand for the exact path.":e.error&&e.error.length>180?`${e.error.slice(0,100)}…${e.error.slice(-70)}`:e.error,f={running:"Running",waiting:"Approval needed",completed:"Done",failed:"Failed"},m=e.startedAt&&e.endedAt?Date.parse(e.endedAt)-Date.parse(e.startedAt):NaN,p=o&&typeof o=="object"&&!Array.isArray(o)?Object.entries(o):null;return r.jsxs("details",{className:`pc-tool-activity pc-tool-activity--${e.status}`,children:[r.jsxs("summary",{className:"pc-tool-activity__summary",children:[r.jsx("span",{className:"pc-tool-activity__state-icon","aria-hidden":"true",children:r.jsx(et,{name:e.status==="completed"?"check":e.status==="failed"?"x":e.status==="waiting"?"warning":"loader",size:15})}),r.jsx("strong",{children:e.name}),r.jsx("span",{className:"pc-tool-activity__preview",title:l.value,children:l.value?r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"pc-tool-activity__key",children:l.label}),u]}):"No parameters"}),r.jsx("span",{className:"pc-tool-activity__status",children:f[e.status]}),Number.isFinite(m)&&m>=0?r.jsxs("span",{className:"pc-tool-activity__duration",children:[(m/1e3).toFixed(1),"s"]}):null,r.jsx("span",{className:"pc-tool-activity__chevron","aria-hidden":"true",children:r.jsx(et,{name:"chevronRight",size:13})}),e.error?r.jsx("span",{className:"pc-tool-activity__error",title:e.error,children:c}):null]}),r.jsxs("div",{className:"pc-tool-activity__detail",children:[e.error?r.jsxs(r.Fragment,{children:[r.jsx("h4",{children:"Error"}),r.jsx("pre",{className:"pc-tool-activity__output",children:e.error})]}):null,r.jsxs("div",{className:"pc-tool-activity__detail-heading",children:[r.jsx("h4",{children:"Parameters"}),t?r.jsxs("button",{type:"button",onClick:async()=>s(await sc(JSON.stringify(e,null,2))),children:[r.jsx(et,{name:"copy",size:13}),n?"Copied":"Copy details"]}):null]}),p?r.jsx("dl",{className:"pc-tool-activity__parameters",children:p.map(([g,w])=>r.jsxs(ve.Fragment,{children:[r.jsx("dt",{children:g}),r.jsx("dd",{children:w&&typeof w=="object"?r.jsx(Ir,{value:w}):r.jsx("code",{children:typeof w=="string"?w:JSON.stringify(w)})})]},g))}):e.arguments===void 0?r.jsx("p",{children:"Arguments are unavailable in this ledger."}):r.jsx(Ir,{value:o}),e.output!==void 0?r.jsxs(r.Fragment,{children:[r.jsx("h4",{children:"Result"}),typeof e.output=="string"?r.jsx("pre",{className:"pc-tool-activity__output",children:e.output}):r.jsx("div",{className:"pc-tool-activity__output",children:r.jsx(Ir,{value:e.output})})]}):null]})]})}function cx({tools:e,showCopy:t}){const n=s=>e.filter(o=>o.status===s).length;return r.jsxs("section",{className:"pc-tool-group","aria-label":"Tool activity",children:[r.jsxs("div",{className:"pc-tool-group__heading",children:[r.jsx(et,{name:"terminal",size:14}),r.jsx("strong",{children:"Tools"}),r.jsxs("span",{children:[e.length," ",e.length===1?"call":"calls"]}),r.jsx("div",{}),n("running")?r.jsxs("span",{className:"pc-tool-group__running",children:[n("running")," running"]}):null,n("waiting")?r.jsxs("span",{className:"pc-tool-group__waiting",children:[n("waiting")," need approval"]}):null,n("failed")?r.jsxs("span",{className:"pc-tool-group__failed",children:[n("failed")," failed"]}):null,n("completed")?r.jsxs("span",{className:"pc-tool-group__completed",children:[n("completed")," done"]}):null]}),e.map(s=>r.jsx(lx,{tool:s,showCopy:t},s.id))]})}const Gr="not reported",ks=e=>e===void 0?Gr:Math.round(e).toLocaleString(),Bs=e=>{if(e===void 0)return Gr;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`},ux=e=>e===void 0?Gr:`${Math.round(e).toLocaleString()} tok/s`,Bk=(e,t)=>t>0?`${Math.round(e/t*100)}%`:"",Ql=(e,t,n=`${t}s`)=>`${e.toLocaleString()} ${e===1?t:n}`,Uk=e=>{const t=e.split("#")[0].replace(/\/+$/,"");return t.slice(t.lastIndexOf("/")+1)||e};function Wk(e){const t=new Map;for(const n of e)n&&t.set(n,(t.get(n)||0)+1);return[...t].map(([n,s])=>s>1?`${n} ×${s}`:n).join(" · ")}function am(e){const t=[],n=(e.models||[]).map(Uk),s=e.providers||[];return(n.length||s.length)&&t.push([n.join(", ")||"model not reported",s.join(", ")].filter(Boolean).join(" · ")),t.push("From the run ledger; summed across this turn and its child runs."),t}function qk(e){const t=e.modelCalls||[],n=[],s=[{label:"Input",value:ks(e.inputTokens)},{label:"Output",value:ks(e.outputTokens)}];if(e.reasoningTokens!==void 0&&s.push({label:"Reasoning",value:ks(e.reasoningTokens),hint:"part of output"}),s.push({label:"Total",value:ks(e.totalTokens)}),n.push({heading:`Usage · ${Ql(e.llmCalls,"model call")}`,rows:s}),e.measuredCacheCalls){const l=e.cachedTokens||0,u=e.fedTokens||0,c=[{label:"Reused from cache",value:`${ks(l)}${l+u?` (${Bk(l,l+u)})`:""}`},{label:"Newly processed",value:ks(e.fedTokens)},{label:"Outcome",value:Wk(t.map(f=>f.cacheOutcome))||(e.cacheOutcomes||[]).join(" · ")||Gr},{label:"Backend",value:(e.cacheBackends||[]).join(", ")||Gr}];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:Gr}]});const o=t.filter(l=>l.inputTokens!==void 0);return o.length===1&&t.length===1?n.push({heading:"Context",rows:[{label:"Prompt size",value:`${ks(o[0].inputTokens)} tokens`}]}):o.length>1&&n.push({heading:"Context",rows:[{label:"First → last call",value:`${ks(o[0].inputTokens)} → ${ks(o[o.length-1].inputTokens)} tokens`}],note:"Each call re-sends the conversation, so the input total counts the context once per call."}),t.length>1&&n.push({heading:"Per call",table:{columns:["#","Input","Cached","New","Output","Cache"],rows:t.map((l,u)=>[String(u+1),ks(l.inputTokens),l.cachedTokens===void 0?"—":ks(l.cachedTokens),l.fedTokens===void 0?"—":ks(l.fedTokens),ks(l.outputTokens),l.cacheOutcome||"—"])}}),{kind:"tokens",title:"Tokens",headline:e.totalTokens===void 0?Gr:`${e.totalTokens.toLocaleString()} total`,sections:n,footer:am(e)}}function Nh(e,t,n,s){if(e===void 0)return Gr;const o=[Bs(e)];return t!==void 0&&o.push(`${t.toLocaleString()} ${s}${n!==void 0?` at ${ux(n)}`:""}`),o.join(" · ")}function Hk(e){var m,p,g;const t=e.modelCalls||[],n=[],s=e.durationMs,o=[{label:"Wall clock",value:Bs(s)}];if(o.push({label:"Model",value:e.genTimeMs===void 0?Gr:`${Bs(e.genTimeMs)} · ${Ql(e.timedCalls||0,"call")}${e.timedCalls!==e.llmCalls?` (of ${e.llmCalls})`:""}`}),o.push({label:"Tools",value:e.toolTimeMs!==void 0?`${Bs(e.toolTimeMs)} · ${Ql(e.toolBatches||0,"batch","batches")}`:e.toolCalls?Gr:"none",hint:e.toolTimeIncludesApproval?"includes approval wait":void 0}),s!==void 0&&e.genTimeMs!==void 0){const w=s-e.genTimeMs-(e.toolTimeMs||0);o.push({label:"Orchestration",value:w>=0?Bs(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:Nh(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:Nh(e.prefillMs,e.prefillNewTokens,e.prefillNewTokensPerSecond,"new tok"),hint:"derived: prompt ÷ provider rate"}):e.prefillMs!==void 0?l.push({label:"Prefill",value:`${Bs(e.prefillMs)}${e.promptTokensPerSecond!==void 0?` at ${ux(e.promptTokensPerSecond)}`:""}`,hint:"provider rate over all prompt tokens, restored included"}):l.push({label:"Prefill",value:Gr}),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?Nh(e.generationPhaseMs,e.generationPhaseTokens,e.generationPhaseTokensPerSecond,"tok"):Nh(e.decodeMs,e.outputTokens,e.generationTokensPerSecond,"tok")}),e.measuredSpeedCalls&&e.measuredSpeedCalls!==e.llmCalls&&l.push({label:"Speeds from",value:`${e.measuredSpeedCalls} of ${e.llmCalls} calls`}),n.push({heading:"Model",rows:l});const f=e.speculation;if(f){const w=(f.draftKinds||[]).map(S=>S.toUpperCase()).join(", "),x=[{label:"Mode",value:`${f.used?"on":"off"}${w?` · ${w}`:""}${(m=f.modes)!=null&&m.length?` (${f.modes.join(", ")})`:""}`,hint:f.calls!==e.llmCalls||f.used!==f.calls?`used on ${f.used} of ${e.llmCalls} calls`:void 0},{label:"Acceptance",value:f.acceptanceRate===void 0?Gr:`${Math.round(f.acceptanceRate*100)}% · ${ks(f.acceptedTokens)} of ${ks(f.draftedTokens)} drafted`}];((p=f.draftLengths)!=null&&p.length||f.rounds!==void 0)&&x.push({label:"Draft length",value:`${(g=f.draftLengths)!=null&&g.length?`${f.draftLengths.join("/")} tok/round`:Gr}${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:`${Bs(e.toolTimeMs)} · ${Ql(e.toolBatches||0,"batch","batches")}`},{label:"Slowest",value:`${Bs(e.slowestToolBatch.ms)} · ${dx(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?"—":`${Bs(w.promptMs)}${w.promptSource==="rate"?"*":""}`,w.promptNewTokensPerSecond===void 0?"—":Math.round(w.promptNewTokensPerSecond).toLocaleString(),w.generationMs===void 0?"—":Bs(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:s===void 0?Gr:`${Bs(s)} wall clock`,sections:n,footer:am(e)}}function dx(e){return e.tools.length===1?`${e.tools[0]} ×${e.calls}`:`${Ql(e.calls,"call")} (${e.tools.join(", ")})`}function Vk(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:am(e)};const s=[{label:"Succeeded",value:(e.toolCalls-(e.toolsFailed||0)).toLocaleString()},{label:"Failed",value:(e.toolsFailed||0).toLocaleString()}];e.toolsRunning&&s.push({label:"Running",value:e.toolsRunning.toLocaleString()}),e.toolsWaiting&&s.push({label:"Awaiting approval",value:e.toolsWaiting.toLocaleString(),hint:"not run yet — not a failure"}),t.push({heading:"Outcome",rows:s});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?`${Bs(f.ms)}${f.sharedBatches?" +shared":""}`:f.sharedBatches?"shared":Gr])},note:o.some(([,c])=>c.sharedBatches)?"A batch that mixed tools ran them together; its time is not split between them.":void 0});const l=o.filter(([,c])=>c.errors&&Object.keys(c.errors).length);l.length&&t.push({heading:"Failures",rows:l.map(([c,f])=>({label:c,value:Object.entries(f.errors).sort((m,p)=>p[1]-m[1]).map(([m,p])=>p>1?`${m} ×${p}`:m).join(" · ")}))});const u=[{label:"Tool time",value:e.toolTimeMs===void 0?Gr:`${Bs(e.toolTimeMs)} · ${Ql(e.toolBatches||0,"batch","batches")}`}];return e.slowestToolBatch&&u.push({label:"Slowest batch",value:`${Bs(e.slowestToolBatch.ms)} · ${dx(e.slowestToolBatch)}`}),t.push({heading:"Timing",rows:u,note:e.toolTimeIncludesApproval?"Gated calls are timed from request to result, so this includes waiting for your approval.":void 0}),{kind:"tools",title:"Tools",headline:`${Ql(e.toolCalls,"call")}${e.toolsFailed?` · ${e.toolsFailed} failed`:""}`,sections:t,footer:am(e)}}function k_(e,t){return e==="tokens"?qk(t):e==="time"?Hk(t):Vk(t)}function Gk(e){const t=e.detail;return r.jsxs("div",{ref:e.panelRef,id:e.id,role:"tooltip",className:`pc-stat-detail pc-stat-detail--${t.kind}`,style:e.style,onMouseEnter:e.onMouseEnter,onMouseLeave:e.onMouseLeave,children:[r.jsxs("div",{className:"pc-stat-detail-head",children:[r.jsx("span",{className:"pc-stat-detail-title",children:t.title}),r.jsx("span",{className:"pc-stat-detail-headline",children:t.headline})]}),t.sections.map(n=>{var s;return r.jsxs("div",{className:"pc-stat-detail-section",children:[r.jsx("div",{className:"pc-stat-detail-heading",children:n.heading}),(s=n.rows)!=null&&s.length?r.jsx("dl",{className:"pc-stat-detail-rows",children:n.rows.map(o=>r.jsxs(ve.Fragment,{children:[r.jsx("dt",{children:o.label}),r.jsxs("dd",{children:[r.jsx("span",{className:o.value===Gr?"pc-stat-detail-value pc-stat-detail-value--absent":"pc-stat-detail-value",children:o.value}),o.hint?r.jsx("span",{className:"pc-stat-detail-hint",children:o.hint}):null]})]},o.label))}):null,n.table?r.jsxs("table",{className:"pc-stat-detail-table",children:[r.jsx("thead",{children:r.jsx("tr",{children:n.table.columns.map(o=>r.jsx("th",{scope:"col",children:o},o))})}),r.jsx("tbody",{children:n.table.rows.map((o,l)=>r.jsx("tr",{children:o.map((u,c)=>r.jsx("td",{children:u},c))},l))})]}):null,n.note?r.jsx("p",{className:"pc-stat-detail-note",children:n.note}):null]},n.heading)}),r.jsx("div",{className:"pc-stat-detail-foot",children:t.footer.map(n=>r.jsx("div",{children:n},n))})]})}const ta=8;function Kk(e){const[t,n]=_.useState(!!e.defaultOpen),[s,o]=_.useState(null),l=_.useRef(null),u=_.useRef(null),c=_.useRef(null),f=`pc-stat-${_.useId().replace(/[^a-zA-Z0-9_-]/g,"")}`,m=_.useCallback(()=>{c.current!==null&&window.clearTimeout(c.current),c.current=null},[]),p=_.useCallback(()=>{m(),n(!0)},[m]),g=_.useCallback(()=>{m(),c.current=window.setTimeout(()=>n(!1),120)},[m]);_.useEffect(()=>m,[m]),_.useLayoutEffect(()=>{if(!t){o(null);return}const j=()=>{const N=l.current,C=u.current;if(!N||!C)return;const E=N.getBoundingClientRect(),T=C.offsetWidth,I=C.offsetHeight,K=window.innerWidth,U=window.innerHeight,J=E.top-ta-I,Y=E.bottom+ta,se=J>=ta?J:Y+I<=U-ta?Y:Math.max(ta,U-ta-I),ce=Math.min(Math.max(ta,E.left),Math.max(ta,K-ta-T));o({top:se,left:ce})};return j(),window.addEventListener("resize",j),window.addEventListener("scroll",j,!0),()=>{window.removeEventListener("resize",j),window.removeEventListener("scroll",j,!0)}},[t]),_.useEffect(()=>{if(!t)return;const j=N=>{N.key==="Escape"&&n(!1)};return document.addEventListener("keydown",j),()=>document.removeEventListener("keydown",j)},[t]);const w=typeof e.onClick=="function",x=w?"button":"span",S=t?r.jsx(Gk,{detail:e.detail,id:f,panelRef:u,onMouseEnter:m,onMouseLeave:g,style:{position:"fixed",top:(s==null?void 0:s.top)??0,left:(s==null?void 0:s.left)??0,visibility:s?"visible":"hidden"}}):null;return r.jsxs(r.Fragment,{children:[r.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:g,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?r.jsx("span",{className:"pc-chat-stat-icon","aria-hidden":"true",children:e.icon}):null,r.jsx("span",{className:"pc-chat-stat-label",children:e.label})]}),S&&typeof document<"u"?Nv.createPortal(S,document.body):S]})}function Yk(e){const t=e.totalTokens!==void 0?k_("tokens",e):null,n=k_("tools",e),s=e.durationMs!==void 0?k_("time",e):null;return[...t?[{label:`${e.totalTokens.toLocaleString()} tokens`,detail:t}]:[],{label:`${e.toolCalls} ${e.toolCalls===1?"tool":"tools"}`,detail:n},...e.changedFiles.length?[{label:`${e.changedFiles.length} ${e.changedFiles.length===1?"file":"files"} changed`,title:e.changedFiles.join(`
66
- `)}]:[],...s?[{label:`${(e.durationMs/1e3).toFixed(e.durationMs<1e4?1:0)}s`,detail:s}]:[]]}function Jk(e){const t=String(e.role||"").trim().toLowerCase()||"system",n=String(e.kind||"").trim().toLowerCase(),s=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()||(s==="error"?"Error":s==="warn"?"Warning":"System"),icon:s==="error"?"error":s==="warn"?"warning":"info",variant:s==="error"?"error":s==="warn"?"warn":"status"}}const Xk=new Set(["blob:","data:","http:","https:"]);function Cy(e){const t=String(e||"").trim();if(t)try{const n=typeof window<"u"&&window.location?window.location.href:"http://same-origin.invalid/";return Xk.has(new URL(t,n).protocol)?t:void 0}catch{return}}function Zk({item:e}){const[t,n]=_.useState(!1),s=Cy(e.src),o=e.href?Cy(e.href):void 0,l=e.kind==="image"||e.kind==="audio"||e.kind==="video"?e.kind:null;if(!l||!s&&!o)return null;const u=l==="image"?"Image":l==="video"?"Video":"Audio",c=String(e.label||"").trim()||`Generated ${u.toLowerCase()}`,f=()=>n(!0);return r.jsxs("figure",{className:`pc-chat-media__item pc-chat-media__item--${l}`,children:[s&&l==="image"?r.jsx("img",{className:"pc-chat-media__image",src:s,alt:c,loading:"lazy",onError:f}):null,s&&l==="video"?r.jsx("video",{className:"pc-chat-media__video",src:s,controls:!0,playsInline:!0,preload:"metadata","aria-label":c,onError:f}):null,s&&l==="audio"?r.jsx("audio",{className:"pc-chat-media__audio",src:s,controls:!0,preload:"metadata","aria-label":c,onError:f}):null,t?r.jsxs("div",{className:"pc-chat-media__error",role:"note",children:[u," could not be decoded by this browser",o?"; open the raw file with the link.":"."]}):null,o?r.jsx("figcaption",{className:"pc-chat-media__caption",children:r.jsx("a",{className:"pc-chat-media__link",href:o,target:"_blank",rel:"noopener noreferrer",children:c})}):null]})}function cg(e){var K;const t=e.message,n=_.useMemo(()=>Jk(t),[t.kind,t.level,t.role,t.title]),s=String(t.ts||"").trim(),o=_.useMemo(()=>{if(!s)return"";const U=new Date(s);return Number.isFinite(U.getTime())?U.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):""},[s]),[l,u]=_.useState("idle"),c=_.useRef(null);_.useEffect(()=>()=>{c.current!==null&&window.clearTimeout(c.current)},[]);const f=t.live,m=!f&&typeof e.onSpeakToggle=="function"&&n.variant==="assistant"&&!!String(t.content||"").trim(),p=m&&((K=e.getSpeakState)==null?void 0:K.call(e,t))||"idle",g=p==="loading"?"loader":p==="playing"?"pause":"speaker",w=p==="loading"?"Generating audio…":p==="playing"?"Pause":p==="paused"?"Resume":"Speak (TTS)",x=e.showCopy!==!1,S=Array.isArray(e.attachments)?e.attachments:[],j=t.statistics,N=t.stats,C=_.useMemo(()=>Array.isArray(e.stats)?e.stats:Array.isArray(N)?N:j?Yk(j):[],[e.stats,N,j]),E=Array.isArray(t.media)?t.media:[],T=String(f?f.reasoning||"":t.reasoning||""),I=!!String(t.content||"").trim();return t.toolActivity?r.jsx(lx,{tool:t.toolActivity,showCopy:e.showCopy}):r.jsxs("div",{className:["pc-chat-item",`pc-chat-item--${n.variant}`,f?"pc-chat-item--live":"",e.className].filter(Boolean).join(" "),...f?{"aria-busy":!0}:{},children:[r.jsxs("div",{className:"pc-chat-header",children:[r.jsx("div",{className:"pc-chat-avatar","aria-hidden":"true",children:r.jsx(et,{name:n.icon,size:14})}),r.jsx("span",{className:"pc-chat-role",children:n.label}),f?r.jsxs("span",{className:"pc-chat-live-indicator",title:f.label?`Pending: ${f.label}`:"The reply is still being written",children:[r.jsx("span",{className:"pc-chat-live-dot","aria-hidden":"true"}),f.label||"streaming"]}):null,f!=null&&f.caption?r.jsx("span",{className:"pc-chat-live-caption",children:f.caption}):null,r.jsx("span",{className:"pc-chat-header-spacer"}),o?r.jsx("span",{className:"pc-chat-time",children:o}):null,r.jsxs("div",{className:"pc-chat-header-actions",children:[m?r.jsx("button",{className:"pc-chat-icon-btn",type:"button","aria-label":w,title:w,onClick:()=>{var U;return(U=e.onSpeakToggle)==null?void 0:U.call(e,t)},children:r.jsx(et,{name:g,size:22})}):null,x?r.jsx("button",{className:`pc-chat-icon-btn ${l!=="idle"?`pc-chat-icon-btn--${l}`:""}`.trim(),type:"button","aria-label":"Copy message",title:l==="idle"?"Copy":l==="copied"?"Copied":"Copy failed",onClick:async()=>{const U=await sc(String(t.content||""));u(U?"copied":"failed"),c.current!==null&&window.clearTimeout(c.current),c.current=window.setTimeout(()=>u("idle"),900)},children:r.jsx(et,{name:"copy",size:22})}):null]})]}),T.trim()?r.jsxs("details",{className:"pc-chat-thinking",children:[r.jsx("summary",{children:"Thinking"}),r.jsx("div",{className:"pc-chat-thinking-body",children:T})]}):null,I||!f&&!E.length?r.jsx("div",{className:"pc-chat-body",children:r.jsx(ox,{text:String(t.content||""),renderMarkdown:e.renderMarkdown,jsonCollapseAfterDepth:e.jsonCollapseAfterDepth,images:e.images||(n.variant==="user"?"inline":"link"),inlineImage:e.inlineImage})}):null,E.length?r.jsx("div",{className:"pc-chat-media",children:E.slice(0,24).map((U,J)=>r.jsx(Zk,{item:U},U.id||`${U.kind}:${U.src}:${J}`))}):null,S.length?r.jsx("div",{className:"pc-chat-attachments","aria-label":"Attachments",children:S.slice(0,24).map((U,J)=>{const Y=String(U.label||"").trim()||"attachment",se=String(U.target||"").trim(),ce=String(U.title||"").trim(),fe=!!U.disabled||typeof U.onClick!="function";return r.jsxs("button",{type:"button",className:"pc-chat-attachment-chip",title:ce||Y,onClick:fe?void 0:U.onClick,disabled:fe,children:[r.jsx(et,{name:"paperclip",size:14}),se?r.jsx("span",{className:`pc-chat-attachment-target pc-chat-attachment-target--${se}`,children:se}):null,r.jsx("span",{className:"pc-chat-attachment-name",children:Y})]},U.id||`${Y}:${J}`)})}):null,C.length?r.jsx("div",{className:"pc-chat-stats","aria-label":"Stats",children:C.slice(0,12).map((U,J)=>{const Y=String(U.label||"").trim();if(!Y)return null;if(U.detail)return r.jsx(Kk,{label:Y,detail:U.detail,icon:U.icon,onClick:U.onClick},U.id||`${Y}:${J}`);const se=String(U.title||"").trim(),ce=typeof U.onClick=="function",fe=ce?"button":"span";return r.jsxs(fe,{...ce?{type:"button"}:{},className:["pc-chat-stat",ce?"pc-chat-stat--clickable":""].filter(Boolean).join(" "),title:se||void 0,onClick:ce?()=>{var W;return(W=U.onClick)==null?void 0:W.call(U)}:void 0,children:[U.icon?r.jsx("span",{className:"pc-chat-stat-icon","aria-hidden":"true",children:U.icon}):null,r.jsx("span",{className:"pc-chat-stat-label",children:Y})]},U.id||`${Y}:${J}`)})}):null]})}function Qk(e,t){const n=Math.max(0,Math.trunc(t));return e.scrollHeight-e.scrollTop-e.clientHeight<=n}function ug(e){const t=typeof e.autoScrollThresholdPx=="number"&&Number.isFinite(e.autoScrollThresholdPx)?e.autoScrollThresholdPx:120,n=e.autoScroll!==!1,s=_.useRef(null),o=_.useRef(null),[l,u]=_.useState(!0),c=_.useMemo(()=>Array.isArray(e.messages)?e.messages:[],[e.messages]),f=_.useMemo(()=>{var g;const p=[];for(const w of c){const x=p[p.length-1];w.toolActivity&&((g=x==null?void 0:x[0])!=null&&g.toolActivity)&&x[0].runId===w.runId?x.push(w):p.push([w])}return p},[c]);_.useEffect(()=>{if(!n)return;const p=s.current;if(!p)return;const g=()=>{u(Qk(p,t))};return p.addEventListener("scroll",g,{passive:!0}),g(),()=>p.removeEventListener("scroll",g)},[n,t]);const m=_.useMemo(()=>{let p=0;for(const g of c)if(p+=String(g.content??"").length,Array.isArray(g.media))for(const w of g.media)p+=String((w==null?void 0:w.src)??"").length+1;return`${c.length}:${p}:${String(e.afterKey??"")}`},[c,e.afterKey]);return _.useEffect(()=>{if(!n||!l)return;const p=s.current;p&&(p.scrollTop=p.scrollHeight)},[n,l,m]),_.useEffect(()=>{if(!n)return;const p=s.current;if(!p)return;const g=()=>{l&&(p.scrollTop=p.scrollHeight)};return p.addEventListener("load",g,!0),p.addEventListener("loadedmetadata",g,!0),()=>{p.removeEventListener("load",g,!0),p.removeEventListener("loadedmetadata",g,!0)}},[n,l]),r.jsxs("div",{ref:s,className:["pc-chat-thread",e.className].filter(Boolean).join(" "),children:[c.length?null:e.empty||null,f.map((p,g)=>{var S;const w=p[0],x=String(w.id||"")||String(w.ts||"")+":"+String(w.role||"")+":"+g;return w.toolActivity?r.jsx(cx,{tools:p.map(j=>j.toolActivity),showCopy:(S=e.messageProps)==null?void 0:S.showCopy},x):r.jsx(cg,{message:w,...e.messageProps||{}},x)}),e.after,r.jsx("div",{ref:o})]})}const dg=ve.forwardRef(function(t,n){const s=typeof t.rows=="number"&&Number.isFinite(t.rows)?Math.max(1,Math.trunc(t.rows)):3,o=!!t.disabled,l=!!t.busy,u=!o&&!l&&!!String(t.value||"").trim();return r.jsxs("div",{className:["pc-composer",t.className].filter(Boolean).join(" "),children:[t.leading,r.jsx("textarea",{ref:n,className:["pc-composer__textarea",t.textareaClassName].filter(Boolean).join(" "),value:t.value,onChange:c=>t.onChange(c.target.value),rows:s,style:{"--pc-composer-rows":String(s)},spellCheck:!1,autoCorrect:"off",autoCapitalize:"off",autoComplete:"off",placeholder:t.placeholder||"","aria-label":t.ariaLabel||t.placeholder||"Message",disabled:o,autoFocus:!!t.autoFocus,onPaste:t.onPaste,onKeyDown:c=>{c.key!=="Enter"||c.shiftKey||c.nativeEvent.isComposing||c.keyCode===229||(c.preventDefault(),u&&t.onSubmit())}}),r.jsxs("div",{className:"pc-composer__row",children:[r.jsx("div",{className:"pc-composer__actions",children:t.actions}),r.jsx("button",{type:"button",className:t.sendButtonClassName||"pc-btn",disabled:!u,onClick:()=>t.onSubmit(),children:l?t.busyLabel||"Thinking…":t.sendLabel||"Send"})]}),t.overlay]})});function e1(e){return!!(e&&typeof e[Symbol.asyncIterator]=="function")}function t1(e){const[t,n]=_.useState([]),s=e.messages??t,o=j=>{e.onMessagesChange&&e.onMessagesChange(j),e.messages===void 0&&n(j)},l=_.useRef(s);l.current=s;const[u,c]=_.useState(""),[f,m]=_.useState(!1),p=_.useRef(null),g=e.assistantName||"Assistant",w=!!e.blockedNotice,x=async j=>{const N=String(j||"").trim();if(!N||f||w)return;c("");const C=l.current,E=[...C,{role:"user",content:N,ts:new Date().toISOString()}];o(E),m(!0);const T=new AbortController;p.current=T;try{const I=e.ask(N,{signal:T.signal,history:C});if(e1(I)){let K="";const U=[...E,{role:"assistant",title:g,content:"",ts:new Date().toISOString()}];o(U);for await(const J of I){if(T.signal.aborted)break;K+=String(J??""),o([...E,{role:"assistant",title:g,content:K,ts:new Date().toISOString()}])}!K.trim()&&!T.signal.aborted&&o([...E,{role:"assistant",title:g,content:"#FALLBACK the assistant returned no answer.",level:"warn",ts:new Date().toISOString()}])}else{const K=String(await I??"").trim();o([...E,K?{role:"assistant",title:g,content:K,ts:new Date().toISOString()}:{role:"assistant",title:g,content:"#FALLBACK the assistant returned no answer.",level:"warn",ts:new Date().toISOString()}])}}catch(I){T.signal.aborted||o([...l.current,{role:"assistant",title:g,content:`#FALLBACK assistant request failed: ${String((I==null?void 0:I.message)||I||"unknown error")}`,level:"error",ts:new Date().toISOString()}])}finally{p.current===T&&(p.current=null),m(!1)}},S=_.useMemo(()=>s.length>0?null:r.jsxs("div",{className:"pc-assistant__empty",children:[r.jsx("div",{className:"pc-assistant__empty-text",children:e.emptyState||"Ask about this app — answers are grounded in its documentation."}),e.suggestions&&e.suggestions.length>0?r.jsx("div",{className:"pc-assistant__suggestions",children:e.suggestions.map(j=>r.jsx("button",{type:"button",className:"pc-assistant__suggestion",onClick:()=>void x(j),disabled:f||w,children:j},j))}):null]}),[s.length,e.emptyState,e.suggestions,f,w]);return r.jsxs("div",{className:`pc-assistant${e.className?` ${e.className}`:""}`,children:[r.jsxs("div",{className:"pc-assistant__thread",children:[S,r.jsx(ug,{messages:s,autoScroll:!0}),w?r.jsx("div",{className:"pc-assistant__blocked",children:e.blockedNotice}):null]}),r.jsx("div",{className:"pc-assistant__composer",children:r.jsx(dg,{value:u,onChange:c,onSubmit:()=>void x(u),placeholder:e.placeholder||"Ask about this app…",disabled:w,busy:f,rows:2,actions:f?r.jsx("button",{type:"button",className:"pc-btn",onClick:()=>{var j;(j=p.current)==null||j.abort()},children:"Stop"}):null})})]})}const Sn=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},Jh=e=>Array.isArray(e)?e.map(Sn):[],Zt=e=>typeof e=="string"?e:"",Wd=e=>Zt(e.runtime_call_id||e.call_uid),qd=e=>Zt(e.call_id||e.id);function fx(e,t){const n=t.record,s=Sn(n.effect);if(s.type!=="tool_calls")return[];const o=Sn(n.result),l=Jh(Sn(s.payload).tool_calls),u=l.length||n.status!=="waiting"?l:Jh(Sn(Sn(o.wait).details).tool_calls),c=Jh(o.results),f=u.length?u:c,m=[];return f.forEach((p,g)=>{let w=Wd(p)?c.filter(U=>Wd(U)===Wd(p)):[];!w.length&&qd(p)&&u.filter(U=>qd(U)===qd(p)).length===1&&(w=c.filter(U=>qd(U)===qd(p)));const x=u.length?w.length===1?w[0]:u.length===c.length?c[g]:{}:p,S=Wd(p)||Wd(x)||`${Zt(n.idempotency_key)||Zt(n.step_id)||t.cursor}:${g}`,j=`${t.runId}:${S}`,N=e.get(j),C=Zt(p.name||x.name)||(N==null?void 0:N.name);if(!C)return;const E=n.status==="completed"||n.status==="failed",T=n.status==="failed"||x.success===!1||!!x.error,I=p.arguments??x.arguments??(N==null?void 0:N.arguments),K={...N,id:j,runId:t.runId,name:C,arguments:I,status:E?T?"failed":"completed":n.status==="waiting"?"waiting":"running",...typeof x.success=="boolean"?{success:x.success}:{},...x.output!==void 0||x.result!==void 0?{output:x.output??x.result}:{},...x.error?{error:String(x.error)}:{},startedAt:(N==null?void 0:N.startedAt)||Zt(n.started_at)||void 0,endedAt:E&&Zt(n.ended_at)||(N==null?void 0:N.endedAt)};N&&["completed","failed"].includes(N.status)&&!E||(e.set(j,K),m.push(K))}),m}function cu(e){if(e==null||e===""||typeof e=="boolean")return;const t=Number(e);return Number.isFinite(t)&&t>=0?t:void 0}function vo(e,t){for(const n of t){const s=e==null?void 0:e[n];if(s==null||s===""||typeof s=="boolean")continue;const o=Number(s);if(Number.isFinite(o)&&o>=0)return Math.trunc(o)}}function hx(e){if(typeof e=="string")try{return Sn(JSON.parse(e))}catch{return{}}return Sn(e)}function nu(e,t){if(t===void 0||t==="")return e;const n=e||[];return n.includes(t)||n.push(t),n}function n1(e){return vo(e,["reasoning_tokens","thinking_tokens"])??vo(Sn(e.completion_tokens_details),["reasoning_tokens"])??vo(Sn(e.output_tokens_details),["reasoning_tokens"])}function r1(e){const t=Sn(typeof e=="string"&&e.trim().startsWith("{")?hx(e):e);return Zt(t.error_class)}function s1(e){const t=new Map;for(const n of e){const s=n.record;if(Sn(s.effect).type!=="emit_event")continue;const o=Sn(s.result);if(Zt(o.name)!=="abstract.progress")continue;const l=Sn(o.payload);if(Zt(l.kind)!=="llm"||!Zt(l.step_id))continue;const u=`${Zt(l.run_id)||n.runId}:${Zt(l.step_id)}`,c=t.get(u)||{},f=cu(l.ttft_s);f!==void 0&&(c.ttftS=f),c.provider=c.provider||Zt(l.provider)||void 0,c.model=c.model||Zt(l.model)||void 0,t.set(u,c)}return t}function N_(e){var j,N,C,E;const t=new Map,n=new Set,s=new Set,o={llmCalls:0,toolCalls:0,changedFiles:[]};let l=1/0,u=-1/0,c=!1,f=0,m=0,p=0;const g=s1(e),w=[],x=new Set;for(const T of e){const I=T.record,K=`${T.runId}:${I.step_id||T.cursor}:${I.status}`;if(n.has(K))continue;n.add(K);for(const ye of[I.started_at,I.ended_at]){const Ne=Date.parse(Zt(ye));Number.isFinite(Ne)&&(l=Math.min(l,Ne),u=Math.max(u,Ne))}for(const ye of fx(t,T))ye.status==="waiting"&&x.add(ye.id);if(Sn(I.effect).type!=="llm_call"||I.status!=="completed")continue;o.llmCalls+=1;const U=Sn(I.result),J=Sn(U.output),Y=Sn(U.usage||U.token_usage||U.tokens||J.usage||J.token_usage||J.tokens),se=vo(Y,["input_tokens","prompt_tokens","prompt","input","in"]),ce=vo(Y,["output_tokens","completion_tokens","completion","output","out"]),fe=vo(Y,["total_tokens","total"])??(se!==void 0||ce!==void 0?(se||0)+(ce||0):void 0);fe!==void 0&&(se===void 0||ce===void 0||se+ce!==fe)&&(c=!0),se!==void 0&&(o.inputTokens=(o.inputTokens||0)+se),ce!==void 0&&(o.outputTokens=(o.outputTokens||0)+ce),fe!==void 0&&(o.totalTokens=(o.totalTokens||0)+fe);const W=cu(U.gen_time??J.gen_time);W!==void 0&&(o.genTimeMs=(o.genTimeMs||0)+W,o.timedCalls=(o.timedCalls||0)+1);const P=Sn(U.metadata||J.metadata),A=Sn(P.performance),z=cu(A.prompt_tokens_per_second),$=cu(A.generation_tokens_per_second),te=Sn(P.prompt_cache),O=cu(te.cached_tokens),F=cu(te.fed_tokens);if(z!==void 0||$!==void 0){if(o.measuredSpeedCalls=(o.measuredSpeedCalls||0)+1,z!==void 0&&z>0&&(o.promptTokensPerSecond=(o.promptTokensPerSecond||0)+z,se!==void 0)){const ye=se/z*1e3;o.prefillMs=(o.prefillMs||0)+ye,F!==void 0&&(f+=F,m+=ye)}$!==void 0&&$>0&&(o.generationTokensPerSecond=(o.generationTokensPerSecond||0)+$,ce!==void 0&&(o.decodeMs=(o.decodeMs||0)+ce/$*1e3))}if(O!==void 0||F!==void 0){o.measuredCacheCalls=(o.measuredCacheCalls||0)+1,o.cachedTokens=(o.cachedTokens||0)+(O||0),o.fedTokens=(o.fedTokens||0)+(F||0);const ye=Zt(te.outcome);if(ye){const Ne=o.cacheOutcomes||[];Ne.includes(ye)||Ne.push(ye),o.cacheOutcomes=Ne}}const G=Zt(I.step_id)||void 0,R=G&&g.get(`${T.runId}:${G}`)||{},Z=Sn(U.route),X={runId:T.runId};G&&(X.stepId=G),Zt(I.started_at)&&(X.startedAt=Zt(I.started_at));const Q=Zt(U.model||J.model)||Zt(Z.model)||R.model,le=Zt(Z.provider)||Zt(Sn(P._provider_request).provider)||R.provider||Zt(U.provider);Q&&(X.model=Q),le&&(X.provider=le),Q&&(o.models=nu(o.models,Q)),le&&(o.providers=nu(o.providers,le)),(fe===void 0||se!==void 0&&ce!==void 0&&se+ce===fe)&&(se!==void 0&&(X.inputTokens=se),ce!==void 0&&(X.outputTokens=ce)),fe!==void 0&&(X.totalTokens=fe);const ge=n1(Y);ge!==void 0&&(X.reasoningTokens=ge,o.reasoningTokens=(o.reasoningTokens||0)+ge),O!==void 0&&(X.cachedTokens=O),F!==void 0&&(X.fedTokens=F),Zt(te.outcome)&&(X.cacheOutcome=Zt(te.outcome)),Zt(te.backend)&&(X.cacheBackend=Zt(te.backend),o.cacheBackends=nu(o.cacheBackends,X.cacheBackend)),W!==void 0&&(X.genTimeMs=W),z!==void 0&&z>0&&(X.promptTokensPerSecond=z),$!==void 0&&$>0&&(X.generationTokensPerSecond=$),R.ttftS!==void 0?(X.ttftMs=R.ttftS*1e3,X.promptMs=X.ttftMs,X.promptSource="ttft",o.ttftMs=(o.ttftMs||0)+X.ttftMs,o.ttftCalls=(o.ttftCalls||0)+1):X.promptTokensPerSecond!==void 0&&se!==void 0&&(X.promptMs=se/X.promptTokensPerSecond*1e3,X.promptSource="rate"),X.promptMs!==void 0&&(o.promptPhaseMs=(o.promptPhaseMs||0)+X.promptMs,o.promptPhaseCalls=(o.promptPhaseCalls||0)+1,F!==void 0&&X.promptMs>0&&(X.promptNewTokensPerSecond=F/(X.promptMs/1e3),o.promptPhaseNewTokens=(o.promptPhaseNewTokens||0)+F,p+=X.promptMs)),X.ttftMs!==void 0&&W!==void 0&&W>=X.ttftMs?X.generationMs=W-X.ttftMs:X.generationTokensPerSecond!==void 0&&ce!==void 0&&(X.generationMs=ce/X.generationTokensPerSecond*1e3),X.generationMs!==void 0&&ce!==void 0&&(o.generationPhaseMs=(o.generationPhaseMs||0)+X.generationMs,o.generationPhaseTokens=(o.generationPhaseTokens||0)+ce);const pe=Sn(P.speculation);if(Object.keys(pe).length){const ye={};Zt(pe.mode)&&(ye.mode=Zt(pe.mode)),typeof pe.used=="boolean"&&(ye.used=pe.used),Zt(pe.draft_kind)&&(ye.draftKind=Zt(pe.draft_kind));const Ne=vo(pe,["accepted_tokens"]),Ue=vo(pe,["drafted_tokens"]),We=vo(pe,["rounds"]),pt=vo(pe,["num_draft_tokens"]);Ne!==void 0&&(ye.acceptedTokens=Ne),Ue!==void 0&&(ye.draftedTokens=Ue),Ne!==void 0&&Ue&&(ye.acceptanceRate=Ne/Ue),We!==void 0&&(ye.rounds=We),pt!==void 0&&(ye.draftLength=pt),X.speculation=ye;const Fe=o.speculation||(o.speculation={calls:0,used:0});Fe.calls+=1,ye.used&&(Fe.used+=1),ye.mode&&(Fe.modes=nu(Fe.modes,ye.mode)),ye.draftKind&&(Fe.draftKinds=nu(Fe.draftKinds,ye.draftKind)),Ne!==void 0&&Ue!==void 0&&(Fe.acceptedTokens=(Fe.acceptedTokens||0)+Ne,Fe.draftedTokens=(Fe.draftedTokens||0)+Ue),We!==void 0&&(Fe.rounds=(Fe.rounds||0)+We),pt!==void 0&&(Fe.draftLengths=nu(Fe.draftLengths,pt))}w.push(X)}w.length&&(w.every(T=>T.startedAt)&&w.sort((T,I)=>Date.parse(T.startedAt)-Date.parse(I.startedAt)),o.modelCalls=w),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)),m>0&&(o.prefillNewTokens=f,o.prefillNewTokensPerSecond=f/(m/1e3));const S=new Map;for(const T of t.values()){if(T.status==="waiting"){o.toolsWaiting=(o.toolsWaiting||0)+1;continue}if(T.status==="running"){o.toolsRunning=(o.toolsRunning||0)+1;continue}if(!["completed","failed"].includes(T.status))continue;o.toolCalls+=1;const I=T.status==="failed";I&&(o.toolsFailed=(o.toolsFailed||0)+1);const K=o.toolBreakdown||(o.toolBreakdown={}),U=K[T.name]||(K[T.name]={calls:0,failed:0});if(U.calls+=1,I){U.failed+=1;const fe=r1(T.output);fe&&((U.errors||(U.errors={}))[fe]=(((N=U.errors)==null?void 0:N[fe])||0)+1)}const J=Date.parse(Zt(T.startedAt)),Y=Date.parse(Zt(T.endedAt));if(Number.isFinite(J)&&Number.isFinite(Y)&&Y>=J){const fe=`${T.runId}|${T.startedAt}|${T.endedAt}`,W=S.get(fe)||{ms:Y-J,calls:0,names:new Map,waited:!1};W.calls+=1,W.names.set(T.name,(W.names.get(T.name)||0)+1),x.has(T.id)&&(W.waited=!0),S.set(fe,W)}if(T.success!==!0||!["write_file","create_file","save_file","edit_file","update_file","replace_in_file","delete_file","remove_file","move_file","rename_file","copy_file"].includes(T.name))continue;const se=hx(T.arguments),ce=Zt(se.destination||se.destination_path||se.file_path||se.path||se.filename);ce&&s.add(ce)}for(const T of S.values()){o.toolBatches=(o.toolBatches||0)+1,o.toolTimeMs=(o.toolTimeMs||0)+T.ms,T.waited&&(o.toolTimeIncludesApproval=!0);const I=[...T.names.keys()].sort();(!o.slowestToolBatch||T.ms>o.slowestToolBatch.ms)&&(o.slowestToolBatch={ms:T.ms,calls:T.calls,tools:I});const K=(C=o.toolBreakdown)==null?void 0:C[I[0]];if(I.length===1&&K)K.ms=(K.ms||0)+T.ms;else for(const U of I){const J=(E=o.toolBreakdown)==null?void 0:E[U];J&&(J.sharedBatches=(J.sharedBatches||0)+1)}}return o.changedFiles=[...s],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 i1(e){const t=Sn(Sn(e).ledgers);return Object.entries(t).flatMap(([n,s])=>Jh(Sn(s).items).map((o,l)=>({runId:n,cursor:Number(o.cursor)||l+1,record:Object.keys(Sn(o.record)).length?Sn(o.record):o})))}function Ch(e){if(!e)return!1;for(let t=0;t<e.length;t+=1)if(e[t]==="Files")return!0;return!1}function Ey(e){var s;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)((s=t[o])==null?void 0:s.kind)==="file"&&(n+=1);return n>0?n:null}function $y(e){return e===1?"Drop file to attach":typeof e=="number"&&e>1?`Drop ${e} files to attach`:"Drop files to attach"}function mx(e){const t=[],n=[],s=e==null?void 0:e.items;if(s&&s.length){for(let l=0;l<s.length;l+=1){const u=s[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 o1(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 a1={"image/png":"png","image/jpeg":"jpg","image/gif":"gif","image/webp":"webp","image/heic":"heic","image/tiff":"tiff","image/bmp":"bmp"};function Hd(e){return String(e).padStart(2,"0")}function l1(e,t,n){const s=String(e||"").trim();if(s&&!/^image\.(png|jpe?g|gif|webp|heic|tiff?|bmp)$/i.test(s))return s;const o=a1[String(t||"").toLowerCase()]||s.split(".").pop()||"bin",l=`${n.getFullYear()}-${Hd(n.getMonth()+1)}-${Hd(n.getDate())} at ${Hd(n.getHours())}.${Hd(n.getMinutes())}.${Hd(n.getSeconds())}`;return`${String(t||"").startsWith("image/")||!s?"Pasted image":"Pasted file"} ${l}.${o}`}function c1(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:s}=mx(e);return s.map(o=>{const l=l1(o.name,o.type,t);return l===o.name?o:new File([o],l,{type:o.type,lastModified:o.lastModified})})}class u1{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 d1(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 f1(e){return(e instanceof Error?e.message:String(e||"Unknown error")).trim()||"Unknown error"}function h1(e){return r.jsxs("div",{className:"pc-workflow-interaction__error",role:"alert",children:[r.jsxs("span",{children:["Could not complete that action: ",e.message]}),r.jsx("button",{type:"button",className:"pc-workflow-interaction__retry",onClick:e.onRetry,disabled:e.disabled,children:"Try again"})]})}function m1(e){var J;const t=e.interaction,[n,s]=_.useState(""),[o,l]=_.useState(()=>t.kind==="event-wait"&&t.initialPayload||""),[u,c]=_.useState(null),[f,m]=_.useState(!1),[p,g]=_.useState(""),[w,x]=_.useState(null),S=`${t.kind}:${t.id}`,j=_.useRef(S),N=_.useRef(!1),C=_.useRef(!1),E=_.useRef(!0),T=_.useRef(0);j.current!==S&&(j.current=S,N.current=!1,C.current=!1,T.current+=1);const I=!!e.disabled||u!==null||f||N.current||C.current,K=async(Y,se)=>{var W;if(e.disabled||N.current||C.current)return;const ce=S,fe=++T.current;N.current=!0,x(null),g(""),c(Y);try{if(await se(),!E.current||j.current!==ce||T.current!==fe)return;C.current=!0,m(!0),g("Response sent. Waiting for the workflow to continue.")}catch(P){if(!E.current||j.current!==ce||T.current!==fe)return;x({submission:Y,message:f1(P)}),g("The action failed. You can try again."),(W=e.onError)==null||W.call(e,P)}finally{if(!E.current||j.current!==ce||T.current!==fe)return;N.current=!1,c(null)}};_.useEffect(()=>{s(""),l(t.kind==="event-wait"&&t.initialPayload||""),x(null),c(null),m(!1),g("")},[S]),_.useEffect(()=>(E.current=!0,()=>{E.current=!1,T.current+=1,N.current=!1}),[]);const U=()=>{w&&K(w.submission,()=>d1(t,w.submission))};return r.jsxs("section",{className:"pc-workflow-interaction","aria-labelledby":`pc-workflow-interaction-${S}`,children:[r.jsxs("div",{className:"pc-workflow-interaction__heading",children:[r.jsx(et,{name:t.kind==="tool-approval"?"warning":t.kind==="event-wait"?"history":"info",size:16}),r.jsxs("div",{children:[r.jsx("h3",{tabIndex:-1,id:`pc-workflow-interaction-${S}`,children:t.title||(t.kind==="tool-approval"?"Tool approval required":"Input required")}),t.description?r.jsx("div",{className:"pc-workflow-interaction__description",children:t.description}):null]})]}),t.kind==="ask-user"?r.jsxs("div",{className:"pc-workflow-interaction__body",children:[r.jsx("div",{className:"pc-workflow-interaction__prompt",children:t.prompt}),(J=t.choices)!=null&&J.length?r.jsx("div",{className:"pc-workflow-interaction__choices","aria-label":"Choices",children:t.choices.map(Y=>r.jsxs("button",{type:"button",className:"pc-workflow-interaction__choice",disabled:I||Y.disabled,onClick:()=>void K({kind:"choice",answer:Y.id},()=>t.onSubmit(Y.id)),children:[r.jsx("span",{children:Y.label}),Y.description?r.jsx("small",{children:Y.description}):null]},Y.id))}):null,t.allowFreeText!==!1?r.jsxs("div",{className:"pc-workflow-interaction__entry",children:[r.jsx("textarea",{"aria-label":"Response",value:n,onChange:Y=>s(Y.target.value),placeholder:t.freeTextPlaceholder||"Type a response",rows:2,disabled:I,onKeyDown:Y=>{Y.key!=="Enter"||Y.shiftKey||Y.nativeEvent.isComposing||Y.keyCode===229||(Y.preventDefault(),n.trim()&&K({kind:"free-text",answer:n},()=>t.onSubmit(n)))}},`${S}:text`),r.jsx("button",{type:"button",className:"pc-btn",disabled:I||!n.trim(),onClick:()=>void K({kind:"free-text",answer:n},()=>t.onSubmit(n)),children:(u==null?void 0:u.kind)==="free-text"?"Sending…":t.submitLabel||"Submit"})]}):null]}):t.kind==="tool-approval"?r.jsxs("div",{className:"pc-workflow-interaction__body",children:[r.jsxs("div",{className:"pc-workflow-interaction__prompt",children:["Allow ",r.jsx("strong",{children:t.toolName})," to run?"]}),t.detail?r.jsx("div",{className:"pc-workflow-interaction__detail",children:t.detail}):null,r.jsxs("div",{className:"pc-workflow-interaction__buttons",children:[r.jsx("button",{type:"button",className:"pc-workflow-interaction__deny",disabled:I,onClick:()=>void K({kind:"deny"},t.onDeny),children:(u==null?void 0:u.kind)==="deny"?"Denying…":t.denyLabel||"Deny"}),r.jsx("button",{type:"button",className:"pc-btn",disabled:I,onClick:()=>void K({kind:"approve"},t.onApprove),children:(u==null?void 0:u.kind)==="approve"?"Approving…":t.approveLabel||"Approve"}),t.onApproveAll?r.jsx("button",{type:"button",className:"pc-workflow-interaction__allow-all",disabled:I,onClick:()=>void K({kind:"approve-all"},t.onApproveAll),children:(u==null?void 0:u.kind)==="approve-all"?"Approving…":t.approveAllLabel||"Allow all"}):null]}),t.onApproveAll&&t.approveAllDescription?r.jsx("p",{className:"pc-workflow-interaction__scope",children:t.approveAllDescription}):null]}):r.jsxs("div",{className:"pc-workflow-interaction__body",children:[r.jsx("div",{className:"pc-workflow-interaction__prompt",children:t.prompt}),r.jsxs("label",{className:"pc-workflow-interaction__entry",children:[r.jsx("span",{children:t.payloadLabel||(t.eventName?`Payload for ${t.eventName}`:"Event payload")}),r.jsx("textarea",{value:o,onChange:Y=>l(Y.target.value),placeholder:t.payloadPlaceholder||"Enter payload",rows:2,"aria-label":t.payloadLabel||(t.eventName?`Payload for ${t.eventName}`:"Event payload"),disabled:I},`${S}:payload`)]}),r.jsx("div",{className:"pc-workflow-interaction__buttons",children:r.jsx("button",{type:"button",className:"pc-btn",disabled:I,onClick:()=>void K({kind:"event",payload:o},()=>t.onSend(o)),children:(u==null?void 0:u.kind)==="event"?"Sending…":t.sendLabel||"Send event"})})]}),w?r.jsx(h1,{message:w.message,onRetry:U,disabled:I}):null,r.jsx("div",{className:"pc-workflow-interaction__outcome","aria-live":"polite",children:p})]})}function Eh(e){return(e instanceof Error?e.message:String(e||"Unknown error")).trim()||"Unknown error"}function _1(e){const[t,n]=_.useState(!1),[s,o]=_.useState(!1),[l,u]=_.useState(!1),[c,f]=_.useState(null),m=_.useRef(!0),p=_.useRef(!1),g=_.useRef(!1),w=_.useRef(!1),x=_.useRef(0),S=_.useRef(0),j=_.useRef(0);_.useEffect(()=>(m.current=!0,()=>{m.current=!1,x.current+=1,S.current+=1,j.current+=1,p.current=!1,g.current=!1,w.current=!1}),[]);const N=!!e.blockedNotice,C=!!e.disabled||N,E=!!e.busy||t,T=t||!!e.busy&&!e.sendWhileBusy,I=e.stopState||null,K=(I==null?void 0:I.phase)==="stopping",U=typeof e.onFiles=="function",J=_.useRef(null),[Y,se]=_.useState(null),[ce,fe]=_.useState(""),W=_.useRef(e.onFiles);W.current=e.onFiles;const P=_.useRef(C);P.current=C;const A=async(X,Q)=>{const le=W.current;if(le){if(P.current){f({action:"attach",message:"attachments are unavailable right now."});return}if(Q.length)f({action:"attach",message:o1(Q)});else if(X.length)f(null);else{f({action:"attach",message:"the drop contained no files."});return}if(X.length){fe(`Attaching ${X.length} ${X.length===1?"file":"files"}…`);try{await le(X)}catch(ge){m.current&&f({action:"attach",message:Eh(ge)})}}}},z=_.useRef(A);z.current=A,_.useEffect(()=>{if(!U||typeof window>"u")return;const X=new u1;let Q=0;const le=Fe=>!!(J.current&&Fe instanceof Node&&J.current.contains(Fe)),ge=()=>{X.reset(),Q&&window.clearInterval(Q),Q=0,se(null)},pe=()=>{Q||(Q=window.setInterval(()=>{X.active(Date.now())||ge()},250))},ye=Fe=>{var Ke;if(!Ch((Ke=Fe.dataTransfer)==null?void 0:Ke.types))return;X.enter(Date.now());const tt=le(Fe.target),lt=Ey(Fe.dataTransfer);se(Se=>Se&&Se.over===tt&&Se.count===(lt??Se.count)?Se:{count:lt??(Se==null?void 0:Se.count)??null,over:tt}),pe()},Ne=Fe=>{var lt;if(!Ch((lt=Fe.dataTransfer)==null?void 0:lt.types))return;Fe.preventDefault(),X.over(Date.now());const tt=le(Fe.target);Fe.dataTransfer&&(Fe.dataTransfer.dropEffect=tt&&!P.current?"copy":"none"),se(Ke=>Ke&&Ke.over===tt?Ke:{count:(Ke==null?void 0:Ke.count)??Ey(Fe.dataTransfer),over:tt}),pe()},Ue=Fe=>{var tt;Ch((tt=Fe.dataTransfer)==null?void 0:tt.types)&&(X.leave(Date.now())||ge())},We=Fe=>{var Re;if(!Ch((Re=Fe.dataTransfer)==null?void 0:Re.types))return;const tt=le(Fe.target),lt=Fe.defaultPrevented&&!tt;if(Fe.preventDefault(),ge(),lt)return;if(!tt){f({action:"attach",message:"drop files on the conversation to attach them."});return}const{files:Ke,folders:Se}=mx(Fe.dataTransfer);z.current(Ke,Se)},pt=Fe=>{Fe.key==="Escape"&&X.depth>0&&ge()};return window.addEventListener("dragenter",ye),window.addEventListener("dragover",Ne),window.addEventListener("dragleave",Ue),window.addEventListener("drop",We),window.addEventListener("dragend",ge),window.addEventListener("blur",ge),window.addEventListener("keydown",pt),()=>{window.removeEventListener("dragenter",ye),window.removeEventListener("dragover",Ne),window.removeEventListener("dragleave",Ue),window.removeEventListener("drop",We),window.removeEventListener("dragend",ge),window.removeEventListener("blur",ge),window.removeEventListener("keydown",pt),Q&&window.clearInterval(Q)}},[U]);const $=X=>{if(!U||C)return;const Q=c1(X.clipboardData);Q.length&&(X.preventDefault(),A(Q,[]))},te=Y?r.jsxs("div",{className:["pc-workflow-chat__dropzone",Y.over?"is-over":"",C?"is-disabled":""].filter(Boolean).join(" "),"aria-hidden":"true",children:[r.jsx("span",{className:"pc-workflow-chat__dropzone-icon",children:r.jsx(et,{name:"paperclip",size:18})}),r.jsxs("span",{className:"pc-workflow-chat__dropzone-text",children:[r.jsx("strong",{children:C?"Attachments are unavailable right now":$y(Y.count)}),C?null:r.jsx("span",{children:Y.over?"Release to upload to this conversation":"Drop anywhere on the conversation"})]})]}):null,O=Y?C?"Attachments are unavailable right now":$y(Y.count):ce,F=async()=>{const X=String(e.draft||"");if(C||p.current||!e.sendWhileBusy&&e.busy||!X.trim())return;const Q=++x.current;p.current=!0,f(null),n(!0);try{await e.onSend(X)}catch(le){m.current&&x.current===Q&&f({action:"send",message:Eh(le)})}finally{m.current&&x.current===Q&&(p.current=!1,n(!1))}},G=async()=>{if(C||g.current||!e.onCancel)return;const X=++S.current;g.current=!0,f(null),o(!0);try{await e.onCancel()}catch(Q){m.current&&S.current===X&&f({action:"cancel",message:Eh(Q)})}finally{m.current&&S.current===X&&(g.current=!1,o(!1))}},R=async()=>{if(C||w.current||!e.onAttach)return;const X=++j.current;w.current=!0,f(null),u(!0);try{await e.onAttach()}catch(Q){m.current&&j.current===X&&f({action:"attach",message:Eh(Q)})}finally{m.current&&j.current===X&&(w.current=!1,u(!1))}},Z=()=>{c&&(c.action==="send"&&F(),c.action==="cancel"&&G(),c.action==="attach"&&R())};return r.jsxs("section",{ref:J,className:["pc-workflow-chat",Y?"pc-workflow-chat--dragging":"",Y!=null&&Y.over?"pc-workflow-chat--drag-over":"",e.className].filter(Boolean).join(" "),"aria-label":"Workflow chat","data-stream-replies":e.streamReplies||"gateway_default",children:[e.header?r.jsx("header",{className:"pc-workflow-chat__header",children:e.header}):null,r.jsx("div",{className:"pc-workflow-chat__transcript",children:r.jsx(ug,{messages:Array.isArray(e.messages)?e.messages:[],empty:e.emptyState,autoScroll:!0,messageProps:{...e.messageProps,...e.renderMarkdown?{renderMarkdown:e.renderMarkdown}:{}},after:r.jsxs(r.Fragment,{children:[e.interaction?r.jsx(m1,{interaction:e.interaction,disabled:C}):null,N?r.jsx("div",{className:"pc-workflow-chat__blocked",role:"status",children:e.blockedNotice}):null]}),afterKey:`${e.interaction?`${e.interaction.kind}:${e.interaction.id}`:""}:${N?"blocked":""}`})}),c?r.jsxs("div",{className:"pc-workflow-chat__error",role:"alert",children:[r.jsxs("span",{children:["Could not ",c.action==="send"?"send this message":c.action==="attach"?"attach a file":"stop the run",": ",c.message]}),r.jsx("button",{type:"button",onClick:Z,disabled:C,children:"Try again"})]}):null,r.jsxs("div",{className:"pc-workflow-chat__composer",children:[r.jsx(dg,{value:e.draft,onChange:e.onDraftChange,onSubmit:()=>void F(),placeholder:e.placeholder||"Send a message",ariaLabel:"Message",disabled:C,busy:T,sendLabel:e.sendLabel,busyLabel:e.busyLabel,rows:2,leading:e.attachments?r.jsx("div",{className:"pc-workflow-chat__attachments",children:e.attachments}):null,overlay:te,onPaste:U?$:void 0,actions:r.jsxs(r.Fragment,{children:[e.onAttach?r.jsxs("button",{type:"button",className:"pc-workflow-chat__icon-button","aria-label":"Attach file",title:"Attach file",disabled:C||l,onClick:()=>void R(),children:[r.jsx(et,{name:"paperclip",size:16}),r.jsx("span",{children:l?"Attaching…":"Attach"})]}):null,e.composerExtras,E&&e.onCancel?r.jsxs("button",{type:"button",className:"pc-workflow-chat__stop",disabled:C||s||K,onClick:()=>void G(),children:[r.jsx(et,{name:"x",size:14}),r.jsx("span",{children:s||K?"Stopping…":"Stop"})]}):I?r.jsx("span",{className:`pc-workflow-chat__stop-state pc-workflow-chat__stop-state--${I.phase}`,role:"status","aria-live":"polite",children:I.label}):null]})}),U?r.jsx("div",{className:"pc-sr-only",role:"status","aria-live":"polite",children:O}):null]}),e.footer?r.jsx("footer",{className:"pc-workflow-chat__footer",children:e.footer}):null]})}const C_="llm.delta",$h="llm.delta_end";function p1(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function ql(e){return typeof e=="string"&&e.trim()!==""}function g1(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0}function y1(e){return"reason"in e}function w1(e,t){const n=p1(e),s=n==null?void 0:n.kind,o=typeof s=="string"&&s?s:n&&"reason"in n?$h:C_,l=f=>{throw new Error(`Malformed ${o} event from the gateway: ${f}`)};if(!n)return l("the payload is not an object");s!==void 0&&s!==C_&&s!==$h&&l(`unknown kind ${JSON.stringify(s)}`),ql(n.run_id)||l("run_id is missing"),ql(n.call_id)||l("call_id is missing"),g1(n.seq)||l("seq is not a non-negative integer");const u=s?s===$h:"reason"in n;n.root_run_id!==void 0&&!ql(n.root_run_id)&&l("root_run_id is not a run id"),n.parent_run_id!==void 0&&n.parent_run_id!==null&&!ql(n.parent_run_id)&&l("parent_run_id is neither a run id nor null");const c={run_id:n.run_id,...ql(n.root_run_id)?{root_run_id:n.root_run_id}:{},...n.parent_run_id!==void 0?{parent_run_id:n.parent_run_id}:{},...ql(n.node_id)?{node_id:n.node_id}:{},call_id:n.call_id,seq:n.seq};return u?(["completed","failed","cancelled","unavailable"].includes(String(n.reason))||l(`unknown reason ${JSON.stringify(n.reason)}`),n.detail!==void 0&&n.detail!==null&&typeof n.detail!="string"&&l("detail is not a string"),{kind:$h,...c,reason:n.reason,...ql(n.detail)?{detail:n.detail}:{}}):(typeof n.text!="string"&&l("text is not a string"),n.channel!=="content"&&n.channel!=="reasoning"&&l(`unknown channel ${JSON.stringify(n.channel)}`),typeof n.snapshot!="boolean"&&l("snapshot is not a boolean"),{kind:C_,...c,text:n.text,channel:n.channel,snapshot:n.snapshot})}const v1={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 x1(e){return`This reply is not streamed: ${e?v1[e]||`the gateway reported "${e}"`:"the gateway gave no reason"}. It appears when it is complete.`}function b1(e){return e.toolApprovalGranted?null:e.interaction}const Ay={messages:[],records:[],run:null,interaction:null,status:"idle",displayStatus:"",loading:!1,error:null,connection:"idle",toolApprovalGranted:!1,stop:null};function kt(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 zs(e){return vt(e==null?void 0:e.status).toLowerCase()||"unknown"}function vr(e){return["completed","failed","cancelled"].includes(e.toLowerCase())}function Za(e){const t=kt(e),n=Number((t==null?void 0:t.status)??(t==null?void 0:t.statusCode));return n===401||n===403}function j1(e){const t=kt(e);return Number((t==null?void 0:t.status)??(t==null?void 0:t.statusCode))}function E_(e){const t=n=>{if(Array.isArray(n))return n.map(t);const s=kt(n);if(!s)return n;const o={};for(const l of Object.keys(s).sort())o[l]=t(s[l]);return o};try{return JSON.stringify(t(e))}catch{return"[unserializable]"}}function bp(e){if(typeof e=="string")return e.trim();const t=kt(e);if(!t)return"";for(const n of["answer","response","message","text","content","output"]){const s=t[n];if(typeof s=="string"&&s.trim())return s.trim()}return""}function ru(e){const t=bp(e);if(t)return t;if(!kt(e)&&!Array.isArray(e))return"";try{return JSON.stringify(e,null,2)}catch{return""}}function Ty(e){if(!e)return"";for(const s of["prompt","request","task","message","query","input"]){const o=vt(e[s]);if(o)return o}const t=kt(e.context);for(const s of["task","message"]){const o=vt(t==null?void 0:t[s]);if(o)return o}const n=sf(t==null?void 0:t.messages);for(let s=n.length-1;s>=0;s-=1){const o=kt(n[s]);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=kt(e.result);return kt(t==null?void 0:t.wait)}function $_(e){return e?vt(e.reason)==="subworkflow"||vt(e.wait_key).startsWith("subworkflow:"):!1}function My(e,t){return!!(e&&e.runId===t.runId&&vt(e.wait.wait_key)===vt(t.wait.wait_key))}function jp(e){return kt(e.effect)||{}}function S1(e,t){return vt(e.run_id)||t}function Ry(e){return vt(e.ended_at)||vt(e.started_at)||void 0}function Ly(e){const t=new Set,n=m=>{const p=vt(m);p&&t.add(p)},s=kt(e.result);n(s==null?void 0:s.sub_run_id),n(s==null?void 0:s.subRunId),n(s==null?void 0:s.child_run_id);const o=jp(e),l=kt(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=kt(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 k1{constructor(t,n={}){this.transport=t,this.options=n,this.snapshot={...Ay},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 s=n.liveRenderIntervalMs??60;if(typeof s!="number"||!Number.isFinite(s)||s<0)throw new Error(`liveRenderIntervalMs must be a non-negative number of milliseconds, got ${JSON.stringify(n.liveRenderIntervalMs)}`);this.liveRenderIntervalMs=s}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({...Ay})}dispose(){this.reset(),this.subscribers.clear()}async load(t){const n=vt(t);if(this.reset(),!n)return;const s=++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(s))return;const c=kt(l),f=kt(c==null?void 0:c.waiting),m=zs(c);if(await this.ingestHistory(u,n,s),!this.live(s))return;if(this.set({...this.snapshot,run:c,status:m,loading:!1,...f&&!vr(m)?{interaction:this.interactionWith({runId:n,wait:f})}:{}}),c&&this.updateRunState(n,c),f)for(const p of Ly({result:{wait:f}}))p!==n&&this.catchUpAndWatch(p,s);await this.catchUpAndWatch(n,s),this.pollRootLifecycle(n,s)}catch(l){!o.signal.aborted&&this.live(s)&&this.fail(l)}}async sendCommand(t,n={}){var p,g;t==="cancel"&&(this.toolApprovalStopped=!0,this.revokeToolApproval(),this.stopRequested=!0,this.recomputeStop());const s=vt(n.wait_key),o=t==="resume"?s?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"&&s&&((p=this.snapshot.interaction)==null?void 0:p.stepId)||"",u=`${o}\0${t}\0${l}\0${E_(n)}`;let c=this.commandIds.get(u);c||(c=this.newCommandId(),this.commandIds.set(u,c));const f=this.generation,m=(g=this.controller)==null?void 0:g.signal;try{const w=await this.transport.submitCommand({command_id:c,run_id:o,type:t,payload:n,...this.options.clientId?{client_id:this.options.clientId}:{}},m);if(!this.live(f))return w;const x=kt(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 s=this.requireInteraction();if(vr(this.snapshot.status))throw new Error("This run has already ended.");if(n&&(s.runId!==n.runId||vt(s.wait.wait_key)!==n.waitKey||n.stepId!==void 0&&s.stepId!==n.stepId))throw new Error("This approval request has changed. Review the current request before deciding.");if(t&&this.toolApprovalPolicy&&!this.toolCallsMatch(s,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(s.wait.wait_key),payload:{approved:!!t}}).then(l=>{if(!this.live(o))return l;const u=this.occurrenceKey(s);return this.approvedWaits.add(u),t&&this.isToolApproval(s)&&!this.grantedToolWaits.has(u)&&(this.grantedToolWaits.add(u),this.set({...this.snapshot})),l})}async approveWithPolicyChange(t,n){const s=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(s)||o!==this.approvalEpoch||this.toolApprovalStopped||vr(this.snapshot.status))&&n()}async allowAllToolsForRun(t){const n=this.generation,s=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)||s!==this.approvalEpoch||vr(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){E_(t)!==E_(this.toolApprovalPolicy)&&(this.approvalEpoch+=1,this.toolApprovalSuspended=!1,this.toolApprovalPolicy=t?{enabledTools:[...t.enabledTools],autoApproveTools:[...t.autoApproveTools]}:null,this.set({...this.snapshot}))}occurrenceKey(t){return`${t.runId}:${vt(t.wait.wait_key)}${t.stepId?`:${t.stepId}`:""}`}interactionWith(t){const n=this.snapshot.interaction;return n&&$_(t.wait)&&!$_(n.wait)?n:n&&My(n,t)&&t.stepId===void 0&&n.stepId!==void 0?{...t,stepId:n.stepId}:t}adoptDurableWait(t,n){const s=kt(n.waiting);if(!s||zs(n)!=="waiting"||$_(s)||vr(this.snapshot.status)||this.resolvedWaits.has(`${t}:${vt(s.wait_key)}`))return;const o=this.interactionWith({runId:t,wait:s}),l=this.snapshot.interaction;l&&My(l,o)&&l.stepId===o.stepId||this.set({...this.snapshot,interaction:o})}coveredByStandingPermission(t,n){var s;return t.loading||this.toolApprovalStopped||this.toolApprovalSuspended||!this.toolApprovalPolicy&&!t.autoApproveTools||vr(t.status)||((s=t.run)==null?void 0:s.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,s=n?this.occurrenceKey(n):"",o=!!(n&&this.isToolApproval(n)&&(this.grantedToolWaits.has(s)||!this.approvedWaits.has(s)&&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 m=o&&f.runId===(n==null?void 0:n.runId)?"running":"waiting";return f.status===m?c:(l=!0,this.toolMessage({...f,status:m}))});return{...t,toolApprovalGranted:o,...l?{messages:u}:{}}}toolCallsMatch(t,n){var o;const s=sf((o=kt(t.wait.details))==null?void 0:o.tool_calls);return s.length>0&&s.every(l=>{var c;const u=vt((c=kt(l))==null?void 0:c.name);return!!u&&n.includes(u)})}isToolApproval(t){const n=kt(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},s=this.occurrenceKey(t);if(this.approvedWaits.has(s))return;this.approvedWaits.add(s),this.grantedToolWaits.add(s);const o=this.generation,l=this.approvalEpoch;this.approve(!0,n).catch(u=>{if(this.live(o)){if(this.grantedToolWaits.delete(s),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 s;if(!(!this.live(n)||this.watchedRuns.has(t))){this.watchedRuns.add(t);try{if(t!==this.rootRunId)try{const o=kt(await this.transport.getRun(t,(s=this.controller)==null?void 0:s.signal));if(!this.live(n))return;o&&this.updateRunState(t,o)}catch(o){if(!this.live(n))return;if(Za(o))throw o;this.fail(o,!1)}if(await this.catchUp(t,n),!this.live(n)||vr(zs(this.runStates.get(t)||null)))return;this.childCatchUpAttempts.delete(t),this.watch(t,n)}catch(o){if(!this.live(n))return;if(this.watchedRuns.delete(t),t===this.rootRunId)throw o;if(Za(o)){this.fail(o);return}const l=(this.childCatchUpAttempts.get(t)||0)+1;if(this.childCatchUpAttempts.set(t,l),this.fail(o,!1),l>=5)return;await this.waitForRetry(Math.min(2e3,150*2**(l-1))),this.live(n)&&this.catchUpAndWatch(t,n)}}}async catchUp(t,n){var s;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,(s=this.controller)==null?void 0:s.signal);if(!this.live(n))return;const c=kt(u),f=Array.isArray(u)?u:sf(c==null?void 0:c.items);for(const p of f)this.ingestItem(t,p);const m=Number(c==null?void 0:c.next_after);if(!f.length||!Number.isFinite(m)||m<=l)break;this.cursors.set(t,m)}}async watch(t,n){try{await this.followStream(t,n)}finally{this.live(n)&&this.closeLiveRepliesVia(t)}}async followStream(t,n){var o;let s=0;for(;this.live(n)&&!vr(zs(this.runStates.get(t)||null));){const l=this.cursors.get(t)||0;this.set({...this.snapshot,connection:s?"reconnecting":"connecting"});try{let u=!1;const c=()=>{!this.live(n)||u||(u=!0,this.set({...this.snapshot,connection:"connected",error:null}))};if(this.dropLiveRepliesVia(t),await this.transport.streamLedger(t,l,m=>{this.live(n)&&(c(),this.ingestItem(t,m))},this.controller.signal,c,m=>{this.live(n)&&(c(),this.ingestDelta(t,m))}),!this.live(n)||(await this.catchUp(t,n),!this.live(n)))return;const f=kt(await this.transport.getRun(t,(o=this.controller)==null?void 0:o.signal));if(!this.live(n))return;f&&this.updateRunState(t,f),s+=1}catch(u){if(!this.live(n))return;if(s+=1,this.fail(u,!1),Za(u)){this.set({...this.snapshot,connection:"disconnected"});return}}if(s>=5||!this.live(n))break;await this.waitForRetry(Math.min(2e3,150*2**(s-1)))}if(this.live(n)){if(vr(zs(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,s){const o=kt(t);if(!o)return;const l=kt(o.session),u=sf(l==null?void 0:l.turns).map(kt).filter(m=>!!m);if(await this.hydrateHistoricalSessionRuns(u,n,s),!this.live(s))return;for(const m of u){const p=vt(m==null?void 0:m.run_id)||n;this.ingestSessionTurn(m,n,p!==n&&this.historicalRuns.get(p)||null)}const c=`turn:${n}:user`;if(!this.seenMessages.has(c)){const m=Ty(kt(o.input_data));m&&this.addMessage({id:c,role:"user",content:m})}const f=kt(o.ledgers);if(f)for(const[m,p]of Object.entries(f)){const g=kt(p);for(const w of sf(g==null?void 0:g.items))this.ingestItem(m,w)}}ingestSessionTurn(t,n,s){if(!t)return;const o=vt(t.run_id)||n,l=kt(t.input_data)||kt(t.input)||{},u=vt(t.prompt)||Ty(l);u&&this.addMessage({id:`turn:${o}:user`,role:"user",content:u,ts:vt(t.created_at)||void 0});const c=this.historicalRunFailures.get(o);if(c){const g=vt(t.answer)||bp(t.output),w=c.missing?"is unavailable because the run no longer exists":"could not be restored",x=g?` Saved reply (not verified as the final result): ${g}`:"";this.addMessage({id:`history:${o}:unavailable`,role:"system",level:"warn",title:"History",content:`The final output for an earlier turn ${w}.${x}`});return}const m=(s&&vr(zs(s))?ru(s.output):"")||(s?vt(t.answer)||bp(t.output):""),p=this.historicalEvidence.get(o);for(const g of(p==null?void 0:p.tools)||[])this.upsertTool(g);m&&this.addRunAssistantMessage(o,{id:`final:${o}`,role:"assistant",content:m,runId:o,statistics:p==null?void 0:p.statistics,ts:vt(t.updated_at)||void 0})}async hydrateHistoricalSessionRuns(t,n,s){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(s))return;let l=0,u=!1;const c=async()=>{var f,m,p;for(;!u&&this.live(s);){const g=o[l++];if(!g)return;try{const w=kt(await this.transport.getRun(g,(f=this.controller)==null?void 0:f.signal));if(!this.live(s))return;if(w){this.historicalRuns.set(g,w);try{const x=await this.transport.getHistory(g,(m=this.controller)==null?void 0:m.signal);if(!this.live(s))return;this.historicalEvidence.set(g,N_(i1(x)))}catch(x){if(!this.live(s))return;if(Za(x))throw x;this.fail(new Error(`Earlier turn activity could not be restored: ${x instanceof Error?x.message:String(x)}`),!1)}}else this.historicalRuns.set(g,null),this.historicalRunFailures.set(g,{missing:!1,detail:"gateway returned an invalid historical run snapshot"})}catch(w){if(!this.live(s))return;const x=j1(w)===404;this.historicalRuns.set(g,null),this.historicalRunFailures.set(g,{missing:x,detail:w instanceof Error?w.message:vt((p=kt(w))==null?void 0:p.detail)||"request failed"}),Za(w)&&(u=!0,this.fail(w))}}};if(await Promise.all(Array.from({length:Math.min(4,o.length)},()=>c())),u&&this.live(s))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 s=kt(n),o=kt(s==null?void 0:s.record)||s;if(!o)return;const l=S1(o,t),u=Number(s==null?void 0:s.cursor),c=Number.isFinite(u)&&u>0?u:(this.cursors.get(l)||0)+1,f=`${l}:${c}`;if(!this.seenRecords.has(f)){if(this.seenRecords.add(f),this.cursors.set(l,Math.max(this.cursors.get(l)||0,c)),this.set({...this.snapshot,records:[...this.snapshot.records,{cursor:c,record:o,runId:l}]}),this.foldRecord(l,o,f),this.snapshot.messages.some(m=>m.id===`final:${this.rootRunId}`)){const m=N_(this.snapshot.records).statistics;this.set({...this.snapshot,messages:this.snapshot.messages.map(p=>p.id===`final:${this.rootRunId}`?{...p,statistics:m}:p)})}for(const m of Ly(o))m!==l&&this.catchUpAndWatch(m,this.generation)}}foldRecord(t,n,s){var p,g,w;const o=jp(n),l=vt(o.type).toLowerCase(),u=kt(n.result),c=vt(n.status).toLowerCase(),f=Ry(n);if(this.foldStopEvidence(t,n,l,c),["llm_call","tool_calls"].includes(l)&&["started","running"].includes(c)){const x=Date.parse(f||"");(!Number.isFinite(x)||x>=this.displayStatusAt)&&(Number.isFinite(x)&&(this.displayStatusAt=x),this.snapshot.displayStatus&&this.set({...this.snapshot,displayStatus:""}))}if(l==="answer_user"&&c==="completed"){const x=ru(u)||ru(kt(o.payload));x&&this.addRunAssistantMessage(t,{id:`answer:${t}:${s}`,role:"assistant",content:x,ts:f})}if(l==="emit_event"&&c==="completed"){const x=kt(o.payload)||{},S=kt(u),j=vt(x.name)||vt(S==null?void 0:S.name),N=x.payload!==void 0?x.payload:S==null?void 0:S.payload;if(["abstract.message","abstractcode.message"].includes(j)){const C=ru(N);if(C){const E=vt((p=kt(N))==null?void 0:p.level).toLowerCase(),T=E==="error"?"error":["warn","warning"].includes(E)?"warn":"info";this.addMessage({id:`event:${t}:${s}`,role:"system",title:"Workflow",content:C,level:T,ts:f})}}if(["abstract.status","abstractcode.status"].includes(j)){const C=kt(N),E=C?C.status??C.text??C.value:N,T=Date.parse(f||"");!vr(this.snapshot.status)&&typeof E=="string"&&(!Number.isFinite(T)||T>=this.displayStatusAt)&&(Number.isFinite(T)&&(this.displayStatusAt=T),this.set({...this.snapshot,displayStatus:E.trim()}))}if(["abstract.tool_execution","abstractcode.tool_execution","abstract.tool_result","abstractcode.tool_result"].includes(j)){const C=ru(N);C&&this.addMessage({id:`event:${t}:${s}`,role:"system",title:"Tool activity",content:C,ts:f})}}const m=_x(n);if(c==="waiting"&&m&&!vr(this.snapshot.status)&&!vr(zs(this.runStates.get(t)||null))&&(this.resolvedWaits.delete(`${t}:${vt(m.wait_key)}`),this.set({...this.snapshot,interaction:this.interactionWith({runId:t,wait:m,...vt(n.step_id)?{stepId:vt(n.step_id)}:{}})})),l==="tool_calls")for(const x of fx(this.toolActivities,{runId:t,cursor:this.cursors.get(t)||0,record:n}))this.upsertTool(x);if(l==="resume"&&(u==null?void 0:u.resumed)===!0){const x=vt((g=kt(o.payload))==null?void 0:g.wait_key);x&&this.resolvedWaits.add(`${t}:${x}`),((w=this.snapshot.interaction)==null?void 0:w.runId)===t&&(this.set({...this.snapshot,interaction:null}),this.refreshRunState(t,this.generation))}}foldStopEvidence(t,n,s,o){let l=!1;if(s==="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(s==="emit_event"&&o==="completed"){const u=kt(jp(n).payload)||{},c=kt(n.result),f=vt(u.name)||vt(c==null?void 0:c.name),m=kt(u.payload!==void 0?u.payload:c==null?void 0:c.payload);f==="abstract.status"&&vt(m==null?void 0:m.killed_by)==="kill_switch"&&(this.forcedStop=m,l=!0)}l&&this.recomputeStop()}recomputeStop(){let t=null;this.forcedStop?t={phase:"forced",label:vt(this.forcedStop.text)||"Stop forced: inference killed",record:this.forcedStop}:this.stopRequested&&(t=this.snapshot.status==="cancelled"&&this.openLlmSteps.size===0?{phase:"stopped",label:"Stopped"}:{phase:"stopping",label:"Stopping…"});const n=this.snapshot.stop||null;((n==null?void 0:n.phase)!==(t==null?void 0:t.phase)||(n==null?void 0:n.label)!==(t==null?void 0:t.label))&&this.set({...this.snapshot,stop:t}),(t==null?void 0:t.phase)==="stopping"&&this.snapshot.status==="cancelled"&&this.followStop(this.generation)}async followStop(t){var n;if(!this.stopFollowing){this.stopFollowing=!0;try{let s=500,o=null;for(;this.live(t)&&((n=this.snapshot.stop)==null?void 0:n.phase)==="stopping";){if(await this.waitForRetry(s),!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),s=Math.min(5e3,s*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),s=this.snapshot.messages.findIndex(l=>l.id===n.id);if(s<0){this.addMessage(n);return}const o=[...this.snapshot.messages];o[s]=n,this.set({...this.snapshot,messages:o})}addRunAssistantMessage(t,n){this.closeLiveRepliesOfRun(t);const s=`answer:${t}:`,o=`final:${t}`;this.snapshot.messages.some(l=>l.role==="assistant"&&l.content===n.content&&(l.id===o||String(l.id||"").startsWith(s)))||this.addMessage(n)}ingestDelta(t,n){let s;try{s=w1(n)}catch(f){this.fail(f,!1);return}const o=`${s.run_id}:${s.call_id}`;if(y1(s)){if(s.reason==="unavailable"){this.noteStreamUnavailable(s);return}if(s.reason==="cancelled"&&s.detail==="reinvoked"){this.closeLiveReply(o,"restarted");return}this.closeLiveReply(o,s.reason==="completed"?void 0:s.reason);return}if(this.closedLiveCalls.has(o)||this.runEnded(s.run_id)||this.runEnded(this.rootRunId))return;const l=this.liveReplies.get(o)||{runId:s.run_id,callId:s.call_id,nodeId:s.node_id||"",via:t,text:"",reasoning:"",seq:{content:-1,reasoning:-1}},u=s.channel==="reasoning"?"reasoning":"text",c=l.seq[s.channel];if(s.snapshot){if(s.seq<c)return;l[u]=s.text}else{if(s.seq<=c)return;l[u]+=s.text}l.seq[s.channel]=s.seq,l.via=t,this.liveReplies.set(o,l),this.liveDirty.add(o),this.scheduleLiveRender()}runEnded(t){return vr(zs(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 s=this.liveReplies.get(n);if(!s)continue;const o=this.liveMessage(s),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 s=this.liveReplies.get(t);if(!s){n==="restarted"&&this.shownLiveCalls.has(t)&&this.addMessage(this.restartNote(t));return}this.liveReplies.delete(t),this.liveDirty.delete(t);const o=`live:${s.runId}:${s.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:${s.runId}:${s.callId}`;this.seenMessages.add(c),u[l]={id:c,role:"system",level:"warn",title:"Reply",runId:s.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:x1(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 s of[...this.liveReplies.values()])(s.via===t||s.runId===t)&&this.closeLiveReply(`${s.runId}:${s.callId}`,n)}endLiveRepliesOfRun(t,n){const s=n==="failed"||n==="cancelled"?n:void 0;if(t===this.rootRunId){for(const o of[...this.liveReplies.values()])this.closeLiveReply(`${o.runId}:${o.callId}`,s);this.closedLiveCalls.clear(),this.shownLiveCalls.clear();return}this.closeLiveRepliesVia(t,s);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[s,o]of this.liveReplies)o.via===t&&(this.liveReplies.delete(s),this.liveDirty.delete(s),n.add(`live:${o.runId}:${o.callId}`));n.size&&this.set({...this.snapshot,messages:this.snapshot.messages.filter(s=>!n.has(String(s.id)))})}fail(t,n=!0){var s,o,l;Za(t)&&(this.approvalEpoch+=1,this.toolApprovalStopped=!0,this.toolApprovalSuspended=!0,(o=(s=this.options).onAuthError)==null||o.call(s,t)),this.set({...this.snapshot,error:t instanceof Error?t.message:vt((l=kt(t))==null?void 0:l.detail)||String(t),...Za(t)?{autoApproveTools:!1}:{},...n?{connection:"disconnected"}:{}})}newCommandId(){const t=globalThis.crypto;if(t&&typeof t.randomUUID=="function")return t.randomUUID();if(t&&typeof t.getRandomValues=="function"){const n=t.getRandomValues(new Uint8Array(16));n[6]=n[6]&15|64,n[8]=n[8]&63|128;const s=Array.from(n,o=>o.toString(16).padStart(2,"0")).join("");return`${s.slice(0,8)}-${s.slice(8,12)}-${s.slice(12,16)}-${s.slice(16,20)}-${s.slice(20)}`}return`workflow-${Date.now()}-${Math.random().toString(36).slice(2)}`}updateRunState(t,n){var l;if(this.runStates.set(t,n),vr(zs(n))&&this.endLiveRepliesOfRun(t,zs(n)),t!==this.rootRunId){vr(zs(n))&&((l=this.snapshot.interaction)==null?void 0:l.runId)===t?this.set({...this.snapshot,interaction:null}):this.adoptDurableWait(t,n);return}const s=zs(n),o=vr(s);if(o){const u=ru(n.output);u&&this.upsertFinal(t,u,Ry(n))}this.set({...this.snapshot,run:n,status:s,...o?{interaction:null,autoApproveTools:!1,displayStatus:""}:{}}),o||this.adoptDurableWait(t,n),(this.stopRequested||this.forcedStop)&&this.recomputeStop()}upsertFinal(t,n,s){this.closeLiveRepliesOfRun(t);const o=`final:${t}`;this.seenMessages.add(o);const l={id:o,role:"assistant",content:n,ts:s,runId:t,statistics:N_(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 s;try{const o=kt(await this.transport.getRun(t,(s=this.controller)==null?void 0:s.signal));o&&this.live(n)&&this.updateRunState(t,o)}catch(o){this.live(n)&&this.fail(o,!1)}}async pollRootLifecycle(t,n){var s;for(;this.live(n)&&this.rootRunId===t&&!vr(zs(this.runStates.get(t)||null));){if(await this.waitForRetry(2e3),!this.live(n)||this.rootRunId!==t||vr(zs(this.runStates.get(t)||null)))return;try{const o=kt(await this.transport.getRun(t,(s=this.controller)==null?void 0:s.signal));o&&this.live(n)&&this.rootRunId===t&&this.updateRunState(t,o)}catch(o){if(!this.live(n))return;if(Za(o)){this.fail(o);return}this.fail(o,!1)}}}waitForRetry(t){var o;const n=(o=this.controller)==null?void 0:o.signal;if(!n||n.aborted)return Promise.resolve();const s=n;return new Promise(l=>{const u=setTimeout(f,t),c=()=>{clearTimeout(u),f()};function f(){s.removeEventListener("abort",c),l()}s.addEventListener("abort",c,{once:!0})})}}function N1(e){const t=_.useMemo(()=>new k1(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=_.useSyncExternalStore(o=>t.subscribe(o),()=>t.getSnapshot(),()=>t.getSnapshot()),s=String(e.runId||"").trim();return _.useEffect(()=>{t.setToolApprovalPolicy(e.enabled===!1?{enabledTools:[],autoApproveTools:[]}:e.toolApprovalPolicy??null)},[t,e.toolApprovalPolicy,e.enabled]),_.useEffect(()=>{if(e.enabled===!1||!s){t.reset();return}return t.load(s),()=>t.reset()},[t,s,e.enabled]),{controller:t,snapshot:n}}function Hl(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function ls(e){return typeof e=="string"?e.trim():e==null?"":typeof e=="number"||typeof e=="boolean"?String(e):""}function Iy(e){return["session","workflow","run","global"].includes(e)?e:null}function el(e){return{scope:ls(e==null?void 0:e.scope).toLowerCase(),name:ls(e==null?void 0:e.name)||ls(e==null?void 0:e.event_name),scopeId:ls(e==null?void 0:e.scope_id)||ls(e==null?void 0:e.scopeId),sessionId:ls(e==null?void 0:e.session_id)||ls(e==null?void 0:e.sessionId),workflowId:ls(e==null?void 0:e.workflow_id)||ls(e==null?void 0:e.workflowId),runId:ls(e==null?void 0:e.run_id)||ls(e==null?void 0:e.runId)}}function C1(e,t){const n=e.wait,s=ls(n.wait_key),o=[el(n),el(Hl(n.details))];for(const l of t){if(l.runId!==e.runId)continue;const u=l.record,c=Hl(u.result),f=Hl(c==null?void 0:c.wait),m=Hl(u.effect),p=Hl(m==null?void 0:m.payload);ls(f==null?void 0:f.wait_key)!==s&&ls(p==null?void 0:p.wait_key)!==s||o.push(el(u),el(p),el(Hl(p==null?void 0:p.details)),el(f),el(Hl(f==null?void 0:f.details)))}return o}function A_(e,t){return t.scopeId?t.scopeId:e==="session"?t.sessionId:e==="workflow"?t.workflowId:e==="run"?t.runId:"global"}function px(e,t,n){return{scope:e,scopeId:t,name:n,...e==="session"?{sessionId:t}:{},...e==="workflow"?{workflowId:t}:{},...e==="run"?{runId:t}:{}}}function E1(e,t,n){if(!n)return null;const s=`evt:${t}:${n}:`;if(!e.startsWith(s))return null;const o=e.slice(s.length);return o?px(t,n,o):null}function $1(e,t=[],n){if(!e)return{target:null,error:"No event wait is available."};const s=ls(e.wait.wait_key),o=/^evt:(session|workflow|run|global):/.exec(s);if(!o)return{target:null,error:"The gateway did not provide a canonical event wait key."};const l=Iy(o[1]);if(!l)return{target:null,error:"The event wait uses an unsupported scope."};const u=C1(e,Array.isArray(t)?t:[]),c=new Map;for(const w of u){const x=Iy(w.scope);if(!x||!w.name)continue;if(x!==l)return{target:null,error:"Event metadata conflicts with the canonical wait scope."};const S=`evt:${x}:`,j=`:${w.name}`;if(!s.startsWith(S)||!s.endsWith(j)||s.length<=S.length+j.length)return{target:null,error:"Event metadata does not exactly match the canonical wait key."};const N=s.slice(S.length,-j.length),C=A_(x,w);if(C&&C!==N)return{target:null,error:"Event metadata conflicts with the canonical wait target."};const E=px(x,N,w.name);c.set(`${E.scope}\0${E.scopeId}\0${E.name}`,E)}if(c.size>1)return{target:null,error:"Multiple event targets match this wait; routing is unavailable."};if(c.size===1)return{target:[...c.values()][0]};const f=new Set;l==="run"&&f.add(e.runId),l==="global"&&f.add("global");for(const w of u){const x=A_(l,w);x&&f.add(x)}if(ls(n==null?void 0:n.run_id)===e.runId){const w=el(n||null),x=A_(l,w);x&&f.add(x)}const p=[...f].map(w=>E1(s,l,w)).filter(w=>!!w),g=new Map(p.map(w=>[`${w.scope}\0${w.scopeId}\0${w.name}`,w]));return g.size===1?{target:[...g.values()][0]}:g.size>1?{target:null,error:"The event key is ambiguous for the available scope metadata."}:{target:null,error:"The gateway did not provide enough canonical event routing metadata."}}const fg=e=>wt(`runs/${encodeURIComponent(e)}/workspace`);function A1(e){return fg(e)}function T1(e,t){return`${fg(e)}/files?${new URLSearchParams({path:t,recursive:"false"})}`}function M1(e,t){return`${fg(e)}/content?${new URLSearchParams({path:t})}`}async function $m(e,t){let n="";try{const s=await e.text();try{const o=JSON.parse(s),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:s}catch{n=s}}catch{n=""}return new Error(`${t} (HTTP ${e.status}): ${n.trim()||e.statusText||"no reason given"}`)}function R1(e,t){const n=e&&typeof e=="object"&&!Array.isArray(e)?e:null,s=u=>{throw new Error(`Unexpected /workspace/files response from the gateway: ${u}.`)};if(!n)return s("not an object");Array.isArray(n.entries)||s("no `entries` list"),typeof n.truncated!="boolean"&&s("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")&&s(`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 L1(e,t,n){const s=await e(A1(t),{signal:n});if(!s.ok)throw await $m(s,"The workspace is not available");const o=await s.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 I1(e,t,n,s){const o=await e(T1(t,n),{signal:s});if(!o.ok)throw await $m(o,"The folder could not be listed");return R1(await o.json(),n)}async function P1(e,t,n,s){const o=await e(M1(t,n),{signal:s});if(!o.ok)throw await $m(o,"The file could not be read");return await o.blob()}async function O1(e,t,n,s){const o=await L1(e,t,s);return{where:o,listing:o.exists?await I1(e,t,n,s):null}}function D1(e){const t=String(e||"").split("/").filter(Boolean),n=[{label:"Workspace",path:""}];return t.forEach((s,o)=>n.push({label:s,path:t.slice(0,o+1).join("/")})),n}function F1(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,s=0;for(;n>=1024&&s<t.length-1;)n/=1024,s+=1;return`${n<10?n.toFixed(1):Math.round(n)} ${t[s]}`}function z1(e){return[...e].sort((t,n)=>t.type===n.type?t.name.localeCompare(n.name):t.type==="dir"?-1:1)}function B1(e){const t=e.hidden||{},n=Number(t.blocked||0)+Number(t.outside_links||0)+Number(t.other||0),s=[];return n>0&&s.push(`${n} ${n===1?"entry":"entries"} hidden by the gateway's workspace rules`),e.truncated&&s.push("the list is truncated"),s.join("; ")}const U1=new Set(["image/png","image/jpeg","image/gif","image/webp","image/avif","image/bmp","application/pdf","text/plain","application/json"]);function W1(e){const t=String(e||"").split(";",1)[0].trim().toLowerCase();return U1.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 gx(e,t,n){const s=n==="open"?W1(e.type):{mode:"download"},o=s.mode==="open"&&s.type!==e.type?new Blob([e],{type:s.type}):e,l=URL.createObjectURL(o);if(s.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 q1(e,t,n){const s=await e(yj(t),{signal:n.signal});if(!s.ok)throw await $m(s,`${n.name} could not be read`);gx(await s.blob(),n.name,n.mode??"open")}function yx(e){const{fetchGateway:t,runId:n}=e,[s,o]=_.useState({runId:n,path:""}),l=s.runId===n?s.path:"",[u,c]=_.useState(null),[f,m]=_.useState(""),[p,g]=_.useState(!!n),[w,x]=_.useState(""),[S,j]=_.useState(0);_.useEffect(()=>{if(!n)return;const E=new AbortController;return g(!0),m(""),(async()=>{try{const T=await O1(t,n,l,E.signal);E.signal.aborted||c({runId:n,...T})}catch(T){E.signal.aborted||m(String((T==null?void 0:T.message)||T))}finally{E.signal.aborted||g(!1)}})(),()=>E.abort()},[t,n,l,S,e.refreshKey]);const N=u&&u.runId===n?u:null,C=_.useCallback(async(E,T)=>{x(E.path),m("");try{gx(await P1(t,n,E.path),E.name,T)}catch(I){m(String((I==null?void 0:I.message)||I))}finally{x("")}},[t,n]);return r.jsx(H1,{title:e.title,note:e.note,where:(N==null?void 0:N.where)??null,path:l,listing:(N==null?void 0:N.listing)??null,error:f,loading:p,fileBusy:w,selectedPath:e.selectedPath,className:e.className,onNavigate:E=>o({runId:n,path:E}),onRefresh:()=>j(E=>E+1),onFile:e.onSelectFile?void 0:(E,T)=>void C(E,T),onSelectFile:e.onSelectFile,onClose:e.onClose})}function H1(e){var s,o,l,u;const t=e.listing?B1(e.listing):"",n=(o=(s=e.where)==null?void 0:s.host)==null?void 0:o.hostname;return r.jsxs("section",{className:`pc-ws${e.className?` ${e.className}`:""}`,"aria-label":e.title,"data-workspace-root":((l=e.where)==null?void 0:l.workspace_root)||void 0,children:[r.jsxs("header",{className:"pc-ws__head",children:[r.jsxs("span",{className:"pc-ws__title",children:[r.jsx(et,{name:"folder",size:15})," ",e.title]}),r.jsx("span",{className:"pc-ws__spacer"}),r.jsx("button",{type:"button",className:"pc-ws__icon-btn","data-action":"refresh-folder",onClick:e.onRefresh,disabled:e.loading,title:"Refresh","aria-label":"Refresh the folder",children:r.jsx(et,{name:"refresh",size:14})}),e.onClose?r.jsx("button",{type:"button",className:"pc-ws__icon-btn","data-action":"close-folder",onClick:e.onClose,title:"Close","aria-label":"Close the file browser",children:r.jsx(et,{name:"x",size:14})}):null]}),e.where?r.jsxs("div",{className:"pc-ws__root",children:[r.jsx("code",{children:e.where.workspace_root}),n&&((u=e.where.host)==null?void 0:u.caller_is_this_machine)!==!0?r.jsxs("span",{className:"pc-ws__muted",children:[" on the gateway host ",n]}):null]}):null,e.note?r.jsx("div",{className:"pc-ws__muted",children:e.note}):null,r.jsx("nav",{className:"pc-ws__crumbs","aria-label":"Folder",children:D1(e.path).map((c,f,m)=>f===m.length-1?r.jsx("span",{"aria-current":"page",children:c.label},c.path):r.jsxs(ve.Fragment,{children:[r.jsx("button",{type:"button",className:"pc-ws__crumb",onClick:()=>e.onNavigate(c.path),children:c.label}),r.jsx("span",{className:"pc-ws__muted",children:" / "})]},c.path))}),e.error?r.jsx("div",{className:"pc-ws__error",role:"alert",children:e.error}):null,e.loading&&!e.listing?r.jsx("div",{className:"pc-ws__muted",role:"status",children:"Loading…"}):null,e.where&&!e.where.exists?r.jsx("div",{className:"pc-ws__muted",children:"The folder does not exist yet: nothing has been written."}):null,e.listing?e.listing.entries.length?r.jsx("ul",{className:"pc-ws__entries",children:z1(e.listing.entries).map(c=>r.jsx("li",{className:`pc-ws__entry${e.selectedPath===c.path?" is-selected":""}`,"data-type":c.type,"data-path":c.path,children:c.type==="dir"?r.jsxs("button",{type:"button",className:"pc-ws__name","data-action":"open-dir",onClick:()=>e.onNavigate(c.path),children:[r.jsx(et,{name:"folder",size:14})," ",c.name,"/"]}):r.jsxs(r.Fragment,{children:[e.onSelectFile?r.jsxs("button",{type:"button",className:"pc-ws__name","data-action":"select-file","aria-pressed":e.selectedPath===c.path,onClick:()=>{var f;return(f=e.onSelectFile)==null?void 0:f.call(e,c)},children:[r.jsx(et,{name:"file",size:14})," ",c.name]}):r.jsxs("span",{className:"pc-ws__name",children:[r.jsx(et,{name:"file",size:14})," ",c.name]}),r.jsx("span",{className:"pc-ws__size",children:F1(c.size_bytes)}),e.onFile?r.jsxs(r.Fragment,{children:[r.jsx("button",{type:"button",className:"pc-ws__btn","data-action":"open-file",disabled:e.fileBusy===c.path,onClick:()=>{var f;return(f=e.onFile)==null?void 0:f.call(e,c,"open")},children:"Open"}),r.jsx("button",{type:"button",className:"pc-ws__icon-btn","data-action":"download-file",disabled:e.fileBusy===c.path,onClick:()=>{var f;return(f=e.onFile)==null?void 0:f.call(e,c,"download")},title:`Download ${c.name}`,"aria-label":`Download ${c.name}`,children:r.jsx(et,{name:"download",size:14})})]}):null]})},c.path))}):r.jsx("div",{className:"pc-ws__muted",children:"This folder is empty."}):null,t?r.jsx("div",{className:"pc-ws__muted","data-hidden-note":"true",children:t}):null]})}function wx(e){return r.jsx(ox,{text:e,images:"link"})}const V1={trigger:"Trigger",answer:"Automation"};function G1(e){return r.jsx(cg,{message:{id:`${e.runId}:${e.kind}`,role:e.role,content:e.text,title:V1[e.kind],runId:e.runId},images:"link"})}const K1={renderText:wx,renderTurn:G1};function Y1(e){const{fetchGateway:t,...n}=e,s=n.onOpenResource??(t?o=>q1(t,o.url,{name:o.name}):void 0);return r.jsx(nk,{...n,onOpenResource:s,...K1})}function J1(e,t,n={}){if(!e)return null;const s=e.wait,o=`${e.runId}:${s.wait_key}:${e.stepId||""}`,l=s.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(s.wait_key||""),stepId:e.stepId},m=[...new Set(c.map(g=>String((g==null?void 0:g.name)||"tool")))],p=n.onPermissionsAll;return{id:o,kind:"tool-approval",title:`${c.length||"Requested"} ${c.length===1?"action needs":"actions need"} permission`,toolName:m.join(", ")||"the requested tools",description:"Review the targets below. Allow once approves this batch only.",detail:r.jsxs("div",{className:"pc-approval-summary",children:[r.jsx(cx,{tools:c.map((g,w)=>({id:String((g==null?void 0:g.call_id)||(g==null?void 0:g.id)||w),runId:e.runId,name:(g==null?void 0:g.name)||"Tool",arguments:g==null?void 0:g.arguments,status:"waiting"}))}),r.jsxs("details",{children:[r.jsx("summary",{children:"Review full tool arguments (JSON)"}),r.jsx(Ir,{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(s.reason==="user"||s.reason==="ask_user")return{id:o,kind:"ask-user",title:"A question for you",prompt:String(s.prompt||l.prompt||"How would you like to continue?"),allowFreeText:s.allow_free_text!==!1,choices:(Array.isArray(s.choices)?s.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(s.wait_key||"");if(s.reason==="event"||u.startsWith("evt:")){const c=$1(e,n.records||[],n.currentRun??null),f=c.target,m=(f==null?void 0:f.name)||"";return{id:o,kind:"event-wait",title:f?"Waiting for an event":"Event routing unavailable",eventName:m,prompt:String(s.prompt||`This workflow will continue when “${m||"its trigger"}” arrives.`),description:f?"You can also send the expected event here.":`This event cannot be sent safely. ${c.error}`,initialPayload:"{}",payloadLabel:"Event data (JSON)",sendLabel:"Send event",onSend:async p=>{if(!f)throw new Error(c.error);const g=JSON.parse(p||"{}"),w={name:f.name,scope:f.scope,payload:g};f.scope==="session"?w.session_id=f.scopeId:f.scope==="workflow"?w.workflow_id=f.scopeId:f.scope==="run"&&(w.run_id=f.scopeId),await t.emitEvent(w)}}}return null}const X1='# AbstractObserver\n\n> Gateway-only observability UI (Web/PWA) for AbstractFramework runs: a browser SPA + tiny Node.js CLI that connects to an AbstractGateway HTTP API (HTTP fetch + SSE ledger streaming) and submits durable commands.\n\nThis repository is UI-only:\n- The packaged CLI (`bin/cli.js` + `bin/server.js`) serves `dist/` (SPA fallback) at `/` or through the gateway at `/apps/observer/` (app-server mount contract: identity header, `<base href>`, cookie path, forwarded client address) and proxies `api/` to the Gateway after browser-session sign-in, using `@abstractframework/app-server`.\n- The browser talks to same-origin `/api` in hosted mode; direct Gateway URLs remain available for local development via `src/lib/gateway_client.ts` (treat this file as the source of truth for HTTP endpoints and request shapes).\n- Hosted sign-in uses Gateway URL + user + token only to create an app-scoped browser session. Settings persistence strips Gateway bearer tokens. With `@abstractframework/app-server` 0.1.10 or newer the proxy sends the browser\'s connection address as `X-Forwarded-For` and `X-AbstractFramework-App-Proxy: abstractobserver` to the Gateway.\n- On non-local hosted UI hostnames, the server-configured Gateway URL is authoritative; browser-supplied Gateway URL changes are rejected unless `ABSTRACTOBSERVER_ALLOW_REMOTE_BROWSER_GATEWAY_CONFIG=1` is enabled behind access control. Forwarded host headers are trusted only when `ABSTRACTOBSERVER_TRUST_PROXY_HEADERS=1` or `ABSTRACTGATEWAY_TRUST_PROXY_HEADERS=1`.\n\n## Quickstart\n- Run packaged UI server (no build step): `npx --yes --package @abstractframework/observer -- abstractobserver`\n- Dev server (Vite; proxies `/api` in dev): `npm install && npm run dev`\n- Unit tests (Vitest): `npm test`\n- Production build (writes `dist/`): `npm run build`\n- Regenerate `llms-full.txt`: `npm run llms:full`\n\nNotes:\n- Build output lives in `dist/` and is served by `bin/cli.js` (don’t edit `dist/` manually).\n- `@abstractframework/ui-kit` and `@abstractframework/panel-chat` are npm dependencies; the monitor packages are Vite aliases to sibling `../abstractuic/*/src` (see `vite.config.ts` and `docs/development.md`).\n- Responsive layout (phones, tablets, small windows): `docs/getting-started.md` → "Responsive layout"; rules in `src/ui/responsive.css`.\n- On/off switches and opening the Observer over plain http from another computer (voice needs https): `docs/getting-started.md` → "Switches", "Open the Observer from another computer over http"; fallbacks in `src/lib/secure-context.ts`.\n- `llms.txt` format reference: https://llmstxt.org/\n\n## Documentation (start here)\n- [README](README.md): Install and quickstart\n- [Getting started](docs/getting-started.md): Run the UI and connect to a gateway; Ask about a run (whole conversation, History note when the 50k-token window drops older messages, error cards never sent back) vs the top-bar Assistant (one gateway session per conversation, New conversation, no tools)\n- [FAQ](docs/faq.md): Common questions (grounded in code), including the CLI `/api` session proxy, the About dialog, chat history windows and the tool-less Assistant\n- [Docs index](docs/README.md): What to read next\n- [Architecture](docs/architecture.md): Components, data flow, diagrams\n- [Configuration](docs/configuration.md): launch flags, serving under the gateway at /apps/observer/, UI settings, deployment patterns\n- [API](docs/api.md): Gateway endpoints used by the UI, including Runtime Activity run pages and canonical artifact envelope search/stats for Runtime Artifact Explorer\n- [Automations](docs/automations.md): 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 xr(){return Sm()}function Z1(e,t){return[...e.filter(n=>!n.local_error),t].map(n=>({role:n.role,content:n.content}))}function Ah(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?Math.trunc(e):0}function Q1(e){const t=Ah(e==null?void 0:e.dropped_messages);if(!e||t<=0)return null;const n=Ah(e.replayed_messages),s=Ah(e.dropped_tokens),o=Ah(e.max_tokens),l=[`Earlier messages not replayed: ${t.toLocaleString("en-US")}${s?` (~${s.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 vx(e){const t=Q1(e.history);return t?r.jsx(cg,{message:{role:"system",level:"info",title:"History",content:t}}):null}const eN=1500,tN=12e4;function nN(e,t){return new Promise((n,s)=>{const o=setTimeout(n,e);t.addEventListener("abort",()=>{clearTimeout(o),s(new DOMException("aborted","AbortError"))},{once:!0})})}const rN=["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) ===",X1,"=== END DOCUMENTATION ==="].join(`
67
- `),sN="observer-docs-assistant";function Py(){return`${sN}:${xr()}`}function iN(e){return{prompt:e,system:rN,tools:[],use_session_history:!0,use_context:!0}}function oN(e){var t,n;for(let s=e.length-1;s>=0;s--){const o=e[s],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 aN(e,t,n=()=>{}){return async(s,o)=>{var f;const l=e(),u=await l.start_run(null,iN(s),{bundle_id:"basic-agent",session_id:t()}),c=Date.now();for(;;){if(await nN(eN,o.signal),Date.now()-c>tN)throw new Error("The assistant run timed out (120s). The run is still visible on the Observe page.");const m=await l.get_run(u),p=String((m==null?void 0:m.status)||"").trim().toLowerCase();if(p==="failed"||p==="cancelled"){const g=String(((f=m==null?void 0:m.error)==null?void 0:f.message)||(m==null?void 0:m.error)||"run "+p).slice(0,400);throw new Error(`The assistant run ${p}: ${g}`)}if(p==="completed"){n((m==null?void 0:m.session_history)??null);const g=await l.get_ledger(u,{after:0,limit:500,signal:o.signal});return oN(g.items)||"(the run completed but produced no readable answer — inspect it on the Observe page)"}}}}function lN(e){const t=_.useRef(e.gateway);t.current=e.gateway;const n=_.useRef(Py()),[s,o]=_.useState([]),[l,u]=_.useState(null),c=_.useMemo(()=>aN(()=>t.current,()=>n.current,u),[]),[f]=_.useState(void 0),m=()=>{n.current=Py(),o([]),u(null)};return r.jsxs(Lj,{open:e.open,onClose:e.onClose,label:"Observer assistant",title:"Assistant",width:420,topOffset:e.topOffset,headerActions:r.jsx("button",{className:"btn",type:"button",disabled:!s.length,onClick:m,title:"Start a new conversation (nothing earlier is replayed)",children:"New conversation"}),children:[r.jsx(vx,{history:l}),r.jsx(t1,{ask:c,messages:s,onMessagesChange:o,assistantName:"Observer",placeholder:"Ask about the observer…",blockedNotice:e.connected?f:"Connect to the gateway to use the assistant.",suggestions:["How do I see why a run failed?","Where do I find the artifacts a run produced?","What does the Board's Review column mean?","How do I launch a workflow on a schedule?"],emptyState:r.jsx("div",{children:"Answers are grounded in this app's documentation. Each question runs once through the connected gateway's basic agent."})})]})}function cN(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 uN(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 dN(e,t,n){return e<=0?-1:t<0?n?e-1:0:(t+(n?e-1:1))%e}const fN='a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';function hN(e){return typeof document>"u"?!1:Array.from(document.querySelectorAll('[role="dialog"][aria-modal="true"]')).some(t=>t!==e)}function mN(e){const[t,n]=_.useReducer(cN,!1),s=_.useRef(null),o=_.useRef(null),l=_.useRef(!1);return _.useEffect(()=>{n({type:"page_change"})},[e.page]),_.useEffect(()=>{n({type:"layout_change"})},[e.is_drawer]),_.useEffect(()=>{var u;if(t){l.current=!0;const c=o.current,f=(c==null?void 0:c.querySelector(".shell_nav_item.active"))||(c==null?void 0:c.querySelector(".shell_nav_item"));f==null||f.focus();const m=p=>{if(p.key==="Escape"){n({type:"escape",default_prevented:p.defaultPrevented,other_modal_open:hN(o.current)});return}if(p.key!=="Tab"||!o.current)return;const g=Array.from(o.current.querySelectorAll(fN)).filter(x=>x.offsetParent!==null||x===document.activeElement),w=dN(g.length,g.indexOf(document.activeElement),p.shiftKey);w>=0&&(p.preventDefault(),g[w].focus())};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)}l.current&&(l.current=!1,(u=s.current)==null||u.focus())},[t]),{open:t,set_open:u=>n({type:u?"open":"close"}),toggle_ref:s,sidebar_ref:o,attrs:uN(e.is_drawer,t)}}const _N="api/local/reveal",pN="sw.js",Sp="#run/";function gN(e){return`${Sp}${encodeURIComponent(String(e||"").trim())}`}function xx(e){const t=String(e||"");if(!t.startsWith(Sp))return"";const n=t.slice(Sp.length).split("?")[0];if(!n||n.includes("/"))return"";try{return decodeURIComponent(n).trim()}catch{return""}}function yN(e){return`Run ${e} cannot be opened: it does not exist on this gateway, or your account cannot see it.`}function wN(e){const t=xx(e.hash);if(t)return t;const n=u=>/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(u),s=u=>{const c=u.split("/").filter(Boolean);return c.length?c[c.length-1].trim():""},o=s(String(e.hash||"").replace(/^#/,""));if(n(o))return o;const l=s(String(e.pathname||""));return n(l)?l:""}const vN={llm_call:"llm_call",tool_calls:"tool",tool_invoke:"tool",entity_tools_execute:"tool",start_subworkflow:"subflow",emit_event:"event",wait_event:"wait",wait_until:"wait",resume:"resume",ask_user:"ask",answer_user:"answer",model_residency:"model",memory_query:"memory",memory_tag:"memory",memory_compact:"memory",memory_note:"memory",memory_rehydrate:"memory",memory_kg_assert:"memory",memory_kg_query:"memory",memory_kg_resolve:"memory",memory_recall:"memory",memory_access:"memory",memory_form:"memory",memory_adjust:"memory",memory_appraise:"memory",memory_consolidate:"memory",memory_probe:"memory",memory_tend:"memory",diary_write:"memory",diary_read:"memory",life_query:"memory",entity_tools_query:"memory",vars_query:"memory"},xN=new Set(["wait","resume","memory","model","node"]),bN=new Set(["abstract.status","abstract.progress","abstract.steer_seen","abstract.summary"]),jN={llm_call:"LLM call",tool:"Tools",subflow:"Subflow",event:"Event",wait:"Wait",resume:"Resume",ask:"Question",answer:"Answer",memory:"Memory",model:"Model",node:"Node",other:"Effect"};function SN(e){const t=String(e||"").trim();return t?vN[t]||"other":"node"}function kN(e,t,n){return n?!1:e==="event"?bN.has(String(t||"").trim()):xN.has(e)}const NN=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function CN(e){const t=new TextEncoder().encode(e),n=t.length*8,s=t.length+9+63>>6<<6,o=new Uint8Array(s);o.set(t),o[t.length]=128;const l=new DataView(o.buffer);l.setUint32(s-8,Math.floor(n/4294967296)),l.setUint32(s-4,n>>>0);const u=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),c=new Uint32Array(64);for(let f=0;f<s;f+=64){for(let C=0;C<16;C++)c[C]=l.getUint32(f+C*4);for(let C=16;C<64;C++){const E=c[C-15],T=c[C-2],I=(E>>>7|E<<25)^(E>>>18|E<<14)^E>>>3,K=(T>>>17|T<<15)^(T>>>19|T<<13)^T>>>10;c[C]=c[C-16]+I+c[C-7]+K>>>0}let[m,p,g,w,x,S,j,N]=u;for(let C=0;C<64;C++){const E=(x>>>6|x<<26)^(x>>>11|x<<21)^(x>>>25|x<<7),T=x&S^~x&j,I=N+E+T+NN[C]+c[C]>>>0,K=(m>>>2|m<<30)^(m>>>13|m<<19)^(m>>>22|m<<10),U=m&p^m&g^p&g,J=K+U>>>0;N=j,j=S,S=x,x=w+I>>>0,w=g,g=p,p=m,m=I+J>>>0}u[0]=u[0]+m>>>0,u[1]=u[1]+p>>>0,u[2]=u[2]+g>>>0,u[3]=u[3]+w>>>0,u[4]=u[4]+x>>>0,u[5]=u[5]+S>>>0,u[6]=u[6]+j>>>0,u[7]=u[7]+N>>>0}return Array.from(u,f=>f.toString(16).padStart(8,"0")).join("")}const kp="$slim";function EN(e){return!!(e&&typeof e=="object"&&!Array.isArray(e)&&e[kp]&&typeof e[kp]=="object")}function $N(e){const t=new Map;for(const n of e||[]){if(!n||typeof n!="object"||String(n.status||"")!=="started")continue;const s=String(n.step_id||""),o=n.effect&&typeof n.effect=="object"?n.effect.payload:null;s&&o&&typeof o=="object"&&!t.has(s)&&t.set(s,o)}return t}function AN(e,t){const n=[];for(const s of t)if(s==="system"){if(typeof e.system_prompt!="string"||!e.system_prompt)return null;n.push({role:"system",content:e.system_prompt})}else if(s==="messages"){if(!Array.isArray(e.messages))return null;for(const o of e.messages)o&&typeof o=="object"&&n.push({...o})}else if(s==="prompt"){if(typeof e.prompt!="string"||!e.prompt)return null;n.push({role:"user",content:e.prompt})}else return null;return n}function TN(e,t){const n=e&&e[kp];if(!n||typeof n!="object")return{state:"missing",reason:"not a $slim marker"};const s=t.get(String(n.step_id||""));if(!s)return{state:"missing",reason:"its started record is not in the loaded ledger"};let o;if(n.kind==="started_payload_field"){const u=String(n.field||"");if(!(u in s))return{state:"missing",reason:`the started record has no "${u}" field`};o=s[u]}else if(n.kind==="started_messages_layout"){if(o=Array.isArray(n.layout)?AN(s,n.layout.map(String)):null,!o)return{state:"missing",reason:"the started record cannot rebuild these messages"}}else return{state:"missing",reason:`unknown $slim kind "${String(n.kind||"")}"`};if(Array.isArray(n.appendix)&&n.appendix.length){if(!Array.isArray(o))return{state:"missing",reason:"appendix on a non-list value"};const u=o.map(f=>f&&typeof f=="object"?{...f}:f),c=[...n.appendix].sort((f,m)=>Number((f==null?void 0:f.at)??-1)-Number((m==null?void 0:m.at)??-1));for(const f of c){const m=Number(f==null?void 0:f.at);if(!Number.isInteger(m)||m<0||m>u.length)return{state:"missing",reason:"appendix position out of range"};u.splice(m,0,f.item)}o=u}return CN(JSON.stringify(o))!==String(n.sha256||"")?{state:"unverified",value:o,reason:"checksum differs from the record"}:{state:"resolved",value:o}}function MN(e,t){const n=[],s=[],o=(l,u,c)=>{if(c>14)return l;if(EN(l)){const f=TN(l,t);return f.state==="missing"?(n.push({path:u,reason:f.reason}),l):(f.state==="unverified"&&s.push({path:u,reason:f.reason}),f.value)}if(Array.isArray(l)){let f=null;return l.forEach((m,p)=>{const g=o(m,`${u}[${p}]`,c+1);g!==m&&((f??(f=[...l]))[p]=g)}),f??l}if(l&&typeof l=="object"){let f=null;for(const m of Object.keys(l)){const p=o(l[m],u?`${u}.${m}`:m,c+1);p!==l[m]&&((f??(f={...l}))[m]=p)}return f??l}return l};return{value:o(e,"",0),unresolved:n,unverified:s}}function Oy(e){const t=Date.parse(String(e||""));return Number.isFinite(t)?t:null}function bx(e){const t=e==null?void 0:e.result;return t&&typeof t=="object"&&Array.isArray(t.results)?t.results:[]}function RN(e,t){return e?String(e.status||"")==="failed"||e.error?!0:t==="tool"&&bx(e).some(n=>n&&n.success===!1):!1}function jx(e,t){var m,p,g,w,x,S;const n=String(t||"").trim(),s=(e||[]).filter(j=>j&&j.record&&String(j.run_id||j.record.run_id||"").trim()===n).sort((j,N)=>(j.cursor||0)-(N.cursor||0)),o=$N(s.map(j=>j.record)),l=new Map,u=[];for(const j of s){const N=j.record,E=String(N.step_id||"")||`cursor:${j.cursor}`;let T=l.get(E);T||(T={cursor:j.cursor,started:null,latest:N,latest_cursor:j.cursor},l.set(E,T),u.push(E)),String(N.status||"")==="started"&&!T.started&&(T.started=N),j.cursor>=T.latest_cursor&&(T.latest=N,T.latest_cursor=j.cursor)}let c=0;const f=[];for(const j of u){const N=l.get(j),C=MN(N.latest,o),E=C.value,T=String(((m=E==null?void 0:E.effect)==null?void 0:m.type)||((g=(p=N.started)==null?void 0:p.effect)==null?void 0:g.type)||"").trim(),I=SN(T),K=I==="event"?String(((x=(w=E==null?void 0:E.effect)==null?void 0:w.payload)==null?void 0:x.name)||"").trim():"";I==="llm_call"&&(c+=1);const U=RN(E,I),J=String(((S=N.started)==null?void 0:S.started_at)||(E==null?void 0:E.started_at)||""),Y=String((E==null?void 0:E.ended_at)||""),se=Oy(J),ce=Oy(Y);f.push({id:`${n}:${j}`,run_id:n,step_id:String((E==null?void 0:E.step_id)||""),node_id:String((E==null?void 0:E.node_id)||""),kind:I,effect_type:T,event_name:K,status:String((E==null?void 0:E.status)||""),cursor:N.cursor,started_at:J,ended_at:Y,duration_ms:se!==null&&ce!==null?Math.max(0,ce-se):null,started:N.started,record:E,failed:U,housekeeping:kN(I,K,U),cycle:c,unresolved:C.unresolved,unverified:C.unverified})}return f}function LN(e){const t=[];for(const n of e){let s=t[t.length-1];(!s||s.cycle!==n.cycle)&&(s={cycle:n.cycle,steps:[],llm:null},t.push(s)),n.kind==="llm_call"&&!s.llm&&(s.llm=n),s.steps.push(n)}return t}const IN={view:"cycles",only:"all",all_steps:!1,q:""};function PN(e,t,n){const s=String(t.q||"").trim().toLowerCase();return e.filter(o=>!(t.only==="llm"&&o.kind!=="llm_call"||t.only==="tools"&&o.kind!=="tool"||t.only==="failed"&&!o.failed||t.only==="all"&&!t.all_steps&&o.housekeeping||s&&!n(o).includes(s)))}const ON=["all","llm","tools","failed"];function Dy(e){const t=String(e||""),n=t.indexOf("?");if(n<0)return{...IN};const s=new URLSearchParams(t.slice(n+1)),o=String(s.get("only")||"");return{view:s.get("view")==="steps"?"steps":"cycles",only:ON.includes(o)?o:"all",all_steps:s.get("all")==="1",q:String(s.get("q")||"")}}function DN(e,t){const n=String(e||"").split("?")[0],s=new URLSearchParams;t.view!=="cycles"&&s.set("view",t.view),t.only!=="all"&&s.set("only",t.only),t.all_steps&&s.set("all","1"),t.q.trim()&&s.set("q",t.q);const o=s.toString();return o?`${n}?${o}`:n}function _u(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>typeof t=="string"?t:typeof(t==null?void 0:t.text)=="string"?t.text:t!=null&&t.type?`[${String(t.type)}]`:JSON.stringify(t)).join(`
68
- `):e==null?"":JSON.stringify(e,null,2)}function Sx(e){if(typeof e!="string")return e??{};try{return JSON.parse(e)}catch{return e}}function kx(e){return Array.isArray(e)?e.filter(t=>t&&typeof t=="object").map(t=>{var n,s;return{name:String(t.name||((n=t.function)==null?void 0:n.name)||"?"),arguments:Sx(t.arguments??((s=t.function)==null?void 0:s.arguments))}}):[]}function Fy(e){const t={role:String((e==null?void 0:e.role)||"?"),content:_u(e==null?void 0:e.content)},n=kx(e==null?void 0:e.tool_calls);return n.length&&(t.tool_calls=n),e!=null&&e.name&&(t.name=String(e.name)),t}function zy(e){const t=Number(e);return Number.isFinite(t)&&e!==null&&e!==void 0?t:null}const FN={"effect.payload.system_prompt":"System","effect.payload.messages":"Messages","effect.payload.prompt":"Prompt","effect.payload.tools":"Tools offered","result.metadata._provider_request.payload.messages":"Messages sent"};function hg(e){var x,S,j,N,C,E;const t=e.record||{},n=((S=(x=e.started)==null?void 0:x.effect)!=null&&S.payload&&typeof e.started.effect.payload=="object"?e.started.effect.payload:(j=t==null?void 0:t.effect)==null?void 0:j.payload)||{},s=t!=null&&t.result&&typeof t.result=="object"?t.result:{},o=s.usage||s.token_usage||{},l=[],u=e.unverified.map(T=>`${T.path}: ${T.reason}`);for(const T of e.unresolved){const I=FN[T.path];I&&l.push(`${I}: ${T.reason}`)}const c=(C=(N=s==null?void 0:s.metadata)==null?void 0:N._provider_request)==null?void 0:C.payload;let f="",m=[],p="";if(c&&Array.isArray(c.messages)){p="sent";for(const T of c.messages)String((T==null?void 0:T.role)||"")==="system"&&!m.length?f+=(f?`
69
-
70
- `:"")+_u(T.content):m.push(Fy(T))}else(Array.isArray(n.messages)||typeof n.prompt=="string")&&(p="payload",m=(Array.isArray(n.messages)?n.messages:[]).map(Fy),typeof n.prompt=="string"&&n.prompt.trim()&&m.push({role:"user",content:n.prompt}));!f&&typeof n.system_prompt=="string"&&(f=n.system_prompt);const w=(Array.isArray(n.tools)?n.tools:Array.isArray(c==null?void 0:c.tools)?c.tools:[]).filter(T=>T&&typeof T=="object").map(T=>{const I=T.function&&typeof T.function=="object"?T.function:T;return{name:String(I.name||"?"),description:String(I.description||""),schema:I.parameters??I.input_schema??null}});return{provider:String(n.provider||s.provider||""),model:String(n.model||s.model||""),tokens_in:zy(o.prompt_tokens??o.input_tokens),tokens_out:zy(o.completion_tokens??o.output_tokens),system:f,messages:m,messages_source:p,tools:w,response:_u(s.content??s.response??""),tool_calls:kx(s.tool_calls),reasoning:_u(s.reasoning??((E=s==null?void 0:s.metadata)==null?void 0:E.reasoning)??""),missing:l,unverified:u}}function mg(e){var o,l,u,c;const t=((l=(o=e.record)==null?void 0:o.effect)==null?void 0:l.payload)||((c=(u=e.started)==null?void 0:u.effect)==null?void 0:c.payload)||{},n=(Array.isArray(t.tool_calls)?t.tool_calls:[]).map(f=>{var m,p;return{name:String((f==null?void 0:f.name)||((m=f==null?void 0:f.function)==null?void 0:m.name)||"?"),arguments:Sx((f==null?void 0:f.arguments)??((p=f==null?void 0:f.function)==null?void 0:p.arguments)),call_id:String((f==null?void 0:f.call_id)||(f==null?void 0:f.id)||"")}}),s=bx(e.record).map(f=>({name:String((f==null?void 0:f.name)||"?"),success:typeof(f==null?void 0:f.success)=="boolean"?f.success:null,output:(f==null?void 0:f.output)==null?"":_u(f.output),error:(f==null?void 0:f.error)==null?"":_u(f.error),call_id:String((f==null?void 0:f.call_id)||"")}));return{calls:n,results:s}}function zN(e){return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).map(([t,n])=>`${t}=${JSON.stringify(n)}`).join(", "):typeof e=="string"?e:JSON.stringify(e??"")}function Nx(e){var s,o,l;const t=(s=e==null?void 0:e.result)==null?void 0:s.wait,n=typeof(t==null?void 0:t.wait_key)=="string"&&t.wait_key.startsWith("subworkflow:")?t.wait_key.slice(12):"";return String(((o=t==null?void 0:t.details)==null?void 0:o.sub_run_id)||((l=e==null?void 0:e.result)==null?void 0:l.sub_run_id)||n||"").trim()}function Cx(e){var n,s,o,l,u,c,f,m,p,g,w;const t=e.record||{};switch(e.kind){case"llm_call":{const x=hg(e);return x.tokens_in!==null||x.tokens_out!==null?`${(x.tokens_in??0).toLocaleString("en-US")} in · ${(x.tokens_out??0).toLocaleString("en-US")} out`:""}case"tool":{const x=mg(e).calls;if(!x.length)return"";const S=`${x[0].name}(${zN(x[0].arguments)})`;return x.length>1?`${S} +${x.length-1} more`:S}case"event":return e.event_name;case"subflow":{const x=Nx(t);return[String(((s=(n=t==null?void 0:t.effect)==null?void 0:n.payload)==null?void 0:s.workflow_id)||""),x].filter(Boolean).join(" · ")}case"wait":case"resume":return String(((l=(o=t==null?void 0:t.result)==null?void 0:o.wait)==null?void 0:l.reason)||((c=(u=t==null?void 0:t.effect)==null?void 0:u.payload)==null?void 0:c.reason)||"");case"ask":return String(((m=(f=t==null?void 0:t.effect)==null?void 0:f.payload)==null?void 0:m.prompt)||"");case"answer":return String(((g=(p=t==null?void 0:t.effect)==null?void 0:p.payload)==null?void 0:g.message)||((w=t==null?void 0:t.result)==null?void 0:w.message)||"");default:return e.effect_type}}function Ex(e){return e.kind==="llm_call"?hg(e).model:""}function BN(e,t){var s,o;const n=[e.kind,e.effect_type,e.event_name,e.node_id,t,e.status,Cx(e),Ex(e)];try{n.push(JSON.stringify(((o=(s=e.started)==null?void 0:s.effect)==null?void 0:o.payload)??null)),n.push(JSON.stringify(e.record??null))}catch{}return n.join(`
71
- `).toLowerCase()}function UN(e){var s,o;const t=Array.from(new Set((e||[]).map(l=>{var u;return String(l.run_id||((u=l.record)==null?void 0:u.run_id)||"").trim()}).filter(Boolean))),n={llm_calls:0,tokens:0,tool_calls:0,tool_failures:0};for(const l of t)for(const u of jx(e,l))if(u.kind==="llm_call"){n.llm_calls+=1;const c=((o=(s=u.record)==null?void 0:s.result)==null?void 0:o.usage)||{};n.tokens+=Number(c.total_tokens??Number(c.prompt_tokens??c.input_tokens??0)+Number(c.completion_tokens??c.output_tokens??0))||0}else if(u.kind==="tool"){const c=mg(u);n.tool_calls+=Math.max(c.calls.length,c.results.length),n.tool_failures+=c.results.filter(f=>f.success===!1).length}return n}function WN(e){const t=[];return e.llm_calls&&t.push(`${e.llm_calls} LLM call${e.llm_calls===1?"":"s"}`),e.tokens&&t.push(`${e.tokens.toLocaleString("en-US")} tokens`),e.tool_calls&&t.push(`${e.tool_calls} tool call${e.tool_calls===1?"":"s"}${e.tool_failures?`, ${e.tool_failures} failed`:""}`),t.join(" · ")}function Ct(){return new Date().toISOString()}function qN(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}function cs(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 St(e,t){const n=typeof(t==null?void 0:t.max_chars)=="number"?t.max_chars:360,s=typeof(t==null?void 0:t.max_lines)=="number"?t.max_lines:2,l=String(e||"").replace(/\r\n/g,`
72
- `).replace(/\r/g,`
73
- `).split(`
74
- `),u=l.slice(0,Math.max(1,s)).join(`
75
- `),c=l.length>s,f=u.length>n?`${u.slice(0,Math.max(0,n-1))}…`:u;return c&&f===u?`${u}…`:f}function Qt(e,t){const n=String(e||"");return n.length<=t?n:`${n.slice(0,Math.max(0,t-1))}…`}function By(e){const t=String(e||"").trim();return t&&t.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")||"untitled"}function qn(e){const t=typeof e=="string"?e.trim():"";if(!t)return null;const n=t.replace(/(\.\d{3})\d+/,"$1"),s=Date.parse(n);return Number.isFinite(s)?s:null}function HN(e){const t=Date.now()-e,n=Math.floor(t/1e3),s=Math.floor(n/60),o=Math.floor(s/60),l=Math.floor(o/24);return n<60?"just now":s<60?`${s}m ago`:o<24?`${o}h ago`:l<=3?`${l}d ago`:new Date(e).toLocaleDateString(void 0,{month:"short",day:"numeric"})}function ec(e){const t=qn(e);return t===null?"—":HN(t)}function Uy(e){if(!Number.isFinite(e))return"";const t=Math.floor(e/1e3);if(t<=0)return"now";const n=Math.floor(t/60),s=Math.floor(n/60),o=Math.floor(s/24),l=t%60,u=n%60,c=s%24;return o>0?`${o}d ${c}h`:s>0?`${s}h ${u}m`:n>0?`${n}m ${l}s`:`${t}s`}function _g(e){if(typeof e!="number"||!Number.isFinite(e)||e<0)return"—";const t=Math.floor(e/1e3),n=t%60,s=Math.floor(t/60),o=s%60,l=Math.floor(s/60),u=l%24,c=Math.floor(l/24);return c>0?`${c}d ${u}h`:l>0?`${l}h ${o}m`:s>0?`${s}m ${n}s`:`${Math.max(0,t)}s`}function bu(e){const t=qn(e);return t===null?"—":new Date(t).toLocaleString()}function _n(...e){for(const t of e){const n=String(t??"").trim();if(n)return n}return""}function VN(...e){for(const t of e){const n=Number(t);if(Number.isFinite(n))return n}return null}function ko(e){const t=String(e||"").trim().toLowerCase();return t==="completed"||t==="failed"||t==="cancelled"}function ju(e){const t=String(e||"").trim().toLowerCase();return t==="running"||t==="waiting"}function fu(e){return String((e==null?void 0:e.started_at)||(e==null?void 0:e.created_at)||"").trim()}function GN(e){const t=String((e==null?void 0:e.status)||"").trim();return ko(t)?String((e==null?void 0:e.finished_at)||(e==null?void 0:e.updated_at)||"").trim():""}function pg(e,t=Date.now()){const n=qn(fu(e));if(n===null)return-1;const s=qn(GN(e));return Math.max(0,(s!==null?s:t)-n)}function ic(e,t=Date.now()){return _g(pg(e,t))}function KN(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 YN(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 oc(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 JN={all:"All",llm:"LLM calls",tools:"Tools",failed:"Failed"};function bi(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}function bo(e){return r.jsxs("details",{className:"rs_section",open:e.open,children:[r.jsxs("summary",{children:[r.jsx("span",{className:"rs_section_title",children:e.title}),e.meta?r.jsx("span",{className:"rs_section_meta",children:e.meta}):null,e.copy!==void 0?r.jsx("button",{type:"button",className:"rs_copy",onClick:t=>{t.preventDefault(),t.stopPropagation(),e.on_copy(e.copy||"")},children:"Copy"}):null]}),r.jsx("div",{className:"rs_section_body",children:e.children})]})}function T_(e){return`${e.toLocaleString("en-US")} chars`}function gg(e){const t=e.step.started&&e.step.started!==e.step.record?{started:e.step.started,record:e.step.record}:e.step.record;return r.jsx(bo,{title:"Raw JSON",copy:bi(t),on_copy:e.on_copy,children:r.jsx("div",{className:"rs_json mono",children:r.jsx(Ir,{value:t,collapseAfterDepth:2,showCopy:!1})})})}function XN(e){const t=hg(e.step),n=!t.system&&!t.messages.length&&!t.missing.length;return r.jsxs(r.Fragment,{children:[t.missing.map(s=>r.jsxs("p",{className:"rs_notice",children:["Prompt body not kept: ",s,"."]},s)),n?r.jsx("p",{className:"rs_notice",children:"Prompt body not kept: this record carries no request messages."}):null,t.unverified.length?r.jsxs("p",{className:"rs_notice",children:["Rebuilt prompt may differ from what was sent: ",t.unverified.join("; "),"."]}):null,t.system?r.jsx(bo,{title:"System",meta:T_(t.system.length),copy:t.system,on_copy:e.on_copy,children:r.jsx("pre",{className:"rs_text",children:t.system})}):null,t.messages.length?r.jsx(bo,{title:"Messages",meta:`${t.messages.length}${t.messages_source==="sent"?" · as sent":""}`,copy:bi(t.messages),on_copy:e.on_copy,children:r.jsx("ol",{className:"rs_messages",children:t.messages.map((s,o)=>{var l;return r.jsxs("li",{className:`rs_msg rs_msg_${s.role}`,children:[r.jsxs("span",{className:"rs_role",children:[s.role,s.name?` · ${s.name}`:""]}),s.content?r.jsx("pre",{className:"rs_text",children:s.content}):null,(l=s.tool_calls)==null?void 0:l.map((u,c)=>r.jsx("pre",{className:"rs_text mono",children:`${u.name}(${bi(u.arguments)})`},c))]},o)})})}):null,t.tools.length?r.jsx(bo,{title:"Tools offered",meta:String(t.tools.length),copy:bi(t.tools),on_copy:e.on_copy,children:r.jsx("ul",{className:"rs_tools",children:t.tools.map(s=>r.jsxs("li",{children:[r.jsx("strong",{className:"mono",children:s.name}),s.description?r.jsxs("span",{children:[" — ",s.description]}):null]},s.name))})}):null,r.jsxs(bo,{title:"Response",meta:t.tool_calls.length?`${t.tool_calls.length} tool call${t.tool_calls.length===1?"":"s"}`:t.response?T_(t.response.length):"empty",copy:t.response||bi(t.tool_calls),open:!0,on_copy:e.on_copy,children:[t.response?r.jsx("div",{className:"rs_markdown",children:r.jsx(Wi,{text:t.response})}):null,t.tool_calls.map((s,o)=>r.jsx("pre",{className:"rs_text mono",children:`${s.name}(${bi(s.arguments)})`},o)),!t.response&&!t.tool_calls.length?r.jsx("p",{className:"rs_muted",children:"No text and no tool call."}):null]}),t.reasoning?r.jsx(bo,{title:"Reasoning",meta:T_(t.reasoning.length),copy:t.reasoning,on_copy:e.on_copy,children:r.jsx("pre",{className:"rs_text",children:t.reasoning})}):null,r.jsx(gg,{step:e.step,on_copy:e.on_copy})]})}function ZN(e){const t=mg(e.step);return r.jsxs(r.Fragment,{children:[r.jsx(bo,{title:"Calls",meta:String(t.calls.length),copy:bi(t.calls),open:!0,on_copy:e.on_copy,children:t.calls.map((n,s)=>r.jsx("pre",{className:"rs_text mono",children:`${n.name}(${bi(n.arguments)})`},s))}),r.jsxs(bo,{title:"Results",meta:String(t.results.length),copy:bi(t.results),open:!0,on_copy:e.on_copy,children:[t.results.length?null:r.jsx("p",{className:"rs_muted",children:"No result recorded yet."}),r.jsx("ol",{className:"rs_messages",children:t.results.map((n,s)=>r.jsxs("li",{className:`rs_msg ${n.success===!1?"rs_msg_failed":""}`,children:[r.jsxs("span",{className:"rs_role",children:[n.name," · ",n.success===!1?"failed":n.success?"ok":"unknown"]}),n.error?r.jsx("pre",{className:"rs_text",children:n.error}):null,n.output?r.jsx("pre",{className:"rs_text",children:n.output}):null]},s))})]}),r.jsx(gg,{step:e.step,on_copy:e.on_copy})]})}function QN(e){var o,l,u;const t=e.step.record||{},n=((l=(o=e.step.started)==null?void 0:o.effect)==null?void 0:l.payload)??((u=t==null?void 0:t.effect)==null?void 0:u.payload),s=e.step.kind==="subflow"?Nx(t):"";return r.jsxs(r.Fragment,{children:[s&&e.on_open_run?r.jsxs("p",{className:"rs_line_actions",children:[r.jsx("span",{className:"mono",children:s}),r.jsx("button",{type:"button",className:"btn btn_sm",onClick:()=>{var c;return(c=e.on_open_run)==null?void 0:c.call(e,s)},children:"Open"})]}):null,t.error?r.jsx("pre",{className:"rs_text rs_error",children:typeof t.error=="string"?t.error:bi(t.error)}):null,n!=null?r.jsx(bo,{title:"Payload",copy:bi(n),on_copy:e.on_copy,children:r.jsx("div",{className:"rs_json mono",children:r.jsx(Ir,{value:n,collapseAfterDepth:2,showCopy:!1})})}):null,t.result!==void 0&&t.result!==null?r.jsx(bo,{title:"Result",copy:bi(t.result),on_copy:e.on_copy,children:r.jsx("div",{className:"rs_json mono",children:r.jsx(Ir,{value:t.result,collapseAfterDepth:2,showCopy:!1})})}):null,r.jsx(gg,{step:e.step,on_copy:e.on_copy})]})}function e2(e){const t=e.step,n=Cx(t),s=Ex(t),o=t.failed&&t.status!=="failed"?"failed":t.status;return r.jsxs("article",{className:`rs_card ${t.failed?"rs_failed":""}`,"data-kind":t.kind,"data-step-id":t.step_id||void 0,children:[r.jsxs("button",{type:"button",className:"rs_card_head","aria-expanded":e.open,onClick:e.on_toggle,children:[r.jsx("span",{className:"rs_chevron","aria-hidden":"true",children:e.open?"▾":"▸"}),r.jsx("span",{className:"rs_kind",children:jN[t.kind]}),r.jsx("span",{className:"rs_node",children:e.node_label||t.node_id||t.effect_type||"step"}),r.jsx("span",{className:`rs_status ${oc(o)}`,children:o||"—"}),r.jsx("span",{className:"rs_dur",children:t.duration_ms!==null?_g(t.duration_ms):""}),s?r.jsx("span",{className:"rs_detail",children:s}):null,n?r.jsx("span",{className:"rs_line",children:n}):null]}),e.open?r.jsx("div",{className:"rs_card_body",children:t.kind==="llm_call"?r.jsx(XN,{step:t,on_copy:e.on_copy}):t.kind==="tool"?r.jsx(ZN,{step:t,on_copy:e.on_copy}):r.jsx(QN,{step:t,on_copy:e.on_copy,on_open_run:e.on_open_run})}):null]})}function t2(e){const{state:t}=e,n=_.useMemo(()=>jx(e.items,e.run_id),[e.items,e.run_id]),[s,o]=_.useState({}),l=S=>e.node_label(S.run_id,S.node_id),u=_.useMemo(()=>new Map,[n]),f=PN(n,t,S=>{let j=u.get(S.id);return j===void 0&&(j=BN(S,l(S)),u.set(S.id,j)),j}),m=n.some(S=>S.kind==="llm_call"),p=n.reduce((S,j)=>j.kind==="llm_call"?S+1:S,0),g=n.length-f.length,w=S=>e.on_state({...t,...S}),x=S=>r.jsx(e2,{step:S,node_label:l(S),open:s[S.id]===!0,on_toggle:()=>o(j=>({...j,[S.id]:!j[S.id]})),on_copy:e.on_copy,on_open_run:e.on_open_run},S.id);return r.jsxs("div",{className:"rs_view",children:[r.jsxs("div",{className:"rs_count",children:[r.jsxs("span",{children:[f.length," of ",n.length," steps",m?` · ${p} cycle${p===1?"":"s"}`:"",g&&t.only==="all"&&!t.all_steps&&!t.q?` · ${g} housekeeping hidden`:""]}),e.run_options.length>1?r.jsx("select",{className:"seg_select mono",value:e.run_id,onChange:S=>e.on_select_run(String(S.target.value||"")),"aria-label":"Run",children:e.run_options.map(S=>r.jsxs("option",{value:S,children:[Qt(S,14),e.run_llm_counts[S]?` · ${e.run_llm_counts[S]} LLM`:""]},S))}):null]}),r.jsxs("div",{className:"rs_toolbar",children:[r.jsx("div",{className:"seg_toggle",role:"radiogroup","aria-label":"Layout",children:["cycles","steps"].map(S=>r.jsx("button",{type:"button",role:"radio","aria-checked":t.view===S,className:`seg_btn ${t.view===S?"active":""}`,onClick:()=>w({view:S}),children:S==="cycles"?"Cycles":"Steps"},S))}),r.jsx("div",{className:"seg_toggle",role:"radiogroup","aria-label":"Show",children:["all","llm","tools","failed"].map(S=>r.jsx("button",{type:"button",role:"radio","data-filter":S,"aria-checked":t.only===S,className:`seg_btn ${t.only===S?"active":""}`,onClick:()=>w({only:S}),children:JN[S]},S))}),r.jsx("input",{className:"rs_search",type:"search",value:t.q,onChange:S=>w({q:S.target.value}),placeholder:"Search steps","aria-label":"Search steps",autoComplete:"off",spellCheck:!1}),t.only==="all"?r.jsx(No,{label:"All steps",action:"show-all-steps",hint:"Also list status events, waits, resumes and memory bookkeeping.",checked:t.all_steps,onChange:S=>w({all_steps:S})}):null]}),n.length?null:r.jsx("p",{className:"rs_muted",children:"No steps recorded for this run yet."}),n.length&&!f.length?r.jsx("p",{className:"rs_muted",children:"No step matches."}):null,t.view==="cycles"&&m?LN(f).map(S=>r.jsxs("section",{className:"rs_cycle","data-cycle":S.cycle,children:[r.jsx("h3",{className:"rs_cycle_head",children:S.cycle===0?"Before the first call":`Cycle ${S.cycle}`}),S.steps.map(x)]},S.cycle)):f.map(x)]})}function n2(e){const[t,n]=_.useState(!1),s=e.answer.length>Wy,o=t||!s?e.answer:`${e.answer.slice(0,Wy).trimEnd()}…`;return r.jsxs("section",{className:"rs_outcome","aria-label":"Run summary",children:[r.jsxs("p",{className:"rs_outcome_facts",children:[r.jsx("span",{className:`rs_status ${oc(e.status)}`,children:e.status||"unknown"}),[e.duration,e.facts].filter(Boolean).join(" · ")]}),e.error?r.jsx("p",{className:"rs_text rs_error",children:e.error}):null,!e.error&&e.answer?r.jsxs("div",{className:"rs_markdown rs_outcome_text",children:[r.jsx(Wi,{text:o}),s?r.jsx("button",{type:"button",className:"rs_link","aria-expanded":t,onClick:()=>n(l=>!l),children:t?"Less":"More"}):null]}):null,r.jsxs("div",{className:"rs_outcome_actions",children:[e.waiting_for_user&&e.on_answer_wait?r.jsx("button",{type:"button",className:"btn primary",onClick:e.on_answer_wait,children:"Answer"}):null,r.jsx("button",{type:"button",className:"btn",onClick:e.on_open_artifacts,title:"This run's artifacts in System",children:"Artifacts"}),e.workspace_root?r.jsx("button",{type:"button",className:"btn",onClick:e.on_reveal_workspace,title:e.workspace_root,children:"Folder"}):null]})]})}const Wy=600,r2="@default:",Su="abstractcode.agent.v1";function qy(e,t){var n;return e?e.kind==="default"?e.interface===Su?"@default":"":((n=t.find(s=>s.bundleId===e.bundle_id&&s.flowId===e.flow_id))==null?void 0:n.value)??"":""}function s2(e,t){return e==="@default"?{kind:"default",interface:Su}:t?{kind:"bundle",bundle_id:t.bundleId,flow_id:t.flowId}:null}function i2(e){return e?e.kind==="default"?`${r2}${e.interface}`:`${e.bundle_id}:${e.flow_id}`:""}function o2(e,t,n){if(!e)return null;if(e.kind==="default")return{flow_id:"@default",interface:e.interface,input_data:n};const s=String(t(e.bundle_id)||"").trim();if(!s)throw new Error(`The gateway listed no bundle_ref for bundle "${e.bundle_id}". Reload bundles, then try again.`);return{bundle_ref:s,flow_id:e.flow_id,input_data:n}}function a2(e){const t={};for(const[n,s]of Object.entries(e||{}))if(typeof s=="string"){const o=s.trim();o&&(t[n]=o)}else s!==void 0&&(t[n]=s);return t}const l2={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 c2(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 u2="#launch/automate";function d2(e){const t=xx(String(e||""));if(t)return{page:"run",run_id:t};const n=String(e||"").replace(/^#\/?/,"");if(n==="automations")return{page:"automations"};const s=/^launch(?:\/(once|automate))?$/.exec(n);return s?{page:"launch",mode:s[1]||"once"}:null}const Np={when:"every",email:Ov,notify_email:!1,email_recipients:ag,amount:"24",unit:"h",once_at:"",context:"independent",tool_approval:"auto",title:"",start_at:"",count:"",until:""},Hy={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."},$x=["use_context"],f2="This choice also sets the workflow's Use Context input: the workflow always reads the history the automation gives it.";function Cp(e,t,n=!1){const s=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,...s&&e.start_at?{startAt:e.start_at}:{},...s&&e.count.trim()?{count:Number(e.count)}:{},...s&&e.until?{until:e.until}:{}}}function h2(e,t){if(t.input_data===null)return{ok:!1,errors:["The inputs are not valid JSON."]};if(e.when==="email"&&!t.email_usable)return{ok:!1,errors:[Ut.not_set_up]};const n=a2(t.input_data),s=typeof n.prompt=="string"?n.prompt:"";delete n.prompt;for(const l of $x)delete n[l];let o;try{o=o2(t.choice,t.bundle_ref_for,n)}catch(l){return{ok:!1,errors:[String((l==null?void 0:l.message)||l)]}}return pp(Cp(e,s,t.email_usable===!0),{target:o,requestId:t.request_id})}function m2(e,t=!1){if(e.when==="email"){if(!t)return"";const l=pp(Cp(e,"preview",!0),{target:{flow_id:"@default",interface:Su},requestId:"preview"});return l.ok?`Runs ${Fv(l.body.trigger.config)}.`:""}const n=pp(Cp(e,"preview"),{target:{flow_id:"@default",interface:Su},requestId:"preview"});if(!n.ok)return"";const s=n.body.trigger.config,o=Tv(s);return e.when==="once"?`Runs ${o}.`:`Runs ${o}, first run ${s.start_at?`at ${la(s.start_at)}`:"now"}.`}class _2{constructor(t){Vr(this,"key","");Vr(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 p2(e,t,n){const s=h2(e,{...t,request_id:""});if(!s.ok)return s;const{request_id:o,...l}=s.body,u=n.id_for(JSON.stringify(l));return{ok:!0,body:{...s.body,request_id:u}}}function na(e){return typeof e=="string"?e:e??null}function g2(e){var t,n,s,o,l,u;return{run_id:String((e==null?void 0:e.run_id)||"").trim(),workflow_id:na(e==null?void 0:e.workflow_id),status:typeof(e==null?void 0:e.status)=="string"?String(e.status):"",created_at:na(e==null?void 0:e.created_at),updated_at:na(e==null?void 0:e.updated_at),ledger_len:typeof(e==null?void 0:e.ledger_len)=="number"?Number(e.ledger_len):(e==null?void 0:e.ledger_len)??null,parent_run_id:na(e==null?void 0:e.parent_run_id),session_id:na(e==null?void 0:e.session_id),actor_id:na(e==null?void 0:e.actor_id),session_kind:na(e==null?void 0:e.session_kind),automation_id:na(e==null?void 0:e.automation_id),role:na(e==null?void 0:e.role),occurrence_index:typeof(e==null?void 0:e.occurrence_index)=="number"?Number(e.occurrence_index):null,is_scheduled:typeof(e==null?void 0:e.is_scheduled)=="boolean"?!!e.is_scheduled:(e==null?void 0:e.is_scheduled)??null,paused:typeof(e==null?void 0:e.paused)=="boolean"?!!e.paused:(e==null?void 0:e.paused)??null,waiting_reason:typeof((t=e==null?void 0:e.waiting)==null?void 0:t.reason)=="string"?String(e.waiting.reason):((n=e==null?void 0:e.waiting)==null?void 0:n.reason)??null,schedule_interval:typeof((s=e==null?void 0:e.schedule)==null?void 0:s.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 uf(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 Ax(e){const t=uf(e);return t==="occurrence"?typeof e.occurrence_index=="number"?`occurrence #${e.occurrence_index}`:"occurrence":t==="legacy"?"legacy schedule":t||""}function Vy(e){return String((e==null?void 0:e.role)||"").trim()==="controller"}function y2(e){var n,s,o;const t=(o=(s=(n=e==null?void 0:e.capabilities)==null?void 0:n.contracts)==null?void 0:s.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 tc(e){return e.legacy===!0||e.capabilities.includes("legacy")}function Tx(e,t=Date.now()){const n=tc(e),s=e.last_occurrence,o=s&&s.attempts>1?` after ${s.attempts} attempts`:"",l=e.attention.unread||e.attention.pending_waits>0;return{id:e.automation_id,title:e.title,cadence:sg(e.trigger),next_run:e.next_fire_at?`${la(e.next_fire_at)} (${Wv(e.next_fire_at,t)})`:e.status==="paused"?"none while paused":"none scheduled",current:Uv(e),state:e.status,last:s?s.excerpt:"",last_status:s?`#${s.index} ${s.status}${o}`:"no runs yet",attention:l?qv(e):null,legacy:n}}function Mx(e){const t=e.last_occurrence;if(!t)return null;const s=["completed","failed","cancelled"].includes(String(t.status))?t.index:t.index-1;return s>=1?s:null}function w2(e,t){const n=sm(e,[],t),s=Mx(e),o=t?{enabled:!1,reason:"Working…"}:tc(e)?{enabled:!1,reason:"Legacy schedule: managed with its existing controls."}:e.capabilities.includes("discuss")?s===null?{enabled:!1,reason:e.last_occurrence?"Available once the first run finishes.":"No occurrence to discuss yet."}:{enabled:!0,reason:`Discuss run #${s} in a new chat (a fork of this automation).`}:{enabled:!1,reason:"Not permitted for this automation."};return{active:n.active,pause:n.pause,resume:n.resume,run_now:n.run_now,edit:n.revise,archive:n.archive,discuss:o}}function v2(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 s=e.status==="paused",o=e.status==="active"||e.status==="paused";return{legacy_pause:s?n("Already suspended."):o?{enabled:!0}:n("The schedule has ended."),legacy_resume:s?{enabled:!0}:n(o?"Already running on schedule.":"The schedule has ended."),legacy_run_now:e.status==="active"?{enabled:!0}:n(s?"The schedule is off: switch Active on first.":"The schedule has ended."),open_run:{enabled:!0},recreate:{enabled:!0}}}function x2(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 b2=/^([1-9][0-9]*)([smhd])$/;function j2(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 S2(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 s=String(n.target_bundle_ref||"").trim(),o=String(n.target_host_bundle_id||n.target_bundle_id||(s.includes("@")?s.slice(0,s.lastIndexOf("@")):"")||(t==null?void 0:t.bundle_id)||"").trim(),l=String(n.target_flow_id||(t==null?void 0:t.flow_id)||"").trim();if(!o||!l)throw new Error("The legacy schedule does not name its target workflow.");const u=[],c={...Np},f=typeof n.interval=="string"?n.interval.trim():"";if(!f)c.when="once",u.push("The legacy schedule ran once; pick the date and time (UTC) to run.");else{const w=b2.exec(f);let x=w?Number(w[1]):0,S=w?w[2]:"";S==="s"&&x%60===0&&(x=x/60,S="m"),S==="m"||S==="h"||S==="d"?(c.amount=String(x),c.unit=S):u.push(`The legacy interval "${f}" is not a whole number of minutes, hours or days; choose an interval.`)}typeof n.repeat_count=="number"&&n.repeat_count>=1&&(c.count=String(n.repeat_count));const m=j2(n.repeat_until);m&&(c.until=m),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:{},g={};for(const[w,x]of Object.entries(p))w==="workflow_selection"||w.startsWith("_")||(g[w]=x);return{choice:{kind:"bundle",bundle_id:o,flow_id:l},input_data:g,form:c,notes:u}}const k2={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 N2(e,t,n){return{answer_wait:async(s,o,l)=>{await e.submit_command({command_id:t(),run_id:s,type:"resume",payload:{wait_key:o,payload:l},client_id:"web_pwa"})},legacy_command:async(s,o,l)=>{await e.submit_command({command_id:t(),run_id:s,type:o,payload:l,client_id:"web_pwa"})},now_iso:n}}function C2(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(s=>typeof s=="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 M_(e){return e.show_archived||e.status_filter==="archived"?e.items:e.items.filter(t=>t.status!=="archived")}function Gy(e){return e.items.filter(t=>t.status==="archived").length}function yg(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 E2=3e4,Th=50;function Di(e){return lg(e)?e:{status:0,code:"client_error",message:e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}}function R_(e,t){const n=new Map;for(const s of e)n.set(s.run_id,s);for(const s of t)n.set(s.run_id,s);return Array.from(n.values()).sort((s,o)=>o.index-s.index)}class $2{constructor(t,n,s=[1500,4e3]){Vr(this,"state",{...k2});Vr(this,"listeners",new Set);Vr(this,"list_seq",0);Vr(this,"detail_seq",0);Vr(this,"sources_loaded",!1);this.client=t,this.host=n,this.followups_ms=s}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 s=0;s<200;s+=1){const o=await this.client.listAutomations({...this.state.status_filter?{status:this.state.status_filter}:{},...n?{cursor:n}:{},limit:Th});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 Nm(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 s=this.state.detail,o=s?n.find(l=>l.automation_id===s.automation_id):void 0;this.set({items:n,loaded:!0,loading:!1,list_error:null,refreshed_at:Date.now(),...s&&o?{detail:{...s,summary:o}}:{}}),s&&await this.reload_occurrences(s.automation_id)}catch(n){if(t!==this.list_seq)return;this.set({loading:!1,loaded:!0,list_error:Di(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(),s=++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&&tc(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:Th})]);if(s!==this.detail_seq)return;this.set({detail:{automation_id:n,summary:l??u.summary,definition:u.definition,occurrences:R_([],c.items),next_cursor:c.next_cursor,error:null}}),await this.load_trigger_sources()}catch(l){if(s!==this.detail_seq)return;this.set({error:Di(l)})}}async reload_occurrences(t){const n=this.state.detail;if(!n||n.automation_id!==t||tc(n.summary))return;const[s,o]=await Promise.all([this.client.getAutomation(t),this.client.listOccurrences(t,{limit:Th})]),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??s.summary,definition:s.definition,occurrences:R_(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:Th}),s=this.state.detail;if(!s||s.automation_id!==t.automation_id)return;this.set({detail:{...s,occurrences:R_(s.occurrences,n.items),next_cursor:n.next_cursor}})}catch(n){this.set({error:Di(n)})}}async after_change(t){await this.refresh();for(const n of this.followups_ms)setTimeout(()=>void this.refresh(),n)}async command(t,n,s,o){this.set({busy:!0});try{const l=await this.client.sendAutomationCommand(t,{type:n,...s?{payload:s}:{},...o?{command_id:o}:{}});return await this.after_change(t),l}catch(l){throw Di(l)}finally{this.set({busy:!1})}}async revise(t,n,s,o){this.set({busy:!0});try{const l=await this.client.reviseAutomation(t,{changes:n,...s!==null?{expected_revision:s}:{},...o?{command_id:o}:{}});return await this.after_change(t),l}catch(l){throw Di(l)}finally{this.set({busy:!1})}}async discuss(t,n,s,o){this.set({busy:!0});try{const l=await this.client.discuss(t,{occurrence_index:n,prompt:s,...o?{request_id:o}:{}});return this.set({notice:yg(n,l)}),l}catch(l){throw Di(l)}finally{this.set({busy:!1})}}async seen(t,n){try{await this.client.markSeen(t,n)}catch(s){throw Di(s)}}async answer_wait(t,n,s,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===s);if(!u)throw new Error(`No loaded wait ${s} on run ${n}; reload the automation.`);await this.host.answer_wait(n,s,C2(u.kind,o)),await this.after_change(t)}catch(u){throw Di(u)}finally{this.set({busy:!1})}}async row_action(t,n){const s=`automation.${n}`;this.set({error:null,notice:""});try{await this.command(t.automation_id,s),this.set({notice:n==="run_now"&&t.status==="paused"?`Run now sent to “${t.title}”; it stays paused.`:n==="pause"||n==="resume"?Ky(t.title,n==="resume"):`${A2[n]} sent to “${t.title}”.`,confirm_archive_id:""})}catch(o){this.set({error:Di(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(!tc(t))throw new Error("legacy_action on a non-legacy automation");const s=x2(n,this.host.now_iso());this.set({busy:!0,error:null,notice:""});try{await this.host.legacy_command(t.automation_id,s.type,s.payload),this.set({notice:n==="legacy_run_now"?`Run now sent to “${t.title}”.`:Ky(t.title,n==="legacy_resume")}),await this.refresh()}catch(o){this.set({error:Di(o)})}finally{this.set({busy:!1})}}report_error(t){this.set({error:Di(t)})}clear_notice(){this.set({notice:"",error:null})}dismiss_notice(){this.state.notice&&this.set({notice:""})}dismiss_error(){this.state.error&&this.set({error:null})}}function Ky(e,t){return t?`“${e}” is active: it runs on its schedule.`:`“${e}” is paused: scheduled runs are skipped.`}const A2={run_now:"Run now",archive:"Archive"};function T2(e){const t=(n,s,o)=>r.jsx("button",{type:"button",role:"radio","aria-checked":e.mode===n,className:`seg_btn ${e.mode===n?"active":""}`,"data-mode":n,title:o,onClick:()=>e.on_change(n),children:s});return r.jsxs("div",{className:"launch_mode",children:[r.jsxs("div",{className:"seg_toggle launch_mode_switch",role:"radiogroup","aria-label":"Launch mode","aria-describedby":"launch_mode_help",children:[t("once","Run once"),t("automate","Automate",e.automate_available?void 0:e.automate_reason)]}),r.jsx("p",{className:"launch_mode_help",id:"launch_mode_help","data-mode-help":e.mode,"aria-live":"polite",children:l2[e.mode]})]})}function M2(e){const t=e.form,n=Nm(e.email_status),s=t.when==="email"&&!n?"every":t.when,o=m2(t,n);return r.jsxs("div",{className:"automate_fields",children:[r.jsxs("fieldset",{"data-section":"when",children:[r.jsx("legend",{children:"When (UTC)"}),r.jsxs("div",{className:"automate_row",role:"radiogroup","aria-label":"Schedule kind",children:[r.jsxs("label",{children:[r.jsx("input",{type:"radio",name:"automate_when",value:"every",checked:s==="every",disabled:e.disabled,onChange:()=>e.on_change({when:"every"})})," Repeat"]}),r.jsxs("label",{children:[r.jsx("input",{type:"radio",name:"automate_when",value:"once",checked:s==="once",disabled:e.disabled,onChange:()=>e.on_change({when:"once"})})," Once at…"]}),r.jsxs("label",{children:[r.jsx("input",{type:"radio",name:"automate_when",value:"email",checked:s==="email",disabled:e.disabled||!n,onChange:()=>e.on_change({when:"email"})})," ",Ut.trigger_label]})]}),n?null:r.jsx(gp,{status:e.email_status,onOpenMyEmail:e.on_open_my_email}),s==="email"?r.jsx(FS,{value:t.email,onChange:l=>e.on_change({email:l}),disabled:e.disabled,idBase:"automate"}):s==="every"?r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"automate_row",role:"group","aria-label":"Presets",children:$S.map(l=>l.when.kind==="every"?r.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)}),r.jsxs("div",{className:"automate_row",children:[r.jsx("span",{children:"Every"}),r.jsx("input",{type:"number",min:1,step:1,value:t.amount,disabled:e.disabled,"aria-label":"Interval amount",onChange:l=>e.on_change({amount:l.target.value})}),r.jsxs("select",{value:t.unit,disabled:e.disabled,"aria-label":"Interval unit",onChange:l=>e.on_change({unit:l.target.value}),children:[r.jsx("option",{value:"m",children:"minutes"}),r.jsx("option",{value:"h",children:"hours"}),r.jsx("option",{value:"d",children:"days"})]})]})]}):r.jsxs("label",{className:"automate_row",children:[r.jsx("span",{children:"Run once at (UTC)"}),r.jsx("input",{type:"datetime-local",value:t.once_at,disabled:e.disabled,onChange:l=>e.on_change({once_at:l.target.value})})]}),r.jsx("div",{className:"automate_preview","aria-live":"polite","data-preview":"true",children:o||(s==="email"?"Incomplete email trigger.":"Incomplete schedule.")})]}),r.jsxs("fieldset",{"data-section":"context",children:[r.jsx("legend",{children:"Context"}),r.jsxs("label",{children:[r.jsx("input",{type:"radio",name:"automate_context",value:"independent",checked:t.context==="independent",disabled:e.disabled,onChange:()=>e.on_change({context:"independent"})})," ",r.jsx("strong",{children:"Independent"})," (default) — ",Hy.independent]}),r.jsxs("label",{children:[r.jsx("input",{type:"radio",name:"automate_context",value:"growing",checked:t.context==="growing",disabled:e.disabled,onChange:()=>e.on_change({context:"growing"})})," ",r.jsx("strong",{children:"Growing"})," — ",Hy.growing]}),r.jsx("p",{className:"help_text muted","data-context-owns":"use_context",children:f2})]}),r.jsxs("fieldset",{"data-section":"tools",children:[r.jsx("legend",{children:"Tools"}),s==="email"?r.jsx("p",{className:"help_text muted","data-email-rule":"untrusted",children:Ut.untrusted_hint}):null,r.jsxs("label",{children:[r.jsx("input",{type:"radio",name:"automate_tools",value:"auto",checked:t.tool_approval==="auto",disabled:e.disabled,onChange:()=>e.on_change({tool_approval:"auto"})})," ",MS,e.tools&&e.tools.length?r.jsxs("span",{className:"automate_preview",children:[" — ",e.tools.join(", ")]}):null]}),r.jsxs("label",{children:[r.jsx("input",{type:"radio",name:"automate_tools",value:"ask",checked:t.tool_approval==="ask",disabled:e.disabled,onChange:()=>e.on_change({tool_approval:"ask"})})," Ask each time — every tool call waits for your approval on the Automations page"]})]}),r.jsxs("fieldset",{"data-section":"email",children:[r.jsx("legend",{children:"Email"}),n?null:r.jsx(gp,{status:e.email_status,onOpenMyEmail:e.on_open_my_email}),r.jsx(zS,{notifyEmail:n&&t.notify_email,onNotifyEmailChange:l=>e.on_change({notify_email:l}),recipients:n?t.email_recipients:ag,onRecipientsChange:l=>e.on_change({email_recipients:l}),disabled:e.disabled||!n,idBase:"automate"})]})]})}function R2(e){const t=e.form;return r.jsxs("div",{className:"automate_fields launch_grid","data-section":"advanced-schedule",children:[r.jsxs("label",{className:"launch_grid_cell",style:{gridColumn:"1 / -1"},children:[r.jsx("span",{className:"launch_label",children:"Title"}),r.jsx("input",{value:t.title,maxLength:120,disabled:e.disabled,placeholder:"Defaults to the prompt's first line",onChange:n=>e.on_change({title:n.target.value})})]}),t.when==="every"?r.jsxs(r.Fragment,{children:[r.jsxs("label",{className:"launch_grid_cell",children:[r.jsx("span",{className:"launch_label",children:"First run at (UTC; empty = now)"}),r.jsx("input",{type:"datetime-local",value:t.start_at,disabled:e.disabled,onChange:n=>e.on_change({start_at:n.target.value})})]}),r.jsxs("label",{className:"launch_grid_cell",children:[r.jsx("span",{className:"launch_label",children:"Stop after this many runs"}),r.jsx("input",{type:"number",min:1,step:1,value:t.count,disabled:e.disabled,onChange:n=>e.on_change({count:n.target.value})})]}),r.jsxs("label",{className:"launch_grid_cell",children:[r.jsx("span",{className:"launch_label",children:"Stop at (UTC)"}),r.jsx("input",{type:"datetime-local",value:t.until,disabled:e.disabled,onChange:n=>e.on_change({until:n.target.value})})]})]}):null]})}const L2="abstractobserver";function I2(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,s)=>e.get_ledger(t,{after:n,limit:200,signal:s}),streamLedger:(t,n,s,o,l)=>e.stream_ledger(t,{after:n,on_step:s,signal:o,on_open:l}),submitCommand:t=>e.submit_command(t)}}function P2(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 O2=new Set(["completed","failed","cancelled"]);function D2(e){var T;const{gateway:t,discussion:n}=e,s=_.useMemo(()=>I2(t),[t]),[o,l]=_.useState(((T=n.session)==null?void 0:T.run_id)||""),[u,c]=_.useState(""),[f,m]=_.useState(!1),[p,g]=_.useState(""),{controller:w,snapshot:x}=N1({transport:s,runId:o,enabled:e.connected,clientId:L2}),S=n.session,j=!!o&&!O2.has(x.status)&&x.status!=="idle",N=b1(x),C=async I=>{var U;const K=I.trim();if(K){m(!0);try{if(S){const J=String(((U=x.run)==null?void 0:U.workflow_id)||""),Y=P2(J),se=await t.start_run(Y.flow_id,{prompt:K},{bundle_id:Y.bundle_id,session_id:S.session_id});l(se)}else{const J=await e.on_fork(n.automation_id,n.occurrence_index,K);l(J.run_id)}c("")}finally{m(!1)}}},E=r.jsxs("div",{className:"discussion_head",children:[r.jsxs("button",{type:"button",className:"btn btn_sm","data-action":"discussion-back",onClick:e.on_close,title:`Back to ${n.automation_title}`,children:[r.jsx(et,{name:"chevronRight",size:13,className:"flip_x"})," ",n.automation_title]}),r.jsxs("span",{className:"discussion_title",children:[r.jsx(et,{name:"chat",size:15})," Discussion — fork at #",n.occurrence_index]}),r.jsx("span",{className:"pane_spacer"}),S?r.jsxs(r.Fragment,{children:[r.jsxs("button",{type:"button",className:`btn btn_sm${p==="own"?" active":""}`,"data-action":"discussion-files",onClick:()=>g(p==="own"?"":"own"),title:S.workspace_root,children:[r.jsx(et,{name:"folder",size:14})," Its files"]}),r.jsxs("button",{type:"button",className:`btn btn_sm${p==="mounted"?" active":""}`,"data-action":"automation-files",onClick:()=>g(p==="mounted"?"":"mounted"),title:S.mounted_workspace,children:[r.jsx(et,{name:"folder",size:14})," Automation files"]})]}):null]});return r.jsxs("section",{className:"pane auto_detail auto_discussion","data-discussion-session":(S==null?void 0:S.session_id)||void 0,children:[p&&S?r.jsx(yx,{fetchGateway:t.fetch_gateway,runId:p==="own"?S.run_id:n.automation_id,title:p==="own"?"Discussion files":"Automation files",note:p==="own"?"The discussion's own writable folder.":"Mounted read-only for the discussion's file tools; nothing is written back.",onClose:()=>g(""),refreshKey:x.status}):null,r.jsx(_1,{header:E,messages:x.messages,draft:u,onDraftChange:c,onSend:C,busy:j||f,busyLabel:f?S?"Starting…":"Forking the automation…":N?"Waiting for you":"Working…",onCancel:j?()=>w.cancel():void 0,stopState:x.stop??null,disabled:!e.connected,interaction:J1(N,w,{records:x.records,currentRun:x.run}),placeholder:S?"Ask a follow-up…":`Ask about run #${n.occurrence_index}…`,emptyState:r.jsxs("div",{className:"help_text muted discussion_intro",children:["A new session that forks this automation at #",n.occurrence_index," with its history (runs 1–",n.occurrence_index,"). It works in its own writable workspace; the automation's files are mounted read-only for the file tools (shell commands are not sandboxed), and nothing is written back into the automation."]}),footer:x.error?r.jsx("div",{className:"observe_context_card error",role:"alert",children:x.error}):null})]})}function Rx(e){return`abstractobserver_list_open_${e}`}function Lx(){try{return typeof localStorage>"u"?null:localStorage}catch{return null}}function F2(e,t=Lx()){try{return(t==null?void 0:t.getItem(Rx(e)))!=="0"}catch{return!0}}function z2(e,t,n=Lx()){try{n==null||n.setItem(Rx(e),t?"1":"0")}catch{}}function df(e){const[t,n]=_.useState(()=>F2(e)),s=_.useCallback(()=>{n(o=>{const l=!o;return z2(e,l),l})},[e]);return[t,s]}function ff(e){return r.jsxs("button",{type:"button",className:`list_disclosure${e.className?` ${e.className}`:""}`,"aria-expanded":e.open,"aria-controls":e.controls,onClick:e.on_toggle,title:e.open?`Hide ${e.title.toLowerCase()}`:`Show ${e.title.toLowerCase()}`,children:[r.jsx(et,{name:e.open?"chevronDown":"chevronRight",size:14}),r.jsx("span",{className:"pane_title",children:e.title}),e.count!==void 0?r.jsx("span",{className:"pane_count",children:e.count}):null]})}const B2=5e3,U2=[["","All"],["active","Active"],["paused","Paused"],["completed","Completed"],["failed","Failed"],["archived","Archived"]],W2={pause:xo.pause,resume:xo.resume,run_now:xo.run_now,edit:xo.revise,archive:`${xo.archive}…`,discuss:xo.discuss},q2={pause:zi.pause,resume:zi.resume,run_now:zi.run_now,edit:zi.revise,archive:zi.archive,discuss:zi.discuss},H2={pause:"pause",resume:"resume",run_now:"run_now",edit:"revise",archive:"archive",discuss:"discuss"},V2={legacy_pause:zi.pause,legacy_resume:zi.resume,legacy_run_now:zi.run_now,open_run:"list",recreate:"refresh"};function G2(e){return r.jsx("span",{className:"auto_state","data-field":"state",children:r.jsx(Gv,{status:e.status})})}function Mh(e){return r.jsxs("span",{className:`auto_fact${e.className?` ${e.className}`:""}`,"data-field":e.field,title:e.label,children:[r.jsx(et,{name:e.icon,size:12}),r.jsx("span",{children:e.children})]})}const K2={legacy_pause:"Suspend",legacy_resume:"Resume",legacy_run_now:"Run now",open_run:"Open run",recreate:"Recreate as automation"},Y2="On: the schedule runs at its times. Off: suspended, scheduled runs are skipped until it is on again.";function Yy(e){const t=e.busy||e.ctl.enabled?null:e.ctl.reason||"Not available now.";return r.jsx(No,{variant:"sm",className:"auto_switch",action:"active",id:`auto-active-${e.summary.automation_id}`,label:xo.active,checked:e.summary.status==="active",unavailableReason:t,busy:e.busy,hint:e.hint,onChange:e.onChange})}function J2(e){const t=e.summary,n=Tx(t),s=e.state.selected_id===t.automation_id,o=e.state.busy,l=(f,m,p,g,w,x,S,j)=>r.jsxs("button",{type:"button",className:`btn btn_sm auto_action${S?" auto_action_icon":""}${w?` ${w}`:""}`,"data-action":f,disabled:!p.enabled,title:[S?m:null,p.enabled?null:p.reason,j].filter(Boolean).join(`
76
- `)||void 0,"aria-label":S?m:void 0,"aria-description":j,onClick:g,children:[x?r.jsx(et,{name:x,size:13}):null,S?null:r.jsx("span",{children:m})]},f);let u;if(n.legacy){const f=v2(t,o),m=t.status==="paused"?"legacy_resume":"legacy_pause",p=["legacy_run_now","open_run","recreate"];u=[r.jsx(Yy,{summary:t,busy:o,ctl:f[m],hint:Y2,onChange:()=>e.h.on_legacy_action(t,m)},"active"),...p.map(g=>l(g,K2[g],f[g],()=>e.h.on_legacy_action(t,g),void 0,V2[g]))]}else{const f=w2(t,o),m=t.status==="active"?"pause":"resume",p=["run_now","edit","discuss","archive"];u=[r.jsx(Yy,{summary:t,busy:o,ctl:f.active,hint:om("active",t),onChange:()=>e.h.on_row_action(t,m)},"active"),...p.map(g=>l(g,W2[g],f[g],()=>e.h.on_row_action(t,g),g==="archive"?"danger auto_action_end":void 0,q2[g],g==="archive",om(H2[g],t)))]}const c=e.state.confirm_archive_id===t.automation_id;return r.jsxs("li",{className:`auto_row${s?" selected":""}`,"data-automation-id":t.automation_id,"data-legacy":n.legacy?"true":void 0,children:[r.jsxs("button",{type:"button",className:"auto_row_main",onClick:()=>e.h.on_select(t.automation_id),"aria-current":s?"true":void 0,children:[r.jsxs("span",{className:"auto_row_title",children:[n.title,n.legacy?r.jsx("span",{className:"chip scheduled",children:"legacy"}):null,r.jsx(G2,{status:n.state}),n.attention?r.jsxs("span",{className:"chip warn auto_row_attention","data-field":"attention",children:[r.jsx(et,{name:"warning",size:12})," ",n.attention]}):null]}),r.jsxs("span",{className:"auto_row_facts",children:[r.jsx(Mh,{icon:"refresh",field:"cadence",label:"When it runs",children:n.cadence}),n.current?r.jsx(Mh,{icon:"loader",field:"current",label:"Running now",className:"auto_row_current",children:n.current}):null,r.jsxs(Mh,{icon:"clock",field:"next",label:"Next run",children:["next: ",n.next_run]}),r.jsx(Mh,{icon:"info",field:"last-status",label:"Last run",children:n.last_status})]}),n.last?r.jsx("span",{className:"auto_row_excerpt","data-field":"excerpt",children:wx(n.last)}):null]}),r.jsx("div",{className:"auto_row_actions",role:"toolbar","aria-label":`Controls for ${n.title}`,children:u}),c?r.jsxs("div",{className:"auto_row_confirm",role:"group","aria-label":"Confirm archive",children:[r.jsxs("span",{children:["Archive “",n.title,"”? Its history stays readable; it will not run again."]}),r.jsxs("button",{type:"button",className:"btn btn_sm danger auto_action","data-action":"archive-confirm",disabled:o,onClick:()=>e.h.on_confirm_archive(t),children:[r.jsx(et,{name:"archive",size:13}),r.jsx("span",{children:"Archive"})]}),r.jsxs("button",{type:"button",className:"btn btn_sm auto_action","data-action":"archive-cancel",onClick:e.h.on_cancel_archive,children:[r.jsx(et,{name:"x",size:13}),r.jsx("span",{children:"Keep it"})]})]}):null]})}function X2(e){const t=e.state,n=e.list?e.list.open:!0,s=t.error??t.list_error,o=s?im(s):null;return r.jsxs("section",{className:`pane auto_list${n?"":" list_collapsed"}`,"aria-label":"Automations",children:[r.jsxs("div",{className:"pane_header",children:[e.list?r.jsx(ff,{open:n,on_toggle:e.list.on_toggle,controls:"auto_list_body",title:"Automations",count:M_(t).length}):r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"pane_title",children:"Automations"}),r.jsx("span",{className:"pane_count",children:M_(t).length})]}),r.jsx("span",{className:"pane_spacer"}),r.jsx("select",{className:"seg_select",value:t.status_filter,onChange:l=>e.h.on_status_filter(l.target.value),"aria-label":"Filter by status",children:U2.map(([l,u])=>r.jsx("option",{value:l,children:u},l||"all"))}),r.jsx("button",{type:"button",className:"btn btn_sm auto_icon_btn","data-action":"refresh",onClick:e.h.on_refresh,disabled:t.loading||!e.available.available,title:"Refresh","aria-label":"Refresh",children:r.jsx(et,{name:t.loading?"loader":"refresh",size:14})}),r.jsxs("a",{className:`btn btn_sm auto_new${e.available.available?"":" disabled"}`,"data-action":"new",href:u2,"aria-disabled":!e.available.available,title:"New automation: opens Launch in Automate mode","aria-label":"New automation",onClick:l=>{l.preventDefault(),e.available.available&&e.h.on_new()},children:[r.jsx(et,{name:"plus",size:14}),r.jsx("span",{className:"auto_new_label",children:"New automation"})]})]}),r.jsxs("div",{className:"pane_body scroll",id:"auto_list_body",hidden:!n,children:[e.available.available?null:r.jsx("div",{className:"warn_callout",role:"note","data-unavailable":"true",children:e.available.reason}),o?r.jsxs("div",{className:"observe_context_card error auto_list_error",role:"alert","data-code":s==null?void 0:s.code,children:[r.jsx(et,{name:"error",size:14}),r.jsxs("span",{className:"auto_list_msg",children:[r.jsx("strong",{children:o.title})," ",r.jsx("span",{children:o.detail})]}),t.error&&e.h.on_dismiss_error?r.jsx("button",{type:"button",className:"auto_dismiss","data-action":"dismiss-error","aria-label":"Dismiss",title:"Dismiss",onClick:e.h.on_dismiss_error,children:r.jsx(et,{name:"x",size:12})}):null]}):null,r.jsx("div",{className:`auto_notice${t.notice?" on":""}`,role:"status",children:t.notice?r.jsxs(r.Fragment,{children:[r.jsx(et,{name:"check",size:13}),r.jsx("span",{className:"auto_list_msg",children:t.notice}),e.h.on_dismiss_notice?r.jsx("button",{type:"button",className:"auto_dismiss","data-action":"dismiss-notice","aria-label":"Dismiss",title:"Dismiss",onClick:e.h.on_dismiss_notice,children:r.jsx(et,{name:"x",size:12})}):null]}):null}),e.available.available&&t.loaded&&!t.items.length?r.jsx("div",{className:"help_text muted",children:"No automations yet. Create one from Launch → Automate."}):null,Gy(t)>0&&t.status_filter!=="archived"?r.jsx("div",{className:"auto_show_archived",children:r.jsx(No,{variant:"sm",action:"show-archived",label:`Archived (${Gy(t)})`,hint:"List archived automations too. Their history stays readable; they do not run.",checked:t.show_archived,onChange:l=>e.h.on_show_archived(l)})}):null,r.jsx("ul",{className:"auto_rows",children:M_(t).map(l=>r.jsx(J2,{summary:l,state:t,h:e.h},l.automation_id))})]})]})}function Z2(e,t,n){const s=e.state,o=s.detail;if(!o||tc(o.summary))return null;const l=o.automation_id;return{summary:o.summary,...o.definition?{definition:o.definition}:{},occurrences:o.occurrences,triggerSources:s.trigger_sources,busy:s.busy,...o.error?{error:o.error}:{},onRevise:(u,c,f)=>e.revise(l,u,c,f==null?void 0:f.command_id),onCommand:(u,c,f)=>e.command(l,u,c,f==null?void 0:f.command_id),onDiscuss:async(u,c,f)=>{const m=await e.discuss(l,u,c,f==null?void 0:f.request_id);return t.on_open_session(m,yg(u,m),u),m},onSeen:u=>e.seen(l,u),onLoadMore:()=>void e.load_more(),onOpenRun:u=>t.on_open_run(u),...t.on_open_workspace?{onOpenWorkspace:t.on_open_workspace}:{},...t.fetch_gateway?{fetchGateway:t.fetch_gateway}:{},onAnswerWait:(u,c,f)=>e.answer_wait(l,u,c,f),...n?{editOpen:n.open,onEditOpenChange:n.on_change}:{},emailStatus:s.email_status,...t.on_open_my_email?{onOpenMyEmail:()=>{var u;return(u=t.on_open_my_email)==null?void 0:u.call(t)}}:{}}}function Q2(e){const t=e.ctl.state.detail;if(!t&&e.ctl.state.selected_id)return r.jsx("section",{className:"pane auto_detail auto_detail_empty","aria-busy":"true",children:r.jsx("div",{className:"help_text muted",children:"Loading…"})});if(!t)return r.jsx("section",{className:"pane auto_detail auto_detail_empty",children:r.jsxs("div",{className:"help_text muted",children:["Select an automation to read its runs as a conversation, change it, or discuss a result (",yp.toLowerCase(),")."]})});if(tc(t.summary)){const s=Tx(t.summary);return r.jsxs("section",{className:"pane auto_detail","data-legacy":"true",children:[r.jsxs("div",{className:"pane_header",children:[r.jsx("span",{className:"pane_title",children:s.title}),r.jsx("span",{className:"chip scheduled",children:"legacy"})]}),r.jsxs("div",{className:"pane_body",children:[r.jsxs("p",{className:"help_text",children:["A schedule created before automations (",s.cadence,"). It keeps working with its existing controls: suspend, resume, run now and edit the interval from its run view. “Recreate as automation” opens Launch → Automate prefilled with its workflow, inputs and interval; the legacy schedule is not changed."]}),r.jsxs("div",{className:"auto_row_actions",children:[r.jsx("button",{type:"button",className:"btn btn_sm","data-action":"open_run",onClick:()=>e.h.on_legacy_action(t.summary,"open_run"),children:"Open run"}),r.jsx("button",{type:"button",className:"btn btn_sm primary","data-action":"recreate",onClick:()=>e.h.on_legacy_action(t.summary,"recreate"),children:"Recreate as automation"})]})]})]})}const n=Z2(e.ctl,e.host,e.edit);return r.jsxs("section",{className:"pane auto_detail",children:[e.browser??null,n?r.jsx(Y1,{...n}):null]})}function eC(e,t){if(t==="edit")return{kind:"edit"};if(t!=="discuss")return{kind:"forward"};const n=Mx(e);return n===null?{kind:"none"}:{kind:"discuss",index:n}}function tC(e){const t=e.ctl,[n,s]=df("automations"),[o,l]=_.useState(null),u=C=>l(E=>({...C,opened:((E==null?void 0:E.opened)||0)+1})),[c,f]=_.useState(""),[m,p]=_.useState("");_.useSyncExternalStore(C=>t.subscribe(C),()=>t.state,()=>t.state);const[g,w]=_.useState(()=>typeof document>"u"||document.visibilityState!=="hidden");_.useEffect(()=>{const C=()=>w(document.visibilityState!=="hidden");return document.addEventListener("visibilitychange",C),()=>document.removeEventListener("visibilitychange",C)},[]),_.useEffect(()=>{if(!e.active||!g||!e.available.available)return;t.refresh();const C=window.setInterval(()=>void t.refresh(),E2);return()=>window.clearInterval(C)},[t,e.active,g,e.available.available]);const x=t.state.detail,S=t.state.notice;_.useEffect(()=>{if(!S)return;const C=window.setTimeout(()=>t.dismiss_notice(),B2);return()=>window.clearTimeout(C)},[t,S]);const j={...e.host,on_open_workspace:C=>f(E=>E===C?"":C),fetch_gateway:e.gateway.fetch_gateway,on_open_session:(C,E,T)=>{e.host.on_open_session(C,E,T),x&&u({automation_id:x.automation_id,automation_title:x.summary.title,occurrence_index:T,session:C})}},N={...e.h,on_select:C=>{l(null),f(""),C!==m&&p(""),e.h.on_select(C)},on_dismiss_notice:()=>t.dismiss_notice(),on_dismiss_error:()=>t.dismiss_error(),on_row_action:(C,E)=>{const T=eC(C,E);T.kind==="forward"?e.h.on_row_action(C,E):T.kind==="edit"?(l(null),f(""),p(C.automation_id),e.h.on_select(C.automation_id)):T.kind==="discuss"&&(e.h.on_select(C.automation_id),u({automation_id:C.automation_id,automation_title:C.title,occurrence_index:T.index}))}};return r.jsxs("div",{className:`page auto_page${n?"":" list_collapsed"}`,children:[r.jsx(X2,{state:t.state,available:e.available,h:N,list:{open:n,on_toggle:s}}),o?r.jsx(D2,{gateway:e.gateway,discussion:o,connected:e.active,on_fork:async(C,E,T)=>{const I=await t.discuss(C,E,T);return e.host.on_open_session(I,yg(E,I),E),l(K=>K&&{...K,session:I}),I},on_close:()=>l(null)},o.opened):r.jsx(Q2,{ctl:t,host:j,h:N,edit:{open:!!x&&m===x.automation_id,on_change:C=>p(C&&x?x.automation_id:"")},browser:c?r.jsx(yx,{fetchGateway:e.gateway.fetch_gateway,runId:c,title:c===(x==null?void 0:x.automation_id)?"Automation files":"Run files",onClose:()=>f("")}):void 0})]})}function nC(e){return r.jsx(No,{variant:"row",action:"auto-connect",label:"Auto-connect on load",description:"Reuse the browser session automatically when the app opens.",checked:e.checked,onChange:e.onChange})}function rC(e){return r.jsx("div",{className:`settings_choice ${e.checked?"on":""}`,children:r.jsx(No,{variant:"row",action:"assistant-skill",label:r.jsxs("span",{className:"settings_choice_name",children:[e.name,e.version?r.jsxs("em",{children:[" v",e.version]}):null]}),ariaLabel:e.name,description:e.description||void 0,checked:e.checked,onChange:e.onChange})})}const sC="On: the schedule runs at its times. Off: suspended, scheduled runs are skipped until it is on again.";function iC(e){return r.jsx(No,{variant:"sm",action:"schedule-active",className:"observe_schedule_switch",label:"Active",hint:sC,checked:e.active,unavailableReason:e.unavailableReason,busy:e.busy,onChange:e.onChange})}function oC(e){return r.jsx(No,{variant:"sm",action:"mindmap-live",label:"Live",hint:"Refresh the map as new memory arrives.",checked:e.checked,onChange:e.onChange})}function aC(e){return r.jsx(No,{variant:"row",action:"apply-immediately",label:"Apply immediately",description:"Recompute the next run from now if the schedule is waiting.",checked:e.checked,busy:e.busy,onChange:e.onChange})}function lC(){const e="0.6.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 cC(){return Fj("abstractobserver",lC())}async function uC(e){let t;try{t=await e.gateway_about()}catch(n){return hy(null,n instanceof Error?n.message||n.name:String(n))}return hy(t)}class cm{constructor(t){this._maxSize=cm._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=cm._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),s=Number.isFinite(n)?n:null;this._values.push(s),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 dC(e){try{return new URL(String(e)),!0}catch{return!1}}function fC({baseUrl:e,endpoint:t}){const n=String(t||"api/gateway/host/metrics/gpu");return dC(n)?n:e&&String(e).trim()?new URL(n,String(e)).toString():n}async function hC({token:e,getToken:t}){if(typeof t=="function"){const n=await t();return n==null?"":String(n)}return e==null?"":String(e)}function mC({token:e}){const t=String(e||"").trim();return t?{Authorization:`Bearer ${t}`}:{}}function _C(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 s=n.map(l=>Number(l&&l.utilization_gpu_pct)).filter(l=>Number.isFinite(l));return s.length?s.reduce((l,u)=>l+u,0)/s.length:null}return null}async function pC({baseUrl:e,endpoint:t,token:n,getToken:s,signal:o,fetchImpl:l}={}){const u=fC({baseUrl:e,endpoint:t}),c=await hC({token:n,getToken:s}),f=l||globalThis.fetch;if(typeof f!="function")return{ok:!1,status:0,error:"fetch_unavailable",payload:null};let m;try{m=await f(u,{method:"GET",headers:{Accept:"application/json",...mC({token:c})},signal:o})}catch(g){return{ok:!1,status:0,error:"network_error",detail:g instanceof Error?g.message:String(g),payload:null}}let p=null;try{p=await m.json()}catch{p=null}return{ok:m.ok,status:m.status,error:m.ok?null:"http_error",payload:p}}const Vd=Object.freeze({tickMs:1500,historySize:20,endpoint:"api/gateway/host/metrics/gpu",baseUrl:"",mode:"full"});function gC(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 L_(e,t=1){const n=Jy(Number(e)/100,0,1),s=Math.round(140-140*n),o=Jy(Number(t),0,1);return o>=1?`hsl(${s} 85% 55%)`:`hsl(${s} 85% 55% / ${o})`}function Zy(e){const t={...Vd,...e||{}};return t.tickMs=Math.max(250,Xy(t.tickMs,Vd.tickMs)),t.historySize=Math.max(1,Math.min(200,Xy(t.historySize,Vd.historySize))),t.endpoint=String(t.endpoint||Vd.endpoint),t.baseUrl=String(t.baseUrl||""),t.mode=String(t.mode||Vd.mode).trim().toLowerCase(),t.mode!=="icon"&&(t.mode="full"),t}function yC(){return`
77
- :host{display:inline-block;font-family:ui-sans-serif,system-ui,-apple-system,Segoe UI,Roboto,Helvetica,Arial,"Apple Color Emoji","Segoe UI Emoji";line-height:1}
78
- .wrap{box-sizing:border-box;display:flex;flex-direction:column;gap:6px;padding:var(--monitor-gpu-padding,8px 10px);border:1px solid var(--monitor-gpu-border,#2a2f3a);border-radius:var(--monitor-gpu-radius,10px);background:var(--monitor-gpu-bg,#0b1020);color:var(--monitor-gpu-fg,#e7eaf0);width:var(--monitor-gpu-width,180px)}
79
- .wrap.icon{gap:var(--monitor-gpu-gap,4px);padding:var(--monitor-gpu-padding,4px);border-radius:var(--monitor-gpu-radius,999px);width:var(--monitor-gpu-width,30px);background:linear-gradient(180deg,rgba(255,255,255,0.08),rgba(255,255,255,0.02)),var(--monitor-gpu-bg,#0b1020);box-shadow:0 0 14px var(--monitor-gpu-accent-glow, rgba(76,195,255,0.18))}
80
- .wrap.icon .top{display:none}
81
- .wrap.icon .bars{height:var(--monitor-gpu-bars-height,18px)}
82
- .top{display:flex;align-items:baseline;justify-content:space-between;gap:10px}
83
- .label{font-size:var(--monitor-gpu-font-size,var(--font-size-sm,12px));opacity:.9}
84
- .value{font-variant-numeric:tabular-nums;font-size:var(--monitor-gpu-font-size,var(--font-size-sm,12px));opacity:.95}
85
- .bars{display:flex;align-items:flex-end;gap:2px;height:var(--monitor-gpu-bars-height,34px);overflow:hidden}
86
- .bar{flex:1;min-width:0;border-radius:2px;background:var(--monitor-gpu-bar,#4cc3ff);height:2px;opacity:.9;transition:height .25s ease, background .25s ease, opacity .25s ease}
87
- .bar.missing{background:var(--monitor-gpu-bar-missing,#62708a);opacity:.35}
88
- .bar.error{background:var(--monitor-gpu-bar-error,#ff6b6b);opacity:.7}
89
- .muted{opacity:.6}
90
- `}class wC{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 cm(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=yC();const s=document.createElement("div");s.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",s.appendChild(o),s.appendChild(c),t.appendChild(n),t.appendChild(s),this._els={wrap:s,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||{}}),s=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"),s&&(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 s=document.createElement("div");s.className="bar missing",s.style.height="2px",t.appendChild(s)}}_render({error:t=!1}={}){if(!this._els)return;const{wrap:n,value:s,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?(s.textContent=t?"N/A":"—",s.classList.add("muted")):(s.textContent=`${c.toFixed(0)}%`,s.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",L_(c,.95)),n.style.setProperty("--monitor-gpu-accent-glow",L_(c,.35))));const f=Array.from(o.children),m=Math.max(0,f.length-l.length),p=Math.max(2,o&&typeof o.clientHeight=="number"&&o.clientHeight>0?o.clientHeight:34);for(let g=0;g<f.length;g+=1){const w=f[g],x=g-m,S=x>=0?l[x]:null,j=Number.isFinite(S)?S:null,N=j==null?0:gC(j/100),C=Math.max(2,Math.min(p,Math.round(N*p)));w.style.height=`${C}px`,w.style.background=j==null?"":L_(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,s=!!t||typeof n=="function";this._abort&&this._abort.abort(),this._abort=new AbortController;const o=await pC({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=_C(l);if(!o.ok){if(this._buffer.push(null),this._render({error:!0}),o.status===401||o.status===403){const f=String(this._token||"").trim(),m=typeof this._getToken=="function";if(!s&&(!!f||m))return;this._stoppedForAuth=!0,this.stop()}else o.status===429&&(this.stop(),this._resumeTimer=setTimeout(()=>{this._resumeTimer=null,this._mounted&&this.start()},3e4));return}if(!u||c==null){this._buffer.push(null),this._render();return}this._buffer.push(c),this._render()}async _poll_loop(t){!this._running||t!==this._timer_gen||(await this._tick(),!(!this._running||t!==this._timer_gen)&&(this._timer=setTimeout(()=>{this._timer=null,this._poll_loop(t)},this._opts.tickMs)))}}function vC(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 wC(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 ku(e){return String(e||"").trim().toLowerCase()}function Am(e){return`${(e==null?void 0:e.filename)||""} ${(e==null?void 0:e.source_path)||""}`.trim().toLowerCase()}function lf(e,t){return t.some(n=>e.endsWith(n))}function xC(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 bC(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 jC(e){const t=String(e||"").trimStart().slice(0,4096).toLowerCase();return t?!!(/^<!doctype\s+html\b/.test(t)||/^<html[\s>]/.test(t)||/<head[\s>][\s\S]*<\/head>/.test(t)||/<body[\s>][\s\S]*<\/body>/.test(t)||/<(?:article|main|section|div|p|h[1-6]|meta|title|script|style)\b[\s\S]*>/.test(t)&&/<\/(?:article|main|section|div|p|h[1-6]|title|script|style)>/.test(t)):!1}function Ix(e,t){var u,c,f,m,p;const n=ku(e==null?void 0:e.content_type),s=Am(e),o=[e==null?void 0:e.semantic_kind,e==null?void 0:e.render_kind,e==null?void 0:e.task,(u=e==null?void 0:e.tags)==null?void 0:u.semantic_kind,(c=e==null?void 0:e.tags)==null?void 0:c.render_kind,(f=e==null?void 0:e.tags)==null?void 0:f.task,(m=e==null?void 0:e.tags)==null?void 0:m.kind,(p=e==null?void 0:e.tags)==null?void 0:p.type].map(g=>String(g||"").trim().toLowerCase()).filter(Boolean).join(" ");if(/(^|[^a-z0-9])(code|source_code|script|program|executable)([^a-z0-9]|$)/i.test(o)||n.includes("javascript")||n.includes("typescript")||n.includes("x-python")||n.includes("x-shellscript")||n.includes("x-rust")||n.includes("x-go")||n.includes("x-java")||n.includes("x-csrc")||n.includes("x-c++src")||lf(s,[".py",".js",".jsx",".ts",".tsx",".mjs",".cjs",".sh",".bash",".zsh",".go",".rs",".java",".c",".cc",".cpp",".h",".hpp",".cs",".php",".rb",".swift",".kt",".sql"]))return!0;const l=String(t||"").replace(/\r\n/g,`
91
- `).replace(/\r/g,`
92
- `).split(`
93
- `);return Px(l)}function SC(e){const n=String(e||"").replace(/\r\n/g,`
94
- `).replace(/\r/g,`
95
- `).split(`
96
- `),s=n.findIndex(u=>/^Markdown Content:\s*$/i.test(u.trim()));if(s===-1)return null;const o=[];for(const u of n.slice(0,s)){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(s+1).join(`
97
- `).trim();return!o.length&&!l?null:{metadata:o,body:l}}function kC(e){const t=e.map(n=>n.trim()).filter(Boolean).slice(0,8);if(t.length<2)return!1;for(const n of[","," ",";"]){const s=t.map(o=>o.split(n).length);if(s[0]>=3&&s.every(o=>Math.abs(o-s[0])<=1))return!0}return!1}function NC(e){const t=e.map(s=>s.trimEnd()).filter(Boolean).slice(0,20);if(!t.length)return!1;const n=t.filter(s=>/^(\[[^\]]+\]|\d{4}-\d{2}-\d{2}[t\s]|\w+:\s|traceback\b|error\b|warn\b|info\b)/i.test(s.trim())).length;return t.length>=4&&n/t.length>=.55?!0:Px(e)}function Px(e){const t=e.map(s=>s.trimEnd()).filter(Boolean).slice(0,20);if(!t.length)return!1;const n=t.filter(s=>/[{};]\s*$/.test(s)||/^\s*(import|export|const|let|var|function|class|def|if|for|while|return)\b/.test(s)).length;return t.length>=4&&n/t.length>=.55}function CC(e){const t=String(e||"");if(!t.trim())return!1;const n=t.match(/\\[A-Za-z]{2,}\b/g)||[];if(n.length>=1&&/\\(?:setcctype|sectctype|documentclass|begin|end|maketitle|geq|leq|cite|ref|label)\b/.test(t)||n.length>=4)return!0;const o=t.replace(/\r\n/g,`
98
- `).replace(/\r/g,`
99
- `).split(`
100
- `).map(f=>f.trim()).filter(Boolean).slice(0,80);if(o.length<12)return!1;const l=o.filter(f=>f.length<=28).length,u=o.filter(f=>/^[,.;:()†]+$/.test(f)).length;return o.filter(f=>/^(abstract\.?|introduction|references|appendix|figure\s+\d+|table\s+\d+)\b/i.test(f)).length>=2&&(l/o.length>=.45||u>=2)}function EC(e,t){var m;const n=String(t||""),s=xC(e);if(/(^|[^a-z0-9])(markdown|mdown)([^a-z0-9]|$)/i.test(s))return!0;if(!n.trim())return!1;if(/(^|\n)\s*Markdown Content:\s*(\n|$)/i.test(n)||n.includes("```")||/(^|\n)\s*#{1,6}\s+\S/.test(n)||/(^|\n)[ \t]*[-*][ \t]+\S/.test(n)||/(^|\n)[ \t]*\d+[\.)][ \t]+\S/.test(n)||/\*\*[^*\n][\s\S]*?\*\*/.test(n)||/\[[^\]\n]+\]\([^)]+\)/.test(n)||/(^|\n)\s*\|.+\|\s*(\n|$)/.test(n)&&/(^|\n)\s*\|?\s*:?-{3,}:?\s*(\|\s*:?-{3,}:?\s*)+\|?\s*(\n|$)/.test(n))return!0;const o=n.replace(/\r\n/g,`
101
- `).replace(/\r/g,`
102
- `).split(`
103
- `),l=o.map(p=>p.trim()).filter(Boolean);if(l.length<2||CC(n)||kC(o)||NC(o))return!1;const u=((m=n.match(/[A-Za-z][A-Za-z'-]+/g))==null?void 0:m.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 cf(e){const t=ku(e==null?void 0:e.modality),n=ku(e==null?void 0:e.content_type),s=Am(e),o=bC(e);return t==="image"||n.startsWith("image/")||lf(s,[".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)||lf(s,[".wav",".mp3",".m4a",".aac",".flac",".ogg",".opus",".aiff",".mid",".midi"])?"audio":t==="video"||n.startsWith("video/")||lf(s,[".mp4",".mov",".webm",".mkv",".avi",".m4v"])?"video":!n||t==="text"||n.startsWith("text/")||n.includes("json")||n.includes("yaml")||n.includes("toml")||n.includes("xml")||n.includes("html")||n.includes("markdown")||n.includes("csv")||Ix(e,"")?"text":"binary"}function um(e,t){const n=ku(e==null?void 0:e.content_type),s=Am(e),o=String(t||"").trim();return n.includes("html")||s.endsWith(".html")||s.endsWith(".htm")||jC(t)?"html":Ix(e,t)?"code":n.includes("markdown")||s.endsWith(".md")||s.endsWith(".markdown")?"markdown":n.includes("json")||s.endsWith(".json")||s.endsWith(".jsonl")||(o.startsWith("{")||o.startsWith("["))&&Em(o)!==null?"json":EC(e,t)?"markdown":"text"}function wg(e,t=""){const n=cf(e);if(n==="image"||n==="video")return n;if(n==="audio"){const s=(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,s.semantic_kind,s.modality,s.kind,s.task,s.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 s=ku(e==null?void 0:e.modality),o=ku(e==null?void 0:e.content_type),l=Am(e);return s==="document"||o.includes("pdf")||lf(l,[".pdf",".doc",".docx",".ppt",".pptx",".xls",".xlsx"])?"document":"other"}return um(e,t)}function I_(e){var m,p;const t=String(e||"").replace(/\r\n/g,`
104
- `).replace(/\r/g,`
105
- `).trim();if(!t)return"";const n=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]),s=t.match(/<!--[\s\S]*?-->|<!doctype\b[^>]*>|<!\[CDATA\[[\s\S]*?\]\]>|<\/?[A-Za-z][^>]*>|[^<]+/gi)||[t],o=[];let l=0,u="";const c=g=>" ".repeat(Math.max(0,g)),f=(g,w)=>{const x=g.match(/^(<\/?|<!)([^\s/>]+)([\s\S]*?)(\/?>)$/);if(!x||g.length<=120||g.startsWith("</")||g.startsWith("<!"))return[`${c(w)}${g.trim()}`];const S=(x[3]||"").trim();if(!S)return[`${c(w)}${g.trim()}`];const j=S.match(/[^\s="'<>`]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'<>`]+))?/g)||[S];return[`${c(w)}${x[1]}${x[2]}`,...j.map(N=>`${c(w+1)}${N.trim()}`),`${c(w)}${x[4]}`]};for(const g of s){const w=String(g||"");if(!w.trim())continue;const x=w.trim().toLowerCase();if(x.startsWith("</")){const j=((m=x.match(/^<\/\s*([a-z0-9:-]+)/))==null?void 0:m[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(`
106
- `).map(N=>`${c(l)}${N.trimEnd()}`));continue}const S=w.replace(/\s+/g," ").trim();S&&o.push(`${c(l)}${S}`)}return o.join(`
107
- `)}const $C=/^\s*<runtime_metadata>\s*([\s\S]*?)\s*<\/runtime_metadata>\s*/i;function vg(e){const t=typeof e=="string"?e:String(e??""),n=$C.exec(t);if(!n)return{text:t.trim(),metadata:null,stripped:!1};let s=null;try{const o=JSON.parse(String(n[1]||"").trim());o&&typeof o=="object"&&!Array.isArray(o)&&(s=o)}catch{s=null}return{text:t.slice(n[0].length).trim(),metadata:s,stripped:!0}}function Ox(...e){const t={};for(const n of e)if(!(!n||typeof n!="object"||Array.isArray(n)))for(const[s,o]of Object.entries(n))o==null||String(o).trim()===""||(t[s]=o);return Object.keys(t).length?t:null}function Ep(e){if(e==null)return"";if(typeof e=="string")return e.trim();if(Array.isArray(e))return e.map(t=>Ep(t)).filter(Boolean).join(`
108
- `).trim();if(typeof e=="object"){const t=e.text??e.content??e.message??e.value;if(t!==e){const n=Ep(t);if(n)return n}}return""}function Dx(e){const t=vg(Ep(e));return{text:t.text,runtime_metadata:t.metadata}}function AC(e){var s,o;if(!e)return{text:"",runtime_metadata:null};const t=typeof e.prompt=="string"?String(e.prompt).trim():"";if(t){const l=vg(t);return{text:l.text,runtime_metadata:l.metadata}}const n=[(s=e.context)==null?void 0:s.messages,e.messages,e.conversation,e.history].filter(Array.isArray);for(const l of n)for(let u=l.length-1;u>=0;u-=1){const c=l[u],f=String((c==null?void 0:c.role)||(c==null?void 0:c.speaker)||"").trim().toLowerCase();if(f&&f!=="user"&&f!=="human")continue;const m=Dx((c==null?void 0:c.content)??(c==null?void 0:c.text)??c);if(m.text)return{text:m.text,runtime_metadata:Ox(m.runtime_metadata,c!=null&&c.runtime_metadata&&typeof c.runtime_metadata=="object"?c.runtime_metadata:null,(o=c==null?void 0:c.metadata)!=null&&o.runtime_metadata&&typeof c.metadata.runtime_metadata=="object"?c.metadata.runtime_metadata:null)}}return{text:"",runtime_metadata:null}}function TC(e,t=6){var l,u;if(!e)return[];const s=[(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 s){const f=String((c==null?void 0:c.role)||(c==null?void 0:c.speaker)||(c==null?void 0:c.author)||"").trim().toLowerCase()||"message",m=Dx((c==null?void 0:c.content)??(c==null?void 0:c.text)??(c==null?void 0:c.message)??c),p=m.text;if(!p)continue;const g=String((c==null?void 0:c.ts)||(c==null?void 0:c.timestamp)||(c==null?void 0:c.created_at)||(c==null?void 0:c.time)||"").trim(),w=Ox(m.runtime_metadata,c!=null&&c.runtime_metadata&&typeof c.runtime_metadata=="object"?c.runtime_metadata:null,(u=c==null?void 0:c.metadata)!=null&&u.runtime_metadata&&typeof c.metadata.runtime_metadata=="object"?c.metadata.runtime_metadata:null);o.push({role:f,text:p,ts:g,runtime_metadata:w})}return o.slice(Math.max(0,o.length-Math.max(1,t)))}function Fx(e){const t=String(e||"").trim().toLowerCase().replace(/\s+/g," ");return t==="please respond:"||t==="please respond"||t==="type response..."||t==="type response"}function MC(e){const t=e.map(n=>String((n==null?void 0:n.name)||"tool").trim()).filter(Boolean);return t.length?`${t.slice(0,3).join(", ")}${t.length>3?` +${t.length-3}`:""}`:""}const zx="inferred from the call's arguments (regex heuristic) — not a declared risk tier; declared tiers replace this when the grant API ships";function Bx(e){const t=String((e==null?void 0:e.name)||"").trim().toLowerCase(),n=e!=null&&e.arguments&&typeof e.arguments=="object"?e.arguments:{},s=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")||s)&&o.push("Shell"),/[;&|]?\s*(rm|rmdir|mv|chmod|chown|sudo)\b/.test(s)&&o.push("Destructive risk"),/(^|\s)(curl|wget|scp|ssh|nc|ncat|ftp)\b/.test(s)&&o.push("Network"),/(^|\s)(cat|sed|rg|grep|ls|find|pwd)\b/.test(s)&&!/[>|]\s*\S/.test(s)&&o.push("Read path"),/[>|]\s*\S|(^|\s)(tee|touch|mkdir|cp)\b/.test(s)&&o.push("Filesystem write"),o.length||o.push("Tool call"),Array.from(new Set(o)).slice(0,4)}function xg(e,t){const n=String((e==null?void 0:e.reason)||"").trim().toLowerCase(),s=MC(t);return t.length?`Approval required: ${s||"tool call"}`:n==="user"?"Waiting for your answer":n==="event"?"Waiting for a user response event":n==="subworkflow"?"Waiting for a subworkflow":n==="until"?"Scheduled wait":n?`Waiting: ${n}`:"Waiting for input"}function Ux(e,t){return t.length?"Review the requested tool call, then approve and execute it, approve without local execution, reject it, or cancel the whole run.":(Array.isArray(e==null?void 0:e.choices)?(e==null?void 0:e.choices)||[]:[]).length?"Select one of the allowed responses, then submit it to resume this run.":(e==null?void 0:e.allow_free_text)===!1?"This wait does not allow free text. Use the available response control or inspect the ledger.":String((e==null?void 0:e.prompt)||"").trim()?"Answer the workflow question below. Submitting resumes only this wait.":"No explicit question was emitted. Inspect the original request and recent ledger context before responding."}function Wx(e,t){const n=String((e==null?void 0:e.prompt)||"").trim(),s=vg(n),o=AC(t);return s.text&&!Fx(s.text)?{text:s.text,runtime_metadata:s.metadata}:o.text?o:{text:s.text||n,runtime_metadata:s.metadata}}function RC(e,t){return Wx(e,t).text}function LC(e,t){return e||String(t||"").trim()||{}}function Bi(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 ac(e){const t=String(e.status||"unknown").trim()||"unknown";return r.jsx("span",{className:`run_status_pill ${oc(t)}`,children:t})}function IC(e){var l;const t=String((e==null?void 0:e.status)||"").trim().toLowerCase();if(ko(t))return"";const n=e!=null&&e.waiting&&typeof e.waiting=="object"?e.waiting:null,s=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?xg(n,o):s==="user"?"Waiting for your answer":s==="event"?"Waiting for a response event":s==="subworkflow"?"Waiting for subworkflow":s==="until"?"Scheduled wait":s?`Waiting: ${s}`:t==="waiting"?"Waiting, reason unknown":""}function dm(e){const t=e==null?void 0:e.error;return t?typeof t=="string"?St(t,{max_chars:220,max_lines:2}):St(cs(t,400),{max_chars:220,max_lines:2}):""}function PC(e){const t=IC(e);if(t)return t;const n=dm(e);if(n)return n;const s=String((e==null?void 0:e.current_node)||"").trim();if(s)return`Current node: ${s}`;const o=String((e==null?void 0:e.status)||"").trim().toLowerCase();return o==="running"?"Running":ko(o)?"Terminal":"No current activity reported"}function qx(e){return e!=null&&e.ref&&typeof e.ref=="object"?e.ref:e!=null&&e.artifact_ref&&typeof e.artifact_ref=="object"?e.artifact_ref:e!=null&&e.artifact&&typeof e.artifact=="object"?e.artifact:{}}function Qy(e){const t=qx(e),n=e!=null&&e.metadata&&typeof e.metadata=="object"?e.metadata:e!=null&&e.meta&&typeof e.meta=="object"?e.meta:{},s=e!=null&&e.tags&&typeof e.tags=="object"?e.tags:{},o=_n(e==null?void 0:e.modality,t==null?void 0:t.modality,n==null?void 0:n.modality,s.modality).toLowerCase();if(o)return o;const l=_n(e==null?void 0:e.content_type,e==null?void 0:e.mime_type,e==null?void 0:e.mime,t==null?void 0:t.content_type,t==null?void 0:t.mime_type,t==null?void 0:t.mime,n==null?void 0:n.content_type,s.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 OC(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 DC(e,t){if(!e||typeof e!="object")return null;const n=OC(e),s=qx(e),o=e!=null&&e.metadata&&typeof e.metadata=="object"?e.metadata:e!=null&&e.meta&&typeof e.meta=="object"?e.meta:{},l=n!=null&&n.descriptor&&typeof n.descriptor=="object"?n.descriptor:e!=null&&e.descriptor&&typeof e.descriptor=="object"?e.descriptor:{},u=_n(n.artifact_id,e.artifact_id,e.$artifact,e.id,s.artifact_id,s.$artifact,s.id,o.artifact_id,o.$artifact);if(!u)return null;const c={...s.tags&&typeof s.tags=="object"?s.tags:{},...o.tags&&typeof o.tags=="object"?o.tags:{},...n.tags&&typeof n.tags=="object"?n.tags:{},...e.tags&&typeof e.tags=="object"?e.tags:{}},f={};for(const[I,K]of Object.entries(c)){const U=String(I||"").trim();U&&(f[U]=String(K??""))}const m=_n(n.filename,e.filename,s.filename,o.filename,f.filename,f.name,e.name,s.name),p=_n(n.source_path,e.source_path,s.source_path,o.source_path,e.path,s.path,f.path,f.source_path,f.file_path),g=_n(n.content_type,e.content_type,e.mime_type,e.mime,s.content_type,s.mime_type,s.mime,o.content_type,f.content_type),w=_n(n.render_kind,l.render_kind,e.render_kind,f.render_kind),x=_n(n.semantic_kind,l.semantic_kind,e.semantic_kind,f.semantic_kind,f.artifact_type),S=n.access&&typeof n.access=="object"?n.access:e.access&&typeof e.access=="object"?e.access:{},j=n.producer&&typeof n.producer=="object"?n.producer:e.producer&&typeof e.producer=="object"?e.producer:l.producer&&typeof l.producer=="object"?l.producer:{},N=n.provenance&&typeof n.provenance=="object"?n.provenance:e.provenance&&typeof e.provenance=="object"?e.provenance:l.provenance&&typeof l.provenance=="object"?l.provenance:{},C=n.generation&&typeof n.generation=="object"?n.generation:e.generation&&typeof e.generation=="object"?e.generation:l.generation&&typeof l.generation=="object"?l.generation:{},E=n.media&&typeof n.media=="object"?n.media:e.media&&typeof e.media=="object"?e.media:l.media&&typeof l.media=="object"?l.media:{},T=n.links&&typeof n.links=="object"?n.links:e.links&&typeof e.links=="object"?e.links:l.links&&typeof l.links=="object"?l.links:{};return{artifact_id:u,run_id:_n(n.run_id,e.run_id,s.run_id,o.run_id,f.run_id,N.run_id),content_type:g,modality:_n(n.modality,e.modality,l.modality,f.modality)||Qy({...e,ref:s,metadata:o,tags:f}),semantic_kind:x||Qy({...e,ref:s,metadata:o,tags:f}),render_kind:w||wg({content_type:g,filename:m,source_path:p,modality:_n(n.modality,e.modality,f.modality),tags:f}),task:_n(n.task,l.task,e.task,f.task,f.provider_task),classification_source:_n(n.classification_source,l.classification_source,e.classification_source),session_id:_n(n.session_id,l.session_id,e.session_id,f.session_id),workflow_id:_n(n.workflow_id,l.workflow_id,e.workflow_id,f.workflow_id,f.workflow),node_id:_n(n.node_id,l.node_id,e.node_id,f.node_id,f.node),step_id:_n(n.step_id,l.step_id,e.step_id,f.step_id),effect_id:_n(n.effect_id,l.effect_id,e.effect_id,f.effect_id,f.effect_idempotency_key),turn_id:_n(n.turn_id,l.turn_id,e.turn_id,f.turn_id,f.turn),ledger_cursor:_n(n.ledger_cursor,l.ledger_cursor,e.ledger_cursor,f.ledger_cursor,f.step_cursor),parent_run_id:_n(n.parent_run_id,l.parent_run_id,e.parent_run_id,f.parent_run_id),actor_id:_n(n.actor_id,l.actor_id,e.actor_id,f.actor_id),title:_n(n.title,e.title,f.title,f.label,f.name),created_at:_n(n.created_at,e.created_at,s.created_at,o.created_at,f.created_at),size_bytes:VN(n.size_bytes,e.size_bytes,s.size_bytes,o.size_bytes,f.size_bytes),filename:m,source_path:p,sha256:_n(n.sha256,e.sha256,s.sha256,o.sha256,f.sha256),tags:f,producer:j,provenance:N,generation:C,media:E,source_refs:Array.isArray(n.source_refs)?n.source_refs:Array.isArray(e.source_refs)?e.source_refs:[],access:S,links:T,available_actions:Array.isArray(n.available_actions)?n.available_actions.map(String):Array.isArray(e.available_actions)?e.available_actions.map(String):[],provider_trace_available:!!(n.provider_trace_available??e.provider_trace_available),audit_available:!!(n.audit_available??e.audit_available),legacy_inferred:!!((n.legacy_inferred??e.legacy_inferred)||/(?:legacy|inferred|runtime_tags|runtime_mime)/i.test(_n(n.classification_source,l.classification_source,e.classification_source))),descriptor:l,source:t,raw:e}}function $p(e){return e.filename||e.title||(e.source_path?e.source_path.split("/").filter(Boolean).slice(-1)[0]:"")||Qt(e.artifact_id,16)}function FC(e,t){if(t==="type")return gu(e);if(t==="run")return e.run_id||"(no run)";if(t==="turn")return Ap(e);if(t==="node")return pu(e)||"(node unknown)";if(t==="workflow")return bg(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 hf(e)||e.source||"artifact";const n=qn(e.created_at);return n===null?"(unknown time)":new Date(n).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}function bg(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 pu(e){const t=(e==null?void 0:e.tags)||{},n=String((e==null?void 0:e.node_id)||t.node_id||t.node||(e==null?void 0:e.step_id)||t.step_id||"").trim();if(n)return n;const o=String((e==null?void 0:e.source_path)||t.path||"").trim().match(/(?:^|[._:/-])(node-[A-Za-z0-9_-]+)/);return o!=null&&o[1]?String(o[1]):""}function Ap(e){const t=(e==null?void 0:e.tags)||{},n=String((e==null?void 0:e.turn_id)||t.turn_id||t.turn||t.cycle||(e==null?void 0:e.ledger_cursor)||t.ledger_cursor||t.step_cursor||"").trim();if(n)return`turn ${n}`;const s=pu(e),o=qn(e==null?void 0:e.created_at),l=o===null?"unknown time":new Date(o).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}),u=e!=null&&e.run_id?Qt(String(e.run_id),10):"unknown run";return s?`${u} · ${s} · ${l}`:`${u} · ${l}`}function ew(e){if(!e)return"provenance unavailable";const t=[],n=bg(e),s=pu(e),o=hf(e),l=Hx(e);return n&&t.push(n),s&&t.push(s),o&&t.push(o),l&&t.push(l),t.length?t.join(" · "):"provenance unavailable"}function Yl(e){if(typeof e!="number"||!Number.isFinite(e)||e<0)return"—";const t=["B","KB","MB","GB","TB"];let n=e,s=0;for(;n>=1024&&s<t.length-1;)n/=1024,s+=1;const o=s===0?0:n>=10?1:2;return`${n.toFixed(o)} ${t[s]}`}function gu(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(),s=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"}[s]||s.replace(/[_-]+/g," ").replace(/\b\w/g,l=>l.toUpperCase())}function zC(e){return e==="html"?"HTML":e==="json"?"JSON":e==="audio"?"Unclassified audio":e==="code"?"Code":e.slice(0,1).toUpperCase()+e.slice(1)}function BC(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 UC(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 tw(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 WC(e){const t=bu(e.created_at),n=ec(e.created_at);return t==="—"?"Created —":`${t}${n&&n!=="—"?` (${n})`:""}`}function nw(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(),s=bu(n);return s==="—"?"—":s}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 s=String(e.source_path||t.path||"").trim();if(s)return s.split("/").filter(Boolean).slice(-1)[0]||s;const o=hf(e),l=gu(e);return o?`${l} ${o}`:`${l} artifact`}function hf(e){var n;const t=e.tags||{};return String(e.task||((n=e.provenance)==null?void 0:n.source)||t.task||t.kind||t.source||e.source||"").trim()}function Hx(e){var s,o,l,u,c,f,m,p;if(!e)return"";const t=_n((s=e.producer)==null?void 0:s.provider,(o=e.producer)==null?void 0:o.provider_id,(l=e.provenance)==null?void 0:l.provider,(u=e.generation)==null?void 0:u.provider),n=_n((c=e.producer)==null?void 0:c.model,(f=e.producer)==null?void 0:f.model_id,(m=e.provenance)==null?void 0:m.model,(p=e.generation)==null?void 0:p.model);return t&&n?`${t} / ${n}`:t||n}function qC(e){var t,n,s,o;return e?_n((t=e.generation)==null?void 0:t.prompt,(n=e.generation)==null?void 0:n.input,(s=e.generation)==null?void 0:s.text,(o=e.provenance)==null?void 0:o.prompt):""}function sw(e){if(!e)return"";const t=e.media||{},n=Number(t.duration_s??t.duration_seconds??t.duration),s=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(s)&&Number.isFinite(o)&&s>0&&o>0)return`${Math.round(s)} x ${Math.round(o)}`;const c=Number(t.page_count??t.pages);return Number.isFinite(c)&&c>0?`${Math.round(c)} pages`:""}function iw(e){return e.source_path||e.filename||""}function fm(e,t,n){const s=e.run_id&&t[e.run_id]||null;if(!s)return e;const o=Bi(s,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 Tp(e,t,n,s=""){const o=fm(e,t,n),l=wg(o,s);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]||gu(o)}function sa(e){var s;const t=e,n=(s=t==null?void 0:t.result)==null?void 0:s.wait;return!n||typeof n!="object"?null:n}function Rh(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 s=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(!s)return null;const o=(c=n==null?void 0:n.payload)==null?void 0:c.payload;return{name:s,payload:o}}function $f(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 s=n==null?void 0:n.tool_calls;return Array.isArray(s)?s:[]}function HC(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(),s=(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"&&s?s:n||t||"record"}function Vx(e){if(!e||typeof e!="object")return"Ledger record";const t=String(e.node_id||"").trim(),n=String(e.status||"").trim(),s=HC(e),o=sa(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 ${s}`:n==="running"?`${t||"node"} started ${s}`:n==="waiting"?`${t||"node"} is waiting`:[t,n,s].filter(Boolean).join(" · ")||"Ledger record"}function su(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):cs(e,320),n=typeof e.duration=="number"?Number(e.duration):-1;return{text:t,duration:n}}return{text:cs(e,320),duration:-1}}function Gx(e){var u,c,f,m,p,g,w,x,S;if(!e||typeof e!="object")return"";const t=String(((u=e==null?void 0:e.effect)==null?void 0:u.type)||"").trim(),n=e==null?void 0:e.result,s=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 N=j,C=[N.response,N.answer,N.message,N.text,N.content];for(const E of C){const T=s(E);if(T)return T}return""};if(t==="answer_user"){const j=s(n==null?void 0:n.message)||s((c=n==null?void 0:n.output)==null?void 0:c.message)||s((f=n==null?void 0:n.output)==null?void 0:f.response)||s((p=(m=e==null?void 0:e.effect)==null?void 0:m.payload)==null?void 0:p.message)||s((w=(g=e==null?void 0:e.effect)==null?void 0:g.payload)==null?void 0:w.text)||s((S=(x=e==null?void 0:e.effect)==null?void 0:x.payload)==null?void 0:S.content);if(j)return j}if(t==="llm_call"){const j=o(n)||s(n==null?void 0:n.output)||o(n==null?void 0:n.output)||s(n==null?void 0:n.response);if(j)return j}return s(n==null?void 0:n.output)||o(n==null?void 0:n.output)||o(n)||s(n==null?void 0:n.response)}function Xh(e){var o;const t=String((e==null?void 0:e.node_id)||""),n=String((e==null?void 0:e.status)||""),s=String(((o=e==null?void 0:e.effect)==null?void 0:o.type)||"");return`${t||"(node?)"} • ${n||"(status?)"} • ${s||"(effect?)"}`}function VC(e){return!!(e&&String(e.status||"")==="waiting")}function GC(e){var n,s;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=(s=l==null?void 0:l.effect)!=null&&s.payload&&typeof l.effect.payload=="object"?l.effect.payload:{},f=l!=null&&l.result&&typeof l.result=="object"?l.result:{},m=(f==null?void 0:f.usage)||(f==null?void 0:f.token_usage)||{},p=typeof c.prompt=="string"?c.prompt:Array.isArray(c.messages)?cs(c.messages,1800):"",g=typeof f.content=="string"?f.content:typeof f.response=="string"?f.response:typeof l.result=="string"?String(l.result):"",w=qn(l.started_at),x=qn(l.ended_at),S=Number(m.prompt_tokens??m.input_tokens??0)||0,j=Number(m.completion_tokens??m.output_tokens??0)||0;t.push({id:`${String(o.run_id||l.run_id||"")}:${o.cursor}`,cursor:Number(o.cursor||0),ts:String(l.ended_at||l.started_at||""),run_id:String(o.run_id||l.run_id||"").trim(),node_id:String(l.node_id||"").trim(),provider:String(c.provider||f.provider||f.runtime_provider||"").trim(),model:String(c.model||f.model||f.runtime_model||"").trim(),prompt_preview:St(p,{max_chars:1200,max_lines:10}),response_preview:St(g,{max_chars:1200,max_lines:10}),missing_response:!String(g||"").trim(),tokens:{prompt:S,completion:j,total:Number(m.total_tokens??S+j)||0},duration_ms:w!==null&&x!==null?Math.max(0,x-w):typeof f.gen_time=="number"?Number(f.gen_time)*1e3:null,status:String(l.status||"").trim(),error:l.error?cs(l.error,500):"",raw:l})}return t.sort((o,l)=>(qn(l.ts)??0)-(qn(o.ts)??0))}function ow(e){const t=e.size||18,n=cf(e.artifact),s=wg(e.artifact,""),o=`artifact_glyph ${s==="code"?"code":n}`,l={width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:1.8,strokeLinecap:"round",strokeLinejoin:"round"};return n==="image"?r.jsx("span",{className:o,children:r.jsxs("svg",{...l,children:[r.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),r.jsx("path",{d:"M7 15l3-3 3 3 2-2 4 4"}),r.jsx("circle",{cx:"8",cy:"9",r:"1.4"})]})}):n==="audio"?r.jsx("span",{className:o,children:r.jsxs("svg",{...l,children:[r.jsx("path",{d:"M4 12h2"}),r.jsx("path",{d:"M8 8v8"}),r.jsx("path",{d:"M12 5v14"}),r.jsx("path",{d:"M16 8v8"}),r.jsx("path",{d:"M20 12h-2"})]})}):n==="video"?r.jsx("span",{className:o,children:r.jsxs("svg",{...l,children:[r.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),r.jsx("path",{d:"M9 9l6 3-6 3V9z",fill:"currentColor",stroke:"none"})]})}):s==="code"?r.jsx("span",{className:o,children:r.jsxs("svg",{...l,children:[r.jsx("path",{d:"M8 8l-4 4 4 4"}),r.jsx("path",{d:"M16 8l4 4-4 4"}),r.jsx("path",{d:"M14 4l-4 16"})]})}):n==="text"?r.jsx("span",{className:o,children:r.jsxs("svg",{...l,children:[r.jsx("path",{d:"M7 3h7l5 5v13H7z"}),r.jsx("path",{d:"M14 3v6h6"}),r.jsx("path",{d:"M10 13h7"}),r.jsx("path",{d:"M10 17h5"})]})}):r.jsx("span",{className:o,children:r.jsxs("svg",{...l,children:[r.jsx("path",{d:"M7 3h7l5 5v13H7z"}),r.jsx("path",{d:"M14 3v6h6"}),r.jsx("path",{d:"M9 14h8"})]})})}const KC=2,YC=Number.MAX_SAFE_INTEGER;function JC(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 XC(e){const t=String(e||"");if(typeof DOMParser>"u")return[{kind:"text",text:I_(t)||t}];try{const n=new DOMParser().parseFromString(t,"text/html"),s=[];n.doctype&&s.push({kind:"doctype",name:n.doctype.name||"html"});const o=l=>{if(l.nodeType===Node.TEXT_NODE){const u=String(l.textContent||"").trim();return u?{kind:"text",text:u}:null}if(l.nodeType===Node.COMMENT_NODE)return{kind:"comment",text:String(l.textContent||"")};if(l.nodeType===Node.ELEMENT_NODE){const u=l,c=Array.from(u.attributes||[]).map(m=>({name:m.name,value:m.value})),f=Array.from(u.childNodes||[]).map(o).filter(Boolean);return{kind:"element",tag:u.tagName.toLowerCase(),attrs:c,children:f}}return null};if(n.documentElement){const l=o(n.documentElement);l&&s.push(l)}return s.length?s:[{kind:"text",text:I_(t)||t}]}catch{return[{kind:"text",text:I_(t)||t}]}}function P_(e){return e.closing?r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"runtime_html_punct",children:"</"}),r.jsx("span",{className:"runtime_html_tag",children:e.tag}),r.jsx("span",{className:"runtime_html_punct",children:">"})]}):r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"runtime_html_punct",children:"<"}),r.jsx("span",{className:"runtime_html_tag",children:e.tag}),e.attrs.map(t=>r.jsxs(ve.Fragment,{children:[" ",r.jsx("span",{className:"runtime_html_attr",children:t.name}),r.jsx("span",{className:"runtime_html_punct",children:"="}),r.jsxs("span",{className:"runtime_html_value",children:['"',t.value,'"']})]},`${e.tag}:${t.name}:${t.value}`)),r.jsx("span",{className:"runtime_html_punct",children:e.selfClosing?" />":">"})]})}function Kx(e){const t=e.node,n=e.depth*14,s=e.depth<e.collapseAfterDepth,[o,l]=_.useState(s);if(_.useEffect(()=>{l(s)},[s,e.expansionVersion]),t.kind==="doctype")return r.jsxs("div",{className:"html-tree__line",style:{paddingLeft:n},children:[r.jsx("span",{className:"runtime_html_punct",children:"<!DOCTYPE "}),r.jsx("span",{className:"runtime_html_tag",children:t.name}),r.jsx("span",{className:"runtime_html_punct",children:">"})]});if(t.kind==="comment")return r.jsx("div",{className:"html-tree__line",style:{paddingLeft:n},children:r.jsx("span",{className:"runtime_html_comment",children:`<!-- ${t.text.trim()} -->`})});if(t.kind==="text")return r.jsx("div",{className:"html-tree__line html-tree__text",style:{paddingLeft:n},children:t.text});if(!t.children.length)return r.jsx("div",{className:"html-tree__line",style:{paddingLeft:n},children:r.jsx(P_,{tag:t.tag,attrs:t.attrs,selfClosing:!0})});const u=t.children.find(c=>c.kind==="text");return r.jsxs("details",{className:"html-tree__details",open:o,onToggle:c=>l(c.currentTarget.open),children:[r.jsxs("summary",{className:"html-tree__summary",style:{paddingLeft:n},children:[r.jsx("span",{className:"html-tree__caret","aria-hidden":"true",children:o?"▾":"▸"}),r.jsx(P_,{tag:t.tag,attrs:t.attrs}),!o&&u?r.jsxs("span",{className:"html-tree__summary_text",children:[" ",JC(u.text)]}):null]}),o?r.jsxs("div",{className:"html-tree__children",children:[t.children.map((c,f)=>r.jsx(Kx,{node:c,depth:e.depth+1,collapseAfterDepth:e.collapseAfterDepth,expansionMode:e.expansionMode,expansionVersion:e.expansionVersion},`${e.depth}:${t.kind}:${t.tag}:${f}`)),r.jsx("div",{className:"html-tree__line",style:{paddingLeft:n},children:r.jsx(P_,{tag:t.tag,attrs:[],closing:!0})})]}):null]})}function ZC(e){const t=_.useMemo(()=>XC(e.text),[e.text]),[n,s]=_.useState({mode:"folded",version:0}),o=n.mode==="unfolded"?YC:KC;_.useEffect(()=>{s(u=>({mode:"folded",version:u.version+1}))},[e.text]);const l=()=>{s(u=>({mode:u.mode==="unfolded"?"folded":"unfolded",version:u.version+1}))};return r.jsxs("div",{className:`${e.className} structured html_source_preview`,children:[r.jsx("div",{className:"html-tree__toolbar",children:r.jsx("button",{type:"button",className:"btn html-tree__toggle",onClick:l,"aria-expanded":n.mode==="unfolded",children:n.mode==="unfolded"?"Fold all":"Unfold all"})}),r.jsx("div",{className:"html-tree__tree",role:"tree","aria-label":"HTML source tree",children:t.map((u,c)=>r.jsx(Kx,{node:u,depth:0,collapseAfterDepth:o,expansionMode:n.mode,expansionVersion:n.version},`root:${c}`))})]})}function QC(e){var s;const t=SC(e.text);if(!t)return r.jsx("div",{className:`${e.className} structured markdown_preview`,children:r.jsx(Wi,{text:e.text})});const n=((s=t.metadata.find(o=>o.label.toLowerCase()==="title"))==null?void 0:s.value)||"";return r.jsxs("div",{className:`${e.className} structured markdown_preview artifact_markdown_report`,children:[n?r.jsx("h1",{className:"artifact_markdown_title",children:n}):null,t.metadata.length?r.jsx("dl",{className:"artifact_markdown_meta",children:t.metadata.map(o=>{const l=/^https?:\/\//i.test(o.value);return r.jsxs("div",{children:[r.jsx("dt",{children:o.label}),r.jsx("dd",{children:l?r.jsx("a",{href:o.value,target:"_blank",rel:"noreferrer",children:o.value}):o.value})]},`${o.label}:${o.value}`)})}):null,r.jsx(Wi,{text:t.body||e.text})]})}function Yx(e){const t=String(e.text||""),n=um(e.artifact,t);if(n==="json"){const s=Em(t);if(s!==null)return r.jsx("div",{className:`${e.className} structured`,children:r.jsx(Ir,{value:s,collapseAfterDepth:4,showCopy:!1})})}return n==="markdown"?r.jsx(QC,{text:t,className:e.className}):n==="html"?r.jsx(ZC,{text:t,className:e.className}):r.jsx("pre",{className:`mono ${e.className}`,children:t})}function eE(e){const t=e.preview,n=e.artifact;return n?t.loading?r.jsx("div",{className:"runtime_inline_preview empty",children:"Loading preview…"}):t.error?r.jsx("div",{className:"runtime_inline_preview empty danger",children:t.error}):t.kind==="image"&&t.url?r.jsx("img",{className:"runtime_inline_preview media",src:t.url,alt:$p(n)}):t.kind==="audio"&&t.url?r.jsx("audio",{className:"runtime_inline_preview audio",src:t.url,controls:!0}):t.kind==="video"&&t.url?r.jsx("video",{className:"runtime_inline_preview media",src:t.url,controls:!0}):r.jsx(Yx,{artifact:n,text:t.text||"Preview unavailable. Use Preview or Download.",className:"runtime_inline_preview text"}):r.jsx("div",{className:"runtime_inline_preview empty",children:"Select an artifact to preview it here."})}function jg(e){const t=e==null?void 0:e.waiting;return t&&typeof t=="object"?t:null}function Jx(e){const t=jg(e);return String((t==null?void 0:t.reason)||(e==null?void 0:e.waiting_reason)||"").trim().toLowerCase()}function aw(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 tE(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 $u(e){const t=String((e==null?void 0:e.status)||"").trim().toLowerCase();if(ko(t)||t!=="waiting")return"none";const n=jg(e),s=Jx(e);return $f(n).length?"tool_approval":s==="until"||String((e==null?void 0:e.role)||"").trim()==="controller"?"scheduled":s==="subworkflow"?"subworkflow":s==="event"?aw(n)?"user_response":"external_event":s==="user"||aw(n)?"user_response":"unknown_wait"}function Xx(e){const t=jg(e),n=$f(t),s=$u(e);return s==="tool_approval"?`Tool approval: ${tE(n)||"tool call"}`:s==="user_response"?Array.isArray(t==null?void 0:t.choices)&&t.choices.length>0?"Choice required":"User response needed":s==="scheduled"?String((e==null?void 0:e.role)||"").trim()==="controller"?"Automation waiting for its next run":"Scheduled wait":s==="subworkflow"?"Waiting for subworkflow":s==="external_event"?"Waiting for external event":s==="unknown_wait"?"Waiting, context unclear":""}function nE(e){const t=$u(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.":ko(n)?"Open the ledger and artifacts for the final outcome.":"Open the run to inspect current activity."}function lw(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 rE(e,t={}){const n=t.now_ms??Date.now(),s=t.workflow_label??"",o=String(e.status||"unknown").trim().toLowerCase()||"unknown",l=$u(e),u=ko(o),c=pg(e,n),f=qn(e.updated_at||e.created_at)??0,m=o==="running"&&c>=14400*1e3,p=Xx(e)||lw(e)||(e.current_node?`Current node: ${e.current_node}`:o==="running"?"Running":u?"Terminal":"No current activity reported");let g="all";l==="tool_approval"?g="tool_approval":l==="user_response"?g="user_wait":l==="scheduled"?g="scheduled":l==="subworkflow"||l==="external_event"?g="subflows":o==="failed"?g="failed":o==="running"?g="running":u&&(g="finished");const w=l==="tool_approval"?0:l==="user_response"?1:l==="unknown_wait"?2:o==="failed"?3:m?4:o==="running"?5:l!=="none"?6:u?8:7,x=l==="tool_approval"||l==="user_response",S=l==="tool_approval"?"Open approval":l==="user_response"?"Open wait":"Open Observe",j=[e.run_id,e.workflow_id,s,e.session_id,e.parent_run_id,e.status,e.current_node,Jx(e),p,lw(e)].join(" ").toLowerCase();return{run:e,run_id:String(e.run_id||"").trim(),status:o,wait_kind:l,queue:g,attention_rank:w,reason:p,expected_action:nE(e),action_label:S,search_text:j,is_terminal:u,needs_user_action:x,is_stale:m,duration_ms:c,updated_ms:f}}function sE(e,t={}){const n=t.now_ms??Date.now(),s=t.workflow_label_by_id??{};return e.map(o=>rE(o,{now_ms:n,workflow_label:s[String(o.workflow_id||"")]||String(o.workflow_id||"")}))}function iE(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 oE(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 aE(e,t){const n=[...e];return n.sort((s,o)=>{if(t==="recent")return o.updated_ms-s.updated_ms;if(t==="oldest")return s.updated_ms-o.updated_ms;if(t==="duration")return o.duration_ms-s.duration_ms;if(t==="tokens")return(Number(o.run.tokens_total||0)||0)-(Number(s.run.tokens_total||0)||0);if(t==="workflow")return String(s.run.workflow_id||"").localeCompare(String(o.run.workflow_id||""));const l=s.attention_rank-o.attention_rank;return l!==0?l:o.updated_ms-s.updated_ms}),n}function lE(e){const[t,n]=_.useState("attention"),[s,o]=df("system_queues"),[l,u]=df("system_runs"),[c,f]=_.useState(""),[m,p]=_.useState("attention"),[g,w]=_.useState(""),x=_.useMemo(()=>{const $={};for(const te of e.artifacts){const O=String(te.run_id||"").trim();O&&($[O]=($[O]||0)+1)}return $},[e.artifacts]),S=_.useMemo(()=>sE(e.runs,{workflow_label_by_id:e.workflow_label_by_id}),[e.runs,e.workflow_label_by_id]),j=_.useMemo(()=>iE(S),[S]),N=_.useMemo(()=>{const $=oE(S,{queue:t,query:c});return aE($,m)},[S,t,c,m]),C=N.find($=>String($.run_id||"")===g)||N.find($=>String($.run_id||"")===e.selected_run_id)||N[0]||null,E=(C==null?void 0:C.run)||null,T=String((E==null?void 0:E.run_id)||"").trim(),I=String((E==null?void 0:E.session_id)||"").trim(),K=_.useMemo(()=>I?new Set(e.runs.filter($=>String($.session_id||"").trim()===I).map($=>String($.run_id||"").trim()).filter(Boolean)):new Set,[e.runs,I]),U=I?K.size:0,J=_.useMemo(()=>I?e.artifacts.filter($=>String($.session_id||"").trim()===I||K.has(String($.run_id||"").trim())).length:0,[e.artifacts,I,K]),Y=E!=null&&E.waiting&&typeof E.waiting=="object"?E.waiting:null,se=Y?$f(Y):[],ce=(C==null?void 0:C.reason)||(Y?xg(Y,se):""),fe=(C==null?void 0:C.expected_action)||(Y?Ux(Y,se):""),W=Y?RC(Y,null):"",P=T&&x[T]||0,A=ko(E==null?void 0:E.status),z=[{key:"attention",label:"Needs attention",count:j.attention},{key:"user_wait",label:"Needs my response",count:j.user_wait},{key:"tool_approval",label:"Tool approvals",count:j.tool_approval},{key:"running",label:"Running",count:j.running},{key:"failed",label:"Failed",count:j.failed},{key:"scheduled",label:"Scheduled",count:j.scheduled},{key:"subflows",label:"Subflows / external events",count:j.subflows},{key:"finished",label:"Finished",count:j.finished},{key:"all",label:"All loaded",count:j.all}];return r.jsxs("div",{className:`runtime_ops_layout${s?"":" queues_collapsed"}${l?"":" runs_collapsed"}`,children:[r.jsxs("aside",{className:`pane runtime_ops_filters${s?"":" list_collapsed"}`,children:[r.jsxs("div",{className:"pane_header runtime_ops_filter_header",children:[r.jsx(ff,{open:s,on_toggle:o,controls:"runtime_ops_queues",title:"Queues"}),r.jsx("div",{className:"pane_spacer"}),r.jsxs("button",{className:"btn btn_icon",onClick:e.gateway_connected?e.on_refresh_runs:e.on_reconnect,children:[r.jsx(et,{name:"refresh",size:14}),e.gateway_connected?"Refresh":"Reconnect"]})]}),r.jsxs("div",{className:"pane_body scroll runtime_ops_queue_list",id:"runtime_ops_queues",hidden:!s,children:[z.map($=>r.jsxs("button",{className:`runtime_ops_filter ${t===$.key?"selected":""}`,"aria-pressed":t===$.key,onClick:()=>n($.key),children:[r.jsx("span",{children:$.label}),r.jsx("strong",{children:$.count.toLocaleString()})]},$.key)),r.jsx("div",{className:"runtime_ops_hint",children:"Counts are for the loaded runtime page. Refine search or refresh when supervising large runtimes."})]})]}),r.jsxs("section",{className:`pane runtime_ops_table_panel${l?"":" list_collapsed"}`,children:[r.jsxs("div",{className:"pane_header runtime_ops_list_header",children:[r.jsx(ff,{open:l,on_toggle:u,controls:"runtime_ops_runs",title:"Runs",count:N.length.toLocaleString()}),r.jsx("div",{className:"pane_spacer"}),r.jsx("input",{value:c,onChange:$=>f($.target.value),placeholder:"Search workflow, run, node, status, error"}),r.jsxs("select",{className:"seg_select",value:m,onChange:$=>p($.target.value),children:[r.jsx("option",{value:"attention",children:"Attention order"}),r.jsx("option",{value:"recent",children:"Latest event"}),r.jsx("option",{value:"oldest",children:"Oldest event"}),r.jsx("option",{value:"duration",children:"Longest duration"}),r.jsx("option",{value:"tokens",children:"Most tokens"}),r.jsx("option",{value:"workflow",children:"Workflow"})]})]}),r.jsxs("div",{className:"pane_body scroll runtime_ops_rows",id:"runtime_ops_runs",hidden:!l,children:[N.length?null:r.jsx("div",{className:"runtime_ops_empty",children:e.gateway_connected?"No runs match this queue.":"Gateway offline. Runtime activity cannot be loaded until the connection is restored."}),N.map($=>{const te=$.run,O=String(te.run_id||"").trim(),F=x[O]||0;return r.jsxs("div",{className:`raised runtime_ops_row ${O===T?"selected":""}`,"aria-current":O===T?"true":void 0,tabIndex:0,onClick:()=>{w(O),e.on_select_run(O)},onKeyDown:G=>{(G.key==="Enter"||G.key===" ")&&(G.preventDefault(),w(O),e.on_select_run(O))},children:[r.jsxs("div",{className:"runtime_ops_row_top",children:[r.jsx("strong",{className:"runtime_ops_row_name",children:Bi(te,e.workflow_label_by_id)}),$.is_stale?r.jsx("span",{className:"chip warn",children:"stale"}):null,r.jsx(ac,{status:te.status})]}),r.jsxs("div",{className:"runtime_ops_row_sub",children:[r.jsx("span",{className:"mono",children:Qt(O,18)}),r.jsx("span",{children:ec(te.updated_at||te.created_at)}),r.jsx("span",{children:ic(te)}),r.jsx("span",{className:"runtime_ops_row_reason",title:$.reason,children:$.reason})]}),r.jsxs("div",{className:"runtime_ops_row_foot",children:[r.jsxs("span",{className:"runtime_ops_row_facts",children:[r.jsxs("span",{children:[Number(te.llm_calls||0).toLocaleString()," llm"]}),r.jsxs("span",{children:[Number(te.tool_calls||0).toLocaleString()," tools"]}),r.jsxs("span",{children:[Number(te.tokens_total||0).toLocaleString()," tok"]}),r.jsxs("span",{children:[F.toLocaleString()," artifacts"]})]}),r.jsxs("div",{className:"runtime_ops_actions",children:[$.needs_user_action?r.jsx("button",{className:"btn primary",onClick:G=>{G.stopPropagation(),e.on_open_run(O)},children:$.action_label}):r.jsx("button",{className:"btn",onClick:G=>{G.stopPropagation(),e.on_open_run(O)},children:"Open"}),r.jsx("button",{className:"btn",onClick:G=>{G.stopPropagation(),e.on_open_ledger(O)},children:"Ledger"}),r.jsx("button",{className:"btn",onClick:G=>{G.stopPropagation(),e.on_select_run(O),e.on_open_logs()},children:"Logs"}),r.jsx("button",{className:"btn",onClick:G=>{G.stopPropagation(),e.on_filter_artifacts(O)},children:"Artifacts"})]})]})]},O)})]})]}),r.jsxs("aside",{className:"pane runtime_ops_inspector",children:[r.jsxs("div",{className:"pane_header",children:[r.jsx("span",{className:"pane_title",children:"Run inspector"}),E?r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"pane_spacer"}),r.jsx(ac,{status:E.status})]}):null]}),r.jsx("div",{className:"pane_body scroll runtime_ops_inspector_body",children:E?r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"runtime_ops_inspector_head",children:[r.jsx("h3",{children:Bi(E,e.workflow_label_by_id)}),r.jsx("span",{className:"mono",children:Qt(T,28)})]}),r.jsxs("div",{className:"runtime_ops_decision",children:[r.jsx("strong",{children:(C==null?void 0:C.reason)||PC(E)}),r.jsx("span",{children:(C==null?void 0:C.expected_action)||(String(E.status||"").toLowerCase()==="waiting"?"This run is paused until the pending wait is resolved or the run is cancelled.":A?"This run is terminal. Open the ledger for the narrative and final error/output.":"This run is active or recently updated. Use ledger/provider logs to inspect live work.")})]}),r.jsxs("div",{className:"artifact_detail_grid",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Started"}),r.jsx("strong",{children:bu(fu(E))})]}),r.jsxs("div",{children:[r.jsx("span",{children:"Elapsed"}),r.jsx("strong",{children:ic(E)})]}),r.jsxs("div",{children:[r.jsx("span",{children:"Last event"}),r.jsx("strong",{children:bu(E.updated_at||E.created_at)})]}),r.jsxs("div",{children:[r.jsx("span",{children:"Session"}),r.jsx("strong",{className:"mono",children:E.session_id?Qt(String(E.session_id),18):"—"})]}),r.jsxs("div",{children:[r.jsx("span",{children:"Node"}),r.jsx("strong",{className:"mono",children:E.current_node||"—"})]}),r.jsxs("div",{children:[r.jsx("span",{children:"Visible artifacts"}),r.jsx("strong",{children:P.toLocaleString()})]}),r.jsxs("div",{children:[r.jsx("span",{children:"Provider calls"}),r.jsx("strong",{children:Number(E.llm_calls||0).toLocaleString()})]}),r.jsxs("div",{children:[r.jsx("span",{children:"Tokens"}),r.jsx("strong",{children:Number(E.tokens_total||0).toLocaleString()})]})]}),I?r.jsxs("section",{className:"runtime_ops_session_context",children:[r.jsxs("div",{children:[r.jsx("span",{className:"run_hero_eyebrow",children:"Session context"}),r.jsx("strong",{className:"mono",children:Qt(I,30)})]}),r.jsxs("div",{className:"runtime_ops_session_facts",children:[r.jsxs("span",{children:[U.toLocaleString()," loaded run",U===1?"":"s"]}),r.jsxs("span",{children:[J.toLocaleString()," visible artifact",J===1?"":"s"]})]}),r.jsxs("div",{className:"runtime_detail_actions compact",children:[r.jsx("button",{className:"btn",onClick:()=>e.on_filter_session_artifacts(I),children:"Open session artifacts"}),r.jsx("button",{className:"btn",onClick:()=>void sc(I),children:"Copy session id"})]})]}):null,Y?r.jsxs("div",{className:"runtime_ops_wait_summary",children:[r.jsxs("div",{className:"runtime_ops_wait_header",children:[r.jsx("span",{className:"run_hero_eyebrow",children:"Blocked on"}),r.jsx("strong",{children:ce})]}),r.jsx("p",{children:fe}),W?r.jsxs("div",{className:"runtime_ops_wait_request",children:[r.jsx("span",{children:"Request"}),r.jsx(Wi,{text:W})]}):r.jsx("div",{className:"runtime_ops_wait_request muted",children:"No explicit prompt is attached to this wait. Open Observe or the ledger for full run context before responding."}),se.length?r.jsx("div",{className:"runtime_ops_wait_tools",children:se.map(($,te)=>r.jsxs(ve.Fragment,{children:[r.jsx("span",{className:"chip mono warn",children:String(($==null?void 0:$.name)||"tool")}),Bx($).map(O=>r.jsxs("span",{className:"chip muted",title:zx,children:[O,"~"]},`${te}:${O}`))]},`${String(($==null?void 0:$.name)||"tool")}:${te}`))}):null,r.jsxs("details",{className:"runtime_raw_details",children:[r.jsx("summary",{className:"muted",children:"Raw wait payload"}),r.jsx(Ir,{value:Y,collapseAfterDepth:3,showCopy:!0})]})]}):null,dm(E)?r.jsx("div",{className:"warn_callout",children:dm(E)}):null,r.jsxs("div",{className:"runtime_detail_actions",children:[r.jsx("button",{className:"btn primary",onClick:()=>e.on_open_run(T),children:"Open Observe"}),r.jsx("button",{className:"btn",onClick:()=>e.on_open_ledger(T),children:"Open ledger"}),r.jsx("button",{className:"btn",onClick:()=>e.on_filter_artifacts(T),children:"Open artifacts"}),r.jsx("button",{className:"btn",onClick:e.on_open_logs,children:"Open logs"}),r.jsx("button",{className:"btn",onClick:()=>void sc(T),children:"Copy run id"})]})]}):r.jsx("div",{className:"empty_state_inline",children:"Select a run to inspect why it is active or blocked."})})]})]})}function cE(e){const t=e.selected_artifact,n=["voice","music","sound","recording","audio","image","video","markdown","html","json","document","code","text","other"],s=[{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=_.useMemo(()=>new Set(e.type_filters),[e.type_filters]),l=Math.max(0,Number(e.artifact_total_count||0)),u=!!e.query.trim()||e.type_filters.length>0||e.date_filter!=="all"||e.scope!=="all"||!!e.artifact_run_filter.trim(),c=Math.max(1,Number(e.artifact_page_size||500)),f=Math.max(1,Math.ceil(l/c)),m=Math.min(Math.max(0,Number(e.artifact_page||0)),f-1),p=l?m*c+1:0,g=Math.min(l,m*c+e.artifacts.length),w=_.useMemo(()=>{const P={},A=e.artifact_type_facets&&Object.keys(e.artifact_type_facets).length?e.artifact_type_facets:e.artifact_facets,z=(A==null?void 0:A.semantic_kind)||{},$=(A==null?void 0:A.render_kind)||{};for(const te of n)P[te]=Number(z[te]||$[te]||0);return P.audio=Number(z.audio||0),P.other=Number(z.other||0)+Number(z.artifact||0)+Number(z.binary||0)+Number(z["(none)"]||0),P},[e.artifact_facets,e.artifact_type_facets]),x=P=>{const A=new Set(o);A.has(P)?A.delete(P):A.add(P),e.on_type_filters_change(Array.from(A.values()))},S=_.useMemo(()=>{const P={waiting:[],running:[],failed:[],cancelled:[],completed:[],other:[]};for(const A of e.runs){const z=String(A.status||"").trim().toLowerCase();z==="waiting"?P.waiting.push(A):z==="running"?P.running.push(A):z==="failed"?P.failed.push(A):z==="cancelled"?P.cancelled.push(A):z==="completed"?P.completed.push(A):P.other.push(A)}return P},[e.runs]),j=t!=null&&t.run_id&&e.run_by_id[t.run_id]||null,N=e.artifact_run_filter?Bi(e.run_by_id[e.artifact_run_filter],e.workflow_label_by_id):"",C=_.useMemo(()=>{var z;const P=new Set,A=((z=e.artifact_facets)==null?void 0:z.run_id)||{};for(const $ of Object.keys(A))$&&$!=="(none)"&&P.add($);for(const $ of e.artifacts)$.run_id&&P.add($.run_id);for(const $ of e.active_runs)$.run_id&&P.add(String($.run_id));return Array.from(P).map($=>e.run_by_id[$]||{run_id:$,workflow_id:null,status:"",created_at:null,updated_at:null}).sort(($,te)=>{const O=ju($.status)?0:1,F=ju(te.status)?0:1;if(O!==F)return O-F;const G=qn($.updated_at||$.created_at)??0;return(qn(te.updated_at||te.created_at)??0)-G}).slice(0,160)},[e.artifacts,e.active_runs,e.run_by_id,e.artifact_facets]),E=P=>{e.on_artifact_run_filter_change(P),e.on_session_filter_change(""),e.on_scope_change(P?"run":"all")},T=P=>e.gateway_connected?Math.max(0,Number(P||0)).toLocaleString():"—",I=e.selected_run_id&&e.run_by_id[e.selected_run_id]||null,K=_.useMemo(()=>{const P=e.runtime_log_query.trim().toLowerCase(),A=e.runtime_ledger_log_items||[];return P?A.filter(z=>{var O,F;const $=z.record||{};return[z.cursor,$.run_id,$.node_id,$.status,(O=$.effect)==null?void 0:O.type,$.started_at,$.ended_at,cs(((F=$.effect)==null?void 0:F.payload)??{},900),cs($.result??{},900)].join(" ").toLowerCase().includes(P)}):A},[e.runtime_ledger_log_items,e.runtime_log_query]),U=_.useMemo(()=>{const P=e.runtime_log_query.trim().toLowerCase(),A=GC(e.runtime_ledger_log_items);return P?A.filter(z=>[z.provider,z.model,z.run_id,z.node_id,z.status,z.error,z.prompt_preview,z.response_preview,z.tokens.prompt,z.tokens.completion,z.tokens.total].join(" ").toLowerCase().includes(P)):A},[e.runtime_ledger_log_items,e.runtime_log_query]),J=U.reduce((P,A)=>P+(Number(A.tokens.total)||0),0),Y=U.filter(P=>P.missing_response||P.error).length,se=_.useMemo(()=>{const P=e.runtime_log_query.trim().toLowerCase(),A=String(e.audit_log_text||"").replace(/\r\n/g,`
109
- `).replace(/\r/g,`
110
- `).split(`
111
- `).filter(Boolean);return P?A.filter(z=>z.toLowerCase().includes(P)):A},[e.audit_log_text,e.runtime_log_query]),ce=e.runtime_log_source==="run_ledger"||e.runtime_log_source==="provider_calls",fe=e.runtime_log_source==="run_ledger"?"Selected Run Ledger":e.runtime_log_source==="provider_calls"?"Provider Calls":"Gateway HTTP Audit",W=e.runtime_log_source==="run_ledger"?"Runtime execution records for the selected workflow run.":e.runtime_log_source==="provider_calls"?"Model/provider call records extracted from the selected run ledger.":"Global Gateway HTTP/audit tail. This is system activity, not artifact provenance.";return r.jsxs("div",{className:"page runtime_page",children:[r.jsxs("section",{className:"runtime_header",children:[r.jsxs("div",{children:[r.jsx("div",{className:"run_hero_eyebrow",children:"System"}),r.jsx("h2",{children:e.tab==="activity"?"Activity monitor":e.tab==="artifacts"?"Artifact explorer":e.tab==="memory"?"Active memory":"Logs"}),r.jsxs("div",{className:"run_hero_meta",children:[r.jsx("span",{className:`status_pill ${e.gateway_connected?"ok":"warn"}`,children:e.gateway_connected?"gateway connected":"gateway offline"}),e.tab==="artifacts"&&e.artifact_run_filter?r.jsxs("span",{className:"chip muted",children:["filtered run ",r.jsx("span",{className:"mono",children:Qt(e.artifact_run_filter,18)})]}):null,e.session_id?r.jsxs("span",{className:"chip muted",children:["session ",r.jsx("span",{className:"mono",children:Qt(e.session_id,18)})]}):null]})]}),r.jsxs("div",{className:"metric_grid compact runtime_header_metrics",children:[r.jsxs("div",{className:"metric_tile",children:[r.jsx("span",{children:"Waiting"}),r.jsx("strong",{children:T(S.waiting.length)})]}),r.jsxs("div",{className:"metric_tile",children:[r.jsx("span",{children:"Running"}),r.jsx("strong",{children:T(S.running.length)})]}),r.jsxs("div",{className:"metric_tile",children:[r.jsx("span",{children:"Failed"}),r.jsx("strong",{children:T(S.failed.length)})]}),r.jsxs("div",{className:"metric_tile",children:[r.jsxs("span",{children:["Artifacts",u?" (filtered)":""]}),r.jsx("strong",{children:T(l)})]})]})]}),r.jsx("nav",{className:"runtime_mode_tabs",role:"tablist","aria-label":"System sections",children:["activity","artifacts","memory","logs"].map(P=>r.jsxs("button",{role:"tab","aria-selected":e.tab===P,className:`runtime_mode_tab ${e.tab===P?"active":""}`,onClick:()=>e.on_tab_change(P),children:[r.jsx(et,{name:P==="activity"?"history":P==="artifacts"?"download":P==="memory"?"agent":"terminal",size:14}),r.jsx("span",{children:P==="activity"?"Activity":P==="artifacts"?"Artifacts":P==="memory"?"Memory":"Logs"})]},P))}),e.gateway_connected?null:r.jsxs("div",{className:"runtime_offline_banner",role:"status",children:[r.jsxs("div",{children:[r.jsx("strong",{children:"Gateway offline"}),r.jsx("span",{children:"Activity, artifacts, memory, and logs are unavailable until the gateway reconnects."})]}),r.jsxs("div",{children:[r.jsx("button",{className:"btn primary",onClick:e.on_reconnect,children:"Reconnect"}),r.jsx("button",{className:"btn",onClick:e.on_open_settings,children:"Settings"})]})]}),e.error?r.jsx("div",{className:"warn_callout",children:e.error}):null,e.tab==="activity"?r.jsx(lE,{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:P=>{E(P),e.on_select_run(P),e.on_tab_change("artifacts")},on_filter_session_artifacts:P=>{P&&(e.on_artifact_run_filter_change(""),e.on_session_filter_change(P),e.on_scope_change("session"),e.on_tab_change("artifacts"))}}):null,e.tab==="memory"?e.memory_panel?r.jsx("div",{className:"runtime_memory_panel",children:e.memory_panel}):r.jsx("div",{className:"empty_state_inline",children:"The memory explorer needs a gateway connection — sign in to browse knowledge-graph assertions."}):null,e.tab==="artifacts"?r.jsxs(r.Fragment,{children:[r.jsxs("section",{className:"pane runtime_artifact_toolbar","aria-label":"Find artifacts",children:[r.jsxs("div",{className:"runtime_artifact_toolbar_top",children:[r.jsxs("label",{className:"artifact_filter_field artifact_filter_search",children:[r.jsx("span",{children:"Search"}),r.jsx("input",{value:e.query,onChange:P=>e.on_query_change(P.target.value),placeholder:"title, path, hash, run, workflow, tag"})]}),r.jsxs("label",{className:"artifact_filter_field",children:[r.jsx("span",{children:"Scope"}),r.jsxs("select",{className:"seg_select",value:e.scope,onChange:P=>{const A=P.target.value;A!=="run"&&e.on_artifact_run_filter_change(""),A==="session"?e.on_session_filter_change(e.session_id):e.on_session_filter_change(""),e.on_scope_change(A)},children:[r.jsx("option",{value:"all",children:"All runtime"}),r.jsx("option",{value:"session",children:"This session"}),r.jsx("option",{value:"run",children:"Selected run"})]})]}),r.jsxs("label",{className:"artifact_filter_field",children:[r.jsx("span",{children:"Group"}),r.jsxs("select",{className:"seg_select",value:e.group_by,onChange:P=>e.on_group_by_change(P.target.value),children:[r.jsx("option",{value:"type",children:"Type"}),r.jsx("option",{value:"time",children:"Date"}),r.jsx("option",{value:"turn",children:"Turn"}),r.jsx("option",{value:"node",children:"Node"}),r.jsx("option",{value:"workflow",children:"Workflow"}),r.jsx("option",{value:"run",children:"Run"}),r.jsx("option",{value:"location",children:"Location"}),r.jsx("option",{value:"source",children:"Source"})]})]}),r.jsxs("label",{className:"artifact_filter_field",children:[r.jsx("span",{children:"Sort"}),r.jsxs("select",{className:"seg_select",value:e.sort_by,onChange:P=>e.on_sort_by_change(P.target.value),children:[r.jsx("option",{value:"newest",children:"Newest"}),r.jsx("option",{value:"oldest",children:"Oldest"}),r.jsx("option",{value:"last_access",children:"Last accessed"}),r.jsx("option",{value:"turn",children:"Turn order"}),r.jsx("option",{value:"type",children:"Type"}),r.jsx("option",{value:"size_desc",children:"Largest"}),r.jsx("option",{value:"size_asc",children:"Smallest"})]})]}),r.jsxs("button",{className:"btn btn_icon",onClick:e.on_refresh_artifacts,disabled:!e.gateway_connected||e.loading,children:[r.jsx(et,{name:"refresh",size:14}),e.loading?"Loading…":"Refresh"]})]}),r.jsxs("div",{className:"artifact_filter_section",children:[r.jsxs("div",{className:"artifact_filter_label",children:["Type ",r.jsx("span",{className:"muted",children:"OR"})]}),r.jsxs("div",{className:"artifact_filter_chips",role:"group","aria-label":"Artifact type filters combine with OR",children:[n.map(P=>{const A=o.has(P),z=w[P]||0,$=zC(P);return r.jsxs("button",{type:"button","aria-pressed":A,"aria-label":`${$} artifact type filter. Type filters combine with OR.`,title:`${$}: ${A?"in the filter":"not in the filter"}. Type filters combine with OR.`,className:`artifact_filter_chip ${A?"active":""}`,onClick:()=>x(P),children:[r.jsx("span",{children:$}),r.jsx("span",{className:"artifact_chip_count",children:e.gateway_connected?z.toLocaleString():"—"})]},P)}),e.type_filters.length?r.jsx("button",{type:"button",className:"artifact_filter_chip clear",onClick:()=>e.on_type_filters_change([]),children:"Clear types"}):null]})]}),r.jsxs("div",{className:"artifact_filter_section",children:[r.jsx("div",{className:"artifact_filter_label",children:"Date"}),r.jsx("div",{className:"artifact_filter_chips",role:"group","aria-label":"Artifact date filters",children:s.map(P=>r.jsx("button",{type:"button","aria-pressed":e.date_filter===P.value,className:`artifact_filter_chip ${e.date_filter===P.value?"active":""}`,onClick:()=>e.on_date_filter_change(P.value),children:P.label},P.value))})]})]}),r.jsx("div",{className:"artifact_scope_banner",children:e.artifact_run_filter?r.jsxs(r.Fragment,{children:["Showing artifacts for ",r.jsx("strong",{children:N||Qt(e.artifact_run_filter,18)}),".",r.jsx("button",{className:"btn",onClick:()=>E(""),children:"Show all"})]}):r.jsxs(r.Fragment,{children:["Showing artifacts across the selected runtime scope. Select a run to filter the inventory. ",e.artifact_total_bytes?r.jsxs("span",{className:"mono muted",children:["Total size ",Yl(e.artifact_total_bytes)]}):null]})}),r.jsxs("div",{className:"runtime_artifacts_layout",children:[r.jsxs("aside",{className:"pane artifact_filter_rail",children:[r.jsxs("div",{className:"pane_header",children:[r.jsx("span",{className:"pane_title",children:"Runs"}),r.jsx("span",{className:"pane_count",children:C.length.toLocaleString()})]}),r.jsxs("div",{className:"pane_body scroll artifact_filter_rail_list",children:[r.jsxs("button",{className:`artifact_filter_run ${e.artifact_run_filter?"":"selected"}`,onClick:()=>E(""),children:[r.jsx("strong",{children:"All artifacts"}),r.jsx("span",{children:e.gateway_connected?`${l.toLocaleString()} match${l===1?"":"es"}`:"counts unavailable"})]}),C.map(P=>{const A=String(P.run_id||"").trim(),z=A===e.artifact_run_filter||A===(t==null?void 0:t.run_id);return r.jsxs("button",{className:`artifact_filter_run ${z?"selected":""}`,onClick:()=>E(A),title:A,children:[r.jsx("strong",{children:Bi(P,e.workflow_label_by_id)}),r.jsx("span",{className:"mono",children:Qt(A,15)}),r.jsx("span",{children:ic(P)})]},A)})]})]}),r.jsxs("section",{className:"pane runtime_artifact_browser",children:[r.jsxs("div",{className:"pane_header artifact_browser_header",children:[r.jsx("span",{className:"pane_title",children:"Artifacts"}),r.jsx("span",{className:"pane_count",children:l?`${p.toLocaleString()}-${g.toLocaleString()} of ${l.toLocaleString()}`:"0 items"}),r.jsx("div",{className:"pane_spacer"}),f>1?r.jsxs("div",{className:"artifact_pagination","aria-label":"Artifact pages",children:[r.jsx("button",{className:"btn",onClick:()=>e.on_artifact_page_change(0),disabled:m<=0,children:"First"}),r.jsx("button",{className:"btn",onClick:()=>e.on_artifact_page_change(m-1),disabled:m<=0,children:"Prev"}),r.jsxs("span",{className:"muted artifact_page_label",children:["Page ",(m+1).toLocaleString()," / ",f.toLocaleString()]}),r.jsx("button",{className:"btn",onClick:()=>e.on_artifact_page_change(m+1),disabled:m>=f-1,children:"Next"}),r.jsx("button",{className:"btn",onClick:()=>e.on_artifact_page_change(f-1),disabled:m>=f-1,children:"Last"})]}):null]}),r.jsxs("div",{className:"pane_body scroll artifact_browser_body",children:[e.artifact_groups.length?null:r.jsx("div",{className:"empty_state_inline",children:e.gateway_connected?"No artifacts match the current filters.":"Gateway offline. Artifact inventory cannot be loaded until the connection is restored."}),r.jsx("div",{className:"artifact_group_list",children:e.artifact_groups.map(P=>r.jsxs("section",{className:"artifact_group",children:[r.jsxs("div",{className:"artifact_group_header",children:[r.jsx("span",{children:P.key}),r.jsx("span",{className:"artifact_group_count",children:P.items.length})]}),P.items.map(A=>{var F;const z=A.run_id&&e.run_by_id[A.run_id]||null,$=z?Bi(z,e.workflow_label_by_id):bg(A),te=sw(A),O=Number(((F=A.access)==null?void 0:F.access_count)||0)||0;return r.jsxs("button",{className:`artifact_row ${(t==null?void 0:t.artifact_id)===A.artifact_id?"selected":""}`,onClick:()=>{e.on_select_artifact(A.artifact_id),A.run_id&&e.on_select_run(A.run_id)},title:A.artifact_id,children:[r.jsx(ow,{artifact:A,size:18}),r.jsxs("div",{className:"artifact_row_main",children:[r.jsxs("div",{className:"artifact_row_title",children:[r.jsx("strong",{children:rw(fm(A,e.run_by_id,e.workflow_label_by_id))}),r.jsx("span",{className:"artifact_type_badge",children:gu(A)}),A.render_kind&&A.render_kind!==A.semantic_kind?r.jsx("span",{className:"artifact_type_badge muted",children:A.render_kind}):null,A.legacy_inferred?r.jsx("span",{className:"artifact_type_badge inferred",children:"legacy inferred"}):null]}),r.jsxs("div",{className:"artifact_row_facts",children:[r.jsxs("span",{children:[r.jsx("b",{children:"Created"})," ",WC(A)]}),r.jsxs("span",{children:[r.jsx("b",{children:"Size"})," ",Yl(A.size_bytes)]}),r.jsxs("span",{children:[r.jsx("b",{children:"Last seen"})," ",nw(A)]}),O?r.jsxs("span",{children:[r.jsx("b",{children:"Accesses"})," ",O.toLocaleString()]}):null,te?r.jsxs("span",{children:[r.jsx("b",{children:"Media"})," ",te]}):null,A.content_type?r.jsxs("span",{children:[r.jsx("b",{children:"MIME"})," ",A.content_type]}):null]}),r.jsxs("div",{className:"artifact_row_facts secondary",children:[$?r.jsxs("span",{children:[r.jsx("b",{children:"Workflow"})," ",$]}):null,A.run_id?r.jsxs("span",{className:"mono",children:[r.jsx("b",{children:"Run"})," ",Qt(A.run_id,13)]}):null,r.jsxs("span",{children:[r.jsx("b",{children:"Turn"})," ",Ap(A)]}),pu(A)?r.jsxs("span",{className:"mono",children:[r.jsx("b",{children:"Node"})," ",pu(A)]}):null,hf(A)?r.jsxs("span",{children:[r.jsx("b",{children:"Source"})," ",hf(A)]}):null]}),r.jsxs("div",{className:"artifact_row_facts tertiary",children:[r.jsxs("span",{className:"mono",children:[r.jsx("b",{children:"ID"})," ",Qt(A.artifact_id,22)]}),r.jsxs("span",{children:[r.jsx("b",{children:"Provenance"})," ",ew(A)]})]}),iw(A)?r.jsx("div",{className:"artifact_row_path mono",children:iw(A)}):null]})]},A.artifact_id)})]},P.key))})]})]}),r.jsx("aside",{className:"runtime_detail",children:r.jsxs("section",{className:"overview_panel runtime_artifact_detail",children:[r.jsxs("div",{className:"overview_panel_header",children:[r.jsx("h3",{children:"Artifact Detail"}),t?r.jsx("span",{className:"chip mono muted",children:e.embedded_preview.render_kind?Tp(t,e.run_by_id,e.workflow_label_by_id,e.embedded_preview.text):Tp(t,e.run_by_id,e.workflow_label_by_id)}):null]}),t?r.jsxs(r.Fragment,{children:[(()=>{var F,G,R,Z,X,Q,le;const P=qC(t),A=Hx(t),z=sw(t),$=Number(((F=t.access)==null?void 0:F.access_count)||0)||0,te=_n((G=t.links)==null?void 0:G.provider_trace,(R=t.links)==null?void 0:R.provider_trace_url,(Z=t.links)==null?void 0:Z.provider_trace_id),O=_n((X=t.links)==null?void 0:X.audit,(Q=t.links)==null?void 0:Q.audit_tail,(le=t.links)==null?void 0:le.audit_url);return r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"artifact_detail_header",children:[r.jsx(ow,{artifact:t,size:22}),r.jsxs("div",{children:[r.jsx("div",{className:"artifact_detail_title",children:rw(fm(t,e.run_by_id,e.workflow_label_by_id))}),r.jsxs("div",{className:"artifact_detail_subtitle",children:[gu(t)," • ",t.render_kind||e.embedded_preview.render_kind||t.modality||"artifact"," • ",t.content_type||"unknown MIME"," • ",Yl(t.size_bytes),t.legacy_inferred?" • legacy inferred":""]})]})]}),r.jsx(eE,{artifact:t,preview:e.embedded_preview}),r.jsxs("div",{className:"artifact_detail_grid",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Semantic type"}),r.jsx("strong",{children:gu(t)})]}),r.jsxs("div",{children:[r.jsx("span",{children:"Render kind"}),r.jsx("strong",{children:t.render_kind||e.embedded_preview.render_kind||"—"})]}),r.jsxs("div",{children:[r.jsx("span",{children:"Created"}),r.jsx("strong",{children:bu(t.created_at)})]}),r.jsxs("div",{children:[r.jsx("span",{children:"Size"}),r.jsx("strong",{children:Yl(t.size_bytes)})]}),r.jsxs("div",{children:[r.jsx("span",{children:"Last seen"}),r.jsx("strong",{children:nw(t)})]}),r.jsxs("div",{children:[r.jsx("span",{children:"Accesses"}),r.jsx("strong",{children:$?$.toLocaleString():"—"})]}),r.jsxs("div",{children:[r.jsx("span",{children:"Run"}),r.jsx("strong",{className:"mono",children:t.run_id?Qt(t.run_id,24):"—"})]}),r.jsxs("div",{children:[r.jsx("span",{children:"Workflow"}),r.jsx("strong",{children:j?Bi(j,e.workflow_label_by_id):"—"})]}),r.jsxs("div",{children:[r.jsx("span",{children:"Turn"}),r.jsx("strong",{children:Ap(t)})]}),r.jsxs("div",{children:[r.jsx("span",{children:"Node"}),r.jsx("strong",{className:"mono",children:pu(t)||"—"})]}),r.jsxs("div",{children:[r.jsx("span",{children:"Provider/model"}),r.jsx("strong",{children:A||"—"})]}),r.jsxs("div",{children:[r.jsx("span",{children:"Media facts"}),r.jsx("strong",{children:z||"—"})]}),r.jsxs("div",{children:[r.jsx("span",{children:"Trace"}),r.jsx("strong",{children:t.provider_trace_available?"available":"not recorded"})]}),r.jsxs("div",{children:[r.jsx("span",{children:"Provenance"}),r.jsx("strong",{children:ew(t)})]}),r.jsxs("div",{children:[r.jsx("span",{children:"Artifact id"}),r.jsx("strong",{className:"mono",children:Qt(t.artifact_id,30)})]}),t.sha256?r.jsxs("div",{children:[r.jsx("span",{children:"sha256"}),r.jsx("strong",{className:"mono",children:Qt(t.sha256,30)})]}):null]}),P?r.jsxs("div",{className:"artifact_provenance_panel",children:[r.jsx("div",{className:"artifact_filter_label",children:"Generation prompt / input"}),r.jsx("div",{className:"artifact_prompt_text",children:P})]}):r.jsxs("div",{className:"artifact_provenance_panel muted",children:[r.jsx("div",{className:"artifact_filter_label",children:"Generation prompt / input"}),r.jsx("div",{className:"artifact_prompt_text",children:"Generation prompt not recorded by the runtime artifact descriptor."})]}),Object.keys(t.generation||{}).length||Object.keys(t.producer||{}).length?r.jsxs("details",{className:"runtime_raw_details",children:[r.jsx("summary",{className:"mono muted",children:"Generation and producer metadata"}),r.jsx(Ir,{value:{generation:t.generation,producer:t.producer,source_refs:t.source_refs},collapseAfterDepth:3,showCopy:!0})]}):null,t.source_path?r.jsx("div",{className:"artifact_detail_path mono",children:t.source_path}):null,r.jsxs("div",{className:"runtime_detail_actions",children:[r.jsx("button",{className:"btn primary",onClick:()=>e.on_preview_artifact(t),disabled:!t.run_id,children:e.embedded_preview.render_kind==="html"?"Open as web page":"Open full preview"}),r.jsx("button",{className:"btn",onClick:()=>e.on_download_artifact(t),disabled:!t.run_id,children:"Download"}),r.jsx("button",{className:"btn",onClick:()=>E(t.run_id),disabled:!t.run_id,children:"Show run artifacts"}),r.jsx("button",{className:"btn",onClick:()=>e.on_open_run(t.run_id),disabled:!t.run_id,children:"Open in Observe"}),r.jsx("button",{className:"btn",onClick:()=>e.on_open_ledger(t.run_id),disabled:!t.run_id,children:"Open run ledger"}),r.jsx("button",{className:"btn",onClick:()=>{te&&window.open(te,"_blank","noopener,noreferrer")},disabled:!te,children:"Open provider trace"}),r.jsx("button",{className:"btn",onClick:()=>{O?window.open(O,"_blank","noopener,noreferrer"):e.on_tab_change("logs")},disabled:!O&&!t.audit_available,children:"Open audit trail"}),r.jsx("button",{className:"btn",onClick:()=>void sc(t.artifact_id),disabled:!t.artifact_id,children:"Copy artifact id"})]})]})})(),r.jsxs("details",{className:"runtime_raw_details",children:[r.jsx("summary",{className:"mono muted",children:"Raw metadata"}),r.jsx(Ir,{value:t.raw,collapseAfterDepth:3,showCopy:!0})]})]}):r.jsx("div",{className:"empty_state_inline",children:"Select an artifact to inspect metadata, preview, or download content."})]})})]})]}):null,e.tab==="logs"?r.jsxs("section",{className:"overview_panel runtime_logs_panel",children:[r.jsxs("div",{className:"overview_panel_header",children:[r.jsxs("div",{children:[r.jsx("h3",{children:fe}),r.jsx("div",{className:"mono muted",children:W})]}),r.jsxs("div",{className:"actions",style:{marginTop:0},children:[ce&&e.runtime_ledger_log_meta?r.jsx("span",{className:"mono muted",children:e.runtime_ledger_log_meta}):null,e.runtime_log_source==="gateway_audit"&&e.audit_log_meta?r.jsx("span",{className:"mono muted",children:e.audit_log_meta}):null,r.jsxs("button",{className:"btn btn_icon",onClick:()=>{ce?e.on_refresh_runtime_ledger(e.selected_run_id):e.on_refresh_audit()},disabled:ce?e.runtime_ledger_log_loading:e.audit_log_loading,children:[r.jsx(et,{name:"refresh",size:14}),ce?e.runtime_ledger_log_loading?"Loading…":"Refresh":e.audit_log_loading?"Loading…":"Refresh"]})]})]}),r.jsxs("div",{className:"runtime_log_toolbar",children:[r.jsxs("div",{className:"seg_toggle mono",children:[r.jsx("button",{className:`seg_btn ${e.runtime_log_source==="run_ledger"?"active":""}`,onClick:()=>e.on_runtime_log_source_change("run_ledger"),children:"Run ledger"}),r.jsx("button",{className:`seg_btn ${e.runtime_log_source==="provider_calls"?"active":""}`,onClick:()=>e.on_runtime_log_source_change("provider_calls"),children:"Provider calls"}),r.jsx("button",{className:`seg_btn ${e.runtime_log_source==="gateway_audit"?"active":""}`,onClick:()=>e.on_runtime_log_source_change("gateway_audit"),children:"Gateway audit"})]}),r.jsx("input",{className:"mono",value:e.runtime_log_query,onChange:P=>e.on_runtime_log_query_change(P.target.value),placeholder:"Search node, status, effect, payload, error"})]}),e.runtime_log_source==="run_ledger"?r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"runtime_log_context",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Selected run"}),r.jsx("strong",{children:I?Bi(I,e.workflow_label_by_id):e.selected_run_id?Qt(e.selected_run_id,24):"No run selected"}),e.selected_run_id?r.jsx("em",{className:"mono",children:Qt(e.selected_run_id,34)}):null]}),r.jsxs("div",{children:[r.jsx("span",{children:"Session"}),r.jsx("strong",{className:"mono",children:I!=null&&I.session_id?Qt(String(I.session_id),28):e.session_id?Qt(e.session_id,28):"—"})]}),r.jsxs("div",{className:"runtime_log_context_actions",children:[r.jsx("button",{className:"btn",onClick:()=>e.on_open_run(e.selected_run_id),disabled:!e.selected_run_id,children:"Open Observe"}),r.jsx("button",{className:"btn",onClick:()=>E(e.selected_run_id),disabled:!e.selected_run_id,children:"Run artifacts"})]})]}),e.runtime_ledger_log_error?r.jsx("div",{className:"warn_callout",children:e.runtime_ledger_log_error}):null,e.selected_run_id?null:r.jsx("div",{className:"empty_state_inline",children:"Select a run in Activity or Artifact Explorer to inspect its runtime ledger."}),e.selected_run_id&&!K.length&&!e.runtime_ledger_log_loading?r.jsx("div",{className:"empty_state_inline",children:"No ledger records match the current search."}):null,r.jsx("div",{className:"runtime_log_event_list","aria-label":"Selected run ledger records",children:K.map(P=>{var X,Q;const A=P.record||{},z=String(((X=A==null?void 0:A.effect)==null?void 0:X.type)||"").trim(),$=String((A==null?void 0:A.status)||"").trim(),te=String((A==null?void 0:A.node_id)||"").trim(),O=_n(A==null?void 0:A.ended_at,A==null?void 0:A.started_at,A==null?void 0:A.ts),F=sa(A),G=Vx(A),R=z?St(cs(((Q=A==null?void 0:A.effect)==null?void 0:Q.payload)??{},1200),{max_chars:1200,max_lines:6}):"",Z=Gx(A)||(F?`Waiting for ${String(F.reason||"input")}`:"")||((A==null?void 0:A.result)!==void 0?cs(A.result,700):"");return r.jsxs("article",{className:`runtime_log_event ${oc($)}`,children:[r.jsxs("div",{className:"runtime_log_event_header",children:[r.jsxs("span",{className:"mono",children:["#",P.cursor]}),r.jsx(ac,{status:$||"record"}),z?r.jsx("span",{className:"chip mono muted",children:z}):null,te?r.jsx("strong",{className:"mono",children:te}):null,O?r.jsx("span",{className:"mono muted",children:bu(O)}):null]}),r.jsxs("div",{className:"runtime_log_event_body",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Request / activity"}),r.jsx("p",{children:[G||Xh(A),R&&R!=="{}"?R:""].filter(Boolean).join(`
112
- `)})]}),r.jsxs("div",{children:[r.jsx("span",{children:"Outcome"}),r.jsx("p",{children:St(Z||"—",{max_chars:1200,max_lines:6})})]})]}),r.jsxs("details",{className:"runtime_raw_details",children:[r.jsx("summary",{className:"mono muted",children:"Raw ledger record"}),r.jsx(Ir,{value:A,collapseAfterDepth:3,showCopy:!0})]})]},`${e.selected_run_id}:${P.cursor}`)})})]}):e.runtime_log_source==="provider_calls"?r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"runtime_log_context",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Selected run"}),r.jsx("strong",{children:I?Bi(I,e.workflow_label_by_id):e.selected_run_id?Qt(e.selected_run_id,24):"No run selected"}),e.selected_run_id?r.jsx("em",{className:"mono",children:Qt(e.selected_run_id,34)}):null]}),r.jsxs("div",{children:[r.jsx("span",{children:"Provider calls"}),r.jsx("strong",{children:U.length.toLocaleString()}),r.jsx("em",{className:"mono",children:J?`${J.toLocaleString()} tokens`:"tokens not recorded"})]}),r.jsxs("div",{children:[r.jsx("span",{children:"Issues"}),r.jsx("strong",{children:Y.toLocaleString()})]}),r.jsxs("div",{className:"runtime_log_context_actions",children:[r.jsx("button",{className:"btn",onClick:()=>e.on_open_run(e.selected_run_id),disabled:!e.selected_run_id,children:"Open Observe"}),r.jsx("button",{className:"btn",onClick:()=>e.on_runtime_log_source_change("run_ledger"),disabled:!e.selected_run_id,children:"Run ledger"})]})]}),e.runtime_ledger_log_error?r.jsx("div",{className:"warn_callout",children:e.runtime_ledger_log_error}):null,e.selected_run_id?null:r.jsx("div",{className:"empty_state_inline",children:"Select a run in Activity or Artifact Explorer to inspect provider calls."}),e.selected_run_id&&!U.length&&!e.runtime_ledger_log_loading?r.jsx("div",{className:"empty_state_inline",children:"No provider calls are present in the selected run ledger, or none match the current search."}):null,r.jsx("div",{className:"provider_activity_list runtime_provider_log_list",children:U.map(P=>r.jsxs("article",{className:`provider_activity ${P.error||P.missing_response?"danger":""}`,children:[r.jsxs("div",{className:"provider_activity_header",children:[r.jsxs("div",{children:[r.jsx("h4",{children:[P.provider||"provider unknown",P.model||"model unknown"].join(" / ")}),r.jsxs("div",{className:"timeline_subtitle",children:[P.node_id?r.jsx("span",{className:"mono",children:P.node_id}):null,P.run_id?r.jsx("span",{className:"mono",children:Qt(P.run_id,16)}):null,r.jsx("span",{children:_g(P.duration_ms)}),P.status?r.jsx(ac,{status:P.status}):null]})]}),r.jsxs("div",{className:"provider_tokens mono",children:[P.tokens.total?P.tokens.total.toLocaleString():"—"," tokens"]})]}),r.jsxs("div",{className:"provider_preview_grid",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Prompt / messages"}),r.jsx("p",{children:P.prompt_preview||"No prompt payload captured"})]}),r.jsxs("div",{children:[r.jsx("span",{children:"Response / error"}),r.jsx("p",{children:P.response_preview||P.error||"No response captured"})]})]}),r.jsxs("details",{className:"runtime_raw_details",children:[r.jsx("summary",{className:"mono muted",children:"Raw provider ledger record"}),r.jsx(Ir,{value:P.raw,collapseAfterDepth:3,showCopy:!0})]})]},P.id))})]}):r.jsxs(r.Fragment,{children:[e.audit_log_error?r.jsx("div",{className:"warn_callout",children:e.audit_log_error}):null,r.jsx("pre",{className:"mono audit_log_tail",children:se.length?se.join(`
113
- `):"(audit tail not loaded or no lines match search)"})]})]}):null]})}function uE(e){const[t,n]=_.useState(""),s=Array.isArray(e.wait.choices)?e.wait.choices:[],o=e.wait.allow_free_text!==!1,l=e.disabled===!0,u=String(e.wait.prompt||"").trim();return r.jsxs(r.Fragment,{children:[s.length?r.jsxs("div",{className:"field",children:[r.jsx("label",{children:"Expected response"}),r.jsxs("select",{className:"mono",value:t,onChange:c=>n(c.target.value),children:[r.jsx("option",{value:"",children:"(select)"}),s.map((c,f)=>r.jsx("option",{value:String(c),children:String(c)},f))]})]}):null,o?r.jsxs("div",{className:"field",children:[r.jsx("label",{children:s.length?"Or type a response":u?"Your answer":"Response to resume this wait"}),r.jsx("textarea",{className:"mono wait_response_input",value:t,onChange:c=>n(c.target.value),placeholder:u?"Type your answer to the request above…":"Type the response the workflow is waiting for…",rows:4})]}):null,r.jsx("div",{className:"actions",children:r.jsx("button",{className:"btn primary",disabled:l||!t.trim(),onClick:()=>e.on_submit(t.trim()),children:"Submit response"})})]})}function cw(e,t,n){if(uf(e)==="automation"){const s=String(e.automation_id||e.run_id||"").trim();return n[s]||"Automation"}return Bi(e,t)}function uw(e){const t=uf(e.run);return t?r.jsx("span",{className:"chip scheduled run_tree_tag","data-tag":t,children:Ax(e.run)}):null}function dE(e){const t=e.selected_run_id.trim(),n=e.list?e.list.open:!0,s=e.root_run_id.trim()||t,o=e.sections.reduce((l,u)=>l+u.rows.reduce((c,f)=>{const m=[f.run,...f.children];return c+m.filter(p=>ju(p.status)).length},0),0);return r.jsxs("aside",{className:`observatory_sidebar pane${n?"":" list_collapsed"}`,children:[r.jsxs("div",{className:"run_nav_header pane_header",children:[e.list?r.jsx(ff,{open:n,on_toggle:e.list.on_toggle,controls:"run_nav_controls run_nav_tree",title:"Runs",count:`${e.total_runs.toLocaleString()} runs • ${o.toLocaleString()} active`}):r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"pane_title",children:"Runs"}),r.jsxs("span",{className:"pane_count",children:[e.total_runs.toLocaleString()," runs • ",o.toLocaleString()," active"]})]}),r.jsx("span",{className:"pane_spacer"}),r.jsxs("button",{className:"btn btn_icon",onClick:e.on_refresh,disabled:e.loading,title:"Refresh workflow runs",children:[r.jsx(et,{name:"refresh",size:14}),e.loading?"…":""]})]}),r.jsxs("div",{className:"run_nav_controls",id:"run_nav_controls",hidden:!n,children:[r.jsx("input",{value:e.search,onChange:l=>e.on_search(l.target.value),placeholder:"Search runs, sessions, workflows"}),r.jsxs("div",{className:"run_nav_filter_row",children:[r.jsx("div",{className:"seg_toggle run_nav_segments",children:["active","waiting","terminal","failed","all"].map(l=>r.jsx("button",{className:`seg_btn ${e.filter===l?"active":""}`,onClick:()=>e.on_filter(l),children:l},l))}),r.jsxs("select",{className:"seg_select",value:e.group_by,onChange:l=>e.on_group_by(l.target.value),title:"Group workflow runs",children:[r.jsx("option",{value:"status",children:"Group by status"}),r.jsx("option",{value:"workflow",children:"Group by workflow"}),r.jsx("option",{value:"session",children:"Group by session"})]})]})]}),r.jsxs("div",{className:"run_tree",id:"run_nav_tree",hidden:!n,children:[e.sections.length?null:e.connected?r.jsx("div",{className:"run_tree_empty",children:"No runs match the current filters."}):r.jsxs("div",{className:"run_tree_empty",children:["Gateway offline — runs are unavailable."," ",r.jsx("button",{className:"btn btn_sm",onClick:e.on_sign_in,children:"Sign in"})]}),e.sections.map(l=>r.jsxs("section",{className:"run_tree_section",children:[r.jsxs("div",{className:"run_tree_section_header",children:[r.jsx("span",{children:l.label}),r.jsx("span",{className:"mono",children:l.rows.length})]}),l.rows.map(u=>{const c=u.run,f=String(c.run_id||"").trim(),m=f===t;return r.jsxs("div",{className:"run_tree_group",children:[r.jsxs("button",{className:`run_tree_item ${m?"selected":""} ${f===s?"root_context":""}`,onClick:()=>e.on_select(f,f),title:f,children:[r.jsxs("div",{className:"run_tree_item_top",children:[r.jsx("span",{className:"run_tree_label",children:cw(c,e.workflow_label_by_id,e.automation_titles)}),r.jsx(uw,{run:c}),c.status?r.jsx(ac,{status:lm(c)}):null]}),r.jsxs("div",{className:"run_tree_meta",children:[r.jsx("span",{className:"mono",children:Qt(f,13)}),r.jsx("span",{children:fu(c)?ec(fu(c)):"no start"}),r.jsx("span",{children:ic(c)})]})]}),u.children.length?r.jsx("div",{className:"run_tree_children",children:u.children.map(p=>{const g=String(p.run_id||"").trim();return r.jsxs("button",{className:`run_tree_item run_tree_child ${g===t?"selected":""}`,onClick:()=>e.on_select(g,f),title:g,children:[r.jsxs("div",{className:"run_tree_item_top",children:[r.jsx("span",{className:"run_tree_label",children:cw(p,e.workflow_label_by_id,e.automation_titles)}),r.jsx(uw,{run:p}),r.jsx(ac,{status:lm(p)})]}),r.jsxs("div",{className:"run_tree_meta",children:[r.jsx("span",{className:"mono",children:Qt(g,13)}),r.jsx("span",{children:fu(p)?ec(fu(p)):"child"}),r.jsx("span",{children:ic(p)})]})]},g)})}):null]},f)})]},l.key))]})]})}class fE{constructor(){Vr(this,"_buffer","");Vr(this,"_current",{data_lines:[]})}push(t,n){for(this._buffer+=t;;){const s=this._buffer.indexOf(`
114
- `);if(s===-1)return;const o=this._buffer.slice(0,s);this._buffer=this._buffer.slice(s+1);const l=o.endsWith("\r")?o.slice(0,-1):o;if(l.startsWith(":"))continue;if(l===""){if(this._current.data_lines.length>0||this._current.event||this._current.id){const m={id:this._current.id,event:this._current.event,data:this._current.data_lines.join(`
115
- `)};n(m)}this._current={data_lines:[]};continue}const u=l.indexOf(":"),c=u===-1?l:l.slice(0,u),f=u===-1?"":l.slice(u+1).trimStart();if(c==="id"){this._current.id=f;continue}if(c==="event"){this._current.event=f;continue}if(c==="data"){this._current.data_lines.push(f);continue}}}}const Lt=rg;function ri(e,t=3e4){const n=AbortSignal.timeout(t);if(!e)return n;const s=AbortSignal.any;return typeof s=="function"?s([e,n]):e}function Zx(){var t;const e={};try{const n=(t=document.cookie.split(";").map(s=>s.trim()).find(s=>s.startsWith("abstractobserver_gateway_csrf=")))==null?void 0:t.slice(30);n&&(e["X-AbstractObserver-CSRF"]=decodeURIComponent(n))}catch{}return e}function Mt(e){const t=(e||"").trim(),n={};return t&&(n.Authorization=`Bearer ${t}`),{...n,...Zx()}}async function Wn(e){try{const t=await e.text();return t!=null&&t.trim()?t.trim():`${e.status}`}catch{return`${e.status}`}}class hE extends Error{constructor(n,s){super(s);Vr(this,"status");this.name="GatewayRequestError",this.status=n}}async function Lh(e,t){let n="";try{n=(await e.text()).trim()}catch{n=""}let s=n;try{const o=JSON.parse(n),l=o&&typeof o=="object"?o.detail:void 0;typeof l=="string"&&l.trim()?s=l.trim():l&&typeof l=="object"&&typeof l.message=="string"&&l.message.trim()&&(s=l.message.trim())}catch{}return new hE(e.status,`${t} (HTTP ${e.status}): ${s||e.statusText||"no reason given"}`)}class O_{constructor(t){Vr(this,"_cfg");Vr(this,"fetch_gateway",(t,n)=>fetch(Lt(this._cfg.base_url,t),{...n,headers:{...n==null?void 0:n.headers,...Mt(this._cfg.auth_token)}}));this._cfg={...t,base_url:(t.base_url||"").trim()}}async start_run(t,n,s){const o=String((s==null?void 0:s.bundle_id)||"").trim(),l=(s==null?void 0:s.session_id)===null||(s==null?void 0:s.session_id)===void 0?"":String(s.session_id||"").trim(),u=String(t||"").trim(),c=String((s==null?void 0:s.interface)||"").trim();if(u==="@default"&&(!c||o))throw new Error("start_run: flow_id '@default' needs `interface` and no bundle_id");const f={input_data:n||{}};o&&(f.bundle_id=o),u&&(f.flow_id=u),u==="@default"&&(f.interface=c),l&&(f.session_id=l);const m=await fetch(Lt(this._cfg.base_url,wt("runs/start")),{method:"POST",headers:{"Content-Type":"application/json",...Mt(this._cfg.auth_token)},body:JSON.stringify(f)});if(!m.ok)throw new Error(`start_run failed: ${m.status}`);const p=await m.json(),g=p==null?void 0:p.run_id;if(typeof g!="string"||!g)throw new Error("start_run: missing run_id");return g}async list_mcp_servers(){for(const t of[wt("mcp/servers"),wt("mcp"),wt("discovery/mcp")])try{const n=await fetch(Lt(this._cfg.base_url,t),{headers:{...Mt(this._cfg.auth_token)},signal:ri()});if(n.status===404||!n.ok)continue;const s=await n.json(),o=Array.isArray(s)?s:Array.isArray(s==null?void 0:s.servers)?s.servers:Array.isArray(s==null?void 0:s.items)?s.items:null;if(!o)continue;return o.map(l=>({name:String((l==null?void 0:l.name)||(l==null?void 0:l.id)||"").trim(),url:typeof(l==null?void 0:l.url)=="string"?l.url:void 0,description:typeof(l==null?void 0:l.description)=="string"?l.description:void 0,auth_required:typeof(l==null?void 0:l.auth_required)=="boolean"?l.auth_required:void 0})).filter(l=>l.name)}catch{return null}return null}async list_skills(){for(const t of[wt("skills"),wt("skills/registry")])try{const n=await fetch(Lt(this._cfg.base_url,t),{headers:{...Mt(this._cfg.auth_token)},signal:ri()});if(n.status===404||!n.ok)continue;const s=await n.json(),o=Array.isArray(s)?s:Array.isArray(s==null?void 0:s.skills)?s.skills:Array.isArray(s==null?void 0:s.items)?s.items:null;if(!o)continue;return o.map(l=>({name:String((l==null?void 0:l.name)||(l==null?void 0:l.id)||"").trim(),description:typeof(l==null?void 0:l.description)=="string"?l.description:void 0,version:typeof(l==null?void 0:l.version)=="string"?l.version:void 0,trust_level:typeof(l==null?void 0:l.trust_level)=="string"?l.trust_level:void 0,blocked:typeof(l==null?void 0:l.blocked)=="boolean"?l.blocked:void 0,requires_review:typeof(l==null?void 0:l.requires_review)=="boolean"?l.requires_review:void 0,tree_hash:typeof(l==null?void 0:l.tree_hash)=="string"?l.tree_hash:void 0,reasons:Array.isArray(l==null?void 0:l.reasons)?l.reasons.map(u=>String(u||"")).filter(Boolean):void 0})).filter(l=>l.name)}catch{return null}return null}async get_run(t){const n=await fetch(Lt(this._cfg.base_url,wt(`runs/${encodeURIComponent(t)}`)),{headers:{...Mt(this._cfg.auth_token)}});if(!n.ok)throw new Error(`get_run failed: ${await Wn(n)}`);return await n.json()}async find_run(t){const n=await fetch(Lt(this._cfg.base_url,wt(`runs/${encodeURIComponent(t)}`)),{headers:{...Mt(this._cfg.auth_token)}});if(n.status===404||n.status===403)return null;if(!n.ok)throw await Lh(n,"Opening the run failed");return await n.json()}async get_run_history_bundle(t,n){const s=String(t||"").trim();if(!s)throw new Error("get_run_history_bundle: run_id is required");const o=new URLSearchParams;(n==null?void 0:n.include_subruns)===!1&&o.set("include_subruns","false"),(n==null?void 0:n.include_session)===!0&&o.set("include_session","true"),typeof(n==null?void 0:n.session_turn_limit)=="number"&&Number.isFinite(n.session_turn_limit)&&o.set("session_turn_limit",String(Math.max(1,Math.trunc(n.session_turn_limit)))),n!=null&&n.ledger_mode&&o.set("ledger_mode",String(n.ledger_mode)),typeof(n==null?void 0:n.ledger_max_items)=="number"&&Number.isFinite(n.ledger_max_items)&&o.set("ledger_max_items",String(Math.max(0,Math.trunc(n.ledger_max_items))));const l=Lt(this._cfg.base_url,wt(`runs/${encodeURIComponent(s)}/history_bundle?${o.toString()}`)),u=await fetch(l,{headers:{...Mt(this._cfg.auth_token)}});if(!u.ok)throw new Error(`get_run_history_bundle failed: ${await Wn(u)}`);return await u.json()}async list_runs(t){const n=typeof(t==null?void 0:t.limit)=="number"?t.limit:50,s=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)),s&&c.set("status",s),o&&c.set("workflow_id",o),l&&c.set("session_id",l),u&&c.set("root_only","true"),typeof(t==null?void 0:t.include_ledger_len)=="boolean"&&c.set("include_ledger_len",String(t.include_ledger_len)),typeof(t==null?void 0:t.include_metrics)=="boolean"&&c.set("include_metrics",String(t.include_metrics)),typeof(t==null?void 0:t.include_drafts)=="boolean"&&c.set("include_drafts",String(t.include_drafts));const f=Lt(this._cfg.base_url,wt(`runs?${c.toString()}`)),m=await fetch(f,{headers:{...Mt(this._cfg.auth_token)},signal:AbortSignal.timeout(3e4)});if(!m.ok)throw new Error(`list_runs failed: ${await Wn(m)}`);return await m.json()}async audit_log_tail(t){const n=typeof(t==null?void 0:t.max_bytes)=="number"?Math.max(1024,Math.min(4e5,Math.floor(t.max_bytes))):8e4,s=Lt(this._cfg.base_url,wt(`audit/tail?max_bytes=${encodeURIComponent(String(n))}`)),o=await fetch(s,{headers:{...Mt(this._cfg.auth_token)}});if(!o.ok)throw new Error(`audit_log_tail failed: ${await Wn(o)}`);return await o.json()}async gateway_about(){const t=await fetch(Lt(this._cfg.base_url,wt("about")),{headers:{...Mt(this._cfg.auth_token)},signal:ri(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 s=await fetch(Lt(this._cfg.base_url,wt(`runs/${encodeURIComponent(n)}/input_data`)),{headers:{...Mt(this._cfg.auth_token)}});if(!s.ok)throw new Error(`get_run_input_data failed: ${await Wn(s)}`);return await s.json()}async list_run_artifacts(t,n){const s=String(t||"").trim();if(!s)throw new Error("list_run_artifacts: run_id is required");const o=typeof(n==null?void 0:n.limit)=="number"?n.limit:200,l=typeof(n==null?void 0:n.offset)=="number"?Math.max(0,Math.floor(n.offset)):0,u=Lt(this._cfg.base_url,wt(`runs/${encodeURIComponent(s)}/artifacts?limit=${encodeURIComponent(String(o))}&offset=${encodeURIComponent(String(l))}`)),c=await fetch(u,{headers:{...Mt(this._cfg.auth_token)}});if(!c.ok)throw new Error(`list_run_artifacts failed: ${await Wn(c)}`);return await c.json()}async list_session_artifacts(t,n){const s=String(t||"").trim();if(!s)throw new Error("list_session_artifacts: session_id is required");const o=typeof(n==null?void 0:n.limit)=="number"?n.limit:200,l=typeof(n==null?void 0:n.offset)=="number"?Math.max(0,Math.floor(n.offset)):0,u=Lt(this._cfg.base_url,wt(`sessions/${encodeURIComponent(s)}/artifacts?limit=${encodeURIComponent(String(o))}&offset=${encodeURIComponent(String(l))}`)),c=await fetch(u,{headers:{...Mt(this._cfg.auth_token)}});if(!c.ok)throw new Error(`list_session_artifacts failed: ${await Wn(c)}`);return await c.json()}async search_artifacts(t){const n=new URLSearchParams;n.set("scope",String((t==null?void 0:t.scope)||"all").trim()||"all");const s=String((t==null?void 0:t.session_id)||"").trim(),o=String((t==null?void 0:t.run_id)||"").trim(),l=String((t==null?void 0:t.modality)||"").trim(),u=String((t==null?void 0:t.artifact_kind)||"").trim(),c=String((t==null?void 0:t.semantic_kind)||"").trim(),f=String((t==null?void 0:t.render_kind)||"").trim(),m=String((t==null?void 0:t.workflow_id)||"").trim(),p=String((t==null?void 0:t.node_id)||"").trim(),g=String((t==null?void 0:t.content_type)||"").trim(),w=String((t==null?void 0:t.query)||"").trim(),x=String((t==null?void 0:t.tags)||"").trim(),S=String((t==null?void 0:t.cursor)||"").trim(),j=String((t==null?void 0:t.order_by)||"").trim(),N=String((t==null?void 0:t.order)||"").trim(),C=String((t==null?void 0:t.created_after)||"").trim(),E=String((t==null?void 0:t.created_before)||"").trim(),T=typeof(t==null?void 0:t.limit)=="number"?t.limit:500,I=typeof(t==null?void 0:t.offset)=="number"?Math.max(0,Math.floor(t.offset)):0;s&&n.set("session_id",s),o&&n.set("run_id",o),l&&n.set("modality",l),u&&n.set("artifact_kind",u),c&&n.set("semantic_kind",c),f&&n.set("render_kind",f),m&&n.set("workflow_id",m),p&&n.set("node_id",p),g&&n.set("content_type",g),w&&n.set("query",w),x&&n.set("tags",x),S&&n.set("cursor",S),j&&n.set("order_by",j),N&&n.set("order",N),C&&n.set("created_after",C),E&&n.set("created_before",E),t!=null&&t.include_stats&&n.set("include_stats","true"),n.set("limit",String(T)),n.set("offset",String(I));const K=await fetch(Lt(this._cfg.base_url,wt(`artifacts/search?${n.toString()}`)),{headers:{...Mt(this._cfg.auth_token)}});if(!K.ok)throw new Error(`search_artifacts failed: ${await Wn(K)}`);return await K.json()}async artifact_stats(t){const n=new URLSearchParams;n.set("scope",String((t==null?void 0:t.scope)||"all").trim()||"all");for(const o of["session_id","run_id","modality","semantic_kind","render_kind","workflow_id","node_id","content_type","query","tags","created_after","created_before"]){const l=String((t==null?void 0:t[o])||"").trim();l&&n.set(o,l)}const s=await fetch(Lt(this._cfg.base_url,wt(`artifacts/stats?${n.toString()}`)),{headers:{...Mt(this._cfg.auth_token)}});if(!s.ok)throw new Error(`artifact_stats failed: ${await Wn(s)}`);return await s.json()}async download_run_artifact_content(t,n,s){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((s==null?void 0:s.access)||"").trim(),c=u?`?access=${encodeURIComponent(u)}`:"",f=Lt(this._cfg.base_url,wt(`runs/${encodeURIComponent(o)}/artifacts/${encodeURIComponent(l)}/content${c}`)),m=await fetch(f,{headers:{...Mt(this._cfg.auth_token)}});if(!m.ok)throw new Error(`download_run_artifact_content failed: ${await Wn(m)}`);return await m.blob()}async list_entities(){const t=await fetch(Lt(this._cfg.base_url,wt("entities")),{headers:{...Mt(this._cfg.auth_token)},signal:ri()});if(!t.ok)throw new Error(`list_entities failed: ${await Wn(t)}`);const n=await t.json();return{entities:Array.isArray(n==null?void 0:n.entities)?n.entities:[]}}async get_entity_phases_spec(){const t=await fetch(Lt(this._cfg.base_url,wt("entities/spec/phases")),{headers:{...Mt(this._cfg.auth_token)},signal:ri()});if(!t.ok)throw new Error(`get_entity_phases_spec failed: ${await Wn(t)}`);return await t.json()}async get_entity_cognition(t){const n=await fetch(Lt(this._cfg.base_url,wt(`entities/${encodeURIComponent(t)}/cognition`)),{headers:{...Mt(this._cfg.auth_token)},signal:ri()});if(!n.ok)throw new Error(`get_entity_cognition failed: ${await Wn(n)}`);return await n.json()}async get_entity_card(t){const n=String(t||"").trim();if(!n)throw new Error("get_entity_card: name is required");const s=await fetch(Lt(this._cfg.base_url,wt(`entities/${encodeURIComponent(n)}/card`)),{headers:{...Mt(this._cfg.auth_token)},signal:ri()});if(!s.ok)throw new Error(`get_entity_card failed: ${await Wn(s)}`);return await s.json()}async read_entity_diary_entry(t,n){const s=String(t||"").trim(),o=String(n||"").trim();if(!s||!o)throw new Error("read_entity_diary_entry: name and entry_id are required");const l=Lt(this._cfg.base_url,wt(`entities/${encodeURIComponent(s)}/diary/${encodeURIComponent(o)}?reason=${encodeURIComponent("observer board hint chip")}`)),u=await fetch(l,{headers:{...Mt(this._cfg.auth_token)},signal:ri()});if(!u.ok)throw new Error(`read_entity_diary_entry failed: ${await Wn(u)}`);return await u.json()}async get_ledger(t,n){const s=Number((n==null?void 0:n.after)||0),o=Number((n==null?void 0:n.limit)||0),l=Lt(this._cfg.base_url,wt(`runs/${encodeURIComponent(t)}/ledger?after=${encodeURIComponent(String(s))}&limit=${encodeURIComponent(String(o))}`)),u=await fetch(l,{headers:{...Mt(this._cfg.auth_token)},signal:ri(n==null?void 0:n.signal)});if(!u.ok)throw new Error(`get_ledger failed: ${u.status}`);const c=await u.json(),f=Array.isArray(c==null?void 0:c.items)?c.items:[],m=typeof(c==null?void 0:c.next_after)=="number"?c.next_after:s;return{items:f,next_after:m}}async get_ledger_batch(t){const n=Array.isArray(t==null?void 0:t.runs)?t.runs:[],s=Number((t==null?void 0:t.limit)||0),o=await fetch(Lt(this._cfg.base_url,wt("runs/ledger/batch")),{method:"POST",headers:{"Content-Type":"application/json",...Mt(this._cfg.auth_token)},body:JSON.stringify({runs:n,limit:s}),signal:ri()});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 s=String(t||"").trim();if(!s)throw new Error("generate_run_summary: run_id is required");const o={include_subruns:(n==null?void 0:n.include_subruns)!==!1},l=typeof(n==null?void 0:n.provider)=="string"?String(n.provider).trim():"";l&&(o.provider=l);const u=typeof(n==null?void 0:n.model)=="string"?String(n.model).trim():"";u&&(o.model=u);const c=await fetch(Lt(this._cfg.base_url,wt(`runs/${encodeURIComponent(s)}/summary`)),{method:"POST",headers:{"Content-Type":"application/json",...Mt(this._cfg.auth_token)},body:JSON.stringify(o)});if(!c.ok)throw await Lh(c,"The gateway could not summarize this run");return await c.json()}async run_chat(t,n){const s=String(t||"").trim();if(!s)throw new Error("run_chat: run_id is required");const o={include_subruns:(n==null?void 0:n.include_subruns)!==!1,messages:Array.isArray(n==null?void 0:n.messages)?n.messages:[],persist:!!(n!=null&&n.persist)},l=typeof(n==null?void 0:n.provider)=="string"?String(n.provider).trim():"";l&&(o.provider=l);const u=typeof(n==null?void 0:n.model)=="string"?String(n.model).trim():"";u&&(o.model=u);const c=await fetch(Lt(this._cfg.base_url,wt(`runs/${encodeURIComponent(s)}/chat`)),{method:"POST",headers:{"Content-Type":"application/json",...Mt(this._cfg.auth_token)},body:JSON.stringify(o)});if(!c.ok)throw await Lh(c,"The gateway could not answer");return await c.json()}async audio_transcribe(t,n){const s=String(t||"").trim();if(!s)throw new Error("audio_transcribe: run_id is required");const o=n==null?void 0:n.audio_artifact;if(!o||typeof o!="object")throw new Error("audio_transcribe: audio_artifact is required");if(!String(o.$artifact||"").trim())throw new Error("audio_transcribe: audio_artifact.$artifact is required");const u={audio_artifact:o},c=String((n==null?void 0:n.language)||"").trim();c&&(u.language=c);const f=String((n==null?void 0:n.request_id)||"").trim();f&&(u.request_id=f);const m=await fetch(Lt(this._cfg.base_url,wt(`runs/${encodeURIComponent(s)}/audio/transcribe`)),{method:"POST",headers:{"Content-Type":"application/json",...Mt(this._cfg.auth_token)},body:JSON.stringify(u)});if(!m.ok)throw new Error(`audio_transcribe failed: ${await Wn(m)}`);const p=await m.json(),g=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:g,transcript_artifact:p==null?void 0:p.transcript_artifact}}async voice_tts(t,n){const s=String(t||"").trim();if(!s)throw new Error("voice_tts: run_id is required");const o=String((n==null?void 0:n.text)||"").trim();if(!o)throw new Error("voice_tts: text is required");const l={text:o},u=String((n==null?void 0:n.voice)||"").trim();u&&(l.voice=u);const c=String((n==null?void 0:n.format)||"").trim();c&&(l.format=c);const f=String((n==null?void 0:n.request_id)||"").trim();f&&(l.request_id=f);const m=await fetch(Lt(this._cfg.base_url,wt(`runs/${encodeURIComponent(s)}/voice/tts`)),{method:"POST",headers:{"Content-Type":"application/json",...Mt(this._cfg.auth_token)},body:JSON.stringify(l)});if(!m.ok)throw new Error(`voice_tts failed: ${await Wn(m)}`);const p=await m.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 s=String(t||"").trim();if(!s)throw new Error("save_chat_thread: run_id is required");const o={include_subruns:(n==null?void 0:n.include_subruns)!==!1,messages:Array.isArray(n==null?void 0:n.messages)?n.messages:[]},l=typeof(n==null?void 0:n.provider)=="string"?String(n.provider).trim():"";l&&(o.provider=l);const u=typeof(n==null?void 0:n.model)=="string"?String(n.model).trim():"";u&&(o.model=u);const c=typeof(n==null?void 0:n.title)=="string"?String(n.title).trim():"";c&&(o.title=c);const f=await fetch(Lt(this._cfg.base_url,wt(`runs/${encodeURIComponent(s)}/chat_threads`)),{method:"POST",headers:{"Content-Type":"application/json",...Mt(this._cfg.auth_token)},body:JSON.stringify(o)});if(!f.ok)throw new Error(`save_chat_thread failed: ${await Wn(f)}`);return await f.json()}async list_bundles(){const t=await fetch(Lt(this._cfg.base_url,wt("bundles")),{headers:{...Mt(this._cfg.auth_token)},signal:ri()});if(!t.ok)throw new Error(`list_bundles failed: ${t.status}`);return await t.json()}async get_gateway_json(t,n){const s=await fetch(Lt(this._cfg.base_url,wt(t)),{headers:{...Mt(this._cfg.auth_token)},signal:n??ri()});if(!s.ok)throw new Error(await Wn(s));return await s.json()}async reload_bundles(){const t=await fetch(Lt(this._cfg.base_url,wt("bundles/reload")),{method:"POST",headers:{...Mt(this._cfg.auth_token)}});if(!t.ok)throw new Error(`reload_bundles failed: ${t.status}`);return await t.json()}async upload_bundle(t,n){const s=(n==null?void 0:n.overwrite)===!0,o=(n==null?void 0:n.reload)!==!1,l=new FormData;l.set("overwrite",s?"true":"false"),l.set("reload",o?"true":"false"),l.set("file",t,t.name||"upload.flow");const u=await fetch(Lt(this._cfg.base_url,wt("bundles/upload")),{method:"POST",headers:{...Mt(this._cfg.auth_token)},body:l});if(!u.ok)throw new Error(`upload_bundle failed: ${await Wn(u)}`);return await u.json()}async attachments_upload(t,n,s){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((s==null?void 0:s.filename)||"").trim()||String((n==null?void 0:n.name)||"").trim()||"upload.bin",u=String((s==null?void 0:s.content_type)||"").trim()||String((n==null?void 0:n.type)||"").trim(),c=new FormData;c.append("session_id",o),c.append("file",n,l),c.append("filename",l),u&&c.append("content_type",u);const f=await fetch(Lt(this._cfg.base_url,wt("attachments/upload")),{method:"POST",headers:{...Mt(this._cfg.auth_token)},body:c});if(!f.ok)throw new Error(`attachments_upload failed: ${await Wn(f)}`);const m=await f.json(),p=m==null?void 0:m.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 s=String(t||"").trim();if(!s)throw new Error("remove_bundle: bundle_id is required");const o=new URLSearchParams,l=String((n==null?void 0:n.bundle_version)||"").trim();l&&o.set("bundle_version",l),o.set("reload",(n==null?void 0:n.reload)===!1?"false":"true");const u=Lt(this._cfg.base_url,wt(`bundles/${encodeURIComponent(s)}?${o.toString()}`)),c=await fetch(u,{method:"DELETE",headers:{...Mt(this._cfg.auth_token)}});if(!c.ok)throw new Error(`remove_bundle failed: ${await Wn(c)}`);return await c.json()}async discovery_tools(){const t=await fetch(Lt(this._cfg.base_url,wt("discovery/tools")),{headers:{...Mt(this._cfg.auth_token)}});if(!t.ok)throw new Error(`discovery_tools failed: ${t.status}`);return await t.json()}async discovery_providers(t){const n=(t==null?void 0:t.include_models)===!0,s=Lt(this._cfg.base_url,wt(`discovery/providers?include_models=${encodeURIComponent(String(n))}`)),o=await fetch(s,{headers:{...Mt(this._cfg.auth_token)}});if(!o.ok)throw new Error(`discovery_providers failed: ${o.status}`);return await o.json()}async discovery_provider_models(t){const n=String(t||"").trim();if(!n)throw new Error("discovery_provider_models: provider_name is required");const s=await fetch(Lt(this._cfg.base_url,wt(`discovery/providers/${encodeURIComponent(n)}/models`)),{headers:{...Mt(this._cfg.auth_token)}});if(!s.ok)throw new Error(`discovery_provider_models failed: ${s.status}`);return await s.json()}async get_bundle(t){const n=String(t||"").trim();if(!n)throw new Error("get_bundle: bundle_id is required");const s=await fetch(Lt(this._cfg.base_url,wt(`bundles/${encodeURIComponent(n)}`)),{headers:{...Mt(this._cfg.auth_token)}});if(!s.ok)throw new Error(`get_bundle failed: ${s.status}`);return await s.json()}async get_bundle_flow(t,n){const s=String(t||"").trim(),o=String(n||"").trim();if(!s)throw new Error("get_bundle_flow: bundle_id is required");if(!o)throw new Error("get_bundle_flow: flow_id is required");const l=await fetch(Lt(this._cfg.base_url,wt(`bundles/${encodeURIComponent(s)}/flows/${encodeURIComponent(o)}`)),{headers:{...Mt(this._cfg.auth_token)}});if(!l.ok)throw new Error(`get_bundle_flow failed: ${l.status}`);return await l.json()}async get_workflow_flow(t){const n=String(t||"").trim();if(!n)throw new Error("get_workflow_flow: workflow_id is required");const s=await fetch(Lt(this._cfg.base_url,wt(`workflows/${encodeURIComponent(n)}/flow`)),{headers:{...Mt(this._cfg.auth_token)}});if(!s.ok)throw new Error(`get_workflow_flow failed: ${s.status}`);return await s.json()}async discovery_capabilities(){const t=await fetch(Lt(this._cfg.base_url,wt("discovery/capabilities")),{headers:{...Mt(this._cfg.auth_token)},signal:ri()});if(!t.ok)throw new Error(`discovery_capabilities failed: ${await Wn(t)}`);return await t.json()}automations_client(){const t=this._cfg.auth_token;return rS({fetch:(n,s)=>fetch(n,s),baseUrl:this._cfg.base_url,headers:()=>Mt(t)})}async submit_command(t){const n=await fetch(Lt(this._cfg.base_url,wt("commands")),{method:"POST",headers:{"Content-Type":"application/json",...Mt(this._cfg.auth_token)},body:JSON.stringify(t)});if(!n.ok)throw new Error(`submit_command failed: ${n.status}`);return await n.json()}async kg_query(t){const n=String((t==null?void 0:t.scope)||"session").trim().toLowerCase(),s=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:s,limit:o},u=String((t==null?void 0:t.run_id)||"").trim();u&&(l.run_id=u);const c=String((t==null?void 0:t.session_id)||"").trim();c&&(l.session_id=c);const f=String((t==null?void 0:t.owner_id)||"").trim();f&&(l.owner_id=f),t!=null&&t.all_owners&&(l.all_owners=!0);const m=String((t==null?void 0:t.subject)||"").trim();m&&(l.subject=m);const p=String((t==null?void 0:t.predicate)||"").trim();p&&(l.predicate=p);const g=String((t==null?void 0:t.object)||"").trim();g&&(l.object=g);const w=String((t==null?void 0:t.since)||"").trim();w&&(l.since=w);const x=String((t==null?void 0:t.until)||"").trim();x&&(l.until=x);const S=String((t==null?void 0:t.active_at)||"").trim();S&&(l.active_at=S);const j=String((t==null?void 0:t.query_text)||"").trim();j&&(l.query_text=j),typeof(t==null?void 0:t.min_score)=="number"&&Number.isFinite(t.min_score)&&(l.min_score=Number(t.min_score));const N=await fetch(Lt(this._cfg.base_url,wt("kg/query")),{method:"POST",headers:{"Content-Type":"application/json",...Mt(this._cfg.auth_token)},body:JSON.stringify(l)});if(!N.ok)throw new Error(`kg_query failed: ${await Wn(N)}`);return await N.json()}async stream_ledger(t,n){var g;const s=Number((n==null?void 0:n.after)||0),o=n.on_step,l=n.signal,u=Lt(this._cfg.base_url,wt(`runs/${encodeURIComponent(t)}/ledger/stream?after=${encodeURIComponent(String(s))}`)),c=await fetch(u,{headers:{Accept:"text/event-stream",...Mt(this._cfg.auth_token)},signal:l});if(!c.ok)throw await Lh(c,"The ledger stream was refused");if(!c.body)throw new Error("stream_ledger: response body is missing");(g=n.on_open)==null||g.call(n);const f=c.body.getReader(),m=new TextDecoder("utf-8"),p=new fE;for(;;){const{value:w,done:x}=await f.read();if(x)return;const S=m.decode(w,{stream:!0});p.push(S,j=>{if(!(j.event!=="step"||!j.data))try{const N=JSON.parse(j.data);N&&typeof N.cursor=="number"&&N.record&&o(N)}catch{}})}}}const Mp=$j("voice and camera")??"Voice and camera are not supported in this browser (getUserMedia unavailable).",mE="Copy failed — select and copy";function Rp(){var t;const e=globalThis.navigator;return typeof((t=e==null?void 0:e.mediaDevices)==null?void 0:t.getUserMedia)=="function"}function _E(e){var o;const t=globalThis.document;if(!t||!t.body||typeof t.execCommand!="function")return!1;const n=t.createElement("textarea");n.value=e,n.setAttribute("readonly",""),n.style.position="fixed",n.style.top="0",n.style.left="-9999px",n.style.opacity="0";const s=t.activeElement;t.body.appendChild(n);try{return n.select(),n.setSelectionRange(0,e.length),t.execCommand("copy")===!0}catch{return!1}finally{t.body.removeChild(n);try{(o=s==null?void 0:s.focus)==null||o.call(s)}catch{}}}async function pE(e){var s;const t=String(e??""),n=globalThis.navigator;if(typeof((s=n==null?void 0:n.clipboard)==null?void 0:s.writeText)=="function")try{return await n.clipboard.writeText(t),!0}catch{}return _E(t)}const gE=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function yE(e){const t=e.length,n=new Uint8Array(t+9+63>>6<<6);n.set(e),n[t]=128;const s=new DataView(n.buffer);s.setUint32(n.length-8,Math.floor(t/536870912),!1),s.setUint32(n.length-4,t<<3>>>0,!1);const o=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),l=new Uint32Array(64),u=(c,f)=>c>>>f|c<<32-f;for(let c=0;c<n.length;c+=64){for(let N=0;N<16;N++)l[N]=s.getUint32(c+N*4,!1);for(let N=16;N<64;N++){const C=u(l[N-15],7)^u(l[N-15],18)^l[N-15]>>>3,E=u(l[N-2],17)^u(l[N-2],19)^l[N-2]>>>10;l[N]=l[N-16]+C+l[N-7]+E>>>0}let[f,m,p,g,w,x,S,j]=[o[0],o[1],o[2],o[3],o[4],o[5],o[6],o[7]];for(let N=0;N<64;N++){const C=u(w,6)^u(w,11)^u(w,25),E=w&x^~w&S,T=j+C+E+gE[N]+l[N]>>>0,I=u(f,2)^u(f,13)^u(f,22),K=f&m^f&p^m&p,U=I+K>>>0;j=S,S=x,x=w,w=g+T>>>0,g=p,p=m,m=f,f=T+U>>>0}o[0]=o[0]+f>>>0,o[1]=o[1]+m>>>0,o[2]=o[2]+p>>>0,o[3]=o[3]+g>>>0,o[4]=o[4]+w>>>0,o[5]=o[5]+x>>>0,o[6]=o[6]+S>>>0,o[7]=o[7]+j>>>0}return Array.from(o,c=>c.toString(16).padStart(8,"0")).join("")}async function wE(e){var s;const t=new TextEncoder().encode(String(e??"")),n=(s=globalThis.crypto)==null?void 0:s.subtle;if(n&&typeof n.digest=="function"){const o=await n.digest("SHA-256",t);return Array.from(new Uint8Array(o),l=>l.toString(16).padStart(2,"0")).join("")}return yE(t)}function vE(e){const t=(e||"").trim();return t?{Authorization:`Bearer ${t}`}:{}}class xE{constructor(t){Vr(this,"_cfg");this._cfg={...t,url:(t.url||"").trim()}}async call_tool(t){const n=String((t==null?void 0:t.name)||"").trim(),s=String((t==null?void 0:t.call_id)||(t==null?void 0:t.id)||xr()),o=t!=null&&t.arguments&&typeof t.arguments=="object"?t.arguments:{};if(!n)return{call_id:s,name:"",success:!1,output:null,error:"Missing tool name"};const l={jsonrpc:"2.0",id:xr(),method:"tools/call",params:{name:n,arguments:o}},u=await fetch(this._cfg.url,{method:"POST",headers:{"Content-Type":"application/json",...vE(this._cfg.auth_token)},body:JSON.stringify(l)});if(!u.ok)return{call_id:s,name:n,success:!1,output:null,error:`Worker HTTP ${u.status}`};const c=await u.json().catch(()=>null),f=c==null?void 0:c.result,m=!!(f!=null&&f.isError),g=(Array.isArray(f==null?void 0:f.content)?f.content:[]).find(x=>x&&x.type==="text"&&typeof x.text=="string"),w=(g==null?void 0:g.text)??"";return m?{call_id:s,name:n,success:!1,output:null,error:w||"Tool failed"}:{call_id:s,name:n,success:!0,output:w,error:null}}}class dw{constructor(t,n){Vr(this,"pending",[]);Vr(this,"scheduled",!1);Vr(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 s=this.pending;this.pending=[],s.length&&this.on_flush(s)})}reset(){this.generation+=1,this.pending=[],this.scheduled=!1}pending_count(){return this.pending.length}}function fw(e,t=""){const n=String(e.role||"").trim(),s=String(e.automation_id||"").trim();return n==="occurrence"&&s&&s!==e.run_id?s:String(e.parent_run_id||t||"").trim()}function bE(e,t){const n=qn(e.updated_at||e.created_at)??0;return(qn(t.updated_at||t.created_at)??0)-n}function jE(e,t){const n=t.query.trim().toLowerCase(),s=[...e],o={};for(const w of s){const x=String(w.run_id||"").trim();x&&(o[x]=w)}for(const w of e){const x=fw(w);if(String(w.role||"")==="occurrence"&&x&&!o[x]){const S={run_id:x,workflow_id:null,status:"",role:"controller",session_kind:"automation",automation_id:x,updated_at:w.updated_at??null,created_at:w.created_at??null};o[x]=S,s.push(S)}}const l={},u={};for(const w of s){const x=String(w.run_id||"").trim();if(!x)continue;const S=fw(w,t.parent_hint?t.parent_hint(x):"");u[x]=S,S&&(l[S]||(l[S]=[])).push(w)}const c=w=>{const x=String(w.status||"").trim().toLowerCase();return t.filter==="all"?!0:t.filter==="active"?ju(x):t.filter==="waiting"?x==="waiting":t.filter==="terminal"?ko(x):t.filter==="failed"?x==="failed":!0},f=w=>{if(!n)return!0;const x=String(w.workflow_id||w.schedule_target_workflow_id||"").trim(),S=x?t.workflow_label_by_id[x]||x:"";return[w.run_id,x,S,w.session_id,w.status,w.session_kind,w.automation_id].join(" ").toLowerCase().includes(n)},m=[];for(const w of s){const x=String(w.run_id||"").trim();if(!x)continue;const S=u[x];(!S||!o[S])&&m.push(x)}const p={},g=w=>{if(t.group_by==="workflow"){const S=String(w.schedule_target_workflow_id||w.workflow_id||"").trim()||"(unknown workflow)";return{key:S,label:t.workflow_label_by_id[S]||S}}if(t.group_by==="session"){const S=String(w.session_id||"").trim()||"(no session)";return{key:S,label:S}}const x=String(w.status||"").trim().toLowerCase()||"unknown";return ju(x)?{key:"active",label:"Active"}:x==="failed"?{key:"failed",label:"Failed"}:ko(x)?{key:"finished",label:"Finished"}:{key:x,label:x}};for(const w of m){const x=o[w];if(!x)continue;const S=[...l[w]||[]].sort(bE),j=S.some(C=>c(C)&&f(C));if(!(c(x)&&f(x))&&!j)continue;const N=g(x);p[N.key]||(p[N.key]={key:N.key,label:N.label,rows:[]}),p[N.key].rows.push({run:x,children:S})}return Object.values(p).sort((w,x)=>{const S={active:0,waiting:1,failed:2,finished:3},j=S[w.key]??10,N=S[x.key]??10;return j!==N?j-N:w.label.localeCompare(x.label)})}const SE={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"},kE=[{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 NE(){const[e,t]=_.useState(!0);return r.jsxs("div",{className:"pin-legend",children:[r.jsxs("button",{className:"pin-legend-toggle mono",type:"button",onClick:()=>t(n=>!n),title:"Pin Type Legend",children:[e?"?":"×"," Pin Types"]}),e?null:r.jsxs("div",{className:"pin-legend-content",children:[kE.map(n=>r.jsxs("div",{className:"pin-legend-row",children:[r.jsx("span",{className:"pin-legend-shape",style:{color:SE[n.type]},children:n.shape}),r.jsx("span",{className:"pin-legend-label mono",children:n.label}),r.jsx("span",{className:"pin-legend-desc mono",children:n.description})]},n.type)),r.jsxs("div",{className:"pin-legend-rules mono",children:[r.jsx("strong",{children:"Connection Rules:"}),r.jsxs("ul",{children:[r.jsx("li",{children:"Execution connects to Execution only"}),r.jsx("li",{children:'"Any" type accepts all data types'}),r.jsx("li",{children:"Same types always compatible"}),r.jsx("li",{children:"Array and Object are interchangeable"}),r.jsx("li",{children:'"Tools" is compatible with Array (specialized string[])'})]})]})]})]})}function dn(e){return typeof e=="string"?e:e==null?"":String(e)}function hw(e,t){const n=dn(e).trim();return n.length<=t?n:`${n.slice(0,Math.max(0,t-1))}…`}function Qx(e){const t=dn(e==null?void 0:e.targetHandle),n=dn(e==null?void 0:e.sourceHandle);return!!(t==="exec-in"||n==="exec-out"||t.includes("exec")||n.includes("exec"))}function eb(e){if(!e||typeof e!="object")return"";const t=e!=null&&e.data&&typeof e.data=="object"?e.data:{};return dn((t==null?void 0:t.nodeType)||(e==null?void 0:e.type)||"").trim()}function tb(e){if(!e||typeof e!="object")return"";const t=e!=null&&e.data&&typeof e.data=="object"?e.data:{},n=(t==null?void 0:t.subflowId)||(t==null?void 0:t.flowId),s=dn(n).trim();if(!s)return"";if(s.includes(":")){const o=s.split(":",2);if(o.length===2&&o[1])return o[1].trim()}return s}function CE(e){const t=dn(e==null?void 0:e.entryNode).trim();if(t)return t;const n=Array.isArray(e==null?void 0:e.nodes)?e.nodes:[];for(const s of n)if(eb(s)==="on_flow_start"){const o=dn(s==null?void 0:s.id).trim();if(o)return o}return""}function D_(e){const t=e!=null&&e.position&&typeof e.position=="object"?e.position:{},n=typeof t.x=="number"?t.x:0,s=typeof t.y=="number"?t.y:0;return{x:n,y:s}}function Gd(e,t){const n=dn(e).trim(),s=dn(t).trim();return s?n?`${n}::${s}`:s:""}function EE(e){const t=e.root&&typeof e.root=="object"?e.root:{};if(!e.expand_subflows)return t;const n=[],s=[],o=new Set,l=(u,c,f,m)=>{if(!u||typeof u!="object"||n.length>=e.max_nodes||s.length>=e.max_edges)return;const p=Array.isArray(u.nodes)?u.nodes:[],g=Array.isArray(u.edges)?u.edges:[];for(const w of p){const x=dn(w==null?void 0:w.id).trim();if(!x)continue;const S=Gd(c,x);if(!S||o.has(S))continue;const j=D_(w),N={...w,id:S,position:{x:j.x+f.x,y:j.y+f.y}};if(n.push(N),o.add(S),n.length>=e.max_nodes)break}for(const w of g){if(!Qx(w))continue;const x=dn(w==null?void 0:w.source).trim(),S=dn(w==null?void 0:w.target).trim();if(!x||!S)continue;const j=Gd(c,x),N=Gd(c,S);if(!j||!N)continue;const C=dn(w==null?void 0:w.id).trim(),E=C?`${j}->${N}::${C}`:`${j}->${N}`;if(s.push({...w,id:E,source:j,target:N}),s.length>=e.max_edges)break}if(!(m>=e.max_depth))for(const w of p){if(n.length>=e.max_nodes||s.length>=e.max_edges)return;if(eb(w)!=="subflow")continue;const x=tb(w);if(!x)continue;const S=e.flow_by_id[x];if(!S||typeof S!="object")continue;const j=Gd(c,dn(w==null?void 0:w.id));if(!j)continue;const N=CE(S);if(!N)continue;const E=(Array.isArray(S.nodes)?S.nodes:[]).find(se=>dn(se==null?void 0:se.id).trim()===N)||null;if(!E)continue;const T=D_(w),I=D_(E),J={x:T.x+f.x+240-I.x,y:T.y+f.y+0-I.y},Y=Gd(j,N);s.push({id:`${j}=>${Y}`,source:j,target:Y,sourceHandle:"exec-out",targetHandle:"exec-in"}),l(S,j,J,m+1)}};return l(t,"",{x:0,y:0},0),{...t,id:dn(t.id),nodes:n,edges:s}}function $E(e){const t=dn(e).trim().toLowerCase();return t?!!(t.startsWith("literal")||t.includes("literal")||t==="concat"||t==="join"||t==="cast"||t==="parse_json"||t==="stringify_json"||t==="break_object"||t==="get_property"||t==="set_property"||t.includes("get_property")||t.includes("set_property")||t==="get_variable"||t==="set_variable"||t.includes("get_variable")||t.includes("set_variable")||t==="json_schema"):!1}function AE(e){const t=e.nodes.filter(l=>e.keep_id(l.id)),n=new Set(t.map(l=>l.id)),s={};for(const l of e.edges)s[l.source]||(s[l.source]=[]),s[l.source].push(l.target);const o=new Map;for(const l of t){const u=new Set,c=(s[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 m=s[f]||[];for(const p of m)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 mw(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 TE(e){const t=typeof e.now_ms=="number"?e.now_ms:Date.now(),n=e.flow,s=dn(e.active_node_id),o=e.recent_nodes||{},l=e.visited_nodes||{},u=e.highlight_path===!0,c=typeof e.vertical_compact=="number"?Math.max(.4,Math.min(1,e.vertical_compact)):.78,{nodes:f,edges:m,bounds:p}=_.useMemo(()=>{const O=EE({root:n||{},flow_by_id:e.flow_by_id||{},expand_subflows:e.expand_subflows===!0,max_depth:3,max_nodes:700,max_edges:900}),F=Array.isArray(O.nodes)?O.nodes:[],G=Array.isArray(O.edges)?O.edges:[];let R=[];for(const Se of F){const Re=dn(Se==null?void 0:Se.id).trim();if(!Re)continue;const ht=Se!=null&&Se.position&&typeof Se.position=="object"?Se.position:{},xe=typeof ht.x=="number"?ht.x:0,Ie=typeof ht.y=="number"?ht.y:0,qe=Se!=null&&Se.data&&typeof Se.data=="object"?Se.data:{},zt=dn((qe==null?void 0:qe.label)||(Se==null?void 0:Se.label)||Re)||Re,en=dn((qe==null?void 0:qe.nodeType)||(Se==null?void 0:Se.type)||"unknown")||"unknown",bn=dn((qe==null?void 0:qe.headerColor)||(Se==null?void 0:Se.headerColor)||"")||"",Wt=qe!=null&&qe.eventConfig&&typeof qe.eventConfig=="object"?qe.eventConfig:null,It=Wt&&typeof Wt.schedule=="string"?dn(Wt.schedule).trim():"",kn=Wt&&typeof Wt.recurrent=="boolean"?!!Wt.recurrent:void 0,nr=en==="subflow"?tb(Se):"",Pt=It||kn!==void 0||nr?{schedule:It||void 0,recurrent:kn,subflow_id:nr||void 0}:void 0;R.push({id:Re,x:xe,y:Ie,label:zt,type:en,color:bn,meta:Pt})}const Z={};for(const Se of R)Z[Se.id]=Se;let X=[];for(const Se of G){if(!Qx(Se))continue;const Re=dn(Se==null?void 0:Se.source).trim(),ht=dn(Se==null?void 0:Se.target).trim();!Re||!ht||X.push({id:dn((Se==null?void 0:Se.id)||`${Re}->${ht}`),source:Re,target:ht})}const Q=new Set(R.map(Se=>Se.id));if(X=X.filter(Se=>Q.has(Se.source)&&Q.has(Se.target)),e.simplify===!0){const Re=AE({nodes:R,edges:X,keep_id:ht=>{if(s&&ht===s)return!0;const xe=Z[ht];if(!xe)return!1;const Ie=dn(xe.type).trim().toLowerCase();return Ie==="on_flow_start"||Ie==="on_flow_end"||Ie==="subflow"?!0:!$E(Ie)},max_edges:900});R=Re.nodes,X=Re.edges}if(e.prefer_vertical===!0&&R.length>=2){const Se=R.map(qe=>qe.x),Re=R.map(qe=>qe.y),ht=Math.max(...Se)-Math.min(...Se),xe=Math.max(...Re)-Math.min(...Re);ht>=xe&&(R=R.map(qe=>({...qe,x:qe.y,y:qe.x})));const Ie=Math.min(...R.map(qe=>qe.y));R=R.map(qe=>({...qe,y:Ie+(qe.y-Ie)*c}))}const le={};for(const Se of R)le[Se.id]=Se;const ge=160,pe=56,ye=ge/2,Ne=pe/2;let Ue=0,We=0,pt=0,Fe=0;R.length&&(Ue=Math.min(...R.map(Se=>Se.x)),We=Math.min(...R.map(Se=>Se.y)),pt=Math.max(...R.map(Se=>Se.x+ge)),Fe=Math.max(...R.map(Se=>Se.y+pe)));let tt=0;if(X.length){const Se=new Set(X.map(Re=>`${Re.source}->${Re.target}`));for(const Re of X){if(!Se.has(`${Re.target}->${Re.source}`))continue;const ht=le[Re.source],xe=le[Re.target];if(!ht||!xe)continue;const Ie=ht.x+ye,qe=ht.y+Ne,zt=xe.x+ye,en=xe.y+Ne,bn=Math.max(1,Math.hypot(zt-Ie,en-qe)),Wt=Math.max(28,Math.min(72,bn*.14)),It=Math.min(200,Wt*3.5);It>tt&&(tt=It)}}const lt=60+tt,Ke={x:Ue-lt,y:We-lt,w:pt-Ue+lt*2,h:Fe-We+lt*2,node_w:ge,node_h:pe};return{nodes:R,edges:X,bounds:Ke}},[n,e.flow_by_id,e.expand_subflows,e.simplify,e.prefer_vertical,s,c]);if(!n)return r.jsx("div",{className:"graph_empty mono",children:"(no graph loaded)"});const g=_.useRef(null),[w,x]=_.useState(()=>({x:p.x,y:p.y,w:p.w,h:p.h})),S=_.useRef(w);S.current=w,_.useEffect(()=>{x({x:p.x,y:p.y,w:p.w,h:p.h})},[p.x,p.y,p.w,p.h]);const j=_.useRef(new Map),N=_.useRef(null),C=`${w.x} ${w.y} ${w.w} ${w.h}`,E={};for(const O of f)E[O.id]=O;const T=O=>{let F=dn(O).trim();if(!F)return"";if(E[F])return F;for(;F.includes("::");)if(F=F.slice(0,Math.max(0,F.lastIndexOf("::"))),E[F])return F;return""},I=T(s),K={};for(const[O,F]of Object.entries(o)){if(typeof F!="number")continue;const G=T(O);G&&(K[G]=Math.max(K[G]||0,F))}const U={};if(u)for(const[O,F]of Object.entries(l)){if(typeof F!="number")continue;const G=T(O);G&&(U[G]=typeof U[G]=="number"?Math.min(U[G],F):F)}const J=dn(e.schedule_next_in).trim(),Y=dn(e.schedule_interval).trim(),se=e.node_last_ms&&typeof e.node_last_ms=="object"?e.node_last_ms:{},ce=O=>{try{const F=new Date(O),G=String(F.getHours()).padStart(2,"0"),R=String(F.getMinutes()).padStart(2,"0");return`${G}:${R}`}catch{return""}},fe=(O,F)=>{var X,Q;const G=dn((X=O.meta)==null?void 0:X.schedule).trim();if(!(((Q=O.meta)==null?void 0:Q.recurrent)===!0))return F&&J?`next ${J}`:G&&G.length<=12&&!G.includes("T")?`in ${G}`:"scheduled";const Z=G||Y;return Z?F&&J?`${Z} • next ${J}`:`every ${Z}`:F&&J?`next ${J}`:"scheduled"},W=O=>{var ge;const F=dn((ge=O.meta)==null?void 0:ge.subflow_id).trim(),G=F&&e.flow_by_id?e.flow_by_id[F]:null,Z=dn(G==null?void 0:G.name).trim()||F||O.label||O.id,X=typeof se[O.id]=="number"?Number(se[O.id]):null,Q=X!==null?ce(X):"",le=Q?`last ${Q}`:"subflow";return{label:Z,sub:le}},P=(O,F,G)=>{const R=G||S.current,Z=g.current;if(!Z)return{x:O,y:F};const X=Z.getBoundingClientRect(),Q=X.width>0?(O-X.left)/X.width:0,le=X.height>0?(F-X.top)/X.height:0;return{x:R.x+Q*R.w,y:R.y+le*R.h}},A=(O,F,G)=>{const R=G||S.current,Z=Math.max(.12,Math.min(8,F)),X=R.w*Z,Q=R.h*Z,le=R.w>0?(O.x-R.x)/R.w:.5,ge=R.h>0?(O.y-R.y)/R.h:.5,pe=O.x-le*X,ye=O.y-ge*Q;x(mw({x:pe,y:ye,w:X,h:Q},p))},z=(O,F,G)=>{const R=G||S.current,Z=g.current;if(!Z)return;const X=Z.getBoundingClientRect(),Q=.88,le=X.width>0?O/X.width*R.w*Q:0,ge=X.height>0?F/X.height*R.h*Q:0;x(pe=>mw({x:(G||pe).x-le,y:(G||pe).y-ge,w:(G||pe).w,h:(G||pe).h},p))},$=_.useMemo(()=>{const O=new Set;for(const F of m)O.add(`${F.source}->${F.target}`);return O},[m]),te=(O,F,G,R)=>{const Z=p.node_w,X=p.node_h,Q=Math.abs(G),le=Math.abs(R);if(Q<1e-6&&le<1e-6)return{x:O,y:F};const ge=Q>1e-6?Z/2/Q:Number.POSITIVE_INFINITY,pe=le>1e-6?X/2/le:Number.POSITIVE_INFINITY,ye=Math.min(ge,pe);return{x:O+G*ye,y:F+R*ye}};return r.jsxs("div",{className:"graph_wrap",children:[r.jsxs("div",{className:"graph_corner",children:[r.jsxs("div",{className:"graph_corner_buttons",children:[r.jsx("button",{className:"btn graph_corner_btn",type:"button",onClick:()=>x({x:p.x,y:p.y,w:p.w,h:p.h}),title:"Recenter",children:"⤢"}),r.jsx("button",{className:"btn graph_corner_btn",type:"button",onClick:()=>{const O=g.current;if(!O)return;const F=O.getBoundingClientRect(),G=P(F.left+F.width/2,F.top+F.height/2);A(G,.84)},title:"Zoom in",children:"+"}),r.jsx("button",{className:"btn graph_corner_btn",type:"button",onClick:()=>{const O=g.current;if(!O)return;const F=O.getBoundingClientRect(),G=P(F.left+F.width/2,F.top+F.height/2);A(G,1.18)},title:"Zoom out",children:"−"})]}),r.jsx(NE,{})]}),r.jsxs("svg",{ref:g,className:"graph_svg",viewBox:C,role:"img","aria-label":"Workflow execution graph",onWheel:O=>{O.preventDefault();const F=P(O.clientX,O.clientY),G=typeof O.deltaY=="number"?O.deltaY:0,R=typeof O.deltaMode=="number"?Number(O.deltaMode):0,Z=R===1?G*24:R===2?G*800:G,X=45e-5*1.15*1.1;let Q=Math.exp(Z*X);Q=Math.max(.86,Math.min(1.16,Q)),A(F,Q)},onPointerDown:O=>{var G,R;(R=(G=O.currentTarget).setPointerCapture)==null||R.call(G,O.pointerId),j.current.set(O.pointerId,{x:O.clientX,y:O.clientY});const F=Array.from(j.current.values());if(F.length===1)N.current={mode:"pan",start_view:S.current,start_client:{x:O.clientX,y:O.clientY},start_dist:0,anchor_svg:{x:0,y:0}};else if(F.length>=2){const Z=F[0],X=F[1],Q=Z.x-X.x,le=Z.y-X.y,ge=Math.max(1,Math.hypot(Q,le)),pe={x:(Z.x+X.x)/2,y:(Z.y+X.y)/2},ye=S.current;N.current={mode:"pinch",start_view:ye,start_client:pe,start_dist:ge,anchor_svg:P(pe.x,pe.y,ye)}}},onPointerMove:O=>{if(!j.current.has(O.pointerId))return;j.current.set(O.pointerId,{x:O.clientX,y:O.clientY});const F=N.current;if(!F)return;const G=Array.from(j.current.values());if(F.mode==="pan"&&G.length===1){const R=O.clientX-F.start_client.x,Z=O.clientY-F.start_client.y;z(R,Z,F.start_view)}else if(F.mode==="pinch"&&G.length>=2){const R=G[0],Z=G[1],X=R.x-Z.x,Q=R.y-Z.y,le=Math.max(1,Math.hypot(X,Q)),ge=F.start_dist/le;A(F.anchor_svg,ge,F.start_view)}},onPointerUp:O=>{j.current.delete(O.pointerId),j.current.size===0&&(N.current=null)},onPointerCancel:O=>{j.current.delete(O.pointerId),j.current.size===0&&(N.current=null)},children:[r.jsxs("defs",{children:[r.jsx("marker",{id:"arrow",viewBox:"0 0 10 10",refX:"9",refY:"5",markerWidth:"8",markerHeight:"8",orient:"auto-start-reverse",children:r.jsx("path",{d:"M 0 0 L 10 5 L 0 10 z",fill:"rgba(148,163,184,0.55)"})}),r.jsxs("filter",{id:"glow",children:[r.jsx("feGaussianBlur",{stdDeviation:"3",result:"coloredBlur"}),r.jsxs("feMerge",{children:[r.jsx("feMergeNode",{in:"coloredBlur"}),r.jsx("feMergeNode",{in:"SourceGraphic"})]})]})]}),m.map(O=>{const F=E[O.source],G=E[O.target];if(!F||!G)return null;const R=F.x+p.node_w/2,Z=F.y+p.node_h/2,X=G.x+p.node_w/2,Q=G.y+p.node_h/2,le=X-R,ge=Q-Z,pe=te(R,Z,le,ge),ye=te(X,Q,-le,-ge),Ne=O.source!==O.target&&$.has(`${O.target}->${O.source}`),Ue=Math.max(1,Math.hypot(le,ge)),We=-ge/Ue,pt=le/Ue,Fe=String(O.source)<String(O.target)?1:-1,lt=Math.abs(le)>=Math.abs(ge)?le>=0:ge>=0,Ke=!Ne||lt,Se=Math.max(28,Math.min(72,Ue*.14)),Re=Math.min(200,Se*3.5),ht=Ne&&!Ke?Re*Fe:0,xe=(pe.x+ye.x)/2+We*ht,Ie=(pe.y+ye.y)/2+pt*ht,qe=Ne&&!Ke?`M ${pe.x} ${pe.y} Q ${xe} ${Ie} ${ye.x} ${ye.y}`:`M ${pe.x} ${pe.y} L ${ye.x} ${ye.y}`,zt=u&&U&&U[O.source]!==void 0&&U[O.target]!==void 0;return r.jsx("path",{d:qe,className:`graph_edge ${zt?"visited":""}`,markerEnd:"url(#arrow)",fill:"none"},O.id)}),f.map(O=>{const G=(typeof K[O.id]=="number"?K[O.id]:0)>t,R=I&&O.id===I,Z=u&&U&&U[O.id]!==void 0,X=`graph_node ${R?"active":G?"recent":""} ${Z?"visited":""}`,Q=O.color||"rgba(255,255,255,0.16)";let le=O.label||O.id,ge=O.type;if(O.type==="on_schedule")ge=fe(O,!!R);else if(O.type==="subflow"){const Ne=W(O);le=Ne.label,ge=Ne.sub}const pe=hw(le,22),ye=hw(ge,22);return r.jsxs("g",{className:X,transform:`translate(${O.x}, ${O.y})`,children:[r.jsx("rect",{className:"graph_node_bg",width:p.node_w,height:p.node_h,rx:12,ry:12}),r.jsx("rect",{className:"graph_node_bar",width:p.node_w,height:6,rx:12,ry:12,fill:Q}),r.jsx("text",{className:"graph_node_label",x:12,y:28,children:pe}),r.jsx("text",{className:"graph_node_type",x:12,y:46,children:ye}),O.type==="on_schedule"?r.jsx("text",{className:"graph_node_icon",x:p.node_w-18,y:18,children:"⏰"}):null]},O.id)})]})]})}function Kr(e){if(typeof e=="string"||typeof e=="number")return""+e;let t="";if(Array.isArray(e))for(let n=0,s;n<e.length;n++)(s=Kr(e[n]))!==""&&(t+=(t&&" ")+s);else for(let n in e)e[n]&&(t+=(t&&" ")+n);return t}var F_={exports:{}},z_={},B_={exports:{}},U_={};/**
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 _w;function ME(){if(_w)return U_;_w=1;var e=kf();function t(g,w){return g===w&&(g!==0||1/g===1/w)||g!==g&&w!==w}var n=typeof Object.is=="function"?Object.is:t,s=e.useState,o=e.useEffect,l=e.useLayoutEffect,u=e.useDebugValue;function c(g,w){var x=w(),S=s({inst:{value:x,getSnapshot:w}}),j=S[0].inst,N=S[1];return l(function(){j.value=x,j.getSnapshot=w,f(j)&&N({inst:j})},[g,x,w]),o(function(){return f(j)&&N({inst:j}),g(function(){f(j)&&N({inst:j})})},[g]),u(x),x}function f(g){var w=g.getSnapshot;g=g.value;try{var x=w();return!n(g,x)}catch{return!0}}function m(g,w){return w()}var p=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?m:c;return U_.useSyncExternalStore=e.useSyncExternalStore!==void 0?e.useSyncExternalStore:p,U_}var pw;function RE(){return pw||(pw=1,B_.exports=ME()),B_.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 gw;function LE(){if(gw)return z_;gw=1;var e=kf(),t=RE();function n(m,p){return m===p&&(m!==0||1/m===1/p)||m!==m&&p!==p}var s=typeof Object.is=="function"?Object.is:n,o=t.useSyncExternalStore,l=e.useRef,u=e.useEffect,c=e.useMemo,f=e.useDebugValue;return z_.useSyncExternalStoreWithSelector=function(m,p,g,w,x){var S=l(null);if(S.current===null){var j={hasValue:!1,value:null};S.current=j}else j=S.current;S=c(function(){function C(U){if(!E){if(E=!0,T=U,U=w(U),x!==void 0&&j.hasValue){var J=j.value;if(x(J,U))return I=J}return I=U}if(J=I,s(T,U))return J;var Y=w(U);return x!==void 0&&x(J,Y)?(T=U,J):(T=U,I=Y)}var E=!1,T,I,K=g===void 0?null:g;return[function(){return C(p())},K===null?void 0:function(){return C(K())}]},[p,g,w,x]);var N=o(m,S[0],S[1]);return u(function(){j.hasValue=!0,j.value=N},[N]),f(N),N},z_}var yw;function IE(){return yw||(yw=1,F_.exports=LE()),F_.exports}var PE=IE();const OE=ng(PE),DE={},ww=e=>{let t;const n=new Set,s=(p,g)=>{const w=typeof p=="function"?p(t):p;if(!Object.is(w,t)){const x=t;t=g??(typeof w!="object"||w===null)?w:Object.assign({},t,w),n.forEach(S=>S(t,x))}},o=()=>t,f={setState:s,getState:o,getInitialState:()=>m,subscribe:p=>(n.add(p),()=>n.delete(p)),destroy:()=>{(DE?"production":void 0)!=="production"&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),n.clear()}},m=t=e(s,o,f);return f},FE=e=>e?ww(e):ww,{useDebugValue:zE}=ve,{useSyncExternalStoreWithSelector:BE}=OE,UE=e=>e;function nb(e,t=UE,n){const s=BE(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return zE(s),s}const vw=(e,t)=>{const n=FE(e),s=(o,l=t)=>nb(n,o,l);return Object.assign(s,n),s},WE=(e,t)=>e?vw(e,t):vw;function Pr(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[s,o]of e)if(!Object.is(o,t.get(s)))return!1;return!0}if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(const s of e)if(!t.has(s))return!1;return!0}const n=Object.keys(e);if(n.length!==Object.keys(t).length)return!1;for(const s of n)if(!Object.prototype.hasOwnProperty.call(t,s)||!Object.is(e[s],t[s]))return!1;return!0}var qE={value:()=>{}};function Tm(){for(var e=0,t=arguments.length,n={},s;e<t;++e){if(!(s=arguments[e]+"")||s in n||/[\s.]/.test(s))throw new Error("illegal type: "+s);n[s]=[]}return new Zh(n)}function Zh(e){this._=e}function HE(e,t){return e.trim().split(/^|\s+/).map(function(n){var s="",o=n.indexOf(".");if(o>=0&&(s=n.slice(o+1),n=n.slice(0,o)),n&&!t.hasOwnProperty(n))throw new Error("unknown type: "+n);return{type:n,name:s}})}Zh.prototype=Tm.prototype={constructor:Zh,on:function(e,t){var n=this._,s=HE(e+"",n),o,l=-1,u=s.length;if(arguments.length<2){for(;++l<u;)if((o=(e=s[l]).type)&&(o=VE(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=s[l]).type)n[o]=xw(n[o],e.name,t);else if(t==null)for(o in n)n[o]=xw(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 Zh(e)},call:function(e,t){if((o=arguments.length-2)>0)for(var n=new Array(o),s=0,o,l;s<o;++s)n[s]=arguments[s+2];if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(l=this._[e],s=0,o=l.length;s<o;++s)l[s].value.apply(t,n)},apply:function(e,t,n){if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(var s=this._[e],o=0,l=s.length;o<l;++o)s[o].value.apply(t,n)}};function VE(e,t){for(var n=0,s=e.length,o;n<s;++n)if((o=e[n]).name===t)return o.value}function xw(e,t,n){for(var s=0,o=e.length;s<o;++s)if(e[s].name===t){e[s]=qE,e=e.slice(0,s).concat(e.slice(s+1));break}return n!=null&&e.push({name:t,value:n}),e}var Lp="http://www.w3.org/1999/xhtml";const bw={svg:"http://www.w3.org/2000/svg",xhtml:Lp,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function Mm(e){var t=e+="",n=t.indexOf(":");return n>=0&&(t=e.slice(0,n))!=="xmlns"&&(e=e.slice(n+1)),bw.hasOwnProperty(t)?{space:bw[t],local:e}:e}function GE(e){return function(){var t=this.ownerDocument,n=this.namespaceURI;return n===Lp&&t.documentElement.namespaceURI===Lp?t.createElement(e):t.createElementNS(n,e)}}function KE(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function rb(e){var t=Mm(e);return(t.local?KE:GE)(t)}function YE(){}function Sg(e){return e==null?YE:function(){return this.querySelector(e)}}function JE(e){typeof e!="function"&&(e=Sg(e));for(var t=this._groups,n=t.length,s=new Array(n),o=0;o<n;++o)for(var l=t[o],u=l.length,c=s[o]=new Array(u),f,m,p=0;p<u;++p)(f=l[p])&&(m=e.call(f,f.__data__,p,l))&&("__data__"in f&&(m.__data__=f.__data__),c[p]=m);return new si(s,this._parents)}function XE(e){return e==null?[]:Array.isArray(e)?e:Array.from(e)}function ZE(){return[]}function sb(e){return e==null?ZE:function(){return this.querySelectorAll(e)}}function QE(e){return function(){return XE(e.apply(this,arguments))}}function e$(e){typeof e=="function"?e=QE(e):e=sb(e);for(var t=this._groups,n=t.length,s=[],o=[],l=0;l<n;++l)for(var u=t[l],c=u.length,f,m=0;m<c;++m)(f=u[m])&&(s.push(e.call(f,f.__data__,m,u)),o.push(f));return new si(s,o)}function ib(e){return function(){return this.matches(e)}}function ob(e){return function(t){return t.matches(e)}}var t$=Array.prototype.find;function n$(e){return function(){return t$.call(this.children,e)}}function r$(){return this.firstElementChild}function s$(e){return this.select(e==null?r$:n$(typeof e=="function"?e:ob(e)))}var i$=Array.prototype.filter;function o$(){return Array.from(this.children)}function a$(e){return function(){return i$.call(this.children,e)}}function l$(e){return this.selectAll(e==null?o$:a$(typeof e=="function"?e:ob(e)))}function c$(e){typeof e!="function"&&(e=ib(e));for(var t=this._groups,n=t.length,s=new Array(n),o=0;o<n;++o)for(var l=t[o],u=l.length,c=s[o]=[],f,m=0;m<u;++m)(f=l[m])&&e.call(f,f.__data__,m,l)&&c.push(f);return new si(s,this._parents)}function ab(e){return new Array(e.length)}function u$(){return new si(this._enter||this._groups.map(ab),this._parents)}function hm(e,t){this.ownerDocument=e.ownerDocument,this.namespaceURI=e.namespaceURI,this._next=null,this._parent=e,this.__data__=t}hm.prototype={constructor:hm,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 d$(e){return function(){return e}}function f$(e,t,n,s,o,l){for(var u=0,c,f=t.length,m=l.length;u<m;++u)(c=t[u])?(c.__data__=l[u],s[u]=c):n[u]=new hm(e,l[u]);for(;u<f;++u)(c=t[u])&&(o[u]=c)}function h$(e,t,n,s,o,l,u){var c,f,m=new Map,p=t.length,g=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)+"",m.has(x)?o[c]=f:m.set(x,f));for(c=0;c<g;++c)x=u.call(e,l[c],c,l)+"",(f=m.get(x))?(s[c]=f,f.__data__=l[c],m.delete(x)):n[c]=new hm(e,l[c]);for(c=0;c<p;++c)(f=t[c])&&m.get(w[c])===f&&(o[c]=f)}function m$(e){return e.__data__}function _$(e,t){if(!arguments.length)return Array.from(this,m$);var n=t?h$:f$,s=this._parents,o=this._groups;typeof e!="function"&&(e=d$(e));for(var l=o.length,u=new Array(l),c=new Array(l),f=new Array(l),m=0;m<l;++m){var p=s[m],g=o[m],w=g.length,x=p$(e.call(p,p&&p.__data__,m,s)),S=x.length,j=c[m]=new Array(S),N=u[m]=new Array(S),C=f[m]=new Array(w);n(p,g,j,N,C,x,t);for(var E=0,T=0,I,K;E<S;++E)if(I=j[E]){for(E>=T&&(T=E+1);!(K=N[T])&&++T<S;);I._next=K||null}}return u=new si(u,s),u._enter=c,u._exit=f,u}function p$(e){return typeof e=="object"&&"length"in e?e:Array.from(e)}function g$(){return new si(this._exit||this._groups.map(ab),this._parents)}function y$(e,t,n){var s=this.enter(),o=this,l=this.exit();return typeof e=="function"?(s=e(s),s&&(s=s.selection())):s=s.append(e+""),t!=null&&(o=t(o),o&&(o=o.selection())),n==null?l.remove():n(l),s&&o?s.merge(o).order():o}function w$(e){for(var t=e.selection?e.selection():e,n=this._groups,s=t._groups,o=n.length,l=s.length,u=Math.min(o,l),c=new Array(o),f=0;f<u;++f)for(var m=n[f],p=s[f],g=m.length,w=c[f]=new Array(g),x,S=0;S<g;++S)(x=m[S]||p[S])&&(w[S]=x);for(;f<o;++f)c[f]=n[f];return new si(c,this._parents)}function v$(){for(var e=this._groups,t=-1,n=e.length;++t<n;)for(var s=e[t],o=s.length-1,l=s[o],u;--o>=0;)(u=s[o])&&(l&&u.compareDocumentPosition(l)^4&&l.parentNode.insertBefore(u,l),l=u);return this}function x$(e){e||(e=b$);function t(g,w){return g&&w?e(g.__data__,w.__data__):!g-!w}for(var n=this._groups,s=n.length,o=new Array(s),l=0;l<s;++l){for(var u=n[l],c=u.length,f=o[l]=new Array(c),m,p=0;p<c;++p)(m=u[p])&&(f[p]=m);f.sort(t)}return new si(o,this._parents).order()}function b$(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}function j$(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this}function S$(){return Array.from(this)}function k$(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var s=e[t],o=0,l=s.length;o<l;++o){var u=s[o];if(u)return u}return null}function N$(){let e=0;for(const t of this)++e;return e}function C$(){return!this.node()}function E$(e){for(var t=this._groups,n=0,s=t.length;n<s;++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 $$(e){return function(){this.removeAttribute(e)}}function A$(e){return function(){this.removeAttributeNS(e.space,e.local)}}function T$(e,t){return function(){this.setAttribute(e,t)}}function M$(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function R$(e,t){return function(){var n=t.apply(this,arguments);n==null?this.removeAttribute(e):this.setAttribute(e,n)}}function L$(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 I$(e,t){var n=Mm(e);if(arguments.length<2){var s=this.node();return n.local?s.getAttributeNS(n.space,n.local):s.getAttribute(n)}return this.each((t==null?n.local?A$:$$:typeof t=="function"?n.local?L$:R$:n.local?M$:T$)(n,t))}function lb(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function P$(e){return function(){this.style.removeProperty(e)}}function O$(e,t,n){return function(){this.style.setProperty(e,t,n)}}function D$(e,t,n){return function(){var s=t.apply(this,arguments);s==null?this.style.removeProperty(e):this.style.setProperty(e,s,n)}}function F$(e,t,n){return arguments.length>1?this.each((t==null?P$:typeof t=="function"?D$:O$)(e,t,n??"")):Nu(this.node(),e)}function Nu(e,t){return e.style.getPropertyValue(t)||lb(e).getComputedStyle(e,null).getPropertyValue(t)}function z$(e){return function(){delete this[e]}}function B$(e,t){return function(){this[e]=t}}function U$(e,t){return function(){var n=t.apply(this,arguments);n==null?delete this[e]:this[e]=n}}function W$(e,t){return arguments.length>1?this.each((t==null?z$:typeof t=="function"?U$:B$)(e,t)):this.node()[e]}function cb(e){return e.trim().split(/^|\s+/)}function kg(e){return e.classList||new ub(e)}function ub(e){this._node=e,this._names=cb(e.getAttribute("class")||"")}ub.prototype={add:function(e){var t=this._names.indexOf(e);t<0&&(this._names.push(e),this._node.setAttribute("class",this._names.join(" ")))},remove:function(e){var t=this._names.indexOf(e);t>=0&&(this._names.splice(t,1),this._node.setAttribute("class",this._names.join(" ")))},contains:function(e){return this._names.indexOf(e)>=0}};function db(e,t){for(var n=kg(e),s=-1,o=t.length;++s<o;)n.add(t[s])}function fb(e,t){for(var n=kg(e),s=-1,o=t.length;++s<o;)n.remove(t[s])}function q$(e){return function(){db(this,e)}}function H$(e){return function(){fb(this,e)}}function V$(e,t){return function(){(t.apply(this,arguments)?db:fb)(this,e)}}function G$(e,t){var n=cb(e+"");if(arguments.length<2){for(var s=kg(this.node()),o=-1,l=n.length;++o<l;)if(!s.contains(n[o]))return!1;return!0}return this.each((typeof t=="function"?V$:t?q$:H$)(n,t))}function K$(){this.textContent=""}function Y$(e){return function(){this.textContent=e}}function J$(e){return function(){var t=e.apply(this,arguments);this.textContent=t??""}}function X$(e){return arguments.length?this.each(e==null?K$:(typeof e=="function"?J$:Y$)(e)):this.node().textContent}function Z$(){this.innerHTML=""}function Q$(e){return function(){this.innerHTML=e}}function eA(e){return function(){var t=e.apply(this,arguments);this.innerHTML=t??""}}function tA(e){return arguments.length?this.each(e==null?Z$:(typeof e=="function"?eA:Q$)(e)):this.node().innerHTML}function nA(){this.nextSibling&&this.parentNode.appendChild(this)}function rA(){return this.each(nA)}function sA(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function iA(){return this.each(sA)}function oA(e){var t=typeof e=="function"?e:rb(e);return this.select(function(){return this.appendChild(t.apply(this,arguments))})}function aA(){return null}function lA(e,t){var n=typeof e=="function"?e:rb(e),s=t==null?aA:typeof t=="function"?t:Sg(t);return this.select(function(){return this.insertBefore(n.apply(this,arguments),s.apply(this,arguments)||null)})}function cA(){var e=this.parentNode;e&&e.removeChild(this)}function uA(){return this.each(cA)}function dA(){var e=this.cloneNode(!1),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function fA(){var e=this.cloneNode(!0),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function hA(e){return this.select(e?fA:dA)}function mA(e){return arguments.length?this.property("__data__",e):this.node().__data__}function _A(e){return function(t){e.call(this,t,this.__data__)}}function pA(e){return e.trim().split(/^|\s+/).map(function(t){var n="",s=t.indexOf(".");return s>=0&&(n=t.slice(s+1),t=t.slice(0,s)),{type:t,name:n}})}function gA(e){return function(){var t=this.__on;if(t){for(var n=0,s=-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[++s]=l;++s?t.length=s:delete this.__on}}}function yA(e,t,n){return function(){var s=this.__on,o,l=_A(t);if(s){for(var u=0,c=s.length;u<c;++u)if((o=s[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},s?s.push(o):this.__on=[o]}}function wA(e,t,n){var s=pA(e+""),o,l=s.length,u;if(arguments.length<2){var c=this.node().__on;if(c){for(var f=0,m=c.length,p;f<m;++f)for(o=0,p=c[f];o<l;++o)if((u=s[o]).type===p.type&&u.name===p.name)return p.value}return}for(c=t?yA:gA,o=0;o<l;++o)this.each(c(s[o],t,n));return this}function hb(e,t,n){var s=lb(e),o=s.CustomEvent;typeof o=="function"?o=new o(t,n):(o=s.document.createEvent("Event"),n?(o.initEvent(t,n.bubbles,n.cancelable),o.detail=n.detail):o.initEvent(t,!1,!1)),e.dispatchEvent(o)}function vA(e,t){return function(){return hb(this,e,t)}}function xA(e,t){return function(){return hb(this,e,t.apply(this,arguments))}}function bA(e,t){return this.each((typeof t=="function"?xA:vA)(e,t))}function*jA(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var s=e[t],o=0,l=s.length,u;o<l;++o)(u=s[o])&&(yield u)}var mb=[null];function si(e,t){this._groups=e,this._parents=t}function Af(){return new si([[document.documentElement]],mb)}function SA(){return this}si.prototype=Af.prototype={constructor:si,select:JE,selectAll:e$,selectChild:s$,selectChildren:l$,filter:c$,data:_$,enter:u$,exit:g$,join:y$,merge:w$,selection:SA,order:v$,sort:x$,call:j$,nodes:S$,node:k$,size:N$,empty:C$,each:E$,attr:I$,style:F$,property:W$,classed:G$,text:X$,html:tA,raise:rA,lower:iA,append:oA,insert:lA,remove:uA,clone:hA,datum:mA,on:wA,dispatch:bA,[Symbol.iterator]:jA};function ji(e){return typeof e=="string"?new si([[document.querySelector(e)]],[document.documentElement]):new si([[e]],mb)}function kA(e){let t;for(;t=e.sourceEvent;)e=t;return e}function Fi(e,t){if(e=kA(e),t===void 0&&(t=e.currentTarget),t){var n=t.ownerSVGElement||t;if(n.createSVGPoint){var s=n.createSVGPoint();return s.x=e.clientX,s.y=e.clientY,s=s.matrixTransform(t.getScreenCTM().inverse()),[s.x,s.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 NA={passive:!1},mf={capture:!0,passive:!1};function W_(e){e.stopImmediatePropagation()}function yu(e){e.preventDefault(),e.stopImmediatePropagation()}function _b(e){var t=e.document.documentElement,n=ji(e).on("dragstart.drag",yu,mf);"onselectstart"in t?n.on("selectstart.drag",yu,mf):(t.__noselect=t.style.MozUserSelect,t.style.MozUserSelect="none")}function pb(e,t){var n=e.document.documentElement,s=ji(e).on("dragstart.drag",null);t&&(s.on("click.drag",yu,mf),setTimeout(function(){s.on("click.drag",null)},0)),"onselectstart"in n?s.on("selectstart.drag",null):(n.style.MozUserSelect=n.__noselect,delete n.__noselect)}const Ih=e=>()=>e;function Ip(e,{sourceEvent:t,subject:n,target:s,identifier:o,active:l,x:u,y:c,dx:f,dy:m,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:s,enumerable:!0,configurable:!0},identifier:{value:o,enumerable:!0,configurable:!0},active:{value:l,enumerable:!0,configurable:!0},x:{value:u,enumerable:!0,configurable:!0},y:{value:c,enumerable:!0,configurable:!0},dx:{value:f,enumerable:!0,configurable:!0},dy:{value:m,enumerable:!0,configurable:!0},_:{value:p}})}Ip.prototype.on=function(){var e=this._.on.apply(this._,arguments);return e===this._?this:e};function CA(e){return!e.ctrlKey&&!e.button}function EA(){return this.parentNode}function $A(e,t){return t??{x:e.x,y:e.y}}function AA(){return navigator.maxTouchPoints||"ontouchstart"in this}function TA(){var e=CA,t=EA,n=$A,s=AA,o={},l=Tm("start","drag","end"),u=0,c,f,m,p,g=0;function w(I){I.on("mousedown.drag",x).filter(s).on("touchstart.drag",N).on("touchmove.drag",C,NA).on("touchend.drag touchcancel.drag",E).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function x(I,K){if(!(p||!e.call(this,I,K))){var U=T(this,t.call(this,I,K),I,K,"mouse");U&&(ji(I.view).on("mousemove.drag",S,mf).on("mouseup.drag",j,mf),_b(I.view),W_(I),m=!1,c=I.clientX,f=I.clientY,U("start",I))}}function S(I){if(yu(I),!m){var K=I.clientX-c,U=I.clientY-f;m=K*K+U*U>g}o.mouse("drag",I)}function j(I){ji(I.view).on("mousemove.drag mouseup.drag",null),pb(I.view,m),yu(I),o.mouse("end",I)}function N(I,K){if(e.call(this,I,K)){var U=I.changedTouches,J=t.call(this,I,K),Y=U.length,se,ce;for(se=0;se<Y;++se)(ce=T(this,J,I,K,U[se].identifier,U[se]))&&(W_(I),ce("start",I,U[se]))}}function C(I){var K=I.changedTouches,U=K.length,J,Y;for(J=0;J<U;++J)(Y=o[K[J].identifier])&&(yu(I),Y("drag",I,K[J]))}function E(I){var K=I.changedTouches,U=K.length,J,Y;for(p&&clearTimeout(p),p=setTimeout(function(){p=null},500),J=0;J<U;++J)(Y=o[K[J].identifier])&&(W_(I),Y("end",I,K[J]))}function T(I,K,U,J,Y,se){var ce=l.copy(),fe=Fi(se||U,K),W,P,A;if((A=n.call(I,new Ip("beforestart",{sourceEvent:U,target:w,identifier:Y,active:u,x:fe[0],y:fe[1],dx:0,dy:0,dispatch:ce}),J))!=null)return W=A.x-fe[0]||0,P=A.y-fe[1]||0,function z($,te,O){var F=fe,G;switch($){case"start":o[Y]=z,G=u++;break;case"end":delete o[Y],--u;case"drag":fe=Fi(O||te,K),G=u;break}ce.call($,I,new Ip($,{sourceEvent:te,subject:A,target:w,identifier:Y,active:G,x:fe[0]+W,y:fe[1]+P,dx:fe[0]-F[0],dy:fe[1]-F[1],dispatch:ce}),J)}}return w.filter=function(I){return arguments.length?(e=typeof I=="function"?I:Ih(!!I),w):e},w.container=function(I){return arguments.length?(t=typeof I=="function"?I:Ih(I),w):t},w.subject=function(I){return arguments.length?(n=typeof I=="function"?I:Ih(I),w):n},w.touchable=function(I){return arguments.length?(s=typeof I=="function"?I:Ih(!!I),w):s},w.on=function(){var I=l.on.apply(l,arguments);return I===l?w:I},w.clickDistance=function(I){return arguments.length?(g=(I=+I)*I,w):Math.sqrt(g)},w}function Ng(e,t,n){e.prototype=t.prototype=n,n.constructor=e}function gb(e,t){var n=Object.create(e.prototype);for(var s in t)n[s]=t[s];return n}function Tf(){}var _f=.7,mm=1/_f,wu="\\s*([+-]?\\d+)\\s*",pf="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",So="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",MA=/^#([0-9a-f]{3,8})$/,RA=new RegExp(`^rgb\\(${wu},${wu},${wu}\\)$`),LA=new RegExp(`^rgb\\(${So},${So},${So}\\)$`),IA=new RegExp(`^rgba\\(${wu},${wu},${wu},${pf}\\)$`),PA=new RegExp(`^rgba\\(${So},${So},${So},${pf}\\)$`),OA=new RegExp(`^hsl\\(${pf},${So},${So}\\)$`),DA=new RegExp(`^hsla\\(${pf},${So},${So},${pf}\\)$`),jw={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};Ng(Tf,gf,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:Sw,formatHex:Sw,formatHex8:FA,formatHsl:zA,formatRgb:kw,toString:kw});function Sw(){return this.rgb().formatHex()}function FA(){return this.rgb().formatHex8()}function zA(){return yb(this).formatHsl()}function kw(){return this.rgb().formatRgb()}function gf(e){var t,n;return e=(e+"").trim().toLowerCase(),(t=MA.exec(e))?(n=t[1].length,t=parseInt(t[1],16),n===6?Nw(t):n===3?new Us(t>>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):n===8?Ph(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?Ph(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=RA.exec(e))?new Us(t[1],t[2],t[3],1):(t=LA.exec(e))?new Us(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=IA.exec(e))?Ph(t[1],t[2],t[3],t[4]):(t=PA.exec(e))?Ph(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=OA.exec(e))?$w(t[1],t[2]/100,t[3]/100,1):(t=DA.exec(e))?$w(t[1],t[2]/100,t[3]/100,t[4]):jw.hasOwnProperty(e)?Nw(jw[e]):e==="transparent"?new Us(NaN,NaN,NaN,0):null}function Nw(e){return new Us(e>>16&255,e>>8&255,e&255,1)}function Ph(e,t,n,s){return s<=0&&(e=t=n=NaN),new Us(e,t,n,s)}function BA(e){return e instanceof Tf||(e=gf(e)),e?(e=e.rgb(),new Us(e.r,e.g,e.b,e.opacity)):new Us}function Pp(e,t,n,s){return arguments.length===1?BA(e):new Us(e,t,n,s??1)}function Us(e,t,n,s){this.r=+e,this.g=+t,this.b=+n,this.opacity=+s}Ng(Us,Pp,gb(Tf,{brighter(e){return e=e==null?mm:Math.pow(mm,e),new Us(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=e==null?_f:Math.pow(_f,e),new Us(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new Us(nc(this.r),nc(this.g),nc(this.b),_m(this.opacity))},displayable(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:Cw,formatHex:Cw,formatHex8:UA,formatRgb:Ew,toString:Ew}));function Cw(){return`#${Jl(this.r)}${Jl(this.g)}${Jl(this.b)}`}function UA(){return`#${Jl(this.r)}${Jl(this.g)}${Jl(this.b)}${Jl((isNaN(this.opacity)?1:this.opacity)*255)}`}function Ew(){const e=_m(this.opacity);return`${e===1?"rgb(":"rgba("}${nc(this.r)}, ${nc(this.g)}, ${nc(this.b)}${e===1?")":`, ${e})`}`}function _m(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function nc(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function Jl(e){return e=nc(e),(e<16?"0":"")+e.toString(16)}function $w(e,t,n,s){return s<=0?e=t=n=NaN:n<=0||n>=1?e=t=NaN:t<=0&&(e=NaN),new Ui(e,t,n,s)}function yb(e){if(e instanceof Ui)return new Ui(e.h,e.s,e.l,e.opacity);if(e instanceof Tf||(e=gf(e)),!e)return new Ui;if(e instanceof Ui)return e;e=e.rgb();var t=e.r/255,n=e.g/255,s=e.b/255,o=Math.min(t,n,s),l=Math.max(t,n,s),u=NaN,c=l-o,f=(l+o)/2;return c?(t===l?u=(n-s)/c+(n<s)*6:n===l?u=(s-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 Ui(u,c,f,e.opacity)}function WA(e,t,n,s){return arguments.length===1?yb(e):new Ui(e,t,n,s??1)}function Ui(e,t,n,s){this.h=+e,this.s=+t,this.l=+n,this.opacity=+s}Ng(Ui,WA,gb(Tf,{brighter(e){return e=e==null?mm:Math.pow(mm,e),new Ui(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?_f:Math.pow(_f,e),new Ui(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,s=n+(n<.5?n:1-n)*t,o=2*n-s;return new Us(q_(e>=240?e-240:e+120,o,s),q_(e,o,s),q_(e<120?e+240:e-120,o,s),this.opacity)},clamp(){return new Ui(Aw(this.h),Oh(this.s),Oh(this.l),_m(this.opacity))},displayable(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl(){const e=_m(this.opacity);return`${e===1?"hsl(":"hsla("}${Aw(this.h)}, ${Oh(this.s)*100}%, ${Oh(this.l)*100}%${e===1?")":`, ${e})`}`}}));function Aw(e){return e=(e||0)%360,e<0?e+360:e}function Oh(e){return Math.max(0,Math.min(1,e||0))}function q_(e,t,n){return(e<60?t+(n-t)*e/60:e<180?n:e<240?t+(n-t)*(240-e)/60:t)*255}const wb=e=>()=>e;function qA(e,t){return function(n){return e+n*t}}function HA(e,t,n){return e=Math.pow(e,n),t=Math.pow(t,n)-e,n=1/n,function(s){return Math.pow(e+s*t,n)}}function VA(e){return(e=+e)==1?vb:function(t,n){return n-t?HA(t,n,e):wb(isNaN(t)?n:t)}}function vb(e,t){var n=t-e;return n?qA(e,n):wb(isNaN(e)?t:e)}const Tw=(function e(t){var n=VA(t);function s(o,l){var u=n((o=Pp(o)).r,(l=Pp(l)).r),c=n(o.g,l.g),f=n(o.b,l.b),m=vb(o.opacity,l.opacity);return function(p){return o.r=u(p),o.g=c(p),o.b=f(p),o.opacity=m(p),o+""}}return s.gamma=e,s})(1);function rl(e,t){return e=+e,t=+t,function(n){return e*(1-n)+t*n}}var Op=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,H_=new RegExp(Op.source,"g");function GA(e){return function(){return e}}function KA(e){return function(t){return e(t)+""}}function YA(e,t){var n=Op.lastIndex=H_.lastIndex=0,s,o,l,u=-1,c=[],f=[];for(e=e+"",t=t+"";(s=Op.exec(e))&&(o=H_.exec(t));)(l=o.index)>n&&(l=t.slice(n,l),c[u]?c[u]+=l:c[++u]=l),(s=s[0])===(o=o[0])?c[u]?c[u]+=o:c[++u]=o:(c[++u]=null,f.push({i:u,x:rl(s,o)})),n=H_.lastIndex;return n<t.length&&(l=t.slice(n),c[u]?c[u]+=l:c[++u]=l),c.length<2?f[0]?KA(f[0].x):GA(t):(t=f.length,function(m){for(var p=0,g;p<t;++p)c[(g=f[p]).i]=g.x(m);return c.join("")})}var Mw=180/Math.PI,Dp={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function xb(e,t,n,s,o,l){var u,c,f;return(u=Math.sqrt(e*e+t*t))&&(e/=u,t/=u),(f=e*n+t*s)&&(n-=e*f,s-=t*f),(c=Math.sqrt(n*n+s*s))&&(n/=c,s/=c,f/=c),e*s<t*n&&(e=-e,t=-t,f=-f,u=-u),{translateX:o,translateY:l,rotate:Math.atan2(t,e)*Mw,skewX:Math.atan(f)*Mw,scaleX:u,scaleY:c}}var Dh;function JA(e){const t=new(typeof DOMMatrix=="function"?DOMMatrix:WebKitCSSMatrix)(e+"");return t.isIdentity?Dp:xb(t.a,t.b,t.c,t.d,t.e,t.f)}function XA(e){return e==null||(Dh||(Dh=document.createElementNS("http://www.w3.org/2000/svg","g")),Dh.setAttribute("transform",e),!(e=Dh.transform.baseVal.consolidate()))?Dp:(e=e.matrix,xb(e.a,e.b,e.c,e.d,e.e,e.f))}function bb(e,t,n,s){function o(m){return m.length?m.pop()+" ":""}function l(m,p,g,w,x,S){if(m!==g||p!==w){var j=x.push("translate(",null,t,null,n);S.push({i:j-4,x:rl(m,g)},{i:j-2,x:rl(p,w)})}else(g||w)&&x.push("translate("+g+t+w+n)}function u(m,p,g,w){m!==p?(m-p>180?p+=360:p-m>180&&(m+=360),w.push({i:g.push(o(g)+"rotate(",null,s)-2,x:rl(m,p)})):p&&g.push(o(g)+"rotate("+p+s)}function c(m,p,g,w){m!==p?w.push({i:g.push(o(g)+"skewX(",null,s)-2,x:rl(m,p)}):p&&g.push(o(g)+"skewX("+p+s)}function f(m,p,g,w,x,S){if(m!==g||p!==w){var j=x.push(o(x)+"scale(",null,",",null,")");S.push({i:j-4,x:rl(m,g)},{i:j-2,x:rl(p,w)})}else(g!==1||w!==1)&&x.push(o(x)+"scale("+g+","+w+")")}return function(m,p){var g=[],w=[];return m=e(m),p=e(p),l(m.translateX,m.translateY,p.translateX,p.translateY,g,w),u(m.rotate,p.rotate,g,w),c(m.skewX,p.skewX,g,w),f(m.scaleX,m.scaleY,p.scaleX,p.scaleY,g,w),m=p=null,function(x){for(var S=-1,j=w.length,N;++S<j;)g[(N=w[S]).i]=N.x(x);return g.join("")}}}var ZA=bb(JA,"px, ","px)","deg)"),QA=bb(XA,", ",")",")"),eT=1e-12;function Rw(e){return((e=Math.exp(e))+1/e)/2}function tT(e){return((e=Math.exp(e))-1/e)/2}function nT(e){return((e=Math.exp(2*e))-1)/(e+1)}const rT=(function e(t,n,s){function o(l,u){var c=l[0],f=l[1],m=l[2],p=u[0],g=u[1],w=u[2],x=p-c,S=g-f,j=x*x+S*S,N,C;if(j<eT)C=Math.log(w/m)/t,N=function(J){return[c+J*x,f+J*S,m*Math.exp(t*J*C)]};else{var E=Math.sqrt(j),T=(w*w-m*m+s*j)/(2*m*n*E),I=(w*w-m*m-s*j)/(2*w*n*E),K=Math.log(Math.sqrt(T*T+1)-T),U=Math.log(Math.sqrt(I*I+1)-I);C=(U-K)/t,N=function(J){var Y=J*C,se=Rw(K),ce=m/(n*E)*(se*nT(t*Y+K)-tT(K));return[c+ce*x,f+ce*S,m*se/Rw(t*Y+K)]}}return N.duration=C*1e3*t/Math.SQRT2,N}return o.rho=function(l){var u=Math.max(.001,+l),c=u*u,f=c*c;return e(u,c,f)},o})(Math.SQRT2,2,4);var Cu=0,of=0,Kd=0,jb=1e3,pm,af,gm=0,lc=0,Rm=0,yf=typeof performance=="object"&&performance.now?performance:Date,Sb=typeof window=="object"&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(e){setTimeout(e,17)};function Cg(){return lc||(Sb(sT),lc=yf.now()+Rm)}function sT(){lc=0}function ym(){this._call=this._time=this._next=null}ym.prototype=kb.prototype={constructor:ym,restart:function(e,t,n){if(typeof e!="function")throw new TypeError("callback is not a function");n=(n==null?Cg():+n)+(t==null?0:+t),!this._next&&af!==this&&(af?af._next=this:pm=this,af=this),this._call=e,this._time=n,Fp()},stop:function(){this._call&&(this._call=null,this._time=1/0,Fp())}};function kb(e,t,n){var s=new ym;return s.restart(e,t,n),s}function iT(){Cg(),++Cu;for(var e=pm,t;e;)(t=lc-e._time)>=0&&e._call.call(void 0,t),e=e._next;--Cu}function Lw(){lc=(gm=yf.now())+Rm,Cu=of=0;try{iT()}finally{Cu=0,aT(),lc=0}}function oT(){var e=yf.now(),t=e-gm;t>jb&&(Rm-=t,gm=e)}function aT(){for(var e,t=pm,n,s=1/0;t;)t._call?(s>t._time&&(s=t._time),e=t,t=t._next):(n=t._next,t._next=null,t=e?e._next=n:pm=n);af=e,Fp(s)}function Fp(e){if(!Cu){of&&(of=clearTimeout(of));var t=e-lc;t>24?(e<1/0&&(of=setTimeout(Lw,e-yf.now()-Rm)),Kd&&(Kd=clearInterval(Kd))):(Kd||(gm=yf.now(),Kd=setInterval(oT,jb)),Cu=1,Sb(Lw))}}function Iw(e,t,n){var s=new ym;return t=t==null?0:+t,s.restart(o=>{s.stop(),e(o+t)},t,n),s}var lT=Tm("start","end","cancel","interrupt"),cT=[],Nb=0,Pw=1,zp=2,Qh=3,Ow=4,Bp=5,em=6;function Lm(e,t,n,s,o,l){var u=e.__transition;if(!u)e.__transition={};else if(n in u)return;uT(e,n,{name:t,index:s,group:o,on:lT,tween:cT,time:l.time,delay:l.delay,duration:l.duration,ease:l.ease,timer:null,state:Nb})}function Eg(e,t){var n=Hi(e,t);if(n.state>Nb)throw new Error("too late; already scheduled");return n}function Co(e,t){var n=Hi(e,t);if(n.state>Qh)throw new Error("too late; already running");return n}function Hi(e,t){var n=e.__transition;if(!n||!(n=n[t]))throw new Error("transition not found");return n}function uT(e,t,n){var s=e.__transition,o;s[t]=n,n.timer=kb(l,0,n.time);function l(m){n.state=Pw,n.timer.restart(u,n.delay,n.time),n.delay<=m&&u(m-n.delay)}function u(m){var p,g,w,x;if(n.state!==Pw)return f();for(p in s)if(x=s[p],x.name===n.name){if(x.state===Qh)return Iw(u);x.state===Ow?(x.state=em,x.timer.stop(),x.on.call("interrupt",e,e.__data__,x.index,x.group),delete s[p]):+p<t&&(x.state=em,x.timer.stop(),x.on.call("cancel",e,e.__data__,x.index,x.group),delete s[p])}if(Iw(function(){n.state===Qh&&(n.state=Ow,n.timer.restart(c,n.delay,n.time),c(m))}),n.state=zp,n.on.call("start",e,e.__data__,n.index,n.group),n.state===zp){for(n.state=Qh,o=new Array(w=n.tween.length),p=0,g=-1;p<w;++p)(x=n.tween[p].value.call(e,e.__data__,n.index,n.group))&&(o[++g]=x);o.length=g+1}}function c(m){for(var p=m<n.duration?n.ease.call(null,m/n.duration):(n.timer.restart(f),n.state=Bp,1),g=-1,w=o.length;++g<w;)o[g].call(e,p);n.state===Bp&&(n.on.call("end",e,e.__data__,n.index,n.group),f())}function f(){n.state=em,n.timer.stop(),delete s[t];for(var m in s)return;delete e.__transition}}function tm(e,t){var n=e.__transition,s,o,l=!0,u;if(n){t=t==null?null:t+"";for(u in n){if((s=n[u]).name!==t){l=!1;continue}o=s.state>zp&&s.state<Bp,s.state=em,s.timer.stop(),s.on.call(o?"interrupt":"cancel",e,e.__data__,s.index,s.group),delete n[u]}l&&delete e.__transition}}function dT(e){return this.each(function(){tm(this,e)})}function fT(e,t){var n,s;return function(){var o=Co(this,e),l=o.tween;if(l!==n){s=n=l;for(var u=0,c=s.length;u<c;++u)if(s[u].name===t){s=s.slice(),s.splice(u,1);break}}o.tween=s}}function hT(e,t,n){var s,o;if(typeof n!="function")throw new Error;return function(){var l=Co(this,e),u=l.tween;if(u!==s){o=(s=u).slice();for(var c={name:t,value:n},f=0,m=o.length;f<m;++f)if(o[f].name===t){o[f]=c;break}f===m&&o.push(c)}l.tween=o}}function mT(e,t){var n=this._id;if(e+="",arguments.length<2){for(var s=Hi(this.node(),n).tween,o=0,l=s.length,u;o<l;++o)if((u=s[o]).name===e)return u.value;return null}return this.each((t==null?fT:hT)(n,e,t))}function $g(e,t,n){var s=e._id;return e.each(function(){var o=Co(this,s);(o.value||(o.value={}))[t]=n.apply(this,arguments)}),function(o){return Hi(o,s).value[t]}}function Cb(e,t){var n;return(typeof t=="number"?rl:t instanceof gf?Tw:(n=gf(t))?(t=n,Tw):YA)(e,t)}function _T(e){return function(){this.removeAttribute(e)}}function pT(e){return function(){this.removeAttributeNS(e.space,e.local)}}function gT(e,t,n){var s,o=n+"",l;return function(){var u=this.getAttribute(e);return u===o?null:u===s?l:l=t(s=u,n)}}function yT(e,t,n){var s,o=n+"",l;return function(){var u=this.getAttributeNS(e.space,e.local);return u===o?null:u===s?l:l=t(s=u,n)}}function wT(e,t,n){var s,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===s&&f===o?l:(o=f,l=t(s=u,c)))}}function vT(e,t,n){var s,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===s&&f===o?l:(o=f,l=t(s=u,c)))}}function xT(e,t){var n=Mm(e),s=n==="transform"?QA:Cb;return this.attrTween(e,typeof t=="function"?(n.local?vT:wT)(n,s,$g(this,"attr."+e,t)):t==null?(n.local?pT:_T)(n):(n.local?yT:gT)(n,s,t))}function bT(e,t){return function(n){this.setAttribute(e,t.call(this,n))}}function jT(e,t){return function(n){this.setAttributeNS(e.space,e.local,t.call(this,n))}}function ST(e,t){var n,s;function o(){var l=t.apply(this,arguments);return l!==s&&(n=(s=l)&&jT(e,l)),n}return o._value=t,o}function kT(e,t){var n,s;function o(){var l=t.apply(this,arguments);return l!==s&&(n=(s=l)&&bT(e,l)),n}return o._value=t,o}function NT(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 s=Mm(e);return this.tween(n,(s.local?ST:kT)(s,t))}function CT(e,t){return function(){Eg(this,e).delay=+t.apply(this,arguments)}}function ET(e,t){return t=+t,function(){Eg(this,e).delay=t}}function $T(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?CT:ET)(t,e)):Hi(this.node(),t).delay}function AT(e,t){return function(){Co(this,e).duration=+t.apply(this,arguments)}}function TT(e,t){return t=+t,function(){Co(this,e).duration=t}}function MT(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?AT:TT)(t,e)):Hi(this.node(),t).duration}function RT(e,t){if(typeof t!="function")throw new Error;return function(){Co(this,e).ease=t}}function LT(e){var t=this._id;return arguments.length?this.each(RT(t,e)):Hi(this.node(),t).ease}function IT(e,t){return function(){var n=t.apply(this,arguments);if(typeof n!="function")throw new Error;Co(this,e).ease=n}}function PT(e){if(typeof e!="function")throw new Error;return this.each(IT(this._id,e))}function OT(e){typeof e!="function"&&(e=ib(e));for(var t=this._groups,n=t.length,s=new Array(n),o=0;o<n;++o)for(var l=t[o],u=l.length,c=s[o]=[],f,m=0;m<u;++m)(f=l[m])&&e.call(f,f.__data__,m,l)&&c.push(f);return new ca(s,this._parents,this._name,this._id)}function DT(e){if(e._id!==this._id)throw new Error;for(var t=this._groups,n=e._groups,s=t.length,o=n.length,l=Math.min(s,o),u=new Array(s),c=0;c<l;++c)for(var f=t[c],m=n[c],p=f.length,g=u[c]=new Array(p),w,x=0;x<p;++x)(w=f[x]||m[x])&&(g[x]=w);for(;c<s;++c)u[c]=t[c];return new ca(u,this._parents,this._name,this._id)}function FT(e){return(e+"").trim().split(/^|\s+/).every(function(t){var n=t.indexOf(".");return n>=0&&(t=t.slice(0,n)),!t||t==="start"})}function zT(e,t,n){var s,o,l=FT(t)?Eg:Co;return function(){var u=l(this,e),c=u.on;c!==s&&(o=(s=c).copy()).on(t,n),u.on=o}}function BT(e,t){var n=this._id;return arguments.length<2?Hi(this.node(),n).on.on(e):this.each(zT(n,e,t))}function UT(e){return function(){var t=this.parentNode;for(var n in this.__transition)if(+n!==e)return;t&&t.removeChild(this)}}function WT(){return this.on("end.remove",UT(this._id))}function qT(e){var t=this._name,n=this._id;typeof e!="function"&&(e=Sg(e));for(var s=this._groups,o=s.length,l=new Array(o),u=0;u<o;++u)for(var c=s[u],f=c.length,m=l[u]=new Array(f),p,g,w=0;w<f;++w)(p=c[w])&&(g=e.call(p,p.__data__,w,c))&&("__data__"in p&&(g.__data__=p.__data__),m[w]=g,Lm(m[w],t,n,w,m,Hi(p,n)));return new ca(l,this._parents,t,n)}function HT(e){var t=this._name,n=this._id;typeof e!="function"&&(e=sb(e));for(var s=this._groups,o=s.length,l=[],u=[],c=0;c<o;++c)for(var f=s[c],m=f.length,p,g=0;g<m;++g)if(p=f[g]){for(var w=e.call(p,p.__data__,g,f),x,S=Hi(p,n),j=0,N=w.length;j<N;++j)(x=w[j])&&Lm(x,t,n,j,w,S);l.push(w),u.push(p)}return new ca(l,u,t,n)}var VT=Af.prototype.constructor;function GT(){return new VT(this._groups,this._parents)}function KT(e,t){var n,s,o;return function(){var l=Nu(this,e),u=(this.style.removeProperty(e),Nu(this,e));return l===u?null:l===n&&u===s?o:o=t(n=l,s=u)}}function Eb(e){return function(){this.style.removeProperty(e)}}function YT(e,t,n){var s,o=n+"",l;return function(){var u=Nu(this,e);return u===o?null:u===s?l:l=t(s=u,n)}}function JT(e,t,n){var s,o,l;return function(){var u=Nu(this,e),c=n(this),f=c+"";return c==null&&(f=c=(this.style.removeProperty(e),Nu(this,e))),u===f?null:u===s&&f===o?l:(o=f,l=t(s=u,c))}}function XT(e,t){var n,s,o,l="style."+t,u="end."+l,c;return function(){var f=Co(this,e),m=f.on,p=f.value[l]==null?c||(c=Eb(t)):void 0;(m!==n||o!==p)&&(s=(n=m).copy()).on(u,o=p),f.on=s}}function ZT(e,t,n){var s=(e+="")=="transform"?ZA:Cb;return t==null?this.styleTween(e,KT(e,s)).on("end.style."+e,Eb(e)):typeof t=="function"?this.styleTween(e,JT(e,s,$g(this,"style."+e,t))).each(XT(this._id,e)):this.styleTween(e,YT(e,s,t),n).on("end.style."+e,null)}function QT(e,t,n){return function(s){this.style.setProperty(e,t.call(this,s),n)}}function eM(e,t,n){var s,o;function l(){var u=t.apply(this,arguments);return u!==o&&(s=(o=u)&&QT(e,u,n)),s}return l._value=t,l}function tM(e,t,n){var s="style."+(e+="");if(arguments.length<2)return(s=this.tween(s))&&s._value;if(t==null)return this.tween(s,null);if(typeof t!="function")throw new Error;return this.tween(s,eM(e,t,n??""))}function nM(e){return function(){this.textContent=e}}function rM(e){return function(){var t=e(this);this.textContent=t??""}}function sM(e){return this.tween("text",typeof e=="function"?rM($g(this,"text",e)):nM(e==null?"":e+""))}function iM(e){return function(t){this.textContent=e.call(this,t)}}function oM(e){var t,n;function s(){var o=e.apply(this,arguments);return o!==n&&(t=(n=o)&&iM(o)),t}return s._value=e,s}function aM(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,oM(e))}function lM(){for(var e=this._name,t=this._id,n=$b(),s=this._groups,o=s.length,l=0;l<o;++l)for(var u=s[l],c=u.length,f,m=0;m<c;++m)if(f=u[m]){var p=Hi(f,t);Lm(f,e,n,m,u,{time:p.time+p.delay+p.duration,delay:0,duration:p.duration,ease:p.ease})}return new ca(s,this._parents,e,n)}function cM(){var e,t,n=this,s=n._id,o=n.size();return new Promise(function(l,u){var c={value:u},f={value:function(){--o===0&&l()}};n.each(function(){var m=Co(this,s),p=m.on;p!==e&&(t=(e=p).copy(),t._.cancel.push(c),t._.interrupt.push(c),t._.end.push(f)),m.on=t}),o===0&&l()})}var uM=0;function ca(e,t,n,s){this._groups=e,this._parents=t,this._name=n,this._id=s}function $b(){return++uM}var ra=Af.prototype;ca.prototype={constructor:ca,select:qT,selectAll:HT,selectChild:ra.selectChild,selectChildren:ra.selectChildren,filter:OT,merge:DT,selection:GT,transition:lM,call:ra.call,nodes:ra.nodes,node:ra.node,size:ra.size,empty:ra.empty,each:ra.each,on:BT,attr:xT,attrTween:NT,style:ZT,styleTween:tM,text:sM,textTween:aM,remove:WT,tween:mT,delay:$T,duration:MT,ease:LT,easeVarying:PT,end:cM,[Symbol.iterator]:ra[Symbol.iterator]};function dM(e){return((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2}var fM={time:null,delay:0,duration:250,ease:dM};function hM(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 mM(e){var t,n;e instanceof ca?(t=e._id,e=e._name):(t=$b(),(n=fM).time=Cg(),e=e==null?null:e+"");for(var s=this._groups,o=s.length,l=0;l<o;++l)for(var u=s[l],c=u.length,f,m=0;m<c;++m)(f=u[m])&&Lm(f,e,t,m,u,n||hM(f,t));return new ca(s,this._parents,e,t)}Af.prototype.interrupt=dT;Af.prototype.transition=mM;const Fh=e=>()=>e;function _M(e,{sourceEvent:t,target:n,transform:s,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:s,enumerable:!0,configurable:!0},_:{value:o}})}function oa(e,t,n){this.k=e,this.x=t,this.y=n}oa.prototype={constructor:oa,scale:function(e){return e===1?this:new oa(this.k*e,this.x,this.y)},translate:function(e,t){return e===0&t===0?this:new oa(this.k,this.x+this.k*e,this.y+this.k*t)},apply:function(e){return[e[0]*this.k+this.x,e[1]*this.k+this.y]},applyX:function(e){return e*this.k+this.x},applyY:function(e){return e*this.k+this.y},invert:function(e){return[(e[0]-this.x)/this.k,(e[1]-this.y)/this.k]},invertX:function(e){return(e-this.x)/this.k},invertY:function(e){return(e-this.y)/this.k},rescaleX:function(e){return e.copy().domain(e.range().map(this.invertX,this).map(e.invert,e))},rescaleY:function(e){return e.copy().domain(e.range().map(this.invertY,this).map(e.invert,e))},toString:function(){return"translate("+this.x+","+this.y+") scale("+this.k+")"}};var aa=new oa(1,0,0);oa.prototype;function V_(e){e.stopImmediatePropagation()}function Yd(e){e.preventDefault(),e.stopImmediatePropagation()}function pM(e){return(!e.ctrlKey||e.type==="wheel")&&!e.button}function gM(){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 Dw(){return this.__zoom||aa}function yM(e){return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*(e.ctrlKey?10:1)}function wM(){return navigator.maxTouchPoints||"ontouchstart"in this}function vM(e,t,n){var s=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>s?(s+o)/2:Math.min(0,s)||Math.max(0,o),u>l?(l+u)/2:Math.min(0,l)||Math.max(0,u))}function Ab(){var e=pM,t=gM,n=vM,s=yM,o=wM,l=[0,1/0],u=[[-1/0,-1/0],[1/0,1/0]],c=250,f=rT,m=Tm("start","zoom","end"),p,g,w,x=500,S=150,j=0,N=10;function C(A){A.property("__zoom",Dw).on("wheel.zoom",Y,{passive:!1}).on("mousedown.zoom",se).on("dblclick.zoom",ce).filter(o).on("touchstart.zoom",fe).on("touchmove.zoom",W).on("touchend.zoom touchcancel.zoom",P).style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}C.transform=function(A,z,$,te){var O=A.selection?A.selection():A;O.property("__zoom",Dw),A!==O?K(A,z,$,te):O.interrupt().each(function(){U(this,arguments).event(te).start().zoom(null,typeof z=="function"?z.apply(this,arguments):z).end()})},C.scaleBy=function(A,z,$,te){C.scaleTo(A,function(){var O=this.__zoom.k,F=typeof z=="function"?z.apply(this,arguments):z;return O*F},$,te)},C.scaleTo=function(A,z,$,te){C.transform(A,function(){var O=t.apply(this,arguments),F=this.__zoom,G=$==null?I(O):typeof $=="function"?$.apply(this,arguments):$,R=F.invert(G),Z=typeof z=="function"?z.apply(this,arguments):z;return n(T(E(F,Z),G,R),O,u)},$,te)},C.translateBy=function(A,z,$,te){C.transform(A,function(){return n(this.__zoom.translate(typeof z=="function"?z.apply(this,arguments):z,typeof $=="function"?$.apply(this,arguments):$),t.apply(this,arguments),u)},null,te)},C.translateTo=function(A,z,$,te,O){C.transform(A,function(){var F=t.apply(this,arguments),G=this.__zoom,R=te==null?I(F):typeof te=="function"?te.apply(this,arguments):te;return n(aa.translate(R[0],R[1]).scale(G.k).translate(typeof z=="function"?-z.apply(this,arguments):-z,typeof $=="function"?-$.apply(this,arguments):-$),F,u)},te,O)};function E(A,z){return z=Math.max(l[0],Math.min(l[1],z)),z===A.k?A:new oa(z,A.x,A.y)}function T(A,z,$){var te=z[0]-$[0]*A.k,O=z[1]-$[1]*A.k;return te===A.x&&O===A.y?A:new oa(A.k,te,O)}function I(A){return[(+A[0][0]+ +A[1][0])/2,(+A[0][1]+ +A[1][1])/2]}function K(A,z,$,te){A.on("start.zoom",function(){U(this,arguments).event(te).start()}).on("interrupt.zoom end.zoom",function(){U(this,arguments).event(te).end()}).tween("zoom",function(){var O=this,F=arguments,G=U(O,F).event(te),R=t.apply(O,F),Z=$==null?I(R):typeof $=="function"?$.apply(O,F):$,X=Math.max(R[1][0]-R[0][0],R[1][1]-R[0][1]),Q=O.__zoom,le=typeof z=="function"?z.apply(O,F):z,ge=f(Q.invert(Z).concat(X/Q.k),le.invert(Z).concat(X/le.k));return function(pe){if(pe===1)pe=le;else{var ye=ge(pe),Ne=X/ye[2];pe=new oa(Ne,Z[0]-ye[0]*Ne,Z[1]-ye[1]*Ne)}G.zoom(null,pe)}})}function U(A,z,$){return!$&&A.__zooming||new J(A,z)}function J(A,z){this.that=A,this.args=z,this.active=0,this.sourceEvent=null,this.extent=t.apply(A,z),this.taps=0}J.prototype={event:function(A){return A&&(this.sourceEvent=A),this},start:function(){return++this.active===1&&(this.that.__zooming=this,this.emit("start")),this},zoom:function(A,z){return this.mouse&&A!=="mouse"&&(this.mouse[1]=z.invert(this.mouse[0])),this.touch0&&A!=="touch"&&(this.touch0[1]=z.invert(this.touch0[0])),this.touch1&&A!=="touch"&&(this.touch1[1]=z.invert(this.touch1[0])),this.that.__zoom=z,this.emit("zoom"),this},end:function(){return--this.active===0&&(delete this.that.__zooming,this.emit("end")),this},emit:function(A){var z=ji(this.that).datum();m.call(A,this.that,new _M(A,{sourceEvent:this.sourceEvent,target:C,transform:this.that.__zoom,dispatch:m}),z)}};function Y(A,...z){if(!e.apply(this,arguments))return;var $=U(this,z).event(A),te=this.__zoom,O=Math.max(l[0],Math.min(l[1],te.k*Math.pow(2,s.apply(this,arguments)))),F=Fi(A);if($.wheel)($.mouse[0][0]!==F[0]||$.mouse[0][1]!==F[1])&&($.mouse[1]=te.invert($.mouse[0]=F)),clearTimeout($.wheel);else{if(te.k===O)return;$.mouse=[F,te.invert(F)],tm(this),$.start()}Yd(A),$.wheel=setTimeout(G,S),$.zoom("mouse",n(T(E(te,O),$.mouse[0],$.mouse[1]),$.extent,u));function G(){$.wheel=null,$.end()}}function se(A,...z){if(w||!e.apply(this,arguments))return;var $=A.currentTarget,te=U(this,z,!0).event(A),O=ji(A.view).on("mousemove.zoom",Z,!0).on("mouseup.zoom",X,!0),F=Fi(A,$),G=A.clientX,R=A.clientY;_b(A.view),V_(A),te.mouse=[F,this.__zoom.invert(F)],tm(this),te.start();function Z(Q){if(Yd(Q),!te.moved){var le=Q.clientX-G,ge=Q.clientY-R;te.moved=le*le+ge*ge>j}te.event(Q).zoom("mouse",n(T(te.that.__zoom,te.mouse[0]=Fi(Q,$),te.mouse[1]),te.extent,u))}function X(Q){O.on("mousemove.zoom mouseup.zoom",null),pb(Q.view,te.moved),Yd(Q),te.event(Q).end()}}function ce(A,...z){if(e.apply(this,arguments)){var $=this.__zoom,te=Fi(A.changedTouches?A.changedTouches[0]:A,this),O=$.invert(te),F=$.k*(A.shiftKey?.5:2),G=n(T(E($,F),te,O),t.apply(this,z),u);Yd(A),c>0?ji(this).transition().duration(c).call(K,G,te,A):ji(this).call(C.transform,G,te,A)}}function fe(A,...z){if(e.apply(this,arguments)){var $=A.touches,te=$.length,O=U(this,z,A.changedTouches.length===te).event(A),F,G,R,Z;for(V_(A),G=0;G<te;++G)R=$[G],Z=Fi(R,this),Z=[Z,this.__zoom.invert(Z),R.identifier],O.touch0?!O.touch1&&O.touch0[2]!==Z[2]&&(O.touch1=Z,O.taps=0):(O.touch0=Z,F=!0,O.taps=1+!!p);p&&(p=clearTimeout(p)),F&&(O.taps<2&&(g=Z[0],p=setTimeout(function(){p=null},x)),tm(this),O.start())}}function W(A,...z){if(this.__zooming){var $=U(this,z).event(A),te=A.changedTouches,O=te.length,F,G,R,Z;for(Yd(A),F=0;F<O;++F)G=te[F],R=Fi(G,this),$.touch0&&$.touch0[2]===G.identifier?$.touch0[0]=R:$.touch1&&$.touch1[2]===G.identifier&&($.touch1[0]=R);if(G=$.that.__zoom,$.touch1){var X=$.touch0[0],Q=$.touch0[1],le=$.touch1[0],ge=$.touch1[1],pe=(pe=le[0]-X[0])*pe+(pe=le[1]-X[1])*pe,ye=(ye=ge[0]-Q[0])*ye+(ye=ge[1]-Q[1])*ye;G=E(G,Math.sqrt(pe/ye)),R=[(X[0]+le[0])/2,(X[1]+le[1])/2],Z=[(Q[0]+ge[0])/2,(Q[1]+ge[1])/2]}else if($.touch0)R=$.touch0[0],Z=$.touch0[1];else return;$.zoom("touch",n(T(G,R,Z),$.extent,u))}}function P(A,...z){if(this.__zooming){var $=U(this,z).event(A),te=A.changedTouches,O=te.length,F,G;for(V_(A),w&&clearTimeout(w),w=setTimeout(function(){w=null},x),F=0;F<O;++F)G=te[F],$.touch0&&$.touch0[2]===G.identifier?delete $.touch0:$.touch1&&$.touch1[2]===G.identifier&&delete $.touch1;if($.touch1&&!$.touch0&&($.touch0=$.touch1,delete $.touch1),$.touch0)$.touch0[1]=this.__zoom.invert($.touch0[0]);else if($.end(),$.taps===2&&(G=Fi(G,this),Math.hypot(g[0]-G[0],g[1]-G[1])<N)){var R=ji(this).on("dblclick.zoom");R&&R.apply(this,arguments)}}}return C.wheelDelta=function(A){return arguments.length?(s=typeof A=="function"?A:Fh(+A),C):s},C.filter=function(A){return arguments.length?(e=typeof A=="function"?A:Fh(!!A),C):e},C.touchable=function(A){return arguments.length?(o=typeof A=="function"?A:Fh(!!A),C):o},C.extent=function(A){return arguments.length?(t=typeof A=="function"?A:Fh([[+A[0][0],+A[0][1]],[+A[1][0],+A[1][1]]]),C):t},C.scaleExtent=function(A){return arguments.length?(l[0]=+A[0],l[1]=+A[1],C):[l[0],l[1]]},C.translateExtent=function(A){return arguments.length?(u[0][0]=+A[0][0],u[1][0]=+A[1][0],u[0][1]=+A[0][1],u[1][1]=+A[1][1],C):[[u[0][0],u[0][1]],[u[1][0],u[1][1]]]},C.constrain=function(A){return arguments.length?(n=A,C):n},C.duration=function(A){return arguments.length?(c=+A,C):c},C.interpolate=function(A){return arguments.length?(f=A,C):f},C.on=function(){var A=m.on.apply(m,arguments);return A===m?C:A},C.clickDistance=function(A){return arguments.length?(j=(A=+A)*A,C):Math.sqrt(j)},C.tapDistance=function(A){return arguments.length?(N=+A,C):N},C}const Im=_.createContext(null),xM=Im.Provider,ua={error001:()=>"[React Flow]: Seems like you have not used zustand provider as an ancestor. Help: https://reactflow.dev/error#001",error002:()=>"It looks like you've created a new nodeTypes or edgeTypes object. If this wasn't on purpose please define the nodeTypes/edgeTypes outside of the component or memoize them.",error003:e=>`Node type "${e}" not found. Using fallback type "default".`,error004:()=>"The React Flow parent container needs a width and a height to render the graph.",error005:()=>"Only child nodes can use a parent extent.",error006:()=>"Can't create edge. An edge needs a source and a target.",error007:e=>`The old edge with id=${e} does not exist.`,error009:e=>`Marker type "${e}" doesn't exist.`,error008:(e,t)=>`Couldn't create edge for ${e?"target":"source"} handle id: "${e?t.targetHandle:t.sourceHandle}", edge id: ${t.id}.`,error010:()=>"Handle: No node id found. Make sure to only use a Handle inside a custom Node.",error011:e=>`Edge type "${e}" not found. Using fallback type "default".`,error012:e=>`Node with id "${e}" does not exist, it may have been removed. This can happen when a node is deleted before the "onNodeClick" handler is called.`},Tb=ua.error001();function Ln(e,t){const n=_.useContext(Im);if(n===null)throw new Error(Tb);return nb(n,e,t)}const br=()=>{const e=_.useContext(Im);if(e===null)throw new Error(Tb);return _.useMemo(()=>({getState:e.getState,setState:e.setState,subscribe:e.subscribe,destroy:e.destroy}),[e])},bM=e=>e.userSelectionActive?"none":"all";function wf({position:e,children:t,className:n,style:s,...o}){const l=Ln(bM),u=`${e}`.split("-");return ve.createElement("div",{className:Kr(["react-flow__panel",n,...u]),style:{...s,pointerEvents:l},...o},t)}function jM({proOptions:e,position:t="bottom-right"}){return e!=null&&e.hideAttribution?null:ve.createElement(wf,{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 SM=({x:e,y:t,label:n,labelStyle:s={},labelShowBg:o=!0,labelBgStyle:l={},labelBgPadding:u=[2,4],labelBgBorderRadius:c=2,children:f,className:m,...p})=>{const g=_.useRef(null),[w,x]=_.useState({x:0,y:0,width:0,height:0}),S=Kr(["react-flow__edge-textwrapper",m]);return _.useEffect(()=>{if(g.current){const j=g.current.getBBox();x({x:j.x,y:j.y,width:j.width,height:j.height})}},[n]),typeof n>"u"||!n?null:ve.createElement("g",{transform:`translate(${e-w.width/2} ${t-w.height/2})`,className:S,visibility:w.width?"visible":"hidden",...p},o&&ve.createElement("rect",{width:w.width+2*u[0],x:-u[0],y:-u[1],height:w.height+2*u[1],className:"react-flow__edge-textbg",style:l,rx:c,ry:c}),ve.createElement("text",{className:"react-flow__edge-text",y:w.height/2,dy:"0.3em",ref:g,style:s},n),f)};var kM=_.memo(SM);const Ag=e=>({width:e.offsetWidth,height:e.offsetHeight}),Eu=(e,t=0,n=1)=>Math.min(Math.max(e,t),n),Tg=(e={x:0,y:0},t)=>({x:Eu(e.x,t[0][0],t[1][0]),y:Eu(e.y,t[0][1],t[1][1])}),Fw=(e,t,n)=>e<t?Eu(Math.abs(e-t),1,50)/50:e>n?-Eu(Math.abs(e-n),1,50)/50:0,Mb=(e,t)=>{const n=Fw(e.x,35,t.width-35)*20,s=Fw(e.y,35,t.height-35)*20;return[n,s]},Rb=e=>{var t;return((t=e.getRootNode)==null?void 0:t.call(e))||(window==null?void 0:window.document)},Lb=(e,t)=>({x:Math.min(e.x,t.x),y:Math.min(e.y,t.y),x2:Math.max(e.x2,t.x2),y2:Math.max(e.y2,t.y2)}),vf=({x:e,y:t,width:n,height:s})=>({x:e,y:t,x2:e+n,y2:t+s}),Ib=({x:e,y:t,x2:n,y2:s})=>({x:e,y:t,width:n-e,height:s-t}),zw=e=>({...e.positionAbsolute||{x:0,y:0},width:e.width||0,height:e.height||0}),NM=(e,t)=>Ib(Lb(vf(e),vf(t))),Up=(e,t)=>{const n=Math.max(0,Math.min(e.x+e.width,t.x+t.width)-Math.max(e.x,t.x)),s=Math.max(0,Math.min(e.y+e.height,t.y+t.height)-Math.max(e.y,t.y));return Math.ceil(n*s)},CM=e=>Si(e.width)&&Si(e.height)&&Si(e.x)&&Si(e.y),Si=e=>!isNaN(e)&&isFinite(e),fr=Symbol.for("internals"),Pb=["Enter"," ","Escape"],EM=(e,t)=>{},$M=e=>"nativeEvent"in e;function Wp(e){var o,l;const t=$M(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 Ob=e=>"clientX"in e,ol=(e,t)=>{var l,u;const n=Ob(e),s=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:s-((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},Mf=({id:e,path:t,labelX:n,labelY:s,label:o,labelStyle:l,labelShowBg:u,labelBgStyle:c,labelBgPadding:f,labelBgBorderRadius:m,style:p,markerEnd:g,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:g,markerStart:w}),x&&ve.createElement("path",{d:t,fill:"none",strokeOpacity:0,strokeWidth:x,className:"react-flow__edge-interaction"}),o&&Si(n)&&Si(s)?ve.createElement(kM,{x:n,y:s,label:o,labelStyle:l,labelShowBg:u,labelBgStyle:c,labelBgPadding:f,labelBgBorderRadius:m}):null);Mf.displayName="BaseEdge";function Jd(e,t,n){return n===void 0?n:s=>{const o=t().edges.find(l=>l.id===e);o&&n(s,{...o})}}function Db({sourceX:e,sourceY:t,targetX:n,targetY:s}){const o=Math.abs(n-e)/2,l=n<e?n+o:n-o,u=Math.abs(s-t)/2,c=s<t?s+u:s-u;return[l,c,o,u]}function Fb({sourceX:e,sourceY:t,targetX:n,targetY:s,sourceControlX:o,sourceControlY:l,targetControlX:u,targetControlY:c}){const f=e*.125+o*.375+u*.375+n*.125,m=t*.125+l*.375+c*.375+s*.125,p=Math.abs(f-e),g=Math.abs(m-t);return[f,m,p,g]}var cc;(function(e){e.Strict="strict",e.Loose="loose"})(cc||(cc={}));var Xl;(function(e){e.Free="free",e.Vertical="vertical",e.Horizontal="horizontal"})(Xl||(Xl={}));var xf;(function(e){e.Partial="partial",e.Full="full"})(xf||(xf={}));var il;(function(e){e.Bezier="default",e.Straight="straight",e.Step="step",e.SmoothStep="smoothstep",e.SimpleBezier="simplebezier"})(il||(il={}));var bf;(function(e){e.Arrow="arrow",e.ArrowClosed="arrowclosed"})(bf||(bf={}));var _t;(function(e){e.Left="left",e.Top="top",e.Right="right",e.Bottom="bottom"})(_t||(_t={}));function Bw({pos:e,x1:t,y1:n,x2:s,y2:o}){return e===_t.Left||e===_t.Right?[.5*(t+s),n]:[t,.5*(n+o)]}function zb({sourceX:e,sourceY:t,sourcePosition:n=_t.Bottom,targetX:s,targetY:o,targetPosition:l=_t.Top}){const[u,c]=Bw({pos:n,x1:e,y1:t,x2:s,y2:o}),[f,m]=Bw({pos:l,x1:s,y1:o,x2:e,y2:t}),[p,g,w,x]=Fb({sourceX:e,sourceY:t,targetX:s,targetY:o,sourceControlX:u,sourceControlY:c,targetControlX:f,targetControlY:m});return[`M${e},${t} C${u},${c} ${f},${m} ${s},${o}`,p,g,w,x]}const Mg=_.memo(({sourceX:e,sourceY:t,targetX:n,targetY:s,sourcePosition:o=_t.Bottom,targetPosition:l=_t.Top,label:u,labelStyle:c,labelShowBg:f,labelBgStyle:m,labelBgPadding:p,labelBgBorderRadius:g,style:w,markerEnd:x,markerStart:S,interactionWidth:j})=>{const[N,C,E]=zb({sourceX:e,sourceY:t,sourcePosition:o,targetX:n,targetY:s,targetPosition:l});return ve.createElement(Mf,{path:N,labelX:C,labelY:E,label:u,labelStyle:c,labelShowBg:f,labelBgStyle:m,labelBgPadding:p,labelBgBorderRadius:g,style:w,markerEnd:x,markerStart:S,interactionWidth:j})});Mg.displayName="SimpleBezierEdge";const Uw={[_t.Left]:{x:-1,y:0},[_t.Right]:{x:1,y:0},[_t.Top]:{x:0,y:-1},[_t.Bottom]:{x:0,y:1}},AM=({source:e,sourcePosition:t=_t.Bottom,target:n})=>t===_t.Left||t===_t.Right?e.x<n.x?{x:1,y:0}:{x:-1,y:0}:e.y<n.y?{x:0,y:1}:{x:0,y:-1},Ww=(e,t)=>Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2));function TM({source:e,sourcePosition:t=_t.Bottom,target:n,targetPosition:s=_t.Top,center:o,offset:l}){const u=Uw[t],c=Uw[s],f={x:e.x+u.x*l,y:e.y+u.y*l},m={x:n.x+c.x*l,y:n.y+c.y*l},p=AM({source:f,sourcePosition:t,target:m}),g=p.x!==0?"x":"y",w=p[g];let x=[],S,j;const N={x:0,y:0},C={x:0,y:0},[E,T,I,K]=Db({sourceX:e.x,sourceY:e.y,targetX:n.x,targetY:n.y});if(u[g]*c[g]===-1){S=o.x||E,j=o.y||T;const J=[{x:S,y:f.y},{x:S,y:m.y}],Y=[{x:f.x,y:j},{x:m.x,y:j}];u[g]===w?x=g==="x"?J:Y:x=g==="x"?Y:J}else{const J=[{x:f.x,y:m.y}],Y=[{x:m.x,y:f.y}];if(g==="x"?x=u.x===w?Y:J:x=u.y===w?J:Y,t===s){const P=Math.abs(e[g]-n[g]);if(P<=l){const A=Math.min(l-1,l-P);u[g]===w?N[g]=(f[g]>e[g]?-1:1)*A:C[g]=(m[g]>n[g]?-1:1)*A}}if(t!==s){const P=g==="x"?"y":"x",A=u[g]===c[P],z=f[P]>m[P],$=f[P]<m[P];(u[g]===1&&(!A&&z||A&&$)||u[g]!==1&&(!A&&$||A&&z))&&(x=g==="x"?J:Y)}const se={x:f.x+N.x,y:f.y+N.y},ce={x:m.x+C.x,y:m.y+C.y},fe=Math.max(Math.abs(se.x-x[0].x),Math.abs(ce.x-x[0].x)),W=Math.max(Math.abs(se.y-x[0].y),Math.abs(ce.y-x[0].y));fe>=W?(S=(se.x+ce.x)/2,j=x[0].y):(S=x[0].x,j=(se.y+ce.y)/2)}return[[e,{x:f.x+N.x,y:f.y+N.y},...x,{x:m.x+C.x,y:m.y+C.y},n],S,j,I,K]}function MM(e,t,n,s){const o=Math.min(Ww(e,t)/2,Ww(t,n)/2,s),{x:l,y:u}=t;if(e.x===l&&l===n.x||e.y===u&&u===n.y)return`L${l} ${u}`;if(e.y===u){const m=e.x<n.x?-1:1,p=e.y<n.y?1:-1;return`L ${l+o*m},${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 qp({sourceX:e,sourceY:t,sourcePosition:n=_t.Bottom,targetX:s,targetY:o,targetPosition:l=_t.Top,borderRadius:u=5,centerX:c,centerY:f,offset:m=20}){const[p,g,w,x,S]=TM({source:{x:e,y:t},sourcePosition:n,target:{x:s,y:o},targetPosition:l,center:{x:c,y:f},offset:m});return[p.reduce((N,C,E)=>{let T="";return E>0&&E<p.length-1?T=MM(p[E-1],C,p[E+1],u):T=`${E===0?"M":"L"}${C.x} ${C.y}`,N+=T,N},""),g,w,x,S]}const Pm=_.memo(({sourceX:e,sourceY:t,targetX:n,targetY:s,label:o,labelStyle:l,labelShowBg:u,labelBgStyle:c,labelBgPadding:f,labelBgBorderRadius:m,style:p,sourcePosition:g=_t.Bottom,targetPosition:w=_t.Top,markerEnd:x,markerStart:S,pathOptions:j,interactionWidth:N})=>{const[C,E,T]=qp({sourceX:e,sourceY:t,sourcePosition:g,targetX:n,targetY:s,targetPosition:w,borderRadius:j==null?void 0:j.borderRadius,offset:j==null?void 0:j.offset});return ve.createElement(Mf,{path:C,labelX:E,labelY:T,label:o,labelStyle:l,labelShowBg:u,labelBgStyle:c,labelBgPadding:f,labelBgBorderRadius:m,style:p,markerEnd:x,markerStart:S,interactionWidth:N})});Pm.displayName="SmoothStepEdge";const Rg=_.memo(e=>{var t;return ve.createElement(Pm,{...e,pathOptions:_.useMemo(()=>{var n;return{borderRadius:0,offset:(n=e.pathOptions)==null?void 0:n.offset}},[(t=e.pathOptions)==null?void 0:t.offset])})});Rg.displayName="StepEdge";function RM({sourceX:e,sourceY:t,targetX:n,targetY:s}){const[o,l,u,c]=Db({sourceX:e,sourceY:t,targetX:n,targetY:s});return[`M ${e},${t}L ${n},${s}`,o,l,u,c]}const Lg=_.memo(({sourceX:e,sourceY:t,targetX:n,targetY:s,label:o,labelStyle:l,labelShowBg:u,labelBgStyle:c,labelBgPadding:f,labelBgBorderRadius:m,style:p,markerEnd:g,markerStart:w,interactionWidth:x})=>{const[S,j,N]=RM({sourceX:e,sourceY:t,targetX:n,targetY:s});return ve.createElement(Mf,{path:S,labelX:j,labelY:N,label:o,labelStyle:l,labelShowBg:u,labelBgStyle:c,labelBgPadding:f,labelBgBorderRadius:m,style:p,markerEnd:g,markerStart:w,interactionWidth:x})});Lg.displayName="StraightEdge";function zh(e,t){return e>=0?.5*e:t*25*Math.sqrt(-e)}function qw({pos:e,x1:t,y1:n,x2:s,y2:o,c:l}){switch(e){case _t.Left:return[t-zh(t-s,l),n];case _t.Right:return[t+zh(s-t,l),n];case _t.Top:return[t,n-zh(n-o,l)];case _t.Bottom:return[t,n+zh(o-n,l)]}}function Bb({sourceX:e,sourceY:t,sourcePosition:n=_t.Bottom,targetX:s,targetY:o,targetPosition:l=_t.Top,curvature:u=.25}){const[c,f]=qw({pos:n,x1:e,y1:t,x2:s,y2:o,c:u}),[m,p]=qw({pos:l,x1:s,y1:o,x2:e,y2:t,c:u}),[g,w,x,S]=Fb({sourceX:e,sourceY:t,targetX:s,targetY:o,sourceControlX:c,sourceControlY:f,targetControlX:m,targetControlY:p});return[`M${e},${t} C${c},${f} ${m},${p} ${s},${o}`,g,w,x,S]}const vm=_.memo(({sourceX:e,sourceY:t,targetX:n,targetY:s,sourcePosition:o=_t.Bottom,targetPosition:l=_t.Top,label:u,labelStyle:c,labelShowBg:f,labelBgStyle:m,labelBgPadding:p,labelBgBorderRadius:g,style:w,markerEnd:x,markerStart:S,pathOptions:j,interactionWidth:N})=>{const[C,E,T]=Bb({sourceX:e,sourceY:t,sourcePosition:o,targetX:n,targetY:s,targetPosition:l,curvature:j==null?void 0:j.curvature});return ve.createElement(Mf,{path:C,labelX:E,labelY:T,label:u,labelStyle:c,labelShowBg:f,labelBgStyle:m,labelBgPadding:p,labelBgBorderRadius:g,style:w,markerEnd:x,markerStart:S,interactionWidth:N})});vm.displayName="BezierEdge";const Ig=_.createContext(null),LM=Ig.Provider;Ig.Consumer;const IM=()=>_.useContext(Ig),PM=e=>"id"in e&&"source"in e&&"target"in e,OM=({source:e,sourceHandle:t,target:n,targetHandle:s})=>`reactflow__edge-${e}${t||""}-${n}${s||""}`,Hp=(e,t)=>typeof e>"u"?"":typeof e=="string"?e:`${t?`${t}__`:""}${Object.keys(e).sort().map(s=>`${s}=${e[s]}`).join("&")}`,DM=(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)),FM=(e,t)=>{if(!e.source||!e.target)return t;let n;return PM(e)?n={...e}:n={...e,id:OM(e)},DM(n,t)?t:t.concat(n)},Vp=({x:e,y:t},[n,s,o],l,[u,c])=>{const f={x:(e-n)/o,y:(t-s)/o};return l?{x:u*Math.round(f.x/u),y:c*Math.round(f.y/c)}:f},Ub=({x:e,y:t},[n,s,o])=>({x:e*o+n,y:t*o+s}),rc=(e,t=[0,0])=>{if(!e)return{x:0,y:0,positionAbsolute:{x:0,y:0}};const n=(e.width??0)*t[0],s=(e.height??0)*t[1],o={x:e.position.x-n,y:e.position.y-s};return{...o,positionAbsolute:e.positionAbsolute?{x:e.positionAbsolute.x-n,y:e.positionAbsolute.y-s}:o}},Om=(e,t=[0,0])=>{if(e.length===0)return{x:0,y:0,width:0,height:0};const n=e.reduce((s,o)=>{const{x:l,y:u}=rc(o,t).positionAbsolute;return Lb(s,vf({x:l,y:u,width:o.width||0,height:o.height||0}))},{x:1/0,y:1/0,x2:-1/0,y2:-1/0});return Ib(n)},Wb=(e,t,[n,s,o]=[0,0,1],l=!1,u=!1,c=[0,0])=>{const f={x:(t.x-n)/o,y:(t.y-s)/o,width:t.width/o,height:t.height/o},m=[];return e.forEach(p=>{const{width:g,height:w,selectable:x=!0,hidden:S=!1}=p;if(u&&!x||S)return!1;const{positionAbsolute:j}=rc(p,c),N={x:j.x,y:j.y,width:g||0,height:w||0},C=Up(f,N),E=typeof g>"u"||typeof w>"u"||g===null||w===null,T=l&&C>0,I=(g||0)*(w||0);(E||T||C>=I||p.dragging)&&m.push(p)}),m},qb=(e,t)=>{const n=e.map(s=>s.id);return t.filter(s=>n.includes(s.source)||n.includes(s.target))},Hb=(e,t,n,s,o,l=.1)=>{const u=t/(e.width*(1+l)),c=n/(e.height*(1+l)),f=Math.min(u,c),m=Eu(f,s,o),p=e.x+e.width/2,g=e.y+e.height/2,w=t/2-p*m,x=n/2-g*m;return{x:w,y:x,zoom:m}},Vl=(e,t=0)=>e.transition().duration(t);function Hw(e,t,n,s){return(t[n]||[]).reduce((o,l)=>{var u,c;return`${e.id}-${l.id}-${n}`!==s&&o.push({id:l.id||null,type:n,nodeId:e.id,x:(((u=e.positionAbsolute)==null?void 0:u.x)??0)+l.x+l.width/2,y:(((c=e.positionAbsolute)==null?void 0:c.y)??0)+l.y+l.height/2}),o},[])}function zM(e,t,n,s,o,l){const{x:u,y:c}=ol(e),m=t.elementsFromPoint(u,c).find(S=>S.classList.contains("react-flow__handle"));if(m){const S=m.getAttribute("data-nodeid");if(S){const j=Pg(void 0,m),N=m.getAttribute("data-handleid"),C=l({nodeId:S,id:N,type:j});if(C){const E=o.find(T=>T.nodeId===S&&T.type===j&&T.id===N);return{handle:{id:N,type:j,nodeId:S,x:(E==null?void 0:E.x)||n.x,y:(E==null?void 0:E.y)||n.y},validHandleResult:C}}}}let p=[],g=1/0;if(o.forEach(S=>{const j=Math.sqrt((S.x-n.x)**2+(S.y-n.y)**2);if(j<=s){const N=l(S);j<=g&&(j<g?p=[{handle:S,validHandleResult:N}]:j===g&&p.push({handle:S,validHandleResult:N}),g=j)}}),!p.length)return{handle:null,validHandleResult:Vb()};if(p.length===1)return p[0];const w=p.some(({validHandleResult:S})=>S.isValid),x=p.some(({handle:S})=>S.type==="target");return p.find(({handle:S,validHandleResult:j})=>x?S.type==="target":w?j.isValid:!0)||p[0]}const BM={source:null,target:null,sourceHandle:null,targetHandle:null},Vb=()=>({handleDomNode:null,isValid:!1,connection:BM,endHandle:null});function Gb(e,t,n,s,o,l,u){const c=o==="target",f=u.querySelector(`.react-flow__handle[data-id="${e==null?void 0:e.nodeId}-${e==null?void 0:e.id}-${e==null?void 0:e.type}"]`),m={...Vb(),handleDomNode:f};if(f){const p=Pg(void 0,f),g=f.getAttribute("data-nodeid"),w=f.getAttribute("data-handleid"),x=f.classList.contains("connectable"),S=f.classList.contains("connectableend"),j={source:c?g:n,sourceHandle:c?w:s,target:c?n:g,targetHandle:c?s:w};m.connection=j,x&&S&&(t===cc.Strict?c&&p==="source"||!c&&p==="target":g!==n||w!==s)&&(m.endHandle={nodeId:g,handleId:w,type:p},m.isValid=l(j))}return m}function UM({nodes:e,nodeId:t,handleId:n,handleType:s}){return e.reduce((o,l)=>{if(l[fr]){const{handleBounds:u}=l[fr];let c=[],f=[];u&&(c=Hw(l,u,"source",`${t}-${n}-${s}`),f=Hw(l,u,"target",`${t}-${n}-${s}`)),o.push(...c,...f)}return o},[])}function Pg(e,t){return e||(t!=null&&t.classList.contains("target")?"target":t!=null&&t.classList.contains("source")?"source":null)}function G_(e){e==null||e.classList.remove("valid","connecting","react-flow__handle-valid","react-flow__handle-connecting")}function WM(e,t){let n=null;return t?n="valid":e&&!t&&(n="invalid"),n}function Kb({event:e,handleId:t,nodeId:n,onConnect:s,isTarget:o,getState:l,setState:u,isValidConnection:c,edgeUpdaterType:f,onEdgeUpdateEnd:m}){const p=Rb(e.target),{connectionMode:g,domNode:w,autoPanOnConnect:x,connectionRadius:S,onConnectStart:j,panBy:N,getNodes:C,cancelConnection:E}=l();let T=0,I;const{x:K,y:U}=ol(e),J=p==null?void 0:p.elementFromPoint(K,U),Y=Pg(f,J),se=w==null?void 0:w.getBoundingClientRect();if(!se||!Y)return;let ce,fe=ol(e,se),W=!1,P=null,A=!1,z=null;const $=UM({nodes:C(),nodeId:n,handleId:t,handleType:Y}),te=()=>{if(!x)return;const[G,R]=Mb(fe,se);N({x:G,y:R}),T=requestAnimationFrame(te)};u({connectionPosition:fe,connectionStatus:null,connectionNodeId:n,connectionHandleId:t,connectionHandleType:Y,connectionStartHandle:{nodeId:n,handleId:t,type:Y},connectionEndHandle:null}),j==null||j(e,{nodeId:n,handleId:t,handleType:Y});function O(G){const{transform:R}=l();fe=ol(G,se);const{handle:Z,validHandleResult:X}=zM(G,p,Vp(fe,R,!1,[1,1]),S,$,Q=>Gb(Q,g,n,t,o?"target":"source",c,p));if(I=Z,W||(te(),W=!0),z=X.handleDomNode,P=X.connection,A=X.isValid,u({connectionPosition:I&&A?Ub({x:I.x,y:I.y},R):fe,connectionStatus:WM(!!I,A),connectionEndHandle:X.endHandle}),!I&&!A&&!z)return G_(ce);P.source!==P.target&&z&&(G_(ce),ce=z,z.classList.add("connecting","react-flow__handle-connecting"),z.classList.toggle("valid",A),z.classList.toggle("react-flow__handle-valid",A))}function F(G){var R,Z;(I||z)&&P&&A&&(s==null||s(P)),(Z=(R=l()).onConnectEnd)==null||Z.call(R,G),f&&(m==null||m(G)),G_(ce),E(),cancelAnimationFrame(T),W=!1,A=!1,P=null,z=null,p.removeEventListener("mousemove",O),p.removeEventListener("mouseup",F),p.removeEventListener("touchmove",O),p.removeEventListener("touchend",F)}p.addEventListener("mousemove",O),p.addEventListener("mouseup",F),p.addEventListener("touchmove",O),p.addEventListener("touchend",F)}const Vw=()=>!0,qM=e=>({connectionStartHandle:e.connectionStartHandle,connectOnClick:e.connectOnClick,noPanClassName:e.noPanClassName}),HM=(e,t,n)=>s=>{const{connectionStartHandle:o,connectionEndHandle:l,connectionClickStartHandle:u}=s;return{connecting:(o==null?void 0:o.nodeId)===e&&(o==null?void 0:o.handleId)===t&&(o==null?void 0:o.type)===n||(l==null?void 0:l.nodeId)===e&&(l==null?void 0:l.handleId)===t&&(l==null?void 0:l.type)===n,clickConnecting:(u==null?void 0:u.nodeId)===e&&(u==null?void 0:u.handleId)===t&&(u==null?void 0:u.type)===n}},Yb=_.forwardRef(({type:e="source",position:t=_t.Top,isValidConnection:n,isConnectable:s=!0,isConnectableStart:o=!0,isConnectableEnd:l=!0,id:u,onConnect:c,children:f,className:m,onMouseDown:p,onTouchStart:g,...w},x)=>{var se,ce;const S=u||null,j=e==="target",N=br(),C=IM(),{connectOnClick:E,noPanClassName:T}=Ln(qM,Pr),{connecting:I,clickConnecting:K}=Ln(HM(C,S,e),Pr);C||(ce=(se=N.getState()).onError)==null||ce.call(se,"010",ua.error010());const U=fe=>{const{defaultEdgeOptions:W,onConnect:P,hasDefaultEdges:A}=N.getState(),z={...W,...fe};if(A){const{edges:$,setEdges:te}=N.getState();te(FM(z,$))}P==null||P(z),c==null||c(z)},J=fe=>{if(!C)return;const W=Ob(fe);o&&(W&&fe.button===0||!W)&&Kb({event:fe,handleId:S,nodeId:C,onConnect:U,isTarget:j,getState:N.getState,setState:N.setState,isValidConnection:n||N.getState().isValidConnection||Vw}),W?p==null||p(fe):g==null||g(fe)},Y=fe=>{const{onClickConnectStart:W,onClickConnectEnd:P,connectionClickStartHandle:A,connectionMode:z,isValidConnection:$}=N.getState();if(!C||!A&&!o)return;if(!A){W==null||W(fe,{nodeId:C,handleId:S,handleType:e}),N.setState({connectionClickStartHandle:{nodeId:C,type:e,handleId:S}});return}const te=Rb(fe.target),O=n||$||Vw,{connection:F,isValid:G}=Gb({nodeId:C,id:S,type:e},z,A.nodeId,A.handleId||null,A.type,O,te);G&&U(F),P==null||P(fe),N.setState({connectionClickStartHandle:null})};return ve.createElement("div",{"data-handleid":S,"data-nodeid":C,"data-handlepos":t,"data-id":`${C}-${S}-${e}`,className:Kr(["react-flow__handle",`react-flow__handle-${t}`,"nodrag",T,m,{source:!j,target:j,connectable:s,connectablestart:o,connectableend:l,connecting:K,connectionindicator:s&&(o&&!I||l&&I)}]),onMouseDown:J,onTouchStart:J,onClick:E?Y:void 0,ref:x,...w},f)});Yb.displayName="Handle";var xm=_.memo(Yb);const Jb=({data:e,isConnectable:t,targetPosition:n=_t.Top,sourcePosition:s=_t.Bottom})=>ve.createElement(ve.Fragment,null,ve.createElement(xm,{type:"target",position:n,isConnectable:t}),e==null?void 0:e.label,ve.createElement(xm,{type:"source",position:s,isConnectable:t}));Jb.displayName="DefaultNode";var Gp=_.memo(Jb);const Xb=({data:e,isConnectable:t,sourcePosition:n=_t.Bottom})=>ve.createElement(ve.Fragment,null,e==null?void 0:e.label,ve.createElement(xm,{type:"source",position:n,isConnectable:t}));Xb.displayName="InputNode";var Zb=_.memo(Xb);const Qb=({data:e,isConnectable:t,targetPosition:n=_t.Top})=>ve.createElement(ve.Fragment,null,ve.createElement(xm,{type:"target",position:n,isConnectable:t}),e==null?void 0:e.label);Qb.displayName="OutputNode";var e0=_.memo(Qb);const Og=()=>null;Og.displayName="GroupNode";const VM=e=>({selectedNodes:e.getNodes().filter(t=>t.selected),selectedEdges:e.edges.filter(t=>t.selected)}),Bh=e=>e.id;function GM(e,t){return Pr(e.selectedNodes.map(Bh),t.selectedNodes.map(Bh))&&Pr(e.selectedEdges.map(Bh),t.selectedEdges.map(Bh))}const t0=_.memo(({onSelectionChange:e})=>{const t=br(),{selectedNodes:n,selectedEdges:s}=Ln(VM,GM);return _.useEffect(()=>{const o={nodes:n,edges:s};e==null||e(o),t.getState().onSelectionChange.forEach(l=>l(o))},[n,s,e]),null});t0.displayName="SelectionListener";const KM=e=>!!e.onSelectionChange;function YM({onSelectionChange:e}){const t=Ln(KM);return e||t?ve.createElement(t0,{onSelectionChange:e}):null}const JM=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 iu(e,t){_.useEffect(()=>{typeof e<"u"&&t(e)},[e])}function Gt(e,t,n){_.useEffect(()=>{typeof t<"u"&&n({[e]:t})},[t])}const XM=({nodes:e,edges:t,defaultNodes:n,defaultEdges:s,onConnect:o,onConnectStart:l,onConnectEnd:u,onClickConnectStart:c,onClickConnectEnd:f,nodesDraggable:m,nodesConnectable:p,nodesFocusable:g,edgesFocusable:w,edgesUpdatable:x,elevateNodesOnSelect:S,minZoom:j,maxZoom:N,nodeExtent:C,onNodesChange:E,onEdgesChange:T,elementsSelectable:I,connectionMode:K,snapGrid:U,snapToGrid:J,translateExtent:Y,connectOnClick:se,defaultEdgeOptions:ce,fitView:fe,fitViewOptions:W,onNodesDelete:P,onEdgesDelete:A,onNodeDrag:z,onNodeDragStart:$,onNodeDragStop:te,onSelectionDrag:O,onSelectionDragStart:F,onSelectionDragStop:G,noPanClassName:R,nodeOrigin:Z,rfId:X,autoPanOnConnect:Q,autoPanOnNodeDrag:le,onError:ge,connectionRadius:pe,isValidConnection:ye,nodeDragThreshold:Ne})=>{const{setNodes:Ue,setEdges:We,setDefaultNodesAndEdges:pt,setMinZoom:Fe,setMaxZoom:tt,setTranslateExtent:lt,setNodeExtent:Ke,reset:Se}=Ln(JM,Pr),Re=br();return _.useEffect(()=>{const ht=s==null?void 0:s.map(xe=>({...xe,...ce}));return pt(n,ht),()=>{Se()}},[]),Gt("defaultEdgeOptions",ce,Re.setState),Gt("connectionMode",K,Re.setState),Gt("onConnect",o,Re.setState),Gt("onConnectStart",l,Re.setState),Gt("onConnectEnd",u,Re.setState),Gt("onClickConnectStart",c,Re.setState),Gt("onClickConnectEnd",f,Re.setState),Gt("nodesDraggable",m,Re.setState),Gt("nodesConnectable",p,Re.setState),Gt("nodesFocusable",g,Re.setState),Gt("edgesFocusable",w,Re.setState),Gt("edgesUpdatable",x,Re.setState),Gt("elementsSelectable",I,Re.setState),Gt("elevateNodesOnSelect",S,Re.setState),Gt("snapToGrid",J,Re.setState),Gt("snapGrid",U,Re.setState),Gt("onNodesChange",E,Re.setState),Gt("onEdgesChange",T,Re.setState),Gt("connectOnClick",se,Re.setState),Gt("fitViewOnInit",fe,Re.setState),Gt("fitViewOnInitOptions",W,Re.setState),Gt("onNodesDelete",P,Re.setState),Gt("onEdgesDelete",A,Re.setState),Gt("onNodeDrag",z,Re.setState),Gt("onNodeDragStart",$,Re.setState),Gt("onNodeDragStop",te,Re.setState),Gt("onSelectionDrag",O,Re.setState),Gt("onSelectionDragStart",F,Re.setState),Gt("onSelectionDragStop",G,Re.setState),Gt("noPanClassName",R,Re.setState),Gt("nodeOrigin",Z,Re.setState),Gt("rfId",X,Re.setState),Gt("autoPanOnConnect",Q,Re.setState),Gt("autoPanOnNodeDrag",le,Re.setState),Gt("onError",ge,Re.setState),Gt("connectionRadius",pe,Re.setState),Gt("isValidConnection",ye,Re.setState),Gt("nodeDragThreshold",Ne,Re.setState),iu(e,Ue),iu(t,We),iu(j,Fe),iu(N,tt),iu(Y,lt),iu(C,Ke),null},Gw={display:"none"},ZM={position:"absolute",width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0px, 0px, 0px, 0px)",clipPath:"inset(100%)"},n0="react-flow__node-desc",r0="react-flow__edge-desc",QM="react-flow__aria-live",eR=e=>e.ariaLiveMessage;function tR({rfId:e}){const t=Ln(eR);return ve.createElement("div",{id:`${QM}-${e}`,"aria-live":"assertive","aria-atomic":"true",style:ZM},t)}function nR({rfId:e,disableKeyboardA11y:t}){return ve.createElement(ve.Fragment,null,ve.createElement("div",{id:`${n0}-${e}`,style:Gw},"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:`${r0}-${e}`,style:Gw},"Press enter or space to select an edge. You can then press delete to remove it or escape to cancel."),!t&&ve.createElement(tR,{rfId:e}))}var jf=(e=null,t={actInsideInputWithModifier:!0})=>{const[n,s]=_.useState(!1),o=_.useRef(!1),l=_.useRef(new Set([])),[u,c]=_.useMemo(()=>{if(e!==null){const m=(Array.isArray(e)?e:[e]).filter(g=>typeof g=="string").map(g=>g.split("+")),p=m.reduce((g,w)=>g.concat(...w),[]);return[m,p]}return[[],[]]},[e]);return _.useEffect(()=>{const f=typeof document<"u"?document:null,m=(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)&&Wp(x))return!1;const j=Yw(x.code,c);l.current.add(x[j]),Kw(u,l.current,!1)&&(x.preventDefault(),s(!0))},g=x=>{if((!o.current||o.current&&!t.actInsideInputWithModifier)&&Wp(x))return!1;const j=Yw(x.code,c);Kw(u,l.current,!0)?(s(!1),l.current.clear()):l.current.delete(x[j]),x.key==="Meta"&&l.current.clear(),o.current=!1},w=()=>{l.current.clear(),s(!1)};return m==null||m.addEventListener("keydown",p),m==null||m.addEventListener("keyup",g),window.addEventListener("blur",w),()=>{m==null||m.removeEventListener("keydown",p),m==null||m.removeEventListener("keyup",g),window.removeEventListener("blur",w)}}},[e,s]),n};function Kw(e,t,n){return e.filter(s=>n||s.length===t.size).some(s=>s.every(o=>t.has(o)))}function Yw(e,t){return t.includes(e)?"code":"key"}function s0(e,t,n,s){var u,c;if(!e.parentNode)return n;const o=t.get(e.parentNode),l=rc(o,s);return s0(o,t,{x:(n.x??0)+l.x,y:(n.y??0)+l.y,z:(((u=o[fr])==null?void 0:u.z)??0)>(n.z??0)?((c=o[fr])==null?void 0:c.z)??0:n.z??0},s)}function i0(e,t,n){e.forEach(s=>{var o;if(s.parentNode&&!e.has(s.parentNode))throw new Error(`Parent node ${s.parentNode} not found`);if(s.parentNode||n!=null&&n[s.id]){const{x:l,y:u,z:c}=s0(s,e,{...s.position,z:((o=s[fr])==null?void 0:o.z)??0},t);s.positionAbsolute={x:l,y:u},s[fr].z=c,n!=null&&n[s.id]&&(s[fr].isParent=!0)}})}function K_(e,t,n,s){const o=new Map,l={},u=s?1e3:0;return e.forEach(c=>{var w;const f=(Si(c.zIndex)?c.zIndex:0)+(c.selected?u:0),m=t.get(c.id),p={...c,positionAbsolute:{x:c.position.x,y:c.position.y}};c.parentNode&&(l[c.parentNode]=!0);const g=(m==null?void 0:m.type)&&(m==null?void 0:m.type)!==c.type;Object.defineProperty(p,fr,{enumerable:!1,value:{handleBounds:g||(w=m==null?void 0:m[fr])==null?void 0:w.handleBounds,z:f}}),o.set(c.id,p)}),i0(o,n,l),o}function o0(e,t={}){const{getNodes:n,width:s,height:o,minZoom:l,maxZoom:u,d3Zoom:c,d3Selection:f,fitViewOnInitDone:m,fitViewOnInit:p,nodeOrigin:g}=e(),w=t.initial&&!m&&p;if(c&&f&&(w||!t.initial)){const S=n().filter(N=>{var E;const C=t.includeHiddenNodes?N.width&&N.height:!N.hidden;return(E=t.nodes)!=null&&E.length?C&&t.nodes.some(T=>T.id===N.id):C}),j=S.every(N=>N.width&&N.height);if(S.length>0&&j){const N=Om(S,g),{x:C,y:E,zoom:T}=Hb(N,s,o,t.minZoom??l,t.maxZoom??u,t.padding??.1),I=aa.translate(C,E).scale(T);return typeof t.duration=="number"&&t.duration>0?c.transform(Vl(f,t.duration),I):c.transform(f,I),!0}}return!1}function rR(e,t){return e.forEach(n=>{const s=t.get(n.id);s&&t.set(s.id,{...s,[fr]:s[fr],selected:n.selected})}),new Map(t)}function sR(e,t){return t.map(n=>{const s=e.find(o=>o.id===n.id);return s&&(n.selected=s.selected),n})}function Uh({changedNodes:e,changedEdges:t,get:n,set:s}){const{nodeInternals:o,edges:l,onNodesChange:u,onEdgesChange:c,hasDefaultNodes:f,hasDefaultEdges:m}=n();e!=null&&e.length&&(f&&s({nodeInternals:rR(e,o)}),u==null||u(e)),t!=null&&t.length&&(m&&s({edges:sR(t,l)}),c==null||c(t))}const ou=()=>{},iR={zoomIn:ou,zoomOut:ou,zoomTo:ou,getZoom:()=>1,setViewport:ou,getViewport:()=>({x:0,y:0,zoom:1}),fitView:()=>!1,setCenter:ou,fitBounds:ou,project:e=>e,screenToFlowPosition:e=>e,flowToScreenPosition:e=>e,viewportInitialized:!1},oR=e=>({d3Zoom:e.d3Zoom,d3Selection:e.d3Selection}),aR=()=>{const e=br(),{d3Zoom:t,d3Selection:n}=Ln(oR,Pr);return _.useMemo(()=>n&&t?{zoomIn:o=>t.scaleBy(Vl(n,o==null?void 0:o.duration),1.2),zoomOut:o=>t.scaleBy(Vl(n,o==null?void 0:o.duration),1/1.2),zoomTo:(o,l)=>t.scaleTo(Vl(n,l==null?void 0:l.duration),o),getZoom:()=>e.getState().transform[2],setViewport:(o,l)=>{const[u,c,f]=e.getState().transform,m=aa.translate(o.x??u,o.y??c).scale(o.zoom??f);t.transform(Vl(n,l==null?void 0:l.duration),m)},getViewport:()=>{const[o,l,u]=e.getState().transform;return{x:o,y:l,zoom:u}},fitView:o=>o0(e.getState,o),setCenter:(o,l,u)=>{const{width:c,height:f,maxZoom:m}=e.getState(),p=typeof(u==null?void 0:u.zoom)<"u"?u.zoom:m,g=c/2-o*p,w=f/2-l*p,x=aa.translate(g,w).scale(p);t.transform(Vl(n,u==null?void 0:u.duration),x)},fitBounds:(o,l)=>{const{width:u,height:c,minZoom:f,maxZoom:m}=e.getState(),{x:p,y:g,zoom:w}=Hb(o,u,c,f,m,(l==null?void 0:l.padding)??.1),x=aa.translate(p,g).scale(w);t.transform(Vl(n,l==null?void 0:l.duration),x)},project:o=>{const{transform:l,snapToGrid:u,snapGrid:c}=e.getState();return console.warn("[DEPRECATED] `project` is deprecated. Instead use `screenToFlowPosition`. There is no need to subtract the react flow bounds anymore! https://reactflow.dev/api-reference/types/react-flow-instance#screen-to-flow-position"),Vp(o,l,u,c)},screenToFlowPosition:o=>{const{transform:l,snapToGrid:u,snapGrid:c,domNode:f}=e.getState();if(!f)return o;const{x:m,y:p}=f.getBoundingClientRect(),g={x:o.x-m,y:o.y-p};return Vp(g,l,u,c)},flowToScreenPosition:o=>{const{transform:l,domNode:u}=e.getState();if(!u)return o;const{x:c,y:f}=u.getBoundingClientRect(),m=Ub(o,l);return{x:m.x+c,y:m.y+f}},viewportInitialized:!0}:iR,[t,n])};function Dg(){const e=aR(),t=br(),n=_.useCallback(()=>t.getState().getNodes().map(j=>({...j})),[]),s=_.useCallback(j=>t.getState().nodeInternals.get(j),[]),o=_.useCallback(()=>{const{edges:j=[]}=t.getState();return j.map(N=>({...N}))},[]),l=_.useCallback(j=>{const{edges:N=[]}=t.getState();return N.find(C=>C.id===j)},[]),u=_.useCallback(j=>{const{getNodes:N,setNodes:C,hasDefaultNodes:E,onNodesChange:T}=t.getState(),I=N(),K=typeof j=="function"?j(I):j;if(E)C(K);else if(T){const U=K.length===0?I.map(J=>({type:"remove",id:J.id})):K.map(J=>({item:J,type:"reset"}));T(U)}},[]),c=_.useCallback(j=>{const{edges:N=[],setEdges:C,hasDefaultEdges:E,onEdgesChange:T}=t.getState(),I=typeof j=="function"?j(N):j;if(E)C(I);else if(T){const K=I.length===0?N.map(U=>({type:"remove",id:U.id})):I.map(U=>({item:U,type:"reset"}));T(K)}},[]),f=_.useCallback(j=>{const N=Array.isArray(j)?j:[j],{getNodes:C,setNodes:E,hasDefaultNodes:T,onNodesChange:I}=t.getState();if(T){const U=[...C(),...N];E(U)}else if(I){const K=N.map(U=>({item:U,type:"add"}));I(K)}},[]),m=_.useCallback(j=>{const N=Array.isArray(j)?j:[j],{edges:C=[],setEdges:E,hasDefaultEdges:T,onEdgesChange:I}=t.getState();if(T)E([...C,...N]);else if(I){const K=N.map(U=>({item:U,type:"add"}));I(K)}},[]),p=_.useCallback(()=>{const{getNodes:j,edges:N=[],transform:C}=t.getState(),[E,T,I]=C;return{nodes:j().map(K=>({...K})),edges:N.map(K=>({...K})),viewport:{x:E,y:T,zoom:I}}},[]),g=_.useCallback(({nodes:j,edges:N})=>{const{nodeInternals:C,getNodes:E,edges:T,hasDefaultNodes:I,hasDefaultEdges:K,onNodesDelete:U,onEdgesDelete:J,onNodesChange:Y,onEdgesChange:se}=t.getState(),ce=(j||[]).map(z=>z.id),fe=(N||[]).map(z=>z.id),W=E().reduce((z,$)=>{const te=!ce.includes($.id)&&$.parentNode&&z.find(F=>F.id===$.parentNode);return(typeof $.deletable=="boolean"?$.deletable:!0)&&(ce.includes($.id)||te)&&z.push($),z},[]),P=T.filter(z=>typeof z.deletable=="boolean"?z.deletable:!0),A=P.filter(z=>fe.includes(z.id));if(W||A){const z=qb(W,P),$=[...A,...z],te=$.reduce((O,F)=>(O.includes(F.id)||O.push(F.id),O),[]);if((K||I)&&(K&&t.setState({edges:T.filter(O=>!te.includes(O.id))}),I&&(W.forEach(O=>{C.delete(O.id)}),t.setState({nodeInternals:new Map(C)}))),te.length>0&&(J==null||J($),se&&se(te.map(O=>({id:O,type:"remove"})))),W.length>0&&(U==null||U(W),Y)){const O=W.map(F=>({id:F.id,type:"remove"}));Y(O)}}},[]),w=_.useCallback(j=>{const N=CM(j),C=N?null:t.getState().nodeInternals.get(j.id);return!N&&!C?[null,null,N]:[N?j:zw(C),C,N]},[]),x=_.useCallback((j,N=!0,C)=>{const[E,T,I]=w(j);return E?(C||t.getState().getNodes()).filter(K=>{if(!I&&(K.id===T.id||!K.positionAbsolute))return!1;const U=zw(K),J=Up(U,E);return N&&J>0||J>=E.width*E.height}):[]},[]),S=_.useCallback((j,N,C=!0)=>{const[E]=w(j);if(!E)return!1;const T=Up(E,N);return C&&T>0||T>=E.width*E.height},[]);return _.useMemo(()=>({...e,getNodes:n,getNode:s,getEdges:o,getEdge:l,setNodes:u,setEdges:c,addNodes:f,addEdges:m,toObject:p,deleteElements:g,getIntersectingNodes:x,isNodeIntersecting:S}),[e,n,s,o,l,u,c,f,m,p,g,x,S])}const lR={actInsideInputWithModifier:!1};var cR=({deleteKeyCode:e,multiSelectionKeyCode:t})=>{const n=br(),{deleteElements:s}=Dg(),o=jf(e,lR),l=jf(t);_.useEffect(()=>{if(o){const{edges:u,getNodes:c}=n.getState(),f=c().filter(p=>p.selected),m=u.filter(p=>p.selected);s({nodes:f,edges:m}),n.setState({nodesSelectionActive:!1})}},[o]),_.useEffect(()=>{n.setState({multiSelectionActive:l})},[l])};function uR(e){const t=br();_.useEffect(()=>{let n;const s=()=>{var l,u;if(!e.current)return;const o=Ag(e.current);(o.height===0||o.width===0)&&((u=(l=t.getState()).onError)==null||u.call(l,"004",ua.error004())),t.setState({width:o.width||500,height:o.height||500})};return s(),window.addEventListener("resize",s),e.current&&(n=new ResizeObserver(()=>s()),n.observe(e.current)),()=>{window.removeEventListener("resize",s),n&&e.current&&n.unobserve(e.current)}},[])}const Fg={position:"absolute",width:"100%",height:"100%",top:0,left:0},dR=(e,t)=>e.x!==t.x||e.y!==t.y||e.zoom!==t.k,Wh=e=>({x:e.x,y:e.y,zoom:e.k}),au=(e,t)=>e.target.closest(`.${t}`),Jw=(e,t)=>t===2&&Array.isArray(e)&&e.includes(2),Xw=e=>{const t=e.ctrlKey&&wm()?10:1;return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*t},fR=e=>({d3Zoom:e.d3Zoom,d3Selection:e.d3Selection,d3ZoomHandler:e.d3ZoomHandler,userSelectionActive:e.userSelectionActive}),hR=({onMove:e,onMoveStart:t,onMoveEnd:n,onPaneContextMenu:s,zoomOnScroll:o=!0,zoomOnPinch:l=!0,panOnScroll:u=!1,panOnScrollSpeed:c=.5,panOnScrollMode:f=Xl.Free,zoomOnDoubleClick:m=!0,elementsSelectable:p,panOnDrag:g=!0,defaultViewport:w,translateExtent:x,minZoom:S,maxZoom:j,zoomActivationKeyCode:N,preventScrolling:C=!0,children:E,noWheelClassName:T,noPanClassName:I})=>{const K=_.useRef(),U=br(),J=_.useRef(!1),Y=_.useRef(!1),se=_.useRef(null),ce=_.useRef({x:0,y:0,zoom:0}),{d3Zoom:fe,d3Selection:W,d3ZoomHandler:P,userSelectionActive:A}=Ln(fR,Pr),z=jf(N),$=_.useRef(0),te=_.useRef(!1),O=_.useRef();return uR(se),_.useEffect(()=>{if(se.current){const F=se.current.getBoundingClientRect(),G=Ab().scaleExtent([S,j]).translateExtent(x),R=ji(se.current).call(G),Z=aa.translate(w.x,w.y).scale(Eu(w.zoom,S,j)),X=[[0,0],[F.width,F.height]],Q=G.constrain()(Z,X,x);G.transform(R,Q),G.wheelDelta(Xw),U.setState({d3Zoom:G,d3Selection:R,d3ZoomHandler:R.on("wheel.zoom"),transform:[Q.x,Q.y,Q.k],domNode:se.current.closest(".react-flow")})}},[]),_.useEffect(()=>{W&&fe&&(u&&!z&&!A?W.on("wheel.zoom",F=>{if(au(F,T))return!1;F.preventDefault(),F.stopImmediatePropagation();const G=W.property("__zoom").k||1,R=wm();if(F.ctrlKey&&l&&R){const Ne=Fi(F),Ue=Xw(F),We=G*Math.pow(2,Ue);fe.scaleTo(W,We,Ne,F);return}const Z=F.deltaMode===1?20:1;let X=f===Xl.Vertical?0:F.deltaX*Z,Q=f===Xl.Horizontal?0:F.deltaY*Z;!R&&F.shiftKey&&f!==Xl.Vertical&&(X=F.deltaY*Z,Q=0),fe.translateBy(W,-(X/G)*c,-(Q/G)*c,{internal:!0});const le=Wh(W.property("__zoom")),{onViewportChangeStart:ge,onViewportChange:pe,onViewportChangeEnd:ye}=U.getState();clearTimeout(O.current),te.current||(te.current=!0,t==null||t(F,le),ge==null||ge(le)),te.current&&(e==null||e(F,le),pe==null||pe(le),O.current=setTimeout(()=>{n==null||n(F,le),ye==null||ye(le),te.current=!1},150))},{passive:!1}):typeof P<"u"&&W.on("wheel.zoom",function(F,G){if(!C||au(F,T))return null;F.preventDefault(),P.call(this,F,G)},{passive:!1}))},[A,u,f,W,fe,P,z,l,C,T,t,e,n]),_.useEffect(()=>{fe&&fe.on("start",F=>{var Z,X;if(!F.sourceEvent||F.sourceEvent.internal)return null;$.current=(Z=F.sourceEvent)==null?void 0:Z.button;const{onViewportChangeStart:G}=U.getState(),R=Wh(F.transform);J.current=!0,ce.current=R,((X=F.sourceEvent)==null?void 0:X.type)==="mousedown"&&U.setState({paneDragging:!0}),G==null||G(R),t==null||t(F.sourceEvent,R)})},[fe,t]),_.useEffect(()=>{fe&&(A&&!J.current?fe.on("zoom",null):A||fe.on("zoom",F=>{var R;const{onViewportChange:G}=U.getState();if(U.setState({transform:[F.transform.x,F.transform.y,F.transform.k]}),Y.current=!!(s&&Jw(g,$.current??0)),(e||G)&&!((R=F.sourceEvent)!=null&&R.internal)){const Z=Wh(F.transform);G==null||G(Z),e==null||e(F.sourceEvent,Z)}}))},[A,fe,e,g,s]),_.useEffect(()=>{fe&&fe.on("end",F=>{if(!F.sourceEvent||F.sourceEvent.internal)return null;const{onViewportChangeEnd:G}=U.getState();if(J.current=!1,U.setState({paneDragging:!1}),s&&Jw(g,$.current??0)&&!Y.current&&s(F.sourceEvent),Y.current=!1,(n||G)&&dR(ce.current,F.transform)){const R=Wh(F.transform);ce.current=R,clearTimeout(K.current),K.current=setTimeout(()=>{G==null||G(R),n==null||n(F.sourceEvent,R)},u?150:0)}})},[fe,u,g,n,s]),_.useEffect(()=>{fe&&fe.filter(F=>{const G=z||o,R=l&&F.ctrlKey;if((g===!0||Array.isArray(g)&&g.includes(1))&&F.button===1&&F.type==="mousedown"&&(au(F,"react-flow__node")||au(F,"react-flow__edge")))return!0;if(!g&&!G&&!u&&!m&&!l||A||!m&&F.type==="dblclick"||au(F,T)&&F.type==="wheel"||au(F,I)&&(F.type!=="wheel"||u&&F.type==="wheel"&&!z)||!l&&F.ctrlKey&&F.type==="wheel"||!G&&!u&&!R&&F.type==="wheel"||!g&&(F.type==="mousedown"||F.type==="touchstart")||Array.isArray(g)&&!g.includes(F.button)&&(F.type==="mousedown"||F.type==="touchstart"))return!1;const Z=Array.isArray(g)&&g.includes(F.button)||!F.button||F.button<=1;return(!F.ctrlKey||F.type==="wheel")&&Z})},[A,fe,o,l,u,m,g,p,z]),ve.createElement("div",{className:"react-flow__renderer",ref:se,style:Fg},E)},mR=e=>({userSelectionActive:e.userSelectionActive,userSelectionRect:e.userSelectionRect});function _R(){const{userSelectionActive:e,userSelectionRect:t}=Ln(mR,Pr);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 Zw(e,t){const n=e.find(s=>s.id===t.parentNode);if(n){const s=t.position.x+t.width-n.width,o=t.position.y+t.height-n.height;if(s>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,s>0&&(n.style.width+=s),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 pR(e,t){if(e.some(s=>s.type==="reset"))return e.filter(s=>s.type==="reset").map(s=>s.item);const n=e.filter(s=>s.type==="add").map(s=>s.item);return t.reduce((s,o)=>{const l=e.filter(c=>c.id===o.id);if(l.length===0)return s.push(o),s;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&&Zw(s,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&&Zw(s,u);break}case"remove":return s}return s.push(u),s},n)}function gR(e,t){return pR(e,t)}const sl=(e,t)=>({id:e,type:"select",selected:t});function hu(e,t){return e.reduce((n,s)=>{const o=t.includes(s.id);return!s.selected&&o?(s.selected=!0,n.push(sl(s.id,!0))):s.selected&&!o&&(s.selected=!1,n.push(sl(s.id,!1))),n},[])}const Y_=(e,t)=>n=>{n.target===t.current&&(e==null||e(n))},yR=e=>({userSelectionActive:e.userSelectionActive,elementsSelectable:e.elementsSelectable,dragging:e.paneDragging}),a0=_.memo(({isSelecting:e,selectionMode:t=xf.Full,panOnDrag:n,onSelectionStart:s,onSelectionEnd:o,onPaneClick:l,onPaneContextMenu:u,onPaneScroll:c,onPaneMouseEnter:f,onPaneMouseMove:m,onPaneMouseLeave:p,children:g})=>{const w=_.useRef(null),x=br(),S=_.useRef(0),j=_.useRef(0),N=_.useRef(),{userSelectionActive:C,elementsSelectable:E,dragging:T}=Ln(yR,Pr),I=()=>{x.setState({userSelectionActive:!1,userSelectionRect:null}),S.current=0,j.current=0},K=P=>{l==null||l(P),x.getState().resetSelectedElements(),x.setState({nodesSelectionActive:!1})},U=P=>{if(Array.isArray(n)&&(n!=null&&n.includes(2))){P.preventDefault();return}u==null||u(P)},J=c?P=>c(P):void 0,Y=P=>{const{resetSelectedElements:A,domNode:z}=x.getState();if(N.current=z==null?void 0:z.getBoundingClientRect(),!E||!e||P.button!==0||P.target!==w.current||!N.current)return;const{x:$,y:te}=ol(P,N.current);A(),x.setState({userSelectionRect:{width:0,height:0,startX:$,startY:te,x:$,y:te}}),s==null||s(P)},se=P=>{const{userSelectionRect:A,nodeInternals:z,edges:$,transform:te,onNodesChange:O,onEdgesChange:F,nodeOrigin:G,getNodes:R}=x.getState();if(!e||!N.current||!A)return;x.setState({userSelectionActive:!0,nodesSelectionActive:!1});const Z=ol(P,N.current),X=A.startX??0,Q=A.startY??0,le={...A,x:Z.x<X?Z.x:X,y:Z.y<Q?Z.y:Q,width:Math.abs(Z.x-X),height:Math.abs(Z.y-Q)},ge=R(),pe=Wb(z,le,te,t===xf.Partial,!0,G),ye=qb(pe,$).map(Ue=>Ue.id),Ne=pe.map(Ue=>Ue.id);if(S.current!==Ne.length){S.current=Ne.length;const Ue=hu(ge,Ne);Ue.length&&(O==null||O(Ue))}if(j.current!==ye.length){j.current=ye.length;const Ue=hu($,ye);Ue.length&&(F==null||F(Ue))}x.setState({userSelectionRect:le})},ce=P=>{if(P.button!==0)return;const{userSelectionRect:A}=x.getState();!C&&A&&P.target===w.current&&(K==null||K(P)),x.setState({nodesSelectionActive:S.current>0}),I(),o==null||o(P)},fe=P=>{C&&(x.setState({nodesSelectionActive:S.current>0}),o==null||o(P)),I()},W=E&&(e||C);return ve.createElement("div",{className:Kr(["react-flow__pane",{dragging:T,selection:e}]),onClick:W?void 0:Y_(K,w),onContextMenu:Y_(U,w),onWheel:Y_(J,w),onMouseEnter:W?void 0:f,onMouseDown:W?Y:void 0,onMouseMove:W?se:m,onMouseUp:W?ce:void 0,onMouseLeave:W?fe:p,ref:w,style:Fg},g,ve.createElement(_R,null))});a0.displayName="Pane";function l0(e,t){if(!e.parentNode)return!1;const n=t.get(e.parentNode);return n?n.selected?!0:l0(n,t):!1}function Qw(e,t,n){let s=e;do{if(s!=null&&s.matches(t))return!0;if(s===n.current)return!1;s=s.parentElement}while(s);return!1}function wR(e,t,n,s){return Array.from(e.values()).filter(o=>(o.selected||o.id===s)&&(!o.parentNode||!l0(o,e))&&(o.draggable||t&&typeof o.draggable>"u")).map(o=>{var l,u;return{id:o.id,position:o.position||{x:0,y:0},positionAbsolute:o.positionAbsolute||{x:0,y:0},distance:{x:n.x-(((l=o.positionAbsolute)==null?void 0:l.x)??0),y:n.y-(((u=o.positionAbsolute)==null?void 0:u.y)??0)},delta:{x:0,y:0},extent:o.extent,parentNode:o.parentNode,width:o.width,height:o.height,expandParent:o.expandParent}})}function vR(e,t){return!t||t==="parent"?t:[t[0],[t[1][0]-(e.width||0),t[1][1]-(e.height||0)]]}function c0(e,t,n,s,o=[0,0],l){const u=vR(e,e.extent||s);let c=u;if(e.extent==="parent"&&!e.expandParent)if(e.parentNode&&e.width&&e.height){const p=n.get(e.parentNode),{x:g,y:w}=rc(p,o).positionAbsolute;c=p&&Si(g)&&Si(w)&&Si(p.width)&&Si(p.height)?[[g+e.width*o[0],w+e.height*o[1]],[g+p.width-e.width+e.width*o[0],w+p.height-e.height+e.height*o[1]]]:c}else l==null||l("005",ua.error005()),c=u;else if(e.extent&&e.parentNode&&e.extent!=="parent"){const p=n.get(e.parentNode),{x:g,y:w}=rc(p,o).positionAbsolute;c=[[e.extent[0][0]+g,e.extent[0][1]+w],[e.extent[1][0]+g,e.extent[1][1]+w]]}let f={x:0,y:0};if(e.parentNode){const p=n.get(e.parentNode);f=rc(p,o).positionAbsolute}const m=c&&c!=="parent"?Tg(t,c):t;return{position:{x:m.x-f.x,y:m.y-f.y},positionAbsolute:m}}function J_({nodeId:e,dragItems:t,nodeInternals:n}){const s=t.map(o=>({...n.get(o.id),position:o.position,positionAbsolute:o.positionAbsolute}));return[e?s.find(o=>o.id===e):s[0],s]}const ev=(e,t,n,s)=>{const o=t.querySelectorAll(e);if(!o||!o.length)return null;const l=Array.from(o),u=t.getBoundingClientRect(),c={x:u.width*s[0],y:u.height*s[1]};return l.map(f=>{const m=f.getBoundingClientRect();return{id:f.getAttribute("data-handleid"),position:f.getAttribute("data-handlepos"),x:(m.left-u.left-c.x)/n,y:(m.top-u.top-c.y)/n,...Ag(f)}})};function Xd(e,t,n){return n===void 0?n:s=>{const o=t().nodeInternals.get(e);o&&n(s,{...o})}}function Kp({id:e,store:t,unselect:n=!1,nodeRef:s}){const{addSelectedNodes:o,unselectNodesAndEdges:l,multiSelectionActive:u,nodeInternals:c,onError:f}=t.getState(),m=c.get(e);if(!m){f==null||f("012",ua.error012(e));return}t.setState({nodesSelectionActive:!1}),m.selected?(n||m.selected&&u)&&(l({nodes:[m],edges:[]}),requestAnimationFrame(()=>{var p;return(p=s==null?void 0:s.current)==null?void 0:p.blur()})):o([e])}function xR(){const e=br();return _.useCallback(({sourceEvent:n})=>{const{transform:s,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-s[0])/s[2],y:(c-s[1])/s[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 X_(e){return(t,n,s)=>e==null?void 0:e(t,s)}function u0({nodeRef:e,disabled:t=!1,noDragClassName:n,handleSelector:s,nodeId:o,isSelectable:l,selectNodesOnDrag:u}){const c=br(),[f,m]=_.useState(!1),p=_.useRef([]),g=_.useRef({x:null,y:null}),w=_.useRef(0),x=_.useRef(null),S=_.useRef({x:0,y:0}),j=_.useRef(null),N=_.useRef(!1),C=_.useRef(!1),E=xR();return _.useEffect(()=>{if(e!=null&&e.current){const T=ji(e.current),I=({x:J,y:Y})=>{const{nodeInternals:se,onNodeDrag:ce,onSelectionDrag:fe,updateNodePositions:W,nodeExtent:P,snapGrid:A,snapToGrid:z,nodeOrigin:$,onError:te}=c.getState();g.current={x:J,y:Y};let O=!1,F={x:0,y:0,x2:0,y2:0};if(p.current.length>1&&P){const R=Om(p.current,$);F=vf(R)}if(p.current=p.current.map(R=>{const Z={x:J-R.distance.x,y:Y-R.distance.y};z&&(Z.x=A[0]*Math.round(Z.x/A[0]),Z.y=A[1]*Math.round(Z.y/A[1]));const X=[[P[0][0],P[0][1]],[P[1][0],P[1][1]]];p.current.length>1&&P&&!R.extent&&(X[0][0]=R.positionAbsolute.x-F.x+P[0][0],X[1][0]=R.positionAbsolute.x+(R.width??0)-F.x2+P[1][0],X[0][1]=R.positionAbsolute.y-F.y+P[0][1],X[1][1]=R.positionAbsolute.y+(R.height??0)-F.y2+P[1][1]);const Q=c0(R,Z,se,X,$,te);return O=O||R.position.x!==Q.position.x||R.position.y!==Q.position.y,R.position=Q.position,R.positionAbsolute=Q.positionAbsolute,R}),!O)return;W(p.current,!0,!0),m(!0);const G=o?ce:X_(fe);if(G&&j.current){const[R,Z]=J_({nodeId:o,dragItems:p.current,nodeInternals:se});G(j.current,R,Z)}},K=()=>{if(!x.current)return;const[J,Y]=Mb(S.current,x.current);if(J!==0||Y!==0){const{transform:se,panBy:ce}=c.getState();g.current.x=(g.current.x??0)-J/se[2],g.current.y=(g.current.y??0)-Y/se[2],ce({x:J,y:Y})&&I(g.current)}w.current=requestAnimationFrame(K)},U=J=>{var $;const{nodeInternals:Y,multiSelectionActive:se,nodesDraggable:ce,unselectNodesAndEdges:fe,onNodeDragStart:W,onSelectionDragStart:P}=c.getState();C.current=!0;const A=o?W:X_(P);(!u||!l)&&!se&&o&&(($=Y.get(o))!=null&&$.selected||fe()),o&&l&&u&&Kp({id:o,store:c,nodeRef:e});const z=E(J);if(g.current=z,p.current=wR(Y,ce,z,o),A&&p.current){const[te,O]=J_({nodeId:o,dragItems:p.current,nodeInternals:Y});A(J.sourceEvent,te,O)}};if(t)T.on(".drag",null);else{const J=TA().on("start",Y=>{const{domNode:se,nodeDragThreshold:ce}=c.getState();ce===0&&U(Y);const fe=E(Y);g.current=fe,x.current=(se==null?void 0:se.getBoundingClientRect())||null,S.current=ol(Y.sourceEvent,x.current)}).on("drag",Y=>{var W,P;const se=E(Y),{autoPanOnNodeDrag:ce,nodeDragThreshold:fe}=c.getState();if(!N.current&&C.current&&ce&&(N.current=!0,K()),!C.current){const A=se.xSnapped-(((W=g==null?void 0:g.current)==null?void 0:W.x)??0),z=se.ySnapped-(((P=g==null?void 0:g.current)==null?void 0:P.y)??0);Math.sqrt(A*A+z*z)>fe&&U(Y)}(g.current.x!==se.xSnapped||g.current.y!==se.ySnapped)&&p.current&&C.current&&(j.current=Y.sourceEvent,S.current=ol(Y.sourceEvent,x.current),I(se))}).on("end",Y=>{if(C.current&&(m(!1),N.current=!1,C.current=!1,cancelAnimationFrame(w.current),p.current)){const{updateNodePositions:se,nodeInternals:ce,onNodeDragStop:fe,onSelectionDragStop:W}=c.getState(),P=o?fe:X_(W);if(se(p.current,!1,!1),P){const[A,z]=J_({nodeId:o,dragItems:p.current,nodeInternals:ce});P(Y.sourceEvent,A,z)}}}).filter(Y=>{const se=Y.target;return!Y.button&&(!n||!Qw(se,`.${n}`,e))&&(!s||Qw(se,s,e))});return T.call(J),()=>{T.on(".drag",null)}}}},[e,t,n,s,l,c,o,u,E]),f}function d0(){const e=br();return _.useCallback(n=>{const{nodeInternals:s,nodeExtent:o,updateNodePositions:l,getNodes:u,snapToGrid:c,snapGrid:f,onError:m,nodesDraggable:p}=e.getState(),g=u().filter(E=>E.selected&&(E.draggable||p&&typeof E.draggable>"u")),w=c?f[0]:5,x=c?f[1]:5,S=n.isShiftPressed?4:1,j=n.x*w*S,N=n.y*x*S,C=g.map(E=>{if(E.positionAbsolute){const T={x:E.positionAbsolute.x+j,y:E.positionAbsolute.y+N};c&&(T.x=f[0]*Math.round(T.x/f[0]),T.y=f[1]*Math.round(T.y/f[1]));const{positionAbsolute:I,position:K}=c0(E,T,s,o,void 0,m);E.position=K,E.positionAbsolute=I}return E});l(C,!0,!1)},[])}const vu={ArrowUp:{x:0,y:-1},ArrowDown:{x:0,y:1},ArrowLeft:{x:-1,y:0},ArrowRight:{x:1,y:0}};var Zd=e=>{const t=({id:n,type:s,data:o,xPos:l,yPos:u,xPosOrigin:c,yPosOrigin:f,selected:m,onClick:p,onMouseEnter:g,onMouseMove:w,onMouseLeave:x,onContextMenu:S,onDoubleClick:j,style:N,className:C,isDraggable:E,isSelectable:T,isConnectable:I,isFocusable:K,selectNodesOnDrag:U,sourcePosition:J,targetPosition:Y,hidden:se,resizeObserver:ce,dragHandle:fe,zIndex:W,isParent:P,noDragClassName:A,noPanClassName:z,initialized:$,disableKeyboardA11y:te,ariaLabel:O,rfId:F,hasHandleBounds:G})=>{const R=br(),Z=_.useRef(null),X=_.useRef(J),Q=_.useRef(Y),le=_.useRef(s),ge=T||E||p||g||w||x,pe=d0(),ye=Xd(n,R.getState,g),Ne=Xd(n,R.getState,w),Ue=Xd(n,R.getState,x),We=Xd(n,R.getState,S),pt=Xd(n,R.getState,j),Fe=Ke=>{const{nodeDragThreshold:Se}=R.getState();if(T&&(!U||!E||Se>0)&&Kp({id:n,store:R,nodeRef:Z}),p){const Re=R.getState().nodeInternals.get(n);Re&&p(Ke,{...Re})}},tt=Ke=>{if(!Wp(Ke))if(Pb.includes(Ke.key)&&T){const Se=Ke.key==="Escape";Kp({id:n,store:R,unselect:Se,nodeRef:Z})}else!te&&E&&m&&Object.prototype.hasOwnProperty.call(vu,Ke.key)&&(R.setState({ariaLiveMessage:`Moved selected node ${Ke.key.replace("Arrow","").toLowerCase()}. New position, x: ${~~l}, y: ${~~u}`}),pe({x:vu[Ke.key].x,y:vu[Ke.key].y,isShiftPressed:Ke.shiftKey}))};_.useEffect(()=>()=>{Z.current&&(ce==null||ce.unobserve(Z.current))},[]),_.useEffect(()=>{if(Z.current&&!se){const Ke=Z.current;(!$||!G)&&(ce==null||ce.unobserve(Ke),ce==null||ce.observe(Ke))}},[se,$,G]),_.useEffect(()=>{const Ke=le.current!==s,Se=X.current!==J,Re=Q.current!==Y;Z.current&&(Ke||Se||Re)&&(Ke&&(le.current=s),Se&&(X.current=J),Re&&(Q.current=Y),R.getState().updateNodeDimensions([{id:n,nodeElement:Z.current,forceUpdate:!0}]))},[n,s,J,Y]);const lt=u0({nodeRef:Z,disabled:se||!E,noDragClassName:A,handleSelector:fe,nodeId:n,isSelectable:T,selectNodesOnDrag:U});return se?null:ve.createElement("div",{className:Kr(["react-flow__node",`react-flow__node-${s}`,{[z]:E},C,{selected:m,selectable:T,parent:P,dragging:lt}]),ref:Z,style:{zIndex:W,transform:`translate(${c}px,${f}px)`,pointerEvents:ge?"all":"none",visibility:$?"visible":"hidden",...N},"data-id":n,"data-testid":`rf__node-${n}`,onMouseEnter:ye,onMouseMove:Ne,onMouseLeave:Ue,onContextMenu:We,onClick:Fe,onDoubleClick:pt,onKeyDown:K?tt:void 0,tabIndex:K?0:void 0,role:K?"button":void 0,"aria-describedby":te?void 0:`${n0}-${F}`,"aria-label":O},ve.createElement(LM,{value:n},ve.createElement(e,{id:n,data:o,type:s,xPos:l,yPos:u,selected:m,isConnectable:I,sourcePosition:J,targetPosition:Y,dragging:lt,dragHandle:fe,zIndex:W})))};return t.displayName="NodeWrapper",_.memo(t)};const bR=e=>{const t=e.getNodes().filter(n=>n.selected);return{...Om(t,e.nodeOrigin),transformString:`translate(${e.transform[0]}px,${e.transform[1]}px) scale(${e.transform[2]})`,userSelectionActive:e.userSelectionActive}};function jR({onSelectionContextMenu:e,noPanClassName:t,disableKeyboardA11y:n}){const s=br(),{width:o,height:l,x:u,y:c,transformString:f,userSelectionActive:m}=Ln(bR,Pr),p=d0(),g=_.useRef(null);if(_.useEffect(()=>{var S;n||(S=g.current)==null||S.focus({preventScroll:!0})},[n]),u0({nodeRef:g}),m||!o||!l)return null;const w=e?S=>{const j=s.getState().getNodes().filter(N=>N.selected);e(S,j)}:void 0,x=S=>{Object.prototype.hasOwnProperty.call(vu,S.key)&&p({x:vu[S.key].x,y:vu[S.key].y,isShiftPressed:S.shiftKey})};return ve.createElement("div",{className:Kr(["react-flow__nodesselection","react-flow__container",t]),style:{transform:f}},ve.createElement("div",{ref:g,className:"react-flow__nodesselection-rect",onContextMenu:w,tabIndex:n?void 0:-1,onKeyDown:n?void 0:x,style:{width:o,height:l,top:c,left:u}}))}var SR=_.memo(jR);const kR=e=>e.nodesSelectionActive,f0=({children:e,onPaneClick:t,onPaneMouseEnter:n,onPaneMouseMove:s,onPaneMouseLeave:o,onPaneContextMenu:l,onPaneScroll:u,deleteKeyCode:c,onMove:f,onMoveStart:m,onMoveEnd:p,selectionKeyCode:g,selectionOnDrag:w,selectionMode:x,onSelectionStart:S,onSelectionEnd:j,multiSelectionKeyCode:N,panActivationKeyCode:C,zoomActivationKeyCode:E,elementsSelectable:T,zoomOnScroll:I,zoomOnPinch:K,panOnScroll:U,panOnScrollSpeed:J,panOnScrollMode:Y,zoomOnDoubleClick:se,panOnDrag:ce,defaultViewport:fe,translateExtent:W,minZoom:P,maxZoom:A,preventScrolling:z,onSelectionContextMenu:$,noWheelClassName:te,noPanClassName:O,disableKeyboardA11y:F})=>{const G=Ln(kR),R=jf(g),Z=jf(C),X=Z||ce,Q=Z||U,le=R||w&&X!==!0;return cR({deleteKeyCode:c,multiSelectionKeyCode:N}),ve.createElement(hR,{onMove:f,onMoveStart:m,onMoveEnd:p,onPaneContextMenu:l,elementsSelectable:T,zoomOnScroll:I,zoomOnPinch:K,panOnScroll:Q,panOnScrollSpeed:J,panOnScrollMode:Y,zoomOnDoubleClick:se,panOnDrag:!R&&X,defaultViewport:fe,translateExtent:W,minZoom:P,maxZoom:A,zoomActivationKeyCode:E,preventScrolling:z,noWheelClassName:te,noPanClassName:O},ve.createElement(a0,{onSelectionStart:S,onSelectionEnd:j,onPaneClick:t,onPaneMouseEnter:n,onPaneMouseMove:s,onPaneMouseLeave:o,onPaneContextMenu:l,onPaneScroll:u,panOnDrag:X,isSelecting:!!le,selectionMode:x},e,G&&ve.createElement(SR,{onSelectionContextMenu:$,noPanClassName:O,disableKeyboardA11y:F})))};f0.displayName="FlowRenderer";var NR=_.memo(f0);function CR(e){return Ln(_.useCallback(n=>e?Wb(n.nodeInternals,{x:0,y:0,width:n.width,height:n.height},n.transform,!0):n.getNodes(),[e]))}function ER(e){const t={input:Zd(e.input||Zb),default:Zd(e.default||Gp),output:Zd(e.output||e0),group:Zd(e.group||Og)},n={},s=Object.keys(e).filter(o=>!["input","default","output","group"].includes(o)).reduce((o,l)=>(o[l]=Zd(e[l]||Gp),o),n);return{...t,...s}}const $R=({x:e,y:t,width:n,height:s,origin:o})=>!n||!s?{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-s*o[1]},AR=e=>({nodesDraggable:e.nodesDraggable,nodesConnectable:e.nodesConnectable,nodesFocusable:e.nodesFocusable,elementsSelectable:e.elementsSelectable,updateNodeDimensions:e.updateNodeDimensions,onError:e.onError}),h0=e=>{const{nodesDraggable:t,nodesConnectable:n,nodesFocusable:s,elementsSelectable:o,updateNodeDimensions:l,onError:u}=Ln(AR,Pr),c=CR(e.onlyRenderVisibleElements),f=_.useRef(),m=_.useMemo(()=>{if(typeof ResizeObserver>"u")return null;const p=new ResizeObserver(g=>{const w=g.map(x=>({id:x.target.getAttribute("data-id"),nodeElement:x.target,forceUpdate:!0}));l(w)});return f.current=p,p},[]);return _.useEffect(()=>()=>{var p;(p=f==null?void 0:f.current)==null||p.disconnect()},[]),ve.createElement("div",{className:"react-flow__nodes",style:Fg},c.map(p=>{var K,U,J;let g=p.type||"default";e.nodeTypes[g]||(u==null||u("003",ua.error003(g)),g="default");const w=e.nodeTypes[g]||e.nodeTypes.default,x=!!(p.draggable||t&&typeof p.draggable>"u"),S=!!(p.selectable||o&&typeof p.selectable>"u"),j=!!(p.connectable||n&&typeof p.connectable>"u"),N=!!(p.focusable||s&&typeof p.focusable>"u"),C=e.nodeExtent?Tg(p.positionAbsolute,e.nodeExtent):p.positionAbsolute,E=(C==null?void 0:C.x)??0,T=(C==null?void 0:C.y)??0,I=$R({x:E,y:T,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:g,data:p.data,sourcePosition:p.sourcePosition||_t.Bottom,targetPosition:p.targetPosition||_t.Top,hidden:p.hidden,xPos:E,yPos:T,xPosOrigin:I.x,yPosOrigin:I.y,selectNodesOnDrag:e.selectNodesOnDrag,onClick:e.onNodeClick,onMouseEnter:e.onNodeMouseEnter,onMouseMove:e.onNodeMouseMove,onMouseLeave:e.onNodeMouseLeave,onContextMenu:e.onNodeContextMenu,onDoubleClick:e.onNodeDoubleClick,selected:!!p.selected,isDraggable:x,isSelectable:S,isConnectable:j,isFocusable:N,resizeObserver:m,dragHandle:p.dragHandle,zIndex:((K=p[fr])==null?void 0:K.z)??0,isParent:!!((U=p[fr])!=null&&U.isParent),noDragClassName:e.noDragClassName,noPanClassName:e.noPanClassName,initialized:!!p.width&&!!p.height,rfId:e.rfId,disableKeyboardA11y:e.disableKeyboardA11y,ariaLabel:p.ariaLabel,hasHandleBounds:!!((J=p[fr])!=null&&J.handleBounds)})}))};h0.displayName="NodeRenderer";var TR=_.memo(h0);const MR=(e,t,n)=>n===_t.Left?e-t:n===_t.Right?e+t:e,RR=(e,t,n)=>n===_t.Top?e-t:n===_t.Bottom?e+t:e,tv="react-flow__edgeupdater",nv=({position:e,centerX:t,centerY:n,radius:s=10,onMouseDown:o,onMouseEnter:l,onMouseOut:u,type:c})=>ve.createElement("circle",{onMouseDown:o,onMouseEnter:l,onMouseOut:u,className:Kr([tv,`${tv}-${c}`]),cx:MR(t,s,e),cy:RR(n,s,e),r:s,stroke:"transparent",fill:"transparent"}),LR=()=>!0;var lu=e=>{const t=({id:n,className:s,type:o,data:l,onClick:u,onEdgeDoubleClick:c,selected:f,animated:m,label:p,labelStyle:g,labelShowBg:w,labelBgStyle:x,labelBgPadding:S,labelBgBorderRadius:j,style:N,source:C,target:E,sourceX:T,sourceY:I,targetX:K,targetY:U,sourcePosition:J,targetPosition:Y,elementsSelectable:se,hidden:ce,sourceHandleId:fe,targetHandleId:W,onContextMenu:P,onMouseEnter:A,onMouseMove:z,onMouseLeave:$,edgeUpdaterRadius:te,onEdgeUpdate:O,onEdgeUpdateStart:F,onEdgeUpdateEnd:G,markerEnd:R,markerStart:Z,rfId:X,ariaLabel:Q,isFocusable:le,isUpdatable:ge,pathOptions:pe,interactionWidth:ye})=>{const Ne=_.useRef(null),[Ue,We]=_.useState(!1),[pt,Fe]=_.useState(!1),tt=br(),lt=_.useMemo(()=>`url('#${Hp(Z,X)}')`,[Z,X]),Ke=_.useMemo(()=>`url('#${Hp(R,X)}')`,[R,X]);if(ce)return null;const Se=Pt=>{var wn;const{edges:pn,addSelectedEdges:Bn,unselectNodesAndEdges:$n,multiSelectionActive:gn}=tt.getState(),In=pn.find(jr=>jr.id===n);In&&(se&&(tt.setState({nodesSelectionActive:!1}),In.selected&&gn?($n({nodes:[],edges:[In]}),(wn=Ne.current)==null||wn.blur()):Bn([n])),u&&u(Pt,In))},Re=Jd(n,tt.getState,c),ht=Jd(n,tt.getState,P),xe=Jd(n,tt.getState,A),Ie=Jd(n,tt.getState,z),qe=Jd(n,tt.getState,$),zt=(Pt,pn)=>{if(Pt.button!==0)return;const{edges:Bn,isValidConnection:$n}=tt.getState(),gn=pn?E:C,In=(pn?W:fe)||null,wn=pn?"target":"source",jr=$n||LR,Kn=pn,Sr=Bn.find(ae=>ae.id===n);Fe(!0),F==null||F(Pt,Sr,wn);const Ns=ae=>{Fe(!1),G==null||G(ae,Sr,wn)};Kb({event:Pt,handleId:In,nodeId:gn,onConnect:ae=>O==null?void 0:O(Sr,ae),isTarget:Kn,getState:tt.getState,setState:tt.setState,isValidConnection:jr,edgeUpdaterType:wn,onEdgeUpdateEnd:Ns})},en=Pt=>zt(Pt,!0),bn=Pt=>zt(Pt,!1),Wt=()=>We(!0),It=()=>We(!1),kn=!se&&!u,nr=Pt=>{var pn;if(Pb.includes(Pt.key)&&se){const{unselectNodesAndEdges:Bn,addSelectedEdges:$n,edges:gn}=tt.getState();Pt.key==="Escape"?((pn=Ne.current)==null||pn.blur(),Bn({edges:[gn.find(wn=>wn.id===n)]})):$n([n])}};return ve.createElement("g",{className:Kr(["react-flow__edge",`react-flow__edge-${o}`,s,{selected:f,animated:m,inactive:kn,updating:Ue}]),onClick:Se,onDoubleClick:Re,onContextMenu:ht,onMouseEnter:xe,onMouseMove:Ie,onMouseLeave:qe,onKeyDown:le?nr:void 0,tabIndex:le?0:void 0,role:le?"button":"img","data-testid":`rf__edge-${n}`,"aria-label":Q===null?void 0:Q||`Edge from ${C} to ${E}`,"aria-describedby":le?`${r0}-${X}`:void 0,ref:Ne},!pt&&ve.createElement(e,{id:n,source:C,target:E,selected:f,animated:m,label:p,labelStyle:g,labelShowBg:w,labelBgStyle:x,labelBgPadding:S,labelBgBorderRadius:j,data:l,style:N,sourceX:T,sourceY:I,targetX:K,targetY:U,sourcePosition:J,targetPosition:Y,sourceHandleId:fe,targetHandleId:W,markerStart:lt,markerEnd:Ke,pathOptions:pe,interactionWidth:ye}),ge&&ve.createElement(ve.Fragment,null,(ge==="source"||ge===!0)&&ve.createElement(nv,{position:J,centerX:T,centerY:I,radius:te,onMouseDown:en,onMouseEnter:Wt,onMouseOut:It,type:"source"}),(ge==="target"||ge===!0)&&ve.createElement(nv,{position:Y,centerX:K,centerY:U,radius:te,onMouseDown:bn,onMouseEnter:Wt,onMouseOut:It,type:"target"})))};return t.displayName="EdgeWrapper",_.memo(t)};function IR(e){const t={default:lu(e.default||vm),straight:lu(e.bezier||Lg),step:lu(e.step||Rg),smoothstep:lu(e.step||Pm),simplebezier:lu(e.simplebezier||Mg)},n={},s=Object.keys(e).filter(o=>!["default","bezier"].includes(o)).reduce((o,l)=>(o[l]=lu(e[l]||vm),o),n);return{...t,...s}}function rv(e,t,n=null){const s=((n==null?void 0:n.x)||0)+t.x,o=((n==null?void 0:n.y)||0)+t.y,l=(n==null?void 0:n.width)||t.width,u=(n==null?void 0:n.height)||t.height;switch(e){case _t.Top:return{x:s+l/2,y:o};case _t.Right:return{x:s+l,y:o+u/2};case _t.Bottom:return{x:s+l/2,y:o+u};case _t.Left:return{x:s,y:o+u/2}}}function sv(e,t){return e?e.length===1||!t?e[0]:t&&e.find(n=>n.id===t)||null:null}const PR=(e,t,n,s,o,l)=>{const u=rv(n,e,t),c=rv(l,s,o);return{sourceX:u.x,sourceY:u.y,targetX:c.x,targetY:c.y}};function OR({sourcePos:e,targetPos:t,sourceWidth:n,sourceHeight:s,targetWidth:o,targetHeight:l,width:u,height:c,transform:f}){const m={x:Math.min(e.x,t.x),y:Math.min(e.y,t.y),x2:Math.max(e.x+n,t.x+o),y2:Math.max(e.y+s,t.y+l)};m.x===m.x2&&(m.x2+=1),m.y===m.y2&&(m.y2+=1);const p=vf({x:(0-f[0])/f[2],y:(0-f[1])/f[2],width:u/f[2],height:c/f[2]}),g=Math.max(0,Math.min(p.x2,m.x2)-Math.max(p.x,m.x)),w=Math.max(0,Math.min(p.y2,m.y2)-Math.max(p.y,m.y));return Math.ceil(g*w)>0}function iv(e){var s,o,l,u,c;const t=((s=e==null?void 0:e[fr])==null?void 0:s.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 DR=[{level:0,isMaxLevel:!0,edges:[]}];function FR(e,t,n=!1){let s=-1;const o=e.reduce((u,c)=>{var p,g;const f=Si(c.zIndex);let m=f?c.zIndex:0;if(n){const w=t.get(c.target),x=t.get(c.source),S=c.selected||(w==null?void 0:w.selected)||(x==null?void 0:x.selected),j=Math.max(((p=x==null?void 0:x[fr])==null?void 0:p.z)||0,((g=w==null?void 0:w[fr])==null?void 0:g.z)||0,1e3);m=(f?c.zIndex:0)+(S?j:0)}return u[m]?u[m].push(c):u[m]=[c],s=m>s?m:s,u},{}),l=Object.entries(o).map(([u,c])=>{const f=+u;return{edges:c,level:f,isMaxLevel:f===s}});return l.length===0?DR:l}function zR(e,t,n){const s=Ln(_.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)&&OR({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 FR(s,t,n)}const BR=({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"}),UR=({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"}),ov={[bf.Arrow]:BR,[bf.ArrowClosed]:UR};function WR(e){const t=br();return _.useMemo(()=>{var o,l;return Object.prototype.hasOwnProperty.call(ov,e)?ov[e]:((l=(o=t.getState()).onError)==null||l.call(o,"009",ua.error009(e)),null)},[e])}const qR=({id:e,type:t,color:n,width:s=12.5,height:o=12.5,markerUnits:l="strokeWidth",strokeWidth:u,orient:c="auto-start-reverse"})=>{const f=WR(t);return f?ve.createElement("marker",{className:"react-flow__arrowhead",id:e,markerWidth:`${s}`,markerHeight:`${o}`,viewBox:"-10 -10 20 20",markerUnits:l,orient:c,refX:"0",refY:"0"},ve.createElement(f,{color:n,strokeWidth:u})):null},HR=({defaultColor:e,rfId:t})=>n=>{const s=[];return n.edges.reduce((o,l)=>([l.markerStart,l.markerEnd].forEach(u=>{if(u&&typeof u=="object"){const c=Hp(u,t);s.includes(c)||(o.push({id:c,color:u.color||e,...u}),s.push(c))}}),o),[]).sort((o,l)=>o.id.localeCompare(l.id))},m0=({defaultColor:e,rfId:t})=>{const n=Ln(_.useCallback(HR({defaultColor:e,rfId:t}),[e,t]),(s,o)=>!(s.length!==o.length||s.some((l,u)=>l.id!==o[u].id)));return ve.createElement("defs",null,n.map(s=>ve.createElement(qR,{id:s.id,key:s.id,type:s.type,color:s.color,width:s.width,height:s.height,markerUnits:s.markerUnits,strokeWidth:s.strokeWidth,orient:s.orient})))};m0.displayName="MarkerDefinitions";var VR=_.memo(m0);const GR=e=>({nodesConnectable:e.nodesConnectable,edgesFocusable:e.edgesFocusable,edgesUpdatable:e.edgesUpdatable,elementsSelectable:e.elementsSelectable,width:e.width,height:e.height,connectionMode:e.connectionMode,nodeInternals:e.nodeInternals,onError:e.onError}),_0=({defaultMarkerColor:e,onlyRenderVisibleElements:t,elevateEdgesOnSelect:n,rfId:s,edgeTypes:o,noPanClassName:l,onEdgeUpdate:u,onEdgeContextMenu:c,onEdgeMouseEnter:f,onEdgeMouseMove:m,onEdgeMouseLeave:p,onEdgeClick:g,edgeUpdaterRadius:w,onEdgeDoubleClick:x,onEdgeUpdateStart:S,onEdgeUpdateEnd:j,children:N})=>{const{edgesFocusable:C,edgesUpdatable:E,elementsSelectable:T,width:I,height:K,connectionMode:U,nodeInternals:J,onError:Y}=Ln(GR,Pr),se=zR(t,J,n);return I?ve.createElement(ve.Fragment,null,se.map(({level:ce,edges:fe,isMaxLevel:W})=>ve.createElement("svg",{key:ce,style:{zIndex:ce},width:I,height:K,className:"react-flow__edges react-flow__container"},W&&ve.createElement(VR,{defaultColor:e,rfId:s}),ve.createElement("g",null,fe.map(P=>{const[A,z,$]=iv(J.get(P.source)),[te,O,F]=iv(J.get(P.target));if(!$||!F)return null;let G=P.type||"default";o[G]||(Y==null||Y("011",ua.error011(G)),G="default");const R=o[G]||o.default,Z=U===cc.Strict?O.target:(O.target??[]).concat(O.source??[]),X=sv(z.source,P.sourceHandle),Q=sv(Z,P.targetHandle),le=(X==null?void 0:X.position)||_t.Bottom,ge=(Q==null?void 0:Q.position)||_t.Top,pe=!!(P.focusable||C&&typeof P.focusable>"u"),ye=typeof u<"u"&&(P.updatable||E&&typeof P.updatable>"u");if(!X||!Q)return Y==null||Y("008",ua.error008(X,P)),null;const{sourceX:Ne,sourceY:Ue,targetX:We,targetY:pt}=PR(A,X,le,te,Q,ge);return ve.createElement(R,{key:P.id,id:P.id,className:Kr([P.className,l]),type:G,data:P.data,selected:!!P.selected,animated:!!P.animated,hidden:!!P.hidden,label:P.label,labelStyle:P.labelStyle,labelShowBg:P.labelShowBg,labelBgStyle:P.labelBgStyle,labelBgPadding:P.labelBgPadding,labelBgBorderRadius:P.labelBgBorderRadius,style:P.style,source:P.source,target:P.target,sourceHandleId:P.sourceHandle,targetHandleId:P.targetHandle,markerEnd:P.markerEnd,markerStart:P.markerStart,sourceX:Ne,sourceY:Ue,targetX:We,targetY:pt,sourcePosition:le,targetPosition:ge,elementsSelectable:T,onEdgeUpdate:u,onContextMenu:c,onMouseEnter:f,onMouseMove:m,onMouseLeave:p,onClick:g,edgeUpdaterRadius:w,onEdgeDoubleClick:x,onEdgeUpdateStart:S,onEdgeUpdateEnd:j,rfId:s,ariaLabel:P.ariaLabel,isFocusable:pe,isUpdatable:ye,pathOptions:"pathOptions"in P?P.pathOptions:void 0,interactionWidth:P.interactionWidth})})))),N):null};_0.displayName="EdgeRenderer";var KR=_.memo(_0);const YR=e=>`translate(${e.transform[0]}px,${e.transform[1]}px) scale(${e.transform[2]})`;function JR({children:e}){const t=Ln(YR);return ve.createElement("div",{className:"react-flow__viewport react-flow__container",style:{transform:t}},e)}function XR(e){const t=Dg(),n=_.useRef(!1);_.useEffect(()=>{!n.current&&t.viewportInitialized&&e&&(setTimeout(()=>e(t),1),n.current=!0)},[e,t.viewportInitialized])}const ZR={[_t.Left]:_t.Right,[_t.Right]:_t.Left,[_t.Top]:_t.Bottom,[_t.Bottom]:_t.Top},p0=({nodeId:e,handleType:t,style:n,type:s=il.Bezier,CustomComponent:o,connectionStatus:l})=>{var U,J,Y;const{fromNode:u,handleId:c,toX:f,toY:m,connectionMode:p}=Ln(_.useCallback(se=>({fromNode:se.nodeInternals.get(e),handleId:se.connectionHandleId,toX:(se.connectionPosition.x-se.transform[0])/se.transform[2],toY:(se.connectionPosition.y-se.transform[1])/se.transform[2],connectionMode:se.connectionMode}),[e]),Pr),g=(U=u==null?void 0:u[fr])==null?void 0:U.handleBounds;let w=g==null?void 0:g[t];if(p===cc.Loose&&(w=w||(g==null?void 0:g[t==="source"?"target":"source"])),!u||!w)return null;const x=c?w.find(se=>se.id===c):w[0],S=x?x.x+x.width/2:(u.width??0)/2,j=x?x.y+x.height/2:u.height??0,N=(((J=u.positionAbsolute)==null?void 0:J.x)??0)+S,C=(((Y=u.positionAbsolute)==null?void 0:Y.y)??0)+j,E=x==null?void 0:x.position,T=E?ZR[E]:null;if(!E||!T)return null;if(o)return ve.createElement(o,{connectionLineType:s,connectionLineStyle:n,fromNode:u,fromHandle:x,fromX:N,fromY:C,toX:f,toY:m,fromPosition:E,toPosition:T,connectionStatus:l});let I="";const K={sourceX:N,sourceY:C,sourcePosition:E,targetX:f,targetY:m,targetPosition:T};return s===il.Bezier?[I]=Bb(K):s===il.Step?[I]=qp({...K,borderRadius:0}):s===il.SmoothStep?[I]=qp(K):s===il.SimpleBezier?[I]=zb(K):I=`M${N},${C} ${f},${m}`,ve.createElement("path",{d:I,fill:"none",className:"react-flow__connection-path",style:n})};p0.displayName="ConnectionLine";const QR=e=>({nodeId:e.connectionNodeId,handleType:e.connectionHandleType,nodesConnectable:e.nodesConnectable,connectionStatus:e.connectionStatus,width:e.width,height:e.height});function e3({containerStyle:e,style:t,type:n,component:s}){const{nodeId:o,handleType:l,nodesConnectable:u,width:c,height:f,connectionStatus:m}=Ln(QR,Pr);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:Kr(["react-flow__connection",m])},ve.createElement(p0,{nodeId:o,handleType:l,style:t,type:n,CustomComponent:s,connectionStatus:m})))}function av(e,t){return _.useRef(null),br(),_.useMemo(()=>t(e),[e])}const g0=({nodeTypes:e,edgeTypes:t,onMove:n,onMoveStart:s,onMoveEnd:o,onInit:l,onNodeClick:u,onEdgeClick:c,onNodeDoubleClick:f,onEdgeDoubleClick:m,onNodeMouseEnter:p,onNodeMouseMove:g,onNodeMouseLeave:w,onNodeContextMenu:x,onSelectionContextMenu:S,onSelectionStart:j,onSelectionEnd:N,connectionLineType:C,connectionLineStyle:E,connectionLineComponent:T,connectionLineContainerStyle:I,selectionKeyCode:K,selectionOnDrag:U,selectionMode:J,multiSelectionKeyCode:Y,panActivationKeyCode:se,zoomActivationKeyCode:ce,deleteKeyCode:fe,onlyRenderVisibleElements:W,elementsSelectable:P,selectNodesOnDrag:A,defaultViewport:z,translateExtent:$,minZoom:te,maxZoom:O,preventScrolling:F,defaultMarkerColor:G,zoomOnScroll:R,zoomOnPinch:Z,panOnScroll:X,panOnScrollSpeed:Q,panOnScrollMode:le,zoomOnDoubleClick:ge,panOnDrag:pe,onPaneClick:ye,onPaneMouseEnter:Ne,onPaneMouseMove:Ue,onPaneMouseLeave:We,onPaneScroll:pt,onPaneContextMenu:Fe,onEdgeUpdate:tt,onEdgeContextMenu:lt,onEdgeMouseEnter:Ke,onEdgeMouseMove:Se,onEdgeMouseLeave:Re,edgeUpdaterRadius:ht,onEdgeUpdateStart:xe,onEdgeUpdateEnd:Ie,noDragClassName:qe,noWheelClassName:zt,noPanClassName:en,elevateEdgesOnSelect:bn,disableKeyboardA11y:Wt,nodeOrigin:It,nodeExtent:kn,rfId:nr})=>{const Pt=av(e,ER),pn=av(t,IR);return XR(l),ve.createElement(NR,{onPaneClick:ye,onPaneMouseEnter:Ne,onPaneMouseMove:Ue,onPaneMouseLeave:We,onPaneContextMenu:Fe,onPaneScroll:pt,deleteKeyCode:fe,selectionKeyCode:K,selectionOnDrag:U,selectionMode:J,onSelectionStart:j,onSelectionEnd:N,multiSelectionKeyCode:Y,panActivationKeyCode:se,zoomActivationKeyCode:ce,elementsSelectable:P,onMove:n,onMoveStart:s,onMoveEnd:o,zoomOnScroll:R,zoomOnPinch:Z,zoomOnDoubleClick:ge,panOnScroll:X,panOnScrollSpeed:Q,panOnScrollMode:le,panOnDrag:pe,defaultViewport:z,translateExtent:$,minZoom:te,maxZoom:O,onSelectionContextMenu:S,preventScrolling:F,noDragClassName:qe,noWheelClassName:zt,noPanClassName:en,disableKeyboardA11y:Wt},ve.createElement(JR,null,ve.createElement(KR,{edgeTypes:pn,onEdgeClick:c,onEdgeDoubleClick:m,onEdgeUpdate:tt,onlyRenderVisibleElements:W,onEdgeContextMenu:lt,onEdgeMouseEnter:Ke,onEdgeMouseMove:Se,onEdgeMouseLeave:Re,onEdgeUpdateStart:xe,onEdgeUpdateEnd:Ie,edgeUpdaterRadius:ht,defaultMarkerColor:G,noPanClassName:en,elevateEdgesOnSelect:!!bn,disableKeyboardA11y:Wt,rfId:nr},ve.createElement(e3,{style:E,type:C,component:T,containerStyle:I})),ve.createElement("div",{className:"react-flow__edgelabel-renderer"}),ve.createElement(TR,{nodeTypes:Pt,onNodeClick:u,onNodeDoubleClick:f,onNodeMouseEnter:p,onNodeMouseMove:g,onNodeMouseLeave:w,onNodeContextMenu:x,selectNodesOnDrag:A,onlyRenderVisibleElements:W,noPanClassName:en,noDragClassName:qe,disableKeyboardA11y:Wt,nodeOrigin:It,nodeExtent:kn,rfId:nr})))};g0.displayName="GraphView";var t3=_.memo(g0);const Yp=[[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY],[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY]],Qa={rfId:"1",width:0,height:0,transform:[0,0,1],nodeInternals:new Map,edges:[],onNodesChange:null,onEdgesChange:null,hasDefaultNodes:!1,hasDefaultEdges:!1,d3Zoom:null,d3Selection:null,d3ZoomHandler:void 0,minZoom:.5,maxZoom:2,translateExtent:Yp,nodeExtent:Yp,nodesSelectionActive:!1,userSelectionActive:!1,userSelectionRect:null,connectionNodeId:null,connectionHandleId:null,connectionHandleType:"source",connectionPosition:{x:0,y:0},connectionStatus:null,connectionMode:cc.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:EM,isValidConnection:void 0},n3=()=>WE((e,t)=>({...Qa,setNodes:n=>{const{nodeInternals:s,nodeOrigin:o,elevateNodesOnSelect:l}=t();e({nodeInternals:K_(n,s,o,l)})},getNodes:()=>Array.from(t().nodeInternals.values()),setEdges:n=>{const{defaultEdgeOptions:s={}}=t();e({edges:n.map(o=>({...s,...o}))})},setDefaultNodesAndEdges:(n,s)=>{const o=typeof n<"u",l=typeof s<"u",u=o?K_(n,new Map,t().nodeOrigin,t().elevateNodesOnSelect):new Map;e({nodeInternals:u,edges:l?s:[],hasDefaultNodes:o,hasDefaultEdges:l})},updateNodeDimensions:n=>{const{onNodesChange:s,nodeInternals:o,fitViewOnInit:l,fitViewOnInitDone:u,fitViewOnInitOptions:c,domNode:f,nodeOrigin:m}=t(),p=f==null?void 0:f.querySelector(".react-flow__viewport");if(!p)return;const g=window.getComputedStyle(p),{m22:w}=new window.DOMMatrixReadOnly(g.transform),x=n.reduce((j,N)=>{const C=o.get(N.id);if(C){const E=Ag(N.nodeElement);!!(E.width&&E.height&&(C.width!==E.width||C.height!==E.height||N.forceUpdate))&&(o.set(C.id,{...C,[fr]:{...C[fr],handleBounds:{source:ev(".source",N.nodeElement,w,m),target:ev(".target",N.nodeElement,w,m)}},...E}),j.push({id:C.id,type:"dimensions",dimensions:E}))}return j},[]);i0(o,m);const S=u||l&&!u&&o0(t,{initial:!0,...c});e({nodeInternals:new Map(o),fitViewOnInitDone:S}),(x==null?void 0:x.length)>0&&(s==null||s(x))},updateNodePositions:(n,s=!0,o=!1)=>{const{triggerNodeChanges:l}=t(),u=n.map(c=>{const f={id:c.id,type:"position",dragging:o};return s&&(f.positionAbsolute=c.positionAbsolute,f.position=c.position),f});l(u)},triggerNodeChanges:n=>{const{onNodesChange:s,nodeInternals:o,hasDefaultNodes:l,nodeOrigin:u,getNodes:c,elevateNodesOnSelect:f}=t();if(n!=null&&n.length){if(l){const m=gR(n,c()),p=K_(m,o,u,f);e({nodeInternals:p})}s==null||s(n)}},addSelectedNodes:n=>{const{multiSelectionActive:s,edges:o,getNodes:l}=t();let u,c=null;s?u=n.map(f=>sl(f,!0)):(u=hu(l(),n),c=hu(o,[])),Uh({changedNodes:u,changedEdges:c,get:t,set:e})},addSelectedEdges:n=>{const{multiSelectionActive:s,edges:o,getNodes:l}=t();let u,c=null;s?u=n.map(f=>sl(f,!0)):(u=hu(o,n),c=hu(l(),[])),Uh({changedNodes:c,changedEdges:u,get:t,set:e})},unselectNodesAndEdges:({nodes:n,edges:s}={})=>{const{edges:o,getNodes:l}=t(),u=n||l(),c=s||o,f=u.map(p=>(p.selected=!1,sl(p.id,!1))),m=c.map(p=>sl(p.id,!1));Uh({changedNodes:f,changedEdges:m,get:t,set:e})},setMinZoom:n=>{const{d3Zoom:s,maxZoom:o}=t();s==null||s.scaleExtent([n,o]),e({minZoom:n})},setMaxZoom:n=>{const{d3Zoom:s,minZoom:o}=t();s==null||s.scaleExtent([o,n]),e({maxZoom:n})},setTranslateExtent:n=>{var s;(s=t().d3Zoom)==null||s.translateExtent(n),e({translateExtent:n})},resetSelectedElements:()=>{const{edges:n,getNodes:s}=t(),l=s().filter(c=>c.selected).map(c=>sl(c.id,!1)),u=n.filter(c=>c.selected).map(c=>sl(c.id,!1));Uh({changedNodes:l,changedEdges:u,get:t,set:e})},setNodeExtent:n=>{const{nodeInternals:s}=t();s.forEach(o=>{o.positionAbsolute=Tg(o.position,n)}),e({nodeExtent:n,nodeInternals:new Map(s)})},panBy:n=>{const{transform:s,width:o,height:l,d3Zoom:u,d3Selection:c,translateExtent:f}=t();if(!u||!c||!n.x&&!n.y)return!1;const m=aa.translate(s[0]+n.x,s[1]+n.y).scale(s[2]),p=[[0,0],[o,l]],g=u==null?void 0:u.constrain()(m,p,f);return u.transform(c,g),s[0]!==g.x||s[1]!==g.y||s[2]!==g.k},cancelConnection:()=>e({connectionNodeId:Qa.connectionNodeId,connectionHandleId:Qa.connectionHandleId,connectionHandleType:Qa.connectionHandleType,connectionStatus:Qa.connectionStatus,connectionStartHandle:Qa.connectionStartHandle,connectionEndHandle:Qa.connectionEndHandle}),reset:()=>e({...Qa})}),Object.is),zg=({children:e})=>{const t=_.useRef(null);return t.current||(t.current=n3()),ve.createElement(xM,{value:t.current},e)};zg.displayName="ReactFlowProvider";const y0=({children:e})=>_.useContext(Im)?ve.createElement(ve.Fragment,null,e):ve.createElement(zg,null,e);y0.displayName="ReactFlowWrapper";const r3={input:Zb,default:Gp,output:e0,group:Og},s3={default:vm,straight:Lg,step:Rg,smoothstep:Pm,simplebezier:Mg},i3=[0,0],o3=[15,15],a3={x:0,y:0,zoom:1},l3={width:"100%",height:"100%",overflow:"hidden",position:"relative",zIndex:0},w0=_.forwardRef(({nodes:e,edges:t,defaultNodes:n,defaultEdges:s,className:o,nodeTypes:l=r3,edgeTypes:u=s3,onNodeClick:c,onEdgeClick:f,onInit:m,onMove:p,onMoveStart:g,onMoveEnd:w,onConnect:x,onConnectStart:S,onConnectEnd:j,onClickConnectStart:N,onClickConnectEnd:C,onNodeMouseEnter:E,onNodeMouseMove:T,onNodeMouseLeave:I,onNodeContextMenu:K,onNodeDoubleClick:U,onNodeDragStart:J,onNodeDrag:Y,onNodeDragStop:se,onNodesDelete:ce,onEdgesDelete:fe,onSelectionChange:W,onSelectionDragStart:P,onSelectionDrag:A,onSelectionDragStop:z,onSelectionContextMenu:$,onSelectionStart:te,onSelectionEnd:O,connectionMode:F=cc.Strict,connectionLineType:G=il.Bezier,connectionLineStyle:R,connectionLineComponent:Z,connectionLineContainerStyle:X,deleteKeyCode:Q="Backspace",selectionKeyCode:le="Shift",selectionOnDrag:ge=!1,selectionMode:pe=xf.Full,panActivationKeyCode:ye="Space",multiSelectionKeyCode:Ne=wm()?"Meta":"Control",zoomActivationKeyCode:Ue=wm()?"Meta":"Control",snapToGrid:We=!1,snapGrid:pt=o3,onlyRenderVisibleElements:Fe=!1,selectNodesOnDrag:tt=!0,nodesDraggable:lt,nodesConnectable:Ke,nodesFocusable:Se,nodeOrigin:Re=i3,edgesFocusable:ht,edgesUpdatable:xe,elementsSelectable:Ie,defaultViewport:qe=a3,minZoom:zt=.5,maxZoom:en=2,translateExtent:bn=Yp,preventScrolling:Wt=!0,nodeExtent:It,defaultMarkerColor:kn="#b1b1b7",zoomOnScroll:nr=!0,zoomOnPinch:Pt=!0,panOnScroll:pn=!1,panOnScrollSpeed:Bn=.5,panOnScrollMode:$n=Xl.Free,zoomOnDoubleClick:gn=!0,panOnDrag:In=!0,onPaneClick:wn,onPaneMouseEnter:jr,onPaneMouseMove:Kn,onPaneMouseLeave:Sr,onPaneScroll:Ns,onPaneContextMenu:Pn,children:ae,onEdgeUpdate:je,onEdgeContextMenu:Ye,onEdgeDoubleClick:Ge,onEdgeMouseEnter:st,onEdgeMouseMove:ct,onEdgeMouseLeave:Et,onEdgeUpdateStart:jt,onEdgeUpdateEnd:Kt,edgeUpdaterRadius:xt=10,onNodesChange:Yt,onEdgesChange:qt,noDragClassName:Ot="nodrag",noWheelClassName:$t="nowheel",noPanClassName:At="nopan",fitView:De=!1,fitViewOptions:on,connectOnClick:dt=!0,attributionPosition:tn,proOptions:ft,defaultEdgeOptions:Un,elevateNodesOnSelect:an=!0,elevateEdgesOnSelect:Yr=!1,disableKeyboardA11y:rr=!1,autoPanOnConnect:Ws=!0,autoPanOnNodeDrag:ds=!0,connectionRadius:ii=20,isValidConnection:oi,onError:Or,style:ue,id:fs,nodeDragThreshold:Vi,...hs},Cs)=>{const qs=fs||"1";return ve.createElement("div",{...hs,style:{...ue,...l3},ref:Cs,className:Kr(["react-flow",o]),"data-testid":"rf__wrapper",id:fs},ve.createElement(y0,null,ve.createElement(t3,{onInit:m,onMove:p,onMoveStart:g,onMoveEnd:w,onNodeClick:c,onEdgeClick:f,onNodeMouseEnter:E,onNodeMouseMove:T,onNodeMouseLeave:I,onNodeContextMenu:K,onNodeDoubleClick:U,nodeTypes:l,edgeTypes:u,connectionLineType:G,connectionLineStyle:R,connectionLineComponent:Z,connectionLineContainerStyle:X,selectionKeyCode:le,selectionOnDrag:ge,selectionMode:pe,deleteKeyCode:Q,multiSelectionKeyCode:Ne,panActivationKeyCode:ye,zoomActivationKeyCode:Ue,onlyRenderVisibleElements:Fe,selectNodesOnDrag:tt,defaultViewport:qe,translateExtent:bn,minZoom:zt,maxZoom:en,preventScrolling:Wt,zoomOnScroll:nr,zoomOnPinch:Pt,zoomOnDoubleClick:gn,panOnScroll:pn,panOnScrollSpeed:Bn,panOnScrollMode:$n,panOnDrag:In,onPaneClick:wn,onPaneMouseEnter:jr,onPaneMouseMove:Kn,onPaneMouseLeave:Sr,onPaneScroll:Ns,onPaneContextMenu:Pn,onSelectionContextMenu:$,onSelectionStart:te,onSelectionEnd:O,onEdgeUpdate:je,onEdgeContextMenu:Ye,onEdgeDoubleClick:Ge,onEdgeMouseEnter:st,onEdgeMouseMove:ct,onEdgeMouseLeave:Et,onEdgeUpdateStart:jt,onEdgeUpdateEnd:Kt,edgeUpdaterRadius:xt,defaultMarkerColor:kn,noDragClassName:Ot,noWheelClassName:$t,noPanClassName:At,elevateEdgesOnSelect:Yr,rfId:qs,disableKeyboardA11y:rr,nodeOrigin:Re,nodeExtent:It}),ve.createElement(XM,{nodes:e,edges:t,defaultNodes:n,defaultEdges:s,onConnect:x,onConnectStart:S,onConnectEnd:j,onClickConnectStart:N,onClickConnectEnd:C,nodesDraggable:lt,nodesConnectable:Ke,nodesFocusable:Se,edgesFocusable:ht,edgesUpdatable:xe,elementsSelectable:Ie,elevateNodesOnSelect:an,minZoom:zt,maxZoom:en,nodeExtent:It,onNodesChange:Yt,onEdgesChange:qt,snapToGrid:We,snapGrid:pt,connectionMode:F,translateExtent:bn,connectOnClick:dt,defaultEdgeOptions:Un,fitView:De,fitViewOptions:on,onNodesDelete:ce,onEdgesDelete:fe,onNodeDragStart:J,onNodeDrag:Y,onNodeDragStop:se,onSelectionDrag:A,onSelectionDragStart:P,onSelectionDragStop:z,noPanClassName:At,nodeOrigin:Re,rfId:qs,autoPanOnConnect:Ws,autoPanOnNodeDrag:ds,onError:Or,connectionRadius:ii,isValidConnection:oi,nodeDragThreshold:Vi}),ve.createElement(YM,{onSelectionChange:W}),ae,ve.createElement(jM,{proOptions:ft,position:tn}),ve.createElement(nR,{rfId:qs,disableKeyboardA11y:rr})))});w0.displayName="ReactFlow";const v0=({id:e,x:t,y:n,width:s,height:o,style:l,color:u,strokeColor:c,strokeWidth:f,className:m,borderRadius:p,shapeRendering:g,onClick:w,selected:x})=>{const{background:S,backgroundColor:j}=l||{},N=u||S||j;return ve.createElement("rect",{className:Kr(["react-flow__minimap-node",{selected:x},m]),x:t,y:n,rx:p,ry:p,width:s,height:o,fill:N,stroke:c,strokeWidth:f,shapeRendering:g,onClick:w?C=>w(C,e):void 0})};v0.displayName="MiniMapNode";var c3=_.memo(v0);const u3=e=>e.nodeOrigin,d3=e=>e.getNodes().filter(t=>!t.hidden&&t.width&&t.height),Z_=e=>e instanceof Function?e:()=>e;function f3({nodeStrokeColor:e="transparent",nodeColor:t="#e2e2e2",nodeClassName:n="",nodeBorderRadius:s=5,nodeStrokeWidth:o=2,nodeComponent:l=c3,onClick:u}){const c=Ln(d3,Pr),f=Ln(u3),m=Z_(t),p=Z_(e),g=Z_(n),w=typeof window>"u"||window.chrome?"crispEdges":"geometricPrecision";return ve.createElement(ve.Fragment,null,c.map(x=>{const{x:S,y:j}=rc(x,f).positionAbsolute;return ve.createElement(l,{key:x.id,x:S,y:j,width:x.width,height:x.height,style:x.style,selected:x.selected,className:g(x),color:m(x),borderRadius:s,strokeColor:p(x),strokeWidth:o,shapeRendering:w,onClick:u,id:x.id})}))}var h3=_.memo(f3);const m3=200,_3=150,p3=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?NM(Om(t,e.nodeOrigin),n):n,rfId:e.rfId}},g3="react-flow__minimap-desc";function x0({style:e,className:t,nodeStrokeColor:n="transparent",nodeColor:s="#e2e2e2",nodeClassName:o="",nodeBorderRadius:l=5,nodeStrokeWidth:u=2,nodeComponent:c,maskColor:f="rgb(240, 240, 240, 0.6)",maskStrokeColor:m="none",maskStrokeWidth:p=1,position:g="bottom-right",onClick:w,onNodeClick:x,pannable:S=!1,zoomable:j=!1,ariaLabel:N="React Flow mini map",inversePan:C=!1,zoomStep:E=10,offsetScale:T=5}){const I=br(),K=_.useRef(null),{boundingRect:U,viewBB:J,rfId:Y}=Ln(p3,Pr),se=(e==null?void 0:e.width)??m3,ce=(e==null?void 0:e.height)??_3,fe=U.width/se,W=U.height/ce,P=Math.max(fe,W),A=P*se,z=P*ce,$=T*P,te=U.x-(A-U.width)/2-$,O=U.y-(z-U.height)/2-$,F=A+$*2,G=z+$*2,R=`${g3}-${Y}`,Z=_.useRef(0);Z.current=P,_.useEffect(()=>{if(K.current){const le=ji(K.current),ge=Ne=>{const{transform:Ue,d3Selection:We,d3Zoom:pt}=I.getState();if(Ne.sourceEvent.type!=="wheel"||!We||!pt)return;const Fe=-Ne.sourceEvent.deltaY*(Ne.sourceEvent.deltaMode===1?.05:Ne.sourceEvent.deltaMode?1:.002)*E,tt=Ue[2]*Math.pow(2,Fe);pt.scaleTo(We,tt)},pe=Ne=>{const{transform:Ue,d3Selection:We,d3Zoom:pt,translateExtent:Fe,width:tt,height:lt}=I.getState();if(Ne.sourceEvent.type!=="mousemove"||!We||!pt)return;const Ke=Z.current*Math.max(1,Ue[2])*(C?-1:1),Se={x:Ue[0]-Ne.sourceEvent.movementX*Ke,y:Ue[1]-Ne.sourceEvent.movementY*Ke},Re=[[0,0],[tt,lt]],ht=aa.translate(Se.x,Se.y).scale(Ue[2]),xe=pt.constrain()(ht,Re,Fe);pt.transform(We,xe)},ye=Ab().on("zoom",S?pe:null).on("zoom.wheel",j?ge:null);return le.call(ye),()=>{le.on("zoom",null)}}},[S,j,C,E]);const X=w?le=>{const ge=Fi(le);w(le,{x:ge[0],y:ge[1]})}:void 0,Q=x?(le,ge)=>{const pe=I.getState().nodeInternals.get(ge);x(le,pe)}:void 0;return ve.createElement(wf,{position:g,style:e,className:Kr(["react-flow__minimap",t]),"data-testid":"rf__minimap"},ve.createElement("svg",{width:se,height:ce,viewBox:`${te} ${O} ${F} ${G}`,role:"img","aria-labelledby":R,ref:K,onClick:X},N&&ve.createElement("title",{id:R},N),ve.createElement(h3,{onClick:Q,nodeColor:s,nodeStrokeColor:n,nodeBorderRadius:l,nodeClassName:o,nodeStrokeWidth:u,nodeComponent:c}),ve.createElement("path",{className:"react-flow__minimap-mask",d:`M${te-$},${O-$}h${F+$*2}v${G+$*2}h${-F-$*2}z
132
- M${J.x},${J.y}h${J.width}v${J.height}h${-J.width}z`,fill:f,fillRule:"evenodd",stroke:m,strokeWidth:p,pointerEvents:"none"})))}x0.displayName="MiniMap";var y3=_.memo(x0);function w3(){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 v3(){return ve.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 5"},ve.createElement("path",{d:"M0 0h32v4.2H0z"}))}function x3(){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 b3(){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 j3(){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 mu=({children:e,className:t,...n})=>ve.createElement("button",{type:"button",className:Kr(["react-flow__controls-button",t]),...n},e);mu.displayName="ControlButton";const S3=e=>({isInteractive:e.nodesDraggable||e.nodesConnectable||e.elementsSelectable,minZoomReached:e.transform[2]<=e.minZoom,maxZoomReached:e.transform[2]>=e.maxZoom}),b0=({style:e,showZoom:t=!0,showFitView:n=!0,showInteractive:s=!0,fitViewOptions:o,onZoomIn:l,onZoomOut:u,onFitView:c,onInteractiveChange:f,className:m,children:p,position:g="bottom-left"})=>{const w=br(),[x,S]=_.useState(!1),{isInteractive:j,minZoomReached:N,maxZoomReached:C}=Ln(S3,Pr),{zoomIn:E,zoomOut:T,fitView:I}=Dg();if(_.useEffect(()=>{S(!0)},[]),!x)return null;const K=()=>{E(),l==null||l()},U=()=>{T(),u==null||u()},J=()=>{I(o),c==null||c()},Y=()=>{w.setState({nodesDraggable:!j,nodesConnectable:!j,elementsSelectable:!j}),f==null||f(!j)};return ve.createElement(wf,{className:Kr(["react-flow__controls",m]),position:g,style:e,"data-testid":"rf__controls"},t&&ve.createElement(ve.Fragment,null,ve.createElement(mu,{onClick:K,className:"react-flow__controls-zoomin",title:"zoom in","aria-label":"zoom in",disabled:C},ve.createElement(w3,null)),ve.createElement(mu,{onClick:U,className:"react-flow__controls-zoomout",title:"zoom out","aria-label":"zoom out",disabled:N},ve.createElement(v3,null))),n&&ve.createElement(mu,{className:"react-flow__controls-fitview",onClick:J,title:"fit view","aria-label":"fit view"},ve.createElement(x3,null)),s&&ve.createElement(mu,{className:"react-flow__controls-interactive",onClick:Y,title:"toggle interactivity","aria-label":"toggle interactivity"},j?ve.createElement(j3,null):ve.createElement(b3,null)),p)};b0.displayName="Controls";var k3=_.memo(b0),qi;(function(e){e.Lines="lines",e.Dots="dots",e.Cross="cross"})(qi||(qi={}));function N3({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 C3({color:e,radius:t}){return ve.createElement("circle",{cx:t,cy:t,r:t,fill:e})}const E3={[qi.Dots]:"#91919a",[qi.Lines]:"#eee",[qi.Cross]:"#e2e2e2"},$3={[qi.Dots]:1,[qi.Lines]:1,[qi.Cross]:6},A3=e=>({transform:e.transform,patternId:`pattern-${e.rfId}`});function j0({id:e,variant:t=qi.Dots,gap:n=20,size:s,lineWidth:o=1,offset:l=2,color:u,style:c,className:f}){const m=_.useRef(null),{transform:p,patternId:g}=Ln(A3,Pr),w=u||E3[t],x=s||$3[t],S=t===qi.Dots,j=t===qi.Cross,N=Array.isArray(n)?n:[n,n],C=[N[0]*p[2]||1,N[1]*p[2]||1],E=x*p[2],T=j?[E,E]:C,I=S?[E/l,E/l]:[T[0]/l,T[1]/l];return ve.createElement("svg",{className:Kr(["react-flow__background",f]),style:{...c,position:"absolute",width:"100%",height:"100%",top:0,left:0},ref:m,"data-testid":"rf__background"},ve.createElement("pattern",{id:g+e,x:p[0]%C[0],y:p[1]%C[1],width:C[0],height:C[1],patternUnits:"userSpaceOnUse",patternTransform:`translate(-${I[0]},-${I[1]})`},S?ve.createElement(C3,{color:w,radius:E/l}):ve.createElement(N3,{dimensions:T,color:w,lineWidth:o})),ve.createElement("rect",{x:"0",y:"0",width:"100%",height:"100%",fill:`url(#${g+e})`}))}j0.displayName="Background";var T3=_.memo(j0);function S0(e,t={}){const n=e&&typeof e=="object"&&!Array.isArray(e)?e:null;if(!n)return null;const s=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(s===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(s)>u||Math.abs(o)>u)return null;const c=typeof t.minZoom=="number"&&Number.isFinite(t.minZoom)?t.minZoom:.025,f=typeof t.maxZoom=="number"&&Number.isFinite(t.maxZoom)?t.maxZoom:6,m=Math.min(c,f),p=Math.max(c,f);return{x:s,y:o,zoom:Math.min(p,Math.max(m,l))}}function bm(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 M3(e){const t=String(e||"").trim();if(!t)return"entity";const n=t.indexOf(":");if(n<=0||n>=t.length-1)return"entity";const s=t.slice(0,n).toLowerCase(),o=t.slice(n+1).toLowerCase();if(s==="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 s==="schema"||s==="skos"||s==="dcterms"||s==="rdf"||s==="cito"?"vocab":"entity"}function R3(e){const t=String(e||"").trim();if(!t)return"";const n=t.indexOf(":");if(n<=0||n>=t.length-1)return bm(t);const s=t.slice(0,n).toLowerCase(),o=t.slice(n+1);if(s==="ex"){const l=o.indexOf("-");if(l>0&&l<o.length-1)return o.slice(l+1)}return bm(t)}function Jp(e){const s=Math.max(1,Math.ceil(Math.sqrt(e.length))),o={};for(let l=0;l<e.length;l++){const u=Math.floor(l/s),c=l%s;o[e[l]]={x:c*240,y:u*120}}return o}function Xp(e){const t=String(e??"");let n=2166136261;for(let s=0;s<t.length;s++)n^=t.charCodeAt(s),n=Math.imul(n,16777619);return n>>>0}function k0(e){let t=e>>>0;return()=>{t+=1831565813;let n=Math.imul(t^t>>>15,1|t);return n^=n+Math.imul(n^n>>>7,61|n),((n^n>>>14)>>>0)/4294967296}}function L3(e,t){const n={},s=e.length;if(!s)return n;const o=Math.max(260,Math.sqrt(s)*150),l=t%360*Math.PI/180;for(let u=0;u<s;u++){const c=l+2*Math.PI*u/s;n[e[u]]={x:o*Math.cos(c),y:o*Math.sin(c)}}return n}function lv(e,t,n){var S;const s={};if(!e.length)return s;const o=new Map;for(const j of e)o.set(j,new Set);for(const j of t){const N=String((j==null?void 0:j.source)||"").trim(),C=String((j==null?void 0:j.target)||"").trim();if(!N||!C||N===C)continue;const E=o.get(N),T=o.get(C);E&&E.add(C),T&&T.add(N)}let l=e[0],u=-1;for(const j of e){const N=((S=o.get(j))==null?void 0:S.size)??0;(N>u||N===u&&j.localeCompare(l)<0)&&(l=j,u=N)}const c=new Map,f=[];for(c.set(l,0),f.push(l);f.length;){const j=f.shift(),N=c.get(j)??0,C=Array.from(o.get(j)??[]);C.sort((E,T)=>E.localeCompare(T));for(const E of C)c.has(E)||(c.set(E,N+1),f.push(E))}let m=0;for(const j of c.values())m=Math.max(m,j);for(const j of e)c.has(j)||c.set(j,m+1);const p=new Map;for(const j of e){const N=c.get(j)??0,C=p.get(N);C?C.push(j):p.set(N,[j])}const g=Array.from(p.keys()).sort((j,N)=>j-N),w=260,x=n%360*Math.PI/180;for(const j of g){const N=p.get(j)||[];if(N.sort((I,K)=>I.localeCompare(K)),j===0){if(N.length===1)s[N[0]]={x:0,y:0};else for(let K=0;K<N.length;K++){const U=x+2*Math.PI*K/N.length;s[N[K]]={x:80*Math.cos(U),y:80*Math.sin(U)}}continue}const C=w*j,E=N.length;if(E===1){s[N[0]]={x:C,y:0};continue}const T=x+j*.35;for(let I=0;I<E;I++){const K=T+2*Math.PI*I/E;s[N[I]]={x:C*Math.cos(K),y:C*Math.sin(K)}}}return s}function uu(e,t={}){const n=t.kind??"grid",s=typeof t.seed=="number"&&Number.isFinite(t.seed)?Math.trunc(t.seed):0,o=e.nodes.map(l=>l.id);if(n==="grid")return Jp(o);if(n==="circle")return L3(o,s);if(n==="radial")return lv(o,e.edges,s);if(n==="force"){const l=lv(o,e.edges,s),u=k0(s||1),c=Math.max(10,Math.min(42,Math.sqrt(o.length)*2.75)),f={};for(const m of o){const p=l[m]||{x:0,y:0};f[m]={x:p.x+(u()-.5)*c,y:p.y+(u()-.5)*c}}return f}return Jp(o)}function I3(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 P3(e,t={}){const n=!!(t.groupEdges??!0),s=Math.max(1,t.maxEdgeLabelPredicates??3),o=I3(e),l=new Set;for(const w of o){const x=String(w.subject||"").trim(),S=String(w.object||"").trim();x&&l.add(x),S&&l.add(S)}const u=Array.from(l);u.sort((w,x)=>w.localeCompare(x));const c=Jp(u),f=u.map(w=>({id:w,type:"default",data:{label:R3(w),kind:M3(w)},position:c[w]||{x:0,y:0}})),m=new Map,p=(w,x)=>{const S=String(w.subject||"").trim(),j=String(w.object||"").trim(),N=String(w.predicate||"").trim();return n?`edge:${S}:${j}`:`edge:${x}:${S}:${N}:${j}`};for(let w=0;w<o.length;w++){const x=o[w],S=p(x,w),j=m.get(S);j?j.push(x):m.set(S,[x])}const g=[];for(const[w,x]of m.entries()){const S=x[0],j=String(S.subject||"").trim(),N=String(S.object||"").trim();if(!j||!N)continue;const C=new Map;for(const J of x){const Y=String(J.predicate||"").trim();Y&&C.set(Y,(C.get(Y)||0)+1)}const E=Array.from(C.entries());E.sort((J,Y)=>Y[1]-J[1]||J[0].localeCompare(Y[0]));const I=E.slice(0,s).map(([J,Y])=>Y>1?`${bm(J)}×${Y}`:bm(J)).join(" | "),K=E.length>s?` +${E.length-s}`:"",U=`${I}${K}`.trim();g.push({id:w,source:j,target:N,label:U,animated:!1,data:{assertions:x,predicateSummary:U}})}return{nodes:f,edges:g}}function O3(e,t,n,s={}){const o=s.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,N,C)=>{const E=c.get(j);E?E.push({to:N,edgeId:C}):c.set(j,[{to:N,edgeId:C}])};for(const j of e.edges)f(j.source,j.target,j.id),o||f(j.target,j.source,j.id);const m=[l],p=new Map,g=new Map;for(p.set(l,null),g.set(l,null);m.length;){const j=m.shift(),N=c.get(j)||[];for(const C of N)if(!p.has(C.to)){if(p.set(C.to,j),g.set(C.to,C.edgeId),C.to===u){m.length=0;break}m.push(C.to)}}if(!p.has(u))return null;const w=[],x=[];let S=u;for(;S;){w.push(S);const j=g.get(S);j&&x.push(j),S=p.get(S)||null}return w.reverse(),x.reverse(),{nodeIds:w,edgeIds:x}}const cv={seed:1,dt:1,springLength:240,springStrength:.03,repulsionStrength:9e3,centeringStrength:.003,damping:.85,maxSpeed:90,maxRepulsionNodes:320};function qh(e,t={}){const n={...cv,...t,seed:typeof t.seed=="number"&&Number.isFinite(t.seed)?Math.trunc(t.seed):cv.seed},s=e.nodes.map(x=>x.id),o=s.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(s[x],x);const m=t.positions??uu(e,{kind:"force",seed:n.seed}),p=k0(n.seed||1),g=Math.max(8,Math.min(38,Math.sqrt(o)*2.25));for(let x=0;x<o;x++){const S=s[x],j=m[S],N=typeof(j==null?void 0:j.x)=="number"&&Number.isFinite(j.x)?j.x:(p()-.5)*500,C=typeof(j==null?void 0:j.y)=="number"&&Number.isFinite(j.y)?j.y:(p()-.5)*500;l[2*x]=N+(p()-.5)*g,l[2*x+1]=C+(p()-.5)*g,u[2*x]=0,u[2*x+1]=0}const w=[];for(const x of e.edges){const S=f.get(String((x==null?void 0:x.source)||"").trim()),j=f.get(String((x==null?void 0:x.target)||"").trim());typeof S!="number"||typeof j!="number"||S===j||w.push(S,j)}return{nodeIds:s,pos:l,vel:u,acc:c,edges:new Uint32Array(w),options:n,tick:0}}function D3(e,t=1){const n=e.nodeIds.length;if(!n)return;const s=e.options,o=s.dt;for(let l=0;l<Math.max(1,Math.trunc(t));l++){if(e.acc.fill(0),n<=s.maxRepulsionNodes){const x=s.repulsionStrength;for(let S=0;S<n;S++){const j=e.pos[2*S],N=e.pos[2*S+1];for(let C=S+1;C<n;C++){const E=e.pos[2*C]-j,T=e.pos[2*C+1]-N,I=E*E+T*T+1e-6,K=1/Math.sqrt(I),U=x/I,J=U*E*K,Y=U*T*K;e.acc[2*S]-=J,e.acc[2*S+1]-=Y,e.acc[2*C]+=J,e.acc[2*C+1]+=Y}}}const c=s.springLength,f=s.springStrength,m=e.edges;for(let x=0;x<m.length;x+=2){const S=m[x],j=m[x+1],N=e.pos[2*S],C=e.pos[2*S+1],E=e.pos[2*j],T=e.pos[2*j+1],I=E-N,K=T-C,U=I*I+K*K+1e-6,J=Math.sqrt(U),Y=f*(J-c),se=Y*I/J,ce=Y*K/J;e.acc[2*S]+=se,e.acc[2*S+1]+=ce,e.acc[2*j]-=se,e.acc[2*j+1]-=ce}const p=s.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 g=s.damping,w=s.maxSpeed;for(let x=0;x<n;x++){let S=(e.vel[2*x]+e.acc[2*x]*o)*g,j=(e.vel[2*x+1]+e.acc[2*x+1]*o)*g;const N=Math.sqrt(S*S+j*j);if(N>w){const C=w/N;S*=C,j*=C}e.vel[2*x]=S,e.vel[2*x+1]=j,e.pos[2*x]+=S*o,e.pos[2*x+1]+=j*o}e.tick+=1}}function F3(e){const t=e.nodeIds.length;if(!t)return 0;let n=0;for(let s=0;s<t;s++){const o=e.vel[2*s],l=e.vel[2*s+1];n+=Math.sqrt(o*o+l*l)}return n/t}function z3(e){const t={},n=e.nodeIds.length;for(let s=0;s<n;s++)t[e.nodeIds[s]]={x:e.pos[2*s],y:e.pos[2*s+1]};return t}function uv(e,t="session"){const n=String(e??"").trim().toLowerCase();return n==="run"||n==="session"||n==="global"||n==="all"?n:t}function B3(){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 U3(){return r.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16","aria-hidden":"true",focusable:"false",children:[r.jsx("rect",{x:"3",y:"3",width:"3",height:"3",rx:"1"}),r.jsx("rect",{x:"3",y:"7",width:"3",height:"3",rx:"1"}),r.jsx("rect",{x:"3",y:"11",width:"3",height:"3",rx:"1"}),r.jsx("rect",{x:"8",y:"3.5",width:"6",height:"2",rx:"1",fill:"none",strokeWidth:"1.4"}),r.jsx("rect",{x:"8",y:"7.5",width:"6",height:"2",rx:"1",fill:"none",strokeWidth:"1.4"}),r.jsx("rect",{x:"8",y:"11.5",width:"6",height:"2",rx:"1",fill:"none",strokeWidth:"1.4"})]})}function N0(e,t,n,s){const o=typeof e=="number"&&Number.isFinite(e)?e:s;return Math.min(n,Math.max(t,o))}function Qd(e){const t=N0(e,.6,2.4,1),n=240*t,s=9e3*t*t;return{springLength:n,repulsionStrength:s}}const Sf="abstractuic_amx_saved_layouts_v1",Zp=.025,Qp=6,C0=1e6;function Bg(){if(typeof window>"u")return null;try{return window.localStorage}catch{return null}}function eg(e,t="grid"){const n=String(e??"").trim().toLowerCase();return n==="grid"||n==="circle"||n==="radial"||n==="force"?n:t}function W3(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,s=typeof t.y=="number"&&Number.isFinite(t.y)?t.y:null;return n===null||s===null?null:{x:n,y:s}}function dv(e){const t=Bg();if(!t)return null;const n=String(e??"").trim();if(!n)return null;try{const s=t.getItem(Sf);if(!s)return null;const o=JSON.parse(s),l=o&&typeof o=="object"&&!Array.isArray(o)?o:null;if(!l)return null;const u=l[n],c=u&&typeof u=="object"&&!Array.isArray(u)?u:null;if(!c)return null;const f=c.version===1?1:null;if(f===null)return null;const m=eg(c.kind,"grid"),p=typeof c.seed=="number"&&Number.isFinite(c.seed)?Math.trunc(c.seed):Xp(n),g=c.positions&&typeof c.positions=="object"&&!Array.isArray(c.positions)?c.positions:null,w={};if(g)for(const[j,N]of Object.entries(g)){const C=W3(N);C&&(w[String(j)]=C)}const x=S0(c.viewport,{minZoom:Zp,maxZoom:Qp,maxAbsTranslate:C0})??void 0,S=typeof c.saved_at=="string"&&c.saved_at.trim()?c.saved_at.trim():"";return{version:f,kind:m,seed:p,positions:w,viewport:x,saved_at:S}}catch{return null}}function q3(e,t){const n=Bg();if(!n)return;const s=String(e??"").trim();if(s)try{const o=n.getItem(Sf),l=o?JSON.parse(o):null,u=l&&typeof l=="object"&&!Array.isArray(l)?{...l}:{};u[s]=t,n.setItem(Sf,JSON.stringify(u))}catch{}}function H3(e){const t=Bg();if(!t)return;const n=String(e??"").trim();if(n)try{const s=t.getItem(Sf);if(!s)return;const o=JSON.parse(s),l=o&&typeof o=="object"&&!Array.isArray(o)?{...o}:null;if(!l||!(n in l))return;delete l[n],t.setItem(Sf,JSON.stringify(l))}catch{}}function V3(e){const t=String(e??"").trim();if(!t)return;const n=Number(t);if(Number.isFinite(n))return n}function Q_(e,t){const n=!!(t!=null&&t.allowZero),s=!!(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(s&&u===-1)return-1;if(!(!n&&u<=0)&&!(n&&u<0))return u}function G3(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e,n=typeof t.recall_level=="string"?t.recall_level:"",s=t.applied&&typeof t.applied=="object"&&!Array.isArray(t.applied)?t.applied:null,o=[];return n&&o.push(`recall_level=${n}`),s&&(typeof s.limit=="number"&&o.push(`limit=${s.limit}`),typeof s.min_score=="number"&&o.push(`min_score=${s.min_score}`),typeof s.max_input_tokens=="number"&&o.push(`max_input_tokens=${s.max_input_tokens}`)),o.length?o.join(" · "):null}function K3(e){if(!e||typeof e!="object")return null;const t=[],n=typeof e.scope=="string"?e.scope.trim():"",s=typeof e.owner_id=="string"?e.owner_id.trim():"";n&&t.push(`scope=${n}`),s&&t.push(`owner_id=${s}`);const o=typeof e.confidence=="number"&&Number.isFinite(e.confidence)?e.confidence:null;o!==null&&t.push(`confidence=${o.toFixed(3)}`);const l=e.provenance&&typeof e.provenance=="object"&&!Array.isArray(e.provenance)?e.provenance:null;if(l){const m=typeof l.writer_run_id=="string"?l.writer_run_id.trim():"",p=typeof l.writer_workflow_id=="string"?l.writer_workflow_id.trim():"";m&&t.push(`writer_run_id=${m}`),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 Y3(e,t){const n=String(e??""),s=String(t??"").trim();if(!s)return n;const o=n.toLowerCase().indexOf(s.toLowerCase());if(o<0)return n;const l=n.slice(0,o),u=n.slice(o,o+s.length),c=n.slice(o+s.length);return r.jsxs(r.Fragment,{children:[l,r.jsx("span",{className:"amx-hl",children:u}),c]})}function ef(e){const t=String(e??"").trim().toLowerCase();return t==="person"?{stroke:"rgba(96, 165, 250, 0.82)",bg:"rgba(96, 165, 250, 0.10)",minimap:"rgba(96, 165, 250, 0.85)"}:t==="org"?{stroke:"rgba(34, 197, 94, 0.78)",bg:"rgba(34, 197, 94, 0.10)",minimap:"rgba(34, 197, 94, 0.82)"}:t==="concept"?{stroke:"rgba(168, 85, 247, 0.78)",bg:"rgba(168, 85, 247, 0.10)",minimap:"rgba(168, 85, 247, 0.82)"}:t==="claim"?{stroke:"rgba(251, 191, 36, 0.78)",bg:"rgba(251, 191, 36, 0.10)",minimap:"rgba(251, 191, 36, 0.82)"}:t==="event"?{stroke:"rgba(239, 68, 68, 0.74)",bg:"rgba(239, 68, 68, 0.10)",minimap:"rgba(239, 68, 68, 0.80)"}:t==="doc"?{stroke:"rgba(14, 165, 233, 0.74)",bg:"rgba(14, 165, 233, 0.10)",minimap:"rgba(14, 165, 233, 0.80)"}:t==="vocab"?{stroke:"rgba(148, 163, 184, 0.55)",bg:"rgba(148, 163, 184, 0.06)",minimap:"rgba(148, 163, 184, 0.70)"}:t==="thing"?{stroke:"rgba(255, 255, 255, 0.20)",bg:"rgba(255, 255, 255, 0.04)",minimap:"rgba(255, 255, 255, 0.30)"}:{stroke:"rgba(255, 255, 255, 0.14)",bg:"rgba(0, 0, 0, 0.18)",minimap:"rgba(255, 255, 255, 0.24)"}}function J3(e){const t=typeof e=="string"?e.trim():"";if(!t)return null;const n=t.replace(/(\.\d{3})\d+/,"$1"),s=Date.parse(n);return Number.isFinite(s)?s:null}function tf(e){const t=J3(e);if(t===null)return"";const n=new Date(t),s=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`${s}/${o}/${l} ${u}:${c}`}function E0(e){const t=String(e??"").trim();if(!t)return"";const n=t.indexOf(":");return n!==-1&&n<t.length-1?t.slice(n+1):t}function ep(e,t){const n=String(e??"").trim().toLowerCase();return!!(n&&t.has(n))}function X3(e,t={}){const n=Math.max(1,t.maxPredicates??3),s=new Map;for(const f of e){const m=String((f==null?void 0:f.predicate)||"").trim();m&&s.set(m,(s.get(m)||0)+1)}const o=Array.from(s.entries());o.sort((f,m)=>m[1]-f[1]||f[0].localeCompare(m[0]));const u=o.slice(0,n).map(([f,m])=>{const p=E0(f);return m>1?`${p}×${m}`:p}).join(" | "),c=o.length>n?` +${o.length-n}`:"";return`${u}${c}`.trim()}function Z3({resetKey:e,queryMode:t,items:n,activeMemoryText:s,packets:o,packetsVersion:l,packedCount:u,dropped:c,estimatedTokens:f,effort:m,warnings:p,onQuery:g,onItemsReplace:w,onOpenSpan:x,onOpenTranscript:S}){var ci;const j=_.useRef(null),N=_.useMemo(()=>{const B=n==null?void 0:n[0],ie=n==null?void 0:n[n.length-1],be=B?`${B.subject}|${B.predicate}|${B.object}`:"",ke=ie?`${ie.subject}|${ie.predicate}|${ie.object}`:"";return`${(n==null?void 0:n.length)||0}:${be}:${ke}`},[n]),C=String(e??N),E=t==="replace"?"replace":"override",[T,I]=_.useState(null),[K,U]=_.useState(null),[J,Y]=_.useState(!1),[se,ce]=_.useState(""),[fe,W]=_.useState(!1),[P,A]=_.useState("");_.useEffect(()=>{I(null),U(null),ce(""),Y(!1),A(""),W(!1)},[C]);const[z,$]=_.useState(""),[te,O]=_.useState(!0),[F,G]=_.useState(!1),[R,Z]=_.useState(!0),[X]=_.useState(()=>({compact:B3(),show:!1})),Q=X.compact,[le,ge]=_.useState(X.show),[pe,ye]=_.useState(!1),Ne=C,Ue=_.useMemo(()=>Xp(Ne),[Ne]),[We,pt]=_.useState("grid"),[Fe,tt]=_.useState(Ue),[lt,Ke]=_.useState(!1),[Se,Re]=_.useState(1),ht=_.useRef(null),xe=_.useRef(null),Ie=_.useRef(!1),[qe,zt]=_.useState(0),en=_.useRef(null),bn=_.useRef(0),Wt=_.useRef(0),It=_.useRef(0),kn=_.useRef(0),[nr,Pt]=_.useState(!1),[pn,Bn]=_.useState(""),[$n,gn]=_.useState({}),In=_.useRef({});_.useEffect(()=>{In.current=$n},[$n]);const[wn,jr]=_.useState(""),[Kn,Sr]=_.useState(""),Ns=_.useMemo(()=>{var ie;const B=(ie=n==null?void 0:n[0])==null?void 0:ie.scope;return uv(B,"session")},[n]),[Pn,ae]=_.useState(Ns),[je,Ye]=_.useState("standard"),[Ge,st]=_.useState(""),[ct,Et]=_.useState(""),[jt,Kt]=_.useState(""),[xt,Yt]=_.useState(""),[qt,Ot]=_.useState(""),[$t,At]=_.useState(""),[De,on]=_.useState(""),[dt,tn]=_.useState("qwen/qwen3-next-80b");_.useEffect(()=>{ae(Ns)},[C]);const ft=Array.isArray(n)?n:[],Un=typeof s=="string"?s:"",an=Array.isArray(o)?o:[],Yr=typeof l=="number"?l:void 0,rr=typeof u=="number"?u:void 0,Ws=typeof c=="number"?c:void 0,ds=typeof f=="number"?f:void 0,ii=m,oi=p,Or=E==="override"&&(T!=null&&T.items)&&Array.isArray(T.items)?T.items:ft,ue=typeof(T==null?void 0:T.active_memory_text)=="string"&&T.active_memory_text.trim()?T.active_memory_text:Un,fs=(T==null?void 0:T.effort)??ii,Vi=(T==null?void 0:T.warnings)??oi,hs=_.useMemo(()=>new Set(["rdf:type","schema:name","skos:preflabel","skos:altlabel","dcterms:title","dcterms:identifier"]),[]),Cs=_.useMemo(()=>R?Or:(Or||[]).filter(B=>!ep(B==null?void 0:B.predicate,hs)),[Or,R,hs]),qs=_.useMemo(()=>P3(Or,{groupEdges:te}),[Or,te]),it=_.useMemo(()=>{if(R)return qs;const B=[];for(const ie of qs.edges){const ke=(ie&&ie.data&&Array.isArray(ie.data.assertions)?ie.data.assertions:[]).filter(He=>!ep(He==null?void 0:He.predicate,hs));if(!ke.length)continue;const Ee=X3(ke);B.push({...ie,label:Ee,data:{...ie.data,assertions:ke,predicateSummary:Ee}})}return{nodes:qs.nodes,edges:B}},[qs,R,hs]),cn=_.useMemo(()=>it.nodes.map(B=>B.id),[it.nodes]),Dr=_.useMemo(()=>{const B=cn[0]||"",ie=cn[cn.length-1]||"";return`${cn.length}:${B}:${ie}`},[cn]),Hs=_.useMemo(()=>{var ie;const B=new Map;for(const be of it.nodes)B.set(be.id,String(((ie=be.data)==null?void 0:ie.label)||be.id));return B},[it.nodes]),sr=_.useMemo(()=>{var ie;const B=new Map;for(const be of it.nodes)B.set(be.id,String(((ie=be.data)==null?void 0:ie.kind)||""));return B},[it.nodes]),Eo=z.trim().toLowerCase(),$o=_.useMemo(()=>{var ie;if(!Eo)return new Set;const B=new Set;for(const be of it.nodes){const ke=String(be.id||"").toLowerCase(),Ee=String(((ie=be.data)==null?void 0:ie.label)||"").toLowerCase();(ke.includes(Eo)||Ee.includes(Eo))&&B.add(be.id)}return B},[it.nodes,Eo]),Ao=_.useCallback((B,ie)=>{const be={};for(const ke of cn){const Ee=B[ke]||ie[ke];be[ke]=Ee?{x:Ee.x,y:Ee.y}:{x:0,y:0}}return be},[cn]);_.useEffect(()=>{gn(B=>{const ie=uu(it,{kind:We,seed:Fe}),be={};for(const ke of cn){const Ee=B[ke]||ie[ke];be[ke]=Ee?{x:Ee.x,y:Ee.y}:{x:0,y:0}}return be})},[it,We,Fe,cn,Dr]),_.useEffect(()=>{if(!Ie.current)return;const B=j.current;if(!(!B||typeof B.fitView!="function")&&cn.length){Ie.current=!1;try{B.fitView({padding:.2,duration:0})}catch{try{B.fitView({padding:.2})}catch{}}}},[cn.length,Dr,$n]),_.useEffect(()=>{Ke(!1),ht.current=null,xe.current=null,Ie.current=!1,bn.current=0,Wt.current=0,It.current=0;const B=dv(Ne);if(B&&Object.keys(B.positions||{}).length){if(pt(B.kind),tt(B.seed),Pt(!0),Bn(B.saved_at||""),B.viewport){xe.current=B.viewport;const Ee=j.current;if(Ee&&typeof Ee.setViewport=="function"){try{Ee.setViewport(B.viewport,{duration:0})}catch{try{Ee.setViewport(B.viewport)}catch{}}xe.current=null}}else Ie.current=!0;const ke=uu(it,{kind:B.kind,seed:B.seed});gn(Ao(B.positions,ke));return}Pt(!1),Bn("");const ie=Xp(Ne);tt(ie);const be=uu(it,{kind:We,seed:ie});gn(be),We==="force"&&it.nodes.length>0&&it.nodes.length<=320&&(ht.current=qh(it,{seed:ie,positions:be,...Qd(Se)}),Ke(!0))},[Ne]);const On=_.useMemo(()=>{const B=String(wn||"").trim(),ie=String(Kn||"").trim();return!B||!ie?null:O3(it,B,ie,{directed:F})},[it,wn,Kn,F]),ms=!!(On&&String(wn||"").trim()&&String(Kn||"").trim()),Hn=_.useMemo(()=>{const B=String(wn||"").trim(),ie=String(Kn||"").trim();if(!B||!ie)return null;const be=F,ke=new Map,Ee=(ot,mt)=>{const Dt=ke.get(ot);Dt?Dt.push(mt):ke.set(ot,[mt])};for(const ot of it.edges)Ee(ot.source,ot.target),be||Ee(ot.target,ot.source);const He=new Set,Qe=[];for(He.add(B),Qe.push(B);Qe.length;){const ot=Qe.shift(),mt=ke.get(ot)||[];for(const Dt of mt)He.has(Dt)||(He.add(Dt),Qe.push(Dt))}return{reachableFromStart:He.size,endReachable:He.has(ie),nodes:it.nodes.length,edges:it.edges.length,assertions:Cs.length}},[F,it.edges,it.nodes.length,Kn,wn,Cs.length]),Gi=_.useMemo(()=>new Set((On==null?void 0:On.nodeIds)||[]),[On]),ai=_.useMemo(()=>new Set((On==null?void 0:On.edgeIds)||[]),[On]),[An,Fr]=_.useState(""),[hr,Jr]=_.useState(""),mr=!!(String(An||"").trim()||String(hr||"").trim()),da=_.useMemo(()=>{const B=new Set,ie=new Set,be=String(An||"").trim(),ke=String(hr||"").trim();if(be){B.add(be);for(const Ee of it.edges)(Ee.source===be||Ee.target===be)&&(ie.add(Ee.id),B.add(Ee.source),B.add(Ee.target));return{nodes:B,edges:ie}}if(ke){const Ee=it.edges.find(He=>He.id===ke);Ee&&(ie.add(Ee.id),B.add(Ee.source),B.add(Ee.target))}return{nodes:B,edges:ie}},[it.edges,hr,An]);_.useEffect(()=>{Fr(""),Jr(""),jr(""),Sr("")},[C]);const[Ki,ln]=_.useState(!1);_.useEffect(()=>{ln(!1)},[C]),_.useEffect(()=>{lt||(ht.current=null)},[lt]),_.useEffect(()=>{if(We!=="force")return;const B=ht.current;if(!B)return;const ie=Qd(Se);B.options.springLength=ie.springLength,B.options.repulsionStrength=ie.repulsionStrength},[We,Se]),_.useEffect(()=>{We!=="force"&&lt&&Ke(!1)},[We,lt]),_.useEffect(()=>{if(!lt||We!=="force"||it.nodes.length===0||typeof window>"u"||typeof window.requestAnimationFrame!="function")return;ht.current||(ht.current=qh(it,{seed:Fe,positions:In.current,...Qd(Se)}));let B=0,ie=0,be=0;const ke=it.nodes.length<=140?2:1,Ee=1600,He=.08,Qe=ot=>{if(B=window.requestAnimationFrame(Qe),ot-ie<33)return;ie=ot;const mt=ht.current;if(!mt){Ke(!1);return}D3(mt,ke),be+=ke,gn(z3(mt)),(F3(mt)<=He||be>=Ee)&&Ke(!1)};return B=window.requestAnimationFrame(Qe),()=>{window.cancelAnimationFrame(B)}},[it,We,lt,Fe]);const fa=_.useMemo(()=>it.nodes.map(B=>{var un;const ie=Gi.has(B.id),be=$o.has(B.id),ke=An===B.id,Ee=mr&&da.nodes.has(B.id),He=ef((un=B.data)==null?void 0:un.kind),Qe="rgba(34, 211, 238, 0.88)",ot=be?"0 0 0 1px rgba(34, 211, 238, 0.34), 0 0 16px rgba(34, 211, 238, 0.26), 0 0 44px rgba(34, 211, 238, 0.14)":"",mt=ie?"rgba(168, 85, 247, 0.9)":be?Qe:He.stroke,Dt=ke?"0 0 0 2px rgba(255,255,255,0.20), 0 18px 46px rgba(0,0,0,0.55)":Ee?"0 0 0 1px rgba(96, 165, 250, 0.28), 0 12px 34px rgba(0,0,0,0.45)":void 0,Xt=ot&&Dt?`${ot}, ${Dt}`:Dt||ot||void 0,Xn=ie?"rgba(168, 85, 247, 0.10)":be?"rgba(34, 211, 238, 0.08)":He.bg,Bt=ms?ie||ke?1:.16:mr?Ee||ke?1:.1:1;return{...B,position:$n[B.id]?{x:$n[B.id].x,y:$n[B.id].y}:B.position,style:{...B.style||{},border:`1px solid ${mt}`,borderRadius:10,background:Xn,color:"rgba(255,255,255,0.92)",opacity:Bt,padding:8,fontSize:12,boxShadow:Xt,width:180,cursor:"pointer"}}}),[it.nodes,ms,$o,$n,An,Gi,mr,da.nodes]),uc=_.useMemo(()=>it.edges.map(B=>{const ie=ai.has(B.id),be=hr===B.id,ke=mr&&da.edges.has(B.id),Ee=ie?"rgba(168, 85, 247, 0.9)":mr?ke||be?"rgba(96, 165, 250, 0.55)":"rgba(255,255,255,0.14)":"rgba(255,255,255,0.18)",He=ie?2.75:mr?ke||be?2.25:1.25:1.5,Qe=be?"drop-shadow(0 0 10px rgba(168, 85, 247, 0.25))":void 0,ot=ie?"rgba(168, 85, 247, 0.9)":ms?"rgba(255,255,255,0.10)":"rgba(255,255,255,0.28)",mt=ms?ie||be?1:.1:mr?ke||be?1:.08:1,Dt=ms?ie||be?1:0:mr?ke||be?1:0:1,Xt=ms?ie||be?String(B.label||""):"":String(B.label||"");return{...B,label:Xt,style:{...B.style||{},stroke:Ee,strokeWidth:He,filter:Qe,opacity:mt},animated:!1,markerEnd:{type:bf.ArrowClosed,color:ot,width:20,height:20},labelShowBg:!0,labelBgPadding:[6,3],labelBgBorderRadius:10,labelBgStyle:{fill:`rgba(0, 0, 0, ${.38*Dt})`,stroke:`rgba(255, 255, 255, ${.14*Dt})`,strokeWidth:1},labelStyle:{fill:`rgba(255, 255, 255, ${.92*Dt})`,fontSize:10,fontWeight:600,letterSpacing:.2,textTransform:"lowercase"}}}),[it.edges,ms,hr,ai,mr,da.edges]),To=_.useMemo(()=>{if(!hr)return[];const B=it.edges.find(be=>be.id===hr),ie=B&&B.data&&Array.isArray(B.data.assertions)?B.data.assertions:[];return Array.isArray(ie)?ie:[]},[it.edges,hr]),_r=_.useMemo(()=>hr&&it.edges.find(B=>B.id===hr)||null,[it.edges,hr]),Es=_.useMemo(()=>{const B=String(An||"").trim();return B?Or.filter(ie=>!ie||typeof ie!="object"||!(ie.subject===B||ie.object===B)?!1:R?!0:!ep(ie.predicate,hs)):[]},[Or,An,R,hs]),$s=_.useMemo(()=>hr?To:Es,[To,hr,Es]),Yi=_.useMemo(()=>{const B=new Map;for(const ie of $s){if(!ie||typeof ie!="object")continue;const be=ie.provenance&&typeof ie.provenance=="object"&&!Array.isArray(ie.provenance)?ie.provenance:null,ke=be&&typeof be.span_id=="string"?be.span_id.trim():"",Ee=be&&typeof be.writer_run_id=="string"?be.writer_run_id.trim():"",He=typeof ie.owner_id=="string"?ie.owner_id.trim():"",Qe=Ee||He;if(!Qe||!ke)continue;const ot=`${Qe}|${ke}`,mt=B.get(ot),Dt=typeof ie.observed_at=="string"?ie.observed_at.trim():"";mt?(mt.count+=1,Dt&&(!mt.last_observed_at||Dt>mt.last_observed_at)&&(mt.last_observed_at=Dt,mt.last_observed_at_fmt=tf(Dt),mt.assertion=ie)):B.set(ot,{span_run_id:Qe,span_id:ke,writer_run_id:Ee,count:1,last_observed_at:Dt,last_observed_at_fmt:tf(Dt),assertion:ie})}return Array.from(B.values()).sort((ie,be)=>String(be.last_observed_at||"").localeCompare(String(ie.last_observed_at||"")))},[$s]),_s=_.useMemo(()=>{const B=new Map;for(const ie of $s){if(!ie||typeof ie!="object")continue;const be=ie.provenance&&typeof ie.provenance=="object"&&!Array.isArray(ie.provenance)?ie.provenance:null,ke=be&&typeof be.span_id=="string"?be.span_id.trim():"",Ee=be&&typeof be.writer_run_id=="string"?be.writer_run_id.trim():"";if(!Ee||ke)continue;const He=B.get(Ee),Qe=typeof ie.observed_at=="string"?ie.observed_at.trim():"";He?(He.count+=1,Qe&&(!He.last_observed_at||Qe>He.last_observed_at)&&(He.last_observed_at=Qe,He.last_observed_at_fmt=tf(Qe),He.assertion=ie)):B.set(Ee,{run_id:Ee,count:1,last_observed_at:Qe,last_observed_at_fmt:tf(Qe),assertion:ie})}return Array.from(B.values()).sort((ie,be)=>String(be.last_observed_at||"").localeCompare(String(ie.last_observed_at||"")))},[$s]),kr=_.useCallback(B=>{const ie=String(B.run_id||"").trim(),be=typeof B.span_id=="string"?String(B.span_id).trim():"";if(ie){if(S){try{S({run_id:ie,span_id:be||void 0,assertion:B.assertion})}catch{}return}if(x&&be)try{x({run_id:ie,span_id:be,assertion:B.assertion})}catch{}}},[x,S]),ps=_.useCallback(async B=>{var be;const ie=String(B??"");if(ie){try{if(typeof((be=navigator.clipboard)==null?void 0:be.writeText)=="function"){await navigator.clipboard.writeText(ie);return}}catch{}try{const ke=document.createElement("textarea");ke.value=ie,ke.style.position="fixed",ke.style.left="-9999px",document.body.appendChild(ke),ke.select(),document.execCommand("copy"),document.body.removeChild(ke)}catch{}}},[]),As=_.useCallback(()=>{const B=j.current;if(!(!B||typeof B.fitView!="function")){if(An&&typeof B.getNode=="function"){const ie=B.getNode(An);if(ie){B.fitView({nodes:[ie],padding:.55,duration:350});return}}B.fitView({padding:.2,duration:350})}},[An]),Xr=_.useCallback(B=>{const ie=B.kind,be=Math.trunc(B.seed);Ke(!1),ht.current=null,xe.current=null,pt(ie),tt(be);const ke=uu(it,{kind:ie,seed:be});gn(ke),ie==="force"&&(B.autoPlay??!0)&&it.nodes.length>0&&it.nodes.length<=320&&(ht.current=qh(it,{seed:be,positions:ke,...Qd(Se)}),Ke(!0))},[it,Se]),ki=_.useCallback(()=>{if(We==="force"){if(lt){Ke(!1);return}ht.current=qh(it,{seed:Fe,positions:In.current,...Qd(Se)}),Ke(!0)}},[it,We,lt,Fe,Se]);_.useEffect(()=>()=>{typeof window>"u"||typeof window.cancelAnimationFrame=="function"&&kn.current&&window.cancelAnimationFrame(kn.current)},[]);const ir=_.useCallback(()=>{const B=j.current;if(!B||typeof B.getViewport!="function"||!cn.length)return null;const ie=en.current;if(!ie)return null;const be=ie.getBoundingClientRect();if(!Number.isFinite(be.width)||!Number.isFinite(be.height)||be.width<64||be.height<64)return null;const ke=B.getViewport(),Ee=typeof(ke==null?void 0:ke.zoom)=="number"&&Number.isFinite(ke.zoom)?ke.zoom:null,He=typeof(ke==null?void 0:ke.x)=="number"&&Number.isFinite(ke.x)?ke.x:null,Qe=typeof(ke==null?void 0:ke.y)=="number"&&Number.isFinite(ke.y)?ke.y:null;if(Ee===null||He===null||Qe===null||Ee<=0)return null;const ot=140,mt=Math.min(cn.length,180),Dt=In.current;let Xt=0,Xn=0;for(const Bt of cn){const un=Dt[Bt];if(!un||!Number.isFinite(un.x)||!Number.isFinite(un.y))continue;Xn+=1;const vn=[{x:un.x,y:un.y},{x:un.x+90,y:un.y+24}];for(const jn of vn){const pr=jn.x*Ee+He,Nr=jn.y*Ee+Qe;if(pr>-ot&&pr<be.width+ot&&Nr>-ot&&Nr<be.height+ot)return!1}if(Xt++,Xt>=mt)break}return Xn?!0:null},[cn]),Ts=_.useCallback(B=>{typeof window>"u"||typeof window.requestAnimationFrame!="function"||kn.current||(kn.current=window.requestAnimationFrame(()=>{kn.current=0;const ie=ir();if(ie===null){if(It.current>=12)return;It.current+=1,window.setTimeout(()=>Ts(`${B}:probe`),120);return}if(ie!==!0){It.current=0,Wt.current=0;return}It.current=0;const be=j.current;if(be&&typeof be.fitView=="function")try{be.fitView({padding:.2,duration:0})}catch{try{be.fitView({padding:.2})}catch{}}if(Wt.current+=1,Wt.current>=4&&bn.current<1){Wt.current=0,bn.current+=1,zt(ke=>ke+1);return}Wt.current<8&&window.setTimeout(()=>Ts(`${B}:retry`),220)}))},[ir]);_.useEffect(()=>{Wt.current=0,bn.current=0,It.current=0,Ts("mount")},[C,Ts]),_.useEffect(()=>{Ts("graph change")},[Dr,Ts]),_.useEffect(()=>{const B=en.current;if(!B||typeof window>"u"||typeof ResizeObserver!="function")return;const ie=new ResizeObserver(()=>Ts("resize"));return ie.observe(B),()=>ie.disconnect()},[Ts]);const ha=_.useCallback(()=>{const B=new Date().toISOString(),ie={};for(const Qe of cn){const ot=In.current[Qe];ot&&typeof ot.x=="number"&&typeof ot.y=="number"&&(ie[Qe]={x:ot.x,y:ot.y})}const be=j.current,ke=be&&typeof be.toObject=="function"?be.toObject():null,Ee=ke&&ke.viewport?ke.viewport:be&&typeof be.getViewport=="function"?be.getViewport():null,He=S0(Ee,{minZoom:Zp,maxZoom:Qp,maxAbsTranslate:C0})??void 0;q3(Ne,{version:1,kind:We,seed:Fe,positions:ie,viewport:He,saved_at:B}),Pt(!0),Bn(B),Ke(!1)},[Ne,We,Fe,cn]),gs=_.useCallback(()=>{const B=dv(Ne);if(!B)return;Ke(!1),ht.current=null,pt(B.kind),tt(B.seed),Pt(!0),Bn(B.saved_at||""),xe.current=B.viewport||null,Ie.current=!B.viewport;const ie=uu(it,{kind:B.kind,seed:B.seed});if(gn(Ao(B.positions,ie)),B.viewport){const be=j.current;if(be&&typeof be.setViewport=="function"){try{be.setViewport(B.viewport,{duration:0})}catch{try{be.setViewport(B.viewport)}catch{}}xe.current=null}}},[Ao,it,Ne]),Ji=_.useCallback(()=>{H3(Ne),Pt(!1),Bn("")},[Ne]),dc=_.useCallback(B=>{if(!Array.isArray(B)||B.length===0)return;let ie=!1;gn(be=>{let ke=be,Ee=!1;for(const He of B){const Qe=He&&typeof He=="object"&&"id"in He&&typeof He.id=="string"?String(He.id):"",ot=(He==null?void 0:He.type)==="position"?He==null?void 0:He.position:null;Qe&&ot&&typeof ot.x=="number"&&typeof ot.y=="number"&&(Ee||(ke={...be},Ee=!0),ke[Qe]={x:ot.x,y:ot.y},He!=null&&He.dragging&&(ie=!0))}return Ee?ke:be}),ie&&lt&&Ke(!1)},[lt]),Ni=_.useMemo(()=>{const B=new Map;for(const ie of it.edges)B.set(ie.id,ie);return B},[it.edges]),Zr=_.useMemo(()=>{var ke;if(!On)return[];const B=On.nodeIds||[],ie=On.edgeIds||[],be=[];for(let Ee=0;Ee<Math.min(B.length-1,ie.length);Ee++){const He=B[Ee],Qe=B[Ee+1],ot=ie[Ee],mt=Ni.get(ot),Dt=String(((ke=mt==null?void 0:mt.data)==null?void 0:ke.predicateSummary)||(mt==null?void 0:mt.label)||"").trim(),Xt=mt&&mt.source===He&&mt.target===Qe?"forward":mt&&mt.source===Qe&&mt.target===He?"reverse":"unknown";be.push({from:He,to:Qe,edgeId:ot,predicate:Dt,dir:Xt})}return be},[Ni,On]),Au=_.useCallback(async()=>{if(g){ce(""),A(""),Y(!0);try{const B=V3(qt),ie=Q_($t,{allowZero:!0,allowNegativeOne:!0}),be=Q_(De,{allowZero:!0}),ke=await g({scope:Pn,owner_id:void 0,recall_level:je,query_text:Ge||void 0,subject:ct||void 0,predicate:jt||void 0,object:xt||void 0,min_score:B,limit:ie,max_input_tokens:be,model:dt||void 0});I(ke),U("live query"),E==="replace"&&w&&ke&&Array.isArray(ke.items)&&w(ke.items,{kind:"live query",result:ke})}catch(B){const ie=B instanceof Error?B.message:String(B);ce(ie||"Query failed")}finally{Y(!1)}}},[$t,De,qt,dt,xt,w,g,jt,E,Ge,je,Pn,ct]),Qr=_.useCallback(async()=>{if(!g)return;const B=String(wn||"").trim(),ie=String(Kn||"").trim();if(!B||!ie)return;const be=Math.max(200,Q_($t)??80),ke=60;A(""),ce(""),W(!0);try{const Ee=[],He=new Set,Qe=Bt=>{if(!Bt||typeof Bt!="object"||typeof Bt.subject!="string"||typeof Bt.predicate!="string"||typeof Bt.object!="string")return;const un=`${Bt.subject}|${Bt.predicate}|${Bt.object}|${String(Bt.observed_at||"")}|${String(Bt.scope||"")}|${String(Bt.owner_id||"")}`;He.has(un)||(He.add(un),Ee.push(Bt))};for(const Bt of Or)Qe(Bt);const ot=F,mt=new Set,Dt=[B],Xt=new Set([B]),Xn=async Bt=>{const un=await g({scope:Pn,recall_level:je,min_score:0,limit:be,subject:Bt,query_text:void 0,max_input_tokens:0,model:void 0});if(un&&Array.isArray(un.items)){for(const vn of un.items)if(Qe(vn),typeof vn.subject=="string"&&vn.subject.trim()===Bt&&typeof vn.object=="string"){const jn=vn.object.trim();jn&&!Xt.has(jn)&&(Xt.add(jn),Dt.push(jn))}}if(!ot){const vn=await g({scope:Pn,recall_level:je,min_score:0,limit:be,object:Bt,query_text:void 0,max_input_tokens:0,model:void 0});if(vn&&Array.isArray(vn.items)){for(const jn of vn.items)if(Qe(jn),typeof jn.object=="string"&&jn.object.trim()===Bt&&typeof jn.subject=="string"){const pr=jn.subject.trim();pr&&!Xt.has(pr)&&(Xt.add(pr),Dt.push(pr))}}}};for(;Dt.length&&mt.size<ke&&!Xt.has(ie);){const Bt=Dt.shift();!Bt||mt.has(Bt)||(mt.add(Bt),await Xn(Bt))}I({ok:!0,count:Ee.length,items:Ee,active_memory_text:ue,raw:{expanded_for_path:!0,expanded_nodes:mt.size,discovered_nodes:Xt.size,merged:Ee.length,directed:ot}}),U("expanded neighborhood"),E==="replace"&&w&&w(Ee,{kind:"expanded neighborhood",result:{ok:!0,count:Ee.length,items:Ee,active_memory_text:ue,raw:{expanded_for_path:!0,expanded_nodes:mt.size,discovered_nodes:Xt.size,merged:Ee.length,directed:ot}}})}catch(Ee){const He=Ee instanceof Error?Ee.message:String(Ee);A(He||"Expand neighborhood failed")}finally{W(!1)}},[F,ue,Or,$t,w,g,Kn,wn,E,je,Pn]),Xi=_.useCallback(()=>{I(null),U(null),ce(""),Y(!1),A(""),W(!1),jr(""),Sr(""),Fr(""),Jr("")},[]),es="Search KG",Mo=it.nodes.length,li=it.edges.length,al=Cs.length;return r.jsx("div",{className:"amx-host",children:r.jsxs("div",{className:"amx-root",children:[r.jsxs("div",{className:"amx-left",children:[r.jsx("div",{className:"amx-graphbar",role:"toolbar","aria-label":"Graph layout controls",children:r.jsxs("div",{className:"amx-graphbar-row",children:[r.jsx("span",{className:"amx-graphbar-title",children:"layout"}),r.jsxs("select",{value:We,onChange:B=>pt(eg(B.target.value,We)),disabled:!cn.length,children:[r.jsx("option",{value:"grid",children:"grid (deterministic)"}),r.jsx("option",{value:"radial",children:"radial (bfs)"}),r.jsx("option",{value:"circle",children:"circle"}),r.jsx("option",{value:"force",children:"force (simulation)"})]}),We==="force"?r.jsxs("label",{className:"amx-graphbar-spread",children:[r.jsx("span",{className:"amx-graphbar-title",children:"spread"}),r.jsx("input",{type:"range",min:"0.7",max:"2.2",step:"0.1",value:Se,onChange:B=>Re(N0(Number(B.target.value),.7,2.2,1))}),r.jsxs("span",{className:"amx-small",children:[Se.toFixed(1),"×"]})]}):null,r.jsx("button",{type:"button",className:"amx-btn",onClick:()=>Xr({kind:We,seed:Fe}),disabled:!cn.length,children:"Apply"}),r.jsx("button",{type:"button",className:"amx-btn",onClick:ki,disabled:!cn.length||We!=="force",children:lt?"Pause simulation":"Play simulation"})]})}),r.jsxs("div",{className:"amx-graph","aria-label":"Knowledge graph",ref:en,children:[r.jsx(zg,{children:r.jsxs(w0,{nodes:fa,edges:uc,defaultViewport:{x:0,y:0,zoom:1},minZoom:Zp,maxZoom:Qp,onInit:B=>{j.current=B;const ie=xe.current;if(ie&&typeof B.setViewport=="function")try{B.setViewport(ie,{duration:0})}catch{try{B.setViewport(ie)}catch{}}if(Ie.current&&typeof B.fitView=="function")try{B.fitView({padding:.2,duration:0})}catch{try{B.fitView({padding:.2})}catch{}}xe.current=null,Ie.current=!1,Ts("init")},nodesDraggable:!0,nodesConnectable:!1,elementsSelectable:!0,onNodesChange:dc,onNodeClick:(B,ie)=>{Jr(""),Fr(ie.id)},onEdgeClick:(B,ie)=>{Fr(""),Jr(ie.id)},onPaneClick:()=>{Fr(""),Jr("")},children:[r.jsx(k3,{className:"amx-flow-controls",children:r.jsx(mu,{type:"button",className:`amx-control-legend ${pe?"amx-control-legend-active":""}`,onClick:()=>ye(B=>!B),title:pe?"Hide node color legend":"Show node color legend","aria-label":pe?"Hide node color legend":"Show node color legend",children:r.jsx(U3,{})})}),r.jsx(wf,{position:"bottom-right",className:"amx-panel-bottom-right",children:r.jsx("div",{className:"amx-panel-toggles",children:r.jsx("button",{type:"button",className:"amx-minimap-toggle",onClick:()=>ge(B=>!B),title:le?"Hide minimap preview":"Show minimap preview","aria-label":le?"Hide minimap preview":"Show minimap preview",children:le?"minimap on":"minimap off"})})}),le?r.jsx(y3,{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:Q?120:160,height:Q?80:110,marginBottom:56},nodeColor:B=>{var ie;return ef((ie=B.data)==null?void 0:ie.kind).minimap}}):null,pe?r.jsxs(wf,{position:"bottom-left",className:"amx-legend-panel",children:[r.jsx("div",{className:"amx-legend-title",children:"node colors"}),r.jsx("div",{className:"amx-legend",children:[{k:"person",label:"person"},{k:"org",label:"org"},{k:"concept",label:"concept"},{k:"claim",label:"claim"},{k:"event",label:"event"},{k:"doc",label:"doc"},{k:"vocab",label:"vocab"}].map(({k:B,label:ie})=>r.jsx("span",{className:"amx-legend-item",style:{borderColor:ef(B).stroke},children:ie},B))})]}):null,r.jsx(T3,{gap:20,size:1,color:"rgba(255,255,255,0.06)"})]})},qe),r.jsxs("details",{className:"amx-panel amx-controls",children:[r.jsxs("summary",{children:[r.jsx("span",{className:"amx-controls-title",children:es}),r.jsxs("span",{className:"amx-small",children:[al," assertions · ",Mo," nodes · ",li," edges"]})]}),r.jsxs("div",{className:"amx-toolbar",style:{marginTop:10},children:[r.jsxs("div",{className:"amx-toolbar-grid",children:[r.jsxs("label",{children:["search / highlight",r.jsx("input",{value:z,onChange:B=>$(B.target.value),placeholder:"filter nodes by id/label"})]}),r.jsxs("label",{children:["group edges",r.jsxs("select",{value:String(te),onChange:B=>O(B.target.value==="true"),children:[r.jsx("option",{value:"true",children:"group (subject→object)"}),r.jsx("option",{value:"false",children:"no grouping"})]})]}),r.jsxs("label",{children:["view",r.jsxs("select",{value:String(R),onChange:B=>Z(B.target.value==="true"),children:[r.jsx("option",{value:"true",children:"all assertions"}),r.jsx("option",{value:"false",children:"hide rdf:type / labels"})]})]}),r.jsxs("label",{children:["path mode",r.jsxs("select",{value:String(F),onChange:B=>G(B.target.value==="true"),children:[r.jsx("option",{value:"false",children:"undirected"}),r.jsx("option",{value:"true",children:"directed"})]})]})]}),r.jsxs("details",{className:"amx-details",children:[r.jsx("summary",{children:"layout"}),r.jsxs("div",{className:"amx-toolbar-grid",style:{marginTop:10},children:[r.jsxs("label",{children:["layout",r.jsxs("select",{value:We,onChange:B=>pt(eg(B.target.value,We)),children:[r.jsx("option",{value:"grid",children:"grid (deterministic)"}),r.jsx("option",{value:"radial",children:"radial (bfs)"}),r.jsx("option",{value:"circle",children:"circle"}),r.jsx("option",{value:"force",children:"force (simulation)"})]})]}),r.jsxs("label",{children:["seed",r.jsx("input",{type:"number",step:"1",value:Fe,onChange:B=>tt(Math.trunc(Number(B.target.value||0)||0))})]})]}),r.jsxs("div",{className:"amx-actions",style:{marginTop:10},children:[r.jsx("button",{type:"button",className:"amx-btn",onClick:()=>Xr({kind:We,seed:Fe}),disabled:!cn.length,children:"Apply layout"}),We==="force"?r.jsx("button",{type:"button",className:"amx-btn",onClick:ki,disabled:!cn.length,children:lt?"Pause simulation":"Play simulation"}):null,r.jsx("button",{type:"button",className:"amx-btn",onClick:ha,disabled:!cn.length,children:"Save layout"}),nr?r.jsxs(r.Fragment,{children:[r.jsx("button",{type:"button",className:"amx-btn",onClick:gs,children:"Load saved"}),r.jsx("button",{type:"button",className:"amx-btn",onClick:Ji,children:"Clear saved"})]}):null]}),r.jsxs("div",{className:"amx-small",style:{marginTop:10,opacity:.9},children:["Drag nodes to adjust manually; use ",r.jsx("span",{className:"amx-mono",children:"Save layout"})," for a stable, replayable view.",nr?r.jsxs("span",{children:[" ","(saved",pn?`: ${pn}`:"",")"]}):r.jsx("span",{children:" (no saved layout)"})]})]}),r.jsxs("details",{className:"amx-details",children:[r.jsx("summary",{children:"path"}),r.jsxs("div",{className:"amx-toolbar-grid",style:{marginTop:10},children:[r.jsxs("label",{children:["path start",r.jsxs("select",{value:wn,onChange:B=>jr(B.target.value),children:[r.jsx("option",{value:"",children:"(none)"}),cn.map(B=>r.jsx("option",{value:B,children:(()=>{const ie=Hs.get(B)||B;return ie===B?ie:`${ie} (${B})`})()},B))]})]}),r.jsxs("label",{children:["path end",r.jsxs("select",{value:Kn,onChange:B=>Sr(B.target.value),children:[r.jsx("option",{value:"",children:"(none)"}),cn.map(B=>r.jsx("option",{value:B,children:(()=>{const ie=Hs.get(B)||B;return ie===B?ie:`${ie} (${B})`})()},B))]})]})]}),On?r.jsx("div",{className:"amx-small",style:{marginTop:10},children:Zr.map((B,ie)=>{const be=Hs.get(B.from)||B.from,ke=Hs.get(B.to)||B.to,Ee=B.dir==="reverse"?" ← ":" → ",He=B.predicate?` (${B.predicate})`:"";return r.jsxs("div",{children:[ie===0?r.jsx("span",{children:be}):null,Ee,r.jsxs("span",{children:[ke,He]})]},`${B.edgeId}:${ie}`)})}):wn&&Kn?r.jsxs("div",{className:"amx-small",style:{marginTop:10,opacity:.9},children:["No path found in the current subgraph (",(Hn==null?void 0:Hn.assertions)??al," assertions · ",(Hn==null?void 0:Hn.nodes)??it.nodes.length," nodes ·"," ",(Hn==null?void 0:Hn.edges)??it.edges.length," edges). Start reaches ",(Hn==null?void 0:Hn.reachableFromStart)??0," nodes.",g?r.jsx("div",{style:{marginTop:10},children:r.jsx("button",{type:"button",className:"amx-btn",onClick:()=>void Qr(),disabled:fe,children:fe?"Expanding…":"Expand neighborhood"})}):null]}):r.jsx("div",{className:"amx-small",style:{marginTop:10},children:"(no path)"})]}),r.jsxs("details",{className:"amx-details",children:[r.jsx("summary",{children:"query"}),r.jsxs("div",{className:"amx-toolbar-grid",style:{marginTop:10},children:[r.jsxs("label",{children:["query_text (semantic)",r.jsx("input",{value:Ge,onChange:B=>st(B.target.value),placeholder:"e.g. emotion chip"})]}),r.jsxs("label",{children:["subject (exact)",r.jsx("input",{value:ct,onChange:B=>Et(B.target.value),placeholder:"e.g. ex:person-data"})]}),r.jsxs("label",{children:["predicate (exact)",r.jsx("input",{value:jt,onChange:B=>Kt(B.target.value),placeholder:"e.g. schema:about"})]}),r.jsxs("label",{children:["object (exact)",r.jsx("input",{value:xt,onChange:B=>Yt(B.target.value),placeholder:"e.g. ex:concept-emotion-chip"})]}),r.jsxs("label",{children:["min_score",r.jsx("input",{type:"number",step:"any",value:qt,onChange:B=>Ot(B.target.value),placeholder:"(auto)"})]}),r.jsxs("label",{children:["limit",r.jsx("input",{type:"number",min:"-1",step:"1",value:$t,onChange:B=>At(B.target.value),placeholder:"0/-1 = unlimited (if supported)"})]})]})]}),r.jsxs("details",{className:"amx-details",children:[r.jsx("summary",{children:"advanced"}),r.jsxs("div",{className:"amx-toolbar-grid",style:{marginTop:10},children:[r.jsxs("label",{children:["scope",r.jsxs("select",{value:Pn,onChange:B=>ae(uv(B.target.value,Pn)),children:[r.jsx("option",{value:"run",children:"run"}),r.jsx("option",{value:"session",children:"session"}),r.jsx("option",{value:"global",children:"global"}),r.jsx("option",{value:"all",children:"all"})]})]}),r.jsxs("label",{children:["recall level",r.jsxs("select",{value:je,onChange:B=>Ye(B.target.value||"standard"),children:[r.jsx("option",{value:"urgent",children:"urgent"}),r.jsx("option",{value:"standard",children:"standard"}),r.jsx("option",{value:"deep",children:"deep"})]})]}),r.jsxs("label",{children:["max_input_tokens",r.jsx("input",{type:"number",min:"0",step:"1",value:De,onChange:B=>on(B.target.value),placeholder:"(auto)"})]}),r.jsxs("label",{children:["model (budgeting)",r.jsx("input",{value:dt,onChange:B=>tn(B.target.value),placeholder:"qwen/qwen3-next-80b"})]})]})]}),r.jsxs("div",{className:"amx-actions",children:[r.jsx("button",{type:"button",className:"amx-btn",onClick:()=>void Au(),disabled:!g||J,children:J?"Querying…":"Query store"}),r.jsx("button",{type:"button",className:"amx-btn",onClick:Xi,disabled:!T&&!se&&!J,children:"Reset to step output"}),T?r.jsxs("span",{className:"amx-small",children:["showing: ",K||"live query"]}):r.jsx("span",{className:"amx-small",children:"showing: step output"}),se?r.jsx("span",{className:"amx-small",style:{color:"var(--error, rgba(255, 80, 80, 0.95))"},children:se}):null,P?r.jsx("span",{className:"amx-small",style:{color:"var(--error, rgba(255, 80, 80, 0.95))"},children:P}):null]})]})]})]})]}),r.jsxs("div",{className:"amx-right",children:[r.jsxs("div",{className:"amx-panel",children:[r.jsx("h3",{children:"Details"}),r.jsx("div",{className:"amx-small",style:{marginBottom:8},children:"Derived from `memory_kg_query` packetization (max_input_tokens); safe to inject into an LLM system prompt."}),(()=>{const B=G3(fs);return B?r.jsx("div",{className:"amx-small",style:{marginBottom:8,opacity:.9},children:B}):null})(),(()=>{const B=Vi;if(!B)return null;const ie=typeof B=="string"?B:Array.isArray(B)?B.map(be=>String(be)).join(" · "):JSON.stringify(B);return!ie||!ie.trim()?null:r.jsx("div",{className:"amx-small",style:{marginBottom:8,color:"var(--warning, rgba(255, 180, 90, 0.95))"},children:ie})})(),r.jsx("div",{className:"amx-small",style:{marginBottom:8,opacity:.9},children:(()=>{const B=(T==null?void 0:T.packets_version)??Yr,ie=(T==null?void 0:T.packed_count)??rr,be=(T==null?void 0:T.dropped)??Ws,ke=(T==null?void 0:T.estimated_tokens)??ds,Ee=[];return typeof B=="number"&&Ee.push(`packets_v${B}`),typeof ie=="number"&&Ee.push(`packed=${ie}`),typeof be=="number"&&Ee.push(`dropped=${be}`),typeof ke=="number"&&Ee.push(`est_tokens=${ke}`),Ee.length?Ee.join(" · "):"No packetization stats (set max_input_tokens > 0)."})()}),r.jsx("div",{className:"amx-active-memory",children:Y3(ue||"(empty)",z)}),(()=>{const B=T!=null&&T.packets&&Array.isArray(T.packets)?T.packets:an;return!Array.isArray(B)||B.length===0?null:r.jsxs("div",{style:{marginTop:10},children:[r.jsxs("button",{type:"button",className:"amx-btn",onClick:()=>ln(ie=>!ie),children:[Ki?"Hide":"Show"," packets (",B.length,")"]}),Ki?r.jsx("div",{className:"amx-list",style:{marginTop:10},children:B.slice(0,120).map((ie,be)=>{const ke=ie&&typeof ie=="object"&&!Array.isArray(ie)?ie:null,Ee=ke&&typeof ke.statement=="string"?ke.statement:typeof ie=="string"?ie:"",He=ke&&(typeof ke.retrieval_score=="number"||typeof ke.retrieval_score=="string")?ke.retrieval_score:null,Qe=ke&&typeof ke.observed_at=="string"?ke.observed_at:null;return r.jsxs("div",{className:"amx-item",children:[r.jsx("div",{className:"amx-mono",children:Ee||"(packet)"}),Qe||He!==null?r.jsxs("div",{className:"amx-small",children:[Qe?`[${Qe}]`:null,Qe&&He!==null?" ":null,He!==null?`score:${He}`:null]}):null]},be)})}):null]})})(),r.jsx("div",{style:{marginTop:14,marginBottom:12,borderTop:"1px solid var(--ui-border-1, rgba(255,255,255,0.08))"}}),r.jsx("div",{className:"amx-small",style:{marginBottom:8,fontWeight:700,opacity:.9},children:"Inspect"}),r.jsx("div",{className:"amx-small",style:{marginBottom:8},children:"Click a node or edge to inspect its assertions."}),An?r.jsxs("div",{className:"amx-item",style:{marginBottom:10,display:"flex",justifyContent:"space-between",gap:10,alignItems:"center"},children:[r.jsxs("div",{style:{minWidth:0},children:[r.jsx("div",{className:"amx-mono",style:{fontSize:11,opacity:.95},children:Hs.get(An)||An}),r.jsxs("div",{className:"amx-small",children:["kind=",sr.get(An)||"entity"," · id=",An]})]}),r.jsxs("div",{className:"amx-actions",children:[r.jsx("button",{type:"button",className:"amx-btn",onClick:()=>void ps(An),children:"Copy id"}),r.jsx("button",{type:"button",className:"amx-btn",onClick:As,children:"Focus"})]})]}):_r&&_r.source&&_r.target?r.jsxs("div",{className:"amx-item",style:{marginBottom:10,display:"flex",justifyContent:"space-between",gap:10,alignItems:"center"},children:[r.jsxs("div",{style:{minWidth:0},children:[r.jsxs("div",{className:"amx-mono",style:{fontSize:11,opacity:.95},children:[_r.source," —",String(_r.label||((ci=_r.data)==null?void 0:ci.predicateSummary)||"").trim()||"?","→ ",_r.target]}),r.jsxs("div",{className:"amx-small",children:["edge_id=",_r.id]})]}),r.jsxs("div",{className:"amx-actions",children:[r.jsx("button",{type:"button",className:"amx-btn",onClick:()=>void ps(_r.id),children:"Copy id"}),r.jsx("button",{type:"button",className:"amx-btn",onClick:As,children:"Fit"})]})]}):r.jsx("div",{className:"amx-small",style:{marginBottom:10,opacity:.9},children:"(no selection)"}),r.jsx("div",{className:"amx-list",children:$s.slice(0,80).map((B,ie)=>{const be=String(B.subject||"").trim(),ke=String(B.predicate||"").trim(),Ee=String(B.object||"").trim(),He=Hs.get(be)||be,Qe=Hs.get(Ee)||Ee,ot=sr.get(be)||"entity",mt=sr.get(Ee)||"entity",Dt=ef(ot),Xt=ef(mt),Xn=tf(B.observed_at),Bt=K3(B),un=B.provenance&&typeof B.provenance=="object"&&!Array.isArray(B.provenance)?B.provenance:null,vn=un&&typeof un.span_id=="string"?un.span_id.trim():"",jn=un&&typeof un.writer_run_id=="string"?un.writer_run_id.trim():"",pr=typeof B.owner_id=="string"?B.owner_id.trim():"",Nr=jn||pr,ys=!!((S||x)&&vn&&Nr),Ro=!!(S&&jn&&!vn),Lo=ys||Ro;return r.jsxs("div",{className:"amx-item amx-triple-card",children:[r.jsxs("div",{className:"amx-triple-row",children:[r.jsx("button",{type:"button",className:"amx-term",style:{borderColor:Dt.stroke,background:Dt.bg},title:be,onClick:()=>{be&&(Jr(""),Fr(be))},children:He||be||"(subject)"}),r.jsx("span",{className:"amx-arrow",children:"—"}),r.jsx("span",{className:"amx-predicate",title:ke,children:E0(ke)||"(predicate)"}),r.jsx("span",{className:"amx-arrow",children:"→"}),r.jsx("button",{type:"button",className:"amx-term",style:{borderColor:Xt.stroke,background:Xt.bg},title:Ee,onClick:()=>{Ee&&(Jr(""),Fr(Ee))},children:Qe||Ee||"(object)"})]}),r.jsxs("div",{className:"amx-triple-meta",children:[Xn?r.jsxs("span",{className:"amx-small",title:String(B.observed_at||""),children:["[",Xn,"]"]}):null,Bt?r.jsx("span",{className:"amx-small",children:Bt}):null]}),vn||jn?r.jsxs("div",{className:"amx-triple-actions",children:[vn?r.jsxs("span",{className:"amx-small",children:["span:",vn]}):null,jn?r.jsxs("span",{className:"amx-small",children:["run:",jn]}):null,Lo?r.jsx("button",{type:"button",className:"amx-btn",onClick:()=>{if(ys&&vn&&Nr){kr({run_id:Nr,span_id:vn,assertion:B});return}Ro&&jn&&kr({run_id:jn,assertion:B})},children:"Open transcript"}):null]}):null]},ie)})})]}),r.jsxs("div",{className:"amx-panel",children:[r.jsx("h3",{children:"Transcript"}),r.jsx("div",{className:"amx-small",style:{marginBottom:8},children:"Pivot from a triple to its provenance transcript (span/note artifact, or run input fallback)."}),Yi.length?r.jsxs("div",{style:{marginBottom:12},children:[r.jsx("div",{className:"amx-small",style:{marginBottom:6,opacity:.85},children:"spans"}),r.jsx("div",{className:"amx-list",style:{maxHeight:320},children:Yi.slice(0,60).map(B=>r.jsxs("div",{className:"amx-item",style:{display:"flex",justifyContent:"space-between",gap:10,alignItems:"center"},children:[r.jsxs("div",{style:{minWidth:0},children:[r.jsxs("div",{className:"amx-mono",style:{fontSize:11,opacity:.95},children:["span:",B.span_id]}),r.jsxs("div",{className:"amx-small",children:["run_id=",B.span_run_id," · assertions=",B.count,B.last_observed_at_fmt?` · last=[${B.last_observed_at_fmt}]`:""]})]}),x||S?r.jsx("button",{type:"button",className:"amx-btn",onClick:()=>kr({run_id:B.span_run_id,span_id:B.span_id,assertion:B.assertion}),children:"Open transcript"}):null]},`${B.span_run_id}|${B.span_id}`))})]}):null,S&&_s.length?r.jsxs("div",{style:{marginBottom:12},children:[r.jsx("div",{className:"amx-small",style:{marginBottom:6,opacity:.85},children:"runs (fallback)"}),r.jsx("div",{className:"amx-list",style:{maxHeight:240},children:_s.slice(0,40).map(B=>r.jsxs("div",{className:"amx-item",style:{display:"flex",justifyContent:"space-between",gap:10,alignItems:"center"},children:[r.jsxs("div",{style:{minWidth:0},children:[r.jsxs("div",{className:"amx-mono",style:{fontSize:11,opacity:.95},children:["run:",B.run_id]}),r.jsxs("div",{className:"amx-small",children:["assertions=",B.count,B.last_observed_at_fmt?` · last=[${B.last_observed_at_fmt}]`:""]})]}),r.jsx("button",{type:"button",className:"amx-btn",onClick:()=>kr({run_id:B.run_id,assertion:B.assertion}),children:"Open transcript"})]},B.run_id))})]}):null,!Yi.length&&!(S&&_s.length)?r.jsx("div",{className:"amx-small",children:"(no provenance)"}):null]})]})]})})}function Kl({open:e,title:t,children:n,actions:s,variant:o="default",onClose:l}){const u=_.useId();if(_.useEffect(()=>{if(!e)return;const f=m=>{m.key==="Escape"&&l()};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[e,l]),!e)return null;const c=o==="fullscreen";return r.jsx("div",{className:`modal_backdrop${c?" fullscreen":""}`,onMouseDown:f=>{f.target===f.currentTarget&&l()},children:r.jsxs("div",{className:`modal_panel${c?" fullscreen":""}`,role:"dialog","aria-modal":"true","aria-labelledby":u,children:[r.jsxs("div",{className:"modal_header",children:[r.jsx("div",{className:"modal_title",id:u,children:t}),r.jsx("button",{className:"btn",onClick:l,children:"Close"})]}),r.jsx("div",{className:"modal_body",children:n}),s?r.jsx("div",{className:"modal_footer",children:s}):null]})})}function tp(e,t="session"){const n=String(e||"").trim().toLowerCase();return n==="run"||n==="session"||n==="global"||n==="all"?n:t}function tl(e){const t=typeof e=="string"?e.trim():"";if(!t)return null;const n=t.replace(/(\.\d{3})\d+/,"$1"),s=Date.parse(n);return Number.isFinite(s)?s:null}function Gl(e){if(typeof e!="number"||!Number.isFinite(e))return"—";const t=new Date(e),n=t.getUTCFullYear(),s=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}/${s}/${o} ${l}:${u}`}function Q3(e){const t=String(e??"").trim();if(!t)return"";if(/^\d{4}\/\d{2}\/\d{2} \d{2}:\d{2}$/.test(t))return t;const n=tl(t);return n!==null?Gl(n):t}function Ug(e){const t=typeof e=="string"?e:String(e??"");return t?!t.includes("\\n")&&!t.includes("\\r")&&!t.includes("\\t")?t:t.replace(/\\r\\n/g,`
133
- `).replace(/\\n/g,`
134
- `).replace(/\\t/g," "):""}function $0(e){return String(e??"").replace(/[*_`~]/g,"")}function Hh(e,t){const n=!!(t!=null&&t.strip_punct),s=Ug(e);let o=$0(s).replace(/\s+/g," ").trim().toLowerCase();return n&&(o=o.replace(/[^\p{L}\p{N}\s]+/gu,"").replace(/\s+/g," ").trim()),o}function Vh(e,t){const n=String(t??"").trim();if(!n)return!1;const s=Hh(n,{strip_punct:!1});if(!s)return!1;if(Hh(String(e??""),{strip_punct:!1}).includes(s))return!0;const l=Hh(n,{strip_punct:!0});return l?Hh(String(e??""),{strip_punct:!0}).includes(l):!1}function fv(e){const t=Ug(e).trim();if(!t)return[];const n=[],s=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&&s(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&&s(f)}}return s($0(t)),n}function eL(e){const t=String(e??"").replace(/\r\n/g,`
135
- `).replace(/\r/g,`
136
- `);if(!t)return null;const n=t.split(`
137
- `);let s;const o=[],l=[];let u=null,c=[],f=!1;const m=()=>{if(!u)return;const w=c.join(`
138
- `).trim();w&&l.push({role:u,lines:[w]}),u=null,c=[]};for(const w of n){const x=s?null:w.match(/^\s*created_at\s*=\s*(.+)\s*$/i);if(x&&x[1]){s=x[1].trim();continue}const S=w.match(/^\s*(USER|ASSISTANT|SYSTEM)\s*:\s*(.*)$/i);if(S){f=!0,m();const j=String(S[1]||"").trim().toLowerCase();u=j==="user"?"user":j==="assistant"?"assistant":"system";const N=String(S[2]??"");c=N?[N]:[];continue}u?c.push(w):o.push(w)}if(m(),!f||!l.length)return null;const p=o.join(`
139
- `).trim(),g={messages:[]};s&&(g.created_at=s),p&&g.messages.push({role:"system",content:p});for(const w of l)g.messages.push({role:w.role,content:w.lines.join(`
140
- `)});return g.messages.length?g:null}function hv(e,t){const n=String(e||""),s=String(t||"");return s>n?s:n}function mv(e){const t=String((e==null?void 0:e.subject)||"").trim(),n=String((e==null?void 0:e.predicate)||"").trim(),s=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}|${s}|${o}|${l}|${u}`}function tL(e){const t=String((e==null?void 0:e.observed_at)||"").trim(),n=String((e==null?void 0:e.subject)||"").trim(),s=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} --${s}--> ${o}${f}`}function nL({gateway:e,selected_run_id:t,selected_session_id:n}){const[s,o]=_.useState(String(t||"").trim()),[l,u]=_.useState(String(n||"").trim()),[c,f]=_.useState("all"),m=c==="all",[p,g]=_.useState(!0),[w,x]=_.useState(750),[S,j]=_.useState(5e3),[N,C]=_.useState([]),[E,T]=_.useState(void 0),[I,K]=_.useState(""),[U,J]=_.useState(!1),[Y,se]=_.useState([]),[ce,fe]=_.useState(!1),[W,P]=_.useState(!1),[A,z]=_.useState(""),[$,te]=_.useState(""),[O,F]=_.useState(""),[G,R]=_.useState(""),[Z,X]=_.useState("artifact"),[Q,le]=_.useState(null),[ge,pe]=_.useState(""),[ye,Ne]=_.useState(null),Ue=_.useRef(!1),We=_.useMemo(()=>{const ae=ye,je=ae!=null&&ae.attributes&&typeof ae.attributes=="object"&&!Array.isArray(ae.attributes)?ae.attributes:null;return(je&&typeof je.evidence_quote=="string"?String(je.evidence_quote):"").trim()},[ye]),pt=_.useMemo(()=>{const ae=Q,je=ae&&typeof ae=="object"&&!Array.isArray(ae)?ae:null,Ye=je&&typeof je.note=="string"?String(je.note):"";return Ug(Ye).trim()},[Q]),Fe=_.useMemo(()=>{const ae=Q&&typeof Q=="object"&&!Array.isArray(Q)?Q:null,je=ae&&Array.isArray(ae.messages)?ae.messages:null;return Array.isArray(je)?je:null},[Q]),tt=_.useMemo(()=>{const ae=pt,je=We;return!ae||!je?!1:Vh(ae,je)},[We,pt]),lt=_.useMemo(()=>{const ae=Fe,je=We;if(!ae||!je)return[];const Ye=[];for(let Ge=0;Ge<Math.min(ae.length,500);Ge++){const st=ae[Ge],ct=(st==null?void 0:st.content)==null?"":String(st.content);Vh(ct,je)&&Ye.push(Ge)}return Ye},[We,Fe]),Ke=_.useMemo(()=>new Set(lt),[lt]),Se=lt.length?lt[0]:null,Re=_.useCallback(ae=>{const je=document.getElementById(`source_msg_${ae}`);je&&typeof je.scrollIntoView=="function"&&je.scrollIntoView({block:"center",behavior:"smooth"})},[]),ht=_.useCallback(()=>{const ae=document.getElementById("source_note_hit_0")||document.getElementById("source_note_msg_hit_0");ae&&typeof ae.scrollIntoView=="function"&&ae.scrollIntoView({block:"center",behavior:"smooth"})},[]);_.useEffect(()=>{if(ce&&!(W||A)&&!Ue.current){if(Se!==null){Ue.current=!0,window.setTimeout(()=>Re(Se),0);return}if(tt){Ue.current=!0,window.setTimeout(()=>ht(),0);return}}},[Re,ht,A,Se,W,tt,ce]);const xe=_.useRef(new Set),Ie=_.useRef(""),qe=_.useRef(null),zt=_.useRef(null);_.useEffect(()=>{o(String(t||"").trim())},[t]),_.useEffect(()=>{u(String(n||"").trim())},[n]);const en=_.useMemo(()=>{const ae=String(s||"").trim(),je=String(l||"").trim();return`mindmap:${c}:${ae}:${je}`},[s,l,c]),bn=_.useMemo(()=>{let ae=null,je=null;for(const Ye of N){const Ge=tl(Ye==null?void 0:Ye.observed_at);Ge!==null&&(ae=ae===null?Ge:Math.min(ae,Ge),je=je===null?Ge:Math.max(je,Ge))}return{min_ms:ae,max_ms:je}},[N]),Wt=1e3,It=_.useMemo(()=>{const ae=bn.min_ms,je=bn.max_ms;if(typeof ae!="number"||typeof je!="number"||!Number.isFinite(ae)||!Number.isFinite(je))return null;if(je<=ae)return{min_ms:ae,max_ms:ae,real_max_ms:je};const Ye=ae+Math.ceil((je-ae)/Wt)*Wt;return{min_ms:ae,max_ms:Ye,real_max_ms:je}},[bn.max_ms,bn.min_ms]),[kn,nr]=_.useState(!0),[Pt,pn]=_.useState(null);_.useEffect(()=>{kn&&It&&pn(It.max_ms)},[kn,It]);const Bn=_.useMemo(()=>{const ae=typeof Pt=="number"?Pt:null;return ae===null?N:N.filter(je=>{const Ye=tl(je==null?void 0:je.observed_at);return Ye===null?!0:Ye<=ae})},[N,Pt]),$n=_.useCallback((ae,je)=>{const Ye=Array.isArray(ae)?ae:[],Ge=String(Ie.current||"").trim(),st=new Set,ct=[];let Et="";for(const jt of Ye){if(!jt||typeof jt!="object"||typeof jt.subject!="string"||typeof jt.predicate!="string"||typeof jt.object!="string")continue;const Kt=mv(jt);if(st.has(Kt))continue;st.add(Kt),ct.push(jt);const xt=String(jt.observed_at||"").trim();xt&&(Et=hv(Et,xt))}C(ct),T(je==null?void 0:je.warnings),xe.current=st,Ie.current=Et||Ge},[]),gn=_.useCallback(async ae=>{const je=tp(ae.scope,"session"),Ye=String(ae.subject||"").trim(),Ge=String(ae.predicate||"").trim(),st=String(ae.object||"").trim(),ct=String(ae.since||"").trim(),Et=String(ae.until||"").trim(),jt=String(ae.active_at||"").trim(),Kt=String(ae.query_text||"").trim(),xt=typeof ae.min_score=="number"&&Number.isFinite(ae.min_score)?Number(ae.min_score):void 0,Yt=ae.order==="asc"?"asc":"desc",qt=typeof ae.limit=="number"&&Number.isFinite(ae.limit)?Number(ae.limit):0,Ot=String(s||"").trim(),$t=String(l||"").trim(),At={scope:je,all_owners:m,limit:qt,order:Yt};Ye&&(At.subject=Ye),Ge&&(At.predicate=Ge),st&&(At.object=st),ct&&(At.since=ct),Et&&(At.until=Et),jt&&(At.active_at=jt),Kt&&(At.query_text=Kt),typeof xt=="number"&&(At.min_score=xt),m||(je==="run"?Ot&&(At.run_id=Ot):je==="session"?$t?At.session_id=$t:Ot&&(At.run_id=Ot):je==="all"&&(Ot?At.run_id=Ot:$t&&(At.session_id=$t)));try{const De=await e.kg_query(At),on=Array.isArray(De==null?void 0:De.items)?De.items:[],dt=De==null?void 0:De.warnings;return{ok:(De==null?void 0:De.ok)!==!1,count:Number((De==null?void 0:De.count)||on.length),items:on,warnings:dt,raw:De}}catch(De){const on=De instanceof Error?De.message:String(De);if(on.includes("Run '")&&on.includes("not found")&&!$t&&(je==="session"||je==="all")&&Ot){const tn=await e.kg_query({...At,run_id:void 0,session_id:Ot}),ft=Array.isArray(tn==null?void 0:tn.items)?tn.items:[],Un=tn==null?void 0:tn.warnings;return{ok:(tn==null?void 0:tn.ok)!==!1,count:Number((tn==null?void 0:tn.count)||ft.length),items:ft,warnings:Un,raw:tn}}throw new Error(on||"KG query failed")}},[m,e,s,l]),In=_.useCallback(async ae=>{var Ge;const je=String(ae.run_id||"").trim(),Ye=String(ae.span_id||"").trim();if(!(!je||!Ye)){fe(!0),P(!0),z(""),F(je),R(Ye),X("artifact"),te(`source span:${Ye}`),le(null),pe(""),Ne(ae.assertion&&typeof ae.assertion=="object"?ae.assertion:null),Ue.current=!1;try{const st=[je],ct=typeof((Ge=ae.assertion)==null?void 0:Ge.owner_id)=="string"?String(ae.assertion.owner_id).trim():"";ct&&ct!==je&&st.push(ct);let Et=null,jt=null;for(const Kt of st)try{jt=await(await e.download_run_artifact_content(Kt,Ye)).text(),Kt!==je&&F(Kt);break}catch(xt){Et=xt instanceof Error?xt.message:String(xt)}if(jt==null)throw new Error(Et||"Failed to load source span");pe(jt);try{const Kt=JSON.parse(jt);le(Kt)}catch{le(null)}}catch(st){const ct=st instanceof Error?st.message:String(st);z(ct||"Failed to load source span")}finally{P(!1)}}},[e]),wn=_.useCallback(async ae=>{const je=String(ae.run_id||"").trim();if(!je)return null;try{const Ye=await e.list_run_artifacts(je,{limit:200}),st=(Array.isArray(Ye==null?void 0:Ye.items)?Ye.items:[]).map(xt=>{const Yt=typeof(xt==null?void 0:xt.artifact_id)=="string"?String(xt.artifact_id).trim():"",qt=xt!=null&&xt.tags&&typeof xt.tags=="object"&&!Array.isArray(xt.tags)?xt.tags:null,Ot=qt&&typeof qt.kind=="string"?String(qt.kind).trim():"";return{artifact_id:Yt,kind:Ot}}).filter(xt=>!!(xt.artifact_id&&(xt.kind==="conversation_span"||xt.kind==="memory_note")));if(!st.length)return null;if(st.length===1)return st[0].artifact_id;const ct=ae.assertion,Et=ct!=null&&ct.attributes&&typeof ct.attributes=="object"&&!Array.isArray(ct.attributes)?ct.attributes:null,Kt=(Et&&typeof Et.evidence_quote=="string"?String(Et.evidence_quote):"").trim();if(!Kt)return null;for(const xt of st.slice(0,10))try{const qt=await(await e.download_run_artifact_content(je,xt.artifact_id)).text(),Ot=JSON.parse(qt);if(Ot&&typeof Ot=="object"){const $t=typeof Ot.note=="string"?String(Ot.note):"";if($t&&$t.includes(Kt))return xt.artifact_id;const At=Array.isArray(Ot.messages)?Ot.messages:null;if(At){for(const De of At.slice(0,200))if(((De==null?void 0:De.content)==null?"":String(De.content)).includes(Kt))return xt.artifact_id}}}catch{}}catch{}return null},[e]),jr=_.useCallback(async ae=>{const je=String(ae.run_id||"").trim();if(je){fe(!0),P(!0),z(""),F(je),R(""),X("run_input"),te(`transcript run:${je}`),le(null),pe(""),Ne(ae.assertion&&typeof ae.assertion=="object"?ae.assertion:null),Ue.current=!1;try{const Ye=await wn({run_id:je,assertion:ae.assertion});if(Ye){await In({run_id:je,span_id:Ye,assertion:ae.assertion});return}const Ge=await e.get_run_input_data(je),st=Ge&&typeof Ge=="object"&&!Array.isArray(Ge)?Ge.input_data:null,ct={kind:"run_input_data",run_id:je};if(Ge&&typeof(Ge==null?void 0:Ge.workflow_id)=="string"&&(ct.workflow_id=String(Ge.workflow_id)),st&&typeof st=="object"&&!Array.isArray(st)){const Et=st.context,Kt=(Et&&typeof Et=="object"&&Array.isArray(Et.messages)?Et.messages:null)||(Array.isArray(st.messages)?st.messages:null);Array.isArray(Kt)&&(ct.messages=Kt);const xt=["text","prompt","task","message"];for(const Yt of xt){const qt=st[Yt];if(typeof qt=="string"&&qt.trim()){ct.note=qt.trim();break}}ct.input_data=st}!ct.messages&&!ct.note&&(ct.note=JSON.stringify(st??Ge??{},null,2));try{const Et=await e.get_run(je),jt=Et&&typeof(Et==null?void 0:Et.created_at)=="string"?String(Et.created_at):"";jt&&(ct.created_at=jt)}catch{}le(ct),pe(JSON.stringify(Ge,null,2))}catch(Ye){const Ge=Ye instanceof Error?Ye.message:String(Ye);z(Ge||"Failed to load run input transcript")}finally{P(!1)}}},[e,In,wn]),Kn=_.useCallback(async()=>{K(""),J(!0);try{const ae=c==="all"?"all":c,je=await gn({scope:ae,limit:0,order:"desc"});$n(je.items||[],{warnings:je.warnings}),qe.current={scope:ae}}catch(ae){const je=ae instanceof Error?ae.message:String(ae);K(je||"Load failed")}finally{J(!1)}},[gn,$n,c]);_.useEffect(()=>{N.length||Kn()},[]);const Sr=_.useCallback(async ae=>{const je=tp(ae.scope,"session");return zt.current=ae,await gn({scope:je,subject:ae.subject,predicate:ae.predicate,object:ae.object,query_text:ae.query_text,min_score:ae.min_score,since:ae.since,until:ae.until,active_at:ae.active_at,limit:typeof ae.limit=="number"?ae.limit:0,order:"desc"})},[gn]),Ns=_.useCallback((ae,je)=>{var Ye;if((je==null?void 0:je.kind)==="live query"){const Ge=zt.current;Ge&&(qe.current={scope:tp(Ge.scope,"session"),subject:typeof Ge.subject=="string"?Ge.subject:void 0,predicate:typeof Ge.predicate=="string"?Ge.predicate:void 0,object:typeof Ge.object=="string"?Ge.object:void 0})}$n(ae,{warnings:(Ye=je==null?void 0:je.result)==null?void 0:Ye.warnings})},[$n]),Pn=_.useCallback(async()=>{const ae=qe.current;if(!ae)return;const je=String(Ie.current||"").trim(),Ye=await gn({scope:ae.scope,subject:ae.subject,predicate:ae.predicate,object:ae.object,since:je||void 0,order:"asc",limit:0}),Ge=Array.isArray(Ye.items)?Ye.items:[];if(!Ge.length)return;const ct=Date.now()+Math.max(250,Math.min(2e4,S)),Et=xe.current,jt=[],Kt=[];let xt=String(Ie.current||"").trim();for(const Yt of Ge){if(!Yt||typeof Yt!="object"||typeof Yt.subject!="string"||typeof Yt.predicate!="string"||typeof Yt.object!="string")continue;const qt=mv(Yt);if(Et.has(qt))continue;Et.add(qt),jt.push(Yt),Kt.push({id:qt,assertion:Yt,expires_at_ms:ct});const Ot=String(Yt.observed_at||"").trim();Ot&&(xt=hv(xt,Ot))}jt.length&&(Ie.current=xt,C(Yt=>{const qt=Yt.concat(jt);return qt.sort((Ot,$t)=>String(($t==null?void 0:$t.observed_at)||"").localeCompare(String((Ot==null?void 0:Ot.observed_at)||""))),qt}),se(Yt=>{const qt=Yt.concat(Kt);return qt.sort((Ot,$t)=>$t.expires_at_ms-Ot.expires_at_ms),qt.slice(0,30)}))},[S,gn]);return _.useEffect(()=>{if(!p)return;let ae=!1,je=null;const Ye=async()=>{if(!ae){try{await Pn()}catch{}ae||(je=window.setTimeout(()=>void Ye(),Math.max(250,Math.min(6e4,w))))}};return Ye(),()=>{ae=!0,je!==null&&window.clearTimeout(je)}},[p,w,Pn]),_.useEffect(()=>{if(!Y.length)return;const ae=window.setInterval(()=>{const je=Date.now();se(Ye=>Ye.filter(Ge=>Ge.expires_at_ms>je))},250);return()=>window.clearInterval(ae)},[Y.length]),r.jsxs("div",{className:"mindmap_root",children:[r.jsxs("div",{className:"mindmap_bar",children:[r.jsx("button",{className:"btn",onClick:()=>void Kn(),disabled:U,children:U?"Loading…":"Load snapshot"}),r.jsxs("label",{className:"field_inline",children:[r.jsx("span",{className:"mono muted",children:"source"}),r.jsxs("select",{value:c,onChange:ae=>{const je=String(ae.target.value||"").trim();(je==="all"||je==="global"||je==="session"||je==="run")&&f(je)},children:[r.jsx("option",{value:"all",children:"all memory"}),r.jsx("option",{value:"global",children:"global"}),r.jsx("option",{value:"session",children:"session"}),r.jsx("option",{value:"run",children:"run"})]})]}),r.jsx(oC,{checked:p,onChange:g}),c==="session"?r.jsxs("label",{className:"field_inline",children:[r.jsx("span",{className:"mono muted",children:"session_id"}),r.jsx("input",{className:"mono",value:l,onChange:ae=>u(String(ae.target.value||"")),placeholder:"(required)"})]}):null,c==="run"?r.jsxs("label",{className:"field_inline",children:[r.jsx("span",{className:"mono muted",children:"run_id"}),r.jsx("input",{className:"mono",value:s,onChange:ae=>o(String(ae.target.value||"")),placeholder:"(required)"})]}):null,r.jsxs("details",{className:"mindmap_details",children:[r.jsx("summary",{className:"mono muted",children:"advanced"}),r.jsx("div",{className:"mindmap_advanced",children:r.jsxs("div",{className:"field_inline",children:[r.jsx("span",{className:"mono muted",style:{width:84},children:"poll_ms"}),r.jsx("input",{type:"number",min:250,max:6e4,step:50,value:w,onChange:ae=>x(Math.max(250,Number(ae.target.value||0)||750))}),r.jsx("span",{className:"mono muted",children:"highlight_ms"}),r.jsx("input",{type:"number",min:250,max:2e4,step:250,value:S,onChange:ae=>j(Math.max(250,Number(ae.target.value||0)||5e3))})]})})]})]}),I?r.jsx("div",{className:"mindmap_error mono",children:I}):null,r.jsxs("div",{className:"mindmap_explorer",children:[r.jsx(Z3,{title:"mindmap",resetKey:en,queryMode:"replace",items:Bn,warnings:E,onQuery:Sr,onItemsReplace:Ns,onOpenSpan:({run_id:ae,span_id:je,assertion:Ye})=>{In({run_id:ae,span_id:je,assertion:Ye})},onOpenTranscript:({run_id:ae,span_id:je,assertion:Ye})=>{const Ge=String(ae||"").trim(),st=typeof je=="string"?String(je).trim():"";Ge&&(st?In({run_id:Ge,span_id:st,assertion:Ye}):jr({run_id:Ge,assertion:Ye}))}},en),Y.length?r.jsxs("div",{className:"mindmap_recent mindmap_overlay mindmap_overlay_recent",children:[r.jsx("div",{className:"mindmap_recent_title mono muted",children:"new assertions"}),r.jsx("div",{className:"mindmap_recent_list",children:Y.slice().sort((ae,je)=>je.expires_at_ms-ae.expires_at_ms).slice(0,12).map(ae=>r.jsx("div",{className:"mindmap_recent_item mono",children:tL(ae.assertion)},ae.id))})]}):null,It?r.jsx("div",{className:"mindmap_timeline mindmap_overlay mindmap_overlay_timeline",children:r.jsxs("div",{className:"mindmap_timeline_row",children:[r.jsx("div",{className:"mindmap_timeline_label mono muted",children:Gl(Math.min(typeof Pt=="number"?Pt:It.max_ms,It.real_max_ms))}),r.jsx("input",{className:"mindmap_slider",type:"range",min:It.min_ms,max:It.max_ms,step:Wt,value:typeof Pt=="number"?Pt:It.max_ms,onChange:ae=>{const je=Number(ae.target.value||0);pn(je),nr(je>=It.max_ms)}}),r.jsxs("div",{className:"mindmap_timeline_counts mono muted",children:[Bn.length.toLocaleString(),"/",N.length.toLocaleString()]})]})}):null]}),r.jsxs(Kl,{open:ce,title:$||"source",onClose:()=>{fe(!1)},children:[W?r.jsx("div",{className:"mono muted",children:"Loading…"}):null,A?r.jsx("div",{className:"mindmap_error mono",children:A}):null,!W&&!A?r.jsxs("div",{className:"source_span",children:[(()=>{const ae=ye;if(!ae)return null;const je=String(ae.subject||"").trim(),Ye=String(ae.predicate||"").trim(),Ge=String(ae.object||"").trim(),st=Gl(tl(ae.observed_at)),ct=ae.attributes&&typeof ae.attributes=="object"&&!Array.isArray(ae.attributes)?ae.attributes:null,Et=ct&&typeof ct.evidence_quote=="string"?String(ct.evidence_quote):"",jt=ct&&typeof ct.original_context=="string"?String(ct.original_context):"";return r.jsxs("div",{className:"source_header",children:[r.jsxs("div",{className:"mono source_triple",title:`${je} --${Ye}--> ${Ge}`,children:[je," ",r.jsxs("span",{className:"muted",children:["—",Ye,"→"]})," ",Ge," ",st?r.jsxs("span",{className:"muted",children:["[",st,"]"]}):null]}),Et?r.jsxs("div",{className:"source_evidence",children:[r.jsx("div",{className:"mono muted",style:{fontSize:11,marginBottom:6},children:"evidence_quote"}),r.jsx("pre",{className:"mono source_evidence_quote",children:Et}),jt?r.jsxs("details",{className:"source_evidence_more",children:[r.jsx("summary",{className:"mono muted",children:"original_context"}),r.jsx("pre",{className:"mono source_evidence_quote",children:jt})]}):null]}):null]})})(),r.jsxs("div",{className:"mono muted",style:{marginBottom:10},children:["run_id=",O," · ",Z==="artifact"?`span_id=${G}`:"source=input_data"]}),r.jsxs("div",{className:"source_actions",children:[Se!==null?r.jsx("button",{className:"btn",onClick:()=>Re(Se),children:"Jump to evidence"}):null,Se===null&&tt?r.jsx("button",{className:"btn",onClick:()=>ht(),children:"Jump to evidence"}):null]}),(()=>{const ae=Q,je=ae&&typeof ae=="object"&&!Array.isArray(ae)?ae:null,Ye=Fe,Ge=pt,st=je&&typeof je.created_at=="string"?String(je.created_at):"",ct=st?tl(st):null,Et=ct!==null?Gl(ct):st,jt=je&&je.span&&typeof je.span=="object"&&!Array.isArray(je.span)?je.span:null,Kt=jt&&typeof jt.from_timestamp=="string"?String(jt.from_timestamp):"",xt=jt&&typeof jt.to_timestamp=="string"?String(jt.to_timestamp):"",Yt=Kt?tl(Kt):null,qt=xt?tl(xt):null,Ot=Yt!==null&&qt!==null?`${Gl(Yt)} → ${Gl(qt)}`:"";if(Ge){const $t=eL(Ge);if($t){const At=We,De=At?$t.messages.findIndex(ft=>Vh(ft.content,At)):-1,on=At?fv(At):[],dt=$t.created_at||st,tn=dt?Q3(dt):st?Et:"";return r.jsx("div",{className:"source_chat",children:$t.messages.map((ft,Un)=>{const an=ft.role,Yr=!!(At&&Vh(ft.content,At)),rr=an==="user"?"USER":an==="assistant"?"ASSISTANT":"SYSTEM";return r.jsxs("div",{id:Un===De?"source_note_msg_hit_0":void 0,className:`source_msg source_${an} ${Yr?"source_match":""}`,children:[r.jsxs("div",{className:"source_msg_meta mono muted",children:[r.jsxs("span",{children:["#",Un+1," · ",rr,Yr?r.jsx("span",{className:"source_match_badge",children:"evidence"}):null]}),tn?r.jsx("span",{title:dt||"",children:tn}):null]}),r.jsx("div",{className:"source_msg_body",children:r.jsx(Wi,{text:ft.content,highlights:Yr&&on.length?on:void 0,highlightClassName:"source_note_hit",highlightId:Un===De?"source_note_hit_0":void 0})})]},`note_msg:${Un}`)})})}return r.jsxs("div",{className:"source_note",children:[st?r.jsx("div",{className:"mono muted",style:{marginBottom:10},children:r.jsxs("span",{title:st,children:["created_at=",Et]})}):null,r.jsx(Wi,{text:Ge,highlights:We?fv(We):void 0,highlightClassName:"source_note_hit",highlightId:"source_note_hit_0"})]})}if(Ye){const $t=new Map;for(const De of Ye){const on=typeof(De==null?void 0:De.role)=="string"?String(De.role):"unknown";$t.set(on,($t.get(on)||0)+1)}const At=Array.from($t.entries()).sort((De,on)=>on[1]-De[1]||De[0].localeCompare(on[0])).map(([De,on])=>`${De}×${on}`).join(" · ");return r.jsxs("div",{className:"source_chat",children:[st?r.jsxs("div",{className:"mono muted",style:{marginBottom:10},children:[r.jsxs("span",{title:st,children:["created_at=",Et]})," · messages=",Ye.length]}):null,Ot?r.jsxs("div",{className:"mono muted",style:{marginBottom:10},children:["span=",Ot]}):null,At?r.jsxs("div",{className:"mono muted",style:{marginBottom:10},children:["participants: ",At]}):null,Ye.slice(0,200).map((De,on)=>{var Ws,ds;const dt=typeof(De==null?void 0:De.role)=="string"?String(De.role):"unknown",tn=(De==null?void 0:De.content)==null?"":String(De.content),ft=typeof(De==null?void 0:De.timestamp)=="string"?String(De.timestamp):"",Un=ft?tl(ft):null,an=Un!==null?Gl(Un):ft,Yr=typeof(De==null?void 0:De.message_id)=="string"?String(De.message_id):typeof((Ws=De==null?void 0:De.metadata)==null?void 0:Ws.message_id)=="string"?String(De.metadata.message_id):typeof((ds=De==null?void 0:De.metadata)==null?void 0:ds.id)=="string"?String(De.metadata.id):"",rr=Ke.has(on);return r.jsxs("div",{id:`source_msg_${on}`,className:`source_msg source_${dt} ${rr?"source_match":""}`,children:[r.jsxs("div",{className:"source_msg_meta mono muted",children:[r.jsxs("span",{children:["#",on+1," · ",dt,rr?r.jsx("span",{className:"source_match_badge",children:"evidence"}):null,Yr?r.jsx("span",{className:"source_msg_id",children:Yr}):null]}),ft?r.jsx("span",{title:ft,children:an}):null]}),r.jsx("div",{className:"source_msg_body",children:r.jsx(Wi,{text:tn})})]},on)})]})}return r.jsx("pre",{className:"mono source_raw",style:{whiteSpace:"pre-wrap",wordBreak:"break-word"},children:(typeof ae=="string"?ae:ge)||"(empty)"})})()]}):null]})]})}const np=4;function rL(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 s=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:s(t.kinds),felt_tones:s(t.felt_tones),dreams:o}}function _v(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 s=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:s}}function sL(e){var c,f;const t=m=>{var g;const p=(g=e==null?void 0:e[m])==null?void 0:g.open;return Array.isArray(p)?p.map(_v).filter(w=>w!==null):[]},n=t("questions"),s=t("problems"),o=(c=e==null?void 0:e.lessons)==null?void 0:c.lessons,l=Array.isArray(o)?o.map(_v).filter(m=>m!==null):[],u=typeof((f=e==null?void 0:e.lessons)==null?void 0:f.total)=="number"?e.lessons.total:l.length;return{questions:n.slice(0,np),questions_total:n.length,problems:s.slice(0,np),problems_total:s.length,lessons:l.slice(0,np),lessons_total:u}}function rp(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 pv={review:"Review",working:"Working",pending:"Pending",done:"Done"},iL={review:"nothing needs you",working:"idle",pending:"nothing scheduled",done:"no recent runs"},oL={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 aL(e){const t=String((e==null?void 0:e.status)||"").trim().toLowerCase();if(ko(t))return"done";const n=$u(e);return n==="tool_approval"||n==="user_response"?"review":n==="scheduled"||t==="pending"||t==="queued"||t==="created"?"pending":"working"}function lL(e){const t=$u(e);return t==="tool_approval"||t==="user_response"}function gv(e,t=Date.now()){const n=aL(e),s=e!=null&&e.waiting&&typeof e.waiting=="object"?e.waiting:null,o=$f(s),l=qn((s==null?void 0:s.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:$u(e),reason:Xx(e),tool_names:o.map(u=>String((u==null?void 0:u.name)||"tool")).filter(Boolean),wait_key:String((s==null?void 0:s.wait_key)||"").trim(),allow_free_text:(s==null?void 0:s.allow_free_text)!==!1,prompt:String((s==null?void 0:s.prompt)||"").trim(),since_ms:l,duration_ms:pg(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:uf(e),tag_label:Ax(e),automation_id:uf(e)==="occurrence"?String((e==null?void 0:e.automation_id)||"").trim():""}}function cL(e,t,n=Date.now()){const s={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)||Vy(u)||lL(u)&&(l.add(c),s.review.push(gv(u,n)))}for(const u of e||[]){const c=String((u==null?void 0:u.run_id)||"").trim();if(!u||!c||l.has(c)||Vy(u))continue;const f=gv(u,n);s[f.column].push(f)}return s.review.sort((u,c)=>(u.since_ms??0)-(c.since_ms??0)),s.working.sort((u,c)=>(c.since_ms??0)-(u.since_ms??0)),s.pending.sort((u,c)=>(c.since_ms??0)-(u.since_ms??0)),s.done.sort((u,c)=>Number(c.failed)-Number(u.failed)||(c.since_ms??0)-(u.since_ms??0)),s}const tg={"12h":12*36e5,"24h":24*36e5,"48h":48*36e5,"72h":72*36e5,"7d":7*864e5,"14d":14*864e5,"1m":30*864e5,all:null},sp={"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"},yv="48h";function uL(e,t,n=Date.now()){const s=tg[t]??null;if(s===null)return{visible:e,hidden_count:0};const o=n-s,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 dL(e,t=Date.now()){const n=String(e||"").trim();if(!n)return null;const s=Date.parse(n);return Number.isFinite(s)?Math.max(0,t-s):null}const fL=6e4;function nf(e,t=Date.now()){if(e===null||!Number.isFinite(e))return"";const n=Math.max(0,t-e);return n<6e4?`${Math.round(n/1e3)}s`:n<36e5?`${Math.round(n/6e4)}m`:n<864e5?`${(n/36e5).toFixed(1)}h`:`${(n/864e5).toFixed(1)}d`}function hL(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 mL(e){const t=String(e||"");return t.length>14?`${t.slice(0,6)}…${t.slice(-6)}`:t}function ip(e){const t=String(e||"").trim();return t.length>72?`${t.slice(0,70)}…`:t}function _L(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 s=t.slice(0,t.lastIndexOf(":"));/[a-z]/i.test(s)&&!/^[0-9a-f]+$/i.test(s.replace(/[@.\-_]/g,""))&&(n=s)}return n.length>34?`${n.slice(0,32)}…`:n}function nm(e){return e.toLowerCase().replace(/[_-]+/g," ")}function pL(e){var m,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 s=Object.keys(n).filter(g=>g&&typeof g=="string");if(!s.length)return null;const o=[];for(const g of s){o.push({needle:nm(g),phase:g});const w=(m=n[g])==null?void 0:m.spoken_synonyms;if(Array.isArray(w))for(const x of w){const S=nm(String(x||"").trim());S&&o.push({needle:S,phase:g})}}const u=(typeof t.initial_phase=="string"&&s.includes(t.initial_phase)?t.initial_phase:null)??(s.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[g,w]of Object.entries(f)){const x=String((w==null?void 0:w.phase)||"").trim(),S=nm(String(g||"").trim());S&&s.includes(x)&&c.push({needle:S,phase:x})}return{phases:s,synonyms:o,modes:c,initial:u,version:typeof t.version=="number"?t.version:null,sha256:String((e==null?void 0:e.sha256)||"").trim()}}const gL=["asleep","sleep","dream"],yL=["rest"],wL=["awake","idle"];function vL(e,t){const n=String(e||"").trim().toLowerCase();if(!n)return"unknown";if(t){const s=nm(n),o=t.synonyms.filter(u=>s.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=>s.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":gL.some(u=>n.includes(u))?t.initial:yL.some(u=>n.includes(u))&&t.phases.includes("personal")?"personal":wL.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 xL=new Set(["visit","work","personal","sleep","paused","resting","stopped","unknown"]),bL=new Set(["visit","work","personal","sleep","paused","resting","stopped","unknown"]);function jL(e){if(!e)return xL;const t=e.phases.filter(n=>bL.has(n));return new Set([...t,"paused","stopped","unknown"])}function SL(e){const[t,n]=df(`board_${e.col}`),s=`mc_column_body_${e.col}`;return r.jsxs("div",{className:`mc_column mc_column_${e.col}${t?"":" list_collapsed"}`,children:[r.jsxs("div",{className:"mc_column_head",children:[r.jsx(ff,{open:t,on_toggle:n,controls:s,title:e.title,className:"mc_column_title"}),e.head]}),r.jsx("div",{className:"mc_column_body",id:s,hidden:!t,children:e.children})]})}function kL(e){var U,J,Y,se,ce,fe;const t=Date.now(),n=_.useMemo(()=>cL(e.runs,e.all_runs,Date.now()),[e.runs,e.all_runs]),[s,o]=_.useState(""),[l,u]=_.useState(""),[c,f]=_.useState(!1),[m,p]=_.useState(()=>{try{const W=localStorage.getItem("abstractobserver_done_window_v1");return W&&W in tg?W:yv}catch{return yv}}),g=_.useMemo(()=>uL(n.done,m,t),[n.done,m]),w=nf(e.runs_refreshed_at,t),x=n.review.length,S=g.visible.filter(W=>W.failed).length,[j,N]=_.useState(""),[C,E]=_.useState(null),T=W=>`${W.run_id}:${W.wait_key}:${W.since_ms??""}`;_.useEffect(()=>{s&&(n.review.some(W=>T(W)===s)||o(""))},[n,s]);async function I(W,P){o(T(W)),u("");try{await e.on_resume_wait(W.run_id,W.wait_key,P)}catch(A){u(`${W.run_id}: ${String((A==null?void 0:A.message)||A||"resume failed")}`),o("")}}function K(W){const P=s===T(W),A=W.column==="review",z=A&&!W.wait_key;return r.jsxs("div",{className:`mc_card ${A?"mc_card_review":""} ${W.failed?"mc_card_failed":""}`,onClick:()=>e.on_open_run(W.run_id),role:"button",tabIndex:0,onKeyDown:$=>{$.key==="Enter"&&$.target===$.currentTarget&&e.on_open_run(W.run_id)},children:[r.jsxs("div",{className:"mc_card_head",children:[r.jsx("span",{className:"mc_card_title",title:W.workflow,children:_L(W.workflow)}),(()=>{const $=W.failed?"failed":lm({status:W.status,paused:W.paused});return r.jsx("span",{className:`mc_status ${oc($)}`,children:$==="unknown"?"?":$})})()]}),r.jsxs("div",{className:"mc_card_meta",children:[r.jsx("span",{className:"mono",title:W.run_id,children:mL(W.run_id)}),W.is_subrun?r.jsx("span",{title:"This wait lives in a child run of an agent workflow",children:"subrun"}):null,W.tag?r.jsx("span",{className:"mc_pill","data-tag":W.tag,children:W.tag_label}):null,W.automation_id?r.jsx("button",{type:"button",className:"btn btn_sm",title:"Open this occurrence's automation",onClick:$=>{$.stopPropagation(),e.on_open_automation(W.automation_id)},onKeyDown:$=>$.stopPropagation(),children:"Automation"}):null,W.duration_ms>=0?r.jsx("span",{children:hL(W.duration_ms)}):null,W.tokens_total!==null?r.jsxs("span",{children:[W.tokens_total.toLocaleString()," tk"]}):null,W.tool_calls!==null&&W.tool_calls>0?r.jsxs("span",{children:[W.tool_calls," tools"]}):null]}),W.is_scheduled&&W.schedule_interval?r.jsxs("div",{className:"mc_card_line",children:["every ",W.schedule_interval]}):null,W.failed&&W.error?r.jsx("div",{className:"mc_card_error",title:W.error,children:W.error.length>120?`${W.error.slice(0,118)}…`:W.error}):null,A?r.jsxs("div",{className:"mc_card_review_body",onClick:$=>$.stopPropagation(),onKeyDown:$=>$.stopPropagation(),children:[r.jsx("div",{className:"mc_card_reason",children:W.reason||"Needs a decision"}),W.prompt?r.jsx("div",{className:"mc_card_prompt",title:W.prompt,children:W.prompt.length>240?`${W.prompt.slice(0,238)}…`:W.prompt}):null,W.tool_names.length?r.jsxs("div",{className:"mc_card_tools",title:"Tool calls awaiting your approval",children:[W.tool_names.slice(0,4).map(($,te)=>r.jsx("span",{className:"mc_tool_chip mono",children:$},`${$}_${te}`)),W.tool_names.length>4?r.jsxs("span",{className:"mc_tool_chip",children:["+",W.tool_names.length-4," more"]}):null]}):null,W.since_ms!==null?r.jsxs("div",{className:"mc_card_waiting",children:["waiting ",nf(W.since_ms,t)]}):null,z?r.jsx("div",{className:"mc_card_line",title:"The wait has not registered a wait_key yet — open the run to inspect.",children:"wait key not published yet — open the run"}):null,z?r.jsx("div",{className:"mc_card_actions",children:r.jsx("button",{className:"btn",onClick:()=>e.on_open_run(W.run_id),children:"Open the run →"})}):W.wait_kind==="tool_approval"?r.jsxs("div",{className:"mc_card_actions",children:[r.jsx("button",{className:"btn success",disabled:P,onClick:()=>void I(W,{approved:!0}),children:P?"Resuming…":"Approve"}),r.jsx("button",{className:"btn danger",disabled:P,onClick:()=>void I(W,{approved:!1}),children:"Reject"})]}):r.jsx("div",{className:"mc_card_actions",children:r.jsx("button",{className:"btn primary",onClick:()=>e.on_open_run(W.run_id),children:"Review & answer →"})})]}):null]},W.run_id)}return r.jsxs("div",{className:"page page_scroll mc_page",children:[r.jsxs("div",{className:"mc_health",children:[r.jsx("span",{className:`mc_led ${e.gateway_connected?"ok":"bad"}`,title:e.gateway_connected?"Gateway connected":"Gateway unreachable"}),e.gateway_connected?null:r.jsx("span",{className:"mc_health_text",children:"gateway unreachable"}),e.runs_refreshed_at===null?r.jsx("span",{className:"mc_health_text muted mc_loading",children:"loading runs…"}):r.jsxs("div",{className:"mc_stats",children:[r.jsxs("div",{className:`mc_stat ${x?"is_hot":""}`,title:"runs blocked on a human decision (Review column)",children:[r.jsx("span",{className:"mc_stat_value",children:x}),r.jsx("span",{className:"mc_stat_label",children:"need you"})]}),r.jsxs("div",{className:`mc_stat ${S?"is_bad":""}`,title:"failed runs in the Done column",children:[r.jsx("span",{className:"mc_stat_value",children:S}),r.jsx("span",{className:"mc_stat_label",children:"failed"})]}),r.jsxs("div",{className:"mc_stat",title:"runs executing or parked listening",children:[r.jsx("span",{className:"mc_stat_value",children:n.working.length}),r.jsx("span",{className:"mc_stat_label",children:"working"})]})]}),r.jsx("span",{className:"mc_spacer"}),r.jsxs("div",{className:"mc_health_side",children:[w?r.jsxs("span",{className:"mc_health_text muted",title:"age of the last runs poll — the board is only as live as this",children:["data ",w," old"]}):null,r.jsx("button",{className:"btn",onClick:e.on_refresh,disabled:e.refreshing,children:e.refreshing?"Refreshing…":"Refresh"})]})]}),l?r.jsx("div",{className:"mc_error",children:l}):null,e.entities.length||e.entities_error?r.jsxs("div",{className:"mc_entities",children:[r.jsxs("div",{className:"mc_entities_head",children:[r.jsxs("span",{children:["Entities",e.entities_total>e.entities.length?` (${e.entities.length} of ${e.entities_total} — open the entity app for all)`:""]}),r.jsx("a",{className:"mc_entity_link",href:e.entity_app_href,target:"_blank",rel:"noreferrer",children:"open the entity app →"})]}),e.entities_error?r.jsx("div",{className:"muted",children:e.entities_error}):null,r.jsx("div",{className:"mc_entities_row",children:e.entities.map(W=>r.jsxs("div",{className:"mc_entity_cell",children:[r.jsxs("a",{className:"mc_entity",href:`${e.entity_app_href}${e.entity_app_href.includes("?")?"&":"?"}entity=${encodeURIComponent(W.name)}&live=1`,target:"_blank",rel:"noreferrer",title:[W.error,W.age_days!==null?`${W.age_days.toFixed(0)} days old`:"",W.last_moment].filter(Boolean).join(" — ")||W.name,children:[r.jsx("span",{className:"mc_entity_name",children:W.name}),(()=>{var F;const P=String(W.live_phase||W.state||"").trim(),A=vL(P,e.phase_graph),z=jL(e.phase_graph).has(A)?A:"other",$=((F=e.phase_graph)==null?void 0:F.initial)??"sleep",te=/awake|idle/i.test(P)&&A===$,O=P&&P.toLowerCase()!==A?` — wire word: ${P}${te?" (settling)":""}`:"";return r.jsx("span",{className:`mc_entity_phase mc_phase_${z}`,title:(W.live_phase?"phase (cognition wire)":"phase from card state — cognition wire unavailable")+O,children:A})})(),W.last_moment?r.jsx("span",{className:"mc_entity_moment",title:W.last_moment,children:W.last_moment.replace(/_/g," ")}):null,(()=>{if(W.working===!0)return r.jsx("span",{className:"mc_entity_live",title:"busy now (loop mid-day or live visit — store-read, never fabricated)",children:"● busy"});const P=dL(W.last_moment_at,t);return W.working===!1?r.jsxs("span",{className:"mc_entity_live muted",title:"idle (cognition wire)",children:["idle",P!==null?` · ${nf(t-P,t)} ago`:""]}):P===null?null:P<=fL?r.jsx("span",{className:"mc_entity_live",title:`last moment ${nf(t-P,t)} ago`,children:"● active"}):r.jsxs("span",{className:"mc_entity_live muted",title:"time since the last recorded moment",children:[nf(t-P,t)," ago"]})})(),W.tokens_total!==null?r.jsxs("span",{className:"muted mc_entity_spend",title:`lifetime billed tokens (home run ledger)${W.live_visit_tokens!==null?`; open visit: ${rp(W.live_visit_tokens)} tk`:""}${W.spend_warning?`; ${W.spend_warning}`:""}`,children:[rp(W.tokens_total)," tk",W.live_visit_tokens!==null?` (+${rp(W.live_visit_tokens)})`:"",W.spend_warning?"*":""]}):null]}),W.open_questions_total||W.open_problems_total||W.lessons_total||W.dreams_brief?r.jsx("button",{type:"button",className:"mc_entity_hints_btn","aria-expanded":j===W.name,title:"open questions / problems + distilled lessons + night signals from the entity card — click to expand",onClick:()=>N(j===W.name?"":W.name),children:[W.open_questions_total?`${W.open_questions_total} question${W.open_questions_total>1?"s":""}`:"",W.open_problems_total?`${W.open_problems_total} problem${W.open_problems_total>1?"s":""}`:"",W.lessons_total?`${W.lessons_total} lesson${W.lessons_total>1?"s":""}`:"",W.dreams_brief?`night: ${W.dreams_brief.count} signal${W.dreams_brief.count>1?"s":""}`:""].filter(Boolean).join(" · ")}):null]},W.name))}),(()=>{if(!j)return null;const W=e.entities.find(z=>z.name===j);if(!W||!W.open_questions.length&&!W.open_problems.length&&!W.lessons.length&&!W.dreams_brief)return null;const P=e.on_read_diary?async z=>{const $=await e.on_read_diary(W.name,z);E({entity:W.name,entry:($==null?void 0:$.entry)??$,seq:typeof($==null?void 0:$.read_recorded_at_seq)=="number"?$.read_recorded_at_seq:null})}:void 0,A=W.open_questions_total-W.open_questions.length+(W.open_problems_total-W.open_problems.length)+(W.lessons_total-W.lessons.length);return r.jsxs("div",{className:"mc_entity_hints_panel",children:[W.open_questions.map((z,$)=>r.jsx(v_,{kind:"question",label:z.title||ip(z.statement),entryId:z.entry_id,onOpen:P,title:z.statement||z.title},`q_${z.record_id||$}`)),W.open_problems.map((z,$)=>r.jsx(v_,{kind:"problem",label:z.title||ip(z.statement),entryId:z.entry_id,onOpen:P,title:z.statement||z.title},`p_${z.record_id||$}`)),W.lessons.map((z,$)=>r.jsx(v_,{kind:"lesson",label:z.title||ip(z.statement),entryId:z.entry_id,onOpen:P,title:z.statement||z.title},`l_${z.record_id||$}`)),W.dreams_brief?r.jsxs("span",{className:"mc_entity_dreams muted",title:"night signals carried by STANDING dreams (the sleep pass's maintenance stream; count = signals, not dreams); felt tones color the content, they never rank it — the entity app renders the full stream",children:["night signals: ",W.dreams_brief.count,W.dreams_brief.dreams?` across ${W.dreams_brief.dreams} dream${W.dreams_brief.dreams>1?"s":""}`:"",W.dreams_brief.kinds.length?` — ${W.dreams_brief.kinds.slice(0,6).join(", ")}${W.dreams_brief.kinds.length>6?` +${W.dreams_brief.kinds.length-6} more`:""}`:"",W.dreams_brief.felt_tones.length?` · felt: ${W.dreams_brief.felt_tones.slice(0,6).join(", ")}`:""]}):null,A>0?r.jsxs("span",{className:"muted mc_entity_hints_more",children:["+",A," more — open the entity app"]}):null]})})()]}):null,C?r.jsx(Kl,{open:!0,title:`${C.entity} — diary entry`,onClose:()=>E(null),children:r.jsxs("div",{className:"mc_diary_entry",children:[r.jsx("div",{className:"mc_diary_meta muted",children:[(U=C.entry)!=null&&U.kind?`kind: ${C.entry.kind}`:"",(J=C.entry)!=null&&J.visibility?`visibility: ${C.entry.visibility}`:"",(Y=C.entry)!=null&&Y.written_at?`written: ${C.entry.written_at}`:"",(se=C.entry)!=null&&se.entry_id?`id: ${C.entry.entry_id}`:""].filter(Boolean).join(" · ")}),r.jsxs("div",{className:"mc_diary_recorded muted",children:["this read was recorded in ",C.entity,"’s stream",C.seq!==null?` (seq ${C.seq})`:""]}),(ce=C.entry)!=null&&ce.gist?r.jsx("div",{className:"mc_diary_gist",children:String(C.entry.gist)}):null,r.jsx("pre",{className:"mc_diary_text",children:String(((fe=C.entry)==null?void 0:fe.text)||"(entry carries no text)")})]})}):null,r.jsx("div",{className:"mc_board",children:Object.keys(pv).map(W=>{const P=W==="done"?g.visible:n[W],A=W==="done"&&!c?P.slice(0,8):P;return r.jsxs(SL,{col:W,title:pv[W],head:r.jsxs(r.Fragment,{children:[W==="done"?r.jsx("select",{className:"mc_window_select",value:m,title:"Show terminal runs from this time window",onClick:z=>z.stopPropagation(),onChange:z=>{const $=z.target.value;p($),f(!1);try{localStorage.setItem("abstractobserver_done_window_v1",$)}catch{}},children:Object.keys(tg).map(z=>r.jsx("option",{value:z,children:sp[z]},z))}):null,r.jsx("span",{className:"mc_column_count",title:W==="done"&&g.hidden_count?`${g.hidden_count} older run(s) outside this window`:void 0,children:P.length})]}),children:[r.jsx("div",{className:"mc_column_hint muted",children:oL[W]}),r.jsxs("div",{className:"mc_column_cards",children:[A.map(z=>K(z)),P.length?null:r.jsx("div",{className:"mc_empty muted",children:e.runs_refreshed_at===null?"loading…":W==="done"&&g.hidden_count?`none in the ${sp[m]} — ${g.hidden_count} older`:iL[W]}),W==="done"&&P.length>8&&!c?r.jsxs("button",{className:"btn mc_more",onClick:()=>f(!0),children:["show all ",P.length]}):null,W==="done"&&g.hidden_count&&P.length?r.jsxs("div",{className:"mc_window_note muted",title:"Widen the window above to see older terminal runs",children:["+",g.hidden_count," older outside ",sp[m]]}):null]})]},W)})})]})}function wv(e){const t=Array.from(new Set(e.map(n=>String(n||"").trim()).filter(Boolean)));return t.sort((n,s)=>n.localeCompare(s)),t}function vv(e){const t=e.disabled===!0,n=_.useMemo(()=>wv(e.options||[]),[e.options]),s=_.useMemo(()=>wv(e.value||[]),[e.value]),[o,l]=_.useState(!1),[u,c]=_.useState(""),f=_.useMemo(()=>{const g=u.trim().toLowerCase();return g?n.filter(w=>w.toLowerCase().includes(g)):n},[n,u]),m=_.useMemo(()=>new Set(s),[s]),p=typeof e.max_list_height_px=="number"?e.max_list_height_px:220;return r.jsxs("div",{className:"multi_select",children:[r.jsxs("div",{className:"multi_select_row",children:[r.jsxs("button",{className:"btn",type:"button",onClick:()=>l(g=>!g),disabled:t||!n.length,"aria-expanded":o,children:[o?"Hide":"Select"," • ",s.length>0?`${s.length} of ${n.length}`:e.placeholder||"(none)"]}),r.jsx("button",{className:"btn",type:"button",onClick:()=>e.onChange(n.slice()),disabled:t||!n.length||s.length===n.length,title:"Select all",children:"All"}),r.jsx("button",{className:"btn",type:"button",onClick:()=>e.onChange([]),disabled:t||s.length===0,title:"Clear selection",children:"Clear"})]}),s.length>0?r.jsx("div",{className:"multi_select_chips",children:s.map(g=>r.jsxs("span",{className:"multi_select_chip",title:g,onClick:()=>{if(t)return;const w=new Set(m);w.delete(g),e.onChange(Array.from(w.values()))},children:[g,t?null:r.jsx("span",{className:"multi_select_chip_x",children:"×"})]},g))}):null,o?r.jsxs("div",{className:"multi_select_panel",children:[r.jsx("input",{className:"mono",value:u,onChange:g=>c(String(g.target.value||"")),placeholder:"filter…",disabled:t}),r.jsxs("div",{className:"multi_select_list",style:{maxHeight:`${p}px`},children:[f.map(g=>{const w=m.has(g);return r.jsxs("label",{className:`multi_select_item mono ${w?"checked":""}`,children:[r.jsx("input",{type:"checkbox",checked:w,disabled:t,onChange:x=>{const S=new Set(m);x.target.checked?S.add(g):S.delete(g),e.onChange(Array.from(S.values()))}}),r.jsx("span",{children:g})]},g)}),f.length?null:r.jsx("div",{className:"mono muted",children:"(no matches)"})]})]}):null]})}function NL(){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 CL(){if(typeof window>"u")return!1;const e=window;return!!(e!=null&&e.AudioContext||e!=null&&e.webkitAudioContext)}function EL(){const e=window.MediaRecorder,t=s=>{var o;try{return!!((o=e==null?void 0:e.isTypeSupported)!=null&&o.call(e,s))}catch{return!1}},n=["audio/webm;codecs=opus","audio/webm","audio/mp4","audio/ogg;codecs=opus","audio/ogg"];for(const s of n)if(t(s))return s;return""}async function $L(e,t){var o;const n=t.slice(0),s=(o=e.decodeAudioData)==null?void 0:o.bind(e);if(typeof s!="function")throw new Error("decodeAudioData not available");try{const l=s(n);if(l&&typeof l.then=="function")return await l}catch{}return await new Promise((l,u)=>{try{s(n,l,u)}catch(c){u(c)}})}function AL(e){const t=z=>{var $;return($=e.on_error)==null?void 0:$.call(e,z)},n=_.useMemo(()=>CL(),[]),s=_.useMemo(()=>NL(),[]),[o,l]=_.useState({key:"",status:"idle"}),u=_.useRef(""),c=_.useRef(""),f=_.useRef(null),m=_.useRef(null),p=_.useRef(null),g=_.useRef(null),w=_.useRef(0),x=_.useRef(0),S=()=>{try{const z=globalThis,$=(z==null?void 0:z.AudioContext)||(z==null?void 0:z.webkitAudioContext);if(!$)return null;if(!f.current){const F=new $,G=F.createGain();G.gain.value=1,G.connect(F.destination),f.current=F,m.current=G}const te=f.current,O=m.current;if(!te||!O)return null;try{te.state==="suspended"&&te.resume()}catch{}return{ctx:te,gain:O}}catch{return null}},j=()=>{const z=p.current;if(p.current=null,!!z){try{z.onended=null}catch{}try{z.stop()}catch{}try{z.disconnect()}catch{}}},N=()=>{j(),c.current="",u.current="",g.current=null,w.current=0,x.current=0,l({key:"",status:"idle"})};_.useEffect(()=>()=>{var z,$;N();try{(z=m.current)==null||z.disconnect()}catch{}try{($=f.current)==null||$.close()}catch{}f.current=null,m.current=null,g.current=null},[]);const C=async(z,$,te)=>{const O=S();if(!O)throw new Error("TTS playback is not supported in this browser");const{ctx:F,gain:G}=O;try{F.state==="suspended"&&await F.resume()}catch{}j();const R=F.createBufferSource();R.buffer=$,R.connect(G);const Z=Number.isFinite(Number($.duration))?Number($.duration):0,X=Math.max(0,Math.min(Number(te||0),Z>0?Math.max(0,Z-.01):0));x.current=F.currentTime-X,w.current=X,p.current=R,u.current=z,R.onended=()=>{p.current===R&&(p.current=null,w.current=0,x.current=0,u.current="",l({key:"",status:"idle"}))},R.start(0,X),l({key:z,status:"playing"})},E=async(z,$)=>{const te=String(z||"").trim(),O=String($||"").trim();if(!te||!O)return;const F=e.gateway,G=String(e.run_id||"").trim();if(!F){t==null||t("Connect to the gateway first.");return}if(!G){t==null||t("Voice store not available (missing run_id).");return}const R=S();if(!R){t==null||t("TTS playback is not supported in this browser.");return}const Z=o.key===te;if(Z&&o.status==="playing"){const X=Math.max(0,R.ctx.currentTime-Number(x.current||0));w.current=X,j(),l({key:te,status:"paused"});return}if(Z&&o.status==="paused"){const X=g.current;if(X){t==null||t("");try{await C(te,X,w.current)}catch(Q){t==null||t(String((Q==null?void 0:Q.message)||Q||"TTS play failed")),l({key:"",status:"idle"})}return}}if(!(Z&&o.status==="loading")){j(),g.current=null,w.current=0,x.current=0,u.current=te,c.current=te,l({key:te,status:"loading"}),t==null||t("");try{const X=await F.voice_tts(G,{text:O,request_id:xr()}),Q=X==null?void 0:X.audio_artifact,le=Q&&typeof Q=="object"&&!Array.isArray(Q)?String(Q.$artifact||"").trim():"";if(!le)throw new Error("TTS failed: missing audio artifact");const pe=await(await F.download_run_artifact_content(G,le)).arrayBuffer();if(c.current!==te)return;const ye=await $L(R.ctx,pe);if(c.current!==te)return;g.current=ye,w.current=0,await C(te,ye,0)}catch(X){c.current===te&&(c.current="",u.current="",l({key:"",status:"idle"})),t==null||t(String((X==null?void 0:X.message)||X||"TTS failed"))}}},[T,I]=_.useState(!1),[K,U]=_.useState(!1),J=_.useRef(null),Y=_.useRef(null),se=_.useRef([]),ce=_.useRef("");function fe(){var z,$;try{($=(z=J.current)==null?void 0:z.getTracks)==null||$.call(z).forEach(te=>{try{te.stop()}catch{}})}catch{}J.current=null}_.useEffect(()=>()=>{var z,$;try{($=(z=Y.current)==null?void 0:z.stop)==null||$.call(z)}catch{}Y.current=null,fe()},[]);async function W(z,$){var G;if(t==null||t(""),!z||!z.size||K)return;const te=e.gateway,O=String(e.session_id||"").trim(),F=String(e.run_id||"").trim();if(!te){t==null||t("Connect to the gateway first.");return}if(!O){t==null||t("Voice input unavailable (missing session_id).");return}if(!F){t==null||t("Voice input unavailable (missing run_id).");return}U(!0);try{const R=String($||z.type||"").toLowerCase(),Z=R.includes("mp4")?"m4a":R.includes("ogg")?"ogg":R.includes("wav")?"wav":"webm",X=new File([z],`recording.${Z}`,{type:R||"audio/webm"}),Q=await te.attachments_upload(O,X,{filename:X.name,content_type:X.type}),le=await te.audio_transcribe(F,{audio_artifact:Q,request_id:xr()}),ge=String((le==null?void 0:le.text)||"").trim();ge&&((G=e.on_transcript)==null||G.call(e,ge))}catch(R){t==null||t(String((R==null?void 0:R.message)||R||"Transcription failed"))}finally{U(!1)}}async function P(){if(t==null||t(""),!s){t==null||t(Rp()?"Voice recording is not supported in this browser (MediaRecorder unavailable).":Mp);return}if(!K&&!(T||Y.current)){se.current=[];try{const z=await navigator.mediaDevices.getUserMedia({audio:!0});J.current=z;const $=EL();ce.current=$;const te=$?new MediaRecorder(z,{mimeType:$}):new MediaRecorder(z);Y.current=te,te.ondataavailable=O=>{try{O!=null&&O.data&&se.current.push(O.data)}catch{}},te.onerror=()=>{t==null||t("Recording failed.")},te.onstop=()=>{I(!1),fe(),Y.current=null;try{const O=new Blob(se.current,{type:ce.current||""});W(O,ce.current)}catch(O){t==null||t(String((O==null?void 0:O.message)||O||"Failed to build recording"))}},te.start(),I(!0)}catch(z){fe(),Y.current=null,I(!1);const $=String((z==null?void 0:z.message)||z||"Failed to access microphone");t==null||t($.toLowerCase().includes("permission")?`Microphone permission denied: ${$}`:$)}}}function A(){const z=Y.current;if(!(!T||!z)){Y.current=null,I(!1);try{z.stop()}catch($){t==null||t(String(($==null?void 0:$.message)||$||"Failed to stop recording"))}}}return _.useEffect(()=>{if(!T)return;const z=()=>A();return window.addEventListener("pointerup",z),window.addEventListener("pointercancel",z),()=>{window.removeEventListener("pointerup",z),window.removeEventListener("pointercancel",z)}},[T]),{tts_supported:n,tts_playback:o,toggle_tts:E,stop_tts:N,voice_ptt_supported:s,voice_ptt_recording:T,voice_ptt_busy:K,start_voice_ptt_recording:P,stop_voice_ptt_recording:A}}const Gh=500,jm="http://127.0.0.1:8080";function xv(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 rf(e){const t=String(e||"").trim();return t.startsWith("abstractcode.")?`abstract.${t.slice(13)}`:t}function op(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,s=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${s} — the loop sees it at this boundary`}function ap(e){const t=String(e||"").trim();return t.startsWith("abstract.")||t.startsWith("abstractcode.")}function TL(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 ML(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 s=n.data&&typeof n.data=="object"?n.data:{},o=Array.isArray(s.outputs)?s.outputs:[],l=s.pinDefaults&&typeof s.pinDefaults=="object"?s.pinDefaults:{},u=[];for(const c of o){if(!c||typeof c!="object")continue;const f=String(c.id||"").trim();if(!f)continue;const m=String(c.type||"").trim();if(m==="execution"||f==="exec-out"||f==="exec")continue;const p=String(c.label||f).trim()||f,g={id:f,label:p,type:m||"unknown"};l&&Object.prototype.hasOwnProperty.call(l,f)&&(g.default=l[f]),u.push(g)}return u}function lp(e,t){const n=String((e==null?void 0:e.message)||e||"Discovery failed");if(/\b401\b/.test(n)){const s=String(t.gateway_user||"").trim();return s?`Gateway authentication failed for user '${s}'. 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 RL=/^[a-zA-Z0-9_-]+$/;function bv(e){return RL.test(String(e||"").trim())}async function LL(e){const t=String(e||"");return wE(t)}async function IL(e){const t=String(e||"").trim();if(!t)throw new Error("session_id is required");if(bv(t)){const s=`session_memory_${t}`;if(bv(s))return s}return`session_memory_sha_${(await LL(t)).slice(0,32)}`}function PL(){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)||jm),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:jm,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 OL(e){localStorage.setItem("abstractobserver_settings",JSON.stringify({...e,auth_token:""}))}function DL(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}))},s=String(e.display??"").trim().replace(/^\[/,"").replace(/\]$/,"");return n("time",s||e.local_datetime),n("tz",e.timezone),n("country",e.country),n("user",e.user),t}function jv(e){const t=DL(e.metadata);return t.length?r.jsx("div",{className:"runtime_metadata_chips","aria-label":"Runtime metadata",children:t.map(n=>r.jsxs("span",{className:"chip mono muted",children:[n.label,": ",n.value]},`${n.label}:${n.value}`))}):null}function FL(){return typeof window>"u"?"":wN(window.location)}function zL(){try{const e="abstractobserver_session_id_v1",t=window.sessionStorage.getItem(e);if(t&&t.trim())return t.trim();const n=`obs_${xr()}`;return window.sessionStorage.setItem(e,n),n}catch{return""}}function BL(){var er,Gn,ur,as,Qo,Yn,Va,wo,Bl,Zc,Ga,Hr,Qc,ea,vi;const[e,t]=_.useState("board"),[n,s]=_.useState(()=>PL()),o=typeof window<"u"&&((er=window.__ABSTRACT_UI_CONFIG__)==null?void 0:er.monitor_gpu)===!0,l=typeof window<"u"&&(((Gn=window.__ABSTRACT_UI_CONFIG__)==null?void 0:Gn.entity_app_url)||"").trim().replace(/\/+$/,"")||"http://127.0.0.1:3007",u=_.useRef(null),[c,f]=_.useState(""),[m,p]=_.useState(""),[g,w]=_.useState(()=>FL()),[x,S]=_.useState(""),[j,N]=_.useState(""),[C,E]=_.useState(""),[T,I]=_.useState("{}"),[K]=_.useState(()=>zL()),[U,J]=_.useState(null),[Y,se]=_.useState(!1),[ce,fe]=_.useState(""),[W,P]=_.useState(!1),[A,z]=_.useState(""),[$,te]=_.useState(!1),O=Nj({appName:"AbstractObserver",variant:"dismissable",defaultGatewayUrl:typeof window<"u"&&((ur=window.__ABSTRACT_UI_CONFIG__)==null?void 0:ur.gateway_url)||jm,onStatusChange:y=>dd(y)}),[F,G]=_.useState(null),[R,Z]=_.useState(null),[X,Q]=_.useState(!1),[le,ge]=_.useState(null),[pe,ye]=_.useState("once"),[Ne,Ue]=_.useState(""),[We,pt]=_.useState(Np),[Fe,tt]=_.useState([]),[lt,Ke]=_.useState(null),[Se,Re]=_.useState(!1),[ht,xe]=_.useState([]),Ie=_.useRef(new _2(xr)),[qe,zt]=_.useState({available:!1,reason:"Sign in to a gateway to use automations."}),[en,bn]=Jj("abstractobserver",{legacyKey:"abstractobserver_settings"}),[Wt,It]=_.useState(!1),[kn,nr]=_.useState(!1),[Pt,pn]=_.useState([]),[Bn,$n]=_.useState([]),[gn,In]=_.useState([]),[wn,jr]=_.useState(!1),[Kn,Sr]=_.useState(null),[Ns,Pn]=_.useState([]),[ae,je]=_.useState(0),[Ye,Ge]=_.useState(""),st=_.useRef(!1),ct=_.useRef(0),Et=_.useRef(0),[jt,Kt]=_.useState(!1),[xt,Yt]=_.useState([]),[qt,Ot]=_.useState([]),[$t,At]=_.useState({}),[De,on]=_.useState(!1),[dt,tn]=_.useState(!1),[ft,Un]=_.useState(!1),[an,Yr]=_.useState([]),[rr,Ws]=_.useState([]),ds=_.useRef(0),ii=_.useRef(null);ii.current||(ii.current=new dw(y=>window.setTimeout(y,40),y=>Yr(k=>k.concat(y))));const oi=_.useRef(null);oi.current||(oi.current=new dw(y=>window.setTimeout(y,40),y=>Ws(k=>k.concat(y))));const Or=_.useRef({scanned:0,found:null}),[ue,fs]=_.useState(null),[Vi,hs]=_.useState(""),[Cs,qs]=_.useState(!1),it=_.useRef(null),[cn,Dr]=_.useState({}),[Hs,sr]=_.useState({}),[Eo,$o]=_.useState(!1),[Ao,On]=_.useState(""),[ms,Hn]=_.useState(!0),[Gi,ai]=_.useState(""),[An,Fr]=_.useState(!1),[hr,Jr]=_.useState(!1),[mr,da]=_.useState(6),[Ki,ln]=_.useState("standard"),[fa,uc]=_.useState(""),[To,_r]=_.useState(""),[Es,$s]=_.useState(!1),[Yi,_s]=_.useState(!1),[kr,ps]=_.useState("pause"),[As,Xr]=_.useState(""),[ki,ir]=_.useState(""),[Ts,ha]=_.useState(""),gs=_.useRef(null),Ji=_.useRef(null),[dc,Ni]=_.useState(!1),Zr=_.useRef(null),[Au,Qr]=_.useState(""),[Xi,es]=_.useState(""),[Mo,li]=_.useState(""),[al,ci]=_.useState(""),[B,ie]=_.useState(""),[be,ke]=_.useState(!1),[Ee,He]=_.useState("idle"),[Qe,ot]=_.useState([]),[mt,Dt]=_.useState(null),Xt=_.useRef(null),[Xn,Bt]=_.useState(!1),[un,vn]=_.useState(""),[jn,pr]=_.useState(""),[Nr,ys]=_.useState(""),[Ro,Lo]=_.useState([]),[ll,fc]=_.useState(!1),[hc,mc]=_.useState(""),[Tu,_c]=_.useState(""),[pc,gc]=_.useState(!1),[Mu,Io]=_.useState(""),Rf=_.useMemo(()=>{if(!Qe.length)return"";try{return JSON.stringify(Qe.map(y=>({role:y.role,content:y.content,ts:y.ts})))}catch{return"1"}},[Qe]),Ru=_.useMemo(()=>Qe.length?Nr?Rf!==Nr:!0:!1,[Rf,Qe.length,Nr]),Lu=_.useMemo(()=>Ro.map(y=>{const k=String(y.title||"").trim()||`Chat ${String(y.thread_id||"").slice(0,8)}`,M=String(y.created_at||"").trim(),D=M?M.replace("T"," ").slice(0,19):"",q=String(y.run_id||"").trim()?String(y.run_id).slice(0,8):"",H=[k,D&&`(${D})`,q&&`run ${q}`].filter(Boolean).join(" • ");return{value:String(y.thread_id||""),label:H}}),[Ro]);_.useEffect(()=>{o&&vC()},[o]),_.useEffect(()=>{if(!o)return;const y=u.current;y&&(y.token=n.gateway_auth_mode==="direct"&&n.auth_token||"")},[o,n.auth_token,n.gateway_auth_mode]);const[Iu,Pu]=_.useState([]),[Ou,nn]=_.useState(""),[yc,Dm]=_.useState(""),[Du,Fm]=_.useState("all"),[Fu,zm]=_.useState("status"),[ts,Zi]=_.useState("ledger"),wc=dy(g_.md),cl=dy(`${g_.sm}, ${g_.short}`),ma=mN({is_drawer:wc,page:e}),vc=ma.open,_a=ma.set_open,[zu,Lf]=df("observe_runs"),If=ma.toggle_ref,pa=ma.sidebar_ref,Pf=_.useRef(null),[Bm,Of]=_.useState(()=>Dy(typeof window<"u"?window.location.hash:"")),[Df,Bu]=_.useState(""),[ga,Po]=_.useState(""),[ya,Qi]=_.useState(""),[wa,va]=_.useState(null),[xa,ul]=_.useState({}),[Uu,ba]=_.useState(!1),[Wu,dl]=_.useState(""),[fl,Um]=_.useState(!1),[qu,Wm]=_.useState(!1),[Vs,eo]=_.useState(()=>Date.now()),[ui,Oo]=_.useState(""),[Ff,hl]=_.useState({}),[Hu,Vu]=_.useState({}),ml=_.useRef([]),gr=_.useRef(null),di=_.useRef(""),to=_.useRef({}),no=_.useRef({}),xc=_.useRef({}),ro=_.useRef(new Set),[ws,ja]=_.useState([]),Sa=_.useRef(""),Ci=_.useRef({}),Ei=_.useRef(null),zr=_.useRef(null),so=_.useRef(0),Do=_.useRef({}),_l=_.useRef(!1),io=_.useRef(new Set),[fi,ka]=_.useState(""),[Ms,oo]=_.useState(""),hi=_.useRef(""),Na=()=>({artifact_id:"",kind:"binary",render_kind:"",text:"",url:"",loading:!1,error:""}),[pl,Gu]=_.useState("activity"),[bc,Nn]=_.useState([]),[jc,gl]=_.useState(0),[yl,Ku]=_.useState(0),[Yu,Ca]=_.useState({}),[Sc,Fo]=_.useState({}),[zf,Bf]=_.useState(!1),[qm,Ju]=_.useState(""),[ao,kc]=_.useState(""),[zo,wl]=_.useState("all"),[Ea,Nc]=_.useState(""),[$a,Uf]=_.useState([]),[Cc,Hm]=_.useState("all"),[lo,co]=_.useState("type"),[vl,Aa]=_.useState("newest"),[yr,Ta]=_.useState(""),[vs,Bo]=_.useState(""),[Wf,Xu]=_.useState(""),[Gs,Uo]=_.useState(0),[Ks,Ma]=_.useState(()=>Na()),[Zu,uo]=_.useState(!1),[$i,En]=_.useState(""),[Cn,xs]=_.useState(""),[fn,wr]=_.useState(""),[Ai,Ra]=_.useState("text"),[ns,La]=_.useState(null),[qf,xl]=_.useState(!1),[bl,jl]=_.useState(""),[mi,Sl]=_.useState(""),[Qu,ed]=_.useState(""),[Hf,Ti]=_.useState(!1),[Ia,Wo]=_.useState(""),[qo,Ec]=_.useState("run_ledger"),[Rs,Ls]=_.useState(""),[Ho,Ys]=_.useState([]),[Mi,Ri]=_.useState(""),[Vf,$c]=_.useState(!1),[td,Br]=_.useState(""),Te=_.useMemo(()=>new O_({base_url:n.gateway_auth_mode==="session"?"":n.gateway_url,auth_token:n.gateway_auth_mode==="session"?"":n.auth_token}),[n.gateway_auth_mode,n.gateway_url,n.auth_token]),Tt=_.useMemo(()=>new $2(Te.automations_client(),N2(Te,xr,Ct)),[Te]),bs=_.useSyncExternalStore(y=>Tt.subscribe(y),()=>Tt.state),nd=c2(n.gateway_url),Ac=nd?()=>{window.open(nd,"_blank","noopener,noreferrer")}:void 0;_.useEffect(()=>{e==="launch"&&pe==="automate"&&$&&Tt.load_email_status()},[e,pe,$,Tt]),_.useEffect(()=>{const y=()=>{const k=d2(window.location.hash);if(k){if(k.page==="run"){w(k.run_id),Of(Dy(window.location.hash));return}k.page==="launch"&&ye(k.mode),t(k.page)}};return y(),window.addEventListener("hashchange",y),()=>window.removeEventListener("hashchange",y)},[]);const rd=_.useMemo(()=>{const y={};for(const k of bs.items)y[k.automation_id]=k.title;return y},[bs.items]),sd=_.useMemo(()=>cC(),[]),[Gf,kl]=_.useState([]),id=_.useRef(0);function Pa(){const y=++id.current;kl([["Gateway","checking…"]]),uC(Te).then(k=>{y===id.current&&kl(k)})}const Oa=_.useMemo(()=>n.worker_url.trim()?new xE({url:n.worker_url.trim(),auth_token:n.worker_token}):null,[n.worker_url,n.worker_token]),Ur=an.length?an[an.length-1].record:null,Ft=_.useMemo(()=>sa(Ur),[Ur]),Zn=_.useMemo(()=>{const y=C.trim();if(!U||!y||String(U.bundle_id||"").trim()&&String(U.bundle_id||"").trim()!==y)return null;const k=Array.isArray(U.entrypoints)?U.entrypoints:[];if(!k.length)return null;const M=j.trim();if(M)return k.find(q=>String(q.flow_id||"").trim()===M)||null;if(k.length===1)return k[0];const D=String(U.default_entrypoint||"").trim();return D&&k.find(q=>String(q.flow_id||"").trim()===D)||null},[U,C,j]),Tc=_.useMemo(()=>{const y=Zn==null?void 0:Zn.inputs;return Array.isArray(y)?y:[]},[Zn]),od=_.useMemo(()=>ML(wa),[wa]),_i=_.useMemo(()=>Tc.length?Tc:od,[Tc,od]),Vo=_.useMemo(()=>{const y=typeof(ue==null?void 0:ue.workflow_id)=="string"?String(ue.workflow_id):"",k=xv(y);if(k&&U&&String(U.bundle_id||"").trim()===k.bundle_id){const q=(Array.isArray(U.entrypoints)?U.entrypoints:[]).find(H=>String((H==null?void 0:H.flow_id)||"").trim()===k.flow_id);if(q&&q.node_index&&typeof q.node_index=="object")return q.node_index}const M=Zn==null?void 0:Zn.node_index;return M&&typeof M=="object"?M:{}},[ue,U,Zn]);_.useEffect(()=>{OL(n)},[n]),_.useEffect(()=>()=>{Ei.current&&Ei.current.abort(),zr.current&&zr.current.abort(),gs.current&&window.clearTimeout(gs.current),Ji.current&&window.clearTimeout(Ji.current),gr.current&&window.clearTimeout(gr.current),Zr.current&&window.clearTimeout(Zr.current)},[]);const ut=_.useMemo(()=>{const y=T.trim();if(!y)return{};try{const k=JSON.parse(y);return typeof k!="object"||k===null||Array.isArray(k)?null:k}catch{return null}},[T]),Mc=typeof(ut==null?void 0:ut.prompt)=="string"?String(ut.prompt):"",fo=typeof(ut==null?void 0:ut.provider)=="string"?String(ut.provider):"",ad=typeof(ut==null?void 0:ut.model)=="string"?String(ut.model):"",ld=typeof(ut==null?void 0:ut.workspace_root)=="string"?String(ut.workspace_root):"",Rc=typeof(ut==null?void 0:ut.workspace_access_mode)=="string"?String(ut.workspace_access_mode):"",cd=_.useMemo(()=>{const y=ut==null?void 0:ut.workspace_allowed_paths;return Array.isArray(y)?y.map(k=>String(k||"").trim()).filter(Boolean).join(`
141
- `):typeof y=="string"?String(y):""},[ut]),Da=_.useMemo(()=>{const y=ut==null?void 0:ut.workspace_ignored_paths;return Array.isArray(y)?y.map(k=>String(k||"").trim()).filter(Boolean).join(`
142
- `):typeof y=="string"?String(y):""},[ut]),Is=_i.length>0&&!!C.trim(),Li=y=>{const k=String(y||"").trim().toLowerCase();return k==="object"||k==="memory"||k==="assertion"||k==="assertions"||k==="any"};_.useEffect(()=>{sr({})},[C,j]),_.useEffect(()=>{ut!==null&&Dr(y=>{const k={};for(const M of _i){if(!M||typeof M!="object")continue;const D=String(M.id||"").trim();if(!D)continue;const q=String(M.type||"").trim();if(!Li(q))continue;if(String(Hs[D]||"").trim()){k[D]=typeof y[D]=="string"?y[D]:"";continue}const V=ut==null?void 0:ut[D];V===void 0?k[D]="":k[D]=qN(V)}return k})},[_i,ut,Hs]);const Js=Ne?{kind:"default",interface:Ne}:C.trim()&&j.trim()?{kind:"bundle",bundle_id:C.trim(),flow_id:j.trim()}:null,ud=i2(Js),or=Array.isArray(ut==null?void 0:ut.skills)?ut.skills.map(y=>String(y||"").trim()).filter(Boolean):[],ar=_.useMemo(()=>{const y={};for(const k of Pt){const M=String(k.workflow_id||"").trim(),D=String(k.label||"").trim();M&&D&&(y[M]=D)}return y},[Pt]),Nl=Xv({interfaceId:null,defaultInterface:Su,request:(y,k)=>Te.get_gateway_json(y,k.signal),enabled:$,reloadKey:Pt}),Kf=_.useMemo(()=>{const y=new Set;for(const k of Array.isArray(qt)?qt:[]){const M=String((k==null?void 0:k.name)||"").trim();M&&y.add(M)}return Array.from(y).sort()},[qt]),Ii=_.useMemo(()=>{const y=[];for(const k of Array.isArray(qt)?qt:[]){const M=String((k==null?void 0:k.name)||"").trim();if(!M)continue;const D=String((k==null?void 0:k.display_name)||"").trim();y.push({name:M,display_name:D||void 0})}return y},[qt]),ho=_.useMemo(()=>{const y=new Set;for(const k of xt||[]){if(!k||typeof k!="object")continue;const M=String(k.name||"").trim();M&&y.add(M)}return Array.from(y).sort()},[xt]),Cl=_.useMemo(()=>{const y=n.maintenance_ai_provider.trim();if(!y)return{models:[],error:""};const k=$t[y];return k?{models:(Array.isArray(k.models)?k.models:[]).map(D=>String(D||"").trim()).filter(Boolean),error:String(k.error||"")}:{models:[],error:""}},[$t,n.maintenance_ai_provider]),Lc=n.maintenance_ai_provider.trim(),Ic=!!(Lc&&$&&!Object.prototype.hasOwnProperty.call($t,Lc));_.useEffect(()=>{const y=fo.trim();if(!y||$t[y]||Ci.current[y])return;Ci.current[y]=!0;let k=!1;return(async()=>{try{const D=await Te.discovery_provider_models(y);if(k)return;const q=Array.isArray(D==null?void 0:D.models)?D.models:[],H=typeof(D==null?void 0:D.error)=="string"?String(D.error):"";At(V=>({...V,[y]:{models:q,error:H||void 0}}))}catch(D){if(k)return;At(q=>({...q,[y]:{models:[],error:String((D==null?void 0:D.message)||D||"Failed to load models")}}))}finally{delete Ci.current[y]}})(),()=>{k=!0}},[fo,$t,Te]),_.useEffect(()=>{const y=n.maintenance_ai_provider.trim();if(!y||!$||$t[y]||Ci.current[y])return;Ci.current[y]=!0;let k=!1;return(async()=>{try{const D=await Te.discovery_provider_models(y);if(k)return;const q=Array.isArray(D==null?void 0:D.models)?D.models:[],H=typeof(D==null?void 0:D.error)=="string"?String(D.error):"";At(V=>({...V,[y]:{models:q,error:H||void 0}}))}catch(D){if(k)return;At(q=>({...q,[y]:{models:[],error:String((D==null?void 0:D.message)||D||"Failed to load models")}}))}finally{delete Ci.current[y]}})(),()=>{k=!0}},[n.maintenance_ai_provider,$t,Te,$]);function Tn(y,k){const M=String(y||"").trim();if(!M)return;let D={};try{const q=JSON.parse(T||"{}");typeof q=="object"&&q!==null&&!Array.isArray(q)&&(D=q)}catch{D={}}if(k==null){delete D[M],I(JSON.stringify(D,null,2));return}if(typeof k=="string")k?D[M]=k:delete D[M];else if(Array.isArray(k)){const q=k.map(H=>H).filter(H=>H!=null);q.length?D[M]=q:delete D[M]}else D[M]=k;I(JSON.stringify(D,null,2))}async function Fa(y){const k=String(y||"").trim();if(!k)return fe("Missing bundle_id"),null;fe(""),se(!0);try{const M=await Te.get_bundle(k);return J(M),Jt({ts:Ct(),kind:"info",title:`Loaded bundle ${k}`}),M}catch(M){return J(null),fe(String((M==null?void 0:M.message)||M||"Failed to load bundle")),null}finally{se(!1)}}function Ps(y){const k=[],M=Array.isArray(y==null?void 0:y.items)?y.items:[];for(const D of M){const q=String((D==null?void 0:D.bundle_id)||"").trim();if(!q)continue;const H=Array.isArray(D==null?void 0:D.entrypoints)?D.entrypoints:[];if(H.length)for(const V of H){const ne=String((V==null?void 0:V.flow_id)||"").trim();if(!ne||(V==null?void 0:V.deprecated)===!0)continue;const Le=`${q}:${ne}`,_e=String((V==null?void 0:V.name)||"").trim(),he=_e?`${q} · ${_e}`:`${q} · ${ne}`,$e=String((V==null?void 0:V.description)||"").trim(),ze=(Array.isArray(V==null?void 0:V.interfaces)?V.interfaces:[]).some(Ve=>String(Ve||"").trim().length>0),Ze=Array.isArray(V==null?void 0:V.agent_default_interfaces)?V.agent_default_interfaces.map(Ve=>String(Ve||"").trim()).filter(Boolean):[];k.push({workflow_id:Le,bundle_id:q,bundle_ref:String((D==null?void 0:D.bundle_ref)||"").trim(),flow_id:ne,label:he,description:$e||void 0,has_interface:ze,agent_default_interfaces:Ze})}}return k.sort((D,q)=>D.label.localeCompare(q.label)),k}async function lr(y=Te,k){if(st.current&&!(k!=null&&k.force))return;st.current=!0;const M=pi.current;jr(!0);try{const D=_e=>_e.map(g2).filter(he=>!!he.run_id),[q,H]=await Promise.all([y.list_runs({limit:200,root_only:!0,include_metrics:!0}),y.list_runs({limit:500,root_only:!1,include_metrics:!0})]);if(M!==pi.current)return;const V=Array.isArray(q==null?void 0:q.items)?q.items:[],ne=Array.isArray(H==null?void 0:H.items)?H.items:[],Le=D(V).filter(_e=>!String(_e.parent_run_id||"").trim()||_e.role==="occurrence");$n(Le),In(D(ne).filter(_e=>!!_e.run_id)),Sr(Date.now()),Et.current=0,ct.current=0}catch(D){const q=String((D==null?void 0:D.message)||D||"");if(Jt({ts:Ct(),kind:"error",title:"Refresh runs failed",preview:St(q)}),(/\b40[13]\b/.test(q)||/unauthorized|forbidden/i.test(q))&&O.refresh().catch(()=>{}),/\b429\b/.test(q)||/too many requests/i.test(q)){const H=Math.min(12e4,Math.max(15e3,Et.current*2||15e3));Et.current=H,ct.current=Date.now()+H,Jt({ts:Ct(),kind:"info",title:`Gateway rate-limited — pausing polls ${Math.round(H/1e3)}s`})}}finally{st.current=!1,jr(!1)}}async function za(y){var ne,Le,_e;const k=pi.current;te(!0),At({});const[M,,D,q,H]=await Promise.allSettled([y.list_bundles(),lr(y),y.discovery_tools(),y.discovery_providers({include_models:!1}),y.discovery_capabilities()]);if(k!==pi.current)return;if(M.status==="rejected"&&D.status==="rejected"&&q.status==="rejected"){te(!1),z(lp(M.reason,n)),Jt({ts:Ct(),kind:"error",title:"Discovery failed",preview:St(String(M.reason||""))});return}zt(H.status==="fulfilled"?y2(H.value):{available:!1,reason:`Could not read the gateway capabilities: ${String(((ne=H.reason)==null?void 0:ne.message)||H.reason)}`});let V=0;if(M.status==="fulfilled"){const he=Ps(M.value);V=he.length,pn(he)}else pn([]),Jt({ts:Ct(),kind:"error",title:"Discovery bundles failed",preview:St(String(M.reason||""))});if(D.status==="fulfilled"){const he=Array.isArray((Le=D.value)==null?void 0:Le.items)?D.value.items:[];Yt(he)}else Yt([]),Jt({ts:Ct(),kind:"error",title:"Discovery tools failed",preview:St(String(D.reason||""))});if(q.status==="fulfilled"){const he=Array.isArray((_e=q.value)==null?void 0:_e.items)?q.value.items:[];Ot(he)}else Ot([]),Jt({ts:Ct(),kind:"error",title:"Discovery providers failed",preview:St(String(q.reason||""))});Jt({ts:Ct(),kind:"info",title:"Gateway discovery loaded",preview:St(`workflows: ${V}`)})}async function Xs(y){var k,M;z(""),te(!1),P(!0);try{if(!(y!=null&&y.prefer_direct)&&(await O.refresh(),El.current))return;const D=String(n.auth_token||"").trim();if(!D){y!=null&&y.open_modal_if_needed&&O.openModal();return}const q=String(n.gateway_url||"").trim();if(q){const V=q.toLowerCase();if(!V.startsWith("http://")&&!V.startsWith("https://"))throw new Error("Gateway URL must start with http:// or https:// (or leave it blank to use same origin / dev proxy).");try{if(String(((k=window==null?void 0:window.location)==null?void 0:k.protocol)||"")==="https:"&&V.startsWith("http://"))throw new Error("Gateway URL is http:// but this page is https:// (mixed content is blocked). Use https:// or leave Gateway URL blank to use same origin /api proxy.");const Le=new URL(q),_e=String(((M=window==null?void 0:window.location)==null?void 0:M.hostname)||"").trim().toLowerCase(),he=String(Le.hostname||"").trim().toLowerCase(),$e=Pe=>Pe==="localhost"||Pe==="127.0.0.1"||Pe==="::1";if($e(he)&&_e&&!$e(_e))throw new Error("Gateway URL points to localhost, which from this device is not your machine. Use the gateway's public URL (e.g. an ngrok https URL) or leave Gateway URL blank to use same origin /api proxy.")}catch(ne){throw new Error(String((ne==null?void 0:ne.message)||ne||"Invalid Gateway URL"))}}const H=new O_({base_url:q,auth_token:D});await H.list_bundles(),s(V=>({...V,gateway_auth_mode:"direct"})),await za(H)}catch(D){z(lp(D,n))}finally{P(!1)}}const El=_.useRef(!1),pi=_.useRef(0),Pc=_.useRef(!1);function dd(y){var M,D,q;G(y);const k=!!(y&&y.has_session&&((M=y.gateway)!=null&&M.ok));if(El.current=k,k){if(Pc.current=!1,$&&n.gateway_auth_mode==="direct")return;const H=String(((q=(D=y==null?void 0:y.gateway)==null?void 0:D.principal)==null?void 0:q.user_id)||"").trim();if(s(V=>({...V,gateway_auth_mode:"session",auth_token:"",gateway_user:H||V.gateway_user})),$&&n.gateway_auth_mode==="session")return;z(""),P(!0),za(new O_({base_url:"",auth_token:""})).catch(V=>z(lp(V,n))).finally(()=>P(!1));return}y&&!y.has_session&&(n.gateway_auth_mode==="session"&&$l({keep_session:!0}),String(n.auth_token||"").trim()&&!$&&!Pc.current&&(Pc.current=!0,Xs({prefer_direct:!0})))}async function Dn(){if(!(jt||W)){Kt(!0);try{await Te.reload_bundles();const y=await Te.list_bundles(),k=Ps(y);pn(k),Jt({ts:Ct(),kind:"info",title:"Bundles reloaded",preview:St(`workflows: ${k.length}`)})}catch(y){const k=String((y==null?void 0:y.message)||y||"Bundle reload failed");Jt({ts:Ct(),kind:"error",title:"Bundle reload failed",preview:St(k),data:{error:k}})}finally{Kt(!1)}}}async function Oc(y){if(Cs||W||!$)return;const k=y;if(k){qs(!0),nn("");try{const M=await Te.upload_bundle(k,{overwrite:!1,reload:!0});Jt({ts:Ct(),kind:"info",title:"Bundle uploaded",preview:St(String((M==null?void 0:M.bundle_ref)||""))});const D=await Te.list_bundles(),q=Ps(D);pn(q)}catch(M){const D=String((M==null?void 0:M.message)||M||"Upload failed");nn(D),Jt({ts:Ct(),kind:"error",title:"Upload .flow failed",preview:St(D),data:{error:D}})}finally{qs(!1);try{it.current&&(it.current.value="")}catch{}}}}function $l(y){pi.current+=1,y!=null&&y.keep_session||(O.signOut().catch(()=>{}),El.current=!1),Uc(),E(""),N(""),Qi(""),J(null),fe(""),se(!1),pn([]),$n([]),In([]),Sr(null),Pn([]),Yt([]),Ot([]),At({}),z(""),te(!1),G(null),s(k=>({...k,auth_token:""})),Jt({ts:Ct(),kind:"info",title:"Gateway disconnected"})}async function Dc(y){const k=String(y??"");k&&Qn(await pE(k)?"Copied to clipboard":mE,2)}_.useEffect(()=>{const y=c.trim();if(!De||!y)return;let k=!1;const M=async()=>{if(!(ct.current>Date.now()))try{const q=await Te.get_run(y);k||fs(q)}catch{}};M();const D=window.setInterval(M,2e3);return()=>{k=!0,window.clearInterval(D)}},[De,c,Te]),_.useEffect(()=>{if(!$)return;let y=null,k=!1,M=!1;const D=V=>{k||(y!==null&&window.clearTimeout(y),y=window.setTimeout(()=>void q(),V))},q=async()=>{if(M)return;const V=ct.current-Date.now();if(V>0){D(V+500);return}M=!0;const ne=Date.now();try{await lr(Te)}finally{M=!1;const Le=Date.now()-ne,_e=document.visibilityState==="hidden"?3e4:5e3;D(Math.max(_e,Le*3))}},H=()=>{document.visibilityState==="visible"&&q()};return q(),document.addEventListener("visibilitychange",H),()=>{k=!0,y!==null&&window.clearTimeout(y),document.removeEventListener("visibilitychange",H)}},[$,Te]);const[Fc,Al]=_.useState(null);_.useEffect(()=>{if(!$){Al(null);return}let y=!1;return(async()=>{try{const k=await Te.get_entity_phases_spec();if(y)return;const M=pL(k);if(Al(M),M)try{const D=localStorage.getItem("abstractobserver_phase_graph_id_v1"),q=D?JSON.parse(D):null;q&&q.sha256&&M.sha256&&q.sha256!==M.sha256&&q.version===M.version&&Jt({ts:Ct(),kind:"error",title:"Phase-graph drift: served bytes changed without a version bump",preview:St(`v${M.version}: ${String(q.sha256).slice(0,12)}… -> ${String(M.sha256).slice(0,12)}…`),data:{prev:q,now:{sha256:M.sha256,version:M.version}}}),localStorage.setItem("abstractobserver_phase_graph_id_v1",JSON.stringify({sha256:M.sha256,version:M.version}))}catch{}}catch(k){if(!y){Al(null);const M=String((k==null?void 0:k.message)||k||"");/404|not found/i.test(M)||Jt({ts:Ct(),kind:"info",title:"Phase-graph fetch failed — pre-wire fallback vocabulary in use (#FALLBACK)",preview:St(M),data:{error:M}})}}})(),()=>{y=!0}},[$]),_.useEffect(()=>{if(!$){Pn([]),Ge("");return}let y=!1,k=null;const M=async()=>{if(!(ct.current>Date.now())){try{const D=await Te.list_entities(),q=D.entities.map(V=>String((V==null?void 0:V.name)||(V==null?void 0:V.slug)||"").trim()).filter(Boolean).slice(0,12),H=await Promise.all(q.map(async V=>{var ne,Le;try{const[_e,he]=await Promise.all([Te.get_entity_card(V),Te.get_entity_cognition(V).catch(()=>null)]),$e=_e!=null&&_e.state&&typeof _e.state=="object"?_e.state:null,Pe=Array.isArray(_e==null?void 0:_e.moments)?_e.moments:[],ze=Pe.length?Pe[Pe.length-1]:null,Ze=(ne=he==null?void 0:he.spend)==null?void 0:ne.lifetime,Ve=(Le=he==null?void 0:he.spend)==null?void 0:Le.live_visit,sn=Array.isArray(he==null?void 0:he.warnings)?he.warnings.map(Be=>String(Be||"")).filter(Boolean):[],Rt=sL(_e);return{name:V,state:String(($e==null?void 0:$e.state)??(typeof(_e==null?void 0:_e.state)=="string"?_e.state:"")).trim(),age_days:typeof(_e==null?void 0:_e.age_days)=="number"?_e.age_days:null,last_moment:String((ze==null?void 0:ze.kind)||"").trim(),last_moment_at:String((ze==null?void 0:ze.at)||"").trim(),working:typeof(he==null?void 0:he.working)=="boolean"?he.working:null,tokens_total:typeof(Ze==null?void 0:Ze.tokens_total)=="number"?Ze.tokens_total:null,live_visit_tokens:typeof(Ve==null?void 0:Ve.tokens_total)=="number"?Ve.tokens_total:null,spend_warning:sn.join(" | "),live_phase:typeof(he==null?void 0:he.phase)=="string"?he.phase:"",open_questions:Rt.questions,open_questions_total:Rt.questions_total,open_problems:Rt.problems,open_problems_total:Rt.problems_total,lessons:Rt.lessons,lessons_total:Rt.lessons_total,dreams_brief:rL(_e),error:""}}catch(_e){return{name:V,state:"",age_days:null,last_moment:"",last_moment_at:"",working:null,tokens_total:null,live_visit_tokens:null,spend_warning:"",live_phase:"",open_questions:[],open_questions_total:0,open_problems:[],open_problems_total:0,lessons:[],lessons_total:0,dreams_brief:null,error:String((_e==null?void 0:_e.message)||_e||"card failed")}}}));y||(Pn(H),je(D.entities.length),Ge(""))}catch(D){if(!y){Pn([]);const q=String((D==null?void 0:D.message)||D||"");Ge(/404|not found/i.test(q)?"":q)}}y||(k=window.setTimeout(()=>void M(),3e4))}};return M(),()=>{y=!0,k!==null&&window.clearTimeout(k)}},[$,Te]);async function Go(y,k,M){const D=String(k||"").trim();if(!y||!D)throw new Error("This wait has no wait_key yet — open the run to inspect.");await Te.submit_command({command_id:xr(),run_id:y,type:"resume",payload:{wait_key:D,payload:M||{}},client_id:"web_pwa"}),Jt({ts:Ct(),kind:"info",title:"Board resume submitted",preview:St(`run ${y} · wait ${D}`),data:{run_id:y,wait_key:D}}),lr(Te,{force:!0}),window.setTimeout(()=>void lr(Te,{force:!0}),1200)}const yn=_.useMemo(()=>{const y=ue==null?void 0:ue.session_id;return typeof y=="string"?y.trim():y==null?"":String(y||"").trim()},[ue]),Mn=_.useMemo(()=>{const y=String(yn||"").trim();return y||String(K||"").trim()},[yn,K]);_.useEffect(()=>{if(!$||!Mn){ie(""),ci("");return}(async()=>{try{const y=await IL(Mn);ie(y)}catch{ie("")}})()},[$,Mn]);const Ht=AL({gateway:$?Te:null,session_id:Mn,run_id:B,on_error:ci,on_transcript:y=>{const k=String(y||"").trim();k&&(es(M=>{const D=String(M||"");return D.trim()?`${D.trimEnd()}
143
- ${k}`:k}),window.setTimeout(()=>{var M;return(M=Xt.current)==null?void 0:M.focus()},0))}});function zc(y,k){try{const M=URL.createObjectURL(y),D=document.createElement("a");D.href=M,D.download=k||"download",D.rel="noreferrer",document.body.appendChild(D),D.click(),document.body.removeChild(D),window.setTimeout(()=>URL.revokeObjectURL(M),5e3)}catch{}}async function Tl(){const y=ga.trim();if(!y){Qn("This run recorded no workspace folder",2);return}try{const k=await fetch(_N,{method:"POST",headers:{"Content-Type":"application/json",...Zx()},body:JSON.stringify({path:y})}),M=await k.json().catch(()=>({}));k.ok&&(M!=null&&M.ok)?Qn(`Opened ${String(M.path||y)}`,2):Qn(String((M==null?void 0:M.error)||`Folder reveal failed (${k.status})`),3)}catch(k){Qn(String((k==null?void 0:k.message)||k||"Folder reveal failed"),3)}}async function Ml(y){const k=String((y==null?void 0:y.run_id)||"").trim(),M=String((y==null?void 0:y.artifact_id)||"").trim();if(!k||!M){Qn("Artifact download needs a run id",3);return}const D=$p(y)||M;try{const q=await Te.download_run_artifact_content(k,M,{access:"preview"});zc(q,By(D)),Qn("Downloaded artifact",2)}catch(q){Qn(String((q==null?void 0:q.message)||q||"Download failed"),3)}}async function Vm(y){const k=String((y==null?void 0:y.run_id)||"").trim(),M=String((y==null?void 0:y.artifact_id)||"").trim();if(!k||!M){Qn("Artifact preview needs a run id",3);return}const D=$p(y),q=String((y==null?void 0:y.content_type)||"").trim().toLowerCase(),H=cf(y);if(En(D||M),xs(""),jl(""),Ra(H),La(y),uo(!0),fn&&(URL.revokeObjectURL(fn),wr("")),H==="binary"){xs(`(Binary artifact: ${q||"unknown"}; download to view.)`);return}if(H==="text"&&typeof y.size_bytes=="number"&&y.size_bytes>15e5){xs(`(Text artifact is ${y.size_bytes.toLocaleString()} bytes; download to view.)`);return}xl(!0);try{const V=await Te.download_run_artifact_content(k,M,{access:"preview"});if(H==="text"){const ne=await V.text(),Le=um(y,ne),_e=Le==="json"?15e5:Le==="markdown"?25e4:Le==="html"?3e5:22e3;xs(ne.length>_e&&Le!=="text"?`${Yl(y.size_bytes??ne.length)} ${Le.toUpperCase()} artifact. Download to inspect it.`:ne.length>_e?`${ne.slice(0,Math.max(0,_e-1))}…`:ne)}else wr(URL.createObjectURL(V))}catch(V){jl(String((V==null?void 0:V.message)||V||"Preview failed"))}finally{xl(!1)}}_.useEffect(()=>()=>{fn&&URL.revokeObjectURL(fn)},[fn]);async function Cr(y){const k=String(y.artifact_id||"").trim(),M=String(y.run_id||"").trim(),D=cf(y);if(!M||!k)return{artifact_id:k,kind:D,render_kind:"",text:"Preview needs artifact run metadata.",url:"",loading:!1,error:""};if(D==="binary")return{artifact_id:k,kind:D,render_kind:"",text:`Preview unavailable for ${y.content_type||y.modality||"this artifact"}. Download to inspect it.`,url:"",loading:!1,error:""};if(D==="text"&&typeof y.size_bytes=="number"&&y.size_bytes>5e5)return{artifact_id:k,kind:D,render_kind:"",text:`${Yl(y.size_bytes)} text artifact. Use Preview for a larger view or Download to inspect locally.`,url:"",loading:!1,error:""};try{const q=await Te.download_run_artifact_content(M,k,{access:"preview"});if(D==="text"){const H=await q.text(),V=um(y,H),ne=V==="json"?5e5:V==="markdown"?12e4:V==="html"?3e5:8e3;return{artifact_id:k,kind:D,render_kind:V,text:H.length>ne&&V!=="text"?`${Yl(y.size_bytes??H.length)} ${V.toUpperCase()} artifact. Use Larger preview or Download to inspect it.`:H.length>ne?`${H.slice(0,Math.max(0,ne-1))}…`:H,url:"",loading:!1,error:""}}return{artifact_id:k,kind:D,render_kind:"",text:"",url:URL.createObjectURL(q),loading:!1,error:""}}catch(q){return{artifact_id:k,kind:D,render_kind:"",text:"",url:"",loading:!1,error:String((q==null?void 0:q.message)||q||"Preview failed")}}}async function fd(y){if(Ks.url&&URL.revokeObjectURL(Ks.url),!y){Ma(Na());return}const k=String(y.artifact_id||"").trim(),M=cf(y);Ma({artifact_id:k,kind:M,render_kind:"",text:"",url:"",loading:!0,error:""}),Ma(await Cr(y))}function Jt(y){const k=String(y.id||"").trim()||xr();Pu(M=>[{...y,id:k},...M].slice(0,800))}function Qn(y,k){ha(y),Ji.current&&window.clearTimeout(Ji.current),Ni(!1),window.requestAnimationFrame(()=>Ni(!0)),Ji.current=window.setTimeout(()=>{Ni(!1),Ji.current=null},1500),gs.current&&(window.clearTimeout(gs.current),gs.current=null),k>0&&(gs.current=window.setTimeout(()=>{ha(""),gs.current=null},Math.max(1,k)*1e3))}function Fn(y,k){const M=String(y||"").trim(),D=String(k||"").trim();if(!D)return"";const q=M?String(to.current[M]||"").trim():"";return q?`${q}::${D}`:D}function rs(y,k,M){const D=String(y||"").trim(),q=String(k||"").trim(),H=String(M||"").trim();if(!D||!q||!H)return;const V=Fn(D,q);V&&(to.current[H]=V,no.current[H]=D,xc.current[H]={parent_run_id:D,parent_node_id:q},ro.current.has(H)||(ro.current.add(H),ja(ne=>ne.includes(H)?ne:[...ne,H])))}function mo(y){const k=String(y||"").trim();if(!k)return;const M=Date.now(),D=di.current;di.current=k,eo(M),hl(q=>{const H={};for(const[_e,he]of Object.entries(q))typeof he=="number"&&he>M&&(H[_e]=he);H[k]=Math.max(H[k]||0,M+2e3),D&&D!==k&&(H[D]=Math.max(H[D]||0,M+2e3));const V=Object.keys(H);if(V.length<=200)return H;const ne=V.sort((_e,he)=>(H[he]||0)-(H[_e]||0)).slice(0,200),Le={};for(const _e of ne)Le[_e]=H[_e]||0;return Le}),Vu(q=>{if(typeof q[k]=="number")return q;const H={...q,[k]:M};if(ml.current.push(k),ml.current.length>8e3){const V=ml.current.splice(0,1500);for(const ne of V)delete H[ne]}return H}),gr.current&&window.clearTimeout(gr.current),gr.current=window.setTimeout(()=>{const q=Date.now();hl(H=>{const V={};for(const[ne,Le]of Object.entries(H))typeof Le=="number"&&Le>q&&(V[ne]=Le);return V}),eo(q),gr.current=null},2200)}function Bc(y,k){var Ve,sn,Rt;const M=String(k||"").trim()||c.trim();ds.current=y.cursor,(Ve=ii.current)==null||Ve.push({cursor:y.cursor,record:y.record}),M&&io.current.add(`${M}:${y.cursor}`);const D=Rh(y.record),q=D&&D.name?rf(D.name):"",H=y.record,V=typeof(H==null?void 0:H.node_id)=="string"?H.node_id:"",ne=typeof(H==null?void 0:H.status)=="string"?H.status:"",Le=typeof((sn=H==null?void 0:H.effect)==null?void 0:sn.type)=="string"?H.effect.type:"",_e=typeof(H==null?void 0:H.run_id)=="string"?H.run_id:"",he=_e||M;if(q==="abstract.status"&&he===M){const{text:Be,duration:bt}=su(D==null?void 0:D.payload);Qn(Be,bt)}const $e=V?Fn(he,V):"";if(ne==="waiting"){const Be=sa(H);if(String((Be==null?void 0:Be.reason)||"").trim()==="subworkflow"){const xn=typeof((Rt=Be==null?void 0:Be.details)==null?void 0:Rt.sub_run_id)=="string"?String(Be.details.sub_run_id):"";xn&&V&&rs(he,V,xn)}}if(V&&(mo(Fn(he,V)),ne==="waiting"||ne==="running")){const Be=Fn(he,V);Be&&(di.current=Be,Oo(Be))}let Pe="step",ze=$e||V||"(node?)",Ze="";if(D&&D.name&&ap(D.name))Pe=q==="abstract.message"?"message":"event",ze=q||D.name,Ze=St(q==="abstract.steer_seen"?op(D==null?void 0:D.payload):su(D==null?void 0:D.payload).text);else if(H!=null&&H.error)Pe="error",ze="error",Ze=St(cs(H.error,360));else if(ne==="waiting"){const Be=sa(H),bt=String((Be==null?void 0:Be.reason)||"").trim();Ze=St(bt?`waiting • ${bt}`:"waiting")}else H!=null&&H.result?Ze=St(cs(H.result,360)):Le?Ze=St(Le):Ze=St(Xh(H));Jt({id:`step:${_e||M||"?"}:${y.cursor}`,ts:String((H==null?void 0:H.ended_at)||(H==null?void 0:H.started_at)||Ct()),kind:Pe,title:ze,preview:Ze,data:H,cursor:y.cursor,run_id:_e||M||void 0,node_id:$e||V,status:ne,effect_type:Le,emit_name:q||(D==null?void 0:D.name)||void 0})}function hd(y,k){var Ze,Ve,sn;so.current=Math.max(so.current,k.cursor);const M=`${y}:${k.cursor}`;if(!!io.current.has(M))return;io.current.add(M),(Ze=oi.current)==null||Ze.push({run_id:y,cursor:k.cursor,record:k.record});const q=Rh(k.record),H=q&&q.name?rf(q.name):"",V=k.record,ne=typeof(V==null?void 0:V.node_id)=="string"?V.node_id:"",Le=ne?Fn(y,ne):"",_e=typeof(V==null?void 0:V.status)=="string"?V.status:"",he=typeof((Ve=V==null?void 0:V.effect)==null?void 0:Ve.type)=="string"?V.effect.type:"";if(_e==="waiting"){const Rt=sa(V);if(String((Rt==null?void 0:Rt.reason)||"").trim()==="subworkflow"){const bt=typeof((sn=Rt==null?void 0:Rt.details)==null?void 0:sn.sub_run_id)=="string"?String(Rt.details.sub_run_id):"";bt&&ne&&rs(y,ne,bt),bt&&hi.current.trim()===String(y||"").trim()&&(hi.current=bt,oo(bt))}}if(ne&&(mo(Fn(y,ne)),_e==="waiting"||_e==="running")){const Rt=Fn(y,ne);Rt&&(di.current=Rt,Oo(Rt))}if((_e==="completed"||_e==="failed")&&hi.current.trim()===String(y||"").trim()){const Rt=String(no.current[String(y||"").trim()]||"").trim();Rt&&Rt!==c.trim()?(hi.current=Rt,oo(Rt)):(hi.current="",oo(""))}if(H==="abstract.status"&&y===c.trim()){const{text:Rt,duration:Be}=su(q==null?void 0:q.payload);Qn(Rt,Be)}let $e="step",Pe=Le||ne||"(node?)",ze="";if(q&&q.name&&ap(q.name))$e=H==="abstract.message"?"message":"event",Pe=`subrun • ${H||q.name}`,ze=St(H==="abstract.steer_seen"?op(q==null?void 0:q.payload):su(q==null?void 0:q.payload).text);else if(V!=null&&V.error)$e="error",Pe="error",ze=St(cs(V.error,360));else if(_e==="waiting"){const Rt=sa(V),Be=String((Rt==null?void 0:Rt.reason)||"").trim();ze=St(Be?`waiting • ${Be}`:"waiting")}else V!=null&&V.result?ze=St(cs(V.result,360)):he?ze=St(he):ze=St(Xh(V));Jt({id:`step:${y}:${k.cursor}`,ts:String((V==null?void 0:V.ended_at)||(V==null?void 0:V.started_at)||Ct()),kind:$e,title:Pe,preview:ze,data:V,cursor:k.cursor,run_id:y,node_id:Le||ne,status:_e,effect_type:he,emit_name:H||(q==null?void 0:q.name)||""})}function Yf(y,k){var Ve,sn,Rt;const M=String(y||"").trim();if(!M)return;const D=`${M}:${k.cursor}`;if(!!io.current.has(D))return;io.current.add(D),(Ve=oi.current)==null||Ve.push({run_id:M,cursor:k.cursor,record:k.record});const H=Rh(k.record),V=H&&H.name?rf(H.name):"",ne=k.record,Le=typeof(ne==null?void 0:ne.node_id)=="string"?ne.node_id:"",_e=Le?Fn(M,Le):"",he=typeof(ne==null?void 0:ne.status)=="string"?ne.status:"",$e=typeof((sn=ne==null?void 0:ne.effect)==null?void 0:sn.type)=="string"?ne.effect.type:"";if(he==="waiting"){const Be=sa(ne);if(String((Be==null?void 0:Be.reason)||"").trim()==="subworkflow"){const xn=typeof((Rt=Be==null?void 0:Be.details)==null?void 0:Rt.sub_run_id)=="string"?String(Be.details.sub_run_id):"";xn&&Le&&rs(M,Le,xn)}}if(Le&&(mo(Fn(M,Le)),he==="waiting"||he==="running")){const Be=Fn(M,Le);Be&&(di.current=Be,Oo(Be))}if(V==="abstract.status"&&M===c.trim()){const{text:Be,duration:bt}=su(H==null?void 0:H.payload);Qn(Be,bt)}let Pe="step",ze=_e||Le||"(node?)",Ze="";if(H&&H.name&&ap(H.name))Pe=V==="abstract.message"?"message":"event",ze=`subrun • ${V||H.name}`,Ze=St(V==="abstract.steer_seen"?op(H==null?void 0:H.payload):su(H==null?void 0:H.payload).text);else if(ne!=null&&ne.error)Pe="error",ze="error",Ze=St(cs(ne.error,360));else if(he==="waiting"){const Be=sa(ne),bt=String((Be==null?void 0:Be.reason)||"").trim();Ze=St(bt?`waiting • ${bt}`:"waiting")}else ne!=null&&ne.result?Ze=St(cs(ne.result,360)):$e?Ze=St($e):Ze=St(Xh(ne));Jt({id:`step:${M}:${k.cursor}`,ts:String((ne==null?void 0:ne.ended_at)||(ne==null?void 0:ne.started_at)||Ct()),kind:Pe,title:ze,preview:Ze,data:ne,cursor:k.cursor,run_id:M,node_id:_e||Le,status:he,effect_type:$e,emit_name:V||(H==null?void 0:H.name)||""})}async function md(y,k){var D,q;let M=k.after;for(;;){if((D=k.signal)!=null&&D.aborted)return M;const H=await Te.get_ledger(y,{after:M,limit:200,signal:k.signal});if((q=k.signal)!=null&&q.aborted)return M;const V=Array.isArray(H.items)?H.items:[];if(!V.length)return ds.current=M,M;const ne=M;for(let Le=0;Le<V.length;Le++){const _e=V[Le];Bc({cursor:ne+Le+1,record:_e},y)}M=typeof H.next_after=="number"?H.next_after:M}}async function Rl(y){var H,V,ne,Le;const k=String(y||"").trim();nn(""),tn(!0),on(!1),(H=ii.current)==null||H.reset(),(V=oi.current)==null||V.reset(),Or.current={scanned:0,found:null},Yr([]),ds.current=0,Ws([]),io.current=new Set,Pu([]),Bu(""),ha(""),fs(null),Qr(""),Po(""),Oo(""),di.current="",hl({}),Vu({}),ml.current=[],eo(Date.now()),to.current=k?{[k]:""}:{},no.current={},xc.current={},ro.current=new Set,ja([]),Sa.current="",hi.current="",oo(""),Do.current={},gr.current&&window.clearTimeout(gr.current),gr.current=null,Zr.current&&window.clearTimeout(Zr.current),Zr.current=null,Ei.current&&Ei.current.abort(),zr.current&&zr.current.abort(),zr.current=null,so.current=0,ka("");const M=new AbortController;Ei.current=M;let D=!1;try{let _e="",he="";try{const $e=await Te.get_run(k);fs($e);const Pe=typeof($e==null?void 0:$e.workflow_id)=="string"?String($e.workflow_id):"",ze=xv(Pe);ze&&(_e=ze.bundle_id,he=ze.flow_id)}catch{}try{const $e=await Te.get_run_input_data(k);typeof($e==null?void 0:$e.bundle_id)=="string"&&(_e=String($e.bundle_id||"").trim()||_e),typeof($e==null?void 0:$e.flow_id)=="string"&&(he=String($e.flow_id||"").trim()||he);const Pe=$e&&typeof $e.input_data=="object"&&$e.input_data&&!Array.isArray($e.input_data)?$e.input_data:null;Pe&&I(JSON.stringify(Pe,null,2));const ze=$e==null?void 0:$e.workspace,Ze=typeof(ze==null?void 0:ze.workspace_root)=="string"?String(ze.workspace_root).trim():"";Po(Ze)}catch{Po("")}_e&&he&&(E(_e),N(he),Qi(he),await Fa(_e)),await md(k,{after:0,signal:M.signal});try{const $e=await Te.get_run_history_bundle(k,{include_subruns:!0,include_session:!1,ledger_mode:"tail",ledger_max_items:1}),Pe=$e&&typeof $e=="object"?$e.ledgers:null,Ze=(Pe&&typeof Pe=="object"?Object.keys(Pe):[]).map(Ve=>String(Ve||"").trim()).filter(Boolean).filter(Ve=>Ve!==k);if(Ze.length){for(const Ve of Ze)ro.current.add(Ve);ja(Ve=>Array.from(new Set([...Ve,...Ze])));try{const Ve=typeof((ne=Pe==null?void 0:Pe[k])==null?void 0:ne.total)=="number"?Number(Pe[k].total):0;let sn="",Rt=-1;for(const Be of Ze){const bt=typeof((Le=Pe==null?void 0:Pe[Be])==null?void 0:Le.total)=="number"?Number(Pe[Be].total):0;bt>Rt&&(sn=Be,Rt=bt)}sn&&Rt>Math.max(Ve*3,Ve+20)&&(hi.current=sn,oo(sn))}catch{}}}catch{}on(!0),Jt({ts:Ct(),kind:"info",title:`Attached to run ${k}`,data:{run_id:k}}),D=!0}catch(_e){const he=String((_e==null?void 0:_e.message)||_e||"unknown error");nn(he),Jt({ts:Ct(),kind:"error",title:"Connection error",preview:St(he),data:{error:he}}),on(!1)}finally{tn(!1)}if(!D||M.signal.aborted)return;(async()=>{let _e=250;for(;!M.signal.aborted;){try{const he=await md(k,{after:ds.current,signal:M.signal});await Te.stream_ledger(k,{after:he,on_step:$e=>Bc($e,k),signal:M.signal})}catch(he){if(M.signal.aborted)break;const $e=String((he==null?void 0:he.message)||he||"stream error");Jt({ts:Ct(),kind:"error",title:"Ledger stream error (will retry)",preview:St($e),data:{error:$e}})}if(M.signal.aborted)break;await new Promise(he=>setTimeout(he,_e)),_e=Math.min(5e3,Math.floor(_e*1.6))}})()}async function Jf(){const y=Js,k=(y==null?void 0:y.kind)==="bundle"?y.flow_id:(y==null?void 0:y.kind)==="default"?"@default":"",M=(y==null?void 0:y.kind)==="bundle"?y.bundle_id:"";if(!y){const D="Select a workflow first (Launch → pick a workflow).";return nn(D),D}nn(""),tn(!0);try{let D={};const q=T.trim();if(q)try{if(D=JSON.parse(q),typeof D!="object"||D===null||Array.isArray(D))throw new Error("input_data must be a JSON object")}catch(he){const $e=`Invalid input_data JSON: ${String((he==null?void 0:he.message)||he)}`;return nn($e),$e}for(const[he,$e]of Object.entries(D)){if(typeof $e!="string")continue;const Pe=$e.trim();Pe?D[he]=Pe:delete D[he]}const H=(_i||[]).find(he=>he&&typeof he=="object"&&he.id==="prompt"),V=H&&typeof H=="object"&&Object.prototype.hasOwnProperty.call(H,"default"),ne=D==null?void 0:D.prompt,Le=typeof ne=="string"?ne.trim():"";if(H&&!V&&!Le){const he="Missing required input_data.prompt";return nn(he),he}const _e=await Te.start_run(k,D,{...M?{bundle_id:M}:{},...y.kind==="default"?{interface:y.interface}:{},session_id:String(K||"").trim()||null});return p(_e),f(_e),hs(""),await Rl(_e),lr(),null}catch(D){const q=String((D==null?void 0:D.message)||D||"start failed");return nn(q),q}finally{tn(!1)}}async function Xf(){if(tt([]),Ke(null),!qe.available){tt([qe.reason]);return}const y=p2(We,{choice:Js,bundle_ref_for:k=>{var M;return((M=Pt.find(D=>D.bundle_id===k))==null?void 0:M.bundle_ref)||""},input_data:ut,email_usable:Tt.email_usable},Ie.current);if(!y.ok){tt(y.errors);return}Re(!0);try{const k=await Te.automations_client().createAutomation(y.body);Ie.current.reset(),xe([]),pt(Np),Jt({ts:Ct(),kind:"info",title:"Automation created",preview:St(`${y.body.title} · ${k.automation_id}`)}),t("automations"),await Tt.refresh(),await Tt.select(k.automation_id)}catch(k){const M=(k&&typeof k=="object"&&typeof k.code=="string"?k:null)||{status:0,code:"client_error",message:String((k==null?void 0:k.message)||k||"Create failed")};Ke(M)}finally{Re(!1)}}async function Zf(){if(hs(""),pe==="automate"){await Xf();return}const y=await Jf();if(y){hs(y);return}Zi("ledger"),t("observe")}async function _d(y){if(Tn("skills",void 0),!!y){if(y.kind==="default"){Ue(y.interface),E(""),N(""),J(null);return}Ue(""),E(y.bundle_id),N(y.flow_id),Qi(y.flow_id),await Fa(y.bundle_id)}}async function pd(y){const[k,M]=await Promise.all([Te.get_run(y),Te.get_run_input_data(y)]),D=S2(k,M);await _d(D.choice),I(JSON.stringify(D.input_data,null,2)),pt(D.form),xe([`Recreating the legacy schedule ${Qt(y,14)} as an automation. The legacy schedule keeps running until you suspend it.`,...D.notes]),Ie.current.reset(),ye("automate"),t("launch")}async function Zs(y,k){const M=String(y||"").trim();if(!M)return;if(dt){Qn(`Still attaching — retry in a moment (${Qt(M,14)})`,2500);return}nn(""),S("");const D=String((k==null?void 0:k.root_run_id)||M).trim()||M;p(D),f(M),await Rl(M)}_.useEffect(()=>{const y=String(g||"").trim();if(!y)return;let k=!1;return(async()=>{try{if($||await Xs({open_modal_if_needed:!0}),k)return;Zi("ledger"),t("observe");const M=await Te.find_run(y);if(k)return;if(M===null){Uc(),S(y);return}await Zs(y),zl()}catch(M){k||nn(String((M==null?void 0:M.message)||M||"Failed to attach run from URL"))}finally{k||w("")}})(),()=>{k=!0}},[g]);function Uc(){var y,k;Ei.current&&Ei.current.abort(),Ei.current=null,zr.current&&zr.current.abort(),zr.current=null,so.current=0,ka(""),f(""),p(""),to.current={},no.current={},xc.current={},ro.current=new Set,ja([]),Sa.current="",hi.current="",oo(""),Do.current={},Qr(""),gr.current&&window.clearTimeout(gr.current),gr.current=null,Zr.current&&window.clearTimeout(Zr.current),Zr.current=null,on(!1),tn(!1),Un(!1),ds.current=0,(y=ii.current)==null||y.reset(),(k=oi.current)==null||k.reset(),Or.current={scanned:0,found:null},Yr([]),Ws([]),io.current=new Set,fs(null),Pu([]),Oo(""),di.current="",hl({}),Vu({}),ml.current=[],eo(Date.now()),Qn("",-1),nn(""),ot([]),Dt(null),es(""),li(""),ke(!1),Bt(!1),vn(""),pr(""),ys(""),Lo([]),fc(!1),mc(""),_c(""),gc(!1),Io("")}_.useEffect(()=>{ot([]),Dt(null),es(""),li(""),ke(!1),Bt(!1),vn(""),pr(""),ys(""),Lo([]),fc(!1),mc(""),_c(""),gc(!1),Io("")},[c]),_.useEffect(()=>{ts==="chat"&&c.trim()&&$&&Wc()},[ts,c,$,ue==null?void 0:ue.workflow_id]);async function Ll(y,k,M){const D=String(y||"").trim();if(!D)return nn("Missing run_id"),"Missing run_id";nn("");try{const q={},H=String((M==null?void 0:M.reason)||"").trim();H&&(q.reason=H),await Te.submit_command({command_id:xr(),run_id:D,type:k,payload:q,client_id:"web_pwa"}),Jt({ts:Ct(),kind:"info",title:`${k} submitted`,preview:H?`reason: ${H}`:"",data:{run_id:D,type:k,reason:H}});try{if(D===c.trim()){const V=await Te.get_run(D);fs(V)}}catch{}return lr(Te,{force:!0}),window.setTimeout(()=>void lr(Te,{force:!0}),900),window.setTimeout(()=>void lr(Te,{force:!0}),2400),null}catch(q){const H=String((q==null?void 0:q.message)||q||`${k} failed`);return nn(H),H}}async function Ba(y,k){return Ll(c.trim(),y,k)}async function gd(y,k="Stopped from AbstractObserver"){const M=String(y||"").trim();if(!M||!window.confirm(`Cancel run ${Qt(M,24)}?`))return;await Ll(M,"cancel",{reason:k})||Qn("Cancel submitted",2)}async function yd(){var M;const y=c.trim();if(!y){nn("Select a run first.");return}if(!$){nn("Connect to the gateway first.");return}if(ft)return;const k=String(((M=ue==null?void 0:ue.waiting)==null?void 0:M.reason)||"").trim().toLowerCase()||String(cr||"").trim().toLowerCase();if(!os||ti||_o||ei.toLowerCase()!=="waiting"||k!=="until"){nn("This run is not a scheduled wait that can be triggered now.");return}nn(""),Un(!0);try{const D={payload:{mode:"run_now",requested_at:Ct()}},q=String(Er||"").trim();q&&(D.wait_key=q),await Te.submit_command({command_id:xr(),run_id:y,type:"resume",payload:D,client_id:"web_pwa"}),Jt({ts:Ct(),kind:"info",title:"Scheduled run triggered",preview:St(`run ${y}`),data:{run_id:y,until:Qs||null}});try{const H=await Te.get_run(y);fs(H)}catch{}}catch(D){nn(String((D==null?void 0:D.message)||D||"Failed to trigger scheduled run"))}finally{Un(!1)}}async function Qf(y){const k=c.trim();if(!k)return nn("Missing run_id"),"Missing run_id";if(An)return"Schedule update already in progress";const M=String(y.interval||"").trim();if(!/^\s*(\d+(?:\.\d+)?)\s*(ms|s|m|h|d)\s*$/i.test(M)){const q="Invalid interval (expected like '20m', '1h', '0.5s', '250ms')";return ai(q),q}ai(""),nn(""),Fr(!0),tn(!0);try{await Te.submit_command({command_id:xr(),run_id:k,type:"update_schedule",payload:{interval:M,apply_immediately:y.apply_immediately!==!1},client_id:"web_pwa"}),Jt({ts:Ct(),kind:"info",title:"Schedule updated",preview:St(`interval: ${M}`),data:{interval:M},run_id:k});try{const q=await Te.get_run(k);fs(q)}catch{}return null}catch(q){const H=String((q==null?void 0:q.message)||q||"update_schedule failed");return ai(H),nn(H),H}finally{tn(!1),Fr(!1)}}async function eh(y){const k=c.trim();if(!k)return nn("Missing run_id"),"Missing run_id";if(Es)return"Compaction already in progress";const M=typeof(y==null?void 0:y.preserve_recent)=="number"?y.preserve_recent:mr,D=Math.max(0,Math.min(500,Math.floor(Number.isFinite(M)?M:6))),q=(y==null?void 0:y.compression_mode)||Ki,H=String((y==null?void 0:y.focus)??fa??"").trim();_r(""),nn(""),$s(!0),tn(!0);try{const V={preserve_recent:D,compression_mode:q};return H&&(V.focus=H),await Te.submit_command({command_id:xr(),run_id:k,type:"compact_memory",payload:V,client_id:"web_pwa"}),Jt({ts:Ct(),kind:"info",title:"Compaction requested",preview:St(`mode: ${q} • preserve_recent: ${D}`),data:V,run_id:k}),null}catch(V){const ne=String((V==null?void 0:V.message)||V||"compact_memory failed");return _r(ne),nn(ne),ne}finally{tn(!1),$s(!1)}}async function th(){const y=c.trim();if(!y){li("Select a run first.");return}if(!$){li("Connect to the gateway first.");return}const k=Xi.trim();if(!k||be)return;if(Ht.voice_ptt_busy){ci("Wait for transcription to finish.");return}li(""),ci(""),ke(!0);const D={id:`local:${xr()}`,role:"user",content:k,ts:Ct()};ot(q=>[...q,D]),es("");try{const q=Z1(Qe,D),H=n.maintenance_ai_provider.trim(),V=n.maintenance_ai_model.trim(),ne=await Te.run_chat(y,{provider:H||void 0,model:V||void 0,include_subruns:!0,messages:q}),Le=String((ne==null?void 0:ne.answer)||"").trim()||"(empty response)",_e=String((ne==null?void 0:ne.generated_at)||"").trim()||Ct();Dt((ne==null?void 0:ne.history)??null),ot(he=>[...he,{id:`local:${xr()}`,role:"assistant",content:Le,ts:_e}])}catch(q){const H=KN(q);li(H),ot(V=>[...V,{id:`local:${xr()}`,role:"assistant",content:`(error: ${H})`,ts:Ct(),local_error:!0}])}finally{ke(!1)}}function nh(y){const k=String(y.id||y.ts||"").trim(),M=String(y.content||"").trim();!k||!M||(ci(""),Ht.toggle_tts(k,M))}function wd(y){const k=String(y.id||y.ts||"").trim(),M=Ht.tts_playback;return!k||!M.key||M.key!==k?"idle":M.status}function vd(y){if(!Qe.length)return;const k=c.trim(),M=k?`Run ${k}`:"Chat",D=kk(Qe.map(q=>({role:q.role,content:q.content,ts:q.ts})),{heading:M});if(y==="download"){const q=new Date().toISOString().slice(0,19).replace(/[:T]/g,"-"),H=`abstractobserver-chat-${By(k||"run")}-${q}.md`;Nk({filename:H,text:D,mime:"text/markdown;charset=utf-8"});return}(async()=>{const q=await sc(D);He(q?"copied":"failed"),window.setTimeout(()=>He("idle"),900)})()}async function Wc(){const y=typeof(ue==null?void 0:ue.workflow_id)=="string"?String(ue.workflow_id).trim():"";if(!y){Lo([]);return}if($&&!ll){mc(""),fc(!0);try{const k=await Te.list_runs({limit:200,workflow_id:y,root_only:!0}),M=Array.isArray(k==null?void 0:k.items)?k.items:[],D=[];for(const _e of M){const he=typeof(_e==null?void 0:_e.run_id)=="string"?String(_e.run_id).trim():"";if(!he)continue;const $e=typeof(_e==null?void 0:_e.ledger_len)=="number"?Number(_e.ledger_len):0;D.push({run_id:he,ledger_len:Number.isFinite($e)?$e:0})}if(!D.length){Lo([]);return}const q=400,H=D.map(_e=>({run_id:_e.run_id,after:Math.max(0,(_e.ledger_len||0)-q)})),V=await Te.get_ledger_batch({runs:H,limit:q}),ne=[],Le=new Set;for(const _e of D){const he=V!=null&&V.runs&&typeof V.runs=="object"?V.runs[_e.run_id]:null,$e=Array.isArray(he==null?void 0:he.items)?he.items:[];for(const Pe of $e){const ze=Pe==null?void 0:Pe.effect;if(!ze||typeof ze!="object"||String(ze.type||"")!=="emit_event")continue;const Ze=ze.payload;if(!Ze||typeof Ze!="object"||String(Ze.name||"")!=="abstract.chat.thread")continue;const Ve=Ze.payload;if(!Ve||typeof Ve!="object")continue;const sn=typeof Ve.thread_id=="string"?String(Ve.thread_id).trim():"";if(!sn||Le.has(sn))continue;Le.add(sn);const Rt=typeof Ve.created_at=="string"?String(Ve.created_at):"",Be=typeof Ve.title=="string"?String(Ve.title):"",bt=typeof Ve.workflow_id=="string"?String(Ve.workflow_id):y,xn=typeof Ve.run_id=="string"?String(Ve.run_id):_e.run_id,hn=typeof Ve.provider=="string"?String(Ve.provider):"",Mr=typeof Ve.model=="string"?String(Ve.model):"",dr=typeof Ve.message_count=="number"?Number(Ve.message_count):null,Ds=Ve.chat_artifact,Ka=Ds&&typeof Ds=="object"&&typeof Ds.$artifact=="string"?String(Ds.$artifact):"";Ka&&ne.push({thread_id:sn,created_at:Rt,title:Be||`Chat ${sn.slice(0,8)}`,run_id:xn,workflow_id:bt,message_count:dr,provider:hn,model:Mr,artifact_id:Ka})}}ne.sort((_e,he)=>String(he.created_at||"").localeCompare(String(_e.created_at||""))),Lo(ne)}catch(k){mc(String((k==null?void 0:k.message)||k||"Failed to load saved discussions"))}finally{fc(!1)}}}async function rh(){const y=c.trim();if(!y){vn("Select a run first.");return}if(!$){vn("Connect to the gateway first.");return}if(Qe.length&&!Xn){vn(""),Bt(!0);try{const k=n.maintenance_ai_provider.trim(),M=n.maintenance_ai_model.trim(),D=await Te.save_chat_thread(y,{provider:k||void 0,model:M||void 0,include_subruns:!0,messages:Qe.map(V=>({role:V.role,content:V.content,ts:V.ts}))}),q=typeof(D==null?void 0:D.created_at)=="string"?String(D.created_at):Ct();pr(q);try{const V=JSON.stringify(Qe.map(ne=>({role:ne.role,content:ne.content,ts:ne.ts})));ys(V)}catch{ys("1")}typeof(D==null?void 0:D.thread_id)=="string"&&String(D.thread_id).trim()&&_c(String(D.thread_id).trim());const H=!!(D!=null&&D.duplicate);Qn(H?"Already saved":"Saved discussion",2),await Wc()}catch(k){vn(String((k==null?void 0:k.message)||k||"Failed to save discussion"))}finally{Bt(!1)}}}async function Gm(){const y=String(Tu||"").trim();if(!y)return;const k=Ro.find(q=>String(q.thread_id||"").trim()===y)||null;if(!k){Io("Saved discussion not found (refresh list).");return}if(!$){Io("Connect to the gateway first.");return}if(pc)return;const M=Qe.length>0,D=(()=>{if(!M)return!1;if(!Nr)return!0;try{return JSON.stringify(Qe.map(H=>({role:H.role,content:H.content,ts:H.ts})))!==Nr}catch{return!0}})();if(!(M&&D&&!window.confirm("Replace the current chat with the selected saved discussion? Unsaved changes will be lost."))){Io(""),gc(!0);try{const H=await(await Te.download_run_artifact_content(k.run_id,k.artifact_id)).text(),V=JSON.parse(H),ne=Array.isArray(V==null?void 0:V.messages)?V.messages:[],Le=typeof(V==null?void 0:V.created_at)=="string"?String(V.created_at):String(k.created_at||""),_e=[];for(let he=0;he<ne.length;he++){const $e=ne[he];if(!$e||typeof $e!="object")continue;const Pe=String($e.role||"").trim()==="assistant"?"assistant":"user",ze=typeof $e.content=="string"?String($e.content):"";if(!ze.trim())continue;const Ze=typeof $e.ts=="string"?String($e.ts):Le||Ct();_e.push({id:`thread:${y}:${he}`,role:Pe,content:ze.trim(),ts:Ze})}ot(_e),Dt(null),es(""),li(""),vn(""),pr(Le||"");try{const he=JSON.stringify(_e.map($e=>({role:$e.role,content:$e.content,ts:$e.ts})));ys(he)}catch{ys("1")}Qn("Loaded discussion",2)}catch(q){Io(String((q==null?void 0:q.message)||q||"Failed to load saved discussion"))}finally{gc(!1)}}}async function Il(y){const k=c.trim(),M=String((Ft==null?void 0:Ft.wait_key)||"").trim();if(!k||!M){nn("No active wait to resume");return}if(String((Ft==null?void 0:Ft.reason)||"").trim()==="subworkflow"){nn("This run is waiting on a subworkflow; attach to the child run instead of resuming manually.");return}nn(""),Un(!0);try{await Te.submit_command({command_id:xr(),run_id:k,type:"resume",payload:{wait_key:M,payload:y||{}},client_id:"web_pwa"}),Jt({ts:Ct(),kind:"info",title:"Resume submitted",preview:St(`wait_key: ${M}`),data:{wait_key:M,payload:y||{}}}),Qr(M);try{const D=await Te.get_run(k);fs(D)}catch{}lr(Te,{force:!0}),window.setTimeout(()=>void lr(Te,{force:!0}),900),window.setTimeout(()=>void lr(Te,{force:!0}),2400),Zr.current&&window.clearTimeout(Zr.current),Zr.current=window.setTimeout(()=>{Qr(D=>D===M?"":D)},2e3)}catch(D){nn(String((D==null?void 0:D.message)||D||"resume failed"))}finally{Un(!1)}}async function Km(y){if(!Oa){nn("No worker configured");return}if(!ft){nn(""),Un(!0);try{const k=[];for(const M of y){const D=await Oa.call_tool(M);k.push(D)}await Il({mode:"executed",results:k})}finally{Un(!1)}}}const Ko=_.useMemo(()=>$f(Ft),[Ft]),Er=String((Ft==null?void 0:Ft.wait_key)||"").trim(),cr=String((Ft==null?void 0:Ft.reason)||"").trim(),Qs=typeof(Ft==null?void 0:Ft.until)=="string"?String(Ft.until):"",ei=typeof(ue==null?void 0:ue.status)=="string"?String(ue.status):"",_o=!!(ue!=null&&ue.paused),ti=ei==="completed"||ei==="failed"||ei==="cancelled",Ym=cr==="until"&&!!Qs,ss=!ti&&VC(Ur)&&(!!Er||Ym),xd=cr==="user",Ua=cr==="event"?rf(TL(Er)):"",sh=cr==="event"&&Ua==="abstract.ask",ih=Ko.length>0,bd=ss&&Er&&(xd||sh||ih)&&Au!==Er&&e!=="board",Pi=typeof((as=Ft==null?void 0:Ft.details)==null?void 0:as.sub_run_id)=="string"?String(Ft.details.sub_run_id):"",gi={run_id:c.trim(),workflow_id:typeof(ue==null?void 0:ue.workflow_id)=="string"?String(ue.workflow_id):null,status:ei,created_at:typeof(ue==null?void 0:ue.created_at)=="string"?String(ue.created_at):null,updated_at:typeof(ue==null?void 0:ue.updated_at)=="string"?String(ue.updated_at):null,session_id:typeof(ue==null?void 0:ue.session_id)=="string"?String(ue.session_id):null,current_node:typeof(ue==null?void 0:ue.current_node)=="string"?String(ue.current_node):null},qc=an.slice(-10).map(y=>{var k,M,D,q,H,V;return{cursor:y.cursor,node_id:String(((k=y.record)==null?void 0:k.node_id)||"").trim(),status:String(((M=y.record)==null?void 0:M.status)||"").trim(),effect_type:String(((q=(D=y.record)==null?void 0:D.effect)==null?void 0:q.type)||"").trim(),ts:String(((H=y.record)==null?void 0:H.ended_at)||((V=y.record)==null?void 0:V.started_at)||"").trim(),summary:Vx(y.record)}}),Hc=xg(Ft,Ko),Jm=Ux(Ft,Ko),jd=Wx(Ft,ut),Yo=jd.text,oh=jd.runtime_metadata,Pl=String((Ft==null?void 0:Ft.prompt)||"").trim(),Sd=TC(ut,6),Xm=!!(Pl&&Fx(Pl)),$r=!!(Pl&&!Xm),Wr=$r?"Question from workflow":Yo&&Yo!==Pl?"Closest prior user request":"Request context",ah=LC(ut,T),lh=!!T.trim(),is=ue!=null&&ue.schedule&&typeof ue.schedule=="object"?ue.schedule:null,Jo=typeof(is==null?void 0:is.interval)=="string"?String(is.interval).trim():"",ch=typeof(is==null?void 0:is.share_context)=="boolean"?!!is.share_context:null,Vc=typeof(is==null?void 0:is.repeat_count)=="number"?Number(is.repeat_count):null,os=!!(ue!=null&&ue.is_scheduled)||!!is,Ol=os&&!!Jo,kd=ei==="running"&&!_o?"Pause":"Resume",Nd=os?_o?"resume":"pause":kd==="Pause"?"pause":"resume",Cd=os?!c.trim()||dt||ft||ti:!c.trim()||dt||ft||ti||Nd==="resume"&&!_o,Ed=c.trim()?ti?"The schedule has ended.":null:"No run selected.",uh=os&&!_o&&!ti&&!dt&&!ft&&ei.toLowerCase()==="waiting"&&(String(((Qo=ue==null?void 0:ue.waiting)==null?void 0:Qo.reason)||"").trim().toLowerCase()==="until"||cr==="until")&&!!String(Qs||"").trim(),qr=(Yn=ue==null?void 0:ue.limits)==null?void 0:Yn.tokens,po=typeof(qr==null?void 0:qr.pct)=="number"?Number(qr.pct):null,dh=qr==null?void 0:qr.estimated_used,$d=(qr==null?void 0:qr.max_input_tokens)??(qr==null?void 0:qr.max_tokens),Dl=_.useMemo(()=>{const y=Or.current;an.length<y.scanned&&(y.scanned=0,y.found=null);for(let k=y.scanned;k<an.length;k++){const M=an[k],D=M==null?void 0:M.record;if(!D)continue;const q=Rh(D);if((q&&q.name?rf(q.name):"")!=="abstract.summary")continue;const V=q!=null&&q.payload&&typeof q.payload=="object"?q.payload:{},ne=typeof(V==null?void 0:V.text)=="string"?String(V.text):"";ne.trim()&&(y.found={cursor:M.cursor,ts:String((D==null?void 0:D.ended_at)||(D==null?void 0:D.started_at)||""),text:ne,provider:typeof(V==null?void 0:V.provider)=="string"?String(V.provider):void 0,model:typeof(V==null?void 0:V.model)=="string"?String(V.model):void 0,generated_at:typeof(V==null?void 0:V.generated_at)=="string"?String(V.generated_at):void 0,source:V==null?void 0:V.source})}return y.scanned=an.length,y.found},[an]);_.useEffect(()=>{hi.current=Ms.trim()},[Ms]),_.useEffect(()=>{const y=c.trim(),k=Pi.trim();if(!(De&&cr==="subworkflow"&&!!k&&k!==y)){Sa.current="",Ms.trim()&&oo("");return}Sa.current!==k&&(Sa.current=k,hi.current=k,oo(k))},[De,c,cr,Pi,Ms]),_.useEffect(()=>{ul({})},[C]);const Ad=_.useMemo(()=>((Array.isArray(U==null?void 0:U.entrypoints)?U==null?void 0:U.entrypoints:[])||[]).map(k=>String((k==null?void 0:k.flow_id)||"").trim()).filter(Boolean),[U]),Os=_.useMemo(()=>{const y=String((ue==null?void 0:ue.workflow_id)||"").trim();return De&&os?y:""},[De,os,ue==null?void 0:ue.workflow_id]),Oi=_.useMemo(()=>{var V;if(!De||!c.trim()||!Os.trim())return ui;const y=String((ue==null?void 0:ue.status)||"").trim().toLowerCase(),k=String((ue==null?void 0:ue.current_node)||"").trim();if(y!=="waiting"&&y!=="running"||!k)return ui;const M=Fn(c.trim(),k);if(!M)return ui;const D=String(cr||((V=ue==null?void 0:ue.waiting)==null?void 0:V.reason)||"").trim().toLowerCase(),q=typeof(Ur==null?void 0:Ur.node_id)=="string"?String(Ur.node_id).trim():"",H=typeof(Ur==null?void 0:Ur.status)=="string"?String(Ur.status).trim().toLowerCase():"";return y==="waiting"&&D==="until"||!ui.trim()||(H==="waiting"||H==="running")&&!q?M:ui},[De,c,Os,ue==null?void 0:ue.status,ue==null?void 0:ue.current_node,(Va=ue==null?void 0:ue.waiting)==null?void 0:Va.reason,cr,ui,Ur]),Zm=_.useMemo(()=>{const y={},k=c.trim(),M=(D,q)=>{if(!q)return;const H=typeof(q==null?void 0:q.node_id)=="string"?String(q.node_id).trim():"";if(!H)return;const V=Fn(D,H);if(!V)return;const ne=String((q==null?void 0:q.ended_at)||(q==null?void 0:q.started_at)||"").trim(),Le=qn(ne);Le!==null&&(y[V]=Math.max(y[V]||0,Le))};for(const D of an)D&&D.record&&M(k,D.record);for(const D of rr)D&&D.record&&M(String(D.run_id||"").trim(),D.record);return y},[an,rr,c,ws]);_.useEffect(()=>{var M;if(!De||!c.trim()||!Os.trim())return;const y=String((ue==null?void 0:ue.current_node)||"").trim();!y||String(((M=ue==null?void 0:ue.waiting)==null?void 0:M.reason)||"").trim()==="subworkflow"||mo(Fn(c.trim(),y))},[De,c,Os,ue==null?void 0:ue.current_node,(wo=ue==null?void 0:ue.waiting)==null?void 0:wo.reason]),_.useEffect(()=>{const y=String((Zn==null?void 0:Zn.flow_id)||"").trim();y&&(ya.trim()||Qi(y))},[Zn,ya]),_.useEffect(()=>{const y=Os.trim(),k=C.trim(),M=ya.trim();if(y){let q=!1;return ba(!0),dl(""),Te.get_workflow_flow(y).then(H=>{if(q)return;const V=H==null?void 0:H.flow;va(V&&typeof V=="object"?V:null)}).catch(H=>{q||(va(null),dl(String((H==null?void 0:H.message)||H||"Failed to load workflow flow")))}).finally(()=>{q||ba(!1)}),()=>{q=!0}}if(!k||!M){va(null),dl(""),ba(!1);return}let D=!1;return ba(!0),dl(""),Te.get_bundle_flow(k,M).then(q=>{if(D)return;const H=q==null?void 0:q.flow,V=H&&typeof H=="object"?H:null;va(V),V&&ul(ne=>({...ne,[M]:V}))}).catch(q=>{D||(va(null),dl(String((q==null?void 0:q.message)||q||"Failed to load flow")))}).finally(()=>{D||ba(!1)}),()=>{D=!0}},[Os,C,ya,Te]),_.useEffect(()=>{const y=C.trim();if(!fl||!y||!wa)return;let k=!1;const M=3,D=_e=>{const he=Array.isArray(_e==null?void 0:_e.nodes)?_e.nodes:[],$e=[];for(const Pe of he){const ze=Pe!=null&&Pe.data&&typeof Pe.data=="object"?Pe.data:{};if(String((ze==null?void 0:ze.nodeType)||(Pe==null?void 0:Pe.type)||"").trim()!=="subflow")continue;const Ve=(ze==null?void 0:ze.subflowId)||(ze==null?void 0:ze.flowId),sn=typeof Ve=="string"?Ve.trim():"";sn&&$e.push(sn.includes(":")?sn.split(":",2)[1]:sn)}return $e},q=new Set,H=new Set,V=(_e,he)=>{if(!(!_e||he>=M))for(const $e of D(_e)){const Pe=String($e||"").trim();if(!Pe||q.has(Pe))continue;q.add(Pe),H.add(Pe);const ze=xa[Pe];ze&&V(ze,he+1)}};V(wa,0);const ne=Array.from(H).filter(_e=>!xa[_e]).slice(0,20);return ne.length?((async()=>{for(const _e of ne){if(k)return;try{const he=await Te.get_bundle_flow(y,_e),$e=he==null?void 0:he.flow,Pe=$e&&typeof $e=="object"?$e:null;if(!Pe)continue;ul(ze=>ze[_e]?ze:{...ze,[_e]:Pe})}catch{}}})(),()=>{k=!0}):void 0},[fl,C,wa,xa,Te]);const Td=_.useMemo(()=>{const k=(Array.isArray(U==null?void 0:U.flows)?U==null?void 0:U.flows:[]).map(M=>String(M||"").trim()).filter(Boolean);return k.length?Array.from(new Set(k)).sort():Array.from(new Set(Ad)).sort()},[U,Ad]);_.useEffect(()=>{ti&&ui.trim()&&(Oo(""),di.current="")},[ti,c,ui]),_.useEffect(()=>{const y=Ms.trim(),k=c.trim();if(!(De&&!!y&&y!==k)){zr.current&&zr.current.abort(),zr.current=null,so.current=0,fi&&ka("");return}if(fi===y)return;zr.current&&zr.current.abort();const D=new AbortController;zr.current=D,so.current=0,ka(y),Jt({ts:Ct(),kind:"info",title:`Following run ${y} (status/events)`});let q=250;return(async()=>{for(;!D.signal.aborted;){try{await Te.stream_ledger(y,{after:so.current,on_step:V=>hd(y,V),signal:D.signal});return}catch(V){if(D.signal.aborted)break;const ne=String((V==null?void 0:V.message)||V||"stream error");Jt({ts:Ct(),kind:"error",title:"Child ledger stream error (will retry)",preview:St(ne),data:{child_run_id:y,error:ne}})}if(D.signal.aborted)break;await new Promise(V=>setTimeout(V,q)),q=Math.min(5e3,Math.floor(q*1.6))}})(),()=>{D.abort()}},[De,Ms,c,Te,fi]),_.useEffect(()=>{if(!De||!c.trim())return;let y=!1;const k=async()=>{if(!y&&!_l.current&&ws.length&&!(ct.current>Date.now())){_l.current=!0;try{const D=ws.map(ne=>String(ne||"").trim()).filter(Boolean);if(!D.length)return;const q=D.map(ne=>({run_id:ne,after:Number(Do.current[ne]||0)})),H=await Te.get_ledger_batch({runs:q,limit:200}),V=H&&typeof H=="object"?H.runs:{};for(const ne of D){if(y)return;const Le=V&&typeof V=="object"?V[ne]:null,_e=Array.isArray(Le==null?void 0:Le.items)?Le.items:[],he=typeof(Le==null?void 0:Le.next_after)=="number"?Le.next_after:Number(Do.current[ne]||0),$e=Number(Do.current[ne]||0);for(let Pe=0;Pe<_e.length;Pe++){const ze=_e[Pe];Yf(ne,{cursor:$e+Pe+1,record:ze})}Do.current[ne]=he}}catch(D){if(y)return;Jt({ts:Ct(),kind:"error",title:"Subrun digest poll failed",preview:St(String((D==null?void 0:D.message)||D||""))})}finally{_l.current=!1}}};k();const M=window.setInterval(()=>void k(),2e3);return()=>{y=!0,window.clearInterval(M),_l.current=!1}},[De,c,ws,Te]);const go=_.useMemo(()=>{const y=c.trim(),k=[];for(const M of an)!M||!M.record||k.push({run_id:y,cursor:M.cursor,record:M.record});for(const M of rr)!M||!M.record||k.push({run_id:String(M.run_id||"").trim(),cursor:M.cursor,record:M.record});return k},[an,rr,c]),Gc=_.useMemo(()=>{var k,M,D,q;const y={};for(const H of go){const V=String(H.run_id||((k=H.record)==null?void 0:k.run_id)||"").trim();!V||String(((D=(M=H.record)==null?void 0:M.effect)==null?void 0:D.type)||"").trim()!=="llm_call"||String(((q=H.record)==null?void 0:q.status)||"")!=="started"&&(y[V]=(y[V]||0)+1)}return y},[go]),fh=_.useMemo(()=>{const y=Ms.trim();if(y)return y;let k="",M=-1;for(const[D,q]of Object.entries(Gc))q>M&&(k=D,M=q);return k||c.trim()},[Gc,Ms,c]),Fl=(Df.trim()||fh).trim(),Ar=_.useMemo(()=>{var q;const y=new Set,k=c.trim(),M=Ms.trim();k&&y.add(k),M&&y.add(M);for(const H of ws){const V=String(H||"").trim();V&&y.add(V)}for(const H of go){const V=String(H.run_id||((q=H.record)==null?void 0:q.run_id)||"").trim();V&&y.add(V)}const D=Array.from(y);return D.sort((H,V)=>k&&H===k&&V!==k?-1:k&&V===k&&H!==k?1:M&&H===M&&V!==M?-1:M&&V===M&&H!==M?1:H<V?-1:H>V?1:0),D},[c,Ms,ws,go]),Qm=_.useMemo(()=>{var y;for(let k=an.length-1;k>=0;k--){const M=Gx((y=an[k])==null?void 0:y.record);if(M)return M}return""},[an]);function e_(y){Of(y);const k=c.trim();if(!(!k||typeof window>"u"))try{window.history.replaceState(null,"",DN(gN(k),y))}catch{}}const Rn=_.useMemo(()=>{const y=c.trim();return y&&(gn.find(k=>String(k.run_id||"").trim()===y)||Bn.find(k=>String(k.run_id||"").trim()===y))||null},[gn,Bn,c]),Vn=String((ue==null?void 0:ue.status)||(Rn==null?void 0:Rn.status)||"").trim(),t_=String(cr||((Bl=ue==null?void 0:ue.waiting)==null?void 0:Bl.reason)||(Rn==null?void 0:Rn.waiting_reason)||"").trim().toLowerCase(),Xe=!!(ue!=null&&ue.is_scheduled||Rn!=null&&Rn.is_scheduled),Xo=!!(ue!=null&&ue.paused||Rn!=null&&Rn.paused),Kc=Xe&&Vn.toLowerCase()==="waiting",Md=Kc&&t_==="until",hh=qn(Qs),Zo=Md&&hh!==null?Uy(hh-Date.now()):"",yo=YN(ue),Wa=Xe&&Xo?"Suspended":Kc?"Scheduled":lm({status:Vn,paused:Xo,stop_reason:yo});async function Rd(){if($){Bf(!0),Ju("");try{const y=zo,k=y==="session"?String(Ea||yn||K||"").trim():"",M=y==="run"?String(yr||c||"").trim():"",D=BC(Cc),q=$a.length?$a.join(","):"",H=UC(vl),V=Math.max(0,Gs)*Gh,ne=await Te.search_artifacts({scope:y,session_id:k||void 0,run_id:M||void 0,query:ao||void 0,artifact_kind:q||void 0,created_after:D||void 0,include_stats:!0,limit:Gh,offset:V,order_by:H.order_by,order:H.order}),Le=[],_e=new Set;for(const Ze of Array.isArray(ne==null?void 0:ne.items)?ne.items:[]){const Ve=DC(Ze,"search");!Ve||_e.has(Ve.artifact_id)||(_e.add(Ve.artifact_id),Le.push(Ve))}const he=ne!=null&&ne.stats&&typeof ne.stats=="object"?ne.stats:{},$e=Number((he==null?void 0:he.total)??(ne==null?void 0:ne.total)??Le.length),Pe=tw(ne);let ze=Pe;if($a.length)try{const Ze=await Te.search_artifacts({scope:y,session_id:k||void 0,run_id:M||void 0,query:ao||void 0,created_after:D||void 0,include_stats:!0,limit:1,offset:0,order_by:H.order_by,order:H.order});ze=tw(Ze)}catch{ze=Pe}gl(Number.isFinite($e)?Math.max(0,$e):Le.length),Ku(Number((he==null?void 0:he.total_bytes)??(he==null?void 0:he.byte_total)??0)||0),Ca(Pe),Fo(ze),Nn(Le),Xu(Ze=>{var Ve;return Ze&&Le.some(sn=>sn.artifact_id===Ze)?Ze:((Ve=Le[0])==null?void 0:Ve.artifact_id)||""})}catch(y){Ju(String((y==null?void 0:y.message)||y||"Failed to load artifacts")),Nn([]),gl(0),Ku(0),Ca({}),Fo({}),Xu("")}finally{Bf(!1)}}}async function Ld(){if($){Ti(!0),Wo("");try{const y=await Te.audit_log_tail({max_bytes:16e4}),k=typeof(y==null?void 0:y.bytes)=="number"?Number(y.bytes):0,M=!!(y!=null&&y.truncated);Sl(String((y==null?void 0:y.content)||"")),ed(`${k.toLocaleString()} bytes${M?" (tail)":""}`)}catch(y){Wo(String((y==null?void 0:y.message)||y||"Failed to load audit log")),Sl(""),ed("")}finally{Ti(!1)}}}async function Id(y){if(!$)return;const k=String(y||vs||yr||c||"").trim();if(!k){Ys([]),Ri(""),Br("Select a run in Activity or Artifacts to load its runtime ledger.");return}$c(!0),Br("");try{const M=await Te.get_ledger(k,{after:0,limit:2e3}),D=Array.isArray(M.items)?M.items:[];Ys(D.map((H,V)=>({cursor:V+1,record:H})));const q=typeof M.next_after=="number"?Number(M.next_after):D.length;Ri(`${D.length.toLocaleString()} record${D.length===1?"":"s"}${q>=2e3?" (first 2,000)":""}`)}catch(M){Br(String((M==null?void 0:M.message)||M||"Failed to load run ledger")),Ys([]),Ri("")}finally{$c(!1)}}_.useEffect(()=>{$&&e==="runtime"&&Rd()},[$,e,zo,Ea,yr,ao,$a,Cc,vl,Gs]),_.useEffect(()=>{$&&(Hf||mi||e==="runtime"&&Ld())},[$,e,ts]),_.useEffect(()=>{if(!$||e!=="runtime"||pl!=="logs"||qo!=="run_ledger"&&qo!=="provider_calls")return;const y=String(vs||yr||c||"").trim();y&&Id(y)},[$,e,pl,qo,vs,yr,c]);const yi=_.useMemo(()=>{const y=new Map;for(const k of[...Bn,...gn]){const M=String(k.run_id||"").trim();M&&y.set(M,k)}for(const k of ws){const M=String(k||"").trim();!M||y.has(M)||y.set(M,{run_id:M,workflow_id:null,status:"",created_at:null,updated_at:null,ledger_len:null,parent_run_id:no.current[M]||null,session_id:yn||null})}return c.trim()&&!y.has(c.trim())&&y.set(c.trim(),{run_id:c.trim(),workflow_id:typeof(ue==null?void 0:ue.workflow_id)=="string"?String(ue.workflow_id):null,status:typeof(ue==null?void 0:ue.status)=="string"?String(ue.status):"",created_at:typeof(ue==null?void 0:ue.created_at)=="string"?String(ue.created_at):null,updated_at:typeof(ue==null?void 0:ue.updated_at)=="string"?String(ue.updated_at):null,ledger_len:an.length||null,parent_run_id:typeof(ue==null?void 0:ue.parent_run_id)=="string"?String(ue.parent_run_id):null,session_id:typeof(ue==null?void 0:ue.session_id)=="string"?String(ue.session_id):yn||null}),Array.from(y.values()).sort((k,M)=>{const D=qn(k.updated_at||k.created_at)??0;return(qn(M.updated_at||M.created_at)??0)-D})},[gn,Bn,c,ue,an.length,ws,yn]),Pd=_.useMemo(()=>jE(yi,{query:yc,filter:Du,group_by:Fu,workflow_label_by_id:ar,parent_hint:y=>no.current[y]||""}),[yi,yc,Du,Fu,ar]),zn=_.useMemo(()=>{const y={};for(const k of yi){const M=String(k.run_id||"").trim();M&&(y[M]=k)}return y},[yi]),js=String(vs||yr||c||"").trim(),wi=js&&zn[js]||null,Od=String(Ea||(wi==null?void 0:wi.session_id)||yn||K||"").trim(),Dd=_.useMemo(()=>bc.map(y=>fm(y,zn,ar)),[bc,zn,ar]);_.useEffect(()=>{Uo(0)},[ao,$a,Cc,yr,vl,lo,zo,Ea]);const ni=Math.max(1,Math.ceil(jc/Gh)),qa=Math.min(Math.max(0,Gs),ni-1);_.useEffect(()=>{Gs!==qa&&Uo(qa)},[Gs,qa]);const Tr=_.useMemo(()=>Dd,[Dd,qa]),n_=_.useMemo(()=>{const y={};for(const k of Tr){const M=lo==="type"?Tp(k,zn,ar):FC(k,lo);y[M]||(y[M]=[]),y[M].push(k)}return Object.entries(y).map(([k,M])=>({key:k,items:M})).sort((k,M)=>{var D,q;if(lo==="time"){const H=qn((D=k.items[0])==null?void 0:D.created_at)??0,V=qn((q=M.items[0])==null?void 0:q.created_at)??0;if(H!==V)return V-H}return k.key.localeCompare(M.key)})},[Tr,lo,zn,ar]),Ha=_.useMemo(()=>{const y=Wf.trim();return y?Tr.find(k=>k.artifact_id===y)||Tr[0]||null:Tr[0]||null},[Tr,Wf]);_.useEffect(()=>{e!=="runtime"||pl!=="artifacts"||fd(Ha)},[e,pl,Ha==null?void 0:Ha.artifact_id]),_.useEffect(()=>()=>{Ks.url&&URL.revokeObjectURL(Ks.url)},[Ks.url]);const mh=_.useMemo(()=>yi.filter(y=>ju(y.status)),[yi]);_.useEffect(()=>{if(e!=="settings"&&e!=="launch"||!$||X)return;let y=!1;return(async()=>{const[k,M]=await Promise.all([Te.list_skills(),Te.list_mcp_servers()]);y||(Z(k),ge(M),Q(!0))})(),()=>{y=!0}},[e,$,X]);function zl(){cl&&window.setTimeout(()=>{var y;return(y=Pf.current)==null?void 0:y.scrollIntoView({block:"start"})},60)}function Yc(y){Zi(y),zl()}const r_=[{id:"board",label:"Board",icon:r.jsx(et,{name:"board",size:16})},{id:"observe",label:"Observe",icon:r.jsx(et,{name:"history",size:16})},{id:"runtime",label:"System",icon:r.jsx(et,{name:"server",size:16})},{id:"launch",label:"Launch",icon:r.jsx(et,{name:"send",size:16})},{id:"automations",label:"Automations",icon:r.jsx(et,{name:"refresh",size:16})}],Jc={board:"Board",observe:"Observe",runtime:"System",launch:"Launch",automations:"Automations",settings:"Settings"},Xc=r.jsxs(r.Fragment,{children:[Js?r.jsxs("details",{className:"launch_capabilities",style:{marginTop:"10px"},children:[r.jsxs("summary",{className:"help_text muted",style:{cursor:"pointer"},children:["Capabilities",or.length?` · ${or.length} skill${or.length===1?"":"s"}`:""]}),r.jsx("div",{className:"help_text muted",style:{marginTop:"8px"},children:"Skills attach knowledge procedures to this run. The gateway resolves selections through the trust gate at start: validated skills activate, unverified ones are held for review, blocked ones never ride."}),R===null?r.jsx("div",{className:"help_text muted",style:{marginTop:"8px"},children:"This gateway does not serve a skills inventory yet — the shelf lights up here when it ships."}):R.length?r.jsx("div",{className:"launch_skill_list",children:R.map(y=>{var q;const k=or.includes(y.name),M=y.blocked===!0,D=y.requires_review===!0&&!M;return r.jsxs("label",{className:`launch_skill_row ${M?"is_blocked":""} ${k?"is_on":""}`,title:[y.description||"",y.tree_hash?`tree ${y.tree_hash.slice(0,16)}…`:"",M&&((q=y.reasons)!=null&&q.length)?`blocked: ${y.reasons.join("; ")}`:""].filter(Boolean).join(`
144
- `),children:[r.jsx("input",{type:"checkbox",checked:k,disabled:M||dt||ft||Se,onChange:H=>{const V=H.target.checked?Array.from(new Set([...or,y.name])):or.filter(ne=>ne!==y.name);Tn("skills",V.length?V:void 0)}}),r.jsx("span",{className:"launch_skill_name",children:y.name}),y.trust_level?r.jsx("span",{className:`chip ${M?"danger":D?"warn":"muted"}`,children:M?"blocked":D?"review":y.trust_level}):null,y.description?r.jsx("span",{className:"launch_skill_desc",children:y.description}):null]},y.name)})}):r.jsx("div",{className:"help_text muted",style:{marginTop:"8px"},children:"The gateway's skills shelf is empty."}),or.length?r.jsx("div",{className:"help_text muted",style:{fontSize:"var(--font-size-xxs)",marginTop:"6px"},children:"Selected skills ride the run as input_data.skills; the resolved verdicts land in the run's record."}):null]}):null,r.jsxs("details",{style:{marginTop:"10px"},children:[r.jsx("summary",{className:"help_text muted",style:{cursor:"pointer"},children:"Workspace"}),r.jsx("div",{className:"help_text muted",style:{marginTop:"8px"},children:"Controls what the agent can access via filesystem tools."}),r.jsxs("div",{className:"launch_grid",style:{marginTop:"8px"},children:[r.jsxs("div",{className:"launch_grid_cell",style:{gridColumn:"1 / -1"},children:[r.jsx("label",{className:"launch_label",children:"Workspace Root"}),r.jsx("input",{className:"mono",value:ld,onChange:y=>Tn("workspace_root",y.target.value),placeholder:"/path/to/workspace",disabled:dt||ft}),r.jsx("div",{className:"help_text muted",style:{fontSize:"var(--font-size-xxs)"},children:"Empty = gateway default (isolated per-run workspace)"})]}),r.jsxs("div",{className:"launch_grid_cell",children:[r.jsx("label",{className:"launch_label",children:"Access Mode"}),r.jsxs("select",{className:"mono",value:(Rc||"workspace_only").trim()||"workspace_only",onChange:y=>Tn("workspace_access_mode",y.target.value),disabled:dt||ft,children:[r.jsx("option",{value:"workspace_only",children:"workspace_only"}),r.jsx("option",{value:"workspace_or_allowed",children:"workspace_or_allowed"}),r.jsx("option",{value:"all_except_ignored",children:"all_except_ignored"})]}),r.jsx("div",{className:"help_text muted",style:{fontSize:"var(--font-size-xxs)"},children:"workspace_only: absolute paths must stay under root. workspace_or_allowed: allow additional roots."})]})]}),(Rc||"").trim()==="workspace_or_allowed"?r.jsxs("div",{className:"field",style:{marginTop:"8px"},children:[r.jsx("label",{className:"launch_label",children:"Allowed Paths"}),r.jsx("textarea",{className:"mono",rows:3,value:cd,onChange:y=>Tn("workspace_allowed_paths",y.target.value),placeholder:`/path/to/project
145
- /path/to/workspace`,disabled:dt||ft,spellCheck:!1,autoCorrect:"off",autoCapitalize:"off",autoComplete:"off"}),r.jsx("div",{className:"help_text muted",style:{fontSize:"var(--font-size-xxs)"},children:"Newline-separated directories (absolute or relative to workspace_root)"})]}):null,r.jsxs("div",{className:"field",style:{marginTop:"8px"},children:[r.jsx("label",{className:"launch_label",children:"Ignored Paths"}),r.jsx("textarea",{className:"mono",rows:3,value:Da,onChange:y=>Tn("workspace_ignored_paths",y.target.value),placeholder:`node_modules
146
- runtime
147
- secret`,disabled:dt||ft,spellCheck:!1,autoCorrect:"off",autoCapitalize:"off",autoComplete:"off"}),r.jsx("div",{className:"help_text muted",style:{fontSize:"var(--font-size-xxs)"},children:"Newline-separated paths to block (absolute or relative to workspace_root)"})]})]}),r.jsxs("details",{className:"launch_bundles",style:{marginTop:"10px"},children:[r.jsx("summary",{className:"help_text muted",style:{cursor:"pointer"},children:"Workflow bundles"}),r.jsxs("div",{className:"launch_workflow_bar",style:{marginTop:"8px"},children:[r.jsx("input",{ref:it,type:"file",accept:".flow",style:{display:"none"},onChange:y=>{const k=y.target.files&&y.target.files.length?y.target.files[0]:null;k&&Oc(k)}}),r.jsx("button",{type:"button",className:"btn launch_btn_upload",onClick:()=>{var y;return(y=it.current)==null?void 0:y.click()},disabled:!$||W||Cs||dt||ft,title:"Upload a .flow bundle",children:Cs?"…":"Upload .flow"}),r.jsxs("button",{type:"button",className:"btn launch_btn_reload",onClick:()=>void Dn(),disabled:!$||W||jt||dt||ft,title:"Reload picks up server-side edits",children:[r.jsx(et,{name:"refresh",size:14}),jt?"…":"Reload bundles"]})]})]})]});function Ss(y){t("observe"),Zi("ledger"),Zs(y)}const rn={on_select:y=>void Tt.select(y),on_row_action:(y,k)=>{if(k==="discuss"||k==="edit")throw new Error(`${k} is routed by AutomationsPage (route_row_action), not the app handlers.`);if(k==="archive"){Tt.ask_archive(y.automation_id);return}Tt.row_action(y,k)},on_legacy_action:(y,k)=>{if(k==="open_run"){Ss(y.automation_id);return}if(k==="recreate"){pd(y.automation_id).catch(M=>Tt.report_error(M));return}Tt.legacy_action(y,k)},on_confirm_archive:y=>void Tt.row_action(y,"archive"),on_cancel_archive:()=>Tt.ask_archive(""),on_status_filter:y=>void Tt.set_status_filter(y),on_refresh:()=>void Tt.refresh(),on_new:()=>{ye("automate"),t("launch")},on_show_archived:y=>Tt.set_show_archived(y)};return r.jsxs("div",{className:`app-shell shell${vc?" nav_open":""}`,children:[wc&&vc?r.jsx("div",{className:"shell_nav_backdrop","aria-hidden":"true",onClick:()=>_a(!1)}):null,r.jsxs("aside",{className:"shell_sidebar",id:"shell_nav",ref:pa,...ma.attrs.aside,children:[r.jsxs("div",{className:"shell_brand",title:"AbstractObserver (Web/PWA)",children:[r.jsx("span",{className:"logo-icon shell_brand_mark","aria-hidden":"true",children:r.jsxs("svg",{viewBox:"0 0 24 24",width:"20",height:"20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[r.jsx("ellipse",{cx:"12",cy:"12",rx:"9",ry:"4.2",transform:"rotate(-18 12 12)",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",opacity:"0.75"}),r.jsx("circle",{cx:"12",cy:"12",r:"4.7",fill:"currentColor",opacity:"0.95"}),r.jsx("circle",{cx:"10.3",cy:"10.7",r:"1.6",fill:"#ffffff",opacity:"0.18"}),r.jsx("circle",{cx:"19",cy:"13.6",r:"1.2",fill:"currentColor"})]})}),r.jsx("span",{className:"shell_brand_name",children:"Observer"}),r.jsx("button",{type:"button",className:"shell_nav_close","aria-label":"Close navigation",title:"Close navigation",onClick:()=>_a(!1),children:r.jsx(et,{name:"x",size:16})})]}),r.jsxs("nav",{className:"shell_nav",children:[r_.map(y=>r.jsxs("button",{className:`shell_nav_item ${e===y.id?"active":""}`,onClick:()=>{t(y.id),_a(!1)},type:"button",children:[r.jsx("span",{className:"shell_nav_icon",children:y.icon}),r.jsx("span",{className:"shell_nav_label",children:y.label})]},y.id)),r.jsxs("a",{className:"shell_nav_item",href:l,target:"_blank",rel:"noreferrer",title:"Open the entity app (memory graph + visits)",children:[r.jsx("span",{className:"shell_nav_icon",children:r.jsx(et,{name:"bot",size:16})}),r.jsx("span",{className:"shell_nav_label",children:"Entities ↗"})]}),r.jsxs("button",{className:`shell_nav_item ${e==="settings"?"active":""}`,onClick:()=>{t("settings"),_a(!1)},type:"button",children:[r.jsx("span",{className:"shell_nav_icon",children:r.jsx(et,{name:"settings",size:16})}),r.jsx("span",{className:"shell_nav_label",children:"Settings"})]})]}),r.jsx("div",{className:"shell_sidebar_footer",children:r.jsxs("div",{className:"shell_connection shell_connection_passive",title:$?"Gateway connected":W?"Gateway: connecting…":"Gateway: signed out",children:[r.jsx("span",{className:`gateway_led ${$?"ok":W?"warn":"err"}`,"aria-hidden":"true"}),r.jsx("span",{className:`shell_connection_label ${$&&((Ga=(Zc=F==null?void 0:F.gateway)==null?void 0:Zc.principal)!=null&&Ga.user_id)?"mono":""}`,children:$?((Qc=(Hr=F==null?void 0:F.gateway)==null?void 0:Hr.principal)==null?void 0:Qc.user_id)||(n.gateway_auth_mode==="direct"?"direct dev":"connected"):W?"connecting…":"signed out"})]})})]}),r.jsxs("div",{className:"shell_main",...ma.attrs.main,children:[r.jsxs("header",{className:"shell_header",children:[r.jsx("button",{ref:If,type:"button",className:"shell_nav_toggle","data-nav-toggle":!0,"aria-label":"Open navigation","aria-controls":"shell_nav","aria-expanded":vc,title:"Navigation",onClick:()=>_a(!0),children:r.jsx(et,{name:"list",size:18})}),r.jsx("div",{className:"shell_header_title",children:Jc[e]||"Observer"}),r.jsxs("div",{className:"shell_header_actions",children:[o?r.jsx("monitor-gpu",{ref:u,mode:"icon","history-size":"5","tick-ms":"1500","base-url":n.gateway_auth_mode==="session"?"":n.gateway_url,title:"GPU usage (host)",style:{"--monitor-gpu-width":"34px","--monitor-gpu-bars-height":"22px","--monitor-gpu-padding":"2px 4px","--monitor-gpu-radius":"999px","--monitor-gpu-bg":"rgba(0,0,0,0.22)","--monitor-gpu-border":"rgba(255,255,255,0.16)",flexShrink:0}}):null,r.jsx(Gj,{assistant:{open:kn,onToggle:()=>nr(y=>!y),label:"Observer assistant (docs-grounded)"},appearance:{onOpen:()=>It(!0)},about:{identity:sd,extraRows:Gf,onOpen:Pa},connection:{phase:O.phase,signingOut:O.signingOut,onConnect:()=>O.openModal(),onDisconnect:()=>$l()}})]})]}),r.jsx(Sj,{...O.modalProps}),r.jsx(Xj,{open:Wt,onClose:()=>It(!1),value:en,onChange:bn}),r.jsx(lN,{open:kn,onClose:()=>nr(!1),connected:$,topOffset:44,gateway:Te}),r.jsxs("div",{className:"app-body shell_content",children:[e==="board"?$?r.jsx(kL,{gateway_connected:$,runs:Bn,all_runs:gn,runs_refreshed_at:Kn,entities:Ns,entities_total:ae,entities_error:Ye,refreshing:wn,on_refresh:()=>void lr(Te,{force:!0}),on_open_run:y=>{t("observe"),Zi("ledger"),Zs(y)},on_resume_wait:Go,on_open_automation:y=>{t("automations"),Tt.refresh().then(()=>Tt.select(y))},entity_app_href:l,on_read_diary:(y,k)=>Te.read_entity_diary_entry(y,k),phase_graph:Fc}):r.jsx("div",{className:"page page_scroll",children:r.jsx("div",{className:"page_inner constrained",children:r.jsxs("div",{className:"card mc_hero",children:[r.jsx("div",{className:"title",children:r.jsx("h1",{children:"Connect to your gateway"})}),r.jsxs("p",{className:"muted",children:["Mission Control shows every run and entity on one board — but nothing is connected yet.",A?` Last attempt: ${A}`:""]}),r.jsxs("div",{className:"row",style:{gap:"8px",alignItems:"center"},children:[r.jsx("button",{className:"btn primary",onClick:()=>O.openModal(),disabled:W,children:W?"Connecting…":"Sign in"}),r.jsx("button",{className:"btn",onClick:()=>void Xs({open_modal_if_needed:!0}),disabled:W,title:"Retry with an existing browser session or a direct dev token",children:"Retry connection"})]})]})})}):null,e==="settings"?r.jsx("div",{className:"page page_scroll",children:r.jsxs("div",{className:"page_inner settings_col",children:[r.jsxs("section",{className:"pane",children:[r.jsxs("div",{className:"pane_header",children:[r.jsx("span",{className:"pane_title",children:"Gateway"}),r.jsx("span",{className:"pane_spacer"}),r.jsx("span",{className:`chip ${$?"ok":"warn"}`,children:Ev(F).label})]}),r.jsxs("div",{className:"pane_body settings_body",children:[r.jsxs("div",{className:"settings_row",children:[r.jsxs("div",{className:"settings_row_main",children:[r.jsx("div",{className:"settings_row_title",children:"Connection"}),r.jsx("div",{className:"settings_row_help",children:"The shared AbstractFramework sign-in: a gateway user token exchanges for an HTTP-only browser session. Raw tokens are never stored."})]}),r.jsxs("div",{className:"settings_row_actions",children:[r.jsx("button",{className:"btn",onClick:()=>O.openModal(),children:"Manage connection…"}),$?r.jsx("button",{className:"btn",onClick:()=>$l(),title:"Sign this browser out of the gateway (this app's session only)",children:"Sign out"}):null]})]}),A?r.jsx("div",{className:"warn_callout",children:A}):null,r.jsx("div",{className:"settings_row",children:r.jsx(nC,{checked:n.auto_connect_gateway,onChange:y=>s(k=>({...k,auto_connect_gateway:y}))})}),r.jsxs("details",{className:"settings_advanced",children:[r.jsx("summary",{children:"Advanced: direct dev connection (bearer token, cross-origin)"}),r.jsxs("div",{className:"field",style:{marginTop:"8px"},children:[r.jsx("label",{children:"Gateway URL"}),r.jsx("input",{value:n.gateway_url,onChange:y=>s(k=>({...k,gateway_url:y.target.value})),placeholder:jm})]}),r.jsxs("div",{className:"field",children:[r.jsx("label",{children:"Dev bearer token"}),r.jsx("input",{type:"password",value:n.auth_token,onChange:y=>s(k=>({...k,auth_token:y.target.value,gateway_auth_mode:"direct"})),placeholder:"development only — prefer the sign-in dialog"})]}),r.jsx("button",{className:"btn",onClick:()=>void Xs({prefer_direct:!0}),disabled:W,children:W?"Connecting…":"Connect directly"})]})]})]}),r.jsxs("section",{className:"pane",children:[r.jsxs("div",{className:"pane_header",children:[r.jsx("span",{className:"pane_title",children:"Assistant"}),r.jsx("span",{className:"pane_spacer"}),r.jsx("span",{className:"chip muted",children:"docs Q&A + run Ask"})]}),r.jsxs("div",{className:"pane_body settings_body",children:[r.jsx("div",{className:"settings_row_help",style:{marginTop:0},children:"The model answering the header assistant and the run page's Ask tab. Blank fields follow the gateway defaults."}),r.jsx(uj,{className:"field",providerLabel:"Provider",modelLabel:"Model",providerPlaceholder:"(gateway default)",modelPlaceholder:"(gateway default)",provider:n.maintenance_ai_provider,model:n.maintenance_ai_model,providers:Ii,models:Cl.models,loadingProviders:W,loadingModels:Ic,modelError:Lc?Cl.error:"",allowCustomProvider:!0,allowCustomModel:!0,allowGatewayDefault:!0,gatewayDefaultLabel:"(gateway default)",onChange:y=>s(k=>({...k,maintenance_ai_provider:y.provider,maintenance_ai_model:y.model}))}),r.jsx("div",{className:"settings_subhead",children:"Skills"}),R===null?r.jsx("div",{className:"settings_row_help",children:$?X?"The gateway does not serve a skills inventory yet — the abstractskill shelf list lights up here the day it ships.":"Probing the gateway for the skills inventory…":"Connect to the gateway to list installable skills (abstractskill shelf)."}):R.length?r.jsx("div",{className:"settings_choice_list",children:R.map(y=>{const k=n.assistant_skill_names.includes(y.name);return r.jsx(rC,{name:y.name,version:y.version,description:y.description,checked:k,onChange:M=>s(D=>({...D,assistant_skill_names:M?Array.from(new Set([...D.assistant_skill_names,y.name])):D.assistant_skill_names.filter(q=>q!==y.name)}))},y.name)})}):r.jsx("div",{className:"settings_row_help",children:"The gateway serves an empty skills inventory."}),r.jsx("div",{className:"settings_row_help",children:"Selected skills ride the assistant's runs once the gateway's skills-attachment lane serves them; the selection persists here meanwhile."}),r.jsx("div",{className:"settings_subhead",children:"MCP servers"}),r.jsx("div",{className:"settings_row_help",style:{marginTop:0},children:"Remote tool endpoints the assistant may call. The gateway does not serve an MCP inventory yet — one manual endpoint is supported (advanced / potentially dangerous: it executes tool waits from this browser)."}),r.jsxs("div",{className:"settings_mcp_row",children:[r.jsx("input",{className:"mono",value:n.worker_url,onChange:y=>s(k=>({...k,worker_url:y.target.value})),placeholder:"https://your-mcp-worker-endpoint"}),r.jsx("input",{className:"mono",type:"password",value:n.worker_token,onChange:y=>s(k=>({...k,worker_token:y.target.value})),placeholder:"Bearer token (optional)"}),r.jsx("span",{className:`chip ${n.worker_url.trim()?"ok":"muted"}`,children:n.worker_url.trim()?"configured":"none"})]})]})]})]})}):null,e==="launch"?r.jsx("div",{className:"page page_scroll",children:r.jsx("div",{className:"page_inner constrained",children:r.jsxs("div",{className:"card",children:[r.jsx(T2,{mode:pe,automate_available:qe.available,automate_reason:qe.reason,on_change:ye}),pe==="automate"&&!qe.available&&$?r.jsx("div",{className:"warn_callout",role:"note",children:qe.reason}):null,pe==="automate"&&ht.length?r.jsx("div",{className:"help_text",role:"note",children:ht.map(y=>r.jsx("div",{children:y},y))}):null,$?null:r.jsxs("div",{className:"warn_callout",children:["Not connected."," ",r.jsx("button",{className:"btn primary",onClick:()=>O.openModal(),children:"Sign in"})," ","to launch workflows on this gateway."]}),pe==="automate"?r.jsx("div",{className:"section_title",children:"What"}):null,r.jsx("div",{className:"launch_workflow_bar",children:r.jsx(wk,{id:"launch-workflow-picker",className:"launch_workflow_picker",interfaceId:null,defaultInterface:Su,ariaLabel:"Workflow",workflows:Nl,value:qy(Js,((ea=Nl.data)==null?void 0:ea.entries)??[]),currentLabel:Js&&!qy(Js,((vi=Nl.data)==null?void 0:vi.entries)??[])?{name:ar[ud]||ud}:null,unavailableReason:$?W?"Loading workflows…":null:"Sign in to load workflows.",onChange:(y,k)=>{const M=s2(y,k);M&&_d(M)}})}),r.jsxs("div",{className:"field",children:[Zn!=null&&Zn.description?r.jsx("div",{className:"help_text muted",style:{fontSize:"var(--font-size-sm)",marginTop:"6px"},children:String(Zn.description)}):null,Y?r.jsx("div",{className:"help_text muted",style:{fontSize:"var(--font-size-sm)"},children:"Loading workflow…"}):null,ce?r.jsx("div",{className:"mono",style:{color:"rgba(239, 68, 68, 0.9)",fontSize:"var(--font-size-sm)"},children:ce}):null]}),r.jsx("div",{className:"section_divider"}),r.jsx("div",{className:"section_title",children:"Inputs"}),Js?ut===null?r.jsxs("div",{className:"log_item",style:{borderColor:"rgba(239, 68, 68, 0.35)",marginTop:"10px"},children:[r.jsxs("div",{className:"meta",children:[r.jsx("span",{className:"mono",children:"input error"}),r.jsx("span",{className:"mono",children:Ct()})]}),r.jsx("div",{className:"body mono",children:"Invalid input JSON — reselect the workflow to reset its inputs."})]}):Is?r.jsx("div",{className:"launch_inputs",children:(()=>{const y=dt||ft,k=[],M=[];for(const H of _i){if(!H||typeof H!="object")continue;const V=String(H.id||"").trim();if(!V||pe==="automate"&&$x.includes(V))continue;const ne=String(H.type||"").trim().toLowerCase();ne==="tools"||ne==="skills"||ne==="mcp"||ne==="mcp_servers"||V==="skills"||V==="mcp"||V==="mcp_servers"||ne==="array"||Li(ne)||V==="prompt"||V==="system"?k.push(H):M.push(H)}const D=H=>String(H||"").trim().replace(/_/g," ").replace(/\b\w/g,V=>V.toUpperCase()),q=(H,V)=>{const ne=String(H.id||"").trim();if(!ne)return null;const Le=String(H.label||ne).trim()||ne,_e=Le===ne?D(ne):Le,he=String(H.type||"").trim().toLowerCase(),$e=Object.prototype.hasOwnProperty.call(H,"default"),Pe=$e?H.default:void 0,ze=$e?typeof Pe=="string"?Pe:cs(Pe,80):"",Ze=ut==null?void 0:ut[ne],Ve=$e?`${ze}`:"";if(he==="tools"){const Be=Array.isArray(Ze)?Ze.map(hn=>String(hn||"").trim()).filter(Boolean):[],bt=Array.isArray(Pe)?Pe.map(hn=>String(hn||"").trim()).filter(Boolean):[],xn=Array.from(new Set([...ho,...Be,...bt])).sort();return r.jsxs("div",{className:"launch_field_wide",children:[r.jsx("label",{className:"launch_label",children:_e}),r.jsx(vv,{options:xn,value:Be,disabled:y,placeholder:"(no tools selected)",onChange:hn=>Tn(ne,hn)})]},ne)}if(he==="skills"||ne==="skills")return null;if(he==="mcp"||he==="mcp_servers"||ne==="mcp"||ne==="mcp_servers"){const Be=Array.isArray(Ze)?Ze.map(hn=>String(hn||"").trim()).filter(Boolean):[];if(le===null&&!Be.length)return r.jsxs("div",{className:"launch_field_wide",children:[r.jsx("label",{className:"launch_label",children:_e}),r.jsx("div",{className:"help_text muted",children:"This gateway does not serve an MCP server inventory yet — MCP selection lights up here when it ships."})]},ne);const bt=(le||[]).map(hn=>hn.name),xn=Array.from(new Set([...bt,...Be])).sort();return r.jsxs("div",{className:"launch_field_wide",children:[r.jsx("label",{className:"launch_label",children:_e}),r.jsx(vv,{options:xn,value:Be,disabled:y,placeholder:"(no MCP servers selected)",onChange:hn=>Tn(ne,hn)})]},ne)}if(he==="provider"||he==="provider_text"){const Be=typeof Ze=="string"?String(Ze):"";return r.jsxs("div",{className:V||"launch_field",children:[r.jsx("label",{className:"launch_label",children:_e}),r.jsxs("select",{value:Be,onChange:bt=>Tn(ne,bt.target.value),disabled:y,children:[r.jsx("option",{value:"",children:Ve||"(select)"}),Kf.map(bt=>r.jsx("option",{value:bt,children:bt},bt))]})]},ne)}if(he==="model"||he==="model_text"){const Be=typeof Ze=="string"?String(Ze):"",bt=String((ut==null?void 0:ut.provider)||"").trim(),xn=bt?$t[bt]:void 0,hn=xn&&Array.isArray(xn.models)?xn.models.map(Mr=>String(Mr||"").trim()).filter(Boolean):[];return r.jsxs("div",{className:V||"launch_field",children:[r.jsx("label",{className:"launch_label",children:_e}),hn.length?r.jsxs("select",{value:Be,onChange:Mr=>Tn(ne,Mr.target.value),disabled:y,children:[r.jsx("option",{value:"",children:Ve||"(select)"}),hn.map(Mr=>r.jsx("option",{value:Mr,children:Mr},Mr))]}):r.jsx("input",{value:Be,onChange:Mr=>Tn(ne,Mr.target.value),placeholder:Ve||"model id",disabled:y})]},ne)}if(he==="boolean"){const Be=typeof Ze=="boolean"?Ze?"true":"false":"";return r.jsxs("div",{className:V||"launch_field",children:[r.jsx("label",{className:"launch_label",children:_e}),r.jsxs("select",{value:Be,onChange:bt=>{const xn=String(bt.target.value||"").trim();xn?Tn(ne,xn==="true"):Tn(ne,void 0)},disabled:y,children:[r.jsx("option",{value:"",children:Ve||"(default)"}),r.jsx("option",{value:"true",children:"Yes"}),r.jsx("option",{value:"false",children:"No"})]})]},ne)}if(he==="number"){const Be=typeof Ze=="number"&&Number.isFinite(Ze)?String(Ze):"";return r.jsxs("div",{className:V||"launch_field",children:[r.jsx("label",{className:"launch_label",children:_e}),r.jsx("input",{type:"number",value:Be,onChange:bt=>{const xn=String(bt.target.value||"").trim();if(!xn){Tn(ne,void 0);return}const hn=Number(xn);Number.isFinite(hn)&&Tn(ne,hn)},placeholder:Ve,disabled:y})]},ne)}if(he==="array"){const Be=Array.isArray(Ze)?Ze.map(bt=>String(bt||"").trim()).filter(Boolean).join(`
148
- `):"";return r.jsxs("div",{className:"launch_field_wide",children:[r.jsx("label",{className:"launch_label",children:_e}),r.jsx("textarea",{className:"mono",value:Be,onChange:bt=>{const xn=String(bt.target.value||"").split(/\r?\n/g).map(hn=>String(hn||"").trim()).filter(Boolean);Tn(ne,xn.length?xn:void 0)},placeholder:Ve||"(one item per line)",rows:2,disabled:y})]},ne)}if(Li(he)){const Be=typeof cn[ne]=="string"?cn[ne]:"",bt=String(Hs[ne]||"").trim();return r.jsxs("div",{className:"launch_field_wide",children:[r.jsxs("label",{className:"launch_label",children:[_e," ",r.jsx("span",{className:"launch_label_type",children:he})]}),r.jsx("textarea",{className:"mono",value:Be,onChange:xn=>{const hn=String(xn.target.value??"");Dr(dr=>({...dr,[ne]:hn}));const Mr=hn.trim();if(!Mr){sr(dr=>{const Ds={...dr};return delete Ds[ne],Ds}),Tn(ne,void 0);return}try{const dr=JSON.parse(Mr);sr(Ds=>{const Ka={...Ds};return delete Ka[ne],Ka}),Tn(ne,dr)}catch(dr){sr(Ds=>({...Ds,[ne]:String((dr==null?void 0:dr.message)||dr||"Invalid JSON")}))}},placeholder:Ve||"{...}",rows:3,disabled:y}),bt?r.jsx("div",{className:"launch_field_error",children:bt}):null]},ne)}const sn=typeof Ze=="string"?String(Ze):"";return ne==="prompt"||ne==="system"?r.jsxs("div",{className:"launch_field_wide",children:[r.jsx("label",{className:"launch_label",children:_e}),r.jsx("textarea",{value:sn,onChange:Be=>Tn(ne,Be.target.value),placeholder:Ve||(ne==="prompt"?"What should the agent do?":"System instructions (optional)"),rows:3,disabled:y})]},ne):r.jsxs("div",{className:V||"launch_field",children:[r.jsx("label",{className:"launch_label",children:_e}),r.jsx("input",{value:sn,onChange:Be=>Tn(ne,Be.target.value),placeholder:Ve,disabled:y})]},ne)};return k.sort((H,V)=>{const ne={system:0,prompt:1,tools:2};return(ne[String(H.id||"")]??10)-(ne[String(V.id||"")]??10)}),r.jsxs(r.Fragment,{children:[k.map(H=>q(H)),M.length>0?r.jsx("div",{className:"launch_grid",children:M.map(H=>q(H,"launch_grid_cell"))}):null]})})()}):r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"field",style:{marginTop:"10px"},children:[r.jsx("label",{children:"Prompt (common)"}),r.jsx("textarea",{value:Mc,onChange:y=>Tn("prompt",y.target.value),placeholder:"What do you want the workflow/agent to do?",rows:3,disabled:dt||ft})]}),r.jsxs("div",{className:"row",children:[r.jsx("div",{className:"col",children:r.jsxs("div",{className:"field",children:[r.jsx("label",{children:"Provider (common)"}),r.jsx("input",{value:fo,onChange:y=>Tn("provider",y.target.value),placeholder:"lmstudio / ollama / openai / ...",disabled:dt||ft})]})}),r.jsx("div",{className:"col",children:r.jsxs("div",{className:"field",children:[r.jsx("label",{children:"Model (common)"}),r.jsx("input",{value:ad,onChange:y=>Tn("model",y.target.value),placeholder:"qwen/qwen3-next-80b / gpt-4.1 / ...",disabled:dt||ft})]})})]})]}):r.jsx("div",{className:"help_text muted",style:{marginTop:"8px"},children:"Select a workflow above to configure inputs."}),pe==="automate"?r.jsxs(r.Fragment,{children:[r.jsx(M2,{form:We,email_status:bs.email_status,on_open_my_email:Ac,tools:Array.isArray(ut==null?void 0:ut.tools)?ut.tools.map(y=>String(y)):void 0,disabled:Se,on_change:y=>pt(k=>({...k,...y}))}),r.jsxs("details",{className:"launch_advanced",style:{marginTop:"10px"},children:[r.jsxs("summary",{className:"help_text muted",style:{cursor:"pointer"},children:["Advanced",or.length?` · ${or.length} skill${or.length===1?"":"s"}`:""]}),r.jsx(R2,{form:We,disabled:Se,on_change:y=>pt(k=>({...k,...y}))}),Xc]})]}):Xc,r.jsx("div",{className:"section_divider"}),Vi?r.jsxs("div",{className:"observe_context_card error",style:{marginBottom:"10px"},children:[r.jsx("span",{className:"chip mono danger",children:"error"}),r.jsx("span",{className:"mono",children:Vi})]}):null,pe==="automate"&&Fe.length?r.jsx("ul",{className:"automate_errors",role:"alert",children:Fe.map(y=>r.jsx("li",{children:y},y))}):null,pe==="automate"&&lt?r.jsxs("div",{className:"observe_context_card error",role:"alert","data-code":lt.code,style:{marginBottom:"10px"},children:[r.jsx("span",{className:"chip mono danger",children:lt.code}),r.jsxs("span",{children:[r.jsx("strong",{children:im(lt).title})," ",im(lt).detail,lt.field?r.jsxs("span",{className:"mono",children:[" (",lt.field,")"]}):null]})]}):null,r.jsx("div",{className:"launch_actions_bar launch_actions_stack",children:(()=>{const y=pe==="automate",k=$?Js?ut===null?"Inputs contain invalid JSON":y&&!qe.available?"Automations unavailable on this gateway":dt||ft?"Attaching to a run…":W||Y?"Loading…":Se?"Submitting…":"":"Select a workflow":"Sign in first";return r.jsxs(r.Fragment,{children:[r.jsx("button",{className:"launch_submit_btn",onClick:()=>void Zf(),disabled:!!k,title:k,children:y?Se?"Creating…":"Create automation":dt?"Launching…":"Launch now"}),k&&!Se&&!dt?r.jsx("span",{className:"mono muted launch_disabled_reason",children:k}):null]})})()})]})})}):null,e==="automations"?r.jsx(tC,{ctl:Tt,gateway:Te,active:e==="automations"&&$,available:qe,h:rn,host:{on_open_run:y=>Ss(y),...Ac?{on_open_my_email:Ac}:{},on_open_session:(y,k)=>{Jt({ts:Ct(),kind:"info",title:"Discussion started",preview:St(k),data:y})}}}):null,e==="runtime"?r.jsx(cE,{gateway_connected:$,tab:pl,runs:yi,active_runs:mh,all_artifacts:bc,artifacts:Tr,artifact_total_count:jc,artifact_total_bytes:yl,artifact_facets:Yu,artifact_type_facets:Sc,artifact_page:qa,artifact_page_size:Gh,artifact_groups:n_,selected_artifact:Ha,embedded_preview:Ks,loading:zf,error:qm,query:ao,scope:zo,type_filters:$a,date_filter:Cc,group_by:lo,sort_by:vl,artifact_run_filter:yr,audit_log_text:mi,audit_log_meta:Qu,audit_log_loading:Hf,audit_log_error:Ia,workflow_label_by_id:ar,run_by_id:zn,selected_run_id:js,session_id:Od,runtime_log_source:qo,runtime_log_query:Rs,runtime_ledger_log_items:Ho,runtime_ledger_log_meta:Mi,runtime_ledger_log_loading:Vf,runtime_ledger_log_error:td,on_tab_change:Gu,on_query_change:kc,on_scope_change:wl,on_session_filter_change:Nc,on_type_filters_change:Uf,on_date_filter_change:Hm,on_group_by_change:co,on_sort_by_change:Aa,on_artifact_page_change:Uo,on_artifact_run_filter_change:y=>{const k=String(y||"").trim();Ta(k),k&&Bo(k),k&&zo!=="run"&&wl("run")},on_refresh_artifacts:()=>void Rd(),on_refresh_audit:()=>void Ld(),on_refresh_runtime_ledger:y=>void Id(y),on_runtime_log_source_change:Ec,on_runtime_log_query_change:Ls,on_select_run:y=>{const k=String(y||"").trim();Bo(k);const M=k&&zn[k]||null,D=String((M==null?void 0:M.session_id)||"").trim();D&&Nc(D)},on_select_artifact:Xu,on_preview_artifact:y=>void Vm(y),on_download_artifact:y=>void Ml(y),on_open_run:y=>{Bo(String(y||"").trim()),t("observe"),Zi("ledger"),Zs(y)},on_open_ledger:y=>{Bo(String(y||"").trim()),t("observe"),Zi("ledger"),Zs(y)},on_refresh_runs:()=>void lr(Te,{force:!0}),on_reconnect:()=>void Xs({open_modal_if_needed:!0}),on_open_settings:()=>t("settings"),memory_panel:$?r.jsx(nL,{gateway:Te,selected_run_id:vs,selected_session_id:Od}):null}):null,e==="observe"?r.jsx("div",{className:"page observe_page",children:r.jsxs("div",{className:`observatory_layout${zu?"":" list_collapsed"}`,children:[r.jsx(dE,{sections:Pd,selected_run_id:c,root_run_id:m,search:yc,filter:Du,group_by:Fu,loading:wn,connected:$,on_sign_in:()=>O.openModal(),total_runs:yi.length,workflow_label_by_id:ar,automation_titles:rd,on_search:Dm,on_filter:Fm,on_group_by:zm,on_refresh:()=>void lr(),on_select:(y,k)=>{Zs(y,{root_run_id:k||y}),zl()},list:{open:zu,on_toggle:Lf}}),r.jsxs("div",{className:"observatory_main",children:[r.jsxs("div",{className:"observe_toolbar",children:[r.jsxs("div",{className:"observe_toolbar_row",children:[c.trim()?r.jsxs("div",{className:"observe_run_identity",title:c.trim(),children:[r.jsx("span",{className:"observe_run_name",children:ar[String((Rn==null?void 0:Rn.workflow_id)||"")]||String((Rn==null?void 0:Rn.workflow_id)||"").trim()||Qt(c.trim(),22)}),r.jsx("span",{className:"chip mono muted",children:Qt(c.trim(),14)}),r.jsx("span",{className:`chip ${oc(Wa||Vn,yo)}`,title:String((yo==null?void 0:yo.headline)||""),children:Wa||Vn||"unknown"})]}):x?r.jsx("span",{className:"observe_run_identity_empty observe_run_link_missing",role:"alert",children:yN(x)}):r.jsx("span",{className:"observe_run_identity_empty",children:"No run selected"}),r.jsx("span",{className:"observe_toolbar_spacer"}),c.trim()?r.jsxs(r.Fragment,{children:[os?r.jsx(iC,{active:!_o,unavailableReason:Ed,busy:dt||ft,onChange:y=>{if(!y){ps("pause"),Xr(""),ir(""),_s(!0);return}Ba("resume")}}):r.jsx("button",{className:"btn",onClick:()=>{if(Nd==="pause"){ps("pause"),Xr(""),ir(""),_s(!0);return}Ba("resume")},disabled:Cd,children:kd}),uh?r.jsx("button",{className:"btn primary",onClick:()=>void yd(),disabled:dt||ft||ti||_o,children:"Run now"}):null,r.jsx("button",{className:"btn danger",onClick:()=>{ps("cancel"),Xr(""),ir(""),_s(!0)},disabled:dt||ft||ti,children:"Cancel"}),r.jsx("button",{className:"btn btn_icon",onClick:Uc,title:"Clear the run view",children:r.jsx(et,{name:"x",size:14})})]}):null]}),c.trim()&&!ti?r.jsx("div",{className:"observe_steer_row",children:r.jsx(Rj,{runId:c.trim(),parked:ss,submit:(y,k)=>Te.submit_command({command_id:`steer-${xr()}`,run_id:y,type:"inject_guidance",payload:{guidance:k},client_id:"web_pwa"}).then(M=>({accepted:!!(M!=null&&M.accepted),duplicate:!!(M!=null&&M.duplicate),seq:Number((M==null?void 0:M.seq)??0)})),onSent:()=>Jt({ts:Ct(),kind:"info",title:"Steer queued",preview:"inject_guidance submitted — delivery shows as abstract.steer_seen in the ledger"})})}):null,ss||os||Ou?r.jsxs("div",{className:"observe_toolbar_context",children:[ss?r.jsxs("div",{className:"observe_context_card info",children:[r.jsxs("div",{className:"observe_context_label",children:[(()=>{const y=os?_o?"suspended":"scheduled":"waiting";return r.jsx("span",{className:`chip ${oc(y)}`,children:y})})(),r.jsx("span",{className:"muted",children:cr||"unknown"})]}),r.jsxs("div",{className:"observe_context_body",children:[Er?r.jsxs("span",{className:"mono",title:Er,children:[r.jsx("span",{className:"muted",children:"wait_key"}),": ",Qt(Er,46)]}):null,cr==="event"&&Ua?r.jsxs("span",{className:"mono",children:[r.jsx("span",{className:"muted",children:"event"}),": ",Ua]}):null,cr==="subworkflow"&&Pi?r.jsxs("span",{className:"mono",children:[r.jsx("span",{className:"muted",children:"child"}),": ",Qt(Pi,18)]}):null,cr==="until"&&Qs?r.jsxs("span",{className:"mono",title:Qs,children:[r.jsx("span",{className:"muted",children:"until"}),": ",Qt(Qs,46)]}):null,cr==="until"&&Qs?r.jsx("span",{className:"mono muted",children:(()=>{const y=qn(Qs),k=y!==null?new Date(y).toLocaleString():Qs,M=y!==null?Uy(y-Date.now()):"";return`Next at ${k}${M?` (in ${M})`:""}`})()}):null]}),cr==="subworkflow"&&Pi?r.jsxs("div",{className:"observe_context_actions",children:[r.jsx("button",{className:"btn primary",onClick:async()=>{f(Pi),await Rl(Pi)},disabled:dt,children:"Attach to child"}),m.trim()&&m.trim()!==c.trim()?r.jsx("button",{className:"btn",onClick:async()=>{f(m.trim()),await Rl(m.trim())},disabled:dt,children:"Back to root"}):null]}):null]}):null,os?r.jsxs("div",{className:"observe_context_card muted",children:[r.jsxs("div",{className:"observe_context_label",children:[r.jsx("span",{className:"chip muted",children:"schedule"}),r.jsx("span",{className:"muted",children:Ol?`every ${Jo}`:"once"})]}),r.jsxs("div",{className:"observe_context_body",children:[Jo?r.jsxs("span",{className:"mono",children:[r.jsx("span",{className:"muted",children:"interval"}),": ",Jo]}):null,r.jsxs("span",{className:"mono",children:[r.jsx("span",{className:"muted",children:"share ctx"}),": ",ch?"yes":"no"]}),typeof Vc=="number"?r.jsxs("span",{className:"mono",children:[r.jsx("span",{className:"muted",children:"repeats"}),": ",Vc]}):null]}),po!==null?r.jsxs("div",{className:"observe_context_budget",children:[r.jsxs("span",{className:"mono muted",children:[typeof dh=="number"&&typeof $d=="number"?`${dh.toLocaleString()} / ${$d.toLocaleString()}`:"",` • ${Math.round(Math.max(0,Math.min(1,po))*100)}%`]}),r.jsx("div",{className:"observe_budget_bar",children:r.jsx("div",{className:`observe_budget_fill ${po>=.9?"danger":po>=.75?"warn":"ok"}`,style:{width:`${Math.round(Math.max(0,Math.min(1,po))*100)}%`}})})]}):null,r.jsxs("div",{className:"observe_context_actions",children:[Ol?r.jsx("button",{className:"btn",onClick:()=>{On(Jo||""),Hn(!0),ai(""),$o(!0)},disabled:dt||An,children:"Edit schedule"}):null,Ol?r.jsx("button",{className:"btn",onClick:()=>{_r(""),Jr(!0)},disabled:dt||Es,children:"Compact context"}):null,r.jsx("button",{className:"btn",onClick:()=>void pd(c.trim()).catch(y=>nn(String((y==null?void 0:y.message)||y))),disabled:dt||!c.trim(),title:"Open Launch → Automate prefilled from this schedule (this schedule is not changed)",children:"Recreate as automation"})]})]}):null,Ou?r.jsxs("div",{className:"observe_context_card error",children:[r.jsx("span",{className:"chip danger",children:"error"}),r.jsx("span",{className:"mono",children:Ou})]}):null]}):null]}),r.jsxs("div",{className:"card panel_card card_scroll observe_viewer observe_viewer_full",ref:Pf,children:[r.jsxs("div",{className:"tab_bar",children:[r.jsxs("div",{role:"tablist","aria-label":"Run views",className:"observe_tablist",children:[r.jsx("button",{role:"tab","aria-selected":ts==="ledger",className:`tab ${ts==="ledger"?"active":""}`,onClick:()=>Yc("ledger"),children:"Ledger"}),r.jsx("button",{role:"tab","aria-selected":ts==="graph",className:`tab ${ts==="graph"?"active":""}`,onClick:()=>Yc("graph"),children:"Flow"}),r.jsx("button",{role:"tab","aria-selected":ts==="chat",className:`tab ${ts==="chat"?"active":""}`,onClick:()=>Yc("chat"),children:"Ask"})]}),ts==="ledger"&&(an.length>0||rr.length>0)?r.jsx("div",{className:"tab_bar_controls",children:r.jsx("button",{className:"seg_action",disabled:!an.length&&!rr.length,title:"Copy full ledger as JSONL",onClick:()=>{const M=[...an.map(H=>({run_id:c.trim()||H.record.run_id||"",cursor:H.cursor,record:H.record})),...rr.map(H=>({run_id:H.run_id,cursor:H.cursor,record:H.record}))].map(H=>{var Le,_e;const V=String(((Le=H.record)==null?void 0:Le.ended_at)||((_e=H.record)==null?void 0:_e.started_at)||"").trim(),ne=qn(V);return{...H,_ms:ne??0}});M.sort((H,V)=>(H._ms||0)-(V._ms||0));const q=(M.length>5e3?M.slice(M.length-5e3):M).map(({_ms:H,...V})=>JSON.stringify(V)).join(`
149
- `);Dc(q)},children:"Copy JSONL"})}):null,ts==="graph"?r.jsxs("div",{className:"tab_bar_controls",children:[r.jsx("button",{className:`seg_action ${fl?"active":""}`,"aria-pressed":fl,onClick:()=>Um(y=>!y),children:"Subflows"}),r.jsx("button",{className:`seg_action ${qu?"active":""}`,"aria-pressed":qu,onClick:()=>Wm(y=>!y),children:"Path"}),Td.length?r.jsx("select",{className:"mono seg_select",value:ya,onChange:y=>Qi(String(y.target.value||"")),disabled:!!Os.trim()||!C.trim()||Uu,children:Td.map(y=>r.jsx("option",{value:y,children:y},y))}):null]}):null]}),ts==="ledger"?c.trim()?r.jsxs("div",{className:"rs_page",children:[r.jsx(n2,{status:Wa||Vn||"unknown",duration:Rn?ic(Rn):"",facts:WN(UN(go)),error:dm(Rn)||String((ue==null?void 0:ue.error)||"").trim(),answer:Qm||String((Dl==null?void 0:Dl.text)||"").trim(),waiting_for_user:!!(Ft!=null&&Ft.wait_key)&&String((Ft==null?void 0:Ft.reason)||"")==="user",on_answer_wait:()=>Qr(""),workspace_root:ga,on_reveal_workspace:()=>void Tl(),on_open_artifacts:()=>{const y=String(c||"").trim();y&&(Bo(y),Ta(y),wl("run")),Gu("artifacts"),t("runtime")}}),Iu.filter(y=>y.kind==="error"&&!y.data).slice(0,3).map(y=>r.jsxs("p",{className:"rs_notice",children:[y.title,": ",y.preview]},y.id)),r.jsx(t2,{items:go,run_id:Fl,run_options:Ar,run_llm_counts:Gc,on_select_run:y=>Bu(y),state:Bm,on_state:e_,node_label:(y,k)=>{const M=k?(Vo==null?void 0:Vo[Fn(y,k)])||(Vo==null?void 0:Vo[k]):null;return String((M==null?void 0:M.label)||k||"").trim()},on_copy:y=>void Dc(y),on_open_run:y=>void Zs(y,{root_run_id:m||c||y})})]}):r.jsx("div",{className:"empty_state_inline",children:"Select a run on the left to inspect it — or start one from Launch."}):null,ts==="graph"?r.jsxs(r.Fragment,{children:[Wu?r.jsxs("div",{className:"log_item log_item_danger",children:[r.jsxs("div",{className:"meta",children:[r.jsx("span",{children:"graph error"}),r.jsx("span",{className:"mono",children:Ct()})]}),r.jsx("div",{className:"body mono",children:Wu})]}):null,Uu?r.jsxs("div",{className:"log_item log_item_info",children:[r.jsxs("div",{className:"meta",children:[r.jsx("span",{children:"loading"}),r.jsx("span",{className:"mono",children:Os.trim()?Os.trim():ya})]}),r.jsx("div",{className:"body mono",children:"Loading graph…"})]}):null,r.jsx("div",{className:"graph_panel",children:r.jsx(TE,{flow:wa,flow_by_id:xa,expand_subflows:fl,simplify:!0,prefer_vertical:!0,vertical_compact:.78,schedule_next_in:Zo,schedule_interval:Jo,node_last_ms:Zm,active_node_id:Oi,recent_nodes:Ff,visited_nodes:Hu,highlight_path:qu,now_ms:Vs})})]}):null,ts==="chat"?r.jsxs("div",{className:"ask_tab log_scroll",style:{marginTop:"6px"},children:[r.jsxs("div",{className:"ask_header",children:[r.jsx("span",{className:"ask_title",children:"Ask about this run"}),r.jsx("span",{className:"chip muted",title:"Model comes from Settings → Assistant (blank = gateway default)",children:(n.maintenance_ai_provider.trim()||"gateway")+" / "+(n.maintenance_ai_model.trim()||"default")}),r.jsx("span",{className:"pane_spacer"}),r.jsx("span",{className:"ask_hint",children:"Read-only · grounded in this run + subflows"})]}),r.jsxs("details",{className:"ask_manage",children:[r.jsx("summary",{children:"History & export"}),r.jsxs("div",{className:"field",style:{marginTop:"10px"},children:[r.jsxs("div",{className:"actions",style:{justifyContent:"space-between",alignItems:"center",gap:"10px",flexWrap:"wrap",marginTop:0},children:[r.jsx("div",{style:{flex:1,minWidth:260},children:r.jsx(xu,{value:Tu,options:Lu,placeholder:ll?"Loading…":Lu.length?"Select a saved discussion…":"(none saved)",disabled:!c.trim()||!$||!Lu.length,loading:ll,searchable:!0,clearable:!0,onChange:y=>{_c(y),Io("")}})}),r.jsxs("div",{className:"actions",style:{justifyContent:"flex-end",marginTop:0},children:[r.jsx("button",{className:"btn",type:"button",disabled:!Tu.trim()||!$||pc,onClick:()=>void Gm(),children:pc?"Loading…":"Load"}),r.jsx("button",{className:"btn",type:"button",disabled:!Qe.length||be||Xn||pc,onClick:()=>{ot([]),Dt(null),es(""),li(""),vn(""),pr(""),ys("")},children:"Clear"}),r.jsx("button",{className:"btn",type:"button",onClick:()=>void Wc(),disabled:!c.trim()||!$||ll,children:ll?"Refreshing…":"Refresh"})]})]}),r.jsxs("div",{className:"actions",style:{justifyContent:"flex-end",marginTop:"8px",flexWrap:"wrap"},children:[r.jsx("button",{className:"btn",type:"button",disabled:!Qe.length||!c.trim()||!$||Xn||!Ru,onClick:()=>void rh(),title:Ru?"":"No changes since last save",children:Xn?"Saving…":!Ru&&jn?"Saved":"Save discussion"}),r.jsx("button",{className:"btn",type:"button",disabled:!Qe.length,onClick:()=>vd("download"),children:"Export Markdown"}),r.jsx("button",{className:"btn",type:"button",disabled:!Qe.length,onClick:()=>vd("copy"),children:Ee==="copied"?"Copied":Ee==="failed"?"Copy failed":"Copy Markdown"})]}),jn?r.jsxs("div",{className:"chat_hint",children:["Last saved: ",ec(jn)]}):null,un?r.jsx("div",{className:"chat_hint chat_hint_danger",children:un}):null,Mu?r.jsx("div",{className:"chat_hint chat_hint_danger",children:Mu}):null,hc?r.jsx("div",{className:"chat_hint chat_hint_danger",children:hc}):null]})]}),Mo?r.jsxs("div",{className:"log_item log_item_danger",children:[r.jsxs("div",{className:"meta",children:[r.jsx("span",{children:"error"}),r.jsx("span",{className:"mono",children:Ct()})]}),r.jsx("div",{className:"body mono",children:Mo})]}):null,al?r.jsxs("div",{className:"log_item log_item_danger",children:[r.jsxs("div",{className:"meta",children:[r.jsx("span",{children:"voice"}),r.jsx("span",{className:"mono",children:Ct()})]}),r.jsx("div",{className:"body mono",children:al})]}):null,r.jsx("div",{className:"chat_messages",style:{marginTop:"10px"},children:r.jsx(ug,{messages:Qe,className:"log_scroll",after:r.jsx(vx,{history:mt}),afterKey:mt?`${mt.replayed_messages}:${mt.dropped_messages}`:null,messageProps:Ht.tts_supported&&$&&B.trim()?{onSpeakToggle:nh,getSpeakState:wd,jsonCollapseAfterDepth:4}:{jsonCollapseAfterDepth:4},empty:r.jsx("div",{className:"chat_empty_hint",children:"Ask about this run (why failed, which tools, what happened in subflows)."})})}),r.jsxs("div",{className:"chat_composer",style:{marginTop:"10px"},children:[r.jsx(dg,{ref:Xt,value:Xi,onChange:es,onSubmit:()=>void th(),placeholder:"Ask about this run…",disabled:!c.trim()||!$||be,busy:be||Ht.voice_ptt_busy,busyLabel:Ht.voice_ptt_busy?"Transcribing…":"Thinking…",rows:3,sendButtonClassName:"btn primary",actions:r.jsxs("button",{className:`btn btn_icon voice_btn${Ht.voice_ptt_recording?" danger":""}`,type:"button",disabled:!$||!Mn.trim()||!B.trim()||be||Ht.voice_ptt_busy||!Ht.voice_ptt_supported,title:Ht.voice_ptt_supported?Ht.voice_ptt_busy?"Transcribing…":Ht.voice_ptt_recording?"Recording… release to transcribe":"Hold to talk (record + transcribe)":Rp()?"Voice recording is not supported in this browser":Mp,"aria-label":"Voice input",onPointerDown:y=>{var k,M;if(!(!$||!Mn.trim()||!B.trim()||be||Ht.voice_ptt_busy||!Ht.voice_ptt_supported)){y.preventDefault();try{(M=(k=y.currentTarget)==null?void 0:k.setPointerCapture)==null||M.call(k,y.pointerId)}catch{}Ht.start_voice_ptt_recording()}},onPointerUp:y=>{y.preventDefault(),Ht.stop_voice_ptt_recording()},onPointerCancel:y=>{y.preventDefault(),Ht.stop_voice_ptt_recording()},children:[r.jsx(et,{name:Ht.voice_ptt_recording?"x":"mic",size:16}),Ht.voice_ptt_busy?"Transcribing…":Ht.voice_ptt_recording?"Recording…":"Voice"]})}),Rp()?null:r.jsx("div",{className:"mono muted","data-testid":"voice-https-hint",style:{fontSize:"var(--font-size-sm)",marginTop:"6px"},children:Mp})]})]}):null,c.trim()?r.jsxs("div",{className:`status_bar ${dc?"pulse":""}`,children:[r.jsx("strong",{children:"Run"}),":"," ",r.jsx("span",{className:"mono",children:Wa||Vn||"unknown"}),Md&&Zo?r.jsxs("span",{className:"mono muted",children:[" • next in ",Zo]}):null,Ts?r.jsxs("span",{className:"mono muted",children:[" • ",Ts]}):null]}):null]})]})]})}):null,r.jsxs(Kl,{open:Zu,title:$i||"Artifact",onClose:()=>{uo(!1),xs(""),jl(""),xl(!1),La(null),fn&&(URL.revokeObjectURL(fn),wr(""))},actions:r.jsx("button",{className:"btn",onClick:()=>{uo(!1),xs(""),jl(""),xl(!1),La(null),fn&&(URL.revokeObjectURL(fn),wr(""))},children:"Close"}),children:[qf?r.jsx("div",{className:"mono muted",style:{fontSize:"var(--font-size-sm)",marginBottom:"8px"},children:"Loading…"}):null,bl?r.jsx("div",{className:"mono",style:{color:"rgba(239, 68, 68, 0.9)",fontSize:"var(--font-size-sm)",marginBottom:"8px"},children:bl}):null,Ai==="image"&&fn?r.jsx("img",{className:"runtime_preview_media",src:fn,alt:$i||"Artifact preview"}):Ai==="audio"&&fn?r.jsx("audio",{className:"runtime_preview_media",controls:!0,src:fn}):Ai==="video"&&fn?r.jsx("video",{className:"runtime_preview_media",controls:!0,src:fn}):r.jsx(Yx,{artifact:ns,text:Cn||"(empty)",className:"runtime_preview_text"})]}),Eo?r.jsxs(Kl,{open:Eo,title:"Edit schedule",onClose:()=>{$o(!1),On(""),Hn(!0),ai(""),Fr(!1)},actions:r.jsxs(r.Fragment,{children:[r.jsx("button",{className:"btn",onClick:()=>{$o(!1),On(""),Hn(!0),ai(""),Fr(!1)},disabled:dt||An,children:"Back"}),r.jsx("button",{className:"btn primary",onClick:async()=>{await Qf({interval:Ao,apply_immediately:ms})||($o(!1),ai(""),Fr(!1))},disabled:dt||An||!Ao.trim(),children:"Save"})]}),children:[Gi?r.jsxs("div",{className:"log_item",style:{borderColor:"rgba(239, 68, 68, 0.35)",marginBottom:"10px"},children:[r.jsxs("div",{className:"meta",children:[r.jsx("span",{className:"mono",children:"error"}),r.jsx("span",{className:"mono",children:Ct()})]}),r.jsx("div",{className:"body mono",children:Gi})]}):null,r.jsxs("div",{className:"field",children:[r.jsx("label",{children:"Interval"}),r.jsx("input",{className:"mono",value:Ao,onChange:y=>On(String(y.target.value||"")),placeholder:"20m / 1h / 0.5s / 250ms",disabled:dt||An}),r.jsxs("div",{className:"mono muted",style:{fontSize:"var(--font-size-sm)"},children:["Accepted units: ",r.jsx("span",{className:"mono",children:"ms"}),", ",r.jsx("span",{className:"mono",children:"s"}),", ",r.jsx("span",{className:"mono",children:"m"}),","," ",r.jsx("span",{className:"mono",children:"h"}),", ",r.jsx("span",{className:"mono",children:"d"}),". This updates the existing scheduled run in place (no context loss)."]})]}),r.jsxs("div",{className:"field",children:[r.jsx("label",{children:"Quick picks"}),r.jsx("div",{className:"actions",style:{gap:"8px",flexWrap:"wrap"},children:["15m","30m","1h","2h","6h","1d"].map(y=>r.jsx("button",{className:"btn",onClick:()=>On(y),disabled:dt||An,children:y},y))})]}),r.jsx("div",{className:"field",children:r.jsx(aC,{checked:ms,busy:dt||An,onChange:Hn})})]}):null,hr?r.jsxs(Kl,{open:hr,title:"Compact scheduled context",onClose:()=>{Jr(!1),_r(""),$s(!1)},actions:r.jsxs(r.Fragment,{children:[r.jsx("button",{className:"btn",onClick:()=>{Jr(!1),_r(""),$s(!1)},disabled:dt||Es,children:"Cancel"}),r.jsx("button",{className:"btn primary",onClick:async()=>{await eh({preserve_recent:mr,compression_mode:Ki,focus:fa})||(Jr(!1),_r(""),$s(!1))},disabled:dt||Es,children:Es?"Compacting…":"Compact"})]}),children:[To?r.jsxs("div",{className:"log_item",style:{borderColor:"rgba(239, 68, 68, 0.35)",marginBottom:"10px"},children:[r.jsxs("div",{className:"meta",children:[r.jsx("span",{className:"mono",children:"error"}),r.jsx("span",{className:"mono",children:Ct()})]}),r.jsx("div",{className:"body mono",children:To})]}):null,r.jsxs("div",{className:"field",children:[r.jsx("label",{children:"Preserve recent turns"}),r.jsx("input",{type:"number",min:1,value:String(mr),onChange:y=>da(Math.max(1,parseInt(y.target.value||"6",10)||6)),disabled:dt||Es})]}),r.jsxs("div",{className:"field",children:[r.jsx("label",{children:"Mode"}),r.jsxs("select",{value:Ki,onChange:y=>ln(y.target.value),disabled:dt||Es,children:[r.jsx("option",{value:"light",children:"light"}),r.jsx("option",{value:"standard",children:"standard"}),r.jsx("option",{value:"heavy",children:"heavy"})]})]}),r.jsxs("div",{className:"field",children:[r.jsx("label",{children:"Focus (optional)"}),r.jsx("input",{className:"mono",value:fa,onChange:y=>uc(String(y.target.value||"")),placeholder:"e.g. important decisions, next steps…",disabled:dt||Es})]})]}):null,Yi?r.jsxs(Kl,{open:Yi,title:kr==="cancel"?"Cancel run":os?"Suspend schedule":"Pause run",onClose:()=>{_s(!1),Xr(""),ir("")},actions:r.jsxs(r.Fragment,{children:[r.jsx("button",{className:"btn",onClick:()=>{_s(!1),Xr(""),ir("")},disabled:dt||ft,children:"Back"}),r.jsx("button",{className:`btn ${kr==="cancel"?"danger":"primary"}`,onClick:async()=>{ir("");const y=await Ba(kr,{reason:As});if(y){ir(y);return}_s(!1),Xr(""),ir("")},disabled:dt||ft,children:kr==="pause"?os?"Suspend":"Pause":"Cancel"})]}),children:[ki?r.jsxs("div",{className:"log_item",style:{borderColor:"rgba(239, 68, 68, 0.35)",marginBottom:"10px"},children:[r.jsxs("div",{className:"meta",children:[r.jsx("span",{className:"mono",children:"error"}),r.jsx("span",{className:"mono",children:Ct()})]}),r.jsx("div",{className:"body mono",children:ki})]}):null,r.jsxs("div",{className:"field",children:[r.jsx("label",{children:"Reason (optional)"}),r.jsx("input",{className:"mono",value:As,onChange:y=>Xr(y.target.value),placeholder:"reason…"})]})]}):null,bd?r.jsxs(Kl,{open:bd,title:Hc,onClose:()=>{Er&&Qr(Er)},actions:r.jsxs(r.Fragment,{children:[r.jsx("button",{className:"btn",onClick:()=>{Zi("ledger"),t("observe"),zl(),Er&&Qr(Er)},disabled:!c.trim(),children:"Open ledger"}),r.jsx("button",{className:"btn",onClick:()=>Er&&Qr(Er),disabled:ft,children:"Dismiss"}),Ko.length?r.jsxs(r.Fragment,{children:[r.jsx("button",{className:"btn danger",disabled:ft,onClick:()=>Il({approved:!1}),children:"Reject"}),r.jsx("button",{className:"btn",disabled:ft,onClick:()=>Il({approved:!0}),children:"Approve only"}),r.jsx("button",{className:"btn primary",disabled:!Oa||ft,onClick:()=>Km(Ko),children:"Approve and execute"})]}):null]}),children:[r.jsxs("div",{className:"wait_context_panel",children:[r.jsxs("div",{className:"wait_context_header",children:[r.jsxs("div",{children:[r.jsx("div",{className:"run_hero_eyebrow",children:"What you need to do"}),r.jsx("strong",{children:Hc}),r.jsx("p",{children:Jm})]}),r.jsx(ac,{status:ei||"waiting"})]}),Yo?r.jsxs("div",{className:`wait_request_card ${$r?"":"inferred"}`,children:[r.jsx("span",{children:Wr}),r.jsx(jv,{metadata:oh}),r.jsx(Wi,{text:Yo}),$r?null:r.jsx("p",{className:"wait_context_note",children:"The runtime did not attach a specific question to this wait. This is inferred from the run input; verify the session turns and workflow steps before answering."})]}):r.jsx("div",{className:"warn_callout",children:"This wait did not provide a clear prompt or recoverable prior user request. Review the full run input and recent workflow steps before submitting a response."}),Sd.length?r.jsxs("section",{className:"wait_context_block wait_conversation_context",children:[r.jsx("span",{children:"Recent session turns"}),r.jsx("div",{className:"wait_turn_list",children:Sd.map((y,k)=>r.jsxs("div",{className:`wait_turn_row role_${y.role.replace(/[^a-z0-9_-]+/g,"_")}`,children:[r.jsxs("div",{className:"wait_turn_meta",children:[r.jsx("strong",{children:y.role==="assistant"?"Assistant":y.role==="user"||y.role==="human"?"User":y.role}),y.ts?r.jsx("span",{className:"mono muted",children:ec(y.ts)}):null]}),r.jsx(jv,{metadata:y.runtime_metadata}),r.jsx(Wi,{text:St(y.text,{max_chars:1200,max_lines:10})})]},`${y.role}:${k}`))})]}):null,r.jsxs("div",{className:"artifact_detail_grid",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Workflow"}),r.jsx("strong",{children:Bi(gi,ar)})]}),r.jsxs("div",{children:[r.jsx("span",{children:"Run"}),r.jsx("strong",{className:"mono",children:Qt(c.trim(),24)})]}),r.jsxs("div",{children:[r.jsx("span",{children:"Node"}),r.jsx("strong",{className:"mono",children:gi.current_node||String((Ur==null?void 0:Ur.node_id)||"—")})]}),r.jsxs("div",{children:[r.jsx("span",{children:"Elapsed"}),r.jsx("strong",{children:ic(gi)})]}),r.jsxs("div",{children:[r.jsx("span",{children:"Session"}),r.jsx("strong",{className:"mono",children:gi.session_id?Qt(String(gi.session_id),18):"—"})]}),r.jsxs("div",{children:[r.jsx("span",{children:"Wait key"}),r.jsx("strong",{className:"mono",children:Qt(Er,28)})]})]}),lh?r.jsxs("details",{className:"runtime_raw_details wait_full_input_details",open:!Yo,children:[r.jsx("summary",{className:"mono muted",children:"Full run input JSON"}),r.jsx("div",{className:"wait_shared_json",children:r.jsx(Ir,{value:ah,collapseAfterDepth:4,showCopy:!0})})]}):null,r.jsxs("section",{className:"wait_context_block",children:[r.jsx("span",{children:"Recent workflow steps leading to this wait"}),r.jsxs("div",{className:"wait_event_list",children:[qc.map(y=>r.jsxs("div",{className:"wait_event_row",children:[r.jsxs("span",{className:"mono",children:["#",y.cursor]}),r.jsx("strong",{children:y.summary||y.effect_type||y.status||"event"}),r.jsx("span",{className:"mono muted",children:[y.node_id,y.status,ec(y.ts)].filter(Boolean).join(" · ")})]},`${y.cursor}:${y.node_id}:${y.status}`)),qc.length?null:r.jsx("div",{className:"empty_state_inline",children:"No ledger context is loaded. Open the ledger before deciding."})]})]})]}),Ko.length?r.jsxs("div",{className:"wait_action_panel",children:[r.jsx("div",{className:"wait_action_intro",children:"Approve and execute runs the listed tool request through your configured worker. Approve only sends approval without local execution. Reject returns a denial. Cancel run stops the whole workflow run."}),r.jsx("div",{className:"wait_tool_list",children:Ko.map((y,k)=>r.jsxs("div",{className:"wait_tool_card",children:[r.jsxs("div",{className:"wait_tool_header",children:[r.jsx("strong",{children:String((y==null?void 0:y.name)||"tool")}),r.jsxs("div",{className:"wait_tool_badges",children:[r.jsx("span",{className:"chip mono warn",children:"approval"}),Bx(y).map(M=>r.jsxs("span",{className:"chip mono muted",title:zx,children:[M,"~"]},M))]})]}),r.jsx("div",{className:"wait_tool_args",children:r.jsx(Ir,{value:(y==null?void 0:y.arguments)||{},collapseAfterDepth:3,showCopy:!0})})]},`${String((y==null?void 0:y.name)||"tool")}:${k}`))}),Oa?null:r.jsx("div",{className:"warn_callout",children:"No tool worker is configured, so Observer cannot execute these calls directly."}),r.jsx("div",{className:"actions",children:r.jsx("button",{className:"btn danger",onClick:()=>void gd(c.trim(),"Cancelled from wait prompt"),disabled:!c.trim()||ft,children:"Cancel whole run"})}),r.jsxs("details",{className:"runtime_raw_details",children:[r.jsx("summary",{className:"mono muted",children:"Diagnostics"}),r.jsx("div",{className:"wait_shared_json",children:r.jsx(Ir,{value:Ft||{},collapseAfterDepth:3,showCopy:!0})})]})]}):r.jsxs("div",{className:"wait_action_panel",children:[r.jsx("div",{className:"wait_action_intro",children:"Submit only when the request above is clear. The response resumes this wait only; Cancel run attempts to stop the whole workflow and prevent further work."}),r.jsx("div",{className:"wait_prompt_text",children:Yo||"No explicit prompt was provided. Open the ledger for context before responding."}),r.jsx(uE,{wait:Ft,disabled:ft,on_submit:y=>Il({response:y})}),r.jsx("div",{className:"actions",children:r.jsx("button",{className:"btn danger",onClick:()=>void gd(c.trim(),"Cancelled from wait prompt"),disabled:!c.trim()||ft,children:"Cancel whole run"})}),r.jsxs("details",{className:"runtime_raw_details",children:[r.jsx("summary",{className:"mono muted",children:"Diagnostics"}),r.jsx("div",{className:"wait_shared_json",children:r.jsx(Ir,{value:Ft||{},collapseAfterDepth:3,showCopy:!0})})]})]})]}):null]})]})]})}if("serviceWorker"in navigator){window.addEventListener("load",()=>{navigator.serviceWorker.register(pN).then(t=>t.update()).catch(()=>{})});let e=!1;navigator.serviceWorker.addEventListener("controllerchange",()=>{e||(e=!0,window.location.reload())})}aj();tj.createRoot(document.getElementById("root")).render(r.jsx(ve.StrictMode,{children:r.jsx(BL,{})}));
150
- //# sourceMappingURL=index-C--XTi5_.js.map