@abstractframework/observer 0.7.0 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -3
- package/dist/assets/index-6qXs9M-h.js +174 -0
- package/dist/assets/index-6qXs9M-h.js.map +1 -0
- package/dist/assets/index-C0KSkRrQ.css +1 -0
- package/dist/index.html +2 -2
- package/dist/llms.txt +1 -1
- package/package.json +4 -3
- package/dist/assets/index-C1U8dkAL.js +0 -162
- package/dist/assets/index-C1U8dkAL.js.map +0 -1
- package/dist/assets/index-gYGGRAVm.css +0 -1
|
@@ -1,162 +0,0 @@
|
|
|
1
|
-
var Dj=Object.defineProperty;var Fj=(e,t,n)=>t in e?Dj(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var cs=(e,t,n)=>Fj(e,typeof t!="symbol"?t+"":t,n);(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))r(o);new MutationObserver(o=>{for(const l of o)if(l.type==="childList")for(const c of l.addedNodes)c.tagName==="LINK"&&c.rel==="modulepreload"&&r(c)}).observe(document,{childList:!0,subtree:!0});function n(o){const l={};return o.integrity&&(l.integrity=o.integrity),o.referrerPolicy&&(l.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?l.credentials="include":o.crossOrigin==="anonymous"?l.credentials="omit":l.credentials="same-origin",l}function r(o){if(o.ep)return;o.ep=!0;const l=n(o);fetch(o.href,l)}})();function Gg(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var J_={exports:{}},Yd={},X_={exports:{}},Yt={};/**
|
|
2
|
-
* @license React
|
|
3
|
-
* react.production.min.js
|
|
4
|
-
*
|
|
5
|
-
* Copyright (c) Facebook, Inc. and its affiliates.
|
|
6
|
-
*
|
|
7
|
-
* This source code is licensed under the MIT license found in the
|
|
8
|
-
* LICENSE file in the root directory of this source tree.
|
|
9
|
-
*/var Ky;function zj(){if(Ky)return Yt;Ky=1;var e=Symbol.for("react.element"),t=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),r=Symbol.for("react.strict_mode"),o=Symbol.for("react.profiler"),l=Symbol.for("react.provider"),c=Symbol.for("react.context"),u=Symbol.for("react.forward_ref"),f=Symbol.for("react.suspense"),h=Symbol.for("react.memo"),m=Symbol.for("react.lazy"),g=Symbol.iterator;function y(O){return O===null||typeof O!="object"?null:(O=g&&O[g]||O["@@iterator"],typeof O=="function"?O:null)}var w={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},k=Object.assign,b={};function S(O,H,Y){this.props=O,this.context=H,this.refs=b,this.updater=Y||w}S.prototype.isReactComponent={},S.prototype.setState=function(O,H){if(typeof O!="object"&&typeof O!="function"&&O!=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,O,H,"setState")},S.prototype.forceUpdate=function(O){this.updater.enqueueForceUpdate(this,O,"forceUpdate")};function N(){}N.prototype=S.prototype;function R(O,H,Y){this.props=O,this.context=H,this.refs=b,this.updater=Y||w}var T=R.prototype=new N;T.constructor=R,k(T,S.prototype),T.isPureReactComponent=!0;var A=Array.isArray,W=Object.prototype.hasOwnProperty,z={current:null},J={key:!0,ref:!0,__self:!0,__source:!0};function K(O,H,Y){var ae,ie={},_e=null,fe=null;if(H!=null)for(ae in H.ref!==void 0&&(fe=H.ref),H.key!==void 0&&(_e=""+H.key),H)W.call(H,ae)&&!J.hasOwnProperty(ae)&&(ie[ae]=H[ae]);var ge=arguments.length-2;if(ge===1)ie.children=Y;else if(1<ge){for(var Ne=Array(ge),Ue=0;Ue<ge;Ue++)Ne[Ue]=arguments[Ue+2];ie.children=Ne}if(O&&O.defaultProps)for(ae in ge=O.defaultProps,ge)ie[ae]===void 0&&(ie[ae]=ge[ae]);return{$$typeof:e,type:O,key:_e,ref:fe,props:ie,_owner:z.current}}function re(O,H){return{$$typeof:e,type:O.type,key:H,ref:O.ref,props:O.props,_owner:O._owner}}function te(O){return typeof O=="object"&&O!==null&&O.$$typeof===e}function Q(O){var H={"=":"=0",":":"=2"};return"$"+O.replace(/[=:]/g,function(Y){return H[Y]})}var D=/\/+/g;function $(O,H){return typeof O=="object"&&O!==null&&O.key!=null?Q(""+O.key):H.toString(36)}function E(O,H,Y,ae,ie){var _e=typeof O;(_e==="undefined"||_e==="boolean")&&(O=null);var fe=!1;if(O===null)fe=!0;else switch(_e){case"string":case"number":fe=!0;break;case"object":switch(O.$$typeof){case e:case t:fe=!0}}if(fe)return fe=O,ie=ie(fe),O=ae===""?"."+$(fe,0):ae,A(ie)?(Y="",O!=null&&(Y=O.replace(D,"$&/")+"/"),E(ie,H,Y,"",function(Ue){return Ue})):ie!=null&&(te(ie)&&(ie=re(ie,Y+(!ie.key||fe&&fe.key===ie.key?"":(""+ie.key).replace(D,"$&/")+"/")+O)),H.push(ie)),1;if(fe=0,ae=ae===""?".":ae+":",A(O))for(var ge=0;ge<O.length;ge++){_e=O[ge];var Ne=ae+$(_e,ge);fe+=E(_e,H,Y,Ne,ie)}else if(Ne=y(O),typeof Ne=="function")for(O=Ne.call(O),ge=0;!(_e=O.next()).done;)_e=_e.value,Ne=ae+$(_e,ge++),fe+=E(_e,H,Y,Ne,ie);else if(_e==="object")throw H=String(O),Error("Objects are not valid as a React child (found: "+(H==="[object Object]"?"object with keys {"+Object.keys(O).join(", ")+"}":H)+"). If you meant to render a collection of children, use an array instead.");return fe}function L(O,H,Y){if(O==null)return O;var ae=[],ie=0;return E(O,ae,"","",function(_e){return H.call(Y,_e,ie++)}),ae}function M(O){if(O._status===-1){var H=O._result;H=H(),H.then(function(Y){(O._status===0||O._status===-1)&&(O._status=1,O._result=Y)},function(Y){(O._status===0||O._status===-1)&&(O._status=2,O._result=Y)}),O._status===-1&&(O._status=0,O._result=H)}if(O._status===1)return O._result.default;throw O._result}var ee={current:null},F={transition:null},U={ReactCurrentDispatcher:ee,ReactCurrentBatchConfig:F,ReactCurrentOwner:z};function V(){throw Error("act(...) is not supported in production builds of React.")}return Yt.Children={map:L,forEach:function(O,H,Y){L(O,function(){H.apply(this,arguments)},Y)},count:function(O){var H=0;return L(O,function(){H++}),H},toArray:function(O){return L(O,function(H){return H})||[]},only:function(O){if(!te(O))throw Error("React.Children.only expected to receive a single React element child.");return O}},Yt.Component=S,Yt.Fragment=n,Yt.Profiler=o,Yt.PureComponent=R,Yt.StrictMode=r,Yt.Suspense=f,Yt.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=U,Yt.act=V,Yt.cloneElement=function(O,H,Y){if(O==null)throw Error("React.cloneElement(...): The argument must be a React element, but you passed "+O+".");var ae=k({},O.props),ie=O.key,_e=O.ref,fe=O._owner;if(H!=null){if(H.ref!==void 0&&(_e=H.ref,fe=z.current),H.key!==void 0&&(ie=""+H.key),O.type&&O.type.defaultProps)var ge=O.type.defaultProps;for(Ne in H)W.call(H,Ne)&&!J.hasOwnProperty(Ne)&&(ae[Ne]=H[Ne]===void 0&&ge!==void 0?ge[Ne]:H[Ne])}var Ne=arguments.length-2;if(Ne===1)ae.children=Y;else if(1<Ne){ge=Array(Ne);for(var Ue=0;Ue<Ne;Ue++)ge[Ue]=arguments[Ue+2];ae.children=ge}return{$$typeof:e,type:O.type,key:ie,ref:_e,props:ae,_owner:fe}},Yt.createContext=function(O){return O={$$typeof:c,_currentValue:O,_currentValue2:O,_threadCount:0,Provider:null,Consumer:null,_defaultValue:null,_globalName:null},O.Provider={$$typeof:l,_context:O},O.Consumer=O},Yt.createElement=K,Yt.createFactory=function(O){var H=K.bind(null,O);return H.type=O,H},Yt.createRef=function(){return{current:null}},Yt.forwardRef=function(O){return{$$typeof:u,render:O}},Yt.isValidElement=te,Yt.lazy=function(O){return{$$typeof:m,_payload:{_status:-1,_result:O},_init:M}},Yt.memo=function(O,H){return{$$typeof:h,type:O,compare:H===void 0?null:H}},Yt.startTransition=function(O){var H=F.transition;F.transition={};try{O()}finally{F.transition=H}},Yt.unstable_act=V,Yt.useCallback=function(O,H){return ee.current.useCallback(O,H)},Yt.useContext=function(O){return ee.current.useContext(O)},Yt.useDebugValue=function(){},Yt.useDeferredValue=function(O){return ee.current.useDeferredValue(O)},Yt.useEffect=function(O,H){return ee.current.useEffect(O,H)},Yt.useId=function(){return ee.current.useId()},Yt.useImperativeHandle=function(O,H,Y){return ee.current.useImperativeHandle(O,H,Y)},Yt.useInsertionEffect=function(O,H){return ee.current.useInsertionEffect(O,H)},Yt.useLayoutEffect=function(O,H){return ee.current.useLayoutEffect(O,H)},Yt.useMemo=function(O,H){return ee.current.useMemo(O,H)},Yt.useReducer=function(O,H,Y){return ee.current.useReducer(O,H,Y)},Yt.useRef=function(O){return ee.current.useRef(O)},Yt.useState=function(O){return ee.current.useState(O)},Yt.useSyncExternalStore=function(O,H,Y){return ee.current.useSyncExternalStore(O,H,Y)},Yt.useTransition=function(){return ee.current.useTransition()},Yt.version="18.3.1",Yt}var Yy;function Gf(){return Yy||(Yy=1,X_.exports=zj()),X_.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 Jy;function Bj(){if(Jy)return Yd;Jy=1;var e=Gf(),t=Symbol.for("react.element"),n=Symbol.for("react.fragment"),r=Object.prototype.hasOwnProperty,o=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,l={key:!0,ref:!0,__self:!0,__source:!0};function c(u,f,h){var m,g={},y=null,w=null;h!==void 0&&(y=""+h),f.key!==void 0&&(y=""+f.key),f.ref!==void 0&&(w=f.ref);for(m in f)r.call(f,m)&&!l.hasOwnProperty(m)&&(g[m]=f[m]);if(u&&u.defaultProps)for(m in f=u.defaultProps,f)g[m]===void 0&&(g[m]=f[m]);return{$$typeof:t,type:u,key:y,ref:w,props:g,_owner:o.current}}return Yd.Fragment=n,Yd.jsx=c,Yd.jsxs=c,Yd}var Xy;function Uj(){return Xy||(Xy=1,J_.exports=Bj()),J_.exports}var s=Uj(),_=Gf();const xe=Gg(_);var rm={},Z_={exports:{}},Ur={},Q_={exports:{}},ep={};/**
|
|
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 Zy;function Wj(){return Zy||(Zy=1,(function(e){function t(F,U){var V=F.length;F.push(U);e:for(;0<V;){var O=V-1>>>1,H=F[O];if(0<o(H,U))F[O]=U,F[V]=H,V=O;else break e}}function n(F){return F.length===0?null:F[0]}function r(F){if(F.length===0)return null;var U=F[0],V=F.pop();if(V!==U){F[0]=V;e:for(var O=0,H=F.length,Y=H>>>1;O<Y;){var ae=2*(O+1)-1,ie=F[ae],_e=ae+1,fe=F[_e];if(0>o(ie,V))_e<H&&0>o(fe,ie)?(F[O]=fe,F[_e]=V,O=_e):(F[O]=ie,F[ae]=V,O=ae);else if(_e<H&&0>o(fe,V))F[O]=fe,F[_e]=V,O=_e;else break e}}return U}function o(F,U){var V=F.sortIndex-U.sortIndex;return V!==0?V:F.id-U.id}if(typeof performance=="object"&&typeof performance.now=="function"){var l=performance;e.unstable_now=function(){return l.now()}}else{var c=Date,u=c.now();e.unstable_now=function(){return c.now()-u}}var f=[],h=[],m=1,g=null,y=3,w=!1,k=!1,b=!1,S=typeof setTimeout=="function"?setTimeout:null,N=typeof clearTimeout=="function"?clearTimeout:null,R=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(F){for(var U=n(h);U!==null;){if(U.callback===null)r(h);else if(U.startTime<=F)r(h),U.sortIndex=U.expirationTime,t(f,U);else break;U=n(h)}}function A(F){if(b=!1,T(F),!k)if(n(f)!==null)k=!0,M(W);else{var U=n(h);U!==null&&ee(A,U.startTime-F)}}function W(F,U){k=!1,b&&(b=!1,N(K),K=-1),w=!0;var V=y;try{for(T(U),g=n(f);g!==null&&(!(g.expirationTime>U)||F&&!Q());){var O=g.callback;if(typeof O=="function"){g.callback=null,y=g.priorityLevel;var H=O(g.expirationTime<=U);U=e.unstable_now(),typeof H=="function"?g.callback=H:g===n(f)&&r(f),T(U)}else r(f);g=n(f)}if(g!==null)var Y=!0;else{var ae=n(h);ae!==null&&ee(A,ae.startTime-U),Y=!1}return Y}finally{g=null,y=V,w=!1}}var z=!1,J=null,K=-1,re=5,te=-1;function Q(){return!(e.unstable_now()-te<re)}function D(){if(J!==null){var F=e.unstable_now();te=F;var U=!0;try{U=J(!0,F)}finally{U?$():(z=!1,J=null)}}else z=!1}var $;if(typeof R=="function")$=function(){R(D)};else if(typeof MessageChannel<"u"){var E=new MessageChannel,L=E.port2;E.port1.onmessage=D,$=function(){L.postMessage(null)}}else $=function(){S(D,0)};function M(F){J=F,z||(z=!0,$())}function ee(F,U){K=S(function(){F(e.unstable_now())},U)}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(F){F.callback=null},e.unstable_continueExecution=function(){k||w||(k=!0,M(W))},e.unstable_forceFrameRate=function(F){0>F||125<F?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):re=0<F?Math.floor(1e3/F):5},e.unstable_getCurrentPriorityLevel=function(){return y},e.unstable_getFirstCallbackNode=function(){return n(f)},e.unstable_next=function(F){switch(y){case 1:case 2:case 3:var U=3;break;default:U=y}var V=y;y=U;try{return F()}finally{y=V}},e.unstable_pauseExecution=function(){},e.unstable_requestPaint=function(){},e.unstable_runWithPriority=function(F,U){switch(F){case 1:case 2:case 3:case 4:case 5:break;default:F=3}var V=y;y=F;try{return U()}finally{y=V}},e.unstable_scheduleCallback=function(F,U,V){var O=e.unstable_now();switch(typeof V=="object"&&V!==null?(V=V.delay,V=typeof V=="number"&&0<V?O+V:O):V=O,F){case 1:var H=-1;break;case 2:H=250;break;case 5:H=1073741823;break;case 4:H=1e4;break;default:H=5e3}return H=V+H,F={id:m++,callback:U,priorityLevel:F,startTime:V,expirationTime:H,sortIndex:-1},V>O?(F.sortIndex=V,t(h,F),n(f)===null&&F===n(h)&&(b?(N(K),K=-1):b=!0,ee(A,V-O))):(F.sortIndex=H,t(f,F),k||w||(k=!0,M(W))),F},e.unstable_shouldYield=Q,e.unstable_wrapCallback=function(F){var U=y;return function(){var V=y;y=U;try{return F.apply(this,arguments)}finally{y=V}}}})(ep)),ep}var Qy;function qj(){return Qy||(Qy=1,Q_.exports=Wj()),Q_.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 ew;function Hj(){if(ew)return Ur;ew=1;var e=Gf(),t=qj();function n(i){for(var a="https://reactjs.org/docs/error-decoder.html?invariant="+i,d=1;d<arguments.length;d++)a+="&args[]="+encodeURIComponent(arguments[d]);return"Minified React error #"+i+"; visit "+a+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}var r=new Set,o={};function l(i,a){c(i,a),c(i+"Capture",a)}function c(i,a){for(o[i]=a,i=0;i<a.length;i++)r.add(a[i])}var u=!(typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),f=Object.prototype.hasOwnProperty,h=/^[: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]*$/,m={},g={};function y(i){return f.call(g,i)?!0:f.call(m,i)?!1:h.test(i)?g[i]=!0:(m[i]=!0,!1)}function w(i,a,d,p){if(d!==null&&d.type===0)return!1;switch(typeof a){case"function":case"symbol":return!0;case"boolean":return p?!1:d!==null?!d.acceptsBooleans:(i=i.toLowerCase().slice(0,5),i!=="data-"&&i!=="aria-");default:return!1}}function k(i,a,d,p){if(a===null||typeof a>"u"||w(i,a,d,p))return!0;if(p)return!1;if(d!==null)switch(d.type){case 3:return!a;case 4:return a===!1;case 5:return isNaN(a);case 6:return isNaN(a)||1>a}return!1}function b(i,a,d,p,x,j,P){this.acceptsBooleans=a===2||a===3||a===4,this.attributeName=p,this.attributeNamespace=x,this.mustUseProperty=d,this.propertyName=i,this.type=a,this.sanitizeURL=j,this.removeEmptyString=P}var S={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(i){S[i]=new b(i,0,!1,i,null,!1,!1)}),[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(i){var a=i[0];S[a]=new b(a,1,!1,i[1],null,!1,!1)}),["contentEditable","draggable","spellCheck","value"].forEach(function(i){S[i]=new b(i,2,!1,i.toLowerCase(),null,!1,!1)}),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(i){S[i]=new b(i,2,!1,i,null,!1,!1)}),"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(i){S[i]=new b(i,3,!1,i.toLowerCase(),null,!1,!1)}),["checked","multiple","muted","selected"].forEach(function(i){S[i]=new b(i,3,!0,i,null,!1,!1)}),["capture","download"].forEach(function(i){S[i]=new b(i,4,!1,i,null,!1,!1)}),["cols","rows","size","span"].forEach(function(i){S[i]=new b(i,6,!1,i,null,!1,!1)}),["rowSpan","start"].forEach(function(i){S[i]=new b(i,5,!1,i.toLowerCase(),null,!1,!1)});var N=/[\-:]([a-z])/g;function R(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(N,R);S[a]=new b(a,1,!1,i,null,!1,!1)}),"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(i){var a=i.replace(N,R);S[a]=new b(a,1,!1,i,"http://www.w3.org/1999/xlink",!1,!1)}),["xml:base","xml:lang","xml:space"].forEach(function(i){var a=i.replace(N,R);S[a]=new b(a,1,!1,i,"http://www.w3.org/XML/1998/namespace",!1,!1)}),["tabIndex","crossOrigin"].forEach(function(i){S[i]=new b(i,1,!1,i.toLowerCase(),null,!1,!1)}),S.xlinkHref=new b("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1),["src","href","action","formAction"].forEach(function(i){S[i]=new b(i,1,!1,i.toLowerCase(),null,!0,!0)});function T(i,a,d,p){var x=S.hasOwnProperty(a)?S[a]:null;(x!==null?x.type!==0:p||!(2<a.length)||a[0]!=="o"&&a[0]!=="O"||a[1]!=="n"&&a[1]!=="N")&&(k(a,d,x,p)&&(d=null),p||x===null?y(a)&&(d===null?i.removeAttribute(a):i.setAttribute(a,""+d)):x.mustUseProperty?i[x.propertyName]=d===null?x.type===3?!1:"":d:(a=x.attributeName,p=x.attributeNamespace,d===null?i.removeAttribute(a):(x=x.type,d=x===3||x===4&&d===!0?"":""+d,p?i.setAttributeNS(p,a,d):i.setAttribute(a,d))))}var A=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,W=Symbol.for("react.element"),z=Symbol.for("react.portal"),J=Symbol.for("react.fragment"),K=Symbol.for("react.strict_mode"),re=Symbol.for("react.profiler"),te=Symbol.for("react.provider"),Q=Symbol.for("react.context"),D=Symbol.for("react.forward_ref"),$=Symbol.for("react.suspense"),E=Symbol.for("react.suspense_list"),L=Symbol.for("react.memo"),M=Symbol.for("react.lazy"),ee=Symbol.for("react.offscreen"),F=Symbol.iterator;function U(i){return i===null||typeof i!="object"?null:(i=F&&i[F]||i["@@iterator"],typeof i=="function"?i:null)}var V=Object.assign,O;function H(i){if(O===void 0)try{throw Error()}catch(d){var a=d.stack.trim().match(/\n( *(at )?)/);O=a&&a[1]||""}return`
|
|
34
|
-
`+O+i}var Y=!1;function ae(i,a){if(!i||Y)return"";Y=!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(ve){var p=ve}Reflect.construct(i,[],a)}else{try{a.call()}catch(ve){p=ve}i.call(a.prototype)}else{try{throw Error()}catch(ve){p=ve}i()}}catch(ve){if(ve&&p&&typeof ve.stack=="string"){for(var x=ve.stack.split(`
|
|
35
|
-
`),j=p.stack.split(`
|
|
36
|
-
`),P=x.length-1,ne=j.length-1;1<=P&&0<=ne&&x[P]!==j[ne];)ne--;for(;1<=P&&0<=ne;P--,ne--)if(x[P]!==j[ne]){if(P!==1||ne!==1)do if(P--,ne--,0>ne||x[P]!==j[ne]){var oe=`
|
|
37
|
-
`+x[P].replace(" at new "," at ");return i.displayName&&oe.includes("<anonymous>")&&(oe=oe.replace("<anonymous>",i.displayName)),oe}while(1<=P&&0<=ne);break}}}finally{Y=!1,Error.prepareStackTrace=d}return(i=i?i.displayName||i.name:"")?H(i):""}function ie(i){switch(i.tag){case 5:return H(i.type);case 16:return H("Lazy");case 13:return H("Suspense");case 19:return H("SuspenseList");case 0:case 2:case 15:return i=ae(i.type,!1),i;case 11:return i=ae(i.type.render,!1),i;case 1:return i=ae(i.type,!0),i;default:return""}}function _e(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 z:return"Portal";case re:return"Profiler";case K:return"StrictMode";case $:return"Suspense";case E:return"SuspenseList"}if(typeof i=="object")switch(i.$$typeof){case Q:return(i.displayName||"Context")+".Consumer";case te:return(i._context.displayName||"Context")+".Provider";case D:var a=i.render;return i=i.displayName,i||(i=a.displayName||a.name||"",i=i!==""?"ForwardRef("+i+")":"ForwardRef"),i;case L:return a=i.displayName||null,a!==null?a:_e(i.type)||"Memo";case M:a=i._payload,i=i._init;try{return _e(i(a))}catch{}}return null}function fe(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 _e(a);case 8:return a===K?"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 ge(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),p=""+i[a];if(!i.hasOwnProperty(a)&&typeof d<"u"&&typeof d.get=="function"&&typeof d.set=="function"){var x=d.get,j=d.set;return Object.defineProperty(i,a,{configurable:!0,get:function(){return x.call(this)},set:function(P){p=""+P,j.call(this,P)}}),Object.defineProperty(i,a,{enumerable:d.enumerable}),{getValue:function(){return p},setValue:function(P){p=""+P},stopTracking:function(){i._valueTracker=null,delete i[a]}}}}function We(i){i._valueTracker||(i._valueTracker=Ue(i))}function ut(i){if(!i)return!1;var a=i._valueTracker;if(!a)return!0;var d=a.getValue(),p="";return i&&(p=Ne(i)?i.checked?"true":"false":i.value),i=p,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 et(i,a){var d=a.checked;return V({},a,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:d??i._wrapperState.initialChecked})}function $e(i,a){var d=a.defaultValue==null?"":a.defaultValue,p=a.checked!=null?a.checked:a.defaultChecked;d=ge(a.value!=null?a.value:d),i._wrapperState={initialChecked:p,initialValue:d,controlled:a.type==="checkbox"||a.type==="radio"?a.checked!=null:a.value!=null}}function Ve(i,a){a=a.checked,a!=null&&T(i,"checked",a,!1)}function le(i,a){Ve(i,a);var d=ge(a.value),p=a.type;if(d!=null)p==="number"?(d===0&&i.value===""||i.value!=d)&&(i.value=""+d):i.value!==""+d&&(i.value=""+d);else if(p==="submit"||p==="reset"){i.removeAttribute("value");return}a.hasOwnProperty("value")?Pe(i,a.type,d):a.hasOwnProperty("defaultValue")&&Pe(i,a.type,ge(a.defaultValue)),a.checked==null&&a.defaultChecked!=null&&(i.defaultChecked=!!a.defaultChecked)}function be(i,a,d){if(a.hasOwnProperty("value")||a.hasOwnProperty("defaultValue")){var p=a.type;if(!(p!=="submit"&&p!=="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 Pe(i,a,d){(a!=="number"||Fe(i.ownerDocument)!==i)&&(d==null?i.defaultValue=""+i._wrapperState.initialValue:i.defaultValue!==""+d&&(i.defaultValue=""+d))}var me=Array.isArray;function Ce(i,a,d,p){if(i=i.options,a){a={};for(var x=0;x<d.length;x++)a["$"+d[x]]=!0;for(d=0;d<i.length;d++)x=a.hasOwnProperty("$"+i[d].value),i[d].selected!==x&&(i[d].selected=x),x&&p&&(i[d].defaultSelected=!0)}else{for(d=""+ge(d),a=null,x=0;x<i.length;x++){if(i[x].value===d){i[x].selected=!0,p&&(i[x].defaultSelected=!0);return}a!==null||i[x].disabled||(a=i[x])}a!==null&&(a.selected=!0)}}function Te(i,a){if(a.dangerouslySetInnerHTML!=null)throw Error(n(91));return V({},a,{value:void 0,defaultValue:void 0,children:""+i._wrapperState.initialValue})}function Je(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(me(d)){if(1<d.length)throw Error(n(93));d=d[0]}a=d}a==null&&(a=""),d=a}i._wrapperState={initialValue:ge(d)}}function rt(i,a){var d=ge(a.value),p=ge(a.defaultValue);d!=null&&(d=""+d,d!==i.value&&(i.value=d),a.defaultValue==null&&i.defaultValue!==d&&(i.defaultValue=d)),p!=null&&(i.defaultValue=""+p)}function ht(i){var a=i.textContent;a===i._wrapperState.initialValue&&a!==""&&a!==null&&(i.value=a)}function lt(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 Ct(i,a){return i==null||i==="http://www.w3.org/1999/xhtml"?lt(a):i==="http://www.w3.org/2000/svg"&&a==="foreignObject"?"http://www.w3.org/1999/xhtml":i}var Xt,Pn=(function(i){return typeof MSApp<"u"&&MSApp.execUnsafeLocalFunction?function(a,d,p,x){MSApp.execUnsafeLocalFunction(function(){return i(a,d,p,x)})}:i})(function(i,a){if(i.namespaceURI!=="http://www.w3.org/2000/svg"||"innerHTML"in i)i.innerHTML=a;else{for(Xt=Xt||document.createElement("div"),Xt.innerHTML="<svg>"+a.valueOf().toString()+"</svg>",a=Xt.firstChild;i.firstChild;)i.removeChild(i.firstChild);for(;a.firstChild;)i.appendChild(a.firstChild)}});function zt(i,a){if(a){var d=i.firstChild;if(d&&d===i.lastChild&&d.nodeType===3){d.nodeValue=a;return}}i.textContent=a}var wn={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},Un=["Webkit","ms","Moz","O"];Object.keys(wn).forEach(function(i){Un.forEach(function(a){a=a+i.charAt(0).toUpperCase()+i.substring(1),wn[a]=wn[i]})});function Mn(i,a,d){return a==null||typeof a=="boolean"||a===""?"":d||typeof a!="number"||a===0||wn.hasOwnProperty(i)&&wn[i]?(""+a).trim():a+"px"}function vn(i,a){i=i.style;for(var d in a)if(a.hasOwnProperty(d)){var p=d.indexOf("--")===0,x=Mn(d,a[d],p);d==="float"&&(d="cssFloat"),p?i.setProperty(d,x):i[d]=x}}var Dn=V({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 bn(i,a){if(a){if(Dn[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 js(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 Ss(i){return i=i.target||i.srcElement||window,i.correspondingUseElement&&(i=i.correspondingUseElement),i.nodeType===3?i.parentNode:i}var Ar=null,Fn=null,de=null;function Se(i){if(i=Vo(i)){if(typeof Ar!="function")throw Error(n(280));var a=i.stateNode;a&&(a=Pa(a),Ar(i.stateNode,i.type,a))}}function tt(i){Fn?de?de.push(i):de=[i]:Fn=i}function Qe(){if(Fn){var i=Fn,a=de;if(de=Fn=null,Se(i),a)for(i=0;i<a.length;i++)Se(a[i])}}function ct(i,a){return i(a)}function mt(){}var It=!1;function Et(i,a,d){if(It)return i(a,d);It=!0;try{return ct(i,a,d)}finally{It=!1,(Fn!==null||de!==null)&&(mt(),Qe())}}function Zt(i,a){var d=i.stateNode;if(d===null)return null;var p=Pa(d);if(p===null)return null;d=p[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":(p=!p.disabled)||(i=i.type,p=!(i==="button"||i==="input"||i==="select"||i==="textarea")),i=!p;break e;default:i=!1}if(i)return null;if(d&&typeof d!="function")throw Error(n(231,a,typeof d));return d}var St=!1;if(u)try{var Qt={};Object.defineProperty(Qt,"passive",{get:function(){St=!0}}),window.addEventListener("test",Qt,Qt),window.removeEventListener("test",Qt,Qt)}catch{St=!1}function Ht(i,a,d,p,x,j,P,ne,oe){var ve=Array.prototype.slice.call(arguments,3);try{a.apply(d,ve)}catch(Le){this.onError(Le)}}var Bt=!1,Pt=null,Dt=!1,qe=null,ln={onError:function(i){Bt=!0,Pt=i}};function pt(i,a,d,p,x,j,P,ne,oe){Bt=!1,Pt=null,Ht.apply(ln,arguments)}function rn(i,a,d,p,x,j,P,ne,oe){if(pt.apply(this,arguments),Bt){if(Bt){var ve=Pt;Bt=!1,Pt=null}else throw Error(n(198));Dt||(Dt=!0,qe=ve)}}function gt(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 Wn(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 cn(i){if(gt(i)!==i)throw Error(n(188))}function Gs(i){var a=i.alternate;if(!a){if(a=gt(i),a===null)throw Error(n(188));return a!==i?null:i}for(var d=i,p=a;;){var x=d.return;if(x===null)break;var j=x.alternate;if(j===null){if(p=x.return,p!==null){d=p;continue}break}if(x.child===j.child){for(j=x.child;j;){if(j===d)return cn(x),i;if(j===p)return cn(x),a;j=j.sibling}throw Error(n(188))}if(d.return!==p.return)d=x,p=j;else{for(var P=!1,ne=x.child;ne;){if(ne===d){P=!0,d=x,p=j;break}if(ne===p){P=!0,p=x,d=j;break}ne=ne.sibling}if(!P){for(ne=j.child;ne;){if(ne===d){P=!0,d=j,p=x;break}if(ne===p){P=!0,p=j,d=x;break}ne=ne.sibling}if(!P)throw Error(n(189))}}if(d.alternate!==p)throw Error(n(190))}if(d.tag!==3)throw Error(n(188));return d.stateNode.current===d?i:a}function ns(i){return i=Gs(i),i!==null?Vr(i):null}function Vr(i){if(i.tag===5||i.tag===6)return i;for(i=i.child;i!==null;){var a=Vr(i);if(a!==null)return a;i=i.sibling}return null}var hr=t.unstable_scheduleCallback,ii=t.unstable_cancelCallback,oi=t.unstable_shouldYield,Ps=t.unstable_requestPaint,he=t.unstable_now,mr=t.unstable_getCurrentPriorityLevel,Xi=t.unstable_ImmediatePriority,_r=t.unstable_UserBlockingPriority,Tr=t.unstable_NormalPriority,Gr=t.unstable_LowPriority,dt=t.unstable_IdlePriority,hn=null,Ds=null;function Kr(i){if(Ds&&typeof Ds.onCommitFiberRoot=="function")try{Ds.onCommitFiberRoot(hn,i,void 0,(i.current.flags&128)===128)}catch{}}var ss=Math.clz32?Math.clz32:Ro,To=Math.log,Mo=Math.LN2;function Ro(i){return i>>>=0,i===0?32:31-(To(i)/Mo|0)|0}var zn=64,pr=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 Zi(i,a){var d=i.pendingLanes;if(d===0)return 0;var p=0,x=i.suspendedLanes,j=i.pingedLanes,P=d&268435455;if(P!==0){var ne=P&~x;ne!==0?p=Hn(ne):(j&=P,j!==0&&(p=Hn(j)))}else P=d&~x,P!==0?p=Hn(P):j!==0&&(p=Hn(j));if(p===0)return 0;if(a!==0&&a!==p&&(a&x)===0&&(x=p&-p,j=a&-a,x>=j||x===16&&(j&4194240)!==0))return a;if((p&4)!==0&&(p|=d&16),a=i.entangledLanes,a!==0)for(i=i.entanglements,a&=p;0<a;)d=31-ss(a),x=1<<d,p|=i[d],a&=~x;return p}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 Rn(i,a){for(var d=i.suspendedLanes,p=i.pingedLanes,x=i.expirationTimes,j=i.pendingLanes;0<j;){var P=31-ss(j),ne=1<<P,oe=x[P];oe===-1?((ne&d)===0||(ne&p)!==0)&&(x[P]=ai(ne,a)):oe<=a&&(i.expiredLanes|=ne),j&=~ne}}function Fs(i){return i=i.pendingLanes&-1073741825,i!==0?i:i&1073741824?1073741824:0}function ds(){var i=zn;return zn<<=1,(zn&4194240)===0&&(zn=64),i}function Ks(i){for(var a=[],d=0;31>d;d++)a.push(i);return a}function fs(i,a,d){i.pendingLanes|=a,a!==536870912&&(i.suspendedLanes=0,i.pingedLanes=0),i=i.eventTimes,a=31-ss(a),i[a]=d}function xa(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 p=i.eventTimes;for(i=i.expirationTimes;0<d;){var x=31-ss(d),j=1<<x;a[x]=0,p[x]=-1,i[x]=-1,d&=~j}}function Qi(i,a){var d=i.entangledLanes|=a;for(i=i.entanglements;d;){var p=31-ss(d),x=1<<p;x&a|i[p]&a&&(i[p]|=a),d&=~x}}var un=0;function ba(i){return i&=-i,1<i?4<i?(i&268435455)!==0?16:536870912:4:1}var Sc,Lo,hs,Mr,Rr,eo=!1,gr=[],Ns=null,yr=null,Lr=null,Ys=new Map,Ci=new Map,rs=[],Ir="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 ka(i,a){switch(i){case"focusin":case"focusout":Ns=null;break;case"dragenter":case"dragleave":yr=null;break;case"mouseover":case"mouseout":Lr=null;break;case"pointerover":case"pointerout":Ys.delete(a.pointerId);break;case"gotpointercapture":case"lostpointercapture":Ci.delete(a.pointerId)}}function wr(i,a,d,p,x,j){return i===null||i.nativeEvent!==j?(i={blockedOn:a,domEventName:d,eventSystemFlags:p,nativeEvent:j,targetContainers:[x]},a!==null&&(a=Vo(a),a!==null&&Lo(a)),i):(i.eventSystemFlags|=p,a=i.targetContainers,x!==null&&a.indexOf(x)===-1&&a.push(x),i)}function to(i,a,d,p,x){switch(a){case"focusin":return Ns=wr(Ns,i,a,d,p,x),!0;case"dragenter":return yr=wr(yr,i,a,d,p,x),!0;case"mouseover":return Lr=wr(Lr,i,a,d,p,x),!0;case"pointerover":var j=x.pointerId;return Ys.set(j,wr(Ys.get(j)||null,i,a,d,p,x)),!0;case"gotpointercapture":return j=x.pointerId,Ci.set(j,wr(Ci.get(j)||null,i,a,d,p,x)),!0}return!1}function Nc(i){var a=Dr(i.target);if(a!==null){var d=gt(a);if(d!==null){if(a=d.tag,a===13){if(a=Wn(d),a!==null){i.blockedOn=a,Rr(i.priority,function(){hs(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 Ei(i){if(i.blockedOn!==null)return!1;for(var a=i.targetContainers;0<a.length;){var d=ce(i.domEventName,i.eventSystemFlags,a[0],i.nativeEvent);if(d===null){d=i.nativeEvent;var p=new d.constructor(d.type,d);Kn=p,d.target.dispatchEvent(p),Kn=null}else return a=Vo(d),a!==null&&Lo(a),i.blockedOn=d,!1;a.shift()}return!0}function Js(i,a,d){Ei(i)&&d.delete(a)}function Yu(){eo=!1,Ns!==null&&Ei(Ns)&&(Ns=null),yr!==null&&Ei(yr)&&(yr=null),Lr!==null&&Ei(Lr)&&(Lr=null),Ys.forEach(Js),Ci.forEach(Js)}function Xs(i,a){i.blockedOn===a&&(i.blockedOn=null,eo||(eo=!0,t.unstable_scheduleCallback(t.unstable_NormalPriority,Yu)))}function no(i){function a(x){return Xs(x,i)}if(0<gr.length){Xs(gr[0],i);for(var d=1;d<gr.length;d++){var p=gr[d];p.blockedOn===i&&(p.blockedOn=null)}}for(Ns!==null&&Xs(Ns,i),yr!==null&&Xs(yr,i),Lr!==null&&Xs(Lr,i),Ys.forEach(a),Ci.forEach(a),d=0;d<rs.length;d++)p=rs[d],p.blockedOn===i&&(p.blockedOn=null);for(;0<rs.length&&(d=rs[0],d.blockedOn===null);)Nc(d),d.blockedOn===null&&rs.shift()}var Zs=A.ReactCurrentBatchConfig,Io=!0;function li(i,a,d,p){var x=un,j=Zs.transition;Zs.transition=null;try{un=1,ci(i,a,d,p)}finally{un=x,Zs.transition=j}}function ja(i,a,d,p){var x=un,j=Zs.transition;Zs.transition=null;try{un=4,ci(i,a,d,p)}finally{un=x,Zs.transition=j}}function ci(i,a,d,p){if(Io){var x=ce(i,a,d,p);if(x===null)fd(i,a,p,q,d),ka(i,p);else if(to(x,i,a,d,p))p.stopPropagation();else if(ka(i,p),a&4&&-1<Ir.indexOf(i)){for(;x!==null;){var j=Vo(x);if(j!==null&&Sc(j),j=ce(i,a,d,p),j===null&&fd(i,a,p,q,d),j===x)break;x=j}x!==null&&p.stopPropagation()}else fd(i,a,p,null,d)}}var q=null;function ce(i,a,d,p){if(q=null,i=Ss(p),i=Dr(i),i!==null)if(a=gt(i),a===null)i=null;else if(d=a.tag,d===13){if(i=Wn(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 q=i,null}function je(i){switch(i){case"cancel":case"click":case"close":case"contextmenu":case"copy":case"cut":case"auxclick":case"dblclick":case"dragend":case"dragstart":case"drop":case"focusin":case"focusout":case"input":case"invalid":case"keydown":case"keypress":case"keyup":case"mousedown":case"mouseup":case"paste":case"pause":case"play":case"pointercancel":case"pointerdown":case"pointerup":case"ratechange":case"reset":case"resize":case"seeked":case"submit":case"touchcancel":case"touchend":case"touchstart":case"volumechange":case"change":case"selectionchange":case"textInput":case"compositionstart":case"compositionend":case"compositionupdate":case"beforeblur":case"afterblur":case"beforeinput":case"blur":case"fullscreenchange":case"focus":case"hashchange":case"popstate":case"select":case"selectstart":return 1;case"drag":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"mousemove":case"mouseout":case"mouseover":case"pointermove":case"pointerout":case"pointerover":case"scroll":case"toggle":case"touchmove":case"wheel":case"mouseenter":case"mouseleave":case"pointerenter":case"pointerleave":return 4;case"message":switch(mr()){case Xi:return 1;case _r:return 4;case Tr:case Gr:return 16;case dt:return 536870912;default:return 16}default:return 16}}var Ae=null,Ee=null,Ge=null;function yt(){if(Ge)return Ge;var i,a=Ee,d=a.length,p,x="value"in Ae?Ae.value:Ae.textContent,j=x.length;for(i=0;i<d&&a[i]===x[i];i++);var P=d-i;for(p=1;p<=P&&a[d-p]===x[j-p];p++);return Ge=x.slice(i,1<p?1-p:void 0)}function _t(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 xt(){return!0}function Ut(){return!1}function Kt(i){function a(d,p,x,j,P){this._reactName=d,this._targetInst=x,this.type=p,this.nativeEvent=j,this.target=P,this.currentTarget=null;for(var ne in i)i.hasOwnProperty(ne)&&(d=i[ne],this[ne]=d?d(j):j[ne]);return this.isDefaultPrevented=(j.defaultPrevented!=null?j.defaultPrevented:j.returnValue===!1)?xt:Ut,this.isPropagationStopped=Ut,this}return V(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=xt)},stopPropagation:function(){var d=this.nativeEvent;d&&(d.stopPropagation?d.stopPropagation():typeof d.cancelBubble!="unknown"&&(d.cancelBubble=!0),this.isPropagationStopped=xt)},persist:function(){},isPersistent:xt}),a}var ms={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(i){return i.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},Ft=Kt(ms),dn=V({},ms,{view:0,detail:0}),En=Kt(dn),xn,Qn,Qs,Yr=V({},dn,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:wl,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!==Qs&&(Qs&&i.type==="mousemove"?(xn=i.screenX-Qs.screenX,Qn=i.screenY-Qs.screenY):Qn=xn=0,Qs=i),xn)},movementY:function(i){return"movementY"in i?i.movementY:Qn}}),$i=Kt(Yr),Sa=V({},Yr,{dataTransfer:0}),rh=Kt(Sa),Cc=V({},dn,{relatedTarget:0}),yl=Kt(Cc),Ec=V({},ms,{animationName:0,elapsedTime:0,pseudoElement:0}),$c=Kt(Ec),Ac=V({},ms,{clipboardData:function(i){return"clipboardData"in i?i.clipboardData:window.clipboardData}}),ih=Kt(Ac),Oo=V({},ms,{data:0}),Ju=Kt(Oo),Xu={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},Zu={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"},C_={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function Qu(i){var a=this.nativeEvent;return a.getModifierState?a.getModifierState(i):(i=C_[i])?!!a[i]:!1}function wl(){return Qu}var on=V({},dn,{key:function(i){if(i.key){var a=Xu[i.key]||i.key;if(a!=="Unidentified")return a}return i.type==="keypress"?(i=_t(i),i===13?"Enter":String.fromCharCode(i)):i.type==="keydown"||i.type==="keyup"?Zu[i.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:wl,charCode:function(i){return i.type==="keypress"?_t(i):0},keyCode:function(i){return i.type==="keydown"||i.type==="keyup"?i.keyCode:0},which:function(i){return i.type==="keypress"?_t(i):i.type==="keydown"||i.type==="keyup"?i.keyCode:0}}),ed=Kt(on),E_=V({},Yr,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),Tc=Kt(E_),$_=V({},dn,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:wl}),td=Kt($_),A_=V({},ms,{propertyName:0,elapsedTime:0,pseudoElement:0}),er=Kt(A_),so=V({},Yr,{deltaX:function(i){return"deltaX"in i?i.deltaX:"wheelDeltaX"in i?-i.wheelDeltaX:0},deltaY:function(i){return"deltaY"in i?i.deltaY:"wheelDeltaY"in i?-i.wheelDeltaY:"wheelDelta"in i?-i.wheelDelta:0},deltaZ:0,deltaMode:0}),oh=Kt(so),T_=[9,13,27,32],ro=u&&"CompositionEvent"in window,Po=null;u&&"documentMode"in document&&(Po=document.documentMode);var vl=u&&"TextEvent"in window&&!Po,nd=u&&(!ro||Po&&8<Po&&11>=Po),ah=" ",lh=!1;function ch(i,a){switch(i){case"keyup":return T_.indexOf(a.keyCode)!==-1;case"keydown":return a.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function sd(i){return i=i.detail,typeof i=="object"&&"data"in i?i.data:null}var Na=!1;function uh(i,a){switch(i){case"compositionend":return sd(a);case"keypress":return a.which!==32?null:(lh=!0,ah);case"textInput":return i=a.data,i===ah&&lh?null:i;default:return null}}function M_(i,a){if(Na)return i==="compositionend"||!ro&&ch(i,a)?(i=yt(),Ge=Ee=Ae=null,Na=!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 nd&&a.locale!=="ko"?null:a.data;default:return null}}var dh={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 rd(i){var a=i&&i.nodeName&&i.nodeName.toLowerCase();return a==="input"?!!dh[i.type]:a==="textarea"}function Mc(i,a,d,p){tt(p),a=Fc(a,"onChange"),0<a.length&&(d=new Ft("onChange","change",null,d,p),i.push({event:d,listeners:a}))}var ui=null,Ai=null;function Ca(i){cd(i,0)}function io(i){var a=Oa(i);if(ut(a))return i}function Rc(i,a){if(i==="change")return a}var Lc=!1;if(u){var Ic;if(u){var Do="oninput"in document;if(!Do){var id=document.createElement("div");id.setAttribute("oninput","return;"),Do=typeof id.oninput=="function"}Ic=Do}else Ic=!1;Lc=Ic&&(!document.documentMode||9<document.documentMode)}function Ea(){ui&&(ui.detachEvent("onpropertychange",$a),Ai=ui=null)}function $a(i){if(i.propertyName==="value"&&io(Ai)){var a=[];Mc(a,Ai,i,Ss(i)),Et(Ca,a)}}function R_(i,a,d){i==="focusin"?(Ea(),ui=a,Ai=d,ui.attachEvent("onpropertychange",$a)):i==="focusout"&&Ea()}function od(i){if(i==="selectionchange"||i==="keyup"||i==="keydown")return io(Ai)}function L_(i,a){if(i==="click")return io(a)}function I_(i,a){if(i==="input"||i==="change")return io(a)}function Oc(i,a){return i===a&&(i!==0||1/i===1/a)||i!==i&&a!==a}var es=typeof Object.is=="function"?Object.is:Oc;function di(i,a){if(es(i,a))return!0;if(typeof i!="object"||i===null||typeof a!="object"||a===null)return!1;var d=Object.keys(i),p=Object.keys(a);if(d.length!==p.length)return!1;for(p=0;p<d.length;p++){var x=d[p];if(!f.call(a,x)||!es(i[x],a[x]))return!1}return!0}function fh(i){for(;i&&i.firstChild;)i=i.firstChild;return i}function xl(i,a){var d=fh(i);i=0;for(var p;d;){if(d.nodeType===3){if(p=i+d.textContent.length,i<=a&&p>=a)return{node:d,offset:a-i};i=p}e:{for(;d;){if(d.nextSibling){d=d.nextSibling;break e}d=d.parentNode}d=void 0}d=fh(d)}}function hh(i,a){return i&&a?i===a?!0:i&&i.nodeType===3?!1:a&&a.nodeType===3?hh(i,a.parentNode):"contains"in i?i.contains(a):i.compareDocumentPosition?!!(i.compareDocumentPosition(a)&16):!1:!1}function Pc(){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 Fo(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 Or(i){var a=Pc(),d=i.focusedElem,p=i.selectionRange;if(a!==d&&d&&d.ownerDocument&&hh(d.ownerDocument.documentElement,d)){if(p!==null&&Fo(d)){if(a=p.start,i=p.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 x=d.textContent.length,j=Math.min(p.start,x);p=p.end===void 0?j:Math.min(p.end,x),!i.extend&&j>p&&(x=p,p=j,j=x),x=xl(d,j);var P=xl(d,p);x&&P&&(i.rangeCount!==1||i.anchorNode!==x.node||i.anchorOffset!==x.offset||i.focusNode!==P.node||i.focusOffset!==P.offset)&&(a=a.createRange(),a.setStart(x.node,x.offset),i.removeAllRanges(),j>p?(i.addRange(a),i.extend(P.node,P.offset)):(a.setEnd(P.node,P.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 oo=u&&"documentMode"in document&&11>=document.documentMode,Ti=null,ao=null,zo=null,Bo=!1;function Mi(i,a,d){var p=d.window===d?d.document:d.nodeType===9?d:d.ownerDocument;Bo||Ti==null||Ti!==Fe(p)||(p=Ti,"selectionStart"in p&&Fo(p)?p={start:p.selectionStart,end:p.selectionEnd}:(p=(p.ownerDocument&&p.ownerDocument.defaultView||window).getSelection(),p={anchorNode:p.anchorNode,anchorOffset:p.anchorOffset,focusNode:p.focusNode,focusOffset:p.focusOffset}),zo&&di(zo,p)||(zo=p,p=Fc(ao,"onSelect"),0<p.length&&(a=new Ft("onSelect","select",null,a,d),i.push({event:a,listeners:p}),a.target=Ti)))}function Uo(i,a){var d={};return d[i.toLowerCase()]=a.toLowerCase(),d["Webkit"+i]="webkit"+a,d["Moz"+i]="moz"+a,d}var fi={animationend:Uo("Animation","AnimationEnd"),animationiteration:Uo("Animation","AnimationIteration"),animationstart:Uo("Animation","AnimationStart"),transitionend:Uo("Transition","TransitionEnd")},lo={},Ri={};u&&(Ri=document.createElement("div").style,"AnimationEvent"in window||(delete fi.animationend.animation,delete fi.animationiteration.animation,delete fi.animationstart.animation),"TransitionEvent"in window||delete fi.transitionend.transition);function _s(i){if(lo[i])return lo[i];if(!fi[i])return i;var a=fi[i],d;for(d in a)if(a.hasOwnProperty(d)&&d in Ri)return lo[i]=a[d];return i}var co=_s("animationend"),Wo=_s("animationiteration"),bl=_s("animationstart"),uo=_s("transitionend"),Dc=new Map,kl="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 ps(i,a){Dc.set(i,a),l(a,[i])}for(var hi=0;hi<kl.length;hi++){var Pr=kl[hi],mh=Pr.toLowerCase(),jl=Pr[0].toUpperCase()+Pr.slice(1);ps(mh,"on"+jl)}ps(co,"onAnimationEnd"),ps(Wo,"onAnimationIteration"),ps(bl,"onAnimationStart"),ps("dblclick","onDoubleClick"),ps("focusin","onFocus"),ps("focusout","onBlur"),ps(uo,"onTransitionEnd"),c("onMouseEnter",["mouseout","mouseover"]),c("onMouseLeave",["mouseout","mouseover"]),c("onPointerEnter",["pointerout","pointerover"]),c("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 Aa="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(" "),ad=new Set("cancel close invalid load scroll toggle".split(" ").concat(Aa));function ld(i,a,d){var p=i.type||"unknown-event";i.currentTarget=d,rn(p,a,void 0,i),i.currentTarget=null}function cd(i,a){a=(a&4)!==0;for(var d=0;d<i.length;d++){var p=i[d],x=p.event;p=p.listeners;e:{var j=void 0;if(a)for(var P=p.length-1;0<=P;P--){var ne=p[P],oe=ne.instance,ve=ne.currentTarget;if(ne=ne.listener,oe!==j&&x.isPropagationStopped())break e;ld(x,ne,ve),j=oe}else for(P=0;P<p.length;P++){if(ne=p[P],oe=ne.instance,ve=ne.currentTarget,ne=ne.listener,oe!==j&&x.isPropagationStopped())break e;ld(x,ne,ve),j=oe}}}if(Dt)throw i=qe,Dt=!1,qe=null,i}function Sn(i,a){var d=a[El];d===void 0&&(d=a[El]=new Set);var p=i+"__bubble";d.has(p)||(dd(a,i,2,!1),d.add(p))}function ud(i,a,d){var p=0;a&&(p|=4),dd(d,i,p,a)}var Sl="_reactListening"+Math.random().toString(36).slice(2);function Nl(i){if(!i[Sl]){i[Sl]=!0,r.forEach(function(d){d!=="selectionchange"&&(ad.has(d)||ud(d,!1,i),ud(d,!0,i))});var a=i.nodeType===9?i:i.ownerDocument;a===null||a[Sl]||(a[Sl]=!0,ud("selectionchange",!1,a))}}function dd(i,a,d,p){switch(je(a)){case 1:var x=li;break;case 4:x=ja;break;default:x=ci}d=x.bind(null,a,d,i),x=void 0,!St||a!=="touchstart"&&a!=="touchmove"&&a!=="wheel"||(x=!0),p?x!==void 0?i.addEventListener(a,d,{capture:!0,passive:x}):i.addEventListener(a,d,!0):x!==void 0?i.addEventListener(a,d,{passive:x}):i.addEventListener(a,d,!1)}function fd(i,a,d,p,x){var j=p;if((a&1)===0&&(a&2)===0&&p!==null)e:for(;;){if(p===null)return;var P=p.tag;if(P===3||P===4){var ne=p.stateNode.containerInfo;if(ne===x||ne.nodeType===8&&ne.parentNode===x)break;if(P===4)for(P=p.return;P!==null;){var oe=P.tag;if((oe===3||oe===4)&&(oe=P.stateNode.containerInfo,oe===x||oe.nodeType===8&&oe.parentNode===x))return;P=P.return}for(;ne!==null;){if(P=Dr(ne),P===null)return;if(oe=P.tag,oe===5||oe===6){p=j=P;continue e}ne=ne.parentNode}}p=p.return}Et(function(){var ve=j,Le=Ss(d),Oe=[];e:{var Re=Dc.get(i);if(Re!==void 0){var nt=Ft,ot=i;switch(i){case"keypress":if(_t(d)===0)break e;case"keydown":case"keyup":nt=ed;break;case"focusin":ot="focus",nt=yl;break;case"focusout":ot="blur",nt=yl;break;case"beforeblur":case"afterblur":nt=yl;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":nt=$i;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":nt=rh;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":nt=td;break;case co:case Wo:case bl:nt=$c;break;case uo:nt=er;break;case"scroll":nt=En;break;case"wheel":nt=oh;break;case"copy":case"cut":case"paste":nt=ih;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":nt=Tc}var at=(a&4)!==0,ts=!at&&i==="scroll",pe=at?Re!==null?Re+"Capture":null:Re;at=[];for(var ue=ve,we;ue!==null;){we=ue;var ze=we.stateNode;if(we.tag===5&&ze!==null&&(we=ze,pe!==null&&(ze=Zt(ue,pe),ze!=null&&at.push(Ta(ue,ze,we)))),ts)break;ue=ue.return}0<at.length&&(Re=new nt(Re,ot,null,d,Le),Oe.push({event:Re,listeners:at}))}}if((a&7)===0){e:{if(Re=i==="mouseover"||i==="pointerover",nt=i==="mouseout"||i==="pointerout",Re&&d!==Kn&&(ot=d.relatedTarget||d.fromElement)&&(Dr(ot)||ot[mi]))break e;if((nt||Re)&&(Re=Le.window===Le?Le:(Re=Le.ownerDocument)?Re.defaultView||Re.parentWindow:window,nt?(ot=d.relatedTarget||d.toElement,nt=ve,ot=ot?Dr(ot):null,ot!==null&&(ts=gt(ot),ot!==ts||ot.tag!==5&&ot.tag!==6)&&(ot=null)):(nt=null,ot=ve),nt!==ot)){if(at=$i,ze="onMouseLeave",pe="onMouseEnter",ue="mouse",(i==="pointerout"||i==="pointerover")&&(at=Tc,ze="onPointerLeave",pe="onPointerEnter",ue="pointer"),ts=nt==null?Re:Oa(nt),we=ot==null?Re:Oa(ot),Re=new at(ze,ue+"leave",nt,d,Le),Re.target=ts,Re.relatedTarget=we,ze=null,Dr(Le)===ve&&(at=new at(pe,ue+"enter",ot,d,Le),at.target=we,at.relatedTarget=ts,ze=at),ts=ze,nt&&ot)t:{for(at=nt,pe=ot,ue=0,we=at;we;we=qo(we))ue++;for(we=0,ze=pe;ze;ze=qo(ze))we++;for(;0<ue-we;)at=qo(at),ue--;for(;0<we-ue;)pe=qo(pe),we--;for(;ue--;){if(at===pe||pe!==null&&at===pe.alternate)break t;at=qo(at),pe=qo(pe)}at=null}else at=null;nt!==null&&_h(Oe,Re,nt,at,!1),ot!==null&&ts!==null&&_h(Oe,ts,ot,at,!0)}}e:{if(Re=ve?Oa(ve):window,nt=Re.nodeName&&Re.nodeName.toLowerCase(),nt==="select"||nt==="input"&&Re.type==="file")var ft=Rc;else if(rd(Re))if(Lc)ft=I_;else{ft=od;var bt=R_}else(nt=Re.nodeName)&&nt.toLowerCase()==="input"&&(Re.type==="checkbox"||Re.type==="radio")&&(ft=L_);if(ft&&(ft=ft(i,ve))){Mc(Oe,ft,d,Le);break e}bt&&bt(i,Re,ve),i==="focusout"&&(bt=Re._wrapperState)&&bt.controlled&&Re.type==="number"&&Pe(Re,"number",Re.value)}switch(bt=ve?Oa(ve):window,i){case"focusin":(rd(bt)||bt.contentEditable==="true")&&(Ti=bt,ao=ve,zo=null);break;case"focusout":zo=ao=Ti=null;break;case"mousedown":Bo=!0;break;case"contextmenu":case"mouseup":case"dragend":Bo=!1,Mi(Oe,d,Le);break;case"selectionchange":if(oo)break;case"keydown":case"keyup":Mi(Oe,d,Le)}var kt;if(ro)e:{switch(i){case"compositionstart":var Mt="onCompositionStart";break e;case"compositionend":Mt="onCompositionEnd";break e;case"compositionupdate":Mt="onCompositionUpdate";break e}Mt=void 0}else Na?ch(i,d)&&(Mt="onCompositionEnd"):i==="keydown"&&d.keyCode===229&&(Mt="onCompositionStart");Mt&&(nd&&d.locale!=="ko"&&(Na||Mt!=="onCompositionStart"?Mt==="onCompositionEnd"&&Na&&(kt=yt()):(Ae=Le,Ee="value"in Ae?Ae.value:Ae.textContent,Na=!0)),bt=Fc(ve,Mt),0<bt.length&&(Mt=new Ju(Mt,i,null,d,Le),Oe.push({event:Mt,listeners:bt}),kt?Mt.data=kt:(kt=sd(d),kt!==null&&(Mt.data=kt)))),(kt=vl?uh(i,d):M_(i,d))&&(ve=Fc(ve,"onBeforeInput"),0<ve.length&&(Le=new Ju("onBeforeInput","beforeinput",null,d,Le),Oe.push({event:Le,listeners:ve}),Le.data=kt))}cd(Oe,a)})}function Ta(i,a,d){return{instance:i,listener:a,currentTarget:d}}function Fc(i,a){for(var d=a+"Capture",p=[];i!==null;){var x=i,j=x.stateNode;x.tag===5&&j!==null&&(x=j,j=Zt(i,d),j!=null&&p.unshift(Ta(i,j,x)),j=Zt(i,a),j!=null&&p.push(Ta(i,j,x))),i=i.return}return p}function qo(i){if(i===null)return null;do i=i.return;while(i&&i.tag!==5);return i||null}function _h(i,a,d,p,x){for(var j=a._reactName,P=[];d!==null&&d!==p;){var ne=d,oe=ne.alternate,ve=ne.stateNode;if(oe!==null&&oe===p)break;ne.tag===5&&ve!==null&&(ne=ve,x?(oe=Zt(d,j),oe!=null&&P.unshift(Ta(d,oe,ne))):x||(oe=Zt(d,j),oe!=null&&P.push(Ta(d,oe,ne)))),d=d.return}P.length!==0&&i.push({event:a,listeners:P})}var ph=/\r\n?/g,Cl=/\u0000|\uFFFD/g;function gh(i){return(typeof i=="string"?i:""+i).replace(ph,`
|
|
38
|
-
`).replace(Cl,"")}function fo(i,a,d){if(a=gh(a),gh(i)!==a&&d)throw Error(n(425))}function Ma(){}var Ra=null,zc=null;function ho(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 hd=typeof setTimeout=="function"?setTimeout:void 0,Bc=typeof clearTimeout=="function"?clearTimeout:void 0,yh=typeof Promise=="function"?Promise:void 0,La=typeof queueMicrotask=="function"?queueMicrotask:typeof yh<"u"?function(i){return yh.resolve(null).then(i).catch(O_)}:hd;function O_(i){setTimeout(function(){throw i})}function Ia(i,a){var d=a,p=0;do{var x=d.nextSibling;if(i.removeChild(d),x&&x.nodeType===8)if(d=x.data,d==="/$"){if(p===0){i.removeChild(x),no(a);return}p--}else d!=="$"&&d!=="$?"&&d!=="$!"||p++;d=x}while(d);no(a)}function mo(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 Li(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 Ho=Math.random().toString(36).slice(2),tr="__reactFiber$"+Ho,Ii="__reactProps$"+Ho,mi="__reactContainer$"+Ho,El="__reactEvents$"+Ho,$l="__reactListeners$"+Ho,md="__reactHandles$"+Ho;function Dr(i){var a=i[tr];if(a)return a;for(var d=i.parentNode;d;){if(a=d[mi]||d[tr]){if(d=a.alternate,a.child!==null||d!==null&&d.child!==null)for(i=Li(i);i!==null;){if(d=i[tr])return d;i=Li(i)}return a}i=d,d=i.parentNode}return null}function Vo(i){return i=i[tr]||i[mi],!i||i.tag!==5&&i.tag!==6&&i.tag!==13&&i.tag!==3?null:i}function Oa(i){if(i.tag===5||i.tag===6)return i.stateNode;throw Error(n(33))}function Pa(i){return i[Ii]||null}var Al=[],Da=-1;function _o(i){return{current:i}}function _n(i){0>Da||(i.current=Al[Da],Al[Da]=null,Da--)}function Wt(i,a){Da++,Al[Da]=i.current,i.current=a}var Jr={},is=_o(Jr),nr=_o(!1),Go=Jr;function po(i,a){var d=i.type.contextTypes;if(!d)return Jr;var p=i.stateNode;if(p&&p.__reactInternalMemoizedUnmaskedChildContext===a)return p.__reactInternalMemoizedMaskedChildContext;var x={},j;for(j in d)x[j]=a[j];return p&&(i=i.stateNode,i.__reactInternalMemoizedUnmaskedChildContext=a,i.__reactInternalMemoizedMaskedChildContext=x),x}function sr(i){return i=i.childContextTypes,i!=null}function Ko(){_n(nr),_n(is)}function _d(i,a,d){if(is.current!==Jr)throw Error(n(168));Wt(is,a),Wt(nr,d)}function Tl(i,a,d){var p=i.stateNode;if(a=a.childContextTypes,typeof p.getChildContext!="function")return d;p=p.getChildContext();for(var x in p)if(!(x in a))throw Error(n(108,fe(i)||"Unknown",x));return V({},d,p)}function Ml(i){return i=(i=i.stateNode)&&i.__reactInternalMemoizedMergedChildContext||Jr,Go=is.current,Wt(is,i),Wt(nr,nr.current),!0}function pd(i,a,d){var p=i.stateNode;if(!p)throw Error(n(169));d?(i=Tl(i,a,Go),p.__reactInternalMemoizedMergedChildContext=i,_n(nr),_n(is),Wt(is,i)):_n(nr),Wt(nr,d)}var Oi=null,Rl=!1,Uc=!1;function gd(i){Oi===null?Oi=[i]:Oi.push(i)}function P_(i){Rl=!0,gd(i)}function Pi(){if(!Uc&&Oi!==null){Uc=!0;var i=0,a=un;try{var d=Oi;for(un=1;i<d.length;i++){var p=d[i];do p=p(!0);while(p!==null)}Oi=null,Rl=!1}catch(x){throw Oi!==null&&(Oi=Oi.slice(i+1)),hr(Xi,Pi),x}finally{un=a,Uc=!1}}return null}var Di=[],Fa=0,Wc=null,qc=0,Fr=[],rr=0,Yo=null,Xr=1,Fi="";function go(i,a){Di[Fa++]=qc,Di[Fa++]=Wc,Wc=i,qc=a}function wh(i,a,d){Fr[rr++]=Xr,Fr[rr++]=Fi,Fr[rr++]=Yo,Yo=i;var p=Xr;i=Fi;var x=32-ss(p)-1;p&=~(1<<x),d+=1;var j=32-ss(a)+x;if(30<j){var P=x-x%5;j=(p&(1<<P)-1).toString(32),p>>=P,x-=P,Xr=1<<32-ss(a)+x|d<<x|p,Fi=j+i}else Xr=1<<j|d<<x|p,Fi=i}function Ll(i){i.return!==null&&(go(i,1),wh(i,1,0))}function De(i){for(;i===Wc;)Wc=Di[--Fa],Di[Fa]=null,qc=Di[--Fa],Di[Fa]=null;for(;i===Yo;)Yo=Fr[--rr],Fr[rr]=null,Fi=Fr[--rr],Fr[rr]=null,Xr=Fr[--rr],Fr[rr]=null}var fn=null,zs=null,$n=!1,vr=null;function vh(i,a){var d=vi(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 xh(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,fn=i,zs=mo(a.firstChild),!0):!1;case 6:return a=i.pendingProps===""||a.nodeType!==3?null:a,a!==null?(i.stateNode=a,fn=i,zs=null,!0):!1;case 13:return a=a.nodeType!==8?null:a,a!==null?(d=Yo!==null?{id:Xr,overflow:Fi}:null,i.memoizedState={dehydrated:a,treeContext:d,retryLane:1073741824},d=vi(18,null,null,0),d.stateNode=a,d.return=i,i.child=d,fn=i,zs=null,!0):!1;default:return!1}}function yd(i){return(i.mode&1)!==0&&(i.flags&128)===0}function Hc(i){if($n){var a=zs;if(a){var d=a;if(!xh(i,a)){if(yd(i))throw Error(n(418));a=mo(d.nextSibling);var p=fn;a&&xh(i,a)?vh(p,d):(i.flags=i.flags&-4097|2,$n=!1,fn=i)}}else{if(yd(i))throw Error(n(418));i.flags=i.flags&-4097|2,$n=!1,fn=i}}}function wd(i){for(i=i.return;i!==null&&i.tag!==5&&i.tag!==3&&i.tag!==13;)i=i.return;fn=i}function Vc(i){if(i!==fn)return!1;if(!$n)return wd(i),$n=!0,!1;var a;if((a=i.tag!==3)&&!(a=i.tag!==5)&&(a=i.type,a=a!=="head"&&a!=="body"&&!ho(i.type,i.memoizedProps)),a&&(a=zs)){if(yd(i))throw Il(),Error(n(418));for(;a;)vh(i,a),a=mo(a.nextSibling)}if(wd(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){zs=mo(i.nextSibling);break e}a--}else d!=="$"&&d!=="$!"&&d!=="$?"||a++}i=i.nextSibling}zs=null}}else zs=fn?mo(i.stateNode.nextSibling):null;return!0}function Il(){for(var i=zs;i;)i=mo(i.nextSibling)}function Jo(){zs=fn=null,$n=!1}function gs(i){vr===null?vr=[i]:vr.push(i)}var Vt=A.ReactCurrentBatchConfig;function Yn(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 p=d.stateNode}if(!p)throw Error(n(147,i));var x=p,j=""+i;return a!==null&&a.ref!==null&&typeof a.ref=="function"&&a.ref._stringRef===j?a.ref:(a=function(P){var ne=x.refs;P===null?delete ne[j]:ne[j]=P},a._stringRef=j,a)}if(typeof i!="string")throw Error(n(284));if(!d._owner)throw Error(n(290,i))}return i}function za(i,a){throw i=Object.prototype.toString.call(a),Error(n(31,i==="[object Object]"?"object with keys {"+Object.keys(a).join(", ")+"}":i))}function vd(i){var a=i._init;return a(i._payload)}function Ba(i){function a(pe,ue){if(i){var we=pe.deletions;we===null?(pe.deletions=[ue],pe.flags|=16):we.push(ue)}}function d(pe,ue){if(!i)return null;for(;ue!==null;)a(pe,ue),ue=ue.sibling;return null}function p(pe,ue){for(pe=new Map;ue!==null;)ue.key!==null?pe.set(ue.key,ue):pe.set(ue.index,ue),ue=ue.sibling;return pe}function x(pe,ue){return pe=sl(pe,ue),pe.index=0,pe.sibling=null,pe}function j(pe,ue,we){return pe.index=we,i?(we=pe.alternate,we!==null?(we=we.index,we<ue?(pe.flags|=2,ue):we):(pe.flags|=2,ue)):(pe.flags|=1048576,ue)}function P(pe){return i&&pe.alternate===null&&(pe.flags|=2),pe}function ne(pe,ue,we,ze){return ue===null||ue.tag!==6?(ue=q_(we,pe.mode,ze),ue.return=pe,ue):(ue=x(ue,we),ue.return=pe,ue)}function oe(pe,ue,we,ze){var ft=we.type;return ft===J?Le(pe,ue,we.props.children,ze,we.key):ue!==null&&(ue.elementType===ft||typeof ft=="object"&&ft!==null&&ft.$$typeof===M&&vd(ft)===ue.type)?(ze=x(ue,we.props),ze.ref=Yn(pe,ue,we),ze.return=pe,ze):(ze=Jh(we.type,we.key,we.props,null,pe.mode,ze),ze.ref=Yn(pe,ue,we),ze.return=pe,ze)}function ve(pe,ue,we,ze){return ue===null||ue.tag!==4||ue.stateNode.containerInfo!==we.containerInfo||ue.stateNode.implementation!==we.implementation?(ue=H_(we,pe.mode,ze),ue.return=pe,ue):(ue=x(ue,we.children||[]),ue.return=pe,ue)}function Le(pe,ue,we,ze,ft){return ue===null||ue.tag!==7?(ue=nc(we,pe.mode,ze,ft),ue.return=pe,ue):(ue=x(ue,we),ue.return=pe,ue)}function Oe(pe,ue,we){if(typeof ue=="string"&&ue!==""||typeof ue=="number")return ue=q_(""+ue,pe.mode,we),ue.return=pe,ue;if(typeof ue=="object"&&ue!==null){switch(ue.$$typeof){case W:return we=Jh(ue.type,ue.key,ue.props,null,pe.mode,we),we.ref=Yn(pe,null,ue),we.return=pe,we;case z:return ue=H_(ue,pe.mode,we),ue.return=pe,ue;case M:var ze=ue._init;return Oe(pe,ze(ue._payload),we)}if(me(ue)||U(ue))return ue=nc(ue,pe.mode,we,null),ue.return=pe,ue;za(pe,ue)}return null}function Re(pe,ue,we,ze){var ft=ue!==null?ue.key:null;if(typeof we=="string"&&we!==""||typeof we=="number")return ft!==null?null:ne(pe,ue,""+we,ze);if(typeof we=="object"&&we!==null){switch(we.$$typeof){case W:return we.key===ft?oe(pe,ue,we,ze):null;case z:return we.key===ft?ve(pe,ue,we,ze):null;case M:return ft=we._init,Re(pe,ue,ft(we._payload),ze)}if(me(we)||U(we))return ft!==null?null:Le(pe,ue,we,ze,null);za(pe,we)}return null}function nt(pe,ue,we,ze,ft){if(typeof ze=="string"&&ze!==""||typeof ze=="number")return pe=pe.get(we)||null,ne(ue,pe,""+ze,ft);if(typeof ze=="object"&&ze!==null){switch(ze.$$typeof){case W:return pe=pe.get(ze.key===null?we:ze.key)||null,oe(ue,pe,ze,ft);case z:return pe=pe.get(ze.key===null?we:ze.key)||null,ve(ue,pe,ze,ft);case M:var bt=ze._init;return nt(pe,ue,we,bt(ze._payload),ft)}if(me(ze)||U(ze))return pe=pe.get(we)||null,Le(ue,pe,ze,ft,null);za(ue,ze)}return null}function ot(pe,ue,we,ze){for(var ft=null,bt=null,kt=ue,Mt=ue=0,Ms=null;kt!==null&&Mt<we.length;Mt++){kt.index>Mt?(Ms=kt,kt=null):Ms=kt.sibling;var pn=Re(pe,kt,we[Mt],ze);if(pn===null){kt===null&&(kt=Ms);break}i&&kt&&pn.alternate===null&&a(pe,kt),ue=j(pn,ue,Mt),bt===null?ft=pn:bt.sibling=pn,bt=pn,kt=Ms}if(Mt===we.length)return d(pe,kt),$n&&go(pe,Mt),ft;if(kt===null){for(;Mt<we.length;Mt++)kt=Oe(pe,we[Mt],ze),kt!==null&&(ue=j(kt,ue,Mt),bt===null?ft=kt:bt.sibling=kt,bt=kt);return $n&&go(pe,Mt),ft}for(kt=p(pe,kt);Mt<we.length;Mt++)Ms=nt(kt,pe,Mt,we[Mt],ze),Ms!==null&&(i&&Ms.alternate!==null&&kt.delete(Ms.key===null?Mt:Ms.key),ue=j(Ms,ue,Mt),bt===null?ft=Ms:bt.sibling=Ms,bt=Ms);return i&&kt.forEach(function(rl){return a(pe,rl)}),$n&&go(pe,Mt),ft}function at(pe,ue,we,ze){var ft=U(we);if(typeof ft!="function")throw Error(n(150));if(we=ft.call(we),we==null)throw Error(n(151));for(var bt=ft=null,kt=ue,Mt=ue=0,Ms=null,pn=we.next();kt!==null&&!pn.done;Mt++,pn=we.next()){kt.index>Mt?(Ms=kt,kt=null):Ms=kt.sibling;var rl=Re(pe,kt,pn.value,ze);if(rl===null){kt===null&&(kt=Ms);break}i&&kt&&rl.alternate===null&&a(pe,kt),ue=j(rl,ue,Mt),bt===null?ft=rl:bt.sibling=rl,bt=rl,kt=Ms}if(pn.done)return d(pe,kt),$n&&go(pe,Mt),ft;if(kt===null){for(;!pn.done;Mt++,pn=we.next())pn=Oe(pe,pn.value,ze),pn!==null&&(ue=j(pn,ue,Mt),bt===null?ft=pn:bt.sibling=pn,bt=pn);return $n&&go(pe,Mt),ft}for(kt=p(pe,kt);!pn.done;Mt++,pn=we.next())pn=nt(kt,pe,Mt,pn.value,ze),pn!==null&&(i&&pn.alternate!==null&&kt.delete(pn.key===null?Mt:pn.key),ue=j(pn,ue,Mt),bt===null?ft=pn:bt.sibling=pn,bt=pn);return i&&kt.forEach(function(Pj){return a(pe,Pj)}),$n&&go(pe,Mt),ft}function ts(pe,ue,we,ze){if(typeof we=="object"&&we!==null&&we.type===J&&we.key===null&&(we=we.props.children),typeof we=="object"&&we!==null){switch(we.$$typeof){case W:e:{for(var ft=we.key,bt=ue;bt!==null;){if(bt.key===ft){if(ft=we.type,ft===J){if(bt.tag===7){d(pe,bt.sibling),ue=x(bt,we.props.children),ue.return=pe,pe=ue;break e}}else if(bt.elementType===ft||typeof ft=="object"&&ft!==null&&ft.$$typeof===M&&vd(ft)===bt.type){d(pe,bt.sibling),ue=x(bt,we.props),ue.ref=Yn(pe,bt,we),ue.return=pe,pe=ue;break e}d(pe,bt);break}else a(pe,bt);bt=bt.sibling}we.type===J?(ue=nc(we.props.children,pe.mode,ze,we.key),ue.return=pe,pe=ue):(ze=Jh(we.type,we.key,we.props,null,pe.mode,ze),ze.ref=Yn(pe,ue,we),ze.return=pe,pe=ze)}return P(pe);case z:e:{for(bt=we.key;ue!==null;){if(ue.key===bt)if(ue.tag===4&&ue.stateNode.containerInfo===we.containerInfo&&ue.stateNode.implementation===we.implementation){d(pe,ue.sibling),ue=x(ue,we.children||[]),ue.return=pe,pe=ue;break e}else{d(pe,ue);break}else a(pe,ue);ue=ue.sibling}ue=H_(we,pe.mode,ze),ue.return=pe,pe=ue}return P(pe);case M:return bt=we._init,ts(pe,ue,bt(we._payload),ze)}if(me(we))return ot(pe,ue,we,ze);if(U(we))return at(pe,ue,we,ze);za(pe,we)}return typeof we=="string"&&we!==""||typeof we=="number"?(we=""+we,ue!==null&&ue.tag===6?(d(pe,ue.sibling),ue=x(ue,we),ue.return=pe,pe=ue):(d(pe,ue),ue=q_(we,pe.mode,ze),ue.return=pe,pe=ue),P(pe)):d(pe,ue)}return ts}var Zr=Ba(!0),Ot=Ba(!1),Gc=_o(null),Ua=null,Wa=null,xd=null;function bd(){xd=Wa=Ua=null}function kd(i){var a=Gc.current;_n(Gc),i._currentValue=a}function Ol(i,a,d){for(;i!==null;){var p=i.alternate;if((i.childLanes&a)!==a?(i.childLanes|=a,p!==null&&(p.childLanes|=a)):p!==null&&(p.childLanes&a)!==a&&(p.childLanes|=a),i===d)break;i=i.return}}function ir(i,a){Ua=i,xd=Wa=null,i=i.dependencies,i!==null&&i.firstContext!==null&&((i.lanes&a)!==0&&(ar=!0),i.firstContext=null)}function xr(i){var a=i._currentValue;if(xd!==i)if(i={context:i,memoizedValue:a,next:null},Wa===null){if(Ua===null)throw Error(n(308));Wa=i,Ua.dependencies={lanes:0,firstContext:i}}else Wa=Wa.next=i;return a}var br=null;function kr(i){br===null?br=[i]:br.push(i)}function Pl(i,a,d,p){var x=a.interleaved;return x===null?(d.next=d,kr(a)):(d.next=x.next,x.next=d),a.interleaved=d,zi(i,p)}function zi(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 yo=!1;function Dl(i){i.updateQueue={baseState:i.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function jd(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 Qr(i,a){return{eventTime:i,lane:a,tag:0,payload:null,callback:null,next:null}}function wo(i,a,d){var p=i.updateQueue;if(p===null)return null;if(p=p.shared,(tn&2)!==0){var x=p.pending;return x===null?a.next=a:(a.next=x.next,x.next=a),p.pending=a,zi(i,d)}return x=p.interleaved,x===null?(a.next=a,kr(p)):(a.next=x.next,x.next=a),p.interleaved=a,zi(i,d)}function Ln(i,a,d){if(a=a.updateQueue,a!==null&&(a=a.shared,(d&4194240)!==0)){var p=a.lanes;p&=i.pendingLanes,d|=p,a.lanes=d,Qi(i,d)}}function Sd(i,a){var d=i.updateQueue,p=i.alternate;if(p!==null&&(p=p.updateQueue,d===p)){var x=null,j=null;if(d=d.firstBaseUpdate,d!==null){do{var P={eventTime:d.eventTime,lane:d.lane,tag:d.tag,payload:d.payload,callback:d.callback,next:null};j===null?x=j=P:j=j.next=P,d=d.next}while(d!==null);j===null?x=j=a:j=j.next=a}else x=j=a;d={baseState:p.baseState,firstBaseUpdate:x,lastBaseUpdate:j,shared:p.shared,effects:p.effects},i.updateQueue=d;return}i=d.lastBaseUpdate,i===null?d.firstBaseUpdate=a:i.next=a,d.lastBaseUpdate=a}function qa(i,a,d,p){var x=i.updateQueue;yo=!1;var j=x.firstBaseUpdate,P=x.lastBaseUpdate,ne=x.shared.pending;if(ne!==null){x.shared.pending=null;var oe=ne,ve=oe.next;oe.next=null,P===null?j=ve:P.next=ve,P=oe;var Le=i.alternate;Le!==null&&(Le=Le.updateQueue,ne=Le.lastBaseUpdate,ne!==P&&(ne===null?Le.firstBaseUpdate=ve:ne.next=ve,Le.lastBaseUpdate=oe))}if(j!==null){var Oe=x.baseState;P=0,Le=ve=oe=null,ne=j;do{var Re=ne.lane,nt=ne.eventTime;if((p&Re)===Re){Le!==null&&(Le=Le.next={eventTime:nt,lane:0,tag:ne.tag,payload:ne.payload,callback:ne.callback,next:null});e:{var ot=i,at=ne;switch(Re=a,nt=d,at.tag){case 1:if(ot=at.payload,typeof ot=="function"){Oe=ot.call(nt,Oe,Re);break e}Oe=ot;break e;case 3:ot.flags=ot.flags&-65537|128;case 0:if(ot=at.payload,Re=typeof ot=="function"?ot.call(nt,Oe,Re):ot,Re==null)break e;Oe=V({},Oe,Re);break e;case 2:yo=!0}}ne.callback!==null&&ne.lane!==0&&(i.flags|=64,Re=x.effects,Re===null?x.effects=[ne]:Re.push(ne))}else nt={eventTime:nt,lane:Re,tag:ne.tag,payload:ne.payload,callback:ne.callback,next:null},Le===null?(ve=Le=nt,oe=Oe):Le=Le.next=nt,P|=Re;if(ne=ne.next,ne===null){if(ne=x.shared.pending,ne===null)break;Re=ne,ne=Re.next,Re.next=null,x.lastBaseUpdate=Re,x.shared.pending=null}}while(!0);if(Le===null&&(oe=Oe),x.baseState=oe,x.firstBaseUpdate=ve,x.lastBaseUpdate=Le,a=x.shared.interleaved,a!==null){x=a;do P|=x.lane,x=x.next;while(x!==a)}else j===null&&(x.shared.lanes=0);jo|=P,i.lanes=P,i.memoizedState=Oe}}function Bs(i,a,d){if(i=a.effects,a.effects=null,i!==null)for(a=0;a<i.length;a++){var p=i[a],x=p.callback;if(x!==null){if(p.callback=null,p=d,typeof x!="function")throw Error(n(191,x));x.call(p)}}}var Ha={},or=_o(Ha),Xo=_o(Ha),Bi=_o(Ha);function Ui(i){if(i===Ha)throw Error(n(174));return i}function Nd(i,a){switch(Wt(Bi,a),Wt(Xo,i),Wt(or,Ha),i=a.nodeType,i){case 9:case 11:a=(a=a.documentElement)?a.namespaceURI:Ct(null,"");break;default:i=i===8?a.parentNode:a,a=i.namespaceURI||null,i=i.tagName,a=Ct(a,i)}_n(or),Wt(or,a)}function Va(){_n(or),_n(Xo),_n(Bi)}function bh(i){Ui(Bi.current);var a=Ui(or.current),d=Ct(a,i.type);a!==d&&(Wt(Xo,i),Wt(or,d))}function Fl(i){Xo.current===i&&(_n(or),_n(Xo))}var In=_o(0);function Kc(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 zl=[];function Cd(){for(var i=0;i<zl.length;i++)zl[i]._workInProgressVersionPrimary=null;zl.length=0}var _i=A.ReactCurrentDispatcher,Ed=A.ReactCurrentBatchConfig,pi=0,Bn=null,Jn=null,Nn=null,Yc=!1,Bl=!1,Ul=0,D_=0;function Cs(){throw Error(n(321))}function $d(i,a){if(a===null)return!1;for(var d=0;d<a.length&&d<i.length;d++)if(!es(i[d],a[d]))return!1;return!0}function Ad(i,a,d,p,x,j){if(pi=j,Bn=a,a.memoizedState=null,a.updateQueue=null,a.lanes=0,_i.current=i===null||i.memoizedState===null?bo:ko,i=d(p,x),Bl){j=0;do{if(Bl=!1,Ul=0,25<=j)throw Error(n(301));j+=1,Nn=Jn=null,a.updateQueue=null,_i.current=ei,i=d(p,x)}while(Bl)}if(_i.current=jr,a=Jn!==null&&Jn.next!==null,pi=0,Nn=Jn=Bn=null,Yc=!1,a)throw Error(n(300));return i}function en(){var i=Ul!==0;return Ul=0,i}function Cn(){var i={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return Nn===null?Bn.memoizedState=Nn=i:Nn=Nn.next=i,Nn}function An(){if(Jn===null){var i=Bn.alternate;i=i!==null?i.memoizedState:null}else i=Jn.next;var a=Nn===null?Bn.memoizedState:Nn.next;if(a!==null)Nn=a,Jn=i;else{if(i===null)throw Error(n(310));Jn=i,i={memoizedState:Jn.memoizedState,baseState:Jn.baseState,baseQueue:Jn.baseQueue,queue:Jn.queue,next:null},Nn===null?Bn.memoizedState=Nn=i:Nn=Nn.next=i}return Nn}function Zo(i,a){return typeof a=="function"?a(i):a}function Ga(i){var a=An(),d=a.queue;if(d===null)throw Error(n(311));d.lastRenderedReducer=i;var p=Jn,x=p.baseQueue,j=d.pending;if(j!==null){if(x!==null){var P=x.next;x.next=j.next,j.next=P}p.baseQueue=x=j,d.pending=null}if(x!==null){j=x.next,p=p.baseState;var ne=P=null,oe=null,ve=j;do{var Le=ve.lane;if((pi&Le)===Le)oe!==null&&(oe=oe.next={lane:0,action:ve.action,hasEagerState:ve.hasEagerState,eagerState:ve.eagerState,next:null}),p=ve.hasEagerState?ve.eagerState:i(p,ve.action);else{var Oe={lane:Le,action:ve.action,hasEagerState:ve.hasEagerState,eagerState:ve.eagerState,next:null};oe===null?(ne=oe=Oe,P=p):oe=oe.next=Oe,Bn.lanes|=Le,jo|=Le}ve=ve.next}while(ve!==null&&ve!==j);oe===null?P=p:oe.next=ne,es(p,a.memoizedState)||(ar=!0),a.memoizedState=p,a.baseState=P,a.baseQueue=oe,d.lastRenderedState=p}if(i=d.interleaved,i!==null){x=i;do j=x.lane,Bn.lanes|=j,jo|=j,x=x.next;while(x!==i)}else x===null&&(d.lanes=0);return[a.memoizedState,d.dispatch]}function Jc(i){var a=An(),d=a.queue;if(d===null)throw Error(n(311));d.lastRenderedReducer=i;var p=d.dispatch,x=d.pending,j=a.memoizedState;if(x!==null){d.pending=null;var P=x=x.next;do j=i(j,P.action),P=P.next;while(P!==x);es(j,a.memoizedState)||(ar=!0),a.memoizedState=j,a.baseQueue===null&&(a.baseState=j),d.lastRenderedState=j}return[j,p]}function kh(){}function jh(i,a){var d=Bn,p=An(),x=a(),j=!es(p.memoizedState,x);if(j&&(p.memoizedState=x,ar=!0),p=p.queue,Zc(Sh.bind(null,d,p,i),[i]),p.getSnapshot!==a||j||Nn!==null&&Nn.memoizedState.tag&1){if(d.flags|=2048,Ka(9,Wl.bind(null,d,p,x,a),void 0,null),as===null)throw Error(n(349));(pi&30)!==0||Td(d,a,x)}return x}function Td(i,a,d){i.flags|=16384,i={getSnapshot:a,value:d},a=Bn.updateQueue,a===null?(a={lastEffect:null,stores:null},Bn.updateQueue=a,a.stores=[i]):(d=a.stores,d===null?a.stores=[i]:d.push(i))}function Wl(i,a,d,p){a.value=d,a.getSnapshot=p,Nh(a)&&Ch(i)}function Sh(i,a,d){return d(function(){Nh(a)&&Ch(i)})}function Nh(i){var a=i.getSnapshot;i=i.value;try{var d=a();return!es(i,d)}catch{return!0}}function Ch(i){var a=zi(i,1);a!==null&&Ie(a,i,1,-1)}function Md(i){var a=Cn();return typeof i=="function"&&(i=i()),a.memoizedState=a.baseState=i,i={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:Zo,lastRenderedState:i},a.queue=i,i=i.dispatch=z_.bind(null,Bn,i),[a.memoizedState,i]}function Ka(i,a,d,p){return i={tag:i,create:a,destroy:d,deps:p,next:null},a=Bn.updateQueue,a===null?(a={lastEffect:null,stores:null},Bn.updateQueue=a,a.lastEffect=i.next=i):(d=a.lastEffect,d===null?a.lastEffect=i.next=i:(p=d.next,d.next=i,i.next=p,a.lastEffect=i)),i}function vo(){return An().memoizedState}function Ya(i,a,d,p){var x=Cn();Bn.flags|=i,x.memoizedState=Ka(1|a,d,void 0,p===void 0?null:p)}function ql(i,a,d,p){var x=An();p=p===void 0?null:p;var j=void 0;if(Jn!==null){var P=Jn.memoizedState;if(j=P.destroy,p!==null&&$d(p,P.deps)){x.memoizedState=Ka(a,d,j,p);return}}Bn.flags|=i,x.memoizedState=Ka(1|a,d,j,p)}function Xc(i,a){return Ya(8390656,8,i,a)}function Zc(i,a){return ql(2048,8,i,a)}function Eh(i,a){return ql(4,2,i,a)}function $h(i,a){return ql(4,4,i,a)}function Ah(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 Th(i,a,d){return d=d!=null?d.concat([i]):null,ql(4,4,Ah.bind(null,a,i),d)}function Rd(){}function Mh(i,a){var d=An();a=a===void 0?null:a;var p=d.memoizedState;return p!==null&&a!==null&&$d(a,p[1])?p[0]:(d.memoizedState=[i,a],i)}function Ld(i,a){var d=An();a=a===void 0?null:a;var p=d.memoizedState;return p!==null&&a!==null&&$d(a,p[1])?p[0]:(i=i(),d.memoizedState=[i,a],i)}function Qc(i,a,d){return(pi&21)===0?(i.baseState&&(i.baseState=!1,ar=!0),i.memoizedState=d):(es(d,a)||(d=ds(),Bn.lanes|=d,jo|=d,i.baseState=!0),a)}function F_(i,a){var d=un;un=d!==0&&4>d?d:4,i(!0);var p=Ed.transition;Ed.transition={};try{i(!1),a()}finally{un=d,Ed.transition=p}}function Rh(){return An().memoizedState}function eu(i,a,d){var p=se(i);if(d={lane:p,action:d,hasEagerState:!1,eagerState:null,next:null},xo(i))Es(a,d);else if(d=Pl(i,a,d,p),d!==null){var x=G();Ie(d,i,p,x),os(d,a,p)}}function z_(i,a,d){var p=se(i),x={lane:p,action:d,hasEagerState:!1,eagerState:null,next:null};if(xo(i))Es(a,x);else{var j=i.alternate;if(i.lanes===0&&(j===null||j.lanes===0)&&(j=a.lastRenderedReducer,j!==null))try{var P=a.lastRenderedState,ne=j(P,d);if(x.hasEagerState=!0,x.eagerState=ne,es(ne,P)){var oe=a.interleaved;oe===null?(x.next=x,kr(a)):(x.next=oe.next,oe.next=x),a.interleaved=x;return}}catch{}finally{}d=Pl(i,a,x,p),d!==null&&(x=G(),Ie(d,i,p,x),os(d,a,p))}}function xo(i){var a=i.alternate;return i===Bn||a!==null&&a===Bn}function Es(i,a){Bl=Yc=!0;var d=i.pending;d===null?a.next=a:(a.next=d.next,d.next=a),i.pending=a}function os(i,a,d){if((d&4194240)!==0){var p=a.lanes;p&=i.pendingLanes,d|=p,a.lanes=d,Qi(i,d)}}var jr={readContext:xr,useCallback:Cs,useContext:Cs,useEffect:Cs,useImperativeHandle:Cs,useInsertionEffect:Cs,useLayoutEffect:Cs,useMemo:Cs,useReducer:Cs,useRef:Cs,useState:Cs,useDebugValue:Cs,useDeferredValue:Cs,useTransition:Cs,useMutableSource:Cs,useSyncExternalStore:Cs,useId:Cs,unstable_isNewReconciler:!1},bo={readContext:xr,useCallback:function(i,a){return Cn().memoizedState=[i,a===void 0?null:a],i},useContext:xr,useEffect:Xc,useImperativeHandle:function(i,a,d){return d=d!=null?d.concat([i]):null,Ya(4194308,4,Ah.bind(null,a,i),d)},useLayoutEffect:function(i,a){return Ya(4194308,4,i,a)},useInsertionEffect:function(i,a){return Ya(4,2,i,a)},useMemo:function(i,a){var d=Cn();return a=a===void 0?null:a,i=i(),d.memoizedState=[i,a],i},useReducer:function(i,a,d){var p=Cn();return a=d!==void 0?d(a):a,p.memoizedState=p.baseState=a,i={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:i,lastRenderedState:a},p.queue=i,i=i.dispatch=eu.bind(null,Bn,i),[p.memoizedState,i]},useRef:function(i){var a=Cn();return i={current:i},a.memoizedState=i},useState:Md,useDebugValue:Rd,useDeferredValue:function(i){return Cn().memoizedState=i},useTransition:function(){var i=Md(!1),a=i[0];return i=F_.bind(null,i[1]),Cn().memoizedState=i,[a,i]},useMutableSource:function(){},useSyncExternalStore:function(i,a,d){var p=Bn,x=Cn();if($n){if(d===void 0)throw Error(n(407));d=d()}else{if(d=a(),as===null)throw Error(n(349));(pi&30)!==0||Td(p,a,d)}x.memoizedState=d;var j={value:d,getSnapshot:a};return x.queue=j,Xc(Sh.bind(null,p,j,i),[i]),p.flags|=2048,Ka(9,Wl.bind(null,p,j,d,a),void 0,null),d},useId:function(){var i=Cn(),a=as.identifierPrefix;if($n){var d=Fi,p=Xr;d=(p&~(1<<32-ss(p)-1)).toString(32)+d,a=":"+a+"R"+d,d=Ul++,0<d&&(a+="H"+d.toString(32)),a+=":"}else d=D_++,a=":"+a+"r"+d.toString(32)+":";return i.memoizedState=a},unstable_isNewReconciler:!1},ko={readContext:xr,useCallback:Mh,useContext:xr,useEffect:Zc,useImperativeHandle:Th,useInsertionEffect:Eh,useLayoutEffect:$h,useMemo:Ld,useReducer:Ga,useRef:vo,useState:function(){return Ga(Zo)},useDebugValue:Rd,useDeferredValue:function(i){var a=An();return Qc(a,Jn.memoizedState,i)},useTransition:function(){var i=Ga(Zo)[0],a=An().memoizedState;return[i,a]},useMutableSource:kh,useSyncExternalStore:jh,useId:Rh,unstable_isNewReconciler:!1},ei={readContext:xr,useCallback:Mh,useContext:xr,useEffect:Zc,useImperativeHandle:Th,useInsertionEffect:Eh,useLayoutEffect:$h,useMemo:Ld,useReducer:Jc,useRef:vo,useState:function(){return Jc(Zo)},useDebugValue:Rd,useDeferredValue:function(i){var a=An();return Jn===null?a.memoizedState=i:Qc(a,Jn.memoizedState,i)},useTransition:function(){var i=Jc(Zo)[0],a=An().memoizedState;return[i,a]},useMutableSource:kh,useSyncExternalStore:jh,useId:Rh,unstable_isNewReconciler:!1};function ti(i,a){if(i&&i.defaultProps){a=V({},a),i=i.defaultProps;for(var d in i)a[d]===void 0&&(a[d]=i[d]);return a}return a}function Ja(i,a,d,p){a=i.memoizedState,d=d(p,a),d=d==null?a:V({},a,d),i.memoizedState=d,i.lanes===0&&(i.updateQueue.baseState=d)}var tu={isMounted:function(i){return(i=i._reactInternals)?gt(i)===i:!1},enqueueSetState:function(i,a,d){i=i._reactInternals;var p=G(),x=se(i),j=Qr(p,x);j.payload=a,d!=null&&(j.callback=d),a=wo(i,j,x),a!==null&&(Ie(a,i,x,p),Ln(a,i,x))},enqueueReplaceState:function(i,a,d){i=i._reactInternals;var p=G(),x=se(i),j=Qr(p,x);j.tag=1,j.payload=a,d!=null&&(j.callback=d),a=wo(i,j,x),a!==null&&(Ie(a,i,x,p),Ln(a,i,x))},enqueueForceUpdate:function(i,a){i=i._reactInternals;var d=G(),p=se(i),x=Qr(d,p);x.tag=2,a!=null&&(x.callback=a),a=wo(i,x,p),a!==null&&(Ie(a,i,p,d),Ln(a,i,p))}};function nu(i,a,d,p,x,j,P){return i=i.stateNode,typeof i.shouldComponentUpdate=="function"?i.shouldComponentUpdate(p,j,P):a.prototype&&a.prototype.isPureReactComponent?!di(d,p)||!di(x,j):!0}function Lh(i,a,d){var p=!1,x=Jr,j=a.contextType;return typeof j=="object"&&j!==null?j=xr(j):(x=sr(a)?Go:is.current,p=a.contextTypes,j=(p=p!=null)?po(i,x):Jr),a=new a(d,j),i.memoizedState=a.state!==null&&a.state!==void 0?a.state:null,a.updater=tu,i.stateNode=a,a._reactInternals=i,p&&(i=i.stateNode,i.__reactInternalMemoizedUnmaskedChildContext=x,i.__reactInternalMemoizedMaskedChildContext=j),a}function Ih(i,a,d,p){i=a.state,typeof a.componentWillReceiveProps=="function"&&a.componentWillReceiveProps(d,p),typeof a.UNSAFE_componentWillReceiveProps=="function"&&a.UNSAFE_componentWillReceiveProps(d,p),a.state!==i&&tu.enqueueReplaceState(a,a.state,null)}function su(i,a,d,p){var x=i.stateNode;x.props=d,x.state=i.memoizedState,x.refs={},Dl(i);var j=a.contextType;typeof j=="object"&&j!==null?x.context=xr(j):(j=sr(a)?Go:is.current,x.context=po(i,j)),x.state=i.memoizedState,j=a.getDerivedStateFromProps,typeof j=="function"&&(Ja(i,a,j,d),x.state=i.memoizedState),typeof a.getDerivedStateFromProps=="function"||typeof x.getSnapshotBeforeUpdate=="function"||typeof x.UNSAFE_componentWillMount!="function"&&typeof x.componentWillMount!="function"||(a=x.state,typeof x.componentWillMount=="function"&&x.componentWillMount(),typeof x.UNSAFE_componentWillMount=="function"&&x.UNSAFE_componentWillMount(),a!==x.state&&tu.enqueueReplaceState(x,x.state,null),qa(i,d,x,p),x.state=i.memoizedState),typeof x.componentDidMount=="function"&&(i.flags|=4194308)}function zr(i,a){try{var d="",p=a;do d+=ie(p),p=p.return;while(p);var x=d}catch(j){x=`
|
|
39
|
-
Error generating stack: `+j.message+`
|
|
40
|
-
`+j.stack}return{value:i,source:a,stack:x,digest:null}}function Qo(i,a,d){return{value:i,source:null,stack:d??null,digest:a??null}}function ru(i,a){try{console.error(a.value)}catch(d){setTimeout(function(){throw d})}}var Oh=typeof WeakMap=="function"?WeakMap:Map;function Ph(i,a,d){d=Qr(-1,d),d.tag=3,d.payload={element:null};var p=a.value;return d.callback=function(){Zl||(Zl=!0,gu=p),ru(i,a)},d}function Id(i,a,d){d=Qr(-1,d),d.tag=3;var p=i.type.getDerivedStateFromError;if(typeof p=="function"){var x=a.value;d.payload=function(){return p(x)},d.callback=function(){ru(i,a)}}var j=i.stateNode;return j!==null&&typeof j.componentDidCatch=="function"&&(d.callback=function(){ru(i,a),typeof p!="function"&&(Wi===null?Wi=new Set([this]):Wi.add(this));var P=a.stack;this.componentDidCatch(a.value,{componentStack:P!==null?P:""})}),d}function ea(i,a,d){var p=i.pingCache;if(p===null){p=i.pingCache=new Oh;var x=new Set;p.set(a,x)}else x=p.get(a),x===void 0&&(x=new Set,p.set(a,x));x.has(d)||(x.add(d),i=Nj.bind(null,i,a,d),a.then(i,i))}function Dh(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 Hl(i,a,d,p,x){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=Qr(-1,1),a.tag=2,wo(d,a,1))),d.lanes|=1),i):(i.flags|=65536,i.lanes=x,i)}var Fh=A.ReactCurrentOwner,ar=!1;function ys(i,a,d,p){a.child=i===null?Ot(a,null,d,p):Zr(a,i.child,d,p)}function zh(i,a,d,p,x){d=d.render;var j=a.ref;return ir(a,x),p=Ad(i,a,d,p,j,x),d=en(),i!==null&&!ar?(a.updateQueue=i.updateQueue,a.flags&=-2053,i.lanes&=~x,ws(i,a,x)):($n&&d&&Ll(a),a.flags|=1,ys(i,a,p,x),a.child)}function Bh(i,a,d,p,x){if(i===null){var j=d.type;return typeof j=="function"&&!W_(j)&&j.defaultProps===void 0&&d.compare===null&&d.defaultProps===void 0?(a.tag=15,a.type=j,Uh(i,a,j,p,x)):(i=Jh(d.type,null,p,a,a.mode,x),i.ref=a.ref,i.return=a,a.child=i)}if(j=i.child,(i.lanes&x)===0){var P=j.memoizedProps;if(d=d.compare,d=d!==null?d:di,d(P,p)&&i.ref===a.ref)return ws(i,a,x)}return a.flags|=1,i=sl(j,p),i.ref=a.ref,i.return=a,a.child=i}function Uh(i,a,d,p,x){if(i!==null){var j=i.memoizedProps;if(di(j,p)&&i.ref===a.ref)if(ar=!1,a.pendingProps=p=j,(i.lanes&x)!==0)(i.flags&131072)!==0&&(ar=!0);else return a.lanes=i.lanes,ws(i,a,x)}return Od(i,a,d,p,x)}function lr(i,a,d){var p=a.pendingProps,x=p.children,j=i!==null?i.memoizedState:null;if(p.mode==="hidden")if((a.mode&1)===0)a.memoizedState={baseLanes:0,cachePool:null,transitions:null},Wt(aa,Nr),Nr|=d;else{if((d&1073741824)===0)return i=j!==null?j.baseLanes|d:d,a.lanes=a.childLanes=1073741824,a.memoizedState={baseLanes:i,cachePool:null,transitions:null},a.updateQueue=null,Wt(aa,Nr),Nr|=i,null;a.memoizedState={baseLanes:0,cachePool:null,transitions:null},p=j!==null?j.baseLanes:d,Wt(aa,Nr),Nr|=p}else j!==null?(p=j.baseLanes|d,a.memoizedState=null):p=d,Wt(aa,Nr),Nr|=p;return ys(i,a,x,d),a.child}function ta(i,a){var d=a.ref;(i===null&&d!==null||i!==null&&i.ref!==d)&&(a.flags|=512,a.flags|=2097152)}function Od(i,a,d,p,x){var j=sr(d)?Go:is.current;return j=po(a,j),ir(a,x),d=Ad(i,a,d,p,j,x),p=en(),i!==null&&!ar?(a.updateQueue=i.updateQueue,a.flags&=-2053,i.lanes&=~x,ws(i,a,x)):($n&&p&&Ll(a),a.flags|=1,ys(i,a,d,x),a.child)}function Pd(i,a,d,p,x){if(sr(d)){var j=!0;Ml(a)}else j=!1;if(ir(a,x),a.stateNode===null)Gl(i,a),Lh(a,d,p),su(a,d,p,x),p=!0;else if(i===null){var P=a.stateNode,ne=a.memoizedProps;P.props=ne;var oe=P.context,ve=d.contextType;typeof ve=="object"&&ve!==null?ve=xr(ve):(ve=sr(d)?Go:is.current,ve=po(a,ve));var Le=d.getDerivedStateFromProps,Oe=typeof Le=="function"||typeof P.getSnapshotBeforeUpdate=="function";Oe||typeof P.UNSAFE_componentWillReceiveProps!="function"&&typeof P.componentWillReceiveProps!="function"||(ne!==p||oe!==ve)&&Ih(a,P,p,ve),yo=!1;var Re=a.memoizedState;P.state=Re,qa(a,p,P,x),oe=a.memoizedState,ne!==p||Re!==oe||nr.current||yo?(typeof Le=="function"&&(Ja(a,d,Le,p),oe=a.memoizedState),(ne=yo||nu(a,d,ne,p,Re,oe,ve))?(Oe||typeof P.UNSAFE_componentWillMount!="function"&&typeof P.componentWillMount!="function"||(typeof P.componentWillMount=="function"&&P.componentWillMount(),typeof P.UNSAFE_componentWillMount=="function"&&P.UNSAFE_componentWillMount()),typeof P.componentDidMount=="function"&&(a.flags|=4194308)):(typeof P.componentDidMount=="function"&&(a.flags|=4194308),a.memoizedProps=p,a.memoizedState=oe),P.props=p,P.state=oe,P.context=ve,p=ne):(typeof P.componentDidMount=="function"&&(a.flags|=4194308),p=!1)}else{P=a.stateNode,jd(i,a),ne=a.memoizedProps,ve=a.type===a.elementType?ne:ti(a.type,ne),P.props=ve,Oe=a.pendingProps,Re=P.context,oe=d.contextType,typeof oe=="object"&&oe!==null?oe=xr(oe):(oe=sr(d)?Go:is.current,oe=po(a,oe));var nt=d.getDerivedStateFromProps;(Le=typeof nt=="function"||typeof P.getSnapshotBeforeUpdate=="function")||typeof P.UNSAFE_componentWillReceiveProps!="function"&&typeof P.componentWillReceiveProps!="function"||(ne!==Oe||Re!==oe)&&Ih(a,P,p,oe),yo=!1,Re=a.memoizedState,P.state=Re,qa(a,p,P,x);var ot=a.memoizedState;ne!==Oe||Re!==ot||nr.current||yo?(typeof nt=="function"&&(Ja(a,d,nt,p),ot=a.memoizedState),(ve=yo||nu(a,d,ve,p,Re,ot,oe)||!1)?(Le||typeof P.UNSAFE_componentWillUpdate!="function"&&typeof P.componentWillUpdate!="function"||(typeof P.componentWillUpdate=="function"&&P.componentWillUpdate(p,ot,oe),typeof P.UNSAFE_componentWillUpdate=="function"&&P.UNSAFE_componentWillUpdate(p,ot,oe)),typeof P.componentDidUpdate=="function"&&(a.flags|=4),typeof P.getSnapshotBeforeUpdate=="function"&&(a.flags|=1024)):(typeof P.componentDidUpdate!="function"||ne===i.memoizedProps&&Re===i.memoizedState||(a.flags|=4),typeof P.getSnapshotBeforeUpdate!="function"||ne===i.memoizedProps&&Re===i.memoizedState||(a.flags|=1024),a.memoizedProps=p,a.memoizedState=ot),P.props=p,P.state=ot,P.context=oe,p=ve):(typeof P.componentDidUpdate!="function"||ne===i.memoizedProps&&Re===i.memoizedState||(a.flags|=4),typeof P.getSnapshotBeforeUpdate!="function"||ne===i.memoizedProps&&Re===i.memoizedState||(a.flags|=1024),p=!1)}return Us(i,a,d,p,j,x)}function Us(i,a,d,p,x,j){ta(i,a);var P=(a.flags&128)!==0;if(!p&&!P)return x&&pd(a,d,!1),ws(i,a,j);p=a.stateNode,Fh.current=a;var ne=P&&typeof d.getDerivedStateFromError!="function"?null:p.render();return a.flags|=1,i!==null&&P?(a.child=Zr(a,i.child,null,j),a.child=Zr(a,null,ne,j)):ys(i,a,ne,j),a.memoizedState=p.state,x&&pd(a,d,!0),a.child}function iu(i){var a=i.stateNode;a.pendingContext?_d(i,a.pendingContext,a.pendingContext!==a.context):a.context&&_d(i,a.context,!1),Nd(i,a.containerInfo)}function Dd(i,a,d,p,x){return Jo(),gs(x),a.flags|=256,ys(i,a,d,p),a.child}var ou={dehydrated:null,treeContext:null,retryLane:0};function Fd(i){return{baseLanes:i,cachePool:null,transitions:null}}function Wh(i,a,d){var p=a.pendingProps,x=In.current,j=!1,P=(a.flags&128)!==0,ne;if((ne=P)||(ne=i!==null&&i.memoizedState===null?!1:(x&2)!==0),ne?(j=!0,a.flags&=-129):(i===null||i.memoizedState!==null)&&(x|=1),Wt(In,x&1),i===null)return Hc(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):(P=p.children,i=p.fallback,j?(p=a.mode,j=a.child,P={mode:"hidden",children:P},(p&1)===0&&j!==null?(j.childLanes=0,j.pendingProps=P):j=Xh(P,p,0,null),i=nc(i,p,d,null),j.return=a,i.return=a,j.sibling=i,a.child=j,a.child.memoizedState=Fd(d),a.memoizedState=ou,i):zd(a,P));if(x=i.memoizedState,x!==null&&(ne=x.dehydrated,ne!==null))return Vl(i,a,P,p,ne,x,d);if(j){j=p.fallback,P=a.mode,x=i.child,ne=x.sibling;var oe={mode:"hidden",children:p.children};return(P&1)===0&&a.child!==x?(p=a.child,p.childLanes=0,p.pendingProps=oe,a.deletions=null):(p=sl(x,oe),p.subtreeFlags=x.subtreeFlags&14680064),ne!==null?j=sl(ne,j):(j=nc(j,P,d,null),j.flags|=2),j.return=a,p.return=a,p.sibling=j,a.child=p,p=j,j=a.child,P=i.child.memoizedState,P=P===null?Fd(d):{baseLanes:P.baseLanes|d,cachePool:null,transitions:P.transitions},j.memoizedState=P,j.childLanes=i.childLanes&~d,a.memoizedState=ou,p}return j=i.child,i=j.sibling,p=sl(j,{mode:"visible",children:p.children}),(a.mode&1)===0&&(p.lanes=d),p.return=a,p.sibling=null,i!==null&&(d=a.deletions,d===null?(a.deletions=[i],a.flags|=16):d.push(i)),a.child=p,a.memoizedState=null,p}function zd(i,a){return a=Xh({mode:"visible",children:a},i.mode,0,null),a.return=i,i.child=a}function $s(i,a,d,p){return p!==null&&gs(p),Zr(a,i.child,null,d),i=zd(a,a.pendingProps.children),i.flags|=2,a.memoizedState=null,i}function Vl(i,a,d,p,x,j,P){if(d)return a.flags&256?(a.flags&=-257,p=Qo(Error(n(422))),$s(i,a,P,p)):a.memoizedState!==null?(a.child=i.child,a.flags|=128,null):(j=p.fallback,x=a.mode,p=Xh({mode:"visible",children:p.children},x,0,null),j=nc(j,x,P,null),j.flags|=2,p.return=a,j.return=a,p.sibling=j,a.child=p,(a.mode&1)!==0&&Zr(a,i.child,null,P),a.child.memoizedState=Fd(P),a.memoizedState=ou,j);if((a.mode&1)===0)return $s(i,a,P,null);if(x.data==="$!"){if(p=x.nextSibling&&x.nextSibling.dataset,p)var ne=p.dgst;return p=ne,j=Error(n(419)),p=Qo(j,p,void 0),$s(i,a,P,p)}if(ne=(P&i.childLanes)!==0,ar||ne){if(p=as,p!==null){switch(P&-P){case 4:x=2;break;case 16:x=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:x=32;break;case 536870912:x=268435456;break;default:x=0}x=(x&(p.suspendedLanes|P))!==0?0:x,x!==0&&x!==j.retryLane&&(j.retryLane=x,zi(i,x),Ie(p,i,x,-1))}return Ts(),p=Qo(Error(n(421))),$s(i,a,P,p)}return x.data==="$?"?(a.flags|=128,a.child=i.child,a=Cj.bind(null,i),x._reactRetry=a,null):(i=j.treeContext,zs=mo(x.nextSibling),fn=a,$n=!0,vr=null,i!==null&&(Fr[rr++]=Xr,Fr[rr++]=Fi,Fr[rr++]=Yo,Xr=i.id,Fi=i.overflow,Yo=a),a=zd(a,p.children),a.flags|=4096,a)}function Bd(i,a,d){i.lanes|=a;var p=i.alternate;p!==null&&(p.lanes|=a),Ol(i.return,a,d)}function au(i,a,d,p,x){var j=i.memoizedState;j===null?i.memoizedState={isBackwards:a,rendering:null,renderingStartTime:0,last:p,tail:d,tailMode:x}:(j.isBackwards=a,j.rendering=null,j.renderingStartTime=0,j.last=p,j.tail=d,j.tailMode=x)}function na(i,a,d){var p=a.pendingProps,x=p.revealOrder,j=p.tail;if(ys(i,a,p.children,d),p=In.current,(p&2)!==0)p=p&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&&Bd(i,d,a);else if(i.tag===19)Bd(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}p&=1}if(Wt(In,p),(a.mode&1)===0)a.memoizedState=null;else switch(x){case"forwards":for(d=a.child,x=null;d!==null;)i=d.alternate,i!==null&&Kc(i)===null&&(x=d),d=d.sibling;d=x,d===null?(x=a.child,a.child=null):(x=d.sibling,d.sibling=null),au(a,!1,x,d,j);break;case"backwards":for(d=null,x=a.child,a.child=null;x!==null;){if(i=x.alternate,i!==null&&Kc(i)===null){a.child=x;break}i=x.sibling,x.sibling=d,d=x,x=i}au(a,!0,d,null,j);break;case"together":au(a,!1,null,null,void 0);break;default:a.memoizedState=null}return a.child}function Gl(i,a){(a.mode&1)===0&&i!==null&&(i.alternate=null,a.alternate=null,a.flags|=2)}function ws(i,a,d){if(i!==null&&(a.dependencies=i.dependencies),jo|=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=sl(i,i.pendingProps),a.child=d,d.return=a;i.sibling!==null;)i=i.sibling,d=d.sibling=sl(i,i.pendingProps),d.return=a;d.sibling=null}return a.child}function B_(i,a,d){switch(a.tag){case 3:iu(a),Jo();break;case 5:bh(a);break;case 1:sr(a.type)&&Ml(a);break;case 4:Nd(a,a.stateNode.containerInfo);break;case 10:var p=a.type._context,x=a.memoizedProps.value;Wt(Gc,p._currentValue),p._currentValue=x;break;case 13:if(p=a.memoizedState,p!==null)return p.dehydrated!==null?(Wt(In,In.current&1),a.flags|=128,null):(d&a.child.childLanes)!==0?Wh(i,a,d):(Wt(In,In.current&1),i=ws(i,a,d),i!==null?i.sibling:null);Wt(In,In.current&1);break;case 19:if(p=(d&a.childLanes)!==0,(i.flags&128)!==0){if(p)return na(i,a,d);a.flags|=128}if(x=a.memoizedState,x!==null&&(x.rendering=null,x.tail=null,x.lastEffect=null),Wt(In,In.current),p)break;return null;case 22:case 23:return a.lanes=0,lr(i,a,d)}return ws(i,a,d)}var qh,lu,sa,cu;qh=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}},lu=function(){},sa=function(i,a,d,p){var x=i.memoizedProps;if(x!==p){i=a.stateNode,Ui(or.current);var j=null;switch(d){case"input":x=et(i,x),p=et(i,p),j=[];break;case"select":x=V({},x,{value:void 0}),p=V({},p,{value:void 0}),j=[];break;case"textarea":x=Te(i,x),p=Te(i,p),j=[];break;default:typeof x.onClick!="function"&&typeof p.onClick=="function"&&(i.onclick=Ma)}bn(d,p);var P;d=null;for(ve in x)if(!p.hasOwnProperty(ve)&&x.hasOwnProperty(ve)&&x[ve]!=null)if(ve==="style"){var ne=x[ve];for(P in ne)ne.hasOwnProperty(P)&&(d||(d={}),d[P]="")}else ve!=="dangerouslySetInnerHTML"&&ve!=="children"&&ve!=="suppressContentEditableWarning"&&ve!=="suppressHydrationWarning"&&ve!=="autoFocus"&&(o.hasOwnProperty(ve)?j||(j=[]):(j=j||[]).push(ve,null));for(ve in p){var oe=p[ve];if(ne=x!=null?x[ve]:void 0,p.hasOwnProperty(ve)&&oe!==ne&&(oe!=null||ne!=null))if(ve==="style")if(ne){for(P in ne)!ne.hasOwnProperty(P)||oe&&oe.hasOwnProperty(P)||(d||(d={}),d[P]="");for(P in oe)oe.hasOwnProperty(P)&&ne[P]!==oe[P]&&(d||(d={}),d[P]=oe[P])}else d||(j||(j=[]),j.push(ve,d)),d=oe;else ve==="dangerouslySetInnerHTML"?(oe=oe?oe.__html:void 0,ne=ne?ne.__html:void 0,oe!=null&&ne!==oe&&(j=j||[]).push(ve,oe)):ve==="children"?typeof oe!="string"&&typeof oe!="number"||(j=j||[]).push(ve,""+oe):ve!=="suppressContentEditableWarning"&&ve!=="suppressHydrationWarning"&&(o.hasOwnProperty(ve)?(oe!=null&&ve==="onScroll"&&Sn("scroll",i),j||ne===oe||(j=[])):(j=j||[]).push(ve,oe))}d&&(j=j||[]).push("style",d);var ve=j;(a.updateQueue=ve)&&(a.flags|=4)}},cu=function(i,a,d,p){d!==p&&(a.flags|=4)};function Kl(i,a){if(!$n)switch(i.tailMode){case"hidden":a=i.tail;for(var d=null;a!==null;)a.alternate!==null&&(d=a),a=a.sibling;d===null?i.tail=null:d.sibling=null;break;case"collapsed":d=i.tail;for(var p=null;d!==null;)d.alternate!==null&&(p=d),d=d.sibling;p===null?a||i.tail===null?i.tail=null:i.tail.sibling=null:p.sibling=null}}function As(i){var a=i.alternate!==null&&i.alternate.child===i.child,d=0,p=0;if(a)for(var x=i.child;x!==null;)d|=x.lanes|x.childLanes,p|=x.subtreeFlags&14680064,p|=x.flags&14680064,x.return=i,x=x.sibling;else for(x=i.child;x!==null;)d|=x.lanes|x.childLanes,p|=x.subtreeFlags,p|=x.flags,x.return=i,x=x.sibling;return i.subtreeFlags|=p,i.childLanes=d,a}function U_(i,a,d){var p=a.pendingProps;switch(De(a),a.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return As(a),null;case 1:return sr(a.type)&&Ko(),As(a),null;case 3:return p=a.stateNode,Va(),_n(nr),_n(is),Cd(),p.pendingContext&&(p.context=p.pendingContext,p.pendingContext=null),(i===null||i.child===null)&&(Vc(a)?a.flags|=4:i===null||i.memoizedState.isDehydrated&&(a.flags&256)===0||(a.flags|=1024,vr!==null&&(He(vr),vr=null))),lu(i,a),As(a),null;case 5:Fl(a);var x=Ui(Bi.current);if(d=a.type,i!==null&&a.stateNode!=null)sa(i,a,d,p,x),i.ref!==a.ref&&(a.flags|=512,a.flags|=2097152);else{if(!p){if(a.stateNode===null)throw Error(n(166));return As(a),null}if(i=Ui(or.current),Vc(a)){p=a.stateNode,d=a.type;var j=a.memoizedProps;switch(p[tr]=a,p[Ii]=j,i=(a.mode&1)!==0,d){case"dialog":Sn("cancel",p),Sn("close",p);break;case"iframe":case"object":case"embed":Sn("load",p);break;case"video":case"audio":for(x=0;x<Aa.length;x++)Sn(Aa[x],p);break;case"source":Sn("error",p);break;case"img":case"image":case"link":Sn("error",p),Sn("load",p);break;case"details":Sn("toggle",p);break;case"input":$e(p,j),Sn("invalid",p);break;case"select":p._wrapperState={wasMultiple:!!j.multiple},Sn("invalid",p);break;case"textarea":Je(p,j),Sn("invalid",p)}bn(d,j),x=null;for(var P in j)if(j.hasOwnProperty(P)){var ne=j[P];P==="children"?typeof ne=="string"?p.textContent!==ne&&(j.suppressHydrationWarning!==!0&&fo(p.textContent,ne,i),x=["children",ne]):typeof ne=="number"&&p.textContent!==""+ne&&(j.suppressHydrationWarning!==!0&&fo(p.textContent,ne,i),x=["children",""+ne]):o.hasOwnProperty(P)&&ne!=null&&P==="onScroll"&&Sn("scroll",p)}switch(d){case"input":We(p),be(p,j,!0);break;case"textarea":We(p),ht(p);break;case"select":case"option":break;default:typeof j.onClick=="function"&&(p.onclick=Ma)}p=x,a.updateQueue=p,p!==null&&(a.flags|=4)}else{P=x.nodeType===9?x:x.ownerDocument,i==="http://www.w3.org/1999/xhtml"&&(i=lt(d)),i==="http://www.w3.org/1999/xhtml"?d==="script"?(i=P.createElement("div"),i.innerHTML="<script><\/script>",i=i.removeChild(i.firstChild)):typeof p.is=="string"?i=P.createElement(d,{is:p.is}):(i=P.createElement(d),d==="select"&&(P=i,p.multiple?P.multiple=!0:p.size&&(P.size=p.size))):i=P.createElementNS(i,d),i[tr]=a,i[Ii]=p,qh(i,a,!1,!1),a.stateNode=i;e:{switch(P=js(d,p),d){case"dialog":Sn("cancel",i),Sn("close",i),x=p;break;case"iframe":case"object":case"embed":Sn("load",i),x=p;break;case"video":case"audio":for(x=0;x<Aa.length;x++)Sn(Aa[x],i);x=p;break;case"source":Sn("error",i),x=p;break;case"img":case"image":case"link":Sn("error",i),Sn("load",i),x=p;break;case"details":Sn("toggle",i),x=p;break;case"input":$e(i,p),x=et(i,p),Sn("invalid",i);break;case"option":x=p;break;case"select":i._wrapperState={wasMultiple:!!p.multiple},x=V({},p,{value:void 0}),Sn("invalid",i);break;case"textarea":Je(i,p),x=Te(i,p),Sn("invalid",i);break;default:x=p}bn(d,x),ne=x;for(j in ne)if(ne.hasOwnProperty(j)){var oe=ne[j];j==="style"?vn(i,oe):j==="dangerouslySetInnerHTML"?(oe=oe?oe.__html:void 0,oe!=null&&Pn(i,oe)):j==="children"?typeof oe=="string"?(d!=="textarea"||oe!=="")&&zt(i,oe):typeof oe=="number"&&zt(i,""+oe):j!=="suppressContentEditableWarning"&&j!=="suppressHydrationWarning"&&j!=="autoFocus"&&(o.hasOwnProperty(j)?oe!=null&&j==="onScroll"&&Sn("scroll",i):oe!=null&&T(i,j,oe,P))}switch(d){case"input":We(i),be(i,p,!1);break;case"textarea":We(i),ht(i);break;case"option":p.value!=null&&i.setAttribute("value",""+ge(p.value));break;case"select":i.multiple=!!p.multiple,j=p.value,j!=null?Ce(i,!!p.multiple,j,!1):p.defaultValue!=null&&Ce(i,!!p.multiple,p.defaultValue,!0);break;default:typeof x.onClick=="function"&&(i.onclick=Ma)}switch(d){case"button":case"input":case"select":case"textarea":p=!!p.autoFocus;break e;case"img":p=!0;break e;default:p=!1}}p&&(a.flags|=4)}a.ref!==null&&(a.flags|=512,a.flags|=2097152)}return As(a),null;case 6:if(i&&a.stateNode!=null)cu(i,a,i.memoizedProps,p);else{if(typeof p!="string"&&a.stateNode===null)throw Error(n(166));if(d=Ui(Bi.current),Ui(or.current),Vc(a)){if(p=a.stateNode,d=a.memoizedProps,p[tr]=a,(j=p.nodeValue!==d)&&(i=fn,i!==null))switch(i.tag){case 3:fo(p.nodeValue,d,(i.mode&1)!==0);break;case 5:i.memoizedProps.suppressHydrationWarning!==!0&&fo(p.nodeValue,d,(i.mode&1)!==0)}j&&(a.flags|=4)}else p=(d.nodeType===9?d:d.ownerDocument).createTextNode(p),p[tr]=a,a.stateNode=p}return As(a),null;case 13:if(_n(In),p=a.memoizedState,i===null||i.memoizedState!==null&&i.memoizedState.dehydrated!==null){if($n&&zs!==null&&(a.mode&1)!==0&&(a.flags&128)===0)Il(),Jo(),a.flags|=98560,j=!1;else if(j=Vc(a),p!==null&&p.dehydrated!==null){if(i===null){if(!j)throw Error(n(318));if(j=a.memoizedState,j=j!==null?j.dehydrated:null,!j)throw Error(n(317));j[tr]=a}else Jo(),(a.flags&128)===0&&(a.memoizedState=null),a.flags|=4;As(a),j=!1}else vr!==null&&(He(vr),vr=null),j=!0;if(!j)return a.flags&65536?a:null}return(a.flags&128)!==0?(a.lanes=d,a):(p=p!==null,p!==(i!==null&&i.memoizedState!==null)&&p&&(a.child.flags|=8192,(a.mode&1)!==0&&(i===null||(In.current&1)!==0?Xn===0&&(Xn=3):Ts())),a.updateQueue!==null&&(a.flags|=4),As(a),null);case 4:return Va(),lu(i,a),i===null&&Nl(a.stateNode.containerInfo),As(a),null;case 10:return kd(a.type._context),As(a),null;case 17:return sr(a.type)&&Ko(),As(a),null;case 19:if(_n(In),j=a.memoizedState,j===null)return As(a),null;if(p=(a.flags&128)!==0,P=j.rendering,P===null)if(p)Kl(j,!1);else{if(Xn!==0||i!==null&&(i.flags&128)!==0)for(i=a.child;i!==null;){if(P=Kc(i),P!==null){for(a.flags|=128,Kl(j,!1),p=P.updateQueue,p!==null&&(a.updateQueue=p,a.flags|=4),a.subtreeFlags=0,p=d,d=a.child;d!==null;)j=d,i=p,j.flags&=14680066,P=j.alternate,P===null?(j.childLanes=0,j.lanes=i,j.child=null,j.subtreeFlags=0,j.memoizedProps=null,j.memoizedState=null,j.updateQueue=null,j.dependencies=null,j.stateNode=null):(j.childLanes=P.childLanes,j.lanes=P.lanes,j.child=P.child,j.subtreeFlags=0,j.deletions=null,j.memoizedProps=P.memoizedProps,j.memoizedState=P.memoizedState,j.updateQueue=P.updateQueue,j.type=P.type,i=P.dependencies,j.dependencies=i===null?null:{lanes:i.lanes,firstContext:i.firstContext}),d=d.sibling;return Wt(In,In.current&1|2),a.child}i=i.sibling}j.tail!==null&&he()>la&&(a.flags|=128,p=!0,Kl(j,!1),a.lanes=4194304)}else{if(!p)if(i=Kc(P),i!==null){if(a.flags|=128,p=!0,d=i.updateQueue,d!==null&&(a.updateQueue=d,a.flags|=4),Kl(j,!0),j.tail===null&&j.tailMode==="hidden"&&!P.alternate&&!$n)return As(a),null}else 2*he()-j.renderingStartTime>la&&d!==1073741824&&(a.flags|=128,p=!0,Kl(j,!1),a.lanes=4194304);j.isBackwards?(P.sibling=a.child,a.child=P):(d=j.last,d!==null?d.sibling=P:a.child=P,j.last=P)}return j.tail!==null?(a=j.tail,j.rendering=a,j.tail=a.sibling,j.renderingStartTime=he(),a.sibling=null,d=In.current,Wt(In,p?d&1|2:d&1),a):(As(a),null);case 22:case 23:return Ke(),p=a.memoizedState!==null,i!==null&&i.memoizedState!==null!==p&&(a.flags|=8192),p&&(a.mode&1)!==0?(Nr&1073741824)!==0&&(As(a),a.subtreeFlags&6&&(a.flags|=8192)):As(a),null;case 24:return null;case 25:return null}throw Error(n(156,a.tag))}function Hh(i,a){switch(De(a),a.tag){case 1:return sr(a.type)&&Ko(),i=a.flags,i&65536?(a.flags=i&-65537|128,a):null;case 3:return Va(),_n(nr),_n(is),Cd(),i=a.flags,(i&65536)!==0&&(i&128)===0?(a.flags=i&-65537|128,a):null;case 5:return Fl(a),null;case 13:if(_n(In),i=a.memoizedState,i!==null&&i.dehydrated!==null){if(a.alternate===null)throw Error(n(340));Jo()}return i=a.flags,i&65536?(a.flags=i&-65537|128,a):null;case 19:return _n(In),null;case 4:return Va(),null;case 10:return kd(a.type._context),null;case 22:case 23:return Ke(),null;case 24:return null;default:return null}}var uu=!1,Gt=!1,Xa=typeof WeakSet=="function"?WeakSet:Set,st=null;function ra(i,a){var d=i.ref;if(d!==null)if(typeof d=="function")try{d(null)}catch(p){Zn(i,a,p)}else d.current=null}function du(i,a,d){try{d()}catch(p){Zn(i,a,p)}}var Ud=!1;function Vh(i,a){if(Ra=Io,i=Pc(),Fo(i)){if("selectionStart"in i)var d={start:i.selectionStart,end:i.selectionEnd};else e:{d=(d=i.ownerDocument)&&d.defaultView||window;var p=d.getSelection&&d.getSelection();if(p&&p.rangeCount!==0){d=p.anchorNode;var x=p.anchorOffset,j=p.focusNode;p=p.focusOffset;try{d.nodeType,j.nodeType}catch{d=null;break e}var P=0,ne=-1,oe=-1,ve=0,Le=0,Oe=i,Re=null;t:for(;;){for(var nt;Oe!==d||x!==0&&Oe.nodeType!==3||(ne=P+x),Oe!==j||p!==0&&Oe.nodeType!==3||(oe=P+p),Oe.nodeType===3&&(P+=Oe.nodeValue.length),(nt=Oe.firstChild)!==null;)Re=Oe,Oe=nt;for(;;){if(Oe===i)break t;if(Re===d&&++ve===x&&(ne=P),Re===j&&++Le===p&&(oe=P),(nt=Oe.nextSibling)!==null)break;Oe=Re,Re=Oe.parentNode}Oe=nt}d=ne===-1||oe===-1?null:{start:ne,end:oe}}else d=null}d=d||{start:0,end:0}}else d=null;for(zc={focusedElem:i,selectionRange:d},Io=!1,st=a;st!==null;)if(a=st,i=a.child,(a.subtreeFlags&1028)!==0&&i!==null)i.return=a,st=i;else for(;st!==null;){a=st;try{var ot=a.alternate;if((a.flags&1024)!==0)switch(a.tag){case 0:case 11:case 15:break;case 1:if(ot!==null){var at=ot.memoizedProps,ts=ot.memoizedState,pe=a.stateNode,ue=pe.getSnapshotBeforeUpdate(a.elementType===a.type?at:ti(a.type,at),ts);pe.__reactInternalSnapshotBeforeUpdate=ue}break;case 3:var we=a.stateNode.containerInfo;we.nodeType===1?we.textContent="":we.nodeType===9&&we.documentElement&&we.removeChild(we.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(n(163))}}catch(ze){Zn(a,a.return,ze)}if(i=a.sibling,i!==null){i.return=a.return,st=i;break}st=a.return}return ot=Ud,Ud=!1,ot}function Za(i,a,d){var p=a.updateQueue;if(p=p!==null?p.lastEffect:null,p!==null){var x=p=p.next;do{if((x.tag&i)===i){var j=x.destroy;x.destroy=void 0,j!==void 0&&du(a,d,j)}x=x.next}while(x!==p)}}function Qa(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 p=d.create;d.destroy=p()}d=d.next}while(d!==a)}}function ia(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 Yl(i){var a=i.alternate;a!==null&&(i.alternate=null,Yl(a)),i.child=null,i.deletions=null,i.sibling=null,i.tag===5&&(a=i.stateNode,a!==null&&(delete a[tr],delete a[Ii],delete a[El],delete a[$l],delete a[md])),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 Wd(i){return i.tag===5||i.tag===3||i.tag===4}function qd(i){e:for(;;){for(;i.sibling===null;){if(i.return===null||Wd(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 fu(i,a,d){var p=i.tag;if(p===5||p===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=Ma));else if(p!==4&&(i=i.child,i!==null))for(fu(i,a,d),i=i.sibling;i!==null;)fu(i,a,d),i=i.sibling}function gi(i,a,d){var p=i.tag;if(p===5||p===6)i=i.stateNode,a?d.insertBefore(i,a):d.appendChild(i);else if(p!==4&&(i=i.child,i!==null))for(gi(i,a,d),i=i.sibling;i!==null;)gi(i,a,d),i=i.sibling}var vs=null,xs=!1;function yi(i,a,d){for(d=d.child;d!==null;)hu(i,a,d),d=d.sibling}function hu(i,a,d){if(Ds&&typeof Ds.onCommitFiberUnmount=="function")try{Ds.onCommitFiberUnmount(hn,d)}catch{}switch(d.tag){case 5:Gt||ra(d,a);case 6:var p=vs,x=xs;vs=null,yi(i,a,d),vs=p,xs=x,vs!==null&&(xs?(i=vs,d=d.stateNode,i.nodeType===8?i.parentNode.removeChild(d):i.removeChild(d)):vs.removeChild(d.stateNode));break;case 18:vs!==null&&(xs?(i=vs,d=d.stateNode,i.nodeType===8?Ia(i.parentNode,d):i.nodeType===1&&Ia(i,d),no(i)):Ia(vs,d.stateNode));break;case 4:p=vs,x=xs,vs=d.stateNode.containerInfo,xs=!0,yi(i,a,d),vs=p,xs=x;break;case 0:case 11:case 14:case 15:if(!Gt&&(p=d.updateQueue,p!==null&&(p=p.lastEffect,p!==null))){x=p=p.next;do{var j=x,P=j.destroy;j=j.tag,P!==void 0&&((j&2)!==0||(j&4)!==0)&&du(d,a,P),x=x.next}while(x!==p)}yi(i,a,d);break;case 1:if(!Gt&&(ra(d,a),p=d.stateNode,typeof p.componentWillUnmount=="function"))try{p.props=d.memoizedProps,p.state=d.memoizedState,p.componentWillUnmount()}catch(ne){Zn(d,a,ne)}yi(i,a,d);break;case 21:yi(i,a,d);break;case 22:d.mode&1?(Gt=(p=Gt)||d.memoizedState!==null,yi(i,a,d),Gt=p):yi(i,a,d);break;default:yi(i,a,d)}}function Hd(i){var a=i.updateQueue;if(a!==null){i.updateQueue=null;var d=i.stateNode;d===null&&(d=i.stateNode=new Xa),a.forEach(function(p){var x=Ej.bind(null,i,p);d.has(p)||(d.add(p),p.then(x,x))})}}function Br(i,a){var d=a.deletions;if(d!==null)for(var p=0;p<d.length;p++){var x=d[p];try{var j=i,P=a,ne=P;e:for(;ne!==null;){switch(ne.tag){case 5:vs=ne.stateNode,xs=!1;break e;case 3:vs=ne.stateNode.containerInfo,xs=!0;break e;case 4:vs=ne.stateNode.containerInfo,xs=!0;break e}ne=ne.return}if(vs===null)throw Error(n(160));hu(j,P,x),vs=null,xs=!1;var oe=x.alternate;oe!==null&&(oe.return=null),x.return=null}catch(ve){Zn(x,a,ve)}}if(a.subtreeFlags&12854)for(a=a.child;a!==null;)Gh(a,i),a=a.sibling}function Gh(i,a){var d=i.alternate,p=i.flags;switch(i.tag){case 0:case 11:case 14:case 15:if(Br(a,i),cr(i),p&4){try{Za(3,i,i.return),Qa(3,i)}catch(at){Zn(i,i.return,at)}try{Za(5,i,i.return)}catch(at){Zn(i,i.return,at)}}break;case 1:Br(a,i),cr(i),p&512&&d!==null&&ra(d,d.return);break;case 5:if(Br(a,i),cr(i),p&512&&d!==null&&ra(d,d.return),i.flags&32){var x=i.stateNode;try{zt(x,"")}catch(at){Zn(i,i.return,at)}}if(p&4&&(x=i.stateNode,x!=null)){var j=i.memoizedProps,P=d!==null?d.memoizedProps:j,ne=i.type,oe=i.updateQueue;if(i.updateQueue=null,oe!==null)try{ne==="input"&&j.type==="radio"&&j.name!=null&&Ve(x,j),js(ne,P);var ve=js(ne,j);for(P=0;P<oe.length;P+=2){var Le=oe[P],Oe=oe[P+1];Le==="style"?vn(x,Oe):Le==="dangerouslySetInnerHTML"?Pn(x,Oe):Le==="children"?zt(x,Oe):T(x,Le,Oe,ve)}switch(ne){case"input":le(x,j);break;case"textarea":rt(x,j);break;case"select":var Re=x._wrapperState.wasMultiple;x._wrapperState.wasMultiple=!!j.multiple;var nt=j.value;nt!=null?Ce(x,!!j.multiple,nt,!1):Re!==!!j.multiple&&(j.defaultValue!=null?Ce(x,!!j.multiple,j.defaultValue,!0):Ce(x,!!j.multiple,j.multiple?[]:"",!1))}x[Ii]=j}catch(at){Zn(i,i.return,at)}}break;case 6:if(Br(a,i),cr(i),p&4){if(i.stateNode===null)throw Error(n(162));x=i.stateNode,j=i.memoizedProps;try{x.nodeValue=j}catch(at){Zn(i,i.return,at)}}break;case 3:if(Br(a,i),cr(i),p&4&&d!==null&&d.memoizedState.isDehydrated)try{no(a.containerInfo)}catch(at){Zn(i,i.return,at)}break;case 4:Br(a,i),cr(i);break;case 13:Br(a,i),cr(i),x=i.child,x.flags&8192&&(j=x.memoizedState!==null,x.stateNode.isHidden=j,!j||x.alternate!==null&&x.alternate.memoizedState!==null||(pu=he())),p&4&&Hd(i);break;case 22:if(Le=d!==null&&d.memoizedState!==null,i.mode&1?(Gt=(ve=Gt)||Le,Br(a,i),Gt=ve):Br(a,i),cr(i),p&8192){if(ve=i.memoizedState!==null,(i.stateNode.isHidden=ve)&&!Le&&(i.mode&1)!==0)for(st=i,Le=i.child;Le!==null;){for(Oe=st=Le;st!==null;){switch(Re=st,nt=Re.child,Re.tag){case 0:case 11:case 14:case 15:Za(4,Re,Re.return);break;case 1:ra(Re,Re.return);var ot=Re.stateNode;if(typeof ot.componentWillUnmount=="function"){p=Re,d=Re.return;try{a=p,ot.props=a.memoizedProps,ot.state=a.memoizedState,ot.componentWillUnmount()}catch(at){Zn(p,d,at)}}break;case 5:ra(Re,Re.return);break;case 22:if(Re.memoizedState!==null){Yh(Oe);continue}}nt!==null?(nt.return=Re,st=nt):Yh(Oe)}Le=Le.sibling}e:for(Le=null,Oe=i;;){if(Oe.tag===5){if(Le===null){Le=Oe;try{x=Oe.stateNode,ve?(j=x.style,typeof j.setProperty=="function"?j.setProperty("display","none","important"):j.display="none"):(ne=Oe.stateNode,oe=Oe.memoizedProps.style,P=oe!=null&&oe.hasOwnProperty("display")?oe.display:null,ne.style.display=Mn("display",P))}catch(at){Zn(i,i.return,at)}}}else if(Oe.tag===6){if(Le===null)try{Oe.stateNode.nodeValue=ve?"":Oe.memoizedProps}catch(at){Zn(i,i.return,at)}}else if((Oe.tag!==22&&Oe.tag!==23||Oe.memoizedState===null||Oe===i)&&Oe.child!==null){Oe.child.return=Oe,Oe=Oe.child;continue}if(Oe===i)break e;for(;Oe.sibling===null;){if(Oe.return===null||Oe.return===i)break e;Le===Oe&&(Le=null),Oe=Oe.return}Le===Oe&&(Le=null),Oe.sibling.return=Oe.return,Oe=Oe.sibling}}break;case 19:Br(a,i),cr(i),p&4&&Hd(i);break;case 21:break;default:Br(a,i),cr(i)}}function cr(i){var a=i.flags;if(a&2){try{e:{for(var d=i.return;d!==null;){if(Wd(d)){var p=d;break e}d=d.return}throw Error(n(160))}switch(p.tag){case 5:var x=p.stateNode;p.flags&32&&(zt(x,""),p.flags&=-33);var j=qd(i);gi(i,j,x);break;case 3:case 4:var P=p.stateNode.containerInfo,ne=qd(i);fu(i,ne,P);break;default:throw Error(n(161))}}catch(oe){Zn(i,i.return,oe)}i.flags&=-3}a&4096&&(i.flags&=-4097)}function oa(i,a,d){st=i,Kh(i)}function Kh(i,a,d){for(var p=(i.mode&1)!==0;st!==null;){var x=st,j=x.child;if(x.tag===22&&p){var P=x.memoizedState!==null||uu;if(!P){var ne=x.alternate,oe=ne!==null&&ne.memoizedState!==null||Gt;ne=uu;var ve=Gt;if(uu=P,(Gt=oe)&&!ve)for(st=x;st!==null;)P=st,oe=P.child,P.tag===22&&P.memoizedState!==null?Jl(x):oe!==null?(oe.return=P,st=oe):Jl(x);for(;j!==null;)st=j,Kh(j),j=j.sibling;st=x,uu=ne,Gt=ve}el(i)}else(x.subtreeFlags&8772)!==0&&j!==null?(j.return=x,st=j):el(i)}}function el(i){for(;st!==null;){var a=st;if((a.flags&8772)!==0){var d=a.alternate;try{if((a.flags&8772)!==0)switch(a.tag){case 0:case 11:case 15:Gt||Qa(5,a);break;case 1:var p=a.stateNode;if(a.flags&4&&!Gt)if(d===null)p.componentDidMount();else{var x=a.elementType===a.type?d.memoizedProps:ti(a.type,d.memoizedProps);p.componentDidUpdate(x,d.memoizedState,p.__reactInternalSnapshotBeforeUpdate)}var j=a.updateQueue;j!==null&&Bs(a,j,p);break;case 3:var P=a.updateQueue;if(P!==null){if(d=null,a.child!==null)switch(a.child.tag){case 5:d=a.child.stateNode;break;case 1:d=a.child.stateNode}Bs(a,P,d)}break;case 5:var ne=a.stateNode;if(d===null&&a.flags&4){d=ne;var oe=a.memoizedProps;switch(a.type){case"button":case"input":case"select":case"textarea":oe.autoFocus&&d.focus();break;case"img":oe.src&&(d.src=oe.src)}}break;case 6:break;case 4:break;case 12:break;case 13:if(a.memoizedState===null){var ve=a.alternate;if(ve!==null){var Le=ve.memoizedState;if(Le!==null){var Oe=Le.dehydrated;Oe!==null&&no(Oe)}}}break;case 19:case 17:case 21:case 22:case 23:case 25:break;default:throw Error(n(163))}Gt||a.flags&512&&ia(a)}catch(Re){Zn(a,a.return,Re)}}if(a===i){st=null;break}if(d=a.sibling,d!==null){d.return=a.return,st=d;break}st=a.return}}function Yh(i){for(;st!==null;){var a=st;if(a===i){st=null;break}var d=a.sibling;if(d!==null){d.return=a.return,st=d;break}st=a.return}}function Jl(i){for(;st!==null;){var a=st;try{switch(a.tag){case 0:case 11:case 15:var d=a.return;try{Qa(4,a)}catch(oe){Zn(a,d,oe)}break;case 1:var p=a.stateNode;if(typeof p.componentDidMount=="function"){var x=a.return;try{p.componentDidMount()}catch(oe){Zn(a,x,oe)}}var j=a.return;try{ia(a)}catch(oe){Zn(a,j,oe)}break;case 5:var P=a.return;try{ia(a)}catch(oe){Zn(a,P,oe)}}}catch(oe){Zn(a,a.return,oe)}if(a===i){st=null;break}var ne=a.sibling;if(ne!==null){ne.return=a.return,st=ne;break}st=a.return}}var Vd=Math.ceil,mu=A.ReactCurrentDispatcher,Gd=A.ReactCurrentOwner,Sr=A.ReactCurrentBatchConfig,tn=0,as=null,Vn=null,ls=0,Nr=0,aa=_o(0),Xn=0,tl=null,jo=0,Xl=0,_u=0,nl=null,Ws=null,pu=0,la=1/0,wi=null,Zl=!1,gu=null,Wi=null,Ql=!1,v=null,C=0,I=0,B=null,Z=-1,X=0;function G(){return(tn&6)!==0?he():Z!==-1?Z:Z=he()}function se(i){return(i.mode&1)===0?1:(tn&2)!==0&&ls!==0?ls&-ls:Vt.transition!==null?(X===0&&(X=ds()),X):(i=un,i!==0||(i=window.event,i=i===void 0?16:je(i.type)),i)}function Ie(i,a,d,p){if(50<I)throw I=0,B=null,Error(n(185));fs(i,d,p),((tn&2)===0||i!==as)&&(i===as&&((tn&2)===0&&(Xl|=d),Xn===4&&Ye(i,ls)),ye(i,p),d===1&&tn===0&&(a.mode&1)===0&&(la=he()+500,Rl&&Pi()))}function ye(i,a){var d=i.callbackNode;Rn(i,a);var p=Zi(i,i===as?ls:0);if(p===0)d!==null&&ii(d),i.callbackNode=null,i.callbackPriority=0;else if(a=p&-p,i.callbackPriority!==a){if(d!=null&&ii(d),a===1)i.tag===0?P_(Ze.bind(null,i)):gd(Ze.bind(null,i)),La(function(){(tn&6)===0&&Pi()}),d=null;else{switch(ba(p)){case 1:d=Xi;break;case 4:d=_r;break;case 16:d=Tr;break;case 536870912:d=dt;break;default:d=Tr}d=Uy(d,ke.bind(null,i))}i.callbackPriority=a,i.callbackNode=d}}function ke(i,a){if(Z=-1,X=0,(tn&6)!==0)throw Error(n(327));var d=i.callbackNode;if(yu()&&i.callbackNode!==d)return null;var p=Zi(i,i===as?ls:0);if(p===0)return null;if((p&30)!==0||(p&i.expiredLanes)!==0||a)a=qs(i,p);else{a=p;var x=tn;tn|=2;var j=Tn();(as!==i||ls!==a)&&(wi=null,la=he()+500,wt(i,a));do try{ec();break}catch(ne){kn(i,ne)}while(!0);bd(),mu.current=j,tn=x,Vn!==null?a=0:(as=null,ls=0,a=Xn)}if(a!==0){if(a===2&&(x=Fs(i),x!==0&&(p=x,a=Me(i,x))),a===1)throw d=tl,wt(i,0),Ye(i,p),ye(i,he()),d;if(a===6)Ye(i,p);else{if(x=i.current.alternate,(p&30)===0&&!Xe(x)&&(a=qs(i,p),a===2&&(j=Fs(i),j!==0&&(p=j,a=Me(i,j))),a===1))throw d=tl,wt(i,0),Ye(i,p),ye(i,he()),d;switch(i.finishedWork=x,i.finishedLanes=p,a){case 0:case 1:throw Error(n(345));case 2:tc(i,Ws,wi);break;case 3:if(Ye(i,p),(p&130023424)===p&&(a=pu+500-he(),10<a)){if(Zi(i,0)!==0)break;if(x=i.suspendedLanes,(x&p)!==p){G(),i.pingedLanes|=i.suspendedLanes&x;break}i.timeoutHandle=hd(tc.bind(null,i,Ws,wi),a);break}tc(i,Ws,wi);break;case 4:if(Ye(i,p),(p&4194240)===p)break;for(a=i.eventTimes,x=-1;0<p;){var P=31-ss(p);j=1<<P,P=a[P],P>x&&(x=P),p&=~j}if(p=x,p=he()-p,p=(120>p?120:480>p?480:1080>p?1080:1920>p?1920:3e3>p?3e3:4320>p?4320:1960*Vd(p/1960))-p,10<p){i.timeoutHandle=hd(tc.bind(null,i,Ws,wi),p);break}tc(i,Ws,wi);break;case 5:tc(i,Ws,wi);break;default:throw Error(n(329))}}}return ye(i,he()),i.callbackNode===d?ke.bind(null,i):null}function Me(i,a){var d=nl;return i.current.memoizedState.isDehydrated&&(wt(i,a).flags|=256),i=qs(i,a),i!==2&&(a=Ws,Ws=d,a!==null&&He(a)),i}function He(i){Ws===null?Ws=i:Ws.push.apply(Ws,i)}function Xe(i){for(var a=i;;){if(a.flags&16384){var d=a.updateQueue;if(d!==null&&(d=d.stores,d!==null))for(var p=0;p<d.length;p++){var x=d[p],j=x.getSnapshot;x=x.value;try{if(!es(j(),x))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 Ye(i,a){for(a&=~_u,a&=~Xl,i.suspendedLanes|=a,i.pingedLanes&=~a,i=i.expirationTimes;0<a;){var d=31-ss(a),p=1<<d;i[d]=-1,a&=~p}}function Ze(i){if((tn&6)!==0)throw Error(n(327));yu();var a=Zi(i,0);if((a&1)===0)return ye(i,he()),null;var d=qs(i,a);if(i.tag!==0&&d===2){var p=Fs(i);p!==0&&(a=p,d=Me(i,p))}if(d===1)throw d=tl,wt(i,0),Ye(i,a),ye(i,he()),d;if(d===6)throw Error(n(345));return i.finishedWork=i.current.alternate,i.finishedLanes=a,tc(i,Ws,wi),ye(i,he()),null}function an(i,a){var d=tn;tn|=1;try{return i(a)}finally{tn=d,tn===0&&(la=he()+500,Rl&&Pi())}}function Nt(i){v!==null&&v.tag===0&&(tn&6)===0&&yu();var a=tn;tn|=1;var d=Sr.transition,p=un;try{if(Sr.transition=null,un=1,i)return i()}finally{un=p,Sr.transition=d,tn=a,(tn&6)===0&&Pi()}}function Ke(){Nr=aa.current,_n(aa)}function wt(i,a){i.finishedWork=null,i.finishedLanes=0;var d=i.timeoutHandle;if(d!==-1&&(i.timeoutHandle=-1,Bc(d)),Vn!==null)for(d=Vn.return;d!==null;){var p=d;switch(De(p),p.tag){case 1:p=p.type.childContextTypes,p!=null&&Ko();break;case 3:Va(),_n(nr),_n(is),Cd();break;case 5:Fl(p);break;case 4:Va();break;case 13:_n(In);break;case 19:_n(In);break;case 10:kd(p.type._context);break;case 22:case 23:Ke()}d=d.return}if(as=i,Vn=i=sl(i.current,null),ls=Nr=a,Xn=0,tl=null,_u=Xl=jo=0,Ws=nl=null,br!==null){for(a=0;a<br.length;a++)if(d=br[a],p=d.interleaved,p!==null){d.interleaved=null;var x=p.next,j=d.pending;if(j!==null){var P=j.next;j.next=x,p.next=P}d.pending=p}br=null}return i}function kn(i,a){do{var d=Vn;try{if(bd(),_i.current=jr,Yc){for(var p=Bn.memoizedState;p!==null;){var x=p.queue;x!==null&&(x.pending=null),p=p.next}Yc=!1}if(pi=0,Nn=Jn=Bn=null,Bl=!1,Ul=0,Gd.current=null,d===null||d.return===null){Xn=1,tl=a,Vn=null;break}e:{var j=i,P=d.return,ne=d,oe=a;if(a=ls,ne.flags|=32768,oe!==null&&typeof oe=="object"&&typeof oe.then=="function"){var ve=oe,Le=ne,Oe=Le.tag;if((Le.mode&1)===0&&(Oe===0||Oe===11||Oe===15)){var Re=Le.alternate;Re?(Le.updateQueue=Re.updateQueue,Le.memoizedState=Re.memoizedState,Le.lanes=Re.lanes):(Le.updateQueue=null,Le.memoizedState=null)}var nt=Dh(P);if(nt!==null){nt.flags&=-257,Hl(nt,P,ne,j,a),nt.mode&1&&ea(j,ve,a),a=nt,oe=ve;var ot=a.updateQueue;if(ot===null){var at=new Set;at.add(oe),a.updateQueue=at}else ot.add(oe);break e}else{if((a&1)===0){ea(j,ve,a),Ts();break e}oe=Error(n(426))}}else if($n&&ne.mode&1){var ts=Dh(P);if(ts!==null){(ts.flags&65536)===0&&(ts.flags|=256),Hl(ts,P,ne,j,a),gs(zr(oe,ne));break e}}j=oe=zr(oe,ne),Xn!==4&&(Xn=2),nl===null?nl=[j]:nl.push(j),j=P;do{switch(j.tag){case 3:j.flags|=65536,a&=-a,j.lanes|=a;var pe=Ph(j,oe,a);Sd(j,pe);break e;case 1:ne=oe;var ue=j.type,we=j.stateNode;if((j.flags&128)===0&&(typeof ue.getDerivedStateFromError=="function"||we!==null&&typeof we.componentDidCatch=="function"&&(Wi===null||!Wi.has(we)))){j.flags|=65536,a&=-a,j.lanes|=a;var ze=Id(j,ne,a);Sd(j,ze);break e}}j=j.return}while(j!==null)}Dy(d)}catch(ft){a=ft,Vn===d&&d!==null&&(Vn=d=d.return);continue}break}while(!0)}function Tn(){var i=mu.current;return mu.current=jr,i===null?jr:i}function Ts(){(Xn===0||Xn===3||Xn===2)&&(Xn=4),as===null||(jo&268435455)===0&&(Xl&268435455)===0||Ye(as,ls)}function qs(i,a){var d=tn;tn|=2;var p=Tn();(as!==i||ls!==a)&&(wi=null,wt(i,a));do try{ni();break}catch(x){kn(i,x)}while(!0);if(bd(),tn=d,mu.current=p,Vn!==null)throw Error(n(261));return as=null,ls=0,Xn}function ni(){for(;Vn!==null;)Py(Vn)}function ec(){for(;Vn!==null&&!oi();)Py(Vn)}function Py(i){var a=By(i.alternate,i,Nr);i.memoizedProps=i.pendingProps,a===null?Dy(i):Vn=a,Gd.current=null}function Dy(i){var a=i;do{var d=a.alternate;if(i=a.return,(a.flags&32768)===0){if(d=U_(d,a,Nr),d!==null){Vn=d;return}}else{if(d=Hh(d,a),d!==null){d.flags&=32767,Vn=d;return}if(i!==null)i.flags|=32768,i.subtreeFlags=0,i.deletions=null;else{Xn=6,Vn=null;return}}if(a=a.sibling,a!==null){Vn=a;return}Vn=a=i}while(a!==null);Xn===0&&(Xn=5)}function tc(i,a,d){var p=un,x=Sr.transition;try{Sr.transition=null,un=1,Sj(i,a,d,p)}finally{Sr.transition=x,un=p}return null}function Sj(i,a,d,p){do yu();while(v!==null);if((tn&6)!==0)throw Error(n(327));d=i.finishedWork;var x=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 j=d.lanes|d.childLanes;if(xa(i,j),i===as&&(Vn=as=null,ls=0),(d.subtreeFlags&2064)===0&&(d.flags&2064)===0||Ql||(Ql=!0,Uy(Tr,function(){return yu(),null})),j=(d.flags&15990)!==0,(d.subtreeFlags&15990)!==0||j){j=Sr.transition,Sr.transition=null;var P=un;un=1;var ne=tn;tn|=4,Gd.current=null,Vh(i,d),Gh(d,i),Or(zc),Io=!!Ra,zc=Ra=null,i.current=d,oa(d),Ps(),tn=ne,un=P,Sr.transition=j}else i.current=d;if(Ql&&(Ql=!1,v=i,C=x),j=i.pendingLanes,j===0&&(Wi=null),Kr(d.stateNode),ye(i,he()),a!==null)for(p=i.onRecoverableError,d=0;d<a.length;d++)x=a[d],p(x.value,{componentStack:x.stack,digest:x.digest});if(Zl)throw Zl=!1,i=gu,gu=null,i;return(C&1)!==0&&i.tag!==0&&yu(),j=i.pendingLanes,(j&1)!==0?i===B?I++:(I=0,B=i):I=0,Pi(),null}function yu(){if(v!==null){var i=ba(C),a=Sr.transition,d=un;try{if(Sr.transition=null,un=16>i?16:i,v===null)var p=!1;else{if(i=v,v=null,C=0,(tn&6)!==0)throw Error(n(331));var x=tn;for(tn|=4,st=i.current;st!==null;){var j=st,P=j.child;if((st.flags&16)!==0){var ne=j.deletions;if(ne!==null){for(var oe=0;oe<ne.length;oe++){var ve=ne[oe];for(st=ve;st!==null;){var Le=st;switch(Le.tag){case 0:case 11:case 15:Za(8,Le,j)}var Oe=Le.child;if(Oe!==null)Oe.return=Le,st=Oe;else for(;st!==null;){Le=st;var Re=Le.sibling,nt=Le.return;if(Yl(Le),Le===ve){st=null;break}if(Re!==null){Re.return=nt,st=Re;break}st=nt}}}var ot=j.alternate;if(ot!==null){var at=ot.child;if(at!==null){ot.child=null;do{var ts=at.sibling;at.sibling=null,at=ts}while(at!==null)}}st=j}}if((j.subtreeFlags&2064)!==0&&P!==null)P.return=j,st=P;else e:for(;st!==null;){if(j=st,(j.flags&2048)!==0)switch(j.tag){case 0:case 11:case 15:Za(9,j,j.return)}var pe=j.sibling;if(pe!==null){pe.return=j.return,st=pe;break e}st=j.return}}var ue=i.current;for(st=ue;st!==null;){P=st;var we=P.child;if((P.subtreeFlags&2064)!==0&&we!==null)we.return=P,st=we;else e:for(P=ue;st!==null;){if(ne=st,(ne.flags&2048)!==0)try{switch(ne.tag){case 0:case 11:case 15:Qa(9,ne)}}catch(ft){Zn(ne,ne.return,ft)}if(ne===P){st=null;break e}var ze=ne.sibling;if(ze!==null){ze.return=ne.return,st=ze;break e}st=ne.return}}if(tn=x,Pi(),Ds&&typeof Ds.onPostCommitFiberRoot=="function")try{Ds.onPostCommitFiberRoot(hn,i)}catch{}p=!0}return p}finally{un=d,Sr.transition=a}}return!1}function Fy(i,a,d){a=zr(d,a),a=Ph(i,a,1),i=wo(i,a,1),a=G(),i!==null&&(fs(i,1,a),ye(i,a))}function Zn(i,a,d){if(i.tag===3)Fy(i,i,d);else for(;a!==null;){if(a.tag===3){Fy(a,i,d);break}else if(a.tag===1){var p=a.stateNode;if(typeof a.type.getDerivedStateFromError=="function"||typeof p.componentDidCatch=="function"&&(Wi===null||!Wi.has(p))){i=zr(d,i),i=Id(a,i,1),a=wo(a,i,1),i=G(),a!==null&&(fs(a,1,i),ye(a,i));break}}a=a.return}}function Nj(i,a,d){var p=i.pingCache;p!==null&&p.delete(a),a=G(),i.pingedLanes|=i.suspendedLanes&d,as===i&&(ls&d)===d&&(Xn===4||Xn===3&&(ls&130023424)===ls&&500>he()-pu?wt(i,0):_u|=d),ye(i,a)}function zy(i,a){a===0&&((i.mode&1)===0?a=1:(a=pr,pr<<=1,(pr&130023424)===0&&(pr=4194304)));var d=G();i=zi(i,a),i!==null&&(fs(i,a,d),ye(i,d))}function Cj(i){var a=i.memoizedState,d=0;a!==null&&(d=a.retryLane),zy(i,d)}function Ej(i,a){var d=0;switch(i.tag){case 13:var p=i.stateNode,x=i.memoizedState;x!==null&&(d=x.retryLane);break;case 19:p=i.stateNode;break;default:throw Error(n(314))}p!==null&&p.delete(a),zy(i,d)}var By;By=function(i,a,d){if(i!==null)if(i.memoizedProps!==a.pendingProps||nr.current)ar=!0;else{if((i.lanes&d)===0&&(a.flags&128)===0)return ar=!1,B_(i,a,d);ar=(i.flags&131072)!==0}else ar=!1,$n&&(a.flags&1048576)!==0&&wh(a,qc,a.index);switch(a.lanes=0,a.tag){case 2:var p=a.type;Gl(i,a),i=a.pendingProps;var x=po(a,is.current);ir(a,d),x=Ad(null,a,p,i,x,d);var j=en();return a.flags|=1,typeof x=="object"&&x!==null&&typeof x.render=="function"&&x.$$typeof===void 0?(a.tag=1,a.memoizedState=null,a.updateQueue=null,sr(p)?(j=!0,Ml(a)):j=!1,a.memoizedState=x.state!==null&&x.state!==void 0?x.state:null,Dl(a),x.updater=tu,a.stateNode=x,x._reactInternals=a,su(a,p,i,d),a=Us(null,a,p,!0,j,d)):(a.tag=0,$n&&j&&Ll(a),ys(null,a,x,d),a=a.child),a;case 16:p=a.elementType;e:{switch(Gl(i,a),i=a.pendingProps,x=p._init,p=x(p._payload),a.type=p,x=a.tag=Aj(p),i=ti(p,i),x){case 0:a=Od(null,a,p,i,d);break e;case 1:a=Pd(null,a,p,i,d);break e;case 11:a=zh(null,a,p,i,d);break e;case 14:a=Bh(null,a,p,ti(p.type,i),d);break e}throw Error(n(306,p,""))}return a;case 0:return p=a.type,x=a.pendingProps,x=a.elementType===p?x:ti(p,x),Od(i,a,p,x,d);case 1:return p=a.type,x=a.pendingProps,x=a.elementType===p?x:ti(p,x),Pd(i,a,p,x,d);case 3:e:{if(iu(a),i===null)throw Error(n(387));p=a.pendingProps,j=a.memoizedState,x=j.element,jd(i,a),qa(a,p,null,d);var P=a.memoizedState;if(p=P.element,j.isDehydrated)if(j={element:p,isDehydrated:!1,cache:P.cache,pendingSuspenseBoundaries:P.pendingSuspenseBoundaries,transitions:P.transitions},a.updateQueue.baseState=j,a.memoizedState=j,a.flags&256){x=zr(Error(n(423)),a),a=Dd(i,a,p,d,x);break e}else if(p!==x){x=zr(Error(n(424)),a),a=Dd(i,a,p,d,x);break e}else for(zs=mo(a.stateNode.containerInfo.firstChild),fn=a,$n=!0,vr=null,d=Ot(a,null,p,d),a.child=d;d;)d.flags=d.flags&-3|4096,d=d.sibling;else{if(Jo(),p===x){a=ws(i,a,d);break e}ys(i,a,p,d)}a=a.child}return a;case 5:return bh(a),i===null&&Hc(a),p=a.type,x=a.pendingProps,j=i!==null?i.memoizedProps:null,P=x.children,ho(p,x)?P=null:j!==null&&ho(p,j)&&(a.flags|=32),ta(i,a),ys(i,a,P,d),a.child;case 6:return i===null&&Hc(a),null;case 13:return Wh(i,a,d);case 4:return Nd(a,a.stateNode.containerInfo),p=a.pendingProps,i===null?a.child=Zr(a,null,p,d):ys(i,a,p,d),a.child;case 11:return p=a.type,x=a.pendingProps,x=a.elementType===p?x:ti(p,x),zh(i,a,p,x,d);case 7:return ys(i,a,a.pendingProps,d),a.child;case 8:return ys(i,a,a.pendingProps.children,d),a.child;case 12:return ys(i,a,a.pendingProps.children,d),a.child;case 10:e:{if(p=a.type._context,x=a.pendingProps,j=a.memoizedProps,P=x.value,Wt(Gc,p._currentValue),p._currentValue=P,j!==null)if(es(j.value,P)){if(j.children===x.children&&!nr.current){a=ws(i,a,d);break e}}else for(j=a.child,j!==null&&(j.return=a);j!==null;){var ne=j.dependencies;if(ne!==null){P=j.child;for(var oe=ne.firstContext;oe!==null;){if(oe.context===p){if(j.tag===1){oe=Qr(-1,d&-d),oe.tag=2;var ve=j.updateQueue;if(ve!==null){ve=ve.shared;var Le=ve.pending;Le===null?oe.next=oe:(oe.next=Le.next,Le.next=oe),ve.pending=oe}}j.lanes|=d,oe=j.alternate,oe!==null&&(oe.lanes|=d),Ol(j.return,d,a),ne.lanes|=d;break}oe=oe.next}}else if(j.tag===10)P=j.type===a.type?null:j.child;else if(j.tag===18){if(P=j.return,P===null)throw Error(n(341));P.lanes|=d,ne=P.alternate,ne!==null&&(ne.lanes|=d),Ol(P,d,a),P=j.sibling}else P=j.child;if(P!==null)P.return=j;else for(P=j;P!==null;){if(P===a){P=null;break}if(j=P.sibling,j!==null){j.return=P.return,P=j;break}P=P.return}j=P}ys(i,a,x.children,d),a=a.child}return a;case 9:return x=a.type,p=a.pendingProps.children,ir(a,d),x=xr(x),p=p(x),a.flags|=1,ys(i,a,p,d),a.child;case 14:return p=a.type,x=ti(p,a.pendingProps),x=ti(p.type,x),Bh(i,a,p,x,d);case 15:return Uh(i,a,a.type,a.pendingProps,d);case 17:return p=a.type,x=a.pendingProps,x=a.elementType===p?x:ti(p,x),Gl(i,a),a.tag=1,sr(p)?(i=!0,Ml(a)):i=!1,ir(a,d),Lh(a,p,x),su(a,p,x,d),Us(null,a,p,!0,i,d);case 19:return na(i,a,d);case 22:return lr(i,a,d)}throw Error(n(156,a.tag))};function Uy(i,a){return hr(i,a)}function $j(i,a,d,p){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=p,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function vi(i,a,d,p){return new $j(i,a,d,p)}function W_(i){return i=i.prototype,!(!i||!i.isReactComponent)}function Aj(i){if(typeof i=="function")return W_(i)?1:0;if(i!=null){if(i=i.$$typeof,i===D)return 11;if(i===L)return 14}return 2}function sl(i,a){var d=i.alternate;return d===null?(d=vi(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 Jh(i,a,d,p,x,j){var P=2;if(p=i,typeof i=="function")W_(i)&&(P=1);else if(typeof i=="string")P=5;else e:switch(i){case J:return nc(d.children,x,j,a);case K:P=8,x|=8;break;case re:return i=vi(12,d,a,x|2),i.elementType=re,i.lanes=j,i;case $:return i=vi(13,d,a,x),i.elementType=$,i.lanes=j,i;case E:return i=vi(19,d,a,x),i.elementType=E,i.lanes=j,i;case ee:return Xh(d,x,j,a);default:if(typeof i=="object"&&i!==null)switch(i.$$typeof){case te:P=10;break e;case Q:P=9;break e;case D:P=11;break e;case L:P=14;break e;case M:P=16,p=null;break e}throw Error(n(130,i==null?i:typeof i,""))}return a=vi(P,d,a,x),a.elementType=i,a.type=p,a.lanes=j,a}function nc(i,a,d,p){return i=vi(7,i,p,a),i.lanes=d,i}function Xh(i,a,d,p){return i=vi(22,i,p,a),i.elementType=ee,i.lanes=d,i.stateNode={isHidden:!1},i}function q_(i,a,d){return i=vi(6,i,null,a),i.lanes=d,i}function H_(i,a,d){return a=vi(4,i.children!==null?i.children:[],i.key,a),a.lanes=d,a.stateNode={containerInfo:i.containerInfo,pendingChildren:null,implementation:i.implementation},a}function Tj(i,a,d,p,x){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=Ks(0),this.expirationTimes=Ks(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Ks(0),this.identifierPrefix=p,this.onRecoverableError=x,this.mutableSourceEagerHydrationData=null}function V_(i,a,d,p,x,j,P,ne,oe){return i=new Tj(i,a,d,ne,oe),a===1?(a=1,j===!0&&(a|=8)):a=0,j=vi(3,null,null,a),i.current=j,j.stateNode=i,j.memoizedState={element:p,isDehydrated:d,cache:null,transitions:null,pendingSuspenseBoundaries:null},Dl(j),i}function Mj(i,a,d){var p=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:z,key:p==null?null:""+p,children:i,containerInfo:a,implementation:d}}function Wy(i){if(!i)return Jr;i=i._reactInternals;e:{if(gt(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(sr(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(sr(d))return Tl(i,d,a)}return a}function qy(i,a,d,p,x,j,P,ne,oe){return i=V_(d,p,!0,i,x,j,P,ne,oe),i.context=Wy(null),d=i.current,p=G(),x=se(d),j=Qr(p,x),j.callback=a??null,wo(d,j,x),i.current.lanes=x,fs(i,x,p),ye(i,p),i}function Zh(i,a,d,p){var x=a.current,j=G(),P=se(x);return d=Wy(d),a.context===null?a.context=d:a.pendingContext=d,a=Qr(j,P),a.payload={element:i},p=p===void 0?null:p,p!==null&&(a.callback=p),i=wo(x,a,P),i!==null&&(Ie(i,x,P,j),Ln(i,x,P)),P}function Qh(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 Hy(i,a){if(i=i.memoizedState,i!==null&&i.dehydrated!==null){var d=i.retryLane;i.retryLane=d!==0&&d<a?d:a}}function G_(i,a){Hy(i,a),(i=i.alternate)&&Hy(i,a)}function Rj(){return null}var Vy=typeof reportError=="function"?reportError:function(i){console.error(i)};function K_(i){this._internalRoot=i}em.prototype.render=K_.prototype.render=function(i){var a=this._internalRoot;if(a===null)throw Error(n(409));Zh(i,a,null,null)},em.prototype.unmount=K_.prototype.unmount=function(){var i=this._internalRoot;if(i!==null){this._internalRoot=null;var a=i.containerInfo;Nt(function(){Zh(null,i,null,null)}),a[mi]=null}};function em(i){this._internalRoot=i}em.prototype.unstable_scheduleHydration=function(i){if(i){var a=Mr();i={blockedOn:null,target:i,priority:a};for(var d=0;d<rs.length&&a!==0&&a<rs[d].priority;d++);rs.splice(d,0,i),d===0&&Nc(i)}};function Y_(i){return!(!i||i.nodeType!==1&&i.nodeType!==9&&i.nodeType!==11)}function tm(i){return!(!i||i.nodeType!==1&&i.nodeType!==9&&i.nodeType!==11&&(i.nodeType!==8||i.nodeValue!==" react-mount-point-unstable "))}function Gy(){}function Lj(i,a,d,p,x){if(x){if(typeof p=="function"){var j=p;p=function(){var ve=Qh(P);j.call(ve)}}var P=qy(a,p,i,0,null,!1,!1,"",Gy);return i._reactRootContainer=P,i[mi]=P.current,Nl(i.nodeType===8?i.parentNode:i),Nt(),P}for(;x=i.lastChild;)i.removeChild(x);if(typeof p=="function"){var ne=p;p=function(){var ve=Qh(oe);ne.call(ve)}}var oe=V_(i,0,!1,null,null,!1,!1,"",Gy);return i._reactRootContainer=oe,i[mi]=oe.current,Nl(i.nodeType===8?i.parentNode:i),Nt(function(){Zh(a,oe,d,p)}),oe}function nm(i,a,d,p,x){var j=d._reactRootContainer;if(j){var P=j;if(typeof x=="function"){var ne=x;x=function(){var oe=Qh(P);ne.call(oe)}}Zh(a,P,i,x)}else P=Lj(d,a,i,x,p);return Qh(P)}Sc=function(i){switch(i.tag){case 3:var a=i.stateNode;if(a.current.memoizedState.isDehydrated){var d=Hn(a.pendingLanes);d!==0&&(Qi(a,d|1),ye(a,he()),(tn&6)===0&&(la=he()+500,Pi()))}break;case 13:Nt(function(){var p=zi(i,1);if(p!==null){var x=G();Ie(p,i,1,x)}}),G_(i,1)}},Lo=function(i){if(i.tag===13){var a=zi(i,134217728);if(a!==null){var d=G();Ie(a,i,134217728,d)}G_(i,134217728)}},hs=function(i){if(i.tag===13){var a=se(i),d=zi(i,a);if(d!==null){var p=G();Ie(d,i,a,p)}G_(i,a)}},Mr=function(){return un},Rr=function(i,a){var d=un;try{return un=i,a()}finally{un=d}},Ar=function(i,a,d){switch(a){case"input":if(le(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 p=d[a];if(p!==i&&p.form===i.form){var x=Pa(p);if(!x)throw Error(n(90));ut(p),le(p,x)}}}break;case"textarea":rt(i,d);break;case"select":a=d.value,a!=null&&Ce(i,!!d.multiple,a,!1)}},ct=an,mt=Nt;var Ij={usingClientEntryPoint:!1,Events:[Vo,Oa,Pa,tt,Qe,an]},Kd={findFiberByHostInstance:Dr,bundleType:0,version:"18.3.1",rendererPackageName:"react-dom"},Oj={bundleType:Kd.bundleType,version:Kd.version,rendererPackageName:Kd.rendererPackageName,rendererConfig:Kd.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:A.ReactCurrentDispatcher,findHostInstanceByFiber:function(i){return i=ns(i),i===null?null:i.stateNode},findFiberByHostInstance:Kd.findFiberByHostInstance||Rj,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 sm=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!sm.isDisabled&&sm.supportsFiber)try{hn=sm.inject(Oj),Ds=sm}catch{}}return Ur.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=Ij,Ur.createPortal=function(i,a){var d=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!Y_(a))throw Error(n(200));return Mj(i,a,null,d)},Ur.createRoot=function(i,a){if(!Y_(i))throw Error(n(299));var d=!1,p="",x=Vy;return a!=null&&(a.unstable_strictMode===!0&&(d=!0),a.identifierPrefix!==void 0&&(p=a.identifierPrefix),a.onRecoverableError!==void 0&&(x=a.onRecoverableError)),a=V_(i,1,!1,null,null,d,!1,p,x),i[mi]=a.current,Nl(i.nodeType===8?i.parentNode:i),new K_(a)},Ur.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=ns(a),i=i===null?null:i.stateNode,i},Ur.flushSync=function(i){return Nt(i)},Ur.hydrate=function(i,a,d){if(!tm(a))throw Error(n(200));return nm(null,i,a,!0,d)},Ur.hydrateRoot=function(i,a,d){if(!Y_(i))throw Error(n(405));var p=d!=null&&d.hydratedSources||null,x=!1,j="",P=Vy;if(d!=null&&(d.unstable_strictMode===!0&&(x=!0),d.identifierPrefix!==void 0&&(j=d.identifierPrefix),d.onRecoverableError!==void 0&&(P=d.onRecoverableError)),a=qy(a,null,i,1,d??null,x,!1,j,P),i[mi]=a.current,Nl(i),p)for(i=0;i<p.length;i++)d=p[i],x=d._getVersion,x=x(d._source),a.mutableSourceEagerHydrationData==null?a.mutableSourceEagerHydrationData=[d,x]:a.mutableSourceEagerHydrationData.push(d,x);return new em(a)},Ur.render=function(i,a,d){if(!tm(a))throw Error(n(200));return nm(null,i,a,!1,d)},Ur.unmountComponentAtNode=function(i){if(!tm(i))throw Error(n(40));return i._reactRootContainer?(Nt(function(){nm(null,null,i,!1,function(){i._reactRootContainer=null,i[mi]=null})}),!0):!1},Ur.unstable_batchedUpdates=an,Ur.unstable_renderSubtreeIntoContainer=function(i,a,d,p){if(!tm(d))throw Error(n(200));if(i==null||i._reactInternals===void 0)throw Error(n(38));return nm(i,a,d,!1,p)},Ur.version="18.3.1-next-f1338f8080-20240426",Ur}var tw;function Ox(){if(tw)return Z_.exports;tw=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(),Z_.exports=Hj(),Z_.exports}var nw;function Vj(){if(nw)return rm;nw=1;var e=Ox();return rm.createRoot=e.createRoot,rm.hydrateRoot=e.hydrateRoot,rm}var Gj=Vj();const Kj=Gg(Gj),Px=[{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"]}];Px.map(e=>({id:e.id,label:e.label}));function Yj(e){return`theme-${String(e||"").trim()||"dark"}`}function sw(e){try{const t=document.documentElement,n=Array.from(t.classList).filter(r=>r.startsWith("theme-"));for(const r of n)t.classList.remove(r);t.classList.add(Yj(e))}catch{}}const Yp=[{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}],Jp=[{id:"compact",label:"Compact",density:.85},{id:"standard",label:"Standard",density:1},{id:"spacious",label:"Spacious",density:1.2}];function Jj(e){const t=String(e).trim();return Yp.find(n=>n.id===t)||Yp[1]}function Xj(e){const t=String(e).trim();return Jp.find(n=>n.id===t)||Jp[1]}function rw(e){try{const t=document.documentElement,n=Jj(e.font_scale||"md"),r=Xj(e.header_density||"standard");t.style.setProperty("--font-scale",String(n.scale)),t.style.setProperty("--header-density",String(r.density))}catch{}}const tp={sm:"(max-width: 767.98px)",md:"(max-width: 1023.98px)",short:"(max-height: 500px)"};function Zj(e){try{return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia(e).matches}catch{return!1}}function iw(e){const[t,n]=_.useState(()=>Zj(e));return _.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const r=window.matchMedia(e),o=()=>n(r.matches);return o(),typeof r.addEventListener=="function"?r.addEventListener("change",o):r.addListener(o),()=>{typeof r.removeEventListener=="function"?r.removeEventListener("change",o):r.removeListener(o)}},[e]),t}let Jd=null;function Qj(e,t){const n=Math.max(0,Math.round(e));if(!(t.scale<=1.01))return{vvHeight:n,keyboardInset:0};const r=Math.max(0,Math.min(n,Math.round(t.height))),o=Math.max(0,Math.round(e-t.height-Math.max(0,t.offsetTop)));return{vvHeight:r,keyboardInset:o}}function eS(){if(Jd)return Jd;if(typeof window>"u"||typeof document>"u")return()=>{};const e=window.visualViewport;if(!e)return()=>{};const t=document.documentElement;let n=0;const r=()=>{n=0;const{vvHeight:l,keyboardInset:c}=Qj(window.innerHeight,{height:e.height,offsetTop:e.offsetTop,scale:e.scale||1});t.style.setProperty("--vv-height",`${l}px`),t.style.setProperty("--keyboard-inset",`${c}px`)},o=()=>{n||(n=window.requestAnimationFrame(r))};return r(),e.addEventListener("resize",o),e.addEventListener("scroll",o),window.addEventListener("orientationchange",o),Jd=()=>{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"),Jd=null},Jd}var Dx=Ox();function wu(...e){return e.filter(Boolean).join(" ")}function si({value:e,options:t,placeholder:n="Select…",disabled:r=!1,loading:o=!1,searchable:l=!0,searchPlaceholder:c="Search…",allowCustom:u=!1,clearable:f=!1,minPopoverWidth:h=240,variant:m="panel",className:g,triggerClassName:y,ariaLabel:w,id:k,includeValueOption:b=!1,onOpen:S,customOptionLabel:N,validateCustomValue:R,onChange:T,renderOption:A,renderValue:W}){const z=_.useRef(null),J=_.useRef(null),K=_.useRef(null),re=_.useRef(S),te=_.useId(),Q=k||`af-select-${te.replace(/[^a-zA-Z0-9_-]/g,"")}`,D=`${Q}-listbox`,[$,E]=_.useState(!1),[L,M]=_.useState(""),[ee,F]=_.useState(0),[U,V]=_.useState("bottom"),[O,H]=_.useState({left:0,top:0,width:0});_.useEffect(()=>{re.current=S},[S]);const Y=_.useMemo(()=>{if(!b)return t;const me=String(e??"").trim();return!me||t.some(Ce=>Ce.value===me)?t:[...t,{value:me,label:me}]},[b,t,e]),ae=_.useMemo(()=>{const me=String(e??"");return Y.find(Ce=>Ce.value===me)||null},[Y,e]),ie=_.useMemo(()=>(ae==null?void 0:ae.label)||String(e||"").trim()||"",[ae,e]),_e=_.useMemo(()=>{const me=L.trim().toLowerCase();return me?Y.filter(Ce=>Ce.label.toLowerCase().includes(me)||Ce.value.toLowerCase().includes(me)):Y},[Y,L]),fe=_.useMemo(()=>{if(!u)return null;const me=L.trim();if(!me||Y.some(Je=>Je.value===me))return null;const Te=(R==null?void 0:R(me,{options:Y}))||"";return{value:me,label:N?N(me):`Use "${me}"`,disabled:!!Te,reason:Te}},[u,N,Y,L,R]),ge=_.useMemo(()=>{const me=fe?[fe,..._e]:_e;if(me.length>0)return me;const Ce=String(e??"").trim();return o&&Ce?[{value:Ce,label:ie||Ce}]:me},[fe,_e,o,ie,e]),Ne=_.useCallback(()=>{const me=z.current;if(!me)return;const Ce=me.getBoundingClientRect(),Te=Math.max(Ce.width,h),Je=Math.max(8,Math.min(Ce.left,window.innerWidth-Te-8)),rt=window.innerHeight-Ce.bottom,ht=Ce.top,lt=rt>=220||rt>=ht?"bottom":"top";V(lt);const Ct=lt==="bottom"?Ce.bottom+6:Ce.top-6;H({left:Je,top:Ct,width:Te})},[h]),Ue=_.useCallback(()=>{E(!1),M("")},[]);_.useEffect(()=>{var me;$&&((me=re.current)==null||me.call(re))},[$]),_.useEffect(()=>{if(!$)return;Ne();const me=()=>Ne();return window.addEventListener("resize",me),window.addEventListener("scroll",me,!0),()=>{window.removeEventListener("resize",me),window.removeEventListener("scroll",me,!0)}},[$,Ne]),_.useEffect(()=>{if(!$)return;const me=Ce=>{var Je,rt;const Te=Ce.target;Te&&((Je=z.current)!=null&&Je.contains(Te)||(rt=J.current)!=null&&rt.contains(Te)||Ue())};return document.addEventListener("mousedown",me,!0),()=>document.removeEventListener("mousedown",me,!0)},[$,Ue]),_.useEffect(()=>{if(!$)return;const me=Math.max(0,ge.findIndex(Ce=>Ce.value===e));F(me===-1?0:me),l&&setTimeout(()=>{var Ce;return(Ce=K.current)==null?void 0:Ce.focus()},0)},[$,l,e,ge]);const We=me=>{var Te;const Ce=ge.find(Je=>Je.value===me);Ce!=null&&Ce.disabled||(T(me),Ue(),(Te=z.current)==null||Te.focus())},ut=me=>{var Ce,Te;if(me.key==="Escape")return me.preventDefault(),Ue(),(Ce=z.current)==null||Ce.focus(),!0;if(me.key==="Tab")return Ue(),(Te=z.current)==null||Te.focus(),!1;if(me.key==="ArrowDown")return me.preventDefault(),F(Je=>Math.min(Je+1,Math.max(0,ge.length-1))),!0;if(me.key==="ArrowUp")return me.preventDefault(),F(Je=>Math.max(Je-1,0)),!0;if(me.key==="Home")return me.preventDefault(),F(0),!0;if(me.key==="End")return me.preventDefault(),F(Math.max(0,ge.length-1)),!0;if(me.key==="Enter"){me.preventDefault();const Je=ge[ee];return Je&&We(Je.value),!0}return!1},Fe=me=>{if(!r){if($){if(ut(me))return;if(me.key===" "&&!l){me.preventDefault();const Ce=ge[ee];Ce&&We(Ce.value)}return}(me.key==="Enter"||me.key===" "||me.key==="ArrowDown"||me.key==="ArrowUp")&&(me.preventDefault(),E(!0))}},et=!!String(e||"").trim(),$e=et?ie:n,Ve=fe!=null&&fe.disabled?fe.reason||"Unavailable":"",le=$&&ge.length>0?`${Q}-opt-${ee}`:void 0,be=s.jsx("span",{className:wu("af-select-value",!et&&"af-select-value--placeholder"),children:o&&!et?"Loading…":$e}),Pe=W?W(ae,String(e||"")):be;return s.jsxs("span",{className:wu("af-select",m==="pin"?"af-select--pin":"af-select--panel",g),children:[s.jsxs("button",{ref:z,id:Q,type:"button",className:wu("af-select-trigger",f&&et&&"af-select-trigger--clearable",y),disabled:r,onMouseDown:me=>me.stopPropagation(),onClick:me=>{me.stopPropagation(),!r&&E(Ce=>!Ce)},onKeyDown:Fe,role:l?void 0:"combobox","aria-haspopup":"listbox","aria-expanded":$,"aria-controls":$?D:void 0,"aria-activedescendant":l?void 0:le,"aria-label":w,children:[Pe,s.jsx("span",{className:wu("af-select-caret",$&&"af-select-caret--open"),children:"▾"})]}),f&&et?s.jsx("button",{type:"button",className:"af-select-clear-btn","aria-label":"Clear selection",disabled:r,onMouseDown:me=>{me.preventDefault(),me.stopPropagation()},onClick:me=>{var Ce;me.preventDefault(),me.stopPropagation(),T(""),Ue(),(Ce=z.current)==null||Ce.focus()},title:"Clear",children:"×"}):null,$?Dx.createPortal(s.jsxs("div",{ref:J,className:wu("af-select-popover",U==="top"&&"af-select-popover--top"),style:{position:"fixed",left:`${O.left}px`,top:`${O.top}px`,width:`${O.width}px`},onMouseDown:me=>me.stopPropagation(),onClick:me=>me.stopPropagation(),onWheel:me=>me.stopPropagation(),onKeyDown:ut,tabIndex:-1,children:[l?s.jsxs("div",{className:"af-select-search",children:[s.jsx("input",{ref:K,className:"af-select-search-input",value:L,onChange:me=>M(me.target.value),placeholder:c,onKeyDown:ut,role:"combobox","aria-expanded":!0,"aria-controls":D,"aria-activedescendant":le,"aria-invalid":!!Ve,"aria-describedby":Ve?`${Q}-custom-error`:void 0}),Ve?s.jsx("div",{id:`${Q}-custom-error`,className:"af-select-custom-error",role:"alert",children:Ve}):null]}):null,s.jsx("div",{className:"af-select-options",role:"listbox",id:D,"aria-label":w,children:o&&ge.length===0?s.jsx("div",{className:"af-select-empty",children:"Loading…"}):ge.length===0?s.jsx("div",{className:"af-select-empty",children:"No results"}):ge.map((me,Ce)=>{var Ct;const Te=me.value===e,Je=Ce===ee,rt=String(me.group||"").trim(),ht=Ce>0?String(((Ct=ge[Ce-1])==null?void 0:Ct.group)||"").trim():"",lt=!!rt&&rt!==ht;return s.jsxs(xe.Fragment,{children:[lt?s.jsx("div",{className:"af-select-group",role:"presentation",children:rt}):null,s.jsx("div",{id:`${Q}-opt-${Ce}`,role:"option","aria-selected":Te,className:wu("af-select-option",Te&&"af-select-option--selected",Je&&"af-select-option--highlighted",me.disabled&&"af-select-option--disabled"),title:me.disabled?me.reason||"Unavailable":void 0,onMouseEnter:()=>F(Ce),onMouseDown:Xt=>{Xt.preventDefault(),Xt.stopPropagation()},onClick:()=>We(me.value),"aria-disabled":me.disabled?!0:void 0,children:A?A(me,{selected:Te,highlighted:Je}):s.jsxs(s.Fragment,{children:[s.jsxs("span",{className:"af-select-option-label",children:[s.jsx("span",{children:me.label}),me.reason?s.jsx("small",{className:"af-select-option-reason",children:me.reason}):null]}),Te?s.jsx("span",{className:"af-select-check",children:"✓"}):null]})})]},me.value)})})]}),document.body):null]})}function tS(e){const t=new Set,n=[];for(const r of e||[]){if(!r||typeof r!="object")continue;const o=String(r.name||"").trim();!o||t.has(o)||(t.add(o),n.push({name:o,display_name:typeof r.display_name=="string"?r.display_name:void 0}))}return n.sort((r,o)=>r.name.localeCompare(o.name)),n}function nS(e){const t=new Set,n=[];for(const r of e||[]){const o=String(r||"").trim();!o||t.has(o)||(t.add(o),n.push(o))}return n.sort(),n}function Fx(e){const t=e.disabled===!0,n=e.layout||"stack",r=e.allowGatewayDefault!==!1,o=String(e.gatewayDefaultLabel||"(gateway default)"),l=String(e.providerLabel||"Provider"),c=String(e.modelLabel||"Model"),u=String(e.providerPlaceholder||"(select)"),f=String(e.modelPlaceholder||"(select)"),h=String(e.provider||"").trim(),m=String(e.model||"").trim(),g=tS(e.providers),y=nS(e.models),w=t||!!e.loadingProviders,k=t||!!e.loadingModels,b=[...r?[{value:"",label:o}]:[],...g.map(N=>({value:N.name,label:N.display_name?`${N.display_name} (${N.name})`:N.name}))],S=[...r?[{value:"",label:o}]:[],...y.map(N=>({value:N,label:N}))];return s.jsxs("div",{className:e.className,style:n==="row"?{display:"flex",gap:"10px",flexWrap:"wrap",alignItems:"flex-start"}:{display:"flex",flexDirection:"column",gap:"10px"},children:[s.jsxs("div",{style:n==="row"?{flex:"1 1 260px",minWidth:240}:void 0,children:[s.jsx("label",{children:l}),s.jsx(si,{value:h,options:b,placeholder:r?o:u,disabled:w,loading:!!e.loadingProviders,searchable:!0,allowCustom:e.allowCustomProvider===!0,clearable:r,variant:"panel",triggerClassName:e.selectClassName,ariaLabel:l,onChange:N=>e.onChange({provider:String(N||"").trim(),model:""})}),e.loadingProviders?s.jsx("div",{className:"mono muted",style:{fontSize:"12px",marginTop:"6px"},children:"Loading providers…"}):null,e.providerError?s.jsx("div",{className:"mono",style:{color:"var(--error)",fontSize:"12px",marginTop:"6px"},children:e.providerError}):null]}),s.jsxs("div",{style:n==="row"?{flex:"1 1 260px",minWidth:240}:void 0,children:[s.jsx("label",{children:c}),s.jsx(si,{value:m,options:S,placeholder:r?o:f,disabled:k,loading:!!e.loadingModels,searchable:!0,allowCustom:e.allowCustomModel===!0,clearable:r,variant:"panel",triggerClassName:e.selectClassName,ariaLabel:c,onChange:N=>e.onChange({provider:h,model:String(N||"").trim()})}),e.loadingModels?s.jsx("div",{className:"mono muted",style:{fontSize:"12px",marginTop:"6px"},children:"Loading models…"}):null,e.modelError?s.jsx("div",{className:"mono",style:{color:"var(--error)",fontSize:"12px",marginTop:"6px"},children:e.modelError}):null]})]})}function sS(e){if(e===!1||e&&typeof e=="object"&&e.mode==="off")return!1;if(!e||typeof e!="object")return;const t=e;if(!(t.mode!=="native_mtp"||!Number.isInteger(t.num_draft_tokens)||Number(t.num_draft_tokens)<1))return{mode:"native_mtp",num_draft_tokens:Number(t.num_draft_tokens),require_acceleration:!0}}function rS(e){var n;const t=(n=e==null?void 0:e.execution)==null?void 0:n.speculation;return!t||typeof t.supported!="boolean"?null:{supported:t.supported,ready:typeof t.ready=="boolean"?t.ready:null,reason:typeof t.reason=="string"?t.reason:null,supported_depths:t.supported&&Array.isArray(t.supported_depths)?[...new Set(t.supported_depths.filter(r=>typeof r=="number"&&Number.isInteger(r)&&r>0))]:[],default:Object.prototype.hasOwnProperty.call(t,"effective_default")?t.effective_default:t.default,requires_reload:typeof t.requires_reload=="boolean"?t.requires_reload:null}}function ow(e){const t=sS(e);return t===!1?"off":t?String(t.num_draft_tokens):""}function iS(e){if(e==="off")return!1;if(!(!/^\d+$/.test(e)||Number(e)<1))return{mode:"native_mtp",num_draft_tokens:Number(e),require_acceleration:!0}}function oS(e){const t=rS(e.capabilities),n=ow(e.value),r=(t==null?void 0:t.supported_depths.map(String))||[],o=ow(t==null?void 0:t.default),l=e.inheritLabel||"Workflow / Gateway default",c=o?`${l} (${o==="off"?"Off":`depth ${o}`})`:l,u=e.error||(e.loading?"Checking MTP capability…":t?t.reason||(t.requires_reload?"Model reload required before MTP can run.":t.ready===!1?"MTP is supported but not ready on this instance.":t.ready===null&&t.supported?"MTP support verified; loaded-instance readiness is unknown.":t.supported?"":"MTP is not supported on this model/backend."):"MTP capability unknown; no depth is assumed.");return s.jsxs("div",{className:"af-pmp__speculation",children:[s.jsx("label",{children:"MTP depth"}),s.jsx(si,{ariaLabel:"MTP depth",value:n,placeholder:c,disabled:e.disabled||e.loading,options:[{value:"",label:c},{value:"off",label:"Off"},...r.map(f=>({value:f,label:`Depth ${f}`})),...n&&n!=="off"&&!r.includes(n)?[{value:n,label:`Depth ${n} (saved; not available)`}]:[]],onChange:f=>e.onChange(iS(f))}),u&&!e.hideNote?s.jsx("div",{role:"status",className:"af-pmp__hint",children:u}):null]})}const aS="Reasoning and MTP choices appear when the gateway can describe the selected model.",lS="Reasoning choices appear when the gateway can describe the selected model.";function zx(e){var V,O;const t=e.disabled===!0,n=e.value||{provider:"",model:""},r=!String(n.provider||"").trim()&&!String(n.model||"").trim(),[o,l]=_.useState(!r),c=r&&!o,u=_.useRef(r);_.useEffect(()=>{r&&!u.current&&l(!1),u.current=r},[r]);const[f,h]=_.useState([]),[m,g]=_.useState(!1),[y,w]=_.useState(""),[k,b]=_.useState([]),[S,N]=_.useState(!1),[R,T]=_.useState(""),A=_.useRef(e);A.current=e,_.useEffect(()=>{if(c||t)return;let H=!0;return g(!0),(async()=>{try{const Y=await A.current.fetchProviders();if(!H)return;h(Array.isArray(Y)?Y:[]),w("")}catch(Y){if(!H)return;h([]),w(`#FALLBACK provider discovery failed: ${String((Y==null?void 0:Y.message)||Y)}`)}finally{H&&g(!1)}})(),()=>{H=!1}},[c,t]);const W=String(n.provider||"").trim();_.useEffect(()=>{if(!W||t){b([]),T(""),N(!1);return}let H=!0;return b([]),N(!0),T(""),(async()=>{try{const Y=await A.current.fetchModels(W);if(!H)return;b(Array.isArray(Y)?Y:[])}catch(Y){if(!H)return;b([]),T(`#FALLBACK model discovery failed: ${String((Y==null?void 0:Y.message)||Y)}`)}finally{H&&N(!1)}})(),()=>{H=!1}},[W,t]);const z=_.useMemo(()=>{const H=[...f];return W&&!H.some(Y=>Y.name===W)&&H.unshift({name:W}),H},[f,W]),J=String(n.model||"").trim(),K=_.useMemo(()=>{const H=[...k];return J&&!H.includes(J)&&H.unshift(J),H},[k,J]),re=e.defaultModeLabel||"Gateway default",te=e.customModeLabel||"Custom",Q=W||((V=e.effectiveDefault)==null?void 0:V.provider)||"",D=J||(W?"":(O=e.effectiveDefault)==null?void 0:O.model)||"",[$,E]=_.useState({levels:[],error:"",loading:!1}),L=!!e.fetchModelCapabilities,[M,ee]=_.useState();_.useEffect(()=>{let H=!0;if(ee(void 0),E({levels:[],error:"",loading:L&&!!D}),!(!L||!D||t))return A.current.fetchModelCapabilities(D,Q).then(Y=>{var fe;if(!H)return;if(Y!=null&&Y.error)throw new Error(String(Y.error));ee(Y);const ae=(Y==null?void 0:Y.capabilities)||Y||{},ie=ae.reasoning_levels||ae.thinking_levels,_e=Array.isArray(ie)?[...new Set(ie.filter(ge=>typeof ge=="string"&&!!ge.trim()))]:[];!_e.length&&ae.thinking_support===!0&&((fe=ae.thinking_control)!=null&&fe.prompt_disable_token)&&_e.push("off","auto"),E({levels:_e,error:"",loading:!1})}).catch(Y=>{H&&E({levels:[],error:String((Y==null?void 0:Y.message)||Y),loading:!1})}),()=>{H=!1}},[Q,D,L,t]);const F=e.inheritLabel||"Workflow / Gateway default",U=!c||e.optionsInDefaultMode!==!1;return s.jsxs("div",{className:`af-pmp${e.className?` ${e.className}`:""}`,children:[s.jsxs("div",{className:"af-pmp__seg",role:"tablist","aria-label":"Provider mode",children:[s.jsx("button",{type:"button",role:"tab","aria-selected":c,className:`af-pmp__seg-btn${c?" is-active":""}`,onClick:()=>{l(!1),e.onChange({...n,provider:"",model:"",...L?{reasoning:""}:{}})},disabled:t,children:re}),s.jsx("button",{type:"button",role:"tab","aria-selected":!c,className:`af-pmp__seg-btn${c?"":" is-active"}`,onClick:()=>{l(!0)},disabled:t,children:te})]}),c?s.jsx("div",{className:"af-pmp__hint",children:e.defaultHint||"The gateway picks its configured default provider and model for this task."}):s.jsx(Fx,{provider:W,model:J,providers:z,models:K,disabled:t,loadingProviders:m,loadingModels:S,providerError:y||void 0,modelError:R||void 0,providerLabel:e.providerLabel,modelLabel:e.modelLabel,allowGatewayDefault:!1,allowCustomProvider:e.allowCustom!==!1,allowCustomModel:e.allowCustom!==!1,onChange:H=>e.onChange({...n,provider:H.provider,model:H.model,...L?{reasoning:""}:{}})}),U&&L&&($.levels.length>0||n.reasoning)?s.jsxs("div",{className:"af-pmp__reasoning",children:[s.jsx("label",{children:e.reasoningLabel||"Reasoning effort"}),s.jsx(si,{ariaLabel:e.reasoningLabel||"Reasoning effort",placeholder:F,value:n.reasoning||"",options:[{value:"",label:F},...$.levels.map(H=>({value:H,label:H})),...n.reasoning&&!$.levels.includes(n.reasoning)?[{value:n.reasoning,label:`${n.reasoning} (saved; not advertised)`}]:[]],disabled:t||$.loading,onChange:H=>e.onChange({...n,reasoning:H})})]}):null,U&&e.enableSpeculation?s.jsx(oS,{value:n.speculation,inheritLabel:F,onChange:H=>e.onChange({...n,speculation:H}),capabilities:M,disabled:t,loading:$.loading,hideNote:!!$.error}):null,U&&$.error?s.jsxs("div",{role:"status",className:"af-pmp__hint","data-discovery":"unavailable",children:[e.enableSpeculation?aS:lS,s.jsxs("details",{className:"af-pmp__details",children:[s.jsx("summary",{children:"Technical details"}),s.jsx("span",{children:$.error})]})]}):null]})}function aw(...e){return e.filter(Boolean).join(" ")}function cS({kicker:e="AbstractGateway connection",title:t="Connect to AbstractGateway",description:n="Sign in with the Gateway user token assigned by the Gateway admin.",statusLabel:r="Not signed in",statusTone:o="neutral",showGatewayUrl:l=!1,gatewayUrl:c="",gatewayUrlPlaceholder:u="http://127.0.0.1:8080",onGatewayUrlChange:f,userId:h,userPlaceholder:m="admin",onUserIdChange:g,token:y,tokenPlaceholder:w="Paste Gateway user token",showToken:k=!1,onTokenChange:b,onShowTokenChange:S,remember:N=!1,rememberLabel:R="Remember this browser",onRememberChange:T,loading:A=!1,submitting:W=!1,submitDisabled:z=!1,submitLabel:J="Sign in",submittingLabel:K="Signing in...",closeLabel:re="Close",signOutLabel:te="Sign out",showClose:Q=!1,showSignOut:D=!1,error:$,message:E,className:L,onSubmit:M,onClose:ee,onSignOut:F}){const U=A||W,V=U||z||!String(h||"").trim()||!String(y||"").trim(),O=H=>{H.preventDefault(),!V&&M()};return s.jsxs("form",{className:aw("af-gateway-signin",L),onSubmit:O,children:[s.jsxs("div",{className:"af-gateway-signin__hero",children:[s.jsxs("div",{children:[s.jsx("div",{className:"af-gateway-signin__kicker",children:e}),s.jsx("h2",{children:t}),n?s.jsx("p",{children:n}):null]}),s.jsx("div",{className:"af-gateway-signin__mark","aria-hidden":"true",children:"↔"})]}),s.jsx("div",{className:"af-gateway-signin__status-row",children:s.jsx("span",{className:aw("af-gateway-signin__status",`af-gateway-signin__status--${o}`),children:r})}),s.jsxs("div",{className:"af-gateway-signin__form",children:[l?s.jsxs(s.Fragment,{children:[s.jsx("label",{className:"af-gateway-signin__label",htmlFor:"gateway-session-url",children:"Gateway URL"}),s.jsx("input",{id:"gateway-session-url",value:c,onChange:H=>f==null?void 0:f(H.target.value),placeholder:u,autoComplete:"url",disabled:U})]}):null,s.jsx("label",{className:"af-gateway-signin__label",htmlFor:"gateway-session-user",children:"Gateway user"}),s.jsx("input",{id:"gateway-session-user",value:h,onChange:H=>g(H.target.value),placeholder:m,autoComplete:"username",disabled:U}),s.jsx("label",{className:"af-gateway-signin__label",htmlFor:"gateway-session-token",children:"Gateway token"}),s.jsxs("div",{className:"af-gateway-signin__token-input",children:[s.jsx("input",{id:"gateway-session-token",type:k?"text":"password",value:y,onChange:H=>b(H.target.value),placeholder:w,autoComplete:"off","data-1p-ignore":"","data-lpignore":"true","data-bwignore":"",spellCheck:!1,disabled:U}),s.jsx("button",{className:"af-gateway-signin__secondary",type:"button",onClick:()=>S==null?void 0:S(!k),disabled:U,children:k?"Hide":"Show"})]}),s.jsxs("label",{className:"af-gateway-signin__checkbox",children:[s.jsx("input",{type:"checkbox",checked:!!N,onChange:H=>T==null?void 0:T(H.target.checked),disabled:U}),R]})]}),$?s.jsx("div",{className:"af-gateway-signin__message af-gateway-signin__message--error",children:$}):null,!$&&E?s.jsx("div",{className:"af-gateway-signin__message af-gateway-signin__message--ok",children:E}):null,s.jsxs("div",{className:"af-gateway-signin__actions",children:[Q?s.jsx("button",{className:"af-gateway-signin__secondary",type:"button",onClick:ee,disabled:U,children:re}):null,D?s.jsx("button",{className:"af-gateway-signin__secondary",type:"button",onClick:()=>void(F==null?void 0:F()),disabled:U,children:te}):null,s.jsx("button",{className:"af-gateway-signin__primary",type:"submit",disabled:V,children:W?K:J})]})]})}function uS(e){return e==="light"?"Light":"Dark"}function dS(e){const t=e.themes&&e.themes.length?e.themes:Px,n=e.showSwatches!==!1,r=e.variant||"panel",o=_.useMemo(()=>{const c={};for(const u of t)c[u.id]=u;return c},[t]),l=_.useMemo(()=>t.map(c=>({value:c.id,label:c.label,group:uS(c.group)})),[t]);return s.jsx(si,{value:e.value,options:l,placeholder:e.placeholder||"Select theme…",disabled:e.disabled===!0,searchable:!0,allowCustom:!1,clearable:!1,variant:r,className:e.className,triggerClassName:e.triggerClassName,onChange:c=>e.onChange(String(c||"").trim()),renderValue:(c,u)=>{const f=String(u||"").trim(),h=o[f],m=(h==null?void 0:h.label)||f||e.placeholder||"Select theme…",g=(h==null?void 0:h.swatches)||null,y=!f;return s.jsxs("span",{className:"af-theme-value",children:[s.jsx("span",{className:`af-theme-label ${y?"af-theme-label--placeholder":""}`.trim(),children:m}),n&&g?s.jsx("span",{className:"af-theme-swatches","aria-hidden":"true",children:g.map((w,k)=>s.jsx("span",{className:"af-theme-swatch",style:{background:w}},`${f}:${k}`))}):null]})},renderOption:(c,u)=>{const f=String(c.value||"").trim(),h=o[f],m=(h==null?void 0:h.swatches)||null;return s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"af-theme-option-label",children:c.label}),s.jsxs("span",{className:"af-theme-option-right",children:[n&&m?s.jsx("span",{className:"af-theme-swatches","aria-hidden":"true",children:m.map((g,y)=>s.jsx("span",{className:"af-theme-swatch",style:{background:g}},`${f}:${y}`))}):null,u.selected?s.jsx("span",{className:"af-select-check",children:"✓"}):null]})]})}})}function fS(e){const t=e.scales&&e.scales.length?e.scales:Yp,n=e.variant||"panel",r=_.useMemo(()=>t.map(o=>({value:o.id,label:o.label})),[t]);return s.jsx(si,{value:e.value,options:r,placeholder:e.placeholder||"Font size…",disabled:e.disabled===!0,searchable:!1,allowCustom:!1,clearable:!1,variant:n,className:e.className,triggerClassName:e.triggerClassName,onChange:o=>e.onChange(String(o||"").trim())})}function hS(e){const t=e.densities&&e.densities.length?e.densities:Jp,n=e.variant||"panel",r=_.useMemo(()=>t.map(o=>({value:o.id,label:o.label})),[t]);return s.jsx(si,{value:e.value,options:r,placeholder:e.placeholder||"Header size…",disabled:e.disabled===!0,searchable:!1,allowCustom:!1,clearable:!1,variant:n,className:e.className,triggerClassName:e.triggerClassName,onChange:o=>e.onChange(String(o||"").trim())})}const mS=new Set(["board","inbox","server","agent","playCircle","list","gear"]);function _S(e){switch(e){case"chat":return s.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H8l-5 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"});case"plus":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M12 5v14"}),s.jsx("path",{d:"M5 12h14"})]});case"history":return s.jsxs(s.Fragment,{children:[s.jsx("circle",{cx:"12",cy:"12",r:"9"}),s.jsx("path",{d:"M12 7v5l3 3"})]});case"refresh":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M21 12a9 9 0 0 0-15.5-6.4L3 8"}),s.jsx("path",{d:"M3 3v5h5"}),s.jsx("path",{d:"M3 12a9 9 0 0 0 15.5 6.4L21 16"}),s.jsx("path",{d:"M21 21v-5h-5"})]});case"cog":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"}),s.jsx("circle",{cx:"12",cy:"12",r:"3"})]});case"activity":return s.jsx("path",{d:"M22 12h-4l-3 9L9 3l-3 9H2"});case"settings":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M4 6h16"}),s.jsx("circle",{cx:"8",cy:"6",r:"2"}),s.jsx("path",{d:"M4 12h16"}),s.jsx("circle",{cx:"16",cy:"12",r:"2"}),s.jsx("path",{d:"M4 18h16"}),s.jsx("circle",{cx:"10",cy:"18",r:"2"})]});case"user":return s.jsxs(s.Fragment,{children:[s.jsx("circle",{cx:"12",cy:"8",r:"4"}),s.jsx("path",{d:"M4 21a8 8 0 0 1 16 0"})]});case"bot":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M12 2v3"}),s.jsx("rect",{x:"5",y:"6",width:"14",height:"14",rx:"3"}),s.jsx("circle",{cx:"9",cy:"13",r:"1",fill:"currentColor",stroke:"none"}),s.jsx("circle",{cx:"15",cy:"13",r:"1",fill:"currentColor",stroke:"none"}),s.jsx("path",{d:"M9 17h6"})]});case"paperclip":return s.jsx("path",{d:"M21.44 11.05l-9.19 9.19a5.5 5.5 0 0 1-7.78-7.78l9.19-9.19a3.5 3.5 0 0 1 4.95 4.95l-9.2 9.19a1.5 1.5 0 0 1-2.12-2.12l8.49-8.48"});case"mic":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M12 14a3 3 0 0 0 3-3V5a3 3 0 0 0-6 0v6a3 3 0 0 0 3 3z"}),s.jsx("path",{d:"M19 11a7 7 0 0 1-14 0"}),s.jsx("path",{d:"M12 18v4"}),s.jsx("path",{d:"M8 22h8"})]});case"speaker":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M11 5L6 9H2v6h4l5 4V5z"}),s.jsx("path",{d:"M15.5 8.5a5 5 0 0 1 0 7"}),s.jsx("path",{d:"M18 6a9 9 0 0 1 0 12"})]});case"pause":return s.jsxs(s.Fragment,{children:[s.jsx("rect",{x:"6",y:"4",width:"4",height:"16",rx:"1",fill:"currentColor",stroke:"none"}),s.jsx("rect",{x:"14",y:"4",width:"4",height:"16",rx:"1",fill:"currentColor",stroke:"none"})]});case"terminal":return s.jsxs(s.Fragment,{children:[s.jsx("rect",{x:"3",y:"4",width:"18",height:"16",rx:"2",ry:"2"}),s.jsx("path",{d:"M7 9l3 3-3 3"}),s.jsx("path",{d:"M12 15h5"})]});case"edit":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M12 20h9"}),s.jsx("path",{d:"M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4 12.5-12.5z"})]});case"download":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),s.jsx("path",{d:"M7 10l5 5 5-5"}),s.jsx("path",{d:"M12 15V3"})]});case"loader":return s.jsx("path",{d:"M21 12a9 9 0 1 1-3.3-6.9"});case"info":return s.jsxs(s.Fragment,{children:[s.jsx("circle",{cx:"12",cy:"12",r:"10"}),s.jsx("path",{d:"M12 16v-4"}),s.jsx("circle",{cx:"12",cy:"8",r:"0.75",fill:"currentColor",stroke:"none"})]});case"warning":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M12 3l10 18H2L12 3z"}),s.jsx("path",{d:"M12 9v4"}),s.jsx("circle",{cx:"12",cy:"17",r:"0.75",fill:"currentColor",stroke:"none"})]});case"error":return s.jsxs(s.Fragment,{children:[s.jsx("circle",{cx:"12",cy:"12",r:"10"}),s.jsx("path",{d:"M15 9l-6 6"}),s.jsx("path",{d:"M9 9l6 6"})]});case"copy":return s.jsxs(s.Fragment,{children:[s.jsx("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2"}),s.jsx("path",{d:"M5 15V5a2 2 0 0 1 2-2h10"})]});case"check":return s.jsx("path",{d:"M20 6L9 17l-5-5"});case"x":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M18 6L6 18"}),s.jsx("path",{d:"M6 6l12 12"})]});case"chevronDown":return s.jsx("path",{d:"M6 9l6 6 6-6"});case"chevronRight":return s.jsx("path",{d:"M9 18l6-6-6-6"});case"trash":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M3 6h18"}),s.jsx("path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"}),s.jsx("path",{d:"M6 6l1 16h10l1-16"}),s.jsx("path",{d:"M10 11v6"}),s.jsx("path",{d:"M14 11v6"})]});case"send":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M22 2L11 13"}),s.jsx("path",{d:"M22 2L15 22l-4-9-9-4 20-7z"})]});case"thumbsUp":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M7 10v11"}),s.jsx("path",{d:"M7 10l4.5-8a2 2 0 0 1 3.6 1.5L14 8h5.2a2 2 0 0 1 2 2.4l-1.6 8a2 2 0 0 1-2 1.6H7"})]});case"thumbsDown":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M17 14V3"}),s.jsx("path",{d:"M17 14l-4.5 8a2 2 0 0 1-3.6-1.5L10 16H4.8a2 2 0 0 1-2-2.4l1.6-8a2 2 0 0 1 2-1.6H17"})]});case"thumbsUpFilled":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M7 10v11"}),s.jsx("path",{d:"M7 10l4.5-8a2 2 0 0 1 3.6 1.5L14 8h5.2a2 2 0 0 1 2 2.4l-1.6 8a2 2 0 0 1-2 1.6H7z",fill:"currentColor",stroke:"none"})]});case"thumbsDownFilled":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M17 14V3"}),s.jsx("path",{d:"M17 14l-4.5 8a2 2 0 0 1-3.6-1.5L10 16H4.8a2 2 0 0 1-2-2.4l1.6-8a2 2 0 0 1 2-1.6H17z",fill:"currentColor",stroke:"none"})]});case"board":return s.jsxs(s.Fragment,{children:[s.jsx("rect",{x:"1.5",y:"2",width:"3.6",height:"12",rx:"1"}),s.jsx("rect",{x:"6.2",y:"2",width:"3.6",height:"8.5",rx:"1"}),s.jsx("rect",{x:"10.9",y:"2",width:"3.6",height:"5.5",rx:"1"})]});case"inbox":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M2 9.5 L4 3.5 h8 l2 6"}),s.jsx("path",{d:"M2 9.5 v3 h12 v-3"}),s.jsx("path",{d:"M2 9.5 h3.4 l1 1.6 h3.2 l1-1.6 H14"})]});case"server":return s.jsxs(s.Fragment,{children:[s.jsx("rect",{x:"2",y:"2.5",width:"12",height:"4.6",rx:"1.2"}),s.jsx("rect",{x:"2",y:"8.9",width:"12",height:"4.6",rx:"1.2"}),s.jsx("circle",{cx:"4.6",cy:"4.8",r:"0.8",fill:"currentColor",stroke:"none"}),s.jsx("circle",{cx:"4.6",cy:"11.2",r:"0.8",fill:"currentColor",stroke:"none"})]});case"agent":return s.jsxs(s.Fragment,{children:[s.jsx("rect",{x:"3",y:"4.5",width:"10",height:"8",rx:"2"}),s.jsx("path",{d:"M8 4.5V2.2"}),s.jsx("circle",{cx:"8",cy:"1.8",r:"0.9",fill:"currentColor",stroke:"none"}),s.jsx("circle",{cx:"5.8",cy:"8.4",r:"0.9",fill:"currentColor",stroke:"none"}),s.jsx("circle",{cx:"10.2",cy:"8.4",r:"0.9",fill:"currentColor",stroke:"none"})]});case"playCircle":return s.jsxs(s.Fragment,{children:[s.jsx("circle",{cx:"8",cy:"8",r:"6.2"}),s.jsx("path",{d:"M6.5 5.6 L11 8 L6.5 10.4 Z",fill:"currentColor",stroke:"none"})]});case"list":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M2.5 4h11"}),s.jsx("path",{d:"M2.5 8h11"}),s.jsx("path",{d:"M2.5 12h7"})]});case"gear":return s.jsxs(s.Fragment,{children:[s.jsx("circle",{cx:"8",cy:"8",r:"2.2"}),s.jsx("path",{d:"M8 1.6v2"}),s.jsx("path",{d:"M8 12.4v2"}),s.jsx("path",{d:"M1.6 8h2"}),s.jsx("path",{d:"M12.4 8h2"}),s.jsx("path",{d:"M3.5 3.5l1.4 1.4"}),s.jsx("path",{d:"M11.1 11.1l1.4 1.4"}),s.jsx("path",{d:"M12.5 3.5l-1.4 1.4"}),s.jsx("path",{d:"M4.9 11.1l-1.4 1.4"})]});case"sparkle":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M12 3l1.9 5.1L19 10l-5.1 1.9L12 17l-1.9-5.1L5 10l5.1-1.9z"}),s.jsx("path",{d:"M18.5 15.5l.8 2.2 2.2.8-2.2.8-.8 2.2-.8-2.2-2.2-.8 2.2-.8z"})]});case"contrast":return s.jsxs(s.Fragment,{children:[s.jsx("circle",{cx:"12",cy:"12",r:"9"}),s.jsx("path",{d:"M12 3a9 9 0 0 1 0 18z",fill:"currentColor",stroke:"none"})]});case"logout":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"}),s.jsx("path",{d:"M16 17l5-5-5-5"}),s.jsx("path",{d:"M21 12H9"})]});case"play":return s.jsx("path",{d:"M7 4.5v15a1 1 0 0 0 1.5.86l12-7.5a1 1 0 0 0 0-1.72l-12-7.5A1 1 0 0 0 7 4.5z",fill:"currentColor",stroke:"none"});case"stop":return s.jsx("rect",{x:"5",y:"5",width:"14",height:"14",rx:"2",fill:"currentColor",stroke:"none"});case"folder":return s.jsx("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"});case"file":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),s.jsx("path",{d:"M14 2v6h6"})]});case"archive":return s.jsxs(s.Fragment,{children:[s.jsx("rect",{x:"2",y:"3",width:"20",height:"5",rx:"1"}),s.jsx("path",{d:"M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8"}),s.jsx("path",{d:"M10 12h4"})]});case"unarchive":return s.jsxs(s.Fragment,{children:[s.jsx("rect",{x:"2",y:"3",width:"20",height:"5",rx:"1"}),s.jsx("path",{d:"M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8"}),s.jsx("path",{d:"M12 18v-6"}),s.jsx("path",{d:"m9 14 3-3 3 3"})]});case"clock":return s.jsxs(s.Fragment,{children:[s.jsx("circle",{cx:"12",cy:"12",r:"10"}),s.jsx("path",{d:"M12 6v6h4"})]});case"book":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M2 4h6a4 4 0 0 1 4 4v13a3 3 0 0 0-3-3H2z"}),s.jsx("path",{d:"M22 4h-6a4 4 0 0 0-4 4v13a3 3 0 0 1 3-3h7z"})]});case"compose":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),s.jsx("path",{d:"M18.4 2.6a2.1 2.1 0 0 1 3 3L12 15l-4 1 1-4z"})]});default:return null}}function Be({name:e,size:t=16,className:n,title:r,...o}){const l=r?void 0:!0,c=mS.has(e);return s.jsxs("svg",{width:t,height:t,viewBox:c?"0 0 16 16":"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:c?1.4:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,"aria-hidden":l,role:r?"img":"presentation",...o,children:[r?s.jsx("title",{children:r}):null,_S(e)]})}const Ef="api/gateway",Kf="api/connection/gateway";function it(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?`${Ef}/${t}`:Ef}function Kg(e,t){const n=String(t||"");if(n.startsWith("/"))throw new Error(`joinBaseUrl takes a relative path, got ${JSON.stringify(n)}.`);let r=String(e??"");for(;r.endsWith("/");)r=r.slice(0,-1);return r?`${r}/${n}`:n}function pS(e){const t=String(e||""),n=`/${Ef}/`;if(!t.startsWith(n)||t.length===n.length)throw new Error(`Not a gateway API path: ${JSON.stringify(t)} (expected ${JSON.stringify(n)}…).`);const r=t.slice(n.length).split(/[?#]/,1)[0];if(/\\|%2f|%5c/i.test(r))throw new Error(`Not a gateway API path: ${JSON.stringify(t)} (encoded slash or backslash).`);for(const o of r.split("/")){const l=o.replace(/%2e/gi,".");if(l==="."||l==="..")throw new Error(`Not a gateway API path: ${JSON.stringify(t)} (a "." or ".." segment).`)}return t.slice(1)}function gS(e){return!String(e.unavailableReason||"").trim()&&!e.busy}function yS(e){return gS(e)?!e.checked:null}let wS=0;function Ni(e){const{label:t,checked:n,onChange:r,description:o,reasonVisible:l=!0,describedBy:c,hint:u,busy:f=!1,variant:h="inline",ariaLabel:m,className:g,id:y,action:w}=e,k=String(e.unavailableReason||"").trim(),b=!!k,S=c||(y?`${y}-reason`:b?`af-switch-reason-${++wS}`:void 0),N=["af-switch",h==="row"?"af-switch--row":h==="sm"?"af-switch--sm":"",b?"af-switch--unavailable":"",g||""].filter(Boolean).join(" "),R=A=>{const W=yS({checked:n,unavailableReason:k,busy:f});if(W===null){A.preventDefault();return}r==null||r(W)},T=s.jsxs("button",{type:"button",role:"switch",id:y,className:N,"data-action":w,"aria-checked":n?"true":"false","aria-disabled":b?"true":void 0,"aria-describedby":b?S:void 0,"aria-busy":f?"true":void 0,"aria-label":m,"aria-description":o?void 0:u,title:b?u?`${k}
|
|
41
|
-
${u}`:k:u,onClick:R,children:[s.jsx("span",{className:"af-switch__track","aria-hidden":"true",children:s.jsx("span",{className:"af-switch__thumb"})}),s.jsxs("span",{className:"af-switch__text",children:[s.jsx("span",{className:"af-switch__label",children:t}),o?s.jsx("span",{className:"af-switch__desc",children:o}):null]})]});return!b||c?T:s.jsxs("span",{className:h==="row"?"af-switch-wrap af-switch-wrap--row":"af-switch-wrap",children:[T,s.jsx("span",{id:S,className:l?"af-switch__reason":"af-switch__reason af-switch__reason--hidden",children:k})]})}function vS(e){const t=String(e.unavailableReason||"").trim(),n=["af-switch","af-switch--native",e.variant==="row"?"af-switch--row":"",t?"af-switch--unavailable":""].filter(Boolean).join(" "),r=t?`${e.id||e.name}-reason`:void 0,o=s.jsxs("label",{className:n,title:t||void 0,"data-action":e.action,children:[s.jsx("input",{type:"checkbox",role:"switch",className:"af-switch__input",id:e.id,name:e.name,defaultChecked:e.defaultChecked,onChange:l=>{var c;return(c=e.onChange)==null?void 0:c.call(e,l.target.checked)},disabled:!!t,"aria-describedby":r}),s.jsx("span",{className:"af-switch__track","aria-hidden":"true",children:s.jsx("span",{className:"af-switch__thumb"})}),s.jsx("span",{className:"af-switch__text",children:s.jsx("span",{className:"af-switch__label",children:e.label})})]});return t?s.jsxs("span",{className:e.variant==="row"?"af-switch-wrap af-switch-wrap--row":"af-switch-wrap",children:[o,s.jsx("span",{id:r,className:"af-switch__reason",children:t})]}):o}const xS=150,Bx="data-af-tip";function bS(e,t,n,r=6,o=8){let l="top",c=e.top-r-t.height;if(c<o){const h=e.bottom+r;(h+t.height<=n.height-o||n.height-e.bottom>e.top)&&(c=h,l="bottom")}let f=(e.left+e.right)/2-t.width/2;return f=Math.max(o,Math.min(f,n.width-o-t.width)),c=Math.max(o,Math.min(c,n.height-o-t.height)),{top:Math.round(c),left:Math.round(f),side:l}}let lw=0;function Ux(e){return e?String(e.getAttribute(Bx)||"").trim():""}function np(e,t){const n=e;if(!n||typeof n.closest!="function")return null;const r=n.closest(`[${Bx}]`);return!r||!t.contains(r)||!Ux(r)?null:r}function kS(e,t={}){if(!e)throw new Error("bindAfTooltips: a root (document or element) is required");const n=e.nodeType===9?e:e.ownerDocument,r=n.defaultView||globalThis,o=typeof t.delayMs=="number"&&t.delayMs>=0?t.delayMs:xS;lw+=1;const l=n.createElement("div");l.className="af-tooltip",l.setAttribute("role","tooltip");const c=`af-tooltip-${lw}`;l.setAttribute("id",c),l.hidden=!0,(n.body||n.documentElement).appendChild(l);let u=null,f=null,h=null,m=null,g=!1,y=null;const w=()=>{h&&clearTimeout(h),h=null,f=null},k=()=>{m&&clearTimeout(m),m=null},b=()=>{if(!u)return;const L=u.getBoundingClientRect(),M=l.getBoundingClientRect(),ee=bS(L,{width:M.width,height:M.height},{width:r.innerWidth,height:r.innerHeight});l.style.top=`${ee.top}px`,l.style.left=`${ee.left}px`,l.setAttribute("data-side",ee.side)},S=()=>{if(w(),k(),!u)return;String(u.getAttribute("aria-describedby")||"").split(/\s+/).includes(c)&&(y?u.setAttribute("aria-describedby",y):u.removeAttribute("aria-describedby")),y=null,u=null,l.hidden=!0,l.textContent=""},N=L=>{w(),k(),u&&u!==L&&S();const M=Ux(L);if(!M||L.isConnected===!1)return;if(u=L,l.textContent=M,l.hidden=!1,String(L.getAttribute("aria-label")||"").trim()!==M){const F=L.getAttribute("aria-describedby");y=F&&F!==c?F:null,L.setAttribute("aria-describedby",y?`${y} ${c}`:c)}b()},R=L=>{k(),u!==L&&f!==L&&(w(),f=L,h=setTimeout(()=>{const M=f;h=null,f=null,M&&N(M)},o))},T=()=>{w(),u&&(k(),m=setTimeout(S,100))},A=L=>{try{if(typeof L.matches=="function")return L.matches(":focus-visible")}catch{}return g},W=L=>{if(L.pointerType==="touch")return;if(l.contains(L.target)){k();return}const ee=np(L.target,e);ee&&R(ee)},z=L=>{const ee=L.relatedTarget||null;if(!(ee&&(l.contains(ee)||u&&u.contains(ee)||f&&f.contains(ee)))){if(f&&!u){w();return}u&&T()}},J=L=>{const M=L.relatedTarget||null;M&&(l.contains(M)||u&&u.contains(M))||T()},K=L=>{const M=np(L.target,e);M&&A(M)&&R(M)},re=L=>{const M=np(L.target,e);M&&(M===u||M===f)&&S()},te=()=>{g=!1,S()},Q=L=>{if(L.key==="Escape"||L.key==="Esc"){u?(L.preventDefault(),S()):w();return}!L.metaKey&&!L.ctrlKey&&!L.altKey&&(g=!0)},D=()=>S(),$=e;$.addEventListener("pointerover",W),$.addEventListener("pointerout",z),$.addEventListener("focusin",K),$.addEventListener("focusout",re),l.addEventListener("pointerover",W),l.addEventListener("pointerout",J),n.addEventListener("pointerdown",te,!0),r.addEventListener("keydown",Q,!0),r.addEventListener("scroll",D,!0),r.addEventListener("resize",D);let E=!1;return()=>{E||(E=!0,S(),$.removeEventListener("pointerover",W),$.removeEventListener("pointerout",z),$.removeEventListener("focusin",K),$.removeEventListener("focusout",re),l.removeEventListener("pointerover",W),l.removeEventListener("pointerout",J),n.removeEventListener("pointerdown",te,!0),r.removeEventListener("keydown",Q,!0),r.removeEventListener("scroll",D,!0),r.removeEventListener("resize",D),l.parentNode&&l.parentNode.removeChild(l))}}const im=new WeakMap;function jS(e){let t=im.get(e);t||(t={count:0,release:kS(e)},im.set(e,t)),t.count+=1;let n=!1;return()=>{if(n)return;n=!0;const r=im.get(e);r&&(r.count-=1,r.count<=0&&(r.release(),im.delete(e)))}}function Yf(){_.useEffect(()=>{if(!(typeof document>"u"))return jS(document)},[])}async function Xp(e=Kf){const t=await fetch(e),n=await t.json().catch(()=>null);if(!t.ok){const r=n&&typeof n=="object"&&n.detail?String(n.detail):`HTTP ${t.status}`;throw new Error(r)}return n}async function SS(e,t=Kf){const n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),r=await n.json().catch(()=>null);if(!n.ok){const o=r&&typeof r=="object"&&r.detail?String(r.detail):`HTTP ${n.status}`;throw new Error(o)}return r}async function Wx(e=Kf){const t=await fetch(e,{method:"DELETE"});if(!t.ok){const n=await t.json().catch(()=>({})),r=n&&typeof n=="object"&&n.detail?String(n.detail):`HTTP ${t.status}`;throw new Error(r)}}function sp(e){let t=String(e||"").trim();for(let n=0;n<2&&t;n+=1){try{const l=JSON.parse(t);if(typeof l=="string"&&l!==t){t=l.trim();continue}}catch{}const r=t[0],o=t[t.length-1];if(r==='"'&&o==='"'||r==="'"&&o==="'"){t=t.slice(1,-1).trim();continue}break}return t.replace(/\/+$/,"")}function qx(e){var l,c;if(!e)return{label:"Signed out",tone:"warn"};if(!e.has_session)return{label:"Signed out",tone:"warn"};const t=e.gateway||{},n=(l=t.principal)==null?void 0:l.user_id,r=(c=t.principal)==null?void 0:c.runtime_id;if(t.ok&&n)return{label:`Signed in as ${n}${r?` · runtime ${r}`:""}`,tone:"ok"};if(t.ok)return{label:"Signed in",tone:"ok"};const o=t.error||t.detail;return typeof o=="string"&&o.trim()?{label:"Session rejected — sign in again",tone:"err"}:{label:"Sign in required",tone:"err"}}function NS(e){const t=e.connectionPath||Kf,[n,r]=_.useState(!1),[o,l]=_.useState(!1),[c,u]=_.useState(null),[f,h]=_.useState(!1);_.useEffect(()=>{e.isOpen||h(!1)},[e.isOpen]);const[m,g]=_.useState(e.defaultGatewayUrl||"http://127.0.0.1:8080"),[y,w]=_.useState("admin"),[k,b]=_.useState(""),[S,N]=_.useState(!1),[R,T]=_.useState(!0),[A,W]=_.useState(""),[z,J]=_.useState(""),K=_.useMemo(()=>qx(c),[c]),re=$=>{var E;u($),(E=e.onStatusChange)==null||E.call(e,$)},te=_.useRef(!1);if(_.useEffect(()=>{var E;if(!e.isOpen)return;const $=!te.current;if(te.current=!0,$&&e.initialStatus!==void 0&&e.initialStatus!==null){const L=e.initialStatus;re(L),typeof L.gateway_url=="string"&&L.gateway_url.trim()&&g(sp(L.gateway_url));const M=(E=L.gateway)==null?void 0:E.principal;M!=null&&M.user_id&&w(M.user_id);return}r(!0),W(""),Xp(t).then(L=>{var ee;re(L),typeof L.gateway_url=="string"&&L.gateway_url.trim()&&g(sp(L.gateway_url));const M=(ee=L.gateway)==null?void 0:ee.principal;M!=null&&M.user_id&&w(M.user_id)}).catch(L=>W(`Failed to load connection status: ${String((L==null?void 0:L.message)||L)}`)).finally(()=>r(!1))},[e.isOpen]),_.useEffect(()=>{if(!e.isOpen)return;const $=E=>{E.key==="Escape"&&!E.defaultPrevented&&!e.blocking&&(E.preventDefault(),e.onClose())};return window.addEventListener("keydown",$),()=>window.removeEventListener("keydown",$)},[e.isOpen,e.blocking,e.onClose]),!e.isOpen||f)return null;const Q=async()=>{l(!0),W(""),J("");try{const $=sp(m);g($);const E=await SS({gateway_url:$,gateway_user_id:y,gateway_token:k,persist:R},t);re(E),b(""),h(!0),e.onClose()}catch($){W(String(($==null?void 0:$.message)||$))}finally{l(!1)}},D=async()=>{l(!0),W(""),J("");try{await Wx(t),b("");const $=await Xp(t).catch(()=>null);re($),J("Signed out. This browser no longer holds a gateway session.")}catch($){W(String(($==null?void 0:$.message)||$))}finally{l(!1)}};return s.jsx("div",{className:"af-connect-overlay",role:"presentation",onMouseDown:$=>{!e.blocking&&$.target===$.currentTarget&&e.onClose()},children:s.jsx("div",{className:"af-connect-modal",role:"dialog","aria-modal":"true","aria-label":"Gateway connection",children:s.jsx(cS,{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:K.label,statusTone:K.tone,showGatewayUrl:!0,gatewayUrl:m,onGatewayUrlChange:$=>g($),userId:y,onUserIdChange:w,token:k,tokenPlaceholder:c!=null&&c.has_session?"(browser session already signed in)":"Paste Gateway user token",showToken:S,onTokenChange:b,onShowTokenChange:N,remember:R,rememberLabel:"Keep this browser signed in",onRememberChange:T,loading:n,submitting:o,submittingLabel:"Signing in...",showClose:!e.blocking,onClose:e.onClose,showSignOut:!e.blocking&&!!(c!=null&&c.has_session),onSignOut:D,error:A,message:z,onSubmit:Q})})})}function CS(e){return!!(e&&e.ok===!0&&e.has_session===!0)}function ES(e){const t=e||{},n=t.connectionPath||Kf,r=t.variant||"dismissable",o=_.useRef(t.onStatusChange);o.current=t.onStatusChange;const l=_.useRef(r);l.current=r;const c=_.useRef(!!t.autoOpenMidSession);c.current=!!t.autoOpenMidSession;const[u,f]=_.useState(null),[h,m]=_.useState("loading"),[g,y]=_.useState(!1),w=_.useRef(!1),k=_.useRef(!1),b=_.useRef("loading"),S=_.useRef("none"),N=_.useRef(!1),R=_.useRef(0),T=_.useCallback(E=>{var M;R.current+=1,f(E),(M=o.current)==null||M.call(o,E);const L=CS(E);if(L)m("connected"),b.current="connected",w.current=!1,S.current="none",k.current||y(!1);else if(E!==null){const ee=b.current;m("disconnected"),b.current="disconnected",ee!=="disconnected"&&(S.current=N.current?"signout":ee==="connected"?"mid":"boot");const F=l.current==="blocking"||S.current!=="mid"||c.current;!w.current&&F&&y(!0)}E!==null&&(k.current=L)},[]),A=_.useCallback(async()=>{const E=R.current;try{const L=await Xp(n);if(R.current!==E)return;T(L)}catch{if(R.current!==E)return;T(null)}},[n,T]),[W,z]=_.useState(!1),[J,K]=_.useState(null),re=_.useCallback(async()=>{z(!0),K(null),R.current+=1;let E=null;try{await Wx(n)}catch(L){E=String((L==null?void 0:L.message)||L||"Sign-out request failed")}N.current=!0;try{await A()}finally{N.current=!1}K(E),z(!1)},[n,A]),te=_.useRef(!1);_.useEffect(()=>{te.current||(te.current=!0,A())},[A]);const Q=_.useCallback(()=>{y(!0)},[]),D=_.useCallback(()=>{const E=b.current;r==="blocking"&&E==="disconnected"||(E==="disconnected"&&(w.current=!0),y(!1))},[r]),$=_.useMemo(()=>({isOpen:g,onClose:D,blocking:r==="blocking"&&h!=="connected",appName:t.appName,connectionPath:n,defaultGatewayUrl:t.defaultGatewayUrl,initialStatus:u,onStatusChange:T}),[g,D,r,h,t.appName,n,t.defaultGatewayUrl,u,T]);return{status:u,phase:h,connected:h==="connected",modalOpen:g,signingOut:W,signOutError:J,openModal:Q,refresh:A,signOut:re,modalProps:$}}function $S(){return globalThis.crypto}function AS(e){if(e.length<16)throw new Error("uuidV4FromBytes: needs 16 bytes");const t=Array.from(e.subarray(0,16));t[6]=t[6]&15|64,t[8]=t[8]&63|128;const n=t.map(r=>r.toString(16).padStart(2,"0")).join("");return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}function pa(){const e=$S();if(e&&typeof e.randomUUID=="function")try{return e.randomUUID()}catch{}if(e&&typeof e.getRandomValues=="function")return AS(e.getRandomValues(new Uint8Array(16)));throw new Error("randomId: Web Crypto (crypto.getRandomValues) is unavailable")}function u_(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 TS(){return pa()}function MS(){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 RS(e){const t=e.commandsPath||it("commands"),n=TS(),r=JSON.stringify({command_id:n,run_id:e.runId,type:"inject_guidance",payload:{guidance:e.guidance}}),o=e.csrfToken!==void 0?[e.csrfToken]:MS();o.length===0&&o.push("");let l=null;for(const c of o){const u=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json",...c?{"x-abstract-csrf":c}:{}},body:r}),f=await u.json().catch(()=>null);if(!u.ok){const h=f&&typeof f=="object"&&f.detail?String(f.detail):`HTTP ${u.status}`;if(l=new Error(h),u.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 LS(e){const[t,n]=_.useState(""),[r,o]=_.useState({kind:"idle"}),l=_.useRef(!1),c=_.useRef(0);_.useEffect(()=>{c.current+=1,o({kind:"idle"})},[e.runId]);const u=!e.disabled&&t.trim().length>0&&r.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]),h=async()=>{var w;const g=t.trim();if(!g||l.current||e.disabled)return;l.current=!0;const y=c.current;o({kind:"sending"});try{const k=e.submit?await e.submit(e.runId,g):await RS({runId:e.runId,guidance:g,commandsPath:e.commandsPath});if(c.current!==y)return;if(!k.accepted&&!k.duplicate){o({kind:"error",detail:"The gateway did not accept this steer (accepted=false)."});return}o({kind:"queued",seq:k.seq,duplicate:k.duplicate}),n(""),(w=e.onSent)==null||w.call(e,{...k,guidance:g})}catch(k){c.current===y&&o({kind:"error",detail:String((k==null?void 0:k.message)||k)})}finally{l.current=!1}},m=g=>{g.key==="Enter"&&(g.metaKey||g.ctrlKey)&&(g.preventDefault(),h())};return s.jsxs("div",{className:`af-steer${e.className?` ${e.className}`:""}`,children:[s.jsxs("div",{className:"af-steer__row",children:[s.jsx("textarea",{className:"af-steer__input",value:t,rows:2,placeholder:e.placeholder||"Steer this run…","aria-label":e.ariaLabel||"Steer message",disabled:e.disabled||r.kind==="sending",onChange:g=>{n(g.target.value),(r.kind==="error"||r.kind==="queued")&&o({kind:"idle"})},onKeyDown:m}),s.jsx("button",{type:"button",className:"af-steer__send",disabled:!u,onClick:()=>void h(),title:"Send guidance (Cmd/Ctrl+Enter)",children:r.kind==="sending"?"Sending…":"Steer"})]}),s.jsx("div",{className:"af-steer__status",role:"status","aria-live":"polite",children:r.kind==="queued"?s.jsxs("span",{className:"af-steer__ok",children:[r.duplicate?`Already queued (seq ${r.seq}).`:`Queued (seq ${r.seq}).`," ",f," ","Watch for the steer_seen ack in the run ledger."]}):r.kind==="error"?s.jsx("span",{className:"af-steer__err",children:r.detail}):s.jsx("span",{className:"af-steer__hint",children:f})})]})}function IS(e){const t=e.closeOnEscape!==!1,n=_.useRef(null);return _.useEffect(()=>{if(!e.open||!t)return;const r=o=>{o.key!=="Escape"||o.defaultPrevented||(o.preventDefault(),e.onClose())};return window.addEventListener("keydown",r),()=>window.removeEventListener("keydown",r)},[e.open,t,e.onClose]),_.useEffect(()=>{const r=n.current;r&&(e.open?r.removeAttribute("inert"):r.setAttribute("inert",""))},[e.open]),s.jsxs(s.Fragment,{children:[e.backdrop&&e.open?s.jsx("div",{className:"af-drawer-backdrop","aria-hidden":"true",onClick:e.onClose,style:{top:e.topOffset||0}}):null,s.jsxs("div",{ref:n,className:`af-drawer${e.side==="left"?" af-drawer--left":""}${e.topOffset?" af-drawer--offset":""}${e.open?" af-drawer--open":""}${e.className?` ${e.className}`:""}`,style:{width:e.width||420,top:e.topOffset||0,display:e.open?void 0:"none"},role:"complementary","aria-label":e.label,"aria-hidden":e.open?void 0:!0,children:[e.title!==void 0?s.jsxs("div",{className:"af-drawer__header",children:[s.jsx("div",{className:"af-drawer__title",children:e.title}),s.jsxs("div",{className:"af-drawer__header-actions",children:[e.headerActions,s.jsx("button",{type:"button",className:"af-drawer__close","aria-label":"Close panel",onClick:e.onClose,children:"×"})]})]}):null,s.jsx("div",{className:"af-drawer__body",children:e.children})]})]})}const OS={name:"AbstractFramework",website:"https://abstractframework.ai",github_org:"https://github.com/lpalbou",author:"Laurent-Philippe Albou, PhD",years:"2023-2026",license:"MIT",copyright:"© 2023-2026 Laurent-Philippe Albou, PhD. Released under the MIT License.",contact_email:"contact@abstractframework.ai"},PS={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"}},DS={framework:OS,apps:PS},Um=DS;function Hx(){return{...Um.framework}}function FS(){return Object.keys(Um.apps).sort()}function zS(e,t){const n=Object.prototype.hasOwnProperty.call(Um.apps,e)?Um.apps[e]:void 0;if(!n)throw new Error(`appIdentity: unknown application id "${e}" (known: ${FS().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 Au(e){return typeof e=="string"?e.trim():""}function cw(e,t){if(t!=null)return{framework:null,gateway:null,gatewayNote:`unavailable (${String(t).trim()||"unknown error"})`};const n=e&&typeof e=="object"&&!Array.isArray(e)?e:{},r=Au(n.abstractgateway),o=Au(n.abstractframework);return{framework:o||null,gateway:r||null,...r&&!o?{frameworkNote:"not installed on the gateway host"}:{},...r?{}:{gatewayNote:"unavailable (the gateway did not report its version)"}}}function BS(e){const t=Hx();return[{id:"website",label:"Website",href:e.website,title:e.website},{id:"source",label:"Source",href:e.repo,title:e.repo},{id:"docs",label:"Docs",href:e.docs,title:e.docs},{id:"issues",label:"Issues",href:e.issues,title:e.issues},{id:"feedback",label:"Feedback",href:e.feedback,title:e.feedback},{id:"contact",label:"Contact",href:`mailto:${t.contact_email}`,title:t.contact_email}]}function US(e){const t=e||{},n=Au(t.framework),r=Au(t.gateway);return[["AbstractFramework",n||Au(t.frameworkNote)||"not reported"],["AbstractGateway",r||Au(t.gatewayNote)||"not connected"]]}const WS='a[href], button:not(:disabled), input:not(:disabled), select:not(:disabled), textarea:not(:disabled), [tabindex]:not([tabindex="-1"])';function qS(e,t,n){if(e.key!=="Tab"||!t)return;const r=Array.from(t.querySelectorAll(WS));if(r.length===0){e.preventDefault();return}const o=r[0],l=r[r.length-1],c=!!n&&t.contains(n);e.shiftKey?(n===o||!c)&&(e.preventDefault(),l.focus()):(n===l||!c)&&(e.preventDefault(),o.focus())}function HS(e){const t=Hx();return s.jsxs("div",{className:`af-about-card${e.className?` ${e.className}`:""}`,"data-app":e.identity.id,children:[s.jsxs("div",{className:"af-about-card__head",children:[s.jsxs("h2",{className:"af-about-card__name",id:e.titleId,children:[e.identity.name," ",s.jsx("span",{className:"af-about-card__version",children:e.identity.version})]}),e.action]}),s.jsx("dl",{className:"af-about-card__versions",children:US(e.versions).map(([n,r])=>s.jsxs("div",{className:"af-about-card__fact",children:[s.jsx("dt",{children:n}),s.jsx("dd",{children:r})]},n))}),s.jsx("nav",{className:"af-about-card__links","aria-label":`${e.identity.name} links`,children:BS(e.identity).map(n=>n.href.startsWith("mailto:")?s.jsx("a",{className:"af-about-card__link","data-link":n.id,href:n.href,title:n.title,children:n.label},n.id):s.jsx("a",{className:"af-about-card__link","data-link":n.id,href:n.href,title:n.title,target:"_blank",rel:"noopener noreferrer",children:n.label},n.id))}),s.jsx("p",{className:"af-about-card__legal",children:t.copyright})]})}function VS(e){Yf();const t=_.useRef(null),n=_.useRef(null),r=_.useId(),o=_.useRef(e.onClose);return o.current=e.onClose,_.useEffect(()=>{var u;if(!e.open)return;const l=document.activeElement;(u=t.current)==null||u.focus();const c=f=>{if(!f.defaultPrevented){if(f.key==="Escape"){f.preventDefault(),o.current();return}qS(f,n.current,document.activeElement)}};return window.addEventListener("keydown",c),()=>{window.removeEventListener("keydown",c),l&&typeof l.focus=="function"&&l.focus()}},[e.open]),e.open?s.jsx("div",{className:"af-appearance-overlay af-about-overlay",onClick:e.onClose,role:"presentation",children:s.jsx("div",{ref:n,className:"af-appearance af-about",role:"dialog","aria-modal":"true","aria-labelledby":r,onClick:l=>l.stopPropagation(),children:s.jsx(HS,{identity:e.identity,versions:e.versions,titleId:r,action:s.jsx("button",{ref:t,type:"button",className:"af-about-card__close","data-action":"close-about",onClick:e.onClose,"aria-label":"Close","data-af-tip":"Close About",children:s.jsx(Be,{name:"x",size:16})})})})}):null}function GS(e){const{connection:t}=e,n=t.phase,r=t.signingOut===!0,[o,l]=_.useState(!1);Yf();const c=e.about,u=r?"Signing out…":n==="connected"?"Disconnect":n==="loading"?"Connecting…":"Connect",f=n==="connected"?"Disconnect from gateway":n==="loading"?"Checking gateway session…":"Connect to gateway";return s.jsxs("div",{className:`af-topbar${e.className?` ${e.className}`:""}`,role:"group","aria-label":"App actions",children:[e.docs?s.jsx("button",{type:"button",className:`af-topbar__btn af-topbar__btn--docs${e.docs.open?" is-active":""}`,"aria-pressed":e.docs.open,"aria-label":e.docs.label||"Docs assistant","data-af-tip":e.docs.label||"Docs assistant",onClick:e.docs.onToggle,children:s.jsx(Be,{name:"book",size:16})}):null,e.assistant?s.jsx("button",{type:"button",className:`af-topbar__btn${e.assistant.open?" is-active":""}`,"aria-pressed":e.assistant.open,"aria-label":e.assistant.label||"Open assistant","data-af-tip":e.assistant.label||"Assistant",onClick:e.assistant.onToggle,children:s.jsx(Be,{name:"sparkle",size:16})}):null,e.appearance?s.jsx("button",{type:"button",className:"af-topbar__btn","aria-label":e.appearance.label||"Appearance (theme and typography)","data-af-tip":e.appearance.label||"Appearance (theme and text size)",onClick:e.appearance.onOpen,children:s.jsx(Be,{name:"contrast",size:16})}):null,c?s.jsx("button",{type:"button",className:"af-topbar__btn af-topbar__btn--about","aria-label":c.label||`About ${c.identity.name}`,"data-af-tip":c.label||`About ${c.identity.name}`,"aria-haspopup":"dialog",onClick:()=>{var h;l(!0),(h=c.onOpen)==null||h.call(c)},children:s.jsx(Be,{name:"info",size:16})}):null,e.extraActions,s.jsxs("button",{type:"button",className:`af-topbar__pill af-topbar__pill--${n}`,onClick:n==="connected"?t.onDisconnect:t.onConnect,disabled:r,title:f,"aria-label":f,children:[s.jsx("span",{className:`af-topbar__dot af-topbar__dot--${n}`,"aria-hidden":"true"}),s.jsx("span",{className:"af-topbar__pill-label",children:u})]}),c?s.jsx(VS,{open:o,onClose:()=>l(!1),identity:c.identity,versions:c.versions}):null]})}const Rm={theme:"dark",font_scale:"md",header_density:"standard"};function KS(e){const t=e&&typeof e=="object"?e:{};return{theme:typeof t.theme=="string"&&t.theme?t.theme:Rm.theme,font_scale:typeof t.font_scale=="string"&&t.font_scale?t.font_scale:Rm.font_scale,header_density:typeof t.header_density=="string"&&t.header_density?t.header_density:Rm.header_density}}function YS(e){return`af_appearance_${e}_v1`}function JS(e,t){const n=YS(e),r=_.useMemo(()=>({...Rm,...(t==null?void 0:t.defaults)||{}}),[JSON.stringify((t==null?void 0:t.defaults)||{})]),[o,l]=_.useState(()=>{let c=r;try{const u=localStorage.getItem(n)??(t!=null&&t.legacyKey?localStorage.getItem(t.legacyKey):null);u&&(c=KS({...r,...JSON.parse(u)}))}catch{}try{sw(c.theme),rw({font_scale:c.font_scale,header_density:c.header_density})}catch{}return c});return _.useEffect(()=>{sw(o.theme),rw({font_scale:o.font_scale,header_density:o.header_density});try{localStorage.setItem(n,JSON.stringify(o))}catch{}},[n,o]),[o,l]}function XS(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?s.jsx("div",{className:"af-appearance-overlay",onClick:e.onClose,role:"presentation",children:s.jsxs("div",{className:"af-appearance",role:"dialog","aria-modal":"true","aria-label":e.title||"Appearance",onClick:t=>t.stopPropagation(),children:[s.jsx("div",{className:"af-appearance__title",children:e.title||"Appearance"}),s.jsx("div",{className:"af-appearance__note",children:e.note||"Stored locally in this browser, per app."}),s.jsxs("div",{className:"af-appearance__grid",children:[s.jsx("label",{className:"af-appearance__label",children:"Theme"}),s.jsx(dS,{value:e.value.theme,onChange:t=>e.onChange({...e.value,theme:t})}),s.jsx("label",{className:"af-appearance__label",children:"Font size"}),s.jsx(fS,{value:e.value.font_scale,onChange:t=>e.onChange({...e.value,font_scale:t})}),s.jsx("label",{className:"af-appearance__label",children:"Header size"}),s.jsx(hS,{value:e.value.header_density,onChange:t=>e.onChange({...e.value,header_density:t})})]}),s.jsx("div",{className:"af-appearance__actions",children:s.jsx("button",{type:"button",className:"af-appearance__close",onClick:e.onClose,children:"Close"})})]})}):null}function Zp(e){return e?[e.provider,e.model].map(t=>String(t||"").trim()).filter(Boolean).join(" / "):""}function uw(e,t,n=!1){if(n)return"unknown";if(!e)return"";const r=e[t];return!r||!r.configured?"not set":Zp(r)||"not set"}function ZS(e,t){var n;return e.stt_provider?Zp({provider:e.stt_provider,model:e.stt_model}):(n=t==null?void 0:t.stt)!=null&&n.configured?Zp(t.stt):""}function Vx(e,t){return`${Math.max(0,Math.floor((t-e)/1e3))} s`}function QS(e,t,n){return`Transcribing… ${Vx(e,t)}${n?` · ${n}`:""}`}const d_=()=>{var e;return(e=globalThis.navigator)==null?void 0:e.mediaDevices};function Qp(e){var o;const t=u_("the microphone");if(t)return t;const n=String((e==null?void 0:e.name)||"");if(n==="NotAllowedError"||n==="SecurityError"||n==="PermissionDeniedError")return"The browser blocked the microphone. Allow it for this site (the icon left of the address), then try again.";if(n==="NotFoundError"||n==="DevicesNotFoundError")return"No microphone was found. Connect one, then try again.";if(n==="OverconstrainedError")return"The chosen microphone is not connected. Pick another one in Settings → Voice.";if(n==="NotReadableError"||n==="TrackStartError")return"Another app is using the microphone. Close it, then try again.";if(!((o=d_())!=null&&o.getUserMedia))return"This browser cannot record audio.";const r=String((e==null?void 0:e.message)||e||"").trim();return r?`The microphone did not start: ${r.replace(/\.$/,"")}.`:"The microphone did not start."}async function eN(e){const t=d_();if(!t||typeof t.enumerateDevices!="function")return{devices:[],labelled:!1};const r=(await t.enumerateDevices()).filter(c=>c.kind===e),o=r.some(c=>!!c.label);return{devices:r.filter(c=>c.deviceId&&c.deviceId!=="default"&&c.deviceId!=="communications").map((c,u)=>({id:String(c.deviceId),label:String(c.label||`${e==="audioinput"?"Microphone":"Speaker"} ${u+1}`)})),labelled:o}}async function tN(){const e=d_();if(!(e!=null&&e.getUserMedia))throw new Error(u_("the microphone")||"This browser cannot record audio.");(await e.getUserMedia({audio:!0})).getTracks().forEach(n=>n.stop())}async function Gx(e){const t=d_();if(!(t!=null&&t.getUserMedia))throw Object.assign(new Error("This browser cannot record audio."),{name:"NotSupportedError"});return t.getUserMedia({audio:e?{deviceId:{exact:e}}:!0})}function f_(){const e=globalThis;return e.AudioContext||e.webkitAudioContext||null}function Kx(){const e=f_();return!!(e&&e.prototype&&typeof e.prototype.createMediaStreamDestination=="function")}function nN(e,t,n=1){const r=f_();if(!r)return()=>{};const o=new r,l=o.createMediaStreamSource(e),c=o.createAnalyser();c.fftSize=1024,l.connect(c);const u=new Float32Array(c.fftSize);let f=!0;const m=setInterval(()=>{if(!f)return;c.getFloatTimeDomainData(u);let g=0;for(let y=0;y<u.length;y+=1)g+=u[y]*u[y];t(Math.min(1,Math.sqrt(g/u.length)*4*n))},50);return()=>{var g;f=!1,clearInterval(m);try{l.disconnect()}catch{}(g=o.close)==null||g.call(o)}}const sN=.02;async function rN(e){var l;const t=globalThis.MediaRecorder;if(typeof t!="function")throw Object.assign(new Error("This browser cannot record audio."),{name:"NotSupportedError"});const n=await Gx(e.deviceId);let r=0;const o=nN(n,c=>{var u;r=Math.max(r,c),(u=e.onLevel)==null||u.call(e,c)},e.gain??1);try{const c=new t(n),u=[],f=new Promise((m,g)=>{c.ondataavailable=y=>(y==null?void 0:y.data)&&u.push(y.data),c.onstop=()=>m(),c.onerror=y=>g((y==null?void 0:y.error)||new Error("Recording failed."))});c.start(),await new Promise(m=>{var y;const g=setTimeout(m,e.ms??3e3);(y=e.signal)==null||y.addEventListener("abort",()=>{clearTimeout(g),m()},{once:!0})}),c.stop(),await f;const h=String(c.mimeType||"audio/webm");return{blob:new Blob(u,{type:h}),peak:r,mime:h}}finally{o(),n.getTracks().forEach(c=>c.stop()),(l=e.onLevel)==null||l.call(e,0)}}async function iN(e,t={}){var o;const n=f_();if(!n)throw new Error("This browser cannot play audio.");const r=new n;try{t.deviceId&&typeof r.setSinkId=="function"&&await r.setSinkId(t.deviceId);const l=e instanceof Blob?await e.arrayBuffer():e,c=await r.decodeAudioData(l.slice(0)),u=r.createGain();u.gain.value=Yg(t.volume),u.connect(r.destination);const f=r.createBufferSource();f.buffer=c,f.connect(u),await new Promise(h=>{f.onended=()=>h(),f.start()})}finally{(o=r.close)==null||o.call(r)}}async function oN(e={}){var r,o;const t=f_();if(!t)throw new Error("This browser cannot play audio.");const n=new t;try{e.deviceId&&typeof n.setSinkId=="function"&&await n.setSinkId(e.deviceId),n.state==="suspended"&&await((r=n.resume)==null?void 0:r.call(n));const l=n.createGain();l.connect(n.destination);const c=.3*Yg(e.volume),u=n.currentTime+.02;[660,880].forEach((f,h)=>{const m=n.createOscillator(),g=n.createGain();m.frequency.value=f,m.connect(g),g.connect(l);const y=u+h*.22;g.gain.setValueAtTime(0,y),g.gain.linearRampToValueAtTime(c,y+.02),g.gain.exponentialRampToValueAtTime(1e-4,y+.2),m.start(y),m.stop(y+.21)}),await new Promise(f=>setTimeout(f,520))}finally{(o=n.close)==null||o.call(n)}}function Yg(e){const t=Number(e);return e==null||e===""||!Number.isFinite(t)?1:Math.min(1,Math.max(0,t))}async function*aN(e){var r,o,l;const t=new AbortController,n=()=>t.abort();(r=e.signal)!=null&&r.aborted?n():(o=e.signal)==null||o.addEventListener("abort",n,{once:!0});try{const c=await fetch(e.path,{method:"POST",headers:{"Content-Type":"application/json",...e.csrfToken?{"x-abstract-csrf":e.csrfToken}:{},...e.headers||{}},body:JSON.stringify(e.body),signal:t.signal});if(!c.ok){const m=await c.json().catch(()=>null),g=m&&typeof m=="object"&&m.detail?String(m.detail):`HTTP ${c.status}`;throw new Error(g)}if(!c.body)throw new Error("TTS stream has no body");const u=c.body.getReader(),f=new TextDecoder;let h="";for(;;){const{done:m,value:g}=await u.read();h+=m?f.decode():f.decode(g,{stream:!0}),m&&h.trim()&&(h+=`
|
|
42
|
-
`);let y;for(;(y=h.indexOf(`
|
|
43
|
-
`))>=0;){const w=h.slice(0,y).trim();if(h=h.slice(y+1),!w)continue;let k=null;try{k=JSON.parse(w)}catch{throw new Error("TTS stream returned invalid JSON.")}if(k&&k.type==="error")throw new Error(String(k.error||"TTS stream error"));const b=k&&typeof k.audio_b64=="string"?k.audio_b64:"";if(b){const S=atob(b),N=new Uint8Array(S.length);for(let R=0;R<S.length;R+=1)N[R]=S.charCodeAt(R);yield N.buffer}if(k&&(k.type==="done"||k.type==="cancelled"))return}if(m)throw new Error("TTS stream ended before synthesis completed.")}}finally{(l=e.signal)==null||l.removeEventListener("abort",n),t.abort()}}function Xd(e,t){const n=String((t==null?void 0:t.message)||t||"").trim().replace(/\.$/,"");return n?`${e}: ${n}.`:`${e}.`}const lN=350;function cN(){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 uN(){if(typeof window>"u")return!1;const e=window;return!!(e!=null&&e.AudioContext||e!=null&&e.webkitAudioContext)}function dN(){const e=window.MediaRecorder,t=r=>{var o;try{return!!((o=e==null?void 0:e.isTypeSupported)!=null&&o.call(e,r))}catch{return!1}},n=["audio/webm;codecs=opus","audio/webm","audio/mp4","audio/ogg;codecs=opus","audio/ogg"];for(const r of n)if(t(r))return r;return""}async function rp(e,t){var o;const n=t.slice(0),r=(o=e.decodeAudioData)==null?void 0:o.bind(e);if(typeof r!="function")throw new Error("decodeAudioData not available");try{const l=r(n);if(l&&typeof l.then=="function")return await l}catch{}return await new Promise((l,c)=>{try{r(n,l,c)}catch(u){c(u)}})}function fN(e){const t=new Uint8Array(e);if(t.length<44)return null;const n=l=>String.fromCharCode(t[l],t[l+1],t[l+2],t[l+3]);if(n(0)!=="RIFF"||n(8)!=="WAVE")return null;const r=new DataView(e);let o=12;for(;o+8<=t.length;){const l=n(o),c=r.getUint32(o+4,!0);if(l==="data")return t.slice(0,o+8);o+=8+c+c%2}return null}function hN(e,t){const n=new Uint8Array(t),r=new Uint8Array(e.length+n.length);r.set(e,0),r.set(n,e.length);const o=new DataView(r.buffer);return o.setUint32(4,r.length-8,!0),o.setUint32(e.length-4,n.length,!0),r.buffer}function mN(){const e=globalThis,t=e==null?void 0:e.AudioContext;return!!(t&&t.prototype&&typeof t.prototype.setSinkId=="function")}const om=new WeakMap;function _N(e,t){const n=e;if(!(typeof n.setSinkId!="function"||om.get(e)===t)){om.set(e,t);try{Promise.resolve(n.setSinkId(t)).catch(()=>om.delete(e))}catch{om.delete(e)}}}function pN(e){const t=_.useRef(e);t.current=e;const n=le=>{var be,Pe;return(Pe=(be=t.current).on_error)==null?void 0:Pe.call(be,le)},r=_.useMemo(()=>uN()&&(typeof e.tts=="function"||typeof e.tts_stream=="function"),[e.tts,e.tts_stream]),o=_.useMemo(()=>cN()&&typeof e.transcribe=="function",[e.transcribe]),[l,c]=_.useState({key:"",status:"idle"}),u=_.useRef(l),f=_.useCallback(le=>{u.current=le,c(be=>be.key===le.key&&be.status===le.status?be:le)},[]),h=_.useRef(""),m=_.useRef(""),g=_.useRef(null),y=_.useRef(null),w=_.useRef(null),k=_.useRef(null),b=_.useRef(0),S=_.useRef(0),N=_.useRef(0),R=_.useRef(null),T=_.useRef([]),A=_.useRef(0),W=_.useRef(!0),z=_.useRef(!1),J=()=>{try{const le=globalThis,be=(le==null?void 0:le.AudioContext)||(le==null?void 0:le.webkitAudioContext);if(!be)return null;if(!g.current){const Ce=new be,Te=Ce.createGain();Te.gain.value=1,Te.connect(Ce.destination),g.current=Ce,y.current=Te}const Pe=g.current,me=y.current;if(!Pe||!me)return null;_N(Pe,t.current.output_device_id||""),me.gain.value=Yg(t.current.volume);try{Pe.state==="suspended"&&Pe.resume()}catch{}return{ctx:Pe,gain:me}}catch{return null}},K=_.useCallback(()=>{const le=w.current;if(w.current=null,!!le){try{le.onended=null}catch{}try{le.stop()}catch{}try{le.disconnect()}catch{}}},[]),re=_.useCallback(()=>{var le;K(),N.current+=1,(le=R.current)==null||le.abort(),R.current=null,T.current=[],A.current=0,W.current=!0,z.current=!1,m.current="",h.current="",k.current=null,b.current=0,S.current=0,f({key:"",status:"idle"})},[K,f]);_.useEffect(()=>()=>{var le,be;re();try{(le=y.current)==null||le.disconnect()}catch{}try{(be=g.current)==null||be.close()}catch{}g.current=null,y.current=null,k.current=null},[]);const te=async(le,be,Pe)=>{const me=N.current,Ce=J();if(!Ce)throw new Error("TTS playback is not supported in this browser");const{ctx:Te,gain:Je}=Ce;try{Te.state==="suspended"&&await Te.resume()}catch{}if(me!==N.current)return;K();const rt=Te.createBufferSource();rt.buffer=be,rt.connect(Je);const ht=Number.isFinite(Number(be.duration))?Number(be.duration):0,lt=Math.max(0,Math.min(Number(Pe||0),ht>0?Math.max(0,ht-.01):0));S.current=Te.currentTime-lt,b.current=lt,w.current=rt,h.current=le,rt.onended=()=>{w.current===rt&&(w.current=null,b.current=0,S.current=0,h.current="",f({key:"",status:"idle"}))},rt.start(0,lt),f({key:le,status:"playing"})},Q=(le,be)=>{if(be!==N.current)return;const Pe=J();if(!Pe)return;const me=T.current,Ce=A.current;if(Ce>=me.length){W.current&&(h.current="",b.current=0,S.current=0,f({key:"",status:"idle"}));return}const Te=me[Ce],{ctx:Je,gain:rt}=Pe;K();const ht=Je.createBufferSource();ht.buffer=Te,ht.connect(rt);const lt=Number.isFinite(Number(Te.duration))?Number(Te.duration):0,Ct=Math.max(0,Math.min(Number(b.current||0),lt>0?Math.max(0,lt-.01):0));S.current=Je.currentTime-Ct,w.current=ht,h.current=le,ht.onended=()=>{be===N.current&&w.current===ht&&(w.current=null,A.current=Ce+1,b.current=0,Q(le,be))};try{Je.state==="suspended"&&Je.resume()}catch{}ht.start(0,Ct),f({key:le,status:"playing"})},D=async(le,be,Pe)=>{var rt;const me=J();if(!me){n==null||n("This browser cannot play spoken replies.");return}K();const Ce=++N.current;(rt=R.current)==null||rt.abort();const Te=new AbortController;R.current=Te,T.current=[],A.current=0,W.current=!1,z.current=!1,k.current=null,b.current=0,S.current=0,h.current=le,m.current=le,f({key:le,status:"loading"}),n==null||n("");let Je=null;try{for await(const ht of Pe(be,Te.signal)){if(Ce!==N.current)return;let lt;try{lt=await rp(me.ctx,ht),Je||(Je=fN(ht))}catch{if(!Je)continue;try{lt=await rp(me.ctx,hN(Je,ht))}catch{continue}}if(Ce!==N.current)return;T.current.push(lt),!w.current&&!z.current&&(m.current="",Q(le,Ce))}if(Ce!==N.current)return;if(W.current=!0,T.current.length===0){n==null||n("Reading aloud failed: the voice engine returned no audio."),re();return}!w.current&&!z.current&&Q(le,Ce)}catch(ht){if(Ce!==N.current)return;n==null||n(Xd("Reading aloud failed",ht)),re()}finally{R.current===Te&&(R.current=null)}},$=_.useCallback(async(le,be)=>{var Ct;const Pe=String(le||"").trim(),me=String(be||"").trim();if(!Pe||!me)return;const Ce=t.current.tts,Te=t.current.tts_stream;if(typeof Ce!="function"&&typeof Te!="function"){n==null||n("Reading aloud is not available on this gateway.");return}const Je=J();if(!Je){n==null||n("This browser cannot play spoken replies.");return}const rt=u.current,ht=rt.key===Pe;if(ht&&rt.status==="playing"){if(w.current){const Xt=Math.max(0,Je.ctx.currentTime-Number(S.current||0));b.current=Xt}else b.current=0;z.current=!0,K(),f({key:Pe,status:"paused"});return}if(ht&&rt.status==="paused"){if(T.current.length>0){n==null||n(""),z.current=!1,f({key:Pe,status:"playing"}),Q(Pe,N.current);return}const Xt=k.current;if(Xt){n==null||n(""),z.current=!1;try{await te(Pe,Xt,b.current)}catch(Pn){n==null||n(Xd("Reading aloud failed",Pn)),f({key:"",status:"idle"})}return}}if(ht&&rt.status==="loading")return;if(typeof Te=="function"){await D(Pe,me,Te);return}K(),N.current+=1,(Ct=R.current)==null||Ct.abort(),R.current=null;const lt=N.current;T.current=[],A.current=0,W.current=!0,z.current=!1,k.current=null,b.current=0,S.current=0,h.current=Pe,m.current=Pe,f({key:Pe,status:"loading"}),n==null||n("");try{const Xt=await Ce(me);if(m.current!==Pe||N.current!==lt)return;const Pn=await rp(Je.ctx,Xt);if(m.current!==Pe||N.current!==lt)return;k.current=Pn,b.current=0,await te(Pe,Pn,0)}catch(Xt){if(N.current!==lt)return;m.current===Pe&&(m.current="",h.current="",f({key:"",status:"idle"})),n==null||n(Xd("Reading aloud failed",Xt))}},[]),[E,L]=_.useState(!1),[M,ee]=_.useState(!1),F=_.useRef(!1),U=_.useRef(o);U.current=o;const V=_.useCallback(le=>{F.current=le,L(be=>be===le?be:le)},[]),O=_.useRef(!1),H=_.useRef(null),Y=_.useRef(null),ae=_.useRef([]),ie=_.useRef(""),_e=_.useRef(0),fe=_.useRef(!1),[ge,Ne]=_.useState(0),Ue=_.useRef(0),We=_.useRef(null);function ut(){var be,Pe;try{(Pe=(be=H.current)==null?void 0:be.getTracks)==null||Pe.call(be).forEach(me=>{try{me.stop()}catch{}})}catch{}H.current=null;const le=We.current;We.current=null;try{le==null||le.close()}catch{}}const Fe=_.useCallback(()=>{_e.current+=1,fe.current=!1;const le=Y.current;if(le){le.onstop=null,le.ondataavailable=null,le.onerror=null;try{le.stop()}catch{}}Y.current=null,ut(),V(!1),O.current=!1,ee(!1),Ne(0),ae.current=[]},[V]);_.useEffect(()=>()=>Fe(),[Fe]);async function et(le,be){var Te,Je;if(n==null||n(""),O.current)return;const Pe=Ue.current?Date.now()-Ue.current:1/0;if(!le||!le.size||Pe<lN){Ne(0),n==null||n("The recording was too short. Hold the microphone button while you speak, or tap it once to start and again to stop.");return}const me=t.current.transcribe;if(typeof me!="function"){n==null||n("Speech to text is not available on this gateway.");return}O.current=!0;const Ce=_e.current;ee(!0),Ne(Date.now());try{const rt=await me(le,be),ht=typeof rt=="string"||!rt?{text:String(rt||"")}:rt,lt=String(ht.text||"").trim();if(Ce!==_e.current)return;lt?(Je=(Te=t.current).on_transcript)==null||Je.call(Te,lt,{...ht,text:lt}):n==null||n("Nothing was heard. Check the microphone in Settings → Voice (Test), then try again.")}catch(rt){if(Ce===_e.current){const ht=String((rt==null?void 0:rt.message)||rt||"").trim().replace(/\.$/,"");n==null||n(ht?`Transcription failed: ${ht}.`:"Transcription failed.")}}finally{Ce===_e.current&&(O.current=!1,ee(!1),Ne(0))}}const $e=_.useCallback(async()=>{if(n==null||n(""),!U.current){n==null||n(u_("the microphone")??"Voice recording is not supported in this browser (MediaRecorder/getUserMedia unavailable).");return}if(O.current||fe.current||F.current||Y.current)return;ae.current=[];const le=_e.current;fe.current=!0;try{const be=await Gx(t.current.input_device_id||"");if(le!==_e.current){be.getTracks().forEach(Je=>Je.stop());return}H.current=be;const Pe=dN();ie.current=Pe;let me=be;const Ce=Number(t.current.input_gain??1);if(Number.isFinite(Ce)&&Ce>0&&Ce!==1&&Kx()){const Je=globalThis.AudioContext||globalThis.webkitAudioContext,rt=new Je,ht=rt.createGain();ht.gain.value=Ce;const lt=rt.createMediaStreamDestination();rt.createMediaStreamSource(be).connect(ht),ht.connect(lt),We.current=rt,me=lt.stream}const Te=Pe?new MediaRecorder(me,{mimeType:Pe}):new MediaRecorder(me);Y.current=Te,Te.ondataavailable=Je=>{if(le===_e.current)try{Je!=null&&Je.data&&ae.current.push(Je.data)}catch{}},Te.onerror=()=>{le===_e.current&&(n==null||n("Recording failed. Try again, or pick another microphone in Settings → Voice."))},Te.onstop=()=>{if(le===_e.current){V(!1),ut(),Y.current=null;try{const Je=new Blob(ae.current,{type:ie.current||""});et(Je,ie.current)}catch(Je){n==null||n(Xd("The recording could not be prepared",Je))}}},Te.start(),Ue.current=Date.now(),Ne(Ue.current),V(!0)}catch(be){if(le!==_e.current)return;ut(),Y.current=null,V(!1),Ne(0),n==null||n(Qp(be))}finally{le===_e.current&&(fe.current=!1)}},[]),Ve=_.useCallback(()=>{const le=Y.current;if(!(!F.current||!le)){V(!1);try{le.stop()}catch(be){n==null||n(Xd("The recording could not stop",be))}}},[]);return _.useEffect(()=>{if(!E||t.current.stop_on_pointerup===!1)return;const le=()=>Ve();return window.addEventListener("pointerup",le),window.addEventListener("pointercancel",le),()=>{window.removeEventListener("pointerup",le),window.removeEventListener("pointercancel",le)}},[E]),{tts_supported:r,tts_playback:l,toggle_tts:$,stop_tts:re,voice_ptt_supported:o,voice_ptt_recording:E,voice_ptt_busy:M,start_voice_ptt_recording:$e,stop_voice_ptt_recording:Ve,cancel_voice_ptt_recording:Fe,voice_ptt_since:ge}}const gN={diary:"var(--accent)",question:"#e7b45a",dream:"#c084dd",interest:"#7bd88a",lesson:"#6ea8d8",world_model:"#5eead4"};function dw(e){const t=String(e||"");return t.length>14?`${t.slice(0,10)}…${t.slice(-4)}`:t}function ip(e){const[t,n]=_.useState(!1),[r,o]=_.useState(null),l=_.useRef(!1),c=typeof e.entryId=="string"&&e.entryId.trim()?e.entryId.trim():null,u=e.kind&&gN[e.kind]||"var(--text-muted)",f=_.useCallback(async()=>{if(!(!c||!e.onOpen||l.current)){l.current=!0,n(!0),o(null);try{await e.onOpen(c)}catch(h){o(String((h==null?void 0:h.message)||h||"could not open"))}finally{l.current=!1,n(!1)}}},[c,e.onOpen]);return!c||!e.onOpen?s.jsxs("span",{className:["af-memory-hint","af-memory-hint--text",e.className||""].filter(Boolean).join(" "),title:e.title,children:[s.jsx("span",{className:"af-memory-hint__dot",style:{background:u},"aria-hidden":"true"}),s.jsx("span",{className:"af-memory-hint__label",children:e.label}),c&&e.showId!==!1?s.jsx("code",{className:"af-memory-hint__id",children:dw(c)}):null]}):s.jsxs("span",{className:["af-memory-hint",e.className||""].filter(Boolean).join(" "),children:[s.jsxs("button",{type:"button",className:"af-memory-hint__btn",onClick:()=>void f(),disabled:t,title:e.title||(e.command?e.command:`open ${c}`),"aria-label":`Open ${e.kind||"memory"} entry: ${e.label}`,children:[s.jsx("span",{className:"af-memory-hint__dot",style:{background:u},"aria-hidden":"true"}),s.jsx("span",{className:"af-memory-hint__label",children:e.label}),e.showId!==!1?s.jsx("code",{className:"af-memory-hint__id",children:dw(c)}):null,s.jsx("span",{className:"af-memory-hint__act","aria-hidden":"true",children:t?"…":"↗"})]}),e.command?s.jsx("code",{className:"af-memory-hint__cmd",children:e.command}):null,r?s.jsx("span",{className:"af-memory-hint__err",role:"alert",children:r}):null]})}const am=e=>Array.isArray(e)?e.map(t=>typeof t=="string"?t:(t==null?void 0:t.id)||(t==null?void 0:t.name)).filter(Boolean):[];function yN({value:e,onChange:t,fetchCatalog:n,intro:r,delivery:o=!0,quality:l=!0,showReset:c=!0,defaultHint:u,voiceDefaultLabel:f}){var z,J,K,re;const h=_.useRef(n);h.current=n;const[m,g]=_.useState({}),[y,w]=_.useState(""),[k,b]=_.useState(!1);_.useEffect(()=>{let te=!0;return b(!0),g({}),w(""),h.current(e.provider,e.model).then(Q=>{te&&(g(Q),w(Q.error?String(Q.error):""))}).catch(Q=>{te&&w(String((Q==null?void 0:Q.message)||Q))}).finally(()=>{te&&b(!1)}),()=>{te=!1}},[e.provider,e.model]);const S=Array.isArray(m.items)?m.items:[...Array.isArray(m.profiles)?m.profiles.map(te=>({...te,voice_kind:"profile"})):[],...Array.isArray(m.voices)?m.voices.map(te=>({...te,voice_kind:"voice"})):[]],N=te=>JSON.stringify([te.provider||"",te.model||"",te.voice_kind==="profile"?"profile":"voice",te.id]),R=S.find(te=>te.id===(e.profile||e.voice)&&te.voice_kind==="profile"==!!e.profile&&(!e.provider||!te.provider||te.provider===e.provider)&&(!e.model||!te.model||te.model===e.model)),T=R?N(R):e.profile||e.voice?JSON.stringify([e.provider||"",e.model||"",e.profile?"profile":"voice",e.profile||e.voice]):"",A=S.filter(te=>(te==null?void 0:te.id)&&(!e.provider||!te.provider||te.provider===e.provider)).map(te=>({value:N(te),label:`${te.label||te.name||te.id}${!e.provider&&te.provider?` · ${te.provider}`:""}`}));T&&!A.some(te=>te.value===T)&&A.unshift({value:T,label:`${e.profile||e.voice} (saved)`});const W=te=>t({...e,...te});return s.jsxs("div",{className:"af-voice-settings",children:[r===void 0?s.jsx("p",{children:"Speech is generated by your authenticated Gateway. Leave routing and voice unset to use its defaults."}):r,s.jsx(zx,{defaultHint:u,value:{provider:e.provider||"",model:e.model||""},onChange:te=>t({...e,...te,voice:"",profile:""}),fetchProviders:async()=>{const te=await h.current();if(te.error&&!am(te.tts_providers||te.providers).length)throw new Error(te.error);return am(te.tts_providers||te.providers).map(Q=>({name:Q}))},fetchModels:async te=>{var D;const Q=await h.current(te);return am(((D=Q.tts_models_by_provider)==null?void 0:D[te])||Q.tts_models||Q.models)},providerLabel:"Speech provider",modelLabel:"Speech model"}),s.jsxs("label",{children:["Voice / profile",s.jsx(si,{ariaLabel:"AI voice",placeholder:f||"Gateway / provider default",value:T,disabled:k,options:[{value:"",label:f||"Gateway / provider default"},...A],onChange:te=>{if(!te){W({voice:"",profile:""});return}const[Q,D,$,E]=JSON.parse(te);W({provider:Q||e.provider||"",model:D||(Q&&Q!==e.provider?"":e.model)||"",voice:$==="voice"?E:"",profile:$==="profile"?E:""})}})]}),k?s.jsx("p",{role:"status",children:"Loading available voices…"}):null,y?s.jsxs("p",{role:"alert",children:["Voice discovery unavailable: ",y,". Your saved choice is preserved."]}):null,o?s.jsxs(s.Fragment,{children:[s.jsxs("label",{children:["Speaking speed",s.jsxs("select",{"aria-label":"Speech speed",value:e.speed??"",onChange:te=>W({speed:te.target.value?Number(te.target.value):void 0}),children:[s.jsx("option",{value:"",children:"Gateway default"}),[.5,.75,1,1.25,1.5,2].map(te=>s.jsxs("option",{value:te,children:[te,"×"]},te))]})]}),l&&((J=(z=m.controls)==null?void 0:z.quality_preset)!=null&&J.supported)?s.jsxs("label",{children:["Quality",s.jsxs("select",{"aria-label":"Speech quality",value:e.quality_preset||"",onChange:te=>W({quality_preset:te.target.value}),children:[s.jsx("option",{value:"",children:"Gateway default"}),am(m.controls.quality_preset.values).map(te=>s.jsx("option",{value:te,children:te},te))]})]}):null,(re=(K=m.controls)==null?void 0:K.instructions)!=null&&re.supported?s.jsxs("label",{children:["Delivery instructions",s.jsx("textarea",{"aria-label":"Voice delivery instructions",rows:3,placeholder:"For example: calm, clear, and conversational",value:e.instructions||"",onChange:te=>W({instructions:te.target.value})})]}):null]}):null,c?s.jsx("button",{type:"button",onClick:()=>t({}),children:"Reset to Gateway defaults"}):null]})}const op=it("automations"),wN=it("trigger-sources"),vN=it("me/email");class fw 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 xN(e,t){const n=t&&typeof t=="object"?t.detail:void 0;if(n&&typeof n=="object"&&!Array.isArray(n)){const r=n;if(typeof r.reason_code=="string"&&r.reason_code&&typeof r.message=="string"){const o={status:e,code:r.reason_code,message:r.message};return typeof r.field=="string"&&(o.field=r.field),typeof r.command_id=="string"&&(o.command_id=r.command_id),o}}return{status:e,code:"invalid_response",message:`The gateway answered HTTP ${e} without an automation error envelope.`}}function ap(e){const t=new URLSearchParams;for(const[r,o]of Object.entries(e))o!==void 0&&t.set(r,String(o));const n=t.toString();return n?`?${n}`:""}function bN(){return pa()}function kN(e){const t=e.newId??bN,n=o=>`${op}/${encodeURIComponent(o)}`;async function r(o,l,c){const u={accept:"application/json",...e.headers?e.headers():{}},f={method:o,headers:u};c!==void 0&&(u["content-type"]="application/json",f.body=JSON.stringify(c));const h=await e.fetch(Kg(e.baseUrl,l),f),m=await h.text();let g,y=!1;if(m)try{g=JSON.parse(m),y=!0}catch{y=!1}if(!h.ok)throw new fw(xN(h.status,g));if(!y||g===null||typeof g!="object")throw new fw({status:h.status,code:"invalid_response",message:`The gateway answered ${o} ${l} with a body that is not a JSON object.`});return g}return{listAutomations:(o={})=>r("GET",`${op}${ap({status:o.status,cursor:o.cursor,limit:o.limit})}`),getAutomation:o=>r("GET",n(o)),createAutomation:o=>r("POST",op,o),reviseAutomation:(o,l)=>r("PATCH",n(o),{command_id:l.command_id??t(),...l.expected_revision!==void 0?{expected_revision:l.expected_revision}:{},changes:l.changes}),sendAutomationCommand:(o,l)=>r("POST",`${n(o)}/commands`,{command_id:l.command_id??t(),type:l.type,...l.payload!==void 0?{payload:l.payload}:{}}),listOccurrences:(o,l={})=>r("GET",`${n(o)}/occurrences${ap({cursor:l.cursor,limit:l.limit})}`),discuss:(o,l)=>r("POST",`${n(o)}/discuss`,{request_id:l.request_id??t(),occurrence_index:l.occurrence_index,prompt:l.prompt}),markSeen:(o,l)=>r("POST",`${n(o)}/seen`,{attention_cursor:l}),listAttention:(o,l={})=>r("GET",`${n(o)}/attention${ap({cursor:l.cursor,limit:l.limit})}`),listTriggerSources:()=>r("GET",wN),getMyEmail:()=>r("GET",vN)}}function Yx(e){const t=e==null?void 0:e._runtime,n=Array.isArray(t==null?void 0:t.allowed_tools)?t.allowed_tools:null,r=Array.isArray(e==null?void 0:e.tools)?e.tools:n;return Array.isArray(r)?r.filter(o=>typeof o=="string"&&(!n||n.includes(o))):null}function Jx(e,t){const n={...e},r=e._runtime&&typeof e._runtime=="object"?{...e._runtime}:{};return t===null?(delete n.tools,delete r.allowed_tools):(n.tools=[...t],r.allowed_tools=[...t]),Object.keys(r).length?n._runtime=r:delete n._runtime,n}function jN(e){const t=["prompt","tools","provider","model","temperature","seed","max_iterations","max_in_tokens","system","_limits"],n={};for(const o of t)o in e&&(n[o]=e[o]);const r=e._runtime;if(r&&typeof r=="object"){const o={};for(const l of["allowed_tools","provider","model","thinking","speculation","stream"])l in r&&(o[l]=r[l]);Object.keys(o).length&&(n._runtime=o)}return n}function eg(e){return e.flow_id==="@default"?"@default":`${"bundle_ref"in e?e.bundle_ref:""}:${e.flow_id}`}const SN={active:"Active",pause:"Pause",resume:"Resume",run_now:"Run now",stop_current:"Stop current",revise:"Edit",archive:"Archive",unarchive:"Unarchive",discuss:"Discuss"},NN={active:`On: it runs on its schedule. Off: paused, scheduled runs are skipped.
|
|
44
|
-
Pausing lets a run in progress finish, without further retries; Run now still works and keeps it paused.
|
|
45
|
-
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.
|
|
46
|
-
A run in progress finishes; a pending retry is cancelled. Run now still works.`,resume:`Restart the schedule at its next time after now.
|
|
47
|
-
Times missed while paused are skipped; resuming does not run it now.`,run_now:`Run it once now, without waiting for the schedule.
|
|
48
|
-
The schedule does not move: the next scheduled run keeps its time, or starts right after this run if its time comes first.
|
|
49
|
-
Does not count toward a run limit. Works while paused; it stays paused.
|
|
50
|
-
Not available while a run is in progress.`,stop_current:`Cancel the run in progress, or its pending retry.
|
|
51
|
-
It ends as cancelled, with no failure notice. The schedule continues.`,revise:`Change the task, schedule or settings.
|
|
52
|
-
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.
|
|
53
|
-
A run in progress finishes; the history stays readable.`,unarchive:`Bring it back from the archive, paused: nothing runs until you make it active.
|
|
54
|
-
An automation that had already finished or failed keeps that status; its history is unchanged.`,discuss:`Talk about the results in a separate conversation, seeded with the runs up to this one.
|
|
55
|
-
It has its own workspace (the automation's files are read-only) and never changes the automation.`},CN="Next scheduled run: {time}.",EN="Growing context: later runs see this run in their history.",$N={run_now:{name:"playCircle"}},AN={trigger_label:"When an email arrives",not_set_up:"Connect a mailbox first — open My email",open_my_email:"open My email",filters_legend:"Only mail that matches (all optional)",from_in:"From these addresses",from_domain_in:"From these domains",to_in:"Sent to these addresses",subject_contains:"Subject contains",has_attachment:"Attachments",has_attachment_any:"any",has_attachment_yes:"only with attachments",has_attachment_no:"only without attachments",list_hint:"Separate entries with commas or new lines. Exact addresses and domains only (no patterns).",every_label:"Check for new mail every",interval_rule:"An automation that runs a model on new mail checks once an hour by default; one that needs no model checks every 60 s. The shortest interval is 60 s.",max_batch_label:"At most this many emails per run",max_batch_hint:"The rest wait for the next run. Each email is read once by this automation; mail that arrived before it was created, or while it is paused, is not processed.",untrusted_hint:"Incoming mail is data, never instructions: the automation acts only on its task. Link-opening tools (fetch_url, browser_probe) always ask for your approval.",notify_label:"Email result",notify_hint:"Email each completed run’s result to the selected recipients.",recipients_legend:"Recipients",recipients_self:"Only me (default)",recipients_list:"Me and these addresses",recipients_hint:"Separate multiple addresses with commas."},Xx={labels:SN,hints:NN,run_now_next_run_line:CN,run_now_growing_line:EN,icons:$N,email:AN},TN=/^([1-9][0-9]*)([smhd])$/,MN={s:["second","seconds"],m:["minute","minutes"],h:["hour","hours"],d:["day","days"]};function Jf(e){if(typeof e!="string")return null;const t=TN.exec(e);return t?{amount:Number(t[1]),unit:t[2]}:null}function Zx(e){const t=Jf(e);if(!t)return`every ${e}`;const[n,r]=MN[t.unit];return t.amount===1?`every ${n}`:`every ${t.amount} ${r}`}function ya(e){if(!e)return"";const t=Date.parse(e);if(Number.isNaN(t))return e;const n=new Date(t).toISOString(),r=n.slice(17,19);return`${n.slice(0,10)} ${n.slice(11,16)}${r==="00"?"":`:${r}`} UTC`}function Qx(e){const t=e;if(typeof t.every!="string")return t.start_at?`once at ${ya(t.start_at)}`:"once, now";const n=[`${Zx(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 ${ya(t.until)}`),n.join(" · ")}function Jg(e){return e.source_id==="schedule"&&e.source_version===1?Qx(e.config):e.source_id==="manual"&&e.source_version===1?"manual runs only":h_(e)?ab(e.config):`${e.source_id}@${e.source_version}`}function eb(e){return e==="growing"?"Growing — each run sees the previous runs":"Independent — each run starts fresh"}const RN={active:"Active",paused:"Paused",completed:"Completed",failed:"Failed",archived:"Archived"},qt=Xx.email,tb="email.received",nb=1,LN="1h",IN="60s",sb=60,Xg=100,tg=1e3,hw=200,mw=200,_w=50;function h_(e){return!!e&&e.source_id===tb&&e.source_version===nb}function m_(e){return!!e&&e.effective_enabled===!0}function rb(e){const t=[];for(const n of String(e??"").split(/[\s,;]+/)){const r=n.trim().toLowerCase();r&&!t.includes(r)&&t.push(r)}return t}const ON=/[\s<>,;:"()[\]]/;function ng(e){const t=e.trim().toLowerCase(),n=t.indexOf("@");return n<=0||n===t.length-1?!1:!t.slice(n+1).includes("@")&&!ON.test(t)}function PN(e){const t=e.trim().toLowerCase();return!!t&&!t.includes("@")&&t.includes(".")&&!t.startsWith(".")&&!t.endsWith(".")&&!/[\s<>,;:"()[\]/*]/.test(t)}const ib={usesModel:!0,every:null,maxBatch:null,fromIn:"",fromDomainIn:"",toIn:"",subjectContains:"",hasAttachment:"any"};function Zg(e){return e?LN:IN}function ob(e){const t=Jf(e);return t?t.amount*{s:1,m:60,h:3600,d:86400}[t.unit]:null}function lp(e,t,n,r,o){const l=rb(e);if(!l.length)return null;const c=l.filter(u=>!n(u));return c.length&&o.push(`${t}: ${c.join(", ")} ${c.length===1?"is not":"are not"} ${r}.`),l.length>hw&&o.push(`${t}: at most ${hw} entries.`),l}function DN(e){const t=[],n={uses_model:e.usesModel};e.every===null?n.every=Zg(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&&(ob(n.every)??0)<sb&&t.push("The check interval is at least 60 seconds."),e.maxBatch===null?n.max_batch=Xg:!Number.isInteger(e.maxBatch)||e.maxBatch<1||e.maxBatch>tg?t.push(`At most this many emails per run: a whole number from 1 to ${tg}.`):n.max_batch=e.maxBatch;const r={},o=lp(e.fromIn,qt.from_in,ng,"an email address",t);o&&(r.from_in=o);const l=lp(e.fromDomainIn,qt.from_domain_in,PN,"a domain like example.com",t);l&&(r.from_domain_in=l);const c=lp(e.toIn,qt.to_in,ng,"an email address",t);c&&(r.to_in=c);const u=e.subjectContains.trim();return u&&(u.length>mw||/[\r\n]/.test(u)?t.push(`${qt.subject_contains}: one line of at most ${mw} characters.`):r.subject_contains=u),e.hasAttachment==="yes"?r.has_attachment=!0:e.hasAttachment==="no"&&(r.has_attachment=!1),Object.keys(r).length&&(n.filter=r),{config:n,errors:t}}function ab(e){const t=e,n=t.filter??{},r=["when an email arrives"],o=[...n.from_in??[],...n.from_domain_in??[]];o.length&&r.push(`from ${o.join(", ")}`),n.to_in&&n.to_in.length&&r.push(`to ${n.to_in.join(", ")}`),typeof n.subject_contains=="string"&&n.subject_contains&&r.push(`subject contains “${n.subject_contains}”`),n.has_attachment===!0&&r.push("with attachments"),n.has_attachment===!1&&r.push("without attachments");const l=typeof t.every=="string"?t.every:Zg(t.uses_model!==!1);r.push(`checked ${Zx(l)}`);const c=typeof t.max_batch=="number"?t.max_batch:Xg;return r.push(`up to ${c} per run`),r.join(" · ")}const Sf={mode:"self",addresses:""};function sg(e){if(e.mode==="self")return{recipients:["self"],errors:[]};const t=[],n=rb(e.addresses).filter(o=>o!=="self");n.length||t.push("Name at least one address the automation may email, or choose Only me.");const r=n.filter(o=>!ng(o));return r.length&&t.push(`${qt.recipients_list}: ${r.join(", ")} ${r.length===1?"is not an email address":"are not email addresses"}.`),n.length+1>_w&&t.push(`At most ${_w-1} addresses.`),{recipients:["self",...n],errors:t}}function FN(e){const t=(e??[]).filter(n=>n!=="self");return t.length?{mode:"list",addresses:t.join(", ")}:{mode:"self",addresses:""}}function zN(e){const t=(e??["self"]).filter(n=>n!=="self");return t.length?`Me and ${t.join(", ")}`:"Only me"}function lb(e,t=["self"]){return{channels:e?["console","email"]:["console"],...t.some(n=>n!=="self")?{recipients:t}:{}}}function cb(e){return!!e&&Array.isArray(e.channels)&&e.channels.includes("email")}function BN(e){return cb(e)?"In the console and by email":"In the console"}const xi={pause:"automation.pause",resume:"automation.resume",run_now:"automation.run_now",stop_current:"automation.stop_current",archive:"automation.archive",unarchive:"automation.unarchive"},UN=new Set(["running","waiting","backoff"]);function WN(e,t=[]){return e.current_occurrence!=null}function ub(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 db(e,t){const n=Date.parse(e);if(Number.isNaN(n))return"";const r=Math.round((n-t)/6e4);if(r<=0)return"due now";if(r<60)return`in ${r} min`;const o=Math.floor(r/60);return o<24?`in ${o} h${r%60?` ${r%60} min`:""}`:`in ${Math.floor(o/24)} d${o%24?` ${o%24} h`:""}`}function Wm(e,t=[],n=!1){const r=new Set(e.capabilities),o=e.status,l=WN(e,t),c=(m,g,y)=>n?{enabled:!1,reason:"Working…"}:e.legacy?{enabled:!1,reason:"Legacy schedule: managed with its existing controls."}:r.has(m)?o==="archived"?{enabled:!1,reason:"Archived: history is kept, nothing runs."}:g?{enabled:!0}:{enabled:!1,reason:y}:{enabled:!1,reason:"Not permitted for this automation."},u=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."}:u?r.has(f)?{enabled:!0}:{enabled:!1,reason:"Not permitted for this automation."}:{enabled:!1,reason:"The automation has ended."},pause:c("pause",o==="active",o==="paused"?"Already paused.":"The automation has ended."),resume:c("resume",o==="paused",o==="active"?"Already running on schedule.":"The automation has ended."),run_now:c("run_now",u&&!l,l?"An occurrence is in progress.":"The automation has ended."),stop_current:c("stop_current",l,"Nothing is running."),revise:c("revise",!0,""),archive:c("archive",!0,""),unarchive:n?{enabled:!1,reason:"Working…"}:e.legacy?{enabled:!1,reason:"Legacy schedule: managed with its existing controls."}:o!=="archived"?{enabled:!1,reason:"Not archived."}:r.has("unarchive")?{enabled:!0}:{enabled:!1,reason:"Not permitted for this automation."},discuss:n?{enabled:!1,reason:"Working…"}:e.legacy?{enabled:!1,reason:"Legacy schedule: discussion is not available."}:r.has("discuss")?{enabled:!0}:{enabled:!1,reason:"Discussion is not permitted for this automation."}}}function qN(e){return e.status==="active"?xi.pause:xi.resume}function HN(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 VN(e){return[...e].sort((t,n)=>t.index-n.index).map(t=>{const n=HN(t),r=`${t.attempts} ${t.attempts===1?"attempt":"attempts"}`,o=n==="failed"?`Failed after ${r}`:n==="waiting"?"Waiting for you":n==="notified"?"Notified":n==="running"?"Running":null,l=t.status==="completed"&&t.attempts>1?`completed after ${r}`:t.status;return{row:t,tone:n,notable:n==="failed"||n==="waiting"||n==="notified",badge:o,statusText:l,canDiscuss:!UN.has(t.status)}})}function GN(e){const t=e.attention.items;return t.length?t[t.length-1].cursor:null}function fb(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 KN={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 qm(e){return{title:KN[e.code]??`The gateway refused the request (${e.code}).`,detail:e.message}}function Qg(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 hb(e,t){var l,c,u;const n=e.trigger,r=n.source_id==="schedule"||h_(n)?n.config.every:void 0,o=t?t.target.input_data.prompt:void 0;return{title:e.title,every:typeof r=="string"?r:null,context:e.context_mode,growingMaxTokens:Number(((c=(l=t==null?void 0:t.context)==null?void 0:l.growing)==null?void 0:c.max_tokens)??e.growing_max_tokens??$f),prompt:typeof o=="string"?o:null,toolApproval:t?t.policy.tool_approval:null,tools:Yx(t==null?void 0:t.target.input_data),notifyEmail:t?cb(t.notify):null,emailRecipients:t?FN((u=t.notify)==null?void 0:u.recipients):null}}function YN(e,t,n){var f;const r=[],o={},l=t.title.trim();l?l.length>120?r.push("Title is at most 120 characters."):l!==e.title&&(o.title=l):r.push("Title is required.");const c=hb(e,n);if(t.every!==c.every&&t.every!==null){const h=h_(e.trigger);if(!Jf(t.every))r.push("Interval must be a whole number of minutes, hours or days.");else if(h&&(ob(t.every)??0)<sb)r.push("The check interval is at least 60 seconds.");else{const m={...e.trigger.config,every:t.every};h&&delete m.start_at,o.trigger={source_id:e.trigger.source_id,source_version:e.trigger.source_version,config:m}}}const u=t.context==="growing"?t.growingMaxTokens??c.growingMaxTokens:c.growingMaxTokens;if(_b(u)||r.push(mb),(t.context!==e.context_mode||u!==c.growingMaxTokens)&&(o.context=pb(t.context,u)),n&&typeof c.prompt=="string"&&typeof t.prompt=="string"&&t.prompt.trim()!==c.prompt.trim()){const h=t.prompt.trim();h?o.target={bundle_ref:n.target.bundle_ref,flow_id:n.target.flow_id,input_data:{...n.target.input_data,prompt:h}}:r.push("Task is required.")}if(n&&t.tools!==void 0&&JSON.stringify(t.tools)!==JSON.stringify(c.tools)){const h=o.target||{bundle_ref:n.target.bundle_ref,flow_id:n.target.flow_id,input_data:n.target.input_data};o.target={...h,input_data:Jx(h.input_data||{},t.tools)}}if(n&&t.toolApproval&&t.toolApproval!==c.toolApproval&&(o.policy={tool_approval:t.toolApproval}),n&&typeof t.notifyEmail=="boolean"){const h=sg(t.notifyEmail?t.emailRecipients??Sf:c.emailRecipients??Sf),m=sg(c.emailRecipients??Sf).recipients;h.errors.length?r.push(...h.errors):(t.notifyEmail!==c.notifyEmail||JSON.stringify(h.recipients)!==JSON.stringify(m))&&(o.notify=lb(t.notifyEmail,h.recipients))}if(r.length)return{errors:r};if(n&&t.target&&eg(t.target)!==eg(n.target)){const h=((f=o.target)==null?void 0:f.input_data)||n.target.input_data;o.target={...t.target,input_data:jN(h)}}return Object.keys(o).length?o:null}const $f=5e4,JN="Limits history carried into the next run, keeping recent whole turns. The newest turn is kept even if oversized. New messages and tool results can grow context beyond this budget.",mb="Max growing context must be a positive whole number of tokens.";function _b(e){return Number.isSafeInteger(e)&&e>0}function pb(e,t){return{mode:e,...t!==$f?{growing:{max_tokens:t}}:{}}}const XN=[{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 cp(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 ZN(e){const t=e.trim().split(`
|
|
56
|
-
`)[0].trim();return t.length>120?`${t.slice(0,119)}…`:t}function QN(e){const t=[],n={};if(e.when.kind==="once"){const o=cp(e.when.at);return o?n.start_at=o:t.push("Pick the date and time (UTC) to run once."),{config:n,errors:t}}const r=e.when.amount;if(!Number.isInteger(r)||r<1?t.push("The interval must be a whole number of at least 1."):n.every=`${r}${e.when.unit}`,e.startAt){const o=cp(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=cp(e.until);o?n.until=o:t.push("Stop at must be a date and time (UTC).")}return{config:n,errors:t}}function rg(e,t){const n=[];t.target||n.push("Choose what to run.");const r=e.prompt.trim();r||n.push("Write the task to run.");const o=(e.title??"").trim()||ZN(r);o.length>120&&n.push("Title is at most 120 characters.");const l=e.trigger==="email",c=l?DN(e.email??ib):QN(e);n.push(...c.errors);const u=e.notifyEmail&&e.emailRecipients&&e.emailRecipients.mode==="list"?sg(e.emailRecipients):null;u&&n.push(...u.errors);const f=e.growingMaxTokens??$f;if(e.context==="growing"&&!_b(f)&&n.push(mb),n.length||!t.target)return{ok:!1,errors:n};const h={...t.target,input_data:{...t.target.input_data??{},prompt:r}},m={request_id:t.requestId,title:o,target:h,trigger:l?{source_id:tb,source_version:nb,config:c.config}:{source_id:"schedule",source_version:1,config:c.config},context:pb(e.context,e.context==="growing"?f:$f),policy:{tool_approval:e.toolApproval??"auto"}};return e.notifyEmail===!0&&(m.notify=lb(!0,u==null?void 0:u.recipients)),{ok:!0,body:m}}const e1="Tools run without asking (you approve them now by creating this automation)";function t1(e){if(e.kind!=="tool_approval"||!Array.isArray(e.details))return null;const t=[];for(const n of e.details){if(!n||typeof n!="object"||Array.isArray(n))return null;const r=n;if(typeof r.name!="string"||!r.arguments||typeof r.arguments!="object"||Array.isArray(r.arguments)||r.call_id!==void 0&&typeof r.call_id!="string")return null;t.push({name:r.name,arguments:r.arguments,...typeof r.call_id=="string"?{call_id:r.call_id}:{}})}return t}function n1(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 gb={ask_user:"Question for you",tool_approval:"Approval needed",event:"Waiting for an event"};class s1{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||r1(n.error))&&this.open.delete(t)}}function r1(e){return Qg(e)&&e.status>0&&e.code!=="invalid_response"}function i1(){return pa()}class o1{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 pw(e,t){if(!e)return null;for(const n of t){const r=e.querySelector(n);if(r&&r.disabled!==!0&&typeof r.focus=="function")return r}return null}function gw(e){const t=Array.from(new Set(e.map(n=>String(n||"").trim()).filter(Boolean)));return t.sort((n,r)=>n.localeCompare(r)),t}function ig(e){const t=e.disabled===!0,n=_.useMemo(()=>gw([...e.options||[],...e.value||[]]),[e.options,e.value]),r=_.useMemo(()=>gw(e.value||[]),[e.value]),[o,l]=_.useState(!1),[c,u]=_.useState(""),f=_.useMemo(()=>{const g=c.trim().toLowerCase();return g?n.filter(y=>y.toLowerCase().includes(g)):n},[n,c]),h=_.useMemo(()=>new Set(r),[r]),m=typeof e.max_list_height_px=="number"?e.max_list_height_px:220;return s.jsxs("div",{className:"af_multi_select",children:[s.jsxs("div",{className:"af_multi_select_row",children:[s.jsxs("button",{className:"btn",type:"button",onClick:()=>l(g=>!g),disabled:t||!n.length,"aria-expanded":o,children:[o?"Hide":"Select"," • ",r.length>0?`${r.length} of ${n.length}`:e.placeholder||"(none)"]}),s.jsx("button",{className:"btn",type:"button",onClick:()=>e.onChange(n.slice()),disabled:t||!n.length||r.length===n.length,title:"Select all",children:"All"}),s.jsx("button",{className:"btn",type:"button",onClick:()=>e.onChange([]),disabled:t||r.length===0,title:"Clear selection",children:"Clear"})]}),r.length>0?s.jsx("div",{className:"af_multi_select_chips",children:r.map(g=>s.jsxs("button",{type:"button",disabled:t,"aria-label":`Remove ${g}`,className:"af_multi_select_chip",title:g,onClick:()=>{if(t)return;const y=new Set(h);y.delete(g),e.onChange(Array.from(y.values()))},children:[g,t?null:s.jsx("span",{className:"af_multi_select_chip_x",children:"×"})]},g))}):null,o?s.jsxs("div",{className:"af_multi_select_panel",children:[s.jsx("input",{className:"mono",value:c,onChange:g=>u(String(g.target.value||"")),placeholder:"filter…","aria-label":"Filter options",disabled:t}),s.jsxs("div",{className:"af_multi_select_list",style:{maxHeight:`${m}px`},children:[f.map(g=>{const y=h.has(g);return s.jsxs("label",{className:`af_multi_select_item mono ${y?"checked":""}`,children:[s.jsx("input",{type:"checkbox",checked:y,disabled:t,onChange:w=>{const k=new Set(h);w.target.checked?k.add(g):k.delete(g),e.onChange(Array.from(k.values()))}}),s.jsx("span",{children:g})]},g)}),f.length?null:s.jsx("div",{className:"mono muted",children:"(no matches)"})]})]}):null]})}function yb(e){return s.jsxs("div",{className:"af-auto__field","data-field":"tool-selection",children:[s.jsxs("label",{children:[s.jsx("input",{type:"checkbox",checked:e.value===null,disabled:e.disabled,onChange:t=>e.onChange(t.target.checked?null:[])})," Use workflow default tools"]}),e.value!==null?s.jsx(ig,{options:e.availableTools,value:e.value,disabled:e.disabled,placeholder:"No tools enabled",onChange:e.onChange}):null,s.jsx("p",{className:"af-auto__hint",children:"Choose which tools this automation can use. An empty selection disables tools. Gateway restrictions always apply."})]})}const wb="@default",vb="No workflows available for this app — ask your admin.",xb={shared:"Shared",mine:"Mine"};class il extends Error{constructor(t){super(t),this.name="WorkflowPickerContractError"}}function a1(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 l1(e={}){return e.allVersions?"bundles?all_versions=true":"bundles"}function c1(e,t={}){return e===null?l1(t):a1(e,t)}function ma(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function Ls(e){return typeof e=="string"?e.trim():""}const lm="update the gateway";function u1(e,t){var u,f;const n=ma(e.default_agent_workflows);if(!n)return{status:"unavailable",reason:"the gateway does not report a default workflow"};const r=ma(n[t]);if(!r)return{status:"unavailable",reason:Ls((f=ma((u=ma(e.default_agent_workflows_unavailable))==null?void 0:u[t]))==null?void 0:f.reason)||`no default workflow for ${t}`};const o=Ls(r.bundle_id),l=Ls(r.flow_id);if(!o||!l)return{status:"unavailable",reason:"the gateway's default workflow is missing its bundle or flow"};const c=Ls(r.bundle_version);return{status:"ok",name:Ls(r.name)||l,bundleId:o,bundleVersion:c,flowId:l,workflowId:Ls(r.workflow_id)||`${o}${c?`@${c}`:""}:${l}`}}function d1(e,t,n={}){var u;const r=ma(e);if(!r)throw new il("The gateway's workflow list is not a JSON object.");const o=Ls(r.executable_for);if(t===null){if(o)throw new il(`Asked for every workflow, the gateway listed only ${o}.`)}else if(o!==t)throw new il(o?`The gateway listed workflows for ${o}, not ${t}.`:`This gateway does not filter workflows per app (no executable_for in its answer): ${lm}.`);if(!Array.isArray(r.items))throw new il("The gateway's workflow list has no items.");const l=[];for(const f of r.items){const h=ma(f),m=Ls(h==null?void 0:h.bundle_id);if(!h||!m)throw new il("The gateway listed a workflow without a bundle id.");const g=ma(h.owner),y=Ls(g==null?void 0:g.kind);if(y!=="gateway"&&y!=="user")throw new il(`The gateway did not say who owns ${m} (owner missing): ${lm}.`);if(typeof h.shipped!="boolean")throw new il(`The gateway did not say whether ${m} ships with it (shipped missing): ${lm}.`);const w=Ls(h.bundle_version),k=Array.isArray(h.entrypoints)?h.entrypoints:[];for(const b of k){const S=ma(b),N=Ls(S==null?void 0:S.flow_id);if(!S||!N)continue;const R=Array.isArray(S.interfaces)?S.interfaces.map(Ls).filter(Boolean):[];if(t===null){if(!R.length)continue}else if(!R.includes(t))throw new il(`The gateway offered ${m}:${N}, which does not declare ${t}: ${lm}.`);l.push({value:Ls(S.workflow_id)||`${m}${w?`@${w}`:""}:${N}`,bundleId:m,bundleVersion:w,flowId:N,name:Ls(S.name)||Ls((u=ma(h.metadata))==null?void 0:u.name)||m,description:Ls(S.description)||Ls(h.description),registryScope:Ls(h.registry_scope)||"private",group:y==="user"?"mine":"shared",shipped:h.shipped,interfaces:R,...t===null?{showInterfaces:!0}:{}})}}const c=n.defaultInterface??t;return{interfaceId:t,entries:l,gatewayDefault:c?u1(r,c):{status:"unavailable",reason:"no interface named for the gateway default"}}}function f1(e){const t=(n,r)=>n.name.localeCompare(r.name)||r.bundleVersion.localeCompare(n.bundleVersion,void 0,{numeric:!0})||n.value.localeCompare(r.value);return["shared","mine"].map(n=>({id:n,label:xb[n],entries:e.filter(r=>r.group===n).sort(t)})).filter(n=>n.entries.length>0)}const h1={"abstractcode.agent.v1":"Code agent","abstractassistant.agent.v1":"Assistant","abstractcode.coding.v1":"Coding",tools:"tools",event:"event",chat:"chat"};function m1(e){return h1[e]??e}function _1(e,t=[]){const n=e.bundleVersion?`@${e.bundleVersion}`:"";return e.showInterfaces?[[...new Set(e.interfaces.map(m1))].join(", "),n].filter(Boolean).join(" · "):n}function p1(e){return e.value}function g1(e){return e?e.status==="unavailable"?e.reason:`${e.name}${e.bundleVersion?` @${e.bundleVersion}`:""}`:""}function y1(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 w1(e,t=!0){const n=(e==null?void 0:e.entries)??[],r=[];t&&r.push({key:"default",value:wb,name:"Gateway default",detail:g1((e==null?void 0:e.gatewayDefault)??null),group:null,entry:null});for(const o of f1(n))for(const l of o.entries)r.push({key:l.value,value:l.value,name:l.name,detail:_1(l,n),title:p1(l),group:o.id,entry:l});return r}async function v1(e,t,n){var l;const r=await fetch(Kg(e,it(t)),{credentials:"include",headers:{Accept:"application/json"},signal:n}),o=await r.json().catch(()=>null);if(!r.ok){const c=((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(c||`The gateway answered ${r.status}.`)}return o}function x1(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 bb(e){const{interfaceId:t,defaultInterface:n,allVersions:r=!1,enabled:o=!0,gatewayBaseUrl:l,reloadKey:c}=e,u=_.useRef(e.request);u.current=e.request;const[f,h]=_.useState(0),[m,g]=_.useState({status:"idle",data:null,error:""});_.useEffect(()=>{if(!o){g({status:"idle",data:null,error:""});return}const w=new AbortController;g(S=>({...S,status:"loading",error:""}));const k=c1(t,{allVersions:r});return(u.current?u.current(k,{signal:w.signal}):v1(l,k,w.signal)).then(S=>{w.signal.aborted||g({status:"ready",data:d1(S,t,{defaultInterface:n}),error:""})}).catch(S=>{w.signal.aborted||g({status:"error",data:null,error:x1(S)})}),()=>w.abort()},[t,n,r,o,l,c,f]);const y=_.useCallback(()=>h(w=>w+1),[]);return{...m,reload:y}}function b1(e){if(!e||typeof window>"u")return{};const t=e.getBoundingClientRect(),n=window.innerWidth,r=window.innerHeight,o=Math.min(Math.max(t.width,300),440,n-32),l=Math.max(16,Math.min(t.left,n-16-o)),c=r-t.bottom-16;return c>=220||c>=t.top?{position:"fixed",left:l,width:o,top:t.bottom+4,maxHeight:Math.max(160,c)}:{position:"fixed",left:l,width:o,bottom:r-t.top+4,maxHeight:Math.max(160,t.top-16)}}function kb(...e){return e.filter(Boolean).join(" ")}function jb(e){const t=bb({interfaceId:e.interfaceId,defaultInterface:e.defaultInterface,request:e.request,gatewayBaseUrl:e.gatewayBaseUrl,allVersions:e.allVersions,enabled:e.workflows?!1:e.enabled!==!1}),n=e.workflows??t,r=e.showDefault!==!1&&(e.interfaceId!==null||!!e.defaultInterface),o=_.useId().replace(/:/g,""),l=`${o}-list`,[c,u]=_.useState(!1),[f,h]=_.useState(-1),m=_.useRef(null),g=_.useRef(null),[y,w]=_.useState({}),k=_.useMemo(()=>w1(n.data,r),[n.data,r]),b=k.find(J=>J.value===e.value),S=b?{name:b.name,detail:b.detail}:e.currentLabel?{name:e.currentLabel.name,detail:e.currentLabel.detail||""}:n.status==="loading"?{name:"Loading workflows…",detail:""}:{name:e.value===wb?"Gateway default":"Choose a workflow",detail:""},N=String(e.unavailableReason||"").trim(),R=!N&&n.status==="ready",T=_.useCallback(()=>{u(!1),h(-1)},[]),A=_.useCallback(()=>{if(!R)return;w(b1(g.current)),u(!0);const J=k.findIndex(K=>K.value===e.value);h(J>=0?J:0)},[R,k,e.value]),W=_.useCallback(J=>{var K;T(),J.value!==e.value&&e.onChange(J.value,J.entry),(K=g.current)==null||K.focus()},[T,e]);_.useEffect(()=>{if(!c)return;const J=re=>{m.current&&!m.current.contains(re.target)&&T()},K=()=>T();return document.addEventListener("mousedown",J),document.addEventListener("touchstart",J),window.addEventListener("resize",K),()=>{document.removeEventListener("mousedown",J),document.removeEventListener("touchstart",J),window.removeEventListener("resize",K)}},[c,T]),_.useEffect(()=>{var K;if(!c||f<0)return;const J=typeof document<"u"?document.getElementById(`${o}-opt-${f}`):null;(K=J==null?void 0:J.scrollIntoView)==null||K.call(J,{block:"nearest"})},[c,f,o]);const z=J=>{if(!c){["Enter"," ","ArrowDown","ArrowUp"].includes(J.key)&&(J.preventDefault(),A());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&&k[f]&&W(k[f]);return}const K=y1(J.key,f,k.length);K!==null&&(J.preventDefault(),h(K))};return s.jsxs("div",{ref:m,className:kb("af-workflow-picker",e.className),"data-interface":e.interfaceId??"any",children:[s.jsxs("button",{ref:g,id:e.id,type:"button",role:"combobox",className:"af-workflow-picker__trigger","aria-label":e.ariaLabel||"Workflow","aria-describedby":`${o}-value`,"aria-haspopup":"listbox","aria-expanded":c,"aria-controls":l,"aria-activedescendant":c&&f>=0?`${o}-opt-${f}`:void 0,"aria-disabled":R?void 0:!0,title:N||void 0,onClick:()=>c?T():A(),onKeyDown:z,children:[s.jsxs("span",{className:"af-workflow-picker__value",id:`${o}-value`,children:[s.jsx("span",{className:"af-workflow-picker__name",children:S.name}),S.detail?s.jsx("span",{className:"af-workflow-picker__detail",children:S.detail}):null]}),s.jsx("span",{className:"af-workflow-picker__caret","aria-hidden":"true"})]}),c?s.jsx(k1,{id:l,idBase:o,rows:k,value:e.value,highlight:f,ariaLabel:e.ariaLabel||"Workflow",style:y,onHighlight:h,onChoose:W}):null,n.status==="error"?s.jsx("span",{className:"af-workflow-picker__error",role:"alert",children:n.error}):n.status==="ready"&&k.every(J=>!J.entry)&&!r?s.jsx("span",{className:"af-workflow-picker__empty",role:"status",children:vb}):null]})}function k1(e){const t=(l,c)=>s.jsxs("div",{id:`${e.idBase}-opt-${c}`,role:"option","aria-selected":l.value===e.value,"data-value":l.value,title:l.title,className:kb("af-workflow-picker__option",c===e.highlight&&"af-workflow-picker__option--highlighted",l.value===e.value&&"af-workflow-picker__option--selected"),onMouseEnter:()=>e.onHighlight(c),onMouseDown:u=>u.preventDefault(),onClick:()=>e.onChoose(l),children:[s.jsx("span",{className:"af-workflow-picker__name",children:l.name}),l.detail?s.jsx("span",{className:"af-workflow-picker__detail",children:l.detail}):null]},l.key),n=e.rows.map((l,c)=>({row:l,index:c})),r=n.filter(l=>l.row.group===null),o=["shared","mine"].map(l=>({g:l,items:n.filter(c=>c.row.group===l)})).filter(l=>l.items.length>0);return s.jsxs("div",{id:e.id,role:"listbox","aria-label":e.ariaLabel,className:"af-workflow-picker__list",style:e.style,children:[r.map(l=>t(l.row,l.index)),o.map(({g:l,items:c})=>s.jsxs("div",{role:"group","aria-labelledby":`${e.idBase}-g-${l}`,"data-group":l,children:[s.jsx("div",{id:`${e.idBase}-g-${l}`,className:"af-workflow-picker__group",role:"presentation",children:xb[l]}),c.map(u=>t(u.row,u.index))]},l)),o.length===0?s.jsx("p",{className:"af-workflow-picker__empty",children:vb}):null]})}function j1(e){const t=eg(e.target);return s.jsxs("div",{className:"af-auto__field",children:[s.jsx("span",{children:"Workflow"}),s.jsx(jb,{...e.options,ariaLabel:"Automation workflow",value:t,currentLabel:{name:t},onChange:(n,r)=>e.onChange(n==="@default"?{flow_id:"@default",interface:e.options.interfaceId||e.options.defaultInterface||"abstractcode.agent.v1"}:{bundle_ref:`${r.bundleId}@${r.bundleVersion}`,flow_id:r.flowId})})]})}async function S1(e,t){var y,w;const n=e.flow_id==="@default"?(w=(y=t.workflows)==null?void 0:y.data)==null?void 0:w.gatewayDefault:null,r="bundle_ref"in e?e.bundle_ref:(n==null?void 0:n.status)==="ok"?`${n.bundleId}@${n.bundleVersion}`:"",o=e.flow_id!=="@default"?e.flow_id:(n==null?void 0:n.status)==="ok"?n.flowId:"";if(!r||!o||!t.request)throw new Error("Workflow inputs could not be checked. Refresh the workflow list and try again.");const l=r.lastIndexOf("@"),c=l<0?r:r.slice(0,l),u=l<0?"":r.slice(l+1),f=await t.request(`bundles/${encodeURIComponent(c)}/flows/${encodeURIComponent(o)}/input_schema${u?`?bundle_version=${encodeURIComponent(u)}`:""}`,{signal:new AbortController().signal}),h=(f==null?void 0:f.input_data_schema)||f;if(!h||typeof h!="object"||!h.properties)throw new Error("This workflow does not report its input requirements. Choose another workflow.");const m={...f.defaults||{}};for(const[k,b]of Object.entries(h.properties))b&&"default"in b&&(m[k]=b.default);Object.assign(m,e.input_data||{});const g=(Array.isArray(h.required)?h.required:[]).filter(k=>m[k]===void 0);if(g.length)throw new Error(`This workflow needs additional inputs: ${g.join(", ")}. Configure a new automation from that workflow's input form, or choose a compatible workflow.`);return{...e,input_data:m}}function og(e){if(m_(e.status))return null;const t=qt.not_set_up,n=qt.open_my_email,r=t.endsWith(n)?t.slice(0,t.length-n.length):`${t} `,o=e.status&&e.status.admin_disabled&&typeof e.status.admin_disabled.cause=="string"?e.status.admin_disabled.cause:"";return s.jsxs("p",{className:"af-auto__hint af-email__notice",role:"note","data-email-setup":"missing",children:[r,e.onOpenMyEmail?s.jsx("button",{type:"button",className:"af-auto__linkbtn","data-action":"open-my-email",onClick:e.onOpenMyEmail,children:n}):n,o?s.jsxs("span",{className:"af-email__cause",children:[" (",o,")"]}):null]})}function N1(e){const t=e.value,n=u=>e.onChange({...t,...u}),r=u=>`${e.idBase}-email-${u}`,o=Jf(Zg(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"}),c=e.disabled===!0;return s.jsxs("div",{className:"af-email__trigger","data-field":"email-trigger",children:[s.jsxs("div",{className:"af-auto__row",children:[s.jsx("span",{children:qt.every_label}),s.jsx("input",{type:"number",min:1,step:1,value:String(l.amount),disabled:c,"aria-label":"Check interval amount",name:"email_every_amount",onChange:u=>n({every:{amount:Number(u.target.value),unit:l.unit}})}),s.jsxs("select",{value:l.unit,disabled:c,"aria-label":"Check interval unit",name:"email_every_unit",onChange:u=>n({every:{amount:l.amount,unit:u.target.value}}),children:[s.jsx("option",{value:"m",children:"minutes"}),s.jsx("option",{value:"h",children:"hours"}),s.jsx("option",{value:"d",children:"days"})]})]}),s.jsx("p",{className:"af-auto__hint","data-email-rule":"interval",children:qt.interval_rule}),s.jsxs("label",{className:"af-auto__field",htmlFor:r("batch"),children:[s.jsx("span",{children:qt.max_batch_label}),s.jsx("input",{id:r("batch"),name:"email_max_batch",type:"number",min:1,max:tg,step:1,disabled:c,value:String(t.maxBatch??Xg),onChange:u=>n({maxBatch:u.target.value.trim()===""?null:Number(u.target.value)})})]}),s.jsx("p",{className:"af-auto__hint",children:qt.max_batch_hint}),s.jsxs("fieldset",{className:"af-auto__field af-email__filters",disabled:c,children:[s.jsx("legend",{children:qt.filters_legend}),s.jsxs("label",{className:"af-auto__field",htmlFor:r("from"),children:[s.jsx("span",{children:qt.from_in}),s.jsx("input",{id:r("from"),name:"email_from_in",value:t.fromIn,spellCheck:!1,placeholder:"alice@example.com, billing@example.org",onChange:u=>n({fromIn:u.target.value})})]}),s.jsxs("label",{className:"af-auto__field",htmlFor:r("domain"),children:[s.jsx("span",{children:qt.from_domain_in}),s.jsx("input",{id:r("domain"),name:"email_from_domain_in",value:t.fromDomainIn,spellCheck:!1,placeholder:"example.com",onChange:u=>n({fromDomainIn:u.target.value})})]}),s.jsxs("label",{className:"af-auto__field",htmlFor:r("to"),children:[s.jsx("span",{children:qt.to_in}),s.jsx("input",{id:r("to"),name:"email_to_in",value:t.toIn,spellCheck:!1,onChange:u=>n({toIn:u.target.value})})]}),s.jsxs("label",{className:"af-auto__field",htmlFor:r("subject"),children:[s.jsx("span",{children:qt.subject_contains}),s.jsx("input",{id:r("subject"),name:"email_subject_contains",value:t.subjectContains,maxLength:200,onChange:u=>n({subjectContains:u.target.value})})]}),s.jsxs("label",{className:"af-auto__field",htmlFor:r("attach"),children:[s.jsx("span",{children:qt.has_attachment}),s.jsxs("select",{id:r("attach"),name:"email_has_attachment",value:t.hasAttachment,onChange:u=>n({hasAttachment:u.target.value}),children:[s.jsx("option",{value:"any",children:qt.has_attachment_any}),s.jsx("option",{value:"yes",children:qt.has_attachment_yes}),s.jsx("option",{value:"no",children:qt.has_attachment_no})]})]}),s.jsx("p",{className:"af-auto__hint",children:qt.list_hint})]})]})}function C1(e){const t=r=>`${e.idBase}-email-${r}`,n=e.disabled===!0;return s.jsxs("div",{className:"af-email__options","data-field":"email-options",children:[s.jsx(Ni,{variant:"row",action:"notify-email",label:qt.notify_label,checked:e.notifyEmail,unavailableReason:n?"Connect a mailbox first.":null,onChange:r=>e.onNotifyEmailChange(r)}),s.jsxs("p",{className:"af-auto__hint",children:[qt.notify_hint," Turn on Email result to choose yourself or other email addresses."]}),e.notifyEmail?s.jsxs("fieldset",{className:"af-auto__field",disabled:n,"data-field":"email-recipients",children:[s.jsx("legend",{children:qt.recipients_legend}),s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:t("rcpt"),value:"self",checked:e.recipients.mode==="self",onChange:()=>e.onRecipientsChange({...e.recipients,mode:"self"})})," ",qt.recipients_self]}),s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:t("rcpt"),value:"list",checked:e.recipients.mode==="list",onChange:()=>e.onRecipientsChange({...e.recipients,mode:"list"})})," ",qt.recipients_list]}),e.recipients.mode==="list"?s.jsx("textarea",{name:"email_recipient_list","aria-label":qt.recipients_list,rows:2,spellCheck:!1,value:e.recipients.addresses,placeholder:"colleague@example.com",onChange:r=>e.onRecipientsChange({mode:"list",addresses:r.target.value})}):null,s.jsx("p",{className:"af-auto__hint",children:qt.recipients_hint})]}):null]})}const E1={active:"play",paused:"pause",completed:"check",failed:"error",archived:"archive"};function Sb(e){const t=String(e.status),n=E1[t];return s.jsxs("span",{className:`af-auto__status af-auto__status--${t}${e.className?` ${e.className}`:""}`,"data-state":t,children:[s.jsx("span",{className:"af-auto__status-word",children:RN[t]??t}),n?s.jsx(Be,{name:n,size:e.iconSize??11,className:"af-auto__status-icon"}):null]})}const ag="Discuss — fork at this occurrence (own workspace, automation files read-only)",__=e=>s.jsx("div",{className:"af-auto-text","data-unformatted":"true",children:e});function $1(e){return Qg(e)?e:{status:0,code:"client_error",message:e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}}function yw(e){const t=e.path.split(new RegExp("(?<=[/\\\\_-])"));return s.jsx("code",{className:"af-auto__path-text",children:t.map((n,r)=>s.jsxs(xe.Fragment,{children:[n,r<t.length-1?s.jsx("wbr",{}):null]},r))})}function A1(e,t){const n=e.trigger,r=t.find(o=>o.id===n.source_id&&o.version===n.source_version);return r?"available"in r&&r.available===!1?`Trigger source ${n.source_id}@${n.source_version} is unavailable${r.unavailable_reason?`: ${r.unavailable_reason}`:"."}`:null:`This gateway does not list the trigger source ${n.source_id}@${n.source_version}.`}function T1(e){const t=e.summary,n=ub(t),r=A1(t,e.triggerSources),o=t.next_fire_at?`${ya(t.next_fire_at)} (${db(t.next_fire_at,e.nowMs??Date.now())})`:t.status==="paused"?"none while paused":"none scheduled";return s.jsxs("header",{className:"af-auto__head",children:[s.jsxs("div",{className:"af-auto__titlebar",children:[s.jsx("h2",{className:"af-auto__title",id:e.titleId,tabIndex:-1,children:t.title}),s.jsx(Sb,{status:t.status}),t.legacy?s.jsx("span",{className:"af-auto__legacy",children:"Legacy schedule"}):null]}),s.jsxs("dl",{className:"af-auto__facts",children:[e.workflowLabel?s.jsxs(s.Fragment,{children:[s.jsx("dt",{children:"Workflow"}),s.jsx("dd",{"data-fact":"workflow",children:e.workflowLabel})]}):null,s.jsx("dt",{children:"When"}),s.jsxs("dd",{"data-fact":"trigger",children:[Jg(t.trigger),r?s.jsxs("span",{className:"af-auto__warn",role:"note",children:[" ",r]}):null]}),s.jsx("dt",{children:"Context"}),s.jsx("dd",{"data-fact":"context",children:eb(t.context_mode)}),n?s.jsxs(s.Fragment,{children:[s.jsx("dt",{children:"Now"}),s.jsx("dd",{"data-fact":"current",className:"is-notable",children:n})]}):null,s.jsx("dt",{children:"Next run"}),s.jsx("dd",{"data-fact":"next",children:o}),s.jsx("dt",{children:"Runs"}),s.jsx("dd",{"data-fact":"count",children:t.occurrence_count}),t.workspace_root?s.jsxs(s.Fragment,{children:[s.jsx("dt",{children:"Workspace"}),s.jsx("dd",{"data-fact":"workspace",className:"af-auto__workspace",children:e.onOpenWorkspace?s.jsxs("button",{type:"button",className:"af-auto__path","data-action":"open-workspace",title:`Browse the automation's folder
|
|
57
|
-
${t.workspace_root}`,"aria-label":`Browse the automation's folder ${t.workspace_root}`,onClick:()=>{var l;return(l=e.onOpenWorkspace)==null?void 0:l.call(e,t.automation_id)},children:[s.jsx(Be,{name:"folder",size:14,className:"af-auto__path-icon"}),s.jsx(yw,{path:t.workspace_root})]}):s.jsxs("span",{className:"af-auto__path af-auto__path--static",children:[s.jsx(Be,{name:"folder",size:14,className:"af-auto__path-icon"}),s.jsx(yw,{path:t.workspace_root})]})})]}):null,s.jsx("dt",{children:"Attention"}),s.jsx("dd",{"data-fact":"attention",className:t.attention.unread||t.attention.pending_waits?"is-notable":void 0,children:fb(t)}),t.revision!==null?s.jsxs(s.Fragment,{children:[s.jsx("dt",{children:"Revision"}),s.jsx("dd",{"data-fact":"revision",children:t.revision})]}):null]})]})}function M1(e){var c,u;const t=e.definition,n=e.renderText??__,r=t.target.input_data.prompt,o=t.policy.retry,l=t.policy.tool_approval;return s.jsxs("details",{className:"af-auto__definition","data-definition-revision":t.revision,open:e.open,children:[s.jsxs("summary",{children:[s.jsx(Be,{name:"chevronRight",size:14,className:"af-auto__definition-chevron"}),s.jsx(Be,{name:"file",size:14}),s.jsx("span",{className:"af-auto__definition-title",children:"Definition"}),s.jsxs("span",{className:"af-auto__definition-meta",children:["revision ",t.revision]})]}),s.jsxs("dl",{className:"af-auto__facts",children:[s.jsx("dt",{children:"Target"}),s.jsx("dd",{"data-def":"target",children:s.jsx("code",{children:t.target.workflow_id})}),typeof r=="string"&&r?s.jsxs(s.Fragment,{children:[s.jsx("dt",{children:"Task"}),s.jsx("dd",{"data-def":"prompt",children:n(r)})]}):null,s.jsx("dt",{children:"Trigger"}),s.jsxs("dd",{"data-def":"trigger",children:[t.trigger.source_id,"@",t.trigger.source_version," · ",Jg(t.trigger),s.jsx("pre",{className:"af-auto__json",children:JSON.stringify(t.trigger.config,null,2)})]}),s.jsx("dt",{children:"Context"}),s.jsxs("dd",{"data-def":"context",children:[eb(t.context.mode),t.context.mode==="growing"?` · ${Number(((c=t.context.growing)==null?void 0:c.max_tokens)??5e4).toLocaleString()} tokens`:""]}),s.jsx("dt",{children:"Tools"}),s.jsx("dd",{"data-def":"tool_approval",children:l==="ask"?"Ask before each tool call (ask)":l==="auto"?"Run without asking (auto)":String(l)}),s.jsx("dt",{children:"Notify"}),s.jsx("dd",{"data-def":"notify",children:BN(t.notify)}),(u=t.notify)!=null&&u.channels.includes("email")?s.jsxs(s.Fragment,{children:[s.jsx("dt",{children:"Recipients"}),s.jsx("dd",{"data-def":"email_recipients",children:zN(t.notify.recipients)})]}):null,s.jsx("dt",{children:"Retries"}),s.jsxs("dd",{"data-def":"retry",children:[o.max_attempts," ",o.max_attempts===1?"attempt":"attempts",", backoff ",o.backoff.initial," ×",o.backoff.factor," up to ",o.backoff.max]}),s.jsx("dt",{children:"Revision"}),s.jsx("dd",{"data-def":"revision",children:t.revision})]})]})}const Xf=Xx,No=Xf.labels,Vi={active:"play",pause:"pause",resume:"play",run_now:Xf.icons.run_now.name,stop_current:"stop",revise:"edit",archive:"archive",unarchive:"unarchive",discuss:"chat"},lg=Xf.hints,R1=Xf.run_now_next_run_line,L1=Xf.run_now_growing_line;function Hm(e,t){const n=[lg[e]];return e==="run_now"&&t&&(t.next_fire_at&&n.push(R1.replace("{time}",ya(t.next_fire_at))),t.context_mode==="growing"&&n.push(L1)),n.join(`
|
|
58
|
-
`)}function I1(e,t,n){const r=new Map;for(const c of t){const u=e[c];if(u.enabled)continue;const f=u.reason??"Not available now.";r.set(f,[...r.get(f)??[],c])}const o=[],l={};return[...r.entries()].forEach(([c,u],f)=>{const h=`${n}-why-${f}`;o.push({id:h,text:`${u.map(m=>No[m]).join(", ")}: ${c}`});for(const m of u)l[m]=h}),{lines:o,describedBy:l}}function fr(e){return s.jsxs(s.Fragment,{children:[s.jsx(Be,{name:e.icon,size:14,className:"af-auto__btn-icon"}),s.jsx("span",{children:e.label})]})}function O1(e){const t=Wm(e.summary,e.occurrences,e.busy),n=e.summary.status==="archived",o=I1(t,["active","run_now","stop_current","revise",n?"unarchive":"archive"],e.idBase??`af-auto-${e.summary.automation_id}`),l=(c,u,f)=>{const h=Hm(c,e.summary);return s.jsx("button",{type:"button",className:`af-auto__btn${f!=null&&f.danger?" af-auto__btn--danger":""}`,"data-action":(f==null?void 0:f.action)??c,disabled:!t[c].enabled,title:t[c].enabled?h:`${t[c].reason}
|
|
59
|
-
${h}`,"aria-description":h,"aria-describedby":o.describedBy[c],"aria-pressed":f==null?void 0:f.pressed,onClick:u,children:s.jsx(fr,{icon:Vi[c],label:(f==null?void 0:f.label)??No[c]})},c)};return s.jsxs("div",{className:"af-auto__controls-wrap",children:[s.jsxs("div",{className:"af-auto__actionbar",children:[s.jsxs("div",{className:"af-auto__controls",role:"toolbar","aria-label":"Automation controls",children:[s.jsx(Ni,{className:"af-auto__switch",action:"active",label:No.active,checked:e.summary.status==="active",unavailableReason:t.active.enabled?null:t.active.reason??"Not available now.",describedBy:o.describedBy.active,busy:e.busy,hint:Hm("active",e.summary),onChange:()=>e.onCommand(qN(e.summary))},"active"),l("run_now",()=>e.onCommand(xi.run_now)),l("stop_current",()=>e.onCommand(xi.stop_current)),l("revise",e.onToggleRevise,{pressed:e.reviseOpen,action:"edit"}),n?l("unarchive",()=>e.onCommand(xi.unarchive)):l("archive",e.onAskArchive,{danger:!0,label:"Archive…"})]}),s.jsx("span",{className:`af-auto__notice${e.notice?" af-auto__notice--on":""}`,role:"status",tabIndex:-1,children:e.notice?s.jsxs(s.Fragment,{children:[s.jsx(Be,{name:"check",size:13}),s.jsx("span",{className:"af-auto__notice-text",children:e.notice}),e.onDismissNotice?s.jsx("button",{type:"button",className:"af-auto__icon-btn af-auto__icon-btn--bare","data-action":"dismiss-notice","aria-label":"Dismiss",title:"Dismiss",onClick:e.onDismissNotice,children:s.jsx(Be,{name:"x",size:12})}):null]}):null})]}),o.lines.length?s.jsxs("p",{className:"af-auto__reasons",children:[s.jsx(Be,{name:"info",size:12,className:"af-auto__reasons-icon"}),o.lines.map(c=>s.jsx("span",{id:c.id,children:c.text},c.id))]}):null,e.summary.status==="paused"&&t.run_now.enabled?s.jsx("p",{className:"af-auto__hint",children:"Paused: scheduled runs are skipped. Run now works and keeps it paused."}):null,e.confirmingArchive&&!n?s.jsxs("div",{className:"af-auto__confirm",role:"group","aria-label":"Confirm archive",children:[s.jsxs("p",{children:["Archive “",e.summary.title,"”? Its history stays readable; it will not run again. The current run, if any, finishes."]}),s.jsxs("div",{className:"af-auto__row",children:[s.jsx("button",{type:"button",className:"af-auto__btn af-auto__btn--danger","data-action":"archive-confirm",disabled:!t.archive.enabled,onClick:()=>e.onCommand(xi.archive),children:s.jsx(fr,{icon:"archive",label:"Archive"})}),s.jsx("button",{type:"button",className:"af-auto__btn","data-action":"archive-cancel",onClick:e.onCancelArchive,children:s.jsx(fr,{icon:"x",label:"Keep it"})})]})]}):null]})}const ww=[["m","minutes"],["h","hours"],["d","days"]];function P1(e,t){const n=S=>{const N=e.elements.namedItem(S);return N&&typeof N.value=="string"?N.value:null},r=n("every_amount"),o=n("every_unit"),l=r!==null&&o!==null?`${r.trim()}${o}`:t.every,c=e.elements.namedItem("context"),u=c&&(c.value==="growing"||c.value==="independent")?c.value:t.context,f=n("prompt"),h=e.elements.namedItem("tool_approval"),m=h&&(h.value==="auto"||h.value==="ask")?h.value:t.toolApproval??null,g=e.elements.namedItem("notify_email"),y=g&&typeof g.checked=="boolean"?g.checked:t.notifyEmail??null,w=e.elements.namedItem("email_recipients"),k=n("email_recipient_list"),b=w&&(w.value==="self"||w.value==="list")?{mode:w.value,addresses:k??""}:t.emailRecipients??null;return{title:n("title")??t.title,every:l,context:u,growingMaxTokens:n("growing_max_tokens")===null?t.growingMaxTokens:Number(n("growing_max_tokens")),prompt:f??t.prompt??null,toolApproval:m,notifyEmail:y,emailRecipients:b}}function D1(e){const t=hb(e.summary,e.definition),[n,r]=_.useState(),[o,l]=_.useState(t.tools??null),[c,u]=_.useState(t.context),[f,h]=_.useState(!!t.notifyEmail),m=t.every?Jf(t.every):null,g=m&&m.unit==="s"?[["s","seconds"],...ww]:ww,y=`af-auto-revise-${e.summary.automation_id}`,w=m_(e.emailStatus),k=h_(e.summary.trigger);return s.jsxs("form",{className:"af-auto__revise","aria-labelledby":`${y}-heading`,onSubmit:b=>{b.preventDefault(),e.onSubmit({...P1(b.currentTarget,t),...n?{target:n}:{},...e.availableTools!==void 0?{tools:o}:{}})},onKeyDown:b=>{b.key==="Escape"&&e.onCancel&&(b.preventDefault(),e.onCancel())},children:[e.heading===null?s.jsx("span",{id:`${y}-heading`,hidden:!0,children:"Edit automation"}):s.jsxs("h3",{className:"af-auto__form-title",id:`${y}-heading`,children:[s.jsx(Be,{name:"edit",size:14})," ",e.heading??"Edit automation"]}),e.definition&&e.workflowPickerOptions?s.jsx(j1,{target:n||e.definition.target,options:e.workflowPickerOptions,onChange:r}):null,s.jsxs("label",{className:"af-auto__field",htmlFor:`${y}-title`,children:[s.jsx("span",{children:"Title"}),s.jsx("input",{id:`${y}-title`,name:"title",defaultValue:t.title,maxLength:120,required:!0})]}),t.prompt!==null&&t.prompt!==void 0?s.jsxs("label",{className:"af-auto__field",htmlFor:`${y}-prompt`,children:[s.jsx("span",{children:"Task"}),s.jsx("textarea",{id:`${y}-prompt`,name:"prompt",defaultValue:t.prompt,rows:Math.min(10,Math.max(3,t.prompt.split(`
|
|
60
|
-
`).length+1)),required:!0})]}):null,m?s.jsxs("fieldset",{className:"af-auto__field",children:[s.jsx("legend",{children:k?qt.every_label:"Repeat every (UTC)"}),s.jsxs("div",{className:"af-auto__row",children:[s.jsx("input",{name:"every_amount",type:"number",min:1,step:1,defaultValue:m.amount,"aria-label":"Interval amount"}),s.jsx("select",{name:"every_unit",defaultValue:m.unit,"aria-label":"Interval unit",children:g.map(([b,S])=>s.jsx("option",{value:b,children:S},b))})]}),k?s.jsx("p",{className:"af-auto__hint","data-email-rule":"interval",children:qt.interval_rule}):null]}):s.jsx("p",{className:"af-auto__hint",children:"This trigger has no interval to change."}),s.jsxs("fieldset",{className:"af-auto__field",children:[s.jsx("legend",{children:"Context"}),s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:"context",value:"independent",defaultChecked:t.context==="independent",onChange:()=>u("independent")})," Independent — each run starts fresh"]}),s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:"context",value:"growing",defaultChecked:t.context==="growing",onChange:()=>u("growing")})," Growing — each run sees the previous runs"]}),s.jsx("div",{hidden:c!=="growing",children:s.jsxs("label",{className:"af-auto__field",children:[s.jsx("span",{children:"Max growing context (tokens)"}),s.jsx("input",{name:"growing_max_tokens",type:"number",min:1,step:1,disabled:e.busy||c!=="growing",defaultValue:t.growingMaxTokens}),s.jsx("span",{className:"af-auto__hint",children:JN})]})})]}),t.toolApproval?s.jsxs("fieldset",{className:"af-auto__field",children:[s.jsx("legend",{children:"Tools"}),e.availableTools!==void 0?s.jsx(yb,{availableTools:e.availableTools,value:o,onChange:l,disabled:e.busy}):null,s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:"tool_approval",value:"auto",defaultChecked:t.toolApproval==="auto"})," Run without asking"]}),s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:"tool_approval",value:"ask",defaultChecked:t.toolApproval==="ask"})," Ask before each tool call"]})]}):null,t.notifyEmail!==null&&t.notifyEmail!==void 0&&t.emailRecipients?s.jsxs("fieldset",{className:"af-auto__field","data-field":"email",children:[s.jsx("legend",{children:"Mailbox"}),w?null:s.jsx(og,{status:e.emailStatus,onOpenMyEmail:e.onOpenMyEmail}),s.jsx(vS,{variant:"row",action:"notify-email",name:"notify_email",label:qt.notify_label,defaultChecked:!!t.notifyEmail,onChange:h,unavailableReason:!w&&!t.notifyEmail?"Connect a mailbox first.":null}),s.jsxs("p",{className:"af-auto__hint",children:[qt.notify_hint," Turn on Email result to choose yourself or other email addresses."]}),s.jsx("div",{hidden:!f,children:s.jsxs("fieldset",{className:"af-auto__field",disabled:!f,"data-field":"email-recipients",children:[s.jsx("legend",{children:qt.recipients_legend}),s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:"email_recipients",value:"self",defaultChecked:t.emailRecipients.mode==="self"})," ",qt.recipients_self]}),s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:"email_recipients",value:"list",defaultChecked:t.emailRecipients.mode==="list",disabled:!w&&t.emailRecipients.mode!=="list"})," ",qt.recipients_list]}),s.jsx("textarea",{name:"email_recipient_list","aria-label":qt.recipients_list,rows:2,spellCheck:!1,defaultValue:t.emailRecipients.addresses,disabled:!w&&t.emailRecipients.mode!=="list"}),s.jsx("p",{className:"af-auto__hint",children:qt.recipients_hint})]})})]}):null,s.jsx("p",{className:"af-auto__hint",children:"Changes apply from the next run; a new interval never fires past ticks."}),e.errors.length?s.jsx("ul",{className:"af-auto__form-errors",role:"alert",children:e.errors.map(b=>s.jsx("li",{children:b},b))}):null,s.jsxs("div",{className:"af-auto__row",children:[s.jsx("button",{type:"submit",className:"af-auto__btn af-auto__btn--primary","data-action":"edit-save",disabled:e.busy,children:s.jsx(fr,{icon:"check",label:e.submitLabel??"Save changes"})}),e.onCancel?s.jsx("button",{type:"button",className:"af-auto__btn","data-action":"edit-cancel",onClick:e.onCancel,children:s.jsx(fr,{icon:"x",label:"Cancel"})}):null]})]})}function cg(e,t){const n=e.elements.namedItem(t);return n&&typeof n.value=="string"?n.value.trim():""}function F1(e){const t=e.wait,n=`${e.idBase}-${t.run_id}-${t.wait_key}-prompt`,r=c=>e.onAnswerWait(t.run_id,t.wait_key,c),o=e.renderText??__,l=c=>s.jsxs("div",{className:"af-auto-wait__prompt",id:n,children:[s.jsx("span",{className:"af-auto-wait__kind",children:gb[t.kind]??"Waiting"}),t.prompt?o(t.prompt):s.jsxs("span",{children:[" ",c]})]});if(t.kind==="tool_approval"){const c=t1(t);return s.jsxs("div",{className:"af-auto-wait af-auto-wait--tool_approval",role:"group","data-wait-key":t.wait_key,"data-wait-kind":t.kind,"aria-labelledby":n,children:[l("A tool call needs your approval."),c&&c.length?s.jsx("ul",{className:"af-auto-wait__calls","aria-label":"Tool calls to approve",children:c.map((u,f)=>s.jsxs("li",{"data-tool":u.name,children:[s.jsx("code",{className:"af-auto-wait__tool",children:u.name}),s.jsx("pre",{className:"af-auto-wait__args",children:JSON.stringify(u.arguments,null,2)})]},u.call_id??`${u.name}:${f}`))}):s.jsx("p",{className:"af-auto__hint",children:"The gateway did not list the tool calls; open the run to see them before approving."}),s.jsxs("div",{className:"af-auto__row",children:[s.jsx("button",{type:"button",className:"af-auto__btn af-auto__btn--primary","data-action":"wait-approve",disabled:e.busy,onClick:()=>r({approved:!0}),children:s.jsx(fr,{icon:"check",label:"Approve"})}),s.jsx("button",{type:"button",className:"af-auto__btn af-auto__btn--danger","data-action":"wait-deny",disabled:e.busy,onClick:()=>r({approved:!1}),children:s.jsx(fr,{icon:"x",label:"Deny"})})]})]})}return t.kind==="event"?s.jsxs("form",{className:"af-auto-wait af-auto-wait--event","data-wait-key":t.wait_key,"data-wait-kind":t.kind,"aria-labelledby":n,onSubmit:c=>{var f;c.preventDefault();const u=n1(cg(c.currentTarget,"payload"));u.ok?r({payload:u.payload}):(f=e.onWaitError)==null||f.call(e,u.error)},children:[l("The run waits for an event."),s.jsx("textarea",{name:"payload",rows:3,"aria-label":"Event payload (JSON)",placeholder:'{"key": "value"}',disabled:e.busy}),s.jsx("div",{className:"af-auto__row",children:s.jsx("button",{type:"submit",className:"af-auto__btn af-auto__btn--primary","data-action":"wait-send-event",disabled:e.busy,children:s.jsx(fr,{icon:"send",label:"Send event"})})})]}):t.kind==="ask_user"?s.jsxs("form",{className:"af-auto-wait af-auto-wait--ask_user","data-wait-key":t.wait_key,"data-wait-kind":t.kind,"aria-labelledby":n,onSubmit:c=>{c.preventDefault();const u=cg(c.currentTarget,"response");u&&r({response:u})},children:[l("The run is waiting for your input."),t.choices&&t.choices.length?s.jsx("div",{className:"af-auto__row",role:"group","aria-label":"Choices",children:t.choices.map(c=>s.jsx("button",{type:"button",className:"af-auto__btn","data-action":"wait-choice",disabled:e.busy,onClick:()=>r({response:c}),children:c},c))}):null,s.jsxs("div",{className:"af-auto__row",children:[s.jsx("input",{name:"response","aria-label":"Your answer",placeholder:"Your answer",disabled:e.busy}),s.jsx("button",{type:"submit",className:"af-auto__btn af-auto__btn--primary","data-action":"wait-answer",disabled:e.busy,children:s.jsx(fr,{icon:"send",label:"Answer"})})]})]}):s.jsxs("div",{className:"af-auto-wait",role:"group","data-wait-key":t.wait_key,"data-wait-kind":String(t.kind),"aria-labelledby":n,children:[l("The run is waiting."),s.jsxs("p",{className:"af-auto__hint",children:["This kind of wait (",String(t.kind),") cannot be answered here; open the run."]})]})}function z1(e){const{row:t,tone:n,badge:r,statusText:o}=e.view,l=`af-auto-occ-${t.run_id}`,c=e.renderText??__,u=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.",h=(y,w)=>e.renderTurn?e.renderTurn({kind:y,role:y==="trigger"?"user":"assistant",text:w,index:t.index,runId:t.run_id}):c(w),m=e.renderTurn?" af-auto-turn--card":"",g=n==="failed"?t.failure?"No answer.":"No answer: the run failed.":n==="waiting"?"Waiting for your answer.":n==="running"?"Running…":"No answer.";return s.jsxs("li",{className:`af-auto-occ af-auto-occ--${n}`,"data-index":t.index,"data-tone":n,"aria-labelledby":`${l}-h`,children:[s.jsxs("div",{className:`af-auto-turn af-auto-turn--trigger${m}`,"data-turn":"trigger",children:[s.jsxs("div",{className:"af-auto-turn__meta",id:`${l}-h`,children:[s.jsxs("span",{className:"af-auto-turn__index",children:["#",t.index]})," · ",t.trigger.summary," · fired ",ya(t.fired_at)]}),s.jsx("div",{className:"af-auto-turn__text",children:h("trigger",t.user_turn)})]}),s.jsxs("div",{className:`af-auto-turn af-auto-turn--answer${m}`,"data-turn":"answer",children:[s.jsxs("div",{className:"af-auto-turn__meta",children:[r?s.jsx("span",{className:`af-auto-badge af-auto-badge--${n}`,children:r}):null,s.jsx("span",{className:"af-auto-turn__status",children:o}),t.finished_at?s.jsxs("span",{children:[" · ",ya(t.finished_at)]}):null]}),t.notify?s.jsxs("div",{className:"af-auto-notify","data-notify":"true",children:[s.jsx("strong",{children:t.notify.title}),t.notify.body?s.jsx("div",{className:"af-auto-notify__body",children:c(t.notify.body)}):null]}):null,t.failure?s.jsxs("div",{className:"af-auto-failure","data-failure":t.failure.reason_code,children:[s.jsx("strong",{children:t.failure.reason_code}),": ",t.failure.message," ",s.jsxs("span",{className:"af-auto-turn__muted",children:["(after ",t.failure.attempts," ",t.failure.attempts===1?"attempt":"attempts",")"]})]}):null,t.answer?s.jsx("div",{className:"af-auto-turn__text",children:h("answer",t.answer)}):s.jsx("div",{className:"af-auto-turn__empty",children:g}),t.artifacts.length?s.jsx("ul",{className:"af-auto-artifacts","aria-label":"Artifacts",children:t.artifacts.map(y=>s.jsxs("li",{children:[e.onOpenResource?s.jsxs("button",{type:"button",className:"af-auto__linkbtn","data-action":"open-artifact",onClick:()=>{var w;return(w=e.onOpenResource)==null?void 0:w.call(e,{kind:"artifact",url:y.url,name:y.name,mimeType:y.mime_type,runId:t.run_id})},children:[s.jsx(Be,{name:"file",size:13,className:"af-auto__btn-icon"})," ",y.name]}):s.jsx("span",{className:"af-auto-artifact__name",children:y.name})," ",s.jsx("span",{className:"af-auto-turn__muted",children:y.mime_type})]},y.artifact_id))}):null,t.waits.map(y=>s.jsx(F1,{wait:y,busy:e.busy,idBase:l,onAnswerWait:e.onAnswerWait,onWaitError:e.onWaitError,renderText:e.renderText},`${y.run_id}:${y.wait_key}`))]}),s.jsxs("div",{className:"af-auto-occ__foot",children:[s.jsxs("details",{className:"af-auto-occ__details",children:[s.jsx("summary",{children:"Run details"}),s.jsxs("dl",{className:"af-auto__facts",children:[s.jsx("dt",{children:"Run"}),s.jsx("dd",{children:s.jsx("code",{children:t.run_id})}),s.jsx("dt",{children:"Attempts"}),s.jsx("dd",{children:t.attempts})]}),s.jsxs("div",{className:"af-auto__row",children:[s.jsx("button",{type:"button",className:"af-auto__btn","data-action":"open-run",onClick:()=>e.onOpenRun(t.run_id),children:s.jsx(fr,{icon:"list",label:"Open run ledger"})}),e.onOpenResource?s.jsx("button",{type:"button",className:"af-auto__btn","data-action":"open-ledger-json",onClick:()=>{var y;return(y=e.onOpenResource)==null?void 0:y.call(e,{kind:"ledger",url:t.ledger_url,name:`run-${t.run_id}-ledger.json`,runId:t.run_id})},children:s.jsx(fr,{icon:"file",label:"Ledger (JSON)"})}):null,t.workspace_url&&e.onOpenWorkspace?s.jsx("button",{type:"button",className:"af-auto__btn","data-action":"open-workspace",title:"Browse this run's folder",onClick:()=>{var y;return(y=e.onOpenWorkspace)==null?void 0:y.call(e,t.run_id)},children:s.jsx(fr,{icon:"folder",label:"Workspace"})}):null]})]}),e.discussOpen?s.jsxs("form",{className:"af-auto-discuss","aria-label":`${ag}, from occurrence ${t.index}`,onSubmit:y=>{y.preventDefault();const w=cg(y.currentTarget,"prompt");w&&e.onDiscussSubmit(t.index,w)},children:[s.jsxs("p",{className:"af-auto__hint",children:["Starts a new session that forks this automation at #",t.index," with its full history (runs 1–",t.index,"). It works in its own writable workspace; the automation's files are mounted read-only for the file tools (shell commands are not sandboxed), and nothing is written back into the automation's session."]}),s.jsx("textarea",{name:"prompt",rows:3,"aria-label":"Your message",placeholder:"Ask about this result…",required:!0}),s.jsxs("div",{className:"af-auto__row",children:[s.jsx("button",{type:"submit",className:"af-auto__btn af-auto__btn--primary","data-action":"discuss-submit",disabled:e.busy,children:s.jsx(fr,{icon:"send",label:"Start discussion"})}),s.jsx("button",{type:"button",className:"af-auto__btn","data-action":"discuss-cancel",onClick:e.onDiscussCancel,children:s.jsx(fr,{icon:"x",label:"Cancel"})})]})]}):s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"af-auto__btn af-auto__btn--quiet","data-action":"discuss",disabled:!u,title:lg.discuss,"aria-description":lg.discuss,"aria-describedby":f?`${l}-discuss-why`:void 0,onClick:()=>e.onDiscussOpen(t.index),children:s.jsx(fr,{icon:Vi.discuss,label:ag})}),f?s.jsx("span",{className:"af-auto__reasons",id:`${l}-discuss-why`,children:f}):null]})]})]})}const B1=5e3,U1={[xi.pause]:"Automation paused.",[xi.resume]:"Automation active.",[xi.run_now]:"Run requested.",[xi.stop_current]:"Stop requested.",[xi.unarchive]:"Unarchived: it is paused until you make it active."};function W1(e){var ae;const{summary:t,busy:n}=e,r=e.renderText??__,o=_.useId(),l=_.useRef(null),[c,u]=_.useState(!1),f=e.editOpen!==void 0,m=Wm(t,e.occurrences,!1).revise.enabled&&(f?e.editOpen===!0:c),g=_.useRef(null);m?(!g.current||g.current.summary.automation_id!==t.automation_id)&&(g.current={summary:t,definition:e.definition}):g.current=null;const y=g.current,w=_.useRef(e.onEditOpenChange);w.current=e.onEditOpenChange;const k=ie=>{var _e;f||u(ie),(_e=w.current)==null||_e.call(w,ie)},[b,S]=_.useState([]),[N,R]=_.useState(!1),[T,A]=_.useState(null),[W,z]=_.useState(null),[J,K]=_.useState(null);_.useEffect(()=>{if(!J)return;const ie=setTimeout(()=>K(null),B1);return()=>clearTimeout(ie)},[J]),_.useEffect(()=>{var _e;if(!m)return;S([]);const ie=pw(l.current,['.af-auto__revise [name="title"]']);ie==null||ie.focus(),(_e=ie==null?void 0:ie.scrollIntoView)==null||_e.call(ie,{block:"nearest"})},[m,t.automation_id]);const[re,te]=_.useState(null);_.useEffect(()=>{var ie;re&&((ie=pw(l.current,[...re,".af-auto__notice",".af-auto__title"]))==null||ie.focus(),te(null))},[re]);const Q=_.useRef(null);Q.current||(Q.current=new s1(e.newId??i1));const D=Q.current,$=ie=>z($1(ie)),E=(ie,_e,fe)=>{z(null),K(null),_e(D.idFor(ie)).then(ge=>{D.settle(ie,{ok:!0}),fe(ge)},ge=>{D.settle(ie,{ok:!1,error:ge}),$(ge)})},L=GN(t),M=_.useRef(e.onSeen);M.current=e.onSeen;const ee=_.useRef(null);ee.current||(ee.current=new o1),_.useEffect(()=>{const ie=ee.current,_e=L?`${t.automation_id}|${L}`:null;if(!L||!ie.next(_e,t))return;const fe=t;M.current(L).then(()=>ie.succeeded(_e),ge=>{ie.failed(_e,fe),$(ge)})});const F=Wm(t,e.occurrences,n),U=VN(e.occurrences),V=t.occurrence_count-e.occurrences.length,O=W??e.error??null,H=O?qm(O):null,Y=t.attention;return s.jsxs("section",{ref:l,className:`af-auto${e.className?` ${e.className}`:""}`,...e.hideHeader?{"aria-label":t.title}:{"aria-labelledby":o},"aria-busy":n,"data-text-rendering":e.renderText?"rich":"unformatted",children:[e.hideHeader?null:s.jsxs(s.Fragment,{children:[s.jsx(T1,{summary:t,workflowLabel:(ae=e.definition)==null?void 0:ae.target.workflow_id,triggerSources:e.triggerSources,titleId:o,nowMs:e.nowMs,onOpenWorkspace:e.onOpenWorkspace}),s.jsx(O1,{summary:t,occurrences:e.occurrences,busy:n,confirmingArchive:N,reviseOpen:m,notice:J,onDismissNotice:()=>K(null),idBase:`${o}-ctl`,onCommand:ie=>E(`command:${ie}`,_e=>e.onCommand(ie,void 0,{command_id:_e}),()=>{ie===xi.archive?(R(!1),K("Archive requested."),te(['[data-action="archive"]'])):K(U1[ie]??"Command sent.")}),onToggleRevise:()=>{S([]),k(!m)},onAskArchive:()=>R(!0),onCancelArchive:()=>{R(!1),te(['[data-action="archive"]'])}})]}),m&&y?s.jsx(D1,{summary:y.summary,definition:y.definition,busy:n,errors:b,availableTools:e.availableTools,workflowPickerOptions:e.workflowPickerOptions,emailStatus:e.emailStatus,onOpenMyEmail:e.onOpenMyEmail,onCancel:()=>{k(!1),te(['[data-action="edit"]'])},onSubmit:ie=>{const _e=y.summary,fe=YN(_e,ie,y.definition);if(fe===null){S(["Nothing changed."]);return}if("errors"in fe){S(fe.errors);return}S([]),E(`revise:${_e.revision}:${JSON.stringify(fe)}`,async ge=>{const Ne=ie.target&&fe.target?{...fe,target:await(e.prepareTarget?e.prepareTarget(fe.target):S1(fe.target,e.workflowPickerOptions))}:fe;return e.onRevise(Ne,_e.revision,{command_id:ge})},()=>{K("Saved; applies from the next run."),k(!1),te(['[data-action="edit"]'])})}}):e.definition?s.jsx(M1,{definition:e.definition,renderText:r}):null,H?s.jsxs("div",{className:"af-auto__error",role:"alert","data-code":O==null?void 0:O.code,children:[s.jsx(Be,{name:"error",size:14,className:"af-auto__btn-icon"}),s.jsxs("span",{className:"af-auto__error-text",children:[s.jsx("strong",{children:H.title})," ",s.jsx("span",{children:H.detail})]}),W?s.jsx("button",{type:"button",className:"af-auto__icon-btn af-auto__icon-btn--bare","data-action":"dismiss-error","aria-label":"Dismiss",title:"Dismiss",onClick:()=>z(null),children:s.jsx(Be,{name:"x",size:12})}):null]}):null,Y.items.length||Y.waits.length?s.jsx("section",{className:"af-auto__attention","aria-label":"Needs attention",children:s.jsxs("ul",{children:[Y.items.map(ie=>s.jsxs("li",{className:`af-auto__attention-item af-auto__attention-item--${ie.kind}`,"data-cursor":ie.cursor,children:[s.jsx("span",{className:`af-auto-badge af-auto-badge--${ie.kind==="failure"?"failed":"notified"}`,children:ie.kind==="failure"?"Failed":"Notified"})," ",s.jsx("strong",{children:ie.title})," ",s.jsxs("span",{className:"af-auto-turn__muted",children:["#",ie.index," · ",ya(ie.at)]}),ie.body?s.jsx("div",{className:"af-auto__attention-body",children:r(ie.body)}):null]},ie.cursor)),Y.waits.map(ie=>s.jsxs("li",{className:"af-auto__attention-item af-auto__attention-item--wait",children:[s.jsx("span",{className:"af-auto-badge af-auto-badge--waiting","data-wait-kind":ie.kind,children:gb[ie.kind]??"Waiting for you"})," ",s.jsxs("span",{className:"af-auto-turn__muted",children:["#",ie.index]}),ie.prompt?s.jsx("div",{className:"af-auto__attention-body",children:r(ie.prompt)}):null]},`${ie.run_id}:${ie.wait_key}`))]})}):null,V>0?s.jsx("button",{type:"button",className:"af-auto__btn af-auto__more","data-action":"load-more",disabled:n,onClick:e.onLoadMore,children:s.jsx(fr,{icon:"history",label:`Load earlier occurrences (${V} more)`})}):null,U.length?s.jsx("ol",{className:"af-auto__timeline","aria-label":"Occurrences",children:U.map(ie=>{const _e=`[data-index="${ie.row.index}"]`;return s.jsx(z1,{view:ie,busy:n,discuss:F.discuss,renderText:r,renderTurn:e.renderTurn,onOpenWorkspace:e.onOpenWorkspace,onOpenResource:e.onOpenResource?fe=>{var ge;z(null);try{Promise.resolve((ge=e.onOpenResource)==null?void 0:ge.call(e,fe)).catch($)}catch(Ne){$(Ne)}}:void 0,discussOpen:T===ie.row.index,onOpenRun:e.onOpenRun,onAnswerWait:(fe,ge,Ne)=>{z(null),e.onAnswerWait(fe,ge,Ne).then(()=>K("Answer sent."),$)},onWaitError:fe=>z({status:0,code:"invalid_payload",message:fe}),onDiscussOpen:A,onDiscussCancel:()=>{A(null),te([`${_e} [data-action="discuss"]`])},onDiscussSubmit:(fe,ge)=>E(`discuss:${fe}:${ge}`,Ne=>e.onDiscuss(fe,ge,{request_id:Ne}),Ne=>{A(null),K(`Discussion started (session ${Ne.session_id}).`),te([`${_e} [data-action="discuss"]`])})},ie.row.run_id)})}):s.jsx("p",{className:"af-auto__empty",children:"No occurrences yet."})]})}const Nb=72;function q1(e,t=Nb){const n=Math.max(1,Math.floor(t)),r=new Array(n).fill(0),o=e.length;if(!o)return r;const l=o/n;let c=0;for(let u=0;u<n;u+=1){const f=Math.floor(u*l),h=Math.max(f+1,Math.floor((u+1)*l));let m=0;for(let g=f;g<h&&g<o;g+=1){const y=Math.abs(Number(e[g])||0);y>m&&(m=y)}r[u]=m,m>c&&(c=m)}return c<=0?r:r.map(u=>u/c)}function cm(e){if(typeof e!="number"||!Number.isFinite(e)||e<0)return"--:--";const t=Math.floor(e),n=Math.floor(t/3600),r=Math.floor(t%3600/60),o=String(t%60).padStart(2,"0");return n>0?`${n}:${String(r).padStart(2,"0")}:${o}`:`${r}:${o}`}function H1(e,t,n){return!(t>0)||!(n>0)?0:Math.min(n,Math.max(0,e/t*n))}function V1(e,t){const[n,r]=_.useState({peaks:t??null,note:""});return _.useEffect(()=>{if(t){r({peaks:t,note:""});return}let o=!0;r({peaks:null,note:""});const l=typeof window<"u"?window.AudioContext||window.webkitAudioContext:void 0;if(!e||!l||typeof fetch!="function"){r({peaks:null,note:"Waveform unavailable in this browser."});return}return(async()=>{let c=null;try{const u=await(await fetch(e)).arrayBuffer();c=new l;const f=await c.decodeAudioData(u);o&&r({peaks:q1(f.getChannelData(0)),note:""})}catch(u){o&&r({peaks:null,note:`Waveform unavailable: ${u instanceof Error?u.message:String(u)}`})}finally{c&&c.close().catch(()=>{})}})(),()=>{o=!1}},[e,t]),n}function p_(e){const t=_.useRef(null),n=_.useRef(null),[r,o]=_.useState(!1),[l,c]=_.useState(0),[u,f]=_.useState(null),[h,m]=_.useState(""),{peaks:g,note:y}=V1(e.src,e.peaks),w=g??new Array(Nb).fill(0),k=u&&u>0?Math.min(1,l/u):0,b=e.name?`Audio ${e.name}`:"Audio",S=_.useCallback(()=>{const A=t.current;A&&(A.paused?A.play().catch(W=>m(W instanceof Error?W.message:String(W))):A.pause())},[]),N=_.useCallback(A=>{const W=t.current;!W||!Number.isFinite(A)||(W.currentTime=A,c(A))},[]),R=A=>{var z;const W=(z=n.current)==null?void 0:z.getBoundingClientRect();!W||!u||N(H1(A-W.left,W.width,u))},T=A=>{if(!u)return;const W=A.key==="ArrowRight"||A.key==="ArrowUp"?5:A.key==="ArrowLeft"||A.key==="ArrowDown"?-5:0;W?(A.preventDefault(),N(Math.min(u,Math.max(0,l+W)))):A.key==="Home"?(A.preventDefault(),N(0)):A.key==="End"?(A.preventDefault(),N(u)):(A.key===" "||A.key==="Enter")&&(A.preventDefault(),S())};return s.jsxs("div",{className:`af-audio${e.className?` ${e.className}`:""}`,"data-playing":r?"true":"false",children:[s.jsx("audio",{ref:t,src:e.src,preload:"metadata",onPlay:()=>o(!0),onPause:()=>o(!1),onEnded:()=>o(!1),onTimeUpdate:A=>c(A.currentTarget.currentTime),onLoadedMetadata:A=>f(Number.isFinite(A.currentTarget.duration)?A.currentTarget.duration:null),onDurationChange:A=>f(Number.isFinite(A.currentTarget.duration)?A.currentTarget.duration:null),onError:()=>m("This audio cannot be played in this browser. Use Download to open it.")}),s.jsx("button",{type:"button",className:"af-audio__play","data-action":r?"pause-audio":"play-audio","aria-label":r?`Pause ${b}`:`Play ${b}`,title:r?"Pause":"Play",onClick:S,children:s.jsx(Be,{name:r?"pause":"play",size:16})}),s.jsx("div",{ref:n,className:"af-audio__wave",role:"slider",tabIndex:0,"aria-label":`Seek in ${b}`,"aria-valuemin":0,"aria-valuemax":Math.round(u??0),"aria-valuenow":Math.round(l),"aria-valuetext":`${cm(l)} of ${cm(u)}`,title:y||void 0,"data-waveform":g?"decoded":"flat",onKeyDown:T,onPointerDown:A=>{var W,z;(z=(W=A.currentTarget).setPointerCapture)==null||z.call(W,A.pointerId),R(A.clientX)},onPointerMove:A=>{A.buttons&1&&R(A.clientX)},children:s.jsx("svg",{viewBox:`0 0 ${w.length*2} 32`,preserveAspectRatio:"none","aria-hidden":"true",focusable:"false",children:w.map((A,W)=>{const z=Math.max(1.5,A*30),J=(W+.5)/w.length<=k;return s.jsx("rect",{className:J?"af-audio__bar af-audio__bar--played":"af-audio__bar",x:W*2+.3,y:16-z/2,width:1.4,height:z,rx:.6},W)})})}),s.jsxs("span",{className:"af-audio__time","aria-hidden":"true",children:[cm(l)," / ",cm(u)]}),h?s.jsx("p",{className:"af-audio__error",role:"alert",children:h}):null]})}const wc=e=>new Set(e.split(/\s+/).filter(Boolean)),G1=wc("if else for while do switch case default break continue return function const let var class extends new this super import export from as async await try catch finally throw typeof instanceof in of void delete yield static public private protected interface type enum implements package struct fn impl trait pub use mod mut match loop where crate self Self func go defer chan map range select int long short char float double bool boolean string true false null nil undefined None True False namespace using template typename virtual override final abstract sealed record val object fun when is"),K1=wc("def class return if elif else for while in not and or is import from as with try except finally raise pass break continue lambda yield global nonlocal assert del async await None True False self match case"),Y1=wc("if then else elif fi for while do done case esac in function return export local readonly set unset echo exit source"),J1=wc("select from where insert into values update set delete create table index view drop alter add join left right inner outer on group by order having limit offset as and or not null is in like between union all distinct primary key foreign references default"),vw=wc("true false null yes no on off"),X1={c:{line:["//"],block:["/*","*/"],strings:['"',"'","`"],keywords:G1},python:{line:["#"],strings:['"',"'"],triple:!0,keywords:K1},shell:{line:["#"],strings:['"',"'"],keywords:Y1},sql:{line:["--"],block:["/*","*/"],strings:["'",'"'],keywords:J1},data:{line:["#"],strings:['"',"'"],keywords:vw},json:{line:[],strings:['"'],keywords:vw},css:{line:[],block:["/*","*/"],strings:['"',"'"],keywords:wc("")},markup:{line:[],block:["<!--","-->"],strings:['"',"'"],keywords:wc("")}},Z1={js:"c",mjs:"c",cjs:"c",jsx:"c",ts:"c",tsx:"c",java:"c",kt:"c",c:"c",h:"c",cc:"c",cpp:"c",hpp:"c",cs:"c",go:"c",rs:"c",swift:"c",scala:"c",dart:"c",php:"c",py:"python",pyi:"python",rb:"shell",sh:"shell",bash:"shell",zsh:"shell",fish:"shell",ps1:"shell",sql:"sql",yaml:"data",yml:"data",toml:"data",ini:"data",cfg:"data",conf:"data",env:"data",json:"json",jsonl:"json",css:"css",scss:"css",less:"css",html:"markup",htm:"markup",xml:"markup",svg:"markup",vue:"markup",javascript:"c",typescript:"c",rust:"c",python:"python",shell:"shell"};function ey(e){const t=String(e||"").trim().toLowerCase(),n=t.split("/").pop()||t;if(n==="dockerfile"||n==="makefile")return"shell";const r=n.lastIndexOf("."),o=r>=0?n.slice(r+1):n;return Z1[o]||""}const Q1=e=>e>="0"&&e<="9",e2=e=>/[A-Za-z_$]/.test(e),xw=e=>/[A-Za-z0-9_$]/.test(e);function Cb(e,t){const n=String(e??""),r=X1[t];if(!r)return n?[{kind:"plain",text:n}]:[];const o=[];let l="";const c=(f,h)=>{if(h){if(f==="plain"){l+=h;return}l&&o.push({kind:"plain",text:l}),l="",o.push({kind:f,text:h})}};let u=0;for(;u<n.length;){const f=n[u];if(r.line.find(m=>n.startsWith(m,u))){const m=n.indexOf(`
|
|
61
|
-
`,u),g=m===-1?n.length:m;c("comment",n.slice(u,g)),u=g;continue}if(r.block&&n.startsWith(r.block[0],u)){const m=n.indexOf(r.block[1],u+r.block[0].length),g=m===-1?n.length:m+r.block[1].length;c("comment",n.slice(u,g)),u=g;continue}if(r.strings.includes(f)){const m=r.triple&&n.startsWith(f.repeat(3),u)?f.repeat(3):"";if(m){const w=n.indexOf(m,u+3),k=w===-1?n.length:w+3;c("string",n.slice(u,k)),u=k;continue}let g=u+1;for(;g<n.length&&n[g]!==f&&(f==="`"||n[g]!==`
|
|
62
|
-
`);)g+=n[g]==="\\"?2:1;const y=Math.min(n.length,g+1);c("string",n.slice(u,y)),u=y;continue}if(Q1(f)&&!(u>0&&xw(n[u-1]))){let m=u+1;for(;m<n.length&&/[0-9a-fA-FxXoObB._]/.test(n[m]);)m+=1;c("number",n.slice(u,m)),u=m;continue}if(e2(f)){let m=u+1;for(;m<n.length&&xw(n[m]);)m+=1;const g=n.slice(u,m),y=t==="sql"?r.keywords.has(g.toLowerCase()):r.keywords.has(g);c(y?"keyword":"plain",g),u=m;continue}c("plain",f),u+=1}return l&&o.push({kind:"plain",text:l}),o}function um({text:e,language:t="",lineNumbers:n=!0,className:r,ariaLabel:o}){const l=ey(t),c=Cb(e,l),u=n?String(e??"").split(`
|
|
63
|
-
`).length:0;return s.jsx("pre",{className:`af-code${n?" af-code--numbered":""}${r?` ${r}`:""}`,"data-language":l||"text","aria-label":o,style:n?{"--af-code-gutter":`${String(u).length+1}ch`}:void 0,children:s.jsx("code",{children:n?t2(c).map((f,h)=>s.jsxs("span",{className:"af-code__line","data-line":h+1,children:[f.map((m,g)=>bw(m,g)),`
|
|
64
|
-
`]},h)):c.map((f,h)=>bw(f,h))})})}function bw(e,t){return e.kind==="plain"?s.jsx(xe.Fragment,{children:e.text},t):s.jsx("span",{className:`af-code__${e.kind}`,children:e.text},t)}function t2(e){const t=[[]];for(const n of e)n.text.split(`
|
|
65
|
-
`).forEach((o,l)=>{l>0&&t.push([]),o&&t[t.length-1].push({kind:n.kind,text:o})});return t}const Eb=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],pf=6e4,gf=60*pf,dm=24*gf;function Zf(e){if(e==null||e==="")return NaN;if(e instanceof Date)return e.getTime();if(typeof e=="number")return Number.isFinite(e)?e<1e12?e*1e3:e:NaN;const t=String(e).trim();return/^\d+(\.\d+)?$/.test(t)?Zf(Number(t)):Date.parse(t)}function kw(e){return e<10?`0${e}`:String(e)}function jw(e,t){const n=Zf(e);if(!Number.isFinite(n))return"";const r=new Date(n),o=r.getFullYear()===new Date(t).getFullYear();return`${Eb[r.getMonth()]} ${r.getDate()}${o?"":`, ${r.getFullYear()}`}`}function $b(e){const t=Zf(e);if(!Number.isFinite(t))return"";const n=new Date(t);return`${Eb[n.getMonth()]} ${n.getDate()}, ${n.getFullYear()}, ${kw(n.getHours())}:${kw(n.getMinutes())}`}function Vm(e,t){const n=Zf(e);if(!Number.isFinite(n)||!Number.isFinite(t))return"";const r=t-n;if(r<0){const l=-r;if(l<pf)return"due now";if(l<gf)return`in ${Math.round(l/pf)} min`;if(l<dm)return`in ${Math.round(l/gf)} h`;const c=Math.round(l/dm);return c<7?`in ${c} ${c===1?"day":"days"}`:jw(n,t)}if(r<pf)return"just now";if(r<gf)return`${Math.floor(r/pf)} min ago`;if(r<dm)return`${Math.floor(r/gf)} h ago`;const o=Math.floor(r/dm);return o===1?"yesterday":o<7?`${o} days ago`:jw(n,t)}const n2=new Set("png jpg jpeg gif webp bmp ico avif".split(" ")),s2=new Set("mp3 wav ogg oga opus m4a aac flac weba".split(" ")),r2=new Set("txt log csv tsv rst adoc org tex diff patch lock".split(" "));function i2(e){const t=String(e||"").split("/").pop()||"",n=t.lastIndexOf(".");return n>0?t.slice(n+1).toLowerCase():t.toLowerCase()}function ug(e,t=""){const n=i2(e),r=String(t||"").split(";",1)[0].trim().toLowerCase();return n==="md"||n==="markdown"||r==="text/markdown"?"markdown":n==="json"||r==="application/json"||r.endsWith("+json")?"json":n==="pdf"||r==="application/pdf"?"pdf":n2.has(n)||r.startsWith("image/")&&r!=="image/svg+xml"?"image":s2.has(n)||r.startsWith("audio/")?"audio":ey(e)?"code":r2.has(n)||r.startsWith("text/")?"text":["application/javascript","application/xml","application/x-yaml","application/toml"].includes(r)?"code":"binary"}function Sw(e){return e==="markdown"||e==="code"||e==="json"||e==="text"}function ty(e){if(typeof e!="number"||!Number.isFinite(e)||e<0)return"";if(e<1024)return`${e} B`;const t=["KiB","MiB","GiB","TiB"];let n=e/1024,r=0;for(;n>=1024&&r<t.length-1;)n/=1024,r+=1;return`${n<10?n.toFixed(1):Math.round(n)} ${t[r]}`}function o2(e){const t=e.kind??ug(e.name,e.contentType),n=ty(e.sizeBytes),r=e.modified!==void 0?Vm(e.modified,e.nowMs):"";return s.jsxs("section",{className:`af-file-viewer${e.className?` ${e.className}`:""}`,"aria-label":`Preview of ${e.name}`,"data-kind":t,children:[s.jsxs("header",{className:"af-file-viewer__head",children:[s.jsx(Be,{name:"file",size:15}),s.jsxs("span",{className:"af-file-viewer__title",children:[s.jsx("strong",{className:"af-file-viewer__name",title:e.path||e.name,children:e.name}),n||r?s.jsxs("span",{className:"af-file-viewer__meta",children:[n?s.jsx("span",{"data-meta":"size",children:n}):null,n&&r?s.jsx("span",{"aria-hidden":"true",children:" · "}):null,r?s.jsx("time",{"data-meta":"modified",title:$b(e.modified),dateTime:new Date(Zf(e.modified)).toISOString(),children:r}):null]}):null]}),e.actions,e.onDownload?s.jsx("button",{type:"button",className:"af-file-viewer__icon-btn","data-action":"download-file",onClick:e.onDownload,title:"Download","aria-label":`Download ${e.name}`,children:s.jsx(Be,{name:"download",size:15})}):null,e.onClose?s.jsx("button",{type:"button",className:"af-file-viewer__icon-btn","data-action":"close-preview",onClick:e.onClose,title:"Close","aria-label":"Close the preview",children:s.jsx(Be,{name:"x",size:15})}):null]}),s.jsx("div",{className:"af-file-viewer__body",children:e.status==="loading"?s.jsx("p",{className:"af-file-viewer__muted",role:"status",children:"Loading preview…"}):e.status==="error"?s.jsx("p",{className:"af-file-viewer__error",role:"alert",children:e.error||"The preview could not be loaded."}):s.jsxs(s.Fragment,{children:[e.partialNote?s.jsx("p",{className:"af-file-viewer__muted",role:"status",children:e.partialNote}):null,s.jsx(a2,{kind:t,p:e})]})})]})}function a2({kind:e,p:t}){const n=t.text??"";switch(e){case"image":return t.url?s.jsx("img",{className:"af-file-viewer__image",src:t.url,alt:t.name}):s.jsx(fm,{});case"audio":return t.url?s.jsx(p_,{src:t.url,name:t.name}):s.jsx(fm,{});case"pdf":return t.url?s.jsx("object",{className:"af-file-viewer__pdf",data:t.url,type:"application/pdf","aria-label":t.name,children:s.jsx("p",{className:"af-file-viewer__muted",children:"This browser cannot show PDFs inline. Use Download to open it."})}):s.jsx(fm,{});case"markdown":return t.renderMarkdown?s.jsx("div",{className:"af-file-viewer__markdown",children:t.renderMarkdown(n)}):s.jsx(um,{text:n,language:""});case"json":{let r=n,o="";try{r=JSON.stringify(JSON.parse(n),null,2)}catch{o=t.partialNote?"":"Not valid JSON; shown as text."}return s.jsxs(s.Fragment,{children:[o?s.jsx("p",{className:"af-file-viewer__muted",children:o}):null,s.jsx(um,{text:r,language:"json"})]})}case"code":return s.jsx(um,{text:n,language:t.name});case"text":return s.jsx(um,{text:n,language:"",lineNumbers:!1});default:return s.jsx(fm,{})}}function fm(){return s.jsx("p",{className:"af-file-viewer__muted",children:"No preview for this file type. Use Download to open it."})}function yf(e){const t=_.useId(),n=`${e.id||t}-title`;return s.jsxs("section",{className:`af-settings-group${e.variant==="flat"?" af-settings-group--flat":""}${e.className?` ${e.className}`:""}`,"aria-labelledby":n,id:e.id,children:[s.jsxs("div",{className:"af-settings-group__head",children:[s.jsx("h3",{className:"af-settings-group__title",id:n,children:e.title}),e.aside?s.jsx("span",{className:"af-settings-group__aside",children:e.aside}):null]}),e.help?s.jsx("p",{className:"af-settings-group__help",children:e.help}):null,s.jsx("div",{className:"af-settings-group__rows",children:e.children})]})}function oc(e){const t=e.htmlFor?"label":"span";return s.jsxs("div",{className:`af-setting-row${e.stack?" af-setting-row--stack":""}${e.className?` ${e.className}`:""}`,"data-setting":e.setting,children:[s.jsxs("div",{className:"af-setting-row__label",children:[s.jsx(t,{className:"af-setting-row__name",...e.htmlFor?{htmlFor:e.htmlFor}:{},children:e.label}),e.help?s.jsx("span",{className:"af-setting-row__help",children:e.help}):null]}),e.children!==void 0||e.trailing?s.jsxs("div",{className:"af-setting-row__control",children:[e.children,e.trailing?s.jsx("span",{className:"af-setting-row__trailing",children:e.trailing}):null]}):null]})}function Nw(e){const t=!!e.overrideSummary,n=_.useId(),r=t?`${e.overrideSummary}${e.overrideOwner?` — ${e.overrideOwner}`:""}`:`Gateway default${e.defaultSummary?` · ${e.defaultSummary}`:""}`;return s.jsxs("div",{className:"af-override","data-setting":e.setting,"data-overridden":t?"true":"false",children:[s.jsx(oc,{label:e.label,help:e.help,trailing:s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"af-setting-btn","data-action":"change","aria-expanded":e.open,"aria-controls":n,disabled:e.disabled,onClick:e.onToggle,children:e.open?"Done":"Change"}),t&&e.onReset?s.jsx("button",{type:"button",className:"af-setting-btn af-setting-btn--quiet","data-action":"use-default",disabled:e.disabled,onClick:e.onReset,children:"Use gateway default"}):null]}),children:s.jsx("span",{className:"af-override__summary",title:r,children:r})}),s.jsx("div",{className:"af-override__editor",id:n,hidden:!e.open,children:e.open?e.children:null})]})}const gn={title:"Workspaces",gatewayTitle:"Eligible workspaces",gatewayHelp:"The workspaces accounts may choose from, and the most each one allows.",accountHelp:"The workspaces this account's agents use, among the eligible ones.",sessionHelp:"The workspaces this conversation uses, among the eligible ones.",runHelp:"The workspaces this run uses, among the eligible ones.",gatewayPrefix:"Gateway:",postureLabel:"Workspaces agents may use",postureAllowedOnly:"Deny everything, allow listed workspaces",postureAllowedOnlyHelp:"Agents may only work in the listed workspaces.",postureAnyExceptDenied:"Allow everything, refuse listed workspaces",postureAnyExceptDeniedHelp:"Agents may work in any workspace except the refused ones.",accessLabel:"Permission",accessRead:"Read-only",accessReadWrite:"Read & write",accessDenied:"Refused",capReadOnly:"The gateway allows this workspace read-only",capRefused:"The gateway refuses this workspace",everythingElse:"Everything else",allowedTitle:"Allowed workspaces",deniedTitle:"Refused workspaces",builtinRefused:"Always refused: the gateway's own data and credentials",emptyAllowed:"No workspace is listed: agents only use their private workspace.",privateNote:"The private workspace of each run is always available, read & write.",addPlaceholder:"Add a workspace path",add:"Add",choose:"Choose…",remove:"Remove",followGateway:"Follow the gateway policy",followGatewayHelp:"On: this account gets exactly what the gateway allows.",useDefault:"Use my default",useDefaultHelp:"On: the account's default workspaces apply.",locked:"These workspaces can be seen here but not changed.",loading:"Loading…",saved:"Saved",notSaved:"Not saved."},$r=gn;function l2(e){return e==="any_except_denied"?$r.postureAnyExceptDenied:$r.postureAllowedOnly}function c2(e){return e==="any_except_denied"?$r.postureAnyExceptDeniedHelp:$r.postureAllowedOnlyHelp}function Cw(e){return e==="ro"?$r.accessRead:e==="deny"?$r.accessDenied:$r.accessReadWrite}function u2(e){return e==="gateway"?$r.gatewayHelp:e==="account"?$r.accountHelp:e==="session"?$r.sessionHelp:$r.runHelp}const Ew={deny:0,ro:1,rw:2},up=["rw","ro","deny"];function d2(e){if(e===null)return{allowed:[...up],reasons:{}};const t=e==="deny"?$r.capRefused:$r.capReadOnly,n=up.filter(o=>Ew[o]<=Ew[e]),r={};for(const o of up)n.includes(o)||(r[o]=t);return{allowed:n,reasons:r}}function f2(e,t){const{policy:n}=t,r=t.effective;if(e==="gateway"?typeof n.summary!="string":!r)throw new Error(e==="gateway"?"The gateway workspace policy has no summary line.":`A ${e}-level workspace chooser needs the gateway's effective workspaces.`);const o=e!=="gateway"&&n.configured===!1,l=t.can_edit===!1,c=new Map(((r==null?void 0:r.folders)??[]).map(w=>[w.path,w.cap])),u=r,f=o?u.folders.map(w=>({path:w.path,mode:w.mode})):n.folders,h=o?u.posture:n.posture,m=o?u.default_mode??n.default_mode:n.default_mode,g=!o&&!l,y=f.map(w=>{const k=e==="gateway"?null:c.get(w.path)??null,{allowed:b,reasons:S}=d2(k);return{path:w.path,mode:w.mode,cap:k,allowed:b,reasons:S,builtin:!1,editable:g}});if(e==="gateway")for(const w of n.builtin_refused??[])y.push({path:w,mode:"deny",cap:null,allowed:[],reasons:{},builtin:!0,editable:!1});return{level:e,posture:h,following:o,rows:y,everythingElse:h==="any_except_denied"?{mode:m,editable:g}:null,canAdd:g,gatewayLine:e==="gateway"?null:`${$r.gatewayPrefix} ${u.gateway_summary}`,summary:e==="gateway"?n.summary:u.summary,locked:l}}function h2(e,t){return t==="any_except_denied"?"deny":e==="gateway"?"rw":"ro"}function Qf(e,t){const n={posture:t.posture,default_mode:t.default_mode,folders:t.folders.map(r=>({path:r.path,mode:r.mode}))};return e==="gateway"?n:{configured:!0,...n}}function m2(e,t,n,r){return Qf(e,{...t,folders:t.folders.map(o=>o.path===n?{path:n,mode:r}:o)})}function _2(e,t,n){return Qf(e,{...t,posture:n})}function p2(e,t,n){return Qf(e,{...t,default_mode:n})}function g2(e,t,n,r){const o=String(n).trim();return Qf(e,{...t,folders:[...t.folders,{path:o,mode:h2(e,t.posture)}]})}function y2(e,t,n){return Qf(e,{...t,folders:t.folders.filter(r=>r.path!==n)})}function w2(e,t){if(t)return{configured:!1};const n=e.effective;if(!n)throw new Error("The follow switch needs the gateway's effective workspaces.");return{configured:!0,posture:n.posture,default_mode:n.default_mode??e.policy.default_mode,folders:n.folders.map(r=>({path:r.path,mode:r.mode}))}}function v2(e){let t=String(e||"");for(;t.endsWith("/");)t=t.slice(0,-1);return t}function x2(e="me",t=Ef){return`${v2(t)}/workspace/effective/${encodeURIComponent(e)}`}const $w=e=>e==="ro"||e==="rw"||e==="deny",b2=e=>e==="ro"||e==="rw",k2=e=>e==="allowed_only"||e==="any_except_denied",Aw="The gateway answered with an older workspace model (it needs the round-11 workspace API).";function j2(e){const t=e&&typeof e=="object"?e:{};if("shared_workspace"in t)throw new Error(Aw);if(!(k2(t.posture)&&(b2(t.default_mode)||t.default_mode===null&&t.posture==="allowed_only")&&typeof t.summary=="string"&&typeof t.gateway_summary=="string"&&Array.isArray(t.folders)&&t.folders.every(r=>r&&typeof r.path=="string"&&$w(r.mode)&&$w(r.cap))))throw new Error(`The gateway answered without the effective workspaces (posture, default_mode, folders with cap, summary, gateway_summary). ${Aw}`);return{posture:t.posture,default_mode:t.default_mode,folders:t.folders.map(r=>({path:r.path,mode:r.mode,cap:r.cap,source:r.source})),summary:t.summary,gateway_summary:t.gateway_summary}}function Af(e,t="me",n=Ef){const r=x2(t,n);return async(o,l)=>j2(await e(r,{method:"POST",body:l?{workspace:o,session:l}:{workspace:o}}))}function g_(e){if(e instanceof Error)return e.message;if(typeof e=="string")return e;const t=e&&typeof e=="object"?e:{},n=t.detail;return n&&typeof n=="object"&&typeof n.message=="string"?n.message:typeof n=="string"?n:typeof t.message=="string"?t.message:""}function Tw(e){const t=g_(e).trim()||"The gateway refused the change.";return`${t}${/[.!?]$/.test(t)?"":"."} ${$r.notSaved}`}const S2=e=>!!e&&typeof e=="object"&&"policy"in e&&"effective"in e;function N2(e,t){return t?{policy:e?{configured:!0,posture:e.posture,default_mode:e.default_mode,folders:e.folders.map(n=>({...n}))}:{configured:!1,posture:t.posture,default_mode:t.default_mode??"rw",folders:[]},effective:t}:null}function Ab(e){Yf();const t=e.idPrefix||"af-workspace",[n,r]=_.useState(null),[o,l]=_.useState({}),[c,u]=_.useState(null),[f,h]=_.useState(""),[m,g]=_.useState(null),y=String(e.unavailableReason||"").trim(),w=e.level,k=e.level==="run"?N2(e.value,e.effective):e.state,b=e.level==="run"?e.effective:e.state,S=m&&m.base===b?m.value:k,N=S?f2(w,S):null,R=L=>{if(e.level==="run"){const M=e,ee=L.configured===!1?null:{posture:L.posture,default_mode:L.default_mode,folders:L.folders};return Promise.resolve(M.onChange(ee))}return e.save(L)};async function T(L,M){if(n!==null||y)return!1;r(L),u(null),l(ee=>{const F={...ee};return delete F[L],F});try{const ee=await R(M);return S2(ee)&&g({base:b,value:ee}),u(L),!0}catch(ee){return l(F=>({...F,[L]:Tw(ee)})),!1}finally{r(null)}}const A=L=>o[L]?s.jsx("span",{className:"af-workspace__refusal",role:"alert","data-workspace":"refusal",children:o[L]}):c===L?s.jsx("span",{className:"af-workspace__saved",role:"status","data-workspace":"saved",children:gn.saved}):null,W=(L,M)=>s.jsx("span",{className:"af-workspace__access-tag","data-workspace":"access","data-access":L,"data-af-tip":M,tabIndex:M?0:void 0,children:Cw(L)}),z=(L,M,ee,F,U)=>s.jsx("span",{className:"af-workspace__access",role:"group","aria-label":L,"data-workspace":U,"data-access":M,children:ee.map(V=>{const O=!!V.reason||!!y;return s.jsx("button",{type:"button",className:"af-workspace__access-btn","aria-pressed":M===V.value?"true":"false","aria-disabled":O?"true":void 0,"data-af-tip":V.reason||void 0,"data-action":`${U}-${V.value}`,onClick:()=>O||n!==null||V.value===M?void 0:F(V.value),children:V.text},V.value)})}),J=L=>{if(L.builtin)return W("deny",gn.builtinRefused);if(!L.editable||!S)return W(L.mode);const M=S.policy;return s.jsxs(s.Fragment,{children:[z(`${gn.accessLabel} ${L.path}`,L.mode,["rw","ro","deny"].map(ee=>({value:ee,text:Cw(ee),reason:L.reasons[ee]})),ee=>void T(L.path,m2(w,M,L.path,ee)),"workspace-mode"),s.jsx("button",{type:"button",className:"af-workspace__icon-btn","data-action":"workspace-remove","aria-label":`${gn.remove} ${L.path}`,"data-af-tip":`${gn.remove} ${L.path}`,"aria-disabled":y||n!==null?"true":void 0,onClick:()=>y||n!==null?void 0:void T(L.path,y2(w,M,L.path)),children:s.jsx(Be,{name:"x",size:16})})]})};async function K(L){if(!S||!N||!N.canAdd)return;const M=L.trim();M&&await T("add",g2(w,S.policy,M))&&h("")}async function re(){if(!e.choose||n!==null||y)return;let L;try{L=await e.choose()}catch(M){l(ee=>({...ee,add:Tw(M)}));return}L&&await K(L)}const te=N?N.rows.filter(L=>L.mode!=="deny"):[],Q=N?N.rows.filter(L=>L.mode==="deny"):[],D=L=>s.jsxs("li",{className:"af-workspace__row","data-workspace":L.builtin?"builtin":"row","data-path":L.path,"data-mode":L.mode,"data-cap":L.cap??void 0,children:[s.jsx("code",{className:"af-workspace__path",children:L.path}),s.jsx("span",{className:"af-workspace__controls",children:J(L)}),A(L.path)]},`${L.builtin?"builtin:":""}${L.path}`),$=w==="account"?gn.followGateway:gn.useDefault,E=w==="account"?gn.followGatewayHelp:gn.useDefaultHelp;return s.jsx(yf,{id:t,className:`af-workspace af-workspace--${w}${e.className?` ${e.className}`:""}`,title:w==="gateway"?gn.gatewayTitle:gn.title,help:u2(w),children:e.loadError?s.jsx("p",{className:"af-workspace__refusal",role:"alert","data-workspace":"load-error",children:e.loadError}):!N||!S?s.jsx("p",{className:"af-workspace__note","data-workspace":"loading",children:gn.loading}):s.jsxs("div",{className:"af-workspace__body","data-level":w,"data-following":N.following?"true":"false",children:[N.gatewayLine?s.jsx("p",{className:"af-workspace__gateway","data-workspace":"gateway-line",children:N.gatewayLine}):null,y?s.jsx("p",{className:"af-workspace__note",id:`${t}-blocked`,"data-workspace":"blocked",children:y}):null,w!=="gateway"?s.jsxs("div",{className:"af-workspace__follow","data-workspace":"follow",children:[s.jsx(Ni,{variant:"row",label:$,description:E,checked:N.following,busy:n==="follow",unavailableReason:y||(N.locked?gn.locked:null),reasonVisible:!1,describedBy:y?`${t}-blocked`:void 0,action:w==="account"?"workspace-follow-gateway":"workspace-use-default",onChange:L=>void T("follow",w2(S,L))}),A("follow")]}):null,s.jsxs("div",{className:"af-workspace__posture","data-workspace":"posture","data-posture":N.posture,children:[N.following||N.locked?s.jsx("span",{className:"af-workspace__badge",children:l2(N.posture)}):z(gn.postureLabel,N.posture,[{value:"allowed_only",text:gn.postureAllowedOnly},{value:"any_except_denied",text:gn.postureAnyExceptDenied}],L=>void T("posture",_2(w,S.policy,L)),"workspace-posture"),s.jsx("span",{className:"af-workspace__note","data-workspace":"posture-help",children:c2(N.posture)}),A("posture")]}),s.jsxs("ul",{className:"af-workspace__list","aria-label":gn.title,"data-workspace":"list",children:[te.length?s.jsx("li",{className:"af-workspace__caption","data-workspace":"caption-allowed",children:gn.allowedTitle}):null,te.map(D),Q.length?s.jsx("li",{className:"af-workspace__caption","data-workspace":"caption-refused",children:gn.deniedTitle}):null,Q.map(D),N.everythingElse?s.jsxs("li",{className:"af-workspace__row","data-workspace":"everything-else","data-mode":N.everythingElse.mode,children:[s.jsx("span",{className:"af-workspace__name",children:gn.everythingElse}),s.jsx("span",{className:"af-workspace__controls",children:N.everythingElse.editable?z(`${gn.accessLabel} ${gn.everythingElse}`,N.everythingElse.mode,[{value:"rw",text:gn.accessReadWrite},{value:"ro",text:gn.accessRead}],L=>void T("everything-else",p2(w,S.policy,L)),"workspace-default"):W(N.everythingElse.mode)}),A("everything-else")]}):null,N.canAdd?s.jsxs("li",{className:"af-workspace__add","data-workspace":"add",children:[s.jsx("input",{type:"text",className:"af-workspace__input","aria-label":gn.addPlaceholder,placeholder:gn.addPlaceholder,value:f,disabled:!!y||n==="add",spellCheck:!1,autoCapitalize:"off",autoCorrect:"off",onChange:L=>h(L.target.value),onKeyDown:L=>{L.key==="Enter"?(L.preventDefault(),K(f)):L.key==="Escape"&&(L.preventDefault(),h(""),l(M=>{const ee={...M};return delete ee.add,ee}))}}),s.jsx("button",{type:"button",className:"af-workspace__add-btn","data-action":"workspace-add",disabled:!!y||!f.trim()||n!==null,onClick:()=>void K(f),children:gn.add}),e.choose?s.jsx("button",{type:"button",className:"af-workspace__add-btn","data-action":"workspace-choose",disabled:!!y||n!==null,onClick:()=>void re(),children:gn.choose}):null,A("add")]}):null]}),N.posture==="allowed_only"&&!te.length?s.jsx("p",{className:"af-workspace__note","data-workspace":"empty",children:gn.emptyAllowed}):null,w==="session"||w==="run"?s.jsx("p",{className:"af-workspace__note","data-workspace":"private",children:gn.privateNote}):null,s.jsx("p",{className:"af-workspace__effective","data-workspace":"effective",children:N.summary}),e.footer?s.jsx("div",{className:"af-workspace__footer",children:e.footer}):null]})})}const C2=["provider","model","voice","profile","speed","quality_preset","instructions"];function E2(e){const t={};for(const n of C2){const r=e[n];r!==void 0&&r!==""&&r!==null&&(t[n]=r)}return t}function $2(e){return{...e.stt_provider?{provider:e.stt_provider}:{},...e.stt_provider&&e.stt_model?{model:e.stt_model}:{},...e.stt_language?{language:e.stt_language}:{}}}const A2=[{value:"",label:"Detect automatically"},{value:"en",label:"English"},{value:"fr",label:"French"},{value:"de",label:"German"},{value:"es",label:"Spanish"},{value:"it",label:"Italian"},{value:"pt",label:"Portuguese"},{value:"nl",label:"Dutch"},{value:"zh",label:"Chinese"},{value:"ja",label:"Japanese"},{value:"ko",label:"Korean"}];function T2(e){return[e.provider,e.model,e.profile||e.voice].filter(Boolean).join(" · ")}function M2(e){return[e.stt_provider,e.stt_model].filter(Boolean).join(" · ")}const R2=[{value:"",label:"Gateway default"},{value:"standard",label:"Balanced"},{value:"low",label:"Faster (lower quality)"},{value:"high",label:"Higher quality (slower)"}],Mw=e=>Array.isArray(e)?e.map(t=>typeof t=="string"?t:(t==null?void 0:t.id)||(t==null?void 0:t.name)).filter(Boolean):[],Zd=e=>`${Math.round(e*100)} %`;function L2(e){var We,ut,Fe,et;const t=e.overrideOwner||"this app",n=!!e.unavailableReason,r=_.useRef(e.fetchCatalog);r.current=e.fetchCatalog;const o=_.useRef(e.fetchDefaults);o.current=e.fetchDefaults;const[l,c]=_.useState({}),[u,f]=_.useState({value:null,failed:!1}),h=e.defaults!==void 0?{value:e.defaults,failed:!1}:u,m=e.defaults!==void 0,[g,y]=_.useState(""),[w,k]=_.useState({devices:[],labelled:!0}),[b,S]=_.useState({devices:[],labelled:!0}),[N,R]=_.useState(""),[T,A]=_.useState({text:"",tone:"info"}),[W,z]=_.useState({phase:"idle",message:"",tone:"info"}),[J,K]=_.useState(0),re=e.outputSelectable??mN(),te=Kx(),Q=e.value,D=e.nested?"flat":"card",$=$e=>e.onChange({...Q,...$e}),E=Q.reply_volume===void 0?1:Math.min(1,Math.max(0,Number(Q.reply_volume)||0)),L=Q.input_gain===void 0?1:Math.min(1.5,Math.max(.5,Number(Q.input_gain)||1));_.useEffect(()=>{if(n)return;let $e=!0;return r.current().then(Ve=>$e&&c(Ve||{})).catch(()=>$e&&c({})),m||o.current().then(Ve=>$e&&f({value:Ve||{},failed:!1})).catch(()=>$e&&f({value:null,failed:!0})),()=>{$e=!1}},[n,m]);const M=e.listDevices||eN,ee=()=>{re&&M("audiooutput").then(k).catch(()=>k({devices:[],labelled:!1})),M("audioinput").then(S).catch(()=>S({devices:[],labelled:!1}))};_.useEffect(()=>{n||ee()},[re,n]);const F=()=>{R(""),tN().then(ee).catch($e=>R(Qp($e)))},U=()=>{A({text:"Playing a short chime…",tone:"info"}),oN({deviceId:re&&Q.output_device||"",volume:E}).then(()=>A({text:"Chime played. Heard nothing? Pick another output or raise the volume.",tone:"ok"})).catch($e=>A({text:`The speaker test failed: ${String(($e==null?void 0:$e.message)||$e).replace(/\.$/,"")}.`,tone:"error"}))},V=()=>{z({phase:"recording",message:"Recording 3 seconds — say something.",tone:"info"}),rN({deviceId:Q.input_device||"",ms:3e3,gain:L,onLevel:K}).then(async({blob:$e,peak:Ve})=>{if(Ve<sN){z({phase:"idle",message:"The microphone recorded silence. Pick another input, or raise its level in the system sound settings.",tone:"error"});return}z({phase:"playing",message:"Playing it back…",tone:"info"}),await iN($e,{deviceId:re&&Q.output_device||"",volume:E}),z({phase:"idle",message:`The microphone works (peak level ${Zd(Ve)}).`,tone:"ok"}),ee()}).catch($e=>z({phase:"idle",message:Qp($e),tone:"error"}))},O=uw(h.value,"tts",h.failed),H=uw(h.value,"stt",h.failed),Y=[(We=h.value)==null?void 0:We.tts,(ut=h.value)==null?void 0:ut.stt].map($e=>$e&&!$e.configured?$e.note:"").filter(Boolean),ae=!!((et=(Fe=l.controls)==null?void 0:Fe.quality_preset)!=null&&et.supported),ie=Q.output_device||"",_e=[{value:"",label:"System default"},...w.devices.map($e=>({value:$e.id,label:$e.label})),...ie&&!w.devices.some($e=>$e.id===ie)?[{value:ie,label:"Saved speaker (not connected)"}]:[]],fe=Q.input_device||"",ge=[{value:"",label:"System default"},...b.devices.map($e=>({value:$e.id,label:$e.label})),...fe&&!b.devices.some($e=>$e.id===fe)?[{value:fe,label:"Saved microphone (not connected)"}]:[]],Ne=!b.labelled||re&&!w.labelled,Ue=W.phase!=="idle";return s.jsxs("div",{className:`af-voice-section${e.className?` ${e.className}`:""}`,children:[e.unavailableReason?s.jsx("p",{className:"af-settings-group__help",role:"status",children:e.unavailableReason}):null,s.jsxs(yf,{variant:D,title:"Engines",help:"Which engines speak and listen.",children:[s.jsx(Nw,{label:"Text → speech",setting:"tts",defaultSummary:O,overrideSummary:T2(Q),overrideOwner:t,open:g==="tts",onToggle:()=>y(g==="tts"?"":"tts"),onReset:()=>$({provider:"",model:"",voice:"",profile:""}),disabled:n,children:s.jsx(yN,{value:Q,onChange:$e=>e.onChange({...Q,...$e}),fetchCatalog:e.fetchCatalog,intro:null,quality:!1,showReset:!1,voiceDefaultLabel:"Gateway default"})}),s.jsx(Nw,{label:"Speech → text",setting:"stt",defaultSummary:H,overrideSummary:M2(Q),overrideOwner:t,open:g==="stt",onToggle:()=>y(g==="stt"?"":"stt"),onReset:()=>$({stt_provider:"",stt_model:""}),disabled:n,children:s.jsx(zx,{value:{provider:Q.stt_provider||"",model:Q.stt_model||""},onChange:$e=>$({stt_provider:$e.provider,stt_model:$e.model}),fetchProviders:async()=>{const $e=await r.current();return Mw($e.stt_providers).map(Ve=>({name:Ve}))},fetchModels:async $e=>{var le;const Ve=await r.current($e);return Mw(((le=Ve.stt_models_by_provider)==null?void 0:le[$e])||Ve.stt_models)},inheritLabel:"Gateway default",providerLabel:"Transcription provider",modelLabel:"Transcription model"})}),h.failed?s.jsx("p",{className:"af-settings-group__help","data-voice-note":"defaults",role:"status",children:"The gateway's default voice routes could not be read. Requests still use them."}):null,Y.map($e=>s.jsx("p",{className:"af-settings-group__help","data-voice-note":"unset",children:$e},$e))]}),s.jsxs(yf,{variant:D,title:"Output",children:[s.jsx(oc,{label:"Output device",setting:"output-device",help:re?void 0:"Safari does not let a page choose the output device: replies play on the system output (change it in the system sound settings).",trailing:s.jsx("button",{type:"button",className:"af-setting-btn","data-action":"test-speaker",disabled:n,onClick:U,children:"Test"}),children:s.jsx(si,{ariaLabel:"Output device",placeholder:"System default",value:re?ie:"",options:_e,disabled:n||!re,searchable:!1,onOpen:ee,onChange:$e=>$({output_device:$e})})}),T.text?s.jsx("p",{className:`af-voice-note af-voice-note--${T.tone}`,role:"status","data-voice-note":"speaker",children:T.text}):null,s.jsxs(oc,{label:"Reply volume",setting:"reply-volume",htmlFor:"af-voice-volume",children:[s.jsx("input",{id:"af-voice-volume",className:"af-voice-range",type:"range",min:0,max:100,step:5,value:Math.round(E*100),disabled:n,"aria-valuetext":Zd(E),onChange:$e=>$({reply_volume:Number($e.currentTarget.value)/100})}),s.jsx("span",{className:"af-voice-range__value",children:Zd(E)})]})]}),s.jsxs(yf,{variant:D,title:"Microphone",children:[s.jsx(oc,{label:"Input device",setting:"input-device",trailing:s.jsx("button",{type:"button",className:"af-setting-btn","data-action":"test-microphone",disabled:n||Ue,onClick:V,children:W.phase==="recording"?"Recording…":W.phase==="playing"?"Playing…":"Test"}),children:s.jsx(si,{ariaLabel:"Input device",placeholder:"System default",value:fe,options:ge,disabled:n,searchable:!1,onOpen:ee,onChange:$e=>$({input_device:$e})})}),s.jsx("div",{className:"af-voice-meter","data-voice-meter":!0,role:"meter","aria-label":"Microphone level","aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":Math.round(J*100),children:s.jsx("span",{className:"af-voice-meter__fill",style:{width:`${Math.round(J*100)}%`}})}),W.message?s.jsx("p",{className:`af-voice-note af-voice-note--${W.tone}`,role:"status","data-voice-note":"microphone",children:W.message}):null,Ne&&!n?s.jsxs("p",{className:"af-voice-note","data-voice-note":"labels",children:["Device names appear once the microphone is allowed."," ",s.jsx("button",{type:"button",className:"af-setting-btn af-setting-btn--quiet","data-action":"show-device-names",onClick:F,children:"Show names"})]}):null,N?s.jsx("p",{className:"af-voice-note af-voice-note--error",role:"status",children:N}):null,s.jsx(oc,{label:"Spoken language",setting:"stt-language",help:"Naming it skips detection: transcription is faster.",children:s.jsx(si,{ariaLabel:"Spoken language",placeholder:"Detect automatically",value:Q.stt_language||"",options:A2,disabled:n,searchable:!1,onChange:$e=>$({stt_language:$e})})}),te?s.jsxs(oc,{label:"Input level",setting:"input-gain",htmlFor:"af-voice-gain",help:"Raises a quiet microphone.",children:[s.jsx("input",{id:"af-voice-gain",className:"af-voice-range",type:"range",min:50,max:150,step:10,value:Math.round(L*100),disabled:n,"aria-valuetext":Zd(L),onChange:$e=>$({input_gain:Number($e.currentTarget.value)/100})}),s.jsx("span",{className:"af-voice-range__value",children:Zd(L)})]}):null]}),s.jsxs(yf,{variant:D,title:"Replies",children:[s.jsx("div",{className:"af-setting-row af-setting-row--switch","data-setting":"read-aloud",children:s.jsx(Ni,{label:"Read aloud",description:"Speak each new reply.",variant:"row",checked:Q.read_aloud===!0,unavailableReason:n?e.unavailableReason:null,reasonVisible:!1,onChange:$e=>$({read_aloud:$e})})}),s.jsx(oc,{label:"Voice latency",setting:"latency",help:ae?"Trades quality for a faster first word.":"This gateway's voice engine has no latency control.",children:s.jsx(si,{ariaLabel:"Voice latency",placeholder:"Gateway default",value:ae&&Q.quality_preset||"",options:R2,disabled:n||!ae,searchable:!1,onChange:$e=>$({quality_preset:$e})})})]})]})}function y_(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 I2(e){if(e==null)return"";if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}}function O2(e){const t=String(e.role||"message").trim()||"message",n=String(e.title||"").trim(),r=String(e.ts||"").trim(),o=[t];return n&&o.push(n),r&&o.push(r),o.join(" · ")}function P2(e){return e.endsWith(`
|
|
66
|
-
`)?e:`${e}
|
|
67
|
-
`}function D2(e){return String(e||"").trimStart().startsWith("```")}function F2(e,t){const r=[`# ${String((t==null?void 0:t.heading)||"Chat").trim()||"Chat"}`,""];for(const o of e){const l=O2(o);r.push(`## ${l}`,"");const c=String(o.content||""),u=y_(c);u!==null&&!D2(c)?r.push("```json",I2(u).trimEnd(),"```",""):r.push(P2(c).trimEnd(),""),r.push("---","")}for(;r.length&&!r[r.length-1].trim();)r.pop();return r.length&&r[r.length-1]==="---"&&r.pop(),`${r.join(`
|
|
68
|
-
`).trimEnd()}
|
|
69
|
-
`}async function gl(e){var n;const t=String(e||"");if(!t)return!1;try{if(typeof navigator<"u"&&typeof((n=navigator.clipboard)==null?void 0:n.writeText)=="function")return await navigator.clipboard.writeText(t),!0}catch{}try{const r=document.createElement("textarea");r.value=t,r.style.position="fixed",r.style.left="-9999px",document.body.appendChild(r),r.select();const o=document.execCommand("copy")===!0;return document.body.removeChild(r),o}catch{return!1}}function z2(e){const t=String(e.filename||"").trim()||"export.txt",n=String(e.text||""),r=String(e.mime),o=new Blob([n],{type:r}),l=URL.createObjectURL(o),c=document.createElement("a");c.href=l,c.download=t,document.body.appendChild(c),c.click(),c.remove(),window.setTimeout(()=>URL.revokeObjectURL(l),1e3)}const B2=3,U2=Number.MAX_SAFE_INTEGER;function Tb(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Mb(e){return Array.isArray(e)}function W2(e){if(e==null)return"";if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}}function Tu({kind:e,children:t}){return s.jsx("span",{className:`pc-json-token ${e}`,children:t})}function q2(e){const t=JSON.stringify(e.value),n=t.length>96||t.includes("\\n")||t.includes("\\r")||t.includes("\\t"),[r,o]=_.useState(!n||e.expansionMode==="unfolded");return _.useEffect(()=>{n&&o(e.expansionMode==="unfolded")},[n,e.expansionMode,e.expansionVersion]),n?s.jsxs("span",{className:`pc-json-string ${r?"open":"collapsed"}`,children:[s.jsx("button",{type:"button",className:"pc-json-string__toggle",onClick:()=>o(l=>!l),"aria-label":r?"Collapse string value":"Expand string value","aria-expanded":r,children:r?"▾":"▸"}),r?s.jsx("span",{className:"pc-json-token string pc-json-string__value",children:t}):s.jsxs("button",{type:"button",className:"pc-json-string__preview",onClick:()=>o(!0),"aria-label":"Expand string value",children:[s.jsx("span",{className:"pc-json-token string pc-json-string__preview_text",children:t}),s.jsx("span",{className:"pc-json-string__suffix",children:"(...)"})]})]}):s.jsx(Tu,{kind:"string",children:t})}function H2(e,t,n){return e===null?s.jsx(Tu,{kind:"null",children:"null"}):typeof e=="string"?s.jsx(q2,{value:e,expansionMode:t,expansionVersion:n}):typeof e=="number"?s.jsx(Tu,{kind:"number",children:String(e)}):typeof e=="boolean"?s.jsx(Tu,{kind:"boolean",children:e?"true":"false"}):s.jsx(Tu,{kind:"string",children:JSON.stringify(String(e))})}function V2(e){return Mb(e)?e.length===1?"1 item":`${e.length} items`:Tb(e)?Object.keys(e).length===1?"1 key":`${Object.keys(e).length} keys`:""}function Rb(e){const{label:t,value:n,depth:r,collapseAfterDepth:o,expansionMode:l,expansionVersion:c,trailingComma:u}=e,f=r*14,h=Tb(n),m=Mb(n),g=h||m,y=r<o,[w,k]=_.useState(y);_.useEffect(()=>{k(y)},[y,c]);const b=t?s.jsxs(s.Fragment,{children:[s.jsx(Tu,{kind:"key",children:JSON.stringify(t)}),": "]}):null;if(!g)return s.jsxs("div",{className:"pc-json-viewer__line",style:{paddingLeft:f},children:[b,H2(n,l,c),u?",":""]});const S=m?"[":"{",N=m?"]":"}",R=V2(n),T=w?`${S}`:`${S}…${N}${R?` (${R})`:""}`,A=m?n.map((W,z)=>({key:String(z),label:void 0,value:W})):Object.entries(n).map(([W,z])=>({key:W,label:W,value:z}));return s.jsxs("details",{className:"pc-json-viewer__details",open:w,onToggle:W=>k(W.currentTarget.open),children:[s.jsxs("summary",{className:"pc-json-viewer__summary",style:{paddingLeft:f},children:[b,s.jsx("span",{className:"pc-json-viewer__caret","aria-hidden":"true",children:w?"▾":"▸"}),s.jsx("span",{className:"pc-json-viewer__punct",children:T}),!w&&u?s.jsx("span",{className:"pc-json-viewer__punct",children:","}):null]}),w?s.jsx("div",{className:"pc-json-viewer__children",children:A.length===0?s.jsxs("div",{className:"pc-json-viewer__line",style:{paddingLeft:f},children:[s.jsx("span",{className:"pc-json-viewer__punct",children:N}),u?",":""]}):s.jsxs(s.Fragment,{children:[A.map((W,z)=>{const J=z===A.length-1;return s.jsx(Rb,{label:W.label,value:W.value,depth:r+1,collapseAfterDepth:o,expansionMode:l,expansionVersion:c,trailingComma:!J},`${r}:${t||"root"}:${W.key}`)}),s.jsxs("div",{className:"pc-json-viewer__line",style:{paddingLeft:f},children:[s.jsx("span",{className:"pc-json-viewer__punct",children:N}),u?",":""]})]})}):null]})}function G2(e){const t=e.trim();if(!t)return e;if(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))try{return JSON.parse(t)}catch{return e}return e}function Is(e){const{value:t,className:n,showCopy:r=!0}=e,[o,l]=_.useState({mode:"folded",version:0}),[c,u]=_.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):B2,h=o.mode==="unfolded"?U2:f,m=_.useMemo(()=>typeof t=="string"?G2(t):t,[t]),g=_.useMemo(()=>W2(t),[t]),y=["pc-json-viewer",n].filter(Boolean).join(" ");_.useEffect(()=>{l(k=>({mode:"folded",version:k.version+1}))},[m]);const w=()=>{l(k=>({mode:k.mode==="unfolded"?"folded":"unfolded",version:k.version+1}))};return s.jsxs("div",{className:y,children:[s.jsxs("div",{className:"pc-json-viewer__toolbar",children:[s.jsx("button",{type:"button",className:"pc-btn pc-json-viewer__toggle-all",onClick:w,"aria-expanded":o.mode==="unfolded",children:o.mode==="unfolded"?"Fold all":"Unfold all"}),r?s.jsx("button",{type:"button",className:"pc-btn pc-json-viewer__copy",onClick:()=>void gl(g).then(k=>{u(k?"copied":"failed"),window.setTimeout(()=>u("idle"),2e3)}),children:c==="copied"?"Copied":c==="failed"?"Copy failed — select and copy":"Copy JSON"}):null]}),s.jsx("div",{className:"pc-json-viewer__tree",role:"tree","aria-label":"JSON viewer",children:s.jsx(Rb,{value:m,depth:0,collapseAfterDepth:h,expansionMode:o.mode,expansionVersion:o.version,trailingComma:!1})})]})}function K2({code:e,lang:t}){const[n,r]=_.useState("idle"),o=_.useRef(null);_.useEffect(()=>()=>{o.current!==null&&window.clearTimeout(o.current)},[]);const l=Cb(e,ey(t));return s.jsxs("div",{className:"pc-md_codeblock",children:[s.jsx("button",{type:"button",className:`pc-md_copy${n!=="idle"?` pc-md_copy--${n}`:""}`,"aria-label":"Copy code",title:n==="idle"?"Copy":n==="copied"?"Copied":"Copy failed",onClick:async()=>{const c=await gl(e);r(c?"copied":"failed"),o.current!==null&&window.clearTimeout(o.current),o.current=window.setTimeout(()=>r("idle"),900)},children:s.jsx(Be,{name:n==="copied"?"check":"copy",size:14})}),s.jsx("pre",{className:"pc-md_pre",children:s.jsx("code",{className:t?`language-${t}`:void 0,children:l.map((c,u)=>c.kind==="plain"?s.jsx(xe.Fragment,{children:c.text},u):s.jsx("span",{className:`af-code__${c.kind}`,children:c.text},u))})})]})}function Qd(e,t){const n=String(e??"");if(!t||!t.needles.length)return[n];const r=[],o=n.toLowerCase();let l=0;for(;l<n.length;){let c=-1,u="";for(let m=0;m<t.needlesLower.length;m++){const g=t.needlesLower[m];if(!g)continue;const y=o.indexOf(g,l);if(y===-1)continue;const w=t.needles[m]||"";w&&(c===-1||y<c||y===c&&w.length>u.length)&&(c=y,u=w)}if(c===-1||!u){r.push(n.slice(l));break}c>l&&r.push(n.slice(l,c));const f=t.hits===0&&t.id?t.id:void 0,h=n.slice(c,c+u.length);r.push(s.jsx("span",{id:f,className:t.className,children:h},`hl:${t.hits}`)),t.hits+=1,l=c+u.length}return r}function Lb(e){const t=String(e||"").trim();if(t&&/^(https?:|mailto:|tel:|#|\/)/i.test(t))return t}const dg="http://same-origin.invalid/";function Y2(e){try{const t=new URL(e,dg);return t.protocol==="http:"&&t.origin===new URL(dg).origin}catch{return!1}}function Ib(e){const t=String(e||"").trim();return Lb(t)??(t&&Y2(t)?t:void 0)}let hc=null;function J2(e){const t=String(e||"").trim();if(!t)return!1;const n=typeof document<"u"&&document.baseURI?document.baseURI:null;if(n===null&&/^[a-z][a-z0-9+.-]*:/i.test(t))return!1;const r=n??dg;let o,l;try{o=new URL(r).origin,l=new URL(t,r)}catch{return!1}return l.protocol!=="http:"&&l.protocol!=="https:"?!1:l.origin===o}function Ob(e,t,n){return s.jsx("a",{className:"pc-md_link pc-md_image_link",href:t,target:"_blank",rel:"noopener noreferrer",children:`image: ${n||t}`},e)}function Rw(e){return!!e&&/[\p{L}\p{N}]/u.test(e)}function ha(e,t){const n=[],r=String(e??"");let o=0,l="";const c=()=>{if(l){for(const u of Qd(l,t))n.push(u);l=""}};for(;o<r.length;){const u=r[o];if(u==="!"&&r[o+1]==="["){const f=r.indexOf("]",o+2);if(f!==-1&&r[f+1]==="("){const h=r.indexOf(")",f+2);if(h!==-1){const m=r.slice(o+2,f),g=Ib(r.slice(f+2,h));if(g&&hc&&!hc(g)){c(),n.push(Ob(`img:${o}`,g,m)),o=h+1;continue}if(g){c(),n.push(s.jsxs("span",{className:"pc-md_image_inline",children:[s.jsx("img",{className:"pc-md_img",src:g,alt:m,loading:"lazy"}),m?s.jsx("span",{className:"pc-md_img_caption",children:t?Qd(m,t):m}):null]},`img:${o}`)),o=h+1;continue}}}}if(u==="["){const f=r.indexOf("]",o+1);if(f!==-1&&r[f+1]==="("){const h=r.indexOf(")",f+2);if(h!==-1){const m=r.slice(o+1,f),g=Lb(r.slice(f+2,h));if(g){c(),n.push(s.jsx("a",{className:"pc-md_link",href:g,target:g.startsWith("#")?void 0:"_blank",rel:"noreferrer",children:ha(m,t)},`link:${o}`)),o=h+1;continue}}}}if(u==="`"){const f=r.indexOf("`",o+1);if(f!==-1){c();const h=r.slice(o+1,f);n.push(s.jsx("code",{children:t?Qd(h,t):h},`code:${o}`)),o=f+1;continue}}if(u==="_"&&!Rw(r[o-1])){const f=r[o+1]==="_"?"__":"_",h=f.length;if(r[o+h]&&!/\s/.test(r[o+h])&&r[o+h]!=="_"){let m=r.indexOf(f,o+h);for(;m!==-1&&(/\s/.test(r[m-1]||" ")||Rw(r[m+h])||h===1&&r[m+1]==="_");)m=r.indexOf(f,m+1);if(m!==-1&&m>o+h){c();const g=r.slice(o+h,m),y=ha(g,t);n.push(h===2?s.jsx("strong",{children:y},`ubold:${o}`):s.jsx("em",{children:y},`uem:${o}`)),o=m+h;continue}}}if(u==="*"&&r[o+1]==="*"){const f=r.indexOf("**",o+2);if(f!==-1){c();const h=r.slice(o+2,f);n.push(s.jsx("strong",{children:t?Qd(h,t):h},`bold:${o}`)),o=f+2;continue}}if(u==="*"&&r[o+1]!=="*"){const f=r.indexOf("*",o+1);if(f!==-1){c();const h=r.slice(o+1,f);n.push(s.jsx("em",{children:t?Qd(h,t):h},`em:${o}`)),o=f+1;continue}}l+=u,o+=1}return c(),n}function X2(e){return String(e??"").replace(/\r\n/g,`
|
|
70
|
-
`).replace(/\r/g,`
|
|
71
|
-
`).split(`
|
|
72
|
-
`)}function Lm(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 Z2(e){const t=[];for(const o of e){const l=Lm(o);l?t.push(l):t.length>0&&o.trim()&&(t[t.length-1].content+=` ${o.trim()}`)}const n=[],r=[];for(const o of t){for(;r.length>0&&o.indent<r[r.length-1].indent;)r.pop();let l=r.length>0?r[r.length-1]:null;if(l&&o.indent>l.indent){const c=l.node.items,u=c[c.length-1];if(u){const f={ordered:o.ordered,start:o.start,items:[]};u.children.push(f),r.push({indent:o.indent,node:f}),l=r[r.length-1]}}else if(l&&l.node.ordered!==o.ordered){r.pop();const c=r.length>0?r[r.length-1]:null,u={ordered:o.ordered,start:o.start,items:[]};if(c){const f=c.node.items,h=f[f.length-1];h?h.children.push(u):c.node.items.push({content:"",children:[u]})}else n.push(u);r.push({indent:o.indent,node:u}),l=r[r.length-1]}if(!l){const c={ordered:o.ordered,start:o.start,items:[]};n.push(c),r.push({indent:o.indent,node:c}),l=r[r.length-1]}l.node.items.push({content:o.content,children:[]})}return n}function Pb(e,t,n){const r=e.items.map((o,l)=>s.jsxs("li",{children:[ha(o.content,t),o.children.map((c,u)=>Pb(c,t,`${n}:${l}:${u}`))]},`${n}:li:${l}`));return e.ordered?s.jsx("ol",{className:"pc-md_ol",start:e.start!==1?e.start:void 0,children:r},n):s.jsx("ul",{className:"pc-md_ul",children:r},n)}function Q2(e,t,n){return Z2(e).map((r,o)=>Pb(r,t,`${n}:${o}`))}function Lw(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 Iw(e){let t=String(e??"").trim();if(!t)return!1;t.startsWith("|")&&(t=t.slice(1)),t.endsWith("|")&&(t=t.slice(0,-1));const n=t.split("|").map(r=>String(r??"").trim());return n.length<2?!1:n.every(r=>/^:?-{3,}:?$/.test(r))}const Ow=/^(#{1,5})\s+(.*)$/;function Pw(e){return e.trim().startsWith("```")}function Dw(e){return e.trimStart().startsWith(">")}function Si(e){const t=hc;hc=e.images==="link"?e.inlineImage||J2:null;try{return eC(e)}finally{hc=t}}function eC({text:e,className:t,highlight:n,highlights:r,highlightClassName:o,highlightId:l}){const c=X2(e),u=[],f=[];Array.isArray(r)&&f.push(...r),typeof n=="string"&&n.trim()&&f.push(n);const h=Array.from(new Set(f.map(w=>String(w??"").trim()).filter(Boolean))).filter(w=>w.length>=4),m=h.length?{needles:h,needlesLower:h.map(w=>w.toLowerCase()),className:o||"pc-md_hl",id:l,hits:0}:null;let g=0;for(;g<c.length;){const w=String(c[g]??"");if(!w.trim()){g+=1;continue}const k=w.trim();if(/^([-_*])(\s*\1){2,}$/.test(k)){u.push(s.jsx("hr",{className:"pc-md_hr"},`hr:${g}`)),g+=1;continue}const b=w.match(/^\s*!\[([^\]]*)\]\(([^)]+)\)\s*$/);if(b){const R=Ib(b[2]||"");if(R&&hc&&!hc(R)){u.push(s.jsx("p",{className:"pc-md_p",children:Ob(`img:${g}`,R,b[1]||"")},`p:${g}`)),g+=1;continue}if(R){const T=b[1]||"";u.push(s.jsxs("figure",{className:"pc-md_figure",children:[s.jsx("img",{className:"pc-md_img",src:R,alt:T,loading:"lazy"}),T?s.jsx("figcaption",{children:ha(T,m)}):null]},`figure:${g}`)),g+=1;continue}}if(Pw(w)){const T=w.trim().replace(/```/g,"").trim(),A=[];for(g+=1;g<c.length&&!String(c[g]??"").trim().startsWith("```");)A.push(String(c[g]??"")),g+=1;g<c.length&&(g+=1);const W=A.join(`
|
|
73
|
-
`);u.push(s.jsx(K2,{code:W,lang:T},`pre:${g}`));continue}const S=w.match(Ow);if(S){const R=S[1].length,T=S[2]||"",A=ha(T,m);R===1?u.push(s.jsx("h1",{children:A},`h1:${g}`)):R===2?u.push(s.jsx("h2",{children:A},`h2:${g}`)):R===3?u.push(s.jsx("h3",{children:A},`h3:${g}`)):R===4?u.push(s.jsx("h4",{children:A},`h4:${g}`)):u.push(s.jsx("h5",{children:A},`h5:${g}`)),g+=1;continue}if(Dw(w)){const R=[];for(;g<c.length&&String(c[g]??"").trimStart().startsWith(">");){const A=String(c[g]??"").trimStart();R.push(A.replace(/^>\s?/,"")),g+=1}u.push(s.jsx("blockquote",{className:"pc-md_quote",children:R.map((T,A)=>s.jsxs(xe.Fragment,{children:[ha(T,m),A<R.length-1?s.jsx("br",{}):null]},`q:${g}:${A}`))},`quote:${g}`));continue}if(w.includes("|")&&g+1<c.length&&Iw(String(c[g+1]??""))){const R=Lw(w),T=Math.max(1,R.length),A=[];for(g+=2;g<c.length;){const W=String(c[g]??"");if(!W.trim()||!W.includes("|"))break;const z=Lw(W),J=[];for(let K=0;K<T;K++)J.push(z[K]??"");A.push(J),g+=1}u.push(s.jsx("div",{className:"pc-md_table_wrap",children:s.jsxs("table",{className:"pc-md_table",children:[s.jsx("thead",{children:s.jsx("tr",{children:R.slice(0,T).map((W,z)=>s.jsx("th",{children:ha(W,m)},`th:${g}:${z}`))})}),s.jsx("tbody",{children:A.map((W,z)=>s.jsx("tr",{children:W.map((J,K)=>s.jsx("td",{children:ha(J,m)},`td:${g}:${z}:${K}`))},`tr:${g}:${z}`))})]})},`table:${g}`));continue}if(Lm(w)){const R=[];for(;g<c.length;){const T=String(c[g]??"");if(!T.trim()||T.trimStart().startsWith("```"))break;if(Lm(T)||/^\s{2,}\S/.test(T)){R.push(T),g+=1;continue}break}u.push(s.jsx(xe.Fragment,{children:Q2(R,m,`list:${g}`)},`list:${g}`));continue}const N=[];for(;g<c.length&&String(c[g]??"").trim()&&!(N.length>0&&Lm(String(c[g]??"")));){const R=String(c[g]??"");if(N.length>0&&(Ow.test(R)||Pw(R)||Dw(R))||N.length>0&&R.includes("|")&&g+1<c.length&&Iw(String(c[g+1]??"")))break;N.push(R),g+=1}u.push(s.jsx("p",{className:"pc-md_p",children:N.map((R,T)=>s.jsxs(xe.Fragment,{children:[ha(R,m),T<N.length-1?s.jsx("br",{}):null]},`pl:${g}:${T}`))},`p:${g}`))}const y=["pc-md",t].filter(Boolean).join(" ");return s.jsx("div",{className:y,children:u})}function Db(e){const t=String(e.text??""),n=_.useMemo(()=>y_(t),[t]),r=["pc-chat-content",e.className].filter(Boolean).join(" ");return n!==null?s.jsx("div",{className:r,children:s.jsx(Is,{value:n,collapseAfterDepth:e.jsonCollapseAfterDepth})}):e.renderMarkdown?s.jsx("div",{className:r,children:e.renderMarkdown(t)}):s.jsx("div",{className:r,children:s.jsx(Si,{text:t,images:e.images,inlineImage:e.inlineImage})})}function wf(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function ul(e){return typeof e=="string"?e.trim():""}function tC(e){var o;const t=wf(e);if(!t)return null;const n=wf(t.sandbox);if(n&&ul(n.kind))return n;const r=wf((o=wf(t.output))==null?void 0:o.sandbox);return r&&ul(r.kind)?r:null}function fg(e){const t=tC(e);if(!t)return null;const n=ul(t.kind),r=ul(t.label)||n,o=Number.isFinite(Number(t.builtin_refused))?Math.max(0,Math.trunc(Number(t.builtin_refused))):0;if(n==="none")return{state:"refused",kind:n,label:r,line:`Sandbox: ${r} — refused`,rows:[],builtinRefused:0};const l=[],c=ul(t.private_workspace);c&&l.push({path:c,mode:"Read & write",private:!0});for(const f of Array.isArray(t.allowed)?t.allowed:[]){const h=wf(f),m=ul(h==null?void 0:h.path);m&&l.push({path:m,mode:ul(h==null?void 0:h.mode)==="ro"?"Read-only":"Read & write"})}for(const f of Array.isArray(t.refused)?t.refused:[]){const h=ul(f);h&&l.push({path:h,mode:"Refused"})}if(n==="unsandboxed")return{state:"unsandboxed",kind:n,label:r,line:`Sandbox: ${r}`,rows:[],builtinRefused:0};const u=l.length;return{state:"sandboxed",kind:n,label:r,line:`Sandbox: ${r} · ${u} ${u===1?"workspace":"workspaces"} enforced`,rows:l,builtinRefused:o}}function Fb({sandbox:e,className:t}){return e?s.jsxs("div",{className:`pc-tool-sandbox is-${e.state}${t?` ${t}`:""}`,"data-sandbox-kind":e.kind,children:[s.jsx("div",{className:"pc-tool-sandbox__line",children:e.line}),e.rows.length?s.jsxs("ul",{className:"pc-tool-sandbox__rows","aria-label":"Workspaces the sandbox enforced",children:[e.rows.map((n,r)=>s.jsxs("li",{children:[s.jsx("code",{children:n.path}),s.jsx("span",{className:"pc-tool-sandbox__mode",children:n.private?`${n.mode} · this run's folder`:n.mode})]},`${n.mode}:${n.path}:${r}`)),e.builtinRefused?s.jsxs("li",{className:"pc-tool-sandbox__builtin",children:[e.builtinRefused," built-in protected ",e.builtinRefused===1?"folder":"folders"," refused"]}):null]}):null]}):null}function zb(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}}function nC(e){const t=zb(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(([c])=>c===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 Bb({tool:e,showCopy:t=!0}){const[n,r]=_.useState(!1),o=zb(e.arguments),l=nC(e.arguments),c=["file path","path"].includes(l.label)&&l.value.length>60?`${l.value.split(/[\\/]/).pop()} · ${l.value.slice(0,24)}…`:l.value,u=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"},h=e.startedAt&&e.endedAt?Date.parse(e.endedAt)-Date.parse(e.startedAt):NaN,m=o&&typeof o=="object"&&!Array.isArray(o)?Object.entries(o):null;return s.jsxs("details",{className:`pc-tool-activity pc-tool-activity--${e.status}`,children:[s.jsxs("summary",{className:"pc-tool-activity__summary",children:[s.jsx("span",{className:"pc-tool-activity__state-icon","aria-hidden":"true",children:s.jsx(Be,{name:e.status==="completed"?"check":e.status==="failed"?"x":e.status==="waiting"?"warning":"loader",size:15})}),s.jsx("strong",{children:e.name}),s.jsx("span",{className:"pc-tool-activity__preview",title:l.value,children:l.value?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"pc-tool-activity__key",children:l.label}),c]}):"No parameters"}),s.jsx("span",{className:"pc-tool-activity__status",children:f[e.status]}),Number.isFinite(h)&&h>=0?s.jsxs("span",{className:"pc-tool-activity__duration",children:[(h/1e3).toFixed(1),"s"]}):null,s.jsx("span",{className:"pc-tool-activity__chevron","aria-hidden":"true",children:s.jsx(Be,{name:"chevronRight",size:13})}),e.error?s.jsx("span",{className:"pc-tool-activity__error",title:e.error,children:u}):null]}),s.jsxs("div",{className:"pc-tool-activity__detail",children:[s.jsx(Fb,{sandbox:e.sandbox}),e.error?s.jsxs(s.Fragment,{children:[s.jsx("h4",{children:"Error"}),s.jsx("pre",{className:"pc-tool-activity__output",children:e.error})]}):null,s.jsxs("div",{className:"pc-tool-activity__detail-heading",children:[s.jsx("h4",{children:"Parameters"}),t?s.jsxs("button",{type:"button",onClick:async()=>r(await gl(JSON.stringify(e,null,2))),children:[s.jsx(Be,{name:"copy",size:13}),n?"Copied":"Copy details"]}):null]}),m?s.jsx("dl",{className:"pc-tool-activity__parameters",children:m.map(([g,y])=>s.jsxs(xe.Fragment,{children:[s.jsx("dt",{children:g}),s.jsx("dd",{children:y&&typeof y=="object"?s.jsx(Is,{value:y}):s.jsx("code",{children:typeof y=="string"?y:JSON.stringify(y)})})]},g))}):e.arguments===void 0?s.jsx("p",{children:"Arguments are unavailable in this ledger."}):s.jsx(Is,{value:o}),e.output!==void 0?s.jsxs(s.Fragment,{children:[s.jsx("h4",{children:"Result"}),typeof e.output=="string"?s.jsx("pre",{className:"pc-tool-activity__output",children:e.output}):s.jsx("div",{className:"pc-tool-activity__output",children:s.jsx(Is,{value:e.output})})]}):null]})]})}function Ub({tools:e,showCopy:t}){const n=r=>e.filter(o=>o.status===r).length;return s.jsxs("section",{className:"pc-tool-group","aria-label":"Tool activity",children:[s.jsxs("div",{className:"pc-tool-group__heading",children:[s.jsx(Be,{name:"terminal",size:14}),s.jsx("strong",{children:"Tools"}),s.jsxs("span",{children:[e.length," ",e.length===1?"call":"calls"]}),s.jsx("div",{}),n("running")?s.jsxs("span",{className:"pc-tool-group__running",children:[n("running")," running"]}):null,n("waiting")?s.jsxs("span",{className:"pc-tool-group__waiting",children:[n("waiting")," need approval"]}):null,n("failed")?s.jsxs("span",{className:"pc-tool-group__failed",children:[n("failed")," failed"]}):null,n("completed")?s.jsxs("span",{className:"pc-tool-group__completed",children:[n("completed")," done"]}):null]}),e.map(r=>s.jsx(Bb,{tool:r,showCopy:t},r.id))]})}const Hs="not reported",Er=e=>e===void 0?Hs:Math.round(e).toLocaleString(),qr=e=>{if(e===void 0)return Hs;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`},Wb=e=>e===void 0?Hs:`${Math.round(e).toLocaleString()} tok/s`,sC=(e,t)=>t>0?`${Math.round(e/t*100)}%`:"",mc=(e,t,n=`${t}s`)=>`${e.toLocaleString()} ${e===1?t:n}`,rC=e=>{const t=e.split("#")[0].replace(/\/+$/,"");return t.slice(t.lastIndexOf("/")+1)||e};function iC(e){const t=new Map;for(const n of e)n&&t.set(n,(t.get(n)||0)+1);return[...t].map(([n,r])=>r>1?`${n} ×${r}`:n).join(" · ")}function Gm(e){const t=[],n=(e.models||[]).map(rC),r=e.providers||[];return(n.length||r.length)&&t.push([n.join(", ")||"model not reported",r.join(", ")].filter(Boolean).join(" · ")),t.push("From the run ledger; summed across this turn and its child runs."),t}function oC(e){const t=e.modelCalls||[],n=[],r=[{label:"Input",value:Er(e.inputTokens)},{label:"Output",value:Er(e.outputTokens)}];if(e.reasoningTokens!==void 0&&r.push({label:"Reasoning",value:Er(e.reasoningTokens),hint:"part of output"}),r.push({label:"Total",value:Er(e.totalTokens)}),n.push({heading:`Usage · ${mc(e.llmCalls,"model call")}`,rows:r}),e.measuredCacheCalls){const l=e.cachedTokens||0,c=e.fedTokens||0,u=[{label:"Reused from cache",value:`${Er(l)}${l+c?` (${sC(l,l+c)})`:""}`},{label:"Newly processed",value:Er(e.fedTokens)},{label:"Outcome",value:iC(t.map(f=>f.cacheOutcome))||(e.cacheOutcomes||[]).join(" · ")||Hs},{label:"Backend",value:(e.cacheBackends||[]).join(", ")||Hs}];e.measuredCacheCalls!==e.llmCalls&&u.push({label:"Measured on",value:`${e.measuredCacheCalls} of ${e.llmCalls} calls`}),n.push({heading:"Prompt cache",rows:u})}else e.llmCalls&&n.push({heading:"Prompt cache",rows:[{label:"Cache reuse",value:Hs}]});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:`${Er(o[0].inputTokens)} tokens`}]}):o.length>1&&n.push({heading:"Context",rows:[{label:"First → last call",value:`${Er(o[0].inputTokens)} → ${Er(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,c)=>[String(c+1),Er(l.inputTokens),l.cachedTokens===void 0?"—":Er(l.cachedTokens),l.fedTokens===void 0?"—":Er(l.fedTokens),Er(l.outputTokens),l.cacheOutcome||"—"])}}),{kind:"tokens",title:"Tokens",headline:e.totalTokens===void 0?Hs:`${e.totalTokens.toLocaleString()} total`,sections:n,footer:Gm(e)}}function hm(e,t,n,r){if(e===void 0)return Hs;const o=[qr(e)];return t!==void 0&&o.push(`${t.toLocaleString()} ${r}${n!==void 0?` at ${Wb(n)}`:""}`),o.join(" · ")}function aC(e){var h,m,g;const t=e.modelCalls||[],n=[],r=e.durationMs,o=[{label:"Wall clock",value:qr(r)}];if(o.push({label:"Model",value:e.genTimeMs===void 0?Hs:`${qr(e.genTimeMs)} · ${mc(e.timedCalls||0,"call")}${e.timedCalls!==e.llmCalls?` (of ${e.llmCalls})`:""}`}),o.push({label:"Tools",value:e.toolTimeMs!==void 0?`${qr(e.toolTimeMs)} · ${mc(e.toolBatches||0,"batch","batches")}`:e.toolCalls?Hs:"none",hint:e.toolTimeIncludesApproval?"includes approval wait":void 0}),r!==void 0&&e.genTimeMs!==void 0){const y=r-e.genTimeMs-(e.toolTimeMs||0);o.push({label:"Orchestration",value:y>=0?qr(y):"overlaps (parallel runs)",hint:"wall − model − tools: routing, hand-offs, model load"})}n.push({heading:"Turn",rows:o});const l=[],c=e.ttftCalls||0,u=e.promptPhaseCalls||0;e.promptPhaseMs!==void 0?l.push({label:c&&c===u?"Prefill (TTFT)":"Prefill",value:hm(e.promptPhaseMs,e.promptPhaseNewTokens,e.promptPhaseTokensPerSecond,"new tok"),hint:c===u?"measured time to first token":c?`TTFT measured on ${c} of ${u}; rest from provider rate`:"derived: prompt ÷ provider rate"}):e.prefillMs!==void 0&&e.prefillNewTokensPerSecond!==void 0?l.push({label:"Prefill",value:hm(e.prefillMs,e.prefillNewTokens,e.prefillNewTokensPerSecond,"new tok"),hint:"derived: prompt ÷ provider rate"}):e.prefillMs!==void 0?l.push({label:"Prefill",value:`${qr(e.prefillMs)}${e.promptTokensPerSecond!==void 0?` at ${Wb(e.promptTokensPerSecond)}`:""}`,hint:"provider rate over all prompt tokens, restored included"}):l.push({label:"Prefill",value:Hs}),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?hm(e.generationPhaseMs,e.generationPhaseTokens,e.generationPhaseTokensPerSecond,"tok"):hm(e.decodeMs,e.outputTokens,e.generationTokensPerSecond,"tok")}),e.measuredSpeedCalls&&e.measuredSpeedCalls!==e.llmCalls&&l.push({label:"Speeds from",value:`${e.measuredSpeedCalls} of ${e.llmCalls} calls`}),n.push({heading:"Model",rows:l});const f=e.speculation;if(f){const y=(f.draftKinds||[]).map(k=>k.toUpperCase()).join(", "),w=[{label:"Mode",value:`${f.used?"on":"off"}${y?` · ${y}`:""}${(h=f.modes)!=null&&h.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?Hs:`${Math.round(f.acceptanceRate*100)}% · ${Er(f.acceptedTokens)} of ${Er(f.draftedTokens)} drafted`}];((m=f.draftLengths)!=null&&m.length||f.rounds!==void 0)&&w.push({label:"Draft length",value:`${(g=f.draftLengths)!=null&&g.length?`${f.draftLengths.join("/")} tok/round`:Hs}${f.rounds!==void 0?` · ${f.rounds.toLocaleString()} rounds`:""}`}),n.push({heading:"Speculation",rows:w})}return e.slowestToolBatch&&n.push({heading:"Tools",rows:[{label:"Total",value:`${qr(e.toolTimeMs)} · ${mc(e.toolBatches||0,"batch","batches")}`},{label:"Slowest",value:`${qr(e.slowestToolBatch.ms)} · ${qb(e.slowestToolBatch)}`}],note:e.toolTimeIncludesApproval?"Gated calls are timed from request to result, so this includes waiting for your approval.":void 0}),t.length>1&&n.push({heading:"Per call",table:{columns:["#","Prefill","New tok/s","Gen","Gen tok/s","Cache"],rows:t.map((y,w)=>[String(w+1),y.promptMs===void 0?"—":`${qr(y.promptMs)}${y.promptSource==="rate"?"*":""}`,y.promptNewTokensPerSecond===void 0?"—":Math.round(y.promptNewTokensPerSecond).toLocaleString(),y.generationMs===void 0?"—":qr(y.generationMs),y.generationTokensPerSecond===void 0?"—":Math.round(y.generationTokensPerSecond).toLocaleString(),y.cacheOutcome||"—"])},note:t.some(y=>y.promptSource==="rate")?"* derived from the provider's prompt rate (no TTFT event).":void 0}),{kind:"time",title:"Time",headline:r===void 0?Hs:`${qr(r)} wall clock`,sections:n,footer:Gm(e)}}function qb(e){return e.tools.length===1?`${e.tools[0]} ×${e.calls}`:`${mc(e.calls,"call")} (${e.tools.join(", ")})`}function lC(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:Gm(e)};const r=[{label:"Succeeded",value:(e.toolCalls-(e.toolsFailed||0)).toLocaleString()},{label:"Failed",value:(e.toolsFailed||0).toLocaleString()}];e.toolsRunning&&r.push({label:"Running",value:e.toolsRunning.toLocaleString()}),e.toolsWaiting&&r.push({label:"Awaiting approval",value:e.toolsWaiting.toLocaleString(),hint:"not run yet — not a failure"}),t.push({heading:"Outcome",rows:r});const o=Object.entries(e.toolBreakdown||{}).sort((u,f)=>f[1].calls-u[1].calls||u[0].localeCompare(f[0]));o.length&&t.push({heading:"By tool",table:{columns:["Tool","Calls","Failed","Time"],rows:o.map(([u,f])=>[u,f.calls.toLocaleString(),f.failed.toLocaleString(),f.ms!==void 0?`${qr(f.ms)}${f.sharedBatches?" +shared":""}`:f.sharedBatches?"shared":Hs])},note:o.some(([,u])=>u.sharedBatches)?"A batch that mixed tools ran them together; its time is not split between them.":void 0});const l=o.filter(([,u])=>u.errors&&Object.keys(u.errors).length);l.length&&t.push({heading:"Failures",rows:l.map(([u,f])=>({label:u,value:Object.entries(f.errors).sort((h,m)=>m[1]-h[1]).map(([h,m])=>m>1?`${h} ×${m}`:h).join(" · ")}))});const c=[{label:"Tool time",value:e.toolTimeMs===void 0?Hs:`${qr(e.toolTimeMs)} · ${mc(e.toolBatches||0,"batch","batches")}`}];return e.slowestToolBatch&&c.push({label:"Slowest batch",value:`${qr(e.slowestToolBatch.ms)} · ${qb(e.slowestToolBatch)}`}),t.push({heading:"Timing",rows:c,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:`${mc(e.toolCalls,"call")}${e.toolsFailed?` · ${e.toolsFailed} failed`:""}`,sections:t,footer:Gm(e)}}function dp(e,t){return e==="tokens"?oC(t):e==="time"?aC(t):lC(t)}function cC(e){const t=e.detail;return s.jsxs("div",{ref:e.panelRef,id:e.id,role:"tooltip",className:`pc-stat-detail pc-stat-detail--${t.kind}`,style:e.style,onMouseEnter:e.onMouseEnter,onMouseLeave:e.onMouseLeave,children:[s.jsxs("div",{className:"pc-stat-detail-head",children:[s.jsx("span",{className:"pc-stat-detail-title",children:t.title}),s.jsx("span",{className:"pc-stat-detail-headline",children:t.headline})]}),t.sections.map(n=>{var r;return s.jsxs("div",{className:"pc-stat-detail-section",children:[s.jsx("div",{className:"pc-stat-detail-heading",children:n.heading}),(r=n.rows)!=null&&r.length?s.jsx("dl",{className:"pc-stat-detail-rows",children:n.rows.map(o=>s.jsxs(xe.Fragment,{children:[s.jsx("dt",{children:o.label}),s.jsxs("dd",{children:[s.jsx("span",{className:o.value===Hs?"pc-stat-detail-value pc-stat-detail-value--absent":"pc-stat-detail-value",children:o.value}),o.hint?s.jsx("span",{className:"pc-stat-detail-hint",children:o.hint}):null]})]},o.label))}):null,n.table?s.jsxs("table",{className:"pc-stat-detail-table",children:[s.jsx("thead",{children:s.jsx("tr",{children:n.table.columns.map(o=>s.jsx("th",{scope:"col",children:o},o))})}),s.jsx("tbody",{children:n.table.rows.map((o,l)=>s.jsx("tr",{children:o.map((c,u)=>s.jsx("td",{children:c},u))},l))})]}):null,n.note?s.jsx("p",{className:"pc-stat-detail-note",children:n.note}):null]},n.heading)}),s.jsx("div",{className:"pc-stat-detail-foot",children:t.footer.map(n=>s.jsx("div",{children:n},n))})]})}const ca=8;function uC(e){const[t,n]=_.useState(!!e.defaultOpen),[r,o]=_.useState(null),l=_.useRef(null),c=_.useRef(null),u=_.useRef(null),f=`pc-stat-${_.useId().replace(/[^a-zA-Z0-9_-]/g,"")}`,h=_.useCallback(()=>{u.current!==null&&window.clearTimeout(u.current),u.current=null},[]),m=_.useCallback(()=>{h(),n(!0)},[h]),g=_.useCallback(()=>{h(),u.current=window.setTimeout(()=>n(!1),120)},[h]);_.useEffect(()=>h,[h]),_.useLayoutEffect(()=>{if(!t){o(null);return}const b=()=>{const S=l.current,N=c.current;if(!S||!N)return;const R=S.getBoundingClientRect(),T=N.offsetWidth,A=N.offsetHeight,W=window.innerWidth,z=window.innerHeight,J=R.top-ca-A,K=R.bottom+ca,re=J>=ca?J:K+A<=z-ca?K:Math.max(ca,z-ca-A),te=Math.min(Math.max(ca,R.left),Math.max(ca,W-ca-T));o({top:re,left:te})};return b(),window.addEventListener("resize",b),window.addEventListener("scroll",b,!0),()=>{window.removeEventListener("resize",b),window.removeEventListener("scroll",b,!0)}},[t]),_.useEffect(()=>{if(!t)return;const b=S=>{S.key==="Escape"&&n(!1)};return document.addEventListener("keydown",b),()=>document.removeEventListener("keydown",b)},[t]);const y=typeof e.onClick=="function",w=y?"button":"span",k=t?s.jsx(cC,{detail:e.detail,id:f,panelRef:c,onMouseEnter:h,onMouseLeave:g,style:{position:"fixed",top:(r==null?void 0:r.top)??0,left:(r==null?void 0:r.left)??0,visibility:r?"visible":"hidden"}}):null;return s.jsxs(s.Fragment,{children:[s.jsxs(w,{ref:l,...y?{type:"button"}:{tabIndex:0},className:["pc-chat-stat","pc-chat-stat--detail",y?"pc-chat-stat--clickable":"",e.className].filter(Boolean).join(" "),"aria-label":`${e.label} — ${e.detail.title.toLowerCase()} details`,"aria-describedby":t?f:void 0,"data-stat-kind":e.detail.kind,onMouseEnter:m,onMouseLeave:g,onFocus:m,onBlur:()=>n(!1),onKeyDown:b=>{b.key==="Escape"&&n(!1)},onClick:y?()=>{var b;return(b=e.onClick)==null?void 0:b.call(e)}:void 0,children:[e.icon?s.jsx("span",{className:"pc-chat-stat-icon","aria-hidden":"true",children:e.icon}):null,s.jsx("span",{className:"pc-chat-stat-label",children:e.label})]}),k&&typeof document<"u"?Dx.createPortal(k,document.body):k]})}function dC(e){const t=e.totalTokens!==void 0?dp("tokens",e):null,n=dp("tools",e),r=e.durationMs!==void 0?dp("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(`
|
|
74
|
-
`)}]:[],...r?[{label:`${(e.durationMs/1e3).toFixed(e.durationMs<1e4?1:0)}s`,detail:r}]:[]]}function fC(e){const t=String(e.role||"").trim().toLowerCase()||"system",n=String(e.kind||"").trim().toLowerCase(),r=String(e.level||"").trim().toLowerCase();return t==="system"&&n==="report_bug"?{label:String(e.title||"").trim()||"Bug report",icon:"warning",variant:"report_bug"}:t==="system"&&n==="report_feature"?{label:String(e.title||"").trim()||"Feature request",icon:"check",variant:"report_feature"}:t==="user"?{label:String(e.title||"").trim()||"You",icon:"user",variant:"user"}:t==="assistant"?{label:String(e.title||"").trim()||"Agent",icon:"bot",variant:"assistant"}:{label:String(e.title||"").trim()||(r==="error"?"Error":r==="warn"?"Warning":"System"),icon:r==="error"?"error":r==="warn"?"warning":"info",variant:r==="error"?"error":r==="warn"?"warn":"status"}}const hC=new Set(["blob:","data:","http:","https:"]);function Fw(e){const t=String(e||"").trim();if(t)try{const n=typeof window<"u"&&window.location?window.location.href:"http://same-origin.invalid/";return hC.has(new URL(t,n).protocol)?t:void 0}catch{return}}function mC({item:e}){const[t,n]=_.useState(!1),r=Fw(e.src),o=e.href?Fw(e.href):void 0,l=e.kind==="image"||e.kind==="audio"||e.kind==="video"?e.kind:null;if(!l||!r&&!o)return null;const c=l==="image"?"Image":l==="video"?"Video":"Audio",u=String(e.label||"").trim()||`Generated ${c.toLowerCase()}`,f=()=>n(!0);return s.jsxs("figure",{className:`pc-chat-media__item pc-chat-media__item--${l}`,children:[r&&l==="image"?s.jsx("img",{className:"pc-chat-media__image",src:r,alt:u,loading:"lazy",onError:f}):null,r&&l==="video"?s.jsx("video",{className:"pc-chat-media__video",src:r,controls:!0,playsInline:!0,preload:"metadata","aria-label":u,onError:f}):null,r&&l==="audio"?s.jsx(p_,{className:"pc-chat-media__audio",src:r,name:u}):null,t?s.jsxs("div",{className:"pc-chat-media__error",role:"note",children:[c," could not be decoded by this browser",o?"; open the raw file with the link.":"."]}):null,o?s.jsx("figcaption",{className:"pc-chat-media__caption",children:s.jsx("a",{className:"pc-chat-media__link",href:o,target:"_blank",rel:"noopener noreferrer",children:u})}):null]})}function ny(e){var W;const t=e.message,n=_.useMemo(()=>fC(t),[t.kind,t.level,t.role,t.title]),r=String(t.ts||"").trim(),o=_.useMemo(()=>{if(!r)return"";const z=new Date(r);return Number.isFinite(z.getTime())?z.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):""},[r]),[l,c]=_.useState("idle"),u=_.useRef(null);_.useEffect(()=>()=>{u.current!==null&&window.clearTimeout(u.current)},[]);const f=t.live,h=!f&&typeof e.onSpeakToggle=="function"&&n.variant==="assistant"&&!!String(t.content||"").trim(),m=h&&((W=e.getSpeakState)==null?void 0:W.call(e,t))||"idle",g=m==="loading"?"loader":m==="playing"?"pause":"speaker",y=m==="loading"?"Generating audio…":m==="playing"?"Pause":m==="paused"?"Resume":"Speak (TTS)",w=e.showCopy!==!1,k=Array.isArray(e.attachments)?e.attachments:Array.isArray(t.attachments)?t.attachments:[],b=t.statistics,S=t.stats,N=_.useMemo(()=>Array.isArray(e.stats)?e.stats:Array.isArray(S)?S:b?dC(b):[],[e.stats,S,b]),R=Array.isArray(t.media)?t.media:[],T=String(f?f.reasoning||"":t.reasoning||""),A=!!String(t.content||"").trim();return t.toolActivity?s.jsx(Bb,{tool:t.toolActivity,showCopy:e.showCopy}):s.jsxs("div",{className:["pc-chat-item",`pc-chat-item--${n.variant}`,f?"pc-chat-item--live":"",e.className].filter(Boolean).join(" "),...f?{"aria-busy":!0}:{},children:[s.jsxs("div",{className:"pc-chat-header",children:[s.jsx("div",{className:"pc-chat-avatar","aria-hidden":"true",children:s.jsx(Be,{name:n.icon,size:14})}),s.jsx("span",{className:"pc-chat-role",children:n.label}),f?s.jsxs("span",{className:"pc-chat-live-indicator",title:f.label?`Pending: ${f.label}`:"The reply is still being written",children:[s.jsx("span",{className:"pc-chat-live-dot","aria-hidden":"true"}),f.label||"streaming"]}):null,f!=null&&f.caption?s.jsx("span",{className:"pc-chat-live-caption",children:f.caption}):null,s.jsx("span",{className:"pc-chat-header-spacer"}),o?s.jsx("span",{className:"pc-chat-time",children:o}):null,s.jsxs("div",{className:"pc-chat-header-actions",children:[h?s.jsx("button",{className:"pc-chat-icon-btn",type:"button","aria-label":y,title:y,onClick:()=>{var z;return(z=e.onSpeakToggle)==null?void 0:z.call(e,t)},children:s.jsx(Be,{name:g,size:22,className:m==="loading"?"pc-chat-speak-spinner":void 0})}):null,w?s.jsx("button",{className:`pc-chat-icon-btn ${l!=="idle"?`pc-chat-icon-btn--${l}`:""}`.trim(),type:"button","aria-label":"Copy message",title:l==="idle"?"Copy":l==="copied"?"Copied":"Copy failed",onClick:async()=>{const z=await gl(String(t.content||""));c(z?"copied":"failed"),u.current!==null&&window.clearTimeout(u.current),u.current=window.setTimeout(()=>c("idle"),900)},children:s.jsx(Be,{name:"copy",size:22})}):null]})]}),T.trim()?s.jsxs("details",{className:"pc-chat-thinking",children:[s.jsx("summary",{children:"Thinking"}),s.jsx("div",{className:"pc-chat-thinking-body",children:T})]}):null,A||!f&&!R.length?s.jsx("div",{className:"pc-chat-body",children:s.jsx(Db,{text:String(t.content||""),renderMarkdown:e.renderMarkdown,jsonCollapseAfterDepth:e.jsonCollapseAfterDepth,images:e.images||(n.variant==="user"?"inline":"link"),inlineImage:e.inlineImage})}):null,R.length?s.jsx("div",{className:"pc-chat-media",children:R.slice(0,24).map((z,J)=>s.jsx(mC,{item:z},z.id||`${z.kind}:${z.src}:${J}`))}):null,k.length?s.jsx("div",{className:"pc-chat-attachments","aria-label":"Attachments",children:k.slice(0,24).map((z,J)=>{const K=String(z.label||"").trim()||"attachment",re=String(z.target||"").trim(),te=String(z.title||"").trim(),Q=!!z.disabled||typeof z.onClick!="function";return s.jsxs("button",{type:"button",className:"pc-chat-attachment-chip",title:te||K,onClick:Q?void 0:z.onClick,disabled:Q,children:[s.jsx(Be,{name:"paperclip",size:14}),re?s.jsx("span",{className:`pc-chat-attachment-target pc-chat-attachment-target--${re}`,children:re}):null,s.jsx("span",{className:"pc-chat-attachment-name",children:K})]},z.id||`${K}:${J}`)})}):null,N.length?s.jsx("div",{className:"pc-chat-stats","aria-label":"Stats",children:N.slice(0,12).map((z,J)=>{const K=String(z.label||"").trim();if(!K)return null;if(z.detail)return s.jsx(uC,{label:K,detail:z.detail,icon:z.icon,onClick:z.onClick},z.id||`${K}:${J}`);const re=String(z.title||"").trim(),te=typeof z.onClick=="function",Q=te?"button":"span";return s.jsxs(Q,{...te?{type:"button"}:{},className:["pc-chat-stat",te?"pc-chat-stat--clickable":""].filter(Boolean).join(" "),title:re||void 0,onClick:te?()=>{var D;return(D=z.onClick)==null?void 0:D.call(z)}:void 0,children:[z.icon?s.jsx("span",{className:"pc-chat-stat-icon","aria-hidden":"true",children:z.icon}):null,s.jsx("span",{className:"pc-chat-stat-label",children:K})]},z.id||`${K}:${J}`)})}):null]})}function _C(e,t){const n=Math.max(0,Math.trunc(t));return e.scrollHeight-e.scrollTop-e.clientHeight<=n}function sy(e){const t=typeof e.autoScrollThresholdPx=="number"&&Number.isFinite(e.autoScrollThresholdPx)?e.autoScrollThresholdPx:120,n=e.autoScroll!==!1,r=_.useRef(null),o=_.useRef(null),[l,c]=_.useState(!0),u=_.useMemo(()=>Array.isArray(e.messages)?e.messages:[],[e.messages]),f=_.useMemo(()=>{var g;const m=[];for(const y of u){const w=m[m.length-1];y.toolActivity&&((g=w==null?void 0:w[0])!=null&&g.toolActivity)&&w[0].runId===y.runId?w.push(y):m.push([y])}return m},[u]);_.useEffect(()=>{if(!n)return;const m=r.current;if(!m)return;const g=()=>{c(_C(m,t))};return m.addEventListener("scroll",g,{passive:!0}),g(),()=>m.removeEventListener("scroll",g)},[n,t]);const h=_.useMemo(()=>{let m=0;for(const g of u)if(m+=String(g.content??"").length,Array.isArray(g.media))for(const y of g.media)m+=String((y==null?void 0:y.src)??"").length+1;return`${u.length}:${m}:${String(e.afterKey??"")}`},[u,e.afterKey]);return _.useEffect(()=>{if(!n||!l)return;const m=r.current;m&&(m.scrollTop=m.scrollHeight)},[n,l,h]),_.useEffect(()=>{if(!n)return;const m=r.current;if(!m)return;const g=()=>{l&&(m.scrollTop=m.scrollHeight)};return m.addEventListener("load",g,!0),m.addEventListener("loadedmetadata",g,!0),()=>{m.removeEventListener("load",g,!0),m.removeEventListener("loadedmetadata",g,!0)}},[n,l]),s.jsxs("div",{ref:r,className:["pc-chat-thread",e.className].filter(Boolean).join(" "),children:[u.length?null:e.empty||null,f.map((m,g)=>{var k;const y=m[0],w=String(y.id||"")||String(y.ts||"")+":"+String(y.role||"")+":"+g;return y.toolActivity?s.jsx(Ub,{tools:m.map(b=>b.toolActivity),showCopy:(k=e.messageProps)==null?void 0:k.showCopy},w):s.jsx(ny,{message:y,...e.messageProps||{}},w)}),e.after,s.jsx("div",{ref:o})]})}const ry=xe.forwardRef(function(t,n){const r=typeof t.rows=="number"&&Number.isFinite(t.rows)?Math.max(1,Math.trunc(t.rows)):3,o=!!t.disabled,l=!!t.busy,c=!o&&!l&&!!String(t.value||"").trim();return s.jsxs("div",{className:["pc-composer",t.className].filter(Boolean).join(" "),children:[t.leading,s.jsx("textarea",{ref:n,className:["pc-composer__textarea",t.textareaClassName].filter(Boolean).join(" "),value:t.value,onChange:u=>t.onChange(u.target.value),rows:r,style:{"--pc-composer-rows":String(r)},spellCheck:!1,autoCorrect:"off",autoCapitalize:"off",autoComplete:"off",placeholder:t.placeholder||"","aria-label":t.ariaLabel||t.placeholder||"Message",disabled:o,autoFocus:!!t.autoFocus,onPaste:t.onPaste,onKeyDown:u=>{u.key!=="Enter"||u.shiftKey||u.nativeEvent.isComposing||u.keyCode===229||(u.preventDefault(),c&&t.onSubmit())}}),s.jsxs("div",{className:"pc-composer__row",children:[s.jsx("div",{className:"pc-composer__actions",children:t.actions}),s.jsx("button",{type:"button",className:t.sendButtonClassName||"pc-btn",disabled:!c,onClick:()=>t.onSubmit(),children:l?t.busyLabel||"Thinking…":t.sendLabel||"Send"})]}),t.overlay]})});function vf(e){if(!e)return!1;for(let t=0;t<e.length;t+=1)if(e[t]==="Files")return!0;return!1}function zw(e){var r;const t=e==null?void 0:e.items;if(!t||!t.length)return null;let n=0;for(let o=0;o<t.length;o+=1)((r=t[o])==null?void 0:r.kind)==="file"&&(n+=1);return n>0?n:null}function Bw(e){return e===1?"Drop file to attach":typeof e=="number"&&e>1?`Drop ${e} files to attach`:"Drop files to attach"}function iy(e){const t=[],n=[],r=e==null?void 0:e.items;if(r&&r.length){for(let l=0;l<r.length;l+=1){const c=r[l];if(!c||c.kind!=="file")continue;const u=typeof c.webkitGetAsEntry=="function"?c.webkitGetAsEntry():null,f=typeof c.getAsFile=="function"?c.getAsFile():null;u!=null&&u.isDirectory?n.push(u.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 Hb(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 pC={"image/png":"png","image/jpeg":"jpg","image/gif":"gif","image/webp":"webp","image/heic":"heic","image/tiff":"tiff","image/bmp":"bmp"};function ef(e){return String(e).padStart(2,"0")}function gC(e,t,n){const r=String(e||"").trim();if(r&&!/^image\.(png|jpe?g|gif|webp|heic|tiff?|bmp)$/i.test(r))return r;const o=pC[String(t||"").toLowerCase()]||r.split(".").pop()||"bin",l=`${n.getFullYear()}-${ef(n.getMonth()+1)}-${ef(n.getDate())} at ${ef(n.getHours())}.${ef(n.getMinutes())}.${ef(n.getSeconds())}`;return`${String(t||"").startsWith("image/")||!r?"Pasted image":"Pasted file"} ${l}.${o}`}function Vb(e,t=new Date){if(!e)return[];const n=e.types?Array.from(e.types):[];if(n.includes("text/plain")&&n.includes("text/html"))return[];const{files:r}=iy(e);return r.map(o=>{const l=gC(o.name,o.type,t);return l===o.name?o:new File([o],l,{type:o.type,lastModified:o.lastModified})})}class yC{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}}const xf="llm.delta",Cu="llm.delta_end";function wC(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function sc(e){return typeof e=="string"&&e.trim()!==""}function vC(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0}function Gb(e){return"reason"in e}function Kb(e,t){const n=wC(e),r=n==null?void 0:n.kind,o=t||(typeof r=="string"&&r?r:n&&"reason"in n?Cu:xf),l=f=>{throw new Error(`Malformed ${o} event from the gateway: ${f}`)};if(t!==void 0&&t!==xf&&t!==Cu&&l(`unknown event name ${JSON.stringify(t)}`),!n)return l("the payload is not an object");r!==void 0&&r!==xf&&r!==Cu&&l(`unknown kind ${JSON.stringify(r)}`),r!==void 0&&t!==void 0&&r!==t&&l(`kind ${JSON.stringify(r)} does not match the event name`),sc(n.run_id)||l("run_id is missing"),sc(n.call_id)||l("call_id is missing"),vC(n.seq)||l("seq is not a non-negative integer");const c=t||r?(t||r)===Cu:"reason"in n;n.root_run_id!==void 0&&!sc(n.root_run_id)&&l("root_run_id is not a run id"),n.parent_run_id!==void 0&&n.parent_run_id!==null&&!sc(n.parent_run_id)&&l("parent_run_id is neither a run id nor null");const u={run_id:n.run_id,...sc(n.root_run_id)?{root_run_id:n.root_run_id}:{},...n.parent_run_id!==void 0?{parent_run_id:n.parent_run_id}:{},...sc(n.node_id)?{node_id:n.node_id}:{},call_id:n.call_id,seq:n.seq};return c?(["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:Cu,...u,reason:n.reason,...sc(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:xf,...u,text:n.text,channel:n.channel,snapshot:n.snapshot})}function xC(e,t){if(e!==xf&&e!==Cu)return null;let n=t;if(typeof t=="string")try{n=JSON.parse(t)}catch{throw new Error(`Malformed ${e} event from the gateway: data is not JSON`)}return Kb(n,e)}const bC={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 kC(e){return`This reply is not streamed: ${e?bC[e]||`the gateway reported "${e}"`:"the gateway gave no reason"}. It appears when it is complete.`}const Uw=1024*1024,jC="1 MiB",SC=25*1024*1024,Yb=(e,t)=>`${it(`runs/${encodeURIComponent(e)}/workspace`)}/content?${new URLSearchParams({path:t})}`;function NC(e){const t=e.headers.get("content-range"),n=t?Number(t.split("/")[1]):NaN;if(Number.isFinite(n))return n;const r=Number(e.headers.get("content-length"));return e.status===200&&Number.isFinite(r)&&e.headers.has("content-length")?r:void 0}async function CC(e,t,n){var h;const r=new TextDecoder;let o="",l=0;const c=(h=e.body)==null?void 0:h.getReader();if(c){for(;l<t;){const{done:m,value:g}=await c.read();if(m)break;const y=g.subarray(0,t-l);l+=y.length,o+=r.decode(y,{stream:!0})}await c.cancel().catch(()=>{})}else o=(await e.text()).slice(0,t),l=o.length;const u=NC(e)??n,f=u!==void 0?u>l:l>=t;return{text:o,received:l,total:u,partial:f}}function EC(e){return`Showing the first ${jC} of ${e!==void 0?ty(e):"a file of unknown size"}; download for the rest.`}function $C(e){try{return decodeURIComponent(e)}catch{return e}}function AC(e,t,n){const r=`${it(`runs/${encodeURIComponent(t)}/workspace`)}/content?`,o=n.split("/").slice(0,-1),l=f=>{if(/^[a-z][a-z0-9+.-]*:/i.test(f)||f.startsWith("/")||f.startsWith("#"))return null;const h=[...o];for(const m of f.split(/[?#]/,1)[0].split("/"))if(!(!m||m==="."))if(m===".."){if(!h.length)return null;h.pop()}else h.push($C(m));return h.length?Yb(t,h.join("/")):null},c=f=>{let h="",m=0;for(;m<f.length;){if(f[m]==="!"&&f[m+1]==="["){const g=f.indexOf("]",m+2);if(g!==-1&&f[g+1]==="("){const y=f.indexOf(")",g+2);if(y!==-1){const w=f.slice(m+2,g),k=f.slice(g+2,y).trim(),b=k.startsWith(r)?k:l(k);h+=b?``:`[image: ${w||k}](${k})`,m=y+1;continue}}}h+=f[m],m+=1}return h};let u=!1;return e.split(`
|
|
75
|
-
`).map(f=>/^\s*(```|~~~)/.test(f)?(u=!u,f):u?f:c(f)).join(`
|
|
76
|
-
`)}function TC(e,t,n,r){const[o,l]=_.useState({status:"idle"});return _.useEffect(()=>{if(!n||!t){l({status:"idle"});return}const c=new AbortController;let u="";const f=ug(n.name);if(f==="binary"){l({status:"ready",kind:"binary",contentType:"",partial:!1});return}if((f==="image"||f==="audio"||f==="pdf")&&typeof n.size_bytes=="number"&&n.size_bytes>SC){l({status:"error",kind:f,message:`Too large to preview (${ty(n.size_bytes)}); use Download.`});return}l({status:"loading",kind:f});const h=Sw(f);return(async()=>{var m;try{const g=await e(Yb(t,n.path),{signal:c.signal,...h?{headers:{Range:`bytes=0-${Uw-1}`}}:{}});if(!g.ok)throw new Error(`Preview failed (HTTP ${g.status}): ${await g.text().catch(()=>"")||g.statusText||"no reason given"}`);const y=g.headers.get("content-type")||"",w=ug(n.name,y);if(Sw(w)){const k=await CC(g,Uw,n.size_bytes);if(c.signal.aborted)return;l({status:"ready",kind:w,contentType:y,text:w==="markdown"?AC(k.text,t,n.path):k.text,partial:k.partial,total:k.total});return}if(w==="image"||w==="audio"||w==="pdf"){const k=await g.blob();if(c.signal.aborted)return;u=URL.createObjectURL(k.type?k:new Blob([k],{type:w==="pdf"?"application/pdf":y})),l({status:"ready",kind:w,contentType:y,url:u,partial:!1});return}await((m=g.body)==null?void 0:m.cancel().catch(()=>{})),c.signal.aborted||l({status:"ready",kind:"binary",contentType:y,partial:!1})}catch(g){c.signal.aborted||l({status:"error",kind:f,message:String((g==null?void 0:g.message)||g)})}})(),()=>{c.abort(),u&&URL.revokeObjectURL(u)}},[e,t,n==null?void 0:n.path,n==null?void 0:n.name,n==null?void 0:n.size_bytes,r]),o}function MC(e){return s.jsx(o2,{...e,nowMs:e.nowMs??Date.now(),renderMarkdown:t=>s.jsx(Si,{text:t})})}function RC(e){return e.status==="idle"||e.status==="loading"?{status:"loading",...e.status==="loading"?{kind:e.kind}:{}}:e.status==="error"?{status:"error",error:e.message,kind:e.kind}:{status:"ready",kind:e.kind,contentType:e.contentType,...e.text!==void 0?{text:e.text}:{},...e.url?{url:e.url}:{},...e.partial?{partialNote:EC(e.total)}:{}}}const oy=e=>it(`runs/${encodeURIComponent(e)}/workspace`);function LC(e){return oy(e)}function IC(e,t){return`${oy(e)}/files?${new URLSearchParams({path:t,recursive:"false"})}`}function OC(e,t){return`${oy(e)}/content?${new URLSearchParams({path:t})}`}async function Gu(e,t){let n="";try{const r=await e.text();try{const o=JSON.parse(r),l=(o==null?void 0:o.detail)??(o==null?void 0:o.error)??(o==null?void 0:o.message);n=typeof l=="string"?l:l&&typeof l.message=="string"?l.message:r}catch{n=r}}catch{n=""}return new Error(`${t} (HTTP ${e.status}): ${n.trim()||e.statusText||"no reason given"}`)}function PC(e,t){const n=e&&typeof e=="object"&&!Array.isArray(e)?e:null,r=c=>{throw new Error(`Unexpected /workspace/files response from the gateway: ${c}.`)};if(!n)return r("not an object");Array.isArray(n.entries)||r("no `entries` list"),typeof n.truncated!="boolean"&&r("no `truncated` flag");const o=n.entries.map((c,u)=>{const f=c&&typeof c=="object"?c:{};return(typeof f.name!="string"||typeof f.path!="string"||f.type!=="file"&&f.type!=="dir")&&r(`entry ${u+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 DC(e,t,n){const r=await e(LC(t),{signal:n});if(!r.ok)throw await Gu(r,"The workspace is not available");const o=await r.json();if(!o||typeof o.workspace_root!="string"||typeof o.exists!="boolean")throw new Error("Unexpected /workspace response from the gateway: no `workspace_root` / `exists`.");return o}async function FC(e,t,n,r){const o=await e(IC(t,n),{signal:r});if(!o.ok)throw await Gu(o,"The folder could not be listed");return PC(await o.json(),n)}async function zC(e,t,n,r){const o=await e(OC(t,n),{signal:r});if(!o.ok)throw await Gu(o,"The file could not be read");return await o.blob()}async function BC(e,t,n,r){const o=await DC(e,t,r);return{where:o,listing:o.exists?await FC(e,t,n,r):null}}function UC(e){const t=String(e||"").split("/").filter(Boolean),n=[{label:"Workspace",path:""}];return t.forEach((r,o)=>n.push({label:r,path:t.slice(0,o+1).join("/")})),n}function WC(e){if(typeof e!="number"||!Number.isFinite(e)||e<0)return"";if(e<1024)return`${e} B`;const t=["KiB","MiB","GiB","TiB"];let n=e/1024,r=0;for(;n>=1024&&r<t.length-1;)n/=1024,r+=1;return`${n<10?n.toFixed(1):Math.round(n)} ${t[r]}`}function qC(e){return[...e].sort((t,n)=>t.type===n.type?t.name.localeCompare(n.name):t.type==="dir"?-1:1)}function HC(e){const t=e.hidden||{},n=Number(t.blocked||0)+Number(t.outside_links||0)+Number(t.other||0),r=[];return n>0&&r.push(`${n} ${n===1?"entry":"entries"} hidden by the gateway's workspace rules`),e.truncated&&r.push("the list is truncated"),r.join("; ")}const VC=new Set(["image/png","image/jpeg","image/gif","image/webp","image/avif","image/bmp","application/pdf","text/plain","application/json"]);function GC(e){const t=String(e||"").split(";",1)[0].trim().toLowerCase();return VC.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 Jb(e,t,n){const r=n==="open"?GC(e.type):{mode:"download"},o=r.mode==="open"&&r.type!==e.type?new Blob([e],{type:r.type}):e,l=URL.createObjectURL(o);if(r.mode==="open")window.open(l,"_blank","noopener");else{const c=document.createElement("a");c.href=l,c.download=t,document.body.appendChild(c),c.click(),c.remove()}window.setTimeout(()=>URL.revokeObjectURL(l),6e4)}async function KC(e,t,n){const r=await e(pS(t),{signal:n.signal});if(!r.ok)throw await Gu(r,`${n.name} could not be read`);Jb(await r.blob(),n.name,n.mode??"open")}function YC(e){const t=String(e||"").split(/[\\/]/).filter(Boolean);return t.length?t[t.length-1]:String(e||"")}function JC(e){var t;return!!(e&&e.open_supported===!0&&((t=e.host)==null?void 0:t.caller_is_this_machine)===!0&&e.exists)}async function XC(e){try{return await navigator.clipboard.writeText(e),!0}catch{return!1}}function Xb(e){var D;const{fetchGateway:t,runId:n}=e,[r,o]=_.useState({runId:n,path:""}),l=r.runId===n?r.path:"",[c,u]=_.useState(null),[f,h]=_.useState(""),[m,g]=_.useState(""),[y,w]=_.useState(!!n),[k,b]=_.useState(""),[S,N]=_.useState(!1),[R,T]=_.useState(0),[A,W]=_.useState(null),z=A&&A.runId===n&&!e.onSelectFile?A.entry:null,J=TC(t,n,z,`${e.refreshKey??""}:${R}`);_.useEffect(()=>{if(!n)return;const $=new AbortController;return w(!0),h(""),(async()=>{try{const E=await BC(t,n,l,$.signal);$.signal.aborted||u({runId:n,...E})}catch(E){$.signal.aborted||h(String((E==null?void 0:E.message)||E))}finally{$.signal.aborted||w(!1)}})(),()=>$.abort()},[t,n,l,R,e.refreshKey]),_.useEffect(()=>g(""),[n]);const K=c&&c.runId===n?c:null,re=_.useCallback(async $=>{b($.path),h("");try{Jb(await zC(t,n,$.path),$.name,"download")}catch(E){h(String((E==null?void 0:E.message)||E))}finally{b("")}},[t,n]),te=(K==null?void 0:K.where.workspace_root)||"",Q=e.nowMs??Date.now();return s.jsx(ZC,{title:e.title,note:e.note,where:(K==null?void 0:K.where)??null,path:l,listing:(K==null?void 0:K.listing)??null,error:f,notice:m,loading:y,fileBusy:k,selectedPath:e.onSelectFile?e.selectedPath:z==null?void 0:z.path,className:e.className,nowMs:Q,openingFolder:S,onNavigate:$=>{W(null),o({runId:n,path:$})},onRefresh:()=>T($=>$+1),onFile:$=>void re($),onSelectFile:e.onSelectFile??($=>W({runId:n,entry:$})),onClose:e.onClose,onCopyPath:te?()=>{(e.copyText||XC)(te).then($=>g($?"Path copied.":"Could not copy; select the path instead."))}:void 0,onOpenFolder:e.onOpenFolder&&JC(K==null?void 0:K.where)?()=>{N(!0),g(""),e.onOpenFolder().then(()=>g("Folder opened on this machine.")).catch($=>g(`Open folder failed: ${String(($==null?void 0:$.message)||$)}`)).finally(()=>N(!1))}:void 0,preview:z?s.jsx(MC,{name:z.name,path:z.path,sizeBytes:z.size_bytes,modified:z.mtime,nowMs:Q,...RC(J),actions:(D=e.fileActions)==null?void 0:D.call(e,z),onDownload:()=>void re(z),onClose:()=>W(null)}):null})}function ZC(e){var l,c,u,f;const t=e.listing?HC(e.listing):"",n=(c=(l=e.where)==null?void 0:l.host)==null?void 0:c.hostname,r=((u=e.where)==null?void 0:u.workspace_root)||"",o=e.nowMs??Date.now();return s.jsxs("section",{className:`pc-ws${e.className?` ${e.className}`:""}`,"aria-label":e.title,"data-workspace-root":r||void 0,children:[s.jsxs("header",{className:"pc-ws__head",children:[s.jsxs("span",{className:"pc-ws__title",children:[s.jsx(Be,{name:"folder",size:15})," ",e.title]}),s.jsx("span",{className:"pc-ws__spacer"}),s.jsx("button",{type:"button",className:"pc-ws__icon-btn","data-action":"refresh-folder",onClick:e.onRefresh,disabled:e.loading,title:"Refresh","aria-label":"Refresh the folder",children:s.jsx(Be,{name:"refresh",size:14})}),e.onClose?s.jsx("button",{type:"button",className:"pc-ws__icon-btn","data-action":"close-folder",onClick:e.onClose,title:"Close","aria-label":"Close the file browser",children:s.jsx(Be,{name:"x",size:14})}):null]}),e.where?s.jsxs("div",{className:"pc-ws__root",children:[s.jsx("span",{className:"pc-ws__root-name",title:r,"data-root-name":"true",children:YC(r)}),e.onOpenFolder?s.jsx("button",{type:"button",className:"pc-ws__icon-btn pc-ws__icon-btn--bare","data-action":"open-folder",onClick:e.onOpenFolder,disabled:e.openingFolder,title:"Open folder","aria-label":"Open the folder on this machine",children:s.jsx(Be,{name:"folder",size:14})}):null,e.onCopyPath?s.jsx("button",{type:"button",className:"pc-ws__icon-btn pc-ws__icon-btn--bare","data-action":"copy-path",onClick:e.onCopyPath,title:"Copy path","aria-label":"Copy the folder path",children:s.jsx(Be,{name:"copy",size:14})}):null,n&&((f=e.where.host)==null?void 0:f.caller_is_this_machine)!==!0?s.jsxs("span",{className:"pc-ws__muted",children:[" on ",n]}):null]}):null,e.note?s.jsx("div",{className:"pc-ws__muted",children:e.note}):null,e.notice?s.jsx("div",{className:"pc-ws__muted",role:"status",children:e.notice}):null,e.error?s.jsx("div",{className:"pc-ws__error",role:"alert",children:e.error}):null,e.preview?s.jsx("div",{className:"pc-ws__preview",children:e.preview}):s.jsxs(s.Fragment,{children:[s.jsx("nav",{className:"pc-ws__crumbs","aria-label":"Folder",children:UC(e.path).map((h,m,g)=>m===g.length-1?s.jsx("span",{"aria-current":"page",children:h.label},h.path):s.jsxs(xe.Fragment,{children:[s.jsx("button",{type:"button",className:"pc-ws__crumb",onClick:()=>e.onNavigate(h.path),children:h.label}),s.jsx("span",{className:"pc-ws__muted",children:" / "})]},h.path))}),e.loading&&!e.listing?s.jsx("div",{className:"pc-ws__muted",role:"status",children:"Loading…"}):null,e.where&&!e.where.exists?s.jsx("div",{className:"pc-ws__muted",children:"The folder does not exist yet: nothing has been written."}):null,e.listing?e.listing.entries.length?s.jsx("ul",{className:"pc-ws__entries",children:qC(e.listing.entries).map(h=>s.jsx("li",{className:`pc-ws__entry${e.selectedPath===h.path?" is-selected":""}`,"data-type":h.type,"data-path":h.path,children:h.type==="dir"?s.jsxs("button",{type:"button",className:"pc-ws__name","data-action":"open-dir",onClick:()=>e.onNavigate(h.path),children:[s.jsx(Be,{name:"folder",size:14})," ",s.jsxs("span",{className:"pc-ws__label",children:[h.name,"/"]})]}):s.jsxs(s.Fragment,{children:[e.onSelectFile?s.jsxs("button",{type:"button",className:"pc-ws__name","data-action":"select-file","aria-pressed":e.selectedPath===h.path,title:`Preview ${h.name}`,onClick:()=>{var m;return(m=e.onSelectFile)==null?void 0:m.call(e,h)},children:[s.jsx(Be,{name:"file",size:14})," ",s.jsx("span",{className:"pc-ws__label",children:h.name})]}):s.jsxs("span",{className:"pc-ws__name",children:[s.jsx(Be,{name:"file",size:14})," ",s.jsx("span",{className:"pc-ws__label",children:h.name})]}),s.jsxs("span",{className:"pc-ws__meta",children:[s.jsx("span",{className:"pc-ws__size",children:WC(h.size_bytes)}),h.mtime!==void 0&&Vm(h.mtime,o)?s.jsx("time",{className:"pc-ws__time",title:$b(h.mtime),"data-meta":"modified",children:Vm(h.mtime,o)}):null]}),e.onFile?s.jsx("button",{type:"button",className:"pc-ws__icon-btn pc-ws__icon-btn--bare","data-action":"download-file",disabled:e.fileBusy===h.path,onClick:()=>{var m;return(m=e.onFile)==null?void 0:m.call(e,h,"download")},title:"Download","aria-label":`Download ${h.name}`,children:s.jsx(Be,{name:"download",size:14})}):null]})},h.path))}):s.jsx("div",{className:"pc-ws__muted",children:"This folder is empty."}):null,t?s.jsx("div",{className:"pc-ws__muted","data-hidden-note":"true",children:t}):null]})]})}const QC={registry_scope:"tenant_catalog",bundle_id:"docs-qa",bundle_version:"0.1.1",flow_id:"docsqa001"},Zb="docs";function eE(e){return it(`docs/corpus?${new URLSearchParams({app:String(e||"")})}`)}function fp(e){return`${String(e||"app")}-docs-assistant:${pa()}`}function tE(e){const t={prompt:e.question,docs:e.docs,app:e.appName,use_session_history:!0};return e.attachments&&e.attachments.length&&(t.context={attachments:e.attachments}),{...QC,session_id:e.sessionId,kind:Zb,input_data:t}}function Qb(e){const t=e==null?void 0:e.output;if(typeof t=="string")return t.trim();const n=t==null?void 0:t.response;return typeof n=="string"?n.trim():""}function nE(e){const t=e&&typeof e=="object"?e:{},n=u=>typeof u=="number"&&Number.isFinite(u)&&u>0?Math.trunc(u):0,r=n(t.dropped_messages);if(!r)return"";const o=n(t.replayed_messages),l=n(t.dropped_tokens),c=n(t.max_tokens);return`Earlier messages not replayed: ${r.toLocaleString("en-US")}${l?` (~${l.toLocaleString("en-US")} tokens)`:""}. The model read the newest ${o.toLocaleString("en-US")} message${o===1?"":"s"}`+(c?` (history window: the most recent ${c.toLocaleString("en-US")} tokens of whole messages).`:".")}async function*sE(e,t){const n=e.getReader(),r=new TextDecoder;let o="";const l=()=>{n.cancel().catch(()=>{})};t==null||t.addEventListener("abort",l,{once:!0});try{for(;;){const{value:c,done:u}=await n.read();if(u)break;o+=r.decode(c,{stream:!0}).replace(/\r\n/g,`
|
|
77
|
-
`);let f=o.indexOf(`
|
|
78
|
-
|
|
79
|
-
`);for(;f>=0;){const h=o.slice(0,f);o=o.slice(f+2);let m="message";const g=[];for(const y of h.split(`
|
|
80
|
-
`))y.startsWith("event:")?m=y.slice(6).trim():y.startsWith("data:")&&g.push(y.slice(5).replace(/^ /,""));g.length&&(yield{event:m,data:g.join(`
|
|
81
|
-
`)}),f=o.indexOf(`
|
|
82
|
-
|
|
83
|
-
`)}}}finally{t==null||t.removeEventListener("abort",l)}}function rE(e,t){return new Promise((n,r)=>{if(t.aborted)return r(new DOMException("Aborted","AbortError"));const o=setTimeout(()=>{t.removeEventListener("abort",l),n()},e),l=()=>{clearTimeout(o),r(new DOMException("Aborted","AbortError"))};t.addEventListener("abort",l,{once:!0})})}async function ml(e,t){if(!e.ok)throw await Gu(e,t);return e.json()}function iE(e){const t=e.pollMs??1e3,n=e.timeoutMs??18e4;let r=null;return async(o,l)=>{var k;const{fetchGateway:c,source:u}=e;if(r===null){const b=await c(eE(u.app),{signal:l.signal,headers:{Accept:"application/json"}}),S=await ml(b,`The ${u.name} documentation could not be read, so nothing was asked`),N=typeof(S==null?void 0:S.text)=="string"?S.text:"";if(!N.trim())throw new Error(`The gateway returned an empty ${u.name} documentation corpus, so nothing was asked.`);r=N}const f=String(r),h=[];for(const b of l.files||[]){const S=new FormData;S.append("session_id",l.sessionId),S.append("file",b,b.name||"upload.bin"),S.append("filename",b.name||"upload.bin"),b.type&&S.append("content_type",b.type);const N=await ml(await c(it("attachments/upload"),{method:"POST",body:S,signal:l.signal}),`"${b.name}" could not be attached`),R=N==null?void 0:N.attachment;if(!R||typeof R.$artifact!="string"||!R.$artifact)throw new Error(`"${b.name}" could not be attached: the gateway returned no attachment reference.`);h.push(R)}const m=await ml(await c(it("runs/start"),{method:"POST",signal:l.signal,headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(tE({question:o,docs:f,appName:u.name,sessionId:l.sessionId,attachments:h}))}),"The docs-qa workflow could not start"),g=String((m==null?void 0:m.run_id)||"");if(!g)throw new Error("The gateway did not return a run id for the docs-qa workflow.");const y=new AbortController,w=()=>y.abort();l.signal.addEventListener("abort",w,{once:!0}),l.onText&&(async()=>{var b;try{const S=await c(it(`runs/${encodeURIComponent(g)}/ledger/stream?after=0`),{signal:y.signal,headers:{Accept:"text/event-stream"}});if(!S.ok||!S.body)return;let N="",R="";for await(const T of sE(S.body,y.signal)){const A=xC(T.event,T.data);!A||Gb(A)||A.channel!=="content"||A.run_id!==g||(A.call_id!==N&&(N=A.call_id,R=""),R=A.snapshot?A.text:R+A.text,(b=l.onText)==null||b.call(l,R))}}catch{}})();try{const b=Date.now()+n;for(;;){await rE(t,l.signal);const S=await ml(await c(it(`runs/${encodeURIComponent(g)}`),{signal:l.signal}),"The docs-qa run could not be read"),N=String((S==null?void 0:S.status)||"").toLowerCase();if(N==="completed"){(k=l.onHistory)==null||k.call(l,(S==null?void 0:S.session_history)??null);const R=Qb(S);if(!R)throw new Error(`The docs-qa run ${g} completed without an answer.`);return R}if(N==="failed"||N==="cancelled"){const R=S==null?void 0:S.error,T=typeof R=="string"?R:typeof(R==null?void 0:R.message)=="string"?R.message:"";throw new Error(`The docs-qa run ${N}${T?`: ${T}`:""}.`)}if(N==="waiting")throw new Error(`The docs-qa run ${g} is waiting for input it should never need. Inspect it in Observer.`);if(Date.now()>=b)throw new Error(`The docs-qa run ${g} is still running after ${Math.round(n/1e3)} s. It stays in the gateway's history.`)}}finally{l.signal.removeEventListener("abort",w),y.abort()}}}async function oE(e,t,n={}){const r=new URLSearchParams({root_only:"true",kind:Zb,limit:"500",include_ledger_len:"false"}),o=await ml(await e(it(`runs?${r}`),{signal:n.signal}),"The docs assistant history could not be read"),l=`${String(t||"app")}-docs-assistant:`,c=new Map;for(const f of Array.isArray(o==null?void 0:o.items)?o.items:[]){const h=String((f==null?void 0:f.session_id)||"");if(!h.startsWith(l)||!(f!=null&&f.run_id))continue;const m=c.get(h)||{runs:[],updatedAt:""};m.runs.push({id:String(f.run_id),created:String(f.created_at||"")});const g=String(f.updated_at||f.created_at||"");g>m.updatedAt&&(m.updatedAt=g),c.set(h,m)}const u=[...c.entries()].sort((f,h)=>f[1].updatedAt<h[1].updatedAt?1:-1).slice(0,n.max??20);return Promise.all(u.map(async([f,h])=>{var y;const m=h.runs.sort((w,k)=>w.created<k.created?-1:1).map(w=>w.id);let g="";try{const w=await ml(await e(it(`runs/${encodeURIComponent(m[0])}/input_data`),{signal:n.signal}),"");g=String(((y=w==null?void 0:w.input_data)==null?void 0:y.prompt)||"").trim()}catch{g=""}return{sessionId:f,title:g||"Untitled question",updatedAt:h.updatedAt,runIds:m}}))}async function aE(e,t,n,r){var l;const o=[];for(const c of t.runIds){const[u,f]=await Promise.all([ml(await e(it(`runs/${encodeURIComponent(c)}/input_data`),{signal:r}),"A past question could not be read"),ml(await e(it(`runs/${encodeURIComponent(c)}`),{signal:r}),"A past answer could not be read")]),h=String(((l=u==null?void 0:u.input_data)==null?void 0:l.prompt)||"").trim();h&&o.push({id:`u-${c}`,role:"user",content:h,ts:String((f==null?void 0:f.created_at)||"")||void 0});const m=Qb(f),g=String((f==null?void 0:f.status)||"").toLowerCase();o.push(m?{id:`a-${c}`,role:"assistant",title:n,content:m,ts:String((f==null?void 0:f.updated_at)||"")||void 0}:{id:`a-${c}`,role:"assistant",title:n,level:"warn",content:g==="completed"?"This answer was empty.":`No answer: the run is ${g||"unknown"}.`})}return o}function lE(e){const[t,n]=_.useState(null);return e.state==="loading"?s.jsx("div",{className:"pc-docs-history__note",role:"status",children:"Loading past conversations…"}):e.state==="error"?s.jsx("div",{className:"pc-docs-history__note pc-docs-history__note--error",role:"alert",children:e.error||"The history could not be read."}):e.items.length?s.jsx("ul",{className:"pc-docs-history","aria-label":"Past conversations",children:e.items.map(r=>s.jsx("li",{className:`pc-docs-history__row${r.sessionId===e.activeSessionId?" is-active":""}`,children:t===r.sessionId?s.jsxs("div",{className:"pc-docs-history__confirm",children:[s.jsx("span",{children:"Archive this conversation? It stays in the gateway; it leaves this list."}),s.jsx("button",{type:"button",className:"pc-docs-history__btn pc-docs-history__btn--danger",onClick:()=>{n(null),e.onArchive(r)},children:"Archive"}),s.jsx("button",{type:"button",className:"pc-docs-history__btn",onClick:()=>n(null),children:"Cancel"})]}):s.jsxs(s.Fragment,{children:[s.jsxs("button",{type:"button",className:"pc-docs-history__open",onClick:()=>e.onOpen(r),title:r.title,children:[s.jsx("span",{className:"pc-docs-history__title",children:r.title}),s.jsxs("span",{className:"pc-docs-history__meta",children:[Vm(r.updatedAt,e.nowMs),r.runIds.length>1?` · ${r.runIds.length} questions`:""]})]}),s.jsx("button",{type:"button",className:"pc-docs-assistant__icon-btn","aria-label":`Archive "${r.title}"`,"data-af-tip":`Archive "${r.title}" (kept, hidden)`,onClick:()=>n(r.sessionId),children:s.jsx(Be,{name:"archive",size:16})})]})},r.sessionId))}):s.jsx("div",{className:"pc-docs-history__note",children:"No past conversations yet."})}const cE=/^image\/(png|jpe?g|gif|webp|avif|bmp|svg\+xml)$/i;function uE(e){const t=_.useRef(null),[n,r]=_.useState(!1),o=!!e.blockedNotice,l=!!e.busy,c=e.files||[],u=typeof e.onAddFiles=="function"&&!o,f=s.jsxs("div",{className:"pc-docs-assistant__empty",children:[s.jsxs("p",{className:"pc-docs-assistant__empty-text",children:["Ask anything about ",e.source.name,"."]}),e.suggestions&&e.suggestions.length?s.jsx("div",{className:"pc-docs-assistant__suggestions",children:e.suggestions.map(h=>s.jsx("button",{type:"button",className:"pc-docs-assistant__suggestion",disabled:l||o,onClick:()=>{var m;return(m=e.onSuggestion)==null?void 0:m.call(e,h)},children:h},h))}):null]});return s.jsxs("div",{className:`pc-docs-assistant${n?" is-dragging":""}`,onDragOver:h=>{var m;!u||!vf((m=h.dataTransfer)==null?void 0:m.types)||(h.preventDefault(),r(!0))},onDragLeave:()=>r(!1),onDrop:h=>{var g,y;if(!u)return;h.preventDefault(),r(!1);const m=iy(h.dataTransfer);m.files.length&&((g=e.onAddFiles)==null||g.call(e,m.files)),m.folders.length&&((y=e.onNotice)==null||y.call(e,Hb(m.folders)))},children:[s.jsx(sy,{className:"pc-docs-assistant__thread",messages:e.messages,autoScroll:!0,empty:f,messageProps:{showCopy:!0}}),o?s.jsx("div",{className:"pc-docs-assistant__blocked",role:"status",children:e.blockedNotice}):null,e.notice?s.jsx("div",{className:"pc-docs-assistant__notice",role:"status",children:e.notice}):null,s.jsx("div",{className:"pc-docs-assistant__composer",children:s.jsx(ry,{value:e.draft,onChange:e.onDraftChange,onSubmit:e.onSend,placeholder:e.placeholder||`Ask about ${e.source.name}…`,ariaLabel:`Question about ${e.source.name}`,disabled:o,busy:l,rows:1,sendLabel:"Send",busyLabel:"Answering…",onPaste:h=>{var g;if(!u)return;const m=Vb(h.clipboardData);m.length&&(h.preventDefault(),(g=e.onAddFiles)==null||g.call(e,m))},leading:c.length?s.jsx("div",{className:"pc-chat-attachments pc-docs-assistant__files",role:"list","aria-label":"Attached files",children:c.map(h=>s.jsxs("span",{role:"listitem",className:"pc-chat-attachment-chip",children:[s.jsx(Be,{name:"paperclip",size:14}),s.jsx("span",{className:"pc-chat-attachment-name",children:h.name}),e.onRemoveFile&&!l?s.jsx("button",{type:"button",className:"pc-docs-assistant__file-remove","aria-label":`Remove ${h.name}`,"data-af-tip":`Remove ${h.name}`,onClick:()=>{var m;return(m=e.onRemoveFile)==null?void 0:m.call(e,h.id)},children:s.jsx(Be,{name:"x",size:12})}):null]},h.id))}):null,actions:s.jsxs(s.Fragment,{children:[u?s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"pc-docs-assistant__icon-btn","aria-label":"Attach files","data-af-tip":"Attach files to your question",disabled:l,onClick:()=>{var h;return(h=t.current)==null?void 0:h.click()},children:s.jsx(Be,{name:"paperclip",size:16})}),s.jsx("input",{ref:t,type:"file",multiple:!0,hidden:!0,"aria-hidden":"true",tabIndex:-1,onChange:h=>{var g;const m=Array.from(h.currentTarget.files||[]);h.currentTarget.value="",m.length&&((g=e.onAddFiles)==null||g.call(e,m))}})]}):null,l&&e.onStop?s.jsx("button",{type:"button",className:"pc-docs-assistant__icon-btn","aria-label":"Stop","data-af-tip":"Stop the answer",onClick:e.onStop,children:s.jsx(Be,{name:"stop",size:14})}):null]})})}),s.jsxs("div",{className:"pc-docs-assistant__footer",title:`Answers come from ${e.source.name}'s documentation (llms.txt) through the gateway's docs-qa workflow.`,children:["Grounded on ",e.source.name,"’s documentation (llms.txt) · docs-qa"]})]})}function mm(){return new Date().toISOString()}function dE(e){Yf();const{source:t}=e,n=_.useRef(e.fetchGateway);n.current=e.fetchGateway;const r=_.useMemo(()=>e.ask||iE({fetchGateway:(Q,D)=>n.current(Q,D),source:t}),[e.ask,t.app,t.name]),o=_.useRef(fp(t.app)),[l,c]=_.useState([]),u=_.useRef(l);u.current=l;const[f,h]=_.useState(""),[m,g]=_.useState([]),[y,w]=_.useState(!1),[k,b]=_.useState(""),S=_.useRef(null),[N,R]=_.useState(!1),[T,A]=_.useState({state:"loading",items:[]});_.useEffect(()=>()=>{var Q;return(Q=S.current)==null?void 0:Q.abort()},[]);const W=_.useCallback(async()=>{A(Q=>({...Q,state:"loading"}));try{const Q=await oE((D,$)=>n.current(D,$),t.app);A({state:"ready",items:Q})}catch(Q){A({state:"error",items:[],error:String((Q==null?void 0:Q.message)||Q)})}},[t.app]),z=_.useCallback(async Q=>{var D;(D=S.current)==null||D.abort(),A($=>({...$,state:"loading"}));try{const $=await aE((E,L)=>n.current(E,L),Q,t.name);o.current=Q.sessionId,c($),b(""),R(!1),A(E=>({...E,state:"ready"}))}catch($){A(E=>({...E,state:"error",error:String(($==null?void 0:$.message)||$)}))}},[t.name]),J=_.useCallback(async Q=>{try{const D=await n.current(it(`sessions/${encodeURIComponent(Q.sessionId)}/archive`),{method:"POST"});if(!D.ok)throw await Gu(D,"The conversation could not be archived");o.current===Q.sessionId&&(o.current=fp(t.app),c([])),A($=>({...$,items:$.items.filter(E=>E.sessionId!==Q.sessionId)}))}catch(D){A($=>({...$,state:"error",error:String((D==null?void 0:D.message)||D)}))}},[t.app]);_.useEffect(()=>{var Q;e.connected||(Q=S.current)==null||Q.abort()},[e.connected]),_.useEffect(()=>()=>{for(const Q of m)Q.preview&&URL.revokeObjectURL(Q.preview)},[]);const K=_.useCallback(Q=>{b(""),g(D=>[...D,...Q.map($=>({id:pa(),file:$,preview:cE.test($.type)&&typeof URL<"u"&&typeof URL.createObjectURL=="function"?URL.createObjectURL($):void 0}))])},[]),re=_.useCallback(async Q=>{const D=String(Q||"").trim();if(!D||y||!e.connected)return;const $=m;h(""),g([]),b("");const E=$.filter(H=>H.preview).map(H=>({kind:"image",src:H.preview,label:H.file.name})),L=$.map(H=>({id:H.id,label:H.file.name,title:H.file.name,disabled:!0})),M={id:`u-${pa()}`,role:"user",content:D,ts:mm(),...E.length?{media:E}:{},...L.length?{attachments:L}:{}},ee=`a-${pa()}`,F=[...u.current,M],U={id:ee,role:"assistant",title:t.name,content:"",ts:mm(),live:{callId:ee,reasoning:"",label:"answering"}};c([...F,U]),w(!0);const V=new AbortController;S.current=V;const O=H=>c([...F,H]);try{const H=await r(D,{signal:V.signal,sessionId:o.current,files:$.map(Y=>Y.file),onText:Y=>{V.signal.aborted||O({...U,content:Y,live:{callId:ee,reasoning:"",label:"streaming"}})},onHistory:Y=>b(nE(Y))});V.signal.aborted||O({id:ee,role:"assistant",title:t.name,content:H,ts:mm()})}catch(H){const Y=V.signal.aborted;O({id:ee,role:"assistant",title:t.name,level:Y?"warn":"error",content:Y?"Stopped. Nothing more will be shown for this question.":String((H==null?void 0:H.message)||H||"The docs assistant failed."),ts:mm()})}finally{S.current===V&&(S.current=null),w(!1)}},[r,y,m,e.connected,t.name]),te=()=>{var Q;(Q=S.current)==null||Q.abort(),o.current=fp(t.app),c([]),g([]),h(""),b("")};return s.jsxs(IS,{open:e.open,onClose:e.onClose,label:"Docs assistant",title:s.jsxs("span",{className:"pc-docs-assistant__title",children:[s.jsx(Be,{name:"book",size:16}),"Docs assistant"]}),width:e.width||420,topOffset:e.topOffset,className:`pc-docs-assistant-drawer${e.className?` ${e.className}`:""}`,headerActions:s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:`pc-docs-assistant__icon-btn${N?" is-active":""}`,"aria-label":"Past conversations","data-af-tip":"Past conversations","aria-pressed":N,disabled:!e.connected||y,onClick:()=>{const Q=!N;R(Q),Q&&W()},children:s.jsx(Be,{name:"history",size:16})}),s.jsx("button",{type:"button",className:"pc-docs-assistant__icon-btn","aria-label":"New conversation","data-af-tip":"Start a new conversation",disabled:!l.length&&!f&&!m.length&&!N,onClick:()=>{te(),R(!1)},children:s.jsx(Be,{name:"compose",size:16})})]}),children:[N?s.jsx("div",{className:"pc-docs-assistant pc-docs-assistant--history",children:s.jsx(lE,{items:T.items,state:T.state,error:T.error,nowMs:Date.now(),activeSessionId:o.current,onOpen:Q=>void z(Q),onArchive:Q=>void J(Q)})}):null,s.jsx("div",{hidden:N,style:{display:N?"none":"contents"},children:s.jsx(uE,{source:t,messages:l,draft:f,onDraftChange:h,onSend:()=>void re(f),onStop:()=>{var Q;return(Q=S.current)==null?void 0:Q.abort()},busy:y,blockedNotice:e.connected?void 0:"Connect to the gateway to use the docs assistant.",files:m.map(Q=>({id:Q.id,name:Q.file.name})),onAddFiles:K,onNotice:b,onRemoveFile:Q=>g(D=>{const $=D.find(E=>E.id===Q);return $!=null&&$.preview&&URL.revokeObjectURL($.preview),D.filter(E=>E.id!==Q)}),notice:k,suggestions:e.suggestions,onSuggestion:Q=>void re(Q),placeholder:e.placeholder})})]})}const jn=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},Im=e=>Array.isArray(e)?e.map(jn):[],nn=e=>typeof e=="string"?e:"",tf=e=>nn(e.runtime_call_id||e.call_uid),nf=e=>nn(e.call_id||e.id);function e0(e,t){const n=t.record,r=jn(n.effect);if(r.type!=="tool_calls")return[];const o=jn(n.result),l=Im(jn(r.payload).tool_calls),c=l.length||n.status!=="waiting"?l:Im(jn(jn(o.wait).details).tool_calls),u=Im(o.results),f=c.length?c:u,h=[];return f.forEach((m,g)=>{let y=tf(m)?u.filter(z=>tf(z)===tf(m)):[];!y.length&&nf(m)&&c.filter(z=>nf(z)===nf(m)).length===1&&(y=u.filter(z=>nf(z)===nf(m)));const w=c.length?y.length===1?y[0]:c.length===u.length?u[g]:{}:m,k=tf(m)||tf(w)||`${nn(n.idempotency_key)||nn(n.step_id)||t.cursor}:${g}`,b=`${t.runId}:${k}`,S=e.get(b),N=nn(m.name||w.name)||(S==null?void 0:S.name);if(!N)return;const R=n.status==="completed"||n.status==="failed",T=n.status==="failed"||w.success===!1||!!w.error,A=m.arguments??w.arguments??(S==null?void 0:S.arguments),W={...S,id:b,runId:t.runId,name:N,arguments:A,status:R?T?"failed":"completed":n.status==="waiting"?"waiting":"running",...typeof w.success=="boolean"?{success:w.success}:{},...w.output!==void 0||w.result!==void 0?{output:w.output??w.result}:{},...w.error?{error:String(w.error)}:{},...fg(w)?{sandbox:fg(w)}:{},startedAt:(S==null?void 0:S.startedAt)||nn(n.started_at)||void 0,endedAt:R&&nn(n.ended_at)||(S==null?void 0:S.endedAt)};S&&["completed","failed"].includes(S.status)&&!R||(e.set(b,W),h.push(W))}),h}function Eu(e){if(e==null||e===""||typeof e=="boolean")return;const t=Number(e);return Number.isFinite(t)&&t>=0?t:void 0}function So(e,t){for(const n of t){const r=e==null?void 0:e[n];if(r==null||r===""||typeof r=="boolean")continue;const o=Number(r);if(Number.isFinite(o)&&o>=0)return Math.trunc(o)}}function t0(e){if(typeof e=="string")try{return jn(JSON.parse(e))}catch{return{}}return jn(e)}function vu(e,t){if(t===void 0||t==="")return e;const n=e||[];return n.includes(t)||n.push(t),n}function fE(e){return So(e,["reasoning_tokens","thinking_tokens"])??So(jn(e.completion_tokens_details),["reasoning_tokens"])??So(jn(e.output_tokens_details),["reasoning_tokens"])}function hE(e){const t=jn(typeof e=="string"&&e.trim().startsWith("{")?t0(e):e);return nn(t.error_class)}function mE(e){const t=new Map;for(const n of e){const r=n.record;if(jn(r.effect).type!=="emit_event")continue;const o=jn(r.result);if(nn(o.name)!=="abstract.progress")continue;const l=jn(o.payload);if(nn(l.kind)!=="llm"||!nn(l.step_id))continue;const c=`${nn(l.run_id)||n.runId}:${nn(l.step_id)}`,u=t.get(c)||{},f=Eu(l.ttft_s);f!==void 0&&(u.ttftS=f),u.provider=u.provider||nn(l.provider)||void 0,u.model=u.model||nn(l.model)||void 0,t.set(c,u)}return t}function hp(e){var b,S,N,R;const t=new Map,n=new Set,r=new Set,o={llmCalls:0,toolCalls:0,changedFiles:[]};let l=1/0,c=-1/0,u=!1,f=0,h=0,m=0;const g=mE(e),y=[],w=new Set;for(const T of e){const A=T.record,W=`${T.runId}:${A.step_id||T.cursor}:${A.status}`;if(n.has(W))continue;n.add(W);for(const ge of[A.started_at,A.ended_at]){const Ne=Date.parse(nn(ge));Number.isFinite(Ne)&&(l=Math.min(l,Ne),c=Math.max(c,Ne))}for(const ge of e0(t,T))ge.status==="waiting"&&w.add(ge.id);if(jn(A.effect).type!=="llm_call"||A.status!=="completed")continue;o.llmCalls+=1;const z=jn(A.result),J=jn(z.output),K=jn(z.usage||z.token_usage||z.tokens||J.usage||J.token_usage||J.tokens),re=So(K,["input_tokens","prompt_tokens","prompt","input","in"]),te=So(K,["output_tokens","completion_tokens","completion","output","out"]),Q=So(K,["total_tokens","total"])??(re!==void 0||te!==void 0?(re||0)+(te||0):void 0);Q!==void 0&&(re===void 0||te===void 0||re+te!==Q)&&(u=!0),re!==void 0&&(o.inputTokens=(o.inputTokens||0)+re),te!==void 0&&(o.outputTokens=(o.outputTokens||0)+te),Q!==void 0&&(o.totalTokens=(o.totalTokens||0)+Q);const D=Eu(z.gen_time??J.gen_time);D!==void 0&&(o.genTimeMs=(o.genTimeMs||0)+D,o.timedCalls=(o.timedCalls||0)+1);const $=jn(z.metadata||J.metadata),E=jn($.performance),L=Eu(E.prompt_tokens_per_second),M=Eu(E.generation_tokens_per_second),ee=jn($.prompt_cache),F=Eu(ee.cached_tokens),U=Eu(ee.fed_tokens);if(L!==void 0||M!==void 0){if(o.measuredSpeedCalls=(o.measuredSpeedCalls||0)+1,L!==void 0&&L>0&&(o.promptTokensPerSecond=(o.promptTokensPerSecond||0)+L,re!==void 0)){const ge=re/L*1e3;o.prefillMs=(o.prefillMs||0)+ge,U!==void 0&&(f+=U,h+=ge)}M!==void 0&&M>0&&(o.generationTokensPerSecond=(o.generationTokensPerSecond||0)+M,te!==void 0&&(o.decodeMs=(o.decodeMs||0)+te/M*1e3))}if(F!==void 0||U!==void 0){o.measuredCacheCalls=(o.measuredCacheCalls||0)+1,o.cachedTokens=(o.cachedTokens||0)+(F||0),o.fedTokens=(o.fedTokens||0)+(U||0);const ge=nn(ee.outcome);if(ge){const Ne=o.cacheOutcomes||[];Ne.includes(ge)||Ne.push(ge),o.cacheOutcomes=Ne}}const V=nn(A.step_id)||void 0,O=V&&g.get(`${T.runId}:${V}`)||{},H=jn(z.route),Y={runId:T.runId};V&&(Y.stepId=V),nn(A.started_at)&&(Y.startedAt=nn(A.started_at));const ae=nn(z.model||J.model)||nn(H.model)||O.model,ie=nn(H.provider)||nn(jn($._provider_request).provider)||O.provider||nn(z.provider);ae&&(Y.model=ae),ie&&(Y.provider=ie),ae&&(o.models=vu(o.models,ae)),ie&&(o.providers=vu(o.providers,ie)),(Q===void 0||re!==void 0&&te!==void 0&&re+te===Q)&&(re!==void 0&&(Y.inputTokens=re),te!==void 0&&(Y.outputTokens=te)),Q!==void 0&&(Y.totalTokens=Q);const _e=fE(K);_e!==void 0&&(Y.reasoningTokens=_e,o.reasoningTokens=(o.reasoningTokens||0)+_e),F!==void 0&&(Y.cachedTokens=F),U!==void 0&&(Y.fedTokens=U),nn(ee.outcome)&&(Y.cacheOutcome=nn(ee.outcome)),nn(ee.backend)&&(Y.cacheBackend=nn(ee.backend),o.cacheBackends=vu(o.cacheBackends,Y.cacheBackend)),D!==void 0&&(Y.genTimeMs=D),L!==void 0&&L>0&&(Y.promptTokensPerSecond=L),M!==void 0&&M>0&&(Y.generationTokensPerSecond=M),O.ttftS!==void 0?(Y.ttftMs=O.ttftS*1e3,Y.promptMs=Y.ttftMs,Y.promptSource="ttft",o.ttftMs=(o.ttftMs||0)+Y.ttftMs,o.ttftCalls=(o.ttftCalls||0)+1):Y.promptTokensPerSecond!==void 0&&re!==void 0&&(Y.promptMs=re/Y.promptTokensPerSecond*1e3,Y.promptSource="rate"),Y.promptMs!==void 0&&(o.promptPhaseMs=(o.promptPhaseMs||0)+Y.promptMs,o.promptPhaseCalls=(o.promptPhaseCalls||0)+1,U!==void 0&&Y.promptMs>0&&(Y.promptNewTokensPerSecond=U/(Y.promptMs/1e3),o.promptPhaseNewTokens=(o.promptPhaseNewTokens||0)+U,m+=Y.promptMs)),Y.ttftMs!==void 0&&D!==void 0&&D>=Y.ttftMs?Y.generationMs=D-Y.ttftMs:Y.generationTokensPerSecond!==void 0&&te!==void 0&&(Y.generationMs=te/Y.generationTokensPerSecond*1e3),Y.generationMs!==void 0&&te!==void 0&&(o.generationPhaseMs=(o.generationPhaseMs||0)+Y.generationMs,o.generationPhaseTokens=(o.generationPhaseTokens||0)+te);const fe=jn($.speculation);if(Object.keys(fe).length){const ge={};nn(fe.mode)&&(ge.mode=nn(fe.mode)),typeof fe.used=="boolean"&&(ge.used=fe.used),nn(fe.draft_kind)&&(ge.draftKind=nn(fe.draft_kind));const Ne=So(fe,["accepted_tokens"]),Ue=So(fe,["drafted_tokens"]),We=So(fe,["rounds"]),ut=So(fe,["num_draft_tokens"]);Ne!==void 0&&(ge.acceptedTokens=Ne),Ue!==void 0&&(ge.draftedTokens=Ue),Ne!==void 0&&Ue&&(ge.acceptanceRate=Ne/Ue),We!==void 0&&(ge.rounds=We),ut!==void 0&&(ge.draftLength=ut),Y.speculation=ge;const Fe=o.speculation||(o.speculation={calls:0,used:0});Fe.calls+=1,ge.used&&(Fe.used+=1),ge.mode&&(Fe.modes=vu(Fe.modes,ge.mode)),ge.draftKind&&(Fe.draftKinds=vu(Fe.draftKinds,ge.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),ut!==void 0&&(Fe.draftLengths=vu(Fe.draftLengths,ut))}y.push(Y)}y.length&&(y.every(T=>T.startedAt)&&y.sort((T,A)=>Date.parse(T.startedAt)-Date.parse(A.startedAt)),o.modelCalls=y),m>0&&o.promptPhaseNewTokens!==void 0&&(o.promptPhaseTokensPerSecond=o.promptPhaseNewTokens/(m/1e3)),o.generationPhaseMs&&o.generationPhaseTokens!==void 0&&(o.generationPhaseTokensPerSecond=o.generationPhaseTokens/(o.generationPhaseMs/1e3)),(b=o.speculation)!=null&&b.draftedTokens&&(o.speculation.acceptanceRate=(o.speculation.acceptedTokens||0)/o.speculation.draftedTokens),o.measuredSpeedCalls&&(o.promptTokensPerSecond!==void 0&&(o.promptTokensPerSecond/=o.measuredSpeedCalls),o.generationTokensPerSecond!==void 0&&(o.generationTokensPerSecond/=o.measuredSpeedCalls)),h>0&&(o.prefillNewTokens=f,o.prefillNewTokensPerSecond=f/(h/1e3));const k=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 A=T.status==="failed";A&&(o.toolsFailed=(o.toolsFailed||0)+1);const W=o.toolBreakdown||(o.toolBreakdown={}),z=W[T.name]||(W[T.name]={calls:0,failed:0});if(z.calls+=1,A){z.failed+=1;const Q=hE(T.output);Q&&((z.errors||(z.errors={}))[Q]=(((S=z.errors)==null?void 0:S[Q])||0)+1)}const J=Date.parse(nn(T.startedAt)),K=Date.parse(nn(T.endedAt));if(Number.isFinite(J)&&Number.isFinite(K)&&K>=J){const Q=`${T.runId}|${T.startedAt}|${T.endedAt}`,D=k.get(Q)||{ms:K-J,calls:0,names:new Map,waited:!1};D.calls+=1,D.names.set(T.name,(D.names.get(T.name)||0)+1),w.has(T.id)&&(D.waited=!0),k.set(Q,D)}if(T.success!==!0||!["write_file","create_file","save_file","edit_file","update_file","replace_in_file","delete_file","remove_file","move_file","rename_file","copy_file"].includes(T.name))continue;const re=t0(T.arguments),te=nn(re.destination||re.destination_path||re.file_path||re.path||re.filename);te&&r.add(te)}for(const T of k.values()){o.toolBatches=(o.toolBatches||0)+1,o.toolTimeMs=(o.toolTimeMs||0)+T.ms,T.waited&&(o.toolTimeIncludesApproval=!0);const A=[...T.names.keys()].sort();(!o.slowestToolBatch||T.ms>o.slowestToolBatch.ms)&&(o.slowestToolBatch={ms:T.ms,calls:T.calls,tools:A});const W=(N=o.toolBreakdown)==null?void 0:N[A[0]];if(A.length===1&&W)W.ms=(W.ms||0)+T.ms;else for(const z of A){const J=(R=o.toolBreakdown)==null?void 0:R[z];J&&(J.sharedBatches=(J.sharedBatches||0)+1)}}return o.changedFiles=[...r],u&&(delete o.inputTokens,delete o.outputTokens),Number.isFinite(l)&&Number.isFinite(c)&&(o.durationMs=Math.max(0,c-l)),{tools:[...t.values()],statistics:o}}function _E(e){const t=jn(jn(e).ledgers);return Object.entries(t).flatMap(([n,r])=>Im(jn(r).items).map((o,l)=>({runId:n,cursor:Number(o.cursor)||l+1,record:Object.keys(jn(o.record)).length?jn(o.record):o})))}function pE(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 gE(e){return(e instanceof Error?e.message:String(e||"Unknown error")).trim()||"Unknown error"}function yE(e){return s.jsxs("div",{className:"pc-workflow-interaction__error",role:"alert",children:[s.jsxs("span",{children:["Could not complete that action: ",e.message]}),s.jsx("button",{type:"button",className:"pc-workflow-interaction__retry",onClick:e.onRetry,disabled:e.disabled,children:"Try again"})]})}function wE(e){var J;const t=e.interaction,[n,r]=_.useState(""),[o,l]=_.useState(()=>t.kind==="event-wait"&&t.initialPayload||""),[c,u]=_.useState(null),[f,h]=_.useState(!1),[m,g]=_.useState(""),[y,w]=_.useState(null),k=`${t.kind}:${t.id}`,b=_.useRef(k),S=_.useRef(!1),N=_.useRef(!1),R=_.useRef(!0),T=_.useRef(0);b.current!==k&&(b.current=k,S.current=!1,N.current=!1,T.current+=1);const A=!!e.disabled||c!==null||f||S.current||N.current,W=async(K,re)=>{var D;if(e.disabled||S.current||N.current)return;const te=k,Q=++T.current;S.current=!0,w(null),g(""),u(K);try{if(await re(),!R.current||b.current!==te||T.current!==Q)return;N.current=!0,h(!0),g("Response sent. Waiting for the workflow to continue.")}catch($){if(!R.current||b.current!==te||T.current!==Q)return;w({submission:K,message:gE($)}),g("The action failed. You can try again."),(D=e.onError)==null||D.call(e,$)}finally{if(!R.current||b.current!==te||T.current!==Q)return;S.current=!1,u(null)}};_.useEffect(()=>{r(""),l(t.kind==="event-wait"&&t.initialPayload||""),w(null),u(null),h(!1),g("")},[k]),_.useEffect(()=>(R.current=!0,()=>{R.current=!1,T.current+=1,S.current=!1}),[]);const z=()=>{y&&W(y.submission,()=>pE(t,y.submission))};return s.jsxs("section",{className:"pc-workflow-interaction","aria-labelledby":`pc-workflow-interaction-${k}`,children:[s.jsxs("div",{className:"pc-workflow-interaction__heading",children:[s.jsx(Be,{name:t.kind==="tool-approval"?"warning":t.kind==="event-wait"?"history":"info",size:16}),s.jsxs("div",{children:[s.jsx("h3",{tabIndex:-1,id:`pc-workflow-interaction-${k}`,children:t.title||(t.kind==="tool-approval"?"Tool approval required":"Input required")}),t.description?s.jsx("div",{className:"pc-workflow-interaction__description",children:t.description}):null]})]}),t.kind==="ask-user"?s.jsxs("div",{className:"pc-workflow-interaction__body",children:[s.jsx("div",{className:"pc-workflow-interaction__prompt",children:t.prompt}),(J=t.choices)!=null&&J.length?s.jsx("div",{className:"pc-workflow-interaction__choices","aria-label":"Choices",children:t.choices.map(K=>s.jsxs("button",{type:"button",className:"pc-workflow-interaction__choice",disabled:A||K.disabled,onClick:()=>void W({kind:"choice",answer:K.id},()=>t.onSubmit(K.id)),children:[s.jsx("span",{children:K.label}),K.description?s.jsx("small",{children:K.description}):null]},K.id))}):null,t.allowFreeText!==!1?s.jsxs("div",{className:"pc-workflow-interaction__entry",children:[s.jsx("textarea",{"aria-label":"Response",value:n,onChange:K=>r(K.target.value),placeholder:t.freeTextPlaceholder||"Type a response",rows:2,disabled:A,onKeyDown:K=>{K.key!=="Enter"||K.shiftKey||K.nativeEvent.isComposing||K.keyCode===229||(K.preventDefault(),n.trim()&&W({kind:"free-text",answer:n},()=>t.onSubmit(n)))}},`${k}:text`),s.jsx("button",{type:"button",className:"pc-btn",disabled:A||!n.trim(),onClick:()=>void W({kind:"free-text",answer:n},()=>t.onSubmit(n)),children:(c==null?void 0:c.kind)==="free-text"?"Sending…":t.submitLabel||"Submit"})]}):null]}):t.kind==="tool-approval"?s.jsxs("div",{className:"pc-workflow-interaction__body",children:[s.jsxs("div",{className:"pc-workflow-interaction__prompt",children:["Allow ",s.jsx("strong",{children:t.toolName})," to run?"]}),t.detail?s.jsx("div",{className:"pc-workflow-interaction__detail",children:t.detail}):null,s.jsxs("div",{className:"pc-workflow-interaction__buttons",children:[s.jsx("button",{type:"button",className:"pc-workflow-interaction__deny",disabled:A,onClick:()=>void W({kind:"deny"},t.onDeny),children:(c==null?void 0:c.kind)==="deny"?"Denying…":t.denyLabel||"Deny"}),s.jsx("button",{type:"button",className:"pc-btn",disabled:A,onClick:()=>void W({kind:"approve"},t.onApprove),children:(c==null?void 0:c.kind)==="approve"?"Approving…":t.approveLabel||"Approve"}),t.onApproveAll?s.jsx("button",{type:"button",className:"pc-workflow-interaction__allow-all",disabled:A,onClick:()=>void W({kind:"approve-all"},t.onApproveAll),children:(c==null?void 0:c.kind)==="approve-all"?"Approving…":t.approveAllLabel||"Allow all"}):null]}),t.onApproveAll&&t.approveAllDescription?s.jsx("p",{className:"pc-workflow-interaction__scope",children:t.approveAllDescription}):null]}):s.jsxs("div",{className:"pc-workflow-interaction__body",children:[s.jsx("div",{className:"pc-workflow-interaction__prompt",children:t.prompt}),s.jsxs("label",{className:"pc-workflow-interaction__entry",children:[s.jsx("span",{children:t.payloadLabel||(t.eventName?`Payload for ${t.eventName}`:"Event payload")}),s.jsx("textarea",{value:o,onChange:K=>l(K.target.value),placeholder:t.payloadPlaceholder||"Enter payload",rows:2,"aria-label":t.payloadLabel||(t.eventName?`Payload for ${t.eventName}`:"Event payload"),disabled:A},`${k}:payload`)]}),s.jsx("div",{className:"pc-workflow-interaction__buttons",children:s.jsx("button",{type:"button",className:"pc-btn",disabled:A,onClick:()=>void W({kind:"event",payload:o},()=>t.onSend(o)),children:(c==null?void 0:c.kind)==="event"?"Sending…":t.sendLabel||"Send event"})})]}),y?s.jsx(yE,{message:y.message,onRetry:z,disabled:A}):null,s.jsx("div",{className:"pc-workflow-interaction__outcome","aria-live":"polite",children:m})]})}function _m(e){return(e instanceof Error?e.message:String(e||"Unknown error")).trim()||"Unknown error"}function vE(e){Yf();const[t,n]=_.useState(!1),[r,o]=_.useState(!1),[l,c]=_.useState(!1),[u,f]=_.useState(null),h=_.useRef(!0),m=_.useRef(!1),g=_.useRef(!1),y=_.useRef(!1),w=_.useRef(0),k=_.useRef(0),b=_.useRef(0);_.useEffect(()=>(h.current=!0,()=>{h.current=!1,w.current+=1,k.current+=1,b.current+=1,m.current=!1,g.current=!1,y.current=!1}),[]);const S=!!e.blockedNotice,N=!!e.disabled||S,R=!!e.busy||t,T=t||!!e.busy&&!e.sendWhileBusy,A=e.stopState||null,W=(A==null?void 0:A.phase)==="stopping",z=typeof e.onFiles=="function",J=_.useRef(null),[K,re]=_.useState(null),[te,Q]=_.useState(""),D=_.useRef(e.onFiles);D.current=e.onFiles;const $=_.useRef(N);$.current=N;const E=async(Y,ae)=>{const ie=D.current;if(ie){if($.current){f({action:"attach",message:"attachments are unavailable right now."});return}if(ae.length)f({action:"attach",message:Hb(ae)});else if(Y.length)f(null);else{f({action:"attach",message:"the drop contained no files."});return}if(Y.length){Q(`Attaching ${Y.length} ${Y.length===1?"file":"files"}…`);try{await ie(Y)}catch(_e){h.current&&f({action:"attach",message:_m(_e)})}}}},L=_.useRef(E);L.current=E,_.useEffect(()=>{if(!z||typeof window>"u")return;const Y=new yC;let ae=0;const ie=Fe=>!!(J.current&&Fe instanceof Node&&J.current.contains(Fe)),_e=()=>{Y.reset(),ae&&window.clearInterval(ae),ae=0,re(null)},fe=()=>{ae||(ae=window.setInterval(()=>{Y.active(Date.now())||_e()},250))},ge=Fe=>{var Ve;if(!vf((Ve=Fe.dataTransfer)==null?void 0:Ve.types))return;Y.enter(Date.now());const et=ie(Fe.target),$e=zw(Fe.dataTransfer);re(le=>le&&le.over===et&&le.count===($e??le.count)?le:{count:$e??(le==null?void 0:le.count)??null,over:et}),fe()},Ne=Fe=>{var $e;if(!vf(($e=Fe.dataTransfer)==null?void 0:$e.types))return;Fe.preventDefault(),Y.over(Date.now());const et=ie(Fe.target);Fe.dataTransfer&&(Fe.dataTransfer.dropEffect=et&&!$.current?"copy":"none"),re(Ve=>Ve&&Ve.over===et?Ve:{count:(Ve==null?void 0:Ve.count)??zw(Fe.dataTransfer),over:et}),fe()},Ue=Fe=>{var et;vf((et=Fe.dataTransfer)==null?void 0:et.types)&&(Y.leave(Date.now())||_e())},We=Fe=>{var be;if(!vf((be=Fe.dataTransfer)==null?void 0:be.types))return;const et=ie(Fe.target),$e=Fe.defaultPrevented&&!et;if(Fe.preventDefault(),_e(),$e)return;if(!et){f({action:"attach",message:"drop files on the conversation to attach them."});return}const{files:Ve,folders:le}=iy(Fe.dataTransfer);L.current(Ve,le)},ut=Fe=>{Fe.key==="Escape"&&Y.depth>0&&_e()};return window.addEventListener("dragenter",ge),window.addEventListener("dragover",Ne),window.addEventListener("dragleave",Ue),window.addEventListener("drop",We),window.addEventListener("dragend",_e),window.addEventListener("blur",_e),window.addEventListener("keydown",ut),()=>{window.removeEventListener("dragenter",ge),window.removeEventListener("dragover",Ne),window.removeEventListener("dragleave",Ue),window.removeEventListener("drop",We),window.removeEventListener("dragend",_e),window.removeEventListener("blur",_e),window.removeEventListener("keydown",ut),ae&&window.clearInterval(ae)}},[z]);const M=Y=>{if(!z||N)return;const ae=Vb(Y.clipboardData);ae.length&&(Y.preventDefault(),E(ae,[]))},ee=K?s.jsxs("div",{className:["pc-workflow-chat__dropzone",K.over?"is-over":"",N?"is-disabled":""].filter(Boolean).join(" "),"aria-hidden":"true",children:[s.jsx("span",{className:"pc-workflow-chat__dropzone-icon",children:s.jsx(Be,{name:"paperclip",size:18})}),s.jsxs("span",{className:"pc-workflow-chat__dropzone-text",children:[s.jsx("strong",{children:N?"Attachments are unavailable right now":Bw(K.count)}),N?null:s.jsx("span",{children:K.over?"Release to upload to this conversation":"Drop anywhere on the conversation"})]})]}):null,F=K?N?"Attachments are unavailable right now":Bw(K.count):te,U=async()=>{const Y=String(e.draft||"");if(N||m.current||!e.sendWhileBusy&&e.busy||!Y.trim())return;const ae=++w.current;m.current=!0,f(null),n(!0);try{await e.onSend(Y)}catch(ie){h.current&&w.current===ae&&f({action:"send",message:_m(ie)})}finally{h.current&&w.current===ae&&(m.current=!1,n(!1))}},V=async()=>{if(N||g.current||!e.onCancel)return;const Y=++k.current;g.current=!0,f(null),o(!0);try{await e.onCancel()}catch(ae){h.current&&k.current===Y&&f({action:"cancel",message:_m(ae)})}finally{h.current&&k.current===Y&&(g.current=!1,o(!1))}},O=async()=>{if(N||y.current||!e.onAttach)return;const Y=++b.current;y.current=!0,f(null),c(!0);try{await e.onAttach()}catch(ae){h.current&&b.current===Y&&f({action:"attach",message:_m(ae)})}finally{h.current&&b.current===Y&&(y.current=!1,c(!1))}},H=()=>{u&&(u.action==="send"&&U(),u.action==="cancel"&&V(),u.action==="attach"&&O())};return s.jsxs("section",{ref:J,className:["pc-workflow-chat",K?"pc-workflow-chat--dragging":"",K!=null&&K.over?"pc-workflow-chat--drag-over":"",e.className].filter(Boolean).join(" "),"aria-label":"Workflow chat","data-stream-replies":e.streamReplies||"gateway_default",children:[e.header?s.jsx("header",{className:"pc-workflow-chat__header",children:e.header}):null,s.jsx("div",{className:"pc-workflow-chat__transcript",children:s.jsx(sy,{messages:Array.isArray(e.messages)?e.messages:[],empty:e.emptyState,autoScroll:!0,messageProps:{...e.messageProps,...e.renderMarkdown?{renderMarkdown:e.renderMarkdown}:{}},after:s.jsxs(s.Fragment,{children:[e.interaction?s.jsx(wE,{interaction:e.interaction,disabled:N}):null,S?s.jsx("div",{className:"pc-workflow-chat__blocked",role:"status",children:e.blockedNotice}):null]}),afterKey:`${e.interaction?`${e.interaction.kind}:${e.interaction.id}`:""}:${S?"blocked":""}`})}),u?s.jsxs("div",{className:"pc-workflow-chat__error",role:"alert",children:[s.jsxs("span",{children:["Could not ",u.action==="send"?"send this message":u.action==="attach"?"attach a file":"stop the run",": ",u.message]}),s.jsx("button",{type:"button",onClick:H,disabled:N,children:"Try again"})]}):null,s.jsxs("div",{className:"pc-workflow-chat__composer",children:[s.jsx(ry,{value:e.draft,onChange:e.onDraftChange,onSubmit:()=>void U(),placeholder:e.placeholder||"Send a message",ariaLabel:"Message",disabled:N,busy:T,sendLabel:e.sendLabel,busyLabel:e.busyLabel,rows:2,leading:e.attachments?s.jsx("div",{className:"pc-workflow-chat__attachments",children:e.attachments}):null,overlay:ee,onPaste:z?M:void 0,actions:s.jsxs(s.Fragment,{children:[e.onAttach?s.jsxs("button",{type:"button",className:"pc-workflow-chat__icon-button","aria-label":"Attach file","data-af-tip":"Attach a file",disabled:N||l,onClick:()=>void O(),children:[s.jsx(Be,{name:"paperclip",size:16}),s.jsx("span",{children:l?"Attaching…":"Attach"})]}):null,e.composerExtras,R&&e.onCancel?s.jsxs("button",{type:"button",className:"pc-workflow-chat__stop",disabled:N||r||W,onClick:()=>void V(),children:[s.jsx(Be,{name:"x",size:14}),s.jsx("span",{children:r||W?"Stopping…":"Stop"})]}):A?s.jsx("span",{className:`pc-workflow-chat__stop-state pc-workflow-chat__stop-state--${A.phase}`,role:"status","aria-live":"polite",children:A.label}):null]})}),z?s.jsx("div",{className:"pc-sr-only",role:"status","aria-live":"polite",children:F}):null]}),e.footer?s.jsx("footer",{className:"pc-workflow-chat__footer",children:e.footer}):null]})}function xE(e){return e.toolApprovalGranted?null:e.interaction}const Ww={messages:[],records:[],run:null,interaction:null,status:"idle",displayStatus:"",loading:!1,error:null,connection:"idle",toolApprovalGranted:!1,stop:null};function Tt(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function jt(e){return typeof e=="string"?e.trim():e==null?"":typeof e=="number"||typeof e=="boolean"?String(e):""}function bf(e){return Array.isArray(e)?e:[]}function Wr(e){return jt(e==null?void 0:e.status).toLowerCase()||"unknown"}function bs(e){return["completed","failed","cancelled"].includes(e.toLowerCase())}function ol(e){const t=Tt(e),n=Number((t==null?void 0:t.status)??(t==null?void 0:t.statusCode));return n===401||n===403}function bE(e){const t=Tt(e);return Number((t==null?void 0:t.status)??(t==null?void 0:t.statusCode))}function mp(e){const t=n=>{if(Array.isArray(n))return n.map(t);const r=Tt(n);if(!r)return n;const o={};for(const l of Object.keys(r).sort())o[l]=t(r[l]);return o};try{return JSON.stringify(t(e))}catch{return"[unserializable]"}}function hg(e){if(typeof e=="string")return e.trim();const t=Tt(e);if(!t)return"";for(const n of["answer","response","message","text","content","output"]){const r=t[n];if(typeof r=="string"&&r.trim())return r.trim()}return""}function xu(e){const t=hg(e);if(t)return t;if(!Tt(e)&&!Array.isArray(e))return"";try{return JSON.stringify(e,null,2)}catch{return""}}function qw(e){if(!e)return"";for(const r of["prompt","request","task","message","query","input"]){const o=jt(e[r]);if(o)return o}const t=Tt(e.context);for(const r of["task","message"]){const o=jt(t==null?void 0:t[r]);if(o)return o}const n=bf(t==null?void 0:t.messages);for(let r=n.length-1;r>=0;r-=1){const o=Tt(n[r]);if(jt(o==null?void 0:o.role).toLowerCase()!=="user")continue;const l=jt(o==null?void 0:o.content);if(l)return l}return""}function n0(e){const t=Tt(e.result);return Tt(t==null?void 0:t.wait)}function _p(e){return e?jt(e.reason)==="subworkflow"||jt(e.wait_key).startsWith("subworkflow:"):!1}function Hw(e,t){return!!(e&&e.runId===t.runId&&jt(e.wait.wait_key)===jt(t.wait.wait_key))}function mg(e){return Tt(e.effect)||{}}function kE(e,t){return jt(e.run_id)||t}function Vw(e){return jt(e.ended_at)||jt(e.started_at)||void 0}function Gw(e){const t=new Set,n=h=>{const m=jt(h);m&&t.add(m)},r=Tt(e.result);n(r==null?void 0:r.sub_run_id),n(r==null?void 0:r.subRunId),n(r==null?void 0:r.child_run_id);const o=mg(e),l=Tt(o.payload);jt(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 c=n0(e),u=Tt(c==null?void 0:c.details);n(u==null?void 0:u.sub_run_id),n(u==null?void 0:u.subRunId),n(u==null?void 0:u.child_run_id);const f=jt(c==null?void 0:c.wait_key);return f.startsWith("subworkflow:")&&n(f.slice(12)),[...t]}class jE{constructor(t,n={}){this.transport=t,this.options=n,this.snapshot={...Ww},this.subscribers=new Set,this.controller=null,this.generation=0,this.rootRunId="",this.cursors=new Map,this.seenRecords=new Set,this.seenMessages=new Set,this.watchedRuns=new Set,this.childCatchUpAttempts=new Map,this.runStates=new Map,this.historicalRuns=new Map,this.historicalRunFailures=new Map,this.commandIds=new Map,this.toolActivities=new Map,this.historicalEvidence=new Map,this.approvedWaits=new Set,this.grantedToolWaits=new Set,this.resolvedWaits=new Set,this.approvalEpoch=0,this.toolApprovalPolicy=null,this.toolApprovalSuspended=!1,this.toolApprovalStopped=!1,this.displayStatusAt=-1/0,this.stopRequested=!1,this.stopFollowing=!1,this.openLlmSteps=new Set,this.forcedStop=null,this.liveReplies=new Map,this.closedLiveCalls=new Set,this.shownLiveCalls=new Set,this.liveDirty=new Set,this.liveRenderTimer=null,this.lastLiveRender=-1/0;const r=n.liveRenderIntervalMs??60;if(typeof r!="number"||!Number.isFinite(r)||r<0)throw new Error(`liveRenderIntervalMs must be a non-negative number of milliseconds, got ${JSON.stringify(n.liveRenderIntervalMs)}`);this.liveRenderIntervalMs=r}subscribe(t){return this.subscribers.add(t),()=>this.subscribers.delete(t)}getSnapshot(){return this.snapshot}reset(){var t;this.toolApprovalSuspended=!1,this.toolApprovalStopped=!1,this.approvalEpoch+=1,this.displayStatusAt=-1/0,this.stopRequested=!1,this.stopFollowing=!1,this.openLlmSteps.clear(),this.forcedStop=null,this.generation+=1,(t=this.controller)==null||t.abort(),this.controller=null,this.rootRunId="",this.cursors.clear(),this.seenRecords.clear(),this.seenMessages.clear(),this.watchedRuns.clear(),this.childCatchUpAttempts.clear(),this.runStates.clear(),this.historicalRuns.clear(),this.historicalRunFailures.clear(),this.commandIds.clear(),this.toolActivities.clear(),this.historicalEvidence.clear(),this.approvedWaits.clear(),this.grantedToolWaits.clear(),this.resolvedWaits.clear(),this.liveReplies.clear(),this.closedLiveCalls.clear(),this.shownLiveCalls.clear(),this.liveDirty.clear(),this.lastLiveRender=-1/0,this.liveRenderTimer&&(clearTimeout(this.liveRenderTimer),this.liveRenderTimer=null),this.set({...Ww})}dispose(){this.reset(),this.subscribers.clear()}async load(t){const n=jt(t);if(this.reset(),!n)return;const r=++this.generation,o=new AbortController;this.controller=o,this.rootRunId=n,this.set({...this.snapshot,loading:!0,status:"loading",error:null,connection:"connecting"});try{const[l,c]=await Promise.all([this.transport.getRun(n,o.signal),this.transport.getHistory(n,o.signal)]);if(!this.live(r))return;const u=Tt(l),f=Tt(u==null?void 0:u.waiting),h=Wr(u);if(await this.ingestHistory(c,n,r),!this.live(r))return;if(this.set({...this.snapshot,run:u,status:h,loading:!1,...f&&!bs(h)?{interaction:this.interactionWith({runId:n,wait:f})}:{}}),u&&this.updateRunState(n,u),f)for(const m of Gw({result:{wait:f}}))m!==n&&this.catchUpAndWatch(m,r);await this.catchUpAndWatch(n,r),this.pollRootLifecycle(n,r)}catch(l){!o.signal.aborted&&this.live(r)&&this.fail(l)}}async sendCommand(t,n={}){var m,g;t==="cancel"&&(this.toolApprovalStopped=!0,this.revokeToolApproval(),this.stopRequested=!0,this.recomputeStop());const r=jt(n.wait_key),o=t==="resume"?r?this.interactionRunId()||this.rootRunId:this.rootRunId:t==="emit_event"?this.interactionRunId()||this.rootRunId:this.rootRunId;if(!o)throw new Error("No workflow run is loaded");const l=t==="resume"&&r&&((m=this.snapshot.interaction)==null?void 0:m.stepId)||"",c=`${o}\0${t}\0${l}\0${mp(n)}`;let u=this.commandIds.get(c);u||(u=this.newCommandId(),this.commandIds.set(c,u));const f=this.generation,h=(g=this.controller)==null?void 0:g.signal;try{const y=await this.transport.submitCommand({command_id:u,run_id:o,type:t,payload:n,...this.options.clientId?{client_id:this.options.clientId}:{}},h);if(!this.live(f))return y;const w=Tt(y);if(w&&w.accepted===!1)throw t==="cancel"&&(this.stopRequested=!1,this.recomputeStop()),new Error(jt(w.detail)||"Gateway did not accept the command");return this.commandIds.delete(c),o===this.rootRunId&&["pause","resume","cancel"].includes(t)&&this.refreshRunState(o,f),y}catch(y){throw this.live(f)&&this.fail(y,!1),y}}resume(t){const n=this.requireInteraction();return this.sendCommand("resume",{wait_key:jt(n.wait.wait_key),payload:{response:t}})}approve(t,n){const r=this.requireInteraction();if(bs(this.snapshot.status))throw new Error("This run has already ended.");if(n&&(r.runId!==n.runId||jt(r.wait.wait_key)!==n.waitKey||n.stepId!==void 0&&r.stepId!==n.stepId))throw new Error("This approval request has changed. Review the current request before deciding.");if(t&&this.toolApprovalPolicy&&!this.toolCallsMatch(r,this.toolApprovalPolicy.enabledTools))throw new Error("This request includes an unavailable or unselected tool. It cannot be authorized. Deny this request or stop the run and change Tools settings.");const o=this.generation;return this.sendCommand("resume",{wait_key:jt(r.wait.wait_key),payload:{approved:!!t}}).then(l=>{if(!this.live(o))return l;const c=this.occurrenceKey(r);return this.approvedWaits.add(c),t&&this.isToolApproval(r)&&!this.grantedToolWaits.has(c)&&(this.grantedToolWaits.add(c),this.set({...this.snapshot})),l})}async approveWithPolicyChange(t,n){const r=this.generation,o=this.approvalEpoch;if(!this.isToolApproval(this.requireInteraction()))throw new Error("This is not a tool approval request.");await this.approve(!0,t),!(!this.live(r)||o!==this.approvalEpoch||this.toolApprovalStopped||bs(this.snapshot.status))&&n()}async allowAllToolsForRun(t){const n=this.generation,r=this.approvalEpoch,o=this.requireInteraction();if(!this.isToolApproval(o))throw new Error("This is not a tool approval request.");await this.approve(!0,t),!(!this.live(n)||r!==this.approvalEpoch||bs(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){mp(t)!==mp(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}:${jt(t.wait.wait_key)}${t.stepId?`:${t.stepId}`:""}`}interactionWith(t){const n=this.snapshot.interaction;return n&&_p(t.wait)&&!_p(n.wait)?n:n&&Hw(n,t)&&t.stepId===void 0&&n.stepId!==void 0?{...t,stepId:n.stepId}:t}adoptDurableWait(t,n){const r=Tt(n.waiting);if(!r||Wr(n)!=="waiting"||_p(r)||bs(this.snapshot.status)||this.resolvedWaits.has(`${t}:${jt(r.wait_key)}`))return;const o=this.interactionWith({runId:t,wait:r}),l=this.snapshot.interaction;l&&Hw(l,o)&&l.stepId===o.stepId||this.set({...this.snapshot,interaction:o})}coveredByStandingPermission(t,n){var r;return t.loading||this.toolApprovalStopped||this.toolApprovalSuspended||!this.toolApprovalPolicy&&!t.autoApproveTools||bs(t.status)||((r=t.run)==null?void 0:r.paused)===!0||t.status==="paused"||!n||!this.isToolApproval(n)||this.toolApprovalPolicy&&(!this.toolCallsMatch(n,this.toolApprovalPolicy.enabledTools)||!this.toolCallsMatch(n,this.toolApprovalPolicy.autoApproveTools))?!1:!!jt(n.wait.wait_key)}present(t){const n=t.interaction,r=n?this.occurrenceKey(n):"",o=!!(n&&this.isToolApproval(n)&&(this.grantedToolWaits.has(r)||!this.approvedWaits.has(r)&&this.coveredByStandingPermission({...t,loading:!1},n)));if(!o&&!this.snapshot.toolApprovalGranted&&!t.toolApprovalGranted)return t.toolApprovalGranted===!1?t:{...t,toolApprovalGranted:!1};let l=!1;const c=t.messages.map(u=>{var m;const f=u.toolActivity;if(!f||((m=this.toolActivities.get(f.id))==null?void 0:m.status)!=="waiting")return u;const h=o&&f.runId===(n==null?void 0:n.runId)?"running":"waiting";return f.status===h?u:(l=!0,this.toolMessage({...f,status:h}))});return{...t,toolApprovalGranted:o,...l?{messages:c}:{}}}toolCallsMatch(t,n){var o;const r=bf((o=Tt(t.wait.details))==null?void 0:o.tool_calls);return r.length>0&&r.every(l=>{var u;const c=jt((u=Tt(l))==null?void 0:u.name);return!!c&&n.includes(c)})}isToolApproval(t){const n=Tt(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:jt(t.wait.wait_key),stepId:t.stepId},r=this.occurrenceKey(t);if(this.approvedWaits.has(r))return;this.approvedWaits.add(r),this.grantedToolWaits.add(r);const o=this.generation,l=this.approvalEpoch;this.approve(!0,n).catch(c=>{if(this.live(o)){if(this.grantedToolWaits.delete(r),l!==this.approvalEpoch){this.set({...this.snapshot});return}this.toolApprovalSuspended=!0,this.set({...this.snapshot,autoApproveTools:!1}),this.fail(c,!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(!jt(this.snapshot.interaction.wait.wait_key))throw new Error("The workflow wait has no wait_key");return this.snapshot.interaction}interactionRunId(){var t;return((t=this.snapshot.interaction)==null?void 0:t.runId)||""}live(t){var n;return t===this.generation&&!((n=this.controller)!=null&&n.signal.aborted)}set(t){this.snapshot=this.present(t);for(const n of this.subscribers)n();this.autoApproveCurrentWait()}async catchUpAndWatch(t,n){var r;if(!(!this.live(n)||this.watchedRuns.has(t))){this.watchedRuns.add(t);try{if(t!==this.rootRunId)try{const o=Tt(await this.transport.getRun(t,(r=this.controller)==null?void 0:r.signal));if(!this.live(n))return;o&&this.updateRunState(t,o)}catch(o){if(!this.live(n))return;if(ol(o))throw o;this.fail(o,!1)}if(await this.catchUp(t,n),!this.live(n)||bs(Wr(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(ol(o)){this.fail(o);return}const l=(this.childCatchUpAttempts.get(t)||0)+1;if(this.childCatchUpAttempts.set(t,l),this.fail(o,!1),l>=5)return;await this.waitForRetry(Math.min(2e3,150*2**(l-1))),this.live(n)&&this.catchUpAndWatch(t,n)}}}async catchUp(t,n){var r;for(let o=0;o<100&&this.live(n);o+=1){const l=this.cursors.get(t)||0,c=await this.transport.getLedger(t,l,(r=this.controller)==null?void 0:r.signal);if(!this.live(n))return;const u=Tt(c),f=Array.isArray(c)?c:bf(u==null?void 0:u.items);for(const m of f)this.ingestItem(t,m);const h=Number(u==null?void 0:u.next_after);if(!f.length||!Number.isFinite(h)||h<=l)break;this.cursors.set(t,h)}}async watch(t,n){try{await this.followStream(t,n)}finally{this.live(n)&&this.closeLiveRepliesVia(t)}}async followStream(t,n){var o;let r=0;for(;this.live(n)&&!bs(Wr(this.runStates.get(t)||null));){const l=this.cursors.get(t)||0;this.set({...this.snapshot,connection:r?"reconnecting":"connecting"});try{let c=!1;const u=()=>{!this.live(n)||c||(c=!0,this.set({...this.snapshot,connection:"connected",error:null}))};if(this.dropLiveRepliesVia(t),await this.transport.streamLedger(t,l,h=>{this.live(n)&&(u(),this.ingestItem(t,h))},this.controller.signal,u,h=>{this.live(n)&&(u(),this.ingestDelta(t,h))}),!this.live(n)||(await this.catchUp(t,n),!this.live(n)))return;const f=Tt(await this.transport.getRun(t,(o=this.controller)==null?void 0:o.signal));if(!this.live(n))return;f&&this.updateRunState(t,f),r+=1}catch(c){if(!this.live(n))return;if(r+=1,this.fail(c,!1),ol(c)){this.set({...this.snapshot,connection:"disconnected"});return}}if(r>=5||!this.live(n))break;await this.waitForRetry(Math.min(2e3,150*2**(r-1)))}if(this.live(n)){if(bs(Wr(this.runStates.get(t)||null))){this.set({...this.snapshot,connection:"disconnected"});return}this.set({...this.snapshot,connection:"disconnected",error:this.snapshot.error||"Ledger stream reconnect limit reached. Reconnect the workflow to continue."})}}async ingestHistory(t,n,r){const o=Tt(t);if(!o)return;const l=Tt(o.session),c=bf(l==null?void 0:l.turns).map(Tt).filter(h=>!!h);if(await this.hydrateHistoricalSessionRuns(c,n,r),!this.live(r))return;for(const h of c){const m=jt(h==null?void 0:h.run_id)||n;this.ingestSessionTurn(h,n,m!==n&&this.historicalRuns.get(m)||null)}const u=`turn:${n}:user`;if(!this.seenMessages.has(u)){const h=qw(Tt(o.input_data));h&&this.addMessage({id:u,role:"user",content:h})}const f=Tt(o.ledgers);if(f)for(const[h,m]of Object.entries(f)){const g=Tt(m);for(const y of bf(g==null?void 0:g.items))this.ingestItem(h,y)}}ingestSessionTurn(t,n,r){if(!t)return;const o=jt(t.run_id)||n,l=Tt(t.input_data)||Tt(t.input)||{},c=jt(t.prompt)||qw(l);c&&this.addMessage({id:`turn:${o}:user`,role:"user",content:c,ts:jt(t.created_at)||void 0});const u=this.historicalRunFailures.get(o);if(u){const g=jt(t.answer)||hg(t.output),y=u.missing?"is unavailable because the run no longer exists":"could not be restored",w=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 ${y}.${w}`});return}const h=(r&&bs(Wr(r))?xu(r.output):"")||(r?jt(t.answer)||hg(t.output):""),m=this.historicalEvidence.get(o);for(const g of(m==null?void 0:m.tools)||[])this.upsertTool(g);h&&this.addRunAssistantMessage(o,{id:`final:${o}`,role:"assistant",content:h,runId:o,statistics:m==null?void 0:m.statistics,ts:jt(t.updated_at)||void 0})}async hydrateHistoricalSessionRuns(t,n,r){const o=[...new Set(t.map(f=>jt(f.run_id)).filter(f=>f&&f!==n&&!this.historicalRuns.has(f)&&!this.historicalRunFailures.has(f)))];if(!o.length||!this.live(r))return;let l=0,c=!1;const u=async()=>{var f,h,m;for(;!c&&this.live(r);){const g=o[l++];if(!g)return;try{const y=Tt(await this.transport.getRun(g,(f=this.controller)==null?void 0:f.signal));if(!this.live(r))return;if(y){this.historicalRuns.set(g,y);try{const w=await this.transport.getHistory(g,(h=this.controller)==null?void 0:h.signal);if(!this.live(r))return;this.historicalEvidence.set(g,hp(_E(w)))}catch(w){if(!this.live(r))return;if(ol(w))throw w;this.fail(new Error(`Earlier turn activity could not be restored: ${w instanceof Error?w.message:String(w)}`),!1)}}else this.historicalRuns.set(g,null),this.historicalRunFailures.set(g,{missing:!1,detail:"gateway returned an invalid historical run snapshot"})}catch(y){if(!this.live(r))return;const w=bE(y)===404;this.historicalRuns.set(g,null),this.historicalRunFailures.set(g,{missing:w,detail:y instanceof Error?y.message:jt((m=Tt(y))==null?void 0:m.detail)||"request failed"}),ol(y)&&(c=!0,this.fail(y))}}};if(await Promise.all(Array.from({length:Math.min(4,o.length)},()=>u())),c&&this.live(r))for(const f of o)!this.historicalRuns.has(f)&&!this.historicalRunFailures.has(f)&&(this.historicalRuns.set(f,null),this.historicalRunFailures.set(f,{missing:!1,detail:"authorization expired before this historical run could be restored"}))}ingestItem(t,n){const r=Tt(n),o=Tt(r==null?void 0:r.record)||r;if(!o)return;const l=kE(o,t),c=Number(r==null?void 0:r.cursor),u=Number.isFinite(c)&&c>0?c:(this.cursors.get(l)||0)+1,f=`${l}:${u}`;if(!this.seenRecords.has(f)){if(this.seenRecords.add(f),this.cursors.set(l,Math.max(this.cursors.get(l)||0,u)),this.set({...this.snapshot,records:[...this.snapshot.records,{cursor:u,record:o,runId:l}]}),this.foldRecord(l,o,f),this.snapshot.messages.some(h=>h.id===`final:${this.rootRunId}`)){const h=hp(this.snapshot.records).statistics;this.set({...this.snapshot,messages:this.snapshot.messages.map(m=>m.id===`final:${this.rootRunId}`?{...m,statistics:h}:m)})}for(const h of Gw(o))h!==l&&this.catchUpAndWatch(h,this.generation)}}foldRecord(t,n,r){var m,g,y;const o=mg(n),l=jt(o.type).toLowerCase(),c=Tt(n.result),u=jt(n.status).toLowerCase(),f=Vw(n);if(this.foldStopEvidence(t,n,l,u),["llm_call","tool_calls"].includes(l)&&["started","running"].includes(u)){const w=Date.parse(f||"");(!Number.isFinite(w)||w>=this.displayStatusAt)&&(Number.isFinite(w)&&(this.displayStatusAt=w),this.snapshot.displayStatus&&this.set({...this.snapshot,displayStatus:""}))}if(l==="answer_user"&&u==="completed"){const w=xu(c)||xu(Tt(o.payload));w&&this.addRunAssistantMessage(t,{id:`answer:${t}:${r}`,role:"assistant",content:w,ts:f})}if(l==="emit_event"&&u==="completed"){const w=Tt(o.payload)||{},k=Tt(c),b=jt(w.name)||jt(k==null?void 0:k.name),S=w.payload!==void 0?w.payload:k==null?void 0:k.payload;if(["abstract.message","abstractcode.message"].includes(b)){const N=xu(S);if(N){const R=jt((m=Tt(S))==null?void 0:m.level).toLowerCase(),T=R==="error"?"error":["warn","warning"].includes(R)?"warn":"info";this.addMessage({id:`event:${t}:${r}`,role:"system",title:"Workflow",content:N,level:T,ts:f})}}if(["abstract.status","abstractcode.status"].includes(b)){const N=Tt(S),R=N?N.status??N.text??N.value:S,T=Date.parse(f||"");!bs(this.snapshot.status)&&typeof R=="string"&&(!Number.isFinite(T)||T>=this.displayStatusAt)&&(Number.isFinite(T)&&(this.displayStatusAt=T),this.set({...this.snapshot,displayStatus:R.trim()}))}if(["abstract.tool_execution","abstractcode.tool_execution","abstract.tool_result","abstractcode.tool_result"].includes(b)){const N=xu(S);N&&this.addMessage({id:`event:${t}:${r}`,role:"system",title:"Tool activity",content:N,ts:f})}}const h=n0(n);if(u==="waiting"&&h&&!bs(this.snapshot.status)&&!bs(Wr(this.runStates.get(t)||null))&&(this.resolvedWaits.delete(`${t}:${jt(h.wait_key)}`),this.set({...this.snapshot,interaction:this.interactionWith({runId:t,wait:h,...jt(n.step_id)?{stepId:jt(n.step_id)}:{}})})),l==="tool_calls")for(const w of e0(this.toolActivities,{runId:t,cursor:this.cursors.get(t)||0,record:n}))this.upsertTool(w);if(l==="resume"&&(c==null?void 0:c.resumed)===!0){const w=jt((g=Tt(o.payload))==null?void 0:g.wait_key);w&&this.resolvedWaits.add(`${t}:${w}`),((y=this.snapshot.interaction)==null?void 0:y.runId)===t&&(this.set({...this.snapshot,interaction:null}),this.refreshRunState(t,this.generation))}}foldStopEvidence(t,n,r,o){let l=!1;if(r==="llm_call"){const c=jt(n.step_id);if(c){const u=`${t}:${c}`;o==="started"?(this.openLlmSteps.add(u),l=!0):["completed","failed","cancelled","waiting"].includes(o)&&(l=this.openLlmSteps.delete(u)||l),["completed","failed","cancelled"].includes(o)&&this.closeLiveReply(u)}}if(r==="emit_event"&&o==="completed"){const c=Tt(mg(n).payload)||{},u=Tt(n.result),f=jt(c.name)||jt(u==null?void 0:u.name),h=Tt(c.payload!==void 0?c.payload:u==null?void 0:u.payload);f==="abstract.status"&&jt(h==null?void 0:h.killed_by)==="kill_switch"&&(this.forcedStop=h,l=!0)}l&&this.recomputeStop()}recomputeStop(){let t=null;this.forcedStop?t={phase:"forced",label:jt(this.forcedStop.text)||"Stop forced: inference killed",record:this.forcedStop}:this.stopRequested&&(t=this.snapshot.status==="cancelled"&&this.openLlmSteps.size===0?{phase:"stopped",label:"Stopped"}:{phase:"stopping",label:"Stopping…"});const n=this.snapshot.stop||null;((n==null?void 0:n.phase)!==(t==null?void 0:t.phase)||(n==null?void 0:n.label)!==(t==null?void 0:t.label))&&this.set({...this.snapshot,stop:t}),(t==null?void 0:t.phase)==="stopping"&&this.snapshot.status==="cancelled"&&this.followStop(this.generation)}async followStop(t){var n;if(!this.stopFollowing){this.stopFollowing=!0;try{let r=500,o=null;for(;this.live(t)&&((n=this.snapshot.stop)==null?void 0:n.phase)==="stopping";){if(await this.waitForRetry(r),!this.live(t))return;const l=[this.rootRunId,...[...this.watchedRuns].filter(u=>u!==this.rootRunId)];let c=!1;for(const u of l)try{await this.catchUp(u,t)}catch(f){c=!0,this.live(t)&&(this.fail(f,!1),o=this.snapshot.error)}!c&&o&&this.snapshot.error===o&&(this.set({...this.snapshot,error:null}),o=null),r=Math.min(5e3,r*2)}}finally{this.generation===t&&(this.stopFollowing=!1)}}}addMessage(t){const n=jt(t.id)||`${t.role}:${t.content}:${t.ts||""}`;this.seenMessages.has(n)||(this.seenMessages.add(n),this.set({...this.snapshot,messages:[...this.snapshot.messages,{...t,id:n}]}))}toolMessage(t){return{id:`tool:${t.id}`,role:"system",kind:"tool_activity",title:"Tool activity",runId:t.runId,toolActivity:t,content:JSON.stringify({tool:t.name,status:t.status,arguments:t.arguments,output:t.output,error:t.error},null,2),ts:t.endedAt||t.startedAt}}upsertTool(t){const n=this.toolMessage(t),r=this.snapshot.messages.findIndex(l=>l.id===n.id);if(r<0){this.addMessage(n);return}const o=[...this.snapshot.messages];o[r]=n,this.set({...this.snapshot,messages:o})}addRunAssistantMessage(t,n){this.closeLiveRepliesOfRun(t);const r=`answer:${t}:`,o=`final:${t}`;this.snapshot.messages.some(l=>l.role==="assistant"&&l.content===n.content&&(l.id===o||String(l.id||"").startsWith(r)))||this.addMessage(n)}ingestDelta(t,n){let r;try{r=Kb(n)}catch(f){this.fail(f,!1);return}const o=`${r.run_id}:${r.call_id}`;if(Gb(r)){if(r.reason==="unavailable"){this.noteStreamUnavailable(r);return}if(r.reason==="cancelled"&&r.detail==="reinvoked"){this.closeLiveReply(o,"restarted");return}this.closeLiveReply(o,r.reason==="completed"?void 0:r.reason);return}if(this.closedLiveCalls.has(o)||this.runEnded(r.run_id)||this.runEnded(this.rootRunId))return;const l=this.liveReplies.get(o)||{runId:r.run_id,callId:r.call_id,nodeId:r.node_id||"",via:t,text:"",reasoning:"",seq:{content:-1,reasoning:-1}},c=r.channel==="reasoning"?"reasoning":"text",u=l.seq[r.channel];if(r.snapshot){if(r.seq<u)return;l[c]=r.text}else{if(r.seq<=u)return;l[c]+=r.text}l.seq[r.channel]=r.seq,l.via=t,this.liveReplies.set(o,l),this.liveDirty.add(o),this.scheduleLiveRender()}runEnded(t){return bs(Wr(this.runStates.get(t)||null))}scheduleLiveRender(){if(this.liveRenderTimer)return;const t=this.lastLiveRender+this.liveRenderIntervalMs-Date.now();if(t<=0){this.renderLiveReplies();return}this.liveRenderTimer=setTimeout(()=>{this.liveRenderTimer=null,this.renderLiveReplies()},t)}renderLiveReplies(){if(this.lastLiveRender=Date.now(),!this.liveDirty.size)return;const t=[...this.snapshot.messages];for(const n of this.liveDirty){const r=this.liveReplies.get(n);if(!r)continue;const o=this.liveMessage(r),l=t.findIndex(c=>c.id===o.id);l<0?t.push(o):t[l]=o,this.shownLiveCalls.add(n)}this.liveDirty.clear(),this.set({...this.snapshot,messages:t})}liveMessage(t){const n=t.runId!==this.rootRunId;return{id:`live:${t.runId}:${t.callId}`,role:"assistant",content:t.text,runId:t.runId,live:{callId:t.callId,reasoning:t.reasoning,...n?{caption:`sub-agent · ${t.nodeId||t.runId}`}:{}}}}closeLiveReply(t,n){this.closedLiveCalls.add(t);const r=this.liveReplies.get(t);if(!r){n==="restarted"&&this.shownLiveCalls.has(t)&&this.addMessage(this.restartNote(t));return}this.liveReplies.delete(t),this.liveDirty.delete(t);const o=`live:${r.runId}:${r.callId}`,l=this.snapshot.messages.findIndex(u=>u.id===o);if(l<0)return;const c=[...this.snapshot.messages];if(n==="restarted"){const u=this.restartNote(t);this.seenMessages.add(String(u.id)),c[l]=u}else if(n){const u=`live-end:${r.runId}:${r.callId}`;this.seenMessages.add(u),c[l]={id:u,role:"system",level:"warn",title:"Reply",runId:r.runId,content:n==="failed"?"The reply stopped because the model call failed.":"The reply stopped because the model call was cancelled."}}else c.splice(l,1);this.set({...this.snapshot,messages:c})}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:kC(t.detail)})}closeLiveRepliesOfRun(t){for(const n of[...this.liveReplies.values()])n.runId===t&&this.closeLiveReply(`${n.runId}:${n.callId}`)}closeLiveRepliesVia(t,n){for(const r of[...this.liveReplies.values()])(r.via===t||r.runId===t)&&this.closeLiveReply(`${r.runId}:${r.callId}`,n)}endLiveRepliesOfRun(t,n){const r=n==="failed"||n==="cancelled"?n:void 0;if(t===this.rootRunId){for(const o of[...this.liveReplies.values()])this.closeLiveReply(`${o.runId}:${o.callId}`,r);this.closedLiveCalls.clear(),this.shownLiveCalls.clear();return}this.closeLiveRepliesVia(t,r);for(const o of[...this.closedLiveCalls])o.startsWith(`${t}:`)&&this.closedLiveCalls.delete(o);for(const o of[...this.shownLiveCalls])o.startsWith(`${t}:`)&&this.shownLiveCalls.delete(o)}dropLiveRepliesVia(t){const n=new Set;for(const[r,o]of this.liveReplies)o.via===t&&(this.liveReplies.delete(r),this.liveDirty.delete(r),n.add(`live:${o.runId}:${o.callId}`));n.size&&this.set({...this.snapshot,messages:this.snapshot.messages.filter(r=>!n.has(String(r.id)))})}fail(t,n=!0){var r,o,l;ol(t)&&(this.approvalEpoch+=1,this.toolApprovalStopped=!0,this.toolApprovalSuspended=!0,(o=(r=this.options).onAuthError)==null||o.call(r,t)),this.set({...this.snapshot,error:t instanceof Error?t.message:jt((l=Tt(t))==null?void 0:l.detail)||String(t),...ol(t)?{autoApproveTools:!1}:{},...n?{connection:"disconnected"}:{}})}newCommandId(){const t=globalThis.crypto;if(t&&typeof t.randomUUID=="function")return t.randomUUID();if(t&&typeof t.getRandomValues=="function"){const n=t.getRandomValues(new Uint8Array(16));n[6]=n[6]&15|64,n[8]=n[8]&63|128;const r=Array.from(n,o=>o.toString(16).padStart(2,"0")).join("");return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20)}`}return`workflow-${Date.now()}-${Math.random().toString(36).slice(2)}`}updateRunState(t,n){var l;if(this.runStates.set(t,n),bs(Wr(n))&&this.endLiveRepliesOfRun(t,Wr(n)),t!==this.rootRunId){bs(Wr(n))&&((l=this.snapshot.interaction)==null?void 0:l.runId)===t?this.set({...this.snapshot,interaction:null}):this.adoptDurableWait(t,n);return}const r=Wr(n),o=bs(r);if(o){const c=xu(n.output);c&&this.upsertFinal(t,c,Vw(n))}this.set({...this.snapshot,run:n,status:r,...o?{interaction:null,autoApproveTools:!1,displayStatus:""}:{}}),o||this.adoptDurableWait(t,n),(this.stopRequested||this.forcedStop)&&this.recomputeStop()}upsertFinal(t,n,r){this.closeLiveRepliesOfRun(t);const o=`final:${t}`;this.seenMessages.add(o);const l={id:o,role:"assistant",content:n,ts:r,runId:t,statistics:hp(this.snapshot.records).statistics},c=this.snapshot.messages.findIndex(f=>f.id===o||String(f.id||"").startsWith(`answer:${t}:`)&&f.content===n);if(c<0){this.set({...this.snapshot,messages:[...this.snapshot.messages,l]});return}const u=[...this.snapshot.messages];u[c]=l,this.set({...this.snapshot,messages:u})}async refreshRunState(t,n){var r;try{const o=Tt(await this.transport.getRun(t,(r=this.controller)==null?void 0:r.signal));o&&this.live(n)&&this.updateRunState(t,o)}catch(o){this.live(n)&&this.fail(o,!1)}}async pollRootLifecycle(t,n){var r;for(;this.live(n)&&this.rootRunId===t&&!bs(Wr(this.runStates.get(t)||null));){if(await this.waitForRetry(2e3),!this.live(n)||this.rootRunId!==t||bs(Wr(this.runStates.get(t)||null)))return;try{const o=Tt(await this.transport.getRun(t,(r=this.controller)==null?void 0:r.signal));o&&this.live(n)&&this.rootRunId===t&&this.updateRunState(t,o)}catch(o){if(!this.live(n))return;if(ol(o)){this.fail(o);return}this.fail(o,!1)}}}waitForRetry(t){var o;const n=(o=this.controller)==null?void 0:o.signal;if(!n||n.aborted)return Promise.resolve();const r=n;return new Promise(l=>{const c=setTimeout(f,t),u=()=>{clearTimeout(c),f()};function f(){r.removeEventListener("abort",u),l()}r.addEventListener("abort",u,{once:!0})})}}function SE(e){const t=_.useMemo(()=>new jE(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()),r=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||!r){t.reset();return}return t.load(r),()=>t.reset()},[t,r,e.enabled]),{controller:t,snapshot:n}}function rc(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function ur(e){return typeof e=="string"?e.trim():e==null?"":typeof e=="number"||typeof e=="boolean"?String(e):""}function Kw(e){return["session","workflow","run","global"].includes(e)?e:null}function ll(e){return{scope:ur(e==null?void 0:e.scope).toLowerCase(),name:ur(e==null?void 0:e.name)||ur(e==null?void 0:e.event_name),scopeId:ur(e==null?void 0:e.scope_id)||ur(e==null?void 0:e.scopeId),sessionId:ur(e==null?void 0:e.session_id)||ur(e==null?void 0:e.sessionId),workflowId:ur(e==null?void 0:e.workflow_id)||ur(e==null?void 0:e.workflowId),runId:ur(e==null?void 0:e.run_id)||ur(e==null?void 0:e.runId)}}function NE(e,t){const n=e.wait,r=ur(n.wait_key),o=[ll(n),ll(rc(n.details))];for(const l of t){if(l.runId!==e.runId)continue;const c=l.record,u=rc(c.result),f=rc(u==null?void 0:u.wait),h=rc(c.effect),m=rc(h==null?void 0:h.payload);ur(f==null?void 0:f.wait_key)!==r&&ur(m==null?void 0:m.wait_key)!==r||o.push(ll(c),ll(m),ll(rc(m==null?void 0:m.details)),ll(f),ll(rc(f==null?void 0:f.details)))}return o}function pp(e,t){return t.scopeId?t.scopeId:e==="session"?t.sessionId:e==="workflow"?t.workflowId:e==="run"?t.runId:"global"}function s0(e,t,n){return{scope:e,scopeId:t,name:n,...e==="session"?{sessionId:t}:{},...e==="workflow"?{workflowId:t}:{},...e==="run"?{runId:t}:{}}}function CE(e,t,n){if(!n)return null;const r=`evt:${t}:${n}:`;if(!e.startsWith(r))return null;const o=e.slice(r.length);return o?s0(t,n,o):null}function EE(e,t=[],n){if(!e)return{target:null,error:"No event wait is available."};const r=ur(e.wait.wait_key),o=/^evt:(session|workflow|run|global):/.exec(r);if(!o)return{target:null,error:"The gateway did not provide a canonical event wait key."};const l=Kw(o[1]);if(!l)return{target:null,error:"The event wait uses an unsupported scope."};const c=NE(e,Array.isArray(t)?t:[]),u=new Map;for(const y of c){const w=Kw(y.scope);if(!w||!y.name)continue;if(w!==l)return{target:null,error:"Event metadata conflicts with the canonical wait scope."};const k=`evt:${w}:`,b=`:${y.name}`;if(!r.startsWith(k)||!r.endsWith(b)||r.length<=k.length+b.length)return{target:null,error:"Event metadata does not exactly match the canonical wait key."};const S=r.slice(k.length,-b.length),N=pp(w,y);if(N&&N!==S)return{target:null,error:"Event metadata conflicts with the canonical wait target."};const R=s0(w,S,y.name);u.set(`${R.scope}\0${R.scopeId}\0${R.name}`,R)}if(u.size>1)return{target:null,error:"Multiple event targets match this wait; routing is unavailable."};if(u.size===1)return{target:[...u.values()][0]};const f=new Set;l==="run"&&f.add(e.runId),l==="global"&&f.add("global");for(const y of c){const w=pp(l,y);w&&f.add(w)}if(ur(n==null?void 0:n.run_id)===e.runId){const y=ll(n||null),w=pp(l,y);w&&f.add(w)}const m=[...f].map(y=>CE(r,l,y)).filter(y=>!!y),g=new Map(m.map(y=>[`${y.scope}\0${y.scopeId}\0${y.name}`,y]));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."}}function r0(e){return s.jsx(Db,{text:e,images:"link"})}const $E={trigger:"Trigger",answer:"Automation"};function i0(e,t){return s.jsx(ny,{...t,message:{id:`${e.runId}:${e.kind}`,role:e.role,content:e.text,title:$E[e.kind],runId:e.runId},images:"link"})}const AE={renderText:r0,renderTurn:i0};function TE(e){const{fetchGateway:t,messageProps:n,...r}=e,o=r.onOpenResource??(t?l=>KC(t,l.url,{name:l.name}):void 0);return s.jsx(W1,{...r,onOpenResource:o,...AE,renderTurn:l=>i0(l,n)})}function ME(e,t,n={}){if(!e)return null;const r=e.wait,o=`${e.runId}:${r.wait_key}:${e.stepId||""}`,l=r.details||{};if(l.mode==="approval_required"||l.kind==="tool_approval"){const u=Array.isArray(l.tool_calls)?l.tool_calls:[],f={runId:e.runId,waitKey:String(r.wait_key||""),stepId:e.stepId},h=[...new Set(u.map(g=>String((g==null?void 0:g.name)||"tool")))],m=n.onPermissionsAll;return{id:o,kind:"tool-approval",title:`${u.length||"Requested"} ${u.length===1?"action needs":"actions need"} permission`,toolName:h.join(", ")||"the requested tools",description:"Review the targets below. Allow once approves this batch only.",detail:s.jsxs("div",{className:"pc-approval-summary",children:[s.jsx(Ub,{tools:u.map((g,y)=>({id:String((g==null?void 0:g.call_id)||(g==null?void 0:g.id)||y),runId:e.runId,name:(g==null?void 0:g.name)||"Tool",arguments:g==null?void 0:g.arguments,status:"waiting"}))}),s.jsxs("details",{children:[s.jsx("summary",{children:"Review full tool arguments (JSON)"}),s.jsx(Is,{value:u.length?u:l})]})]}),approveLabel:"Allow once",denyLabel:"Deny",approveAllLabel:m?"Allow all enabled tools":void 0,approveAllDescription:m?"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:m?async()=>{await t.approveWithPolicyChange(f,()=>{m()})}:void 0,onApprove:async()=>{await t.approve(!0,f)},onDeny:async()=>{await t.approve(!1,f)}}}if(r.reason==="user"||r.reason==="ask_user")return{id:o,kind:"ask-user",title:"A question for you",prompt:String(r.prompt||l.prompt||"How would you like to continue?"),allowFreeText:r.allow_free_text!==!1,choices:(Array.isArray(r.choices)?r.choices:[]).map(u=>typeof u=="object"&&u!==null?{id:String(u.value??u.id??u.label),label:String(u.label??u.text??u.value??u.id),description:u.description}:{id:String(u),label:String(u)}),onSubmit:async u=>{await t.resume(u)}};const c=String(r.wait_key||"");if(r.reason==="event"||c.startsWith("evt:")){const u=EE(e,n.records||[],n.currentRun??null),f=u.target,h=(f==null?void 0:f.name)||"";return{id:o,kind:"event-wait",title:f?"Waiting for an event":"Event routing unavailable",eventName:h,prompt:String(r.prompt||`This workflow will continue when “${h||"its trigger"}” arrives.`),description:f?"You can also send the expected event here.":`This event cannot be sent safely. ${u.error}`,initialPayload:"{}",payloadLabel:"Event data (JSON)",sendLabel:"Send event",onSend:async m=>{if(!f)throw new Error(u.error);const g=JSON.parse(m||"{}"),y={name:f.name,scope:f.scope,payload:g};f.scope==="session"?y.session_id=f.scopeId:f.scope==="workflow"?y.workflow_id=f.scopeId:f.scope==="run"&&(y.run_id=f.scopeId),await t.emitEvent(y)}}}return null}const RE={app:"observer",name:"AbstractObserver"},LE=["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?"];function IE(e){const t=_.useRef(e.gateway);t.current=e.gateway;const n=(r,o)=>t.current.fetch_gateway(r,o);return s.jsx(dE,{open:e.open,onClose:e.onClose,source:RE,fetchGateway:n,connected:e.connected,topOffset:e.topOffset,placeholder:"Ask about the observer…",suggestions:LE})}function OE(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 PE(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 DE(e,t,n){return e<=0?-1:t<0?n?e-1:0:(t+(n?e-1:1))%e}const FE='a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';function zE(e){return typeof document>"u"?!1:Array.from(document.querySelectorAll('[role="dialog"][aria-modal="true"]')).some(t=>t!==e)}function BE(e){const[t,n]=_.useReducer(OE,!1),r=_.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 c;if(t){l.current=!0;const u=o.current,f=(u==null?void 0:u.querySelector(".shell_nav_item.active"))||(u==null?void 0:u.querySelector(".shell_nav_item"));f==null||f.focus();const h=m=>{if(m.key==="Escape"){n({type:"escape",default_prevented:m.defaultPrevented,other_modal_open:zE(o.current)});return}if(m.key!=="Tab"||!o.current)return;const g=Array.from(o.current.querySelectorAll(FE)).filter(w=>w.offsetParent!==null||w===document.activeElement),y=DE(g.length,g.indexOf(document.activeElement),m.shiftKey);y>=0&&(m.preventDefault(),g[y].focus())};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)}l.current&&(l.current=!1,(c=r.current)==null||c.focus())},[t]),{open:t,set_open:c=>n({type:c?"open":"close"}),toggle_ref:r,sidebar_ref:o,attrs:PE(e.is_drawer,t)}}function UE(e,t){return[...e.filter(n=>!n.local_error),t].map(n=>({role:n.role,content:n.content}))}function pm(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?Math.trunc(e):0}function WE(e){const t=pm(e==null?void 0:e.dropped_messages);if(!e||t<=0)return null;const n=pm(e.replayed_messages),r=pm(e.dropped_tokens),o=pm(e.max_tokens),l=[`Earlier messages not replayed: ${t.toLocaleString("en-US")}${r?` (~${r.toLocaleString("en-US")} tokens)`:""}.`,`The model read the newest ${n.toLocaleString("en-US")} message${n===1?"":"s"}`+(o?` (history window: the most recent ${o.toLocaleString("en-US")} tokens of whole messages).`:".")];return e.oversize_turn_kept&&l.push("Your latest message alone is larger than the window; it was sent whole."),l.join(" ")}function qE(e){const t=WE(e.history);return t?s.jsx(ny,{message:{role:"system",level:"info",title:"History",content:t}}):null}const HE="api/local/reveal",VE="sw.js",_g="#run/";function GE(e){return`${_g}${encodeURIComponent(String(e||"").trim())}`}function o0(e){const t=String(e||"");if(!t.startsWith(_g))return"";const n=t.slice(_g.length).split("?")[0];if(!n||n.includes("/"))return"";try{return decodeURIComponent(n).trim()}catch{return""}}function KE(e){return`Run ${e} cannot be opened: it does not exist on this gateway, or your account cannot see it.`}function YE(e){const t=o0(e.hash);if(t)return t;const n=c=>/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(c),r=c=>{const u=c.split("/").filter(Boolean);return u.length?u[u.length-1].trim():""},o=r(String(e.hash||"").replace(/^#/,""));if(n(o))return o;const l=r(String(e.pathname||""));return n(l)?l:""}const JE={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"},XE=new Set(["wait","resume","memory","model","node"]),ZE=new Set(["abstract.status","abstract.progress","abstract.steer_seen","abstract.summary"]),QE={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 e$(e){const t=String(e||"").trim();return t?JE[t]||"other":"node"}function t$(e,t,n){return n?!1:e==="event"?ZE.has(String(t||"").trim()):XE.has(e)}const n$=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 s$(e){const t=new TextEncoder().encode(e),n=t.length*8,r=t.length+9+63>>6<<6,o=new Uint8Array(r);o.set(t),o[t.length]=128;const l=new DataView(o.buffer);l.setUint32(r-8,Math.floor(n/4294967296)),l.setUint32(r-4,n>>>0);const c=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),u=new Uint32Array(64);for(let f=0;f<r;f+=64){for(let N=0;N<16;N++)u[N]=l.getUint32(f+N*4);for(let N=16;N<64;N++){const R=u[N-15],T=u[N-2],A=(R>>>7|R<<25)^(R>>>18|R<<14)^R>>>3,W=(T>>>17|T<<15)^(T>>>19|T<<13)^T>>>10;u[N]=u[N-16]+A+u[N-7]+W>>>0}let[h,m,g,y,w,k,b,S]=c;for(let N=0;N<64;N++){const R=(w>>>6|w<<26)^(w>>>11|w<<21)^(w>>>25|w<<7),T=w&k^~w&b,A=S+R+T+n$[N]+u[N]>>>0,W=(h>>>2|h<<30)^(h>>>13|h<<19)^(h>>>22|h<<10),z=h&m^h&g^m&g,J=W+z>>>0;S=b,b=k,k=w,w=y+A>>>0,y=g,g=m,m=h,h=A+J>>>0}c[0]=c[0]+h>>>0,c[1]=c[1]+m>>>0,c[2]=c[2]+g>>>0,c[3]=c[3]+y>>>0,c[4]=c[4]+w>>>0,c[5]=c[5]+k>>>0,c[6]=c[6]+b>>>0,c[7]=c[7]+S>>>0}return Array.from(c,f=>f.toString(16).padStart(8,"0")).join("")}const pg="$slim";function r$(e){return!!(e&&typeof e=="object"&&!Array.isArray(e)&&e[pg]&&typeof e[pg]=="object")}function i$(e){const t=new Map;for(const n of e||[]){if(!n||typeof n!="object"||String(n.status||"")!=="started")continue;const r=String(n.step_id||""),o=n.effect&&typeof n.effect=="object"?n.effect.payload:null;r&&o&&typeof o=="object"&&!t.has(r)&&t.set(r,o)}return t}function o$(e,t){const n=[];for(const r of t)if(r==="system"){if(typeof e.system_prompt!="string"||!e.system_prompt)return null;n.push({role:"system",content:e.system_prompt})}else if(r==="messages"){if(!Array.isArray(e.messages))return null;for(const o of e.messages)o&&typeof o=="object"&&n.push({...o})}else if(r==="prompt"){if(typeof e.prompt!="string"||!e.prompt)return null;n.push({role:"user",content:e.prompt})}else return null;return n}function a$(e,t){const n=e&&e[pg];if(!n||typeof n!="object")return{state:"missing",reason:"not a $slim marker"};const r=t.get(String(n.step_id||""));if(!r)return{state:"missing",reason:"its started record is not in the loaded ledger"};let o;if(n.kind==="started_payload_field"){const c=String(n.field||"");if(!(c in r))return{state:"missing",reason:`the started record has no "${c}" field`};o=r[c]}else if(n.kind==="started_messages_layout"){if(o=Array.isArray(n.layout)?o$(r,n.layout.map(String)):null,!o)return{state:"missing",reason:"the started record cannot rebuild these messages"}}else return{state:"missing",reason:`unknown $slim kind "${String(n.kind||"")}"`};if(Array.isArray(n.appendix)&&n.appendix.length){if(!Array.isArray(o))return{state:"missing",reason:"appendix on a non-list value"};const c=o.map(f=>f&&typeof f=="object"?{...f}:f),u=[...n.appendix].sort((f,h)=>Number((f==null?void 0:f.at)??-1)-Number((h==null?void 0:h.at)??-1));for(const f of u){const h=Number(f==null?void 0:f.at);if(!Number.isInteger(h)||h<0||h>c.length)return{state:"missing",reason:"appendix position out of range"};c.splice(h,0,f.item)}o=c}return s$(JSON.stringify(o))!==String(n.sha256||"")?{state:"unverified",value:o,reason:"checksum differs from the record"}:{state:"resolved",value:o}}function l$(e,t){const n=[],r=[],o=(l,c,u)=>{if(u>14)return l;if(r$(l)){const f=a$(l,t);return f.state==="missing"?(n.push({path:c,reason:f.reason}),l):(f.state==="unverified"&&r.push({path:c,reason:f.reason}),f.value)}if(Array.isArray(l)){let f=null;return l.forEach((h,m)=>{const g=o(h,`${c}[${m}]`,u+1);g!==h&&((f??(f=[...l]))[m]=g)}),f??l}if(l&&typeof l=="object"){let f=null;for(const h of Object.keys(l)){const m=o(l[h],c?`${c}.${h}`:h,u+1);m!==l[h]&&((f??(f={...l}))[h]=m)}return f??l}return l};return{value:o(e,"",0),unresolved:n,unverified:r}}function Yw(e){const t=Date.parse(String(e||""));return Number.isFinite(t)?t:null}function a0(e){const t=e==null?void 0:e.result;return t&&typeof t=="object"&&Array.isArray(t.results)?t.results:[]}function c$(e,t){return e?String(e.status||"")==="failed"||e.error?!0:t==="tool"&&a0(e).some(n=>n&&n.success===!1):!1}function l0(e,t){var h,m,g,y,w,k;const n=String(t||"").trim(),r=(e||[]).filter(b=>b&&b.record&&String(b.run_id||b.record.run_id||"").trim()===n).sort((b,S)=>(b.cursor||0)-(S.cursor||0)),o=i$(r.map(b=>b.record)),l=new Map,c=[];for(const b of r){const S=b.record,R=String(S.step_id||"")||`cursor:${b.cursor}`;let T=l.get(R);T||(T={cursor:b.cursor,started:null,latest:S,latest_cursor:b.cursor},l.set(R,T),c.push(R)),String(S.status||"")==="started"&&!T.started&&(T.started=S),b.cursor>=T.latest_cursor&&(T.latest=S,T.latest_cursor=b.cursor)}let u=0;const f=[];for(const b of c){const S=l.get(b),N=l$(S.latest,o),R=N.value,T=String(((h=R==null?void 0:R.effect)==null?void 0:h.type)||((g=(m=S.started)==null?void 0:m.effect)==null?void 0:g.type)||"").trim(),A=e$(T),W=A==="event"?String(((w=(y=R==null?void 0:R.effect)==null?void 0:y.payload)==null?void 0:w.name)||"").trim():"";A==="llm_call"&&(u+=1);const z=c$(R,A),J=String(((k=S.started)==null?void 0:k.started_at)||(R==null?void 0:R.started_at)||""),K=String((R==null?void 0:R.ended_at)||""),re=Yw(J),te=Yw(K);f.push({id:`${n}:${b}`,run_id:n,step_id:String((R==null?void 0:R.step_id)||""),node_id:String((R==null?void 0:R.node_id)||""),kind:A,effect_type:T,event_name:W,status:String((R==null?void 0:R.status)||""),cursor:S.cursor,started_at:J,ended_at:K,duration_ms:re!==null&&te!==null?Math.max(0,te-re):null,started:S.started,record:R,failed:z,housekeeping:t$(A,W,z),cycle:u,unresolved:N.unresolved,unverified:N.unverified})}return f}function u$(e){const t=[];for(const n of e){let r=t[t.length-1];(!r||r.cycle!==n.cycle)&&(r={cycle:n.cycle,steps:[],llm:null},t.push(r)),n.kind==="llm_call"&&!r.llm&&(r.llm=n),r.steps.push(n)}return t}const d$={view:"cycles",only:"all",all_steps:!1,q:""};function f$(e,t,n){const r=String(t.q||"").trim().toLowerCase();return e.filter(o=>!(t.only==="llm"&&o.kind!=="llm_call"||t.only==="tools"&&o.kind!=="tool"||t.only==="failed"&&!o.failed||t.only==="all"&&!t.all_steps&&o.housekeeping||r&&!n(o).includes(r)))}const h$=["all","llm","tools","failed"];function Jw(e){const t=String(e||""),n=t.indexOf("?");if(n<0)return{...d$};const r=new URLSearchParams(t.slice(n+1)),o=String(r.get("only")||"");return{view:r.get("view")==="steps"?"steps":"cycles",only:h$.includes(o)?o:"all",all_steps:r.get("all")==="1",q:String(r.get("q")||"")}}function m$(e,t){const n=String(e||"").split("?")[0],r=new URLSearchParams;t.view!=="cycles"&&r.set("view",t.view),t.only!=="all"&&r.set("only",t.only),t.all_steps&&r.set("all","1"),t.q.trim()&&r.set("q",t.q);const o=r.toString();return o?`${n}?${o}`:n}function Iu(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(`
|
|
84
|
-
`):e==null?"":JSON.stringify(e,null,2)}function c0(e){if(typeof e!="string")return e??{};try{return JSON.parse(e)}catch{return e}}function u0(e){return Array.isArray(e)?e.filter(t=>t&&typeof t=="object").map(t=>{var n,r;return{name:String(t.name||((n=t.function)==null?void 0:n.name)||"?"),arguments:c0(t.arguments??((r=t.function)==null?void 0:r.arguments))}}):[]}function Xw(e){const t={role:String((e==null?void 0:e.role)||"?"),content:Iu(e==null?void 0:e.content)},n=u0(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 Zw(e){const t=Number(e);return Number.isFinite(t)&&e!==null&&e!==void 0?t:null}const _$={"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 ay(e){var w,k,b,S,N,R;const t=e.record||{},n=((k=(w=e.started)==null?void 0:w.effect)!=null&&k.payload&&typeof e.started.effect.payload=="object"?e.started.effect.payload:(b=t==null?void 0:t.effect)==null?void 0:b.payload)||{},r=t!=null&&t.result&&typeof t.result=="object"?t.result:{},o=r.usage||r.token_usage||{},l=[],c=e.unverified.map(T=>`${T.path}: ${T.reason}`);for(const T of e.unresolved){const A=_$[T.path];A&&l.push(`${A}: ${T.reason}`)}const u=(N=(S=r==null?void 0:r.metadata)==null?void 0:S._provider_request)==null?void 0:N.payload;let f="",h=[],m="";if(u&&Array.isArray(u.messages)){m="sent";for(const T of u.messages)String((T==null?void 0:T.role)||"")==="system"&&!h.length?f+=(f?`
|
|
85
|
-
|
|
86
|
-
`:"")+Iu(T.content):h.push(Xw(T))}else(Array.isArray(n.messages)||typeof n.prompt=="string")&&(m="payload",h=(Array.isArray(n.messages)?n.messages:[]).map(Xw),typeof n.prompt=="string"&&n.prompt.trim()&&h.push({role:"user",content:n.prompt}));!f&&typeof n.system_prompt=="string"&&(f=n.system_prompt);const y=(Array.isArray(n.tools)?n.tools:Array.isArray(u==null?void 0:u.tools)?u.tools:[]).filter(T=>T&&typeof T=="object").map(T=>{const A=T.function&&typeof T.function=="object"?T.function:T;return{name:String(A.name||"?"),description:String(A.description||""),schema:A.parameters??A.input_schema??null}});return{provider:String(n.provider||r.provider||""),model:String(n.model||r.model||""),tokens_in:Zw(o.prompt_tokens??o.input_tokens),tokens_out:Zw(o.completion_tokens??o.output_tokens),system:f,messages:h,messages_source:m,tools:y,response:Iu(r.content??r.response??""),tool_calls:u0(r.tool_calls),reasoning:Iu(r.reasoning??((R=r==null?void 0:r.metadata)==null?void 0:R.reasoning)??""),missing:l,unverified:c}}function ly(e){var o,l,c,u;const t=((l=(o=e.record)==null?void 0:o.effect)==null?void 0:l.payload)||((u=(c=e.started)==null?void 0:c.effect)==null?void 0:u.payload)||{},n=(Array.isArray(t.tool_calls)?t.tool_calls:[]).map(f=>{var h,m;return{name:String((f==null?void 0:f.name)||((h=f==null?void 0:f.function)==null?void 0:h.name)||"?"),arguments:c0((f==null?void 0:f.arguments)??((m=f==null?void 0:f.function)==null?void 0:m.arguments)),call_id:String((f==null?void 0:f.call_id)||(f==null?void 0:f.id)||"")}}),r=a0(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?"":Iu(f.output),error:(f==null?void 0:f.error)==null?"":Iu(f.error),call_id:String((f==null?void 0:f.call_id)||""),raw:f}));return{calls:n,results:r}}function p$(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 d0(e){var r,o,l;const t=(r=e==null?void 0:e.result)==null?void 0:r.wait,n=typeof(t==null?void 0:t.wait_key)=="string"&&t.wait_key.startsWith("subworkflow:")?t.wait_key.slice(12):"";return String(((o=t==null?void 0:t.details)==null?void 0:o.sub_run_id)||((l=e==null?void 0:e.result)==null?void 0:l.sub_run_id)||n||"").trim()}function f0(e){var n,r,o,l,c,u,f,h,m,g,y;const t=e.record||{};switch(e.kind){case"llm_call":{const w=ay(e);return w.tokens_in!==null||w.tokens_out!==null?`${(w.tokens_in??0).toLocaleString("en-US")} in · ${(w.tokens_out??0).toLocaleString("en-US")} out`:""}case"tool":{const w=ly(e).calls;if(!w.length)return"";const k=`${w[0].name}(${p$(w[0].arguments)})`;return w.length>1?`${k} +${w.length-1} more`:k}case"event":return e.event_name;case"subflow":{const w=d0(t);return[String(((r=(n=t==null?void 0:t.effect)==null?void 0:n.payload)==null?void 0:r.workflow_id)||""),w].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)||((u=(c=t==null?void 0:t.effect)==null?void 0:c.payload)==null?void 0:u.reason)||"");case"ask":return String(((h=(f=t==null?void 0:t.effect)==null?void 0:f.payload)==null?void 0:h.prompt)||"");case"answer":return String(((g=(m=t==null?void 0:t.effect)==null?void 0:m.payload)==null?void 0:g.message)||((y=t==null?void 0:t.result)==null?void 0:y.message)||"");default:return e.effect_type}}function h0(e){return e.kind==="llm_call"?ay(e).model:""}function g$(e,t){var r,o;const n=[e.kind,e.effect_type,e.event_name,e.node_id,t,e.status,f0(e),h0(e)];try{n.push(JSON.stringify(((o=(r=e.started)==null?void 0:r.effect)==null?void 0:o.payload)??null)),n.push(JSON.stringify(e.record??null))}catch{}return n.join(`
|
|
87
|
-
`).toLowerCase()}function y$(e){var r,o;const t=Array.from(new Set((e||[]).map(l=>{var c;return String(l.run_id||((c=l.record)==null?void 0:c.run_id)||"").trim()}).filter(Boolean))),n={llm_calls:0,tokens:0,tool_calls:0,tool_failures:0};for(const l of t)for(const c of l0(e,l))if(c.kind==="llm_call"){n.llm_calls+=1;const u=((o=(r=c.record)==null?void 0:r.result)==null?void 0:o.usage)||{};n.tokens+=Number(u.total_tokens??Number(u.prompt_tokens??u.input_tokens??0)+Number(u.completion_tokens??u.output_tokens??0))||0}else if(c.kind==="tool"){const u=ly(c);n.tool_calls+=Math.max(u.calls.length,u.results.length),n.tool_failures+=u.results.filter(f=>f.success===!1).length}return n}function w$(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 Rt(){return new Date().toISOString()}function v$(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}function dr(e,t){try{const n=JSON.stringify(e);return typeof n!="string"?String(e):n.length<=t?n:`${n.slice(0,Math.max(0,t-1))}…`}catch{const n=String(e);return n.length<=t?n:`${n.slice(0,Math.max(0,t-1))}…`}}function At(e,t){const n=typeof(t==null?void 0:t.max_chars)=="number"?t.max_chars:360,r=typeof(t==null?void 0:t.max_lines)=="number"?t.max_lines:2,l=String(e||"").replace(/\r\n/g,`
|
|
88
|
-
`).replace(/\r/g,`
|
|
89
|
-
`).split(`
|
|
90
|
-
`),c=l.slice(0,Math.max(1,r)).join(`
|
|
91
|
-
`),u=l.length>r,f=c.length>n?`${c.slice(0,Math.max(0,n-1))}…`:c;return u&&f===c?`${c}…`:f}function sn(e,t){const n=String(e||"");return n.length<=t?n:`${n.slice(0,Math.max(0,t-1))}…`}function Qw(e){const t=String(e||"").trim();return t&&t.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")||"untitled"}function qn(e){const t=typeof e=="string"?e.trim():"";if(!t)return null;const n=t.replace(/(\.\d{3})\d+/,"$1"),r=Date.parse(n);return Number.isFinite(r)?r:null}function x$(e){const t=Date.now()-e,n=Math.floor(t/1e3),r=Math.floor(n/60),o=Math.floor(r/60),l=Math.floor(o/24);return n<60?"just now":r<60?`${r}m ago`:o<24?`${o}h ago`:l<=3?`${l}d ago`:new Date(e).toLocaleDateString(void 0,{month:"short",day:"numeric"})}function _c(e){const t=qn(e);return t===null?"—":x$(t)}function ev(e){if(!Number.isFinite(e))return"";const t=Math.floor(e/1e3);if(t<=0)return"now";const n=Math.floor(t/60),r=Math.floor(n/60),o=Math.floor(r/24),l=t%60,c=n%60,u=r%24;return o>0?`${o}d ${u}h`:r>0?`${r}h ${c}m`:n>0?`${n}m ${l}s`:`${t}s`}function cy(e){if(typeof e!="number"||!Number.isFinite(e)||e<0)return"—";const t=Math.floor(e/1e3),n=t%60,r=Math.floor(t/60),o=r%60,l=Math.floor(r/60),c=l%24,u=Math.floor(l/24);return u>0?`${u}d ${c}h`:l>0?`${l}h ${o}m`:r>0?`${r}m ${n}s`:`${Math.max(0,t)}s`}function Bu(e){const t=qn(e);return t===null?"—":new Date(t).toLocaleString()}function yn(...e){for(const t of e){const n=String(t??"").trim();if(n)return n}return""}function b$(...e){for(const t of e){const n=Number(t);if(Number.isFinite(n))return n}return null}function $o(e){const t=String(e||"").trim().toLowerCase();return t==="completed"||t==="failed"||t==="cancelled"}function Uu(e){const t=String(e||"").trim().toLowerCase();return t==="running"||t==="waiting"}function Mu(e){return String((e==null?void 0:e.started_at)||(e==null?void 0:e.created_at)||"").trim()}function k$(e){const t=String((e==null?void 0:e.status)||"").trim();return $o(t)?String((e==null?void 0:e.finished_at)||(e==null?void 0:e.updated_at)||"").trim():""}function uy(e,t=Date.now()){const n=qn(Mu(e));if(n===null)return-1;const r=qn(k$(e));return Math.max(0,(r!==null?r:t)-n)}function vc(e,t=Date.now()){return cy(uy(e,t))}function j$(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 S$(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 Km(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 xc(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 N$={all:"All",llm:"LLM calls",tools:"Tools",failed:"Failed"};function bi(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}function Co(e){return s.jsxs("details",{className:"rs_section",open:e.open,children:[s.jsxs("summary",{children:[s.jsx("span",{className:"rs_section_title",children:e.title}),e.meta?s.jsx("span",{className:"rs_section_meta",children:e.meta}):null,e.copy!==void 0?s.jsx("button",{type:"button",className:"rs_copy",onClick:t=>{t.preventDefault(),t.stopPropagation(),e.on_copy(e.copy||"")},children:"Copy"}):null]}),s.jsx("div",{className:"rs_section_body",children:e.children})]})}function gp(e){return`${e.toLocaleString("en-US")} chars`}function dy(e){const t=e.step.started&&e.step.started!==e.step.record?{started:e.step.started,record:e.step.record}:e.step.record;return s.jsx(Co,{title:"Raw JSON",copy:bi(t),on_copy:e.on_copy,children:s.jsx("div",{className:"rs_json mono",children:s.jsx(Is,{value:t,collapseAfterDepth:2,showCopy:!1})})})}function C$(e){const t=ay(e.step),n=!t.system&&!t.messages.length&&!t.missing.length;return s.jsxs(s.Fragment,{children:[t.missing.map(r=>s.jsxs("p",{className:"rs_notice",children:["Prompt body not kept: ",r,"."]},r)),n?s.jsx("p",{className:"rs_notice",children:"Prompt body not kept: this record carries no request messages."}):null,t.unverified.length?s.jsxs("p",{className:"rs_notice",children:["Rebuilt prompt may differ from what was sent: ",t.unverified.join("; "),"."]}):null,t.system?s.jsx(Co,{title:"System",meta:gp(t.system.length),copy:t.system,on_copy:e.on_copy,children:s.jsx("pre",{className:"rs_text",children:t.system})}):null,t.messages.length?s.jsx(Co,{title:"Messages",meta:`${t.messages.length}${t.messages_source==="sent"?" · as sent":""}`,copy:bi(t.messages),on_copy:e.on_copy,children:s.jsx("ol",{className:"rs_messages",children:t.messages.map((r,o)=>{var l;return s.jsxs("li",{className:`rs_msg rs_msg_${r.role}`,children:[s.jsxs("span",{className:"rs_role",children:[r.role,r.name?` · ${r.name}`:""]}),r.content?s.jsx("pre",{className:"rs_text",children:r.content}):null,(l=r.tool_calls)==null?void 0:l.map((c,u)=>s.jsx("pre",{className:"rs_text mono",children:`${c.name}(${bi(c.arguments)})`},u))]},o)})})}):null,t.tools.length?s.jsx(Co,{title:"Tools offered",meta:String(t.tools.length),copy:bi(t.tools),on_copy:e.on_copy,children:s.jsx("ul",{className:"rs_tools",children:t.tools.map(r=>s.jsxs("li",{children:[s.jsx("strong",{className:"mono",children:r.name}),r.description?s.jsxs("span",{children:[" — ",r.description]}):null]},r.name))})}):null,s.jsxs(Co,{title:"Response",meta:t.tool_calls.length?`${t.tool_calls.length} tool call${t.tool_calls.length===1?"":"s"}`:t.response?gp(t.response.length):"empty",copy:t.response||bi(t.tool_calls),open:!0,on_copy:e.on_copy,children:[t.response?s.jsx("div",{className:"rs_markdown",children:s.jsx(Si,{text:t.response})}):null,t.tool_calls.map((r,o)=>s.jsx("pre",{className:"rs_text mono",children:`${r.name}(${bi(r.arguments)})`},o)),!t.response&&!t.tool_calls.length?s.jsx("p",{className:"rs_muted",children:"No text and no tool call."}):null]}),t.reasoning?s.jsx(Co,{title:"Reasoning",meta:gp(t.reasoning.length),copy:t.reasoning,on_copy:e.on_copy,children:s.jsx("pre",{className:"rs_text",children:t.reasoning})}):null,s.jsx(dy,{step:e.step,on_copy:e.on_copy})]})}function E$(e){const t=ly(e.step);return s.jsxs(s.Fragment,{children:[s.jsx(Co,{title:"Calls",meta:String(t.calls.length),copy:bi(t.calls),open:!0,on_copy:e.on_copy,children:t.calls.map((n,r)=>s.jsx("pre",{className:"rs_text mono",children:`${n.name}(${bi(n.arguments)})`},r))}),s.jsxs(Co,{title:"Results",meta:String(t.results.length),copy:bi(t.results),open:!0,on_copy:e.on_copy,children:[t.results.length?null:s.jsx("p",{className:"rs_muted",children:"No result recorded yet."}),s.jsx("ol",{className:"rs_messages",children:t.results.map((n,r)=>s.jsxs("li",{className:`rs_msg ${n.success===!1?"rs_msg_failed":""}`,children:[s.jsxs("span",{className:"rs_role",children:[n.name," · ",n.success===!1?"failed":n.success?"ok":"unknown"]}),s.jsx(Fb,{sandbox:fg(n.raw),className:"rs_sandbox"}),n.error?s.jsx("pre",{className:"rs_text",children:n.error}):null,n.output?s.jsx("pre",{className:"rs_text",children:n.output}):null]},r))})]}),s.jsx(dy,{step:e.step,on_copy:e.on_copy})]})}function $$(e){var o,l,c;const t=e.step.record||{},n=((l=(o=e.step.started)==null?void 0:o.effect)==null?void 0:l.payload)??((c=t==null?void 0:t.effect)==null?void 0:c.payload),r=e.step.kind==="subflow"?d0(t):"";return s.jsxs(s.Fragment,{children:[r&&e.on_open_run?s.jsxs("p",{className:"rs_line_actions",children:[s.jsx("span",{className:"mono",children:r}),s.jsx("button",{type:"button",className:"btn btn_sm",onClick:()=>{var u;return(u=e.on_open_run)==null?void 0:u.call(e,r)},children:"Open"})]}):null,t.error?s.jsx("pre",{className:"rs_text rs_error",children:typeof t.error=="string"?t.error:bi(t.error)}):null,n!=null?s.jsx(Co,{title:"Payload",copy:bi(n),on_copy:e.on_copy,children:s.jsx("div",{className:"rs_json mono",children:s.jsx(Is,{value:n,collapseAfterDepth:2,showCopy:!1})})}):null,t.result!==void 0&&t.result!==null?s.jsx(Co,{title:"Result",copy:bi(t.result),on_copy:e.on_copy,children:s.jsx("div",{className:"rs_json mono",children:s.jsx(Is,{value:t.result,collapseAfterDepth:2,showCopy:!1})})}):null,s.jsx(dy,{step:e.step,on_copy:e.on_copy})]})}function A$(e){const t=e.step,n=f0(t),r=h0(t),o=t.failed&&t.status!=="failed"?"failed":t.status;return s.jsxs("article",{className:`rs_card ${t.failed?"rs_failed":""}`,"data-kind":t.kind,"data-step-id":t.step_id||void 0,children:[s.jsxs("button",{type:"button",className:"rs_card_head","aria-expanded":e.open,onClick:e.on_toggle,children:[s.jsx("span",{className:"rs_chevron","aria-hidden":"true",children:e.open?"▾":"▸"}),s.jsx("span",{className:"rs_kind",children:QE[t.kind]}),s.jsx("span",{className:"rs_node",children:e.node_label||t.node_id||t.effect_type||"step"}),s.jsx("span",{className:`rs_status ${xc(o)}`,children:o||"—"}),s.jsx("span",{className:"rs_dur",children:t.duration_ms!==null?cy(t.duration_ms):""}),r?s.jsx("span",{className:"rs_detail",children:r}):null,n?s.jsx("span",{className:"rs_line",children:n}):null]}),e.open?s.jsx("div",{className:"rs_card_body",children:t.kind==="llm_call"?s.jsx(C$,{step:t,on_copy:e.on_copy}):t.kind==="tool"?s.jsx(E$,{step:t,on_copy:e.on_copy}):s.jsx($$,{step:t,on_copy:e.on_copy,on_open_run:e.on_open_run})}):null]})}function T$(e){const{state:t}=e,n=_.useMemo(()=>l0(e.items,e.run_id),[e.items,e.run_id]),[r,o]=_.useState({}),l=k=>e.node_label(k.run_id,k.node_id),c=_.useMemo(()=>new Map,[n]),f=f$(n,t,k=>{let b=c.get(k.id);return b===void 0&&(b=g$(k,l(k)),c.set(k.id,b)),b}),h=n.some(k=>k.kind==="llm_call"),m=n.reduce((k,b)=>b.kind==="llm_call"?k+1:k,0),g=n.length-f.length,y=k=>e.on_state({...t,...k}),w=k=>s.jsx(A$,{step:k,node_label:l(k),open:r[k.id]===!0,on_toggle:()=>o(b=>({...b,[k.id]:!b[k.id]})),on_copy:e.on_copy,on_open_run:e.on_open_run},k.id);return s.jsxs("div",{className:"rs_view",children:[s.jsxs("div",{className:"rs_count",children:[s.jsxs("span",{children:[f.length," of ",n.length," steps",h?` · ${m} cycle${m===1?"":"s"}`:"",g&&t.only==="all"&&!t.all_steps&&!t.q?` · ${g} housekeeping hidden`:""]}),e.run_options.length>1?s.jsx("select",{className:"seg_select mono",value:e.run_id,onChange:k=>e.on_select_run(String(k.target.value||"")),"aria-label":"Run",children:e.run_options.map(k=>s.jsxs("option",{value:k,children:[sn(k,14),e.run_llm_counts[k]?` · ${e.run_llm_counts[k]} LLM`:""]},k))}):null]}),s.jsxs("div",{className:"rs_toolbar",children:[s.jsx("div",{className:"seg_toggle",role:"radiogroup","aria-label":"Layout",children:["cycles","steps"].map(k=>s.jsx("button",{type:"button",role:"radio","aria-checked":t.view===k,className:`seg_btn ${t.view===k?"active":""}`,onClick:()=>y({view:k}),children:k==="cycles"?"Cycles":"Steps"},k))}),s.jsx("div",{className:"seg_toggle",role:"radiogroup","aria-label":"Show",children:["all","llm","tools","failed"].map(k=>s.jsx("button",{type:"button",role:"radio","data-filter":k,"aria-checked":t.only===k,className:`seg_btn ${t.only===k?"active":""}`,onClick:()=>y({only:k}),children:N$[k]},k))}),s.jsx("input",{className:"rs_search",type:"search",value:t.q,onChange:k=>y({q:k.target.value}),placeholder:"Search steps","aria-label":"Search steps",autoComplete:"off",spellCheck:!1}),t.only==="all"?s.jsx(Ni,{label:"All steps",action:"show-all-steps",hint:"Also list status events, waits, resumes and memory bookkeeping.",checked:t.all_steps,onChange:k=>y({all_steps:k})}):null]}),n.length?null:s.jsx("p",{className:"rs_muted",children:"No steps recorded for this run yet."}),n.length&&!f.length?s.jsx("p",{className:"rs_muted",children:"No step matches."}):null,t.view==="cycles"&&h?u$(f).map(k=>s.jsxs("section",{className:"rs_cycle","data-cycle":k.cycle,children:[s.jsx("h3",{className:"rs_cycle_head",children:k.cycle===0?"Before the first call":`Cycle ${k.cycle}`}),k.steps.map(w)]},k.cycle)):f.map(w)]})}function M$(e){const[t,n]=_.useState(!1),r=e.answer.length>tv,o=t||!r?e.answer:`${e.answer.slice(0,tv).trimEnd()}…`;return s.jsxs("section",{className:"rs_outcome","aria-label":"Run summary",children:[s.jsxs("p",{className:"rs_outcome_facts",children:[s.jsx("span",{className:`rs_status ${xc(e.status)}`,children:e.status||"unknown"}),[e.duration,e.facts].filter(Boolean).join(" · ")]}),e.error?s.jsx("p",{className:"rs_text rs_error",children:e.error}):null,!e.error&&e.answer?s.jsxs("div",{className:"rs_markdown rs_outcome_text",children:[s.jsx(Si,{text:o}),r?s.jsx("button",{type:"button",className:"rs_link","aria-expanded":t,onClick:()=>n(l=>!l),children:t?"Less":"More"}):null]}):null,s.jsxs("div",{className:"rs_outcome_actions",children:[e.waiting_for_user&&e.on_answer_wait?s.jsx("button",{type:"button",className:"btn primary",onClick:e.on_answer_wait,children:"Answer"}):null,e.speak,s.jsx("button",{type:"button",className:"btn",onClick:e.on_open_artifacts,title:"This run's artifacts in System",children:"Artifacts"}),e.workspace_root?s.jsx("button",{type:"button",className:"btn",onClick:e.on_reveal_workspace,title:e.workspace_root,children:"Folder"}):null]})]})}const tv=600,R$="@default:",pc="abstractcode.agent.v1";function nv(e,t){var n;return e?e.kind==="default"?e.interface===pc?"@default":"":((n=t.find(r=>r.bundleId===e.bundle_id&&r.flowId===e.flow_id))==null?void 0:n.value)??"":""}function L$(e,t){return e==="@default"?{kind:"default",interface:pc}:t?{kind:"bundle",bundle_id:t.bundleId,flow_id:t.flowId}:null}function I$(e){return e?e.kind==="default"?`${R$}${e.interface}`:`${e.bundle_id}:${e.flow_id}`:""}function O$(e,t,n){if(!e)return null;if(e.kind==="default")return{flow_id:"@default",interface:e.interface,input_data:n};const r=String(t(e.bundle_id)||"").trim();if(!r)throw new Error(`The gateway listed no bundle_ref for bundle "${e.bundle_id}". Reload bundles, then try again.`);return{bundle_ref:r,flow_id:e.flow_id,input_data:n}}function P$(e){const t={};for(const[n,r]of Object.entries(e||{}))if(typeof r=="string"){const o=r.trim();o&&(t[n]=o)}else r!==void 0&&(t[n]=r);return t}const D$={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 F$(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 z$="#launch/automate";function B$(e){const t=o0(String(e||""));if(t)return{page:"run",run_id:t};const n=String(e||"").replace(/^#\/?/,"");if(n==="automations")return{page:"automations"};const r=/^launch(?:\/(once|automate))?$/.exec(n);return r?{page:"launch",mode:r[1]||"once"}:null}const gg={when:"every",email:ib,notify_email:!1,email_recipients:Sf,amount:"24",unit:"h",once_at:"",context:"independent",growing_max_tokens:String($f),tool_approval:"auto",title:"",start_at:"",count:"",until:""},sv={independent:"Each run starts fresh in its own session. Runs never see each other.",growing:"Each run is a new turn of one conversation and sees the previous runs. The most recent whole turns are replayed within your token budget; older runs drop out. The newest turn is kept whole even if it exceeds the budget."},m0=["use_context"],U$="This choice also sets the workflow's Use Context input: the workflow always reads the history the automation gives it.";function yg(e,t,n=!1){const r=e.when==="every";return{prompt:t,when:e.when==="once"?{kind:"once",at:e.once_at}:{kind:"every",amount:Number(e.amount),unit:e.unit},...n&&e.when==="email"?{trigger:"email",email:e.email}:{},...n&&e.notify_email?{notifyEmail:!0}:{},...n&&e.email_recipients.mode==="list"?{emailRecipients:e.email_recipients}:{},context:e.context,growingMaxTokens:Number(e.growing_max_tokens),toolApproval:e.tool_approval,title:e.title,...r&&e.start_at?{startAt:e.start_at}:{},...r&&e.count.trim()?{count:Number(e.count)}:{},...r&&e.until?{until:e.until}:{}}}function W$(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:[qt.not_set_up]};const n=P$(t.input_data),r=typeof n.prompt=="string"?n.prompt:"";delete n.prompt;for(const l of m0)delete n[l];delete n.workspace_root;let o;try{o=O$(t.choice,t.bundle_ref_for,n)}catch(l){return{ok:!1,errors:[String((l==null?void 0:l.message)||l)]}}return rg(yg(e,r,t.email_usable===!0),{target:o,requestId:t.request_id})}function q$(e,t=!1){if(e.when==="email"){if(!t)return"";const l=rg(yg(e,"preview",!0),{target:{flow_id:"@default",interface:pc},requestId:"preview"});return l.ok?`Runs ${ab(l.body.trigger.config)}.`:""}const n=rg(yg(e,"preview"),{target:{flow_id:"@default",interface:pc},requestId:"preview"});if(!n.ok)return"";const r=n.body.trigger.config,o=Qx(r);return e.when==="once"?`Runs ${o}.`:`Runs ${o}, first run ${r.start_at?`at ${ya(r.start_at)}`:"now"}.`}class H${constructor(t){cs(this,"key","");cs(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 V$(e,t,n){const r=W$(e,{...t,request_id:""});if(!r.ok)return r;const{request_id:o,...l}=r.body,c=n.id_for(JSON.stringify(l));return{ok:!0,body:{...r.body,request_id:c}}}function ua(e){return typeof e=="string"?e:e??null}function G$(e){var t,n,r,o,l,c;return{run_id:String((e==null?void 0:e.run_id)||"").trim(),workflow_id:ua(e==null?void 0:e.workflow_id),status:typeof(e==null?void 0:e.status)=="string"?String(e.status):"",created_at:ua(e==null?void 0:e.created_at),updated_at:ua(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:ua(e==null?void 0:e.parent_run_id),session_id:ua(e==null?void 0:e.session_id),actor_id:ua(e==null?void 0:e.actor_id),session_kind:ua(e==null?void 0:e.session_kind),automation_id:ua(e==null?void 0:e.automation_id),role:ua(e==null?void 0:e.role),occurrence_index:typeof(e==null?void 0:e.occurrence_index)=="number"?Number(e.occurrence_index):null,is_scheduled:typeof(e==null?void 0:e.is_scheduled)=="boolean"?!!e.is_scheduled:(e==null?void 0:e.is_scheduled)??null,paused:typeof(e==null?void 0:e.paused)=="boolean"?!!e.paused:(e==null?void 0:e.paused)??null,waiting_reason:typeof((t=e==null?void 0:e.waiting)==null?void 0:t.reason)=="string"?String(e.waiting.reason):((n=e==null?void 0:e.waiting)==null?void 0:n.reason)??null,schedule_interval:typeof((r=e==null?void 0:e.schedule)==null?void 0:r.interval)=="string"?String(e.schedule.interval).trim():((o=e==null?void 0:e.schedule)==null?void 0:o.interval)??null,schedule_target_workflow_id:typeof((l=e==null?void 0:e.schedule)==null?void 0:l.target_workflow_id)=="string"?String(e.schedule.target_workflow_id).trim():((c=e==null?void 0:e.schedule)==null?void 0:c.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,archived:(e==null?void 0:e.archived)===!0}}function K$(e,t){const n=new Set(e.map(o=>String((o==null?void 0:o.run_id)||""))),r=[...e];for(const o of t){const l=String((o==null?void 0:o.run_id)||"");!l||n.has(l)||(n.add(l),r.push(o))}return r}function Tf(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 _0(e){const t=Tf(e);return t==="occurrence"?typeof e.occurrence_index=="number"?`occurrence #${e.occurrence_index}`:"occurrence":t==="legacy"?"legacy schedule":t||""}function rv(e){return String((e==null?void 0:e.role)||"").trim()==="controller"}function Y$(e){var n,r,o;const t=(o=(r=(n=e==null?void 0:e.capabilities)==null?void 0:n.contracts)==null?void 0:r.common)==null?void 0:o.automations;return t&&typeof t=="object"&&t.available===!0?{available:!0,reason:""}:t&&typeof t=="object"&&t.available===!1?{available:!1,reason:"This gateway has the Automations API turned off."}:{available:!1,reason:"This gateway does not advertise the Automations API (capabilities.contracts.common.automations). Update AbstractGateway to use automations; legacy schedules stay manageable from their run view."}}function _l(e){return e.legacy===!0||e.capabilities.includes("legacy")}function p0(e,t=Date.now()){const n=_l(e),r=e.last_occurrence,o=r&&r.attempts>1?` after ${r.attempts} attempts`:"",l=e.attention.unread||e.attention.pending_waits>0;return{id:e.automation_id,title:e.title,cadence:Jg(e.trigger),next_run:e.next_fire_at?`${ya(e.next_fire_at)} (${db(e.next_fire_at,t)})`:e.status==="paused"?"none while paused":"none scheduled",current:ub(e),state:e.status,last:r?r.excerpt:"",last_status:r?`#${r.index} ${r.status}${o}`:"no runs yet",attention:l?fb(e):null,legacy:n}}function g0(e){const t=e.last_occurrence;if(!t)return null;const r=["completed","failed","cancelled"].includes(String(t.status))?t.index:t.index-1;return r>=1?r:null}function J$(e,t){const n=Wm(e,[],t),r=g0(e),o=t?{enabled:!1,reason:"Working…"}:_l(e)?{enabled:!1,reason:"Legacy schedule: managed with its existing controls."}:e.capabilities.includes("discuss")?r===null?{enabled:!1,reason:e.last_occurrence?"Available once the first run finishes.":"No occurrence to discuss yet."}:{enabled:!0,reason:`Discuss run #${r} in a new chat (a fork of this automation).`}:{enabled:!1,reason:"Not permitted for this automation."};return{active:n.active,pause:n.pause,resume:n.resume,run_now:n.run_now,edit:n.revise,archive:n.archive,discuss:o}}function X$(e,t){const n=l=>({enabled:!1,reason:l});if(t)return{legacy_pause:n("Working…"),legacy_resume:n("Working…"),legacy_run_now:n("Working…"),open_run:{enabled:!0},recreate:n("Working…")};const r=e.status==="paused",o=e.status==="active"||e.status==="paused";return{legacy_pause:r?n("Already suspended."):o?{enabled:!0}:n("The schedule has ended."),legacy_resume:r?{enabled:!0}:n(o?"Already running on schedule.":"The schedule has ended."),legacy_run_now:e.status==="active"?{enabled:!0}:n(r?"The schedule is off: switch Active on first.":"The schedule has ended."),open_run:{enabled:!0},recreate:{enabled:!0}}}function Z$(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 Q$=/^([1-9][0-9]*)([smhd])$/;function eA(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 tA(e,t){const n=e!=null&&e.schedule&&typeof e.schedule=="object"?e.schedule:null;if(!n)throw new Error("This run carries no legacy schedule metadata; nothing to recreate.");const r=String(n.target_bundle_ref||"").trim(),o=String(n.target_host_bundle_id||n.target_bundle_id||(r.includes("@")?r.slice(0,r.lastIndexOf("@")):"")||(t==null?void 0:t.bundle_id)||"").trim(),l=String(n.target_flow_id||(t==null?void 0:t.flow_id)||"").trim();if(!o||!l)throw new Error("The legacy schedule does not name its target workflow.");const c=[],u={...gg},f=typeof n.interval=="string"?n.interval.trim():"";if(!f)u.when="once",c.push("The legacy schedule ran once; pick the date and time (UTC) to run.");else{const y=Q$.exec(f);let w=y?Number(y[1]):0,k=y?y[2]:"";k==="s"&&w%60===0&&(w=w/60,k="m"),k==="m"||k==="h"||k==="d"?(u.amount=String(w),u.unit=k):c.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&&(u.count=String(n.repeat_count));const h=eA(n.repeat_until);h&&(u.until=h),u.context=n.share_context===!1?"independent":"growing";const m=t&&typeof t.input_data=="object"&&t.input_data&&!Array.isArray(t.input_data)?t.input_data:{},g={};for(const[y,w]of Object.entries(m))y==="workflow_selection"||y.startsWith("_")||(g[y]=w);return{choice:{kind:"bundle",bundle_id:o,flow_id:l},input_data:g,form:u,notes:c}}const nA={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 sA(e,t,n){return{answer_wait:async(r,o,l)=>{await e.submit_command({command_id:t(),run_id:r,type:"resume",payload:{wait_key:o,payload:l},client_id:"web_pwa"})},legacy_command:async(r,o,l)=>{await e.submit_command({command_id:t(),run_id:r,type:o,payload:l,client_id:"web_pwa"})},now_iso:n}}function rA(e,t){if(e==="ask_user"){if(typeof t.response!="string")throw new Error("An ask_user wait is answered with {response: string}.");return{response:t.response}}if(e==="tool_approval"){if(typeof t.approved!="boolean")throw new Error("A tool_approval wait is answered with {approved: true|false}.");const n=t.tool_ids;if(n!==void 0&&!(Array.isArray(n)&&n.every(r=>typeof r=="string")))throw new Error("tool_ids must be a list of strings.");return{approved:t.approved,...n!==void 0?{tool_ids:n}:{}}}if(e==="event"){if(!("payload"in t))throw new Error("An event wait is answered with {payload}.");return{payload:t.payload}}throw new Error(`This wait has no known kind (${JSON.stringify(e)}); the gateway must type its waits (ask_user, tool_approval, event).`)}function yp(e){return e.show_archived||e.status_filter==="archived"?e.items:e.items.filter(t=>t.status!=="archived")}function iv(e){return e.items.filter(t=>t.status==="archived").length}function fy(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 iA=3e4,gm=50;function qi(e){return Qg(e)?e:{status:0,code:"client_error",message:e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}}function wp(e,t){const n=new Map;for(const r of e)n.set(r.run_id,r);for(const r of t)n.set(r.run_id,r);return Array.from(n.values()).sort((r,o)=>o.index-r.index)}class oA{constructor(t,n,r=[1500,4e3]){cs(this,"state",{...nA});cs(this,"listeners",new Set);cs(this,"list_seq",0);cs(this,"detail_seq",0);cs(this,"sources_loaded",!1);cs(this,"definitions",new Map);this.client=t,this.host=n,this.followups_ms=r}subscribe(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}set(t){this.state={...this.state,...t};for(const n of this.listeners)n()}async list_all(){const t=[];let n;for(let r=0;r<200;r+=1){const o=await this.client.listAutomations({...this.state.status_filter?{status:this.state.status_filter}:{},...n?{cursor:n}:{},limit:gm});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 m_(this.state.email_status)}async refresh(){const t=++this.list_seq;this.set({loading:!0});try{const n=await this.list_all();if(this.load_email_status(),t!==this.list_seq)return;const r=this.state.detail,o=r?n.find(l=>l.automation_id===r.automation_id):void 0;this.set({items:n,loaded:!0,loading:!1,list_error:null,refreshed_at:Date.now(),...r&&o?{detail:{...r,summary:o}}:{}}),r&&await this.reload_occurrences(r.automation_id)}catch(n){if(t!==this.list_seq)return;this.set({loading:!1,loaded:!0,list_error:qi(n)})}}async set_status_filter(t){this.set({status_filter:t}),await this.refresh()}async load_trigger_sources(){if(this.sources_loaded)return;const t=await this.client.listTriggerSources();this.sources_loaded=!0,this.set({trigger_sources:t.items})}async select(t){var o;const n=String(t||"").trim(),r=++this.detail_seq;if(!n){this.set({selected_id:"",detail:null});return}this.set({selected_id:n,notice:"",...((o=this.state.detail)==null?void 0:o.automation_id)!==n?{detail:null}:{}});try{const l=this.state.items.find(f=>f.automation_id===n);if(l&&_l(l)){this.set({detail:{automation_id:n,summary:l,definition:null,occurrences:[],next_cursor:null,error:null}});return}const[c,u]=await Promise.all([this.client.getAutomation(n),this.client.listOccurrences(n,{limit:gm})]);if(r!==this.detail_seq)return;this.set({detail:{automation_id:n,summary:l??c.summary,definition:c.definition,occurrences:wp([],u.items),next_cursor:u.next_cursor,error:null}}),await this.load_trigger_sources()}catch(l){if(r!==this.detail_seq)return;this.set({error:qi(l)})}}async reload_occurrences(t){const n=this.state.detail;if(!n||n.automation_id!==t||_l(n.summary))return;const[r,o]=await Promise.all([this.client.getAutomation(t),this.client.listOccurrences(t,{limit:gm})]),l=this.state.detail;if(!l||l.automation_id!==t)return;const c=this.state.items.find(u=>u.automation_id===t);this.set({detail:{...l,summary:c??r.summary,definition:r.definition,occurrences:wp(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:gm}),r=this.state.detail;if(!r||r.automation_id!==t.automation_id)return;this.set({detail:{...r,occurrences:wp(r.occurrences,n.items),next_cursor:n.next_cursor}})}catch(n){this.set({error:qi(n)})}}async after_change(t){await this.refresh();for(const n of this.followups_ms)setTimeout(()=>void this.refresh(),n)}async command(t,n,r,o){this.set({busy:!0});try{const l=await this.client.sendAutomationCommand(t,{type:n,...r?{payload:r}:{},...o?{command_id:o}:{}});return await this.after_change(t),l}catch(l){throw qi(l)}finally{this.set({busy:!1})}}async revise(t,n,r,o){this.set({busy:!0});try{const l=await this.client.reviseAutomation(t,{changes:n,...r!==null?{expected_revision:r}:{},...o?{command_id:o}:{}});return await this.after_change(t),l}catch(l){throw qi(l)}finally{this.set({busy:!1})}}definition(t){if(_l(t))return Promise.resolve(null);const n=t.automation_id,r=this.state.detail;if(r&&r.automation_id===n&&r.definition&&r.definition.revision===t.revision)return Promise.resolve(r.definition);const o=this.definitions.get(n);if(o&&o.revision===t.revision)return o.answer;const l=this.client.getAutomation(n).then(c=>c.definition??null);return l.catch(()=>this.definitions.delete(n)),this.definitions.set(n,{revision:t.revision,answer:l}),l}async discuss(t,n,r,o){this.set({busy:!0});try{const l=await this.client.discuss(t,{occurrence_index:n,prompt:r,...o?{request_id:o}:{}});return this.set({notice:fy(n,l)}),l}catch(l){throw qi(l)}finally{this.set({busy:!1})}}async seen(t,n){try{await this.client.markSeen(t,n)}catch(r){throw qi(r)}}async answer_wait(t,n,r,o){var l;this.set({busy:!0});try{const c=(((l=this.state.detail)==null?void 0:l.occurrences)||[]).flatMap(u=>u.waits).find(u=>u.run_id===n&&u.wait_key===r);if(!c)throw new Error(`No loaded wait ${r} on run ${n}; reload the automation.`);await this.host.answer_wait(n,r,rA(c.kind,o)),await this.after_change(t)}catch(c){throw qi(c)}finally{this.set({busy:!1})}}async row_action(t,n){const r=`automation.${n}`;this.set({error:null,notice:""});try{await this.command(t.automation_id,r),this.set({notice:n==="run_now"&&t.status==="paused"?`Run now sent to “${t.title}”; it stays paused.`:n==="pause"||n==="resume"?ov(t.title,n==="resume"):`${aA[n]} sent to “${t.title}”.`,confirm_archive_id:""})}catch(o){this.set({error:qi(o)})}}set_show_archived(t){this.set({show_archived:t})}ask_archive(t){this.set({confirm_archive_id:t})}async legacy_action(t,n){if(!_l(t))throw new Error("legacy_action on a non-legacy automation");const r=Z$(n,this.host.now_iso());this.set({busy:!0,error:null,notice:""});try{await this.host.legacy_command(t.automation_id,r.type,r.payload),this.set({notice:n==="legacy_run_now"?`Run now sent to “${t.title}”.`:ov(t.title,n==="legacy_resume")}),await this.refresh()}catch(o){this.set({error:qi(o)})}finally{this.set({busy:!1})}}report_error(t){this.set({error:qi(t)})}clear_notice(){this.set({notice:"",error:null})}dismiss_notice(){this.state.notice&&this.set({notice:""})}dismiss_error(){this.state.error&&this.set({error:null})}}function ov(e,t){return t?`“${e}” is active: it runs on its schedule.`:`“${e}” is paused: scheduled runs are skipped.`}const aA={run_now:"Run now",archive:"Archive"};function lA(e){const t=(n,r,o)=>s.jsx("button",{type:"button",role:"radio","aria-checked":e.mode===n,className:`seg_btn ${e.mode===n?"active":""}`,"data-mode":n,title:o,onClick:()=>e.on_change(n),children:r});return s.jsxs("div",{className:"launch_mode",children:[s.jsxs("div",{className:"seg_toggle launch_mode_switch",role:"radiogroup","aria-label":"Launch mode","aria-describedby":"launch_mode_help",children:[t("once","Run once"),t("automate","Automate",e.automate_available?void 0:e.automate_reason)]}),s.jsx("p",{className:"launch_mode_help",id:"launch_mode_help","data-mode-help":e.mode,"aria-live":"polite",children:D$[e.mode]})]})}function cA(e){const t=e.form,n=m_(e.email_status),r=t.when==="email"&&!n?"every":t.when,o=q$(t,n);return s.jsxs("div",{className:"automate_fields",children:[s.jsxs("fieldset",{"data-section":"when",children:[s.jsx("legend",{children:"When (UTC)"}),s.jsxs("div",{className:"automate_row",role:"radiogroup","aria-label":"Schedule kind",children:[s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:"automate_when",value:"every",checked:r==="every",disabled:e.disabled,onChange:()=>e.on_change({when:"every"})})," Repeat"]}),s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:"automate_when",value:"once",checked:r==="once",disabled:e.disabled,onChange:()=>e.on_change({when:"once"})})," Once at…"]}),s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:"automate_when",value:"email",checked:r==="email",disabled:e.disabled||!n,onChange:()=>e.on_change({when:"email"})})," ",qt.trigger_label]})]}),n?null:s.jsx(og,{status:e.email_status,onOpenMyEmail:e.on_open_my_email}),r==="email"?s.jsx(N1,{value:t.email,onChange:l=>e.on_change({email:l}),disabled:e.disabled,idBase:"automate"}):r==="every"?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"automate_row",role:"group","aria-label":"Presets",children:XN.map(l=>l.when.kind==="every"?s.jsx("button",{type:"button",className:"btn btn_sm","data-preset":l.label,"aria-pressed":Number(t.amount)===l.when.amount&&t.unit===l.when.unit,disabled:e.disabled,onClick:()=>{l.when.kind==="every"&&e.on_change({amount:String(l.when.amount),unit:l.when.unit})},children:l.label},l.label):null)}),s.jsxs("div",{className:"automate_row",children:[s.jsx("span",{children:"Every"}),s.jsx("input",{type:"number",min:1,step:1,value:t.amount,disabled:e.disabled,"aria-label":"Interval amount",onChange:l=>e.on_change({amount:l.target.value})}),s.jsxs("select",{value:t.unit,disabled:e.disabled,"aria-label":"Interval unit",onChange:l=>e.on_change({unit:l.target.value}),children:[s.jsx("option",{value:"m",children:"minutes"}),s.jsx("option",{value:"h",children:"hours"}),s.jsx("option",{value:"d",children:"days"})]})]})]}):s.jsxs("label",{className:"automate_row",children:[s.jsx("span",{children:"Run once at (UTC)"}),s.jsx("input",{type:"datetime-local",value:t.once_at,disabled:e.disabled,onChange:l=>e.on_change({once_at:l.target.value})})]}),s.jsx("div",{className:"automate_preview","aria-live":"polite","data-preview":"true",children:o||(r==="email"?"Incomplete email trigger.":"Incomplete schedule.")})]}),s.jsxs("fieldset",{"data-section":"context",children:[s.jsx("legend",{children:"Context"}),s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:"automate_context",value:"independent",checked:t.context==="independent",disabled:e.disabled,onChange:()=>e.on_change({context:"independent"})})," ",s.jsx("strong",{children:"Independent"})," (default) — ",sv.independent]}),s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:"automate_context",value:"growing",checked:t.context==="growing",disabled:e.disabled,onChange:()=>e.on_change({context:"growing"})})," ",s.jsx("strong",{children:"Growing"})," — ",sv.growing]}),t.context==="growing"?s.jsxs("label",{children:["Max growing context (tokens)",s.jsx("input",{type:"number",min:1,step:1,required:!0,value:t.growing_max_tokens,disabled:e.disabled,onChange:l=>e.on_change({growing_max_tokens:l.target.value})})]}):null,s.jsx("p",{className:"help_text muted","data-context-owns":"use_context",children:U$})]}),s.jsxs("fieldset",{"data-section":"tools",children:[s.jsx("legend",{children:"Tools"}),e.available_tools&&e.on_tools_change?s.jsx(yb,{availableTools:e.available_tools,value:e.tools??null,onChange:e.on_tools_change,disabled:e.disabled}):null,r==="email"?s.jsx("p",{className:"help_text muted","data-email-rule":"untrusted",children:qt.untrusted_hint}):null,s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:"automate_tools",value:"auto",checked:t.tool_approval==="auto",disabled:e.disabled,onChange:()=>e.on_change({tool_approval:"auto"})})," ",e1,e.tools&&e.tools.length?s.jsxs("span",{className:"automate_preview",children:[" — ",e.tools.join(", ")]}):null]}),s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:"automate_tools",value:"ask",checked:t.tool_approval==="ask",disabled:e.disabled,onChange:()=>e.on_change({tool_approval:"ask"})})," Ask each time — every tool call waits for your approval on the Automations page"]})]}),e.workspaces?s.jsx("div",{className:"automate_workspaces","data-section":"workspaces",role:"group","aria-label":"Workspaces",children:e.workspaces}):null,s.jsxs("fieldset",{"data-section":"email",children:[s.jsx("legend",{children:"Email"}),n?null:s.jsx(og,{status:e.email_status,onOpenMyEmail:e.on_open_my_email}),s.jsx(C1,{notifyEmail:n&&t.notify_email,onNotifyEmailChange:l=>e.on_change({notify_email:l}),recipients:n?t.email_recipients:Sf,onRecipientsChange:l=>e.on_change({email_recipients:l}),disabled:e.disabled||!n,idBase:"automate"})]})]})}function uA(e){const t=e.form;return s.jsx("div",{className:"automate_fields",children:s.jsxs("fieldset",{className:"automate_limits","data-section":"limits",children:[s.jsx("legend",{children:"Title and limits"}),s.jsxs("div",{className:"launch_grid",children:[s.jsxs("label",{className:"launch_grid_cell",style:{gridColumn:"1 / -1"},children:[s.jsx("span",{className:"launch_label",children:"Title"}),s.jsx("input",{value:t.title,maxLength:120,disabled:e.disabled,placeholder:"Defaults to the task's first line",onChange:n=>e.on_change({title:n.target.value})})]}),t.when==="every"?s.jsxs(s.Fragment,{children:[s.jsxs("label",{className:"launch_grid_cell",children:[s.jsx("span",{className:"launch_label",children:"First run at (UTC; empty = now)"}),s.jsx("input",{type:"datetime-local",value:t.start_at,disabled:e.disabled,onChange:n=>e.on_change({start_at:n.target.value})})]}),s.jsxs("label",{className:"launch_grid_cell",children:[s.jsx("span",{className:"launch_label",children:"Stop after this many runs"}),s.jsx("input",{type:"number",min:1,step:1,value:t.count,disabled:e.disabled,onChange:n=>e.on_change({count:n.target.value})})]}),s.jsxs("label",{className:"launch_grid_cell",children:[s.jsx("span",{className:"launch_label",children:"Stop at (UTC)"}),s.jsx("input",{type:"datetime-local",value:t.until,disabled:e.disabled,onChange:n=>e.on_change({until:n.target.value})})]})]}):null]})]})})}function Rs(){return pa()}const y0=u_("voice and camera")??"Voice and camera are not supported in this browser (getUserMedia unavailable).",dA="Copy failed — select and copy";function w0(){var t;const e=globalThis.navigator;return typeof((t=e==null?void 0:e.mediaDevices)==null?void 0:t.getUserMedia)=="function"}function fA(e){var o;const t=globalThis.document;if(!t||!t.body||typeof t.execCommand!="function")return!1;const n=t.createElement("textarea");n.value=e,n.setAttribute("readonly",""),n.style.position="fixed",n.style.top="0",n.style.left="-9999px",n.style.opacity="0";const r=t.activeElement;t.body.appendChild(n);try{return n.select(),n.setSelectionRange(0,e.length),t.execCommand("copy")===!0}catch{return!1}finally{t.body.removeChild(n);try{(o=r==null?void 0:r.focus)==null||o.call(r)}catch{}}}async function hA(e){var r;const t=String(e??""),n=globalThis.navigator;if(typeof((r=n==null?void 0:n.clipboard)==null?void 0:r.writeText)=="function")try{return await n.clipboard.writeText(t),!0}catch{}return fA(t)}const mA=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 _A(e){const t=e.length,n=new Uint8Array(t+9+63>>6<<6);n.set(e),n[t]=128;const r=new DataView(n.buffer);r.setUint32(n.length-8,Math.floor(t/536870912),!1),r.setUint32(n.length-4,t<<3>>>0,!1);const o=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),l=new Uint32Array(64),c=(u,f)=>u>>>f|u<<32-f;for(let u=0;u<n.length;u+=64){for(let S=0;S<16;S++)l[S]=r.getUint32(u+S*4,!1);for(let S=16;S<64;S++){const N=c(l[S-15],7)^c(l[S-15],18)^l[S-15]>>>3,R=c(l[S-2],17)^c(l[S-2],19)^l[S-2]>>>10;l[S]=l[S-16]+N+l[S-7]+R>>>0}let[f,h,m,g,y,w,k,b]=[o[0],o[1],o[2],o[3],o[4],o[5],o[6],o[7]];for(let S=0;S<64;S++){const N=c(y,6)^c(y,11)^c(y,25),R=y&w^~y&k,T=b+N+R+mA[S]+l[S]>>>0,A=c(f,2)^c(f,13)^c(f,22),W=f&h^f&m^h&m,z=A+W>>>0;b=k,k=w,w=y,y=g+T>>>0,g=m,m=h,h=f,f=T+z>>>0}o[0]=o[0]+f>>>0,o[1]=o[1]+h>>>0,o[2]=o[2]+m>>>0,o[3]=o[3]+g>>>0,o[4]=o[4]+y>>>0,o[5]=o[5]+w>>>0,o[6]=o[6]+k>>>0,o[7]=o[7]+b>>>0}return Array.from(o,u=>u.toString(16).padStart(8,"0")).join("")}async function pA(e){var r;const t=new TextEncoder().encode(String(e??"")),n=(r=globalThis.crypto)==null?void 0:r.subtle;if(n&&typeof n.digest=="function"){const o=await n.digest("SHA-256",t);return Array.from(new Uint8Array(o),l=>l.toString(16).padStart(2,"0")).join("")}return _A(t)}const gA=/^[a-zA-Z0-9_-]+$/;function av(e){return gA.test(String(e||"").trim())}async function yA(e){const t=String(e||"");return pA(t)}async function wA(e){const t=String(e||"").trim();if(!t)throw new Error("session_id is required");if(av(t)){const r=`session_memory_${t}`;if(av(r))return r}return`session_memory_sha_${(await yA(t)).slice(0,32)}`}const v0="abstractobserver_voice";function vA(){var e;try{const t=(e=globalThis.localStorage)==null?void 0:e.getItem(v0),n=t?JSON.parse(t):null;return n&&typeof n=="object"&&!Array.isArray(n)?n:{}}catch{return{}}}const wg=new Set;function xA(e){var t;try{(t=globalThis.localStorage)==null||t.setItem(v0,JSON.stringify(e||{}))}catch{}for(const n of wg)n(e||{})}function x0(){const[e,t]=_.useState(()=>vA());return _.useEffect(()=>(wg.add(t),()=>{wg.delete(t)}),[]),[e,xA]}function b0(e,t){const[n,r]=_.useState({value:null,failed:!1});return _.useEffect(()=>{if(!t||!e){r({value:null,failed:!1});return}let o=!0;return e.voice_defaults().then(l=>o&&r({value:l||{},failed:!1})).catch(()=>o&&r({value:null,failed:!0})),()=>{o=!1}},[e,t]),n}function bA(e){const t=e.gateway;return s.jsx(L2,{value:e.value,onChange:e.onChange,fetchCatalog:(n,r)=>t?t.voice_catalog(n,r):Promise.reject(new Error("Connect to a gateway to configure voice.")),fetchDefaults:()=>t?t.voice_defaults():Promise.reject(new Error("Connect to a gateway to configure voice.")),defaults:e.defaults.value??void 0,overrideOwner:"this app",nested:!0,unavailableReason:e.connected&&t?null:"Connect to a gateway to configure voice."})}const kA=18e4;function jA(e,t,n,r=()=>{}){return async function*(o,l){r(),yield*aN({path:e.gateway_url(it(`runs/${encodeURIComponent(t)}/voice/tts/stream`)),headers:e.auth_headers(),signal:l,body:{text:o,request_id:Rs(),...E2(n())}})}}function SA(e,t,n,r,o=()=>{},l=kA){return async(c,u)=>{o();const f=String(u||c.type||"").toLowerCase(),h=f.includes("mp4")?"m4a":f.includes("ogg")?"ogg":f.includes("wav")?"wav":"webm",m=new File([c],`recording.${h}`,{type:f||"audio/webm"}),g=await e.attachments_upload(t,m,{filename:m.name,content_type:m.type});o();let y;const w=await Promise.race([e.audio_transcribe(n,{audio_artifact:g,request_id:Rs(),...$2(r())}),new Promise((k,b)=>{y=setTimeout(()=>b(new Error(`the gateway did not answer within ${Math.round(l/1e3)} s`)),l)})]).finally(()=>clearTimeout(y));return o(),{text:String(w.text||""),provider:w.provider,model:w.model}}}function k0(e){const{gateway:t,prefs:n}=e,r=String(e.session_id||"").trim(),[o,l]=_.useState("");_.useEffect(()=>{let w=!0;if(!r){l("");return}return wA(r).then(k=>w&&l(k)).catch(()=>w&&l("")),()=>{w=!1}},[r]);const c=`${r}|${o}`,u=_.useRef(c);u.current=c;const f=_.useRef(n);f.current=n;const h=_.useRef(e);h.current=e;const m=()=>{if(u.current!==c)throw new Error("Voice session changed.")},g=!!(t&&o&&r),y=pN({output_device_id:n.output_device||"",input_device_id:n.input_device||"",input_gain:n.input_gain,volume:n.reply_volume,stop_on_pointerup:!1,tts_stream:g?jA(t,o,()=>f.current,m):void 0,transcribe:g?SA(t,r,o,()=>f.current,m):void 0,on_transcript:w=>{u.current===c&&h.current.on_transcript(w)},on_error:w=>{u.current===c&&h.current.on_error(w)}});return _.useEffect(()=>{var w;return y.stop_tts(),(w=y.cancel_voice_ptt_recording)==null||w.call(y),()=>{var k;y.stop_tts(),(k=y.cancel_voice_ptt_recording)==null||k.call(y)}},[c,y.stop_tts,y.cancel_voice_ptt_recording]),{...y,run_id:o}}function j0(e,t,n){const r=_.useRef(null);_.useEffect(()=>{const o=(n==null?void 0:n.key)||"";if(r.current===null){r.current=o;return}!o||o===r.current||(r.current=o,t&&e.tts_supported&&(n!=null&&n.text.trim())&&e.toggle_tts(o,n.text))},[n==null?void 0:n.key,n==null?void 0:n.text,t,e.tts_supported,e.toggle_tts])}function NA(e){const[t,n]=_.useState(()=>Date.now());return _.useEffect(()=>{if(!e)return;n(Date.now());const r=setInterval(()=>n(Date.now()),1e3);return()=>clearInterval(r)},[e]),t}const CA=350;function S0(e){const{voice:t}=e,n=_.useRef(!1),r=_.useRef(!1),o=_.useRef(0),l=()=>{if(r.current){r.current=!1,t.stop_voice_ptt_recording();return}n.current=!0,o.current=Date.now(),t.start_voice_ptt_recording().then(()=>{!n.current&&!r.current&&t.stop_voice_ptt_recording()})},c=()=>{if(n.current){if(n.current=!1,Date.now()-o.current<CA){r.current=!0;return}t.stop_voice_ptt_recording()}};_.useEffect(()=>{const w=()=>{n.current=!1,r.current=!1,t.stop_voice_ptt_recording()};return window.addEventListener("pointerup",c),window.addEventListener("pointercancel",c),window.addEventListener("blur",w),()=>{window.removeEventListener("pointerup",c),window.removeEventListener("pointercancel",c),window.removeEventListener("blur",w)}},[t.stop_voice_ptt_recording]),_.useEffect(()=>{t.voice_ptt_recording||(r.current=!1)},[t.voice_ptt_recording]);const u=t.voice_ptt_since||0,f=NA(!!u),h=ZS(e.prefs,e.defaults),m=t.voice_ptt_recording?`Recording… ${u?Vx(u,f):""}`.trim():t.voice_ptt_busy?QS(u||f,f,h):"",y=!w0()?y0:e.blocked||(t.voice_ptt_supported?null:"Dictation is not available on this gateway connection.");return s.jsxs("span",{className:"voice_tools","data-voice-tools":!0,children:[s.jsx("button",{type:"button",className:`btn btn_icon voice_btn${t.voice_ptt_recording?" danger":""}`,"data-action":"dictate","aria-label":t.voice_ptt_recording?"Recording — tap or release to transcribe":"Hold to dictate","aria-pressed":t.voice_ptt_recording,title:y||"Hold to dictate, or tap to start and tap again to stop (Space or Enter on keyboard)",disabled:!!y||t.voice_ptt_busy,onPointerDown:w=>{w.button===0&&l()},onPointerUp:c,onPointerCancel:c,onKeyDown:w=>{[" ","Enter"].includes(w.key)&&!w.repeat&&(w.preventDefault(),l())},onKeyUp:w=>{[" ","Enter"].includes(w.key)&&(w.preventDefault(),c())},children:s.jsx(Be,{name:t.voice_ptt_busy?"loader":"mic",size:15})}),t.tts_playback.status!=="idle"?s.jsx("button",{type:"button",className:"btn btn_icon","data-action":"stop-speaking","aria-label":"Stop spoken reply",title:"Stop spoken reply",onClick:t.stop_tts,children:s.jsx(Be,{name:"x",size:14})}):null,m?s.jsx("span",{role:"status",className:"voice_status mono","data-voice-status":!0,children:m}):null,e.error?s.jsx("span",{role:"alert",className:"voice_error","data-voice-error":!0,children:e.error}):null]})}function EA(e){const{voice:t}=e;if(!t.tts_supported||!e.text.trim())return null;const n=t.tts_playback.key===e.speak_key?t.tts_playback.status:"idle",r=n==="loading"?"Preparing…":n==="playing"?"Stop":n==="paused"?"Resume":"Read aloud";return s.jsxs(s.Fragment,{children:[s.jsxs("button",{type:"button",className:"btn","data-action":"read-aloud","data-speak-state":n,"aria-pressed":n==="playing"||n==="loading",title:n==="playing"?"Stop reading aloud":"Read this aloud with the gateway's voice",onClick:()=>n==="playing"||n==="loading"?t.stop_tts():void t.toggle_tts(e.speak_key,e.text),children:[s.jsx(Be,{name:n==="playing"||n==="loading"?"x":"speaker",size:14})," ",r]}),e.error?s.jsx("span",{role:"alert",className:"voice_error","data-voice-error":!0,children:e.error}):null]})}const $A="abstractobserver";function AA(e){return{getRun:t=>e.get_run(t),getHistory:t=>e.get_run_history_bundle(t,{include_subruns:!0,include_session:!0,ledger_mode:"full"}),getLedger:(t,n,r)=>e.get_ledger(t,{after:n,limit:200,signal:r}),streamLedger:(t,n,r,o,l)=>e.stream_ledger(t,{after:n,on_step:r,signal:o,on_open:l}),submitCommand:t=>e.submit_command(t)}}function TA(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 MA=new Set(["completed","failed","cancelled"]);function RA(e){var te;const{gateway:t,discussion:n}=e,r=_.useMemo(()=>AA(t),[t]),[o,l]=_.useState(((te=n.session)==null?void 0:te.run_id)||""),[c,u]=_.useState(""),[f,h]=_.useState(!1),[m,g]=_.useState(""),{controller:y,snapshot:w}=SE({transport:r,runId:o,enabled:e.connected,clientId:$A}),k=n.session,b=!!o&&!MA.has(w.status)&&w.status!=="idle",S=xE(w),[N]=x0(),R=b0(e.connected?t:null,e.connected),[T,A]=_.useState(""),W=k0({gateway:e.connected?t:null,session_id:(k==null?void 0:k.session_id)||e.voice_session_id||"",prefs:N,on_error:A,on_transcript:Q=>u(D=>D.trim()?`${D.trimEnd()}
|
|
92
|
-
${Q}`:Q)}),z=_.useMemo(()=>{for(let Q=w.messages.length-1;Q>=0;Q-=1){const D=w.messages[Q];if(D.role==="assistant")return D.live?null:{key:String(D.id||""),text:String(D.content||"")}}return null},[w.messages]);j0(W,N.read_aloud===!0,z);const J=Q=>W.tts_playback.key&&W.tts_playback.key===String(Q.id||"")?W.tts_playback.status:"idle",K=async Q=>{var $;const D=Q.trim();if(D){h(!0);try{if(k){const E=String((($=w.run)==null?void 0:$.workflow_id)||""),L=TA(E),M=await t.start_run(L.flow_id,{prompt:D},{bundle_id:L.bundle_id,session_id:k.session_id});l(M)}else{const E=await e.on_fork(n.automation_id,n.occurrence_index,D);l(E.run_id)}u("")}finally{h(!1)}}},re=s.jsxs("div",{className:"discussion_head",children:[s.jsxs("button",{type:"button",className:"btn btn_sm","data-action":"discussion-back",onClick:e.on_close,title:`Back to ${n.automation_title}`,children:[s.jsx(Be,{name:"chevronRight",size:13,className:"flip_x"})," ",n.automation_title]}),s.jsxs("span",{className:"discussion_title",children:[s.jsx(Be,{name:"chat",size:15})," Discussion — fork at #",n.occurrence_index]}),s.jsx("span",{className:"pane_spacer"}),k?s.jsxs(s.Fragment,{children:[s.jsxs("button",{type:"button",className:`btn btn_sm${m==="own"?" active":""}`,"data-action":"discussion-files",onClick:()=>g(m==="own"?"":"own"),title:k.workspace_root,children:[s.jsx(Be,{name:"folder",size:14})," Its files"]}),s.jsxs("button",{type:"button",className:`btn btn_sm${m==="mounted"?" active":""}`,"data-action":"automation-files",onClick:()=>g(m==="mounted"?"":"mounted"),title:k.mounted_workspace,children:[s.jsx(Be,{name:"folder",size:14})," Automation files"]})]}):null]});return s.jsxs("section",{className:"pane auto_detail auto_discussion","data-discussion-session":(k==null?void 0:k.session_id)||void 0,children:[m&&k?s.jsx(Xb,{fetchGateway:t.fetch_gateway,runId:m==="own"?k.run_id:n.automation_id,title:m==="own"?"Discussion files":"Automation files",note:m==="own"?"The discussion's own writable folder.":"Mounted read-only for the discussion's file tools; nothing is written back.",onClose:()=>g(""),refreshKey:w.status}):null,s.jsx(vE,{header:re,messages:w.messages,draft:c,onDraftChange:u,onSend:K,busy:b||f,busyLabel:f?k?"Starting…":"Forking the automation…":S?"Waiting for you":"Working…",onCancel:b?()=>y.cancel():void 0,stopState:w.stop??null,disabled:!e.connected,interaction:ME(S,y,{records:w.records,currentRun:w.run}),placeholder:k?"Ask a follow-up…":`Ask about run #${n.occurrence_index}…`,emptyState:s.jsxs("div",{className:"help_text muted discussion_intro",children:["A new session that forks this automation at #",n.occurrence_index," with its history (runs 1–",n.occurrence_index,"). It works in its own writable workspace; the automation's files are mounted read-only for the file tools (shell commands are not sandboxed), and nothing is written back into the automation."]}),composerExtras:s.jsx(S0,{voice:W,defaults:R.value,prefs:N,blocked:e.connected?null:"Connect to the gateway first.",error:T}),messageProps:W.tts_supported?{onSpeakToggle:Q=>{A(""),W.toggle_tts(String(Q.id||""),String(Q.content||""))},getSpeakState:J}:void 0,footer:w.error?s.jsx("div",{className:"observe_context_card error",role:"alert",children:w.error}):null})]})}const LA=gn.title;function lv(e){return`${LA}: ${e}`}const IA=["workspace_access_mode","workspace_allowed_paths"];function OA(e){return!!(e&&typeof e=="object"&&!Array.isArray(e)&&Array.isArray(e.folders))}function N0(e){var n,r;const t=(r=(n=e==null?void 0:e.target)==null?void 0:n.input_data)==null?void 0:r.workspace;return OA(t)?t:null}function C0(e,t){const n={...e||{}};for(const r of IA)delete n[r];return t===null?delete n.workspace:n.workspace={posture:t.posture,default_mode:t.default_mode,folders:t.folders.map(r=>({path:r.path,mode:r.mode}))},n}function PA(e,t){const n=e.target;return{target:{bundle_ref:n.bundle_ref,flow_id:n.flow_id,input_data:C0(n.input_data,t)}}}const DA=3e4,vg=new WeakMap;function FA(e,t,n=Date.now()){let r=vg.get(e);r||vg.set(e,r=new Map);const o=JSON.stringify(t),l=r.get(o);if(l&&n-l.at<DA)return l.answer;const c=Af(e)(t).then(u=>u.summary);return c.catch(()=>r==null?void 0:r.delete(o)),r.set(o,{at:n,answer:c}),c}function zA(e){vg.delete(e)}function E0(e){const[t,n]=_.useState(null),r=JSON.stringify(e.value);return _.useEffect(()=>{if(!e.connected||!e.request){n(null);return}let o=!0;return FA(e.request,e.value).then(l=>o&&n(lv(l))).catch(l=>o&&n(lv(g_(l)))),()=>{o=!1}},[e.request,e.connected,r,e.refresh_key]),t?s.jsx("span",{className:"auto_workspaces_line","data-field":"workspaces",title:t,children:t}):null}function BA(e){const{connected:t,request:n,value:r}=e,[o,l]=_.useState(null),[c,u]=_.useState(null),f=JSON.stringify(r);_.useEffect(()=>{if(!t){l(null),u(null);return}let y=!0;return u(null),Af(n)(r).then(w=>y&&l(w)).catch(w=>y&&u(`Could not read your workspaces: ${g_(w)}`)),()=>{y=!1}},[t,f,n]);const h=e.on_change,m=_.useCallback(async y=>{const w=await Af(n)(y);await h(y),l(w),zA(n)},[n,h]),g=t?e.disabled?"Saving…":null:"Connect to your gateway to choose workspaces.";return s.jsx(Ab,{level:"run",idPrefix:e.id_prefix,value:r,effective:o,onChange:m,loadError:t?c:g,unavailableReason:g,footer:e.footer})}class UA{constructor(){cs(this,"made",new Map);cs(this,"current",new Map)}record(t,n,r){if(this.current.set(t,r),n===null)return;let o=this.made.get(t);o||this.made.set(t,o=new Set),o.add(n+1)}note(t,n){if(n===null)return;let r=this.made.get(t);r||this.made.set(t,r=new Set),r.add(n+1)}expected(t,n){if(n===null)return null;const r=this.made.get(t);let o=n;for(;r&&r.has(o+1);)o+=1;return o}changes(t,n){if(!this.current.has(t)||!n.target)return n;const r=this.current.get(t)??null;return{...n,target:{...n.target,input_data:C0(n.target.input_data,r)}}}}async function WA(e,t,n,r,o){const l=t.expected(n.automation_id,n.summary.revision);await e.revise(n.automation_id,PA(n.definition,r),l,o),t.record(n.automation_id,l,r)}function $0(e){return`abstractobserver_list_open_${e}`}function A0(){try{return typeof localStorage>"u"?null:localStorage}catch{return null}}function qA(e,t=A0()){try{return(t==null?void 0:t.getItem($0(e)))!=="0"}catch{return!0}}function HA(e,t,n=A0()){try{n==null||n.setItem($0(e),t?"1":"0")}catch{}}function Mf(e){const[t,n]=_.useState(()=>qA(e)),r=_.useCallback(()=>{n(o=>{const l=!o;return HA(e,l),l})},[e]);return[t,r]}function Rf(e){return s.jsxs("button",{type:"button",className:`list_disclosure${e.className?` ${e.className}`:""}`,"aria-expanded":e.open,"aria-controls":e.controls,onClick:e.on_toggle,title:e.open?`Hide ${e.title.toLowerCase()}`:`Show ${e.title.toLowerCase()}`,children:[s.jsx(Be,{name:e.open?"chevronDown":"chevronRight",size:14}),s.jsx("span",{className:"pane_title",children:e.title}),e.count!==void 0?s.jsx("span",{className:"pane_count",children:e.count}):null]})}const VA=5e3,GA=[["","All"],["active","Active"],["paused","Paused"],["completed","Completed"],["failed","Failed"],["archived","Archived"]],KA={pause:No.pause,resume:No.resume,run_now:No.run_now,edit:No.revise,archive:`${No.archive}…`,discuss:No.discuss},YA={pause:Vi.pause,resume:Vi.resume,run_now:Vi.run_now,edit:Vi.revise,archive:Vi.archive,discuss:Vi.discuss},JA={pause:"pause",resume:"resume",run_now:"run_now",edit:"revise",archive:"archive",discuss:"discuss"},XA={legacy_pause:Vi.pause,legacy_resume:Vi.resume,legacy_run_now:Vi.run_now,open_run:"list",recreate:"refresh"};function ZA(e){return s.jsx("span",{className:"auto_state","data-field":"state",children:s.jsx(Sb,{status:e.status})})}function ym(e){return s.jsxs("span",{className:`auto_fact${e.className?` ${e.className}`:""}`,"data-field":e.field,title:e.label,children:[s.jsx(Be,{name:e.icon,size:12}),s.jsx("span",{children:e.children})]})}const QA={legacy_pause:"Suspend",legacy_resume:"Resume",legacy_run_now:"Run now",open_run:"Open run",recreate:"Recreate as automation"},eT="On: the schedule runs at its times. Off: suspended, scheduled runs are skipped until it is on again.";function cv(e){const t=e.busy||e.ctl.enabled?null:e.ctl.reason||"Not available now.";return s.jsx(Ni,{variant:"sm",className:"auto_switch",action:"active",id:`auto-active-${e.summary.automation_id}`,label:No.active,checked:e.summary.status==="active",unavailableReason:t,busy:e.busy,hint:e.hint,onChange:e.onChange})}function tT(e){const[t,n]=_.useState(void 0),{summary:r,ws:o}=e;return _.useEffect(()=>{let l=!0;return o.definition(r).then(c=>l&&n(c?N0(c):void 0),()=>l&&n(void 0)),()=>{l=!1}},[r.automation_id,r.revision,o.definition]),t===void 0?null:s.jsx(E0,{request:o.request,connected:o.connected,value:t,refresh_key:r.revision??""})}function nT(e){const t=e.summary,n=p0(t),r=e.state.selected_id===t.automation_id,o=e.state.busy,l=(f,h,m,g,y,w,k,b)=>s.jsxs("button",{type:"button",className:`btn btn_sm auto_action${k?" auto_action_icon":""}${y?` ${y}`:""}`,"data-action":f,disabled:!m.enabled,title:[k?h:null,m.enabled?null:m.reason,b].filter(Boolean).join(`
|
|
93
|
-
`)||void 0,"aria-label":k?h:void 0,"aria-description":b,onClick:g,children:[w?s.jsx(Be,{name:w,size:13}):null,k?null:s.jsx("span",{children:h})]},f);let c;if(n.legacy){const f=X$(t,o),h=t.status==="paused"?"legacy_resume":"legacy_pause",m=["legacy_run_now","open_run","recreate"];c=[s.jsx(cv,{summary:t,busy:o,ctl:f[h],hint:eT,onChange:()=>e.h.on_legacy_action(t,h)},"active"),...m.map(g=>l(g,QA[g],f[g],()=>e.h.on_legacy_action(t,g),void 0,XA[g]))]}else{const f=J$(t,o),h=t.status==="active"?"pause":"resume",m=["run_now","edit","discuss","archive"];c=[s.jsx(cv,{summary:t,busy:o,ctl:f.active,hint:Hm("active",t),onChange:()=>e.h.on_row_action(t,h)},"active"),...m.map(g=>l(g,KA[g],f[g],()=>e.h.on_row_action(t,g),g==="archive"?"danger auto_action_end":void 0,YA[g],g==="archive",Hm(JA[g],t)))]}const u=e.state.confirm_archive_id===t.automation_id;return s.jsxs("li",{className:`auto_row${r?" selected":""}`,"data-automation-id":t.automation_id,"data-legacy":n.legacy?"true":void 0,children:[s.jsxs("button",{type:"button",className:"auto_row_main",onClick:()=>e.h.on_select(t.automation_id),"aria-current":r?"true":void 0,children:[s.jsxs("span",{className:"auto_row_title",children:[n.title,n.legacy?s.jsx("span",{className:"chip scheduled",children:"legacy"}):null,s.jsx(ZA,{status:n.state}),n.attention?s.jsxs("span",{className:"chip warn auto_row_attention","data-field":"attention",children:[s.jsx(Be,{name:"warning",size:12})," ",n.attention]}):null]}),s.jsxs("span",{className:"auto_row_facts",children:[s.jsx(ym,{icon:"refresh",field:"cadence",label:"When it runs",children:n.cadence}),n.current?s.jsx(ym,{icon:"loader",field:"current",label:"Running now",className:"auto_row_current",children:n.current}):null,s.jsxs(ym,{icon:"clock",field:"next",label:"Next run",children:["next: ",n.next_run]}),s.jsx(ym,{icon:"info",field:"last-status",label:"Last run",children:n.last_status})]}),e.ws&&!n.legacy?s.jsx(tT,{summary:t,ws:e.ws}):null,n.last?s.jsx("span",{className:"auto_row_excerpt","data-field":"excerpt",children:r0(n.last)}):null]}),s.jsx("div",{className:"auto_row_actions",role:"toolbar","aria-label":`Controls for ${n.title}`,children:c}),u?s.jsxs("div",{className:"auto_row_confirm",role:"group","aria-label":"Confirm archive",children:[s.jsxs("span",{children:["Archive “",n.title,"”? Its history stays readable; it will not run again."]}),s.jsxs("button",{type:"button",className:"btn btn_sm danger auto_action","data-action":"archive-confirm",disabled:o,onClick:()=>e.h.on_confirm_archive(t),children:[s.jsx(Be,{name:"archive",size:13}),s.jsx("span",{children:"Archive"})]}),s.jsxs("button",{type:"button",className:"btn btn_sm auto_action","data-action":"archive-cancel",onClick:e.h.on_cancel_archive,children:[s.jsx(Be,{name:"x",size:13}),s.jsx("span",{children:"Keep it"})]})]}):null]})}function sT(e){const t=e.state,n=e.list?e.list.open:!0,r=t.error??t.list_error,o=r?qm(r):null;return s.jsxs("section",{className:`pane auto_list${n?"":" list_collapsed"}`,"aria-label":"Automations",children:[s.jsxs("div",{className:"pane_header",children:[e.list?s.jsx(Rf,{open:n,on_toggle:e.list.on_toggle,controls:"auto_list_body",title:"Automations",count:yp(t).length}):s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"pane_title",children:"Automations"}),s.jsx("span",{className:"pane_count",children:yp(t).length})]}),s.jsx("span",{className:"pane_spacer"}),s.jsx("select",{className:"seg_select",value:t.status_filter,onChange:l=>e.h.on_status_filter(l.target.value),"aria-label":"Filter by status",children:GA.map(([l,c])=>s.jsx("option",{value:l,children:c},l||"all"))}),s.jsx("button",{type:"button",className:"btn btn_sm auto_icon_btn","data-action":"refresh",onClick:e.h.on_refresh,disabled:t.loading||!e.available.available,title:"Refresh","aria-label":"Refresh",children:s.jsx(Be,{name:t.loading?"loader":"refresh",size:14})}),s.jsxs("a",{className:`btn btn_sm auto_new${e.available.available?"":" disabled"}`,"data-action":"new",href:z$,"aria-disabled":!e.available.available,title:"New automation: opens Launch in Automate mode","aria-label":"New automation",onClick:l=>{l.preventDefault(),e.available.available&&e.h.on_new()},children:[s.jsx(Be,{name:"plus",size:14}),s.jsx("span",{className:"auto_new_label",children:"New automation"})]})]}),s.jsxs("div",{className:"pane_body scroll",id:"auto_list_body",hidden:!n,children:[e.available.available?null:s.jsx("div",{className:"warn_callout",role:"note","data-unavailable":"true",children:e.available.reason}),o?s.jsxs("div",{className:"observe_context_card error auto_list_error",role:"alert","data-code":r==null?void 0:r.code,children:[s.jsx(Be,{name:"error",size:14}),s.jsxs("span",{className:"auto_list_msg",children:[s.jsx("strong",{children:o.title})," ",s.jsx("span",{children:o.detail})]}),t.error&&e.h.on_dismiss_error?s.jsx("button",{type:"button",className:"auto_dismiss","data-action":"dismiss-error","aria-label":"Dismiss",title:"Dismiss",onClick:e.h.on_dismiss_error,children:s.jsx(Be,{name:"x",size:12})}):null]}):null,s.jsx("div",{className:`auto_notice${t.notice?" on":""}`,role:"status",children:t.notice?s.jsxs(s.Fragment,{children:[s.jsx(Be,{name:"check",size:13}),s.jsx("span",{className:"auto_list_msg",children:t.notice}),e.h.on_dismiss_notice?s.jsx("button",{type:"button",className:"auto_dismiss","data-action":"dismiss-notice","aria-label":"Dismiss",title:"Dismiss",onClick:e.h.on_dismiss_notice,children:s.jsx(Be,{name:"x",size:12})}):null]}):null}),e.available.available&&t.loaded&&!t.items.length?s.jsx("div",{className:"help_text muted",children:"No automations yet. Create one from Launch → Automate."}):null,iv(t)>0&&t.status_filter!=="archived"?s.jsx("div",{className:"auto_show_archived",children:s.jsx(Ni,{variant:"sm",action:"show-archived",label:`Archived (${iv(t)})`,hint:"List archived automations too. Their history stays readable; they do not run.",checked:t.show_archived,onChange:l=>e.h.on_show_archived(l)})}):null,s.jsx("ul",{className:"auto_rows",children:yp(t).map(l=>s.jsx(nT,{summary:l,state:t,h:e.h,ws:e.ws},l.automation_id))})]})]})}function rT(e,t,n,r){const o=e.state,l=o.detail;if(!l||_l(l.summary))return null;const c=l.automation_id;return{summary:l.summary,...l.definition?{definition:l.definition}:{},occurrences:l.occurrences,triggerSources:o.trigger_sources,busy:o.busy,...l.error?{error:l.error}:{},onRevise:async(u,f,h)=>{if(!r)return e.revise(c,u,f,h==null?void 0:h.command_id);const m=r.expected(c,f),g=await e.revise(c,r.changes(c,u),m,h==null?void 0:h.command_id);return r.note(c,m),g},onCommand:(u,f,h)=>e.command(c,u,f,h==null?void 0:h.command_id),onDiscuss:async(u,f,h)=>{const m=await e.discuss(c,u,f,h==null?void 0:h.request_id);return t.on_open_session(m,fy(u,m),u),m},onSeen:u=>e.seen(c,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,f,h)=>e.answer_wait(c,u,f,h),...n?{editOpen:n.open,onEditOpenChange:n.on_change}:{},emailStatus:o.email_status,...t.on_open_my_email?{onOpenMyEmail:()=>{var u;return(u=t.on_open_my_email)==null?void 0:u.call(t)}}:{}}}function iT(e){var u,f;const t=e.ctl.state.detail;if(!t&&e.ctl.state.selected_id)return s.jsx("section",{className:"pane auto_detail auto_detail_empty","aria-busy":"true",children:s.jsx("div",{className:"help_text muted",children:"Loading…"})});if(!t)return s.jsx("section",{className:"pane auto_detail auto_detail_empty",children:s.jsxs("div",{className:"help_text muted",children:["Select an automation to read its runs as a conversation, change it, or discuss a result (",ag.toLowerCase(),")."]})});if(_l(t.summary)){const h=p0(t.summary);return s.jsxs("section",{className:"pane auto_detail","data-legacy":"true",children:[s.jsxs("div",{className:"pane_header",children:[s.jsx("span",{className:"pane_title",children:h.title}),s.jsx("span",{className:"chip scheduled",children:"legacy"})]}),s.jsxs("div",{className:"pane_body",children:[s.jsxs("p",{className:"help_text",children:["A schedule created before automations (",h.cadence,"). It keeps working with its existing controls: suspend, resume, run now and edit the interval from its run view. “Recreate as automation” opens Launch → Automate prefilled with its workflow, inputs and interval; the legacy schedule is not changed."]}),s.jsxs("div",{className:"auto_row_actions",children:[s.jsx("button",{type:"button",className:"btn btn_sm","data-action":"open_run",onClick:()=>e.h.on_legacy_action(t.summary,"open_run"),children:"Open run"}),s.jsx("button",{type:"button",className:"btn btn_sm primary","data-action":"recreate",onClick:()=>e.h.on_legacy_action(t.summary,"recreate"),children:"Recreate as automation"})]})]})]})}const n=e.workspaces,r=rT(e.ctl,e.host,e.edit,n==null?void 0:n.revisions),o=e.ctl,l=t.definition,c=N0(l);return s.jsxs("section",{className:"pane auto_detail",children:[e.browser??null,n&&l?s.jsx("div",{className:"auto_workspaces","data-section":"workspaces","data-editing":(u=e.edit)!=null&&u.open?"true":void 0,children:(f=e.edit)!=null&&f.open?s.jsx(s.Fragment,{children:s.jsx(BA,{footer:s.jsx("p",{className:"help_text muted auto_workspaces_help",children:"Each change is saved at once as a new revision; it applies from the next run."}),id_prefix:`observer-automation-workspace-${t.automation_id}`,connected:n.connected,request:n.request,value:c,disabled:o.state.busy,on_change:h=>WA(o,n.revisions,{automation_id:t.automation_id,summary:t.summary,definition:l},h,pa())})}):s.jsx(E0,{request:n.request,connected:n.connected,value:c,refresh_key:t.summary.revision??""})}):null,r?s.jsx(TE,{...r,workflowPickerOptions:e.workflowPickerOptions,availableTools:e.availableTools}):null]})}function oT(e,t){if(t==="edit")return{kind:"edit"};if(t!=="discuss")return{kind:"forward"};const n=g0(e);return n===null?{kind:"none"}:{kind:"discuss",index:n}}function aT(e){const t=e.ctl,n=_.useRef(null);n.current||(n.current=new UA);const r=e.workspace_request?{request:e.workspace_request,connected:e.active,definition:T=>t.definition(T)}:void 0,[o,l]=Mf("automations"),[c,u]=_.useState(null),f=T=>u(A=>({...T,opened:((A==null?void 0:A.opened)||0)+1})),[h,m]=_.useState(""),[g,y]=_.useState("");_.useSyncExternalStore(T=>t.subscribe(T),()=>t.state,()=>t.state);const[w,k]=_.useState(()=>typeof document>"u"||document.visibilityState!=="hidden");_.useEffect(()=>{const T=()=>k(document.visibilityState!=="hidden");return document.addEventListener("visibilitychange",T),()=>document.removeEventListener("visibilitychange",T)},[]),_.useEffect(()=>{if(!e.active||!w||!e.available.available)return;t.refresh();const T=window.setInterval(()=>void t.refresh(),iA);return()=>window.clearInterval(T)},[t,e.active,w,e.available.available]);const b=t.state.detail,S=t.state.notice;_.useEffect(()=>{if(!S)return;const T=window.setTimeout(()=>t.dismiss_notice(),VA);return()=>window.clearTimeout(T)},[t,S]);const N={...e.host,on_open_workspace:T=>m(A=>A===T?"":T),fetch_gateway:e.gateway.fetch_gateway,on_open_session:(T,A,W)=>{e.host.on_open_session(T,A,W),b&&f({automation_id:b.automation_id,automation_title:b.summary.title,occurrence_index:W,session:T})}},R={...e.h,on_select:T=>{u(null),m(""),T!==g&&y(""),e.h.on_select(T)},on_dismiss_notice:()=>t.dismiss_notice(),on_dismiss_error:()=>t.dismiss_error(),on_row_action:(T,A)=>{const W=oT(T,A);W.kind==="forward"?e.h.on_row_action(T,A):W.kind==="edit"?(u(null),m(""),y(T.automation_id),e.h.on_select(T.automation_id)):W.kind==="discuss"&&(e.h.on_select(T.automation_id),f({automation_id:T.automation_id,automation_title:T.title,occurrence_index:W.index}))}};return s.jsxs("div",{className:`page auto_page${o?"":" list_collapsed"}`,children:[s.jsx(sT,{state:t.state,available:e.available,h:R,list:{open:o,on_toggle:l},ws:r}),c?s.jsx(RA,{gateway:e.gateway,discussion:c,connected:e.active,voice_session_id:e.voice_session_id||"",on_fork:async(T,A,W)=>{const z=await t.discuss(T,A,W);return e.host.on_open_session(z,fy(A,z),A),u(J=>J&&{...J,session:z}),z},on_close:()=>u(null)},c.opened):s.jsx(iT,{workflowPickerOptions:e.workflowPickerOptions,availableTools:e.availableTools,ctl:t,host:N,h:R,edit:{open:!!b&&g===b.automation_id,on_change:T=>y(T&&b?b.automation_id:"")},workspaces:e.workspace_request?{request:e.workspace_request,connected:e.active,revisions:n.current}:void 0,browser:h?s.jsx(Xb,{fetchGateway:e.gateway.fetch_gateway,runId:h,title:h===(b==null?void 0:b.automation_id)?"Automation files":"Run files",onClose:()=>m("")}):void 0})]})}function lT(e){return s.jsx(Ni,{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 cT(e){return s.jsx("div",{className:`settings_choice ${e.checked?"on":""}`,children:s.jsx(Ni,{variant:"row",action:"assistant-skill",label:s.jsxs("span",{className:"settings_choice_name",children:[e.name,e.version?s.jsxs("em",{children:[" v",e.version]}):null]}),ariaLabel:e.name,description:e.description||void 0,checked:e.checked,onChange:e.onChange})})}const uT="On: the schedule runs at its times. Off: suspended, scheduled runs are skipped until it is on again.";function dT(e){return s.jsx(Ni,{variant:"sm",action:"schedule-active",className:"observe_schedule_switch",label:"Active",hint:uT,checked:e.active,unavailableReason:e.unavailableReason,busy:e.busy,onChange:e.onChange})}function fT(e){return s.jsx(Ni,{variant:"sm",action:"mindmap-live",label:"Live",hint:"Refresh the map as new memory arrives.",checked:e.checked,onChange:e.onChange})}function hT(e){return s.jsx(Ni,{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})}const uv={framework:null,gateway:null,gatewayNote:"checking…"};function mT(){const e="0.7.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 _T(){return zS("abstractobserver",mT())}async function pT(e){let t;try{t=await e.gateway_about()}catch(n){return cw(null,n instanceof Error?n.message||n.name:String(n))}return cw(t)}class Ym{constructor(t){this._maxSize=Ym._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=Ym._normalizeMaxSize(t);this._maxSize=n,this._values.length>n&&(this._values=this._values.slice(this._values.length-n))}clear(){this._values=[]}push(t){const n=Number(t),r=Number.isFinite(n)?n:null;this._values.push(r),this._values.length>this._maxSize&&this._values.splice(0,this._values.length-this._maxSize)}values(){return this._values.slice()}last(){return this._values.length?this._values[this._values.length-1]:null}}function gT(e){try{return new URL(String(e)),!0}catch{return!1}}function yT({baseUrl:e,endpoint:t}){const n=String(t||"api/gateway/host/metrics/gpu");return gT(n)?n:e&&String(e).trim()?new URL(n,String(e)).toString():n}async function wT({token:e,getToken:t}){if(typeof t=="function"){const n=await t();return n==null?"":String(n)}return e==null?"":String(e)}function vT({token:e}){const t=String(e||"").trim();return t?{Authorization:`Bearer ${t}`}:{}}function xT(e){if(!e||typeof e!="object")return null;const t=Number(e.utilization_gpu_pct);if(Number.isFinite(t))return t;const n=e.gpus;if(Array.isArray(n)&&n.length){const r=n.map(l=>Number(l&&l.utilization_gpu_pct)).filter(l=>Number.isFinite(l));return r.length?r.reduce((l,c)=>l+c,0)/r.length:null}return null}async function bT({baseUrl:e,endpoint:t,token:n,getToken:r,signal:o,fetchImpl:l}={}){const c=yT({baseUrl:e,endpoint:t}),u=await wT({token:n,getToken:r}),f=l||globalThis.fetch;if(typeof f!="function")return{ok:!1,status:0,error:"fetch_unavailable",payload:null};let h;try{h=await f(c,{method:"GET",headers:{Accept:"application/json",...vT({token:u})},signal:o})}catch(g){return{ok:!1,status:0,error:"network_error",detail:g instanceof Error?g.message:String(g),payload:null}}let m=null;try{m=await h.json()}catch{m=null}return{ok:h.ok,status:h.status,error:h.ok?null:"http_error",payload:m}}const sf=Object.freeze({tickMs:1500,historySize:20,endpoint:"api/gateway/host/metrics/gpu",baseUrl:"",mode:"full"});function kT(e){return Number.isFinite(e)?Math.min(1,Math.max(0,e)):0}function dv(e,t,n){return Number.isFinite(e)?Math.min(n,Math.max(t,e)):t}function fv(e,t){const n=Number(e);return Number.isFinite(n)?Math.floor(n):t}function vp(e,t=1){const n=dv(Number(e)/100,0,1),r=Math.round(140-140*n),o=dv(Number(t),0,1);return o>=1?`hsl(${r} 85% 55%)`:`hsl(${r} 85% 55% / ${o})`}function hv(e){const t={...sf,...e||{}};return t.tickMs=Math.max(250,fv(t.tickMs,sf.tickMs)),t.historySize=Math.max(1,Math.min(200,fv(t.historySize,sf.historySize))),t.endpoint=String(t.endpoint||sf.endpoint),t.baseUrl=String(t.baseUrl||""),t.mode=String(t.mode||sf.mode).trim().toLowerCase(),t.mode!=="icon"&&(t.mode="full"),t}function jT(){return`
|
|
94
|
-
: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}
|
|
95
|
-
.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)}
|
|
96
|
-
.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))}
|
|
97
|
-
.wrap.icon .top{display:none}
|
|
98
|
-
.wrap.icon .bars{height:var(--monitor-gpu-bars-height,18px)}
|
|
99
|
-
.top{display:flex;align-items:baseline;justify-content:space-between;gap:10px}
|
|
100
|
-
.label{font-size:var(--monitor-gpu-font-size,var(--font-size-sm,12px));opacity:.9}
|
|
101
|
-
.value{font-variant-numeric:tabular-nums;font-size:var(--monitor-gpu-font-size,var(--font-size-sm,12px));opacity:.95}
|
|
102
|
-
.bars{display:flex;align-items:flex-end;gap:2px;height:var(--monitor-gpu-bars-height,34px);overflow:hidden}
|
|
103
|
-
.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}
|
|
104
|
-
.bar.missing{background:var(--monitor-gpu-bar-missing,#62708a);opacity:.35}
|
|
105
|
-
.bar.error{background:var(--monitor-gpu-bar-error,#ff6b6b);opacity:.7}
|
|
106
|
-
.muted{opacity:.6}
|
|
107
|
-
`}class ST{constructor(t,n={}){if(!t||typeof t!="object")throw new TypeError("target element is required");this._target=t,this._opts=hv(n),this._buffer=new Ym(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=jT();const r=document.createElement("div");r.className=this._opts.mode==="icon"?"wrap icon":"wrap";const o=document.createElement("div");o.className="top";const l=document.createElement("div");l.className="label",l.textContent="GPU";const c=document.createElement("div");c.className="value muted",c.textContent="—",o.appendChild(l),o.appendChild(c);const u=document.createElement("div");u.className="bars",r.appendChild(o),r.appendChild(u),t.appendChild(n),t.appendChild(r),this._els={wrap:r,value:c,bars:u},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=hv({...this._opts,...t||{}}),r=n.historySize!==this._opts.historySize,o=n.tickMs!==this._opts.tickMs,l=n.mode!==this._opts.mode;this._opts=n,l&&this._mounted&&this._els&&this._els.wrap&&(this._els.wrap.className=n.mode==="icon"?"wrap icon":"wrap"),r&&(this._buffer.setMaxSize(n.historySize),this._mounted&&this._rebuildBars()),o&&this._running?(this.stop(),this.start()):this._mounted&&this._render()}push(t){this._buffer.push(t),this._render()}_rebuildBars(){if(!this._els)return;const{bars:t}=this._els;t.textContent="";for(let n=0;n<this._opts.historySize;n+=1){const r=document.createElement("div");r.className="bar missing",r.style.height="2px",t.appendChild(r)}}_render({error:t=!1}={}){if(!this._els)return;const{wrap:n,value:r,bars:o}=this._els,l=this._buffer.values(),c=this._buffer.last(),u=Number.isFinite(c)?Math.max(0,Math.min(100,c)):null;u==null?(r.textContent=t?"N/A":"—",r.classList.add("muted")):(r.textContent=`${u.toFixed(0)}%`,r.classList.remove("muted")),n&&(n.title=u==null?"GPU —":`GPU ${u.toFixed(0)}%`,u==null?(n.style.removeProperty("--monitor-gpu-accent"),n.style.removeProperty("--monitor-gpu-accent-glow")):(n.style.setProperty("--monitor-gpu-accent",vp(u,.95)),n.style.setProperty("--monitor-gpu-accent-glow",vp(u,.35))));const f=Array.from(o.children),h=Math.max(0,f.length-l.length),m=Math.max(2,o&&typeof o.clientHeight=="number"&&o.clientHeight>0?o.clientHeight:34);for(let g=0;g<f.length;g+=1){const y=f[g],w=g-h,k=w>=0?l[w]:null,b=Number.isFinite(k)?k:null,S=b==null?0:kT(b/100),N=Math.max(2,Math.min(m,Math.round(S*m)));y.style.height=`${N}px`,y.style.background=b==null?"":vp(b),y.className="bar",b==null&&y.classList.add("missing"),t&&y.classList.add("error")}}async _tick(){const t=String(this._token||"").trim(),n=this._getToken,r=!!t||typeof n=="function";this._abort&&this._abort.abort(),this._abort=new AbortController;const o=await bT({baseUrl:this._opts.baseUrl,endpoint:this._opts.endpoint,token:t,getToken:n,signal:this._abort.signal}),l=o&&o.payload,c=l&&typeof l=="object"?l.supported!==!1:!0,u=xT(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(),h=typeof this._getToken=="function";if(!r&&(!!f||h))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(!c||u==null){this._buffer.push(null),this._render();return}this._buffer.push(u),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 NT(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 ST(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"),c=this.getAttribute("endpoint"),u=this.getAttribute("base-url"),f=this.getAttribute("mode");return{...o!=null?{tickMs:o}:{},...l!=null?{historySize:l}:{},...c!=null?{endpoint:c}:{},...u!=null?{baseUrl:u}:{},...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 Wu(e){return String(e||"").trim().toLowerCase()}function w_(e){return`${(e==null?void 0:e.filename)||""} ${(e==null?void 0:e.source_path)||""}`.trim().toLowerCase()}function Nf(e,t){return t.some(n=>e.endsWith(n))}function CT(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 ET(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 $T(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 T0(e,t){var c,u,f,h,m;const n=Wu(e==null?void 0:e.content_type),r=w_(e),o=[e==null?void 0:e.semantic_kind,e==null?void 0:e.render_kind,e==null?void 0:e.task,(c=e==null?void 0:e.tags)==null?void 0:c.semantic_kind,(u=e==null?void 0:e.tags)==null?void 0:u.render_kind,(f=e==null?void 0:e.tags)==null?void 0:f.task,(h=e==null?void 0:e.tags)==null?void 0:h.kind,(m=e==null?void 0:e.tags)==null?void 0:m.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")||Nf(r,[".py",".js",".jsx",".ts",".tsx",".mjs",".cjs",".sh",".bash",".zsh",".go",".rs",".java",".c",".cc",".cpp",".h",".hpp",".cs",".php",".rb",".swift",".kt",".sql"]))return!0;const l=String(t||"").replace(/\r\n/g,`
|
|
108
|
-
`).replace(/\r/g,`
|
|
109
|
-
`).split(`
|
|
110
|
-
`);return M0(l)}function AT(e){const n=String(e||"").replace(/\r\n/g,`
|
|
111
|
-
`).replace(/\r/g,`
|
|
112
|
-
`).split(`
|
|
113
|
-
`),r=n.findIndex(c=>/^Markdown Content:\s*$/i.test(c.trim()));if(r===-1)return null;const o=[];for(const c of n.slice(0,r)){const u=c.match(/^\s*([A-Za-z][A-Za-z0-9 /_-]{1,40}):\s*(.+?)\s*$/);u&&o.push({label:u[1].trim(),value:u[2].trim()})}const l=n.slice(r+1).join(`
|
|
114
|
-
`).trim();return!o.length&&!l?null:{metadata:o,body:l}}function TT(e){const t=e.map(n=>n.trim()).filter(Boolean).slice(0,8);if(t.length<2)return!1;for(const n of[","," ",";"]){const r=t.map(o=>o.split(n).length);if(r[0]>=3&&r.every(o=>Math.abs(o-r[0])<=1))return!0}return!1}function MT(e){const t=e.map(r=>r.trimEnd()).filter(Boolean).slice(0,20);if(!t.length)return!1;const n=t.filter(r=>/^(\[[^\]]+\]|\d{4}-\d{2}-\d{2}[t\s]|\w+:\s|traceback\b|error\b|warn\b|info\b)/i.test(r.trim())).length;return t.length>=4&&n/t.length>=.55?!0:M0(e)}function M0(e){const t=e.map(r=>r.trimEnd()).filter(Boolean).slice(0,20);if(!t.length)return!1;const n=t.filter(r=>/[{};]\s*$/.test(r)||/^\s*(import|export|const|let|var|function|class|def|if|for|while|return)\b/.test(r)).length;return t.length>=4&&n/t.length>=.55}function RT(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,`
|
|
115
|
-
`).replace(/\r/g,`
|
|
116
|
-
`).split(`
|
|
117
|
-
`).map(f=>f.trim()).filter(Boolean).slice(0,80);if(o.length<12)return!1;const l=o.filter(f=>f.length<=28).length,c=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||c>=2)}function LT(e,t){var h;const n=String(t||""),r=CT(e);if(/(^|[^a-z0-9])(markdown|mdown)([^a-z0-9]|$)/i.test(r))return!0;if(!n.trim())return!1;if(/(^|\n)\s*Markdown Content:\s*(\n|$)/i.test(n)||n.includes("```")||/(^|\n)\s*#{1,6}\s+\S/.test(n)||/(^|\n)[ \t]*[-*][ \t]+\S/.test(n)||/(^|\n)[ \t]*\d+[\.)][ \t]+\S/.test(n)||/\*\*[^*\n][\s\S]*?\*\*/.test(n)||/\[[^\]\n]+\]\([^)]+\)/.test(n)||/(^|\n)\s*\|.+\|\s*(\n|$)/.test(n)&&/(^|\n)\s*\|?\s*:?-{3,}:?\s*(\|\s*:?-{3,}:?\s*)+\|?\s*(\n|$)/.test(n))return!0;const o=n.replace(/\r\n/g,`
|
|
118
|
-
`).replace(/\r/g,`
|
|
119
|
-
`).split(`
|
|
120
|
-
`),l=o.map(m=>m.trim()).filter(Boolean);if(l.length<2||RT(n)||TT(o)||MT(o))return!1;const c=((h=n.match(/[A-Za-z][A-Za-z'-]+/g))==null?void 0:h.length)||0,u=o.filter(m=>!m.trim()).length,f=l.filter(m=>/[A-Za-z]{3,}/.test(m)&&m.length>=12).length;return c>=24&&f>=2&&(u>=1||l[0].length<=140)}function Cf(e){const t=Wu(e==null?void 0:e.modality),n=Wu(e==null?void 0:e.content_type),r=w_(e),o=ET(e);return t==="image"||n.startsWith("image/")||Nf(r,[".png",".jpg",".jpeg",".gif",".webp",".bmp",".svg",".tif",".tiff",".heic"])?"image":t==="audio"||t==="voice"||t==="music"||t==="sound"||n.startsWith("audio/")||/(tts|stt|voice|music|sound|speech|audio)/i.test(o)||Nf(r,[".wav",".mp3",".m4a",".aac",".flac",".ogg",".opus",".aiff",".mid",".midi"])?"audio":t==="video"||n.startsWith("video/")||Nf(r,[".mp4",".mov",".webm",".mkv",".avi",".m4v"])?"video":!n||t==="text"||n.startsWith("text/")||n.includes("json")||n.includes("yaml")||n.includes("toml")||n.includes("xml")||n.includes("html")||n.includes("markdown")||n.includes("csv")||T0(e,"")?"text":"binary"}function Jm(e,t){const n=Wu(e==null?void 0:e.content_type),r=w_(e),o=String(t||"").trim();return n.includes("html")||r.endsWith(".html")||r.endsWith(".htm")||$T(t)?"html":T0(e,t)?"code":n.includes("markdown")||r.endsWith(".md")||r.endsWith(".markdown")?"markdown":n.includes("json")||r.endsWith(".json")||r.endsWith(".jsonl")||(o.startsWith("{")||o.startsWith("["))&&y_(o)!==null?"json":LT(e,t)?"markdown":"text"}function hy(e,t=""){const n=Cf(e);if(n==="image"||n==="video")return n;if(n==="audio"){const r=(e==null?void 0:e.tags)||{},o=[e==null?void 0:e.semantic_kind,e==null?void 0:e.modality,e==null?void 0:e.task,r.semantic_kind,r.modality,r.kind,r.task,r.source,e==null?void 0:e.filename,e==null?void 0:e.source_path].map(l=>String(l||"").trim().toLowerCase()).filter(Boolean).join(" ");return/(^|[^a-z0-9])(voice|tts|speech)([^a-z0-9]|$)/i.test(o)?"voice":/(^|[^a-z0-9])(music|song|instrumental|t2m)([^a-z0-9]|$)/i.test(o)?"music":/(^|[^a-z0-9])(sound|sfx|recording)([^a-z0-9]|$)/i.test(o)?"sound":"audio"}if(n==="binary"){const r=Wu(e==null?void 0:e.modality),o=Wu(e==null?void 0:e.content_type),l=w_(e);return r==="document"||o.includes("pdf")||Nf(l,[".pdf",".doc",".docx",".ppt",".pptx",".xls",".xlsx"])?"document":"other"}return Jm(e,t)}function xp(e){var h,m;const t=String(e||"").replace(/\r\n/g,`
|
|
121
|
-
`).replace(/\r/g,`
|
|
122
|
-
`).trim();if(!t)return"";const n=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]),r=t.match(/<!--[\s\S]*?-->|<!doctype\b[^>]*>|<!\[CDATA\[[\s\S]*?\]\]>|<\/?[A-Za-z][^>]*>|[^<]+/gi)||[t],o=[];let l=0,c="";const u=g=>" ".repeat(Math.max(0,g)),f=(g,y)=>{const w=g.match(/^(<\/?|<!)([^\s/>]+)([\s\S]*?)(\/?>)$/);if(!w||g.length<=120||g.startsWith("</")||g.startsWith("<!"))return[`${u(y)}${g.trim()}`];const k=(w[3]||"").trim();if(!k)return[`${u(y)}${g.trim()}`];const b=k.match(/[^\s="'<>`]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'<>`]+))?/g)||[k];return[`${u(y)}${w[1]}${w[2]}`,...b.map(S=>`${u(y+1)}${S.trim()}`),`${u(y)}${w[4]}`]};for(const g of r){const y=String(g||"");if(!y.trim())continue;const w=y.trim().toLowerCase();if(w.startsWith("</")){const b=((h=w.match(/^<\/\s*([a-z0-9:-]+)/))==null?void 0:h[1])||"";c&&b===c&&(c=""),l=Math.max(0,l-1),o.push(`${u(l)}${y.trim()}`);continue}if(y.trimStart().startsWith("<")){o.push(...f(y,l));const b=((m=w.match(/^<\s*([a-z0-9:-]+)/))==null?void 0:m[1])||"";/\/>\s*$/.test(y)||w.startsWith("<!")||n.has(b)||(l+=1,(b==="script"||b==="style")&&(c=b));continue}if(c){const b=y.trim();b&&o.push(...b.split(`
|
|
123
|
-
`).map(S=>`${u(l)}${S.trimEnd()}`));continue}const k=y.replace(/\s+/g," ").trim();k&&o.push(`${u(l)}${k}`)}return o.join(`
|
|
124
|
-
`)}const IT=/^\s*<runtime_metadata>\s*([\s\S]*?)\s*<\/runtime_metadata>\s*/i;function my(e){const t=typeof e=="string"?e:String(e??""),n=IT.exec(t);if(!n)return{text:t.trim(),metadata:null,stripped:!1};let r=null;try{const o=JSON.parse(String(n[1]||"").trim());o&&typeof o=="object"&&!Array.isArray(o)&&(r=o)}catch{r=null}return{text:t.slice(n[0].length).trim(),metadata:r,stripped:!0}}function R0(...e){const t={};for(const n of e)if(!(!n||typeof n!="object"||Array.isArray(n)))for(const[r,o]of Object.entries(n))o==null||String(o).trim()===""||(t[r]=o);return Object.keys(t).length?t:null}function xg(e){if(e==null)return"";if(typeof e=="string")return e.trim();if(Array.isArray(e))return e.map(t=>xg(t)).filter(Boolean).join(`
|
|
125
|
-
`).trim();if(typeof e=="object"){const t=e.text??e.content??e.message??e.value;if(t!==e){const n=xg(t);if(n)return n}}return""}function L0(e){const t=my(xg(e));return{text:t.text,runtime_metadata:t.metadata}}function OT(e){var r,o;if(!e)return{text:"",runtime_metadata:null};const t=typeof e.prompt=="string"?String(e.prompt).trim():"";if(t){const l=my(t);return{text:l.text,runtime_metadata:l.metadata}}const n=[(r=e.context)==null?void 0:r.messages,e.messages,e.conversation,e.history].filter(Array.isArray);for(const l of n)for(let c=l.length-1;c>=0;c-=1){const u=l[c],f=String((u==null?void 0:u.role)||(u==null?void 0:u.speaker)||"").trim().toLowerCase();if(f&&f!=="user"&&f!=="human")continue;const h=L0((u==null?void 0:u.content)??(u==null?void 0:u.text)??u);if(h.text)return{text:h.text,runtime_metadata:R0(h.runtime_metadata,u!=null&&u.runtime_metadata&&typeof u.runtime_metadata=="object"?u.runtime_metadata:null,(o=u==null?void 0:u.metadata)!=null&&o.runtime_metadata&&typeof u.metadata.runtime_metadata=="object"?u.metadata.runtime_metadata:null)}}return{text:"",runtime_metadata:null}}function PT(e,t=6){var l,c;if(!e)return[];const r=[(l=e.context)==null?void 0:l.messages,e.messages,e.conversation,e.history].filter(Array.isArray).find(u=>u.length)||[],o=[];for(const u of r){const f=String((u==null?void 0:u.role)||(u==null?void 0:u.speaker)||(u==null?void 0:u.author)||"").trim().toLowerCase()||"message",h=L0((u==null?void 0:u.content)??(u==null?void 0:u.text)??(u==null?void 0:u.message)??u),m=h.text;if(!m)continue;const g=String((u==null?void 0:u.ts)||(u==null?void 0:u.timestamp)||(u==null?void 0:u.created_at)||(u==null?void 0:u.time)||"").trim(),y=R0(h.runtime_metadata,u!=null&&u.runtime_metadata&&typeof u.runtime_metadata=="object"?u.runtime_metadata:null,(c=u==null?void 0:u.metadata)!=null&&c.runtime_metadata&&typeof u.metadata.runtime_metadata=="object"?u.metadata.runtime_metadata:null);o.push({role:f,text:m,ts:g,runtime_metadata:y})}return o.slice(Math.max(0,o.length-Math.max(1,t)))}function I0(e){const t=String(e||"").trim().toLowerCase().replace(/\s+/g," ");return t==="please respond:"||t==="please respond"||t==="type response..."||t==="type response"}function DT(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 O0="inferred from the call's arguments (regex heuristic) — not a declared risk tier; declared tiers replace this when the grant API ships";function P0(e){const t=String((e==null?void 0:e.name)||"").trim().toLowerCase(),n=e!=null&&e.arguments&&typeof e.arguments=="object"?e.arguments:{},r=String((n==null?void 0:n.command)||(n==null?void 0:n.cmd)||(n==null?void 0:n.shell)||"").trim().toLowerCase(),o=[];return(t.includes("execute_command")||t.includes("terminal")||r)&&o.push("Shell"),/[;&|]?\s*(rm|rmdir|mv|chmod|chown|sudo)\b/.test(r)&&o.push("Destructive risk"),/(^|\s)(curl|wget|scp|ssh|nc|ncat|ftp)\b/.test(r)&&o.push("Network"),/(^|\s)(cat|sed|rg|grep|ls|find|pwd)\b/.test(r)&&!/[>|]\s*\S/.test(r)&&o.push("Read path"),/[>|]\s*\S|(^|\s)(tee|touch|mkdir|cp)\b/.test(r)&&o.push("Filesystem write"),o.length||o.push("Tool call"),Array.from(new Set(o)).slice(0,4)}function _y(e,t){const n=String((e==null?void 0:e.reason)||"").trim().toLowerCase(),r=DT(t);return t.length?`Approval required: ${r||"tool call"}`:n==="user"?"Waiting for your answer":n==="event"?"Waiting for a user response event":n==="subworkflow"?"Waiting for a subworkflow":n==="until"?"Scheduled wait":n?`Waiting: ${n}`:"Waiting for input"}function D0(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 F0(e,t){const n=String((e==null?void 0:e.prompt)||"").trim(),r=my(n),o=OT(t);return r.text&&!I0(r.text)?{text:r.text,runtime_metadata:r.metadata}:o.text?o:{text:r.text||n,runtime_metadata:r.metadata}}function FT(e,t){return F0(e,t).text}function zT(e,t){return e||String(t||"").trim()||{}}function Gi(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 bc(e){const t=String(e.status||"unknown").trim()||"unknown";return s.jsx("span",{className:`run_status_pill ${xc(t)}`,children:t})}function BT(e){var l;const t=String((e==null?void 0:e.status)||"").trim().toLowerCase();if($o(t))return"";const n=e!=null&&e.waiting&&typeof e.waiting=="object"?e.waiting:null,r=String((n==null?void 0:n.reason)||(e==null?void 0:e.waiting_reason)||"").trim().toLowerCase(),o=Array.isArray((l=n==null?void 0:n.details)==null?void 0:l.tool_calls)?n.details.tool_calls:[];return o.length?_y(n,o):r==="user"?"Waiting for your answer":r==="event"?"Waiting for a response event":r==="subworkflow"?"Waiting for subworkflow":r==="until"?"Scheduled wait":r?`Waiting: ${r}`:t==="waiting"?"Waiting, reason unknown":""}function Lf(e){const t=e==null?void 0:e.error;return t?typeof t=="string"?At(t,{max_chars:220,max_lines:2}):At(dr(t,400),{max_chars:220,max_lines:2}):""}function UT(e){const t=BT(e);if(t)return t;const n=Lf(e);if(n)return n;const r=String((e==null?void 0:e.current_node)||"").trim();if(r)return`Current node: ${r}`;const o=String((e==null?void 0:e.status)||"").trim().toLowerCase();return o==="running"?"Running":$o(o)?"Terminal":"No current activity reported"}function z0(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 mv(e){const t=z0(e),n=e!=null&&e.metadata&&typeof e.metadata=="object"?e.metadata:e!=null&&e.meta&&typeof e.meta=="object"?e.meta:{},r=e!=null&&e.tags&&typeof e.tags=="object"?e.tags:{},o=yn(e==null?void 0:e.modality,t==null?void 0:t.modality,n==null?void 0:n.modality,r.modality).toLowerCase();if(o)return o;const l=yn(e==null?void 0:e.content_type,e==null?void 0:e.mime_type,e==null?void 0:e.mime,t==null?void 0:t.content_type,t==null?void 0:t.mime_type,t==null?void 0:t.mime,n==null?void 0:n.content_type,r.content_type).toLowerCase();return l.startsWith("image/")?"image":l.startsWith("audio/")?"audio":l.startsWith("video/")?"video":l.includes("pdf")?"document":l.startsWith("text/")||l.includes("json")||l.includes("markdown")||l.includes("csv")?"text":"artifact"}function WT(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 qT(e,t){if(!e||typeof e!="object")return null;const n=WT(e),r=z0(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:{},c=yn(n.artifact_id,e.artifact_id,e.$artifact,e.id,r.artifact_id,r.$artifact,r.id,o.artifact_id,o.$artifact);if(!c)return null;const u={...r.tags&&typeof r.tags=="object"?r.tags:{},...o.tags&&typeof o.tags=="object"?o.tags:{},...n.tags&&typeof n.tags=="object"?n.tags:{},...e.tags&&typeof e.tags=="object"?e.tags:{}},f={};for(const[A,W]of Object.entries(u)){const z=String(A||"").trim();z&&(f[z]=String(W??""))}const h=yn(n.filename,e.filename,r.filename,o.filename,f.filename,f.name,e.name,r.name),m=yn(n.source_path,e.source_path,r.source_path,o.source_path,e.path,r.path,f.path,f.source_path,f.file_path),g=yn(n.content_type,e.content_type,e.mime_type,e.mime,r.content_type,r.mime_type,r.mime,o.content_type,f.content_type),y=yn(n.render_kind,l.render_kind,e.render_kind,f.render_kind),w=yn(n.semantic_kind,l.semantic_kind,e.semantic_kind,f.semantic_kind,f.artifact_type),k=n.access&&typeof n.access=="object"?n.access:e.access&&typeof e.access=="object"?e.access:{},b=n.producer&&typeof n.producer=="object"?n.producer:e.producer&&typeof e.producer=="object"?e.producer:l.producer&&typeof l.producer=="object"?l.producer:{},S=n.provenance&&typeof n.provenance=="object"?n.provenance:e.provenance&&typeof e.provenance=="object"?e.provenance:l.provenance&&typeof l.provenance=="object"?l.provenance:{},N=n.generation&&typeof n.generation=="object"?n.generation:e.generation&&typeof e.generation=="object"?e.generation:l.generation&&typeof l.generation=="object"?l.generation:{},R=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:c,run_id:yn(n.run_id,e.run_id,r.run_id,o.run_id,f.run_id,S.run_id),content_type:g,modality:yn(n.modality,e.modality,l.modality,f.modality)||mv({...e,ref:r,metadata:o,tags:f}),semantic_kind:w||mv({...e,ref:r,metadata:o,tags:f}),render_kind:y||hy({content_type:g,filename:h,source_path:m,modality:yn(n.modality,e.modality,f.modality),tags:f}),task:yn(n.task,l.task,e.task,f.task,f.provider_task),classification_source:yn(n.classification_source,l.classification_source,e.classification_source),session_id:yn(n.session_id,l.session_id,e.session_id,f.session_id),workflow_id:yn(n.workflow_id,l.workflow_id,e.workflow_id,f.workflow_id,f.workflow),node_id:yn(n.node_id,l.node_id,e.node_id,f.node_id,f.node),step_id:yn(n.step_id,l.step_id,e.step_id,f.step_id),effect_id:yn(n.effect_id,l.effect_id,e.effect_id,f.effect_id,f.effect_idempotency_key),turn_id:yn(n.turn_id,l.turn_id,e.turn_id,f.turn_id,f.turn),ledger_cursor:yn(n.ledger_cursor,l.ledger_cursor,e.ledger_cursor,f.ledger_cursor,f.step_cursor),parent_run_id:yn(n.parent_run_id,l.parent_run_id,e.parent_run_id,f.parent_run_id),actor_id:yn(n.actor_id,l.actor_id,e.actor_id,f.actor_id),title:yn(n.title,e.title,f.title,f.label,f.name),created_at:yn(n.created_at,e.created_at,r.created_at,o.created_at,f.created_at),size_bytes:b$(n.size_bytes,e.size_bytes,r.size_bytes,o.size_bytes,f.size_bytes),filename:h,source_path:m,sha256:yn(n.sha256,e.sha256,r.sha256,o.sha256,f.sha256),tags:f,producer:b,provenance:S,generation:N,media:R,source_refs:Array.isArray(n.source_refs)?n.source_refs:Array.isArray(e.source_refs)?e.source_refs:[],access:k,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(yn(n.classification_source,l.classification_source,e.classification_source))),descriptor:l,source:t,raw:e}}function Xm(e){return e.filename||e.title||(e.source_path?e.source_path.split("/").filter(Boolean).slice(-1)[0]:"")||sn(e.artifact_id,16)}function HT(e,t){if(t==="type")return Pu(e);if(t==="run")return e.run_id||"(no run)";if(t==="turn")return bg(e);if(t==="node")return Ou(e)||"(node unknown)";if(t==="workflow")return py(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 If(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 py(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 Ou(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 bg(e){const t=(e==null?void 0:e.tags)||{},n=String((e==null?void 0:e.turn_id)||t.turn_id||t.turn||t.cycle||(e==null?void 0:e.ledger_cursor)||t.ledger_cursor||t.step_cursor||"").trim();if(n)return`turn ${n}`;const r=Ou(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"}),c=e!=null&&e.run_id?sn(String(e.run_id),10):"unknown run";return r?`${c} · ${r} · ${l}`:`${c} · ${l}`}function _v(e){if(!e)return"provenance unavailable";const t=[],n=py(e),r=Ou(e),o=If(e),l=B0(e);return n&&t.push(n),r&&t.push(r),o&&t.push(o),l&&t.push(l),t.length?t.join(" · "):"provenance unavailable"}function uc(e){if(typeof e!="number"||!Number.isFinite(e)||e<0)return"—";const t=["B","KB","MB","GB","TB"];let n=e,r=0;for(;n>=1024&&r<t.length-1;)n/=1024,r+=1;const o=r===0?0:n>=10?1:2;return`${n.toFixed(o)} ${t[r]}`}function Pu(e){const t=String((e==null?void 0:e.semantic_kind)||(e==null?void 0:e.modality)||"").trim().toLowerCase(),n=String((e==null?void 0:e.render_kind)||"").trim().toLowerCase(),r=t||n||"artifact";return{voice:"Voice",music:"Music",sound:"Sound",recording:"Recording",audio:"Unclassified audio",image:"Image",video:"Video",markdown:"Markdown",html:"HTML",json:"JSON",document:"Document",code:"Code",text:"Text",binary:"Other",artifact:"Other"}[r]||r.replace(/[_-]+/g," ").replace(/\b\w/g,l=>l.toUpperCase())}function VT(e){return e==="html"?"HTML":e==="json"?"JSON":e==="audio"?"Unclassified audio":e==="code"?"Code":e.slice(0,1).toUpperCase()+e.slice(1)}function GT(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 KT(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 pv(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 YT(e){const t=Bu(e.created_at),n=_c(e.created_at);return t==="—"?"Created —":`${t}${n&&n!=="—"?` (${n})`:""}`}function gv(e){var o;const t=e.tags||{},n=String(((o=e.access)==null?void 0:o.last_accessed_at)||t.last_accessed_at||t.accessed_at||t.updated_at||e.created_at||"").trim(),r=Bu(n);return r==="—"?"—":r}function yv(e){const t=e.tags||{},n=String(e.title||t.title||t.name||t.label||e.filename||"").trim();if(n)return n;const r=String(e.source_path||t.path||"").trim();if(r)return r.split("/").filter(Boolean).slice(-1)[0]||r;const o=If(e),l=Pu(e);return o?`${l} ${o}`:`${l} artifact`}function If(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 B0(e){var r,o,l,c,u,f,h,m;if(!e)return"";const t=yn((r=e.producer)==null?void 0:r.provider,(o=e.producer)==null?void 0:o.provider_id,(l=e.provenance)==null?void 0:l.provider,(c=e.generation)==null?void 0:c.provider),n=yn((u=e.producer)==null?void 0:u.model,(f=e.producer)==null?void 0:f.model_id,(h=e.provenance)==null?void 0:h.model,(m=e.generation)==null?void 0:m.model);return t&&n?`${t} / ${n}`:t||n}function JT(e){var t,n,r,o;return e?yn((t=e.generation)==null?void 0:t.prompt,(n=e.generation)==null?void 0:n.input,(r=e.generation)==null?void 0:r.text,(o=e.provenance)==null?void 0:o.prompt):""}function wv(e){if(!e)return"";const t=e.media||{},n=Number(t.duration_s??t.duration_seconds??t.duration),r=Number(t.width??t.image_width??t.video_width),o=Number(t.height??t.image_height??t.video_height),l=Number(t.sample_rate??t.sample_rate_hz),c=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(c)&&c>0&&f.push(`${c} ch`),f.join(" · ")}if(Number.isFinite(r)&&Number.isFinite(o)&&r>0&&o>0)return`${Math.round(r)} x ${Math.round(o)}`;const u=Number(t.page_count??t.pages);return Number.isFinite(u)&&u>0?`${Math.round(u)} pages`:""}function vv(e){return e.source_path||e.filename||""}function Zm(e,t,n){const r=e.run_id&&t[e.run_id]||null;if(!r)return e;const o=Gi(r,n),l={...e.tags||{}};return o&&!l.workflow&&(l.workflow=o),o&&!l.workflow_id&&(l.workflow_id=o),{...e,workflow_id:e.workflow_id||o,tags:l}}function kg(e,t,n,r=""){const o=Zm(e,t,n),l=hy(o,r);return{json:"JSON",html:"HTML",markdown:"Markdown",code:"Code",voice:"Voice",music:"Music",sound:"Sound",audio:"Unclassified audio",image:"Image",video:"Video",document:"Document",text:"Text",other:"Other"}[l]||Pu(o)}function fa(e){var r;const t=e,n=(r=t==null?void 0:t.result)==null?void 0:r.wait;return!n||typeof n!="object"?null:n}function wm(e){var l,c,u;const t=e,n=t==null?void 0:t.effect;if(!n||typeof n!="object"||String(n.type||"")!=="emit_event")return null;const r=String(((l=n==null?void 0:n.payload)==null?void 0:l.name)||((c=n==null?void 0:n.payload)==null?void 0:c.event_name)||"").trim();if(!r)return null;const o=(u=n==null?void 0:n.payload)==null?void 0:u.payload;return{name:r,payload:o}}function eh(e){const t=e,n=t==null?void 0:t.details;if(!n||typeof n!="object")return[];if(Array.isArray(n))return n.filter(o=>o&&typeof o=="object"&&typeof o.name=="string");const r=n==null?void 0:n.tool_calls;return Array.isArray(r)?r:[]}function XT(e){var o,l;const t=String((e==null?void 0:e.status)||"").trim(),n=String(((o=e==null?void 0:e.effect)==null?void 0:o.type)||"").trim(),r=(l=e==null?void 0:e.effect)!=null&&l.payload&&typeof e.effect.payload=="object"?String(e.effect.payload.name||"").trim():"";return n==="emit_event"&&r?r:n||t||"record"}function U0(e){if(!e||typeof e!="object")return"Ledger record";const t=String(e.node_id||"").trim(),n=String(e.status||"").trim(),r=XT(e),o=fa(e);if(o){const l=String(o.reason||"").trim();if(String(o.prompt||"").trim())return`${t||"node"} is waiting for a response`;if(l)return`${t||"node"} is waiting (${l})`}return e.error?`${t||"node"} failed`:n==="completed"?`${t||"node"} completed ${r}`:n==="running"?`${t||"node"} started ${r}`:n==="waiting"?`${t||"node"} is waiting`:[t,n,r].filter(Boolean).join(" · ")||"Ledger record"}function bu(e){if(typeof e=="string")return{text:e,duration:-1};if(e&&typeof e=="object"){const t=typeof e.text=="string"?String(e.text):typeof e.value=="string"?String(e.value):typeof e.message=="string"?String(e.message):dr(e,320),n=typeof e.duration=="number"?Number(e.duration):-1;return{text:t,duration:n}}return{text:dr(e,320),duration:-1}}function W0(e){var c,u,f,h,m,g,y,w,k;if(!e||typeof e!="object")return"";const t=String(((c=e==null?void 0:e.effect)==null?void 0:c.type)||"").trim(),n=e==null?void 0:e.result,r=b=>typeof b=="string"?b.trim():b==null?"":typeof b=="number"||typeof b=="boolean"?String(b):"",o=b=>{if(!b||typeof b!="object")return"";const S=b,N=[S.response,S.answer,S.message,S.text,S.content];for(const R of N){const T=r(R);if(T)return T}return""};if(t==="answer_user"){const b=r(n==null?void 0:n.message)||r((u=n==null?void 0:n.output)==null?void 0:u.message)||r((f=n==null?void 0:n.output)==null?void 0:f.response)||r((m=(h=e==null?void 0:e.effect)==null?void 0:h.payload)==null?void 0:m.message)||r((y=(g=e==null?void 0:e.effect)==null?void 0:g.payload)==null?void 0:y.text)||r((k=(w=e==null?void 0:e.effect)==null?void 0:w.payload)==null?void 0:k.content);if(b)return b}if(t==="llm_call"){const b=o(n)||r(n==null?void 0:n.output)||o(n==null?void 0:n.output)||r(n==null?void 0:n.response);if(b)return b}return r(n==null?void 0:n.output)||o(n==null?void 0:n.output)||o(n)||r(n==null?void 0:n.response)}function Om(e){var o;const t=String((e==null?void 0:e.node_id)||""),n=String((e==null?void 0:e.status)||""),r=String(((o=e==null?void 0:e.effect)==null?void 0:o.type)||"");return`${t||"(node?)"} • ${n||"(status?)"} • ${r||"(effect?)"}`}function ZT(e){return!!(e&&String(e.status||"")==="waiting")}function QT(e){var n,r;const t=[];for(const o of e||[]){const l=o.record;if(String(((n=l==null?void 0:l.effect)==null?void 0:n.type)||"").trim()!=="llm_call")continue;const u=(r=l==null?void 0:l.effect)!=null&&r.payload&&typeof l.effect.payload=="object"?l.effect.payload:{},f=l!=null&&l.result&&typeof l.result=="object"?l.result:{},h=(f==null?void 0:f.usage)||(f==null?void 0:f.token_usage)||{},m=typeof u.prompt=="string"?u.prompt:Array.isArray(u.messages)?dr(u.messages,1800):"",g=typeof f.content=="string"?f.content:typeof f.response=="string"?f.response:typeof l.result=="string"?String(l.result):"",y=qn(l.started_at),w=qn(l.ended_at),k=Number(h.prompt_tokens??h.input_tokens??0)||0,b=Number(h.completion_tokens??h.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(u.provider||f.provider||f.runtime_provider||"").trim(),model:String(u.model||f.model||f.runtime_model||"").trim(),prompt_preview:At(m,{max_chars:1200,max_lines:10}),response_preview:At(g,{max_chars:1200,max_lines:10}),missing_response:!String(g||"").trim(),tokens:{prompt:k,completion:b,total:Number(h.total_tokens??k+b)||0},duration_ms:y!==null&&w!==null?Math.max(0,w-y):typeof f.gen_time=="number"?Number(f.gen_time)*1e3:null,status:String(l.status||"").trim(),error:l.error?dr(l.error,500):"",raw:l})}return t.sort((o,l)=>(qn(l.ts)??0)-(qn(o.ts)??0))}function xv(e){const t=e.size||18,n=Cf(e.artifact),r=hy(e.artifact,""),o=`artifact_glyph ${r==="code"?"code":n}`,l={width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:1.8,strokeLinecap:"round",strokeLinejoin:"round"};return n==="image"?s.jsx("span",{className:o,children:s.jsxs("svg",{...l,children:[s.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),s.jsx("path",{d:"M7 15l3-3 3 3 2-2 4 4"}),s.jsx("circle",{cx:"8",cy:"9",r:"1.4"})]})}):n==="audio"?s.jsx("span",{className:o,children:s.jsxs("svg",{...l,children:[s.jsx("path",{d:"M4 12h2"}),s.jsx("path",{d:"M8 8v8"}),s.jsx("path",{d:"M12 5v14"}),s.jsx("path",{d:"M16 8v8"}),s.jsx("path",{d:"M20 12h-2"})]})}):n==="video"?s.jsx("span",{className:o,children:s.jsxs("svg",{...l,children:[s.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),s.jsx("path",{d:"M9 9l6 3-6 3V9z",fill:"currentColor",stroke:"none"})]})}):r==="code"?s.jsx("span",{className:o,children:s.jsxs("svg",{...l,children:[s.jsx("path",{d:"M8 8l-4 4 4 4"}),s.jsx("path",{d:"M16 8l4 4-4 4"}),s.jsx("path",{d:"M14 4l-4 16"})]})}):n==="text"?s.jsx("span",{className:o,children:s.jsxs("svg",{...l,children:[s.jsx("path",{d:"M7 3h7l5 5v13H7z"}),s.jsx("path",{d:"M14 3v6h6"}),s.jsx("path",{d:"M10 13h7"}),s.jsx("path",{d:"M10 17h5"})]})}):s.jsx("span",{className:o,children:s.jsxs("svg",{...l,children:[s.jsx("path",{d:"M7 3h7l5 5v13H7z"}),s.jsx("path",{d:"M14 3v6h6"}),s.jsx("path",{d:"M9 14h8"})]})})}const eM=2,tM=Number.MAX_SAFE_INTEGER;function nM(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 sM(e){const t=String(e||"");if(typeof DOMParser>"u")return[{kind:"text",text:xp(t)||t}];try{const n=new DOMParser().parseFromString(t,"text/html"),r=[];n.doctype&&r.push({kind:"doctype",name:n.doctype.name||"html"});const o=l=>{if(l.nodeType===Node.TEXT_NODE){const c=String(l.textContent||"").trim();return c?{kind:"text",text:c}:null}if(l.nodeType===Node.COMMENT_NODE)return{kind:"comment",text:String(l.textContent||"")};if(l.nodeType===Node.ELEMENT_NODE){const c=l,u=Array.from(c.attributes||[]).map(h=>({name:h.name,value:h.value})),f=Array.from(c.childNodes||[]).map(o).filter(Boolean);return{kind:"element",tag:c.tagName.toLowerCase(),attrs:u,children:f}}return null};if(n.documentElement){const l=o(n.documentElement);l&&r.push(l)}return r.length?r:[{kind:"text",text:xp(t)||t}]}catch{return[{kind:"text",text:xp(t)||t}]}}function bp(e){return e.closing?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"runtime_html_punct",children:"</"}),s.jsx("span",{className:"runtime_html_tag",children:e.tag}),s.jsx("span",{className:"runtime_html_punct",children:">"})]}):s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"runtime_html_punct",children:"<"}),s.jsx("span",{className:"runtime_html_tag",children:e.tag}),e.attrs.map(t=>s.jsxs(xe.Fragment,{children:[" ",s.jsx("span",{className:"runtime_html_attr",children:t.name}),s.jsx("span",{className:"runtime_html_punct",children:"="}),s.jsxs("span",{className:"runtime_html_value",children:['"',t.value,'"']})]},`${e.tag}:${t.name}:${t.value}`)),s.jsx("span",{className:"runtime_html_punct",children:e.selfClosing?" />":">"})]})}function q0(e){const t=e.node,n=e.depth*14,r=e.depth<e.collapseAfterDepth,[o,l]=_.useState(r);if(_.useEffect(()=>{l(r)},[r,e.expansionVersion]),t.kind==="doctype")return s.jsxs("div",{className:"html-tree__line",style:{paddingLeft:n},children:[s.jsx("span",{className:"runtime_html_punct",children:"<!DOCTYPE "}),s.jsx("span",{className:"runtime_html_tag",children:t.name}),s.jsx("span",{className:"runtime_html_punct",children:">"})]});if(t.kind==="comment")return s.jsx("div",{className:"html-tree__line",style:{paddingLeft:n},children:s.jsx("span",{className:"runtime_html_comment",children:`<!-- ${t.text.trim()} -->`})});if(t.kind==="text")return s.jsx("div",{className:"html-tree__line html-tree__text",style:{paddingLeft:n},children:t.text});if(!t.children.length)return s.jsx("div",{className:"html-tree__line",style:{paddingLeft:n},children:s.jsx(bp,{tag:t.tag,attrs:t.attrs,selfClosing:!0})});const c=t.children.find(u=>u.kind==="text");return s.jsxs("details",{className:"html-tree__details",open:o,onToggle:u=>l(u.currentTarget.open),children:[s.jsxs("summary",{className:"html-tree__summary",style:{paddingLeft:n},children:[s.jsx("span",{className:"html-tree__caret","aria-hidden":"true",children:o?"▾":"▸"}),s.jsx(bp,{tag:t.tag,attrs:t.attrs}),!o&&c?s.jsxs("span",{className:"html-tree__summary_text",children:[" ",nM(c.text)]}):null]}),o?s.jsxs("div",{className:"html-tree__children",children:[t.children.map((u,f)=>s.jsx(q0,{node:u,depth:e.depth+1,collapseAfterDepth:e.collapseAfterDepth,expansionMode:e.expansionMode,expansionVersion:e.expansionVersion},`${e.depth}:${t.kind}:${t.tag}:${f}`)),s.jsx("div",{className:"html-tree__line",style:{paddingLeft:n},children:s.jsx(bp,{tag:t.tag,attrs:[],closing:!0})})]}):null]})}function rM(e){const t=_.useMemo(()=>sM(e.text),[e.text]),[n,r]=_.useState({mode:"folded",version:0}),o=n.mode==="unfolded"?tM:eM;_.useEffect(()=>{r(c=>({mode:"folded",version:c.version+1}))},[e.text]);const l=()=>{r(c=>({mode:c.mode==="unfolded"?"folded":"unfolded",version:c.version+1}))};return s.jsxs("div",{className:`${e.className} structured html_source_preview`,children:[s.jsx("div",{className:"html-tree__toolbar",children:s.jsx("button",{type:"button",className:"btn html-tree__toggle",onClick:l,"aria-expanded":n.mode==="unfolded",children:n.mode==="unfolded"?"Fold all":"Unfold all"})}),s.jsx("div",{className:"html-tree__tree",role:"tree","aria-label":"HTML source tree",children:t.map((c,u)=>s.jsx(q0,{node:c,depth:0,collapseAfterDepth:o,expansionMode:n.mode,expansionVersion:n.version},`root:${u}`))})]})}function iM(e){var r;const t=AT(e.text);if(!t)return s.jsx("div",{className:`${e.className} structured markdown_preview`,children:s.jsx(Si,{text:e.text})});const n=((r=t.metadata.find(o=>o.label.toLowerCase()==="title"))==null?void 0:r.value)||"";return s.jsxs("div",{className:`${e.className} structured markdown_preview artifact_markdown_report`,children:[n?s.jsx("h1",{className:"artifact_markdown_title",children:n}):null,t.metadata.length?s.jsx("dl",{className:"artifact_markdown_meta",children:t.metadata.map(o=>{const l=/^https?:\/\//i.test(o.value);return s.jsxs("div",{children:[s.jsx("dt",{children:o.label}),s.jsx("dd",{children:l?s.jsx("a",{href:o.value,target:"_blank",rel:"noreferrer",children:o.value}):o.value})]},`${o.label}:${o.value}`)})}):null,s.jsx(Si,{text:t.body||e.text})]})}function H0(e){const t=String(e.text||""),n=Jm(e.artifact,t);if(n==="json"){const r=y_(t);if(r!==null)return s.jsx("div",{className:`${e.className} structured`,children:s.jsx(Is,{value:r,collapseAfterDepth:4,showCopy:!1})})}return n==="markdown"?s.jsx(iM,{text:t,className:e.className}):n==="html"?s.jsx(rM,{text:t,className:e.className}):s.jsx("pre",{className:`mono ${e.className}`,children:t})}function oM(e){const t=e.preview,n=e.artifact;return n?t.loading?s.jsx("div",{className:"runtime_inline_preview empty",children:"Loading preview…"}):t.error?s.jsx("div",{className:"runtime_inline_preview empty danger",children:t.error}):t.kind==="image"&&t.url?s.jsx("img",{className:"runtime_inline_preview media",src:t.url,alt:Xm(n)}):t.kind==="audio"&&t.url?s.jsx(p_,{className:"runtime_inline_preview audio",src:t.url,name:Xm(n)}):t.kind==="video"&&t.url?s.jsx("video",{className:"runtime_inline_preview media",src:t.url,controls:!0}):s.jsx(H0,{artifact:n,text:t.text||"Preview unavailable. Use Preview or Download.",className:"runtime_inline_preview text"}):s.jsx("div",{className:"runtime_inline_preview empty",children:"Select an artifact to preview it here."})}function gy(e){const t=e==null?void 0:e.waiting;return t&&typeof t=="object"?t:null}function V0(e){const t=gy(e);return String((t==null?void 0:t.reason)||(e==null?void 0:e.waiting_reason)||"").trim().toLowerCase()}function bv(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 aM(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 Ku(e){const t=String((e==null?void 0:e.status)||"").trim().toLowerCase();if($o(t)||t!=="waiting")return"none";const n=gy(e),r=V0(e);return eh(n).length?"tool_approval":r==="until"||String((e==null?void 0:e.role)||"").trim()==="controller"?"scheduled":r==="subworkflow"?"subworkflow":r==="event"?bv(n)?"user_response":"external_event":r==="user"||bv(n)?"user_response":"unknown_wait"}function G0(e){const t=gy(e),n=eh(t),r=Ku(e);return r==="tool_approval"?`Tool approval: ${aM(n)||"tool call"}`:r==="user_response"?Array.isArray(t==null?void 0:t.choices)&&t.choices.length>0?"Choice required":"User response needed":r==="scheduled"?String((e==null?void 0:e.role)||"").trim()==="controller"?"Automation waiting for its next run":"Scheduled wait":r==="subworkflow"?"Waiting for subworkflow":r==="external_event"?"Waiting for external event":r==="unknown_wait"?"Waiting, context unclear":""}function lM(e){const t=Ku(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.":$o(n)?"Open the ledger and artifacts for the final outcome.":"Open the run to inspect current activity."}function kv(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 cM(e,t={}){const n=t.now_ms??Date.now(),r=t.workflow_label??"",o=String(e.status||"unknown").trim().toLowerCase()||"unknown",l=Ku(e),c=$o(o),u=uy(e,n),f=qn(e.updated_at||e.created_at)??0,h=o==="running"&&u>=14400*1e3,m=G0(e)||kv(e)||(e.current_node?`Current node: ${e.current_node}`:o==="running"?"Running":c?"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":c&&(g="finished");const y=l==="tool_approval"?0:l==="user_response"?1:l==="unknown_wait"?2:o==="failed"?3:h?4:o==="running"?5:l!=="none"?6:c?8:7,w=l==="tool_approval"||l==="user_response",k=l==="tool_approval"?"Open approval":l==="user_response"?"Open wait":"Open Observe",b=[e.run_id,e.workflow_id,r,e.session_id,e.parent_run_id,e.status,e.current_node,V0(e),m,kv(e)].join(" ").toLowerCase();return{run:e,run_id:String(e.run_id||"").trim(),status:o,wait_kind:l,queue:g,attention_rank:y,reason:m,expected_action:lM(e),action_label:k,search_text:b,is_terminal:c,needs_user_action:w,is_stale:h,duration_ms:u,updated_ms:f}}function uM(e,t={}){const n=t.now_ms??Date.now(),r=t.workflow_label_by_id??{};return e.map(o=>cM(o,{now_ms:n,workflow_label:r[String(o.workflow_id||"")]||String(o.workflow_id||"")}))}function dM(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 fM(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 hM(e,t){const n=[...e];return n.sort((r,o)=>{if(t==="recent")return o.updated_ms-r.updated_ms;if(t==="oldest")return r.updated_ms-o.updated_ms;if(t==="duration")return o.duration_ms-r.duration_ms;if(t==="tokens")return(Number(o.run.tokens_total||0)||0)-(Number(r.run.tokens_total||0)||0);if(t==="workflow")return String(r.run.workflow_id||"").localeCompare(String(o.run.workflow_id||""));const l=r.attention_rank-o.attention_rank;return l!==0?l:o.updated_ms-r.updated_ms}),n}function mM(e){const[t,n]=_.useState("attention"),[r,o]=Mf("system_queues"),[l,c]=Mf("system_runs"),[u,f]=_.useState(""),[h,m]=_.useState("attention"),[g,y]=_.useState(""),w=_.useMemo(()=>{const M={};for(const ee of e.artifacts){const F=String(ee.run_id||"").trim();F&&(M[F]=(M[F]||0)+1)}return M},[e.artifacts]),k=_.useMemo(()=>uM(e.runs,{workflow_label_by_id:e.workflow_label_by_id}),[e.runs,e.workflow_label_by_id]),b=_.useMemo(()=>dM(k),[k]),S=_.useMemo(()=>{const M=fM(k,{queue:t,query:u});return hM(M,h)},[k,t,u,h]),N=S.find(M=>String(M.run_id||"")===g)||S.find(M=>String(M.run_id||"")===e.selected_run_id)||S[0]||null,R=(N==null?void 0:N.run)||null,T=String((R==null?void 0:R.run_id)||"").trim(),A=String((R==null?void 0:R.session_id)||"").trim(),W=_.useMemo(()=>A?new Set(e.runs.filter(M=>String(M.session_id||"").trim()===A).map(M=>String(M.run_id||"").trim()).filter(Boolean)):new Set,[e.runs,A]),z=A?W.size:0,J=_.useMemo(()=>A?e.artifacts.filter(M=>String(M.session_id||"").trim()===A||W.has(String(M.run_id||"").trim())).length:0,[e.artifacts,A,W]),K=R!=null&&R.waiting&&typeof R.waiting=="object"?R.waiting:null,re=K?eh(K):[],te=(N==null?void 0:N.reason)||(K?_y(K,re):""),Q=(N==null?void 0:N.expected_action)||(K?D0(K,re):""),D=K?FT(K,null):"",$=T&&w[T]||0,E=$o(R==null?void 0:R.status),L=[{key:"attention",label:"Needs attention",count:b.attention},{key:"user_wait",label:"Needs my response",count:b.user_wait},{key:"tool_approval",label:"Tool approvals",count:b.tool_approval},{key:"running",label:"Running",count:b.running},{key:"failed",label:"Failed",count:b.failed},{key:"scheduled",label:"Scheduled",count:b.scheduled},{key:"subflows",label:"Subflows / external events",count:b.subflows},{key:"finished",label:"Finished",count:b.finished},{key:"all",label:"All loaded",count:b.all}];return s.jsxs("div",{className:`runtime_ops_layout${r?"":" queues_collapsed"}${l?"":" runs_collapsed"}`,children:[s.jsxs("aside",{className:`pane runtime_ops_filters${r?"":" list_collapsed"}`,children:[s.jsxs("div",{className:"pane_header runtime_ops_filter_header",children:[s.jsx(Rf,{open:r,on_toggle:o,controls:"runtime_ops_queues",title:"Queues"}),s.jsx("div",{className:"pane_spacer"}),s.jsxs("button",{className:"btn btn_icon",onClick:e.gateway_connected?e.on_refresh_runs:e.on_reconnect,children:[s.jsx(Be,{name:"refresh",size:14}),e.gateway_connected?"Refresh":"Reconnect"]})]}),s.jsxs("div",{className:"pane_body scroll runtime_ops_queue_list",id:"runtime_ops_queues",hidden:!r,children:[L.map(M=>s.jsxs("button",{className:`runtime_ops_filter ${t===M.key?"selected":""}`,"aria-pressed":t===M.key,onClick:()=>n(M.key),children:[s.jsx("span",{children:M.label}),s.jsx("strong",{children:M.count.toLocaleString()})]},M.key)),s.jsx("div",{className:"runtime_ops_hint",children:"Counts are for the loaded runtime page. Refine search or refresh when supervising large runtimes."})]})]}),s.jsxs("section",{className:`pane runtime_ops_table_panel${l?"":" list_collapsed"}`,children:[s.jsxs("div",{className:"pane_header runtime_ops_list_header",children:[s.jsx(Rf,{open:l,on_toggle:c,controls:"runtime_ops_runs",title:"Runs",count:S.length.toLocaleString()}),s.jsx("div",{className:"pane_spacer"}),s.jsx("input",{value:u,onChange:M=>f(M.target.value),placeholder:"Search workflow, run, node, status, error"}),s.jsxs("select",{className:"seg_select",value:h,onChange:M=>m(M.target.value),children:[s.jsx("option",{value:"attention",children:"Attention order"}),s.jsx("option",{value:"recent",children:"Latest event"}),s.jsx("option",{value:"oldest",children:"Oldest event"}),s.jsx("option",{value:"duration",children:"Longest duration"}),s.jsx("option",{value:"tokens",children:"Most tokens"}),s.jsx("option",{value:"workflow",children:"Workflow"})]})]}),s.jsxs("div",{className:"pane_body scroll runtime_ops_rows",id:"runtime_ops_runs",hidden:!l,children:[S.length?null:s.jsx("div",{className:"runtime_ops_empty",children:e.gateway_connected?"No runs match this queue.":"Gateway offline. Runtime activity cannot be loaded until the connection is restored."}),S.map(M=>{const ee=M.run,F=String(ee.run_id||"").trim(),U=w[F]||0;return s.jsxs("div",{className:`raised runtime_ops_row ${F===T?"selected":""}`,"aria-current":F===T?"true":void 0,tabIndex:0,onClick:()=>{y(F),e.on_select_run(F)},onKeyDown:V=>{(V.key==="Enter"||V.key===" ")&&(V.preventDefault(),y(F),e.on_select_run(F))},children:[s.jsxs("div",{className:"runtime_ops_row_top",children:[s.jsx("strong",{className:"runtime_ops_row_name",children:Gi(ee,e.workflow_label_by_id)}),M.is_stale?s.jsx("span",{className:"chip warn",children:"stale"}):null,s.jsx(bc,{status:ee.status})]}),s.jsxs("div",{className:"runtime_ops_row_sub",children:[s.jsx("span",{className:"mono",children:sn(F,18)}),s.jsx("span",{children:_c(ee.updated_at||ee.created_at)}),s.jsx("span",{children:vc(ee)}),s.jsx("span",{className:"runtime_ops_row_reason",title:M.reason,children:M.reason})]}),s.jsxs("div",{className:"runtime_ops_row_foot",children:[s.jsxs("span",{className:"runtime_ops_row_facts",children:[s.jsxs("span",{children:[Number(ee.llm_calls||0).toLocaleString()," llm"]}),s.jsxs("span",{children:[Number(ee.tool_calls||0).toLocaleString()," tools"]}),s.jsxs("span",{children:[Number(ee.tokens_total||0).toLocaleString()," tok"]}),s.jsxs("span",{children:[U.toLocaleString()," artifacts"]})]}),s.jsxs("div",{className:"runtime_ops_actions",children:[M.needs_user_action?s.jsx("button",{className:"btn primary",onClick:V=>{V.stopPropagation(),e.on_open_run(F)},children:M.action_label}):s.jsx("button",{className:"btn",onClick:V=>{V.stopPropagation(),e.on_open_run(F)},children:"Open"}),s.jsx("button",{className:"btn",onClick:V=>{V.stopPropagation(),e.on_open_ledger(F)},children:"Ledger"}),s.jsx("button",{className:"btn",onClick:V=>{V.stopPropagation(),e.on_select_run(F),e.on_open_logs()},children:"Logs"}),s.jsx("button",{className:"btn",onClick:V=>{V.stopPropagation(),e.on_filter_artifacts(F)},children:"Artifacts"})]})]})]},F)})]})]}),s.jsxs("aside",{className:"pane runtime_ops_inspector",children:[s.jsxs("div",{className:"pane_header",children:[s.jsx("span",{className:"pane_title",children:"Run inspector"}),R?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"pane_spacer"}),s.jsx(bc,{status:R.status})]}):null]}),s.jsx("div",{className:"pane_body scroll runtime_ops_inspector_body",children:R?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"runtime_ops_inspector_head",children:[s.jsx("h3",{children:Gi(R,e.workflow_label_by_id)}),s.jsx("span",{className:"mono",children:sn(T,28)})]}),s.jsxs("div",{className:"runtime_ops_decision",children:[s.jsx("strong",{children:(N==null?void 0:N.reason)||UT(R)}),s.jsx("span",{children:(N==null?void 0:N.expected_action)||(String(R.status||"").toLowerCase()==="waiting"?"This run is paused until the pending wait is resolved or the run is cancelled.":E?"This run is terminal. Open the ledger for the narrative and final error/output.":"This run is active or recently updated. Use ledger/provider logs to inspect live work.")})]}),s.jsxs("div",{className:"artifact_detail_grid",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Started"}),s.jsx("strong",{children:Bu(Mu(R))})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Elapsed"}),s.jsx("strong",{children:vc(R)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Last event"}),s.jsx("strong",{children:Bu(R.updated_at||R.created_at)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Session"}),s.jsx("strong",{className:"mono",children:R.session_id?sn(String(R.session_id),18):"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Node"}),s.jsx("strong",{className:"mono",children:R.current_node||"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Visible artifacts"}),s.jsx("strong",{children:$.toLocaleString()})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Provider calls"}),s.jsx("strong",{children:Number(R.llm_calls||0).toLocaleString()})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Tokens"}),s.jsx("strong",{children:Number(R.tokens_total||0).toLocaleString()})]})]}),A?s.jsxs("section",{className:"runtime_ops_session_context",children:[s.jsxs("div",{children:[s.jsx("span",{className:"run_hero_eyebrow",children:"Session context"}),s.jsx("strong",{className:"mono",children:sn(A,30)})]}),s.jsxs("div",{className:"runtime_ops_session_facts",children:[s.jsxs("span",{children:[z.toLocaleString()," loaded run",z===1?"":"s"]}),s.jsxs("span",{children:[J.toLocaleString()," visible artifact",J===1?"":"s"]})]}),s.jsxs("div",{className:"runtime_detail_actions compact",children:[s.jsx("button",{className:"btn",onClick:()=>e.on_filter_session_artifacts(A),children:"Open session artifacts"}),s.jsx("button",{className:"btn",onClick:()=>void gl(A),children:"Copy session id"})]})]}):null,K?s.jsxs("div",{className:"runtime_ops_wait_summary",children:[s.jsxs("div",{className:"runtime_ops_wait_header",children:[s.jsx("span",{className:"run_hero_eyebrow",children:"Blocked on"}),s.jsx("strong",{children:te})]}),s.jsx("p",{children:Q}),D?s.jsxs("div",{className:"runtime_ops_wait_request",children:[s.jsx("span",{children:"Request"}),s.jsx(Si,{text:D})]}):s.jsx("div",{className:"runtime_ops_wait_request muted",children:"No explicit prompt is attached to this wait. Open Observe or the ledger for full run context before responding."}),re.length?s.jsx("div",{className:"runtime_ops_wait_tools",children:re.map((M,ee)=>s.jsxs(xe.Fragment,{children:[s.jsx("span",{className:"chip mono warn",children:String((M==null?void 0:M.name)||"tool")}),P0(M).map(F=>s.jsxs("span",{className:"chip muted",title:O0,children:[F,"~"]},`${ee}:${F}`))]},`${String((M==null?void 0:M.name)||"tool")}:${ee}`))}):null,s.jsxs("details",{className:"runtime_raw_details",children:[s.jsx("summary",{className:"muted",children:"Raw wait payload"}),s.jsx(Is,{value:K,collapseAfterDepth:3,showCopy:!0})]})]}):null,Lf(R)?s.jsx("div",{className:"warn_callout",children:Lf(R)}):null,s.jsxs("div",{className:"runtime_detail_actions",children:[s.jsx("button",{className:"btn primary",onClick:()=>e.on_open_run(T),children:"Open Observe"}),s.jsx("button",{className:"btn",onClick:()=>e.on_open_ledger(T),children:"Open ledger"}),s.jsx("button",{className:"btn",onClick:()=>e.on_filter_artifacts(T),children:"Open artifacts"}),s.jsx("button",{className:"btn",onClick:e.on_open_logs,children:"Open logs"}),s.jsx("button",{className:"btn",onClick:()=>void gl(T),children:"Copy run id"})]})]}):s.jsx("div",{className:"empty_state_inline",children:"Select a run to inspect why it is active or blocked."})})]})]})}function _M(e){const t=e.selected_artifact,n=["voice","music","sound","recording","audio","image","video","markdown","html","json","document","code","text","other"],r=[{value:"all",label:"Any time"},{value:"hour",label:"Last hour"},{value:"today",label:"Today"},{value:"week",label:"7 days"},{value:"month",label:"30 days"}],o=_.useMemo(()=>new Set(e.type_filters),[e.type_filters]),l=Math.max(0,Number(e.artifact_total_count||0)),c=!!e.query.trim()||e.type_filters.length>0||e.date_filter!=="all"||e.scope!=="all"||!!e.artifact_run_filter.trim(),u=Math.max(1,Number(e.artifact_page_size||500)),f=Math.max(1,Math.ceil(l/u)),h=Math.min(Math.max(0,Number(e.artifact_page||0)),f-1),m=l?h*u+1:0,g=Math.min(l,h*u+e.artifacts.length),y=_.useMemo(()=>{const $={},E=e.artifact_type_facets&&Object.keys(e.artifact_type_facets).length?e.artifact_type_facets:e.artifact_facets,L=(E==null?void 0:E.semantic_kind)||{},M=(E==null?void 0:E.render_kind)||{};for(const ee of n)$[ee]=Number(L[ee]||M[ee]||0);return $.audio=Number(L.audio||0),$.other=Number(L.other||0)+Number(L.artifact||0)+Number(L.binary||0)+Number(L["(none)"]||0),$},[e.artifact_facets,e.artifact_type_facets]),w=$=>{const E=new Set(o);E.has($)?E.delete($):E.add($),e.on_type_filters_change(Array.from(E.values()))},k=_.useMemo(()=>{const $={waiting:[],running:[],failed:[],cancelled:[],completed:[],other:[]};for(const E of e.runs){const L=String(E.status||"").trim().toLowerCase();L==="waiting"?$.waiting.push(E):L==="running"?$.running.push(E):L==="failed"?$.failed.push(E):L==="cancelled"?$.cancelled.push(E):L==="completed"?$.completed.push(E):$.other.push(E)}return $},[e.runs]),b=t!=null&&t.run_id&&e.run_by_id[t.run_id]||null,S=e.artifact_run_filter?Gi(e.run_by_id[e.artifact_run_filter],e.workflow_label_by_id):"",N=_.useMemo(()=>{var L;const $=new Set,E=((L=e.artifact_facets)==null?void 0:L.run_id)||{};for(const M of Object.keys(E))M&&M!=="(none)"&&$.add(M);for(const M of e.artifacts)M.run_id&&$.add(M.run_id);for(const M of e.active_runs)M.run_id&&$.add(String(M.run_id));return Array.from($).map(M=>e.run_by_id[M]||{run_id:M,workflow_id:null,status:"",created_at:null,updated_at:null}).sort((M,ee)=>{const F=Uu(M.status)?0:1,U=Uu(ee.status)?0:1;if(F!==U)return F-U;const V=qn(M.updated_at||M.created_at)??0;return(qn(ee.updated_at||ee.created_at)??0)-V}).slice(0,160)},[e.artifacts,e.active_runs,e.run_by_id,e.artifact_facets]),R=$=>{e.on_artifact_run_filter_change($),e.on_session_filter_change(""),e.on_scope_change($?"run":"all")},T=$=>e.gateway_connected?Math.max(0,Number($||0)).toLocaleString():"—",A=e.selected_run_id&&e.run_by_id[e.selected_run_id]||null,W=_.useMemo(()=>{const $=e.runtime_log_query.trim().toLowerCase(),E=e.runtime_ledger_log_items||[];return $?E.filter(L=>{var F,U;const M=L.record||{};return[L.cursor,M.run_id,M.node_id,M.status,(F=M.effect)==null?void 0:F.type,M.started_at,M.ended_at,dr(((U=M.effect)==null?void 0:U.payload)??{},900),dr(M.result??{},900)].join(" ").toLowerCase().includes($)}):E},[e.runtime_ledger_log_items,e.runtime_log_query]),z=_.useMemo(()=>{const $=e.runtime_log_query.trim().toLowerCase(),E=QT(e.runtime_ledger_log_items);return $?E.filter(L=>[L.provider,L.model,L.run_id,L.node_id,L.status,L.error,L.prompt_preview,L.response_preview,L.tokens.prompt,L.tokens.completion,L.tokens.total].join(" ").toLowerCase().includes($)):E},[e.runtime_ledger_log_items,e.runtime_log_query]),J=z.reduce(($,E)=>$+(Number(E.tokens.total)||0),0),K=z.filter($=>$.missing_response||$.error).length,re=_.useMemo(()=>{const $=e.runtime_log_query.trim().toLowerCase(),E=String(e.audit_log_text||"").replace(/\r\n/g,`
|
|
126
|
-
`).replace(/\r/g,`
|
|
127
|
-
`).split(`
|
|
128
|
-
`).filter(Boolean);return $?E.filter(L=>L.toLowerCase().includes($)):E},[e.audit_log_text,e.runtime_log_query]),te=e.runtime_log_source==="run_ledger"||e.runtime_log_source==="provider_calls",Q=e.runtime_log_source==="run_ledger"?"Selected Run Ledger":e.runtime_log_source==="provider_calls"?"Provider Calls":"Gateway HTTP Audit",D=e.runtime_log_source==="run_ledger"?"Runtime execution records for the selected workflow run.":e.runtime_log_source==="provider_calls"?"Model/provider call records extracted from the selected run ledger.":"Global Gateway HTTP/audit tail. This is system activity, not artifact provenance.";return s.jsxs("div",{className:"page runtime_page",children:[s.jsxs("section",{className:"runtime_header",children:[s.jsxs("div",{children:[s.jsx("div",{className:"run_hero_eyebrow",children:"System"}),s.jsx("h2",{children:e.tab==="activity"?"Activity monitor":e.tab==="artifacts"?"Artifact explorer":e.tab==="memory"?"Active memory":"Logs"}),s.jsxs("div",{className:"run_hero_meta",children:[s.jsx("span",{className:`status_pill ${e.gateway_connected?"ok":"warn"}`,children:e.gateway_connected?"gateway connected":"gateway offline"}),e.tab==="artifacts"&&e.artifact_run_filter?s.jsxs("span",{className:"chip muted",children:["filtered run ",s.jsx("span",{className:"mono",children:sn(e.artifact_run_filter,18)})]}):null,e.session_id?s.jsxs("span",{className:"chip muted",children:["session ",s.jsx("span",{className:"mono",children:sn(e.session_id,18)})]}):null]})]}),s.jsxs("div",{className:"metric_grid compact runtime_header_metrics",children:[s.jsxs("div",{className:"metric_tile",children:[s.jsx("span",{children:"Waiting"}),s.jsx("strong",{children:T(k.waiting.length)})]}),s.jsxs("div",{className:"metric_tile",children:[s.jsx("span",{children:"Running"}),s.jsx("strong",{children:T(k.running.length)})]}),s.jsxs("div",{className:"metric_tile",children:[s.jsx("span",{children:"Failed"}),s.jsx("strong",{children:T(k.failed.length)})]}),s.jsxs("div",{className:"metric_tile",children:[s.jsxs("span",{children:["Artifacts",c?" (filtered)":""]}),s.jsx("strong",{children:T(l)})]})]})]}),s.jsx("nav",{className:"runtime_mode_tabs",role:"tablist","aria-label":"System sections",children:["activity","artifacts","memory","logs"].map($=>s.jsxs("button",{role:"tab","aria-selected":e.tab===$,className:`runtime_mode_tab ${e.tab===$?"active":""}`,onClick:()=>e.on_tab_change($),children:[s.jsx(Be,{name:$==="activity"?"history":$==="artifacts"?"download":$==="memory"?"agent":"terminal",size:14}),s.jsx("span",{children:$==="activity"?"Activity":$==="artifacts"?"Artifacts":$==="memory"?"Memory":"Logs"})]},$))}),e.gateway_connected?null:s.jsxs("div",{className:"runtime_offline_banner",role:"status",children:[s.jsxs("div",{children:[s.jsx("strong",{children:"Gateway offline"}),s.jsx("span",{children:"Activity, artifacts, memory, and logs are unavailable until the gateway reconnects."})]}),s.jsxs("div",{children:[s.jsx("button",{className:"btn primary",onClick:e.on_reconnect,children:"Reconnect"}),s.jsx("button",{className:"btn",onClick:e.on_open_settings,children:"Settings"})]})]}),e.error?s.jsx("div",{className:"warn_callout",children:e.error}):null,e.tab==="activity"?s.jsx(mM,{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:$=>{R($),e.on_select_run($),e.on_tab_change("artifacts")},on_filter_session_artifacts:$=>{$&&(e.on_artifact_run_filter_change(""),e.on_session_filter_change($),e.on_scope_change("session"),e.on_tab_change("artifacts"))}}):null,e.tab==="memory"?e.memory_panel?s.jsx("div",{className:"runtime_memory_panel",children:e.memory_panel}):s.jsx("div",{className:"empty_state_inline",children:"The memory explorer needs a gateway connection — sign in to browse knowledge-graph assertions."}):null,e.tab==="artifacts"?s.jsxs(s.Fragment,{children:[s.jsxs("section",{className:"pane runtime_artifact_toolbar","aria-label":"Find artifacts",children:[s.jsxs("div",{className:"runtime_artifact_toolbar_top",children:[s.jsxs("label",{className:"artifact_filter_field artifact_filter_search",children:[s.jsx("span",{children:"Search"}),s.jsx("input",{value:e.query,onChange:$=>e.on_query_change($.target.value),placeholder:"title, path, hash, run, workflow, tag"})]}),s.jsxs("label",{className:"artifact_filter_field",children:[s.jsx("span",{children:"Scope"}),s.jsxs("select",{className:"seg_select",value:e.scope,onChange:$=>{const E=$.target.value;E!=="run"&&e.on_artifact_run_filter_change(""),E==="session"?e.on_session_filter_change(e.session_id):e.on_session_filter_change(""),e.on_scope_change(E)},children:[s.jsx("option",{value:"all",children:"All runtime"}),s.jsx("option",{value:"session",children:"This session"}),s.jsx("option",{value:"run",children:"Selected run"})]})]}),s.jsxs("label",{className:"artifact_filter_field",children:[s.jsx("span",{children:"Group"}),s.jsxs("select",{className:"seg_select",value:e.group_by,onChange:$=>e.on_group_by_change($.target.value),children:[s.jsx("option",{value:"type",children:"Type"}),s.jsx("option",{value:"time",children:"Date"}),s.jsx("option",{value:"turn",children:"Turn"}),s.jsx("option",{value:"node",children:"Node"}),s.jsx("option",{value:"workflow",children:"Workflow"}),s.jsx("option",{value:"run",children:"Run"}),s.jsx("option",{value:"location",children:"Location"}),s.jsx("option",{value:"source",children:"Source"})]})]}),s.jsxs("label",{className:"artifact_filter_field",children:[s.jsx("span",{children:"Sort"}),s.jsxs("select",{className:"seg_select",value:e.sort_by,onChange:$=>e.on_sort_by_change($.target.value),children:[s.jsx("option",{value:"newest",children:"Newest"}),s.jsx("option",{value:"oldest",children:"Oldest"}),s.jsx("option",{value:"last_access",children:"Last accessed"}),s.jsx("option",{value:"turn",children:"Turn order"}),s.jsx("option",{value:"type",children:"Type"}),s.jsx("option",{value:"size_desc",children:"Largest"}),s.jsx("option",{value:"size_asc",children:"Smallest"})]})]}),s.jsxs("button",{className:"btn btn_icon",onClick:e.on_refresh_artifacts,disabled:!e.gateway_connected||e.loading,children:[s.jsx(Be,{name:"refresh",size:14}),e.loading?"Loading…":"Refresh"]})]}),s.jsxs("div",{className:"artifact_filter_section",children:[s.jsxs("div",{className:"artifact_filter_label",children:["Type ",s.jsx("span",{className:"muted",children:"OR"})]}),s.jsxs("div",{className:"artifact_filter_chips",role:"group","aria-label":"Artifact type filters combine with OR",children:[n.map($=>{const E=o.has($),L=y[$]||0,M=VT($);return s.jsxs("button",{type:"button","aria-pressed":E,"aria-label":`${M} artifact type filter. Type filters combine with OR.`,title:`${M}: ${E?"in the filter":"not in the filter"}. Type filters combine with OR.`,className:`artifact_filter_chip ${E?"active":""}`,onClick:()=>w($),children:[s.jsx("span",{children:M}),s.jsx("span",{className:"artifact_chip_count",children:e.gateway_connected?L.toLocaleString():"—"})]},$)}),e.type_filters.length?s.jsx("button",{type:"button",className:"artifact_filter_chip clear",onClick:()=>e.on_type_filters_change([]),children:"Clear types"}):null]})]}),s.jsxs("div",{className:"artifact_filter_section",children:[s.jsx("div",{className:"artifact_filter_label",children:"Date"}),s.jsx("div",{className:"artifact_filter_chips",role:"group","aria-label":"Artifact date filters",children:r.map($=>s.jsx("button",{type:"button","aria-pressed":e.date_filter===$.value,className:`artifact_filter_chip ${e.date_filter===$.value?"active":""}`,onClick:()=>e.on_date_filter_change($.value),children:$.label},$.value))})]})]}),s.jsx("div",{className:"artifact_scope_banner",children:e.artifact_run_filter?s.jsxs(s.Fragment,{children:["Showing artifacts for ",s.jsx("strong",{children:S||sn(e.artifact_run_filter,18)}),".",s.jsx("button",{className:"btn",onClick:()=>R(""),children:"Show all"})]}):s.jsxs(s.Fragment,{children:["Showing artifacts across the selected runtime scope. Select a run to filter the inventory. ",e.artifact_total_bytes?s.jsxs("span",{className:"mono muted",children:["Total size ",uc(e.artifact_total_bytes)]}):null]})}),s.jsxs("div",{className:"runtime_artifacts_layout",children:[s.jsxs("aside",{className:"pane artifact_filter_rail",children:[s.jsxs("div",{className:"pane_header",children:[s.jsx("span",{className:"pane_title",children:"Runs"}),s.jsx("span",{className:"pane_count",children:N.length.toLocaleString()})]}),s.jsxs("div",{className:"pane_body scroll artifact_filter_rail_list",children:[s.jsxs("button",{className:`artifact_filter_run ${e.artifact_run_filter?"":"selected"}`,onClick:()=>R(""),children:[s.jsx("strong",{children:"All artifacts"}),s.jsx("span",{children:e.gateway_connected?`${l.toLocaleString()} match${l===1?"":"es"}`:"counts unavailable"})]}),N.map($=>{const E=String($.run_id||"").trim(),L=E===e.artifact_run_filter||E===(t==null?void 0:t.run_id);return s.jsxs("button",{className:`artifact_filter_run ${L?"selected":""}`,onClick:()=>R(E),title:E,children:[s.jsx("strong",{children:Gi($,e.workflow_label_by_id)}),s.jsx("span",{className:"mono",children:sn(E,15)}),s.jsx("span",{children:vc($)})]},E)})]})]}),s.jsxs("section",{className:"pane runtime_artifact_browser",children:[s.jsxs("div",{className:"pane_header artifact_browser_header",children:[s.jsx("span",{className:"pane_title",children:"Artifacts"}),s.jsx("span",{className:"pane_count",children:l?`${m.toLocaleString()}-${g.toLocaleString()} of ${l.toLocaleString()}`:"0 items"}),s.jsx("div",{className:"pane_spacer"}),f>1?s.jsxs("div",{className:"artifact_pagination","aria-label":"Artifact pages",children:[s.jsx("button",{className:"btn",onClick:()=>e.on_artifact_page_change(0),disabled:h<=0,children:"First"}),s.jsx("button",{className:"btn",onClick:()=>e.on_artifact_page_change(h-1),disabled:h<=0,children:"Prev"}),s.jsxs("span",{className:"muted artifact_page_label",children:["Page ",(h+1).toLocaleString()," / ",f.toLocaleString()]}),s.jsx("button",{className:"btn",onClick:()=>e.on_artifact_page_change(h+1),disabled:h>=f-1,children:"Next"}),s.jsx("button",{className:"btn",onClick:()=>e.on_artifact_page_change(f-1),disabled:h>=f-1,children:"Last"})]}):null]}),s.jsxs("div",{className:"pane_body scroll artifact_browser_body",children:[e.artifact_groups.length?null:s.jsx("div",{className:"empty_state_inline",children:e.gateway_connected?"No artifacts match the current filters.":"Gateway offline. Artifact inventory cannot be loaded until the connection is restored."}),s.jsx("div",{className:"artifact_group_list",children:e.artifact_groups.map($=>s.jsxs("section",{className:"artifact_group",children:[s.jsxs("div",{className:"artifact_group_header",children:[s.jsx("span",{children:$.key}),s.jsx("span",{className:"artifact_group_count",children:$.items.length})]}),$.items.map(E=>{var U;const L=E.run_id&&e.run_by_id[E.run_id]||null,M=L?Gi(L,e.workflow_label_by_id):py(E),ee=wv(E),F=Number(((U=E.access)==null?void 0:U.access_count)||0)||0;return s.jsxs("button",{className:`artifact_row ${(t==null?void 0:t.artifact_id)===E.artifact_id?"selected":""}`,onClick:()=>{e.on_select_artifact(E.artifact_id),E.run_id&&e.on_select_run(E.run_id)},title:E.artifact_id,children:[s.jsx(xv,{artifact:E,size:18}),s.jsxs("div",{className:"artifact_row_main",children:[s.jsxs("div",{className:"artifact_row_title",children:[s.jsx("strong",{children:yv(Zm(E,e.run_by_id,e.workflow_label_by_id))}),s.jsx("span",{className:"artifact_type_badge",children:Pu(E)}),E.render_kind&&E.render_kind!==E.semantic_kind?s.jsx("span",{className:"artifact_type_badge muted",children:E.render_kind}):null,E.legacy_inferred?s.jsx("span",{className:"artifact_type_badge inferred",children:"legacy inferred"}):null]}),s.jsxs("div",{className:"artifact_row_facts",children:[s.jsxs("span",{children:[s.jsx("b",{children:"Created"})," ",YT(E)]}),s.jsxs("span",{children:[s.jsx("b",{children:"Size"})," ",uc(E.size_bytes)]}),s.jsxs("span",{children:[s.jsx("b",{children:"Last seen"})," ",gv(E)]}),F?s.jsxs("span",{children:[s.jsx("b",{children:"Accesses"})," ",F.toLocaleString()]}):null,ee?s.jsxs("span",{children:[s.jsx("b",{children:"Media"})," ",ee]}):null,E.content_type?s.jsxs("span",{children:[s.jsx("b",{children:"MIME"})," ",E.content_type]}):null]}),s.jsxs("div",{className:"artifact_row_facts secondary",children:[M?s.jsxs("span",{children:[s.jsx("b",{children:"Workflow"})," ",M]}):null,E.run_id?s.jsxs("span",{className:"mono",children:[s.jsx("b",{children:"Run"})," ",sn(E.run_id,13)]}):null,s.jsxs("span",{children:[s.jsx("b",{children:"Turn"})," ",bg(E)]}),Ou(E)?s.jsxs("span",{className:"mono",children:[s.jsx("b",{children:"Node"})," ",Ou(E)]}):null,If(E)?s.jsxs("span",{children:[s.jsx("b",{children:"Source"})," ",If(E)]}):null]}),s.jsxs("div",{className:"artifact_row_facts tertiary",children:[s.jsxs("span",{className:"mono",children:[s.jsx("b",{children:"ID"})," ",sn(E.artifact_id,22)]}),s.jsxs("span",{children:[s.jsx("b",{children:"Provenance"})," ",_v(E)]})]}),vv(E)?s.jsx("div",{className:"artifact_row_path mono",children:vv(E)}):null]})]},E.artifact_id)})]},$.key))})]})]}),s.jsx("aside",{className:"runtime_detail",children:s.jsxs("section",{className:"overview_panel runtime_artifact_detail",children:[s.jsxs("div",{className:"overview_panel_header",children:[s.jsx("h3",{children:"Artifact Detail"}),t?s.jsx("span",{className:"chip mono muted",children:e.embedded_preview.render_kind?kg(t,e.run_by_id,e.workflow_label_by_id,e.embedded_preview.text):kg(t,e.run_by_id,e.workflow_label_by_id)}):null]}),t?s.jsxs(s.Fragment,{children:[(()=>{var U,V,O,H,Y,ae,ie;const $=JT(t),E=B0(t),L=wv(t),M=Number(((U=t.access)==null?void 0:U.access_count)||0)||0,ee=yn((V=t.links)==null?void 0:V.provider_trace,(O=t.links)==null?void 0:O.provider_trace_url,(H=t.links)==null?void 0:H.provider_trace_id),F=yn((Y=t.links)==null?void 0:Y.audit,(ae=t.links)==null?void 0:ae.audit_tail,(ie=t.links)==null?void 0:ie.audit_url);return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"artifact_detail_header",children:[s.jsx(xv,{artifact:t,size:22}),s.jsxs("div",{children:[s.jsx("div",{className:"artifact_detail_title",children:yv(Zm(t,e.run_by_id,e.workflow_label_by_id))}),s.jsxs("div",{className:"artifact_detail_subtitle",children:[Pu(t)," • ",t.render_kind||e.embedded_preview.render_kind||t.modality||"artifact"," • ",t.content_type||"unknown MIME"," • ",uc(t.size_bytes),t.legacy_inferred?" • legacy inferred":""]})]})]}),s.jsx(oM,{artifact:t,preview:e.embedded_preview}),s.jsxs("div",{className:"artifact_detail_grid",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Semantic type"}),s.jsx("strong",{children:Pu(t)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Render kind"}),s.jsx("strong",{children:t.render_kind||e.embedded_preview.render_kind||"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Created"}),s.jsx("strong",{children:Bu(t.created_at)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Size"}),s.jsx("strong",{children:uc(t.size_bytes)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Last seen"}),s.jsx("strong",{children:gv(t)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Accesses"}),s.jsx("strong",{children:M?M.toLocaleString():"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Run"}),s.jsx("strong",{className:"mono",children:t.run_id?sn(t.run_id,24):"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Workflow"}),s.jsx("strong",{children:b?Gi(b,e.workflow_label_by_id):"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Turn"}),s.jsx("strong",{children:bg(t)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Node"}),s.jsx("strong",{className:"mono",children:Ou(t)||"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Provider/model"}),s.jsx("strong",{children:E||"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Media facts"}),s.jsx("strong",{children:L||"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Trace"}),s.jsx("strong",{children:t.provider_trace_available?"available":"not recorded"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Provenance"}),s.jsx("strong",{children:_v(t)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Artifact id"}),s.jsx("strong",{className:"mono",children:sn(t.artifact_id,30)})]}),t.sha256?s.jsxs("div",{children:[s.jsx("span",{children:"sha256"}),s.jsx("strong",{className:"mono",children:sn(t.sha256,30)})]}):null]}),$?s.jsxs("div",{className:"artifact_provenance_panel",children:[s.jsx("div",{className:"artifact_filter_label",children:"Generation prompt / input"}),s.jsx("div",{className:"artifact_prompt_text",children:$})]}):s.jsxs("div",{className:"artifact_provenance_panel muted",children:[s.jsx("div",{className:"artifact_filter_label",children:"Generation prompt / input"}),s.jsx("div",{className:"artifact_prompt_text",children:"Generation prompt not recorded by the runtime artifact descriptor."})]}),Object.keys(t.generation||{}).length||Object.keys(t.producer||{}).length?s.jsxs("details",{className:"runtime_raw_details",children:[s.jsx("summary",{className:"mono muted",children:"Generation and producer metadata"}),s.jsx(Is,{value:{generation:t.generation,producer:t.producer,source_refs:t.source_refs},collapseAfterDepth:3,showCopy:!0})]}):null,t.source_path?s.jsx("div",{className:"artifact_detail_path mono",children:t.source_path}):null,s.jsxs("div",{className:"runtime_detail_actions",children:[s.jsx("button",{className:"btn primary",onClick:()=>e.on_preview_artifact(t),disabled:!t.run_id,children:e.embedded_preview.render_kind==="html"?"Open as web page":"Open full preview"}),s.jsx("button",{className:"btn",onClick:()=>e.on_download_artifact(t),disabled:!t.run_id,children:"Download"}),s.jsx("button",{className:"btn",onClick:()=>R(t.run_id),disabled:!t.run_id,children:"Show run artifacts"}),s.jsx("button",{className:"btn",onClick:()=>e.on_open_run(t.run_id),disabled:!t.run_id,children:"Open in Observe"}),s.jsx("button",{className:"btn",onClick:()=>e.on_open_ledger(t.run_id),disabled:!t.run_id,children:"Open run ledger"}),s.jsx("button",{className:"btn",onClick:()=>{ee&&window.open(ee,"_blank","noopener,noreferrer")},disabled:!ee,children:"Open provider trace"}),s.jsx("button",{className:"btn",onClick:()=>{F?window.open(F,"_blank","noopener,noreferrer"):e.on_tab_change("logs")},disabled:!F&&!t.audit_available,children:"Open audit trail"}),s.jsx("button",{className:"btn",onClick:()=>void gl(t.artifact_id),disabled:!t.artifact_id,children:"Copy artifact id"})]})]})})(),s.jsxs("details",{className:"runtime_raw_details",children:[s.jsx("summary",{className:"mono muted",children:"Raw metadata"}),s.jsx(Is,{value:t.raw,collapseAfterDepth:3,showCopy:!0})]})]}):s.jsx("div",{className:"empty_state_inline",children:"Select an artifact to inspect metadata, preview, or download content."})]})})]})]}):null,e.tab==="logs"?s.jsxs("section",{className:"overview_panel runtime_logs_panel",children:[s.jsxs("div",{className:"overview_panel_header",children:[s.jsxs("div",{children:[s.jsx("h3",{children:Q}),s.jsx("div",{className:"mono muted",children:D})]}),s.jsxs("div",{className:"actions",style:{marginTop:0},children:[te&&e.runtime_ledger_log_meta?s.jsx("span",{className:"mono muted",children:e.runtime_ledger_log_meta}):null,e.runtime_log_source==="gateway_audit"&&e.audit_log_meta?s.jsx("span",{className:"mono muted",children:e.audit_log_meta}):null,s.jsxs("button",{className:"btn btn_icon",onClick:()=>{te?e.on_refresh_runtime_ledger(e.selected_run_id):e.on_refresh_audit()},disabled:te?e.runtime_ledger_log_loading:e.audit_log_loading,children:[s.jsx(Be,{name:"refresh",size:14}),te?e.runtime_ledger_log_loading?"Loading…":"Refresh":e.audit_log_loading?"Loading…":"Refresh"]})]})]}),s.jsxs("div",{className:"runtime_log_toolbar",children:[s.jsxs("div",{className:"seg_toggle mono",children:[s.jsx("button",{className:`seg_btn ${e.runtime_log_source==="run_ledger"?"active":""}`,onClick:()=>e.on_runtime_log_source_change("run_ledger"),children:"Run ledger"}),s.jsx("button",{className:`seg_btn ${e.runtime_log_source==="provider_calls"?"active":""}`,onClick:()=>e.on_runtime_log_source_change("provider_calls"),children:"Provider calls"}),s.jsx("button",{className:`seg_btn ${e.runtime_log_source==="gateway_audit"?"active":""}`,onClick:()=>e.on_runtime_log_source_change("gateway_audit"),children:"Gateway audit"})]}),s.jsx("input",{className:"mono",value:e.runtime_log_query,onChange:$=>e.on_runtime_log_query_change($.target.value),placeholder:"Search node, status, effect, payload, error"})]}),e.runtime_log_source==="run_ledger"?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"runtime_log_context",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Selected run"}),s.jsx("strong",{children:A?Gi(A,e.workflow_label_by_id):e.selected_run_id?sn(e.selected_run_id,24):"No run selected"}),e.selected_run_id?s.jsx("em",{className:"mono",children:sn(e.selected_run_id,34)}):null]}),s.jsxs("div",{children:[s.jsx("span",{children:"Session"}),s.jsx("strong",{className:"mono",children:A!=null&&A.session_id?sn(String(A.session_id),28):e.session_id?sn(e.session_id,28):"—"})]}),s.jsxs("div",{className:"runtime_log_context_actions",children:[s.jsx("button",{className:"btn",onClick:()=>e.on_open_run(e.selected_run_id),disabled:!e.selected_run_id,children:"Open Observe"}),s.jsx("button",{className:"btn",onClick:()=>R(e.selected_run_id),disabled:!e.selected_run_id,children:"Run artifacts"})]})]}),e.runtime_ledger_log_error?s.jsx("div",{className:"warn_callout",children:e.runtime_ledger_log_error}):null,e.selected_run_id?null:s.jsx("div",{className:"empty_state_inline",children:"Select a run in Activity or Artifact Explorer to inspect its runtime ledger."}),e.selected_run_id&&!W.length&&!e.runtime_ledger_log_loading?s.jsx("div",{className:"empty_state_inline",children:"No ledger records match the current search."}):null,s.jsx("div",{className:"runtime_log_event_list","aria-label":"Selected run ledger records",children:W.map($=>{var Y,ae;const E=$.record||{},L=String(((Y=E==null?void 0:E.effect)==null?void 0:Y.type)||"").trim(),M=String((E==null?void 0:E.status)||"").trim(),ee=String((E==null?void 0:E.node_id)||"").trim(),F=yn(E==null?void 0:E.ended_at,E==null?void 0:E.started_at,E==null?void 0:E.ts),U=fa(E),V=U0(E),O=L?At(dr(((ae=E==null?void 0:E.effect)==null?void 0:ae.payload)??{},1200),{max_chars:1200,max_lines:6}):"",H=W0(E)||(U?`Waiting for ${String(U.reason||"input")}`:"")||((E==null?void 0:E.result)!==void 0?dr(E.result,700):"");return s.jsxs("article",{className:`runtime_log_event ${xc(M)}`,children:[s.jsxs("div",{className:"runtime_log_event_header",children:[s.jsxs("span",{className:"mono",children:["#",$.cursor]}),s.jsx(bc,{status:M||"record"}),L?s.jsx("span",{className:"chip mono muted",children:L}):null,ee?s.jsx("strong",{className:"mono",children:ee}):null,F?s.jsx("span",{className:"mono muted",children:Bu(F)}):null]}),s.jsxs("div",{className:"runtime_log_event_body",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Request / activity"}),s.jsx("p",{children:[V||Om(E),O&&O!=="{}"?O:""].filter(Boolean).join(`
|
|
129
|
-
`)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Outcome"}),s.jsx("p",{children:At(H||"—",{max_chars:1200,max_lines:6})})]})]}),s.jsxs("details",{className:"runtime_raw_details",children:[s.jsx("summary",{className:"mono muted",children:"Raw ledger record"}),s.jsx(Is,{value:E,collapseAfterDepth:3,showCopy:!0})]})]},`${e.selected_run_id}:${$.cursor}`)})})]}):e.runtime_log_source==="provider_calls"?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"runtime_log_context",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Selected run"}),s.jsx("strong",{children:A?Gi(A,e.workflow_label_by_id):e.selected_run_id?sn(e.selected_run_id,24):"No run selected"}),e.selected_run_id?s.jsx("em",{className:"mono",children:sn(e.selected_run_id,34)}):null]}),s.jsxs("div",{children:[s.jsx("span",{children:"Provider calls"}),s.jsx("strong",{children:z.length.toLocaleString()}),s.jsx("em",{className:"mono",children:J?`${J.toLocaleString()} tokens`:"tokens not recorded"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Issues"}),s.jsx("strong",{children:K.toLocaleString()})]}),s.jsxs("div",{className:"runtime_log_context_actions",children:[s.jsx("button",{className:"btn",onClick:()=>e.on_open_run(e.selected_run_id),disabled:!e.selected_run_id,children:"Open Observe"}),s.jsx("button",{className:"btn",onClick:()=>e.on_runtime_log_source_change("run_ledger"),disabled:!e.selected_run_id,children:"Run ledger"})]})]}),e.runtime_ledger_log_error?s.jsx("div",{className:"warn_callout",children:e.runtime_ledger_log_error}):null,e.selected_run_id?null:s.jsx("div",{className:"empty_state_inline",children:"Select a run in Activity or Artifact Explorer to inspect provider calls."}),e.selected_run_id&&!z.length&&!e.runtime_ledger_log_loading?s.jsx("div",{className:"empty_state_inline",children:"No provider calls are present in the selected run ledger, or none match the current search."}):null,s.jsx("div",{className:"provider_activity_list runtime_provider_log_list",children:z.map($=>s.jsxs("article",{className:`provider_activity ${$.error||$.missing_response?"danger":""}`,children:[s.jsxs("div",{className:"provider_activity_header",children:[s.jsxs("div",{children:[s.jsx("h4",{children:[$.provider||"provider unknown",$.model||"model unknown"].join(" / ")}),s.jsxs("div",{className:"timeline_subtitle",children:[$.node_id?s.jsx("span",{className:"mono",children:$.node_id}):null,$.run_id?s.jsx("span",{className:"mono",children:sn($.run_id,16)}):null,s.jsx("span",{children:cy($.duration_ms)}),$.status?s.jsx(bc,{status:$.status}):null]})]}),s.jsxs("div",{className:"provider_tokens mono",children:[$.tokens.total?$.tokens.total.toLocaleString():"—"," tokens"]})]}),s.jsxs("div",{className:"provider_preview_grid",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Prompt / messages"}),s.jsx("p",{children:$.prompt_preview||"No prompt payload captured"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Response / error"}),s.jsx("p",{children:$.response_preview||$.error||"No response captured"})]})]}),s.jsxs("details",{className:"runtime_raw_details",children:[s.jsx("summary",{className:"mono muted",children:"Raw provider ledger record"}),s.jsx(Is,{value:$.raw,collapseAfterDepth:3,showCopy:!0})]})]},$.id))})]}):s.jsxs(s.Fragment,{children:[e.audit_log_error?s.jsx("div",{className:"warn_callout",children:e.audit_log_error}):null,s.jsx("pre",{className:"mono audit_log_tail",children:re.length?re.join(`
|
|
130
|
-
`):"(audit tail not loaded or no lines match search)"})]})]}):null]})}function pM(e){const[t,n]=_.useState(""),r=Array.isArray(e.wait.choices)?e.wait.choices:[],o=e.wait.allow_free_text!==!1,l=e.disabled===!0,c=String(e.wait.prompt||"").trim();return s.jsxs(s.Fragment,{children:[r.length?s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Expected response"}),s.jsxs("select",{className:"mono",value:t,onChange:u=>n(u.target.value),children:[s.jsx("option",{value:"",children:"(select)"}),r.map((u,f)=>s.jsx("option",{value:String(u),children:String(u)},f))]})]}):null,o?s.jsxs("div",{className:"field",children:[s.jsx("label",{children:r.length?"Or type a response":c?"Your answer":"Response to resume this wait"}),s.jsx("textarea",{className:"mono wait_response_input",value:t,onChange:u=>n(u.target.value),placeholder:c?"Type your answer to the request above…":"Type the response the workflow is waiting for…",rows:4})]}):null,s.jsx("div",{className:"actions",children:s.jsx("button",{className:"btn primary",disabled:l||!t.trim(),onClick:()=>e.on_submit(t.trim()),children:"Submit response"})})]})}function jv(e,t,n){if(Tf(e)==="automation"){const r=String(e.automation_id||e.run_id||"").trim();return n[r]||"Automation"}return Gi(e,t)}function Sv(e){const t=Tf(e.run);return t?s.jsx("span",{className:"chip scheduled run_tree_tag","data-tag":t,children:_0(e.run)}):null}function gM(e){const t=e.selected_run_id.trim(),n=e.list?e.list.open:!0,r=e.root_run_id.trim()||t,o=e.sections.reduce((l,c)=>l+c.rows.reduce((u,f)=>{const h=[f.run,...f.children];return u+h.filter(m=>Uu(m.status)).length},0),0);return s.jsxs("aside",{className:`observatory_sidebar pane${n?"":" list_collapsed"}`,children:[s.jsxs("div",{className:"run_nav_header pane_header",children:[e.list?s.jsx(Rf,{open:n,on_toggle:e.list.on_toggle,controls:"run_nav_controls run_nav_tree",title:"Runs",count:`${e.total_runs.toLocaleString()} runs • ${o.toLocaleString()} active`}):s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"pane_title",children:"Runs"}),s.jsxs("span",{className:"pane_count",children:[e.total_runs.toLocaleString()," runs • ",o.toLocaleString()," active"]})]}),s.jsx("span",{className:"pane_spacer"}),s.jsxs("button",{className:"btn btn_icon",onClick:e.on_refresh,disabled:e.loading,title:"Refresh workflow runs",children:[s.jsx(Be,{name:"refresh",size:14}),e.loading?"…":""]})]}),s.jsxs("div",{className:"run_nav_controls",id:"run_nav_controls",hidden:!n,children:[s.jsx("input",{value:e.search,onChange:l=>e.on_search(l.target.value),placeholder:"Search runs, sessions, workflows"}),s.jsxs("div",{className:"run_nav_filter_row",children:[s.jsx("div",{className:"seg_toggle run_nav_segments",children:["active","waiting","terminal","failed","all"].map(l=>s.jsx("button",{className:`seg_btn ${e.filter===l?"active":""}`,onClick:()=>e.on_filter(l),children:l},l))}),s.jsxs("select",{className:"seg_select",value:e.group_by,onChange:l=>e.on_group_by(l.target.value),title:"Group workflow runs",children:[s.jsx("option",{value:"status",children:"Group by status"}),s.jsx("option",{value:"workflow",children:"Group by workflow"}),s.jsx("option",{value:"session",children:"Group by session"})]})]})]}),s.jsxs("div",{className:"run_tree",id:"run_nav_tree",hidden:!n,children:[e.sections.length?null:e.connected?s.jsx("div",{className:"run_tree_empty",children:"No runs match the current filters."}):s.jsxs("div",{className:"run_tree_empty",children:["Gateway offline — runs are unavailable."," ",s.jsx("button",{className:"btn btn_sm",onClick:e.on_sign_in,children:"Sign in"})]}),e.sections.map(l=>s.jsxs("section",{className:"run_tree_section",children:[s.jsxs("div",{className:"run_tree_section_header",children:[s.jsx("span",{children:l.label}),s.jsx("span",{className:"mono",children:l.rows.length})]}),l.rows.map(c=>{const u=c.run,f=String(u.run_id||"").trim(),h=f===t;return s.jsxs("div",{className:"run_tree_group",children:[s.jsxs("button",{className:`run_tree_item ${h?"selected":""} ${f===r?"root_context":""}`,onClick:()=>e.on_select(f,f),title:f,children:[s.jsxs("div",{className:"run_tree_item_top",children:[s.jsx("span",{className:"run_tree_label",children:jv(u,e.workflow_label_by_id,e.automation_titles)}),s.jsx(Sv,{run:u}),u.status?s.jsx(bc,{status:Km(u)}):null]}),s.jsxs("div",{className:"run_tree_meta",children:[s.jsx("span",{className:"mono",children:sn(f,13)}),s.jsx("span",{children:Mu(u)?_c(Mu(u)):"no start"}),s.jsx("span",{children:vc(u)})]})]}),c.children.length?s.jsx("div",{className:"run_tree_children",children:c.children.map(m=>{const g=String(m.run_id||"").trim();return s.jsxs("button",{className:`run_tree_item run_tree_child ${g===t?"selected":""}`,onClick:()=>e.on_select(g,f),title:g,children:[s.jsxs("div",{className:"run_tree_item_top",children:[s.jsx("span",{className:"run_tree_label",children:jv(m,e.workflow_label_by_id,e.automation_titles)}),s.jsx(Sv,{run:m}),s.jsx(bc,{status:Km(m)})]}),s.jsxs("div",{className:"run_tree_meta",children:[s.jsx("span",{className:"mono",children:sn(g,13)}),s.jsx("span",{children:Mu(m)?_c(Mu(m)):"child"}),s.jsx("span",{children:vc(m)})]})]},g)})}):null]},f)})]},l.key))]})]})}class yM{constructor(){cs(this,"_buffer","");cs(this,"_current",{data_lines:[]})}push(t,n){for(this._buffer+=t;;){const r=this._buffer.indexOf(`
|
|
131
|
-
`);if(r===-1)return;const o=this._buffer.slice(0,r);this._buffer=this._buffer.slice(r+1);const l=o.endsWith("\r")?o.slice(0,-1):o;if(l.startsWith(":"))continue;if(l===""){if(this._current.data_lines.length>0||this._current.event||this._current.id){const h={id:this._current.id,event:this._current.event,data:this._current.data_lines.join(`
|
|
132
|
-
`)};n(h)}this._current={data_lines:[]};continue}const c=l.indexOf(":"),u=c===-1?l:l.slice(0,c),f=c===-1?"":l.slice(c+1).trimStart();if(u==="id"){this._current.id=f;continue}if(u==="event"){this._current.event=f;continue}if(u==="data"){this._current.data_lines.push(f);continue}}}}const Lt=Kg;function Cr(e,t=3e4){const n=AbortSignal.timeout(t);if(!e)return n;const r=AbortSignal.any;return typeof r=="function"?r([e,n]):e}function jg(){var t;const e={};try{const n=(t=document.cookie.split(";").map(r=>r.trim()).find(r=>r.startsWith("abstractobserver_gateway_csrf=")))==null?void 0:t.slice(30);n&&(e["X-AbstractObserver-CSRF"]=decodeURIComponent(n))}catch{}return e}function $t(e){const t=(e||"").trim(),n={};return t&&(n.Authorization=`Bearer ${t}`),{...n,...jg()}}async function Gn(e){try{const t=await e.text();return t!=null&&t.trim()?t.trim():`${e.status}`}catch{return`${e.status}`}}class wM extends Error{constructor(n,r){super(r);cs(this,"status");this.name="GatewayRequestError",this.status=n}}async function ic(e,t){let n="";try{n=(await e.text()).trim()}catch{n=""}let r=n;try{const o=JSON.parse(n),l=o&&typeof o=="object"?o.detail:void 0;typeof l=="string"&&l.trim()?r=l.trim():l&&typeof l=="object"&&typeof l.message=="string"&&l.message.trim()&&(r=l.message.trim())}catch{}return new wM(e.status,`${t} (HTTP ${e.status}): ${r||e.statusText||"no reason given"}`)}async function vM(e){var n;let t="";try{t=(await e.text()).trim()}catch{return""}try{const r=(n=JSON.parse(t))==null?void 0:n.detail;return typeof r=="string"?r.trim():r&&typeof r.message=="string"?r.message.trim():""}catch{return t}}class kp{constructor(t){cs(this,"_cfg");cs(this,"fetch_gateway",(t,n)=>fetch(Lt(this._cfg.base_url,t),{...n,headers:{...n==null?void 0:n.headers,...$t(this._cfg.auth_token)}}));this._cfg={...t,base_url:(t.base_url||"").trim()}}async start_run(t,n,r){const o=String((r==null?void 0:r.bundle_id)||"").trim(),l=(r==null?void 0:r.session_id)===null||(r==null?void 0:r.session_id)===void 0?"":String(r.session_id||"").trim(),c=String(t||"").trim(),u=String((r==null?void 0:r.interface)||"").trim();if(c==="@default"&&(!u||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),c&&(f.flow_id=c),c==="@default"&&(f.interface=u),l&&(f.session_id=l),r!=null&&r.workspace&&(f.workspace=r.workspace);const h=await fetch(Lt(this._cfg.base_url,it("runs/start")),{method:"POST",headers:{"Content-Type":"application/json",...$t(this._cfg.auth_token)},body:JSON.stringify(f)});if(!h.ok)throw new Error(await vM(h)||`start_run failed: ${h.status}`);const m=await h.json(),g=m==null?void 0:m.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[it("mcp/servers"),it("mcp"),it("discovery/mcp")])try{const n=await fetch(Lt(this._cfg.base_url,t),{headers:{...$t(this._cfg.auth_token)},signal:Cr()});if(n.status===404||!n.ok)continue;const r=await n.json(),o=Array.isArray(r)?r:Array.isArray(r==null?void 0:r.servers)?r.servers:Array.isArray(r==null?void 0:r.items)?r.items:null;if(!o)continue;return o.map(l=>({name:String((l==null?void 0:l.name)||(l==null?void 0:l.id)||"").trim(),url:typeof(l==null?void 0:l.url)=="string"?l.url:void 0,description:typeof(l==null?void 0:l.description)=="string"?l.description:void 0,auth_required:typeof(l==null?void 0:l.auth_required)=="boolean"?l.auth_required:void 0})).filter(l=>l.name)}catch{return null}return null}async list_skills(){for(const t of[it("skills"),it("skills/registry")])try{const n=await fetch(Lt(this._cfg.base_url,t),{headers:{...$t(this._cfg.auth_token)},signal:Cr()});if(n.status===404||!n.ok)continue;const r=await n.json(),o=Array.isArray(r)?r:Array.isArray(r==null?void 0:r.skills)?r.skills:Array.isArray(r==null?void 0:r.items)?r.items:null;if(!o)continue;return o.map(l=>({name:String((l==null?void 0:l.name)||(l==null?void 0:l.id)||"").trim(),description:typeof(l==null?void 0:l.description)=="string"?l.description:void 0,version:typeof(l==null?void 0:l.version)=="string"?l.version:void 0,trust_level:typeof(l==null?void 0:l.trust_level)=="string"?l.trust_level:void 0,blocked:typeof(l==null?void 0:l.blocked)=="boolean"?l.blocked:void 0,requires_review:typeof(l==null?void 0:l.requires_review)=="boolean"?l.requires_review:void 0,tree_hash:typeof(l==null?void 0:l.tree_hash)=="string"?l.tree_hash:void 0,reasons:Array.isArray(l==null?void 0:l.reasons)?l.reasons.map(c=>String(c||"")).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,it(`runs/${encodeURIComponent(t)}`)),{headers:{...$t(this._cfg.auth_token)}});if(!n.ok)throw new Error(`get_run failed: ${await Gn(n)}`);return await n.json()}async find_run(t){const n=await fetch(Lt(this._cfg.base_url,it(`runs/${encodeURIComponent(t)}`)),{headers:{...$t(this._cfg.auth_token)}});if(n.status===404||n.status===403)return null;if(!n.ok)throw await ic(n,"Opening the run failed");return await n.json()}async get_run_history_bundle(t,n){const r=String(t||"").trim();if(!r)throw new Error("get_run_history_bundle: run_id is required");const o=new URLSearchParams;(n==null?void 0:n.include_subruns)===!1&&o.set("include_subruns","false"),(n==null?void 0:n.include_session)===!0&&o.set("include_session","true"),typeof(n==null?void 0:n.session_turn_limit)=="number"&&Number.isFinite(n.session_turn_limit)&&o.set("session_turn_limit",String(Math.max(1,Math.trunc(n.session_turn_limit)))),n!=null&&n.ledger_mode&&o.set("ledger_mode",String(n.ledger_mode)),typeof(n==null?void 0:n.ledger_max_items)=="number"&&Number.isFinite(n.ledger_max_items)&&o.set("ledger_max_items",String(Math.max(0,Math.trunc(n.ledger_max_items))));const l=Lt(this._cfg.base_url,it(`runs/${encodeURIComponent(r)}/history_bundle?${o.toString()}`)),c=await fetch(l,{headers:{...$t(this._cfg.auth_token)}});if(!c.ok)throw new Error(`get_run_history_bundle failed: ${await Gn(c)}`);return await c.json()}async list_runs(t){const n=typeof(t==null?void 0:t.limit)=="number"?t.limit:50,r=String((t==null?void 0:t.status)||"").trim(),o=String((t==null?void 0:t.workflow_id)||"").trim(),l=String((t==null?void 0:t.session_id)||"").trim(),c=(t==null?void 0:t.root_only)===!0,u=new URLSearchParams;u.set("limit",String(n)),r&&u.set("status",r),o&&u.set("workflow_id",o),l&&u.set("session_id",l),c&&u.set("root_only","true"),(t==null?void 0:t.archived_only)===!0&&u.set("archived_only","true"),typeof(t==null?void 0:t.include_ledger_len)=="boolean"&&u.set("include_ledger_len",String(t.include_ledger_len)),typeof(t==null?void 0:t.include_metrics)=="boolean"&&u.set("include_metrics",String(t.include_metrics)),typeof(t==null?void 0:t.include_drafts)=="boolean"&&u.set("include_drafts",String(t.include_drafts));const f=Lt(this._cfg.base_url,it(`runs?${u.toString()}`)),h=await fetch(f,{headers:{...$t(this._cfg.auth_token)},signal:AbortSignal.timeout(3e4)});if(!h.ok)throw new Error(`list_runs failed: ${await Gn(h)}`);return await h.json()}async audit_log_tail(t){const n=typeof(t==null?void 0:t.max_bytes)=="number"?Math.max(1024,Math.min(4e5,Math.floor(t.max_bytes))):8e4,r=Lt(this._cfg.base_url,it(`audit/tail?max_bytes=${encodeURIComponent(String(n))}`)),o=await fetch(r,{headers:{...$t(this._cfg.auth_token)}});if(!o.ok)throw new Error(`audit_log_tail failed: ${await Gn(o)}`);return await o.json()}async gateway_about(){const t=await fetch(Lt(this._cfg.base_url,it("about")),{headers:{...$t(this._cfg.auth_token)},signal:Cr(void 0,1e4)});if(!t.ok)throw new Error(`HTTP ${t.status}`);return await t.json()}async get_run_input_data(t){const n=String(t||"").trim();if(!n)throw new Error("get_run_input_data: run_id is required");const r=await fetch(Lt(this._cfg.base_url,it(`runs/${encodeURIComponent(n)}/input_data`)),{headers:{...$t(this._cfg.auth_token)}});if(!r.ok)throw new Error(`get_run_input_data failed: ${await Gn(r)}`);return await r.json()}async list_run_artifacts(t,n){const r=String(t||"").trim();if(!r)throw new Error("list_run_artifacts: run_id is required");const o=typeof(n==null?void 0:n.limit)=="number"?n.limit:200,l=typeof(n==null?void 0:n.offset)=="number"?Math.max(0,Math.floor(n.offset)):0,c=Lt(this._cfg.base_url,it(`runs/${encodeURIComponent(r)}/artifacts?limit=${encodeURIComponent(String(o))}&offset=${encodeURIComponent(String(l))}`)),u=await fetch(c,{headers:{...$t(this._cfg.auth_token)}});if(!u.ok)throw new Error(`list_run_artifacts failed: ${await Gn(u)}`);return await u.json()}async list_session_artifacts(t,n){const r=String(t||"").trim();if(!r)throw new Error("list_session_artifacts: session_id is required");const o=typeof(n==null?void 0:n.limit)=="number"?n.limit:200,l=typeof(n==null?void 0:n.offset)=="number"?Math.max(0,Math.floor(n.offset)):0,c=Lt(this._cfg.base_url,it(`sessions/${encodeURIComponent(r)}/artifacts?limit=${encodeURIComponent(String(o))}&offset=${encodeURIComponent(String(l))}`)),u=await fetch(c,{headers:{...$t(this._cfg.auth_token)}});if(!u.ok)throw new Error(`list_session_artifacts failed: ${await Gn(u)}`);return await u.json()}async search_artifacts(t){const n=new URLSearchParams;n.set("scope",String((t==null?void 0:t.scope)||"all").trim()||"all");const r=String((t==null?void 0:t.session_id)||"").trim(),o=String((t==null?void 0:t.run_id)||"").trim(),l=String((t==null?void 0:t.modality)||"").trim(),c=String((t==null?void 0:t.artifact_kind)||"").trim(),u=String((t==null?void 0:t.semantic_kind)||"").trim(),f=String((t==null?void 0:t.render_kind)||"").trim(),h=String((t==null?void 0:t.workflow_id)||"").trim(),m=String((t==null?void 0:t.node_id)||"").trim(),g=String((t==null?void 0:t.content_type)||"").trim(),y=String((t==null?void 0:t.query)||"").trim(),w=String((t==null?void 0:t.tags)||"").trim(),k=String((t==null?void 0:t.cursor)||"").trim(),b=String((t==null?void 0:t.order_by)||"").trim(),S=String((t==null?void 0:t.order)||"").trim(),N=String((t==null?void 0:t.created_after)||"").trim(),R=String((t==null?void 0:t.created_before)||"").trim(),T=typeof(t==null?void 0:t.limit)=="number"?t.limit:500,A=typeof(t==null?void 0:t.offset)=="number"?Math.max(0,Math.floor(t.offset)):0;r&&n.set("session_id",r),o&&n.set("run_id",o),l&&n.set("modality",l),c&&n.set("artifact_kind",c),u&&n.set("semantic_kind",u),f&&n.set("render_kind",f),h&&n.set("workflow_id",h),m&&n.set("node_id",m),g&&n.set("content_type",g),y&&n.set("query",y),w&&n.set("tags",w),k&&n.set("cursor",k),b&&n.set("order_by",b),S&&n.set("order",S),N&&n.set("created_after",N),R&&n.set("created_before",R),t!=null&&t.include_stats&&n.set("include_stats","true"),n.set("limit",String(T)),n.set("offset",String(A));const W=await fetch(Lt(this._cfg.base_url,it(`artifacts/search?${n.toString()}`)),{headers:{...$t(this._cfg.auth_token)}});if(!W.ok)throw new Error(`search_artifacts failed: ${await Gn(W)}`);return await W.json()}async artifact_stats(t){const n=new URLSearchParams;n.set("scope",String((t==null?void 0:t.scope)||"all").trim()||"all");for(const o of["session_id","run_id","modality","semantic_kind","render_kind","workflow_id","node_id","content_type","query","tags","created_after","created_before"]){const l=String((t==null?void 0:t[o])||"").trim();l&&n.set(o,l)}const r=await fetch(Lt(this._cfg.base_url,it(`artifacts/stats?${n.toString()}`)),{headers:{...$t(this._cfg.auth_token)}});if(!r.ok)throw new Error(`artifact_stats failed: ${await Gn(r)}`);return await r.json()}async download_run_artifact_content(t,n,r){const o=String(t||"").trim(),l=String(n||"").trim();if(!o)throw new Error("download_run_artifact_content: run_id is required");if(!l)throw new Error("download_run_artifact_content: artifact_id is required");const c=String((r==null?void 0:r.access)||"").trim(),u=c?`?access=${encodeURIComponent(c)}`:"",f=Lt(this._cfg.base_url,it(`runs/${encodeURIComponent(o)}/artifacts/${encodeURIComponent(l)}/content${u}`)),h=await fetch(f,{headers:{...$t(this._cfg.auth_token)}});if(!h.ok)throw new Error(`download_run_artifact_content failed: ${await Gn(h)}`);return await h.blob()}async list_entities(){const t=await fetch(Lt(this._cfg.base_url,it("entities")),{headers:{...$t(this._cfg.auth_token)},signal:Cr()});if(!t.ok)throw new Error(`list_entities failed: ${await Gn(t)}`);const n=await t.json();return{entities:Array.isArray(n==null?void 0:n.entities)?n.entities:[]}}async get_entity_phases_spec(){const t=await fetch(Lt(this._cfg.base_url,it("entities/spec/phases")),{headers:{...$t(this._cfg.auth_token)},signal:Cr()});if(!t.ok)throw new Error(`get_entity_phases_spec failed: ${await Gn(t)}`);return await t.json()}async get_entity_cognition(t){const n=await fetch(Lt(this._cfg.base_url,it(`entities/${encodeURIComponent(t)}/cognition`)),{headers:{...$t(this._cfg.auth_token)},signal:Cr()});if(!n.ok)throw new Error(`get_entity_cognition failed: ${await Gn(n)}`);return await n.json()}async get_entity_card(t){const n=String(t||"").trim();if(!n)throw new Error("get_entity_card: name is required");const r=await fetch(Lt(this._cfg.base_url,it(`entities/${encodeURIComponent(n)}/card`)),{headers:{...$t(this._cfg.auth_token)},signal:Cr()});if(!r.ok)throw new Error(`get_entity_card failed: ${await Gn(r)}`);return await r.json()}async read_entity_diary_entry(t,n){const r=String(t||"").trim(),o=String(n||"").trim();if(!r||!o)throw new Error("read_entity_diary_entry: name and entry_id are required");const l=Lt(this._cfg.base_url,it(`entities/${encodeURIComponent(r)}/diary/${encodeURIComponent(o)}?reason=${encodeURIComponent("observer board hint chip")}`)),c=await fetch(l,{headers:{...$t(this._cfg.auth_token)},signal:Cr()});if(!c.ok)throw new Error(`read_entity_diary_entry failed: ${await Gn(c)}`);return await c.json()}async get_ledger(t,n){const r=Number((n==null?void 0:n.after)||0),o=Number((n==null?void 0:n.limit)||0),l=Lt(this._cfg.base_url,it(`runs/${encodeURIComponent(t)}/ledger?after=${encodeURIComponent(String(r))}&limit=${encodeURIComponent(String(o))}`)),c=await fetch(l,{headers:{...$t(this._cfg.auth_token)},signal:Cr(n==null?void 0:n.signal)});if(!c.ok)throw new Error(`get_ledger failed: ${c.status}`);const u=await c.json(),f=Array.isArray(u==null?void 0:u.items)?u.items:[],h=typeof(u==null?void 0:u.next_after)=="number"?u.next_after:r;return{items:f,next_after:h}}async get_ledger_batch(t){const n=Array.isArray(t==null?void 0:t.runs)?t.runs:[],r=Number((t==null?void 0:t.limit)||0),o=await fetch(Lt(this._cfg.base_url,it("runs/ledger/batch")),{method:"POST",headers:{"Content-Type":"application/json",...$t(this._cfg.auth_token)},body:JSON.stringify({runs:n,limit:r}),signal:Cr()});if(!o.ok)throw new Error(`get_ledger_batch failed: ${o.status}`);const l=await o.json(),u=(l&&typeof l=="object"?l:{}).runs;return{runs:u&&typeof u=="object"?u:{}}}async generate_run_summary(t,n){const r=String(t||"").trim();if(!r)throw new Error("generate_run_summary: run_id is required");const o={include_subruns:(n==null?void 0:n.include_subruns)!==!1},l=typeof(n==null?void 0:n.provider)=="string"?String(n.provider).trim():"";l&&(o.provider=l);const c=typeof(n==null?void 0:n.model)=="string"?String(n.model).trim():"";c&&(o.model=c);const u=await fetch(Lt(this._cfg.base_url,it(`runs/${encodeURIComponent(r)}/summary`)),{method:"POST",headers:{"Content-Type":"application/json",...$t(this._cfg.auth_token)},body:JSON.stringify(o)});if(!u.ok)throw await ic(u,"The gateway could not summarize this run");return await u.json()}async run_chat(t,n){const r=String(t||"").trim();if(!r)throw new Error("run_chat: run_id is required");const o={include_subruns:(n==null?void 0:n.include_subruns)!==!1,messages:Array.isArray(n==null?void 0:n.messages)?n.messages:[],persist:!!(n!=null&&n.persist)},l=typeof(n==null?void 0:n.provider)=="string"?String(n.provider).trim():"";l&&(o.provider=l);const c=typeof(n==null?void 0:n.model)=="string"?String(n.model).trim():"";c&&(o.model=c);const u=await fetch(Lt(this._cfg.base_url,it(`runs/${encodeURIComponent(r)}/chat`)),{method:"POST",headers:{"Content-Type":"application/json",...$t(this._cfg.auth_token)},body:JSON.stringify(o)});if(!u.ok)throw await ic(u,"The gateway could not answer");return await u.json()}async audio_transcribe(t,n){const r=String(t||"").trim();if(!r)throw new Error("audio_transcribe: run_id is required");const o=n==null?void 0:n.audio_artifact;if(!o||typeof o!="object")throw new Error("audio_transcribe: audio_artifact is required");if(!String(o.$artifact||"").trim())throw new Error("audio_transcribe: audio_artifact.$artifact is required");const c={audio_artifact:o};for(const m of["language","provider","model","request_id"]){const g=String((n==null?void 0:n[m])||"").trim();g&&(c[m]=g)}const u=await fetch(Lt(this._cfg.base_url,it(`runs/${encodeURIComponent(r)}/audio/transcribe`)),{method:"POST",headers:{"Content-Type":"application/json",...$t(this._cfg.auth_token)},body:JSON.stringify(c)});if(!u.ok)throw await ic(u,"The gateway refused the transcription");const f=await u.json(),h=String((f==null?void 0:f.text)||"");return{ok:!!(f!=null&&f.ok),run_id:String((f==null?void 0:f.run_id)||""),request_id:String((f==null?void 0:f.request_id)||""),text:h,transcript_artifact:f==null?void 0:f.transcript_artifact,provider:f!=null&&f.provider?String(f.provider):null,model:f!=null&&f.model?String(f.model):null,duration_ms:Number.isFinite(Number(f==null?void 0:f.duration_ms))?Number(f.duration_ms):null}}async voice_defaults(){const t=await fetch(Lt(this._cfg.base_url,it("voice/defaults")),{headers:{...$t(this._cfg.auth_token)},signal:Cr()});if(!t.ok)throw await ic(t,"The gateway could not list its voice defaults");return await t.json()}async voice_catalog(t,n){const r=new URLSearchParams({compact:"true"});t&&r.set("provider",t),n&&r.set("model",n);const o=await fetch(Lt(this._cfg.base_url,it(`voice/voices?${r.toString()}`)),{headers:{...$t(this._cfg.auth_token)},signal:Cr()});if(!o.ok)throw await ic(o,"The gateway could not list its voices");return await o.json()}gateway_url(t){return Lt(this._cfg.base_url,t)}auth_headers(){return $t(this._cfg.auth_token)}async voice_tts(t,n){const r=String(t||"").trim();if(!r)throw new Error("voice_tts: run_id is required");const o=String((n==null?void 0:n.text)||"").trim();if(!o)throw new Error("voice_tts: text is required");const l={text:o},c=String((n==null?void 0:n.voice)||"").trim();c&&(l.voice=c);const u=String((n==null?void 0:n.format)||"").trim();u&&(l.format=u);const f=String((n==null?void 0:n.request_id)||"").trim();f&&(l.request_id=f);const h=await fetch(Lt(this._cfg.base_url,it(`runs/${encodeURIComponent(r)}/voice/tts`)),{method:"POST",headers:{"Content-Type":"application/json",...$t(this._cfg.auth_token)},body:JSON.stringify(l)});if(!h.ok)throw new Error(`voice_tts failed: ${await Gn(h)}`);const m=await h.json();return{ok:!!(m!=null&&m.ok),run_id:String((m==null?void 0:m.run_id)||""),request_id:String((m==null?void 0:m.request_id)||""),audio_artifact:m==null?void 0:m.audio_artifact}}async save_chat_thread(t,n){const r=String(t||"").trim();if(!r)throw new Error("save_chat_thread: run_id is required");const o={include_subruns:(n==null?void 0:n.include_subruns)!==!1,messages:Array.isArray(n==null?void 0:n.messages)?n.messages:[]},l=typeof(n==null?void 0:n.provider)=="string"?String(n.provider).trim():"";l&&(o.provider=l);const c=typeof(n==null?void 0:n.model)=="string"?String(n.model).trim():"";c&&(o.model=c);const u=typeof(n==null?void 0:n.title)=="string"?String(n.title).trim():"";u&&(o.title=u);const f=await fetch(Lt(this._cfg.base_url,it(`runs/${encodeURIComponent(r)}/chat_threads`)),{method:"POST",headers:{"Content-Type":"application/json",...$t(this._cfg.auth_token)},body:JSON.stringify(o)});if(!f.ok)throw new Error(`save_chat_thread failed: ${await Gn(f)}`);return await f.json()}async list_bundles(){const t=await fetch(Lt(this._cfg.base_url,it("bundles")),{headers:{...$t(this._cfg.auth_token)},signal:Cr()});if(!t.ok)throw new Error(`list_bundles failed: ${t.status}`);return await t.json()}async get_gateway_json(t,n){const r=await fetch(Lt(this._cfg.base_url,it(t)),{headers:{...$t(this._cfg.auth_token)},signal:n??Cr()});if(!r.ok)throw new Error(await Gn(r));return await r.json()}async reload_bundles(){const t=await fetch(Lt(this._cfg.base_url,it("bundles/reload")),{method:"POST",headers:{...$t(this._cfg.auth_token)}});if(!t.ok)throw new Error(`reload_bundles failed: ${t.status}`);return await t.json()}async upload_bundle(t,n){const r=(n==null?void 0:n.overwrite)===!0,o=(n==null?void 0:n.reload)!==!1,l=new FormData;l.set("overwrite",r?"true":"false"),l.set("reload",o?"true":"false"),l.set("file",t,t.name||"upload.flow");const c=await fetch(Lt(this._cfg.base_url,it("bundles/upload")),{method:"POST",headers:{...$t(this._cfg.auth_token)},body:l});if(!c.ok)throw new Error(`upload_bundle failed: ${await Gn(c)}`);return await c.json()}async attachments_upload(t,n,r){const o=String(t||"").trim();if(!o)throw new Error("attachments_upload: session_id is required");if(!n)throw new Error("attachments_upload: file is required");const l=String((r==null?void 0:r.filename)||"").trim()||String((n==null?void 0:n.name)||"").trim()||"upload.bin",c=String((r==null?void 0:r.content_type)||"").trim()||String((n==null?void 0:n.type)||"").trim(),u=new FormData;u.append("session_id",o),u.append("file",n,l),u.append("filename",l),c&&u.append("content_type",c);const f=await fetch(Lt(this._cfg.base_url,it("attachments/upload")),{method:"POST",headers:{...$t(this._cfg.auth_token)},body:u});if(!f.ok)throw new Error(`attachments_upload failed: ${await Gn(f)}`);const h=await f.json(),m=h==null?void 0:h.attachment;if(!m||typeof m!="object")throw new Error("attachments_upload: missing attachment");if(!String(m.$artifact||"").trim())throw new Error("attachments_upload: missing attachment.$artifact");return m}async remove_bundle(t,n){const r=String(t||"").trim();if(!r)throw new Error("remove_bundle: bundle_id is required");const o=new URLSearchParams,l=String((n==null?void 0:n.bundle_version)||"").trim();l&&o.set("bundle_version",l),o.set("reload",(n==null?void 0:n.reload)===!1?"false":"true");const c=Lt(this._cfg.base_url,it(`bundles/${encodeURIComponent(r)}?${o.toString()}`)),u=await fetch(c,{method:"DELETE",headers:{...$t(this._cfg.auth_token)}});if(!u.ok)throw new Error(`remove_bundle failed: ${await Gn(u)}`);return await u.json()}async discovery_tools(){const t=await fetch(Lt(this._cfg.base_url,it("discovery/tools")),{headers:{...$t(this._cfg.auth_token)}});if(!t.ok)throw new Error(`discovery_tools failed: ${t.status}`);return await t.json()}async discovery_providers(t){const n=(t==null?void 0:t.include_models)===!0,r=Lt(this._cfg.base_url,it(`discovery/providers?include_models=${encodeURIComponent(String(n))}`)),o=await fetch(r,{headers:{...$t(this._cfg.auth_token)}});if(!o.ok)throw new Error(`discovery_providers failed: ${o.status}`);return await o.json()}async discovery_provider_models(t){const n=String(t||"").trim();if(!n)throw new Error("discovery_provider_models: provider_name is required");const r=await fetch(Lt(this._cfg.base_url,it(`discovery/providers/${encodeURIComponent(n)}/models`)),{headers:{...$t(this._cfg.auth_token)}});if(!r.ok)throw new Error(`discovery_provider_models failed: ${r.status}`);return await r.json()}async get_bundle(t){const n=String(t||"").trim();if(!n)throw new Error("get_bundle: bundle_id is required");const r=await fetch(Lt(this._cfg.base_url,it(`bundles/${encodeURIComponent(n)}`)),{headers:{...$t(this._cfg.auth_token)}});if(!r.ok)throw new Error(`get_bundle failed: ${r.status}`);return await r.json()}async get_bundle_flow(t,n){const r=String(t||"").trim(),o=String(n||"").trim();if(!r)throw new Error("get_bundle_flow: bundle_id is required");if(!o)throw new Error("get_bundle_flow: flow_id is required");const l=await fetch(Lt(this._cfg.base_url,it(`bundles/${encodeURIComponent(r)}/flows/${encodeURIComponent(o)}`)),{headers:{...$t(this._cfg.auth_token)}});if(!l.ok)throw new Error(`get_bundle_flow failed: ${l.status}`);return await l.json()}async get_workflow_flow(t){const n=String(t||"").trim();if(!n)throw new Error("get_workflow_flow: workflow_id is required");const r=await fetch(Lt(this._cfg.base_url,it(`workflows/${encodeURIComponent(n)}/flow`)),{headers:{...$t(this._cfg.auth_token)}});if(!r.ok)throw new Error(`get_workflow_flow failed: ${r.status}`);return await r.json()}async discovery_capabilities(){const t=await fetch(Lt(this._cfg.base_url,it("discovery/capabilities")),{headers:{...$t(this._cfg.auth_token)},signal:Cr()});if(!t.ok)throw new Error(`discovery_capabilities failed: ${await Gn(t)}`);return await t.json()}automations_client(){const t=this._cfg.auth_token;return kN({fetch:(n,r)=>fetch(n,r),baseUrl:this._cfg.base_url,headers:()=>$t(t)})}async submit_command(t){const n=await fetch(Lt(this._cfg.base_url,it("commands")),{method:"POST",headers:{"Content-Type":"application/json",...$t(this._cfg.auth_token)},body:JSON.stringify(t)});if(!n.ok)throw new Error(`submit_command failed: ${n.status}`);return await n.json()}async kg_query(t){const n=String((t==null?void 0:t.scope)||"session").trim().toLowerCase(),r=String((t==null?void 0:t.order)||"desc").trim().toLowerCase(),o=typeof(t==null?void 0:t.limit)=="number"&&Number.isFinite(t.limit)?Number(t.limit):500,l={scope:n,order:r,limit:o},c=String((t==null?void 0:t.run_id)||"").trim();c&&(l.run_id=c);const u=String((t==null?void 0:t.session_id)||"").trim();u&&(l.session_id=u);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 h=String((t==null?void 0:t.subject)||"").trim();h&&(l.subject=h);const m=String((t==null?void 0:t.predicate)||"").trim();m&&(l.predicate=m);const g=String((t==null?void 0:t.object)||"").trim();g&&(l.object=g);const y=String((t==null?void 0:t.since)||"").trim();y&&(l.since=y);const w=String((t==null?void 0:t.until)||"").trim();w&&(l.until=w);const k=String((t==null?void 0:t.active_at)||"").trim();k&&(l.active_at=k);const b=String((t==null?void 0:t.query_text)||"").trim();b&&(l.query_text=b),typeof(t==null?void 0:t.min_score)=="number"&&Number.isFinite(t.min_score)&&(l.min_score=Number(t.min_score));const S=await fetch(Lt(this._cfg.base_url,it("kg/query")),{method:"POST",headers:{"Content-Type":"application/json",...$t(this._cfg.auth_token)},body:JSON.stringify(l)});if(!S.ok)throw new Error(`kg_query failed: ${await Gn(S)}`);return await S.json()}async stream_ledger(t,n){var g;const r=Number((n==null?void 0:n.after)||0),o=n.on_step,l=n.signal,c=Lt(this._cfg.base_url,it(`runs/${encodeURIComponent(t)}/ledger/stream?after=${encodeURIComponent(String(r))}`)),u=await fetch(c,{headers:{Accept:"text/event-stream",...$t(this._cfg.auth_token)},signal:l});if(!u.ok)throw await ic(u,"The ledger stream was refused");if(!u.body)throw new Error("stream_ledger: response body is missing");(g=n.on_open)==null||g.call(n);const f=u.body.getReader(),h=new TextDecoder("utf-8"),m=new yM;for(;;){const{value:y,done:w}=await f.read();if(w)return;const k=h.decode(y,{stream:!0});m.push(k,b=>{if(!(b.event!=="step"||!b.data))try{const S=JSON.parse(b.data);S&&typeof S.cursor=="number"&&S.record&&o(S)}catch{}})}}}function xM(e,t=()=>({})){return async(n,r)=>{var u;const o=await e(n,{method:r.method,headers:{Accept:"application/json",...r.body!==void 0?{"Content-Type":"application/json"}:{},...t()},...r.body!==void 0?{body:JSON.stringify(r.body)}:{}}),l=await o.text();let c=null;try{c=l?JSON.parse(l):null}catch{c=null}if(!o.ok)throw new Error(typeof(c==null?void 0:c.detail)=="string"?c.detail:typeof((u=c==null?void 0:c.detail)==null?void 0:u.message)=="string"?c.detail.message:l||`Gateway request failed (${o.status})`);return c}}function bM({connected:e,request:t,value:n,onChange:r,disabled:o}){const[l,c]=_.useState(null),[u,f]=_.useState(null),h=JSON.stringify(n);_.useEffect(()=>{if(!e){c(null),f(null);return}let y=!0;return f(null),Af(t)(n).then(w=>y&&c(w)).catch(w=>y&&f(`Could not read your workspaces: ${g_(w)}`)),()=>{y=!1}},[e,h,t]);const m=_.useCallback(async y=>{const w=await Af(t)(y);c(w),r(y)},[t,r]),g=e?o?"The run is starting.":null:"Connect to your gateway to choose workspaces.";return s.jsx(Ab,{level:"run",idPrefix:"observer-launch-workspace",value:n,effective:l,onChange:m,loadError:e?u:g,unavailableReason:g})}function kM(e){const t=(e||"").trim();return t?{Authorization:`Bearer ${t}`}:{}}class jM{constructor(t){cs(this,"_cfg");this._cfg={...t,url:(t.url||"").trim()}}async call_tool(t){const n=String((t==null?void 0:t.name)||"").trim(),r=String((t==null?void 0:t.call_id)||(t==null?void 0:t.id)||Rs()),o=t!=null&&t.arguments&&typeof t.arguments=="object"?t.arguments:{};if(!n)return{call_id:r,name:"",success:!1,output:null,error:"Missing tool name"};const l={jsonrpc:"2.0",id:Rs(),method:"tools/call",params:{name:n,arguments:o}},c=await fetch(this._cfg.url,{method:"POST",headers:{"Content-Type":"application/json",...kM(this._cfg.auth_token)},body:JSON.stringify(l)});if(!c.ok)return{call_id:r,name:n,success:!1,output:null,error:`Worker HTTP ${c.status}`};const u=await c.json().catch(()=>null),f=u==null?void 0:u.result,h=!!(f!=null&&f.isError),g=(Array.isArray(f==null?void 0:f.content)?f.content:[]).find(w=>w&&w.type==="text"&&typeof w.text=="string"),y=(g==null?void 0:g.text)??"";return h?{call_id:r,name:n,success:!1,output:null,error:y||"Tool failed"}:{call_id:r,name:n,success:!0,output:y,error:null}}}class Nv{constructor(t,n){cs(this,"pending",[]);cs(this,"scheduled",!1);cs(this,"generation",0);this.schedule=t,this.on_flush=n}push(t){if(this.pending.push(t),this.scheduled)return;this.scheduled=!0;const n=this.generation;this.schedule(()=>{if(n!==this.generation)return;this.scheduled=!1;const r=this.pending;this.pending=[],r.length&&this.on_flush(r)})}reset(){this.generation+=1,this.pending=[],this.scheduled=!1}pending_count(){return this.pending.length}}function Cv(e,t=""){const n=String(e.role||"").trim(),r=String(e.automation_id||"").trim();return n==="occurrence"&&r&&r!==e.run_id?r:String(e.parent_run_id||t||"").trim()}function SM(e,t){const n=qn(e.updated_at||e.created_at)??0;return(qn(t.updated_at||t.created_at)??0)-n}function NM(e,t){const n=t.query.trim().toLowerCase(),r=[...e],o={};for(const y of r){const w=String(y.run_id||"").trim();w&&(o[w]=y)}for(const y of e){const w=Cv(y);if(String(y.role||"")==="occurrence"&&w&&!o[w]){const k={run_id:w,workflow_id:null,status:"",role:"controller",session_kind:"automation",automation_id:w,updated_at:y.updated_at??null,created_at:y.created_at??null};o[w]=k,r.push(k)}}const l={},c={};for(const y of r){const w=String(y.run_id||"").trim();if(!w)continue;const k=Cv(y,t.parent_hint?t.parent_hint(w):"");c[w]=k,k&&(l[k]||(l[k]=[])).push(y)}const u=y=>{const w=String(y.status||"").trim().toLowerCase();return t.filter==="all"?!0:t.filter==="active"?Uu(w):t.filter==="waiting"?w==="waiting":t.filter==="terminal"?$o(w):t.filter==="failed"?w==="failed":!0},f=y=>{if(!n)return!0;const w=String(y.workflow_id||y.schedule_target_workflow_id||"").trim(),k=w?t.workflow_label_by_id[w]||w:"";return[y.run_id,w,k,y.session_id,y.status,y.session_kind,y.automation_id].join(" ").toLowerCase().includes(n)},h=[];for(const y of r){const w=String(y.run_id||"").trim();if(!w)continue;const k=c[w];(!k||!o[k])&&h.push(w)}const m={},g=y=>{if(t.group_by==="workflow"){const k=String(y.schedule_target_workflow_id||y.workflow_id||"").trim()||"(unknown workflow)";return{key:k,label:t.workflow_label_by_id[k]||k}}if(t.group_by==="session"){const k=String(y.session_id||"").trim()||"(no session)";return{key:k,label:k}}const w=String(y.status||"").trim().toLowerCase()||"unknown";return Uu(w)?{key:"active",label:"Active"}:w==="failed"?{key:"failed",label:"Failed"}:$o(w)?{key:"finished",label:"Finished"}:{key:w,label:w}};for(const y of h){const w=o[y];if(!w)continue;const k=[...l[y]||[]].sort(SM),b=k.some(N=>u(N)&&f(N));if(!(u(w)&&f(w))&&!b)continue;const S=g(w);m[S.key]||(m[S.key]={key:S.key,label:S.label,rows:[]}),m[S.key].rows.push({run:w,children:k})}return Object.values(m).sort((y,w)=>{const k={active:0,waiting:1,failed:2,finished:3},b=k[y.key]??10,S=k[w.key]??10;return b!==S?b-S:y.label.localeCompare(w.label)})}const CM={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"},EM=[{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 $M(){const[e,t]=_.useState(!0);return s.jsxs("div",{className:"pin-legend",children:[s.jsxs("button",{className:"pin-legend-toggle mono",type:"button",onClick:()=>t(n=>!n),title:"Pin Type Legend",children:[e?"?":"×"," Pin Types"]}),e?null:s.jsxs("div",{className:"pin-legend-content",children:[EM.map(n=>s.jsxs("div",{className:"pin-legend-row",children:[s.jsx("span",{className:"pin-legend-shape",style:{color:CM[n.type]},children:n.shape}),s.jsx("span",{className:"pin-legend-label mono",children:n.label}),s.jsx("span",{className:"pin-legend-desc mono",children:n.description})]},n.type)),s.jsxs("div",{className:"pin-legend-rules mono",children:[s.jsx("strong",{children:"Connection Rules:"}),s.jsxs("ul",{children:[s.jsx("li",{children:"Execution connects to Execution only"}),s.jsx("li",{children:'"Any" type accepts all data types'}),s.jsx("li",{children:"Same types always compatible"}),s.jsx("li",{children:"Array and Object are interchangeable"}),s.jsx("li",{children:'"Tools" is compatible with Array (specialized string[])'})]})]})]})]})}function mn(e){return typeof e=="string"?e:e==null?"":String(e)}function Ev(e,t){const n=mn(e).trim();return n.length<=t?n:`${n.slice(0,Math.max(0,t-1))}…`}function K0(e){const t=mn(e==null?void 0:e.targetHandle),n=mn(e==null?void 0:e.sourceHandle);return!!(t==="exec-in"||n==="exec-out"||t.includes("exec")||n.includes("exec"))}function Y0(e){if(!e||typeof e!="object")return"";const t=e!=null&&e.data&&typeof e.data=="object"?e.data:{};return mn((t==null?void 0:t.nodeType)||(e==null?void 0:e.type)||"").trim()}function J0(e){if(!e||typeof e!="object")return"";const t=e!=null&&e.data&&typeof e.data=="object"?e.data:{},n=(t==null?void 0:t.subflowId)||(t==null?void 0:t.flowId),r=mn(n).trim();if(!r)return"";if(r.includes(":")){const o=r.split(":",2);if(o.length===2&&o[1])return o[1].trim()}return r}function AM(e){const t=mn(e==null?void 0:e.entryNode).trim();if(t)return t;const n=Array.isArray(e==null?void 0:e.nodes)?e.nodes:[];for(const r of n)if(Y0(r)==="on_flow_start"){const o=mn(r==null?void 0:r.id).trim();if(o)return o}return""}function jp(e){const t=e!=null&&e.position&&typeof e.position=="object"?e.position:{},n=typeof t.x=="number"?t.x:0,r=typeof t.y=="number"?t.y:0;return{x:n,y:r}}function rf(e,t){const n=mn(e).trim(),r=mn(t).trim();return r?n?`${n}::${r}`:r:""}function TM(e){const t=e.root&&typeof e.root=="object"?e.root:{};if(!e.expand_subflows)return t;const n=[],r=[],o=new Set,l=(c,u,f,h)=>{if(!c||typeof c!="object"||n.length>=e.max_nodes||r.length>=e.max_edges)return;const m=Array.isArray(c.nodes)?c.nodes:[],g=Array.isArray(c.edges)?c.edges:[];for(const y of m){const w=mn(y==null?void 0:y.id).trim();if(!w)continue;const k=rf(u,w);if(!k||o.has(k))continue;const b=jp(y),S={...y,id:k,position:{x:b.x+f.x,y:b.y+f.y}};if(n.push(S),o.add(k),n.length>=e.max_nodes)break}for(const y of g){if(!K0(y))continue;const w=mn(y==null?void 0:y.source).trim(),k=mn(y==null?void 0:y.target).trim();if(!w||!k)continue;const b=rf(u,w),S=rf(u,k);if(!b||!S)continue;const N=mn(y==null?void 0:y.id).trim(),R=N?`${b}->${S}::${N}`:`${b}->${S}`;if(r.push({...y,id:R,source:b,target:S}),r.length>=e.max_edges)break}if(!(h>=e.max_depth))for(const y of m){if(n.length>=e.max_nodes||r.length>=e.max_edges)return;if(Y0(y)!=="subflow")continue;const w=J0(y);if(!w)continue;const k=e.flow_by_id[w];if(!k||typeof k!="object")continue;const b=rf(u,mn(y==null?void 0:y.id));if(!b)continue;const S=AM(k);if(!S)continue;const R=(Array.isArray(k.nodes)?k.nodes:[]).find(re=>mn(re==null?void 0:re.id).trim()===S)||null;if(!R)continue;const T=jp(y),A=jp(R),J={x:T.x+f.x+240-A.x,y:T.y+f.y+0-A.y},K=rf(b,S);r.push({id:`${b}=>${K}`,source:b,target:K,sourceHandle:"exec-out",targetHandle:"exec-in"}),l(k,b,J,h+1)}};return l(t,"",{x:0,y:0},0),{...t,id:mn(t.id),nodes:n,edges:r}}function MM(e){const t=mn(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 RM(e){const t=e.nodes.filter(l=>e.keep_id(l.id)),n=new Set(t.map(l=>l.id)),r={};for(const l of e.edges)r[l.source]||(r[l.source]=[]),r[l.source].push(l.target);const o=new Map;for(const l of t){const c=new Set,u=(r[l.id]||[]).slice();for(;u.length;){const f=u.pop();if(!f||c.has(f))continue;if(c.add(f),n.has(f)){const m=`${l.id}->${f}`;o.has(m)||o.set(m,{id:m,source:l.id,target:f});continue}const h=r[f]||[];for(const m of h)c.has(m)||u.push(m);if(o.size>=e.max_edges)break}if(o.size>=e.max_edges)break}return{nodes:t,edges:Array.from(o.values())}}function $v(e,t){const o=Math.max(t.w*8,160),l=Math.max(t.h*8,120),c=Math.max(160,Math.min(o,e.w)),u=Math.max(120,Math.min(l,e.h));return{x:e.x,y:e.y,w:c,h:u}}function LM(e){const t=typeof e.now_ms=="number"?e.now_ms:Date.now(),n=e.flow,r=mn(e.active_node_id),o=e.recent_nodes||{},l=e.visited_nodes||{},c=e.highlight_path===!0,u=typeof e.vertical_compact=="number"?Math.max(.4,Math.min(1,e.vertical_compact)):.78,{nodes:f,edges:h,bounds:m}=_.useMemo(()=>{const F=TM({root:n||{},flow_by_id:e.flow_by_id||{},expand_subflows:e.expand_subflows===!0,max_depth:3,max_nodes:700,max_edges:900}),U=Array.isArray(F.nodes)?F.nodes:[],V=Array.isArray(F.edges)?F.edges:[];let O=[];for(const le of U){const be=mn(le==null?void 0:le.id).trim();if(!be)continue;const Pe=le!=null&&le.position&&typeof le.position=="object"?le.position:{},me=typeof Pe.x=="number"?Pe.x:0,Ce=typeof Pe.y=="number"?Pe.y:0,Te=le!=null&&le.data&&typeof le.data=="object"?le.data:{},Je=mn((Te==null?void 0:Te.label)||(le==null?void 0:le.label)||be)||be,rt=mn((Te==null?void 0:Te.nodeType)||(le==null?void 0:le.type)||"unknown")||"unknown",ht=mn((Te==null?void 0:Te.headerColor)||(le==null?void 0:le.headerColor)||"")||"",lt=Te!=null&&Te.eventConfig&&typeof Te.eventConfig=="object"?Te.eventConfig:null,Ct=lt&&typeof lt.schedule=="string"?mn(lt.schedule).trim():"",Xt=lt&&typeof lt.recurrent=="boolean"?!!lt.recurrent:void 0,Pn=rt==="subflow"?J0(le):"",zt=Ct||Xt!==void 0||Pn?{schedule:Ct||void 0,recurrent:Xt,subflow_id:Pn||void 0}:void 0;O.push({id:be,x:me,y:Ce,label:Je,type:rt,color:ht,meta:zt})}const H={};for(const le of O)H[le.id]=le;let Y=[];for(const le of V){if(!K0(le))continue;const be=mn(le==null?void 0:le.source).trim(),Pe=mn(le==null?void 0:le.target).trim();!be||!Pe||Y.push({id:mn((le==null?void 0:le.id)||`${be}->${Pe}`),source:be,target:Pe})}const ae=new Set(O.map(le=>le.id));if(Y=Y.filter(le=>ae.has(le.source)&&ae.has(le.target)),e.simplify===!0){const be=RM({nodes:O,edges:Y,keep_id:Pe=>{if(r&&Pe===r)return!0;const me=H[Pe];if(!me)return!1;const Ce=mn(me.type).trim().toLowerCase();return Ce==="on_flow_start"||Ce==="on_flow_end"||Ce==="subflow"?!0:!MM(Ce)},max_edges:900});O=be.nodes,Y=be.edges}if(e.prefer_vertical===!0&&O.length>=2){const le=O.map(Te=>Te.x),be=O.map(Te=>Te.y),Pe=Math.max(...le)-Math.min(...le),me=Math.max(...be)-Math.min(...be);Pe>=me&&(O=O.map(Te=>({...Te,x:Te.y,y:Te.x})));const Ce=Math.min(...O.map(Te=>Te.y));O=O.map(Te=>({...Te,y:Ce+(Te.y-Ce)*u}))}const ie={};for(const le of O)ie[le.id]=le;const _e=160,fe=56,ge=_e/2,Ne=fe/2;let Ue=0,We=0,ut=0,Fe=0;O.length&&(Ue=Math.min(...O.map(le=>le.x)),We=Math.min(...O.map(le=>le.y)),ut=Math.max(...O.map(le=>le.x+_e)),Fe=Math.max(...O.map(le=>le.y+fe)));let et=0;if(Y.length){const le=new Set(Y.map(be=>`${be.source}->${be.target}`));for(const be of Y){if(!le.has(`${be.target}->${be.source}`))continue;const Pe=ie[be.source],me=ie[be.target];if(!Pe||!me)continue;const Ce=Pe.x+ge,Te=Pe.y+Ne,Je=me.x+ge,rt=me.y+Ne,ht=Math.max(1,Math.hypot(Je-Ce,rt-Te)),lt=Math.max(28,Math.min(72,ht*.14)),Ct=Math.min(200,lt*3.5);Ct>et&&(et=Ct)}}const $e=60+et,Ve={x:Ue-$e,y:We-$e,w:ut-Ue+$e*2,h:Fe-We+$e*2,node_w:_e,node_h:fe};return{nodes:O,edges:Y,bounds:Ve}},[n,e.flow_by_id,e.expand_subflows,e.simplify,e.prefer_vertical,r,u]);if(!n)return s.jsx("div",{className:"graph_empty mono",children:"(no graph loaded)"});const g=_.useRef(null),[y,w]=_.useState(()=>({x:m.x,y:m.y,w:m.w,h:m.h})),k=_.useRef(y);k.current=y,_.useEffect(()=>{w({x:m.x,y:m.y,w:m.w,h:m.h})},[m.x,m.y,m.w,m.h]);const b=_.useRef(new Map),S=_.useRef(null),N=`${y.x} ${y.y} ${y.w} ${y.h}`,R={};for(const F of f)R[F.id]=F;const T=F=>{let U=mn(F).trim();if(!U)return"";if(R[U])return U;for(;U.includes("::");)if(U=U.slice(0,Math.max(0,U.lastIndexOf("::"))),R[U])return U;return""},A=T(r),W={};for(const[F,U]of Object.entries(o)){if(typeof U!="number")continue;const V=T(F);V&&(W[V]=Math.max(W[V]||0,U))}const z={};if(c)for(const[F,U]of Object.entries(l)){if(typeof U!="number")continue;const V=T(F);V&&(z[V]=typeof z[V]=="number"?Math.min(z[V],U):U)}const J=mn(e.schedule_next_in).trim(),K=mn(e.schedule_interval).trim(),re=e.node_last_ms&&typeof e.node_last_ms=="object"?e.node_last_ms:{},te=F=>{try{const U=new Date(F),V=String(U.getHours()).padStart(2,"0"),O=String(U.getMinutes()).padStart(2,"0");return`${V}:${O}`}catch{return""}},Q=(F,U)=>{var Y,ae;const V=mn((Y=F.meta)==null?void 0:Y.schedule).trim();if(!(((ae=F.meta)==null?void 0:ae.recurrent)===!0))return U&&J?`next ${J}`:V&&V.length<=12&&!V.includes("T")?`in ${V}`:"scheduled";const H=V||K;return H?U&&J?`${H} • next ${J}`:`every ${H}`:U&&J?`next ${J}`:"scheduled"},D=F=>{var _e;const U=mn((_e=F.meta)==null?void 0:_e.subflow_id).trim(),V=U&&e.flow_by_id?e.flow_by_id[U]:null,H=mn(V==null?void 0:V.name).trim()||U||F.label||F.id,Y=typeof re[F.id]=="number"?Number(re[F.id]):null,ae=Y!==null?te(Y):"",ie=ae?`last ${ae}`:"subflow";return{label:H,sub:ie}},$=(F,U,V)=>{const O=V||k.current,H=g.current;if(!H)return{x:F,y:U};const Y=H.getBoundingClientRect(),ae=Y.width>0?(F-Y.left)/Y.width:0,ie=Y.height>0?(U-Y.top)/Y.height:0;return{x:O.x+ae*O.w,y:O.y+ie*O.h}},E=(F,U,V)=>{const O=V||k.current,H=Math.max(.12,Math.min(8,U)),Y=O.w*H,ae=O.h*H,ie=O.w>0?(F.x-O.x)/O.w:.5,_e=O.h>0?(F.y-O.y)/O.h:.5,fe=F.x-ie*Y,ge=F.y-_e*ae;w($v({x:fe,y:ge,w:Y,h:ae},m))},L=(F,U,V)=>{const O=V||k.current,H=g.current;if(!H)return;const Y=H.getBoundingClientRect(),ae=.88,ie=Y.width>0?F/Y.width*O.w*ae:0,_e=Y.height>0?U/Y.height*O.h*ae:0;w(fe=>$v({x:(V||fe).x-ie,y:(V||fe).y-_e,w:(V||fe).w,h:(V||fe).h},m))},M=_.useMemo(()=>{const F=new Set;for(const U of h)F.add(`${U.source}->${U.target}`);return F},[h]),ee=(F,U,V,O)=>{const H=m.node_w,Y=m.node_h,ae=Math.abs(V),ie=Math.abs(O);if(ae<1e-6&&ie<1e-6)return{x:F,y:U};const _e=ae>1e-6?H/2/ae:Number.POSITIVE_INFINITY,fe=ie>1e-6?Y/2/ie:Number.POSITIVE_INFINITY,ge=Math.min(_e,fe);return{x:F+V*ge,y:U+O*ge}};return s.jsxs("div",{className:"graph_wrap",children:[s.jsxs("div",{className:"graph_corner",children:[s.jsxs("div",{className:"graph_corner_buttons",children:[s.jsx("button",{className:"btn graph_corner_btn",type:"button",onClick:()=>w({x:m.x,y:m.y,w:m.w,h:m.h}),title:"Recenter",children:"⤢"}),s.jsx("button",{className:"btn graph_corner_btn",type:"button",onClick:()=>{const F=g.current;if(!F)return;const U=F.getBoundingClientRect(),V=$(U.left+U.width/2,U.top+U.height/2);E(V,.84)},title:"Zoom in",children:"+"}),s.jsx("button",{className:"btn graph_corner_btn",type:"button",onClick:()=>{const F=g.current;if(!F)return;const U=F.getBoundingClientRect(),V=$(U.left+U.width/2,U.top+U.height/2);E(V,1.18)},title:"Zoom out",children:"−"})]}),s.jsx($M,{})]}),s.jsxs("svg",{ref:g,className:"graph_svg",viewBox:N,role:"img","aria-label":"Workflow execution graph",onWheel:F=>{F.preventDefault();const U=$(F.clientX,F.clientY),V=typeof F.deltaY=="number"?F.deltaY:0,O=typeof F.deltaMode=="number"?Number(F.deltaMode):0,H=O===1?V*24:O===2?V*800:V,Y=45e-5*1.15*1.1;let ae=Math.exp(H*Y);ae=Math.max(.86,Math.min(1.16,ae)),E(U,ae)},onPointerDown:F=>{var V,O;(O=(V=F.currentTarget).setPointerCapture)==null||O.call(V,F.pointerId),b.current.set(F.pointerId,{x:F.clientX,y:F.clientY});const U=Array.from(b.current.values());if(U.length===1)S.current={mode:"pan",start_view:k.current,start_client:{x:F.clientX,y:F.clientY},start_dist:0,anchor_svg:{x:0,y:0}};else if(U.length>=2){const H=U[0],Y=U[1],ae=H.x-Y.x,ie=H.y-Y.y,_e=Math.max(1,Math.hypot(ae,ie)),fe={x:(H.x+Y.x)/2,y:(H.y+Y.y)/2},ge=k.current;S.current={mode:"pinch",start_view:ge,start_client:fe,start_dist:_e,anchor_svg:$(fe.x,fe.y,ge)}}},onPointerMove:F=>{if(!b.current.has(F.pointerId))return;b.current.set(F.pointerId,{x:F.clientX,y:F.clientY});const U=S.current;if(!U)return;const V=Array.from(b.current.values());if(U.mode==="pan"&&V.length===1){const O=F.clientX-U.start_client.x,H=F.clientY-U.start_client.y;L(O,H,U.start_view)}else if(U.mode==="pinch"&&V.length>=2){const O=V[0],H=V[1],Y=O.x-H.x,ae=O.y-H.y,ie=Math.max(1,Math.hypot(Y,ae)),_e=U.start_dist/ie;E(U.anchor_svg,_e,U.start_view)}},onPointerUp:F=>{b.current.delete(F.pointerId),b.current.size===0&&(S.current=null)},onPointerCancel:F=>{b.current.delete(F.pointerId),b.current.size===0&&(S.current=null)},children:[s.jsxs("defs",{children:[s.jsx("marker",{id:"arrow",viewBox:"0 0 10 10",refX:"9",refY:"5",markerWidth:"8",markerHeight:"8",orient:"auto-start-reverse",children:s.jsx("path",{d:"M 0 0 L 10 5 L 0 10 z",fill:"rgba(148,163,184,0.55)"})}),s.jsxs("filter",{id:"glow",children:[s.jsx("feGaussianBlur",{stdDeviation:"3",result:"coloredBlur"}),s.jsxs("feMerge",{children:[s.jsx("feMergeNode",{in:"coloredBlur"}),s.jsx("feMergeNode",{in:"SourceGraphic"})]})]})]}),h.map(F=>{const U=R[F.source],V=R[F.target];if(!U||!V)return null;const O=U.x+m.node_w/2,H=U.y+m.node_h/2,Y=V.x+m.node_w/2,ae=V.y+m.node_h/2,ie=Y-O,_e=ae-H,fe=ee(O,H,ie,_e),ge=ee(Y,ae,-ie,-_e),Ne=F.source!==F.target&&M.has(`${F.target}->${F.source}`),Ue=Math.max(1,Math.hypot(ie,_e)),We=-_e/Ue,ut=ie/Ue,Fe=String(F.source)<String(F.target)?1:-1,$e=Math.abs(ie)>=Math.abs(_e)?ie>=0:_e>=0,Ve=!Ne||$e,le=Math.max(28,Math.min(72,Ue*.14)),be=Math.min(200,le*3.5),Pe=Ne&&!Ve?be*Fe:0,me=(fe.x+ge.x)/2+We*Pe,Ce=(fe.y+ge.y)/2+ut*Pe,Te=Ne&&!Ve?`M ${fe.x} ${fe.y} Q ${me} ${Ce} ${ge.x} ${ge.y}`:`M ${fe.x} ${fe.y} L ${ge.x} ${ge.y}`,Je=c&&z&&z[F.source]!==void 0&&z[F.target]!==void 0;return s.jsx("path",{d:Te,className:`graph_edge ${Je?"visited":""}`,markerEnd:"url(#arrow)",fill:"none"},F.id)}),f.map(F=>{const V=(typeof W[F.id]=="number"?W[F.id]:0)>t,O=A&&F.id===A,H=c&&z&&z[F.id]!==void 0,Y=`graph_node ${O?"active":V?"recent":""} ${H?"visited":""}`,ae=F.color||"rgba(255,255,255,0.16)";let ie=F.label||F.id,_e=F.type;if(F.type==="on_schedule")_e=Q(F,!!O);else if(F.type==="subflow"){const Ne=D(F);ie=Ne.label,_e=Ne.sub}const fe=Ev(ie,22),ge=Ev(_e,22);return s.jsxs("g",{className:Y,transform:`translate(${F.x}, ${F.y})`,children:[s.jsx("rect",{className:"graph_node_bg",width:m.node_w,height:m.node_h,rx:12,ry:12}),s.jsx("rect",{className:"graph_node_bar",width:m.node_w,height:6,rx:12,ry:12,fill:ae}),s.jsx("text",{className:"graph_node_label",x:12,y:28,children:fe}),s.jsx("text",{className:"graph_node_type",x:12,y:46,children:ge}),F.type==="on_schedule"?s.jsx("text",{className:"graph_node_icon",x:m.node_w-18,y:18,children:"⏰"}):null]},F.id)})]})]})}function Vs(e){if(typeof e=="string"||typeof e=="number")return""+e;let t="";if(Array.isArray(e))for(let n=0,r;n<e.length;n++)(r=Vs(e[n]))!==""&&(t+=(t&&" ")+r);else for(let n in e)e[n]&&(t+=(t&&" ")+n);return t}var Sp={exports:{}},Np={},Cp={exports:{}},Ep={};/**
|
|
133
|
-
* @license React
|
|
134
|
-
* use-sync-external-store-shim.production.js
|
|
135
|
-
*
|
|
136
|
-
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
|
137
|
-
*
|
|
138
|
-
* This source code is licensed under the MIT license found in the
|
|
139
|
-
* LICENSE file in the root directory of this source tree.
|
|
140
|
-
*/var Av;function IM(){if(Av)return Ep;Av=1;var e=Gf();function t(g,y){return g===y&&(g!==0||1/g===1/y)||g!==g&&y!==y}var n=typeof Object.is=="function"?Object.is:t,r=e.useState,o=e.useEffect,l=e.useLayoutEffect,c=e.useDebugValue;function u(g,y){var w=y(),k=r({inst:{value:w,getSnapshot:y}}),b=k[0].inst,S=k[1];return l(function(){b.value=w,b.getSnapshot=y,f(b)&&S({inst:b})},[g,w,y]),o(function(){return f(b)&&S({inst:b}),g(function(){f(b)&&S({inst:b})})},[g]),c(w),w}function f(g){var y=g.getSnapshot;g=g.value;try{var w=y();return!n(g,w)}catch{return!0}}function h(g,y){return y()}var m=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?h:u;return Ep.useSyncExternalStore=e.useSyncExternalStore!==void 0?e.useSyncExternalStore:m,Ep}var Tv;function OM(){return Tv||(Tv=1,Cp.exports=IM()),Cp.exports}/**
|
|
141
|
-
* @license React
|
|
142
|
-
* use-sync-external-store-shim/with-selector.production.js
|
|
143
|
-
*
|
|
144
|
-
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
|
145
|
-
*
|
|
146
|
-
* This source code is licensed under the MIT license found in the
|
|
147
|
-
* LICENSE file in the root directory of this source tree.
|
|
148
|
-
*/var Mv;function PM(){if(Mv)return Np;Mv=1;var e=Gf(),t=OM();function n(h,m){return h===m&&(h!==0||1/h===1/m)||h!==h&&m!==m}var r=typeof Object.is=="function"?Object.is:n,o=t.useSyncExternalStore,l=e.useRef,c=e.useEffect,u=e.useMemo,f=e.useDebugValue;return Np.useSyncExternalStoreWithSelector=function(h,m,g,y,w){var k=l(null);if(k.current===null){var b={hasValue:!1,value:null};k.current=b}else b=k.current;k=u(function(){function N(z){if(!R){if(R=!0,T=z,z=y(z),w!==void 0&&b.hasValue){var J=b.value;if(w(J,z))return A=J}return A=z}if(J=A,r(T,z))return J;var K=y(z);return w!==void 0&&w(J,K)?(T=z,J):(T=z,A=K)}var R=!1,T,A,W=g===void 0?null:g;return[function(){return N(m())},W===null?void 0:function(){return N(W())}]},[m,g,y,w]);var S=o(h,k[0],k[1]);return c(function(){b.hasValue=!0,b.value=S},[S]),f(S),S},Np}var Rv;function DM(){return Rv||(Rv=1,Sp.exports=PM()),Sp.exports}var FM=DM();const zM=Gg(FM),BM={},Lv=e=>{let t;const n=new Set,r=(m,g)=>{const y=typeof m=="function"?m(t):m;if(!Object.is(y,t)){const w=t;t=g??(typeof y!="object"||y===null)?y:Object.assign({},t,y),n.forEach(k=>k(t,w))}},o=()=>t,f={setState:r,getState:o,getInitialState:()=>h,subscribe:m=>(n.add(m),()=>n.delete(m)),destroy:()=>{(BM?"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()}},h=t=e(r,o,f);return f},UM=e=>e?Lv(e):Lv,{useDebugValue:WM}=xe,{useSyncExternalStoreWithSelector:qM}=zM,HM=e=>e;function X0(e,t=HM,n){const r=qM(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return WM(r),r}const Iv=(e,t)=>{const n=UM(e),r=(o,l=t)=>X0(n,o,l);return Object.assign(r,n),r},VM=(e,t)=>e?Iv(e,t):Iv;function Os(e,t){if(Object.is(e,t))return!0;if(typeof e!="object"||e===null||typeof t!="object"||t===null)return!1;if(e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(const[r,o]of e)if(!Object.is(o,t.get(r)))return!1;return!0}if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(const r of e)if(!t.has(r))return!1;return!0}const n=Object.keys(e);if(n.length!==Object.keys(t).length)return!1;for(const r of n)if(!Object.prototype.hasOwnProperty.call(t,r)||!Object.is(e[r],t[r]))return!1;return!0}var GM={value:()=>{}};function v_(){for(var e=0,t=arguments.length,n={},r;e<t;++e){if(!(r=arguments[e]+"")||r in n||/[\s.]/.test(r))throw new Error("illegal type: "+r);n[r]=[]}return new Pm(n)}function Pm(e){this._=e}function KM(e,t){return e.trim().split(/^|\s+/).map(function(n){var r="",o=n.indexOf(".");if(o>=0&&(r=n.slice(o+1),n=n.slice(0,o)),n&&!t.hasOwnProperty(n))throw new Error("unknown type: "+n);return{type:n,name:r}})}Pm.prototype=v_.prototype={constructor:Pm,on:function(e,t){var n=this._,r=KM(e+"",n),o,l=-1,c=r.length;if(arguments.length<2){for(;++l<c;)if((o=(e=r[l]).type)&&(o=YM(n[o],e.name)))return o;return}if(t!=null&&typeof t!="function")throw new Error("invalid callback: "+t);for(;++l<c;)if(o=(e=r[l]).type)n[o]=Ov(n[o],e.name,t);else if(t==null)for(o in n)n[o]=Ov(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 Pm(e)},call:function(e,t){if((o=arguments.length-2)>0)for(var n=new Array(o),r=0,o,l;r<o;++r)n[r]=arguments[r+2];if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(l=this._[e],r=0,o=l.length;r<o;++r)l[r].value.apply(t,n)},apply:function(e,t,n){if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(var r=this._[e],o=0,l=r.length;o<l;++o)r[o].value.apply(t,n)}};function YM(e,t){for(var n=0,r=e.length,o;n<r;++n)if((o=e[n]).name===t)return o.value}function Ov(e,t,n){for(var r=0,o=e.length;r<o;++r)if(e[r].name===t){e[r]=GM,e=e.slice(0,r).concat(e.slice(r+1));break}return n!=null&&e.push({name:t,value:n}),e}var Sg="http://www.w3.org/1999/xhtml";const Pv={svg:"http://www.w3.org/2000/svg",xhtml:Sg,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function x_(e){var t=e+="",n=t.indexOf(":");return n>=0&&(t=e.slice(0,n))!=="xmlns"&&(e=e.slice(n+1)),Pv.hasOwnProperty(t)?{space:Pv[t],local:e}:e}function JM(e){return function(){var t=this.ownerDocument,n=this.namespaceURI;return n===Sg&&t.documentElement.namespaceURI===Sg?t.createElement(e):t.createElementNS(n,e)}}function XM(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function Z0(e){var t=x_(e);return(t.local?XM:JM)(t)}function ZM(){}function yy(e){return e==null?ZM:function(){return this.querySelector(e)}}function QM(e){typeof e!="function"&&(e=yy(e));for(var t=this._groups,n=t.length,r=new Array(n),o=0;o<n;++o)for(var l=t[o],c=l.length,u=r[o]=new Array(c),f,h,m=0;m<c;++m)(f=l[m])&&(h=e.call(f,f.__data__,m,l))&&("__data__"in f&&(h.__data__=f.__data__),u[m]=h);return new ri(r,this._parents)}function eR(e){return e==null?[]:Array.isArray(e)?e:Array.from(e)}function tR(){return[]}function Q0(e){return e==null?tR:function(){return this.querySelectorAll(e)}}function nR(e){return function(){return eR(e.apply(this,arguments))}}function sR(e){typeof e=="function"?e=nR(e):e=Q0(e);for(var t=this._groups,n=t.length,r=[],o=[],l=0;l<n;++l)for(var c=t[l],u=c.length,f,h=0;h<u;++h)(f=c[h])&&(r.push(e.call(f,f.__data__,h,c)),o.push(f));return new ri(r,o)}function ek(e){return function(){return this.matches(e)}}function tk(e){return function(t){return t.matches(e)}}var rR=Array.prototype.find;function iR(e){return function(){return rR.call(this.children,e)}}function oR(){return this.firstElementChild}function aR(e){return this.select(e==null?oR:iR(typeof e=="function"?e:tk(e)))}var lR=Array.prototype.filter;function cR(){return Array.from(this.children)}function uR(e){return function(){return lR.call(this.children,e)}}function dR(e){return this.selectAll(e==null?cR:uR(typeof e=="function"?e:tk(e)))}function fR(e){typeof e!="function"&&(e=ek(e));for(var t=this._groups,n=t.length,r=new Array(n),o=0;o<n;++o)for(var l=t[o],c=l.length,u=r[o]=[],f,h=0;h<c;++h)(f=l[h])&&e.call(f,f.__data__,h,l)&&u.push(f);return new ri(r,this._parents)}function nk(e){return new Array(e.length)}function hR(){return new ri(this._enter||this._groups.map(nk),this._parents)}function Qm(e,t){this.ownerDocument=e.ownerDocument,this.namespaceURI=e.namespaceURI,this._next=null,this._parent=e,this.__data__=t}Qm.prototype={constructor:Qm,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 mR(e){return function(){return e}}function _R(e,t,n,r,o,l){for(var c=0,u,f=t.length,h=l.length;c<h;++c)(u=t[c])?(u.__data__=l[c],r[c]=u):n[c]=new Qm(e,l[c]);for(;c<f;++c)(u=t[c])&&(o[c]=u)}function pR(e,t,n,r,o,l,c){var u,f,h=new Map,m=t.length,g=l.length,y=new Array(m),w;for(u=0;u<m;++u)(f=t[u])&&(y[u]=w=c.call(f,f.__data__,u,t)+"",h.has(w)?o[u]=f:h.set(w,f));for(u=0;u<g;++u)w=c.call(e,l[u],u,l)+"",(f=h.get(w))?(r[u]=f,f.__data__=l[u],h.delete(w)):n[u]=new Qm(e,l[u]);for(u=0;u<m;++u)(f=t[u])&&h.get(y[u])===f&&(o[u]=f)}function gR(e){return e.__data__}function yR(e,t){if(!arguments.length)return Array.from(this,gR);var n=t?pR:_R,r=this._parents,o=this._groups;typeof e!="function"&&(e=mR(e));for(var l=o.length,c=new Array(l),u=new Array(l),f=new Array(l),h=0;h<l;++h){var m=r[h],g=o[h],y=g.length,w=wR(e.call(m,m&&m.__data__,h,r)),k=w.length,b=u[h]=new Array(k),S=c[h]=new Array(k),N=f[h]=new Array(y);n(m,g,b,S,N,w,t);for(var R=0,T=0,A,W;R<k;++R)if(A=b[R]){for(R>=T&&(T=R+1);!(W=S[T])&&++T<k;);A._next=W||null}}return c=new ri(c,r),c._enter=u,c._exit=f,c}function wR(e){return typeof e=="object"&&"length"in e?e:Array.from(e)}function vR(){return new ri(this._exit||this._groups.map(nk),this._parents)}function xR(e,t,n){var r=this.enter(),o=this,l=this.exit();return typeof e=="function"?(r=e(r),r&&(r=r.selection())):r=r.append(e+""),t!=null&&(o=t(o),o&&(o=o.selection())),n==null?l.remove():n(l),r&&o?r.merge(o).order():o}function bR(e){for(var t=e.selection?e.selection():e,n=this._groups,r=t._groups,o=n.length,l=r.length,c=Math.min(o,l),u=new Array(o),f=0;f<c;++f)for(var h=n[f],m=r[f],g=h.length,y=u[f]=new Array(g),w,k=0;k<g;++k)(w=h[k]||m[k])&&(y[k]=w);for(;f<o;++f)u[f]=n[f];return new ri(u,this._parents)}function kR(){for(var e=this._groups,t=-1,n=e.length;++t<n;)for(var r=e[t],o=r.length-1,l=r[o],c;--o>=0;)(c=r[o])&&(l&&c.compareDocumentPosition(l)^4&&l.parentNode.insertBefore(c,l),l=c);return this}function jR(e){e||(e=SR);function t(g,y){return g&&y?e(g.__data__,y.__data__):!g-!y}for(var n=this._groups,r=n.length,o=new Array(r),l=0;l<r;++l){for(var c=n[l],u=c.length,f=o[l]=new Array(u),h,m=0;m<u;++m)(h=c[m])&&(f[m]=h);f.sort(t)}return new ri(o,this._parents).order()}function SR(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}function NR(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this}function CR(){return Array.from(this)}function ER(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var r=e[t],o=0,l=r.length;o<l;++o){var c=r[o];if(c)return c}return null}function $R(){let e=0;for(const t of this)++e;return e}function AR(){return!this.node()}function TR(e){for(var t=this._groups,n=0,r=t.length;n<r;++n)for(var o=t[n],l=0,c=o.length,u;l<c;++l)(u=o[l])&&e.call(u,u.__data__,l,o);return this}function MR(e){return function(){this.removeAttribute(e)}}function RR(e){return function(){this.removeAttributeNS(e.space,e.local)}}function LR(e,t){return function(){this.setAttribute(e,t)}}function IR(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function OR(e,t){return function(){var n=t.apply(this,arguments);n==null?this.removeAttribute(e):this.setAttribute(e,n)}}function PR(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 DR(e,t){var n=x_(e);if(arguments.length<2){var r=this.node();return n.local?r.getAttributeNS(n.space,n.local):r.getAttribute(n)}return this.each((t==null?n.local?RR:MR:typeof t=="function"?n.local?PR:OR:n.local?IR:LR)(n,t))}function sk(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function FR(e){return function(){this.style.removeProperty(e)}}function zR(e,t,n){return function(){this.style.setProperty(e,t,n)}}function BR(e,t,n){return function(){var r=t.apply(this,arguments);r==null?this.style.removeProperty(e):this.style.setProperty(e,r,n)}}function UR(e,t,n){return arguments.length>1?this.each((t==null?FR:typeof t=="function"?BR:zR)(e,t,n??"")):qu(this.node(),e)}function qu(e,t){return e.style.getPropertyValue(t)||sk(e).getComputedStyle(e,null).getPropertyValue(t)}function WR(e){return function(){delete this[e]}}function qR(e,t){return function(){this[e]=t}}function HR(e,t){return function(){var n=t.apply(this,arguments);n==null?delete this[e]:this[e]=n}}function VR(e,t){return arguments.length>1?this.each((t==null?WR:typeof t=="function"?HR:qR)(e,t)):this.node()[e]}function rk(e){return e.trim().split(/^|\s+/)}function wy(e){return e.classList||new ik(e)}function ik(e){this._node=e,this._names=rk(e.getAttribute("class")||"")}ik.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 ok(e,t){for(var n=wy(e),r=-1,o=t.length;++r<o;)n.add(t[r])}function ak(e,t){for(var n=wy(e),r=-1,o=t.length;++r<o;)n.remove(t[r])}function GR(e){return function(){ok(this,e)}}function KR(e){return function(){ak(this,e)}}function YR(e,t){return function(){(t.apply(this,arguments)?ok:ak)(this,e)}}function JR(e,t){var n=rk(e+"");if(arguments.length<2){for(var r=wy(this.node()),o=-1,l=n.length;++o<l;)if(!r.contains(n[o]))return!1;return!0}return this.each((typeof t=="function"?YR:t?GR:KR)(n,t))}function XR(){this.textContent=""}function ZR(e){return function(){this.textContent=e}}function QR(e){return function(){var t=e.apply(this,arguments);this.textContent=t??""}}function eL(e){return arguments.length?this.each(e==null?XR:(typeof e=="function"?QR:ZR)(e)):this.node().textContent}function tL(){this.innerHTML=""}function nL(e){return function(){this.innerHTML=e}}function sL(e){return function(){var t=e.apply(this,arguments);this.innerHTML=t??""}}function rL(e){return arguments.length?this.each(e==null?tL:(typeof e=="function"?sL:nL)(e)):this.node().innerHTML}function iL(){this.nextSibling&&this.parentNode.appendChild(this)}function oL(){return this.each(iL)}function aL(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function lL(){return this.each(aL)}function cL(e){var t=typeof e=="function"?e:Z0(e);return this.select(function(){return this.appendChild(t.apply(this,arguments))})}function uL(){return null}function dL(e,t){var n=typeof e=="function"?e:Z0(e),r=t==null?uL:typeof t=="function"?t:yy(t);return this.select(function(){return this.insertBefore(n.apply(this,arguments),r.apply(this,arguments)||null)})}function fL(){var e=this.parentNode;e&&e.removeChild(this)}function hL(){return this.each(fL)}function mL(){var e=this.cloneNode(!1),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function _L(){var e=this.cloneNode(!0),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function pL(e){return this.select(e?_L:mL)}function gL(e){return arguments.length?this.property("__data__",e):this.node().__data__}function yL(e){return function(t){e.call(this,t,this.__data__)}}function wL(e){return e.trim().split(/^|\s+/).map(function(t){var n="",r=t.indexOf(".");return r>=0&&(n=t.slice(r+1),t=t.slice(0,r)),{type:t,name:n}})}function vL(e){return function(){var t=this.__on;if(t){for(var n=0,r=-1,o=t.length,l;n<o;++n)l=t[n],(!e.type||l.type===e.type)&&l.name===e.name?this.removeEventListener(l.type,l.listener,l.options):t[++r]=l;++r?t.length=r:delete this.__on}}}function xL(e,t,n){return function(){var r=this.__on,o,l=yL(t);if(r){for(var c=0,u=r.length;c<u;++c)if((o=r[c]).type===e.type&&o.name===e.name){this.removeEventListener(o.type,o.listener,o.options),this.addEventListener(o.type,o.listener=l,o.options=n),o.value=t;return}}this.addEventListener(e.type,l,n),o={type:e.type,name:e.name,value:t,listener:l,options:n},r?r.push(o):this.__on=[o]}}function bL(e,t,n){var r=wL(e+""),o,l=r.length,c;if(arguments.length<2){var u=this.node().__on;if(u){for(var f=0,h=u.length,m;f<h;++f)for(o=0,m=u[f];o<l;++o)if((c=r[o]).type===m.type&&c.name===m.name)return m.value}return}for(u=t?xL:vL,o=0;o<l;++o)this.each(u(r[o],t,n));return this}function lk(e,t,n){var r=sk(e),o=r.CustomEvent;typeof o=="function"?o=new o(t,n):(o=r.document.createEvent("Event"),n?(o.initEvent(t,n.bubbles,n.cancelable),o.detail=n.detail):o.initEvent(t,!1,!1)),e.dispatchEvent(o)}function kL(e,t){return function(){return lk(this,e,t)}}function jL(e,t){return function(){return lk(this,e,t.apply(this,arguments))}}function SL(e,t){return this.each((typeof t=="function"?jL:kL)(e,t))}function*NL(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var r=e[t],o=0,l=r.length,c;o<l;++o)(c=r[o])&&(yield c)}var ck=[null];function ri(e,t){this._groups=e,this._parents=t}function th(){return new ri([[document.documentElement]],ck)}function CL(){return this}ri.prototype=th.prototype={constructor:ri,select:QM,selectAll:sR,selectChild:aR,selectChildren:dR,filter:fR,data:yR,enter:hR,exit:vR,join:xR,merge:bR,selection:CL,order:kR,sort:jR,call:NR,nodes:CR,node:ER,size:$R,empty:AR,each:TR,attr:DR,style:UR,property:VR,classed:JR,text:eL,html:rL,raise:oL,lower:lL,append:cL,insert:dL,remove:hL,clone:pL,datum:gL,on:bL,dispatch:SL,[Symbol.iterator]:NL};function ki(e){return typeof e=="string"?new ri([[document.querySelector(e)]],[document.documentElement]):new ri([[e]],ck)}function EL(e){let t;for(;t=e.sourceEvent;)e=t;return e}function Hi(e,t){if(e=EL(e),t===void 0&&(t=e.currentTarget),t){var n=t.ownerSVGElement||t;if(n.createSVGPoint){var r=n.createSVGPoint();return r.x=e.clientX,r.y=e.clientY,r=r.matrixTransform(t.getScreenCTM().inverse()),[r.x,r.y]}if(t.getBoundingClientRect){var o=t.getBoundingClientRect();return[e.clientX-o.left-t.clientLeft,e.clientY-o.top-t.clientTop]}}return[e.pageX,e.pageY]}const $L={passive:!1},Of={capture:!0,passive:!1};function $p(e){e.stopImmediatePropagation()}function Du(e){e.preventDefault(),e.stopImmediatePropagation()}function uk(e){var t=e.document.documentElement,n=ki(e).on("dragstart.drag",Du,Of);"onselectstart"in t?n.on("selectstart.drag",Du,Of):(t.__noselect=t.style.MozUserSelect,t.style.MozUserSelect="none")}function dk(e,t){var n=e.document.documentElement,r=ki(e).on("dragstart.drag",null);t&&(r.on("click.drag",Du,Of),setTimeout(function(){r.on("click.drag",null)},0)),"onselectstart"in n?r.on("selectstart.drag",null):(n.style.MozUserSelect=n.__noselect,delete n.__noselect)}const vm=e=>()=>e;function Ng(e,{sourceEvent:t,subject:n,target:r,identifier:o,active:l,x:c,y:u,dx:f,dy:h,dispatch:m}){Object.defineProperties(this,{type:{value:e,enumerable:!0,configurable:!0},sourceEvent:{value:t,enumerable:!0,configurable:!0},subject:{value:n,enumerable:!0,configurable:!0},target:{value:r,enumerable:!0,configurable:!0},identifier:{value:o,enumerable:!0,configurable:!0},active:{value:l,enumerable:!0,configurable:!0},x:{value:c,enumerable:!0,configurable:!0},y:{value:u,enumerable:!0,configurable:!0},dx:{value:f,enumerable:!0,configurable:!0},dy:{value:h,enumerable:!0,configurable:!0},_:{value:m}})}Ng.prototype.on=function(){var e=this._.on.apply(this._,arguments);return e===this._?this:e};function AL(e){return!e.ctrlKey&&!e.button}function TL(){return this.parentNode}function ML(e,t){return t??{x:e.x,y:e.y}}function RL(){return navigator.maxTouchPoints||"ontouchstart"in this}function LL(){var e=AL,t=TL,n=ML,r=RL,o={},l=v_("start","drag","end"),c=0,u,f,h,m,g=0;function y(A){A.on("mousedown.drag",w).filter(r).on("touchstart.drag",S).on("touchmove.drag",N,$L).on("touchend.drag touchcancel.drag",R).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function w(A,W){if(!(m||!e.call(this,A,W))){var z=T(this,t.call(this,A,W),A,W,"mouse");z&&(ki(A.view).on("mousemove.drag",k,Of).on("mouseup.drag",b,Of),uk(A.view),$p(A),h=!1,u=A.clientX,f=A.clientY,z("start",A))}}function k(A){if(Du(A),!h){var W=A.clientX-u,z=A.clientY-f;h=W*W+z*z>g}o.mouse("drag",A)}function b(A){ki(A.view).on("mousemove.drag mouseup.drag",null),dk(A.view,h),Du(A),o.mouse("end",A)}function S(A,W){if(e.call(this,A,W)){var z=A.changedTouches,J=t.call(this,A,W),K=z.length,re,te;for(re=0;re<K;++re)(te=T(this,J,A,W,z[re].identifier,z[re]))&&($p(A),te("start",A,z[re]))}}function N(A){var W=A.changedTouches,z=W.length,J,K;for(J=0;J<z;++J)(K=o[W[J].identifier])&&(Du(A),K("drag",A,W[J]))}function R(A){var W=A.changedTouches,z=W.length,J,K;for(m&&clearTimeout(m),m=setTimeout(function(){m=null},500),J=0;J<z;++J)(K=o[W[J].identifier])&&($p(A),K("end",A,W[J]))}function T(A,W,z,J,K,re){var te=l.copy(),Q=Hi(re||z,W),D,$,E;if((E=n.call(A,new Ng("beforestart",{sourceEvent:z,target:y,identifier:K,active:c,x:Q[0],y:Q[1],dx:0,dy:0,dispatch:te}),J))!=null)return D=E.x-Q[0]||0,$=E.y-Q[1]||0,function L(M,ee,F){var U=Q,V;switch(M){case"start":o[K]=L,V=c++;break;case"end":delete o[K],--c;case"drag":Q=Hi(F||ee,W),V=c;break}te.call(M,A,new Ng(M,{sourceEvent:ee,subject:E,target:y,identifier:K,active:V,x:Q[0]+D,y:Q[1]+$,dx:Q[0]-U[0],dy:Q[1]-U[1],dispatch:te}),J)}}return y.filter=function(A){return arguments.length?(e=typeof A=="function"?A:vm(!!A),y):e},y.container=function(A){return arguments.length?(t=typeof A=="function"?A:vm(A),y):t},y.subject=function(A){return arguments.length?(n=typeof A=="function"?A:vm(A),y):n},y.touchable=function(A){return arguments.length?(r=typeof A=="function"?A:vm(!!A),y):r},y.on=function(){var A=l.on.apply(l,arguments);return A===l?y:A},y.clickDistance=function(A){return arguments.length?(g=(A=+A)*A,y):Math.sqrt(g)},y}function vy(e,t,n){e.prototype=t.prototype=n,n.constructor=e}function fk(e,t){var n=Object.create(e.prototype);for(var r in t)n[r]=t[r];return n}function nh(){}var Pf=.7,e_=1/Pf,Fu="\\s*([+-]?\\d+)\\s*",Df="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",Eo="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",IL=/^#([0-9a-f]{3,8})$/,OL=new RegExp(`^rgb\\(${Fu},${Fu},${Fu}\\)$`),PL=new RegExp(`^rgb\\(${Eo},${Eo},${Eo}\\)$`),DL=new RegExp(`^rgba\\(${Fu},${Fu},${Fu},${Df}\\)$`),FL=new RegExp(`^rgba\\(${Eo},${Eo},${Eo},${Df}\\)$`),zL=new RegExp(`^hsl\\(${Df},${Eo},${Eo}\\)$`),BL=new RegExp(`^hsla\\(${Df},${Eo},${Eo},${Df}\\)$`),Dv={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};vy(nh,Ff,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:Fv,formatHex:Fv,formatHex8:UL,formatHsl:WL,formatRgb:zv,toString:zv});function Fv(){return this.rgb().formatHex()}function UL(){return this.rgb().formatHex8()}function WL(){return hk(this).formatHsl()}function zv(){return this.rgb().formatRgb()}function Ff(e){var t,n;return e=(e+"").trim().toLowerCase(),(t=IL.exec(e))?(n=t[1].length,t=parseInt(t[1],16),n===6?Bv(t):n===3?new Hr(t>>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):n===8?xm(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?xm(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=OL.exec(e))?new Hr(t[1],t[2],t[3],1):(t=PL.exec(e))?new Hr(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=DL.exec(e))?xm(t[1],t[2],t[3],t[4]):(t=FL.exec(e))?xm(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=zL.exec(e))?qv(t[1],t[2]/100,t[3]/100,1):(t=BL.exec(e))?qv(t[1],t[2]/100,t[3]/100,t[4]):Dv.hasOwnProperty(e)?Bv(Dv[e]):e==="transparent"?new Hr(NaN,NaN,NaN,0):null}function Bv(e){return new Hr(e>>16&255,e>>8&255,e&255,1)}function xm(e,t,n,r){return r<=0&&(e=t=n=NaN),new Hr(e,t,n,r)}function qL(e){return e instanceof nh||(e=Ff(e)),e?(e=e.rgb(),new Hr(e.r,e.g,e.b,e.opacity)):new Hr}function Cg(e,t,n,r){return arguments.length===1?qL(e):new Hr(e,t,n,r??1)}function Hr(e,t,n,r){this.r=+e,this.g=+t,this.b=+n,this.opacity=+r}vy(Hr,Cg,fk(nh,{brighter(e){return e=e==null?e_:Math.pow(e_,e),new Hr(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=e==null?Pf:Math.pow(Pf,e),new Hr(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new Hr(gc(this.r),gc(this.g),gc(this.b),t_(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:Uv,formatHex:Uv,formatHex8:HL,formatRgb:Wv,toString:Wv}));function Uv(){return`#${dc(this.r)}${dc(this.g)}${dc(this.b)}`}function HL(){return`#${dc(this.r)}${dc(this.g)}${dc(this.b)}${dc((isNaN(this.opacity)?1:this.opacity)*255)}`}function Wv(){const e=t_(this.opacity);return`${e===1?"rgb(":"rgba("}${gc(this.r)}, ${gc(this.g)}, ${gc(this.b)}${e===1?")":`, ${e})`}`}function t_(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function gc(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function dc(e){return e=gc(e),(e<16?"0":"")+e.toString(16)}function qv(e,t,n,r){return r<=0?e=t=n=NaN:n<=0||n>=1?e=t=NaN:t<=0&&(e=NaN),new Ki(e,t,n,r)}function hk(e){if(e instanceof Ki)return new Ki(e.h,e.s,e.l,e.opacity);if(e instanceof nh||(e=Ff(e)),!e)return new Ki;if(e instanceof Ki)return e;e=e.rgb();var t=e.r/255,n=e.g/255,r=e.b/255,o=Math.min(t,n,r),l=Math.max(t,n,r),c=NaN,u=l-o,f=(l+o)/2;return u?(t===l?c=(n-r)/u+(n<r)*6:n===l?c=(r-t)/u+2:c=(t-n)/u+4,u/=f<.5?l+o:2-l-o,c*=60):u=f>0&&f<1?0:c,new Ki(c,u,f,e.opacity)}function VL(e,t,n,r){return arguments.length===1?hk(e):new Ki(e,t,n,r??1)}function Ki(e,t,n,r){this.h=+e,this.s=+t,this.l=+n,this.opacity=+r}vy(Ki,VL,fk(nh,{brighter(e){return e=e==null?e_:Math.pow(e_,e),new Ki(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?Pf:Math.pow(Pf,e),new Ki(this.h,this.s,this.l*e,this.opacity)},rgb(){var e=this.h%360+(this.h<0)*360,t=isNaN(e)||isNaN(this.s)?0:this.s,n=this.l,r=n+(n<.5?n:1-n)*t,o=2*n-r;return new Hr(Ap(e>=240?e-240:e+120,o,r),Ap(e,o,r),Ap(e<120?e+240:e-120,o,r),this.opacity)},clamp(){return new Ki(Hv(this.h),bm(this.s),bm(this.l),t_(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=t_(this.opacity);return`${e===1?"hsl(":"hsla("}${Hv(this.h)}, ${bm(this.s)*100}%, ${bm(this.l)*100}%${e===1?")":`, ${e})`}`}}));function Hv(e){return e=(e||0)%360,e<0?e+360:e}function bm(e){return Math.max(0,Math.min(1,e||0))}function Ap(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 mk=e=>()=>e;function GL(e,t){return function(n){return e+n*t}}function KL(e,t,n){return e=Math.pow(e,n),t=Math.pow(t,n)-e,n=1/n,function(r){return Math.pow(e+r*t,n)}}function YL(e){return(e=+e)==1?_k:function(t,n){return n-t?KL(t,n,e):mk(isNaN(t)?n:t)}}function _k(e,t){var n=t-e;return n?GL(e,n):mk(isNaN(e)?t:e)}const Vv=(function e(t){var n=YL(t);function r(o,l){var c=n((o=Cg(o)).r,(l=Cg(l)).r),u=n(o.g,l.g),f=n(o.b,l.b),h=_k(o.opacity,l.opacity);return function(m){return o.r=c(m),o.g=u(m),o.b=f(m),o.opacity=h(m),o+""}}return r.gamma=e,r})(1);function dl(e,t){return e=+e,t=+t,function(n){return e*(1-n)+t*n}}var Eg=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,Tp=new RegExp(Eg.source,"g");function JL(e){return function(){return e}}function XL(e){return function(t){return e(t)+""}}function ZL(e,t){var n=Eg.lastIndex=Tp.lastIndex=0,r,o,l,c=-1,u=[],f=[];for(e=e+"",t=t+"";(r=Eg.exec(e))&&(o=Tp.exec(t));)(l=o.index)>n&&(l=t.slice(n,l),u[c]?u[c]+=l:u[++c]=l),(r=r[0])===(o=o[0])?u[c]?u[c]+=o:u[++c]=o:(u[++c]=null,f.push({i:c,x:dl(r,o)})),n=Tp.lastIndex;return n<t.length&&(l=t.slice(n),u[c]?u[c]+=l:u[++c]=l),u.length<2?f[0]?XL(f[0].x):JL(t):(t=f.length,function(h){for(var m=0,g;m<t;++m)u[(g=f[m]).i]=g.x(h);return u.join("")})}var Gv=180/Math.PI,$g={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function pk(e,t,n,r,o,l){var c,u,f;return(c=Math.sqrt(e*e+t*t))&&(e/=c,t/=c),(f=e*n+t*r)&&(n-=e*f,r-=t*f),(u=Math.sqrt(n*n+r*r))&&(n/=u,r/=u,f/=u),e*r<t*n&&(e=-e,t=-t,f=-f,c=-c),{translateX:o,translateY:l,rotate:Math.atan2(t,e)*Gv,skewX:Math.atan(f)*Gv,scaleX:c,scaleY:u}}var km;function QL(e){const t=new(typeof DOMMatrix=="function"?DOMMatrix:WebKitCSSMatrix)(e+"");return t.isIdentity?$g:pk(t.a,t.b,t.c,t.d,t.e,t.f)}function e3(e){return e==null||(km||(km=document.createElementNS("http://www.w3.org/2000/svg","g")),km.setAttribute("transform",e),!(e=km.transform.baseVal.consolidate()))?$g:(e=e.matrix,pk(e.a,e.b,e.c,e.d,e.e,e.f))}function gk(e,t,n,r){function o(h){return h.length?h.pop()+" ":""}function l(h,m,g,y,w,k){if(h!==g||m!==y){var b=w.push("translate(",null,t,null,n);k.push({i:b-4,x:dl(h,g)},{i:b-2,x:dl(m,y)})}else(g||y)&&w.push("translate("+g+t+y+n)}function c(h,m,g,y){h!==m?(h-m>180?m+=360:m-h>180&&(h+=360),y.push({i:g.push(o(g)+"rotate(",null,r)-2,x:dl(h,m)})):m&&g.push(o(g)+"rotate("+m+r)}function u(h,m,g,y){h!==m?y.push({i:g.push(o(g)+"skewX(",null,r)-2,x:dl(h,m)}):m&&g.push(o(g)+"skewX("+m+r)}function f(h,m,g,y,w,k){if(h!==g||m!==y){var b=w.push(o(w)+"scale(",null,",",null,")");k.push({i:b-4,x:dl(h,g)},{i:b-2,x:dl(m,y)})}else(g!==1||y!==1)&&w.push(o(w)+"scale("+g+","+y+")")}return function(h,m){var g=[],y=[];return h=e(h),m=e(m),l(h.translateX,h.translateY,m.translateX,m.translateY,g,y),c(h.rotate,m.rotate,g,y),u(h.skewX,m.skewX,g,y),f(h.scaleX,h.scaleY,m.scaleX,m.scaleY,g,y),h=m=null,function(w){for(var k=-1,b=y.length,S;++k<b;)g[(S=y[k]).i]=S.x(w);return g.join("")}}}var t3=gk(QL,"px, ","px)","deg)"),n3=gk(e3,", ",")",")"),s3=1e-12;function Kv(e){return((e=Math.exp(e))+1/e)/2}function r3(e){return((e=Math.exp(e))-1/e)/2}function i3(e){return((e=Math.exp(2*e))-1)/(e+1)}const o3=(function e(t,n,r){function o(l,c){var u=l[0],f=l[1],h=l[2],m=c[0],g=c[1],y=c[2],w=m-u,k=g-f,b=w*w+k*k,S,N;if(b<s3)N=Math.log(y/h)/t,S=function(J){return[u+J*w,f+J*k,h*Math.exp(t*J*N)]};else{var R=Math.sqrt(b),T=(y*y-h*h+r*b)/(2*h*n*R),A=(y*y-h*h-r*b)/(2*y*n*R),W=Math.log(Math.sqrt(T*T+1)-T),z=Math.log(Math.sqrt(A*A+1)-A);N=(z-W)/t,S=function(J){var K=J*N,re=Kv(W),te=h/(n*R)*(re*i3(t*K+W)-r3(W));return[u+te*w,f+te*k,h*re/Kv(t*K+W)]}}return S.duration=N*1e3*t/Math.SQRT2,S}return o.rho=function(l){var c=Math.max(.001,+l),u=c*c,f=u*u;return e(c,u,f)},o})(Math.SQRT2,2,4);var Hu=0,kf=0,of=0,yk=1e3,n_,jf,s_=0,kc=0,b_=0,zf=typeof performance=="object"&&performance.now?performance:Date,wk=typeof window=="object"&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(e){setTimeout(e,17)};function xy(){return kc||(wk(a3),kc=zf.now()+b_)}function a3(){kc=0}function r_(){this._call=this._time=this._next=null}r_.prototype=vk.prototype={constructor:r_,restart:function(e,t,n){if(typeof e!="function")throw new TypeError("callback is not a function");n=(n==null?xy():+n)+(t==null?0:+t),!this._next&&jf!==this&&(jf?jf._next=this:n_=this,jf=this),this._call=e,this._time=n,Ag()},stop:function(){this._call&&(this._call=null,this._time=1/0,Ag())}};function vk(e,t,n){var r=new r_;return r.restart(e,t,n),r}function l3(){xy(),++Hu;for(var e=n_,t;e;)(t=kc-e._time)>=0&&e._call.call(void 0,t),e=e._next;--Hu}function Yv(){kc=(s_=zf.now())+b_,Hu=kf=0;try{l3()}finally{Hu=0,u3(),kc=0}}function c3(){var e=zf.now(),t=e-s_;t>yk&&(b_-=t,s_=e)}function u3(){for(var e,t=n_,n,r=1/0;t;)t._call?(r>t._time&&(r=t._time),e=t,t=t._next):(n=t._next,t._next=null,t=e?e._next=n:n_=n);jf=e,Ag(r)}function Ag(e){if(!Hu){kf&&(kf=clearTimeout(kf));var t=e-kc;t>24?(e<1/0&&(kf=setTimeout(Yv,e-zf.now()-b_)),of&&(of=clearInterval(of))):(of||(s_=zf.now(),of=setInterval(c3,yk)),Hu=1,wk(Yv))}}function Jv(e,t,n){var r=new r_;return t=t==null?0:+t,r.restart(o=>{r.stop(),e(o+t)},t,n),r}var d3=v_("start","end","cancel","interrupt"),f3=[],xk=0,Xv=1,Tg=2,Dm=3,Zv=4,Mg=5,Fm=6;function k_(e,t,n,r,o,l){var c=e.__transition;if(!c)e.__transition={};else if(n in c)return;h3(e,n,{name:t,index:r,group:o,on:d3,tween:f3,time:l.time,delay:l.delay,duration:l.duration,ease:l.ease,timer:null,state:xk})}function by(e,t){var n=Ji(e,t);if(n.state>xk)throw new Error("too late; already scheduled");return n}function Ao(e,t){var n=Ji(e,t);if(n.state>Dm)throw new Error("too late; already running");return n}function Ji(e,t){var n=e.__transition;if(!n||!(n=n[t]))throw new Error("transition not found");return n}function h3(e,t,n){var r=e.__transition,o;r[t]=n,n.timer=vk(l,0,n.time);function l(h){n.state=Xv,n.timer.restart(c,n.delay,n.time),n.delay<=h&&c(h-n.delay)}function c(h){var m,g,y,w;if(n.state!==Xv)return f();for(m in r)if(w=r[m],w.name===n.name){if(w.state===Dm)return Jv(c);w.state===Zv?(w.state=Fm,w.timer.stop(),w.on.call("interrupt",e,e.__data__,w.index,w.group),delete r[m]):+m<t&&(w.state=Fm,w.timer.stop(),w.on.call("cancel",e,e.__data__,w.index,w.group),delete r[m])}if(Jv(function(){n.state===Dm&&(n.state=Zv,n.timer.restart(u,n.delay,n.time),u(h))}),n.state=Tg,n.on.call("start",e,e.__data__,n.index,n.group),n.state===Tg){for(n.state=Dm,o=new Array(y=n.tween.length),m=0,g=-1;m<y;++m)(w=n.tween[m].value.call(e,e.__data__,n.index,n.group))&&(o[++g]=w);o.length=g+1}}function u(h){for(var m=h<n.duration?n.ease.call(null,h/n.duration):(n.timer.restart(f),n.state=Mg,1),g=-1,y=o.length;++g<y;)o[g].call(e,m);n.state===Mg&&(n.on.call("end",e,e.__data__,n.index,n.group),f())}function f(){n.state=Fm,n.timer.stop(),delete r[t];for(var h in r)return;delete e.__transition}}function zm(e,t){var n=e.__transition,r,o,l=!0,c;if(n){t=t==null?null:t+"";for(c in n){if((r=n[c]).name!==t){l=!1;continue}o=r.state>Tg&&r.state<Mg,r.state=Fm,r.timer.stop(),r.on.call(o?"interrupt":"cancel",e,e.__data__,r.index,r.group),delete n[c]}l&&delete e.__transition}}function m3(e){return this.each(function(){zm(this,e)})}function _3(e,t){var n,r;return function(){var o=Ao(this,e),l=o.tween;if(l!==n){r=n=l;for(var c=0,u=r.length;c<u;++c)if(r[c].name===t){r=r.slice(),r.splice(c,1);break}}o.tween=r}}function p3(e,t,n){var r,o;if(typeof n!="function")throw new Error;return function(){var l=Ao(this,e),c=l.tween;if(c!==r){o=(r=c).slice();for(var u={name:t,value:n},f=0,h=o.length;f<h;++f)if(o[f].name===t){o[f]=u;break}f===h&&o.push(u)}l.tween=o}}function g3(e,t){var n=this._id;if(e+="",arguments.length<2){for(var r=Ji(this.node(),n).tween,o=0,l=r.length,c;o<l;++o)if((c=r[o]).name===e)return c.value;return null}return this.each((t==null?_3:p3)(n,e,t))}function ky(e,t,n){var r=e._id;return e.each(function(){var o=Ao(this,r);(o.value||(o.value={}))[t]=n.apply(this,arguments)}),function(o){return Ji(o,r).value[t]}}function bk(e,t){var n;return(typeof t=="number"?dl:t instanceof Ff?Vv:(n=Ff(t))?(t=n,Vv):ZL)(e,t)}function y3(e){return function(){this.removeAttribute(e)}}function w3(e){return function(){this.removeAttributeNS(e.space,e.local)}}function v3(e,t,n){var r,o=n+"",l;return function(){var c=this.getAttribute(e);return c===o?null:c===r?l:l=t(r=c,n)}}function x3(e,t,n){var r,o=n+"",l;return function(){var c=this.getAttributeNS(e.space,e.local);return c===o?null:c===r?l:l=t(r=c,n)}}function b3(e,t,n){var r,o,l;return function(){var c,u=n(this),f;return u==null?void this.removeAttribute(e):(c=this.getAttribute(e),f=u+"",c===f?null:c===r&&f===o?l:(o=f,l=t(r=c,u)))}}function k3(e,t,n){var r,o,l;return function(){var c,u=n(this),f;return u==null?void this.removeAttributeNS(e.space,e.local):(c=this.getAttributeNS(e.space,e.local),f=u+"",c===f?null:c===r&&f===o?l:(o=f,l=t(r=c,u)))}}function j3(e,t){var n=x_(e),r=n==="transform"?n3:bk;return this.attrTween(e,typeof t=="function"?(n.local?k3:b3)(n,r,ky(this,"attr."+e,t)):t==null?(n.local?w3:y3)(n):(n.local?x3:v3)(n,r,t))}function S3(e,t){return function(n){this.setAttribute(e,t.call(this,n))}}function N3(e,t){return function(n){this.setAttributeNS(e.space,e.local,t.call(this,n))}}function C3(e,t){var n,r;function o(){var l=t.apply(this,arguments);return l!==r&&(n=(r=l)&&N3(e,l)),n}return o._value=t,o}function E3(e,t){var n,r;function o(){var l=t.apply(this,arguments);return l!==r&&(n=(r=l)&&S3(e,l)),n}return o._value=t,o}function $3(e,t){var n="attr."+e;if(arguments.length<2)return(n=this.tween(n))&&n._value;if(t==null)return this.tween(n,null);if(typeof t!="function")throw new Error;var r=x_(e);return this.tween(n,(r.local?C3:E3)(r,t))}function A3(e,t){return function(){by(this,e).delay=+t.apply(this,arguments)}}function T3(e,t){return t=+t,function(){by(this,e).delay=t}}function M3(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?A3:T3)(t,e)):Ji(this.node(),t).delay}function R3(e,t){return function(){Ao(this,e).duration=+t.apply(this,arguments)}}function L3(e,t){return t=+t,function(){Ao(this,e).duration=t}}function I3(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?R3:L3)(t,e)):Ji(this.node(),t).duration}function O3(e,t){if(typeof t!="function")throw new Error;return function(){Ao(this,e).ease=t}}function P3(e){var t=this._id;return arguments.length?this.each(O3(t,e)):Ji(this.node(),t).ease}function D3(e,t){return function(){var n=t.apply(this,arguments);if(typeof n!="function")throw new Error;Ao(this,e).ease=n}}function F3(e){if(typeof e!="function")throw new Error;return this.each(D3(this._id,e))}function z3(e){typeof e!="function"&&(e=ek(e));for(var t=this._groups,n=t.length,r=new Array(n),o=0;o<n;++o)for(var l=t[o],c=l.length,u=r[o]=[],f,h=0;h<c;++h)(f=l[h])&&e.call(f,f.__data__,h,l)&&u.push(f);return new wa(r,this._parents,this._name,this._id)}function B3(e){if(e._id!==this._id)throw new Error;for(var t=this._groups,n=e._groups,r=t.length,o=n.length,l=Math.min(r,o),c=new Array(r),u=0;u<l;++u)for(var f=t[u],h=n[u],m=f.length,g=c[u]=new Array(m),y,w=0;w<m;++w)(y=f[w]||h[w])&&(g[w]=y);for(;u<r;++u)c[u]=t[u];return new wa(c,this._parents,this._name,this._id)}function U3(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 W3(e,t,n){var r,o,l=U3(t)?by:Ao;return function(){var c=l(this,e),u=c.on;u!==r&&(o=(r=u).copy()).on(t,n),c.on=o}}function q3(e,t){var n=this._id;return arguments.length<2?Ji(this.node(),n).on.on(e):this.each(W3(n,e,t))}function H3(e){return function(){var t=this.parentNode;for(var n in this.__transition)if(+n!==e)return;t&&t.removeChild(this)}}function V3(){return this.on("end.remove",H3(this._id))}function G3(e){var t=this._name,n=this._id;typeof e!="function"&&(e=yy(e));for(var r=this._groups,o=r.length,l=new Array(o),c=0;c<o;++c)for(var u=r[c],f=u.length,h=l[c]=new Array(f),m,g,y=0;y<f;++y)(m=u[y])&&(g=e.call(m,m.__data__,y,u))&&("__data__"in m&&(g.__data__=m.__data__),h[y]=g,k_(h[y],t,n,y,h,Ji(m,n)));return new wa(l,this._parents,t,n)}function K3(e){var t=this._name,n=this._id;typeof e!="function"&&(e=Q0(e));for(var r=this._groups,o=r.length,l=[],c=[],u=0;u<o;++u)for(var f=r[u],h=f.length,m,g=0;g<h;++g)if(m=f[g]){for(var y=e.call(m,m.__data__,g,f),w,k=Ji(m,n),b=0,S=y.length;b<S;++b)(w=y[b])&&k_(w,t,n,b,y,k);l.push(y),c.push(m)}return new wa(l,c,t,n)}var Y3=th.prototype.constructor;function J3(){return new Y3(this._groups,this._parents)}function X3(e,t){var n,r,o;return function(){var l=qu(this,e),c=(this.style.removeProperty(e),qu(this,e));return l===c?null:l===n&&c===r?o:o=t(n=l,r=c)}}function kk(e){return function(){this.style.removeProperty(e)}}function Z3(e,t,n){var r,o=n+"",l;return function(){var c=qu(this,e);return c===o?null:c===r?l:l=t(r=c,n)}}function Q3(e,t,n){var r,o,l;return function(){var c=qu(this,e),u=n(this),f=u+"";return u==null&&(f=u=(this.style.removeProperty(e),qu(this,e))),c===f?null:c===r&&f===o?l:(o=f,l=t(r=c,u))}}function e4(e,t){var n,r,o,l="style."+t,c="end."+l,u;return function(){var f=Ao(this,e),h=f.on,m=f.value[l]==null?u||(u=kk(t)):void 0;(h!==n||o!==m)&&(r=(n=h).copy()).on(c,o=m),f.on=r}}function t4(e,t,n){var r=(e+="")=="transform"?t3:bk;return t==null?this.styleTween(e,X3(e,r)).on("end.style."+e,kk(e)):typeof t=="function"?this.styleTween(e,Q3(e,r,ky(this,"style."+e,t))).each(e4(this._id,e)):this.styleTween(e,Z3(e,r,t),n).on("end.style."+e,null)}function n4(e,t,n){return function(r){this.style.setProperty(e,t.call(this,r),n)}}function s4(e,t,n){var r,o;function l(){var c=t.apply(this,arguments);return c!==o&&(r=(o=c)&&n4(e,c,n)),r}return l._value=t,l}function r4(e,t,n){var r="style."+(e+="");if(arguments.length<2)return(r=this.tween(r))&&r._value;if(t==null)return this.tween(r,null);if(typeof t!="function")throw new Error;return this.tween(r,s4(e,t,n??""))}function i4(e){return function(){this.textContent=e}}function o4(e){return function(){var t=e(this);this.textContent=t??""}}function a4(e){return this.tween("text",typeof e=="function"?o4(ky(this,"text",e)):i4(e==null?"":e+""))}function l4(e){return function(t){this.textContent=e.call(this,t)}}function c4(e){var t,n;function r(){var o=e.apply(this,arguments);return o!==n&&(t=(n=o)&&l4(o)),t}return r._value=e,r}function u4(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,c4(e))}function d4(){for(var e=this._name,t=this._id,n=jk(),r=this._groups,o=r.length,l=0;l<o;++l)for(var c=r[l],u=c.length,f,h=0;h<u;++h)if(f=c[h]){var m=Ji(f,t);k_(f,e,n,h,c,{time:m.time+m.delay+m.duration,delay:0,duration:m.duration,ease:m.ease})}return new wa(r,this._parents,e,n)}function f4(){var e,t,n=this,r=n._id,o=n.size();return new Promise(function(l,c){var u={value:c},f={value:function(){--o===0&&l()}};n.each(function(){var h=Ao(this,r),m=h.on;m!==e&&(t=(e=m).copy(),t._.cancel.push(u),t._.interrupt.push(u),t._.end.push(f)),h.on=t}),o===0&&l()})}var h4=0;function wa(e,t,n,r){this._groups=e,this._parents=t,this._name=n,this._id=r}function jk(){return++h4}var da=th.prototype;wa.prototype={constructor:wa,select:G3,selectAll:K3,selectChild:da.selectChild,selectChildren:da.selectChildren,filter:z3,merge:B3,selection:J3,transition:d4,call:da.call,nodes:da.nodes,node:da.node,size:da.size,empty:da.empty,each:da.each,on:q3,attr:j3,attrTween:$3,style:t4,styleTween:r4,text:a4,textTween:u4,remove:V3,tween:g3,delay:M3,duration:I3,ease:P3,easeVarying:F3,end:f4,[Symbol.iterator]:da[Symbol.iterator]};function m4(e){return((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2}var _4={time:null,delay:0,duration:250,ease:m4};function p4(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 g4(e){var t,n;e instanceof wa?(t=e._id,e=e._name):(t=jk(),(n=_4).time=xy(),e=e==null?null:e+"");for(var r=this._groups,o=r.length,l=0;l<o;++l)for(var c=r[l],u=c.length,f,h=0;h<u;++h)(f=c[h])&&k_(f,e,t,h,c,n||p4(f,t));return new wa(r,this._parents,e,t)}th.prototype.interrupt=m3;th.prototype.transition=g4;const jm=e=>()=>e;function y4(e,{sourceEvent:t,target:n,transform:r,dispatch:o}){Object.defineProperties(this,{type:{value:e,enumerable:!0,configurable:!0},sourceEvent:{value:t,enumerable:!0,configurable:!0},target:{value:n,enumerable:!0,configurable:!0},transform:{value:r,enumerable:!0,configurable:!0},_:{value:o}})}function _a(e,t,n){this.k=e,this.x=t,this.y=n}_a.prototype={constructor:_a,scale:function(e){return e===1?this:new _a(this.k*e,this.x,this.y)},translate:function(e,t){return e===0&t===0?this:new _a(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 ga=new _a(1,0,0);_a.prototype;function Mp(e){e.stopImmediatePropagation()}function af(e){e.preventDefault(),e.stopImmediatePropagation()}function w4(e){return(!e.ctrlKey||e.type==="wheel")&&!e.button}function v4(){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 Qv(){return this.__zoom||ga}function x4(e){return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*(e.ctrlKey?10:1)}function b4(){return navigator.maxTouchPoints||"ontouchstart"in this}function k4(e,t,n){var r=e.invertX(t[0][0])-n[0][0],o=e.invertX(t[1][0])-n[1][0],l=e.invertY(t[0][1])-n[0][1],c=e.invertY(t[1][1])-n[1][1];return e.translate(o>r?(r+o)/2:Math.min(0,r)||Math.max(0,o),c>l?(l+c)/2:Math.min(0,l)||Math.max(0,c))}function Sk(){var e=w4,t=v4,n=k4,r=x4,o=b4,l=[0,1/0],c=[[-1/0,-1/0],[1/0,1/0]],u=250,f=o3,h=v_("start","zoom","end"),m,g,y,w=500,k=150,b=0,S=10;function N(E){E.property("__zoom",Qv).on("wheel.zoom",K,{passive:!1}).on("mousedown.zoom",re).on("dblclick.zoom",te).filter(o).on("touchstart.zoom",Q).on("touchmove.zoom",D).on("touchend.zoom touchcancel.zoom",$).style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}N.transform=function(E,L,M,ee){var F=E.selection?E.selection():E;F.property("__zoom",Qv),E!==F?W(E,L,M,ee):F.interrupt().each(function(){z(this,arguments).event(ee).start().zoom(null,typeof L=="function"?L.apply(this,arguments):L).end()})},N.scaleBy=function(E,L,M,ee){N.scaleTo(E,function(){var F=this.__zoom.k,U=typeof L=="function"?L.apply(this,arguments):L;return F*U},M,ee)},N.scaleTo=function(E,L,M,ee){N.transform(E,function(){var F=t.apply(this,arguments),U=this.__zoom,V=M==null?A(F):typeof M=="function"?M.apply(this,arguments):M,O=U.invert(V),H=typeof L=="function"?L.apply(this,arguments):L;return n(T(R(U,H),V,O),F,c)},M,ee)},N.translateBy=function(E,L,M,ee){N.transform(E,function(){return n(this.__zoom.translate(typeof L=="function"?L.apply(this,arguments):L,typeof M=="function"?M.apply(this,arguments):M),t.apply(this,arguments),c)},null,ee)},N.translateTo=function(E,L,M,ee,F){N.transform(E,function(){var U=t.apply(this,arguments),V=this.__zoom,O=ee==null?A(U):typeof ee=="function"?ee.apply(this,arguments):ee;return n(ga.translate(O[0],O[1]).scale(V.k).translate(typeof L=="function"?-L.apply(this,arguments):-L,typeof M=="function"?-M.apply(this,arguments):-M),U,c)},ee,F)};function R(E,L){return L=Math.max(l[0],Math.min(l[1],L)),L===E.k?E:new _a(L,E.x,E.y)}function T(E,L,M){var ee=L[0]-M[0]*E.k,F=L[1]-M[1]*E.k;return ee===E.x&&F===E.y?E:new _a(E.k,ee,F)}function A(E){return[(+E[0][0]+ +E[1][0])/2,(+E[0][1]+ +E[1][1])/2]}function W(E,L,M,ee){E.on("start.zoom",function(){z(this,arguments).event(ee).start()}).on("interrupt.zoom end.zoom",function(){z(this,arguments).event(ee).end()}).tween("zoom",function(){var F=this,U=arguments,V=z(F,U).event(ee),O=t.apply(F,U),H=M==null?A(O):typeof M=="function"?M.apply(F,U):M,Y=Math.max(O[1][0]-O[0][0],O[1][1]-O[0][1]),ae=F.__zoom,ie=typeof L=="function"?L.apply(F,U):L,_e=f(ae.invert(H).concat(Y/ae.k),ie.invert(H).concat(Y/ie.k));return function(fe){if(fe===1)fe=ie;else{var ge=_e(fe),Ne=Y/ge[2];fe=new _a(Ne,H[0]-ge[0]*Ne,H[1]-ge[1]*Ne)}V.zoom(null,fe)}})}function z(E,L,M){return!M&&E.__zooming||new J(E,L)}function J(E,L){this.that=E,this.args=L,this.active=0,this.sourceEvent=null,this.extent=t.apply(E,L),this.taps=0}J.prototype={event:function(E){return E&&(this.sourceEvent=E),this},start:function(){return++this.active===1&&(this.that.__zooming=this,this.emit("start")),this},zoom:function(E,L){return this.mouse&&E!=="mouse"&&(this.mouse[1]=L.invert(this.mouse[0])),this.touch0&&E!=="touch"&&(this.touch0[1]=L.invert(this.touch0[0])),this.touch1&&E!=="touch"&&(this.touch1[1]=L.invert(this.touch1[0])),this.that.__zoom=L,this.emit("zoom"),this},end:function(){return--this.active===0&&(delete this.that.__zooming,this.emit("end")),this},emit:function(E){var L=ki(this.that).datum();h.call(E,this.that,new y4(E,{sourceEvent:this.sourceEvent,target:N,transform:this.that.__zoom,dispatch:h}),L)}};function K(E,...L){if(!e.apply(this,arguments))return;var M=z(this,L).event(E),ee=this.__zoom,F=Math.max(l[0],Math.min(l[1],ee.k*Math.pow(2,r.apply(this,arguments)))),U=Hi(E);if(M.wheel)(M.mouse[0][0]!==U[0]||M.mouse[0][1]!==U[1])&&(M.mouse[1]=ee.invert(M.mouse[0]=U)),clearTimeout(M.wheel);else{if(ee.k===F)return;M.mouse=[U,ee.invert(U)],zm(this),M.start()}af(E),M.wheel=setTimeout(V,k),M.zoom("mouse",n(T(R(ee,F),M.mouse[0],M.mouse[1]),M.extent,c));function V(){M.wheel=null,M.end()}}function re(E,...L){if(y||!e.apply(this,arguments))return;var M=E.currentTarget,ee=z(this,L,!0).event(E),F=ki(E.view).on("mousemove.zoom",H,!0).on("mouseup.zoom",Y,!0),U=Hi(E,M),V=E.clientX,O=E.clientY;uk(E.view),Mp(E),ee.mouse=[U,this.__zoom.invert(U)],zm(this),ee.start();function H(ae){if(af(ae),!ee.moved){var ie=ae.clientX-V,_e=ae.clientY-O;ee.moved=ie*ie+_e*_e>b}ee.event(ae).zoom("mouse",n(T(ee.that.__zoom,ee.mouse[0]=Hi(ae,M),ee.mouse[1]),ee.extent,c))}function Y(ae){F.on("mousemove.zoom mouseup.zoom",null),dk(ae.view,ee.moved),af(ae),ee.event(ae).end()}}function te(E,...L){if(e.apply(this,arguments)){var M=this.__zoom,ee=Hi(E.changedTouches?E.changedTouches[0]:E,this),F=M.invert(ee),U=M.k*(E.shiftKey?.5:2),V=n(T(R(M,U),ee,F),t.apply(this,L),c);af(E),u>0?ki(this).transition().duration(u).call(W,V,ee,E):ki(this).call(N.transform,V,ee,E)}}function Q(E,...L){if(e.apply(this,arguments)){var M=E.touches,ee=M.length,F=z(this,L,E.changedTouches.length===ee).event(E),U,V,O,H;for(Mp(E),V=0;V<ee;++V)O=M[V],H=Hi(O,this),H=[H,this.__zoom.invert(H),O.identifier],F.touch0?!F.touch1&&F.touch0[2]!==H[2]&&(F.touch1=H,F.taps=0):(F.touch0=H,U=!0,F.taps=1+!!m);m&&(m=clearTimeout(m)),U&&(F.taps<2&&(g=H[0],m=setTimeout(function(){m=null},w)),zm(this),F.start())}}function D(E,...L){if(this.__zooming){var M=z(this,L).event(E),ee=E.changedTouches,F=ee.length,U,V,O,H;for(af(E),U=0;U<F;++U)V=ee[U],O=Hi(V,this),M.touch0&&M.touch0[2]===V.identifier?M.touch0[0]=O:M.touch1&&M.touch1[2]===V.identifier&&(M.touch1[0]=O);if(V=M.that.__zoom,M.touch1){var Y=M.touch0[0],ae=M.touch0[1],ie=M.touch1[0],_e=M.touch1[1],fe=(fe=ie[0]-Y[0])*fe+(fe=ie[1]-Y[1])*fe,ge=(ge=_e[0]-ae[0])*ge+(ge=_e[1]-ae[1])*ge;V=R(V,Math.sqrt(fe/ge)),O=[(Y[0]+ie[0])/2,(Y[1]+ie[1])/2],H=[(ae[0]+_e[0])/2,(ae[1]+_e[1])/2]}else if(M.touch0)O=M.touch0[0],H=M.touch0[1];else return;M.zoom("touch",n(T(V,O,H),M.extent,c))}}function $(E,...L){if(this.__zooming){var M=z(this,L).event(E),ee=E.changedTouches,F=ee.length,U,V;for(Mp(E),y&&clearTimeout(y),y=setTimeout(function(){y=null},w),U=0;U<F;++U)V=ee[U],M.touch0&&M.touch0[2]===V.identifier?delete M.touch0:M.touch1&&M.touch1[2]===V.identifier&&delete M.touch1;if(M.touch1&&!M.touch0&&(M.touch0=M.touch1,delete M.touch1),M.touch0)M.touch0[1]=this.__zoom.invert(M.touch0[0]);else if(M.end(),M.taps===2&&(V=Hi(V,this),Math.hypot(g[0]-V[0],g[1]-V[1])<S)){var O=ki(this).on("dblclick.zoom");O&&O.apply(this,arguments)}}}return N.wheelDelta=function(E){return arguments.length?(r=typeof E=="function"?E:jm(+E),N):r},N.filter=function(E){return arguments.length?(e=typeof E=="function"?E:jm(!!E),N):e},N.touchable=function(E){return arguments.length?(o=typeof E=="function"?E:jm(!!E),N):o},N.extent=function(E){return arguments.length?(t=typeof E=="function"?E:jm([[+E[0][0],+E[0][1]],[+E[1][0],+E[1][1]]]),N):t},N.scaleExtent=function(E){return arguments.length?(l[0]=+E[0],l[1]=+E[1],N):[l[0],l[1]]},N.translateExtent=function(E){return arguments.length?(c[0][0]=+E[0][0],c[1][0]=+E[1][0],c[0][1]=+E[0][1],c[1][1]=+E[1][1],N):[[c[0][0],c[0][1]],[c[1][0],c[1][1]]]},N.constrain=function(E){return arguments.length?(n=E,N):n},N.duration=function(E){return arguments.length?(u=+E,N):u},N.interpolate=function(E){return arguments.length?(f=E,N):f},N.on=function(){var E=h.on.apply(h,arguments);return E===h?N:E},N.clickDistance=function(E){return arguments.length?(b=(E=+E)*E,N):Math.sqrt(b)},N.tapDistance=function(E){return arguments.length?(S=+E,N):S},N}const j_=_.createContext(null),j4=j_.Provider,va={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.`},Nk=va.error001();function On(e,t){const n=_.useContext(j_);if(n===null)throw new Error(Nk);return X0(n,e,t)}const ks=()=>{const e=_.useContext(j_);if(e===null)throw new Error(Nk);return _.useMemo(()=>({getState:e.getState,setState:e.setState,subscribe:e.subscribe,destroy:e.destroy}),[e])},S4=e=>e.userSelectionActive?"none":"all";function Bf({position:e,children:t,className:n,style:r,...o}){const l=On(S4),c=`${e}`.split("-");return xe.createElement("div",{className:Vs(["react-flow__panel",n,...c]),style:{...r,pointerEvents:l},...o},t)}function N4({proOptions:e,position:t="bottom-right"}){return e!=null&&e.hideAttribution?null:xe.createElement(Bf,{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"},xe.createElement("a",{href:"https://reactflow.dev",target:"_blank",rel:"noopener noreferrer","aria-label":"React Flow attribution"},"React Flow"))}const C4=({x:e,y:t,label:n,labelStyle:r={},labelShowBg:o=!0,labelBgStyle:l={},labelBgPadding:c=[2,4],labelBgBorderRadius:u=2,children:f,className:h,...m})=>{const g=_.useRef(null),[y,w]=_.useState({x:0,y:0,width:0,height:0}),k=Vs(["react-flow__edge-textwrapper",h]);return _.useEffect(()=>{if(g.current){const b=g.current.getBBox();w({x:b.x,y:b.y,width:b.width,height:b.height})}},[n]),typeof n>"u"||!n?null:xe.createElement("g",{transform:`translate(${e-y.width/2} ${t-y.height/2})`,className:k,visibility:y.width?"visible":"hidden",...m},o&&xe.createElement("rect",{width:y.width+2*c[0],x:-c[0],y:-c[1],height:y.height+2*c[1],className:"react-flow__edge-textbg",style:l,rx:u,ry:u}),xe.createElement("text",{className:"react-flow__edge-text",y:y.height/2,dy:"0.3em",ref:g,style:r},n),f)};var E4=_.memo(C4);const jy=e=>({width:e.offsetWidth,height:e.offsetHeight}),Vu=(e,t=0,n=1)=>Math.min(Math.max(e,t),n),Sy=(e={x:0,y:0},t)=>({x:Vu(e.x,t[0][0],t[1][0]),y:Vu(e.y,t[0][1],t[1][1])}),ex=(e,t,n)=>e<t?Vu(Math.abs(e-t),1,50)/50:e>n?-Vu(Math.abs(e-n),1,50)/50:0,Ck=(e,t)=>{const n=ex(e.x,35,t.width-35)*20,r=ex(e.y,35,t.height-35)*20;return[n,r]},Ek=e=>{var t;return((t=e.getRootNode)==null?void 0:t.call(e))||(window==null?void 0:window.document)},$k=(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)}),Uf=({x:e,y:t,width:n,height:r})=>({x:e,y:t,x2:e+n,y2:t+r}),Ak=({x:e,y:t,x2:n,y2:r})=>({x:e,y:t,width:n-e,height:r-t}),tx=e=>({...e.positionAbsolute||{x:0,y:0},width:e.width||0,height:e.height||0}),$4=(e,t)=>Ak($k(Uf(e),Uf(t))),Rg=(e,t)=>{const n=Math.max(0,Math.min(e.x+e.width,t.x+t.width)-Math.max(e.x,t.x)),r=Math.max(0,Math.min(e.y+e.height,t.y+t.height)-Math.max(e.y,t.y));return Math.ceil(n*r)},A4=e=>ji(e.width)&&ji(e.height)&&ji(e.x)&&ji(e.y),ji=e=>!isNaN(e)&&isFinite(e),us=Symbol.for("internals"),Tk=["Enter"," ","Escape"],T4=(e,t)=>{},M4=e=>"nativeEvent"in e;function Lg(e){var o,l;const t=M4(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 Mk=e=>"clientX"in e,pl=(e,t)=>{var l,c;const n=Mk(e),r=n?e.clientX:(l=e.touches)==null?void 0:l[0].clientX,o=n?e.clientY:(c=e.touches)==null?void 0:c[0].clientY;return{x:r-((t==null?void 0:t.left)??0),y:o-((t==null?void 0:t.top)??0)}},i_=()=>{var e;return typeof navigator<"u"&&((e=navigator==null?void 0:navigator.userAgent)==null?void 0:e.indexOf("Mac"))>=0},sh=({id:e,path:t,labelX:n,labelY:r,label:o,labelStyle:l,labelShowBg:c,labelBgStyle:u,labelBgPadding:f,labelBgBorderRadius:h,style:m,markerEnd:g,markerStart:y,interactionWidth:w=20})=>xe.createElement(xe.Fragment,null,xe.createElement("path",{id:e,style:m,d:t,fill:"none",className:"react-flow__edge-path",markerEnd:g,markerStart:y}),w&&xe.createElement("path",{d:t,fill:"none",strokeOpacity:0,strokeWidth:w,className:"react-flow__edge-interaction"}),o&&ji(n)&&ji(r)?xe.createElement(E4,{x:n,y:r,label:o,labelStyle:l,labelShowBg:c,labelBgStyle:u,labelBgPadding:f,labelBgBorderRadius:h}):null);sh.displayName="BaseEdge";function lf(e,t,n){return n===void 0?n:r=>{const o=t().edges.find(l=>l.id===e);o&&n(r,{...o})}}function Rk({sourceX:e,sourceY:t,targetX:n,targetY:r}){const o=Math.abs(n-e)/2,l=n<e?n+o:n-o,c=Math.abs(r-t)/2,u=r<t?r+c:r-c;return[l,u,o,c]}function Lk({sourceX:e,sourceY:t,targetX:n,targetY:r,sourceControlX:o,sourceControlY:l,targetControlX:c,targetControlY:u}){const f=e*.125+o*.375+c*.375+n*.125,h=t*.125+l*.375+u*.375+r*.125,m=Math.abs(f-e),g=Math.abs(h-t);return[f,h,m,g]}var jc;(function(e){e.Strict="strict",e.Loose="loose"})(jc||(jc={}));var fc;(function(e){e.Free="free",e.Vertical="vertical",e.Horizontal="horizontal"})(fc||(fc={}));var Wf;(function(e){e.Partial="partial",e.Full="full"})(Wf||(Wf={}));var hl;(function(e){e.Bezier="default",e.Straight="straight",e.Step="step",e.SmoothStep="smoothstep",e.SimpleBezier="simplebezier"})(hl||(hl={}));var qf;(function(e){e.Arrow="arrow",e.ArrowClosed="arrowclosed"})(qf||(qf={}));var vt;(function(e){e.Left="left",e.Top="top",e.Right="right",e.Bottom="bottom"})(vt||(vt={}));function nx({pos:e,x1:t,y1:n,x2:r,y2:o}){return e===vt.Left||e===vt.Right?[.5*(t+r),n]:[t,.5*(n+o)]}function Ik({sourceX:e,sourceY:t,sourcePosition:n=vt.Bottom,targetX:r,targetY:o,targetPosition:l=vt.Top}){const[c,u]=nx({pos:n,x1:e,y1:t,x2:r,y2:o}),[f,h]=nx({pos:l,x1:r,y1:o,x2:e,y2:t}),[m,g,y,w]=Lk({sourceX:e,sourceY:t,targetX:r,targetY:o,sourceControlX:c,sourceControlY:u,targetControlX:f,targetControlY:h});return[`M${e},${t} C${c},${u} ${f},${h} ${r},${o}`,m,g,y,w]}const Ny=_.memo(({sourceX:e,sourceY:t,targetX:n,targetY:r,sourcePosition:o=vt.Bottom,targetPosition:l=vt.Top,label:c,labelStyle:u,labelShowBg:f,labelBgStyle:h,labelBgPadding:m,labelBgBorderRadius:g,style:y,markerEnd:w,markerStart:k,interactionWidth:b})=>{const[S,N,R]=Ik({sourceX:e,sourceY:t,sourcePosition:o,targetX:n,targetY:r,targetPosition:l});return xe.createElement(sh,{path:S,labelX:N,labelY:R,label:c,labelStyle:u,labelShowBg:f,labelBgStyle:h,labelBgPadding:m,labelBgBorderRadius:g,style:y,markerEnd:w,markerStart:k,interactionWidth:b})});Ny.displayName="SimpleBezierEdge";const sx={[vt.Left]:{x:-1,y:0},[vt.Right]:{x:1,y:0},[vt.Top]:{x:0,y:-1},[vt.Bottom]:{x:0,y:1}},R4=({source:e,sourcePosition:t=vt.Bottom,target:n})=>t===vt.Left||t===vt.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},rx=(e,t)=>Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2));function L4({source:e,sourcePosition:t=vt.Bottom,target:n,targetPosition:r=vt.Top,center:o,offset:l}){const c=sx[t],u=sx[r],f={x:e.x+c.x*l,y:e.y+c.y*l},h={x:n.x+u.x*l,y:n.y+u.y*l},m=R4({source:f,sourcePosition:t,target:h}),g=m.x!==0?"x":"y",y=m[g];let w=[],k,b;const S={x:0,y:0},N={x:0,y:0},[R,T,A,W]=Rk({sourceX:e.x,sourceY:e.y,targetX:n.x,targetY:n.y});if(c[g]*u[g]===-1){k=o.x||R,b=o.y||T;const J=[{x:k,y:f.y},{x:k,y:h.y}],K=[{x:f.x,y:b},{x:h.x,y:b}];c[g]===y?w=g==="x"?J:K:w=g==="x"?K:J}else{const J=[{x:f.x,y:h.y}],K=[{x:h.x,y:f.y}];if(g==="x"?w=c.x===y?K:J:w=c.y===y?J:K,t===r){const $=Math.abs(e[g]-n[g]);if($<=l){const E=Math.min(l-1,l-$);c[g]===y?S[g]=(f[g]>e[g]?-1:1)*E:N[g]=(h[g]>n[g]?-1:1)*E}}if(t!==r){const $=g==="x"?"y":"x",E=c[g]===u[$],L=f[$]>h[$],M=f[$]<h[$];(c[g]===1&&(!E&&L||E&&M)||c[g]!==1&&(!E&&M||E&&L))&&(w=g==="x"?J:K)}const re={x:f.x+S.x,y:f.y+S.y},te={x:h.x+N.x,y:h.y+N.y},Q=Math.max(Math.abs(re.x-w[0].x),Math.abs(te.x-w[0].x)),D=Math.max(Math.abs(re.y-w[0].y),Math.abs(te.y-w[0].y));Q>=D?(k=(re.x+te.x)/2,b=w[0].y):(k=w[0].x,b=(re.y+te.y)/2)}return[[e,{x:f.x+S.x,y:f.y+S.y},...w,{x:h.x+N.x,y:h.y+N.y},n],k,b,A,W]}function I4(e,t,n,r){const o=Math.min(rx(e,t)/2,rx(t,n)/2,r),{x:l,y:c}=t;if(e.x===l&&l===n.x||e.y===c&&c===n.y)return`L${l} ${c}`;if(e.y===c){const h=e.x<n.x?-1:1,m=e.y<n.y?1:-1;return`L ${l+o*h},${c}Q ${l},${c} ${l},${c+o*m}`}const u=e.x<n.x?1:-1,f=e.y<n.y?-1:1;return`L ${l},${c+o*f}Q ${l},${c} ${l+o*u},${c}`}function Ig({sourceX:e,sourceY:t,sourcePosition:n=vt.Bottom,targetX:r,targetY:o,targetPosition:l=vt.Top,borderRadius:c=5,centerX:u,centerY:f,offset:h=20}){const[m,g,y,w,k]=L4({source:{x:e,y:t},sourcePosition:n,target:{x:r,y:o},targetPosition:l,center:{x:u,y:f},offset:h});return[m.reduce((S,N,R)=>{let T="";return R>0&&R<m.length-1?T=I4(m[R-1],N,m[R+1],c):T=`${R===0?"M":"L"}${N.x} ${N.y}`,S+=T,S},""),g,y,w,k]}const S_=_.memo(({sourceX:e,sourceY:t,targetX:n,targetY:r,label:o,labelStyle:l,labelShowBg:c,labelBgStyle:u,labelBgPadding:f,labelBgBorderRadius:h,style:m,sourcePosition:g=vt.Bottom,targetPosition:y=vt.Top,markerEnd:w,markerStart:k,pathOptions:b,interactionWidth:S})=>{const[N,R,T]=Ig({sourceX:e,sourceY:t,sourcePosition:g,targetX:n,targetY:r,targetPosition:y,borderRadius:b==null?void 0:b.borderRadius,offset:b==null?void 0:b.offset});return xe.createElement(sh,{path:N,labelX:R,labelY:T,label:o,labelStyle:l,labelShowBg:c,labelBgStyle:u,labelBgPadding:f,labelBgBorderRadius:h,style:m,markerEnd:w,markerStart:k,interactionWidth:S})});S_.displayName="SmoothStepEdge";const Cy=_.memo(e=>{var t;return xe.createElement(S_,{...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])})});Cy.displayName="StepEdge";function O4({sourceX:e,sourceY:t,targetX:n,targetY:r}){const[o,l,c,u]=Rk({sourceX:e,sourceY:t,targetX:n,targetY:r});return[`M ${e},${t}L ${n},${r}`,o,l,c,u]}const Ey=_.memo(({sourceX:e,sourceY:t,targetX:n,targetY:r,label:o,labelStyle:l,labelShowBg:c,labelBgStyle:u,labelBgPadding:f,labelBgBorderRadius:h,style:m,markerEnd:g,markerStart:y,interactionWidth:w})=>{const[k,b,S]=O4({sourceX:e,sourceY:t,targetX:n,targetY:r});return xe.createElement(sh,{path:k,labelX:b,labelY:S,label:o,labelStyle:l,labelShowBg:c,labelBgStyle:u,labelBgPadding:f,labelBgBorderRadius:h,style:m,markerEnd:g,markerStart:y,interactionWidth:w})});Ey.displayName="StraightEdge";function Sm(e,t){return e>=0?.5*e:t*25*Math.sqrt(-e)}function ix({pos:e,x1:t,y1:n,x2:r,y2:o,c:l}){switch(e){case vt.Left:return[t-Sm(t-r,l),n];case vt.Right:return[t+Sm(r-t,l),n];case vt.Top:return[t,n-Sm(n-o,l)];case vt.Bottom:return[t,n+Sm(o-n,l)]}}function Ok({sourceX:e,sourceY:t,sourcePosition:n=vt.Bottom,targetX:r,targetY:o,targetPosition:l=vt.Top,curvature:c=.25}){const[u,f]=ix({pos:n,x1:e,y1:t,x2:r,y2:o,c}),[h,m]=ix({pos:l,x1:r,y1:o,x2:e,y2:t,c}),[g,y,w,k]=Lk({sourceX:e,sourceY:t,targetX:r,targetY:o,sourceControlX:u,sourceControlY:f,targetControlX:h,targetControlY:m});return[`M${e},${t} C${u},${f} ${h},${m} ${r},${o}`,g,y,w,k]}const o_=_.memo(({sourceX:e,sourceY:t,targetX:n,targetY:r,sourcePosition:o=vt.Bottom,targetPosition:l=vt.Top,label:c,labelStyle:u,labelShowBg:f,labelBgStyle:h,labelBgPadding:m,labelBgBorderRadius:g,style:y,markerEnd:w,markerStart:k,pathOptions:b,interactionWidth:S})=>{const[N,R,T]=Ok({sourceX:e,sourceY:t,sourcePosition:o,targetX:n,targetY:r,targetPosition:l,curvature:b==null?void 0:b.curvature});return xe.createElement(sh,{path:N,labelX:R,labelY:T,label:c,labelStyle:u,labelShowBg:f,labelBgStyle:h,labelBgPadding:m,labelBgBorderRadius:g,style:y,markerEnd:w,markerStart:k,interactionWidth:S})});o_.displayName="BezierEdge";const $y=_.createContext(null),P4=$y.Provider;$y.Consumer;const D4=()=>_.useContext($y),F4=e=>"id"in e&&"source"in e&&"target"in e,z4=({source:e,sourceHandle:t,target:n,targetHandle:r})=>`reactflow__edge-${e}${t||""}-${n}${r||""}`,Og=(e,t)=>typeof e>"u"?"":typeof e=="string"?e:`${t?`${t}__`:""}${Object.keys(e).sort().map(r=>`${r}=${e[r]}`).join("&")}`,B4=(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)),U4=(e,t)=>{if(!e.source||!e.target)return t;let n;return F4(e)?n={...e}:n={...e,id:z4(e)},B4(n,t)?t:t.concat(n)},Pg=({x:e,y:t},[n,r,o],l,[c,u])=>{const f={x:(e-n)/o,y:(t-r)/o};return l?{x:c*Math.round(f.x/c),y:u*Math.round(f.y/u)}:f},Pk=({x:e,y:t},[n,r,o])=>({x:e*o+n,y:t*o+r}),yc=(e,t=[0,0])=>{if(!e)return{x:0,y:0,positionAbsolute:{x:0,y:0}};const n=(e.width??0)*t[0],r=(e.height??0)*t[1],o={x:e.position.x-n,y:e.position.y-r};return{...o,positionAbsolute:e.positionAbsolute?{x:e.positionAbsolute.x-n,y:e.positionAbsolute.y-r}:o}},N_=(e,t=[0,0])=>{if(e.length===0)return{x:0,y:0,width:0,height:0};const n=e.reduce((r,o)=>{const{x:l,y:c}=yc(o,t).positionAbsolute;return $k(r,Uf({x:l,y:c,width:o.width||0,height:o.height||0}))},{x:1/0,y:1/0,x2:-1/0,y2:-1/0});return Ak(n)},Dk=(e,t,[n,r,o]=[0,0,1],l=!1,c=!1,u=[0,0])=>{const f={x:(t.x-n)/o,y:(t.y-r)/o,width:t.width/o,height:t.height/o},h=[];return e.forEach(m=>{const{width:g,height:y,selectable:w=!0,hidden:k=!1}=m;if(c&&!w||k)return!1;const{positionAbsolute:b}=yc(m,u),S={x:b.x,y:b.y,width:g||0,height:y||0},N=Rg(f,S),R=typeof g>"u"||typeof y>"u"||g===null||y===null,T=l&&N>0,A=(g||0)*(y||0);(R||T||N>=A||m.dragging)&&h.push(m)}),h},Fk=(e,t)=>{const n=e.map(r=>r.id);return t.filter(r=>n.includes(r.source)||n.includes(r.target))},zk=(e,t,n,r,o,l=.1)=>{const c=t/(e.width*(1+l)),u=n/(e.height*(1+l)),f=Math.min(c,u),h=Vu(f,r,o),m=e.x+e.width/2,g=e.y+e.height/2,y=t/2-m*h,w=n/2-g*h;return{x:y,y:w,zoom:h}},ac=(e,t=0)=>e.transition().duration(t);function ox(e,t,n,r){return(t[n]||[]).reduce((o,l)=>{var c,u;return`${e.id}-${l.id}-${n}`!==r&&o.push({id:l.id||null,type:n,nodeId:e.id,x:(((c=e.positionAbsolute)==null?void 0:c.x)??0)+l.x+l.width/2,y:(((u=e.positionAbsolute)==null?void 0:u.y)??0)+l.y+l.height/2}),o},[])}function W4(e,t,n,r,o,l){const{x:c,y:u}=pl(e),h=t.elementsFromPoint(c,u).find(k=>k.classList.contains("react-flow__handle"));if(h){const k=h.getAttribute("data-nodeid");if(k){const b=Ay(void 0,h),S=h.getAttribute("data-handleid"),N=l({nodeId:k,id:S,type:b});if(N){const R=o.find(T=>T.nodeId===k&&T.type===b&&T.id===S);return{handle:{id:S,type:b,nodeId:k,x:(R==null?void 0:R.x)||n.x,y:(R==null?void 0:R.y)||n.y},validHandleResult:N}}}}let m=[],g=1/0;if(o.forEach(k=>{const b=Math.sqrt((k.x-n.x)**2+(k.y-n.y)**2);if(b<=r){const S=l(k);b<=g&&(b<g?m=[{handle:k,validHandleResult:S}]:b===g&&m.push({handle:k,validHandleResult:S}),g=b)}}),!m.length)return{handle:null,validHandleResult:Bk()};if(m.length===1)return m[0];const y=m.some(({validHandleResult:k})=>k.isValid),w=m.some(({handle:k})=>k.type==="target");return m.find(({handle:k,validHandleResult:b})=>w?k.type==="target":y?b.isValid:!0)||m[0]}const q4={source:null,target:null,sourceHandle:null,targetHandle:null},Bk=()=>({handleDomNode:null,isValid:!1,connection:q4,endHandle:null});function Uk(e,t,n,r,o,l,c){const u=o==="target",f=c.querySelector(`.react-flow__handle[data-id="${e==null?void 0:e.nodeId}-${e==null?void 0:e.id}-${e==null?void 0:e.type}"]`),h={...Bk(),handleDomNode:f};if(f){const m=Ay(void 0,f),g=f.getAttribute("data-nodeid"),y=f.getAttribute("data-handleid"),w=f.classList.contains("connectable"),k=f.classList.contains("connectableend"),b={source:u?g:n,sourceHandle:u?y:r,target:u?n:g,targetHandle:u?r:y};h.connection=b,w&&k&&(t===jc.Strict?u&&m==="source"||!u&&m==="target":g!==n||y!==r)&&(h.endHandle={nodeId:g,handleId:y,type:m},h.isValid=l(b))}return h}function H4({nodes:e,nodeId:t,handleId:n,handleType:r}){return e.reduce((o,l)=>{if(l[us]){const{handleBounds:c}=l[us];let u=[],f=[];c&&(u=ox(l,c,"source",`${t}-${n}-${r}`),f=ox(l,c,"target",`${t}-${n}-${r}`)),o.push(...u,...f)}return o},[])}function Ay(e,t){return e||(t!=null&&t.classList.contains("target")?"target":t!=null&&t.classList.contains("source")?"source":null)}function Rp(e){e==null||e.classList.remove("valid","connecting","react-flow__handle-valid","react-flow__handle-connecting")}function V4(e,t){let n=null;return t?n="valid":e&&!t&&(n="invalid"),n}function Wk({event:e,handleId:t,nodeId:n,onConnect:r,isTarget:o,getState:l,setState:c,isValidConnection:u,edgeUpdaterType:f,onEdgeUpdateEnd:h}){const m=Ek(e.target),{connectionMode:g,domNode:y,autoPanOnConnect:w,connectionRadius:k,onConnectStart:b,panBy:S,getNodes:N,cancelConnection:R}=l();let T=0,A;const{x:W,y:z}=pl(e),J=m==null?void 0:m.elementFromPoint(W,z),K=Ay(f,J),re=y==null?void 0:y.getBoundingClientRect();if(!re||!K)return;let te,Q=pl(e,re),D=!1,$=null,E=!1,L=null;const M=H4({nodes:N(),nodeId:n,handleId:t,handleType:K}),ee=()=>{if(!w)return;const[V,O]=Ck(Q,re);S({x:V,y:O}),T=requestAnimationFrame(ee)};c({connectionPosition:Q,connectionStatus:null,connectionNodeId:n,connectionHandleId:t,connectionHandleType:K,connectionStartHandle:{nodeId:n,handleId:t,type:K},connectionEndHandle:null}),b==null||b(e,{nodeId:n,handleId:t,handleType:K});function F(V){const{transform:O}=l();Q=pl(V,re);const{handle:H,validHandleResult:Y}=W4(V,m,Pg(Q,O,!1,[1,1]),k,M,ae=>Uk(ae,g,n,t,o?"target":"source",u,m));if(A=H,D||(ee(),D=!0),L=Y.handleDomNode,$=Y.connection,E=Y.isValid,c({connectionPosition:A&&E?Pk({x:A.x,y:A.y},O):Q,connectionStatus:V4(!!A,E),connectionEndHandle:Y.endHandle}),!A&&!E&&!L)return Rp(te);$.source!==$.target&&L&&(Rp(te),te=L,L.classList.add("connecting","react-flow__handle-connecting"),L.classList.toggle("valid",E),L.classList.toggle("react-flow__handle-valid",E))}function U(V){var O,H;(A||L)&&$&&E&&(r==null||r($)),(H=(O=l()).onConnectEnd)==null||H.call(O,V),f&&(h==null||h(V)),Rp(te),R(),cancelAnimationFrame(T),D=!1,E=!1,$=null,L=null,m.removeEventListener("mousemove",F),m.removeEventListener("mouseup",U),m.removeEventListener("touchmove",F),m.removeEventListener("touchend",U)}m.addEventListener("mousemove",F),m.addEventListener("mouseup",U),m.addEventListener("touchmove",F),m.addEventListener("touchend",U)}const ax=()=>!0,G4=e=>({connectionStartHandle:e.connectionStartHandle,connectOnClick:e.connectOnClick,noPanClassName:e.noPanClassName}),K4=(e,t,n)=>r=>{const{connectionStartHandle:o,connectionEndHandle:l,connectionClickStartHandle:c}=r;return{connecting:(o==null?void 0:o.nodeId)===e&&(o==null?void 0:o.handleId)===t&&(o==null?void 0:o.type)===n||(l==null?void 0:l.nodeId)===e&&(l==null?void 0:l.handleId)===t&&(l==null?void 0:l.type)===n,clickConnecting:(c==null?void 0:c.nodeId)===e&&(c==null?void 0:c.handleId)===t&&(c==null?void 0:c.type)===n}},qk=_.forwardRef(({type:e="source",position:t=vt.Top,isValidConnection:n,isConnectable:r=!0,isConnectableStart:o=!0,isConnectableEnd:l=!0,id:c,onConnect:u,children:f,className:h,onMouseDown:m,onTouchStart:g,...y},w)=>{var re,te;const k=c||null,b=e==="target",S=ks(),N=D4(),{connectOnClick:R,noPanClassName:T}=On(G4,Os),{connecting:A,clickConnecting:W}=On(K4(N,k,e),Os);N||(te=(re=S.getState()).onError)==null||te.call(re,"010",va.error010());const z=Q=>{const{defaultEdgeOptions:D,onConnect:$,hasDefaultEdges:E}=S.getState(),L={...D,...Q};if(E){const{edges:M,setEdges:ee}=S.getState();ee(U4(L,M))}$==null||$(L),u==null||u(L)},J=Q=>{if(!N)return;const D=Mk(Q);o&&(D&&Q.button===0||!D)&&Wk({event:Q,handleId:k,nodeId:N,onConnect:z,isTarget:b,getState:S.getState,setState:S.setState,isValidConnection:n||S.getState().isValidConnection||ax}),D?m==null||m(Q):g==null||g(Q)},K=Q=>{const{onClickConnectStart:D,onClickConnectEnd:$,connectionClickStartHandle:E,connectionMode:L,isValidConnection:M}=S.getState();if(!N||!E&&!o)return;if(!E){D==null||D(Q,{nodeId:N,handleId:k,handleType:e}),S.setState({connectionClickStartHandle:{nodeId:N,type:e,handleId:k}});return}const ee=Ek(Q.target),F=n||M||ax,{connection:U,isValid:V}=Uk({nodeId:N,id:k,type:e},L,E.nodeId,E.handleId||null,E.type,F,ee);V&&z(U),$==null||$(Q),S.setState({connectionClickStartHandle:null})};return xe.createElement("div",{"data-handleid":k,"data-nodeid":N,"data-handlepos":t,"data-id":`${N}-${k}-${e}`,className:Vs(["react-flow__handle",`react-flow__handle-${t}`,"nodrag",T,h,{source:!b,target:b,connectable:r,connectablestart:o,connectableend:l,connecting:W,connectionindicator:r&&(o&&!A||l&&A)}]),onMouseDown:J,onTouchStart:J,onClick:R?K:void 0,ref:w,...y},f)});qk.displayName="Handle";var a_=_.memo(qk);const Hk=({data:e,isConnectable:t,targetPosition:n=vt.Top,sourcePosition:r=vt.Bottom})=>xe.createElement(xe.Fragment,null,xe.createElement(a_,{type:"target",position:n,isConnectable:t}),e==null?void 0:e.label,xe.createElement(a_,{type:"source",position:r,isConnectable:t}));Hk.displayName="DefaultNode";var Dg=_.memo(Hk);const Vk=({data:e,isConnectable:t,sourcePosition:n=vt.Bottom})=>xe.createElement(xe.Fragment,null,e==null?void 0:e.label,xe.createElement(a_,{type:"source",position:n,isConnectable:t}));Vk.displayName="InputNode";var Gk=_.memo(Vk);const Kk=({data:e,isConnectable:t,targetPosition:n=vt.Top})=>xe.createElement(xe.Fragment,null,xe.createElement(a_,{type:"target",position:n,isConnectable:t}),e==null?void 0:e.label);Kk.displayName="OutputNode";var Yk=_.memo(Kk);const Ty=()=>null;Ty.displayName="GroupNode";const Y4=e=>({selectedNodes:e.getNodes().filter(t=>t.selected),selectedEdges:e.edges.filter(t=>t.selected)}),Nm=e=>e.id;function J4(e,t){return Os(e.selectedNodes.map(Nm),t.selectedNodes.map(Nm))&&Os(e.selectedEdges.map(Nm),t.selectedEdges.map(Nm))}const Jk=_.memo(({onSelectionChange:e})=>{const t=ks(),{selectedNodes:n,selectedEdges:r}=On(Y4,J4);return _.useEffect(()=>{const o={nodes:n,edges:r};e==null||e(o),t.getState().onSelectionChange.forEach(l=>l(o))},[n,r,e]),null});Jk.displayName="SelectionListener";const X4=e=>!!e.onSelectionChange;function Z4({onSelectionChange:e}){const t=On(X4);return e||t?xe.createElement(Jk,{onSelectionChange:e}):null}const Q4=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 ku(e,t){_.useEffect(()=>{typeof e<"u"&&t(e)},[e])}function Jt(e,t,n){_.useEffect(()=>{typeof t<"u"&&n({[e]:t})},[t])}const eI=({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,onConnect:o,onConnectStart:l,onConnectEnd:c,onClickConnectStart:u,onClickConnectEnd:f,nodesDraggable:h,nodesConnectable:m,nodesFocusable:g,edgesFocusable:y,edgesUpdatable:w,elevateNodesOnSelect:k,minZoom:b,maxZoom:S,nodeExtent:N,onNodesChange:R,onEdgesChange:T,elementsSelectable:A,connectionMode:W,snapGrid:z,snapToGrid:J,translateExtent:K,connectOnClick:re,defaultEdgeOptions:te,fitView:Q,fitViewOptions:D,onNodesDelete:$,onEdgesDelete:E,onNodeDrag:L,onNodeDragStart:M,onNodeDragStop:ee,onSelectionDrag:F,onSelectionDragStart:U,onSelectionDragStop:V,noPanClassName:O,nodeOrigin:H,rfId:Y,autoPanOnConnect:ae,autoPanOnNodeDrag:ie,onError:_e,connectionRadius:fe,isValidConnection:ge,nodeDragThreshold:Ne})=>{const{setNodes:Ue,setEdges:We,setDefaultNodesAndEdges:ut,setMinZoom:Fe,setMaxZoom:et,setTranslateExtent:$e,setNodeExtent:Ve,reset:le}=On(Q4,Os),be=ks();return _.useEffect(()=>{const Pe=r==null?void 0:r.map(me=>({...me,...te}));return ut(n,Pe),()=>{le()}},[]),Jt("defaultEdgeOptions",te,be.setState),Jt("connectionMode",W,be.setState),Jt("onConnect",o,be.setState),Jt("onConnectStart",l,be.setState),Jt("onConnectEnd",c,be.setState),Jt("onClickConnectStart",u,be.setState),Jt("onClickConnectEnd",f,be.setState),Jt("nodesDraggable",h,be.setState),Jt("nodesConnectable",m,be.setState),Jt("nodesFocusable",g,be.setState),Jt("edgesFocusable",y,be.setState),Jt("edgesUpdatable",w,be.setState),Jt("elementsSelectable",A,be.setState),Jt("elevateNodesOnSelect",k,be.setState),Jt("snapToGrid",J,be.setState),Jt("snapGrid",z,be.setState),Jt("onNodesChange",R,be.setState),Jt("onEdgesChange",T,be.setState),Jt("connectOnClick",re,be.setState),Jt("fitViewOnInit",Q,be.setState),Jt("fitViewOnInitOptions",D,be.setState),Jt("onNodesDelete",$,be.setState),Jt("onEdgesDelete",E,be.setState),Jt("onNodeDrag",L,be.setState),Jt("onNodeDragStart",M,be.setState),Jt("onNodeDragStop",ee,be.setState),Jt("onSelectionDrag",F,be.setState),Jt("onSelectionDragStart",U,be.setState),Jt("onSelectionDragStop",V,be.setState),Jt("noPanClassName",O,be.setState),Jt("nodeOrigin",H,be.setState),Jt("rfId",Y,be.setState),Jt("autoPanOnConnect",ae,be.setState),Jt("autoPanOnNodeDrag",ie,be.setState),Jt("onError",_e,be.setState),Jt("connectionRadius",fe,be.setState),Jt("isValidConnection",ge,be.setState),Jt("nodeDragThreshold",Ne,be.setState),ku(e,Ue),ku(t,We),ku(b,Fe),ku(S,et),ku(K,$e),ku(N,Ve),null},lx={display:"none"},tI={position:"absolute",width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0px, 0px, 0px, 0px)",clipPath:"inset(100%)"},Xk="react-flow__node-desc",Zk="react-flow__edge-desc",nI="react-flow__aria-live",sI=e=>e.ariaLiveMessage;function rI({rfId:e}){const t=On(sI);return xe.createElement("div",{id:`${nI}-${e}`,"aria-live":"assertive","aria-atomic":"true",style:tI},t)}function iI({rfId:e,disableKeyboardA11y:t}){return xe.createElement(xe.Fragment,null,xe.createElement("div",{id:`${Xk}-${e}`,style:lx},"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."," "),xe.createElement("div",{id:`${Zk}-${e}`,style:lx},"Press enter or space to select an edge. You can then press delete to remove it or escape to cancel."),!t&&xe.createElement(rI,{rfId:e}))}var Hf=(e=null,t={actInsideInputWithModifier:!0})=>{const[n,r]=_.useState(!1),o=_.useRef(!1),l=_.useRef(new Set([])),[c,u]=_.useMemo(()=>{if(e!==null){const h=(Array.isArray(e)?e:[e]).filter(g=>typeof g=="string").map(g=>g.split("+")),m=h.reduce((g,y)=>g.concat(...y),[]);return[h,m]}return[[],[]]},[e]);return _.useEffect(()=>{const f=typeof document<"u"?document:null,h=(t==null?void 0:t.target)||f;if(e!==null){const m=w=>{if(o.current=w.ctrlKey||w.metaKey||w.shiftKey,(!o.current||o.current&&!t.actInsideInputWithModifier)&&Lg(w))return!1;const b=ux(w.code,u);l.current.add(w[b]),cx(c,l.current,!1)&&(w.preventDefault(),r(!0))},g=w=>{if((!o.current||o.current&&!t.actInsideInputWithModifier)&&Lg(w))return!1;const b=ux(w.code,u);cx(c,l.current,!0)?(r(!1),l.current.clear()):l.current.delete(w[b]),w.key==="Meta"&&l.current.clear(),o.current=!1},y=()=>{l.current.clear(),r(!1)};return h==null||h.addEventListener("keydown",m),h==null||h.addEventListener("keyup",g),window.addEventListener("blur",y),()=>{h==null||h.removeEventListener("keydown",m),h==null||h.removeEventListener("keyup",g),window.removeEventListener("blur",y)}}},[e,r]),n};function cx(e,t,n){return e.filter(r=>n||r.length===t.size).some(r=>r.every(o=>t.has(o)))}function ux(e,t){return t.includes(e)?"code":"key"}function Qk(e,t,n,r){var c,u;if(!e.parentNode)return n;const o=t.get(e.parentNode),l=yc(o,r);return Qk(o,t,{x:(n.x??0)+l.x,y:(n.y??0)+l.y,z:(((c=o[us])==null?void 0:c.z)??0)>(n.z??0)?((u=o[us])==null?void 0:u.z)??0:n.z??0},r)}function ej(e,t,n){e.forEach(r=>{var o;if(r.parentNode&&!e.has(r.parentNode))throw new Error(`Parent node ${r.parentNode} not found`);if(r.parentNode||n!=null&&n[r.id]){const{x:l,y:c,z:u}=Qk(r,e,{...r.position,z:((o=r[us])==null?void 0:o.z)??0},t);r.positionAbsolute={x:l,y:c},r[us].z=u,n!=null&&n[r.id]&&(r[us].isParent=!0)}})}function Lp(e,t,n,r){const o=new Map,l={},c=r?1e3:0;return e.forEach(u=>{var y;const f=(ji(u.zIndex)?u.zIndex:0)+(u.selected?c:0),h=t.get(u.id),m={...u,positionAbsolute:{x:u.position.x,y:u.position.y}};u.parentNode&&(l[u.parentNode]=!0);const g=(h==null?void 0:h.type)&&(h==null?void 0:h.type)!==u.type;Object.defineProperty(m,us,{enumerable:!1,value:{handleBounds:g||(y=h==null?void 0:h[us])==null?void 0:y.handleBounds,z:f}}),o.set(u.id,m)}),ej(o,n,l),o}function tj(e,t={}){const{getNodes:n,width:r,height:o,minZoom:l,maxZoom:c,d3Zoom:u,d3Selection:f,fitViewOnInitDone:h,fitViewOnInit:m,nodeOrigin:g}=e(),y=t.initial&&!h&&m;if(u&&f&&(y||!t.initial)){const k=n().filter(S=>{var R;const N=t.includeHiddenNodes?S.width&&S.height:!S.hidden;return(R=t.nodes)!=null&&R.length?N&&t.nodes.some(T=>T.id===S.id):N}),b=k.every(S=>S.width&&S.height);if(k.length>0&&b){const S=N_(k,g),{x:N,y:R,zoom:T}=zk(S,r,o,t.minZoom??l,t.maxZoom??c,t.padding??.1),A=ga.translate(N,R).scale(T);return typeof t.duration=="number"&&t.duration>0?u.transform(ac(f,t.duration),A):u.transform(f,A),!0}}return!1}function oI(e,t){return e.forEach(n=>{const r=t.get(n.id);r&&t.set(r.id,{...r,[us]:r[us],selected:n.selected})}),new Map(t)}function aI(e,t){return t.map(n=>{const r=e.find(o=>o.id===n.id);return r&&(n.selected=r.selected),n})}function Cm({changedNodes:e,changedEdges:t,get:n,set:r}){const{nodeInternals:o,edges:l,onNodesChange:c,onEdgesChange:u,hasDefaultNodes:f,hasDefaultEdges:h}=n();e!=null&&e.length&&(f&&r({nodeInternals:oI(e,o)}),c==null||c(e)),t!=null&&t.length&&(h&&r({edges:aI(t,l)}),u==null||u(t))}const ju=()=>{},lI={zoomIn:ju,zoomOut:ju,zoomTo:ju,getZoom:()=>1,setViewport:ju,getViewport:()=>({x:0,y:0,zoom:1}),fitView:()=>!1,setCenter:ju,fitBounds:ju,project:e=>e,screenToFlowPosition:e=>e,flowToScreenPosition:e=>e,viewportInitialized:!1},cI=e=>({d3Zoom:e.d3Zoom,d3Selection:e.d3Selection}),uI=()=>{const e=ks(),{d3Zoom:t,d3Selection:n}=On(cI,Os);return _.useMemo(()=>n&&t?{zoomIn:o=>t.scaleBy(ac(n,o==null?void 0:o.duration),1.2),zoomOut:o=>t.scaleBy(ac(n,o==null?void 0:o.duration),1/1.2),zoomTo:(o,l)=>t.scaleTo(ac(n,l==null?void 0:l.duration),o),getZoom:()=>e.getState().transform[2],setViewport:(o,l)=>{const[c,u,f]=e.getState().transform,h=ga.translate(o.x??c,o.y??u).scale(o.zoom??f);t.transform(ac(n,l==null?void 0:l.duration),h)},getViewport:()=>{const[o,l,c]=e.getState().transform;return{x:o,y:l,zoom:c}},fitView:o=>tj(e.getState,o),setCenter:(o,l,c)=>{const{width:u,height:f,maxZoom:h}=e.getState(),m=typeof(c==null?void 0:c.zoom)<"u"?c.zoom:h,g=u/2-o*m,y=f/2-l*m,w=ga.translate(g,y).scale(m);t.transform(ac(n,c==null?void 0:c.duration),w)},fitBounds:(o,l)=>{const{width:c,height:u,minZoom:f,maxZoom:h}=e.getState(),{x:m,y:g,zoom:y}=zk(o,c,u,f,h,(l==null?void 0:l.padding)??.1),w=ga.translate(m,g).scale(y);t.transform(ac(n,l==null?void 0:l.duration),w)},project:o=>{const{transform:l,snapToGrid:c,snapGrid:u}=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"),Pg(o,l,c,u)},screenToFlowPosition:o=>{const{transform:l,snapToGrid:c,snapGrid:u,domNode:f}=e.getState();if(!f)return o;const{x:h,y:m}=f.getBoundingClientRect(),g={x:o.x-h,y:o.y-m};return Pg(g,l,c,u)},flowToScreenPosition:o=>{const{transform:l,domNode:c}=e.getState();if(!c)return o;const{x:u,y:f}=c.getBoundingClientRect(),h=Pk(o,l);return{x:h.x+u,y:h.y+f}},viewportInitialized:!0}:lI,[t,n])};function My(){const e=uI(),t=ks(),n=_.useCallback(()=>t.getState().getNodes().map(b=>({...b})),[]),r=_.useCallback(b=>t.getState().nodeInternals.get(b),[]),o=_.useCallback(()=>{const{edges:b=[]}=t.getState();return b.map(S=>({...S}))},[]),l=_.useCallback(b=>{const{edges:S=[]}=t.getState();return S.find(N=>N.id===b)},[]),c=_.useCallback(b=>{const{getNodes:S,setNodes:N,hasDefaultNodes:R,onNodesChange:T}=t.getState(),A=S(),W=typeof b=="function"?b(A):b;if(R)N(W);else if(T){const z=W.length===0?A.map(J=>({type:"remove",id:J.id})):W.map(J=>({item:J,type:"reset"}));T(z)}},[]),u=_.useCallback(b=>{const{edges:S=[],setEdges:N,hasDefaultEdges:R,onEdgesChange:T}=t.getState(),A=typeof b=="function"?b(S):b;if(R)N(A);else if(T){const W=A.length===0?S.map(z=>({type:"remove",id:z.id})):A.map(z=>({item:z,type:"reset"}));T(W)}},[]),f=_.useCallback(b=>{const S=Array.isArray(b)?b:[b],{getNodes:N,setNodes:R,hasDefaultNodes:T,onNodesChange:A}=t.getState();if(T){const z=[...N(),...S];R(z)}else if(A){const W=S.map(z=>({item:z,type:"add"}));A(W)}},[]),h=_.useCallback(b=>{const S=Array.isArray(b)?b:[b],{edges:N=[],setEdges:R,hasDefaultEdges:T,onEdgesChange:A}=t.getState();if(T)R([...N,...S]);else if(A){const W=S.map(z=>({item:z,type:"add"}));A(W)}},[]),m=_.useCallback(()=>{const{getNodes:b,edges:S=[],transform:N}=t.getState(),[R,T,A]=N;return{nodes:b().map(W=>({...W})),edges:S.map(W=>({...W})),viewport:{x:R,y:T,zoom:A}}},[]),g=_.useCallback(({nodes:b,edges:S})=>{const{nodeInternals:N,getNodes:R,edges:T,hasDefaultNodes:A,hasDefaultEdges:W,onNodesDelete:z,onEdgesDelete:J,onNodesChange:K,onEdgesChange:re}=t.getState(),te=(b||[]).map(L=>L.id),Q=(S||[]).map(L=>L.id),D=R().reduce((L,M)=>{const ee=!te.includes(M.id)&&M.parentNode&&L.find(U=>U.id===M.parentNode);return(typeof M.deletable=="boolean"?M.deletable:!0)&&(te.includes(M.id)||ee)&&L.push(M),L},[]),$=T.filter(L=>typeof L.deletable=="boolean"?L.deletable:!0),E=$.filter(L=>Q.includes(L.id));if(D||E){const L=Fk(D,$),M=[...E,...L],ee=M.reduce((F,U)=>(F.includes(U.id)||F.push(U.id),F),[]);if((W||A)&&(W&&t.setState({edges:T.filter(F=>!ee.includes(F.id))}),A&&(D.forEach(F=>{N.delete(F.id)}),t.setState({nodeInternals:new Map(N)}))),ee.length>0&&(J==null||J(M),re&&re(ee.map(F=>({id:F,type:"remove"})))),D.length>0&&(z==null||z(D),K)){const F=D.map(U=>({id:U.id,type:"remove"}));K(F)}}},[]),y=_.useCallback(b=>{const S=A4(b),N=S?null:t.getState().nodeInternals.get(b.id);return!S&&!N?[null,null,S]:[S?b:tx(N),N,S]},[]),w=_.useCallback((b,S=!0,N)=>{const[R,T,A]=y(b);return R?(N||t.getState().getNodes()).filter(W=>{if(!A&&(W.id===T.id||!W.positionAbsolute))return!1;const z=tx(W),J=Rg(z,R);return S&&J>0||J>=R.width*R.height}):[]},[]),k=_.useCallback((b,S,N=!0)=>{const[R]=y(b);if(!R)return!1;const T=Rg(R,S);return N&&T>0||T>=R.width*R.height},[]);return _.useMemo(()=>({...e,getNodes:n,getNode:r,getEdges:o,getEdge:l,setNodes:c,setEdges:u,addNodes:f,addEdges:h,toObject:m,deleteElements:g,getIntersectingNodes:w,isNodeIntersecting:k}),[e,n,r,o,l,c,u,f,h,m,g,w,k])}const dI={actInsideInputWithModifier:!1};var fI=({deleteKeyCode:e,multiSelectionKeyCode:t})=>{const n=ks(),{deleteElements:r}=My(),o=Hf(e,dI),l=Hf(t);_.useEffect(()=>{if(o){const{edges:c,getNodes:u}=n.getState(),f=u().filter(m=>m.selected),h=c.filter(m=>m.selected);r({nodes:f,edges:h}),n.setState({nodesSelectionActive:!1})}},[o]),_.useEffect(()=>{n.setState({multiSelectionActive:l})},[l])};function hI(e){const t=ks();_.useEffect(()=>{let n;const r=()=>{var l,c;if(!e.current)return;const o=jy(e.current);(o.height===0||o.width===0)&&((c=(l=t.getState()).onError)==null||c.call(l,"004",va.error004())),t.setState({width:o.width||500,height:o.height||500})};return r(),window.addEventListener("resize",r),e.current&&(n=new ResizeObserver(()=>r()),n.observe(e.current)),()=>{window.removeEventListener("resize",r),n&&e.current&&n.unobserve(e.current)}},[])}const Ry={position:"absolute",width:"100%",height:"100%",top:0,left:0},mI=(e,t)=>e.x!==t.x||e.y!==t.y||e.zoom!==t.k,Em=e=>({x:e.x,y:e.y,zoom:e.k}),Su=(e,t)=>e.target.closest(`.${t}`),dx=(e,t)=>t===2&&Array.isArray(e)&&e.includes(2),fx=e=>{const t=e.ctrlKey&&i_()?10:1;return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*t},_I=e=>({d3Zoom:e.d3Zoom,d3Selection:e.d3Selection,d3ZoomHandler:e.d3ZoomHandler,userSelectionActive:e.userSelectionActive}),pI=({onMove:e,onMoveStart:t,onMoveEnd:n,onPaneContextMenu:r,zoomOnScroll:o=!0,zoomOnPinch:l=!0,panOnScroll:c=!1,panOnScrollSpeed:u=.5,panOnScrollMode:f=fc.Free,zoomOnDoubleClick:h=!0,elementsSelectable:m,panOnDrag:g=!0,defaultViewport:y,translateExtent:w,minZoom:k,maxZoom:b,zoomActivationKeyCode:S,preventScrolling:N=!0,children:R,noWheelClassName:T,noPanClassName:A})=>{const W=_.useRef(),z=ks(),J=_.useRef(!1),K=_.useRef(!1),re=_.useRef(null),te=_.useRef({x:0,y:0,zoom:0}),{d3Zoom:Q,d3Selection:D,d3ZoomHandler:$,userSelectionActive:E}=On(_I,Os),L=Hf(S),M=_.useRef(0),ee=_.useRef(!1),F=_.useRef();return hI(re),_.useEffect(()=>{if(re.current){const U=re.current.getBoundingClientRect(),V=Sk().scaleExtent([k,b]).translateExtent(w),O=ki(re.current).call(V),H=ga.translate(y.x,y.y).scale(Vu(y.zoom,k,b)),Y=[[0,0],[U.width,U.height]],ae=V.constrain()(H,Y,w);V.transform(O,ae),V.wheelDelta(fx),z.setState({d3Zoom:V,d3Selection:O,d3ZoomHandler:O.on("wheel.zoom"),transform:[ae.x,ae.y,ae.k],domNode:re.current.closest(".react-flow")})}},[]),_.useEffect(()=>{D&&Q&&(c&&!L&&!E?D.on("wheel.zoom",U=>{if(Su(U,T))return!1;U.preventDefault(),U.stopImmediatePropagation();const V=D.property("__zoom").k||1,O=i_();if(U.ctrlKey&&l&&O){const Ne=Hi(U),Ue=fx(U),We=V*Math.pow(2,Ue);Q.scaleTo(D,We,Ne,U);return}const H=U.deltaMode===1?20:1;let Y=f===fc.Vertical?0:U.deltaX*H,ae=f===fc.Horizontal?0:U.deltaY*H;!O&&U.shiftKey&&f!==fc.Vertical&&(Y=U.deltaY*H,ae=0),Q.translateBy(D,-(Y/V)*u,-(ae/V)*u,{internal:!0});const ie=Em(D.property("__zoom")),{onViewportChangeStart:_e,onViewportChange:fe,onViewportChangeEnd:ge}=z.getState();clearTimeout(F.current),ee.current||(ee.current=!0,t==null||t(U,ie),_e==null||_e(ie)),ee.current&&(e==null||e(U,ie),fe==null||fe(ie),F.current=setTimeout(()=>{n==null||n(U,ie),ge==null||ge(ie),ee.current=!1},150))},{passive:!1}):typeof $<"u"&&D.on("wheel.zoom",function(U,V){if(!N||Su(U,T))return null;U.preventDefault(),$.call(this,U,V)},{passive:!1}))},[E,c,f,D,Q,$,L,l,N,T,t,e,n]),_.useEffect(()=>{Q&&Q.on("start",U=>{var H,Y;if(!U.sourceEvent||U.sourceEvent.internal)return null;M.current=(H=U.sourceEvent)==null?void 0:H.button;const{onViewportChangeStart:V}=z.getState(),O=Em(U.transform);J.current=!0,te.current=O,((Y=U.sourceEvent)==null?void 0:Y.type)==="mousedown"&&z.setState({paneDragging:!0}),V==null||V(O),t==null||t(U.sourceEvent,O)})},[Q,t]),_.useEffect(()=>{Q&&(E&&!J.current?Q.on("zoom",null):E||Q.on("zoom",U=>{var O;const{onViewportChange:V}=z.getState();if(z.setState({transform:[U.transform.x,U.transform.y,U.transform.k]}),K.current=!!(r&&dx(g,M.current??0)),(e||V)&&!((O=U.sourceEvent)!=null&&O.internal)){const H=Em(U.transform);V==null||V(H),e==null||e(U.sourceEvent,H)}}))},[E,Q,e,g,r]),_.useEffect(()=>{Q&&Q.on("end",U=>{if(!U.sourceEvent||U.sourceEvent.internal)return null;const{onViewportChangeEnd:V}=z.getState();if(J.current=!1,z.setState({paneDragging:!1}),r&&dx(g,M.current??0)&&!K.current&&r(U.sourceEvent),K.current=!1,(n||V)&&mI(te.current,U.transform)){const O=Em(U.transform);te.current=O,clearTimeout(W.current),W.current=setTimeout(()=>{V==null||V(O),n==null||n(U.sourceEvent,O)},c?150:0)}})},[Q,c,g,n,r]),_.useEffect(()=>{Q&&Q.filter(U=>{const V=L||o,O=l&&U.ctrlKey;if((g===!0||Array.isArray(g)&&g.includes(1))&&U.button===1&&U.type==="mousedown"&&(Su(U,"react-flow__node")||Su(U,"react-flow__edge")))return!0;if(!g&&!V&&!c&&!h&&!l||E||!h&&U.type==="dblclick"||Su(U,T)&&U.type==="wheel"||Su(U,A)&&(U.type!=="wheel"||c&&U.type==="wheel"&&!L)||!l&&U.ctrlKey&&U.type==="wheel"||!V&&!c&&!O&&U.type==="wheel"||!g&&(U.type==="mousedown"||U.type==="touchstart")||Array.isArray(g)&&!g.includes(U.button)&&(U.type==="mousedown"||U.type==="touchstart"))return!1;const H=Array.isArray(g)&&g.includes(U.button)||!U.button||U.button<=1;return(!U.ctrlKey||U.type==="wheel")&&H})},[E,Q,o,l,c,h,g,m,L]),xe.createElement("div",{className:"react-flow__renderer",ref:re,style:Ry},R)},gI=e=>({userSelectionActive:e.userSelectionActive,userSelectionRect:e.userSelectionRect});function yI(){const{userSelectionActive:e,userSelectionRect:t}=On(gI,Os);return e&&t?xe.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 hx(e,t){const n=e.find(r=>r.id===t.parentNode);if(n){const r=t.position.x+t.width-n.width,o=t.position.y+t.height-n.height;if(r>0||o>0||t.position.x<0||t.position.y<0){if(n.style={...n.style},n.style.width=n.style.width??n.width,n.style.height=n.style.height??n.height,r>0&&(n.style.width+=r),o>0&&(n.style.height+=o),t.position.x<0){const l=Math.abs(t.position.x);n.position.x=n.position.x-l,n.style.width+=l,t.position.x=0}if(t.position.y<0){const l=Math.abs(t.position.y);n.position.y=n.position.y-l,n.style.height+=l,t.position.y=0}n.width=n.style.width,n.height=n.style.height}}}function wI(e,t){if(e.some(r=>r.type==="reset"))return e.filter(r=>r.type==="reset").map(r=>r.item);const n=e.filter(r=>r.type==="add").map(r=>r.item);return t.reduce((r,o)=>{const l=e.filter(u=>u.id===o.id);if(l.length===0)return r.push(o),r;const c={...o};for(const u of l)if(u)switch(u.type){case"select":{c.selected=u.selected;break}case"position":{typeof u.position<"u"&&(c.position=u.position),typeof u.positionAbsolute<"u"&&(c.positionAbsolute=u.positionAbsolute),typeof u.dragging<"u"&&(c.dragging=u.dragging),c.expandParent&&hx(r,c);break}case"dimensions":{typeof u.dimensions<"u"&&(c.width=u.dimensions.width,c.height=u.dimensions.height),typeof u.updateStyle<"u"&&(c.style={...c.style||{},...u.dimensions}),typeof u.resizing=="boolean"&&(c.resizing=u.resizing),c.expandParent&&hx(r,c);break}case"remove":return r}return r.push(c),r},n)}function vI(e,t){return wI(e,t)}const fl=(e,t)=>({id:e,type:"select",selected:t});function Ru(e,t){return e.reduce((n,r)=>{const o=t.includes(r.id);return!r.selected&&o?(r.selected=!0,n.push(fl(r.id,!0))):r.selected&&!o&&(r.selected=!1,n.push(fl(r.id,!1))),n},[])}const Ip=(e,t)=>n=>{n.target===t.current&&(e==null||e(n))},xI=e=>({userSelectionActive:e.userSelectionActive,elementsSelectable:e.elementsSelectable,dragging:e.paneDragging}),nj=_.memo(({isSelecting:e,selectionMode:t=Wf.Full,panOnDrag:n,onSelectionStart:r,onSelectionEnd:o,onPaneClick:l,onPaneContextMenu:c,onPaneScroll:u,onPaneMouseEnter:f,onPaneMouseMove:h,onPaneMouseLeave:m,children:g})=>{const y=_.useRef(null),w=ks(),k=_.useRef(0),b=_.useRef(0),S=_.useRef(),{userSelectionActive:N,elementsSelectable:R,dragging:T}=On(xI,Os),A=()=>{w.setState({userSelectionActive:!1,userSelectionRect:null}),k.current=0,b.current=0},W=$=>{l==null||l($),w.getState().resetSelectedElements(),w.setState({nodesSelectionActive:!1})},z=$=>{if(Array.isArray(n)&&(n!=null&&n.includes(2))){$.preventDefault();return}c==null||c($)},J=u?$=>u($):void 0,K=$=>{const{resetSelectedElements:E,domNode:L}=w.getState();if(S.current=L==null?void 0:L.getBoundingClientRect(),!R||!e||$.button!==0||$.target!==y.current||!S.current)return;const{x:M,y:ee}=pl($,S.current);E(),w.setState({userSelectionRect:{width:0,height:0,startX:M,startY:ee,x:M,y:ee}}),r==null||r($)},re=$=>{const{userSelectionRect:E,nodeInternals:L,edges:M,transform:ee,onNodesChange:F,onEdgesChange:U,nodeOrigin:V,getNodes:O}=w.getState();if(!e||!S.current||!E)return;w.setState({userSelectionActive:!0,nodesSelectionActive:!1});const H=pl($,S.current),Y=E.startX??0,ae=E.startY??0,ie={...E,x:H.x<Y?H.x:Y,y:H.y<ae?H.y:ae,width:Math.abs(H.x-Y),height:Math.abs(H.y-ae)},_e=O(),fe=Dk(L,ie,ee,t===Wf.Partial,!0,V),ge=Fk(fe,M).map(Ue=>Ue.id),Ne=fe.map(Ue=>Ue.id);if(k.current!==Ne.length){k.current=Ne.length;const Ue=Ru(_e,Ne);Ue.length&&(F==null||F(Ue))}if(b.current!==ge.length){b.current=ge.length;const Ue=Ru(M,ge);Ue.length&&(U==null||U(Ue))}w.setState({userSelectionRect:ie})},te=$=>{if($.button!==0)return;const{userSelectionRect:E}=w.getState();!N&&E&&$.target===y.current&&(W==null||W($)),w.setState({nodesSelectionActive:k.current>0}),A(),o==null||o($)},Q=$=>{N&&(w.setState({nodesSelectionActive:k.current>0}),o==null||o($)),A()},D=R&&(e||N);return xe.createElement("div",{className:Vs(["react-flow__pane",{dragging:T,selection:e}]),onClick:D?void 0:Ip(W,y),onContextMenu:Ip(z,y),onWheel:Ip(J,y),onMouseEnter:D?void 0:f,onMouseDown:D?K:void 0,onMouseMove:D?re:h,onMouseUp:D?te:void 0,onMouseLeave:D?Q:m,ref:y,style:Ry},g,xe.createElement(yI,null))});nj.displayName="Pane";function sj(e,t){if(!e.parentNode)return!1;const n=t.get(e.parentNode);return n?n.selected?!0:sj(n,t):!1}function mx(e,t,n){let r=e;do{if(r!=null&&r.matches(t))return!0;if(r===n.current)return!1;r=r.parentElement}while(r);return!1}function bI(e,t,n,r){return Array.from(e.values()).filter(o=>(o.selected||o.id===r)&&(!o.parentNode||!sj(o,e))&&(o.draggable||t&&typeof o.draggable>"u")).map(o=>{var l,c;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-(((c=o.positionAbsolute)==null?void 0:c.y)??0)},delta:{x:0,y:0},extent:o.extent,parentNode:o.parentNode,width:o.width,height:o.height,expandParent:o.expandParent}})}function kI(e,t){return!t||t==="parent"?t:[t[0],[t[1][0]-(e.width||0),t[1][1]-(e.height||0)]]}function rj(e,t,n,r,o=[0,0],l){const c=kI(e,e.extent||r);let u=c;if(e.extent==="parent"&&!e.expandParent)if(e.parentNode&&e.width&&e.height){const m=n.get(e.parentNode),{x:g,y}=yc(m,o).positionAbsolute;u=m&&ji(g)&&ji(y)&&ji(m.width)&&ji(m.height)?[[g+e.width*o[0],y+e.height*o[1]],[g+m.width-e.width+e.width*o[0],y+m.height-e.height+e.height*o[1]]]:u}else l==null||l("005",va.error005()),u=c;else if(e.extent&&e.parentNode&&e.extent!=="parent"){const m=n.get(e.parentNode),{x:g,y}=yc(m,o).positionAbsolute;u=[[e.extent[0][0]+g,e.extent[0][1]+y],[e.extent[1][0]+g,e.extent[1][1]+y]]}let f={x:0,y:0};if(e.parentNode){const m=n.get(e.parentNode);f=yc(m,o).positionAbsolute}const h=u&&u!=="parent"?Sy(t,u):t;return{position:{x:h.x-f.x,y:h.y-f.y},positionAbsolute:h}}function Op({nodeId:e,dragItems:t,nodeInternals:n}){const r=t.map(o=>({...n.get(o.id),position:o.position,positionAbsolute:o.positionAbsolute}));return[e?r.find(o=>o.id===e):r[0],r]}const _x=(e,t,n,r)=>{const o=t.querySelectorAll(e);if(!o||!o.length)return null;const l=Array.from(o),c=t.getBoundingClientRect(),u={x:c.width*r[0],y:c.height*r[1]};return l.map(f=>{const h=f.getBoundingClientRect();return{id:f.getAttribute("data-handleid"),position:f.getAttribute("data-handlepos"),x:(h.left-c.left-u.x)/n,y:(h.top-c.top-u.y)/n,...jy(f)}})};function cf(e,t,n){return n===void 0?n:r=>{const o=t().nodeInternals.get(e);o&&n(r,{...o})}}function Fg({id:e,store:t,unselect:n=!1,nodeRef:r}){const{addSelectedNodes:o,unselectNodesAndEdges:l,multiSelectionActive:c,nodeInternals:u,onError:f}=t.getState(),h=u.get(e);if(!h){f==null||f("012",va.error012(e));return}t.setState({nodesSelectionActive:!1}),h.selected?(n||h.selected&&c)&&(l({nodes:[h],edges:[]}),requestAnimationFrame(()=>{var m;return(m=r==null?void 0:r.current)==null?void 0:m.blur()})):o([e])}function jI(){const e=ks();return _.useCallback(({sourceEvent:n})=>{const{transform:r,snapGrid:o,snapToGrid:l}=e.getState(),c=n.touches?n.touches[0].clientX:n.clientX,u=n.touches?n.touches[0].clientY:n.clientY,f={x:(c-r[0])/r[2],y:(u-r[1])/r[2]};return{xSnapped:l?o[0]*Math.round(f.x/o[0]):f.x,ySnapped:l?o[1]*Math.round(f.y/o[1]):f.y,...f}},[])}function Pp(e){return(t,n,r)=>e==null?void 0:e(t,r)}function ij({nodeRef:e,disabled:t=!1,noDragClassName:n,handleSelector:r,nodeId:o,isSelectable:l,selectNodesOnDrag:c}){const u=ks(),[f,h]=_.useState(!1),m=_.useRef([]),g=_.useRef({x:null,y:null}),y=_.useRef(0),w=_.useRef(null),k=_.useRef({x:0,y:0}),b=_.useRef(null),S=_.useRef(!1),N=_.useRef(!1),R=jI();return _.useEffect(()=>{if(e!=null&&e.current){const T=ki(e.current),A=({x:J,y:K})=>{const{nodeInternals:re,onNodeDrag:te,onSelectionDrag:Q,updateNodePositions:D,nodeExtent:$,snapGrid:E,snapToGrid:L,nodeOrigin:M,onError:ee}=u.getState();g.current={x:J,y:K};let F=!1,U={x:0,y:0,x2:0,y2:0};if(m.current.length>1&&$){const O=N_(m.current,M);U=Uf(O)}if(m.current=m.current.map(O=>{const H={x:J-O.distance.x,y:K-O.distance.y};L&&(H.x=E[0]*Math.round(H.x/E[0]),H.y=E[1]*Math.round(H.y/E[1]));const Y=[[$[0][0],$[0][1]],[$[1][0],$[1][1]]];m.current.length>1&&$&&!O.extent&&(Y[0][0]=O.positionAbsolute.x-U.x+$[0][0],Y[1][0]=O.positionAbsolute.x+(O.width??0)-U.x2+$[1][0],Y[0][1]=O.positionAbsolute.y-U.y+$[0][1],Y[1][1]=O.positionAbsolute.y+(O.height??0)-U.y2+$[1][1]);const ae=rj(O,H,re,Y,M,ee);return F=F||O.position.x!==ae.position.x||O.position.y!==ae.position.y,O.position=ae.position,O.positionAbsolute=ae.positionAbsolute,O}),!F)return;D(m.current,!0,!0),h(!0);const V=o?te:Pp(Q);if(V&&b.current){const[O,H]=Op({nodeId:o,dragItems:m.current,nodeInternals:re});V(b.current,O,H)}},W=()=>{if(!w.current)return;const[J,K]=Ck(k.current,w.current);if(J!==0||K!==0){const{transform:re,panBy:te}=u.getState();g.current.x=(g.current.x??0)-J/re[2],g.current.y=(g.current.y??0)-K/re[2],te({x:J,y:K})&&A(g.current)}y.current=requestAnimationFrame(W)},z=J=>{var M;const{nodeInternals:K,multiSelectionActive:re,nodesDraggable:te,unselectNodesAndEdges:Q,onNodeDragStart:D,onSelectionDragStart:$}=u.getState();N.current=!0;const E=o?D:Pp($);(!c||!l)&&!re&&o&&((M=K.get(o))!=null&&M.selected||Q()),o&&l&&c&&Fg({id:o,store:u,nodeRef:e});const L=R(J);if(g.current=L,m.current=bI(K,te,L,o),E&&m.current){const[ee,F]=Op({nodeId:o,dragItems:m.current,nodeInternals:K});E(J.sourceEvent,ee,F)}};if(t)T.on(".drag",null);else{const J=LL().on("start",K=>{const{domNode:re,nodeDragThreshold:te}=u.getState();te===0&&z(K);const Q=R(K);g.current=Q,w.current=(re==null?void 0:re.getBoundingClientRect())||null,k.current=pl(K.sourceEvent,w.current)}).on("drag",K=>{var D,$;const re=R(K),{autoPanOnNodeDrag:te,nodeDragThreshold:Q}=u.getState();if(!S.current&&N.current&&te&&(S.current=!0,W()),!N.current){const E=re.xSnapped-(((D=g==null?void 0:g.current)==null?void 0:D.x)??0),L=re.ySnapped-((($=g==null?void 0:g.current)==null?void 0:$.y)??0);Math.sqrt(E*E+L*L)>Q&&z(K)}(g.current.x!==re.xSnapped||g.current.y!==re.ySnapped)&&m.current&&N.current&&(b.current=K.sourceEvent,k.current=pl(K.sourceEvent,w.current),A(re))}).on("end",K=>{if(N.current&&(h(!1),S.current=!1,N.current=!1,cancelAnimationFrame(y.current),m.current)){const{updateNodePositions:re,nodeInternals:te,onNodeDragStop:Q,onSelectionDragStop:D}=u.getState(),$=o?Q:Pp(D);if(re(m.current,!1,!1),$){const[E,L]=Op({nodeId:o,dragItems:m.current,nodeInternals:te});$(K.sourceEvent,E,L)}}}).filter(K=>{const re=K.target;return!K.button&&(!n||!mx(re,`.${n}`,e))&&(!r||mx(re,r,e))});return T.call(J),()=>{T.on(".drag",null)}}}},[e,t,n,r,l,u,o,c,R]),f}function oj(){const e=ks();return _.useCallback(n=>{const{nodeInternals:r,nodeExtent:o,updateNodePositions:l,getNodes:c,snapToGrid:u,snapGrid:f,onError:h,nodesDraggable:m}=e.getState(),g=c().filter(R=>R.selected&&(R.draggable||m&&typeof R.draggable>"u")),y=u?f[0]:5,w=u?f[1]:5,k=n.isShiftPressed?4:1,b=n.x*y*k,S=n.y*w*k,N=g.map(R=>{if(R.positionAbsolute){const T={x:R.positionAbsolute.x+b,y:R.positionAbsolute.y+S};u&&(T.x=f[0]*Math.round(T.x/f[0]),T.y=f[1]*Math.round(T.y/f[1]));const{positionAbsolute:A,position:W}=rj(R,T,r,o,void 0,h);R.position=W,R.positionAbsolute=A}return R});l(N,!0,!1)},[])}const zu={ArrowUp:{x:0,y:-1},ArrowDown:{x:0,y:1},ArrowLeft:{x:-1,y:0},ArrowRight:{x:1,y:0}};var uf=e=>{const t=({id:n,type:r,data:o,xPos:l,yPos:c,xPosOrigin:u,yPosOrigin:f,selected:h,onClick:m,onMouseEnter:g,onMouseMove:y,onMouseLeave:w,onContextMenu:k,onDoubleClick:b,style:S,className:N,isDraggable:R,isSelectable:T,isConnectable:A,isFocusable:W,selectNodesOnDrag:z,sourcePosition:J,targetPosition:K,hidden:re,resizeObserver:te,dragHandle:Q,zIndex:D,isParent:$,noDragClassName:E,noPanClassName:L,initialized:M,disableKeyboardA11y:ee,ariaLabel:F,rfId:U,hasHandleBounds:V})=>{const O=ks(),H=_.useRef(null),Y=_.useRef(J),ae=_.useRef(K),ie=_.useRef(r),_e=T||R||m||g||y||w,fe=oj(),ge=cf(n,O.getState,g),Ne=cf(n,O.getState,y),Ue=cf(n,O.getState,w),We=cf(n,O.getState,k),ut=cf(n,O.getState,b),Fe=Ve=>{const{nodeDragThreshold:le}=O.getState();if(T&&(!z||!R||le>0)&&Fg({id:n,store:O,nodeRef:H}),m){const be=O.getState().nodeInternals.get(n);be&&m(Ve,{...be})}},et=Ve=>{if(!Lg(Ve))if(Tk.includes(Ve.key)&&T){const le=Ve.key==="Escape";Fg({id:n,store:O,unselect:le,nodeRef:H})}else!ee&&R&&h&&Object.prototype.hasOwnProperty.call(zu,Ve.key)&&(O.setState({ariaLiveMessage:`Moved selected node ${Ve.key.replace("Arrow","").toLowerCase()}. New position, x: ${~~l}, y: ${~~c}`}),fe({x:zu[Ve.key].x,y:zu[Ve.key].y,isShiftPressed:Ve.shiftKey}))};_.useEffect(()=>()=>{H.current&&(te==null||te.unobserve(H.current))},[]),_.useEffect(()=>{if(H.current&&!re){const Ve=H.current;(!M||!V)&&(te==null||te.unobserve(Ve),te==null||te.observe(Ve))}},[re,M,V]),_.useEffect(()=>{const Ve=ie.current!==r,le=Y.current!==J,be=ae.current!==K;H.current&&(Ve||le||be)&&(Ve&&(ie.current=r),le&&(Y.current=J),be&&(ae.current=K),O.getState().updateNodeDimensions([{id:n,nodeElement:H.current,forceUpdate:!0}]))},[n,r,J,K]);const $e=ij({nodeRef:H,disabled:re||!R,noDragClassName:E,handleSelector:Q,nodeId:n,isSelectable:T,selectNodesOnDrag:z});return re?null:xe.createElement("div",{className:Vs(["react-flow__node",`react-flow__node-${r}`,{[L]:R},N,{selected:h,selectable:T,parent:$,dragging:$e}]),ref:H,style:{zIndex:D,transform:`translate(${u}px,${f}px)`,pointerEvents:_e?"all":"none",visibility:M?"visible":"hidden",...S},"data-id":n,"data-testid":`rf__node-${n}`,onMouseEnter:ge,onMouseMove:Ne,onMouseLeave:Ue,onContextMenu:We,onClick:Fe,onDoubleClick:ut,onKeyDown:W?et:void 0,tabIndex:W?0:void 0,role:W?"button":void 0,"aria-describedby":ee?void 0:`${Xk}-${U}`,"aria-label":F},xe.createElement(P4,{value:n},xe.createElement(e,{id:n,data:o,type:r,xPos:l,yPos:c,selected:h,isConnectable:A,sourcePosition:J,targetPosition:K,dragging:$e,dragHandle:Q,zIndex:D})))};return t.displayName="NodeWrapper",_.memo(t)};const SI=e=>{const t=e.getNodes().filter(n=>n.selected);return{...N_(t,e.nodeOrigin),transformString:`translate(${e.transform[0]}px,${e.transform[1]}px) scale(${e.transform[2]})`,userSelectionActive:e.userSelectionActive}};function NI({onSelectionContextMenu:e,noPanClassName:t,disableKeyboardA11y:n}){const r=ks(),{width:o,height:l,x:c,y:u,transformString:f,userSelectionActive:h}=On(SI,Os),m=oj(),g=_.useRef(null);if(_.useEffect(()=>{var k;n||(k=g.current)==null||k.focus({preventScroll:!0})},[n]),ij({nodeRef:g}),h||!o||!l)return null;const y=e?k=>{const b=r.getState().getNodes().filter(S=>S.selected);e(k,b)}:void 0,w=k=>{Object.prototype.hasOwnProperty.call(zu,k.key)&&m({x:zu[k.key].x,y:zu[k.key].y,isShiftPressed:k.shiftKey})};return xe.createElement("div",{className:Vs(["react-flow__nodesselection","react-flow__container",t]),style:{transform:f}},xe.createElement("div",{ref:g,className:"react-flow__nodesselection-rect",onContextMenu:y,tabIndex:n?void 0:-1,onKeyDown:n?void 0:w,style:{width:o,height:l,top:u,left:c}}))}var CI=_.memo(NI);const EI=e=>e.nodesSelectionActive,aj=({children:e,onPaneClick:t,onPaneMouseEnter:n,onPaneMouseMove:r,onPaneMouseLeave:o,onPaneContextMenu:l,onPaneScroll:c,deleteKeyCode:u,onMove:f,onMoveStart:h,onMoveEnd:m,selectionKeyCode:g,selectionOnDrag:y,selectionMode:w,onSelectionStart:k,onSelectionEnd:b,multiSelectionKeyCode:S,panActivationKeyCode:N,zoomActivationKeyCode:R,elementsSelectable:T,zoomOnScroll:A,zoomOnPinch:W,panOnScroll:z,panOnScrollSpeed:J,panOnScrollMode:K,zoomOnDoubleClick:re,panOnDrag:te,defaultViewport:Q,translateExtent:D,minZoom:$,maxZoom:E,preventScrolling:L,onSelectionContextMenu:M,noWheelClassName:ee,noPanClassName:F,disableKeyboardA11y:U})=>{const V=On(EI),O=Hf(g),H=Hf(N),Y=H||te,ae=H||z,ie=O||y&&Y!==!0;return fI({deleteKeyCode:u,multiSelectionKeyCode:S}),xe.createElement(pI,{onMove:f,onMoveStart:h,onMoveEnd:m,onPaneContextMenu:l,elementsSelectable:T,zoomOnScroll:A,zoomOnPinch:W,panOnScroll:ae,panOnScrollSpeed:J,panOnScrollMode:K,zoomOnDoubleClick:re,panOnDrag:!O&&Y,defaultViewport:Q,translateExtent:D,minZoom:$,maxZoom:E,zoomActivationKeyCode:R,preventScrolling:L,noWheelClassName:ee,noPanClassName:F},xe.createElement(nj,{onSelectionStart:k,onSelectionEnd:b,onPaneClick:t,onPaneMouseEnter:n,onPaneMouseMove:r,onPaneMouseLeave:o,onPaneContextMenu:l,onPaneScroll:c,panOnDrag:Y,isSelecting:!!ie,selectionMode:w},e,V&&xe.createElement(CI,{onSelectionContextMenu:M,noPanClassName:F,disableKeyboardA11y:U})))};aj.displayName="FlowRenderer";var $I=_.memo(aj);function AI(e){return On(_.useCallback(n=>e?Dk(n.nodeInternals,{x:0,y:0,width:n.width,height:n.height},n.transform,!0):n.getNodes(),[e]))}function TI(e){const t={input:uf(e.input||Gk),default:uf(e.default||Dg),output:uf(e.output||Yk),group:uf(e.group||Ty)},n={},r=Object.keys(e).filter(o=>!["input","default","output","group"].includes(o)).reduce((o,l)=>(o[l]=uf(e[l]||Dg),o),n);return{...t,...r}}const MI=({x:e,y:t,width:n,height:r,origin:o})=>!n||!r?{x:e,y:t}:o[0]<0||o[1]<0||o[0]>1||o[1]>1?{x:e,y:t}:{x:e-n*o[0],y:t-r*o[1]},RI=e=>({nodesDraggable:e.nodesDraggable,nodesConnectable:e.nodesConnectable,nodesFocusable:e.nodesFocusable,elementsSelectable:e.elementsSelectable,updateNodeDimensions:e.updateNodeDimensions,onError:e.onError}),lj=e=>{const{nodesDraggable:t,nodesConnectable:n,nodesFocusable:r,elementsSelectable:o,updateNodeDimensions:l,onError:c}=On(RI,Os),u=AI(e.onlyRenderVisibleElements),f=_.useRef(),h=_.useMemo(()=>{if(typeof ResizeObserver>"u")return null;const m=new ResizeObserver(g=>{const y=g.map(w=>({id:w.target.getAttribute("data-id"),nodeElement:w.target,forceUpdate:!0}));l(y)});return f.current=m,m},[]);return _.useEffect(()=>()=>{var m;(m=f==null?void 0:f.current)==null||m.disconnect()},[]),xe.createElement("div",{className:"react-flow__nodes",style:Ry},u.map(m=>{var W,z,J;let g=m.type||"default";e.nodeTypes[g]||(c==null||c("003",va.error003(g)),g="default");const y=e.nodeTypes[g]||e.nodeTypes.default,w=!!(m.draggable||t&&typeof m.draggable>"u"),k=!!(m.selectable||o&&typeof m.selectable>"u"),b=!!(m.connectable||n&&typeof m.connectable>"u"),S=!!(m.focusable||r&&typeof m.focusable>"u"),N=e.nodeExtent?Sy(m.positionAbsolute,e.nodeExtent):m.positionAbsolute,R=(N==null?void 0:N.x)??0,T=(N==null?void 0:N.y)??0,A=MI({x:R,y:T,width:m.width??0,height:m.height??0,origin:e.nodeOrigin});return xe.createElement(y,{key:m.id,id:m.id,className:m.className,style:m.style,type:g,data:m.data,sourcePosition:m.sourcePosition||vt.Bottom,targetPosition:m.targetPosition||vt.Top,hidden:m.hidden,xPos:R,yPos:T,xPosOrigin:A.x,yPosOrigin:A.y,selectNodesOnDrag:e.selectNodesOnDrag,onClick:e.onNodeClick,onMouseEnter:e.onNodeMouseEnter,onMouseMove:e.onNodeMouseMove,onMouseLeave:e.onNodeMouseLeave,onContextMenu:e.onNodeContextMenu,onDoubleClick:e.onNodeDoubleClick,selected:!!m.selected,isDraggable:w,isSelectable:k,isConnectable:b,isFocusable:S,resizeObserver:h,dragHandle:m.dragHandle,zIndex:((W=m[us])==null?void 0:W.z)??0,isParent:!!((z=m[us])!=null&&z.isParent),noDragClassName:e.noDragClassName,noPanClassName:e.noPanClassName,initialized:!!m.width&&!!m.height,rfId:e.rfId,disableKeyboardA11y:e.disableKeyboardA11y,ariaLabel:m.ariaLabel,hasHandleBounds:!!((J=m[us])!=null&&J.handleBounds)})}))};lj.displayName="NodeRenderer";var LI=_.memo(lj);const II=(e,t,n)=>n===vt.Left?e-t:n===vt.Right?e+t:e,OI=(e,t,n)=>n===vt.Top?e-t:n===vt.Bottom?e+t:e,px="react-flow__edgeupdater",gx=({position:e,centerX:t,centerY:n,radius:r=10,onMouseDown:o,onMouseEnter:l,onMouseOut:c,type:u})=>xe.createElement("circle",{onMouseDown:o,onMouseEnter:l,onMouseOut:c,className:Vs([px,`${px}-${u}`]),cx:II(t,r,e),cy:OI(n,r,e),r,stroke:"transparent",fill:"transparent"}),PI=()=>!0;var Nu=e=>{const t=({id:n,className:r,type:o,data:l,onClick:c,onEdgeDoubleClick:u,selected:f,animated:h,label:m,labelStyle:g,labelShowBg:y,labelBgStyle:w,labelBgPadding:k,labelBgBorderRadius:b,style:S,source:N,target:R,sourceX:T,sourceY:A,targetX:W,targetY:z,sourcePosition:J,targetPosition:K,elementsSelectable:re,hidden:te,sourceHandleId:Q,targetHandleId:D,onContextMenu:$,onMouseEnter:E,onMouseMove:L,onMouseLeave:M,edgeUpdaterRadius:ee,onEdgeUpdate:F,onEdgeUpdateStart:U,onEdgeUpdateEnd:V,markerEnd:O,markerStart:H,rfId:Y,ariaLabel:ae,isFocusable:ie,isUpdatable:_e,pathOptions:fe,interactionWidth:ge})=>{const Ne=_.useRef(null),[Ue,We]=_.useState(!1),[ut,Fe]=_.useState(!1),et=ks(),$e=_.useMemo(()=>`url('#${Og(H,Y)}')`,[H,Y]),Ve=_.useMemo(()=>`url('#${Og(O,Y)}')`,[O,Y]);if(te)return null;const le=zt=>{var bn;const{edges:wn,addSelectedEdges:Un,unselectNodesAndEdges:Mn,multiSelectionActive:vn}=et.getState(),Dn=wn.find(js=>js.id===n);Dn&&(re&&(et.setState({nodesSelectionActive:!1}),Dn.selected&&vn?(Mn({nodes:[],edges:[Dn]}),(bn=Ne.current)==null||bn.blur()):Un([n])),c&&c(zt,Dn))},be=lf(n,et.getState,u),Pe=lf(n,et.getState,$),me=lf(n,et.getState,E),Ce=lf(n,et.getState,L),Te=lf(n,et.getState,M),Je=(zt,wn)=>{if(zt.button!==0)return;const{edges:Un,isValidConnection:Mn}=et.getState(),vn=wn?R:N,Dn=(wn?D:Q)||null,bn=wn?"target":"source",js=Mn||PI,Kn=wn,Ss=Un.find(de=>de.id===n);Fe(!0),U==null||U(zt,Ss,bn);const Ar=de=>{Fe(!1),V==null||V(de,Ss,bn)};Wk({event:zt,handleId:Dn,nodeId:vn,onConnect:de=>F==null?void 0:F(Ss,de),isTarget:Kn,getState:et.getState,setState:et.setState,isValidConnection:js,edgeUpdaterType:bn,onEdgeUpdateEnd:Ar})},rt=zt=>Je(zt,!0),ht=zt=>Je(zt,!1),lt=()=>We(!0),Ct=()=>We(!1),Xt=!re&&!c,Pn=zt=>{var wn;if(Tk.includes(zt.key)&&re){const{unselectNodesAndEdges:Un,addSelectedEdges:Mn,edges:vn}=et.getState();zt.key==="Escape"?((wn=Ne.current)==null||wn.blur(),Un({edges:[vn.find(bn=>bn.id===n)]})):Mn([n])}};return xe.createElement("g",{className:Vs(["react-flow__edge",`react-flow__edge-${o}`,r,{selected:f,animated:h,inactive:Xt,updating:Ue}]),onClick:le,onDoubleClick:be,onContextMenu:Pe,onMouseEnter:me,onMouseMove:Ce,onMouseLeave:Te,onKeyDown:ie?Pn:void 0,tabIndex:ie?0:void 0,role:ie?"button":"img","data-testid":`rf__edge-${n}`,"aria-label":ae===null?void 0:ae||`Edge from ${N} to ${R}`,"aria-describedby":ie?`${Zk}-${Y}`:void 0,ref:Ne},!ut&&xe.createElement(e,{id:n,source:N,target:R,selected:f,animated:h,label:m,labelStyle:g,labelShowBg:y,labelBgStyle:w,labelBgPadding:k,labelBgBorderRadius:b,data:l,style:S,sourceX:T,sourceY:A,targetX:W,targetY:z,sourcePosition:J,targetPosition:K,sourceHandleId:Q,targetHandleId:D,markerStart:$e,markerEnd:Ve,pathOptions:fe,interactionWidth:ge}),_e&&xe.createElement(xe.Fragment,null,(_e==="source"||_e===!0)&&xe.createElement(gx,{position:J,centerX:T,centerY:A,radius:ee,onMouseDown:rt,onMouseEnter:lt,onMouseOut:Ct,type:"source"}),(_e==="target"||_e===!0)&&xe.createElement(gx,{position:K,centerX:W,centerY:z,radius:ee,onMouseDown:ht,onMouseEnter:lt,onMouseOut:Ct,type:"target"})))};return t.displayName="EdgeWrapper",_.memo(t)};function DI(e){const t={default:Nu(e.default||o_),straight:Nu(e.bezier||Ey),step:Nu(e.step||Cy),smoothstep:Nu(e.step||S_),simplebezier:Nu(e.simplebezier||Ny)},n={},r=Object.keys(e).filter(o=>!["default","bezier"].includes(o)).reduce((o,l)=>(o[l]=Nu(e[l]||o_),o),n);return{...t,...r}}function yx(e,t,n=null){const r=((n==null?void 0:n.x)||0)+t.x,o=((n==null?void 0:n.y)||0)+t.y,l=(n==null?void 0:n.width)||t.width,c=(n==null?void 0:n.height)||t.height;switch(e){case vt.Top:return{x:r+l/2,y:o};case vt.Right:return{x:r+l,y:o+c/2};case vt.Bottom:return{x:r+l/2,y:o+c};case vt.Left:return{x:r,y:o+c/2}}}function wx(e,t){return e?e.length===1||!t?e[0]:t&&e.find(n=>n.id===t)||null:null}const FI=(e,t,n,r,o,l)=>{const c=yx(n,e,t),u=yx(l,r,o);return{sourceX:c.x,sourceY:c.y,targetX:u.x,targetY:u.y}};function zI({sourcePos:e,targetPos:t,sourceWidth:n,sourceHeight:r,targetWidth:o,targetHeight:l,width:c,height:u,transform:f}){const h={x:Math.min(e.x,t.x),y:Math.min(e.y,t.y),x2:Math.max(e.x+n,t.x+o),y2:Math.max(e.y+r,t.y+l)};h.x===h.x2&&(h.x2+=1),h.y===h.y2&&(h.y2+=1);const m=Uf({x:(0-f[0])/f[2],y:(0-f[1])/f[2],width:c/f[2],height:u/f[2]}),g=Math.max(0,Math.min(m.x2,h.x2)-Math.max(m.x,h.x)),y=Math.max(0,Math.min(m.y2,h.y2)-Math.max(m.y,h.y));return Math.ceil(g*y)>0}function vx(e){var r,o,l,c,u;const t=((r=e==null?void 0:e[us])==null?void 0:r.handleBounds)||null,n=t&&(e==null?void 0:e.width)&&(e==null?void 0:e.height)&&typeof((o=e==null?void 0:e.positionAbsolute)==null?void 0:o.x)<"u"&&typeof((l=e==null?void 0:e.positionAbsolute)==null?void 0:l.y)<"u";return[{x:((c=e==null?void 0:e.positionAbsolute)==null?void 0:c.x)||0,y:((u=e==null?void 0:e.positionAbsolute)==null?void 0:u.y)||0,width:(e==null?void 0:e.width)||0,height:(e==null?void 0:e.height)||0},t,!!n]}const BI=[{level:0,isMaxLevel:!0,edges:[]}];function UI(e,t,n=!1){let r=-1;const o=e.reduce((c,u)=>{var m,g;const f=ji(u.zIndex);let h=f?u.zIndex:0;if(n){const y=t.get(u.target),w=t.get(u.source),k=u.selected||(y==null?void 0:y.selected)||(w==null?void 0:w.selected),b=Math.max(((m=w==null?void 0:w[us])==null?void 0:m.z)||0,((g=y==null?void 0:y[us])==null?void 0:g.z)||0,1e3);h=(f?u.zIndex:0)+(k?b:0)}return c[h]?c[h].push(u):c[h]=[u],r=h>r?h:r,c},{}),l=Object.entries(o).map(([c,u])=>{const f=+c;return{edges:u,level:f,isMaxLevel:f===r}});return l.length===0?BI:l}function WI(e,t,n){const r=On(_.useCallback(o=>e?o.edges.filter(l=>{const c=t.get(l.source),u=t.get(l.target);return(c==null?void 0:c.width)&&(c==null?void 0:c.height)&&(u==null?void 0:u.width)&&(u==null?void 0:u.height)&&zI({sourcePos:c.positionAbsolute||{x:0,y:0},targetPos:u.positionAbsolute||{x:0,y:0},sourceWidth:c.width,sourceHeight:c.height,targetWidth:u.width,targetHeight:u.height,width:o.width,height:o.height,transform:o.transform})}):o.edges,[e,t]));return UI(r,t,n)}const qI=({color:e="none",strokeWidth:t=1})=>xe.createElement("polyline",{style:{stroke:e,strokeWidth:t},strokeLinecap:"round",strokeLinejoin:"round",fill:"none",points:"-5,-4 0,0 -5,4"}),HI=({color:e="none",strokeWidth:t=1})=>xe.createElement("polyline",{style:{stroke:e,fill:e,strokeWidth:t},strokeLinecap:"round",strokeLinejoin:"round",points:"-5,-4 0,0 -5,4 -5,-4"}),xx={[qf.Arrow]:qI,[qf.ArrowClosed]:HI};function VI(e){const t=ks();return _.useMemo(()=>{var o,l;return Object.prototype.hasOwnProperty.call(xx,e)?xx[e]:((l=(o=t.getState()).onError)==null||l.call(o,"009",va.error009(e)),null)},[e])}const GI=({id:e,type:t,color:n,width:r=12.5,height:o=12.5,markerUnits:l="strokeWidth",strokeWidth:c,orient:u="auto-start-reverse"})=>{const f=VI(t);return f?xe.createElement("marker",{className:"react-flow__arrowhead",id:e,markerWidth:`${r}`,markerHeight:`${o}`,viewBox:"-10 -10 20 20",markerUnits:l,orient:u,refX:"0",refY:"0"},xe.createElement(f,{color:n,strokeWidth:c})):null},KI=({defaultColor:e,rfId:t})=>n=>{const r=[];return n.edges.reduce((o,l)=>([l.markerStart,l.markerEnd].forEach(c=>{if(c&&typeof c=="object"){const u=Og(c,t);r.includes(u)||(o.push({id:u,color:c.color||e,...c}),r.push(u))}}),o),[]).sort((o,l)=>o.id.localeCompare(l.id))},cj=({defaultColor:e,rfId:t})=>{const n=On(_.useCallback(KI({defaultColor:e,rfId:t}),[e,t]),(r,o)=>!(r.length!==o.length||r.some((l,c)=>l.id!==o[c].id)));return xe.createElement("defs",null,n.map(r=>xe.createElement(GI,{id:r.id,key:r.id,type:r.type,color:r.color,width:r.width,height:r.height,markerUnits:r.markerUnits,strokeWidth:r.strokeWidth,orient:r.orient})))};cj.displayName="MarkerDefinitions";var YI=_.memo(cj);const JI=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}),uj=({defaultMarkerColor:e,onlyRenderVisibleElements:t,elevateEdgesOnSelect:n,rfId:r,edgeTypes:o,noPanClassName:l,onEdgeUpdate:c,onEdgeContextMenu:u,onEdgeMouseEnter:f,onEdgeMouseMove:h,onEdgeMouseLeave:m,onEdgeClick:g,edgeUpdaterRadius:y,onEdgeDoubleClick:w,onEdgeUpdateStart:k,onEdgeUpdateEnd:b,children:S})=>{const{edgesFocusable:N,edgesUpdatable:R,elementsSelectable:T,width:A,height:W,connectionMode:z,nodeInternals:J,onError:K}=On(JI,Os),re=WI(t,J,n);return A?xe.createElement(xe.Fragment,null,re.map(({level:te,edges:Q,isMaxLevel:D})=>xe.createElement("svg",{key:te,style:{zIndex:te},width:A,height:W,className:"react-flow__edges react-flow__container"},D&&xe.createElement(YI,{defaultColor:e,rfId:r}),xe.createElement("g",null,Q.map($=>{const[E,L,M]=vx(J.get($.source)),[ee,F,U]=vx(J.get($.target));if(!M||!U)return null;let V=$.type||"default";o[V]||(K==null||K("011",va.error011(V)),V="default");const O=o[V]||o.default,H=z===jc.Strict?F.target:(F.target??[]).concat(F.source??[]),Y=wx(L.source,$.sourceHandle),ae=wx(H,$.targetHandle),ie=(Y==null?void 0:Y.position)||vt.Bottom,_e=(ae==null?void 0:ae.position)||vt.Top,fe=!!($.focusable||N&&typeof $.focusable>"u"),ge=typeof c<"u"&&($.updatable||R&&typeof $.updatable>"u");if(!Y||!ae)return K==null||K("008",va.error008(Y,$)),null;const{sourceX:Ne,sourceY:Ue,targetX:We,targetY:ut}=FI(E,Y,ie,ee,ae,_e);return xe.createElement(O,{key:$.id,id:$.id,className:Vs([$.className,l]),type:V,data:$.data,selected:!!$.selected,animated:!!$.animated,hidden:!!$.hidden,label:$.label,labelStyle:$.labelStyle,labelShowBg:$.labelShowBg,labelBgStyle:$.labelBgStyle,labelBgPadding:$.labelBgPadding,labelBgBorderRadius:$.labelBgBorderRadius,style:$.style,source:$.source,target:$.target,sourceHandleId:$.sourceHandle,targetHandleId:$.targetHandle,markerEnd:$.markerEnd,markerStart:$.markerStart,sourceX:Ne,sourceY:Ue,targetX:We,targetY:ut,sourcePosition:ie,targetPosition:_e,elementsSelectable:T,onEdgeUpdate:c,onContextMenu:u,onMouseEnter:f,onMouseMove:h,onMouseLeave:m,onClick:g,edgeUpdaterRadius:y,onEdgeDoubleClick:w,onEdgeUpdateStart:k,onEdgeUpdateEnd:b,rfId:r,ariaLabel:$.ariaLabel,isFocusable:fe,isUpdatable:ge,pathOptions:"pathOptions"in $?$.pathOptions:void 0,interactionWidth:$.interactionWidth})})))),S):null};uj.displayName="EdgeRenderer";var XI=_.memo(uj);const ZI=e=>`translate(${e.transform[0]}px,${e.transform[1]}px) scale(${e.transform[2]})`;function QI({children:e}){const t=On(ZI);return xe.createElement("div",{className:"react-flow__viewport react-flow__container",style:{transform:t}},e)}function e5(e){const t=My(),n=_.useRef(!1);_.useEffect(()=>{!n.current&&t.viewportInitialized&&e&&(setTimeout(()=>e(t),1),n.current=!0)},[e,t.viewportInitialized])}const t5={[vt.Left]:vt.Right,[vt.Right]:vt.Left,[vt.Top]:vt.Bottom,[vt.Bottom]:vt.Top},dj=({nodeId:e,handleType:t,style:n,type:r=hl.Bezier,CustomComponent:o,connectionStatus:l})=>{var z,J,K;const{fromNode:c,handleId:u,toX:f,toY:h,connectionMode:m}=On(_.useCallback(re=>({fromNode:re.nodeInternals.get(e),handleId:re.connectionHandleId,toX:(re.connectionPosition.x-re.transform[0])/re.transform[2],toY:(re.connectionPosition.y-re.transform[1])/re.transform[2],connectionMode:re.connectionMode}),[e]),Os),g=(z=c==null?void 0:c[us])==null?void 0:z.handleBounds;let y=g==null?void 0:g[t];if(m===jc.Loose&&(y=y||(g==null?void 0:g[t==="source"?"target":"source"])),!c||!y)return null;const w=u?y.find(re=>re.id===u):y[0],k=w?w.x+w.width/2:(c.width??0)/2,b=w?w.y+w.height/2:c.height??0,S=(((J=c.positionAbsolute)==null?void 0:J.x)??0)+k,N=(((K=c.positionAbsolute)==null?void 0:K.y)??0)+b,R=w==null?void 0:w.position,T=R?t5[R]:null;if(!R||!T)return null;if(o)return xe.createElement(o,{connectionLineType:r,connectionLineStyle:n,fromNode:c,fromHandle:w,fromX:S,fromY:N,toX:f,toY:h,fromPosition:R,toPosition:T,connectionStatus:l});let A="";const W={sourceX:S,sourceY:N,sourcePosition:R,targetX:f,targetY:h,targetPosition:T};return r===hl.Bezier?[A]=Ok(W):r===hl.Step?[A]=Ig({...W,borderRadius:0}):r===hl.SmoothStep?[A]=Ig(W):r===hl.SimpleBezier?[A]=Ik(W):A=`M${S},${N} ${f},${h}`,xe.createElement("path",{d:A,fill:"none",className:"react-flow__connection-path",style:n})};dj.displayName="ConnectionLine";const n5=e=>({nodeId:e.connectionNodeId,handleType:e.connectionHandleType,nodesConnectable:e.nodesConnectable,connectionStatus:e.connectionStatus,width:e.width,height:e.height});function s5({containerStyle:e,style:t,type:n,component:r}){const{nodeId:o,handleType:l,nodesConnectable:c,width:u,height:f,connectionStatus:h}=On(n5,Os);return!(o&&l&&u&&c)?null:xe.createElement("svg",{style:e,width:u,height:f,className:"react-flow__edges react-flow__connectionline react-flow__container"},xe.createElement("g",{className:Vs(["react-flow__connection",h])},xe.createElement(dj,{nodeId:o,handleType:l,style:t,type:n,CustomComponent:r,connectionStatus:h})))}function bx(e,t){return _.useRef(null),ks(),_.useMemo(()=>t(e),[e])}const fj=({nodeTypes:e,edgeTypes:t,onMove:n,onMoveStart:r,onMoveEnd:o,onInit:l,onNodeClick:c,onEdgeClick:u,onNodeDoubleClick:f,onEdgeDoubleClick:h,onNodeMouseEnter:m,onNodeMouseMove:g,onNodeMouseLeave:y,onNodeContextMenu:w,onSelectionContextMenu:k,onSelectionStart:b,onSelectionEnd:S,connectionLineType:N,connectionLineStyle:R,connectionLineComponent:T,connectionLineContainerStyle:A,selectionKeyCode:W,selectionOnDrag:z,selectionMode:J,multiSelectionKeyCode:K,panActivationKeyCode:re,zoomActivationKeyCode:te,deleteKeyCode:Q,onlyRenderVisibleElements:D,elementsSelectable:$,selectNodesOnDrag:E,defaultViewport:L,translateExtent:M,minZoom:ee,maxZoom:F,preventScrolling:U,defaultMarkerColor:V,zoomOnScroll:O,zoomOnPinch:H,panOnScroll:Y,panOnScrollSpeed:ae,panOnScrollMode:ie,zoomOnDoubleClick:_e,panOnDrag:fe,onPaneClick:ge,onPaneMouseEnter:Ne,onPaneMouseMove:Ue,onPaneMouseLeave:We,onPaneScroll:ut,onPaneContextMenu:Fe,onEdgeUpdate:et,onEdgeContextMenu:$e,onEdgeMouseEnter:Ve,onEdgeMouseMove:le,onEdgeMouseLeave:be,edgeUpdaterRadius:Pe,onEdgeUpdateStart:me,onEdgeUpdateEnd:Ce,noDragClassName:Te,noWheelClassName:Je,noPanClassName:rt,elevateEdgesOnSelect:ht,disableKeyboardA11y:lt,nodeOrigin:Ct,nodeExtent:Xt,rfId:Pn})=>{const zt=bx(e,TI),wn=bx(t,DI);return e5(l),xe.createElement($I,{onPaneClick:ge,onPaneMouseEnter:Ne,onPaneMouseMove:Ue,onPaneMouseLeave:We,onPaneContextMenu:Fe,onPaneScroll:ut,deleteKeyCode:Q,selectionKeyCode:W,selectionOnDrag:z,selectionMode:J,onSelectionStart:b,onSelectionEnd:S,multiSelectionKeyCode:K,panActivationKeyCode:re,zoomActivationKeyCode:te,elementsSelectable:$,onMove:n,onMoveStart:r,onMoveEnd:o,zoomOnScroll:O,zoomOnPinch:H,zoomOnDoubleClick:_e,panOnScroll:Y,panOnScrollSpeed:ae,panOnScrollMode:ie,panOnDrag:fe,defaultViewport:L,translateExtent:M,minZoom:ee,maxZoom:F,onSelectionContextMenu:k,preventScrolling:U,noDragClassName:Te,noWheelClassName:Je,noPanClassName:rt,disableKeyboardA11y:lt},xe.createElement(QI,null,xe.createElement(XI,{edgeTypes:wn,onEdgeClick:u,onEdgeDoubleClick:h,onEdgeUpdate:et,onlyRenderVisibleElements:D,onEdgeContextMenu:$e,onEdgeMouseEnter:Ve,onEdgeMouseMove:le,onEdgeMouseLeave:be,onEdgeUpdateStart:me,onEdgeUpdateEnd:Ce,edgeUpdaterRadius:Pe,defaultMarkerColor:V,noPanClassName:rt,elevateEdgesOnSelect:!!ht,disableKeyboardA11y:lt,rfId:Pn},xe.createElement(s5,{style:R,type:N,component:T,containerStyle:A})),xe.createElement("div",{className:"react-flow__edgelabel-renderer"}),xe.createElement(LI,{nodeTypes:zt,onNodeClick:c,onNodeDoubleClick:f,onNodeMouseEnter:m,onNodeMouseMove:g,onNodeMouseLeave:y,onNodeContextMenu:w,selectNodesOnDrag:E,onlyRenderVisibleElements:D,noPanClassName:rt,noDragClassName:Te,disableKeyboardA11y:lt,nodeOrigin:Ct,nodeExtent:Xt,rfId:Pn})))};fj.displayName="GraphView";var r5=_.memo(fj);const zg=[[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY],[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY]],al={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:zg,nodeExtent:zg,nodesSelectionActive:!1,userSelectionActive:!1,userSelectionRect:null,connectionNodeId:null,connectionHandleId:null,connectionHandleType:"source",connectionPosition:{x:0,y:0},connectionStatus:null,connectionMode:jc.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:T4,isValidConnection:void 0},i5=()=>VM((e,t)=>({...al,setNodes:n=>{const{nodeInternals:r,nodeOrigin:o,elevateNodesOnSelect:l}=t();e({nodeInternals:Lp(n,r,o,l)})},getNodes:()=>Array.from(t().nodeInternals.values()),setEdges:n=>{const{defaultEdgeOptions:r={}}=t();e({edges:n.map(o=>({...r,...o}))})},setDefaultNodesAndEdges:(n,r)=>{const o=typeof n<"u",l=typeof r<"u",c=o?Lp(n,new Map,t().nodeOrigin,t().elevateNodesOnSelect):new Map;e({nodeInternals:c,edges:l?r:[],hasDefaultNodes:o,hasDefaultEdges:l})},updateNodeDimensions:n=>{const{onNodesChange:r,nodeInternals:o,fitViewOnInit:l,fitViewOnInitDone:c,fitViewOnInitOptions:u,domNode:f,nodeOrigin:h}=t(),m=f==null?void 0:f.querySelector(".react-flow__viewport");if(!m)return;const g=window.getComputedStyle(m),{m22:y}=new window.DOMMatrixReadOnly(g.transform),w=n.reduce((b,S)=>{const N=o.get(S.id);if(N){const R=jy(S.nodeElement);!!(R.width&&R.height&&(N.width!==R.width||N.height!==R.height||S.forceUpdate))&&(o.set(N.id,{...N,[us]:{...N[us],handleBounds:{source:_x(".source",S.nodeElement,y,h),target:_x(".target",S.nodeElement,y,h)}},...R}),b.push({id:N.id,type:"dimensions",dimensions:R}))}return b},[]);ej(o,h);const k=c||l&&!c&&tj(t,{initial:!0,...u});e({nodeInternals:new Map(o),fitViewOnInitDone:k}),(w==null?void 0:w.length)>0&&(r==null||r(w))},updateNodePositions:(n,r=!0,o=!1)=>{const{triggerNodeChanges:l}=t(),c=n.map(u=>{const f={id:u.id,type:"position",dragging:o};return r&&(f.positionAbsolute=u.positionAbsolute,f.position=u.position),f});l(c)},triggerNodeChanges:n=>{const{onNodesChange:r,nodeInternals:o,hasDefaultNodes:l,nodeOrigin:c,getNodes:u,elevateNodesOnSelect:f}=t();if(n!=null&&n.length){if(l){const h=vI(n,u()),m=Lp(h,o,c,f);e({nodeInternals:m})}r==null||r(n)}},addSelectedNodes:n=>{const{multiSelectionActive:r,edges:o,getNodes:l}=t();let c,u=null;r?c=n.map(f=>fl(f,!0)):(c=Ru(l(),n),u=Ru(o,[])),Cm({changedNodes:c,changedEdges:u,get:t,set:e})},addSelectedEdges:n=>{const{multiSelectionActive:r,edges:o,getNodes:l}=t();let c,u=null;r?c=n.map(f=>fl(f,!0)):(c=Ru(o,n),u=Ru(l(),[])),Cm({changedNodes:u,changedEdges:c,get:t,set:e})},unselectNodesAndEdges:({nodes:n,edges:r}={})=>{const{edges:o,getNodes:l}=t(),c=n||l(),u=r||o,f=c.map(m=>(m.selected=!1,fl(m.id,!1))),h=u.map(m=>fl(m.id,!1));Cm({changedNodes:f,changedEdges:h,get:t,set:e})},setMinZoom:n=>{const{d3Zoom:r,maxZoom:o}=t();r==null||r.scaleExtent([n,o]),e({minZoom:n})},setMaxZoom:n=>{const{d3Zoom:r,minZoom:o}=t();r==null||r.scaleExtent([o,n]),e({maxZoom:n})},setTranslateExtent:n=>{var r;(r=t().d3Zoom)==null||r.translateExtent(n),e({translateExtent:n})},resetSelectedElements:()=>{const{edges:n,getNodes:r}=t(),l=r().filter(u=>u.selected).map(u=>fl(u.id,!1)),c=n.filter(u=>u.selected).map(u=>fl(u.id,!1));Cm({changedNodes:l,changedEdges:c,get:t,set:e})},setNodeExtent:n=>{const{nodeInternals:r}=t();r.forEach(o=>{o.positionAbsolute=Sy(o.position,n)}),e({nodeExtent:n,nodeInternals:new Map(r)})},panBy:n=>{const{transform:r,width:o,height:l,d3Zoom:c,d3Selection:u,translateExtent:f}=t();if(!c||!u||!n.x&&!n.y)return!1;const h=ga.translate(r[0]+n.x,r[1]+n.y).scale(r[2]),m=[[0,0],[o,l]],g=c==null?void 0:c.constrain()(h,m,f);return c.transform(u,g),r[0]!==g.x||r[1]!==g.y||r[2]!==g.k},cancelConnection:()=>e({connectionNodeId:al.connectionNodeId,connectionHandleId:al.connectionHandleId,connectionHandleType:al.connectionHandleType,connectionStatus:al.connectionStatus,connectionStartHandle:al.connectionStartHandle,connectionEndHandle:al.connectionEndHandle}),reset:()=>e({...al})}),Object.is),Ly=({children:e})=>{const t=_.useRef(null);return t.current||(t.current=i5()),xe.createElement(j4,{value:t.current},e)};Ly.displayName="ReactFlowProvider";const hj=({children:e})=>_.useContext(j_)?xe.createElement(xe.Fragment,null,e):xe.createElement(Ly,null,e);hj.displayName="ReactFlowWrapper";const o5={input:Gk,default:Dg,output:Yk,group:Ty},a5={default:o_,straight:Ey,step:Cy,smoothstep:S_,simplebezier:Ny},l5=[0,0],c5=[15,15],u5={x:0,y:0,zoom:1},d5={width:"100%",height:"100%",overflow:"hidden",position:"relative",zIndex:0},mj=_.forwardRef(({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,className:o,nodeTypes:l=o5,edgeTypes:c=a5,onNodeClick:u,onEdgeClick:f,onInit:h,onMove:m,onMoveStart:g,onMoveEnd:y,onConnect:w,onConnectStart:k,onConnectEnd:b,onClickConnectStart:S,onClickConnectEnd:N,onNodeMouseEnter:R,onNodeMouseMove:T,onNodeMouseLeave:A,onNodeContextMenu:W,onNodeDoubleClick:z,onNodeDragStart:J,onNodeDrag:K,onNodeDragStop:re,onNodesDelete:te,onEdgesDelete:Q,onSelectionChange:D,onSelectionDragStart:$,onSelectionDrag:E,onSelectionDragStop:L,onSelectionContextMenu:M,onSelectionStart:ee,onSelectionEnd:F,connectionMode:U=jc.Strict,connectionLineType:V=hl.Bezier,connectionLineStyle:O,connectionLineComponent:H,connectionLineContainerStyle:Y,deleteKeyCode:ae="Backspace",selectionKeyCode:ie="Shift",selectionOnDrag:_e=!1,selectionMode:fe=Wf.Full,panActivationKeyCode:ge="Space",multiSelectionKeyCode:Ne=i_()?"Meta":"Control",zoomActivationKeyCode:Ue=i_()?"Meta":"Control",snapToGrid:We=!1,snapGrid:ut=c5,onlyRenderVisibleElements:Fe=!1,selectNodesOnDrag:et=!0,nodesDraggable:$e,nodesConnectable:Ve,nodesFocusable:le,nodeOrigin:be=l5,edgesFocusable:Pe,edgesUpdatable:me,elementsSelectable:Ce,defaultViewport:Te=u5,minZoom:Je=.5,maxZoom:rt=2,translateExtent:ht=zg,preventScrolling:lt=!0,nodeExtent:Ct,defaultMarkerColor:Xt="#b1b1b7",zoomOnScroll:Pn=!0,zoomOnPinch:zt=!0,panOnScroll:wn=!1,panOnScrollSpeed:Un=.5,panOnScrollMode:Mn=fc.Free,zoomOnDoubleClick:vn=!0,panOnDrag:Dn=!0,onPaneClick:bn,onPaneMouseEnter:js,onPaneMouseMove:Kn,onPaneMouseLeave:Ss,onPaneScroll:Ar,onPaneContextMenu:Fn,children:de,onEdgeUpdate:Se,onEdgeContextMenu:tt,onEdgeDoubleClick:Qe,onEdgeMouseEnter:ct,onEdgeMouseMove:mt,onEdgeMouseLeave:It,onEdgeUpdateStart:Et,onEdgeUpdateEnd:Zt,edgeUpdaterRadius:St=10,onNodesChange:Qt,onEdgesChange:Ht,noDragClassName:Bt="nodrag",noWheelClassName:Pt="nowheel",noPanClassName:Dt="nopan",fitView:qe=!1,fitViewOptions:ln,connectOnClick:pt=!0,attributionPosition:rn,proOptions:gt,defaultEdgeOptions:Wn,elevateNodesOnSelect:cn=!0,elevateEdgesOnSelect:Gs=!1,disableKeyboardA11y:ns=!1,autoPanOnConnect:Vr=!0,autoPanOnNodeDrag:hr=!0,connectionRadius:ii=20,isValidConnection:oi,onError:Ps,style:he,id:mr,nodeDragThreshold:Xi,..._r},Tr)=>{const Gr=mr||"1";return xe.createElement("div",{..._r,style:{...he,...d5},ref:Tr,className:Vs(["react-flow",o]),"data-testid":"rf__wrapper",id:mr},xe.createElement(hj,null,xe.createElement(r5,{onInit:h,onMove:m,onMoveStart:g,onMoveEnd:y,onNodeClick:u,onEdgeClick:f,onNodeMouseEnter:R,onNodeMouseMove:T,onNodeMouseLeave:A,onNodeContextMenu:W,onNodeDoubleClick:z,nodeTypes:l,edgeTypes:c,connectionLineType:V,connectionLineStyle:O,connectionLineComponent:H,connectionLineContainerStyle:Y,selectionKeyCode:ie,selectionOnDrag:_e,selectionMode:fe,deleteKeyCode:ae,multiSelectionKeyCode:Ne,panActivationKeyCode:ge,zoomActivationKeyCode:Ue,onlyRenderVisibleElements:Fe,selectNodesOnDrag:et,defaultViewport:Te,translateExtent:ht,minZoom:Je,maxZoom:rt,preventScrolling:lt,zoomOnScroll:Pn,zoomOnPinch:zt,zoomOnDoubleClick:vn,panOnScroll:wn,panOnScrollSpeed:Un,panOnScrollMode:Mn,panOnDrag:Dn,onPaneClick:bn,onPaneMouseEnter:js,onPaneMouseMove:Kn,onPaneMouseLeave:Ss,onPaneScroll:Ar,onPaneContextMenu:Fn,onSelectionContextMenu:M,onSelectionStart:ee,onSelectionEnd:F,onEdgeUpdate:Se,onEdgeContextMenu:tt,onEdgeDoubleClick:Qe,onEdgeMouseEnter:ct,onEdgeMouseMove:mt,onEdgeMouseLeave:It,onEdgeUpdateStart:Et,onEdgeUpdateEnd:Zt,edgeUpdaterRadius:St,defaultMarkerColor:Xt,noDragClassName:Bt,noWheelClassName:Pt,noPanClassName:Dt,elevateEdgesOnSelect:Gs,rfId:Gr,disableKeyboardA11y:ns,nodeOrigin:be,nodeExtent:Ct}),xe.createElement(eI,{nodes:e,edges:t,defaultNodes:n,defaultEdges:r,onConnect:w,onConnectStart:k,onConnectEnd:b,onClickConnectStart:S,onClickConnectEnd:N,nodesDraggable:$e,nodesConnectable:Ve,nodesFocusable:le,edgesFocusable:Pe,edgesUpdatable:me,elementsSelectable:Ce,elevateNodesOnSelect:cn,minZoom:Je,maxZoom:rt,nodeExtent:Ct,onNodesChange:Qt,onEdgesChange:Ht,snapToGrid:We,snapGrid:ut,connectionMode:U,translateExtent:ht,connectOnClick:pt,defaultEdgeOptions:Wn,fitView:qe,fitViewOptions:ln,onNodesDelete:te,onEdgesDelete:Q,onNodeDragStart:J,onNodeDrag:K,onNodeDragStop:re,onSelectionDrag:E,onSelectionDragStart:$,onSelectionDragStop:L,noPanClassName:Dt,nodeOrigin:be,rfId:Gr,autoPanOnConnect:Vr,autoPanOnNodeDrag:hr,onError:Ps,connectionRadius:ii,isValidConnection:oi,nodeDragThreshold:Xi}),xe.createElement(Z4,{onSelectionChange:D}),de,xe.createElement(N4,{proOptions:gt,position:rn}),xe.createElement(iI,{rfId:Gr,disableKeyboardA11y:ns})))});mj.displayName="ReactFlow";const _j=({id:e,x:t,y:n,width:r,height:o,style:l,color:c,strokeColor:u,strokeWidth:f,className:h,borderRadius:m,shapeRendering:g,onClick:y,selected:w})=>{const{background:k,backgroundColor:b}=l||{},S=c||k||b;return xe.createElement("rect",{className:Vs(["react-flow__minimap-node",{selected:w},h]),x:t,y:n,rx:m,ry:m,width:r,height:o,fill:S,stroke:u,strokeWidth:f,shapeRendering:g,onClick:y?N=>y(N,e):void 0})};_j.displayName="MiniMapNode";var f5=_.memo(_j);const h5=e=>e.nodeOrigin,m5=e=>e.getNodes().filter(t=>!t.hidden&&t.width&&t.height),Dp=e=>e instanceof Function?e:()=>e;function _5({nodeStrokeColor:e="transparent",nodeColor:t="#e2e2e2",nodeClassName:n="",nodeBorderRadius:r=5,nodeStrokeWidth:o=2,nodeComponent:l=f5,onClick:c}){const u=On(m5,Os),f=On(h5),h=Dp(t),m=Dp(e),g=Dp(n),y=typeof window>"u"||window.chrome?"crispEdges":"geometricPrecision";return xe.createElement(xe.Fragment,null,u.map(w=>{const{x:k,y:b}=yc(w,f).positionAbsolute;return xe.createElement(l,{key:w.id,x:k,y:b,width:w.width,height:w.height,style:w.style,selected:w.selected,className:g(w),color:h(w),borderRadius:r,strokeColor:m(w),strokeWidth:o,shapeRendering:y,onClick:c,id:w.id})}))}var p5=_.memo(_5);const g5=200,y5=150,w5=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?$4(N_(t,e.nodeOrigin),n):n,rfId:e.rfId}},v5="react-flow__minimap-desc";function pj({style:e,className:t,nodeStrokeColor:n="transparent",nodeColor:r="#e2e2e2",nodeClassName:o="",nodeBorderRadius:l=5,nodeStrokeWidth:c=2,nodeComponent:u,maskColor:f="rgb(240, 240, 240, 0.6)",maskStrokeColor:h="none",maskStrokeWidth:m=1,position:g="bottom-right",onClick:y,onNodeClick:w,pannable:k=!1,zoomable:b=!1,ariaLabel:S="React Flow mini map",inversePan:N=!1,zoomStep:R=10,offsetScale:T=5}){const A=ks(),W=_.useRef(null),{boundingRect:z,viewBB:J,rfId:K}=On(w5,Os),re=(e==null?void 0:e.width)??g5,te=(e==null?void 0:e.height)??y5,Q=z.width/re,D=z.height/te,$=Math.max(Q,D),E=$*re,L=$*te,M=T*$,ee=z.x-(E-z.width)/2-M,F=z.y-(L-z.height)/2-M,U=E+M*2,V=L+M*2,O=`${v5}-${K}`,H=_.useRef(0);H.current=$,_.useEffect(()=>{if(W.current){const ie=ki(W.current),_e=Ne=>{const{transform:Ue,d3Selection:We,d3Zoom:ut}=A.getState();if(Ne.sourceEvent.type!=="wheel"||!We||!ut)return;const Fe=-Ne.sourceEvent.deltaY*(Ne.sourceEvent.deltaMode===1?.05:Ne.sourceEvent.deltaMode?1:.002)*R,et=Ue[2]*Math.pow(2,Fe);ut.scaleTo(We,et)},fe=Ne=>{const{transform:Ue,d3Selection:We,d3Zoom:ut,translateExtent:Fe,width:et,height:$e}=A.getState();if(Ne.sourceEvent.type!=="mousemove"||!We||!ut)return;const Ve=H.current*Math.max(1,Ue[2])*(N?-1:1),le={x:Ue[0]-Ne.sourceEvent.movementX*Ve,y:Ue[1]-Ne.sourceEvent.movementY*Ve},be=[[0,0],[et,$e]],Pe=ga.translate(le.x,le.y).scale(Ue[2]),me=ut.constrain()(Pe,be,Fe);ut.transform(We,me)},ge=Sk().on("zoom",k?fe:null).on("zoom.wheel",b?_e:null);return ie.call(ge),()=>{ie.on("zoom",null)}}},[k,b,N,R]);const Y=y?ie=>{const _e=Hi(ie);y(ie,{x:_e[0],y:_e[1]})}:void 0,ae=w?(ie,_e)=>{const fe=A.getState().nodeInternals.get(_e);w(ie,fe)}:void 0;return xe.createElement(Bf,{position:g,style:e,className:Vs(["react-flow__minimap",t]),"data-testid":"rf__minimap"},xe.createElement("svg",{width:re,height:te,viewBox:`${ee} ${F} ${U} ${V}`,role:"img","aria-labelledby":O,ref:W,onClick:Y},S&&xe.createElement("title",{id:O},S),xe.createElement(p5,{onClick:ae,nodeColor:r,nodeStrokeColor:n,nodeBorderRadius:l,nodeClassName:o,nodeStrokeWidth:c,nodeComponent:u}),xe.createElement("path",{className:"react-flow__minimap-mask",d:`M${ee-M},${F-M}h${U+M*2}v${V+M*2}h${-U-M*2}z
|
|
149
|
-
M${J.x},${J.y}h${J.width}v${J.height}h${-J.width}z`,fill:f,fillRule:"evenodd",stroke:h,strokeWidth:m,pointerEvents:"none"})))}pj.displayName="MiniMap";var x5=_.memo(pj);function b5(){return xe.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 32"},xe.createElement("path",{d:"M32 18.133H18.133V32h-4.266V18.133H0v-4.266h13.867V0h4.266v13.867H32z"}))}function k5(){return xe.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 5"},xe.createElement("path",{d:"M0 0h32v4.2H0z"}))}function j5(){return xe.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 30"},xe.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 S5(){return xe.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 25 32"},xe.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 N5(){return xe.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 25 32"},xe.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 Lu=({children:e,className:t,...n})=>xe.createElement("button",{type:"button",className:Vs(["react-flow__controls-button",t]),...n},e);Lu.displayName="ControlButton";const C5=e=>({isInteractive:e.nodesDraggable||e.nodesConnectable||e.elementsSelectable,minZoomReached:e.transform[2]<=e.minZoom,maxZoomReached:e.transform[2]>=e.maxZoom}),gj=({style:e,showZoom:t=!0,showFitView:n=!0,showInteractive:r=!0,fitViewOptions:o,onZoomIn:l,onZoomOut:c,onFitView:u,onInteractiveChange:f,className:h,children:m,position:g="bottom-left"})=>{const y=ks(),[w,k]=_.useState(!1),{isInteractive:b,minZoomReached:S,maxZoomReached:N}=On(C5,Os),{zoomIn:R,zoomOut:T,fitView:A}=My();if(_.useEffect(()=>{k(!0)},[]),!w)return null;const W=()=>{R(),l==null||l()},z=()=>{T(),c==null||c()},J=()=>{A(o),u==null||u()},K=()=>{y.setState({nodesDraggable:!b,nodesConnectable:!b,elementsSelectable:!b}),f==null||f(!b)};return xe.createElement(Bf,{className:Vs(["react-flow__controls",h]),position:g,style:e,"data-testid":"rf__controls"},t&&xe.createElement(xe.Fragment,null,xe.createElement(Lu,{onClick:W,className:"react-flow__controls-zoomin",title:"zoom in","aria-label":"zoom in",disabled:N},xe.createElement(b5,null)),xe.createElement(Lu,{onClick:z,className:"react-flow__controls-zoomout",title:"zoom out","aria-label":"zoom out",disabled:S},xe.createElement(k5,null))),n&&xe.createElement(Lu,{className:"react-flow__controls-fitview",onClick:J,title:"fit view","aria-label":"fit view"},xe.createElement(j5,null)),r&&xe.createElement(Lu,{className:"react-flow__controls-interactive",onClick:K,title:"toggle interactivity","aria-label":"toggle interactivity"},b?xe.createElement(N5,null):xe.createElement(S5,null)),m)};gj.displayName="Controls";var E5=_.memo(gj),Yi;(function(e){e.Lines="lines",e.Dots="dots",e.Cross="cross"})(Yi||(Yi={}));function $5({color:e,dimensions:t,lineWidth:n}){return xe.createElement("path",{stroke:e,strokeWidth:n,d:`M${t[0]/2} 0 V${t[1]} M0 ${t[1]/2} H${t[0]}`})}function A5({color:e,radius:t}){return xe.createElement("circle",{cx:t,cy:t,r:t,fill:e})}const T5={[Yi.Dots]:"#91919a",[Yi.Lines]:"#eee",[Yi.Cross]:"#e2e2e2"},M5={[Yi.Dots]:1,[Yi.Lines]:1,[Yi.Cross]:6},R5=e=>({transform:e.transform,patternId:`pattern-${e.rfId}`});function yj({id:e,variant:t=Yi.Dots,gap:n=20,size:r,lineWidth:o=1,offset:l=2,color:c,style:u,className:f}){const h=_.useRef(null),{transform:m,patternId:g}=On(R5,Os),y=c||T5[t],w=r||M5[t],k=t===Yi.Dots,b=t===Yi.Cross,S=Array.isArray(n)?n:[n,n],N=[S[0]*m[2]||1,S[1]*m[2]||1],R=w*m[2],T=b?[R,R]:N,A=k?[R/l,R/l]:[T[0]/l,T[1]/l];return xe.createElement("svg",{className:Vs(["react-flow__background",f]),style:{...u,position:"absolute",width:"100%",height:"100%",top:0,left:0},ref:h,"data-testid":"rf__background"},xe.createElement("pattern",{id:g+e,x:m[0]%N[0],y:m[1]%N[1],width:N[0],height:N[1],patternUnits:"userSpaceOnUse",patternTransform:`translate(-${A[0]},-${A[1]})`},k?xe.createElement(A5,{color:y,radius:R/l}):xe.createElement($5,{dimensions:T,color:y,lineWidth:o})),xe.createElement("rect",{x:"0",y:"0",width:"100%",height:"100%",fill:`url(#${g+e})`}))}yj.displayName="Background";var L5=_.memo(yj);function wj(e,t={}){const n=e&&typeof e=="object"&&!Array.isArray(e)?e:null;if(!n)return null;const r=typeof n.x=="number"&&Number.isFinite(n.x)?n.x:null,o=typeof n.y=="number"&&Number.isFinite(n.y)?n.y:null,l=typeof n.zoom=="number"&&Number.isFinite(n.zoom)?n.zoom:null;if(r===null||o===null||l===null)return null;const c=typeof t.maxAbsTranslate=="number"&&Number.isFinite(t.maxAbsTranslate)?Math.abs(t.maxAbsTranslate):1e6;if(Math.abs(r)>c||Math.abs(o)>c)return null;const u=typeof t.minZoom=="number"&&Number.isFinite(t.minZoom)?t.minZoom:.025,f=typeof t.maxZoom=="number"&&Number.isFinite(t.maxZoom)?t.maxZoom:6,h=Math.min(u,f),m=Math.max(u,f);return{x:r,y:o,zoom:Math.min(m,Math.max(h,l))}}function l_(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 I5(e){const t=String(e||"").trim();if(!t)return"entity";const n=t.indexOf(":");if(n<=0||n>=t.length-1)return"entity";const r=t.slice(0,n).toLowerCase(),o=t.slice(n+1).toLowerCase();if(r==="ex"){const l=o.indexOf("-"),c=l>0?o.slice(0,l):o;return c==="person"?"person":c==="org"?"org":c==="concept"?"concept":c==="claim"?"claim":c==="event"?"event":c==="doc"?"doc":c==="thing"?"thing":"entity"}return r==="schema"||r==="skos"||r==="dcterms"||r==="rdf"||r==="cito"?"vocab":"entity"}function O5(e){const t=String(e||"").trim();if(!t)return"";const n=t.indexOf(":");if(n<=0||n>=t.length-1)return l_(t);const r=t.slice(0,n).toLowerCase(),o=t.slice(n+1);if(r==="ex"){const l=o.indexOf("-");if(l>0&&l<o.length-1)return o.slice(l+1)}return l_(t)}function Bg(e){const r=Math.max(1,Math.ceil(Math.sqrt(e.length))),o={};for(let l=0;l<e.length;l++){const c=Math.floor(l/r),u=l%r;o[e[l]]={x:u*240,y:c*120}}return o}function Ug(e){const t=String(e??"");let n=2166136261;for(let r=0;r<t.length;r++)n^=t.charCodeAt(r),n=Math.imul(n,16777619);return n>>>0}function vj(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 P5(e,t){const n={},r=e.length;if(!r)return n;const o=Math.max(260,Math.sqrt(r)*150),l=t%360*Math.PI/180;for(let c=0;c<r;c++){const u=l+2*Math.PI*c/r;n[e[c]]={x:o*Math.cos(u),y:o*Math.sin(u)}}return n}function kx(e,t,n){var k;const r={};if(!e.length)return r;const o=new Map;for(const b of e)o.set(b,new Set);for(const b of t){const S=String((b==null?void 0:b.source)||"").trim(),N=String((b==null?void 0:b.target)||"").trim();if(!S||!N||S===N)continue;const R=o.get(S),T=o.get(N);R&&R.add(N),T&&T.add(S)}let l=e[0],c=-1;for(const b of e){const S=((k=o.get(b))==null?void 0:k.size)??0;(S>c||S===c&&b.localeCompare(l)<0)&&(l=b,c=S)}const u=new Map,f=[];for(u.set(l,0),f.push(l);f.length;){const b=f.shift(),S=u.get(b)??0,N=Array.from(o.get(b)??[]);N.sort((R,T)=>R.localeCompare(T));for(const R of N)u.has(R)||(u.set(R,S+1),f.push(R))}let h=0;for(const b of u.values())h=Math.max(h,b);for(const b of e)u.has(b)||u.set(b,h+1);const m=new Map;for(const b of e){const S=u.get(b)??0,N=m.get(S);N?N.push(b):m.set(S,[b])}const g=Array.from(m.keys()).sort((b,S)=>b-S),y=260,w=n%360*Math.PI/180;for(const b of g){const S=m.get(b)||[];if(S.sort((A,W)=>A.localeCompare(W)),b===0){if(S.length===1)r[S[0]]={x:0,y:0};else for(let W=0;W<S.length;W++){const z=w+2*Math.PI*W/S.length;r[S[W]]={x:80*Math.cos(z),y:80*Math.sin(z)}}continue}const N=y*b,R=S.length;if(R===1){r[S[0]]={x:N,y:0};continue}const T=w+b*.35;for(let A=0;A<R;A++){const W=T+2*Math.PI*A/R;r[S[A]]={x:N*Math.cos(W),y:N*Math.sin(W)}}}return r}function $u(e,t={}){const n=t.kind??"grid",r=typeof t.seed=="number"&&Number.isFinite(t.seed)?Math.trunc(t.seed):0,o=e.nodes.map(l=>l.id);if(n==="grid")return Bg(o);if(n==="circle")return P5(o,r);if(n==="radial")return kx(o,e.edges,r);if(n==="force"){const l=kx(o,e.edges,r),c=vj(r||1),u=Math.max(10,Math.min(42,Math.sqrt(o.length)*2.75)),f={};for(const h of o){const m=l[h]||{x:0,y:0};f[h]={x:m.x+(c()-.5)*u,y:m.y+(c()-.5)*u}}return f}return Bg(o)}function D5(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 F5(e,t={}){const n=!!(t.groupEdges??!0),r=Math.max(1,t.maxEdgeLabelPredicates??3),o=D5(e),l=new Set;for(const y of o){const w=String(y.subject||"").trim(),k=String(y.object||"").trim();w&&l.add(w),k&&l.add(k)}const c=Array.from(l);c.sort((y,w)=>y.localeCompare(w));const u=Bg(c),f=c.map(y=>({id:y,type:"default",data:{label:O5(y),kind:I5(y)},position:u[y]||{x:0,y:0}})),h=new Map,m=(y,w)=>{const k=String(y.subject||"").trim(),b=String(y.object||"").trim(),S=String(y.predicate||"").trim();return n?`edge:${k}:${b}`:`edge:${w}:${k}:${S}:${b}`};for(let y=0;y<o.length;y++){const w=o[y],k=m(w,y),b=h.get(k);b?b.push(w):h.set(k,[w])}const g=[];for(const[y,w]of h.entries()){const k=w[0],b=String(k.subject||"").trim(),S=String(k.object||"").trim();if(!b||!S)continue;const N=new Map;for(const J of w){const K=String(J.predicate||"").trim();K&&N.set(K,(N.get(K)||0)+1)}const R=Array.from(N.entries());R.sort((J,K)=>K[1]-J[1]||J[0].localeCompare(K[0]));const A=R.slice(0,r).map(([J,K])=>K>1?`${l_(J)}×${K}`:l_(J)).join(" | "),W=R.length>r?` +${R.length-r}`:"",z=`${A}${W}`.trim();g.push({id:y,source:b,target:S,label:z,animated:!1,data:{assertions:w,predicateSummary:z}})}return{nodes:f,edges:g}}function z5(e,t,n,r={}){const o=r.directed!==!1,l=String(t||"").trim(),c=String(n||"").trim();if(!l||!c)return null;if(l===c)return{nodeIds:[l],edgeIds:[]};const u=new Map,f=(b,S,N)=>{const R=u.get(b);R?R.push({to:S,edgeId:N}):u.set(b,[{to:S,edgeId:N}])};for(const b of e.edges)f(b.source,b.target,b.id),o||f(b.target,b.source,b.id);const h=[l],m=new Map,g=new Map;for(m.set(l,null),g.set(l,null);h.length;){const b=h.shift(),S=u.get(b)||[];for(const N of S)if(!m.has(N.to)){if(m.set(N.to,b),g.set(N.to,N.edgeId),N.to===c){h.length=0;break}h.push(N.to)}}if(!m.has(c))return null;const y=[],w=[];let k=c;for(;k;){y.push(k);const b=g.get(k);b&&w.push(b),k=m.get(k)||null}return y.reverse(),w.reverse(),{nodeIds:y,edgeIds:w}}const jx={seed:1,dt:1,springLength:240,springStrength:.03,repulsionStrength:9e3,centeringStrength:.003,damping:.85,maxSpeed:90,maxRepulsionNodes:320};function $m(e,t={}){const n={...jx,...t,seed:typeof t.seed=="number"&&Number.isFinite(t.seed)?Math.trunc(t.seed):jx.seed},r=e.nodes.map(w=>w.id),o=r.length,l=new Float64Array(2*o),c=new Float64Array(2*o),u=new Float64Array(2*o),f=new Map;for(let w=0;w<o;w++)f.set(r[w],w);const h=t.positions??$u(e,{kind:"force",seed:n.seed}),m=vj(n.seed||1),g=Math.max(8,Math.min(38,Math.sqrt(o)*2.25));for(let w=0;w<o;w++){const k=r[w],b=h[k],S=typeof(b==null?void 0:b.x)=="number"&&Number.isFinite(b.x)?b.x:(m()-.5)*500,N=typeof(b==null?void 0:b.y)=="number"&&Number.isFinite(b.y)?b.y:(m()-.5)*500;l[2*w]=S+(m()-.5)*g,l[2*w+1]=N+(m()-.5)*g,c[2*w]=0,c[2*w+1]=0}const y=[];for(const w of e.edges){const k=f.get(String((w==null?void 0:w.source)||"").trim()),b=f.get(String((w==null?void 0:w.target)||"").trim());typeof k!="number"||typeof b!="number"||k===b||y.push(k,b)}return{nodeIds:r,pos:l,vel:c,acc:u,edges:new Uint32Array(y),options:n,tick:0}}function B5(e,t=1){const n=e.nodeIds.length;if(!n)return;const r=e.options,o=r.dt;for(let l=0;l<Math.max(1,Math.trunc(t));l++){if(e.acc.fill(0),n<=r.maxRepulsionNodes){const w=r.repulsionStrength;for(let k=0;k<n;k++){const b=e.pos[2*k],S=e.pos[2*k+1];for(let N=k+1;N<n;N++){const R=e.pos[2*N]-b,T=e.pos[2*N+1]-S,A=R*R+T*T+1e-6,W=1/Math.sqrt(A),z=w/A,J=z*R*W,K=z*T*W;e.acc[2*k]-=J,e.acc[2*k+1]-=K,e.acc[2*N]+=J,e.acc[2*N+1]+=K}}}const u=r.springLength,f=r.springStrength,h=e.edges;for(let w=0;w<h.length;w+=2){const k=h[w],b=h[w+1],S=e.pos[2*k],N=e.pos[2*k+1],R=e.pos[2*b],T=e.pos[2*b+1],A=R-S,W=T-N,z=A*A+W*W+1e-6,J=Math.sqrt(z),K=f*(J-u),re=K*A/J,te=K*W/J;e.acc[2*k]+=re,e.acc[2*k+1]+=te,e.acc[2*b]-=re,e.acc[2*b+1]-=te}const m=r.centeringStrength;for(let w=0;w<n;w++)e.acc[2*w]+=-m*e.pos[2*w],e.acc[2*w+1]+=-m*e.pos[2*w+1];const g=r.damping,y=r.maxSpeed;for(let w=0;w<n;w++){let k=(e.vel[2*w]+e.acc[2*w]*o)*g,b=(e.vel[2*w+1]+e.acc[2*w+1]*o)*g;const S=Math.sqrt(k*k+b*b);if(S>y){const N=y/S;k*=N,b*=N}e.vel[2*w]=k,e.vel[2*w+1]=b,e.pos[2*w]+=k*o,e.pos[2*w+1]+=b*o}e.tick+=1}}function U5(e){const t=e.nodeIds.length;if(!t)return 0;let n=0;for(let r=0;r<t;r++){const o=e.vel[2*r],l=e.vel[2*r+1];n+=Math.sqrt(o*o+l*l)}return n/t}function W5(e){const t={},n=e.nodeIds.length;for(let r=0;r<n;r++)t[e.nodeIds[r]]={x:e.pos[2*r],y:e.pos[2*r+1]};return t}function Sx(e,t="session"){const n=String(e??"").trim().toLowerCase();return n==="run"||n==="session"||n==="global"||n==="all"?n:t}function q5(){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 H5(){return s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16","aria-hidden":"true",focusable:"false",children:[s.jsx("rect",{x:"3",y:"3",width:"3",height:"3",rx:"1"}),s.jsx("rect",{x:"3",y:"7",width:"3",height:"3",rx:"1"}),s.jsx("rect",{x:"3",y:"11",width:"3",height:"3",rx:"1"}),s.jsx("rect",{x:"8",y:"3.5",width:"6",height:"2",rx:"1",fill:"none",strokeWidth:"1.4"}),s.jsx("rect",{x:"8",y:"7.5",width:"6",height:"2",rx:"1",fill:"none",strokeWidth:"1.4"}),s.jsx("rect",{x:"8",y:"11.5",width:"6",height:"2",rx:"1",fill:"none",strokeWidth:"1.4"})]})}function xj(e,t,n,r){const o=typeof e=="number"&&Number.isFinite(e)?e:r;return Math.min(n,Math.max(t,o))}function df(e){const t=xj(e,.6,2.4,1),n=240*t,r=9e3*t*t;return{springLength:n,repulsionStrength:r}}const Vf="abstractuic_amx_saved_layouts_v1",Wg=.025,qg=6,bj=1e6;function Iy(){if(typeof window>"u")return null;try{return window.localStorage}catch{return null}}function Hg(e,t="grid"){const n=String(e??"").trim().toLowerCase();return n==="grid"||n==="circle"||n==="radial"||n==="force"?n:t}function V5(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:null;if(!t)return null;const n=typeof t.x=="number"&&Number.isFinite(t.x)?t.x:null,r=typeof t.y=="number"&&Number.isFinite(t.y)?t.y:null;return n===null||r===null?null:{x:n,y:r}}function Nx(e){const t=Iy();if(!t)return null;const n=String(e??"").trim();if(!n)return null;try{const r=t.getItem(Vf);if(!r)return null;const o=JSON.parse(r),l=o&&typeof o=="object"&&!Array.isArray(o)?o:null;if(!l)return null;const c=l[n],u=c&&typeof c=="object"&&!Array.isArray(c)?c:null;if(!u)return null;const f=u.version===1?1:null;if(f===null)return null;const h=Hg(u.kind,"grid"),m=typeof u.seed=="number"&&Number.isFinite(u.seed)?Math.trunc(u.seed):Ug(n),g=u.positions&&typeof u.positions=="object"&&!Array.isArray(u.positions)?u.positions:null,y={};if(g)for(const[b,S]of Object.entries(g)){const N=V5(S);N&&(y[String(b)]=N)}const w=wj(u.viewport,{minZoom:Wg,maxZoom:qg,maxAbsTranslate:bj})??void 0,k=typeof u.saved_at=="string"&&u.saved_at.trim()?u.saved_at.trim():"";return{version:f,kind:h,seed:m,positions:y,viewport:w,saved_at:k}}catch{return null}}function G5(e,t){const n=Iy();if(!n)return;const r=String(e??"").trim();if(r)try{const o=n.getItem(Vf),l=o?JSON.parse(o):null,c=l&&typeof l=="object"&&!Array.isArray(l)?{...l}:{};c[r]=t,n.setItem(Vf,JSON.stringify(c))}catch{}}function K5(e){const t=Iy();if(!t)return;const n=String(e??"").trim();if(n)try{const r=t.getItem(Vf);if(!r)return;const o=JSON.parse(r),l=o&&typeof o=="object"&&!Array.isArray(o)?{...o}:null;if(!l||!(n in l))return;delete l[n],t.setItem(Vf,JSON.stringify(l))}catch{}}function Y5(e){const t=String(e??"").trim();if(!t)return;const n=Number(t);if(Number.isFinite(n))return n}function Fp(e,t){const n=!!(t!=null&&t.allowZero),r=!!(t!=null&&t.allowNegativeOne),o=String(e??"").trim();if(!o)return;const l=Number(o);if(!Number.isFinite(l))return;const c=Math.trunc(l);if(r&&c===-1)return-1;if(!(!n&&c<=0)&&!(n&&c<0))return c}function J5(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e,n=typeof t.recall_level=="string"?t.recall_level:"",r=t.applied&&typeof t.applied=="object"&&!Array.isArray(t.applied)?t.applied:null,o=[];return n&&o.push(`recall_level=${n}`),r&&(typeof r.limit=="number"&&o.push(`limit=${r.limit}`),typeof r.min_score=="number"&&o.push(`min_score=${r.min_score}`),typeof r.max_input_tokens=="number"&&o.push(`max_input_tokens=${r.max_input_tokens}`)),o.length?o.join(" · "):null}function X5(e){if(!e||typeof e!="object")return null;const t=[],n=typeof e.scope=="string"?e.scope.trim():"",r=typeof e.owner_id=="string"?e.owner_id.trim():"";n&&t.push(`scope=${n}`),r&&t.push(`owner_id=${r}`);const o=typeof e.confidence=="number"&&Number.isFinite(e.confidence)?e.confidence:null;o!==null&&t.push(`confidence=${o.toFixed(3)}`);const l=e.provenance&&typeof e.provenance=="object"&&!Array.isArray(e.provenance)?e.provenance:null;if(l){const h=typeof l.writer_run_id=="string"?l.writer_run_id.trim():"",m=typeof l.writer_workflow_id=="string"?l.writer_workflow_id.trim():"";h&&t.push(`writer_run_id=${h}`),m&&t.push(`writer_workflow_id=${m}`)}const c=e.attributes&&typeof e.attributes=="object"&&!Array.isArray(e.attributes)?e.attributes:null,u=c&&c._retrieval&&typeof c._retrieval=="object"&&!Array.isArray(c._retrieval)?c._retrieval:null,f=u&&typeof u.score=="number"&&Number.isFinite(u.score)?u.score:null;return f!==null&&t.push(`score=${f.toFixed(3)}`),t.length?t.join(" · "):null}function Z5(e,t){const n=String(e??""),r=String(t??"").trim();if(!r)return n;const o=n.toLowerCase().indexOf(r.toLowerCase());if(o<0)return n;const l=n.slice(0,o),c=n.slice(o,o+r.length),u=n.slice(o+r.length);return s.jsxs(s.Fragment,{children:[l,s.jsx("span",{className:"amx-hl",children:c}),u]})}function ff(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 Q5(e){const t=typeof e=="string"?e.trim():"";if(!t)return null;const n=t.replace(/(\.\d{3})\d+/,"$1"),r=Date.parse(n);return Number.isFinite(r)?r:null}function hf(e){const t=Q5(e);if(t===null)return"";const n=new Date(t),r=n.getUTCFullYear(),o=String(n.getUTCMonth()+1).padStart(2,"0"),l=String(n.getUTCDate()).padStart(2,"0"),c=String(n.getUTCHours()).padStart(2,"0"),u=String(n.getUTCMinutes()).padStart(2,"0");return`${r}/${o}/${l} ${c}:${u}`}function kj(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 zp(e,t){const n=String(e??"").trim().toLowerCase();return!!(n&&t.has(n))}function eO(e,t={}){const n=Math.max(1,t.maxPredicates??3),r=new Map;for(const f of e){const h=String((f==null?void 0:f.predicate)||"").trim();h&&r.set(h,(r.get(h)||0)+1)}const o=Array.from(r.entries());o.sort((f,h)=>h[1]-f[1]||f[0].localeCompare(h[0]));const c=o.slice(0,n).map(([f,h])=>{const m=kj(f);return h>1?`${m}×${h}`:m}).join(" | "),u=o.length>n?` +${o.length-n}`:"";return`${c}${u}`.trim()}function tO({resetKey:e,queryMode:t,items:n,activeMemoryText:r,packets:o,packetsVersion:l,packedCount:c,dropped:u,estimatedTokens:f,effort:h,warnings:m,onQuery:g,onItemsReplace:y,onOpenSpan:w,onOpenTranscript:k}){var ci;const b=_.useRef(null),S=_.useMemo(()=>{const q=n==null?void 0:n[0],ce=n==null?void 0:n[n.length-1],je=q?`${q.subject}|${q.predicate}|${q.object}`:"",Ae=ce?`${ce.subject}|${ce.predicate}|${ce.object}`:"";return`${(n==null?void 0:n.length)||0}:${je}:${Ae}`},[n]),N=String(e??S),R=t==="replace"?"replace":"override",[T,A]=_.useState(null),[W,z]=_.useState(null),[J,K]=_.useState(!1),[re,te]=_.useState(""),[Q,D]=_.useState(!1),[$,E]=_.useState("");_.useEffect(()=>{A(null),z(null),te(""),K(!1),E(""),D(!1)},[N]);const[L,M]=_.useState(""),[ee,F]=_.useState(!0),[U,V]=_.useState(!1),[O,H]=_.useState(!0),[Y]=_.useState(()=>({compact:q5(),show:!1})),ae=Y.compact,[ie,_e]=_.useState(Y.show),[fe,ge]=_.useState(!1),Ne=N,Ue=_.useMemo(()=>Ug(Ne),[Ne]),[We,ut]=_.useState("grid"),[Fe,et]=_.useState(Ue),[$e,Ve]=_.useState(!1),[le,be]=_.useState(1),Pe=_.useRef(null),me=_.useRef(null),Ce=_.useRef(!1),[Te,Je]=_.useState(0),rt=_.useRef(null),ht=_.useRef(0),lt=_.useRef(0),Ct=_.useRef(0),Xt=_.useRef(0),[Pn,zt]=_.useState(!1),[wn,Un]=_.useState(""),[Mn,vn]=_.useState({}),Dn=_.useRef({});_.useEffect(()=>{Dn.current=Mn},[Mn]);const[bn,js]=_.useState(""),[Kn,Ss]=_.useState(""),Ar=_.useMemo(()=>{var ce;const q=(ce=n==null?void 0:n[0])==null?void 0:ce.scope;return Sx(q,"session")},[n]),[Fn,de]=_.useState(Ar),[Se,tt]=_.useState("standard"),[Qe,ct]=_.useState(""),[mt,It]=_.useState(""),[Et,Zt]=_.useState(""),[St,Qt]=_.useState(""),[Ht,Bt]=_.useState(""),[Pt,Dt]=_.useState(""),[qe,ln]=_.useState(""),[pt,rn]=_.useState("qwen/qwen3-next-80b");_.useEffect(()=>{de(Ar)},[N]);const gt=Array.isArray(n)?n:[],Wn=typeof r=="string"?r:"",cn=Array.isArray(o)?o:[],Gs=typeof l=="number"?l:void 0,ns=typeof c=="number"?c:void 0,Vr=typeof u=="number"?u:void 0,hr=typeof f=="number"?f:void 0,ii=h,oi=m,Ps=R==="override"&&(T!=null&&T.items)&&Array.isArray(T.items)?T.items:gt,he=typeof(T==null?void 0:T.active_memory_text)=="string"&&T.active_memory_text.trim()?T.active_memory_text:Wn,mr=(T==null?void 0:T.effort)??ii,Xi=(T==null?void 0:T.warnings)??oi,_r=_.useMemo(()=>new Set(["rdf:type","schema:name","skos:preflabel","skos:altlabel","dcterms:title","dcterms:identifier"]),[]),Tr=_.useMemo(()=>O?Ps:(Ps||[]).filter(q=>!zp(q==null?void 0:q.predicate,_r)),[Ps,O,_r]),Gr=_.useMemo(()=>F5(Ps,{groupEdges:ee}),[Ps,ee]),dt=_.useMemo(()=>{if(O)return Gr;const q=[];for(const ce of Gr.edges){const Ae=(ce&&ce.data&&Array.isArray(ce.data.assertions)?ce.data.assertions:[]).filter(Ge=>!zp(Ge==null?void 0:Ge.predicate,_r));if(!Ae.length)continue;const Ee=eO(Ae);q.push({...ce,label:Ee,data:{...ce.data,assertions:Ae,predicateSummary:Ee}})}return{nodes:Gr.nodes,edges:q}},[Gr,O,_r]),hn=_.useMemo(()=>dt.nodes.map(q=>q.id),[dt.nodes]),Ds=_.useMemo(()=>{const q=hn[0]||"",ce=hn[hn.length-1]||"";return`${hn.length}:${q}:${ce}`},[hn]),Kr=_.useMemo(()=>{var ce;const q=new Map;for(const je of dt.nodes)q.set(je.id,String(((ce=je.data)==null?void 0:ce.label)||je.id));return q},[dt.nodes]),ss=_.useMemo(()=>{var ce;const q=new Map;for(const je of dt.nodes)q.set(je.id,String(((ce=je.data)==null?void 0:ce.kind)||""));return q},[dt.nodes]),To=L.trim().toLowerCase(),Mo=_.useMemo(()=>{var ce;if(!To)return new Set;const q=new Set;for(const je of dt.nodes){const Ae=String(je.id||"").toLowerCase(),Ee=String(((ce=je.data)==null?void 0:ce.label)||"").toLowerCase();(Ae.includes(To)||Ee.includes(To))&&q.add(je.id)}return q},[dt.nodes,To]),Ro=_.useCallback((q,ce)=>{const je={};for(const Ae of hn){const Ee=q[Ae]||ce[Ae];je[Ae]=Ee?{x:Ee.x,y:Ee.y}:{x:0,y:0}}return je},[hn]);_.useEffect(()=>{vn(q=>{const ce=$u(dt,{kind:We,seed:Fe}),je={};for(const Ae of hn){const Ee=q[Ae]||ce[Ae];je[Ae]=Ee?{x:Ee.x,y:Ee.y}:{x:0,y:0}}return je})},[dt,We,Fe,hn,Ds]),_.useEffect(()=>{if(!Ce.current)return;const q=b.current;if(!(!q||typeof q.fitView!="function")&&hn.length){Ce.current=!1;try{q.fitView({padding:.2,duration:0})}catch{try{q.fitView({padding:.2})}catch{}}}},[hn.length,Ds,Mn]),_.useEffect(()=>{Ve(!1),Pe.current=null,me.current=null,Ce.current=!1,ht.current=0,lt.current=0,Ct.current=0;const q=Nx(Ne);if(q&&Object.keys(q.positions||{}).length){if(ut(q.kind),et(q.seed),zt(!0),Un(q.saved_at||""),q.viewport){me.current=q.viewport;const Ee=b.current;if(Ee&&typeof Ee.setViewport=="function"){try{Ee.setViewport(q.viewport,{duration:0})}catch{try{Ee.setViewport(q.viewport)}catch{}}me.current=null}}else Ce.current=!0;const Ae=$u(dt,{kind:q.kind,seed:q.seed});vn(Ro(q.positions,Ae));return}zt(!1),Un("");const ce=Ug(Ne);et(ce);const je=$u(dt,{kind:We,seed:ce});vn(je),We==="force"&&dt.nodes.length>0&&dt.nodes.length<=320&&(Pe.current=$m(dt,{seed:ce,positions:je,...df(le)}),Ve(!0))},[Ne]);const zn=_.useMemo(()=>{const q=String(bn||"").trim(),ce=String(Kn||"").trim();return!q||!ce?null:z5(dt,q,ce,{directed:U})},[dt,bn,Kn,U]),pr=!!(zn&&String(bn||"").trim()&&String(Kn||"").trim()),Hn=_.useMemo(()=>{const q=String(bn||"").trim(),ce=String(Kn||"").trim();if(!q||!ce)return null;const je=U,Ae=new Map,Ee=(_t,xt)=>{const Ut=Ae.get(_t);Ut?Ut.push(xt):Ae.set(_t,[xt])};for(const _t of dt.edges)Ee(_t.source,_t.target),je||Ee(_t.target,_t.source);const Ge=new Set,yt=[];for(Ge.add(q),yt.push(q);yt.length;){const _t=yt.shift(),xt=Ae.get(_t)||[];for(const Ut of xt)Ge.has(Ut)||(Ge.add(Ut),yt.push(Ut))}return{reachableFromStart:Ge.size,endReachable:Ge.has(ce),nodes:dt.nodes.length,edges:dt.edges.length,assertions:Tr.length}},[U,dt.edges,dt.nodes.length,Kn,bn,Tr.length]),Zi=_.useMemo(()=>new Set((zn==null?void 0:zn.nodeIds)||[]),[zn]),ai=_.useMemo(()=>new Set((zn==null?void 0:zn.edgeIds)||[]),[zn]),[Rn,Fs]=_.useState(""),[ds,Ks]=_.useState(""),fs=!!(String(Rn||"").trim()||String(ds||"").trim()),xa=_.useMemo(()=>{const q=new Set,ce=new Set,je=String(Rn||"").trim(),Ae=String(ds||"").trim();if(je){q.add(je);for(const Ee of dt.edges)(Ee.source===je||Ee.target===je)&&(ce.add(Ee.id),q.add(Ee.source),q.add(Ee.target));return{nodes:q,edges:ce}}if(Ae){const Ee=dt.edges.find(Ge=>Ge.id===Ae);Ee&&(ce.add(Ee.id),q.add(Ee.source),q.add(Ee.target))}return{nodes:q,edges:ce}},[dt.edges,ds,Rn]);_.useEffect(()=>{Fs(""),Ks(""),js(""),Ss("")},[N]);const[Qi,un]=_.useState(!1);_.useEffect(()=>{un(!1)},[N]),_.useEffect(()=>{$e||(Pe.current=null)},[$e]),_.useEffect(()=>{if(We!=="force")return;const q=Pe.current;if(!q)return;const ce=df(le);q.options.springLength=ce.springLength,q.options.repulsionStrength=ce.repulsionStrength},[We,le]),_.useEffect(()=>{We!=="force"&&$e&&Ve(!1)},[We,$e]),_.useEffect(()=>{if(!$e||We!=="force"||dt.nodes.length===0||typeof window>"u"||typeof window.requestAnimationFrame!="function")return;Pe.current||(Pe.current=$m(dt,{seed:Fe,positions:Dn.current,...df(le)}));let q=0,ce=0,je=0;const Ae=dt.nodes.length<=140?2:1,Ee=1600,Ge=.08,yt=_t=>{if(q=window.requestAnimationFrame(yt),_t-ce<33)return;ce=_t;const xt=Pe.current;if(!xt){Ve(!1);return}B5(xt,Ae),je+=Ae,vn(W5(xt)),(U5(xt)<=Ge||je>=Ee)&&Ve(!1)};return q=window.requestAnimationFrame(yt),()=>{window.cancelAnimationFrame(q)}},[dt,We,$e,Fe]);const ba=_.useMemo(()=>dt.nodes.map(q=>{var dn;const ce=Zi.has(q.id),je=Mo.has(q.id),Ae=Rn===q.id,Ee=fs&&xa.nodes.has(q.id),Ge=ff((dn=q.data)==null?void 0:dn.kind),yt="rgba(34, 211, 238, 0.88)",_t=je?"0 0 0 1px rgba(34, 211, 238, 0.34), 0 0 16px rgba(34, 211, 238, 0.26), 0 0 44px rgba(34, 211, 238, 0.14)":"",xt=ce?"rgba(168, 85, 247, 0.9)":je?yt:Ge.stroke,Ut=Ae?"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,Kt=_t&&Ut?`${_t}, ${Ut}`:Ut||_t||void 0,ms=ce?"rgba(168, 85, 247, 0.10)":je?"rgba(34, 211, 238, 0.08)":Ge.bg,Ft=pr?ce||Ae?1:.16:fs?Ee||Ae?1:.1:1;return{...q,position:Mn[q.id]?{x:Mn[q.id].x,y:Mn[q.id].y}:q.position,style:{...q.style||{},border:`1px solid ${xt}`,borderRadius:10,background:ms,color:"rgba(255,255,255,0.92)",opacity:Ft,padding:8,fontSize:12,boxShadow:Kt,width:180,cursor:"pointer"}}}),[dt.nodes,pr,Mo,Mn,Rn,Zi,fs,xa.nodes]),Sc=_.useMemo(()=>dt.edges.map(q=>{const ce=ai.has(q.id),je=ds===q.id,Ae=fs&&xa.edges.has(q.id),Ee=ce?"rgba(168, 85, 247, 0.9)":fs?Ae||je?"rgba(96, 165, 250, 0.55)":"rgba(255,255,255,0.14)":"rgba(255,255,255,0.18)",Ge=ce?2.75:fs?Ae||je?2.25:1.25:1.5,yt=je?"drop-shadow(0 0 10px rgba(168, 85, 247, 0.25))":void 0,_t=ce?"rgba(168, 85, 247, 0.9)":pr?"rgba(255,255,255,0.10)":"rgba(255,255,255,0.28)",xt=pr?ce||je?1:.1:fs?Ae||je?1:.08:1,Ut=pr?ce||je?1:0:fs?Ae||je?1:0:1,Kt=pr?ce||je?String(q.label||""):"":String(q.label||"");return{...q,label:Kt,style:{...q.style||{},stroke:Ee,strokeWidth:Ge,filter:yt,opacity:xt},animated:!1,markerEnd:{type:qf.ArrowClosed,color:_t,width:20,height:20},labelShowBg:!0,labelBgPadding:[6,3],labelBgBorderRadius:10,labelBgStyle:{fill:`rgba(0, 0, 0, ${.38*Ut})`,stroke:`rgba(255, 255, 255, ${.14*Ut})`,strokeWidth:1},labelStyle:{fill:`rgba(255, 255, 255, ${.92*Ut})`,fontSize:10,fontWeight:600,letterSpacing:.2,textTransform:"lowercase"}}}),[dt.edges,pr,ds,ai,fs,xa.edges]),Lo=_.useMemo(()=>{if(!ds)return[];const q=dt.edges.find(je=>je.id===ds),ce=q&&q.data&&Array.isArray(q.data.assertions)?q.data.assertions:[];return Array.isArray(ce)?ce:[]},[dt.edges,ds]),hs=_.useMemo(()=>ds&&dt.edges.find(q=>q.id===ds)||null,[dt.edges,ds]),Mr=_.useMemo(()=>{const q=String(Rn||"").trim();return q?Ps.filter(ce=>!ce||typeof ce!="object"||!(ce.subject===q||ce.object===q)?!1:O?!0:!zp(ce.predicate,_r)):[]},[Ps,Rn,O,_r]),Rr=_.useMemo(()=>ds?Lo:Mr,[Lo,ds,Mr]),eo=_.useMemo(()=>{const q=new Map;for(const ce of Rr){if(!ce||typeof ce!="object")continue;const je=ce.provenance&&typeof ce.provenance=="object"&&!Array.isArray(ce.provenance)?ce.provenance:null,Ae=je&&typeof je.span_id=="string"?je.span_id.trim():"",Ee=je&&typeof je.writer_run_id=="string"?je.writer_run_id.trim():"",Ge=typeof ce.owner_id=="string"?ce.owner_id.trim():"",yt=Ee||Ge;if(!yt||!Ae)continue;const _t=`${yt}|${Ae}`,xt=q.get(_t),Ut=typeof ce.observed_at=="string"?ce.observed_at.trim():"";xt?(xt.count+=1,Ut&&(!xt.last_observed_at||Ut>xt.last_observed_at)&&(xt.last_observed_at=Ut,xt.last_observed_at_fmt=hf(Ut),xt.assertion=ce)):q.set(_t,{span_run_id:yt,span_id:Ae,writer_run_id:Ee,count:1,last_observed_at:Ut,last_observed_at_fmt:hf(Ut),assertion:ce})}return Array.from(q.values()).sort((ce,je)=>String(je.last_observed_at||"").localeCompare(String(ce.last_observed_at||"")))},[Rr]),gr=_.useMemo(()=>{const q=new Map;for(const ce of Rr){if(!ce||typeof ce!="object")continue;const je=ce.provenance&&typeof ce.provenance=="object"&&!Array.isArray(ce.provenance)?ce.provenance:null,Ae=je&&typeof je.span_id=="string"?je.span_id.trim():"",Ee=je&&typeof je.writer_run_id=="string"?je.writer_run_id.trim():"";if(!Ee||Ae)continue;const Ge=q.get(Ee),yt=typeof ce.observed_at=="string"?ce.observed_at.trim():"";Ge?(Ge.count+=1,yt&&(!Ge.last_observed_at||yt>Ge.last_observed_at)&&(Ge.last_observed_at=yt,Ge.last_observed_at_fmt=hf(yt),Ge.assertion=ce)):q.set(Ee,{run_id:Ee,count:1,last_observed_at:yt,last_observed_at_fmt:hf(yt),assertion:ce})}return Array.from(q.values()).sort((ce,je)=>String(je.last_observed_at||"").localeCompare(String(ce.last_observed_at||"")))},[Rr]),Ns=_.useCallback(q=>{const ce=String(q.run_id||"").trim(),je=typeof q.span_id=="string"?String(q.span_id).trim():"";if(ce){if(k){try{k({run_id:ce,span_id:je||void 0,assertion:q.assertion})}catch{}return}if(w&&je)try{w({run_id:ce,span_id:je,assertion:q.assertion})}catch{}}},[w,k]),yr=_.useCallback(async q=>{var je;const ce=String(q??"");if(ce){try{if(typeof((je=navigator.clipboard)==null?void 0:je.writeText)=="function"){await navigator.clipboard.writeText(ce);return}}catch{}try{const Ae=document.createElement("textarea");Ae.value=ce,Ae.style.position="fixed",Ae.style.left="-9999px",document.body.appendChild(Ae),Ae.select(),document.execCommand("copy"),document.body.removeChild(Ae)}catch{}}},[]),Lr=_.useCallback(()=>{const q=b.current;if(!(!q||typeof q.fitView!="function")){if(Rn&&typeof q.getNode=="function"){const ce=q.getNode(Rn);if(ce){q.fitView({nodes:[ce],padding:.55,duration:350});return}}q.fitView({padding:.2,duration:350})}},[Rn]),Ys=_.useCallback(q=>{const ce=q.kind,je=Math.trunc(q.seed);Ve(!1),Pe.current=null,me.current=null,ut(ce),et(je);const Ae=$u(dt,{kind:ce,seed:je});vn(Ae),ce==="force"&&(q.autoPlay??!0)&&dt.nodes.length>0&&dt.nodes.length<=320&&(Pe.current=$m(dt,{seed:je,positions:Ae,...df(le)}),Ve(!0))},[dt,le]),Ci=_.useCallback(()=>{if(We==="force"){if($e){Ve(!1);return}Pe.current=$m(dt,{seed:Fe,positions:Dn.current,...df(le)}),Ve(!0)}},[dt,We,$e,Fe,le]);_.useEffect(()=>()=>{typeof window>"u"||typeof window.cancelAnimationFrame=="function"&&Xt.current&&window.cancelAnimationFrame(Xt.current)},[]);const rs=_.useCallback(()=>{const q=b.current;if(!q||typeof q.getViewport!="function"||!hn.length)return null;const ce=rt.current;if(!ce)return null;const je=ce.getBoundingClientRect();if(!Number.isFinite(je.width)||!Number.isFinite(je.height)||je.width<64||je.height<64)return null;const Ae=q.getViewport(),Ee=typeof(Ae==null?void 0:Ae.zoom)=="number"&&Number.isFinite(Ae.zoom)?Ae.zoom:null,Ge=typeof(Ae==null?void 0:Ae.x)=="number"&&Number.isFinite(Ae.x)?Ae.x:null,yt=typeof(Ae==null?void 0:Ae.y)=="number"&&Number.isFinite(Ae.y)?Ae.y:null;if(Ee===null||Ge===null||yt===null||Ee<=0)return null;const _t=140,xt=Math.min(hn.length,180),Ut=Dn.current;let Kt=0,ms=0;for(const Ft of hn){const dn=Ut[Ft];if(!dn||!Number.isFinite(dn.x)||!Number.isFinite(dn.y))continue;ms+=1;const En=[{x:dn.x,y:dn.y},{x:dn.x+90,y:dn.y+24}];for(const xn of En){const Qn=xn.x*Ee+Ge,Qs=xn.y*Ee+yt;if(Qn>-_t&&Qn<je.width+_t&&Qs>-_t&&Qs<je.height+_t)return!1}if(Kt++,Kt>=xt)break}return ms?!0:null},[hn]),Ir=_.useCallback(q=>{typeof window>"u"||typeof window.requestAnimationFrame!="function"||Xt.current||(Xt.current=window.requestAnimationFrame(()=>{Xt.current=0;const ce=rs();if(ce===null){if(Ct.current>=12)return;Ct.current+=1,window.setTimeout(()=>Ir(`${q}:probe`),120);return}if(ce!==!0){Ct.current=0,lt.current=0;return}Ct.current=0;const je=b.current;if(je&&typeof je.fitView=="function")try{je.fitView({padding:.2,duration:0})}catch{try{je.fitView({padding:.2})}catch{}}if(lt.current+=1,lt.current>=4&&ht.current<1){lt.current=0,ht.current+=1,Je(Ae=>Ae+1);return}lt.current<8&&window.setTimeout(()=>Ir(`${q}:retry`),220)}))},[rs]);_.useEffect(()=>{lt.current=0,ht.current=0,Ct.current=0,Ir("mount")},[N,Ir]),_.useEffect(()=>{Ir("graph change")},[Ds,Ir]),_.useEffect(()=>{const q=rt.current;if(!q||typeof window>"u"||typeof ResizeObserver!="function")return;const ce=new ResizeObserver(()=>Ir("resize"));return ce.observe(q),()=>ce.disconnect()},[Ir]);const ka=_.useCallback(()=>{const q=new Date().toISOString(),ce={};for(const yt of hn){const _t=Dn.current[yt];_t&&typeof _t.x=="number"&&typeof _t.y=="number"&&(ce[yt]={x:_t.x,y:_t.y})}const je=b.current,Ae=je&&typeof je.toObject=="function"?je.toObject():null,Ee=Ae&&Ae.viewport?Ae.viewport:je&&typeof je.getViewport=="function"?je.getViewport():null,Ge=wj(Ee,{minZoom:Wg,maxZoom:qg,maxAbsTranslate:bj})??void 0;G5(Ne,{version:1,kind:We,seed:Fe,positions:ce,viewport:Ge,saved_at:q}),zt(!0),Un(q),Ve(!1)},[Ne,We,Fe,hn]),wr=_.useCallback(()=>{const q=Nx(Ne);if(!q)return;Ve(!1),Pe.current=null,ut(q.kind),et(q.seed),zt(!0),Un(q.saved_at||""),me.current=q.viewport||null,Ce.current=!q.viewport;const ce=$u(dt,{kind:q.kind,seed:q.seed});if(vn(Ro(q.positions,ce)),q.viewport){const je=b.current;if(je&&typeof je.setViewport=="function"){try{je.setViewport(q.viewport,{duration:0})}catch{try{je.setViewport(q.viewport)}catch{}}me.current=null}}},[Ro,dt,Ne]),to=_.useCallback(()=>{K5(Ne),zt(!1),Un("")},[Ne]),Nc=_.useCallback(q=>{if(!Array.isArray(q)||q.length===0)return;let ce=!1;vn(je=>{let Ae=je,Ee=!1;for(const Ge of q){const yt=Ge&&typeof Ge=="object"&&"id"in Ge&&typeof Ge.id=="string"?String(Ge.id):"",_t=(Ge==null?void 0:Ge.type)==="position"?Ge==null?void 0:Ge.position:null;yt&&_t&&typeof _t.x=="number"&&typeof _t.y=="number"&&(Ee||(Ae={...je},Ee=!0),Ae[yt]={x:_t.x,y:_t.y},Ge!=null&&Ge.dragging&&(ce=!0))}return Ee?Ae:je}),ce&&$e&&Ve(!1)},[$e]),Ei=_.useMemo(()=>{const q=new Map;for(const ce of dt.edges)q.set(ce.id,ce);return q},[dt.edges]),Js=_.useMemo(()=>{var Ae;if(!zn)return[];const q=zn.nodeIds||[],ce=zn.edgeIds||[],je=[];for(let Ee=0;Ee<Math.min(q.length-1,ce.length);Ee++){const Ge=q[Ee],yt=q[Ee+1],_t=ce[Ee],xt=Ei.get(_t),Ut=String(((Ae=xt==null?void 0:xt.data)==null?void 0:Ae.predicateSummary)||(xt==null?void 0:xt.label)||"").trim(),Kt=xt&&xt.source===Ge&&xt.target===yt?"forward":xt&&xt.source===yt&&xt.target===Ge?"reverse":"unknown";je.push({from:Ge,to:yt,edgeId:_t,predicate:Ut,dir:Kt})}return je},[Ei,zn]),Yu=_.useCallback(async()=>{if(g){te(""),E(""),K(!0);try{const q=Y5(Ht),ce=Fp(Pt,{allowZero:!0,allowNegativeOne:!0}),je=Fp(qe,{allowZero:!0}),Ae=await g({scope:Fn,owner_id:void 0,recall_level:Se,query_text:Qe||void 0,subject:mt||void 0,predicate:Et||void 0,object:St||void 0,min_score:q,limit:ce,max_input_tokens:je,model:pt||void 0});A(Ae),z("live query"),R==="replace"&&y&&Ae&&Array.isArray(Ae.items)&&y(Ae.items,{kind:"live query",result:Ae})}catch(q){const ce=q instanceof Error?q.message:String(q);te(ce||"Query failed")}finally{K(!1)}}},[Pt,qe,Ht,pt,St,y,g,Et,R,Qe,Se,Fn,mt]),Xs=_.useCallback(async()=>{if(!g)return;const q=String(bn||"").trim(),ce=String(Kn||"").trim();if(!q||!ce)return;const je=Math.max(200,Fp(Pt)??80),Ae=60;E(""),te(""),D(!0);try{const Ee=[],Ge=new Set,yt=Ft=>{if(!Ft||typeof Ft!="object"||typeof Ft.subject!="string"||typeof Ft.predicate!="string"||typeof Ft.object!="string")return;const dn=`${Ft.subject}|${Ft.predicate}|${Ft.object}|${String(Ft.observed_at||"")}|${String(Ft.scope||"")}|${String(Ft.owner_id||"")}`;Ge.has(dn)||(Ge.add(dn),Ee.push(Ft))};for(const Ft of Ps)yt(Ft);const _t=U,xt=new Set,Ut=[q],Kt=new Set([q]),ms=async Ft=>{const dn=await g({scope:Fn,recall_level:Se,min_score:0,limit:je,subject:Ft,query_text:void 0,max_input_tokens:0,model:void 0});if(dn&&Array.isArray(dn.items)){for(const En of dn.items)if(yt(En),typeof En.subject=="string"&&En.subject.trim()===Ft&&typeof En.object=="string"){const xn=En.object.trim();xn&&!Kt.has(xn)&&(Kt.add(xn),Ut.push(xn))}}if(!_t){const En=await g({scope:Fn,recall_level:Se,min_score:0,limit:je,object:Ft,query_text:void 0,max_input_tokens:0,model:void 0});if(En&&Array.isArray(En.items)){for(const xn of En.items)if(yt(xn),typeof xn.object=="string"&&xn.object.trim()===Ft&&typeof xn.subject=="string"){const Qn=xn.subject.trim();Qn&&!Kt.has(Qn)&&(Kt.add(Qn),Ut.push(Qn))}}}};for(;Ut.length&&xt.size<Ae&&!Kt.has(ce);){const Ft=Ut.shift();!Ft||xt.has(Ft)||(xt.add(Ft),await ms(Ft))}A({ok:!0,count:Ee.length,items:Ee,active_memory_text:he,raw:{expanded_for_path:!0,expanded_nodes:xt.size,discovered_nodes:Kt.size,merged:Ee.length,directed:_t}}),z("expanded neighborhood"),R==="replace"&&y&&y(Ee,{kind:"expanded neighborhood",result:{ok:!0,count:Ee.length,items:Ee,active_memory_text:he,raw:{expanded_for_path:!0,expanded_nodes:xt.size,discovered_nodes:Kt.size,merged:Ee.length,directed:_t}}})}catch(Ee){const Ge=Ee instanceof Error?Ee.message:String(Ee);E(Ge||"Expand neighborhood failed")}finally{D(!1)}},[U,he,Ps,Pt,y,g,Kn,bn,R,Se,Fn]),no=_.useCallback(()=>{A(null),z(null),te(""),K(!1),E(""),D(!1),js(""),Ss(""),Fs(""),Ks("")},[]),Zs="Search KG",Io=dt.nodes.length,li=dt.edges.length,ja=Tr.length;return s.jsx("div",{className:"amx-host",children:s.jsxs("div",{className:"amx-root",children:[s.jsxs("div",{className:"amx-left",children:[s.jsx("div",{className:"amx-graphbar",role:"toolbar","aria-label":"Graph layout controls",children:s.jsxs("div",{className:"amx-graphbar-row",children:[s.jsx("span",{className:"amx-graphbar-title",children:"layout"}),s.jsxs("select",{value:We,onChange:q=>ut(Hg(q.target.value,We)),disabled:!hn.length,children:[s.jsx("option",{value:"grid",children:"grid (deterministic)"}),s.jsx("option",{value:"radial",children:"radial (bfs)"}),s.jsx("option",{value:"circle",children:"circle"}),s.jsx("option",{value:"force",children:"force (simulation)"})]}),We==="force"?s.jsxs("label",{className:"amx-graphbar-spread",children:[s.jsx("span",{className:"amx-graphbar-title",children:"spread"}),s.jsx("input",{type:"range",min:"0.7",max:"2.2",step:"0.1",value:le,onChange:q=>be(xj(Number(q.target.value),.7,2.2,1))}),s.jsxs("span",{className:"amx-small",children:[le.toFixed(1),"×"]})]}):null,s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>Ys({kind:We,seed:Fe}),disabled:!hn.length,children:"Apply"}),s.jsx("button",{type:"button",className:"amx-btn",onClick:Ci,disabled:!hn.length||We!=="force",children:$e?"Pause simulation":"Play simulation"})]})}),s.jsxs("div",{className:"amx-graph","aria-label":"Knowledge graph",ref:rt,children:[s.jsx(Ly,{children:s.jsxs(mj,{nodes:ba,edges:Sc,defaultViewport:{x:0,y:0,zoom:1},minZoom:Wg,maxZoom:qg,onInit:q=>{b.current=q;const ce=me.current;if(ce&&typeof q.setViewport=="function")try{q.setViewport(ce,{duration:0})}catch{try{q.setViewport(ce)}catch{}}if(Ce.current&&typeof q.fitView=="function")try{q.fitView({padding:.2,duration:0})}catch{try{q.fitView({padding:.2})}catch{}}me.current=null,Ce.current=!1,Ir("init")},nodesDraggable:!0,nodesConnectable:!1,elementsSelectable:!0,onNodesChange:Nc,onNodeClick:(q,ce)=>{Ks(""),Fs(ce.id)},onEdgeClick:(q,ce)=>{Fs(""),Ks(ce.id)},onPaneClick:()=>{Fs(""),Ks("")},children:[s.jsx(E5,{className:"amx-flow-controls",children:s.jsx(Lu,{type:"button",className:`amx-control-legend ${fe?"amx-control-legend-active":""}`,onClick:()=>ge(q=>!q),title:fe?"Hide node color legend":"Show node color legend","aria-label":fe?"Hide node color legend":"Show node color legend",children:s.jsx(H5,{})})}),s.jsx(Bf,{position:"bottom-right",className:"amx-panel-bottom-right",children:s.jsx("div",{className:"amx-panel-toggles",children:s.jsx("button",{type:"button",className:"amx-minimap-toggle",onClick:()=>_e(q=>!q),title:ie?"Hide minimap preview":"Show minimap preview","aria-label":ie?"Hide minimap preview":"Show minimap preview",children:ie?"minimap on":"minimap off"})})}),ie?s.jsx(x5,{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:ae?120:160,height:ae?80:110,marginBottom:56},nodeColor:q=>{var ce;return ff((ce=q.data)==null?void 0:ce.kind).minimap}}):null,fe?s.jsxs(Bf,{position:"bottom-left",className:"amx-legend-panel",children:[s.jsx("div",{className:"amx-legend-title",children:"node colors"}),s.jsx("div",{className:"amx-legend",children:[{k:"person",label:"person"},{k:"org",label:"org"},{k:"concept",label:"concept"},{k:"claim",label:"claim"},{k:"event",label:"event"},{k:"doc",label:"doc"},{k:"vocab",label:"vocab"}].map(({k:q,label:ce})=>s.jsx("span",{className:"amx-legend-item",style:{borderColor:ff(q).stroke},children:ce},q))})]}):null,s.jsx(L5,{gap:20,size:1,color:"rgba(255,255,255,0.06)"})]})},Te),s.jsxs("details",{className:"amx-panel amx-controls",children:[s.jsxs("summary",{children:[s.jsx("span",{className:"amx-controls-title",children:Zs}),s.jsxs("span",{className:"amx-small",children:[ja," assertions · ",Io," nodes · ",li," edges"]})]}),s.jsxs("div",{className:"amx-toolbar",style:{marginTop:10},children:[s.jsxs("div",{className:"amx-toolbar-grid",children:[s.jsxs("label",{children:["search / highlight",s.jsx("input",{value:L,onChange:q=>M(q.target.value),placeholder:"filter nodes by id/label"})]}),s.jsxs("label",{children:["group edges",s.jsxs("select",{value:String(ee),onChange:q=>F(q.target.value==="true"),children:[s.jsx("option",{value:"true",children:"group (subject→object)"}),s.jsx("option",{value:"false",children:"no grouping"})]})]}),s.jsxs("label",{children:["view",s.jsxs("select",{value:String(O),onChange:q=>H(q.target.value==="true"),children:[s.jsx("option",{value:"true",children:"all assertions"}),s.jsx("option",{value:"false",children:"hide rdf:type / labels"})]})]}),s.jsxs("label",{children:["path mode",s.jsxs("select",{value:String(U),onChange:q=>V(q.target.value==="true"),children:[s.jsx("option",{value:"false",children:"undirected"}),s.jsx("option",{value:"true",children:"directed"})]})]})]}),s.jsxs("details",{className:"amx-details",children:[s.jsx("summary",{children:"layout"}),s.jsxs("div",{className:"amx-toolbar-grid",style:{marginTop:10},children:[s.jsxs("label",{children:["layout",s.jsxs("select",{value:We,onChange:q=>ut(Hg(q.target.value,We)),children:[s.jsx("option",{value:"grid",children:"grid (deterministic)"}),s.jsx("option",{value:"radial",children:"radial (bfs)"}),s.jsx("option",{value:"circle",children:"circle"}),s.jsx("option",{value:"force",children:"force (simulation)"})]})]}),s.jsxs("label",{children:["seed",s.jsx("input",{type:"number",step:"1",value:Fe,onChange:q=>et(Math.trunc(Number(q.target.value||0)||0))})]})]}),s.jsxs("div",{className:"amx-actions",style:{marginTop:10},children:[s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>Ys({kind:We,seed:Fe}),disabled:!hn.length,children:"Apply layout"}),We==="force"?s.jsx("button",{type:"button",className:"amx-btn",onClick:Ci,disabled:!hn.length,children:$e?"Pause simulation":"Play simulation"}):null,s.jsx("button",{type:"button",className:"amx-btn",onClick:ka,disabled:!hn.length,children:"Save layout"}),Pn?s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"amx-btn",onClick:wr,children:"Load saved"}),s.jsx("button",{type:"button",className:"amx-btn",onClick:to,children:"Clear saved"})]}):null]}),s.jsxs("div",{className:"amx-small",style:{marginTop:10,opacity:.9},children:["Drag nodes to adjust manually; use ",s.jsx("span",{className:"amx-mono",children:"Save layout"})," for a stable, replayable view.",Pn?s.jsxs("span",{children:[" ","(saved",wn?`: ${wn}`:"",")"]}):s.jsx("span",{children:" (no saved layout)"})]})]}),s.jsxs("details",{className:"amx-details",children:[s.jsx("summary",{children:"path"}),s.jsxs("div",{className:"amx-toolbar-grid",style:{marginTop:10},children:[s.jsxs("label",{children:["path start",s.jsxs("select",{value:bn,onChange:q=>js(q.target.value),children:[s.jsx("option",{value:"",children:"(none)"}),hn.map(q=>s.jsx("option",{value:q,children:(()=>{const ce=Kr.get(q)||q;return ce===q?ce:`${ce} (${q})`})()},q))]})]}),s.jsxs("label",{children:["path end",s.jsxs("select",{value:Kn,onChange:q=>Ss(q.target.value),children:[s.jsx("option",{value:"",children:"(none)"}),hn.map(q=>s.jsx("option",{value:q,children:(()=>{const ce=Kr.get(q)||q;return ce===q?ce:`${ce} (${q})`})()},q))]})]})]}),zn?s.jsx("div",{className:"amx-small",style:{marginTop:10},children:Js.map((q,ce)=>{const je=Kr.get(q.from)||q.from,Ae=Kr.get(q.to)||q.to,Ee=q.dir==="reverse"?" ← ":" → ",Ge=q.predicate?` (${q.predicate})`:"";return s.jsxs("div",{children:[ce===0?s.jsx("span",{children:je}):null,Ee,s.jsxs("span",{children:[Ae,Ge]})]},`${q.edgeId}:${ce}`)})}):bn&&Kn?s.jsxs("div",{className:"amx-small",style:{marginTop:10,opacity:.9},children:["No path found in the current subgraph (",(Hn==null?void 0:Hn.assertions)??ja," assertions · ",(Hn==null?void 0:Hn.nodes)??dt.nodes.length," nodes ·"," ",(Hn==null?void 0:Hn.edges)??dt.edges.length," edges). Start reaches ",(Hn==null?void 0:Hn.reachableFromStart)??0," nodes.",g?s.jsx("div",{style:{marginTop:10},children:s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>void Xs(),disabled:Q,children:Q?"Expanding…":"Expand neighborhood"})}):null]}):s.jsx("div",{className:"amx-small",style:{marginTop:10},children:"(no path)"})]}),s.jsxs("details",{className:"amx-details",children:[s.jsx("summary",{children:"query"}),s.jsxs("div",{className:"amx-toolbar-grid",style:{marginTop:10},children:[s.jsxs("label",{children:["query_text (semantic)",s.jsx("input",{value:Qe,onChange:q=>ct(q.target.value),placeholder:"e.g. emotion chip"})]}),s.jsxs("label",{children:["subject (exact)",s.jsx("input",{value:mt,onChange:q=>It(q.target.value),placeholder:"e.g. ex:person-data"})]}),s.jsxs("label",{children:["predicate (exact)",s.jsx("input",{value:Et,onChange:q=>Zt(q.target.value),placeholder:"e.g. schema:about"})]}),s.jsxs("label",{children:["object (exact)",s.jsx("input",{value:St,onChange:q=>Qt(q.target.value),placeholder:"e.g. ex:concept-emotion-chip"})]}),s.jsxs("label",{children:["min_score",s.jsx("input",{type:"number",step:"any",value:Ht,onChange:q=>Bt(q.target.value),placeholder:"(auto)"})]}),s.jsxs("label",{children:["limit",s.jsx("input",{type:"number",min:"-1",step:"1",value:Pt,onChange:q=>Dt(q.target.value),placeholder:"0/-1 = unlimited (if supported)"})]})]})]}),s.jsxs("details",{className:"amx-details",children:[s.jsx("summary",{children:"advanced"}),s.jsxs("div",{className:"amx-toolbar-grid",style:{marginTop:10},children:[s.jsxs("label",{children:["scope",s.jsxs("select",{value:Fn,onChange:q=>de(Sx(q.target.value,Fn)),children:[s.jsx("option",{value:"run",children:"run"}),s.jsx("option",{value:"session",children:"session"}),s.jsx("option",{value:"global",children:"global"}),s.jsx("option",{value:"all",children:"all"})]})]}),s.jsxs("label",{children:["recall level",s.jsxs("select",{value:Se,onChange:q=>tt(q.target.value||"standard"),children:[s.jsx("option",{value:"urgent",children:"urgent"}),s.jsx("option",{value:"standard",children:"standard"}),s.jsx("option",{value:"deep",children:"deep"})]})]}),s.jsxs("label",{children:["max_input_tokens",s.jsx("input",{type:"number",min:"0",step:"1",value:qe,onChange:q=>ln(q.target.value),placeholder:"(auto)"})]}),s.jsxs("label",{children:["model (budgeting)",s.jsx("input",{value:pt,onChange:q=>rn(q.target.value),placeholder:"qwen/qwen3-next-80b"})]})]})]}),s.jsxs("div",{className:"amx-actions",children:[s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>void Yu(),disabled:!g||J,children:J?"Querying…":"Query store"}),s.jsx("button",{type:"button",className:"amx-btn",onClick:no,disabled:!T&&!re&&!J,children:"Reset to step output"}),T?s.jsxs("span",{className:"amx-small",children:["showing: ",W||"live query"]}):s.jsx("span",{className:"amx-small",children:"showing: step output"}),re?s.jsx("span",{className:"amx-small",style:{color:"var(--error, rgba(255, 80, 80, 0.95))"},children:re}):null,$?s.jsx("span",{className:"amx-small",style:{color:"var(--error, rgba(255, 80, 80, 0.95))"},children:$}):null]})]})]})]})]}),s.jsxs("div",{className:"amx-right",children:[s.jsxs("div",{className:"amx-panel",children:[s.jsx("h3",{children:"Details"}),s.jsx("div",{className:"amx-small",style:{marginBottom:8},children:"Derived from `memory_kg_query` packetization (max_input_tokens); safe to inject into an LLM system prompt."}),(()=>{const q=J5(mr);return q?s.jsx("div",{className:"amx-small",style:{marginBottom:8,opacity:.9},children:q}):null})(),(()=>{const q=Xi;if(!q)return null;const ce=typeof q=="string"?q:Array.isArray(q)?q.map(je=>String(je)).join(" · "):JSON.stringify(q);return!ce||!ce.trim()?null:s.jsx("div",{className:"amx-small",style:{marginBottom:8,color:"var(--warning, rgba(255, 180, 90, 0.95))"},children:ce})})(),s.jsx("div",{className:"amx-small",style:{marginBottom:8,opacity:.9},children:(()=>{const q=(T==null?void 0:T.packets_version)??Gs,ce=(T==null?void 0:T.packed_count)??ns,je=(T==null?void 0:T.dropped)??Vr,Ae=(T==null?void 0:T.estimated_tokens)??hr,Ee=[];return typeof q=="number"&&Ee.push(`packets_v${q}`),typeof ce=="number"&&Ee.push(`packed=${ce}`),typeof je=="number"&&Ee.push(`dropped=${je}`),typeof Ae=="number"&&Ee.push(`est_tokens=${Ae}`),Ee.length?Ee.join(" · "):"No packetization stats (set max_input_tokens > 0)."})()}),s.jsx("div",{className:"amx-active-memory",children:Z5(he||"(empty)",L)}),(()=>{const q=T!=null&&T.packets&&Array.isArray(T.packets)?T.packets:cn;return!Array.isArray(q)||q.length===0?null:s.jsxs("div",{style:{marginTop:10},children:[s.jsxs("button",{type:"button",className:"amx-btn",onClick:()=>un(ce=>!ce),children:[Qi?"Hide":"Show"," packets (",q.length,")"]}),Qi?s.jsx("div",{className:"amx-list",style:{marginTop:10},children:q.slice(0,120).map((ce,je)=>{const Ae=ce&&typeof ce=="object"&&!Array.isArray(ce)?ce:null,Ee=Ae&&typeof Ae.statement=="string"?Ae.statement:typeof ce=="string"?ce:"",Ge=Ae&&(typeof Ae.retrieval_score=="number"||typeof Ae.retrieval_score=="string")?Ae.retrieval_score:null,yt=Ae&&typeof Ae.observed_at=="string"?Ae.observed_at:null;return s.jsxs("div",{className:"amx-item",children:[s.jsx("div",{className:"amx-mono",children:Ee||"(packet)"}),yt||Ge!==null?s.jsxs("div",{className:"amx-small",children:[yt?`[${yt}]`:null,yt&&Ge!==null?" ":null,Ge!==null?`score:${Ge}`:null]}):null]},je)})}):null]})})(),s.jsx("div",{style:{marginTop:14,marginBottom:12,borderTop:"1px solid var(--ui-border-1, rgba(255,255,255,0.08))"}}),s.jsx("div",{className:"amx-small",style:{marginBottom:8,fontWeight:700,opacity:.9},children:"Inspect"}),s.jsx("div",{className:"amx-small",style:{marginBottom:8},children:"Click a node or edge to inspect its assertions."}),Rn?s.jsxs("div",{className:"amx-item",style:{marginBottom:10,display:"flex",justifyContent:"space-between",gap:10,alignItems:"center"},children:[s.jsxs("div",{style:{minWidth:0},children:[s.jsx("div",{className:"amx-mono",style:{fontSize:11,opacity:.95},children:Kr.get(Rn)||Rn}),s.jsxs("div",{className:"amx-small",children:["kind=",ss.get(Rn)||"entity"," · id=",Rn]})]}),s.jsxs("div",{className:"amx-actions",children:[s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>void yr(Rn),children:"Copy id"}),s.jsx("button",{type:"button",className:"amx-btn",onClick:Lr,children:"Focus"})]})]}):hs&&hs.source&&hs.target?s.jsxs("div",{className:"amx-item",style:{marginBottom:10,display:"flex",justifyContent:"space-between",gap:10,alignItems:"center"},children:[s.jsxs("div",{style:{minWidth:0},children:[s.jsxs("div",{className:"amx-mono",style:{fontSize:11,opacity:.95},children:[hs.source," —",String(hs.label||((ci=hs.data)==null?void 0:ci.predicateSummary)||"").trim()||"?","→ ",hs.target]}),s.jsxs("div",{className:"amx-small",children:["edge_id=",hs.id]})]}),s.jsxs("div",{className:"amx-actions",children:[s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>void yr(hs.id),children:"Copy id"}),s.jsx("button",{type:"button",className:"amx-btn",onClick:Lr,children:"Fit"})]})]}):s.jsx("div",{className:"amx-small",style:{marginBottom:10,opacity:.9},children:"(no selection)"}),s.jsx("div",{className:"amx-list",children:Rr.slice(0,80).map((q,ce)=>{const je=String(q.subject||"").trim(),Ae=String(q.predicate||"").trim(),Ee=String(q.object||"").trim(),Ge=Kr.get(je)||je,yt=Kr.get(Ee)||Ee,_t=ss.get(je)||"entity",xt=ss.get(Ee)||"entity",Ut=ff(_t),Kt=ff(xt),ms=hf(q.observed_at),Ft=X5(q),dn=q.provenance&&typeof q.provenance=="object"&&!Array.isArray(q.provenance)?q.provenance:null,En=dn&&typeof dn.span_id=="string"?dn.span_id.trim():"",xn=dn&&typeof dn.writer_run_id=="string"?dn.writer_run_id.trim():"",Qn=typeof q.owner_id=="string"?q.owner_id.trim():"",Qs=xn||Qn,Yr=!!((k||w)&&En&&Qs),$i=!!(k&&xn&&!En),Sa=Yr||$i;return s.jsxs("div",{className:"amx-item amx-triple-card",children:[s.jsxs("div",{className:"amx-triple-row",children:[s.jsx("button",{type:"button",className:"amx-term",style:{borderColor:Ut.stroke,background:Ut.bg},title:je,onClick:()=>{je&&(Ks(""),Fs(je))},children:Ge||je||"(subject)"}),s.jsx("span",{className:"amx-arrow",children:"—"}),s.jsx("span",{className:"amx-predicate",title:Ae,children:kj(Ae)||"(predicate)"}),s.jsx("span",{className:"amx-arrow",children:"→"}),s.jsx("button",{type:"button",className:"amx-term",style:{borderColor:Kt.stroke,background:Kt.bg},title:Ee,onClick:()=>{Ee&&(Ks(""),Fs(Ee))},children:yt||Ee||"(object)"})]}),s.jsxs("div",{className:"amx-triple-meta",children:[ms?s.jsxs("span",{className:"amx-small",title:String(q.observed_at||""),children:["[",ms,"]"]}):null,Ft?s.jsx("span",{className:"amx-small",children:Ft}):null]}),En||xn?s.jsxs("div",{className:"amx-triple-actions",children:[En?s.jsxs("span",{className:"amx-small",children:["span:",En]}):null,xn?s.jsxs("span",{className:"amx-small",children:["run:",xn]}):null,Sa?s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>{if(Yr&&En&&Qs){Ns({run_id:Qs,span_id:En,assertion:q});return}$i&&xn&&Ns({run_id:xn,assertion:q})},children:"Open transcript"}):null]}):null]},ce)})})]}),s.jsxs("div",{className:"amx-panel",children:[s.jsx("h3",{children:"Transcript"}),s.jsx("div",{className:"amx-small",style:{marginBottom:8},children:"Pivot from a triple to its provenance transcript (span/note artifact, or run input fallback)."}),eo.length?s.jsxs("div",{style:{marginBottom:12},children:[s.jsx("div",{className:"amx-small",style:{marginBottom:6,opacity:.85},children:"spans"}),s.jsx("div",{className:"amx-list",style:{maxHeight:320},children:eo.slice(0,60).map(q=>s.jsxs("div",{className:"amx-item",style:{display:"flex",justifyContent:"space-between",gap:10,alignItems:"center"},children:[s.jsxs("div",{style:{minWidth:0},children:[s.jsxs("div",{className:"amx-mono",style:{fontSize:11,opacity:.95},children:["span:",q.span_id]}),s.jsxs("div",{className:"amx-small",children:["run_id=",q.span_run_id," · assertions=",q.count,q.last_observed_at_fmt?` · last=[${q.last_observed_at_fmt}]`:""]})]}),w||k?s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>Ns({run_id:q.span_run_id,span_id:q.span_id,assertion:q.assertion}),children:"Open transcript"}):null]},`${q.span_run_id}|${q.span_id}`))})]}):null,k&&gr.length?s.jsxs("div",{style:{marginBottom:12},children:[s.jsx("div",{className:"amx-small",style:{marginBottom:6,opacity:.85},children:"runs (fallback)"}),s.jsx("div",{className:"amx-list",style:{maxHeight:240},children:gr.slice(0,40).map(q=>s.jsxs("div",{className:"amx-item",style:{display:"flex",justifyContent:"space-between",gap:10,alignItems:"center"},children:[s.jsxs("div",{style:{minWidth:0},children:[s.jsxs("div",{className:"amx-mono",style:{fontSize:11,opacity:.95},children:["run:",q.run_id]}),s.jsxs("div",{className:"amx-small",children:["assertions=",q.count,q.last_observed_at_fmt?` · last=[${q.last_observed_at_fmt}]`:""]})]}),s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>Ns({run_id:q.run_id,assertion:q.assertion}),children:"Open transcript"})]},q.run_id))})]}):null,!eo.length&&!(k&&gr.length)?s.jsx("div",{className:"amx-small",children:"(no provenance)"}):null]})]})]})})}function cc({open:e,title:t,children:n,actions:r,variant:o="default",onClose:l}){const c=_.useId();if(_.useEffect(()=>{if(!e)return;const f=h=>{h.key==="Escape"&&l()};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[e,l]),!e)return null;const u=o==="fullscreen";return s.jsx("div",{className:`modal_backdrop${u?" fullscreen":""}`,onMouseDown:f=>{f.target===f.currentTarget&&l()},children:s.jsxs("div",{className:`modal_panel${u?" fullscreen":""}`,role:"dialog","aria-modal":"true","aria-labelledby":c,children:[s.jsxs("div",{className:"modal_header",children:[s.jsx("div",{className:"modal_title",id:c,children:t}),s.jsx("button",{className:"btn",onClick:l,children:"Close"})]}),s.jsx("div",{className:"modal_body",children:n}),r?s.jsx("div",{className:"modal_footer",children:r}):null]})})}function Bp(e,t="session"){const n=String(e||"").trim().toLowerCase();return n==="run"||n==="session"||n==="global"||n==="all"?n:t}function cl(e){const t=typeof e=="string"?e.trim():"";if(!t)return null;const n=t.replace(/(\.\d{3})\d+/,"$1"),r=Date.parse(n);return Number.isFinite(r)?r:null}function lc(e){if(typeof e!="number"||!Number.isFinite(e))return"—";const t=new Date(e),n=t.getUTCFullYear(),r=String(t.getUTCMonth()+1).padStart(2,"0"),o=String(t.getUTCDate()).padStart(2,"0"),l=String(t.getUTCHours()).padStart(2,"0"),c=String(t.getUTCMinutes()).padStart(2,"0");return`${n}/${r}/${o} ${l}:${c}`}function nO(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=cl(t);return n!==null?lc(n):t}function Oy(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,`
|
|
150
|
-
`).replace(/\\n/g,`
|
|
151
|
-
`).replace(/\\t/g," "):""}function jj(e){return String(e??"").replace(/[*_`~]/g,"")}function Am(e,t){const n=!!(t!=null&&t.strip_punct),r=Oy(e);let o=jj(r).replace(/\s+/g," ").trim().toLowerCase();return n&&(o=o.replace(/[^\p{L}\p{N}\s]+/gu,"").replace(/\s+/g," ").trim()),o}function Tm(e,t){const n=String(t??"").trim();if(!n)return!1;const r=Am(n,{strip_punct:!1});if(!r)return!1;if(Am(String(e??""),{strip_punct:!1}).includes(r))return!0;const l=Am(n,{strip_punct:!0});return l?Am(String(e??""),{strip_punct:!0}).includes(l):!1}function Cx(e){const t=Oy(e).trim();if(!t)return[];const n=[],r=c=>{const u=String(c??"").replace(/\s+/g," ").trim();u&&(u.length<6||n.includes(u)||n.push(u))},o=t.search(/[`*_~]/);if(o>0){const c=t.slice(0,o);c.replace(/\s+/g," ").trim().length>=10&&r(c)}const l=[/`([^`]+)`/g,/\*\*([^*]+)\*\*/g,/__([^_]+)__/g,/\*([^*]+)\*/g,/_([^_]+)_/g];for(const c of l){let u;for(;(u=c.exec(t))!==null;){const f=String(u[1]??"").trim();f&&r(f)}}return r(jj(t)),n}function sO(e){const t=String(e??"").replace(/\r\n/g,`
|
|
152
|
-
`).replace(/\r/g,`
|
|
153
|
-
`);if(!t)return null;const n=t.split(`
|
|
154
|
-
`);let r;const o=[],l=[];let c=null,u=[],f=!1;const h=()=>{if(!c)return;const y=u.join(`
|
|
155
|
-
`).trim();y&&l.push({role:c,lines:[y]}),c=null,u=[]};for(const y of n){const w=r?null:y.match(/^\s*created_at\s*=\s*(.+)\s*$/i);if(w&&w[1]){r=w[1].trim();continue}const k=y.match(/^\s*(USER|ASSISTANT|SYSTEM)\s*:\s*(.*)$/i);if(k){f=!0,h();const b=String(k[1]||"").trim().toLowerCase();c=b==="user"?"user":b==="assistant"?"assistant":"system";const S=String(k[2]??"");u=S?[S]:[];continue}c?u.push(y):o.push(y)}if(h(),!f||!l.length)return null;const m=o.join(`
|
|
156
|
-
`).trim(),g={messages:[]};r&&(g.created_at=r),m&&g.messages.push({role:"system",content:m});for(const y of l)g.messages.push({role:y.role,content:y.lines.join(`
|
|
157
|
-
`)});return g.messages.length?g:null}function Ex(e,t){const n=String(e||""),r=String(t||"");return r>n?r:n}function $x(e){const t=String((e==null?void 0:e.subject)||"").trim(),n=String((e==null?void 0:e.predicate)||"").trim(),r=String((e==null?void 0:e.object)||"").trim(),o=String((e==null?void 0:e.observed_at)||"").trim(),l=String((e==null?void 0:e.scope)||"").trim(),c=String((e==null?void 0:e.owner_id)||"").trim();return`${t}|${n}|${r}|${o}|${l}|${c}`}function rO(e){const t=String((e==null?void 0:e.observed_at)||"").trim(),n=String((e==null?void 0:e.subject)||"").trim(),r=String((e==null?void 0:e.predicate)||"").trim(),o=String((e==null?void 0:e.object)||"").trim(),l=String((e==null?void 0:e.scope)||"").trim(),c=String((e==null?void 0:e.owner_id)||"").trim(),u=[];l&&u.push(`scope=${l}`),c&&u.push(`owner=${c}`);const f=u.length?` (${u.join(", ")})`:"";return`${t?`[${t}] `:""}${n} --${r}--> ${o}${f}`}function iO({gateway:e,selected_run_id:t,selected_session_id:n}){const[r,o]=_.useState(String(t||"").trim()),[l,c]=_.useState(String(n||"").trim()),[u,f]=_.useState("all"),h=u==="all",[m,g]=_.useState(!0),[y,w]=_.useState(750),[k,b]=_.useState(5e3),[S,N]=_.useState([]),[R,T]=_.useState(void 0),[A,W]=_.useState(""),[z,J]=_.useState(!1),[K,re]=_.useState([]),[te,Q]=_.useState(!1),[D,$]=_.useState(!1),[E,L]=_.useState(""),[M,ee]=_.useState(""),[F,U]=_.useState(""),[V,O]=_.useState(""),[H,Y]=_.useState("artifact"),[ae,ie]=_.useState(null),[_e,fe]=_.useState(""),[ge,Ne]=_.useState(null),Ue=_.useRef(!1),We=_.useMemo(()=>{const de=ge,Se=de!=null&&de.attributes&&typeof de.attributes=="object"&&!Array.isArray(de.attributes)?de.attributes:null;return(Se&&typeof Se.evidence_quote=="string"?String(Se.evidence_quote):"").trim()},[ge]),ut=_.useMemo(()=>{const de=ae,Se=de&&typeof de=="object"&&!Array.isArray(de)?de:null,tt=Se&&typeof Se.note=="string"?String(Se.note):"";return Oy(tt).trim()},[ae]),Fe=_.useMemo(()=>{const de=ae&&typeof ae=="object"&&!Array.isArray(ae)?ae:null,Se=de&&Array.isArray(de.messages)?de.messages:null;return Array.isArray(Se)?Se:null},[ae]),et=_.useMemo(()=>{const de=ut,Se=We;return!de||!Se?!1:Tm(de,Se)},[We,ut]),$e=_.useMemo(()=>{const de=Fe,Se=We;if(!de||!Se)return[];const tt=[];for(let Qe=0;Qe<Math.min(de.length,500);Qe++){const ct=de[Qe],mt=(ct==null?void 0:ct.content)==null?"":String(ct.content);Tm(mt,Se)&&tt.push(Qe)}return tt},[We,Fe]),Ve=_.useMemo(()=>new Set($e),[$e]),le=$e.length?$e[0]:null,be=_.useCallback(de=>{const Se=document.getElementById(`source_msg_${de}`);Se&&typeof Se.scrollIntoView=="function"&&Se.scrollIntoView({block:"center",behavior:"smooth"})},[]),Pe=_.useCallback(()=>{const de=document.getElementById("source_note_hit_0")||document.getElementById("source_note_msg_hit_0");de&&typeof de.scrollIntoView=="function"&&de.scrollIntoView({block:"center",behavior:"smooth"})},[]);_.useEffect(()=>{if(te&&!(D||E)&&!Ue.current){if(le!==null){Ue.current=!0,window.setTimeout(()=>be(le),0);return}if(et){Ue.current=!0,window.setTimeout(()=>Pe(),0);return}}},[be,Pe,E,le,D,et,te]);const me=_.useRef(new Set),Ce=_.useRef(""),Te=_.useRef(null),Je=_.useRef(null);_.useEffect(()=>{o(String(t||"").trim())},[t]),_.useEffect(()=>{c(String(n||"").trim())},[n]);const rt=_.useMemo(()=>{const de=String(r||"").trim(),Se=String(l||"").trim();return`mindmap:${u}:${de}:${Se}`},[r,l,u]),ht=_.useMemo(()=>{let de=null,Se=null;for(const tt of S){const Qe=cl(tt==null?void 0:tt.observed_at);Qe!==null&&(de=de===null?Qe:Math.min(de,Qe),Se=Se===null?Qe:Math.max(Se,Qe))}return{min_ms:de,max_ms:Se}},[S]),lt=1e3,Ct=_.useMemo(()=>{const de=ht.min_ms,Se=ht.max_ms;if(typeof de!="number"||typeof Se!="number"||!Number.isFinite(de)||!Number.isFinite(Se))return null;if(Se<=de)return{min_ms:de,max_ms:de,real_max_ms:Se};const tt=de+Math.ceil((Se-de)/lt)*lt;return{min_ms:de,max_ms:tt,real_max_ms:Se}},[ht.max_ms,ht.min_ms]),[Xt,Pn]=_.useState(!0),[zt,wn]=_.useState(null);_.useEffect(()=>{Xt&&Ct&&wn(Ct.max_ms)},[Xt,Ct]);const Un=_.useMemo(()=>{const de=typeof zt=="number"?zt:null;return de===null?S:S.filter(Se=>{const tt=cl(Se==null?void 0:Se.observed_at);return tt===null?!0:tt<=de})},[S,zt]),Mn=_.useCallback((de,Se)=>{const tt=Array.isArray(de)?de:[],Qe=String(Ce.current||"").trim(),ct=new Set,mt=[];let It="";for(const Et of tt){if(!Et||typeof Et!="object"||typeof Et.subject!="string"||typeof Et.predicate!="string"||typeof Et.object!="string")continue;const Zt=$x(Et);if(ct.has(Zt))continue;ct.add(Zt),mt.push(Et);const St=String(Et.observed_at||"").trim();St&&(It=Ex(It,St))}N(mt),T(Se==null?void 0:Se.warnings),me.current=ct,Ce.current=It||Qe},[]),vn=_.useCallback(async de=>{const Se=Bp(de.scope,"session"),tt=String(de.subject||"").trim(),Qe=String(de.predicate||"").trim(),ct=String(de.object||"").trim(),mt=String(de.since||"").trim(),It=String(de.until||"").trim(),Et=String(de.active_at||"").trim(),Zt=String(de.query_text||"").trim(),St=typeof de.min_score=="number"&&Number.isFinite(de.min_score)?Number(de.min_score):void 0,Qt=de.order==="asc"?"asc":"desc",Ht=typeof de.limit=="number"&&Number.isFinite(de.limit)?Number(de.limit):0,Bt=String(r||"").trim(),Pt=String(l||"").trim(),Dt={scope:Se,all_owners:h,limit:Ht,order:Qt};tt&&(Dt.subject=tt),Qe&&(Dt.predicate=Qe),ct&&(Dt.object=ct),mt&&(Dt.since=mt),It&&(Dt.until=It),Et&&(Dt.active_at=Et),Zt&&(Dt.query_text=Zt),typeof St=="number"&&(Dt.min_score=St),h||(Se==="run"?Bt&&(Dt.run_id=Bt):Se==="session"?Pt?Dt.session_id=Pt:Bt&&(Dt.run_id=Bt):Se==="all"&&(Bt?Dt.run_id=Bt:Pt&&(Dt.session_id=Pt)));try{const qe=await e.kg_query(Dt),ln=Array.isArray(qe==null?void 0:qe.items)?qe.items:[],pt=qe==null?void 0:qe.warnings;return{ok:(qe==null?void 0:qe.ok)!==!1,count:Number((qe==null?void 0:qe.count)||ln.length),items:ln,warnings:pt,raw:qe}}catch(qe){const ln=qe instanceof Error?qe.message:String(qe);if(ln.includes("Run '")&&ln.includes("not found")&&!Pt&&(Se==="session"||Se==="all")&&Bt){const rn=await e.kg_query({...Dt,run_id:void 0,session_id:Bt}),gt=Array.isArray(rn==null?void 0:rn.items)?rn.items:[],Wn=rn==null?void 0:rn.warnings;return{ok:(rn==null?void 0:rn.ok)!==!1,count:Number((rn==null?void 0:rn.count)||gt.length),items:gt,warnings:Wn,raw:rn}}throw new Error(ln||"KG query failed")}},[h,e,r,l]),Dn=_.useCallback(async de=>{var Qe;const Se=String(de.run_id||"").trim(),tt=String(de.span_id||"").trim();if(!(!Se||!tt)){Q(!0),$(!0),L(""),U(Se),O(tt),Y("artifact"),ee(`source span:${tt}`),ie(null),fe(""),Ne(de.assertion&&typeof de.assertion=="object"?de.assertion:null),Ue.current=!1;try{const ct=[Se],mt=typeof((Qe=de.assertion)==null?void 0:Qe.owner_id)=="string"?String(de.assertion.owner_id).trim():"";mt&&mt!==Se&&ct.push(mt);let It=null,Et=null;for(const Zt of ct)try{Et=await(await e.download_run_artifact_content(Zt,tt)).text(),Zt!==Se&&U(Zt);break}catch(St){It=St instanceof Error?St.message:String(St)}if(Et==null)throw new Error(It||"Failed to load source span");fe(Et);try{const Zt=JSON.parse(Et);ie(Zt)}catch{ie(null)}}catch(ct){const mt=ct instanceof Error?ct.message:String(ct);L(mt||"Failed to load source span")}finally{$(!1)}}},[e]),bn=_.useCallback(async de=>{const Se=String(de.run_id||"").trim();if(!Se)return null;try{const tt=await e.list_run_artifacts(Se,{limit:200}),ct=(Array.isArray(tt==null?void 0:tt.items)?tt.items:[]).map(St=>{const Qt=typeof(St==null?void 0:St.artifact_id)=="string"?String(St.artifact_id).trim():"",Ht=St!=null&&St.tags&&typeof St.tags=="object"&&!Array.isArray(St.tags)?St.tags:null,Bt=Ht&&typeof Ht.kind=="string"?String(Ht.kind).trim():"";return{artifact_id:Qt,kind:Bt}}).filter(St=>!!(St.artifact_id&&(St.kind==="conversation_span"||St.kind==="memory_note")));if(!ct.length)return null;if(ct.length===1)return ct[0].artifact_id;const mt=de.assertion,It=mt!=null&&mt.attributes&&typeof mt.attributes=="object"&&!Array.isArray(mt.attributes)?mt.attributes:null,Zt=(It&&typeof It.evidence_quote=="string"?String(It.evidence_quote):"").trim();if(!Zt)return null;for(const St of ct.slice(0,10))try{const Ht=await(await e.download_run_artifact_content(Se,St.artifact_id)).text(),Bt=JSON.parse(Ht);if(Bt&&typeof Bt=="object"){const Pt=typeof Bt.note=="string"?String(Bt.note):"";if(Pt&&Pt.includes(Zt))return St.artifact_id;const Dt=Array.isArray(Bt.messages)?Bt.messages:null;if(Dt){for(const qe of Dt.slice(0,200))if(((qe==null?void 0:qe.content)==null?"":String(qe.content)).includes(Zt))return St.artifact_id}}}catch{}}catch{}return null},[e]),js=_.useCallback(async de=>{const Se=String(de.run_id||"").trim();if(Se){Q(!0),$(!0),L(""),U(Se),O(""),Y("run_input"),ee(`transcript run:${Se}`),ie(null),fe(""),Ne(de.assertion&&typeof de.assertion=="object"?de.assertion:null),Ue.current=!1;try{const tt=await bn({run_id:Se,assertion:de.assertion});if(tt){await Dn({run_id:Se,span_id:tt,assertion:de.assertion});return}const Qe=await e.get_run_input_data(Se),ct=Qe&&typeof Qe=="object"&&!Array.isArray(Qe)?Qe.input_data:null,mt={kind:"run_input_data",run_id:Se};if(Qe&&typeof(Qe==null?void 0:Qe.workflow_id)=="string"&&(mt.workflow_id=String(Qe.workflow_id)),ct&&typeof ct=="object"&&!Array.isArray(ct)){const It=ct.context,Zt=(It&&typeof It=="object"&&Array.isArray(It.messages)?It.messages:null)||(Array.isArray(ct.messages)?ct.messages:null);Array.isArray(Zt)&&(mt.messages=Zt);const St=["text","prompt","task","message"];for(const Qt of St){const Ht=ct[Qt];if(typeof Ht=="string"&&Ht.trim()){mt.note=Ht.trim();break}}mt.input_data=ct}!mt.messages&&!mt.note&&(mt.note=JSON.stringify(ct??Qe??{},null,2));try{const It=await e.get_run(Se),Et=It&&typeof(It==null?void 0:It.created_at)=="string"?String(It.created_at):"";Et&&(mt.created_at=Et)}catch{}ie(mt),fe(JSON.stringify(Qe,null,2))}catch(tt){const Qe=tt instanceof Error?tt.message:String(tt);L(Qe||"Failed to load run input transcript")}finally{$(!1)}}},[e,Dn,bn]),Kn=_.useCallback(async()=>{W(""),J(!0);try{const de=u==="all"?"all":u,Se=await vn({scope:de,limit:0,order:"desc"});Mn(Se.items||[],{warnings:Se.warnings}),Te.current={scope:de}}catch(de){const Se=de instanceof Error?de.message:String(de);W(Se||"Load failed")}finally{J(!1)}},[vn,Mn,u]);_.useEffect(()=>{S.length||Kn()},[]);const Ss=_.useCallback(async de=>{const Se=Bp(de.scope,"session");return Je.current=de,await vn({scope:Se,subject:de.subject,predicate:de.predicate,object:de.object,query_text:de.query_text,min_score:de.min_score,since:de.since,until:de.until,active_at:de.active_at,limit:typeof de.limit=="number"?de.limit:0,order:"desc"})},[vn]),Ar=_.useCallback((de,Se)=>{var tt;if((Se==null?void 0:Se.kind)==="live query"){const Qe=Je.current;Qe&&(Te.current={scope:Bp(Qe.scope,"session"),subject:typeof Qe.subject=="string"?Qe.subject:void 0,predicate:typeof Qe.predicate=="string"?Qe.predicate:void 0,object:typeof Qe.object=="string"?Qe.object:void 0})}Mn(de,{warnings:(tt=Se==null?void 0:Se.result)==null?void 0:tt.warnings})},[Mn]),Fn=_.useCallback(async()=>{const de=Te.current;if(!de)return;const Se=String(Ce.current||"").trim(),tt=await vn({scope:de.scope,subject:de.subject,predicate:de.predicate,object:de.object,since:Se||void 0,order:"asc",limit:0}),Qe=Array.isArray(tt.items)?tt.items:[];if(!Qe.length)return;const mt=Date.now()+Math.max(250,Math.min(2e4,k)),It=me.current,Et=[],Zt=[];let St=String(Ce.current||"").trim();for(const Qt of Qe){if(!Qt||typeof Qt!="object"||typeof Qt.subject!="string"||typeof Qt.predicate!="string"||typeof Qt.object!="string")continue;const Ht=$x(Qt);if(It.has(Ht))continue;It.add(Ht),Et.push(Qt),Zt.push({id:Ht,assertion:Qt,expires_at_ms:mt});const Bt=String(Qt.observed_at||"").trim();Bt&&(St=Ex(St,Bt))}Et.length&&(Ce.current=St,N(Qt=>{const Ht=Qt.concat(Et);return Ht.sort((Bt,Pt)=>String((Pt==null?void 0:Pt.observed_at)||"").localeCompare(String((Bt==null?void 0:Bt.observed_at)||""))),Ht}),re(Qt=>{const Ht=Qt.concat(Zt);return Ht.sort((Bt,Pt)=>Pt.expires_at_ms-Bt.expires_at_ms),Ht.slice(0,30)}))},[k,vn]);return _.useEffect(()=>{if(!m)return;let de=!1,Se=null;const tt=async()=>{if(!de){try{await Fn()}catch{}de||(Se=window.setTimeout(()=>void tt(),Math.max(250,Math.min(6e4,y))))}};return tt(),()=>{de=!0,Se!==null&&window.clearTimeout(Se)}},[m,y,Fn]),_.useEffect(()=>{if(!K.length)return;const de=window.setInterval(()=>{const Se=Date.now();re(tt=>tt.filter(Qe=>Qe.expires_at_ms>Se))},250);return()=>window.clearInterval(de)},[K.length]),s.jsxs("div",{className:"mindmap_root",children:[s.jsxs("div",{className:"mindmap_bar",children:[s.jsx("button",{className:"btn",onClick:()=>void Kn(),disabled:z,children:z?"Loading…":"Load snapshot"}),s.jsxs("label",{className:"field_inline",children:[s.jsx("span",{className:"mono muted",children:"source"}),s.jsxs("select",{value:u,onChange:de=>{const Se=String(de.target.value||"").trim();(Se==="all"||Se==="global"||Se==="session"||Se==="run")&&f(Se)},children:[s.jsx("option",{value:"all",children:"all memory"}),s.jsx("option",{value:"global",children:"global"}),s.jsx("option",{value:"session",children:"session"}),s.jsx("option",{value:"run",children:"run"})]})]}),s.jsx(fT,{checked:m,onChange:g}),u==="session"?s.jsxs("label",{className:"field_inline",children:[s.jsx("span",{className:"mono muted",children:"session_id"}),s.jsx("input",{className:"mono",value:l,onChange:de=>c(String(de.target.value||"")),placeholder:"(required)"})]}):null,u==="run"?s.jsxs("label",{className:"field_inline",children:[s.jsx("span",{className:"mono muted",children:"run_id"}),s.jsx("input",{className:"mono",value:r,onChange:de=>o(String(de.target.value||"")),placeholder:"(required)"})]}):null,s.jsxs("details",{className:"mindmap_details",children:[s.jsx("summary",{className:"mono muted",children:"advanced"}),s.jsx("div",{className:"mindmap_advanced",children:s.jsxs("div",{className:"field_inline",children:[s.jsx("span",{className:"mono muted",style:{width:84},children:"poll_ms"}),s.jsx("input",{type:"number",min:250,max:6e4,step:50,value:y,onChange:de=>w(Math.max(250,Number(de.target.value||0)||750))}),s.jsx("span",{className:"mono muted",children:"highlight_ms"}),s.jsx("input",{type:"number",min:250,max:2e4,step:250,value:k,onChange:de=>b(Math.max(250,Number(de.target.value||0)||5e3))})]})})]})]}),A?s.jsx("div",{className:"mindmap_error mono",children:A}):null,s.jsxs("div",{className:"mindmap_explorer",children:[s.jsx(tO,{title:"mindmap",resetKey:rt,queryMode:"replace",items:Un,warnings:R,onQuery:Ss,onItemsReplace:Ar,onOpenSpan:({run_id:de,span_id:Se,assertion:tt})=>{Dn({run_id:de,span_id:Se,assertion:tt})},onOpenTranscript:({run_id:de,span_id:Se,assertion:tt})=>{const Qe=String(de||"").trim(),ct=typeof Se=="string"?String(Se).trim():"";Qe&&(ct?Dn({run_id:Qe,span_id:ct,assertion:tt}):js({run_id:Qe,assertion:tt}))}},rt),K.length?s.jsxs("div",{className:"mindmap_recent mindmap_overlay mindmap_overlay_recent",children:[s.jsx("div",{className:"mindmap_recent_title mono muted",children:"new assertions"}),s.jsx("div",{className:"mindmap_recent_list",children:K.slice().sort((de,Se)=>Se.expires_at_ms-de.expires_at_ms).slice(0,12).map(de=>s.jsx("div",{className:"mindmap_recent_item mono",children:rO(de.assertion)},de.id))})]}):null,Ct?s.jsx("div",{className:"mindmap_timeline mindmap_overlay mindmap_overlay_timeline",children:s.jsxs("div",{className:"mindmap_timeline_row",children:[s.jsx("div",{className:"mindmap_timeline_label mono muted",children:lc(Math.min(typeof zt=="number"?zt:Ct.max_ms,Ct.real_max_ms))}),s.jsx("input",{className:"mindmap_slider",type:"range",min:Ct.min_ms,max:Ct.max_ms,step:lt,value:typeof zt=="number"?zt:Ct.max_ms,onChange:de=>{const Se=Number(de.target.value||0);wn(Se),Pn(Se>=Ct.max_ms)}}),s.jsxs("div",{className:"mindmap_timeline_counts mono muted",children:[Un.length.toLocaleString(),"/",S.length.toLocaleString()]})]})}):null]}),s.jsxs(cc,{open:te,title:M||"source",onClose:()=>{Q(!1)},children:[D?s.jsx("div",{className:"mono muted",children:"Loading…"}):null,E?s.jsx("div",{className:"mindmap_error mono",children:E}):null,!D&&!E?s.jsxs("div",{className:"source_span",children:[(()=>{const de=ge;if(!de)return null;const Se=String(de.subject||"").trim(),tt=String(de.predicate||"").trim(),Qe=String(de.object||"").trim(),ct=lc(cl(de.observed_at)),mt=de.attributes&&typeof de.attributes=="object"&&!Array.isArray(de.attributes)?de.attributes:null,It=mt&&typeof mt.evidence_quote=="string"?String(mt.evidence_quote):"",Et=mt&&typeof mt.original_context=="string"?String(mt.original_context):"";return s.jsxs("div",{className:"source_header",children:[s.jsxs("div",{className:"mono source_triple",title:`${Se} --${tt}--> ${Qe}`,children:[Se," ",s.jsxs("span",{className:"muted",children:["—",tt,"→"]})," ",Qe," ",ct?s.jsxs("span",{className:"muted",children:["[",ct,"]"]}):null]}),It?s.jsxs("div",{className:"source_evidence",children:[s.jsx("div",{className:"mono muted",style:{fontSize:11,marginBottom:6},children:"evidence_quote"}),s.jsx("pre",{className:"mono source_evidence_quote",children:It}),Et?s.jsxs("details",{className:"source_evidence_more",children:[s.jsx("summary",{className:"mono muted",children:"original_context"}),s.jsx("pre",{className:"mono source_evidence_quote",children:Et})]}):null]}):null]})})(),s.jsxs("div",{className:"mono muted",style:{marginBottom:10},children:["run_id=",F," · ",H==="artifact"?`span_id=${V}`:"source=input_data"]}),s.jsxs("div",{className:"source_actions",children:[le!==null?s.jsx("button",{className:"btn",onClick:()=>be(le),children:"Jump to evidence"}):null,le===null&&et?s.jsx("button",{className:"btn",onClick:()=>Pe(),children:"Jump to evidence"}):null]}),(()=>{const de=ae,Se=de&&typeof de=="object"&&!Array.isArray(de)?de:null,tt=Fe,Qe=ut,ct=Se&&typeof Se.created_at=="string"?String(Se.created_at):"",mt=ct?cl(ct):null,It=mt!==null?lc(mt):ct,Et=Se&&Se.span&&typeof Se.span=="object"&&!Array.isArray(Se.span)?Se.span:null,Zt=Et&&typeof Et.from_timestamp=="string"?String(Et.from_timestamp):"",St=Et&&typeof Et.to_timestamp=="string"?String(Et.to_timestamp):"",Qt=Zt?cl(Zt):null,Ht=St?cl(St):null,Bt=Qt!==null&&Ht!==null?`${lc(Qt)} → ${lc(Ht)}`:"";if(Qe){const Pt=sO(Qe);if(Pt){const Dt=We,qe=Dt?Pt.messages.findIndex(gt=>Tm(gt.content,Dt)):-1,ln=Dt?Cx(Dt):[],pt=Pt.created_at||ct,rn=pt?nO(pt):ct?It:"";return s.jsx("div",{className:"source_chat",children:Pt.messages.map((gt,Wn)=>{const cn=gt.role,Gs=!!(Dt&&Tm(gt.content,Dt)),ns=cn==="user"?"USER":cn==="assistant"?"ASSISTANT":"SYSTEM";return s.jsxs("div",{id:Wn===qe?"source_note_msg_hit_0":void 0,className:`source_msg source_${cn} ${Gs?"source_match":""}`,children:[s.jsxs("div",{className:"source_msg_meta mono muted",children:[s.jsxs("span",{children:["#",Wn+1," · ",ns,Gs?s.jsx("span",{className:"source_match_badge",children:"evidence"}):null]}),rn?s.jsx("span",{title:pt||"",children:rn}):null]}),s.jsx("div",{className:"source_msg_body",children:s.jsx(Si,{text:gt.content,highlights:Gs&&ln.length?ln:void 0,highlightClassName:"source_note_hit",highlightId:Wn===qe?"source_note_hit_0":void 0})})]},`note_msg:${Wn}`)})})}return s.jsxs("div",{className:"source_note",children:[ct?s.jsx("div",{className:"mono muted",style:{marginBottom:10},children:s.jsxs("span",{title:ct,children:["created_at=",It]})}):null,s.jsx(Si,{text:Qe,highlights:We?Cx(We):void 0,highlightClassName:"source_note_hit",highlightId:"source_note_hit_0"})]})}if(tt){const Pt=new Map;for(const qe of tt){const ln=typeof(qe==null?void 0:qe.role)=="string"?String(qe.role):"unknown";Pt.set(ln,(Pt.get(ln)||0)+1)}const Dt=Array.from(Pt.entries()).sort((qe,ln)=>ln[1]-qe[1]||qe[0].localeCompare(ln[0])).map(([qe,ln])=>`${qe}×${ln}`).join(" · ");return s.jsxs("div",{className:"source_chat",children:[ct?s.jsxs("div",{className:"mono muted",style:{marginBottom:10},children:[s.jsxs("span",{title:ct,children:["created_at=",It]})," · messages=",tt.length]}):null,Bt?s.jsxs("div",{className:"mono muted",style:{marginBottom:10},children:["span=",Bt]}):null,Dt?s.jsxs("div",{className:"mono muted",style:{marginBottom:10},children:["participants: ",Dt]}):null,tt.slice(0,200).map((qe,ln)=>{var Vr,hr;const pt=typeof(qe==null?void 0:qe.role)=="string"?String(qe.role):"unknown",rn=(qe==null?void 0:qe.content)==null?"":String(qe.content),gt=typeof(qe==null?void 0:qe.timestamp)=="string"?String(qe.timestamp):"",Wn=gt?cl(gt):null,cn=Wn!==null?lc(Wn):gt,Gs=typeof(qe==null?void 0:qe.message_id)=="string"?String(qe.message_id):typeof((Vr=qe==null?void 0:qe.metadata)==null?void 0:Vr.message_id)=="string"?String(qe.metadata.message_id):typeof((hr=qe==null?void 0:qe.metadata)==null?void 0:hr.id)=="string"?String(qe.metadata.id):"",ns=Ve.has(ln);return s.jsxs("div",{id:`source_msg_${ln}`,className:`source_msg source_${pt} ${ns?"source_match":""}`,children:[s.jsxs("div",{className:"source_msg_meta mono muted",children:[s.jsxs("span",{children:["#",ln+1," · ",pt,ns?s.jsx("span",{className:"source_match_badge",children:"evidence"}):null,Gs?s.jsx("span",{className:"source_msg_id",children:Gs}):null]}),gt?s.jsx("span",{title:gt,children:cn}):null]}),s.jsx("div",{className:"source_msg_body",children:s.jsx(Si,{text:rn})})]},ln)})]})}return s.jsx("pre",{className:"mono source_raw",style:{whiteSpace:"pre-wrap",wordBreak:"break-word"},children:(typeof de=="string"?de:_e)||"(empty)"})})()]}):null]})]})}const Up=4;function oO(e){var l;const t=(l=e==null?void 0:e.discoveries)==null?void 0:l.dreams_signals_brief;if(!t||typeof t!="object"||Array.isArray(t))return null;const n=typeof t.count=="number"&&Number.isInteger(t.count)&&t.count>0?t.count:0;if(!n)return null;const r=c=>Array.isArray(c)?c.filter(u=>typeof u=="string").map(u=>u.trim()).filter(Boolean):[],o=typeof t.dreams=="number"&&Number.isInteger(t.dreams)&&t.dreams>0?t.dreams:null;return{count:n,kinds:r(t.kinds),felt_tones:r(t.felt_tones),dreams:o}}function Ax(e){if(!e||typeof e!="object")return null;const t=String(e.title||"").trim(),n=String(e.statement||"").trim();if(!t&&!n)return null;const r=typeof e.entry_id=="string"&&e.entry_id.trim()?e.entry_id.trim():null;return{record_id:String(e.record_id||"").trim(),title:t,statement:n,entry_id:r}}function aO(e){var u,f;const t=h=>{var g;const m=(g=e==null?void 0:e[h])==null?void 0:g.open;return Array.isArray(m)?m.map(Ax).filter(y=>y!==null):[]},n=t("questions"),r=t("problems"),o=(u=e==null?void 0:e.lessons)==null?void 0:u.lessons,l=Array.isArray(o)?o.map(Ax).filter(h=>h!==null):[],c=typeof((f=e==null?void 0:e.lessons)==null?void 0:f.total)=="number"?e.lessons.total:l.length;return{questions:n.slice(0,Up),questions_total:n.length,problems:r.slice(0,Up),problems_total:r.length,lessons:l.slice(0,Up),lessons_total:c}}function Wp(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 Tx={review:"Review",working:"Working",pending:"Pending",done:"Done"},lO={review:"nothing needs you",working:"idle",pending:"nothing scheduled",done:"no recent runs"},cO={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 uO(e){const t=String((e==null?void 0:e.status)||"").trim().toLowerCase();if($o(t))return"done";const n=Ku(e);return n==="tool_approval"||n==="user_response"?"review":n==="scheduled"||t==="pending"||t==="queued"||t==="created"?"pending":"working"}function dO(e){const t=Ku(e);return t==="tool_approval"||t==="user_response"}function Mx(e,t=Date.now()){const n=uO(e),r=e!=null&&e.waiting&&typeof e.waiting=="object"?e.waiting:null,o=eh(r),l=qn((r==null?void 0:r.since)||(e==null?void 0:e.updated_at)||(e==null?void 0:e.created_at)||"");return{run_id:String((e==null?void 0:e.run_id)||""),column:n,workflow:String((e==null?void 0:e.workflow_id)||"").trim()||"(workflow?)",status:String((e==null?void 0:e.status)||"").trim().toLowerCase(),wait_kind:Ku(e),reason:G0(e),tool_names:o.map(c=>String((c==null?void 0:c.name)||"tool")).filter(Boolean),wait_key:String((r==null?void 0:r.wait_key)||"").trim(),allow_free_text:(r==null?void 0:r.allow_free_text)!==!1,prompt:String((r==null?void 0:r.prompt)||"").trim(),since_ms:l,duration_ms:uy(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:Tf(e),tag_label:_0(e),archived:(e==null?void 0:e.archived)===!0,automation_id:Tf(e)==="occurrence"?String((e==null?void 0:e.automation_id)||"").trim():""}}function fO(e,t,n=Date.now()){const r={pending:[],working:[],review:[],done:[]},o=t&&t.length?t:e,l=new Set;for(const c of o||[]){const u=String((c==null?void 0:c.run_id)||"").trim();!c||!u||l.has(u)||rv(c)||dO(c)&&(l.add(u),r.review.push(Mx(c,n)))}for(const c of e||[]){const u=String((c==null?void 0:c.run_id)||"").trim();if(!c||!u||l.has(u)||rv(c))continue;const f=Mx(c,n);r[f.column].push(f)}return r.review.sort((c,u)=>(c.since_ms??0)-(u.since_ms??0)),r.working.sort((c,u)=>(u.since_ms??0)-(c.since_ms??0)),r.pending.sort((c,u)=>(u.since_ms??0)-(c.since_ms??0)),r.done.sort((c,u)=>Number(u.failed)-Number(c.failed)||(u.since_ms??0)-(c.since_ms??0)),r}const Vg={"12h":12*36e5,"24h":24*36e5,"48h":48*36e5,"72h":72*36e5,"7d":7*864e5,"14d":14*864e5,"1m":30*864e5,all:null},qp={"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"},Rx="48h";function hO(e,t,n=Date.now()){const r=Vg[t]??null;if(r===null)return{visible:e,hidden_count:0};const o=n-r,l=[];let c=0;for(const u of e)u.since_ms===null||u.since_ms>=o?l.push(u):c+=1;return{visible:l,hidden_count:c}}function mO(e,t=Date.now()){const n=String(e||"").trim();if(!n)return null;const r=Date.parse(n);return Number.isFinite(r)?Math.max(0,t-r):null}const _O=6e4;function mf(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 pO(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 gO(e){const t=String(e||"");return t.length>14?`${t.slice(0,6)}…${t.slice(-6)}`:t}function Hp(e){const t=String(e||"").trim();return t.length>72?`${t.slice(0,70)}…`:t}function yO(e){const t=String(e||"");let n=t.includes(":")?t.slice(t.lastIndexOf(":")+1):t;if(t.includes(":")&&/^[0-9a-f]{6,}$/i.test(n.trim())){const r=t.slice(0,t.lastIndexOf(":"));/[a-z]/i.test(r)&&!/^[0-9a-f]+$/i.test(r.replace(/[@.\-_]/g,""))&&(n=r)}return n.length>34?`${n.slice(0,32)}…`:n}function Bm(e){return e.toLowerCase().replace(/[_-]+/g," ")}function wO(e){var h,m;const t=e!=null&&e.spec&&typeof e.spec=="object"?e.spec:null,n=t!=null&&t.phases&&typeof t.phases=="object"&&!Array.isArray(t.phases)?t.phases:null;if(!n)return null;const r=Object.keys(n).filter(g=>g&&typeof g=="string");if(!r.length)return null;const o=[];for(const g of r){o.push({needle:Bm(g),phase:g});const y=(h=n[g])==null?void 0:h.spoken_synonyms;if(Array.isArray(y))for(const w of y){const k=Bm(String(w||"").trim());k&&o.push({needle:k,phase:g})}}const c=(typeof t.initial_phase=="string"&&r.includes(t.initial_phase)?t.initial_phase:null)??(r.includes("sleep")?"sleep":null);if(!c)return null;const u=[],f=(m=t==null?void 0:t.state_mode_axis)==null?void 0:m.words;if(f&&typeof f=="object"&&!Array.isArray(f))for(const[g,y]of Object.entries(f)){const w=String((y==null?void 0:y.phase)||"").trim(),k=Bm(String(g||"").trim());k&&r.includes(w)&&u.push({needle:k,phase:w})}return{phases:r,synonyms:o,modes:u,initial:c,version:typeof t.version=="number"?t.version:null,sha256:String((e==null?void 0:e.sha256)||"").trim()}}const vO=["asleep","sleep","dream"],xO=["rest"],bO=["awake","idle"];function kO(e,t){const n=String(e||"").trim().toLowerCase();if(!n)return"unknown";if(t){const r=Bm(n),o=t.synonyms.filter(c=>r.includes(c.needle)).sort((c,u)=>u.needle.length-c.needle.length);if(o.length)return o[0].phase;const l=t.modes.filter(c=>r.includes(c.needle)).sort((c,u)=>u.needle.length-c.needle.length);return l.length?l[0].phase:n.includes("task")&&!n.includes("no_task")&&t.phases.includes("work")?"work":vO.some(c=>n.includes(c))?t.initial:xO.some(c=>n.includes(c))&&t.phases.includes("personal")?"personal":bO.some(c=>n.includes(c))?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 jO=new Set(["visit","work","personal","sleep","paused","resting","stopped","unknown"]),SO=new Set(["visit","work","personal","sleep","paused","resting","stopped","unknown"]);function NO(e){if(!e)return jO;const t=e.phases.filter(n=>SO.has(n));return new Set([...t,"paused","stopped","unknown"])}function CO(e){const[t,n]=Mf(`board_${e.col}`),r=`mc_column_body_${e.col}`;return s.jsxs("div",{className:`mc_column mc_column_${e.col}${t?"":" list_collapsed"}`,children:[s.jsxs("div",{className:"mc_column_head",children:[s.jsx(Rf,{open:t,on_toggle:n,controls:r,title:e.title,className:"mc_column_title"}),e.head]}),s.jsx("div",{className:"mc_column_body",id:r,hidden:!t,children:e.children})]})}function EO(e){var z,J,K,re,te,Q;const t=Date.now(),n=_.useMemo(()=>fO(e.runs,e.all_runs,Date.now()),[e.runs,e.all_runs]),[r,o]=_.useState(""),[l,c]=_.useState(""),[u,f]=_.useState(!1),[h,m]=_.useState(()=>{try{const D=localStorage.getItem("abstractobserver_done_window_v1");return D&&D in Vg?D:Rx}catch{return Rx}}),g=_.useMemo(()=>hO(n.done,h,t),[n.done,h]),y=mf(e.runs_refreshed_at,t),w=n.review.length,k=g.visible.filter(D=>D.failed).length,[b,S]=_.useState(""),[N,R]=_.useState(null),T=D=>`${D.run_id}:${D.wait_key}:${D.since_ms??""}`;_.useEffect(()=>{r&&(n.review.some(D=>T(D)===r)||o(""))},[n,r]);async function A(D,$){o(T(D)),c("");try{await e.on_resume_wait(D.run_id,D.wait_key,$)}catch(E){c(`${D.run_id}: ${String((E==null?void 0:E.message)||E||"resume failed")}`),o("")}}function W(D){const $=r===T(D),E=D.column==="review",L=E&&!D.wait_key;return s.jsxs("div",{className:`mc_card ${E?"mc_card_review":""} ${D.failed?"mc_card_failed":""}`,onClick:()=>e.on_open_run(D.run_id),role:"button",tabIndex:0,onKeyDown:M=>{M.key==="Enter"&&M.target===M.currentTarget&&e.on_open_run(D.run_id)},children:[s.jsxs("div",{className:"mc_card_head",children:[s.jsx("span",{className:"mc_card_title",title:D.workflow,children:yO(D.workflow)}),(()=>{const M=D.failed?"failed":Km({status:D.status,paused:D.paused});return s.jsx("span",{className:`mc_status ${xc(M)}`,children:M==="unknown"?"?":M})})()]}),s.jsxs("div",{className:"mc_card_meta",children:[s.jsx("span",{className:"mono",title:D.run_id,children:gO(D.run_id)}),D.is_subrun?s.jsx("span",{title:"This wait lives in a child run of an agent workflow",children:"subrun"}):null,D.tag?s.jsx("span",{className:"mc_pill","data-tag":D.tag,children:D.tag_label}):null,D.archived?s.jsx("span",{className:"mc_pill","data-tag":"archived",title:"This conversation is archived: hidden from chat lists, kept here and in the ledger",children:"Archived"}):null,D.automation_id?s.jsx("button",{type:"button",className:"btn btn_sm",title:"Open this occurrence's automation",onClick:M=>{M.stopPropagation(),e.on_open_automation(D.automation_id)},onKeyDown:M=>M.stopPropagation(),children:"Automation"}):null,D.duration_ms>=0?s.jsx("span",{children:pO(D.duration_ms)}):null,D.tokens_total!==null?s.jsxs("span",{children:[D.tokens_total.toLocaleString()," tk"]}):null,D.tool_calls!==null&&D.tool_calls>0?s.jsxs("span",{children:[D.tool_calls," tools"]}):null]}),D.is_scheduled&&D.schedule_interval?s.jsxs("div",{className:"mc_card_line",children:["every ",D.schedule_interval]}):null,D.failed&&D.error?s.jsx("div",{className:"mc_card_error",title:D.error,children:D.error.length>120?`${D.error.slice(0,118)}…`:D.error}):null,E?s.jsxs("div",{className:"mc_card_review_body",onClick:M=>M.stopPropagation(),onKeyDown:M=>M.stopPropagation(),children:[s.jsx("div",{className:"mc_card_reason",children:D.reason||"Needs a decision"}),D.prompt?s.jsx("div",{className:"mc_card_prompt",title:D.prompt,children:D.prompt.length>240?`${D.prompt.slice(0,238)}…`:D.prompt}):null,D.tool_names.length?s.jsxs("div",{className:"mc_card_tools",title:"Tool calls awaiting your approval",children:[D.tool_names.slice(0,4).map((M,ee)=>s.jsx("span",{className:"mc_tool_chip mono",children:M},`${M}_${ee}`)),D.tool_names.length>4?s.jsxs("span",{className:"mc_tool_chip",children:["+",D.tool_names.length-4," more"]}):null]}):null,D.since_ms!==null?s.jsxs("div",{className:"mc_card_waiting",children:["waiting ",mf(D.since_ms,t)]}):null,L?s.jsx("div",{className:"mc_card_line",title:"The wait has not registered a wait_key yet — open the run to inspect.",children:"wait key not published yet — open the run"}):null,L?s.jsx("div",{className:"mc_card_actions",children:s.jsx("button",{className:"btn",onClick:()=>e.on_open_run(D.run_id),children:"Open the run →"})}):D.wait_kind==="tool_approval"?s.jsxs("div",{className:"mc_card_actions",children:[s.jsx("button",{className:"btn success",disabled:$,onClick:()=>void A(D,{approved:!0}),children:$?"Resuming…":"Approve"}),s.jsx("button",{className:"btn danger",disabled:$,onClick:()=>void A(D,{approved:!1}),children:"Reject"})]}):s.jsx("div",{className:"mc_card_actions",children:s.jsx("button",{className:"btn primary",onClick:()=>e.on_open_run(D.run_id),children:"Review & answer →"})})]}):null]},D.run_id)}return s.jsxs("div",{className:"page page_scroll mc_page",children:[s.jsxs("div",{className:"mc_health",children:[s.jsx("span",{className:`mc_led ${e.gateway_connected?"ok":"bad"}`,title:e.gateway_connected?"Gateway connected":"Gateway unreachable"}),e.gateway_connected?null:s.jsx("span",{className:"mc_health_text",children:"gateway unreachable"}),e.runs_refreshed_at===null?s.jsx("span",{className:"mc_health_text muted mc_loading",children:"loading runs…"}):s.jsxs("div",{className:"mc_stats",children:[s.jsxs("div",{className:`mc_stat ${w?"is_hot":""}`,title:"runs blocked on a human decision (Review column)",children:[s.jsx("span",{className:"mc_stat_value",children:w}),s.jsx("span",{className:"mc_stat_label",children:"need you"})]}),s.jsxs("div",{className:`mc_stat ${k?"is_bad":""}`,title:"failed runs in the Done column",children:[s.jsx("span",{className:"mc_stat_value",children:k}),s.jsx("span",{className:"mc_stat_label",children:"failed"})]}),s.jsxs("div",{className:"mc_stat",title:"runs executing or parked listening",children:[s.jsx("span",{className:"mc_stat_value",children:n.working.length}),s.jsx("span",{className:"mc_stat_label",children:"working"})]})]}),s.jsx("span",{className:"mc_spacer"}),s.jsxs("div",{className:"mc_health_side",children:[y?s.jsxs("span",{className:"mc_health_text muted",title:"age of the last runs poll — the board is only as live as this",children:["data ",y," old"]}):null,s.jsx("button",{className:"btn",onClick:e.on_refresh,disabled:e.refreshing,children:e.refreshing?"Refreshing…":"Refresh"})]})]}),l?s.jsx("div",{className:"mc_error",children:l}):null,e.entities.length||e.entities_error?s.jsxs("div",{className:"mc_entities",children:[s.jsxs("div",{className:"mc_entities_head",children:[s.jsxs("span",{children:["Entities",e.entities_total>e.entities.length?` (${e.entities.length} of ${e.entities_total} — open the entity app for all)`:""]}),s.jsx("a",{className:"mc_entity_link",href:e.entity_app_href,target:"_blank",rel:"noreferrer",children:"open the entity app →"})]}),e.entities_error?s.jsx("div",{className:"muted",children:e.entities_error}):null,s.jsx("div",{className:"mc_entities_row",children:e.entities.map(D=>s.jsxs("div",{className:"mc_entity_cell",children:[s.jsxs("a",{className:"mc_entity",href:`${e.entity_app_href}${e.entity_app_href.includes("?")?"&":"?"}entity=${encodeURIComponent(D.name)}&live=1`,target:"_blank",rel:"noreferrer",title:[D.error,D.age_days!==null?`${D.age_days.toFixed(0)} days old`:"",D.last_moment].filter(Boolean).join(" — ")||D.name,children:[s.jsx("span",{className:"mc_entity_name",children:D.name}),(()=>{var U;const $=String(D.live_phase||D.state||"").trim(),E=kO($,e.phase_graph),L=NO(e.phase_graph).has(E)?E:"other",M=((U=e.phase_graph)==null?void 0:U.initial)??"sleep",ee=/awake|idle/i.test($)&&E===M,F=$&&$.toLowerCase()!==E?` — wire word: ${$}${ee?" (settling)":""}`:"";return s.jsx("span",{className:`mc_entity_phase mc_phase_${L}`,title:(D.live_phase?"phase (cognition wire)":"phase from card state — cognition wire unavailable")+F,children:E})})(),D.last_moment?s.jsx("span",{className:"mc_entity_moment",title:D.last_moment,children:D.last_moment.replace(/_/g," ")}):null,(()=>{if(D.working===!0)return s.jsx("span",{className:"mc_entity_live",title:"busy now (loop mid-day or live visit — store-read, never fabricated)",children:"● busy"});const $=mO(D.last_moment_at,t);return D.working===!1?s.jsxs("span",{className:"mc_entity_live muted",title:"idle (cognition wire)",children:["idle",$!==null?` · ${mf(t-$,t)} ago`:""]}):$===null?null:$<=_O?s.jsx("span",{className:"mc_entity_live",title:`last moment ${mf(t-$,t)} ago`,children:"● active"}):s.jsxs("span",{className:"mc_entity_live muted",title:"time since the last recorded moment",children:[mf(t-$,t)," ago"]})})(),D.tokens_total!==null?s.jsxs("span",{className:"muted mc_entity_spend",title:`lifetime billed tokens (home run ledger)${D.live_visit_tokens!==null?`; open visit: ${Wp(D.live_visit_tokens)} tk`:""}${D.spend_warning?`; ${D.spend_warning}`:""}`,children:[Wp(D.tokens_total)," tk",D.live_visit_tokens!==null?` (+${Wp(D.live_visit_tokens)})`:"",D.spend_warning?"*":""]}):null]}),D.open_questions_total||D.open_problems_total||D.lessons_total||D.dreams_brief?s.jsx("button",{type:"button",className:"mc_entity_hints_btn","aria-expanded":b===D.name,title:"open questions / problems + distilled lessons + night signals from the entity card — click to expand",onClick:()=>S(b===D.name?"":D.name),children:[D.open_questions_total?`${D.open_questions_total} question${D.open_questions_total>1?"s":""}`:"",D.open_problems_total?`${D.open_problems_total} problem${D.open_problems_total>1?"s":""}`:"",D.lessons_total?`${D.lessons_total} lesson${D.lessons_total>1?"s":""}`:"",D.dreams_brief?`night: ${D.dreams_brief.count} signal${D.dreams_brief.count>1?"s":""}`:""].filter(Boolean).join(" · ")}):null]},D.name))}),(()=>{if(!b)return null;const D=e.entities.find(L=>L.name===b);if(!D||!D.open_questions.length&&!D.open_problems.length&&!D.lessons.length&&!D.dreams_brief)return null;const $=e.on_read_diary?async L=>{const M=await e.on_read_diary(D.name,L);R({entity:D.name,entry:(M==null?void 0:M.entry)??M,seq:typeof(M==null?void 0:M.read_recorded_at_seq)=="number"?M.read_recorded_at_seq:null})}:void 0,E=D.open_questions_total-D.open_questions.length+(D.open_problems_total-D.open_problems.length)+(D.lessons_total-D.lessons.length);return s.jsxs("div",{className:"mc_entity_hints_panel",children:[D.open_questions.map((L,M)=>s.jsx(ip,{kind:"question",label:L.title||Hp(L.statement),entryId:L.entry_id,onOpen:$,title:L.statement||L.title},`q_${L.record_id||M}`)),D.open_problems.map((L,M)=>s.jsx(ip,{kind:"problem",label:L.title||Hp(L.statement),entryId:L.entry_id,onOpen:$,title:L.statement||L.title},`p_${L.record_id||M}`)),D.lessons.map((L,M)=>s.jsx(ip,{kind:"lesson",label:L.title||Hp(L.statement),entryId:L.entry_id,onOpen:$,title:L.statement||L.title},`l_${L.record_id||M}`)),D.dreams_brief?s.jsxs("span",{className:"mc_entity_dreams muted",title:"night signals carried by STANDING dreams (the sleep pass's maintenance stream; count = signals, not dreams); felt tones color the content, they never rank it — the entity app renders the full stream",children:["night signals: ",D.dreams_brief.count,D.dreams_brief.dreams?` across ${D.dreams_brief.dreams} dream${D.dreams_brief.dreams>1?"s":""}`:"",D.dreams_brief.kinds.length?` — ${D.dreams_brief.kinds.slice(0,6).join(", ")}${D.dreams_brief.kinds.length>6?` +${D.dreams_brief.kinds.length-6} more`:""}`:"",D.dreams_brief.felt_tones.length?` · felt: ${D.dreams_brief.felt_tones.slice(0,6).join(", ")}`:""]}):null,E>0?s.jsxs("span",{className:"muted mc_entity_hints_more",children:["+",E," more — open the entity app"]}):null]})})()]}):null,N?s.jsx(cc,{open:!0,title:`${N.entity} — diary entry`,onClose:()=>R(null),children:s.jsxs("div",{className:"mc_diary_entry",children:[s.jsx("div",{className:"mc_diary_meta muted",children:[(z=N.entry)!=null&&z.kind?`kind: ${N.entry.kind}`:"",(J=N.entry)!=null&&J.visibility?`visibility: ${N.entry.visibility}`:"",(K=N.entry)!=null&&K.written_at?`written: ${N.entry.written_at}`:"",(re=N.entry)!=null&&re.entry_id?`id: ${N.entry.entry_id}`:""].filter(Boolean).join(" · ")}),s.jsxs("div",{className:"mc_diary_recorded muted",children:["this read was recorded in ",N.entity,"’s stream",N.seq!==null?` (seq ${N.seq})`:""]}),(te=N.entry)!=null&&te.gist?s.jsx("div",{className:"mc_diary_gist",children:String(N.entry.gist)}):null,s.jsx("pre",{className:"mc_diary_text",children:String(((Q=N.entry)==null?void 0:Q.text)||"(entry carries no text)")})]})}):null,s.jsx("div",{className:"mc_board",children:Object.keys(Tx).map(D=>{const $=D==="done"?g.visible:n[D],E=D==="done"&&!u?$.slice(0,8):$;return s.jsxs(CO,{col:D,title:Tx[D],head:s.jsxs(s.Fragment,{children:[D==="done"?s.jsx("select",{className:"mc_window_select",value:h,title:"Show terminal runs from this time window",onClick:L=>L.stopPropagation(),onChange:L=>{const M=L.target.value;m(M),f(!1);try{localStorage.setItem("abstractobserver_done_window_v1",M)}catch{}},children:Object.keys(Vg).map(L=>s.jsx("option",{value:L,children:qp[L]},L))}):null,s.jsx("span",{className:"mc_column_count",title:D==="done"&&g.hidden_count?`${g.hidden_count} older run(s) outside this window`:void 0,children:$.length})]}),children:[s.jsx("div",{className:"mc_column_hint muted",children:cO[D]}),s.jsxs("div",{className:"mc_column_cards",children:[E.map(L=>W(L)),$.length?null:s.jsx("div",{className:"mc_empty muted",children:e.runs_refreshed_at===null?"loading…":D==="done"&&g.hidden_count?`none in the ${qp[h]} — ${g.hidden_count} older`:lO[D]}),D==="done"&&$.length>8&&!u?s.jsxs("button",{className:"btn mc_more",onClick:()=>f(!0),children:["show all ",$.length]}):null,D==="done"&&g.hidden_count&&$.length?s.jsxs("div",{className:"mc_window_note muted",title:"Widen the window above to see older terminal runs",children:["+",g.hidden_count," older outside ",qp[h]]}):null]})]},D)})})]})}const Mm=500,c_="http://127.0.0.1:8080";function Lx(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 _f(e){const t=String(e||"").trim();return t.startsWith("abstractcode.")?`abstract.${t.slice(13)}`:t}function Vp(e){const t=e&&typeof e=="object"?e:{},n=typeof(t==null?void 0:t.count)=="number"&&Number.isFinite(t.count)?Number(t.count):null,r=typeof(t==null?void 0:t.node_id)=="string"&&t.node_id.trim()?` before ${t.node_id.trim()}`:"";return`${n===null?"steering":`${n} steer message${n===1?"":"s"}`} folded into the run${r} — the loop sees it at this boundary`}function Gp(e){const t=String(e||"").trim();return t.startsWith("abstract.")||t.startsWith("abstractcode.")}function $O(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 AO(e){if(!e||typeof e!="object")return[];const t=Array.isArray(e.nodes)?e.nodes:[];if(!t.length)return[];let n=null;for(const u of t){if(!u||typeof u!="object")continue;const f=u.data&&typeof u.data=="object"?u.data:{};if(String(f.nodeType||u.type||"").trim()==="on_flow_start"){n=u;break}}if(!n)return[];const r=n.data&&typeof n.data=="object"?n.data:{},o=Array.isArray(r.outputs)?r.outputs:[],l=r.pinDefaults&&typeof r.pinDefaults=="object"?r.pinDefaults:{},c=[];for(const u of o){if(!u||typeof u!="object")continue;const f=String(u.id||"").trim();if(!f)continue;const h=String(u.type||"").trim();if(h==="execution"||f==="exec-out"||f==="exec")continue;const m=String(u.label||f).trim()||f,g={id:f,label:m,type:h||"unknown"};l&&Object.prototype.hasOwnProperty.call(l,f)&&(g.default=l[f]),c.push(g)}return c}function Kp(e,t){const n=String((e==null?void 0:e.message)||e||"Discovery failed");if(/\b401\b/.test(n)){const r=String(t.gateway_user||"").trim();return r?`Gateway authentication failed for user '${r}'. Sign in again through the connection dialog. (${n})`:`Gateway authentication failed. Sign in through the connection dialog (or check the dev bearer token under Settings → Advanced). (${n})`}return n}function TO(){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)||c_),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:c_,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 MO(e){localStorage.setItem("abstractobserver_settings",JSON.stringify({...e,auth_token:""}))}function RO(e){if(!e||typeof e!="object"||Array.isArray(e))return[];const t=[],n=(o,l)=>{const c=String(l??"").trim();c&&(t.some(u=>u.label===o&&u.value===c)||t.push({label:o,value:c}))},r=String(e.display??"").trim().replace(/^\[/,"").replace(/\]$/,"");return n("time",r||e.local_datetime),n("tz",e.timezone),n("country",e.country),n("user",e.user),t}function Ix(e){const t=RO(e.metadata);return t.length?s.jsx("div",{className:"runtime_metadata_chips","aria-label":"Runtime metadata",children:t.map(n=>s.jsxs("span",{className:"chip mono muted",children:[n.label,": ",n.value]},`${n.label}:${n.value}`))}):null}function LO(){return typeof window>"u"?"":YE(window.location)}function IO(){try{const e="abstractobserver_session_id_v1",t=window.sessionStorage.getItem(e);if(t&&t.trim())return t.trim();const n=`obs_${Rs()}`;return window.sessionStorage.setItem(e,n),n}catch{return""}}function OO(){var aa,Xn,tl,jo,Xl,_u,nl,Ws,pu,la,wi,Zl,gu,Wi,Ql;const[e,t]=_.useState("board"),[n,r]=_.useState(()=>TO()),o=typeof window<"u"&&((aa=window.__ABSTRACT_UI_CONFIG__)==null?void 0:aa.monitor_gpu)===!0,l=typeof window<"u"&&(((Xn=window.__ABSTRACT_UI_CONFIG__)==null?void 0:Xn.entity_app_url)||"").trim().replace(/\/+$/,"")||"http://127.0.0.1:3007",c=_.useRef(null),[u,f]=_.useState(""),[h,m]=_.useState(""),[g,y]=_.useState(()=>LO()),[w,k]=_.useState(""),[b,S]=_.useState(""),[N,R]=_.useState(""),[T,A]=_.useState("{}"),[W]=_.useState(()=>IO()),[z,J]=_.useState(null),[K,re]=_.useState(!1),[te,Q]=_.useState(""),[D,$]=_.useState(!1),[E,L]=_.useState(""),[M,ee]=_.useState(!1),F=ES({appName:"AbstractObserver",variant:"dismissable",defaultGatewayUrl:typeof window<"u"&&((tl=window.__ABSTRACT_UI_CONFIG__)==null?void 0:tl.gateway_url)||c_,onStatusChange:v=>Nd(v)}),[U,V]=_.useState(null),[O,H]=_.useState(null),[Y,ae]=_.useState(!1),[ie,_e]=_.useState(null),[fe,ge]=_.useState("once"),[Ne,Ue]=_.useState(""),[We,ut]=_.useState(gg),[Fe,et]=_.useState([]),[$e,Ve]=_.useState(null),[le,be]=_.useState(!1),[Pe,me]=_.useState([]),Ce=_.useRef(new H$(Rs)),[Te,Je]=_.useState({available:!1,reason:"Sign in to a gateway to use automations."}),[rt,ht]=JS("abstractobserver",{legacyKey:"abstractobserver_settings"}),[lt,Ct]=_.useState(!1),[Xt,Pn]=_.useState(!1),[zt,wn]=_.useState([]),[Un,Mn]=_.useState([]),[vn,Dn]=_.useState([]),[bn,js]=_.useState(!1),[Kn,Ss]=_.useState(null),[Ar,Fn]=_.useState([]),[de,Se]=_.useState(0),[tt,Qe]=_.useState(""),ct=_.useRef(!1),mt=_.useRef(0),It=_.useRef(0),[Et,Zt]=_.useState(!1),[St,Qt]=_.useState([]),[Ht,Bt]=_.useState([]),[Pt,Dt]=_.useState({}),[qe,ln]=_.useState(!1),[pt,rn]=_.useState(!1),[gt,Wn]=_.useState(!1),[cn,Gs]=_.useState([]),[ns,Vr]=_.useState([]),hr=_.useRef(0),ii=_.useRef(null);ii.current||(ii.current=new Nv(v=>window.setTimeout(v,40),v=>Gs(C=>C.concat(v))));const oi=_.useRef(null);oi.current||(oi.current=new Nv(v=>window.setTimeout(v,40),v=>Vr(C=>C.concat(v))));const Ps=_.useRef({scanned:0,found:null}),[he,mr]=_.useState(null),[Xi,_r]=_.useState(""),[Tr,Gr]=_.useState(!1),dt=_.useRef(null),[hn,Ds]=_.useState({}),[Kr,ss]=_.useState({}),[To,Mo]=_.useState(!1),[Ro,zn]=_.useState(""),[pr,Hn]=_.useState(!0),[Zi,ai]=_.useState(""),[Rn,Fs]=_.useState(!1),[ds,Ks]=_.useState(!1),[fs,xa]=_.useState(6),[Qi,un]=_.useState("standard"),[ba,Sc]=_.useState(""),[Lo,hs]=_.useState(""),[Mr,Rr]=_.useState(!1),[eo,gr]=_.useState(!1),[Ns,yr]=_.useState("pause"),[Lr,Ys]=_.useState(""),[Ci,rs]=_.useState(""),[Ir,ka]=_.useState(""),wr=_.useRef(null),to=_.useRef(null),[Nc,Ei]=_.useState(!1),Js=_.useRef(null),[Yu,Xs]=_.useState(""),[no,Zs]=_.useState(""),[Io,li]=_.useState(""),[ja,ci]=_.useState(""),[q,ce]=_.useState(!1),[je,Ae]=_.useState("idle"),[Ee,Ge]=_.useState([]),[yt,_t]=_.useState(null),xt=_.useRef(null),[Ut,Kt]=_.useState(!1),[ms,Ft]=_.useState(""),[dn,En]=_.useState(""),[xn,Qn]=_.useState(""),[Qs,Yr]=_.useState([]),[$i,Sa]=_.useState(!1),[rh,Cc]=_.useState(""),[yl,Ec]=_.useState(""),[$c,Ac]=_.useState(!1),[ih,Oo]=_.useState(""),Ju=_.useMemo(()=>{if(!Ee.length)return"";try{return JSON.stringify(Ee.map(v=>({role:v.role,content:v.content,ts:v.ts})))}catch{return"1"}},[Ee]),Xu=_.useMemo(()=>Ee.length?xn?Ju!==xn:!0:!1,[Ju,Ee.length,xn]),Zu=_.useMemo(()=>Qs.map(v=>{const C=String(v.title||"").trim()||`Chat ${String(v.thread_id||"").slice(0,8)}`,I=String(v.created_at||"").trim(),B=I?I.replace("T"," ").slice(0,19):"",Z=String(v.run_id||"").trim()?String(v.run_id).slice(0,8):"",X=[C,B&&`(${B})`,Z&&`run ${Z}`].filter(Boolean).join(" • ");return{value:String(v.thread_id||""),label:X}}),[Qs]);_.useEffect(()=>{o&&NT()},[o]),_.useEffect(()=>{if(!o)return;const v=c.current;v&&(v.token=n.gateway_auth_mode==="direct"&&n.auth_token||"")},[o,n.auth_token,n.gateway_auth_mode]);const[C_,Qu]=_.useState([]),[wl,on]=_.useState(""),[ed,E_]=_.useState(""),[Tc,$_]=_.useState("all"),[td,A_]=_.useState("status"),[er,so]=_.useState("ledger"),oh=iw(tp.md),T_=iw(`${tp.sm}, ${tp.short}`),ro=BE({is_drawer:oh,page:e}),Po=ro.open,vl=ro.set_open,[nd,ah]=Mf("observe_runs"),lh=ro.toggle_ref,ch=ro.sidebar_ref,sd=_.useRef(null),[Na,uh]=_.useState(()=>Jw(typeof window<"u"?window.location.hash:"")),[M_,dh]=_.useState(""),[rd,Mc]=_.useState(""),[ui,Ai]=_.useState(""),[Ca,io]=_.useState(null),[Rc,Lc]=_.useState({}),[Ic,Do]=_.useState(!1),[id,Ea]=_.useState(""),[$a,R_]=_.useState(!1),[od,L_]=_.useState(!1),[I_,Oc]=_.useState(()=>Date.now()),[es,di]=_.useState(""),[fh,xl]=_.useState({}),[hh,Pc]=_.useState({}),Fo=_.useRef([]),Or=_.useRef(null),oo=_.useRef(""),Ti=_.useRef({}),ao=_.useRef({}),zo=_.useRef({}),Bo=_.useRef(new Set),[Mi,Uo]=_.useState([]),fi=_.useRef(""),lo=_.useRef({}),Ri=_.useRef(null),_s=_.useRef(null),co=_.useRef(0),Wo=_.useRef({}),bl=_.useRef(!1),uo=_.useRef(new Set),[Dc,kl]=_.useState(""),[ps,hi]=_.useState(""),Pr=_.useRef(""),mh=()=>({artifact_id:"",kind:"binary",render_kind:"",text:"",url:"",loading:!1,error:""}),[jl,Aa]=_.useState("activity"),[ad,ld]=_.useState([]),[cd,Sn]=_.useState(0),[ud,Sl]=_.useState(0),[Nl,dd]=_.useState({}),[fd,Ta]=_.useState({}),[Fc,qo]=_.useState(!1),[_h,ph]=_.useState(""),[Cl,gh]=_.useState(""),[fo,Ma]=_.useState("all"),[Ra,zc]=_.useState(""),[ho,hd]=_.useState([]),[Bc,yh]=_.useState("all"),[La,O_]=_.useState("type"),[Ia,mo]=_.useState("newest"),[Li,Ho]=_.useState(""),[tr,Ii]=_.useState(""),[mi,El]=_.useState(""),[$l,md]=_.useState(0),[Dr,Vo]=_.useState(()=>mh()),[Oa,Pa]=_.useState(!1),[Al,Da]=_.useState(""),[_o,_n]=_.useState(""),[Wt,Jr]=_.useState(""),[is,nr]=_.useState("text"),[Go,po]=_.useState(null),[sr,Ko]=_.useState(!1),[_d,Tl]=_.useState(""),[Ml,pd]=_.useState(""),[Oi,Rl]=_.useState(""),[Uc,gd]=_.useState(!1),[P_,Pi]=_.useState(""),[Di,Fa]=_.useState("run_ledger"),[Wc,qc]=_.useState(""),[Fr,rr]=_.useState([]),[Yo,Xr]=_.useState(""),[Fi,go]=_.useState(!1),[wh,Ll]=_.useState(""),De=_.useMemo(()=>new kp({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]),fn=_.useMemo(()=>new oA(De.automations_client(),sA(De,Rs,Rt)),[De]),zs=_.useSyncExternalStore(v=>fn.subscribe(v),()=>fn.state),$n=F$(n.gateway_url),vr=$n?()=>{window.open($n,"_blank","noopener,noreferrer")}:void 0;_.useEffect(()=>{e==="launch"&&fe==="automate"&&M&&fn.load_email_status()},[e,fe,M,fn]),_.useEffect(()=>{const v=()=>{const C=B$(window.location.hash);if(C){if(C.page==="run"){y(C.run_id),uh(Jw(window.location.hash));return}C.page==="launch"&&ge(C.mode),t(C.page)}};return v(),window.addEventListener("hashchange",v),()=>window.removeEventListener("hashchange",v)},[]);const vh=_.useMemo(()=>{const v={};for(const C of zs.items)v[C.automation_id]=C.title;return v},[zs.items]),xh=_.useMemo(()=>_T(),[]),[yd,Hc]=_.useState(uv),wd=_.useRef(0);function Vc(){const v=++wd.current;Hc(uv),pT(De).then(C=>{v===wd.current&&Hc(C)})}const Il=_.useMemo(()=>n.worker_url.trim()?new jM({url:n.worker_url.trim(),auth_token:n.worker_token}):null,[n.worker_url,n.worker_token]),Jo=_.useMemo(()=>xM(De.fetch_gateway,jg),[De]),gs=cn.length?cn[cn.length-1].record:null,Vt=_.useMemo(()=>fa(gs),[gs]),Yn=_.useMemo(()=>{const v=N.trim();if(!z||!v||String(z.bundle_id||"").trim()&&String(z.bundle_id||"").trim()!==v)return null;const C=Array.isArray(z.entrypoints)?z.entrypoints:[];if(!C.length)return null;const I=b.trim();if(I)return C.find(Z=>String(Z.flow_id||"").trim()===I)||null;if(C.length===1)return C[0];const B=String(z.default_entrypoint||"").trim();return B&&C.find(Z=>String(Z.flow_id||"").trim()===B)||null},[z,N,b]),za=_.useMemo(()=>{const v=Yn==null?void 0:Yn.inputs;return Array.isArray(v)?v:[]},[Yn]),vd=_.useMemo(()=>AO(Ca),[Ca]),Ba=_.useMemo(()=>za.length?za:vd,[za,vd]),Zr=_.useMemo(()=>{const v=typeof(he==null?void 0:he.workflow_id)=="string"?String(he.workflow_id):"",C=Lx(v);if(C&&z&&String(z.bundle_id||"").trim()===C.bundle_id){const Z=(Array.isArray(z.entrypoints)?z.entrypoints:[]).find(X=>String((X==null?void 0:X.flow_id)||"").trim()===C.flow_id);if(Z&&Z.node_index&&typeof Z.node_index=="object")return Z.node_index}const I=Yn==null?void 0:Yn.node_index;return I&&typeof I=="object"?I:{}},[he,z,Yn]);_.useEffect(()=>{MO(n)},[n]),_.useEffect(()=>()=>{Ri.current&&Ri.current.abort(),_s.current&&_s.current.abort(),wr.current&&window.clearTimeout(wr.current),to.current&&window.clearTimeout(to.current),Or.current&&window.clearTimeout(Or.current),Js.current&&window.clearTimeout(Js.current)},[]);const Ot=_.useMemo(()=>{const v=T.trim();if(!v)return{};try{const C=JSON.parse(v);return typeof C!="object"||C===null||Array.isArray(C)?null:C}catch{return null}},[T]),Gc=typeof(Ot==null?void 0:Ot.prompt)=="string"?String(Ot.prompt):"",Ua=typeof(Ot==null?void 0:Ot.provider)=="string"?String(Ot.provider):"",Wa=typeof(Ot==null?void 0:Ot.model)=="string"?String(Ot.model):"",xd=typeof(Ot==null?void 0:Ot.workspace_root)=="string"?String(Ot.workspace_root):"",bd=_.useMemo(()=>{const v=Ot==null?void 0:Ot.workspace;return v&&typeof v=="object"&&!Array.isArray(v)?v:null},[Ot]),kd=Ba.length>0&&!!N.trim(),Ol=v=>{const C=String(v||"").trim().toLowerCase();return C==="object"||C==="memory"||C==="assertion"||C==="assertions"||C==="any"};_.useEffect(()=>{ss({})},[N,b]),_.useEffect(()=>{Ot!==null&&Ds(v=>{const C={};for(const I of Ba){if(!I||typeof I!="object")continue;const B=String(I.id||"").trim();if(!B)continue;const Z=String(I.type||"").trim();if(!Ol(Z))continue;if(String(Kr[B]||"").trim()){C[B]=typeof v[B]=="string"?v[B]:"";continue}const G=Ot==null?void 0:Ot[B];G===void 0?C[B]="":C[B]=v$(G)}return C})},[Ba,Ot,Kr]);const ir=Ne?{kind:"default",interface:Ne}:N.trim()&&b.trim()?{kind:"bundle",bundle_id:N.trim(),flow_id:b.trim()}:null,xr=I$(ir),br=Array.isArray(Ot==null?void 0:Ot.skills)?Ot.skills.map(v=>String(v||"").trim()).filter(Boolean):[],kr=_.useMemo(()=>{const v={};for(const C of zt){const I=String(C.workflow_id||"").trim(),B=String(C.label||"").trim();I&&B&&(v[I]=B)}return v},[zt]),Pl=bb({interfaceId:null,defaultInterface:pc,request:(v,C)=>De.get_gateway_json(v,C.signal),enabled:M,reloadKey:zt}),zi=_.useMemo(()=>{const v=new Set;for(const C of Array.isArray(Ht)?Ht:[]){const I=String((C==null?void 0:C.name)||"").trim();I&&v.add(I)}return Array.from(v).sort()},[Ht]),yo=_.useMemo(()=>{const v=[];for(const C of Array.isArray(Ht)?Ht:[]){const I=String((C==null?void 0:C.name)||"").trim();if(!I)continue;const B=String((C==null?void 0:C.display_name)||"").trim();v.push({name:I,display_name:B||void 0})}return v},[Ht]),Dl=_.useMemo(()=>{const v=new Set;for(const C of St||[]){if(!C||typeof C!="object")continue;const I=String(C.name||"").trim();I&&v.add(I)}return Array.from(v).sort()},[St]),jd=_.useMemo(()=>{const v=n.maintenance_ai_provider.trim();if(!v)return{models:[],error:""};const C=Pt[v];return C?{models:(Array.isArray(C.models)?C.models:[]).map(B=>String(B||"").trim()).filter(Boolean),error:String(C.error||"")}:{models:[],error:""}},[Pt,n.maintenance_ai_provider]),Qr=n.maintenance_ai_provider.trim(),wo=!!(Qr&&M&&!Object.prototype.hasOwnProperty.call(Pt,Qr));_.useEffect(()=>{const v=Ua.trim();if(!v||Pt[v]||lo.current[v])return;lo.current[v]=!0;let C=!1;return(async()=>{try{const B=await De.discovery_provider_models(v);if(C)return;const Z=Array.isArray(B==null?void 0:B.models)?B.models:[],X=typeof(B==null?void 0:B.error)=="string"?String(B.error):"";Dt(G=>({...G,[v]:{models:Z,error:X||void 0}}))}catch(B){if(C)return;Dt(Z=>({...Z,[v]:{models:[],error:String((B==null?void 0:B.message)||B||"Failed to load models")}}))}finally{delete lo.current[v]}})(),()=>{C=!0}},[Ua,Pt,De]),_.useEffect(()=>{const v=n.maintenance_ai_provider.trim();if(!v||!M||Pt[v]||lo.current[v])return;lo.current[v]=!0;let C=!1;return(async()=>{try{const B=await De.discovery_provider_models(v);if(C)return;const Z=Array.isArray(B==null?void 0:B.models)?B.models:[],X=typeof(B==null?void 0:B.error)=="string"?String(B.error):"";Dt(G=>({...G,[v]:{models:Z,error:X||void 0}}))}catch(B){if(C)return;Dt(Z=>({...Z,[v]:{models:[],error:String((B==null?void 0:B.message)||B||"Failed to load models")}}))}finally{delete lo.current[v]}})(),()=>{C=!0}},[n.maintenance_ai_provider,Pt,De,M]);function Ln(v,C){const I=String(v||"").trim();if(!I)return;let B={};try{const Z=JSON.parse(T||"{}");typeof Z=="object"&&Z!==null&&!Array.isArray(Z)&&(B=Z)}catch{B={}}if(C==null){delete B[I],A(JSON.stringify(B,null,2));return}if(typeof C=="string")C?B[I]=C:delete B[I];else if(Array.isArray(C)){const Z=C.map(X=>X).filter(X=>X!=null);Z.length?B[I]=Z:delete B[I]}else B[I]=C;A(JSON.stringify(B,null,2))}async function Sd(v){const C=String(v||"").trim();if(!C)return Q("Missing bundle_id"),null;Q(""),re(!0);try{const I=await De.get_bundle(C);return J(I),en({ts:Rt(),kind:"info",title:`Loaded bundle ${C}`}),I}catch(I){return J(null),Q(String((I==null?void 0:I.message)||I||"Failed to load bundle")),null}finally{re(!1)}}function qa(v){const C=[],I=Array.isArray(v==null?void 0:v.items)?v.items:[];for(const B of I){const Z=String((B==null?void 0:B.bundle_id)||"").trim();if(!Z)continue;const X=Array.isArray(B==null?void 0:B.entrypoints)?B.entrypoints:[];if(X.length)for(const G of X){const se=String((G==null?void 0:G.flow_id)||"").trim();if(!se||(G==null?void 0:G.deprecated)===!0)continue;const Ie=`${Z}:${se}`,ye=String((G==null?void 0:G.name)||"").trim(),ke=ye?`${Z} · ${ye}`:`${Z} · ${se}`,Me=String((G==null?void 0:G.description)||"").trim(),Xe=(Array.isArray(G==null?void 0:G.interfaces)?G.interfaces:[]).some(Ze=>String(Ze||"").trim().length>0),Ye=Array.isArray(G==null?void 0:G.agent_default_interfaces)?G.agent_default_interfaces.map(Ze=>String(Ze||"").trim()).filter(Boolean):[];C.push({workflow_id:Ie,bundle_id:Z,bundle_ref:String((B==null?void 0:B.bundle_ref)||"").trim(),flow_id:se,label:ke,description:Me||void 0,has_interface:Xe,agent_default_interfaces:Ye})}}return C.sort((B,Z)=>B.label.localeCompare(Z.label)),C}async function Bs(v=De,C){if(ct.current&&!(C!=null&&C.force))return;ct.current=!0;const I=Bi.current;js(!0);try{const B=ke=>ke.map(G$).filter(Me=>!!Me.run_id),[Z,X,G]=await Promise.all([v.list_runs({limit:200,root_only:!0,include_metrics:!0}),v.list_runs({limit:500,root_only:!1,include_metrics:!0}),v.list_runs({limit:200,root_only:!0,archived_only:!0,include_metrics:!0})]);if(I!==Bi.current)return;const se=K$(Array.isArray(Z==null?void 0:Z.items)?Z.items:[],Array.isArray(G==null?void 0:G.items)?G.items:[]),Ie=Array.isArray(X==null?void 0:X.items)?X.items:[],ye=B(se).filter(ke=>!String(ke.parent_run_id||"").trim()||ke.role==="occurrence");Mn(ye),Dn(B(Ie).filter(ke=>!!ke.run_id)),Ss(Date.now()),It.current=0,mt.current=0}catch(B){const Z=String((B==null?void 0:B.message)||B||"");if(en({ts:Rt(),kind:"error",title:"Refresh runs failed",preview:At(Z)}),(/\b40[13]\b/.test(Z)||/unauthorized|forbidden/i.test(Z))&&F.refresh().catch(()=>{}),/\b429\b/.test(Z)||/too many requests/i.test(Z)){const X=Math.min(12e4,Math.max(15e3,It.current*2||15e3));It.current=X,mt.current=Date.now()+X,en({ts:Rt(),kind:"info",title:`Gateway rate-limited — pausing polls ${Math.round(X/1e3)}s`})}}finally{ct.current=!1,js(!1)}}async function Ha(v){var se,Ie,ye;const C=Bi.current;ee(!0),Dt({});const[I,,B,Z,X]=await Promise.allSettled([v.list_bundles(),Bs(v),v.discovery_tools(),v.discovery_providers({include_models:!1}),v.discovery_capabilities()]);if(C!==Bi.current)return;if(I.status==="rejected"&&B.status==="rejected"&&Z.status==="rejected"){ee(!1),L(Kp(I.reason,n)),en({ts:Rt(),kind:"error",title:"Discovery failed",preview:At(String(I.reason||""))});return}Je(X.status==="fulfilled"?Y$(X.value):{available:!1,reason:`Could not read the gateway capabilities: ${String(((se=X.reason)==null?void 0:se.message)||X.reason)}`});let G=0;if(I.status==="fulfilled"){const ke=qa(I.value);G=ke.length,wn(ke)}else wn([]),en({ts:Rt(),kind:"error",title:"Discovery bundles failed",preview:At(String(I.reason||""))});if(B.status==="fulfilled"){const ke=Array.isArray((Ie=B.value)==null?void 0:Ie.items)?B.value.items:[];Qt(ke)}else Qt([]),en({ts:Rt(),kind:"error",title:"Discovery tools failed",preview:At(String(B.reason||""))});if(Z.status==="fulfilled"){const ke=Array.isArray((ye=Z.value)==null?void 0:ye.items)?Z.value.items:[];Bt(ke)}else Bt([]),en({ts:Rt(),kind:"error",title:"Discovery providers failed",preview:At(String(Z.reason||""))});en({ts:Rt(),kind:"info",title:"Gateway discovery loaded",preview:At(`workflows: ${G}`)})}async function or(v){var C,I;L(""),ee(!1),$(!0);try{if(!(v!=null&&v.prefer_direct)&&(await F.refresh(),Xo.current))return;const B=String(n.auth_token||"").trim();if(!B){v!=null&&v.open_modal_if_needed&&F.openModal();return}const Z=String(n.gateway_url||"").trim();if(Z){const G=Z.toLowerCase();if(!G.startsWith("http://")&&!G.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(((C=window==null?void 0:window.location)==null?void 0:C.protocol)||"")==="https:"&&G.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 Ie=new URL(Z),ye=String(((I=window==null?void 0:window.location)==null?void 0:I.hostname)||"").trim().toLowerCase(),ke=String(Ie.hostname||"").trim().toLowerCase(),Me=He=>He==="localhost"||He==="127.0.0.1"||He==="::1";if(Me(ke)&&ye&&!Me(ye))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(se){throw new Error(String((se==null?void 0:se.message)||se||"Invalid Gateway URL"))}}const X=new kp({base_url:Z,auth_token:B});await X.list_bundles(),r(G=>({...G,gateway_auth_mode:"direct"})),await Ha(X)}catch(B){L(Kp(B,n))}finally{$(!1)}}const Xo=_.useRef(!1),Bi=_.useRef(0),Ui=_.useRef(!1);function Nd(v){var I,B,Z;V(v);const C=!!(v&&v.has_session&&((I=v.gateway)!=null&&I.ok));if(Xo.current=C,C){if(Ui.current=!1,M&&n.gateway_auth_mode==="direct")return;const X=String(((Z=(B=v==null?void 0:v.gateway)==null?void 0:B.principal)==null?void 0:Z.user_id)||"").trim();if(r(G=>({...G,gateway_auth_mode:"session",auth_token:"",gateway_user:X||G.gateway_user})),M&&n.gateway_auth_mode==="session")return;L(""),$(!0),Ha(new kp({base_url:"",auth_token:""})).catch(G=>L(Kp(G,n))).finally(()=>$(!1));return}v&&!v.has_session&&(n.gateway_auth_mode==="session"&&Fl({keep_session:!0}),String(n.auth_token||"").trim()&&!M&&!Ui.current&&(Ui.current=!0,or({prefer_direct:!0})))}async function Va(){if(!(Et||D)){Zt(!0);try{await De.reload_bundles();const v=await De.list_bundles(),C=qa(v);wn(C),en({ts:Rt(),kind:"info",title:"Bundles reloaded",preview:At(`workflows: ${C.length}`)})}catch(v){const C=String((v==null?void 0:v.message)||v||"Bundle reload failed");en({ts:Rt(),kind:"error",title:"Bundle reload failed",preview:At(C),data:{error:C}})}finally{Zt(!1)}}}async function bh(v){if(Tr||D||!M)return;const C=v;if(C){Gr(!0),on("");try{const I=await De.upload_bundle(C,{overwrite:!1,reload:!0});en({ts:Rt(),kind:"info",title:"Bundle uploaded",preview:At(String((I==null?void 0:I.bundle_ref)||""))});const B=await De.list_bundles(),Z=qa(B);wn(Z)}catch(I){const B=String((I==null?void 0:I.message)||I||"Upload failed");on(B),en({ts:Rt(),kind:"error",title:"Upload .flow failed",preview:At(B),data:{error:B}})}finally{Gr(!1);try{dt.current&&(dt.current.value="")}catch{}}}}function Fl(v){Bi.current+=1,v!=null&&v.keep_session||(F.signOut().catch(()=>{}),Xo.current=!1),Ya(),R(""),S(""),Ai(""),J(null),Q(""),re(!1),wn([]),Mn([]),Dn([]),Ss(null),Fn([]),Qt([]),Bt([]),Dt({}),L(""),ee(!1),V(null),r(C=>({...C,auth_token:""})),en({ts:Rt(),kind:"info",title:"Gateway disconnected"})}async function In(v){const C=String(v??"");C&&Cn(await hA(C)?"Copied to clipboard":dA,2)}_.useEffect(()=>{const v=u.trim();if(!qe||!v)return;let C=!1;const I=async()=>{if(!(mt.current>Date.now()))try{const Z=await De.get_run(v);C||mr(Z)}catch{}};I();const B=window.setInterval(I,2e3);return()=>{C=!0,window.clearInterval(B)}},[qe,u,De]),_.useEffect(()=>{if(!M)return;let v=null,C=!1,I=!1;const B=G=>{C||(v!==null&&window.clearTimeout(v),v=window.setTimeout(()=>void Z(),G))},Z=async()=>{if(I)return;const G=mt.current-Date.now();if(G>0){B(G+500);return}I=!0;const se=Date.now();try{await Bs(De)}finally{I=!1;const Ie=Date.now()-se,ye=document.visibilityState==="hidden"?3e4:5e3;B(Math.max(ye,Ie*3))}},X=()=>{document.visibilityState==="visible"&&Z()};return Z(),document.addEventListener("visibilitychange",X),()=>{C=!0,v!==null&&window.clearTimeout(v),document.removeEventListener("visibilitychange",X)}},[M,De]);const[Kc,zl]=_.useState(null);_.useEffect(()=>{if(!M){zl(null);return}let v=!1;return(async()=>{try{const C=await De.get_entity_phases_spec();if(v)return;const I=wO(C);if(zl(I),I)try{const B=localStorage.getItem("abstractobserver_phase_graph_id_v1"),Z=B?JSON.parse(B):null;Z&&Z.sha256&&I.sha256&&Z.sha256!==I.sha256&&Z.version===I.version&&en({ts:Rt(),kind:"error",title:"Phase-graph drift: served bytes changed without a version bump",preview:At(`v${I.version}: ${String(Z.sha256).slice(0,12)}… -> ${String(I.sha256).slice(0,12)}…`),data:{prev:Z,now:{sha256:I.sha256,version:I.version}}}),localStorage.setItem("abstractobserver_phase_graph_id_v1",JSON.stringify({sha256:I.sha256,version:I.version}))}catch{}}catch(C){if(!v){zl(null);const I=String((C==null?void 0:C.message)||C||"");/404|not found/i.test(I)||en({ts:Rt(),kind:"info",title:"Phase-graph fetch failed — pre-wire fallback vocabulary in use (#FALLBACK)",preview:At(I),data:{error:I}})}}})(),()=>{v=!0}},[M]),_.useEffect(()=>{if(!M){Fn([]),Qe("");return}let v=!1,C=null;const I=async()=>{if(!(mt.current>Date.now())){try{const B=await De.list_entities(),Z=B.entities.map(G=>String((G==null?void 0:G.name)||(G==null?void 0:G.slug)||"").trim()).filter(Boolean).slice(0,12),X=await Promise.all(Z.map(async G=>{var se,Ie;try{const[ye,ke]=await Promise.all([De.get_entity_card(G),De.get_entity_cognition(G).catch(()=>null)]),Me=ye!=null&&ye.state&&typeof ye.state=="object"?ye.state:null,He=Array.isArray(ye==null?void 0:ye.moments)?ye.moments:[],Xe=He.length?He[He.length-1]:null,Ye=(se=ke==null?void 0:ke.spend)==null?void 0:se.lifetime,Ze=(Ie=ke==null?void 0:ke.spend)==null?void 0:Ie.live_visit,an=Array.isArray(ke==null?void 0:ke.warnings)?ke.warnings.map(Ke=>String(Ke||"")).filter(Boolean):[],Nt=aO(ye);return{name:G,state:String((Me==null?void 0:Me.state)??(typeof(ye==null?void 0:ye.state)=="string"?ye.state:"")).trim(),age_days:typeof(ye==null?void 0:ye.age_days)=="number"?ye.age_days:null,last_moment:String((Xe==null?void 0:Xe.kind)||"").trim(),last_moment_at:String((Xe==null?void 0:Xe.at)||"").trim(),working:typeof(ke==null?void 0:ke.working)=="boolean"?ke.working:null,tokens_total:typeof(Ye==null?void 0:Ye.tokens_total)=="number"?Ye.tokens_total:null,live_visit_tokens:typeof(Ze==null?void 0:Ze.tokens_total)=="number"?Ze.tokens_total:null,spend_warning:an.join(" | "),live_phase:typeof(ke==null?void 0:ke.phase)=="string"?ke.phase:"",open_questions:Nt.questions,open_questions_total:Nt.questions_total,open_problems:Nt.problems,open_problems_total:Nt.problems_total,lessons:Nt.lessons,lessons_total:Nt.lessons_total,dreams_brief:oO(ye),error:""}}catch(ye){return{name:G,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((ye==null?void 0:ye.message)||ye||"card failed")}}}));v||(Fn(X),Se(B.entities.length),Qe(""))}catch(B){if(!v){Fn([]);const Z=String((B==null?void 0:B.message)||B||"");Qe(/404|not found/i.test(Z)?"":Z)}}v||(C=window.setTimeout(()=>void I(),3e4))}};return I(),()=>{v=!0,C!==null&&window.clearTimeout(C)}},[M,De]);async function Cd(v,C,I){const B=String(C||"").trim();if(!v||!B)throw new Error("This wait has no wait_key yet — open the run to inspect.");await De.submit_command({command_id:Rs(),run_id:v,type:"resume",payload:{wait_key:B,payload:I||{}},client_id:"web_pwa"}),en({ts:Rt(),kind:"info",title:"Board resume submitted",preview:At(`run ${v} · wait ${B}`),data:{run_id:v,wait_key:B}}),Bs(De,{force:!0}),window.setTimeout(()=>void Bs(De,{force:!0}),1200)}const _i=_.useMemo(()=>{const v=he==null?void 0:he.session_id;return typeof v=="string"?v.trim():v==null?"":String(v||"").trim()},[he]),Ed=_.useMemo(()=>{const v=String(_i||"").trim();return v||String(W||"").trim()},[_i,W]);_.useEffect(()=>{M||ci("")},[M]);const[pi,Bn]=x0(),Jn=b0(M?De:null,M),Nn=k0({gateway:M?De:null,session_id:Ed,prefs:pi,on_error:ci,on_transcript:v=>{const C=String(v||"").trim();C&&(Zs(I=>{const B=String(I||"");return B.trim()?`${B.trimEnd()}
|
|
158
|
-
${C}`:C}),window.setTimeout(()=>{var I;return(I=xt.current)==null?void 0:I.focus()},0))}}),Yc=_.useMemo(()=>{for(let v=Ee.length-1;v>=0;v-=1){const C=Ee[v];if(C.role==="assistant")return C.local_error?null:{key:String(C.id||C.ts||""),text:String(C.content||"")}}return null},[Ee]);j0(Nn,pi.read_aloud===!0,Yc);function Bl(v,C){try{const I=URL.createObjectURL(v),B=document.createElement("a");B.href=I,B.download=C||"download",B.rel="noreferrer",document.body.appendChild(B),B.click(),document.body.removeChild(B),window.setTimeout(()=>URL.revokeObjectURL(I),5e3)}catch{}}async function Ul(){const v=rd.trim();if(!v){Cn("This run recorded no workspace",2);return}try{const C=await fetch(HE,{method:"POST",headers:{"Content-Type":"application/json",...jg()},body:JSON.stringify({path:v})}),I=await C.json().catch(()=>({}));C.ok&&(I!=null&&I.ok)?Cn(`Opened ${String(I.path||v)}`,2):Cn(String((I==null?void 0:I.error)||`Folder reveal failed (${C.status})`),3)}catch(C){Cn(String((C==null?void 0:C.message)||C||"Folder reveal failed"),3)}}async function D_(v){const C=String((v==null?void 0:v.run_id)||"").trim(),I=String((v==null?void 0:v.artifact_id)||"").trim();if(!C||!I){Cn("Artifact download needs a run id",3);return}const B=Xm(v)||I;try{const Z=await De.download_run_artifact_content(C,I,{access:"preview"});Bl(Z,Qw(B)),Cn("Downloaded artifact",2)}catch(Z){Cn(String((Z==null?void 0:Z.message)||Z||"Download failed"),3)}}async function Cs(v){const C=String((v==null?void 0:v.run_id)||"").trim(),I=String((v==null?void 0:v.artifact_id)||"").trim();if(!C||!I){Cn("Artifact preview needs a run id",3);return}const B=Xm(v),Z=String((v==null?void 0:v.content_type)||"").trim().toLowerCase(),X=Cf(v);if(Da(B||I),_n(""),Tl(""),nr(X),po(v),Pa(!0),Wt&&(URL.revokeObjectURL(Wt),Jr("")),X==="binary"){_n(`(Binary artifact: ${Z||"unknown"}; download to view.)`);return}if(X==="text"&&typeof v.size_bytes=="number"&&v.size_bytes>15e5){_n(`(Text artifact is ${v.size_bytes.toLocaleString()} bytes; download to view.)`);return}Ko(!0);try{const G=await De.download_run_artifact_content(C,I,{access:"preview"});if(X==="text"){const se=await G.text(),Ie=Jm(v,se),ye=Ie==="json"?15e5:Ie==="markdown"?25e4:Ie==="html"?3e5:22e3;_n(se.length>ye&&Ie!=="text"?`${uc(v.size_bytes??se.length)} ${Ie.toUpperCase()} artifact. Download to inspect it.`:se.length>ye?`${se.slice(0,Math.max(0,ye-1))}…`:se)}else Jr(URL.createObjectURL(G))}catch(G){Tl(String((G==null?void 0:G.message)||G||"Preview failed"))}finally{Ko(!1)}}_.useEffect(()=>()=>{Wt&&URL.revokeObjectURL(Wt)},[Wt]);async function $d(v){const C=String(v.artifact_id||"").trim(),I=String(v.run_id||"").trim(),B=Cf(v);if(!I||!C)return{artifact_id:C,kind:B,render_kind:"",text:"Preview needs artifact run metadata.",url:"",loading:!1,error:""};if(B==="binary")return{artifact_id:C,kind:B,render_kind:"",text:`Preview unavailable for ${v.content_type||v.modality||"this artifact"}. Download to inspect it.`,url:"",loading:!1,error:""};if(B==="text"&&typeof v.size_bytes=="number"&&v.size_bytes>5e5)return{artifact_id:C,kind:B,render_kind:"",text:`${uc(v.size_bytes)} text artifact. Use Preview for a larger view or Download to inspect locally.`,url:"",loading:!1,error:""};try{const Z=await De.download_run_artifact_content(I,C,{access:"preview"});if(B==="text"){const X=await Z.text(),G=Jm(v,X),se=G==="json"?5e5:G==="markdown"?12e4:G==="html"?3e5:8e3;return{artifact_id:C,kind:B,render_kind:G,text:X.length>se&&G!=="text"?`${uc(v.size_bytes??X.length)} ${G.toUpperCase()} artifact. Use Larger preview or Download to inspect it.`:X.length>se?`${X.slice(0,Math.max(0,se-1))}…`:X,url:"",loading:!1,error:""}}return{artifact_id:C,kind:B,render_kind:"",text:"",url:URL.createObjectURL(Z),loading:!1,error:""}}catch(Z){return{artifact_id:C,kind:B,render_kind:"",text:"",url:"",loading:!1,error:String((Z==null?void 0:Z.message)||Z||"Preview failed")}}}async function Ad(v){if(Dr.url&&URL.revokeObjectURL(Dr.url),!v){Vo(mh());return}const C=String(v.artifact_id||"").trim(),I=Cf(v);Vo({artifact_id:C,kind:I,render_kind:"",text:"",url:"",loading:!0,error:""}),Vo(await $d(v))}function en(v){const C=String(v.id||"").trim()||Rs();Qu(I=>[{...v,id:C},...I].slice(0,800))}function Cn(v,C){ka(v),to.current&&window.clearTimeout(to.current),Ei(!1),window.requestAnimationFrame(()=>Ei(!0)),to.current=window.setTimeout(()=>{Ei(!1),to.current=null},1500),wr.current&&(window.clearTimeout(wr.current),wr.current=null),C>0&&(wr.current=window.setTimeout(()=>{ka(""),wr.current=null},Math.max(1,C)*1e3))}function An(v,C){const I=String(v||"").trim(),B=String(C||"").trim();if(!B)return"";const Z=I?String(Ti.current[I]||"").trim():"";return Z?`${Z}::${B}`:B}function Zo(v,C,I){const B=String(v||"").trim(),Z=String(C||"").trim(),X=String(I||"").trim();if(!B||!Z||!X)return;const G=An(B,Z);G&&(Ti.current[X]=G,ao.current[X]=B,zo.current[X]={parent_run_id:B,parent_node_id:Z},Bo.current.has(X)||(Bo.current.add(X),Uo(se=>se.includes(X)?se:[...se,X])))}function Ga(v){const C=String(v||"").trim();if(!C)return;const I=Date.now(),B=oo.current;oo.current=C,Oc(I),xl(Z=>{const X={};for(const[ye,ke]of Object.entries(Z))typeof ke=="number"&&ke>I&&(X[ye]=ke);X[C]=Math.max(X[C]||0,I+2e3),B&&B!==C&&(X[B]=Math.max(X[B]||0,I+2e3));const G=Object.keys(X);if(G.length<=200)return X;const se=G.sort((ye,ke)=>(X[ke]||0)-(X[ye]||0)).slice(0,200),Ie={};for(const ye of se)Ie[ye]=X[ye]||0;return Ie}),Pc(Z=>{if(typeof Z[C]=="number")return Z;const X={...Z,[C]:I};if(Fo.current.push(C),Fo.current.length>8e3){const G=Fo.current.splice(0,1500);for(const se of G)delete X[se]}return X}),Or.current&&window.clearTimeout(Or.current),Or.current=window.setTimeout(()=>{const Z=Date.now();xl(X=>{const G={};for(const[se,Ie]of Object.entries(X))typeof Ie=="number"&&Ie>Z&&(G[se]=Ie);return G}),Oc(Z),Or.current=null},2200)}function Jc(v,C){var Ze,an,Nt;const I=String(C||"").trim()||u.trim();hr.current=v.cursor,(Ze=ii.current)==null||Ze.push({cursor:v.cursor,record:v.record}),I&&uo.current.add(`${I}:${v.cursor}`);const B=wm(v.record),Z=B&&B.name?_f(B.name):"",X=v.record,G=typeof(X==null?void 0:X.node_id)=="string"?X.node_id:"",se=typeof(X==null?void 0:X.status)=="string"?X.status:"",Ie=typeof((an=X==null?void 0:X.effect)==null?void 0:an.type)=="string"?X.effect.type:"",ye=typeof(X==null?void 0:X.run_id)=="string"?X.run_id:"",ke=ye||I;if(Z==="abstract.status"&&ke===I){const{text:Ke,duration:wt}=bu(B==null?void 0:B.payload);Cn(Ke,wt)}const Me=G?An(ke,G):"";if(se==="waiting"){const Ke=fa(X);if(String((Ke==null?void 0:Ke.reason)||"").trim()==="subworkflow"){const kn=typeof((Nt=Ke==null?void 0:Ke.details)==null?void 0:Nt.sub_run_id)=="string"?String(Ke.details.sub_run_id):"";kn&&G&&Zo(ke,G,kn)}}if(G&&(Ga(An(ke,G)),se==="waiting"||se==="running")){const Ke=An(ke,G);Ke&&(oo.current=Ke,di(Ke))}let He="step",Xe=Me||G||"(node?)",Ye="";if(B&&B.name&&Gp(B.name))He=Z==="abstract.message"?"message":"event",Xe=Z||B.name,Ye=At(Z==="abstract.steer_seen"?Vp(B==null?void 0:B.payload):bu(B==null?void 0:B.payload).text);else if(X!=null&&X.error)He="error",Xe="error",Ye=At(dr(X.error,360));else if(se==="waiting"){const Ke=fa(X),wt=String((Ke==null?void 0:Ke.reason)||"").trim();Ye=At(wt?`waiting • ${wt}`:"waiting")}else X!=null&&X.result?Ye=At(dr(X.result,360)):Ie?Ye=At(Ie):Ye=At(Om(X));en({id:`step:${ye||I||"?"}:${v.cursor}`,ts:String((X==null?void 0:X.ended_at)||(X==null?void 0:X.started_at)||Rt()),kind:He,title:Xe,preview:Ye,data:X,cursor:v.cursor,run_id:ye||I||void 0,node_id:Me||G,status:se,effect_type:Ie,emit_name:Z||(B==null?void 0:B.name)||void 0})}function kh(v,C){var Ye,Ze,an;co.current=Math.max(co.current,C.cursor);const I=`${v}:${C.cursor}`;if(!!uo.current.has(I))return;uo.current.add(I),(Ye=oi.current)==null||Ye.push({run_id:v,cursor:C.cursor,record:C.record});const Z=wm(C.record),X=Z&&Z.name?_f(Z.name):"",G=C.record,se=typeof(G==null?void 0:G.node_id)=="string"?G.node_id:"",Ie=se?An(v,se):"",ye=typeof(G==null?void 0:G.status)=="string"?G.status:"",ke=typeof((Ze=G==null?void 0:G.effect)==null?void 0:Ze.type)=="string"?G.effect.type:"";if(ye==="waiting"){const Nt=fa(G);if(String((Nt==null?void 0:Nt.reason)||"").trim()==="subworkflow"){const wt=typeof((an=Nt==null?void 0:Nt.details)==null?void 0:an.sub_run_id)=="string"?String(Nt.details.sub_run_id):"";wt&&se&&Zo(v,se,wt),wt&&Pr.current.trim()===String(v||"").trim()&&(Pr.current=wt,hi(wt))}}if(se&&(Ga(An(v,se)),ye==="waiting"||ye==="running")){const Nt=An(v,se);Nt&&(oo.current=Nt,di(Nt))}if((ye==="completed"||ye==="failed")&&Pr.current.trim()===String(v||"").trim()){const Nt=String(ao.current[String(v||"").trim()]||"").trim();Nt&&Nt!==u.trim()?(Pr.current=Nt,hi(Nt)):(Pr.current="",hi(""))}if(X==="abstract.status"&&v===u.trim()){const{text:Nt,duration:Ke}=bu(Z==null?void 0:Z.payload);Cn(Nt,Ke)}let Me="step",He=Ie||se||"(node?)",Xe="";if(Z&&Z.name&&Gp(Z.name))Me=X==="abstract.message"?"message":"event",He=`subrun • ${X||Z.name}`,Xe=At(X==="abstract.steer_seen"?Vp(Z==null?void 0:Z.payload):bu(Z==null?void 0:Z.payload).text);else if(G!=null&&G.error)Me="error",He="error",Xe=At(dr(G.error,360));else if(ye==="waiting"){const Nt=fa(G),Ke=String((Nt==null?void 0:Nt.reason)||"").trim();Xe=At(Ke?`waiting • ${Ke}`:"waiting")}else G!=null&&G.result?Xe=At(dr(G.result,360)):ke?Xe=At(ke):Xe=At(Om(G));en({id:`step:${v}:${C.cursor}`,ts:String((G==null?void 0:G.ended_at)||(G==null?void 0:G.started_at)||Rt()),kind:Me,title:He,preview:Xe,data:G,cursor:C.cursor,run_id:v,node_id:Ie||se,status:ye,effect_type:ke,emit_name:X||(Z==null?void 0:Z.name)||""})}function jh(v,C){var Ze,an,Nt;const I=String(v||"").trim();if(!I)return;const B=`${I}:${C.cursor}`;if(!!uo.current.has(B))return;uo.current.add(B),(Ze=oi.current)==null||Ze.push({run_id:I,cursor:C.cursor,record:C.record});const X=wm(C.record),G=X&&X.name?_f(X.name):"",se=C.record,Ie=typeof(se==null?void 0:se.node_id)=="string"?se.node_id:"",ye=Ie?An(I,Ie):"",ke=typeof(se==null?void 0:se.status)=="string"?se.status:"",Me=typeof((an=se==null?void 0:se.effect)==null?void 0:an.type)=="string"?se.effect.type:"";if(ke==="waiting"){const Ke=fa(se);if(String((Ke==null?void 0:Ke.reason)||"").trim()==="subworkflow"){const kn=typeof((Nt=Ke==null?void 0:Ke.details)==null?void 0:Nt.sub_run_id)=="string"?String(Ke.details.sub_run_id):"";kn&&Ie&&Zo(I,Ie,kn)}}if(Ie&&(Ga(An(I,Ie)),ke==="waiting"||ke==="running")){const Ke=An(I,Ie);Ke&&(oo.current=Ke,di(Ke))}if(G==="abstract.status"&&I===u.trim()){const{text:Ke,duration:wt}=bu(X==null?void 0:X.payload);Cn(Ke,wt)}let He="step",Xe=ye||Ie||"(node?)",Ye="";if(X&&X.name&&Gp(X.name))He=G==="abstract.message"?"message":"event",Xe=`subrun • ${G||X.name}`,Ye=At(G==="abstract.steer_seen"?Vp(X==null?void 0:X.payload):bu(X==null?void 0:X.payload).text);else if(se!=null&&se.error)He="error",Xe="error",Ye=At(dr(se.error,360));else if(ke==="waiting"){const Ke=fa(se),wt=String((Ke==null?void 0:Ke.reason)||"").trim();Ye=At(wt?`waiting • ${wt}`:"waiting")}else se!=null&&se.result?Ye=At(dr(se.result,360)):Me?Ye=At(Me):Ye=At(Om(se));en({id:`step:${I}:${C.cursor}`,ts:String((se==null?void 0:se.ended_at)||(se==null?void 0:se.started_at)||Rt()),kind:He,title:Xe,preview:Ye,data:se,cursor:C.cursor,run_id:I,node_id:ye||Ie,status:ke,effect_type:Me,emit_name:G||(X==null?void 0:X.name)||""})}async function Td(v,C){var B,Z;let I=C.after;for(;;){if((B=C.signal)!=null&&B.aborted)return I;const X=await De.get_ledger(v,{after:I,limit:200,signal:C.signal});if((Z=C.signal)!=null&&Z.aborted)return I;const G=Array.isArray(X.items)?X.items:[];if(!G.length)return hr.current=I,I;const se=I;for(let Ie=0;Ie<G.length;Ie++){const ye=G[Ie];Jc({cursor:se+Ie+1,record:ye},v)}I=typeof X.next_after=="number"?X.next_after:I}}async function Wl(v){var X,G,se,Ie;const C=String(v||"").trim();on(""),rn(!0),ln(!1),(X=ii.current)==null||X.reset(),(G=oi.current)==null||G.reset(),Ps.current={scanned:0,found:null},Gs([]),hr.current=0,Vr([]),uo.current=new Set,Qu([]),dh(""),ka(""),mr(null),Xs(""),Mc(""),di(""),oo.current="",xl({}),Pc({}),Fo.current=[],Oc(Date.now()),Ti.current=C?{[C]:""}:{},ao.current={},zo.current={},Bo.current=new Set,Uo([]),fi.current="",Pr.current="",hi(""),Wo.current={},Or.current&&window.clearTimeout(Or.current),Or.current=null,Js.current&&window.clearTimeout(Js.current),Js.current=null,Ri.current&&Ri.current.abort(),_s.current&&_s.current.abort(),_s.current=null,co.current=0,kl("");const I=new AbortController;Ri.current=I;let B=!1;try{let ye="",ke="";try{const Me=await De.get_run(C);mr(Me);const He=typeof(Me==null?void 0:Me.workflow_id)=="string"?String(Me.workflow_id):"",Xe=Lx(He);Xe&&(ye=Xe.bundle_id,ke=Xe.flow_id)}catch{}try{const Me=await De.get_run_input_data(C);typeof(Me==null?void 0:Me.bundle_id)=="string"&&(ye=String(Me.bundle_id||"").trim()||ye),typeof(Me==null?void 0:Me.flow_id)=="string"&&(ke=String(Me.flow_id||"").trim()||ke);const He=Me&&typeof Me.input_data=="object"&&Me.input_data&&!Array.isArray(Me.input_data)?Me.input_data:null;He&&A(JSON.stringify(He,null,2));const Xe=Me==null?void 0:Me.workspace,Ye=typeof(Xe==null?void 0:Xe.workspace_root)=="string"?String(Xe.workspace_root).trim():"";Mc(Ye)}catch{Mc("")}ye&&ke&&(R(ye),S(ke),Ai(ke),await Sd(ye)),await Td(C,{after:0,signal:I.signal});try{const Me=await De.get_run_history_bundle(C,{include_subruns:!0,include_session:!1,ledger_mode:"tail",ledger_max_items:1}),He=Me&&typeof Me=="object"?Me.ledgers:null,Ye=(He&&typeof He=="object"?Object.keys(He):[]).map(Ze=>String(Ze||"").trim()).filter(Boolean).filter(Ze=>Ze!==C);if(Ye.length){for(const Ze of Ye)Bo.current.add(Ze);Uo(Ze=>Array.from(new Set([...Ze,...Ye])));try{const Ze=typeof((se=He==null?void 0:He[C])==null?void 0:se.total)=="number"?Number(He[C].total):0;let an="",Nt=-1;for(const Ke of Ye){const wt=typeof((Ie=He==null?void 0:He[Ke])==null?void 0:Ie.total)=="number"?Number(He[Ke].total):0;wt>Nt&&(an=Ke,Nt=wt)}an&&Nt>Math.max(Ze*3,Ze+20)&&(Pr.current=an,hi(an))}catch{}}}catch{}ln(!0),en({ts:Rt(),kind:"info",title:`Attached to run ${C}`,data:{run_id:C}}),B=!0}catch(ye){const ke=String((ye==null?void 0:ye.message)||ye||"unknown error");on(ke),en({ts:Rt(),kind:"error",title:"Connection error",preview:At(ke),data:{error:ke}}),ln(!1)}finally{rn(!1)}if(!B||I.signal.aborted)return;(async()=>{let ye=250;for(;!I.signal.aborted;){try{const ke=await Td(C,{after:hr.current,signal:I.signal});await De.stream_ledger(C,{after:ke,on_step:Me=>Jc(Me,C),signal:I.signal})}catch(ke){if(I.signal.aborted)break;const Me=String((ke==null?void 0:ke.message)||ke||"stream error");en({ts:Rt(),kind:"error",title:"Ledger stream error (will retry)",preview:At(Me),data:{error:Me}})}if(I.signal.aborted)break;await new Promise(ke=>setTimeout(ke,ye)),ye=Math.min(5e3,Math.floor(ye*1.6))}})()}async function Sh(){const v=ir,C=(v==null?void 0:v.kind)==="bundle"?v.flow_id:(v==null?void 0:v.kind)==="default"?"@default":"",I=(v==null?void 0:v.kind)==="bundle"?v.bundle_id:"";if(!v){const B="Select a workflow first (Launch → pick a workflow).";return on(B),B}on(""),rn(!0);try{let B={};const Z=T.trim();if(Z)try{if(B=JSON.parse(Z),typeof B!="object"||B===null||Array.isArray(B))throw new Error("input_data must be a JSON object")}catch(Me){const He=`Invalid input_data JSON: ${String((Me==null?void 0:Me.message)||Me)}`;return on(He),He}for(const[Me,He]of Object.entries(B)){if(typeof He!="string")continue;const Xe=He.trim();Xe?B[Me]=Xe:delete B[Me]}const X=(Ba||[]).find(Me=>Me&&typeof Me=="object"&&Me.id==="prompt"),G=X&&typeof X=="object"&&Object.prototype.hasOwnProperty.call(X,"default"),se=B==null?void 0:B.prompt,Ie=typeof se=="string"?se.trim():"";if(X&&!G&&!Ie){const Me="Missing required input_data.prompt";return on(Me),Me}const ye=B.workspace&&typeof B.workspace=="object"?B.workspace:null;delete B.workspace;const ke=await De.start_run(C,B,{...ye?{workspace:ye}:{},...I?{bundle_id:I}:{},...v.kind==="default"?{interface:v.interface}:{},session_id:String(W||"").trim()||null});return m(ke),f(ke),_r(""),await Wl(ke),Bs(),null}catch(B){const Z=String((B==null?void 0:B.message)||B||"start failed");return on(Z),Z}finally{rn(!1)}}async function Nh(){if(et([]),Ve(null),!Te.available){et([Te.reason]);return}const v=V$(We,{choice:ir,bundle_ref_for:C=>{var I;return((I=zt.find(B=>B.bundle_id===C))==null?void 0:I.bundle_ref)||""},input_data:Ot,email_usable:fn.email_usable},Ce.current);if(!v.ok){et(v.errors);return}be(!0);try{const C=await De.automations_client().createAutomation(v.body);Ce.current.reset(),me([]),ut(gg),en({ts:Rt(),kind:"info",title:"Automation created",preview:At(`${v.body.title} · ${C.automation_id}`)}),t("automations"),await fn.refresh(),await fn.select(C.automation_id)}catch(C){const I=(C&&typeof C=="object"&&typeof C.code=="string"?C:null)||{status:0,code:"client_error",message:String((C==null?void 0:C.message)||C||"Create failed")};Ve(I)}finally{be(!1)}}async function Ch(){if(_r(""),fe==="automate"){await Nh();return}const v=await Sh();if(v){_r(v);return}so("ledger"),t("observe")}async function Md(v){if(Ln("skills",void 0),!!v){if(v.kind==="default"){Ue(v.interface),R(""),S(""),J(null);return}Ue(""),R(v.bundle_id),S(v.flow_id),Ai(v.flow_id),await Sd(v.bundle_id)}}async function Ka(v){const[C,I]=await Promise.all([De.get_run(v),De.get_run_input_data(v)]),B=tA(C,I);await Md(B.choice),A(JSON.stringify(B.input_data,null,2)),ut(B.form),me([`Recreating the legacy schedule ${sn(v,14)} as an automation. The legacy schedule keeps running until you suspend it.`,...B.notes]),Ce.current.reset(),ge("automate"),t("launch")}async function vo(v,C){const I=String(v||"").trim();if(!I)return;if(pt){Cn(`Still attaching — retry in a moment (${sn(I,14)})`,2500);return}on(""),k("");const B=String((C==null?void 0:C.root_run_id)||I).trim()||I;m(B),f(I),await Wl(I)}_.useEffect(()=>{const v=String(g||"").trim();if(!v)return;let C=!1;return(async()=>{try{if(M||await or({open_modal_if_needed:!0}),C)return;so("ledger"),t("observe");const I=await De.find_run(v);if(C)return;if(I===null){Ya(),k(v);return}await vo(v),Jl()}catch(I){C||on(String((I==null?void 0:I.message)||I||"Failed to attach run from URL"))}finally{C||y("")}})(),()=>{C=!0}},[g]);function Ya(){var v,C;Ri.current&&Ri.current.abort(),Ri.current=null,_s.current&&_s.current.abort(),_s.current=null,co.current=0,kl(""),f(""),m(""),Ti.current={},ao.current={},zo.current={},Bo.current=new Set,Uo([]),fi.current="",Pr.current="",hi(""),Wo.current={},Xs(""),Or.current&&window.clearTimeout(Or.current),Or.current=null,Js.current&&window.clearTimeout(Js.current),Js.current=null,ln(!1),rn(!1),Wn(!1),hr.current=0,(v=ii.current)==null||v.reset(),(C=oi.current)==null||C.reset(),Ps.current={scanned:0,found:null},Gs([]),Vr([]),uo.current=new Set,mr(null),Qu([]),di(""),oo.current="",xl({}),Pc({}),Fo.current=[],Oc(Date.now()),Cn("",-1),on(""),Ge([]),_t(null),Zs(""),li(""),ce(!1),Kt(!1),Ft(""),En(""),Qn(""),Yr([]),Sa(!1),Cc(""),Ec(""),Ac(!1),Oo("")}_.useEffect(()=>{Ge([]),_t(null),Zs(""),li(""),ce(!1),Kt(!1),Ft(""),En(""),Qn(""),Yr([]),Sa(!1),Cc(""),Ec(""),Ac(!1),Oo("")},[u]),_.useEffect(()=>{er==="chat"&&u.trim()&&M&&Qc()},[er,u,M,he==null?void 0:he.workflow_id]);async function ql(v,C,I){const B=String(v||"").trim();if(!B)return on("Missing run_id"),"Missing run_id";on("");try{const Z={},X=String((I==null?void 0:I.reason)||"").trim();X&&(Z.reason=X),await De.submit_command({command_id:Rs(),run_id:B,type:C,payload:Z,client_id:"web_pwa"}),en({ts:Rt(),kind:"info",title:`${C} submitted`,preview:X?`reason: ${X}`:"",data:{run_id:B,type:C,reason:X}});try{if(B===u.trim()){const G=await De.get_run(B);mr(G)}}catch{}return Bs(De,{force:!0}),window.setTimeout(()=>void Bs(De,{force:!0}),900),window.setTimeout(()=>void Bs(De,{force:!0}),2400),null}catch(Z){const X=String((Z==null?void 0:Z.message)||Z||`${C} failed`);return on(X),X}}async function Xc(v,C){return ql(u.trim(),v,C)}async function Zc(v,C="Stopped from AbstractObserver"){const I=String(v||"").trim();if(!I||!window.confirm(`Cancel run ${sn(I,24)}?`))return;await ql(I,"cancel",{reason:C})||Cn("Cancel submitted",2)}async function Eh(){var I;const v=u.trim();if(!v){on("Select a run first.");return}if(!M){on("Connect to the gateway first.");return}if(gt)return;const C=String(((I=he==null?void 0:he.waiting)==null?void 0:I.reason)||"").trim().toLowerCase()||String(os||"").trim().toLowerCase();if(!Us||ei||ko||bo.toLowerCase()!=="waiting"||C!=="until"){on("This run is not a scheduled wait that can be triggered now.");return}on(""),Wn(!0);try{const B={payload:{mode:"run_now",requested_at:Rt()}},Z=String(Es||"").trim();Z&&(B.wait_key=Z),await De.submit_command({command_id:Rs(),run_id:v,type:"resume",payload:B,client_id:"web_pwa"}),en({ts:Rt(),kind:"info",title:"Scheduled run triggered",preview:At(`run ${v}`),data:{run_id:v,until:jr||null}});try{const X=await De.get_run(v);mr(X)}catch{}}catch(B){on(String((B==null?void 0:B.message)||B||"Failed to trigger scheduled run"))}finally{Wn(!1)}}async function $h(v){const C=u.trim();if(!C)return on("Missing run_id"),"Missing run_id";if(Rn)return"Schedule update already in progress";const I=String(v.interval||"").trim();if(!/^\s*(\d+(?:\.\d+)?)\s*(ms|s|m|h|d)\s*$/i.test(I)){const Z="Invalid interval (expected like '20m', '1h', '0.5s', '250ms')";return ai(Z),Z}ai(""),on(""),Fs(!0),rn(!0);try{await De.submit_command({command_id:Rs(),run_id:C,type:"update_schedule",payload:{interval:I,apply_immediately:v.apply_immediately!==!1},client_id:"web_pwa"}),en({ts:Rt(),kind:"info",title:"Schedule updated",preview:At(`interval: ${I}`),data:{interval:I},run_id:C});try{const Z=await De.get_run(C);mr(Z)}catch{}return null}catch(Z){const X=String((Z==null?void 0:Z.message)||Z||"update_schedule failed");return ai(X),on(X),X}finally{rn(!1),Fs(!1)}}async function Ah(v){const C=u.trim();if(!C)return on("Missing run_id"),"Missing run_id";if(Mr)return"Compaction already in progress";const I=typeof(v==null?void 0:v.preserve_recent)=="number"?v.preserve_recent:fs,B=Math.max(0,Math.min(500,Math.floor(Number.isFinite(I)?I:6))),Z=(v==null?void 0:v.compression_mode)||Qi,X=String((v==null?void 0:v.focus)??ba??"").trim();hs(""),on(""),Rr(!0),rn(!0);try{const G={preserve_recent:B,compression_mode:Z};return X&&(G.focus=X),await De.submit_command({command_id:Rs(),run_id:C,type:"compact_memory",payload:G,client_id:"web_pwa"}),en({ts:Rt(),kind:"info",title:"Compaction requested",preview:At(`mode: ${Z} • preserve_recent: ${B}`),data:G,run_id:C}),null}catch(G){const se=String((G==null?void 0:G.message)||G||"compact_memory failed");return hs(se),on(se),se}finally{rn(!1),Rr(!1)}}async function Th(){const v=u.trim();if(!v){li("Select a run first.");return}if(!M){li("Connect to the gateway first.");return}const C=no.trim();if(!C||q)return;if(Nn.voice_ptt_busy){ci("Wait for transcription to finish.");return}li(""),ci(""),ce(!0);const B={id:`local:${Rs()}`,role:"user",content:C,ts:Rt()};Ge(Z=>[...Z,B]),Zs("");try{const Z=UE(Ee,B),X=n.maintenance_ai_provider.trim(),G=n.maintenance_ai_model.trim(),se=await De.run_chat(v,{provider:X||void 0,model:G||void 0,include_subruns:!0,messages:Z}),Ie=String((se==null?void 0:se.answer)||"").trim()||"(empty response)",ye=String((se==null?void 0:se.generated_at)||"").trim()||Rt();_t((se==null?void 0:se.history)??null),Ge(ke=>[...ke,{id:`local:${Rs()}`,role:"assistant",content:Ie,ts:ye}])}catch(Z){const X=j$(Z);li(X),Ge(G=>[...G,{id:`local:${Rs()}`,role:"assistant",content:`(error: ${X})`,ts:Rt(),local_error:!0}])}finally{ce(!1)}}function Rd(v){const C=String(v.id||v.ts||"").trim(),I=String(v.content||"").trim();!C||!I||(ci(""),Nn.toggle_tts(C,I))}function Mh(v){const C=String(v.id||v.ts||"").trim(),I=Nn.tts_playback;return!C||!I.key||I.key!==C?"idle":I.status}function Ld(v){if(!Ee.length)return;const C=u.trim(),I=C?`Run ${C}`:"Chat",B=F2(Ee.map(Z=>({role:Z.role,content:Z.content,ts:Z.ts})),{heading:I});if(v==="download"){const Z=new Date().toISOString().slice(0,19).replace(/[:T]/g,"-"),X=`abstractobserver-chat-${Qw(C||"run")}-${Z}.md`;z2({filename:X,text:B,mime:"text/markdown;charset=utf-8"});return}(async()=>{const Z=await gl(B);Ae(Z?"copied":"failed"),window.setTimeout(()=>Ae("idle"),900)})()}async function Qc(){const v=typeof(he==null?void 0:he.workflow_id)=="string"?String(he.workflow_id).trim():"";if(!v){Yr([]);return}if(M&&!$i){Cc(""),Sa(!0);try{const C=await De.list_runs({limit:200,workflow_id:v,root_only:!0}),I=Array.isArray(C==null?void 0:C.items)?C.items:[],B=[];for(const ye of I){const ke=typeof(ye==null?void 0:ye.run_id)=="string"?String(ye.run_id).trim():"";if(!ke)continue;const Me=typeof(ye==null?void 0:ye.ledger_len)=="number"?Number(ye.ledger_len):0;B.push({run_id:ke,ledger_len:Number.isFinite(Me)?Me:0})}if(!B.length){Yr([]);return}const Z=400,X=B.map(ye=>({run_id:ye.run_id,after:Math.max(0,(ye.ledger_len||0)-Z)})),G=await De.get_ledger_batch({runs:X,limit:Z}),se=[],Ie=new Set;for(const ye of B){const ke=G!=null&&G.runs&&typeof G.runs=="object"?G.runs[ye.run_id]:null,Me=Array.isArray(ke==null?void 0:ke.items)?ke.items:[];for(const He of Me){const Xe=He==null?void 0:He.effect;if(!Xe||typeof Xe!="object"||String(Xe.type||"")!=="emit_event")continue;const Ye=Xe.payload;if(!Ye||typeof Ye!="object"||String(Ye.name||"")!=="abstract.chat.thread")continue;const Ze=Ye.payload;if(!Ze||typeof Ze!="object")continue;const an=typeof Ze.thread_id=="string"?String(Ze.thread_id).trim():"";if(!an||Ie.has(an))continue;Ie.add(an);const Nt=typeof Ze.created_at=="string"?String(Ze.created_at):"",Ke=typeof Ze.title=="string"?String(Ze.title):"",wt=typeof Ze.workflow_id=="string"?String(Ze.workflow_id):v,kn=typeof Ze.run_id=="string"?String(Ze.run_id):ye.run_id,Tn=typeof Ze.provider=="string"?String(Ze.provider):"",Ts=typeof Ze.model=="string"?String(Ze.model):"",qs=typeof Ze.message_count=="number"?Number(Ze.message_count):null,ni=Ze.chat_artifact,ec=ni&&typeof ni=="object"&&typeof ni.$artifact=="string"?String(ni.$artifact):"";ec&&se.push({thread_id:an,created_at:Nt,title:Ke||`Chat ${an.slice(0,8)}`,run_id:kn,workflow_id:wt,message_count:qs,provider:Tn,model:Ts,artifact_id:ec})}}se.sort((ye,ke)=>String(ke.created_at||"").localeCompare(String(ye.created_at||""))),Yr(se)}catch(C){Cc(String((C==null?void 0:C.message)||C||"Failed to load saved discussions"))}finally{Sa(!1)}}}async function F_(){const v=u.trim();if(!v){Ft("Select a run first.");return}if(!M){Ft("Connect to the gateway first.");return}if(Ee.length&&!Ut){Ft(""),Kt(!0);try{const C=n.maintenance_ai_provider.trim(),I=n.maintenance_ai_model.trim(),B=await De.save_chat_thread(v,{provider:C||void 0,model:I||void 0,include_subruns:!0,messages:Ee.map(G=>({role:G.role,content:G.content,ts:G.ts}))}),Z=typeof(B==null?void 0:B.created_at)=="string"?String(B.created_at):Rt();En(Z);try{const G=JSON.stringify(Ee.map(se=>({role:se.role,content:se.content,ts:se.ts})));Qn(G)}catch{Qn("1")}typeof(B==null?void 0:B.thread_id)=="string"&&String(B.thread_id).trim()&&Ec(String(B.thread_id).trim());const X=!!(B!=null&&B.duplicate);Cn(X?"Already saved":"Saved discussion",2),await Qc()}catch(C){Ft(String((C==null?void 0:C.message)||C||"Failed to save discussion"))}finally{Kt(!1)}}}async function Rh(){const v=String(yl||"").trim();if(!v)return;const C=Qs.find(Z=>String(Z.thread_id||"").trim()===v)||null;if(!C){Oo("Saved discussion not found (refresh list).");return}if(!M){Oo("Connect to the gateway first.");return}if($c)return;const I=Ee.length>0,B=(()=>{if(!I)return!1;if(!xn)return!0;try{return JSON.stringify(Ee.map(X=>({role:X.role,content:X.content,ts:X.ts})))!==xn}catch{return!0}})();if(!(I&&B&&!window.confirm("Replace the current chat with the selected saved discussion? Unsaved changes will be lost."))){Oo(""),Ac(!0);try{const X=await(await De.download_run_artifact_content(C.run_id,C.artifact_id)).text(),G=JSON.parse(X),se=Array.isArray(G==null?void 0:G.messages)?G.messages:[],Ie=typeof(G==null?void 0:G.created_at)=="string"?String(G.created_at):String(C.created_at||""),ye=[];for(let ke=0;ke<se.length;ke++){const Me=se[ke];if(!Me||typeof Me!="object")continue;const He=String(Me.role||"").trim()==="assistant"?"assistant":"user",Xe=typeof Me.content=="string"?String(Me.content):"";if(!Xe.trim())continue;const Ye=typeof Me.ts=="string"?String(Me.ts):Ie||Rt();ye.push({id:`thread:${v}:${ke}`,role:He,content:Xe.trim(),ts:Ye})}Ge(ye),_t(null),Zs(""),li(""),Ft(""),En(Ie||"");try{const ke=JSON.stringify(ye.map(Me=>({role:Me.role,content:Me.content,ts:Me.ts})));Qn(ke)}catch{Qn("1")}Cn("Loaded discussion",2)}catch(Z){Oo(String((Z==null?void 0:Z.message)||Z||"Failed to load saved discussion"))}finally{Ac(!1)}}}async function eu(v){const C=u.trim(),I=String((Vt==null?void 0:Vt.wait_key)||"").trim();if(!C||!I){on("No active wait to resume");return}if(String((Vt==null?void 0:Vt.reason)||"").trim()==="subworkflow"){on("This run is waiting on a subworkflow; attach to the child run instead of resuming manually.");return}on(""),Wn(!0);try{await De.submit_command({command_id:Rs(),run_id:C,type:"resume",payload:{wait_key:I,payload:v||{}},client_id:"web_pwa"}),en({ts:Rt(),kind:"info",title:"Resume submitted",preview:At(`wait_key: ${I}`),data:{wait_key:I,payload:v||{}}}),Xs(I);try{const B=await De.get_run(C);mr(B)}catch{}Bs(De,{force:!0}),window.setTimeout(()=>void Bs(De,{force:!0}),900),window.setTimeout(()=>void Bs(De,{force:!0}),2400),Js.current&&window.clearTimeout(Js.current),Js.current=window.setTimeout(()=>{Xs(B=>B===I?"":B)},2e3)}catch(B){on(String((B==null?void 0:B.message)||B||"resume failed"))}finally{Wn(!1)}}async function z_(v){if(!Il){on("No worker configured");return}if(!gt){on(""),Wn(!0);try{const C=[];for(const I of v){const B=await Il.call_tool(I);C.push(B)}await eu({mode:"executed",results:C})}finally{Wn(!1)}}}const xo=_.useMemo(()=>eh(Vt),[Vt]),Es=String((Vt==null?void 0:Vt.wait_key)||"").trim(),os=String((Vt==null?void 0:Vt.reason)||"").trim(),jr=typeof(Vt==null?void 0:Vt.until)=="string"?String(Vt.until):"",bo=typeof(he==null?void 0:he.status)=="string"?String(he.status):"",ko=!!(he!=null&&he.paused),ei=bo==="completed"||bo==="failed"||bo==="cancelled",ti=os==="until"&&!!jr,Ja=!ei&&ZT(gs)&&(!!Es||ti),tu=os==="user",nu=os==="event"?_f($O(Es)):"",Lh=os==="event"&&nu==="abstract.ask",Ih=xo.length>0,su=Ja&&Es&&(tu||Lh||Ih)&&Yu!==Es&&e!=="board",zr=typeof((jo=Vt==null?void 0:Vt.details)==null?void 0:jo.sub_run_id)=="string"?String(Vt.details.sub_run_id):"",Qo={run_id:u.trim(),workflow_id:typeof(he==null?void 0:he.workflow_id)=="string"?String(he.workflow_id):null,status:bo,created_at:typeof(he==null?void 0:he.created_at)=="string"?String(he.created_at):null,updated_at:typeof(he==null?void 0:he.updated_at)=="string"?String(he.updated_at):null,session_id:typeof(he==null?void 0:he.session_id)=="string"?String(he.session_id):null,current_node:typeof(he==null?void 0:he.current_node)=="string"?String(he.current_node):null},ru=cn.slice(-10).map(v=>{var C,I,B,Z,X,G;return{cursor:v.cursor,node_id:String(((C=v.record)==null?void 0:C.node_id)||"").trim(),status:String(((I=v.record)==null?void 0:I.status)||"").trim(),effect_type:String(((Z=(B=v.record)==null?void 0:B.effect)==null?void 0:Z.type)||"").trim(),ts:String(((X=v.record)==null?void 0:X.ended_at)||((G=v.record)==null?void 0:G.started_at)||"").trim(),summary:U0(v.record)}}),Oh=_y(Vt,xo),Ph=D0(Vt,xo),Id=F0(Vt,Ot),ea=Id.text,Dh=Id.runtime_metadata,Hl=String((Vt==null?void 0:Vt.prompt)||"").trim(),Fh=PT(Ot,6),ar=!!(Hl&&I0(Hl)),ys=!!(Hl&&!ar),zh=ys?"Question from workflow":ea&&ea!==Hl?"Closest prior user request":"Request context",Bh=zT(Ot,T),Uh=!!T.trim(),lr=he!=null&&he.schedule&&typeof he.schedule=="object"?he.schedule:null,ta=typeof(lr==null?void 0:lr.interval)=="string"?String(lr.interval).trim():"",Od=typeof(lr==null?void 0:lr.share_context)=="boolean"?!!lr.share_context:null,Pd=typeof(lr==null?void 0:lr.repeat_count)=="number"?Number(lr.repeat_count):null,Us=!!(he!=null&&he.is_scheduled)||!!lr,iu=Us&&!!ta,Dd=bo==="running"&&!ko?"Pause":"Resume",ou=Us?ko?"resume":"pause":Dd==="Pause"?"pause":"resume",Fd=Us?!u.trim()||pt||gt||ei:!u.trim()||pt||gt||ei||ou==="resume"&&!ko,Wh=u.trim()?ei?"The schedule has ended.":null:"No run selected.",zd=Us&&!ko&&!ei&&!pt&&!gt&&bo.toLowerCase()==="waiting"&&(String(((Xl=he==null?void 0:he.waiting)==null?void 0:Xl.reason)||"").trim().toLowerCase()==="until"||os==="until")&&!!String(jr||"").trim(),$s=(_u=he==null?void 0:he.limits)==null?void 0:_u.tokens,Vl=typeof($s==null?void 0:$s.pct)=="number"?Number($s.pct):null,Bd=$s==null?void 0:$s.estimated_used,au=($s==null?void 0:$s.max_input_tokens)??($s==null?void 0:$s.max_tokens),na=_.useMemo(()=>{const v=Ps.current;cn.length<v.scanned&&(v.scanned=0,v.found=null);for(let C=v.scanned;C<cn.length;C++){const I=cn[C],B=I==null?void 0:I.record;if(!B)continue;const Z=wm(B);if((Z&&Z.name?_f(Z.name):"")!=="abstract.summary")continue;const G=Z!=null&&Z.payload&&typeof Z.payload=="object"?Z.payload:{},se=typeof(G==null?void 0:G.text)=="string"?String(G.text):"";se.trim()&&(v.found={cursor:I.cursor,ts:String((B==null?void 0:B.ended_at)||(B==null?void 0:B.started_at)||""),text:se,provider:typeof(G==null?void 0:G.provider)=="string"?String(G.provider):void 0,model:typeof(G==null?void 0:G.model)=="string"?String(G.model):void 0,generated_at:typeof(G==null?void 0:G.generated_at)=="string"?String(G.generated_at):void 0,source:G==null?void 0:G.source})}return v.scanned=cn.length,v.found},[cn]);_.useEffect(()=>{Pr.current=ps.trim()},[ps]),_.useEffect(()=>{const v=u.trim(),C=zr.trim();if(!(qe&&os==="subworkflow"&&!!C&&C!==v)){fi.current="",ps.trim()&&hi("");return}fi.current!==C&&(fi.current=C,Pr.current=C,hi(C))},[qe,u,os,zr,ps]),_.useEffect(()=>{Lc({})},[N]);const Gl=_.useMemo(()=>((Array.isArray(z==null?void 0:z.entrypoints)?z==null?void 0:z.entrypoints:[])||[]).map(C=>String((C==null?void 0:C.flow_id)||"").trim()).filter(Boolean),[z]),ws=_.useMemo(()=>{const v=String((he==null?void 0:he.workflow_id)||"").trim();return qe&&Us?v:""},[qe,Us,he==null?void 0:he.workflow_id]),B_=_.useMemo(()=>{var G;if(!qe||!u.trim()||!ws.trim())return es;const v=String((he==null?void 0:he.status)||"").trim().toLowerCase(),C=String((he==null?void 0:he.current_node)||"").trim();if(v!=="waiting"&&v!=="running"||!C)return es;const I=An(u.trim(),C);if(!I)return es;const B=String(os||((G=he==null?void 0:he.waiting)==null?void 0:G.reason)||"").trim().toLowerCase(),Z=typeof(gs==null?void 0:gs.node_id)=="string"?String(gs.node_id).trim():"",X=typeof(gs==null?void 0:gs.status)=="string"?String(gs.status).trim().toLowerCase():"";return v==="waiting"&&B==="until"||!es.trim()||(X==="waiting"||X==="running")&&!Z?I:es},[qe,u,ws,he==null?void 0:he.status,he==null?void 0:he.current_node,(nl=he==null?void 0:he.waiting)==null?void 0:nl.reason,os,es,gs]),qh=_.useMemo(()=>{const v={},C=u.trim(),I=(B,Z)=>{if(!Z)return;const X=typeof(Z==null?void 0:Z.node_id)=="string"?String(Z.node_id).trim():"";if(!X)return;const G=An(B,X);if(!G)return;const se=String((Z==null?void 0:Z.ended_at)||(Z==null?void 0:Z.started_at)||"").trim(),Ie=qn(se);Ie!==null&&(v[G]=Math.max(v[G]||0,Ie))};for(const B of cn)B&&B.record&&I(C,B.record);for(const B of ns)B&&B.record&&I(String(B.run_id||"").trim(),B.record);return v},[cn,ns,u,Mi]);_.useEffect(()=>{var I;if(!qe||!u.trim()||!ws.trim())return;const v=String((he==null?void 0:he.current_node)||"").trim();!v||String(((I=he==null?void 0:he.waiting)==null?void 0:I.reason)||"").trim()==="subworkflow"||Ga(An(u.trim(),v))},[qe,u,ws,he==null?void 0:he.current_node,(Ws=he==null?void 0:he.waiting)==null?void 0:Ws.reason]),_.useEffect(()=>{const v=String((Yn==null?void 0:Yn.flow_id)||"").trim();v&&(ui.trim()||Ai(v))},[Yn,ui]),_.useEffect(()=>{const v=ws.trim(),C=N.trim(),I=ui.trim();if(v){let Z=!1;return Do(!0),Ea(""),De.get_workflow_flow(v).then(X=>{if(Z)return;const G=X==null?void 0:X.flow;io(G&&typeof G=="object"?G:null)}).catch(X=>{Z||(io(null),Ea(String((X==null?void 0:X.message)||X||"Failed to load workflow flow")))}).finally(()=>{Z||Do(!1)}),()=>{Z=!0}}if(!C||!I){io(null),Ea(""),Do(!1);return}let B=!1;return Do(!0),Ea(""),De.get_bundle_flow(C,I).then(Z=>{if(B)return;const X=Z==null?void 0:Z.flow,G=X&&typeof X=="object"?X:null;io(G),G&&Lc(se=>({...se,[I]:G}))}).catch(Z=>{B||(io(null),Ea(String((Z==null?void 0:Z.message)||Z||"Failed to load flow")))}).finally(()=>{B||Do(!1)}),()=>{B=!0}},[ws,N,ui,De]),_.useEffect(()=>{const v=N.trim();if(!$a||!v||!Ca)return;let C=!1;const I=3,B=ye=>{const ke=Array.isArray(ye==null?void 0:ye.nodes)?ye.nodes:[],Me=[];for(const He of ke){const Xe=He!=null&&He.data&&typeof He.data=="object"?He.data:{};if(String((Xe==null?void 0:Xe.nodeType)||(He==null?void 0:He.type)||"").trim()!=="subflow")continue;const Ze=(Xe==null?void 0:Xe.subflowId)||(Xe==null?void 0:Xe.flowId),an=typeof Ze=="string"?Ze.trim():"";an&&Me.push(an.includes(":")?an.split(":",2)[1]:an)}return Me},Z=new Set,X=new Set,G=(ye,ke)=>{if(!(!ye||ke>=I))for(const Me of B(ye)){const He=String(Me||"").trim();if(!He||Z.has(He))continue;Z.add(He),X.add(He);const Xe=Rc[He];Xe&&G(Xe,ke+1)}};G(Ca,0);const se=Array.from(X).filter(ye=>!Rc[ye]).slice(0,20);return se.length?((async()=>{for(const ye of se){if(C)return;try{const ke=await De.get_bundle_flow(v,ye),Me=ke==null?void 0:ke.flow,He=Me&&typeof Me=="object"?Me:null;if(!He)continue;Lc(Xe=>Xe[ye]?Xe:{...Xe,[ye]:He})}catch{}}})(),()=>{C=!0}):void 0},[$a,N,Ca,Rc,De]);const lu=_.useMemo(()=>{const C=(Array.isArray(z==null?void 0:z.flows)?z==null?void 0:z.flows:[]).map(I=>String(I||"").trim()).filter(Boolean);return C.length?Array.from(new Set(C)).sort():Array.from(new Set(Gl)).sort()},[z,Gl]);_.useEffect(()=>{ei&&es.trim()&&(di(""),oo.current="")},[ei,u,es]),_.useEffect(()=>{const v=ps.trim(),C=u.trim();if(!(qe&&!!v&&v!==C)){_s.current&&_s.current.abort(),_s.current=null,co.current=0,Dc&&kl("");return}if(Dc===v)return;_s.current&&_s.current.abort();const B=new AbortController;_s.current=B,co.current=0,kl(v),en({ts:Rt(),kind:"info",title:`Following run ${v} (status/events)`});let Z=250;return(async()=>{for(;!B.signal.aborted;){try{await De.stream_ledger(v,{after:co.current,on_step:G=>kh(v,G),signal:B.signal});return}catch(G){if(B.signal.aborted)break;const se=String((G==null?void 0:G.message)||G||"stream error");en({ts:Rt(),kind:"error",title:"Child ledger stream error (will retry)",preview:At(se),data:{child_run_id:v,error:se}})}if(B.signal.aborted)break;await new Promise(G=>setTimeout(G,Z)),Z=Math.min(5e3,Math.floor(Z*1.6))}})(),()=>{B.abort()}},[qe,ps,u,De,Dc]),_.useEffect(()=>{if(!qe||!u.trim())return;let v=!1;const C=async()=>{if(!v&&!bl.current&&Mi.length&&!(mt.current>Date.now())){bl.current=!0;try{const B=Mi.map(se=>String(se||"").trim()).filter(Boolean);if(!B.length)return;const Z=B.map(se=>({run_id:se,after:Number(Wo.current[se]||0)})),X=await De.get_ledger_batch({runs:Z,limit:200}),G=X&&typeof X=="object"?X.runs:{};for(const se of B){if(v)return;const Ie=G&&typeof G=="object"?G[se]:null,ye=Array.isArray(Ie==null?void 0:Ie.items)?Ie.items:[],ke=typeof(Ie==null?void 0:Ie.next_after)=="number"?Ie.next_after:Number(Wo.current[se]||0),Me=Number(Wo.current[se]||0);for(let He=0;He<ye.length;He++){const Xe=ye[He];jh(se,{cursor:Me+He+1,record:Xe})}Wo.current[se]=ke}}catch(B){if(v)return;en({ts:Rt(),kind:"error",title:"Subrun digest poll failed",preview:At(String((B==null?void 0:B.message)||B||""))})}finally{bl.current=!1}}};C();const I=window.setInterval(()=>void C(),2e3);return()=>{v=!0,window.clearInterval(I),bl.current=!1}},[qe,u,Mi,De]);const sa=_.useMemo(()=>{const v=u.trim(),C=[];for(const I of cn)!I||!I.record||C.push({run_id:v,cursor:I.cursor,record:I.record});for(const I of ns)!I||!I.record||C.push({run_id:String(I.run_id||"").trim(),cursor:I.cursor,record:I.record});return C},[cn,ns,u]),cu=_.useMemo(()=>{var C,I,B,Z;const v={};for(const X of sa){const G=String(X.run_id||((C=X.record)==null?void 0:C.run_id)||"").trim();!G||String(((B=(I=X.record)==null?void 0:I.effect)==null?void 0:B.type)||"").trim()!=="llm_call"||String(((Z=X.record)==null?void 0:Z.status)||"")!=="started"&&(v[G]=(v[G]||0)+1)}return v},[sa]),Kl=_.useMemo(()=>{const v=ps.trim();if(v)return v;let C="",I=-1;for(const[B,Z]of Object.entries(cu))Z>I&&(C=B,I=Z);return C||u.trim()},[cu,ps,u]),As=(M_.trim()||Kl).trim(),U_=_.useMemo(()=>{var Z;const v=new Set,C=u.trim(),I=ps.trim();C&&v.add(C),I&&v.add(I);for(const X of Mi){const G=String(X||"").trim();G&&v.add(G)}for(const X of sa){const G=String(X.run_id||((Z=X.record)==null?void 0:Z.run_id)||"").trim();G&&v.add(G)}const B=Array.from(v);return B.sort((X,G)=>C&&X===C&&G!==C?-1:C&&G===C&&X!==C?1:I&&X===I&&G!==I?-1:I&&G===I&&X!==I?1:X<G?-1:X>G?1:0),B},[u,ps,Mi,sa]),Hh=_.useMemo(()=>{var v;for(let C=cn.length-1;C>=0;C--){const I=W0((v=cn[C])==null?void 0:v.record);if(I)return I}return""},[cn]);function uu(v){uh(v);const C=u.trim();if(!(!C||typeof window>"u"))try{window.history.replaceState(null,"",m$(GE(C),v))}catch{}}const Gt=_.useMemo(()=>{const v=u.trim();return v&&(vn.find(C=>String(C.run_id||"").trim()===v)||Un.find(C=>String(C.run_id||"").trim()===v))||null},[vn,Un,u]),Xa=String((he==null?void 0:he.status)||(Gt==null?void 0:Gt.status)||"").trim(),st=String(os||((pu=he==null?void 0:he.waiting)==null?void 0:pu.reason)||(Gt==null?void 0:Gt.waiting_reason)||"").trim().toLowerCase(),ra=!!(he!=null&&he.is_scheduled||Gt!=null&&Gt.is_scheduled),du=!!(he!=null&&he.paused||Gt!=null&&Gt.paused),Ud=ra&&Xa.toLowerCase()==="waiting",Vh=Ud&&st==="until",Za=qn(jr),Qa=Vh&&Za!==null?ev(Za-Date.now()):"",ia=S$(he),Yl=ra&&du?"Suspended":Ud?"Scheduled":Km({status:Xa,paused:du,stop_reason:ia});async function Wd(){if(M){qo(!0),ph("");try{const v=fo,C=v==="session"?String(Ra||_i||W||"").trim():"",I=v==="run"?String(Li||u||"").trim():"",B=GT(Bc),Z=ho.length?ho.join(","):"",X=KT(Ia),G=Math.max(0,$l)*Mm,se=await De.search_artifacts({scope:v,session_id:C||void 0,run_id:I||void 0,query:Cl||void 0,artifact_kind:Z||void 0,created_after:B||void 0,include_stats:!0,limit:Mm,offset:G,order_by:X.order_by,order:X.order}),Ie=[],ye=new Set;for(const Ye of Array.isArray(se==null?void 0:se.items)?se.items:[]){const Ze=qT(Ye,"search");!Ze||ye.has(Ze.artifact_id)||(ye.add(Ze.artifact_id),Ie.push(Ze))}const ke=se!=null&&se.stats&&typeof se.stats=="object"?se.stats:{},Me=Number((ke==null?void 0:ke.total)??(se==null?void 0:se.total)??Ie.length),He=pv(se);let Xe=He;if(ho.length)try{const Ye=await De.search_artifacts({scope:v,session_id:C||void 0,run_id:I||void 0,query:Cl||void 0,created_after:B||void 0,include_stats:!0,limit:1,offset:0,order_by:X.order_by,order:X.order});Xe=pv(Ye)}catch{Xe=He}Sn(Number.isFinite(Me)?Math.max(0,Me):Ie.length),Sl(Number((ke==null?void 0:ke.total_bytes)??(ke==null?void 0:ke.byte_total)??0)||0),dd(He),Ta(Xe),ld(Ie),El(Ye=>{var Ze;return Ye&&Ie.some(an=>an.artifact_id===Ye)?Ye:((Ze=Ie[0])==null?void 0:Ze.artifact_id)||""})}catch(v){ph(String((v==null?void 0:v.message)||v||"Failed to load artifacts")),ld([]),Sn(0),Sl(0),dd({}),Ta({}),El("")}finally{qo(!1)}}}async function qd(){if(M){gd(!0),Pi("");try{const v=await De.audit_log_tail({max_bytes:16e4}),C=typeof(v==null?void 0:v.bytes)=="number"?Number(v.bytes):0,I=!!(v!=null&&v.truncated);pd(String((v==null?void 0:v.content)||"")),Rl(`${C.toLocaleString()} bytes${I?" (tail)":""}`)}catch(v){Pi(String((v==null?void 0:v.message)||v||"Failed to load audit log")),pd(""),Rl("")}finally{gd(!1)}}}async function fu(v){if(!M)return;const C=String(v||tr||Li||u||"").trim();if(!C){rr([]),Xr(""),Ll("Select a run in Activity or Artifacts to load its runtime ledger.");return}go(!0),Ll("");try{const I=await De.get_ledger(C,{after:0,limit:2e3}),B=Array.isArray(I.items)?I.items:[];rr(B.map((X,G)=>({cursor:G+1,record:X})));const Z=typeof I.next_after=="number"?Number(I.next_after):B.length;Xr(`${B.length.toLocaleString()} record${B.length===1?"":"s"}${Z>=2e3?" (first 2,000)":""}`)}catch(I){Ll(String((I==null?void 0:I.message)||I||"Failed to load run ledger")),rr([]),Xr("")}finally{go(!1)}}_.useEffect(()=>{M&&e==="runtime"&&Wd()},[M,e,fo,Ra,Li,Cl,ho,Bc,Ia,$l]),_.useEffect(()=>{M&&(Uc||Ml||e==="runtime"&&qd())},[M,e,er]),_.useEffect(()=>{if(!M||e!=="runtime"||jl!=="logs"||Di!=="run_ledger"&&Di!=="provider_calls")return;const v=String(tr||Li||u||"").trim();v&&fu(v)},[M,e,jl,Di,tr,Li,u]);const gi=_.useMemo(()=>{const v=new Map;for(const C of[...Un,...vn]){const I=String(C.run_id||"").trim();I&&v.set(I,C)}for(const C of Mi){const I=String(C||"").trim();!I||v.has(I)||v.set(I,{run_id:I,workflow_id:null,status:"",created_at:null,updated_at:null,ledger_len:null,parent_run_id:ao.current[I]||null,session_id:_i||null})}return u.trim()&&!v.has(u.trim())&&v.set(u.trim(),{run_id:u.trim(),workflow_id:typeof(he==null?void 0:he.workflow_id)=="string"?String(he.workflow_id):null,status:typeof(he==null?void 0:he.status)=="string"?String(he.status):"",created_at:typeof(he==null?void 0:he.created_at)=="string"?String(he.created_at):null,updated_at:typeof(he==null?void 0:he.updated_at)=="string"?String(he.updated_at):null,ledger_len:cn.length||null,parent_run_id:typeof(he==null?void 0:he.parent_run_id)=="string"?String(he.parent_run_id):null,session_id:typeof(he==null?void 0:he.session_id)=="string"?String(he.session_id):_i||null}),Array.from(v.values()).sort((C,I)=>{const B=qn(C.updated_at||C.created_at)??0;return(qn(I.updated_at||I.created_at)??0)-B})},[vn,Un,u,he,cn.length,Mi,_i]),vs=_.useMemo(()=>NM(gi,{query:ed,filter:Tc,group_by:td,workflow_label_by_id:kr,parent_hint:v=>ao.current[v]||""}),[gi,ed,Tc,td,kr]),xs=_.useMemo(()=>{const v={};for(const C of gi){const I=String(C.run_id||"").trim();I&&(v[I]=C)}return v},[gi]),yi=String(tr||Li||u||"").trim(),hu=yi&&xs[yi]||null,Hd=String(Ra||(hu==null?void 0:hu.session_id)||_i||W||"").trim(),Br=_.useMemo(()=>ad.map(v=>Zm(v,xs,kr)),[ad,xs,kr]);_.useEffect(()=>{md(0)},[Cl,ho,Bc,Li,Ia,La,fo,Ra]);const Gh=Math.max(1,Math.ceil(cd/Mm)),cr=Math.min(Math.max(0,$l),Gh-1);_.useEffect(()=>{$l!==cr&&md(cr)},[$l,cr]);const oa=_.useMemo(()=>Br,[Br,cr]),Kh=_.useMemo(()=>{const v={};for(const C of oa){const I=La==="type"?kg(C,xs,kr):HT(C,La);v[I]||(v[I]=[]),v[I].push(C)}return Object.entries(v).map(([C,I])=>({key:C,items:I})).sort((C,I)=>{var B,Z;if(La==="time"){const X=qn((B=C.items[0])==null?void 0:B.created_at)??0,G=qn((Z=I.items[0])==null?void 0:Z.created_at)??0;if(X!==G)return G-X}return C.key.localeCompare(I.key)})},[oa,La,xs,kr]),el=_.useMemo(()=>{const v=mi.trim();return v?oa.find(C=>C.artifact_id===v)||oa[0]||null:oa[0]||null},[oa,mi]);_.useEffect(()=>{e!=="runtime"||jl!=="artifacts"||Ad(el)},[e,jl,el==null?void 0:el.artifact_id]),_.useEffect(()=>()=>{Dr.url&&URL.revokeObjectURL(Dr.url)},[Dr.url]);const Yh=_.useMemo(()=>gi.filter(v=>Uu(v.status)),[gi]);_.useEffect(()=>{if(e!=="settings"&&e!=="launch"||!M||Y)return;let v=!1;return(async()=>{const[C,I]=await Promise.all([De.list_skills(),De.list_mcp_servers()]);v||(H(C),_e(I),ae(!0))})(),()=>{v=!0}},[e,M,Y]);function Jl(){T_&&window.setTimeout(()=>{var v;return(v=sd.current)==null?void 0:v.scrollIntoView({block:"start"})},60)}function Vd(v){so(v),Jl()}const mu=[{id:"board",label:"Board",icon:s.jsx(Be,{name:"board",size:16})},{id:"observe",label:"Observe",icon:s.jsx(Be,{name:"history",size:16})},{id:"runtime",label:"System",icon:s.jsx(Be,{name:"server",size:16})},{id:"launch",label:"Launch",icon:s.jsx(Be,{name:"send",size:16})},{id:"automations",label:"Automations",icon:s.jsx(Be,{name:"refresh",size:16})}],Gd={board:"Board",observe:"Observe",runtime:"System",launch:"Launch",automations:"Automations",settings:"Settings"},Sr=s.jsx(bM,{connected:M,request:Jo,value:bd,onChange:v=>Ln("workspace",v===null?void 0:v),disabled:pt||gt}),tn=s.jsx(s.Fragment,{children:ir?s.jsxs("details",{className:"launch_capabilities",style:{marginTop:"10px"},children:[s.jsxs("summary",{className:"help_text muted",style:{cursor:"pointer"},children:["Capabilities",br.length?` · ${br.length} skill${br.length===1?"":"s"}`:""]}),s.jsx("div",{className:"help_text muted",style:{marginTop:"8px"},children:"Skills attach knowledge procedures to this run. The gateway resolves selections through the trust gate at start: validated skills activate, unverified ones are held for review, blocked ones never ride."}),O===null?s.jsx("div",{className:"help_text muted",style:{marginTop:"8px"},children:"This gateway does not serve a skills inventory yet — the shelf lights up here when it ships."}):O.length?s.jsx("div",{className:"launch_skill_list",children:O.map(v=>{var Z;const C=br.includes(v.name),I=v.blocked===!0,B=v.requires_review===!0&&!I;return s.jsxs("label",{className:`launch_skill_row ${I?"is_blocked":""} ${C?"is_on":""}`,title:[v.description||"",v.tree_hash?`tree ${v.tree_hash.slice(0,16)}…`:"",I&&((Z=v.reasons)!=null&&Z.length)?`blocked: ${v.reasons.join("; ")}`:""].filter(Boolean).join(`
|
|
159
|
-
`),children:[s.jsx("input",{type:"checkbox",checked:C,disabled:I||pt||gt||le,onChange:X=>{const G=X.target.checked?Array.from(new Set([...br,v.name])):br.filter(se=>se!==v.name);Ln("skills",G.length?G:void 0)}}),s.jsx("span",{className:"launch_skill_name",children:v.name}),v.trust_level?s.jsx("span",{className:`chip ${I?"danger":B?"warn":"muted"}`,children:I?"blocked":B?"review":v.trust_level}):null,v.description?s.jsx("span",{className:"launch_skill_desc",children:v.description}):null]},v.name)})}):s.jsx("div",{className:"help_text muted",style:{marginTop:"8px"},children:"The gateway's skills shelf is empty."}),br.length?s.jsx("div",{className:"help_text muted",style:{fontSize:"var(--font-size-xxs)",marginTop:"6px"},children:"Selected skills ride the run as input_data.skills; the resolved verdicts land in the run's record."}):null]}):null}),as=s.jsxs("section",{className:"launch_workspaces","data-section":"workspaces",style:{marginTop:"10px"},children:[s.jsx("div",{className:"launch_label launch_section_title",children:"Workspaces"}),Sr,s.jsx("div",{className:"launch_grid",style:{marginTop:"8px"},children:s.jsxs("div",{className:"launch_grid_cell",style:{gridColumn:"1 / -1"},children:[s.jsx("label",{className:"launch_label",children:"Run workspace"}),s.jsx("input",{className:"mono",value:xd,onChange:v=>Ln("workspace_root",v.target.value||void 0),placeholder:"/path/to/workspace",disabled:pt||gt}),s.jsx("div",{className:"help_text muted",style:{fontSize:"var(--font-size-xxs)"},children:"Empty = the run's own private workspace. Otherwise a workspace the gateway's posture reaches; the gateway refuses any other."})]})})]}),Vn=s.jsxs("details",{className:"launch_bundles",style:{marginTop:"10px"},children:[s.jsx("summary",{className:"help_text muted",style:{cursor:"pointer"},children:"Workflow bundles"}),s.jsxs("div",{className:"launch_workflow_bar",style:{marginTop:"8px"},children:[s.jsx("input",{ref:dt,type:"file",accept:".flow",style:{display:"none"},onChange:v=>{const C=v.target.files&&v.target.files.length?v.target.files[0]:null;C&&bh(C)}}),s.jsx("button",{type:"button",className:"btn launch_btn_upload",onClick:()=>{var v;return(v=dt.current)==null?void 0:v.click()},disabled:!M||D||Tr||pt||gt,title:"Upload a .flow bundle",children:Tr?"…":"Upload .flow"}),s.jsxs("button",{type:"button",className:"btn launch_btn_reload",onClick:()=>void Va(),disabled:!M||D||Et||pt||gt,title:"Reload picks up server-side edits",children:[s.jsx(Be,{name:"refresh",size:14}),Et?"…":"Reload bundles"]})]})]});function ls(v){t("observe"),so("ledger"),vo(v)}const Nr={on_select:v=>void fn.select(v),on_row_action:(v,C)=>{if(C==="discuss"||C==="edit")throw new Error(`${C} is routed by AutomationsPage (route_row_action), not the app handlers.`);if(C==="archive"){fn.ask_archive(v.automation_id);return}fn.row_action(v,C)},on_legacy_action:(v,C)=>{if(C==="open_run"){ls(v.automation_id);return}if(C==="recreate"){Ka(v.automation_id).catch(I=>fn.report_error(I));return}fn.legacy_action(v,C)},on_confirm_archive:v=>void fn.row_action(v,"archive"),on_cancel_archive:()=>fn.ask_archive(""),on_status_filter:v=>void fn.set_status_filter(v),on_refresh:()=>void fn.refresh(),on_new:()=>{ge("automate"),t("launch")},on_show_archived:v=>fn.set_show_archived(v)};return s.jsxs("div",{className:`app-shell shell${Po?" nav_open":""}`,children:[oh&&Po?s.jsx("div",{className:"shell_nav_backdrop","aria-hidden":"true",onClick:()=>vl(!1)}):null,s.jsxs("aside",{className:"shell_sidebar",id:"shell_nav",ref:ch,...ro.attrs.aside,children:[s.jsxs("div",{className:"shell_brand",title:"AbstractObserver (Web/PWA)",children:[s.jsx("span",{className:"logo-icon shell_brand_mark","aria-hidden":"true",children:s.jsxs("svg",{viewBox:"0 0 24 24",width:"20",height:"20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[s.jsx("ellipse",{cx:"12",cy:"12",rx:"9",ry:"4.2",transform:"rotate(-18 12 12)",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",opacity:"0.75"}),s.jsx("circle",{cx:"12",cy:"12",r:"4.7",fill:"currentColor",opacity:"0.95"}),s.jsx("circle",{cx:"10.3",cy:"10.7",r:"1.6",fill:"#ffffff",opacity:"0.18"}),s.jsx("circle",{cx:"19",cy:"13.6",r:"1.2",fill:"currentColor"})]})}),s.jsx("span",{className:"shell_brand_name",children:"Observer"}),s.jsx("button",{type:"button",className:"shell_nav_close","aria-label":"Close navigation",title:"Close navigation",onClick:()=>vl(!1),children:s.jsx(Be,{name:"x",size:16})})]}),s.jsxs("nav",{className:"shell_nav",children:[mu.map(v=>s.jsxs("button",{className:`shell_nav_item ${e===v.id?"active":""}`,onClick:()=>{t(v.id),vl(!1)},type:"button",children:[s.jsx("span",{className:"shell_nav_icon",children:v.icon}),s.jsx("span",{className:"shell_nav_label",children:v.label})]},v.id)),s.jsxs("a",{className:"shell_nav_item",href:l,target:"_blank",rel:"noreferrer",title:"Open the entity app (memory graph + visits)",children:[s.jsx("span",{className:"shell_nav_icon",children:s.jsx(Be,{name:"bot",size:16})}),s.jsx("span",{className:"shell_nav_label",children:"Entities ↗"})]}),s.jsxs("button",{className:`shell_nav_item ${e==="settings"?"active":""}`,onClick:()=>{t("settings"),vl(!1)},type:"button",children:[s.jsx("span",{className:"shell_nav_icon",children:s.jsx(Be,{name:"settings",size:16})}),s.jsx("span",{className:"shell_nav_label",children:"Settings"})]})]}),s.jsx("div",{className:"shell_sidebar_footer",children:s.jsxs("div",{className:"shell_connection shell_connection_passive",title:M?"Gateway connected":D?"Gateway: connecting…":"Gateway: signed out",children:[s.jsx("span",{className:`gateway_led ${M?"ok":D?"warn":"err"}`,"aria-hidden":"true"}),s.jsx("span",{className:`shell_connection_label ${M&&((wi=(la=U==null?void 0:U.gateway)==null?void 0:la.principal)!=null&&wi.user_id)?"mono":""}`,children:M?((gu=(Zl=U==null?void 0:U.gateway)==null?void 0:Zl.principal)==null?void 0:gu.user_id)||(n.gateway_auth_mode==="direct"?"direct dev":"connected"):D?"connecting…":"signed out"})]})})]}),s.jsxs("div",{className:"shell_main",...ro.attrs.main,children:[s.jsxs("header",{className:"shell_header",children:[s.jsx("button",{ref:lh,type:"button",className:"shell_nav_toggle","data-nav-toggle":!0,"aria-label":"Open navigation","aria-controls":"shell_nav","aria-expanded":Po,title:"Navigation",onClick:()=>vl(!0),children:s.jsx(Be,{name:"list",size:18})}),s.jsx("div",{className:"shell_header_title",children:Gd[e]||"Observer"}),s.jsxs("div",{className:"shell_header_actions",children:[o?s.jsx("monitor-gpu",{ref:c,mode:"icon","history-size":"5","tick-ms":"1500","base-url":n.gateway_auth_mode==="session"?"":n.gateway_url,title:"GPU usage (host)",style:{"--monitor-gpu-width":"34px","--monitor-gpu-bars-height":"22px","--monitor-gpu-padding":"2px 4px","--monitor-gpu-radius":"999px","--monitor-gpu-bg":"rgba(0,0,0,0.22)","--monitor-gpu-border":"rgba(255,255,255,0.16)",flexShrink:0}}):null,s.jsx(GS,{docs:{open:Xt,onToggle:()=>Pn(v=>!v),label:"Docs assistant"},appearance:{onOpen:()=>Ct(!0)},about:{identity:xh,versions:yd,onOpen:Vc},connection:{phase:F.phase,signingOut:F.signingOut,onConnect:()=>F.openModal(),onDisconnect:()=>Fl()}})]})]}),s.jsx(NS,{...F.modalProps}),s.jsx(XS,{open:lt,onClose:()=>Ct(!1),value:rt,onChange:ht}),s.jsx(IE,{open:Xt,onClose:()=>Pn(!1),connected:M,topOffset:44,gateway:De}),s.jsxs("div",{className:"app-body shell_content",children:[e==="board"?M?s.jsx(EO,{gateway_connected:M,runs:Un,all_runs:vn,runs_refreshed_at:Kn,entities:Ar,entities_total:de,entities_error:tt,refreshing:bn,on_refresh:()=>void Bs(De,{force:!0}),on_open_run:v=>{t("observe"),so("ledger"),vo(v)},on_resume_wait:Cd,on_open_automation:v=>{t("automations"),fn.refresh().then(()=>fn.select(v))},entity_app_href:l,on_read_diary:(v,C)=>De.read_entity_diary_entry(v,C),phase_graph:Kc}):s.jsx("div",{className:"page page_scroll",children:s.jsx("div",{className:"page_inner constrained",children:s.jsxs("div",{className:"card mc_hero",children:[s.jsx("div",{className:"title",children:s.jsx("h1",{children:"Connect to your gateway"})}),s.jsxs("p",{className:"muted",children:["Mission Control shows every run and entity on one board — but nothing is connected yet.",E?` Last attempt: ${E}`:""]}),s.jsxs("div",{className:"row",style:{gap:"8px",alignItems:"center"},children:[s.jsx("button",{className:"btn primary",onClick:()=>F.openModal(),disabled:D,children:D?"Connecting…":"Sign in"}),s.jsx("button",{className:"btn",onClick:()=>void or({open_modal_if_needed:!0}),disabled:D,title:"Retry with an existing browser session or a direct dev token",children:"Retry connection"})]})]})})}):null,e==="settings"?s.jsx("div",{className:"page page_scroll",children:s.jsxs("div",{className:"page_inner settings_col",children:[s.jsxs("section",{className:"pane",children:[s.jsxs("div",{className:"pane_header",children:[s.jsx("span",{className:"pane_title",children:"Gateway"}),s.jsx("span",{className:"pane_spacer"}),s.jsx("span",{className:`chip ${M?"ok":"warn"}`,children:qx(U).label})]}),s.jsxs("div",{className:"pane_body settings_body",children:[s.jsxs("div",{className:"settings_row",children:[s.jsxs("div",{className:"settings_row_main",children:[s.jsx("div",{className:"settings_row_title",children:"Connection"}),s.jsx("div",{className:"settings_row_help",children:"The shared AbstractFramework sign-in: a gateway user token exchanges for an HTTP-only browser session. Raw tokens are never stored."})]}),s.jsxs("div",{className:"settings_row_actions",children:[s.jsx("button",{className:"btn",onClick:()=>F.openModal(),children:"Manage connection…"}),M?s.jsx("button",{className:"btn",onClick:()=>Fl(),title:"Sign this browser out of the gateway (this app's session only)",children:"Sign out"}):null]})]}),E?s.jsx("div",{className:"warn_callout",children:E}):null,s.jsx("div",{className:"settings_row",children:s.jsx(lT,{checked:n.auto_connect_gateway,onChange:v=>r(C=>({...C,auto_connect_gateway:v}))})}),s.jsxs("details",{className:"settings_advanced",children:[s.jsx("summary",{children:"Advanced: direct dev connection (bearer token, cross-origin)"}),s.jsxs("div",{className:"field",style:{marginTop:"8px"},children:[s.jsx("label",{children:"Gateway URL"}),s.jsx("input",{value:n.gateway_url,onChange:v=>r(C=>({...C,gateway_url:v.target.value})),placeholder:c_})]}),s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Dev bearer token"}),s.jsx("input",{type:"password",value:n.auth_token,onChange:v=>r(C=>({...C,auth_token:v.target.value,gateway_auth_mode:"direct"})),placeholder:"development only — prefer the sign-in dialog"})]}),s.jsx("button",{className:"btn",onClick:()=>void or({prefer_direct:!0}),disabled:D,children:D?"Connecting…":"Connect directly"})]})]})]}),s.jsxs("section",{className:"pane",children:[s.jsxs("div",{className:"pane_header",children:[s.jsx("span",{className:"pane_title",children:"Assistant"}),s.jsx("span",{className:"pane_spacer"}),s.jsx("span",{className:"chip muted",children:"docs Q&A + run Ask"})]}),s.jsxs("div",{className:"pane_body settings_body",children:[s.jsx("div",{className:"settings_row_help",style:{marginTop:0},children:"The model answering the header assistant and the run page's Ask tab. Blank fields follow the gateway defaults."}),s.jsx(Fx,{className:"field",providerLabel:"Provider",modelLabel:"Model",providerPlaceholder:"(gateway default)",modelPlaceholder:"(gateway default)",provider:n.maintenance_ai_provider,model:n.maintenance_ai_model,providers:yo,models:jd.models,loadingProviders:D,loadingModels:wo,modelError:Qr?jd.error:"",allowCustomProvider:!0,allowCustomModel:!0,allowGatewayDefault:!0,gatewayDefaultLabel:"(gateway default)",onChange:v=>r(C=>({...C,maintenance_ai_provider:v.provider,maintenance_ai_model:v.model}))}),s.jsx("div",{className:"settings_subhead",children:"Skills"}),O===null?s.jsx("div",{className:"settings_row_help",children:M?Y?"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)."}):O.length?s.jsx("div",{className:"settings_choice_list",children:O.map(v=>{const C=n.assistant_skill_names.includes(v.name);return s.jsx(cT,{name:v.name,version:v.version,description:v.description,checked:C,onChange:I=>r(B=>({...B,assistant_skill_names:I?Array.from(new Set([...B.assistant_skill_names,v.name])):B.assistant_skill_names.filter(Z=>Z!==v.name)}))},v.name)})}):s.jsx("div",{className:"settings_row_help",children:"The gateway serves an empty skills inventory."}),s.jsx("div",{className:"settings_row_help",children:"Selected skills ride the assistant's runs once the gateway's skills-attachment lane serves them; the selection persists here meanwhile."}),s.jsx("div",{className:"settings_subhead",children:"MCP servers"}),s.jsx("div",{className:"settings_row_help",style:{marginTop:0},children:"Remote tool endpoints the assistant may call. The gateway does not serve an MCP inventory yet — one manual endpoint is supported (advanced / potentially dangerous: it executes tool waits from this browser)."}),s.jsxs("div",{className:"settings_mcp_row",children:[s.jsx("input",{className:"mono",value:n.worker_url,onChange:v=>r(C=>({...C,worker_url:v.target.value})),placeholder:"https://your-mcp-worker-endpoint"}),s.jsx("input",{className:"mono",type:"password",value:n.worker_token,onChange:v=>r(C=>({...C,worker_token:v.target.value})),placeholder:"Bearer token (optional)"}),s.jsx("span",{className:`chip ${n.worker_url.trim()?"ok":"muted"}`,children:n.worker_url.trim()?"configured":"none"})]})]})]}),s.jsxs("section",{className:"pane","data-settings-section":"voice",children:[s.jsx("div",{className:"pane_header",children:s.jsx("span",{className:"pane_title",children:"Voice"})}),s.jsx("div",{className:"pane_body settings_body",children:s.jsx(bA,{gateway:M?De:null,connected:M,defaults:Jn,value:pi,onChange:Bn})})]})]})}):null,e==="launch"?s.jsx("div",{className:"page page_scroll",children:s.jsx("div",{className:"page_inner constrained",children:s.jsxs("div",{className:"card",children:[s.jsx(lA,{mode:fe,automate_available:Te.available,automate_reason:Te.reason,on_change:ge}),fe==="automate"&&!Te.available&&M?s.jsx("div",{className:"warn_callout",role:"note",children:Te.reason}):null,fe==="automate"&&Pe.length?s.jsx("div",{className:"help_text",role:"note",children:Pe.map(v=>s.jsx("div",{children:v},v))}):null,M?null:s.jsxs("div",{className:"warn_callout",children:["Not connected."," ",s.jsx("button",{className:"btn primary",onClick:()=>F.openModal(),children:"Sign in"})," ","to launch workflows on this gateway."]}),fe==="automate"?s.jsx("div",{className:"section_title",children:"What"}):null,s.jsx("div",{className:"launch_workflow_bar",children:s.jsx(jb,{id:"launch-workflow-picker",className:"launch_workflow_picker",interfaceId:null,defaultInterface:pc,ariaLabel:"Workflow",workflows:Pl,value:nv(ir,((Wi=Pl.data)==null?void 0:Wi.entries)??[]),currentLabel:ir&&!nv(ir,((Ql=Pl.data)==null?void 0:Ql.entries)??[])?{name:kr[xr]||xr}:null,unavailableReason:M?D?"Loading workflows…":null:"Sign in to load workflows.",onChange:(v,C)=>{const I=L$(v,C);I&&Md(I)}})}),s.jsxs("div",{className:"field",children:[Yn!=null&&Yn.description?s.jsx("div",{className:"help_text muted",style:{fontSize:"var(--font-size-sm)",marginTop:"6px"},children:String(Yn.description)}):null,K?s.jsx("div",{className:"help_text muted",style:{fontSize:"var(--font-size-sm)"},children:"Loading workflow…"}):null,te?s.jsx("div",{className:"mono",style:{color:"rgba(239, 68, 68, 0.9)",fontSize:"var(--font-size-sm)"},children:te}):null]}),s.jsx("div",{className:"section_divider"}),s.jsx("div",{className:"section_title",children:"Inputs"}),ir?Ot===null?s.jsxs("div",{className:"log_item",style:{borderColor:"rgba(239, 68, 68, 0.35)",marginTop:"10px"},children:[s.jsxs("div",{className:"meta",children:[s.jsx("span",{className:"mono",children:"input error"}),s.jsx("span",{className:"mono",children:Rt()})]}),s.jsx("div",{className:"body mono",children:"Invalid input JSON — reselect the workflow to reset its inputs."})]}):kd?s.jsx("div",{className:"launch_inputs",children:(()=>{const v=pt||gt,C=[],I=[];for(const X of Ba){if(!X||typeof X!="object")continue;const G=String(X.id||"").trim();if(!G||fe==="automate"&&m0.includes(G))continue;const se=String(X.type||"").trim().toLowerCase();se==="tools"||se==="skills"||se==="mcp"||se==="mcp_servers"||G==="skills"||G==="mcp"||G==="mcp_servers"||se==="array"||Ol(se)||G==="prompt"||G==="system"?C.push(X):I.push(X)}const B=X=>String(X||"").trim().replace(/_/g," ").replace(/\b\w/g,G=>G.toUpperCase()),Z=(X,G)=>{const se=String(X.id||"").trim();if(!se)return null;const Ie=String(X.label||se).trim()||se,ye=Ie===se?B(se):Ie,ke=String(X.type||"").trim().toLowerCase(),Me=Object.prototype.hasOwnProperty.call(X,"default"),He=Me?X.default:void 0,Xe=Me?typeof He=="string"?He:dr(He,80):"",Ye=Ot==null?void 0:Ot[se],Ze=Me?`${Xe}`:"";if(ke==="tools"){if(fe==="automate"&&se==="tools")return null;const Ke=Array.isArray(Ye)?Ye.map(Tn=>String(Tn||"").trim()).filter(Boolean):[],wt=Array.isArray(He)?He.map(Tn=>String(Tn||"").trim()).filter(Boolean):[],kn=Array.from(new Set([...Dl,...Ke,...wt])).sort();return s.jsxs("div",{className:"launch_field_wide",children:[s.jsx("label",{className:"launch_label",children:ye}),s.jsx(ig,{options:kn,value:Ke,disabled:v,placeholder:"(no tools selected)",onChange:Tn=>Ln(se,Tn)})]},se)}if(ke==="skills"||se==="skills")return null;if(ke==="mcp"||ke==="mcp_servers"||se==="mcp"||se==="mcp_servers"){const Ke=Array.isArray(Ye)?Ye.map(Tn=>String(Tn||"").trim()).filter(Boolean):[];if(ie===null&&!Ke.length)return s.jsxs("div",{className:"launch_field_wide",children:[s.jsx("label",{className:"launch_label",children:ye}),s.jsx("div",{className:"help_text muted",children:"This gateway does not serve an MCP server inventory yet — MCP selection lights up here when it ships."})]},se);const wt=(ie||[]).map(Tn=>Tn.name),kn=Array.from(new Set([...wt,...Ke])).sort();return s.jsxs("div",{className:"launch_field_wide",children:[s.jsx("label",{className:"launch_label",children:ye}),s.jsx(ig,{options:kn,value:Ke,disabled:v,placeholder:"(no MCP servers selected)",onChange:Tn=>Ln(se,Tn)})]},se)}if(ke==="provider"||ke==="provider_text"){const Ke=typeof Ye=="string"?String(Ye):"";return s.jsxs("div",{className:G||"launch_field",children:[s.jsx("label",{className:"launch_label",children:ye}),s.jsxs("select",{value:Ke,onChange:wt=>Ln(se,wt.target.value),disabled:v,children:[s.jsx("option",{value:"",children:Ze||"(select)"}),zi.map(wt=>s.jsx("option",{value:wt,children:wt},wt))]})]},se)}if(ke==="model"||ke==="model_text"){const Ke=typeof Ye=="string"?String(Ye):"",wt=String((Ot==null?void 0:Ot.provider)||"").trim(),kn=wt?Pt[wt]:void 0,Tn=kn&&Array.isArray(kn.models)?kn.models.map(Ts=>String(Ts||"").trim()).filter(Boolean):[];return s.jsxs("div",{className:G||"launch_field",children:[s.jsx("label",{className:"launch_label",children:ye}),Tn.length?s.jsxs("select",{value:Ke,onChange:Ts=>Ln(se,Ts.target.value),disabled:v,children:[s.jsx("option",{value:"",children:Ze||"(select)"}),Tn.map(Ts=>s.jsx("option",{value:Ts,children:Ts},Ts))]}):s.jsx("input",{value:Ke,onChange:Ts=>Ln(se,Ts.target.value),placeholder:Ze||"model id",disabled:v})]},se)}if(ke==="boolean"){const Ke=typeof Ye=="boolean"?Ye?"true":"false":"";return s.jsxs("div",{className:G||"launch_field",children:[s.jsx("label",{className:"launch_label",children:ye}),s.jsxs("select",{value:Ke,onChange:wt=>{const kn=String(wt.target.value||"").trim();kn?Ln(se,kn==="true"):Ln(se,void 0)},disabled:v,children:[s.jsx("option",{value:"",children:Ze||"(default)"}),s.jsx("option",{value:"true",children:"Yes"}),s.jsx("option",{value:"false",children:"No"})]})]},se)}if(ke==="number"){const Ke=typeof Ye=="number"&&Number.isFinite(Ye)?String(Ye):"";return s.jsxs("div",{className:G||"launch_field",children:[s.jsx("label",{className:"launch_label",children:ye}),s.jsx("input",{type:"number",value:Ke,onChange:wt=>{const kn=String(wt.target.value||"").trim();if(!kn){Ln(se,void 0);return}const Tn=Number(kn);Number.isFinite(Tn)&&Ln(se,Tn)},placeholder:Ze,disabled:v})]},se)}if(ke==="array"){const Ke=Array.isArray(Ye)?Ye.map(wt=>String(wt||"").trim()).filter(Boolean).join(`
|
|
160
|
-
`):"";return s.jsxs("div",{className:"launch_field_wide",children:[s.jsx("label",{className:"launch_label",children:ye}),s.jsx("textarea",{className:"mono",value:Ke,onChange:wt=>{const kn=String(wt.target.value||"").split(/\r?\n/g).map(Tn=>String(Tn||"").trim()).filter(Boolean);Ln(se,kn.length?kn:void 0)},placeholder:Ze||"(one item per line)",rows:2,disabled:v})]},se)}if(Ol(ke)){const Ke=typeof hn[se]=="string"?hn[se]:"",wt=String(Kr[se]||"").trim();return s.jsxs("div",{className:"launch_field_wide",children:[s.jsxs("label",{className:"launch_label",children:[ye," ",s.jsx("span",{className:"launch_label_type",children:ke})]}),s.jsx("textarea",{className:"mono",value:Ke,onChange:kn=>{const Tn=String(kn.target.value??"");Ds(qs=>({...qs,[se]:Tn}));const Ts=Tn.trim();if(!Ts){ss(qs=>{const ni={...qs};return delete ni[se],ni}),Ln(se,void 0);return}try{const qs=JSON.parse(Ts);ss(ni=>{const ec={...ni};return delete ec[se],ec}),Ln(se,qs)}catch(qs){ss(ni=>({...ni,[se]:String((qs==null?void 0:qs.message)||qs||"Invalid JSON")}))}},placeholder:Ze||"{...}",rows:3,disabled:v}),wt?s.jsx("div",{className:"launch_field_error",children:wt}):null]},se)}const an=typeof Ye=="string"?String(Ye):"";return se==="prompt"||se==="system"?s.jsxs("div",{className:"launch_field_wide",children:[s.jsx("label",{className:"launch_label",children:ye}),s.jsx("textarea",{value:an,onChange:Ke=>Ln(se,Ke.target.value),placeholder:Ze||(se==="prompt"?"What should the agent do?":"System instructions (optional)"),rows:3,disabled:v})]},se):s.jsxs("div",{className:G||"launch_field",children:[s.jsx("label",{className:"launch_label",children:ye}),s.jsx("input",{value:an,onChange:Ke=>Ln(se,Ke.target.value),placeholder:Ze,disabled:v})]},se)};return C.sort((X,G)=>{const se={system:0,prompt:1,tools:2};return(se[String(X.id||"")]??10)-(se[String(G.id||"")]??10)}),s.jsxs(s.Fragment,{children:[C.map(X=>Z(X)),I.length>0?s.jsx("div",{className:"launch_grid",children:I.map(X=>Z(X,"launch_grid_cell"))}):null]})})()}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"field",style:{marginTop:"10px"},children:[s.jsx("label",{children:"Prompt (common)"}),s.jsx("textarea",{value:Gc,onChange:v=>Ln("prompt",v.target.value),placeholder:"What do you want the workflow/agent to do?",rows:3,disabled:pt||gt})]}),s.jsxs("div",{className:"row",children:[s.jsx("div",{className:"col",children:s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Provider (common)"}),s.jsx("input",{value:Ua,onChange:v=>Ln("provider",v.target.value),placeholder:"lmstudio / ollama / openai / ...",disabled:pt||gt})]})}),s.jsx("div",{className:"col",children:s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Model (common)"}),s.jsx("input",{value:Wa,onChange:v=>Ln("model",v.target.value),placeholder:"qwen/qwen3-next-80b / gpt-4.1 / ...",disabled:pt||gt})]})})]})]}):s.jsx("div",{className:"help_text muted",style:{marginTop:"8px"},children:"Select a workflow above to configure inputs."}),fe==="automate"?s.jsxs(s.Fragment,{children:[s.jsx(cA,{form:We,email_status:zs.email_status,on_open_my_email:vr,tools:Yx(Ot||{})??void 0,available_tools:Dl,on_tools_change:v=>A(JSON.stringify(Jx(Ot||{},v),null,2)),disabled:le,on_change:v=>ut(C=>({...C,...v})),workspaces:Sr}),s.jsx(uA,{form:We,disabled:le,on_change:v=>ut(C=>({...C,...v}))}),tn,Vn]}):s.jsxs(s.Fragment,{children:[tn,as,Vn]}),s.jsx("div",{className:"section_divider"}),Xi?s.jsxs("div",{className:"observe_context_card error",style:{marginBottom:"10px"},children:[s.jsx("span",{className:"chip mono danger",children:"error"}),s.jsx("span",{className:"mono",children:Xi})]}):null,fe==="automate"&&Fe.length?s.jsx("ul",{className:"automate_errors",role:"alert",children:Fe.map(v=>s.jsx("li",{children:v},v))}):null,fe==="automate"&&$e?s.jsxs("div",{className:"observe_context_card error",role:"alert","data-code":$e.code,style:{marginBottom:"10px"},children:[s.jsx("span",{className:"chip mono danger",children:$e.code}),s.jsxs("span",{children:[s.jsx("strong",{children:qm($e).title})," ",qm($e).detail,$e.field?s.jsxs("span",{className:"mono",children:[" (",$e.field,")"]}):null]})]}):null,s.jsx("div",{className:"launch_actions_bar launch_actions_stack",children:(()=>{const v=fe==="automate",C=M?ir?Ot===null?"Inputs contain invalid JSON":v&&!Te.available?"Automations unavailable on this gateway":pt||gt?"Attaching to a run…":D||K?"Loading…":le?"Submitting…":"":"Select a workflow":"Sign in first";return s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"launch_submit_btn",onClick:()=>void Ch(),disabled:!!C,title:C,children:v?le?"Creating…":"Create automation":pt?"Launching…":"Launch now"}),C&&!le&&!pt?s.jsx("span",{className:"mono muted launch_disabled_reason",children:C}):null]})})()})]})})}):null,e==="automations"?s.jsx(aT,{workflowPickerOptions:{interfaceId:null,defaultInterface:pc,workflows:Pl,request:(v,C)=>De.get_gateway_json(v,C.signal)},availableTools:Dl,ctl:fn,gateway:De,active:e==="automations"&&M,available:Te,h:Nr,voice_session_id:W,workspace_request:Jo,host:{on_open_run:v=>ls(v),...vr?{on_open_my_email:vr}:{},on_open_session:(v,C)=>{en({ts:Rt(),kind:"info",title:"Discussion started",preview:At(C),data:v})}}}):null,e==="runtime"?s.jsx(_M,{gateway_connected:M,tab:jl,runs:gi,active_runs:Yh,all_artifacts:ad,artifacts:oa,artifact_total_count:cd,artifact_total_bytes:ud,artifact_facets:Nl,artifact_type_facets:fd,artifact_page:cr,artifact_page_size:Mm,artifact_groups:Kh,selected_artifact:el,embedded_preview:Dr,loading:Fc,error:_h,query:Cl,scope:fo,type_filters:ho,date_filter:Bc,group_by:La,sort_by:Ia,artifact_run_filter:Li,audit_log_text:Ml,audit_log_meta:Oi,audit_log_loading:Uc,audit_log_error:P_,workflow_label_by_id:kr,run_by_id:xs,selected_run_id:yi,session_id:Hd,runtime_log_source:Di,runtime_log_query:Wc,runtime_ledger_log_items:Fr,runtime_ledger_log_meta:Yo,runtime_ledger_log_loading:Fi,runtime_ledger_log_error:wh,on_tab_change:Aa,on_query_change:gh,on_scope_change:Ma,on_session_filter_change:zc,on_type_filters_change:hd,on_date_filter_change:yh,on_group_by_change:O_,on_sort_by_change:mo,on_artifact_page_change:md,on_artifact_run_filter_change:v=>{const C=String(v||"").trim();Ho(C),C&&Ii(C),C&&fo!=="run"&&Ma("run")},on_refresh_artifacts:()=>void Wd(),on_refresh_audit:()=>void qd(),on_refresh_runtime_ledger:v=>void fu(v),on_runtime_log_source_change:Fa,on_runtime_log_query_change:qc,on_select_run:v=>{const C=String(v||"").trim();Ii(C);const I=C&&xs[C]||null,B=String((I==null?void 0:I.session_id)||"").trim();B&&zc(B)},on_select_artifact:El,on_preview_artifact:v=>void Cs(v),on_download_artifact:v=>void D_(v),on_open_run:v=>{Ii(String(v||"").trim()),t("observe"),so("ledger"),vo(v)},on_open_ledger:v=>{Ii(String(v||"").trim()),t("observe"),so("ledger"),vo(v)},on_refresh_runs:()=>void Bs(De,{force:!0}),on_reconnect:()=>void or({open_modal_if_needed:!0}),on_open_settings:()=>t("settings"),memory_panel:M?s.jsx(iO,{gateway:De,selected_run_id:tr,selected_session_id:Hd}):null}):null,e==="observe"?s.jsx("div",{className:"page observe_page",children:s.jsxs("div",{className:`observatory_layout${nd?"":" list_collapsed"}`,children:[s.jsx(gM,{sections:vs,selected_run_id:u,root_run_id:h,search:ed,filter:Tc,group_by:td,loading:bn,connected:M,on_sign_in:()=>F.openModal(),total_runs:gi.length,workflow_label_by_id:kr,automation_titles:vh,on_search:E_,on_filter:$_,on_group_by:A_,on_refresh:()=>void Bs(),on_select:(v,C)=>{vo(v,{root_run_id:C||v}),Jl()},list:{open:nd,on_toggle:ah}}),s.jsxs("div",{className:"observatory_main",children:[s.jsxs("div",{className:"observe_toolbar",children:[s.jsxs("div",{className:"observe_toolbar_row",children:[u.trim()?s.jsxs("div",{className:"observe_run_identity",title:u.trim(),children:[s.jsx("span",{className:"observe_run_name",children:kr[String((Gt==null?void 0:Gt.workflow_id)||"")]||String((Gt==null?void 0:Gt.workflow_id)||"").trim()||sn(u.trim(),22)}),s.jsx("span",{className:"chip mono muted",children:sn(u.trim(),14)}),s.jsx("span",{className:`chip ${xc(Yl||Xa,ia)}`,title:String((ia==null?void 0:ia.headline)||""),children:Yl||Xa||"unknown"})]}):w?s.jsx("span",{className:"observe_run_identity_empty observe_run_link_missing",role:"alert",children:KE(w)}):s.jsx("span",{className:"observe_run_identity_empty",children:"No run selected"}),s.jsx("span",{className:"observe_toolbar_spacer"}),u.trim()?s.jsxs(s.Fragment,{children:[Us?s.jsx(dT,{active:!ko,unavailableReason:Wh,busy:pt||gt,onChange:v=>{if(!v){yr("pause"),Ys(""),rs(""),gr(!0);return}Xc("resume")}}):s.jsx("button",{className:"btn",onClick:()=>{if(ou==="pause"){yr("pause"),Ys(""),rs(""),gr(!0);return}Xc("resume")},disabled:Fd,children:Dd}),zd?s.jsx("button",{className:"btn primary",onClick:()=>void Eh(),disabled:pt||gt||ei||ko,children:"Run now"}):null,s.jsx("button",{className:"btn danger",onClick:()=>{yr("cancel"),Ys(""),rs(""),gr(!0)},disabled:pt||gt||ei,children:"Cancel"}),s.jsx("button",{className:"btn btn_icon",onClick:Ya,title:"Clear the run view",children:s.jsx(Be,{name:"x",size:14})})]}):null]}),u.trim()&&!ei?s.jsx("div",{className:"observe_steer_row",children:s.jsx(LS,{runId:u.trim(),parked:Ja,submit:(v,C)=>De.submit_command({command_id:`steer-${Rs()}`,run_id:v,type:"inject_guidance",payload:{guidance:C},client_id:"web_pwa"}).then(I=>({accepted:!!(I!=null&&I.accepted),duplicate:!!(I!=null&&I.duplicate),seq:Number((I==null?void 0:I.seq)??0)})),onSent:()=>en({ts:Rt(),kind:"info",title:"Steer queued",preview:"inject_guidance submitted — delivery shows as abstract.steer_seen in the ledger"})})}):null,Ja||Us||wl?s.jsxs("div",{className:"observe_toolbar_context",children:[Ja?s.jsxs("div",{className:"observe_context_card info",children:[s.jsxs("div",{className:"observe_context_label",children:[(()=>{const v=Us?ko?"suspended":"scheduled":"waiting";return s.jsx("span",{className:`chip ${xc(v)}`,children:v})})(),s.jsx("span",{className:"muted",children:os||"unknown"})]}),s.jsxs("div",{className:"observe_context_body",children:[Es?s.jsxs("span",{className:"mono",title:Es,children:[s.jsx("span",{className:"muted",children:"wait_key"}),": ",sn(Es,46)]}):null,os==="event"&&nu?s.jsxs("span",{className:"mono",children:[s.jsx("span",{className:"muted",children:"event"}),": ",nu]}):null,os==="subworkflow"&&zr?s.jsxs("span",{className:"mono",children:[s.jsx("span",{className:"muted",children:"child"}),": ",sn(zr,18)]}):null,os==="until"&&jr?s.jsxs("span",{className:"mono",title:jr,children:[s.jsx("span",{className:"muted",children:"until"}),": ",sn(jr,46)]}):null,os==="until"&&jr?s.jsx("span",{className:"mono muted",children:(()=>{const v=qn(jr),C=v!==null?new Date(v).toLocaleString():jr,I=v!==null?ev(v-Date.now()):"";return`Next at ${C}${I?` (in ${I})`:""}`})()}):null]}),os==="subworkflow"&&zr?s.jsxs("div",{className:"observe_context_actions",children:[s.jsx("button",{className:"btn primary",onClick:async()=>{f(zr),await Wl(zr)},disabled:pt,children:"Attach to child"}),h.trim()&&h.trim()!==u.trim()?s.jsx("button",{className:"btn",onClick:async()=>{f(h.trim()),await Wl(h.trim())},disabled:pt,children:"Back to root"}):null]}):null]}):null,Us?s.jsxs("div",{className:"observe_context_card muted",children:[s.jsxs("div",{className:"observe_context_label",children:[s.jsx("span",{className:"chip muted",children:"schedule"}),s.jsx("span",{className:"muted",children:iu?`every ${ta}`:"once"})]}),s.jsxs("div",{className:"observe_context_body",children:[ta?s.jsxs("span",{className:"mono",children:[s.jsx("span",{className:"muted",children:"interval"}),": ",ta]}):null,s.jsxs("span",{className:"mono",children:[s.jsx("span",{className:"muted",children:"share ctx"}),": ",Od?"yes":"no"]}),typeof Pd=="number"?s.jsxs("span",{className:"mono",children:[s.jsx("span",{className:"muted",children:"repeats"}),": ",Pd]}):null]}),Vl!==null?s.jsxs("div",{className:"observe_context_budget",children:[s.jsxs("span",{className:"mono muted",children:[typeof Bd=="number"&&typeof au=="number"?`${Bd.toLocaleString()} / ${au.toLocaleString()}`:"",` • ${Math.round(Math.max(0,Math.min(1,Vl))*100)}%`]}),s.jsx("div",{className:"observe_budget_bar",children:s.jsx("div",{className:`observe_budget_fill ${Vl>=.9?"danger":Vl>=.75?"warn":"ok"}`,style:{width:`${Math.round(Math.max(0,Math.min(1,Vl))*100)}%`}})})]}):null,s.jsxs("div",{className:"observe_context_actions",children:[iu?s.jsx("button",{className:"btn",onClick:()=>{zn(ta||""),Hn(!0),ai(""),Mo(!0)},disabled:pt||Rn,children:"Edit schedule"}):null,iu?s.jsx("button",{className:"btn",onClick:()=>{hs(""),Ks(!0)},disabled:pt||Mr,children:"Compact context"}):null,s.jsx("button",{className:"btn",onClick:()=>void Ka(u.trim()).catch(v=>on(String((v==null?void 0:v.message)||v))),disabled:pt||!u.trim(),title:"Open Launch → Automate prefilled from this schedule (this schedule is not changed)",children:"Recreate as automation"})]})]}):null,wl?s.jsxs("div",{className:"observe_context_card error",children:[s.jsx("span",{className:"chip danger",children:"error"}),s.jsx("span",{className:"mono",children:wl})]}):null]}):null]}),s.jsxs("div",{className:"card panel_card card_scroll observe_viewer observe_viewer_full",ref:sd,children:[s.jsxs("div",{className:"tab_bar",children:[s.jsxs("div",{role:"tablist","aria-label":"Run views",className:"observe_tablist",children:[s.jsx("button",{role:"tab","aria-selected":er==="ledger",className:`tab ${er==="ledger"?"active":""}`,onClick:()=>Vd("ledger"),children:"Ledger"}),s.jsx("button",{role:"tab","aria-selected":er==="graph",className:`tab ${er==="graph"?"active":""}`,onClick:()=>Vd("graph"),children:"Flow"}),s.jsx("button",{role:"tab","aria-selected":er==="chat",className:`tab ${er==="chat"?"active":""}`,onClick:()=>Vd("chat"),children:"Ask"})]}),er==="ledger"&&(cn.length>0||ns.length>0)?s.jsx("div",{className:"tab_bar_controls",children:s.jsx("button",{className:"seg_action",disabled:!cn.length&&!ns.length,title:"Copy full ledger as JSONL",onClick:()=>{const I=[...cn.map(X=>({run_id:u.trim()||X.record.run_id||"",cursor:X.cursor,record:X.record})),...ns.map(X=>({run_id:X.run_id,cursor:X.cursor,record:X.record}))].map(X=>{var Ie,ye;const G=String(((Ie=X.record)==null?void 0:Ie.ended_at)||((ye=X.record)==null?void 0:ye.started_at)||"").trim(),se=qn(G);return{...X,_ms:se??0}});I.sort((X,G)=>(X._ms||0)-(G._ms||0));const Z=(I.length>5e3?I.slice(I.length-5e3):I).map(({_ms:X,...G})=>JSON.stringify(G)).join(`
|
|
161
|
-
`);In(Z)},children:"Copy JSONL"})}):null,er==="graph"?s.jsxs("div",{className:"tab_bar_controls",children:[s.jsx("button",{className:`seg_action ${$a?"active":""}`,"aria-pressed":$a,onClick:()=>R_(v=>!v),children:"Subflows"}),s.jsx("button",{className:`seg_action ${od?"active":""}`,"aria-pressed":od,onClick:()=>L_(v=>!v),children:"Path"}),lu.length?s.jsx("select",{className:"mono seg_select",value:ui,onChange:v=>Ai(String(v.target.value||"")),disabled:!!ws.trim()||!N.trim()||Ic,children:lu.map(v=>s.jsx("option",{value:v,children:v},v))}):null]}):null]}),er==="ledger"?u.trim()?s.jsxs("div",{className:"rs_page",children:[s.jsx(M$,{status:Yl||Xa||"unknown",duration:Gt?vc(Gt):"",facts:w$(y$(sa)),error:Lf(Gt)||String((he==null?void 0:he.error)||"").trim(),answer:Hh||String((na==null?void 0:na.text)||"").trim(),waiting_for_user:!!(Vt!=null&&Vt.wait_key)&&String((Vt==null?void 0:Vt.reason)||"")==="user",on_answer_wait:()=>Xs(""),workspace_root:rd,on_reveal_workspace:()=>void Ul(),speak:M?s.jsx(EA,{voice:Nn,speak_key:`outcome:${u.trim()}`,text:Lf(Gt)||String((he==null?void 0:he.error)||"").trim()||Hh||String((na==null?void 0:na.text)||"").trim(),error:ja}):null,on_open_artifacts:()=>{const v=String(u||"").trim();v&&(Ii(v),Ho(v),Ma("run")),Aa("artifacts"),t("runtime")}}),C_.filter(v=>v.kind==="error"&&!v.data).slice(0,3).map(v=>s.jsxs("p",{className:"rs_notice",children:[v.title,": ",v.preview]},v.id)),s.jsx(T$,{items:sa,run_id:As,run_options:U_,run_llm_counts:cu,on_select_run:v=>dh(v),state:Na,on_state:uu,node_label:(v,C)=>{const I=C?(Zr==null?void 0:Zr[An(v,C)])||(Zr==null?void 0:Zr[C]):null;return String((I==null?void 0:I.label)||C||"").trim()},on_copy:v=>void In(v),on_open_run:v=>void vo(v,{root_run_id:h||u||v})})]}):s.jsx("div",{className:"empty_state_inline",children:"Select a run on the left to inspect it — or start one from Launch."}):null,er==="graph"?s.jsxs(s.Fragment,{children:[id?s.jsxs("div",{className:"log_item log_item_danger",children:[s.jsxs("div",{className:"meta",children:[s.jsx("span",{children:"graph error"}),s.jsx("span",{className:"mono",children:Rt()})]}),s.jsx("div",{className:"body mono",children:id})]}):null,Ic?s.jsxs("div",{className:"log_item log_item_info",children:[s.jsxs("div",{className:"meta",children:[s.jsx("span",{children:"loading"}),s.jsx("span",{className:"mono",children:ws.trim()?ws.trim():ui})]}),s.jsx("div",{className:"body mono",children:"Loading graph…"})]}):null,s.jsx("div",{className:"graph_panel",children:s.jsx(LM,{flow:Ca,flow_by_id:Rc,expand_subflows:$a,simplify:!0,prefer_vertical:!0,vertical_compact:.78,schedule_next_in:Qa,schedule_interval:ta,node_last_ms:qh,active_node_id:B_,recent_nodes:fh,visited_nodes:hh,highlight_path:od,now_ms:I_})})]}):null,er==="chat"?s.jsxs("div",{className:"ask_tab log_scroll",style:{marginTop:"6px"},children:[s.jsxs("div",{className:"ask_header",children:[s.jsx("span",{className:"ask_title",children:"Ask about this run"}),s.jsx("span",{className:"chip muted",title:"Model comes from Settings → Assistant (blank = gateway default)",children:(n.maintenance_ai_provider.trim()||"gateway")+" / "+(n.maintenance_ai_model.trim()||"default")}),s.jsx("span",{className:"pane_spacer"}),s.jsx("span",{className:"ask_hint",children:"Read-only · grounded in this run + subflows"})]}),s.jsxs("details",{className:"ask_manage",children:[s.jsx("summary",{children:"History & export"}),s.jsxs("div",{className:"field",style:{marginTop:"10px"},children:[s.jsxs("div",{className:"actions",style:{justifyContent:"space-between",alignItems:"center",gap:"10px",flexWrap:"wrap",marginTop:0},children:[s.jsx("div",{style:{flex:1,minWidth:260},children:s.jsx(si,{value:yl,options:Zu,placeholder:$i?"Loading…":Zu.length?"Select a saved discussion…":"(none saved)",disabled:!u.trim()||!M||!Zu.length,loading:$i,searchable:!0,clearable:!0,onChange:v=>{Ec(v),Oo("")}})}),s.jsxs("div",{className:"actions",style:{justifyContent:"flex-end",marginTop:0},children:[s.jsx("button",{className:"btn",type:"button",disabled:!yl.trim()||!M||$c,onClick:()=>void Rh(),children:$c?"Loading…":"Load"}),s.jsx("button",{className:"btn",type:"button",disabled:!Ee.length||q||Ut||$c,onClick:()=>{Ge([]),_t(null),Zs(""),li(""),Ft(""),En(""),Qn("")},children:"Clear"}),s.jsx("button",{className:"btn",type:"button",onClick:()=>void Qc(),disabled:!u.trim()||!M||$i,children:$i?"Refreshing…":"Refresh"})]})]}),s.jsxs("div",{className:"actions",style:{justifyContent:"flex-end",marginTop:"8px",flexWrap:"wrap"},children:[s.jsx("button",{className:"btn",type:"button",disabled:!Ee.length||!u.trim()||!M||Ut||!Xu,onClick:()=>void F_(),title:Xu?"":"No changes since last save",children:Ut?"Saving…":!Xu&&dn?"Saved":"Save discussion"}),s.jsx("button",{className:"btn",type:"button",disabled:!Ee.length,onClick:()=>Ld("download"),children:"Export Markdown"}),s.jsx("button",{className:"btn",type:"button",disabled:!Ee.length,onClick:()=>Ld("copy"),children:je==="copied"?"Copied":je==="failed"?"Copy failed":"Copy Markdown"})]}),dn?s.jsxs("div",{className:"chat_hint",children:["Last saved: ",_c(dn)]}):null,ms?s.jsx("div",{className:"chat_hint chat_hint_danger",children:ms}):null,ih?s.jsx("div",{className:"chat_hint chat_hint_danger",children:ih}):null,rh?s.jsx("div",{className:"chat_hint chat_hint_danger",children:rh}):null]})]}),Io?s.jsxs("div",{className:"log_item log_item_danger",children:[s.jsxs("div",{className:"meta",children:[s.jsx("span",{children:"error"}),s.jsx("span",{className:"mono",children:Rt()})]}),s.jsx("div",{className:"body mono",children:Io})]}):null,ja?s.jsxs("div",{className:"log_item log_item_danger",children:[s.jsxs("div",{className:"meta",children:[s.jsx("span",{children:"voice"}),s.jsx("span",{className:"mono",children:Rt()})]}),s.jsx("div",{className:"body mono",children:ja})]}):null,s.jsx("div",{className:"chat_messages",style:{marginTop:"10px"},children:s.jsx(sy,{messages:Ee,className:"log_scroll",after:s.jsx(qE,{history:yt}),afterKey:yt?`${yt.replayed_messages}:${yt.dropped_messages}`:null,messageProps:Nn.tts_supported&&M?{onSpeakToggle:Rd,getSpeakState:Mh,jsonCollapseAfterDepth:4}:{jsonCollapseAfterDepth:4},empty:s.jsx("div",{className:"chat_empty_hint",children:"Ask about this run (why failed, which tools, what happened in subflows)."})})}),s.jsxs("div",{className:"chat_composer",style:{marginTop:"10px"},children:[s.jsx(ry,{ref:xt,value:no,onChange:Zs,onSubmit:()=>void Th(),placeholder:"Ask about this run…",disabled:!u.trim()||!M||q,busy:q||Nn.voice_ptt_busy,busyLabel:Nn.voice_ptt_busy?"Transcribing…":"Thinking…",rows:3,sendButtonClassName:"btn primary",actions:s.jsx(S0,{voice:Nn,defaults:Jn.value,prefs:pi,blocked:M?q?"Wait for the answer.":null:"Connect to the gateway first."})}),w0()?null:s.jsx("div",{className:"mono muted","data-testid":"voice-https-hint",style:{fontSize:"var(--font-size-sm)",marginTop:"6px"},children:y0})]})]}):null,u.trim()?s.jsxs("div",{className:`status_bar ${Nc?"pulse":""}`,children:[s.jsx("strong",{children:"Run"}),":"," ",s.jsx("span",{className:"mono",children:Yl||Xa||"unknown"}),Vh&&Qa?s.jsxs("span",{className:"mono muted",children:[" • next in ",Qa]}):null,Ir?s.jsxs("span",{className:"mono muted",children:[" • ",Ir]}):null]}):null]})]})]})}):null,s.jsxs(cc,{open:Oa,title:Al||"Artifact",onClose:()=>{Pa(!1),_n(""),Tl(""),Ko(!1),po(null),Wt&&(URL.revokeObjectURL(Wt),Jr(""))},actions:s.jsx("button",{className:"btn",onClick:()=>{Pa(!1),_n(""),Tl(""),Ko(!1),po(null),Wt&&(URL.revokeObjectURL(Wt),Jr(""))},children:"Close"}),children:[sr?s.jsx("div",{className:"mono muted",style:{fontSize:"var(--font-size-sm)",marginBottom:"8px"},children:"Loading…"}):null,_d?s.jsx("div",{className:"mono",style:{color:"rgba(239, 68, 68, 0.9)",fontSize:"var(--font-size-sm)",marginBottom:"8px"},children:_d}):null,is==="image"&&Wt?s.jsx("img",{className:"runtime_preview_media",src:Wt,alt:Al||"Artifact preview"}):is==="audio"&&Wt?s.jsx(p_,{className:"runtime_preview_media",src:Wt,name:Al||void 0}):is==="video"&&Wt?s.jsx("video",{className:"runtime_preview_media",controls:!0,src:Wt}):s.jsx(H0,{artifact:Go,text:_o||"(empty)",className:"runtime_preview_text"})]}),To?s.jsxs(cc,{open:To,title:"Edit schedule",onClose:()=>{Mo(!1),zn(""),Hn(!0),ai(""),Fs(!1)},actions:s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"btn",onClick:()=>{Mo(!1),zn(""),Hn(!0),ai(""),Fs(!1)},disabled:pt||Rn,children:"Back"}),s.jsx("button",{className:"btn primary",onClick:async()=>{await $h({interval:Ro,apply_immediately:pr})||(Mo(!1),ai(""),Fs(!1))},disabled:pt||Rn||!Ro.trim(),children:"Save"})]}),children:[Zi?s.jsxs("div",{className:"log_item",style:{borderColor:"rgba(239, 68, 68, 0.35)",marginBottom:"10px"},children:[s.jsxs("div",{className:"meta",children:[s.jsx("span",{className:"mono",children:"error"}),s.jsx("span",{className:"mono",children:Rt()})]}),s.jsx("div",{className:"body mono",children:Zi})]}):null,s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Interval"}),s.jsx("input",{className:"mono",value:Ro,onChange:v=>zn(String(v.target.value||"")),placeholder:"20m / 1h / 0.5s / 250ms",disabled:pt||Rn}),s.jsxs("div",{className:"mono muted",style:{fontSize:"var(--font-size-sm)"},children:["Accepted units: ",s.jsx("span",{className:"mono",children:"ms"}),", ",s.jsx("span",{className:"mono",children:"s"}),", ",s.jsx("span",{className:"mono",children:"m"}),","," ",s.jsx("span",{className:"mono",children:"h"}),", ",s.jsx("span",{className:"mono",children:"d"}),". This updates the existing scheduled run in place (no context loss)."]})]}),s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Quick picks"}),s.jsx("div",{className:"actions",style:{gap:"8px",flexWrap:"wrap"},children:["15m","30m","1h","2h","6h","1d"].map(v=>s.jsx("button",{className:"btn",onClick:()=>zn(v),disabled:pt||Rn,children:v},v))})]}),s.jsx("div",{className:"field",children:s.jsx(hT,{checked:pr,busy:pt||Rn,onChange:Hn})})]}):null,ds?s.jsxs(cc,{open:ds,title:"Compact scheduled context",onClose:()=>{Ks(!1),hs(""),Rr(!1)},actions:s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"btn",onClick:()=>{Ks(!1),hs(""),Rr(!1)},disabled:pt||Mr,children:"Cancel"}),s.jsx("button",{className:"btn primary",onClick:async()=>{await Ah({preserve_recent:fs,compression_mode:Qi,focus:ba})||(Ks(!1),hs(""),Rr(!1))},disabled:pt||Mr,children:Mr?"Compacting…":"Compact"})]}),children:[Lo?s.jsxs("div",{className:"log_item",style:{borderColor:"rgba(239, 68, 68, 0.35)",marginBottom:"10px"},children:[s.jsxs("div",{className:"meta",children:[s.jsx("span",{className:"mono",children:"error"}),s.jsx("span",{className:"mono",children:Rt()})]}),s.jsx("div",{className:"body mono",children:Lo})]}):null,s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Preserve recent turns"}),s.jsx("input",{type:"number",min:1,value:String(fs),onChange:v=>xa(Math.max(1,parseInt(v.target.value||"6",10)||6)),disabled:pt||Mr})]}),s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Mode"}),s.jsxs("select",{value:Qi,onChange:v=>un(v.target.value),disabled:pt||Mr,children:[s.jsx("option",{value:"light",children:"light"}),s.jsx("option",{value:"standard",children:"standard"}),s.jsx("option",{value:"heavy",children:"heavy"})]})]}),s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Focus (optional)"}),s.jsx("input",{className:"mono",value:ba,onChange:v=>Sc(String(v.target.value||"")),placeholder:"e.g. important decisions, next steps…",disabled:pt||Mr})]})]}):null,eo?s.jsxs(cc,{open:eo,title:Ns==="cancel"?"Cancel run":Us?"Suspend schedule":"Pause run",onClose:()=>{gr(!1),Ys(""),rs("")},actions:s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"btn",onClick:()=>{gr(!1),Ys(""),rs("")},disabled:pt||gt,children:"Back"}),s.jsx("button",{className:`btn ${Ns==="cancel"?"danger":"primary"}`,onClick:async()=>{rs("");const v=await Xc(Ns,{reason:Lr});if(v){rs(v);return}gr(!1),Ys(""),rs("")},disabled:pt||gt,children:Ns==="pause"?Us?"Suspend":"Pause":"Cancel"})]}),children:[Ci?s.jsxs("div",{className:"log_item",style:{borderColor:"rgba(239, 68, 68, 0.35)",marginBottom:"10px"},children:[s.jsxs("div",{className:"meta",children:[s.jsx("span",{className:"mono",children:"error"}),s.jsx("span",{className:"mono",children:Rt()})]}),s.jsx("div",{className:"body mono",children:Ci})]}):null,s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Reason (optional)"}),s.jsx("input",{className:"mono",value:Lr,onChange:v=>Ys(v.target.value),placeholder:"reason…"})]})]}):null,su?s.jsxs(cc,{open:su,title:Oh,onClose:()=>{Es&&Xs(Es)},actions:s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"btn",onClick:()=>{so("ledger"),t("observe"),Jl(),Es&&Xs(Es)},disabled:!u.trim(),children:"Open ledger"}),s.jsx("button",{className:"btn",onClick:()=>Es&&Xs(Es),disabled:gt,children:"Dismiss"}),xo.length?s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"btn danger",disabled:gt,onClick:()=>eu({approved:!1}),children:"Reject"}),s.jsx("button",{className:"btn",disabled:gt,onClick:()=>eu({approved:!0}),children:"Approve only"}),s.jsx("button",{className:"btn primary",disabled:!Il||gt,onClick:()=>z_(xo),children:"Approve and execute"})]}):null]}),children:[s.jsxs("div",{className:"wait_context_panel",children:[s.jsxs("div",{className:"wait_context_header",children:[s.jsxs("div",{children:[s.jsx("div",{className:"run_hero_eyebrow",children:"What you need to do"}),s.jsx("strong",{children:Oh}),s.jsx("p",{children:Ph})]}),s.jsx(bc,{status:bo||"waiting"})]}),ea?s.jsxs("div",{className:`wait_request_card ${ys?"":"inferred"}`,children:[s.jsx("span",{children:zh}),s.jsx(Ix,{metadata:Dh}),s.jsx(Si,{text:ea}),ys?null:s.jsx("p",{className:"wait_context_note",children:"The runtime did not attach a specific question to this wait. This is inferred from the run input; verify the session turns and workflow steps before answering."})]}):s.jsx("div",{className:"warn_callout",children:"This wait did not provide a clear prompt or recoverable prior user request. Review the full run input and recent workflow steps before submitting a response."}),Fh.length?s.jsxs("section",{className:"wait_context_block wait_conversation_context",children:[s.jsx("span",{children:"Recent session turns"}),s.jsx("div",{className:"wait_turn_list",children:Fh.map((v,C)=>s.jsxs("div",{className:`wait_turn_row role_${v.role.replace(/[^a-z0-9_-]+/g,"_")}`,children:[s.jsxs("div",{className:"wait_turn_meta",children:[s.jsx("strong",{children:v.role==="assistant"?"Assistant":v.role==="user"||v.role==="human"?"User":v.role}),v.ts?s.jsx("span",{className:"mono muted",children:_c(v.ts)}):null]}),s.jsx(Ix,{metadata:v.runtime_metadata}),s.jsx(Si,{text:At(v.text,{max_chars:1200,max_lines:10})})]},`${v.role}:${C}`))})]}):null,s.jsxs("div",{className:"artifact_detail_grid",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Workflow"}),s.jsx("strong",{children:Gi(Qo,kr)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Run"}),s.jsx("strong",{className:"mono",children:sn(u.trim(),24)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Node"}),s.jsx("strong",{className:"mono",children:Qo.current_node||String((gs==null?void 0:gs.node_id)||"—")})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Elapsed"}),s.jsx("strong",{children:vc(Qo)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Session"}),s.jsx("strong",{className:"mono",children:Qo.session_id?sn(String(Qo.session_id),18):"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Wait key"}),s.jsx("strong",{className:"mono",children:sn(Es,28)})]})]}),Uh?s.jsxs("details",{className:"runtime_raw_details wait_full_input_details",open:!ea,children:[s.jsx("summary",{className:"mono muted",children:"Full run input JSON"}),s.jsx("div",{className:"wait_shared_json",children:s.jsx(Is,{value:Bh,collapseAfterDepth:4,showCopy:!0})})]}):null,s.jsxs("section",{className:"wait_context_block",children:[s.jsx("span",{children:"Recent workflow steps leading to this wait"}),s.jsxs("div",{className:"wait_event_list",children:[ru.map(v=>s.jsxs("div",{className:"wait_event_row",children:[s.jsxs("span",{className:"mono",children:["#",v.cursor]}),s.jsx("strong",{children:v.summary||v.effect_type||v.status||"event"}),s.jsx("span",{className:"mono muted",children:[v.node_id,v.status,_c(v.ts)].filter(Boolean).join(" · ")})]},`${v.cursor}:${v.node_id}:${v.status}`)),ru.length?null:s.jsx("div",{className:"empty_state_inline",children:"No ledger context is loaded. Open the ledger before deciding."})]})]})]}),xo.length?s.jsxs("div",{className:"wait_action_panel",children:[s.jsx("div",{className:"wait_action_intro",children:"Approve and execute runs the listed tool request through your configured worker. Approve only sends approval without local execution. Reject returns a denial. Cancel run stops the whole workflow run."}),s.jsx("div",{className:"wait_tool_list",children:xo.map((v,C)=>s.jsxs("div",{className:"wait_tool_card",children:[s.jsxs("div",{className:"wait_tool_header",children:[s.jsx("strong",{children:String((v==null?void 0:v.name)||"tool")}),s.jsxs("div",{className:"wait_tool_badges",children:[s.jsx("span",{className:"chip mono warn",children:"approval"}),P0(v).map(I=>s.jsxs("span",{className:"chip mono muted",title:O0,children:[I,"~"]},I))]})]}),s.jsx("div",{className:"wait_tool_args",children:s.jsx(Is,{value:(v==null?void 0:v.arguments)||{},collapseAfterDepth:3,showCopy:!0})})]},`${String((v==null?void 0:v.name)||"tool")}:${C}`))}),Il?null:s.jsx("div",{className:"warn_callout",children:"No tool worker is configured, so Observer cannot execute these calls directly."}),s.jsx("div",{className:"actions",children:s.jsx("button",{className:"btn danger",onClick:()=>void Zc(u.trim(),"Cancelled from wait prompt"),disabled:!u.trim()||gt,children:"Cancel whole run"})}),s.jsxs("details",{className:"runtime_raw_details",children:[s.jsx("summary",{className:"mono muted",children:"Diagnostics"}),s.jsx("div",{className:"wait_shared_json",children:s.jsx(Is,{value:Vt||{},collapseAfterDepth:3,showCopy:!0})})]})]}):s.jsxs("div",{className:"wait_action_panel",children:[s.jsx("div",{className:"wait_action_intro",children:"Submit only when the request above is clear. The response resumes this wait only; Cancel run attempts to stop the whole workflow and prevent further work."}),s.jsx("div",{className:"wait_prompt_text",children:ea||"No explicit prompt was provided. Open the ledger for context before responding."}),s.jsx(pM,{wait:Vt,disabled:gt,on_submit:v=>eu({response:v})}),s.jsx("div",{className:"actions",children:s.jsx("button",{className:"btn danger",onClick:()=>void Zc(u.trim(),"Cancelled from wait prompt"),disabled:!u.trim()||gt,children:"Cancel whole run"})}),s.jsxs("details",{className:"runtime_raw_details",children:[s.jsx("summary",{className:"mono muted",children:"Diagnostics"}),s.jsx("div",{className:"wait_shared_json",children:s.jsx(Is,{value:Vt||{},collapseAfterDepth:3,showCopy:!0})})]})]})]}):null]})]})]})}if("serviceWorker"in navigator){window.addEventListener("load",()=>{navigator.serviceWorker.register(VE).then(t=>t.update()).catch(()=>{})});let e=!1;navigator.serviceWorker.addEventListener("controllerchange",()=>{e||(e=!0,window.location.reload())})}eS();Kj.createRoot(document.getElementById("root")).render(s.jsx(xe.StrictMode,{children:s.jsx(OO,{})}));
|
|
162
|
-
//# sourceMappingURL=index-C1U8dkAL.js.map
|