@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
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
var $$=Object.defineProperty;var C$=(e,t,n)=>t in e?$$(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var yn=(e,t,n)=>C$(e,typeof t!="symbol"?t+"":t,n);(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))r(i);new MutationObserver(i=>{for(const a of i)if(a.type==="childList")for(const u of a.addedNodes)u.tagName==="LINK"&&u.rel==="modulepreload"&&r(u)}).observe(document,{childList:!0,subtree:!0});function n(i){const a={};return i.integrity&&(a.integrity=i.integrity),i.referrerPolicy&&(a.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?a.credentials="include":i.crossOrigin==="anonymous"?a.credentials="omit":a.credentials="same-origin",a}function r(i){if(i.ep)return;i.ep=!0;const a=n(i);fetch(i.href,a)}})();function iv(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Ig={exports:{}},sm={},Og={exports:{}},pn={};/**
|
|
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 mx;function E$(){if(mx)return pn;mx=1;var e=Symbol.for("react.element"),t=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),r=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),a=Symbol.for("react.provider"),u=Symbol.for("react.context"),c=Symbol.for("react.forward_ref"),d=Symbol.for("react.suspense"),m=Symbol.for("react.memo"),h=Symbol.for("react.lazy"),p=Symbol.iterator;function y(W){return W===null||typeof W!="object"?null:(W=p&&W[p]||W["@@iterator"],typeof W=="function"?W:null)}var w={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},x=Object.assign,k={};function b(W,Y,K){this.props=W,this.context=Y,this.refs=k,this.updater=K||w}b.prototype.isReactComponent={},b.prototype.setState=function(W,Y){if(typeof W!="object"&&typeof W!="function"&&W!=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,W,Y,"setState")},b.prototype.forceUpdate=function(W){this.updater.enqueueForceUpdate(this,W,"forceUpdate")};function S(){}S.prototype=b.prototype;function $(W,Y,K){this.props=W,this.context=Y,this.refs=k,this.updater=K||w}var A=$.prototype=new S;A.constructor=$,x(A,b.prototype),A.isPureReactComponent=!0;var E=Array.isArray,z=Object.prototype.hasOwnProperty,F={current:null},M={key:!0,ref:!0,__self:!0,__source:!0};function D(W,Y,K){var fe,ae={},ve=null,ge=null;if(Y!=null)for(fe in Y.ref!==void 0&&(ge=Y.ref),Y.key!==void 0&&(ve=""+Y.key),Y)z.call(Y,fe)&&!M.hasOwnProperty(fe)&&(ae[fe]=Y[fe]);var pe=arguments.length-2;if(pe===1)ae.children=K;else if(1<pe){for(var $e=Array(pe),De=0;De<pe;De++)$e[De]=arguments[De+2];ae.children=$e}if(W&&W.defaultProps)for(fe in pe=W.defaultProps,pe)ae[fe]===void 0&&(ae[fe]=pe[fe]);return{$$typeof:e,type:W,key:ve,ref:ge,props:ae,_owner:F.current}}function H(W,Y){return{$$typeof:e,type:W.type,key:Y,ref:W.ref,props:W.props,_owner:W._owner}}function q(W){return typeof W=="object"&&W!==null&&W.$$typeof===e}function I(W){var Y={"=":"=0",":":"=2"};return"$"+W.replace(/[=:]/g,function(K){return Y[K]})}var Z=/\/+/g;function R(W,Y){return typeof W=="object"&&W!==null&&W.key!=null?I(""+W.key):Y.toString(36)}function T(W,Y,K,fe,ae){var ve=typeof W;(ve==="undefined"||ve==="boolean")&&(W=null);var ge=!1;if(W===null)ge=!0;else switch(ve){case"string":case"number":ge=!0;break;case"object":switch(W.$$typeof){case e:case t:ge=!0}}if(ge)return ge=W,ae=ae(ge),W=fe===""?"."+R(ge,0):fe,E(ae)?(K="",W!=null&&(K=W.replace(Z,"$&/")+"/"),T(ae,Y,K,"",function(De){return De})):ae!=null&&(q(ae)&&(ae=H(ae,K+(!ae.key||ge&&ge.key===ae.key?"":(""+ae.key).replace(Z,"$&/")+"/")+W)),Y.push(ae)),1;if(ge=0,fe=fe===""?".":fe+":",E(W))for(var pe=0;pe<W.length;pe++){ve=W[pe];var $e=fe+R(ve,pe);ge+=T(ve,Y,K,$e,ae)}else if($e=y(W),typeof $e=="function")for(W=$e.call(W),pe=0;!(ve=W.next()).done;)ve=ve.value,$e=fe+R(ve,pe++),ge+=T(ve,Y,K,$e,ae);else if(ve==="object")throw Y=String(W),Error("Objects are not valid as a React child (found: "+(Y==="[object Object]"?"object with keys {"+Object.keys(W).join(", ")+"}":Y)+"). If you meant to render a collection of children, use an array instead.");return ge}function P(W,Y,K){if(W==null)return W;var fe=[],ae=0;return T(W,fe,"","",function(ve){return Y.call(K,ve,ae++)}),fe}function L(W){if(W._status===-1){var Y=W._result;Y=Y(),Y.then(function(K){(W._status===0||W._status===-1)&&(W._status=1,W._result=K)},function(K){(W._status===0||W._status===-1)&&(W._status=2,W._result=K)}),W._status===-1&&(W._status=0,W._result=Y)}if(W._status===1)return W._result.default;throw W._result}var te={current:null},X={transition:null},V={ReactCurrentDispatcher:te,ReactCurrentBatchConfig:X,ReactCurrentOwner:F};function ne(){throw Error("act(...) is not supported in production builds of React.")}return pn.Children={map:P,forEach:function(W,Y,K){P(W,function(){Y.apply(this,arguments)},K)},count:function(W){var Y=0;return P(W,function(){Y++}),Y},toArray:function(W){return P(W,function(Y){return Y})||[]},only:function(W){if(!q(W))throw Error("React.Children.only expected to receive a single React element child.");return W}},pn.Component=b,pn.Fragment=n,pn.Profiler=i,pn.PureComponent=$,pn.StrictMode=r,pn.Suspense=d,pn.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=V,pn.act=ne,pn.cloneElement=function(W,Y,K){if(W==null)throw Error("React.cloneElement(...): The argument must be a React element, but you passed "+W+".");var fe=x({},W.props),ae=W.key,ve=W.ref,ge=W._owner;if(Y!=null){if(Y.ref!==void 0&&(ve=Y.ref,ge=F.current),Y.key!==void 0&&(ae=""+Y.key),W.type&&W.type.defaultProps)var pe=W.type.defaultProps;for($e in Y)z.call(Y,$e)&&!M.hasOwnProperty($e)&&(fe[$e]=Y[$e]===void 0&&pe!==void 0?pe[$e]:Y[$e])}var $e=arguments.length-2;if($e===1)fe.children=K;else if(1<$e){pe=Array($e);for(var De=0;De<$e;De++)pe[De]=arguments[De+2];fe.children=pe}return{$$typeof:e,type:W.type,key:ae,ref:ve,props:fe,_owner:ge}},pn.createContext=function(W){return W={$$typeof:u,_currentValue:W,_currentValue2:W,_threadCount:0,Provider:null,Consumer:null,_defaultValue:null,_globalName:null},W.Provider={$$typeof:a,_context:W},W.Consumer=W},pn.createElement=D,pn.createFactory=function(W){var Y=D.bind(null,W);return Y.type=W,Y},pn.createRef=function(){return{current:null}},pn.forwardRef=function(W){return{$$typeof:c,render:W}},pn.isValidElement=q,pn.lazy=function(W){return{$$typeof:h,_payload:{_status:-1,_result:W},_init:L}},pn.memo=function(W,Y){return{$$typeof:m,type:W,compare:Y===void 0?null:Y}},pn.startTransition=function(W){var Y=X.transition;X.transition={};try{W()}finally{X.transition=Y}},pn.unstable_act=ne,pn.useCallback=function(W,Y){return te.current.useCallback(W,Y)},pn.useContext=function(W){return te.current.useContext(W)},pn.useDebugValue=function(){},pn.useDeferredValue=function(W){return te.current.useDeferredValue(W)},pn.useEffect=function(W,Y){return te.current.useEffect(W,Y)},pn.useId=function(){return te.current.useId()},pn.useImperativeHandle=function(W,Y,K){return te.current.useImperativeHandle(W,Y,K)},pn.useInsertionEffect=function(W,Y){return te.current.useInsertionEffect(W,Y)},pn.useLayoutEffect=function(W,Y){return te.current.useLayoutEffect(W,Y)},pn.useMemo=function(W,Y){return te.current.useMemo(W,Y)},pn.useReducer=function(W,Y,K){return te.current.useReducer(W,Y,K)},pn.useRef=function(W){return te.current.useRef(W)},pn.useState=function(W){return te.current.useState(W)},pn.useSyncExternalStore=function(W,Y,K){return te.current.useSyncExternalStore(W,Y,K)},pn.useTransition=function(){return te.current.useTransition()},pn.version="18.3.1",pn}var hx;function rh(){return hx||(hx=1,Og.exports=E$()),Og.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 _x;function A$(){if(_x)return sm;_x=1;var e=rh(),t=Symbol.for("react.element"),n=Symbol.for("react.fragment"),r=Object.prototype.hasOwnProperty,i=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,a={key:!0,ref:!0,__self:!0,__source:!0};function u(c,d,m){var h,p={},y=null,w=null;m!==void 0&&(y=""+m),d.key!==void 0&&(y=""+d.key),d.ref!==void 0&&(w=d.ref);for(h in d)r.call(d,h)&&!a.hasOwnProperty(h)&&(p[h]=d[h]);if(c&&c.defaultProps)for(h in d=c.defaultProps,d)p[h]===void 0&&(p[h]=d[h]);return{$$typeof:t,type:c,key:y,ref:w,props:p,_owner:i.current}}return sm.Fragment=n,sm.jsx=u,sm.jsxs=u,sm}var px;function T$(){return px||(px=1,Ig.exports=A$()),Ig.exports}var s=T$(),_=rh();const Ne=iv(_);var $_={},Pg={exports:{}},pi={},Dg={exports:{}},Fg={};/**
|
|
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 gx;function M$(){return gx||(gx=1,(function(e){function t(X,V){var ne=X.length;X.push(V);e:for(;0<ne;){var W=ne-1>>>1,Y=X[W];if(0<i(Y,V))X[W]=V,X[ne]=Y,ne=W;else break e}}function n(X){return X.length===0?null:X[0]}function r(X){if(X.length===0)return null;var V=X[0],ne=X.pop();if(ne!==V){X[0]=ne;e:for(var W=0,Y=X.length,K=Y>>>1;W<K;){var fe=2*(W+1)-1,ae=X[fe],ve=fe+1,ge=X[ve];if(0>i(ae,ne))ve<Y&&0>i(ge,ae)?(X[W]=ge,X[ve]=ne,W=ve):(X[W]=ae,X[fe]=ne,W=fe);else if(ve<Y&&0>i(ge,ne))X[W]=ge,X[ve]=ne,W=ve;else break e}}return V}function i(X,V){var ne=X.sortIndex-V.sortIndex;return ne!==0?ne:X.id-V.id}if(typeof performance=="object"&&typeof performance.now=="function"){var a=performance;e.unstable_now=function(){return a.now()}}else{var u=Date,c=u.now();e.unstable_now=function(){return u.now()-c}}var d=[],m=[],h=1,p=null,y=3,w=!1,x=!1,k=!1,b=typeof setTimeout=="function"?setTimeout:null,S=typeof clearTimeout=="function"?clearTimeout:null,$=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function A(X){for(var V=n(m);V!==null;){if(V.callback===null)r(m);else if(V.startTime<=X)r(m),V.sortIndex=V.expirationTime,t(d,V);else break;V=n(m)}}function E(X){if(k=!1,A(X),!x)if(n(d)!==null)x=!0,L(z);else{var V=n(m);V!==null&&te(E,V.startTime-X)}}function z(X,V){x=!1,k&&(k=!1,S(D),D=-1),w=!0;var ne=y;try{for(A(V),p=n(d);p!==null&&(!(p.expirationTime>V)||X&&!I());){var W=p.callback;if(typeof W=="function"){p.callback=null,y=p.priorityLevel;var Y=W(p.expirationTime<=V);V=e.unstable_now(),typeof Y=="function"?p.callback=Y:p===n(d)&&r(d),A(V)}else r(d);p=n(d)}if(p!==null)var K=!0;else{var fe=n(m);fe!==null&&te(E,fe.startTime-V),K=!1}return K}finally{p=null,y=ne,w=!1}}var F=!1,M=null,D=-1,H=5,q=-1;function I(){return!(e.unstable_now()-q<H)}function Z(){if(M!==null){var X=e.unstable_now();q=X;var V=!0;try{V=M(!0,X)}finally{V?R():(F=!1,M=null)}}else F=!1}var R;if(typeof $=="function")R=function(){$(Z)};else if(typeof MessageChannel<"u"){var T=new MessageChannel,P=T.port2;T.port1.onmessage=Z,R=function(){P.postMessage(null)}}else R=function(){b(Z,0)};function L(X){M=X,F||(F=!0,R())}function te(X,V){D=b(function(){X(e.unstable_now())},V)}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(X){X.callback=null},e.unstable_continueExecution=function(){x||w||(x=!0,L(z))},e.unstable_forceFrameRate=function(X){0>X||125<X?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):H=0<X?Math.floor(1e3/X):5},e.unstable_getCurrentPriorityLevel=function(){return y},e.unstable_getFirstCallbackNode=function(){return n(d)},e.unstable_next=function(X){switch(y){case 1:case 2:case 3:var V=3;break;default:V=y}var ne=y;y=V;try{return X()}finally{y=ne}},e.unstable_pauseExecution=function(){},e.unstable_requestPaint=function(){},e.unstable_runWithPriority=function(X,V){switch(X){case 1:case 2:case 3:case 4:case 5:break;default:X=3}var ne=y;y=X;try{return V()}finally{y=ne}},e.unstable_scheduleCallback=function(X,V,ne){var W=e.unstable_now();switch(typeof ne=="object"&&ne!==null?(ne=ne.delay,ne=typeof ne=="number"&&0<ne?W+ne:W):ne=W,X){case 1:var Y=-1;break;case 2:Y=250;break;case 5:Y=1073741823;break;case 4:Y=1e4;break;default:Y=5e3}return Y=ne+Y,X={id:h++,callback:V,priorityLevel:X,startTime:ne,expirationTime:Y,sortIndex:-1},ne>W?(X.sortIndex=ne,t(m,X),n(d)===null&&X===n(m)&&(k?(S(D),D=-1):k=!0,te(E,ne-W))):(X.sortIndex=Y,t(d,X),x||w||(x=!0,L(z))),X},e.unstable_shouldYield=I,e.unstable_wrapCallback=function(X){var V=y;return function(){var ne=y;y=V;try{return X.apply(this,arguments)}finally{y=ne}}}})(Fg)),Fg}var yx;function R$(){return yx||(yx=1,Dg.exports=M$()),Dg.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 wx;function L$(){if(wx)return pi;wx=1;var e=rh(),t=R$();function n(o){for(var l="https://reactjs.org/docs/error-decoder.html?invariant="+o,f=1;f<arguments.length;f++)l+="&args[]="+encodeURIComponent(arguments[f]);return"Minified React error #"+o+"; visit "+l+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}var r=new Set,i={};function a(o,l){u(o,l),u(o+"Capture",l)}function u(o,l){for(i[o]=l,o=0;o<l.length;o++)r.add(l[o])}var c=!(typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),d=Object.prototype.hasOwnProperty,m=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,h={},p={};function y(o){return d.call(p,o)?!0:d.call(h,o)?!1:m.test(o)?p[o]=!0:(h[o]=!0,!1)}function w(o,l,f,g){if(f!==null&&f.type===0)return!1;switch(typeof l){case"function":case"symbol":return!0;case"boolean":return g?!1:f!==null?!f.acceptsBooleans:(o=o.toLowerCase().slice(0,5),o!=="data-"&&o!=="aria-");default:return!1}}function x(o,l,f,g){if(l===null||typeof l>"u"||w(o,l,f,g))return!0;if(g)return!1;if(f!==null)switch(f.type){case 3:return!l;case 4:return l===!1;case 5:return isNaN(l);case 6:return isNaN(l)||1>l}return!1}function k(o,l,f,g,j,N,U){this.acceptsBooleans=l===2||l===3||l===4,this.attributeName=g,this.attributeNamespace=j,this.mustUseProperty=f,this.propertyName=o,this.type=l,this.sanitizeURL=N,this.removeEmptyString=U}var b={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(o){b[o]=new k(o,0,!1,o,null,!1,!1)}),[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(o){var l=o[0];b[l]=new k(l,1,!1,o[1],null,!1,!1)}),["contentEditable","draggable","spellCheck","value"].forEach(function(o){b[o]=new k(o,2,!1,o.toLowerCase(),null,!1,!1)}),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(o){b[o]=new k(o,2,!1,o,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(o){b[o]=new k(o,3,!1,o.toLowerCase(),null,!1,!1)}),["checked","multiple","muted","selected"].forEach(function(o){b[o]=new k(o,3,!0,o,null,!1,!1)}),["capture","download"].forEach(function(o){b[o]=new k(o,4,!1,o,null,!1,!1)}),["cols","rows","size","span"].forEach(function(o){b[o]=new k(o,6,!1,o,null,!1,!1)}),["rowSpan","start"].forEach(function(o){b[o]=new k(o,5,!1,o.toLowerCase(),null,!1,!1)});var S=/[\-:]([a-z])/g;function $(o){return o[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(o){var l=o.replace(S,$);b[l]=new k(l,1,!1,o,null,!1,!1)}),"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(o){var l=o.replace(S,$);b[l]=new k(l,1,!1,o,"http://www.w3.org/1999/xlink",!1,!1)}),["xml:base","xml:lang","xml:space"].forEach(function(o){var l=o.replace(S,$);b[l]=new k(l,1,!1,o,"http://www.w3.org/XML/1998/namespace",!1,!1)}),["tabIndex","crossOrigin"].forEach(function(o){b[o]=new k(o,1,!1,o.toLowerCase(),null,!1,!1)}),b.xlinkHref=new k("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1),["src","href","action","formAction"].forEach(function(o){b[o]=new k(o,1,!1,o.toLowerCase(),null,!0,!0)});function A(o,l,f,g){var j=b.hasOwnProperty(l)?b[l]:null;(j!==null?j.type!==0:g||!(2<l.length)||l[0]!=="o"&&l[0]!=="O"||l[1]!=="n"&&l[1]!=="N")&&(x(l,f,j,g)&&(f=null),g||j===null?y(l)&&(f===null?o.removeAttribute(l):o.setAttribute(l,""+f)):j.mustUseProperty?o[j.propertyName]=f===null?j.type===3?!1:"":f:(l=j.attributeName,g=j.attributeNamespace,f===null?o.removeAttribute(l):(j=j.type,f=j===3||j===4&&f===!0?"":""+f,g?o.setAttributeNS(g,l,f):o.setAttribute(l,f))))}var E=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,z=Symbol.for("react.element"),F=Symbol.for("react.portal"),M=Symbol.for("react.fragment"),D=Symbol.for("react.strict_mode"),H=Symbol.for("react.profiler"),q=Symbol.for("react.provider"),I=Symbol.for("react.context"),Z=Symbol.for("react.forward_ref"),R=Symbol.for("react.suspense"),T=Symbol.for("react.suspense_list"),P=Symbol.for("react.memo"),L=Symbol.for("react.lazy"),te=Symbol.for("react.offscreen"),X=Symbol.iterator;function V(o){return o===null||typeof o!="object"?null:(o=X&&o[X]||o["@@iterator"],typeof o=="function"?o:null)}var ne=Object.assign,W;function Y(o){if(W===void 0)try{throw Error()}catch(f){var l=f.stack.trim().match(/\n( *(at )?)/);W=l&&l[1]||""}return`
|
|
34
|
+
`+W+o}var K=!1;function fe(o,l){if(!o||K)return"";K=!0;var f=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{if(l)if(l=function(){throw Error()},Object.defineProperty(l.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(l,[])}catch(Ce){var g=Ce}Reflect.construct(o,[],l)}else{try{l.call()}catch(Ce){g=Ce}o.call(l.prototype)}else{try{throw Error()}catch(Ce){g=Ce}o()}}catch(Ce){if(Ce&&g&&typeof Ce.stack=="string"){for(var j=Ce.stack.split(`
|
|
35
|
+
`),N=g.stack.split(`
|
|
36
|
+
`),U=j.length-1,oe=N.length-1;1<=U&&0<=oe&&j[U]!==N[oe];)oe--;for(;1<=U&&0<=oe;U--,oe--)if(j[U]!==N[oe]){if(U!==1||oe!==1)do if(U--,oe--,0>oe||j[U]!==N[oe]){var le=`
|
|
37
|
+
`+j[U].replace(" at new "," at ");return o.displayName&&le.includes("<anonymous>")&&(le=le.replace("<anonymous>",o.displayName)),le}while(1<=U&&0<=oe);break}}}finally{K=!1,Error.prepareStackTrace=f}return(o=o?o.displayName||o.name:"")?Y(o):""}function ae(o){switch(o.tag){case 5:return Y(o.type);case 16:return Y("Lazy");case 13:return Y("Suspense");case 19:return Y("SuspenseList");case 0:case 2:case 15:return o=fe(o.type,!1),o;case 11:return o=fe(o.type.render,!1),o;case 1:return o=fe(o.type,!0),o;default:return""}}function ve(o){if(o==null)return null;if(typeof o=="function")return o.displayName||o.name||null;if(typeof o=="string")return o;switch(o){case M:return"Fragment";case F:return"Portal";case H:return"Profiler";case D:return"StrictMode";case R:return"Suspense";case T:return"SuspenseList"}if(typeof o=="object")switch(o.$$typeof){case I:return(o.displayName||"Context")+".Consumer";case q:return(o._context.displayName||"Context")+".Provider";case Z:var l=o.render;return o=o.displayName,o||(o=l.displayName||l.name||"",o=o!==""?"ForwardRef("+o+")":"ForwardRef"),o;case P:return l=o.displayName||null,l!==null?l:ve(o.type)||"Memo";case L:l=o._payload,o=o._init;try{return ve(o(l))}catch{}}return null}function ge(o){var l=o.type;switch(o.tag){case 24:return"Cache";case 9:return(l.displayName||"Context")+".Consumer";case 10:return(l._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return o=l.render,o=o.displayName||o.name||"",l.displayName||(o!==""?"ForwardRef("+o+")":"ForwardRef");case 7:return"Fragment";case 5:return l;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return ve(l);case 8:return l===D?"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 l=="function")return l.displayName||l.name||null;if(typeof l=="string")return l}return null}function pe(o){switch(typeof o){case"boolean":case"number":case"string":case"undefined":return o;case"object":return o;default:return""}}function $e(o){var l=o.type;return(o=o.nodeName)&&o.toLowerCase()==="input"&&(l==="checkbox"||l==="radio")}function De(o){var l=$e(o)?"checked":"value",f=Object.getOwnPropertyDescriptor(o.constructor.prototype,l),g=""+o[l];if(!o.hasOwnProperty(l)&&typeof f<"u"&&typeof f.get=="function"&&typeof f.set=="function"){var j=f.get,N=f.set;return Object.defineProperty(o,l,{configurable:!0,get:function(){return j.call(this)},set:function(U){g=""+U,N.call(this,U)}}),Object.defineProperty(o,l,{enumerable:f.enumerable}),{getValue:function(){return g},setValue:function(U){g=""+U},stopTracking:function(){o._valueTracker=null,delete o[l]}}}}function ot(o){o._valueTracker||(o._valueTracker=De(o))}function bt(o){if(!o)return!1;var l=o._valueTracker;if(!l)return!0;var f=l.getValue(),g="";return o&&(g=$e(o)?o.checked?"true":"false":o.value),o=g,o!==f?(l.setValue(o),!0):!1}function Ue(o){if(o=o||(typeof document<"u"?document:void 0),typeof o>"u")return null;try{return o.activeElement||o.body}catch{return o.body}}function at(o,l){var f=l.checked;return ne({},l,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:f??o._wrapperState.initialChecked})}function Nt(o,l){var f=l.defaultValue==null?"":l.defaultValue,g=l.checked!=null?l.checked:l.defaultChecked;f=pe(l.value!=null?l.value:f),o._wrapperState={initialChecked:g,initialValue:f,controlled:l.type==="checkbox"||l.type==="radio"?l.checked!=null:l.value!=null}}function ut(o,l){l=l.checked,l!=null&&A(o,"checked",l,!1)}function Se(o,l){ut(o,l);var f=pe(l.value),g=l.type;if(f!=null)g==="number"?(f===0&&o.value===""||o.value!=f)&&(o.value=""+f):o.value!==""+f&&(o.value=""+f);else if(g==="submit"||g==="reset"){o.removeAttribute("value");return}l.hasOwnProperty("value")?Ve(o,l.type,f):l.hasOwnProperty("defaultValue")&&Ve(o,l.type,pe(l.defaultValue)),l.checked==null&&l.defaultChecked!=null&&(o.defaultChecked=!!l.defaultChecked)}function me(o,l,f){if(l.hasOwnProperty("value")||l.hasOwnProperty("defaultValue")){var g=l.type;if(!(g!=="submit"&&g!=="reset"||l.value!==void 0&&l.value!==null))return;l=""+o._wrapperState.initialValue,f||l===o.value||(o.value=l),o.defaultValue=l}f=o.name,f!==""&&(o.name=""),o.defaultChecked=!!o._wrapperState.initialChecked,f!==""&&(o.name=f)}function Ve(o,l,f){(l!=="number"||Ue(o.ownerDocument)!==o)&&(f==null?o.defaultValue=""+o._wrapperState.initialValue:o.defaultValue!==""+f&&(o.defaultValue=""+f))}var ye=Array.isArray;function Ie(o,l,f,g){if(o=o.options,l){l={};for(var j=0;j<f.length;j++)l["$"+f[j]]=!0;for(f=0;f<o.length;f++)j=l.hasOwnProperty("$"+o[f].value),o[f].selected!==j&&(o[f].selected=j),j&&g&&(o[f].defaultSelected=!0)}else{for(f=""+pe(f),l=null,j=0;j<o.length;j++){if(o[j].value===f){o[j].selected=!0,g&&(o[j].defaultSelected=!0);return}l!==null||o[j].disabled||(l=o[j])}l!==null&&(l.selected=!0)}}function ct(o,l){if(l.dangerouslySetInnerHTML!=null)throw Error(n(91));return ne({},l,{value:void 0,defaultValue:void 0,children:""+o._wrapperState.initialValue})}function ie(o,l){var f=l.value;if(f==null){if(f=l.children,l=l.defaultValue,f!=null){if(l!=null)throw Error(n(92));if(ye(f)){if(1<f.length)throw Error(n(93));f=f[0]}l=f}l==null&&(l=""),f=l}o._wrapperState={initialValue:pe(f)}}function Te(o,l){var f=pe(l.value),g=pe(l.defaultValue);f!=null&&(f=""+f,f!==o.value&&(o.value=f),l.defaultValue==null&&o.defaultValue!==f&&(o.defaultValue=f)),g!=null&&(o.defaultValue=""+g)}function et(o){var l=o.textContent;l===o._wrapperState.initialValue&&l!==""&&l!==null&&(o.value=l)}function Ge(o){switch(o){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 Be(o,l){return o==null||o==="http://www.w3.org/1999/xhtml"?Ge(l):o==="http://www.w3.org/2000/svg"&&l==="foreignObject"?"http://www.w3.org/1999/xhtml":o}var Rt,Nn=(function(o){return typeof MSApp<"u"&&MSApp.execUnsafeLocalFunction?function(l,f,g,j){MSApp.execUnsafeLocalFunction(function(){return o(l,f,g,j)})}:o})(function(o,l){if(o.namespaceURI!=="http://www.w3.org/2000/svg"||"innerHTML"in o)o.innerHTML=l;else{for(Rt=Rt||document.createElement("div"),Rt.innerHTML="<svg>"+l.valueOf().toString()+"</svg>",l=Rt.firstChild;o.firstChild;)o.removeChild(o.firstChild);for(;l.firstChild;)o.appendChild(l.firstChild)}});function Qt(o,l){if(l){var f=o.firstChild;if(f&&f===o.lastChild&&f.nodeType===3){f.nodeValue=l;return}}o.textContent=l}var Un={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},rs=["Webkit","ms","Moz","O"];Object.keys(Un).forEach(function(o){rs.forEach(function(l){l=l+o.charAt(0).toUpperCase()+o.substring(1),Un[l]=Un[o]})});function Dn(o,l,f){return l==null||typeof l=="boolean"||l===""?"":f||typeof l!="number"||l===0||Un.hasOwnProperty(o)&&Un[o]?(""+l).trim():l+"px"}function $n(o,l){o=o.style;for(var f in l)if(l.hasOwnProperty(f)){var g=f.indexOf("--")===0,j=Dn(f,l[f],g);f==="float"&&(f="cssFloat"),g?o.setProperty(f,j):o[f]=j}}var Cn=ne({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 an(o,l){if(l){if(Cn[o]&&(l.children!=null||l.dangerouslySetInnerHTML!=null))throw Error(n(137,o));if(l.dangerouslySetInnerHTML!=null){if(l.children!=null)throw Error(n(60));if(typeof l.dangerouslySetInnerHTML!="object"||!("__html"in l.dangerouslySetInnerHTML))throw Error(n(61))}if(l.style!=null&&typeof l.style!="object")throw Error(n(62))}}function is(o,l){if(o.indexOf("-")===-1)return typeof l.is=="string";switch(o){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 Wn=null;function Fn(o){return o=o.target||o.srcElement||window,o.correspondingUseElement&&(o=o.correspondingUseElement),o.nodeType===3?o.parentNode:o}var Hs=null,es=null,he=null;function Ee(o){if(o=Xo(o)){if(typeof Hs!="function")throw Error(n(280));var l=o.stateNode;l&&(l=No(l),Hs(o.stateNode,o.type,l))}}function mt(o){es?he?he.push(o):he=[o]:es=o}function se(){if(es){var o=es,l=he;if(he=es=null,Ee(o),l)for(o=0;o<l.length;o++)Ee(l[o])}}function ce(o,l){return o(l)}function je(){}var Ae=!1;function ze(o,l,f){if(Ae)return o(l,f);Ae=!0;try{return ce(o,l,f)}finally{Ae=!1,(es!==null||he!==null)&&(je(),se())}}function Fe(o,l){var f=o.stateNode;if(f===null)return null;var g=No(f);if(g===null)return null;f=g[l];e:switch(l){case"onClick":case"onClickCapture":case"onDoubleClick":case"onDoubleClickCapture":case"onMouseDown":case"onMouseDownCapture":case"onMouseMove":case"onMouseMoveCapture":case"onMouseUp":case"onMouseUpCapture":case"onMouseEnter":(g=!g.disabled)||(o=o.type,g=!(o==="button"||o==="input"||o==="select"||o==="textarea")),o=!g;break e;default:o=!1}if(o)return null;if(f&&typeof f!="function")throw Error(n(231,l,typeof f));return f}var Ze=!1;if(c)try{var lt={};Object.defineProperty(lt,"passive",{get:function(){Ze=!0}}),window.addEventListener("test",lt,lt),window.removeEventListener("test",lt,lt)}catch{Ze=!1}function ht(o,l,f,g,j,N,U,oe,le){var Ce=Array.prototype.slice.call(arguments,3);try{l.apply(f,Ce)}catch(Ye){this.onError(Ye)}}var _t=!1,kt=null,At=!1,rt=null,zt={onError:function(o){_t=!0,kt=o}};function dn(o,l,f,g,j,N,U,oe,le){_t=!1,kt=null,ht.apply(zt,arguments)}function on(o,l,f,g,j,N,U,oe,le){if(dn.apply(this,arguments),_t){if(_t){var Ce=kt;_t=!1,kt=null}else throw Error(n(198));At||(At=!0,rt=Ce)}}function Ht(o){var l=o,f=o;if(o.alternate)for(;l.return;)l=l.return;else{o=l;do l=o,(l.flags&4098)!==0&&(f=l.return),o=l.return;while(o)}return l.tag===3?f:null}function Ot(o){if(o.tag===13){var l=o.memoizedState;if(l===null&&(o=o.alternate,o!==null&&(l=o.memoizedState)),l!==null)return l.dehydrated}return null}function ts(o){if(Ht(o)!==o)throw Error(n(188))}function Pe(o){var l=o.alternate;if(!l){if(l=Ht(o),l===null)throw Error(n(188));return l!==o?null:o}for(var f=o,g=l;;){var j=f.return;if(j===null)break;var N=j.alternate;if(N===null){if(g=j.return,g!==null){f=g;continue}break}if(j.child===N.child){for(N=j.child;N;){if(N===f)return ts(j),o;if(N===g)return ts(j),l;N=N.sibling}throw Error(n(188))}if(f.return!==g.return)f=j,g=N;else{for(var U=!1,oe=j.child;oe;){if(oe===f){U=!0,f=j,g=N;break}if(oe===g){U=!0,g=j,f=N;break}oe=oe.sibling}if(!U){for(oe=N.child;oe;){if(oe===f){U=!0,f=N,g=j;break}if(oe===g){U=!0,g=N,f=j;break}oe=oe.sibling}if(!U)throw Error(n(189))}}if(f.alternate!==g)throw Error(n(190))}if(f.tag!==3)throw Error(n(188));return f.stateNode.current===f?o:l}function Ut(o){return o=Pe(o),o!==null?St(o):null}function St(o){if(o.tag===5||o.tag===6)return o;for(o=o.child;o!==null;){var l=St(o);if(l!==null)return l;o=o.sibling}return null}var Mn=t.unstable_scheduleCallback,nn=t.unstable_cancelCallback,Je=t.unstable_shouldYield,en=t.unstable_requestPaint,Yt=t.unstable_now,Cr=t.unstable_getCurrentPriorityLevel,Ns=t.unstable_ImmediatePriority,ps=t.unstable_UserBlockingPriority,_r=t.unstable_NormalPriority,we=t.unstable_LowPriority,wt=t.unstable_IdlePriority,Rn=null,tr=null;function bi(o){if(tr&&typeof tr.onCommitFiberRoot=="function")try{tr.onCommitFiberRoot(Rn,o,void 0,(o.current.flags&128)===128)}catch{}}var nr=Math.clz32?Math.clz32:Qa,po=Math.log,sc=Math.LN2;function Qa(o){return o>>>=0,o===0?32:31-(po(o)/sc|0)|0}var ws=64,pr=4194304;function Ms(o){switch(o&-o){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 o&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return o&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return o}}function Fi(o,l){var f=o.pendingLanes;if(f===0)return 0;var g=0,j=o.suspendedLanes,N=o.pingedLanes,U=f&268435455;if(U!==0){var oe=U&~j;oe!==0?g=Ms(oe):(N&=U,N!==0&&(g=Ms(N)))}else U=f&~j,U!==0?g=Ms(U):N!==0&&(g=Ms(N));if(g===0)return 0;if(l!==0&&l!==g&&(l&j)===0&&(j=g&-g,N=l&-l,j>=N||j===16&&(N&4194240)!==0))return l;if((g&4)!==0&&(g|=f&16),l=o.entangledLanes,l!==0)for(o=o.entanglements,l&=g;0<l;)f=31-nr(l),j=1<<f,g|=o[f],l&=~j;return g}function el(o,l){switch(o){case 1:case 2:case 4:return l+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 l+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 gs(o,l){for(var f=o.suspendedLanes,g=o.pingedLanes,j=o.expirationTimes,N=o.pendingLanes;0<N;){var U=31-nr(N),oe=1<<U,le=j[U];le===-1?((oe&f)===0||(oe&g)!==0)&&(j[U]=el(oe,l)):le<=l&&(o.expiredLanes|=oe),N&=~oe}}function si(o){return o=o.pendingLanes&-1073741825,o!==0?o:o&1073741824?1073741824:0}function Rs(){var o=ws;return ws<<=1,(ws&4194240)===0&&(ws=64),o}function ri(o){for(var l=[],f=0;31>f;f++)l.push(o);return l}function vs(o,l,f){o.pendingLanes|=l,l!==536870912&&(o.suspendedLanes=0,o.pingedLanes=0),o=o.eventTimes,l=31-nr(l),o[l]=f}function ii(o,l){var f=o.pendingLanes&~l;o.pendingLanes=l,o.suspendedLanes=0,o.pingedLanes=0,o.expiredLanes&=l,o.mutableReadLanes&=l,o.entangledLanes&=l,l=o.entanglements;var g=o.eventTimes;for(o=o.expirationTimes;0<f;){var j=31-nr(f),N=1<<j;l[j]=0,g[j]=-1,o[j]=-1,f&=~N}}function zi(o,l){var f=o.entangledLanes|=l;for(o=o.entanglements;f;){var g=31-nr(f),j=1<<g;j&l|o[g]&l&&(o[g]|=l),f&=~j}}var Sn=0;function ga(o){return o&=-o,1<o?4<o?(o&268435455)!==0?16:536870912:4:1}var tl,nl,Er,rc,Bi,ya=!1,go=[],Ps=null,Ds=null,gr=null,yo=new Map,Wr=new Map,Ar=[],qr="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 ic(o,l){switch(o){case"focusin":case"focusout":Ps=null;break;case"dragenter":case"dragleave":Ds=null;break;case"mouseover":case"mouseout":gr=null;break;case"pointerover":case"pointerout":yo.delete(l.pointerId);break;case"gotpointercapture":case"lostpointercapture":Wr.delete(l.pointerId)}}function Hr(o,l,f,g,j,N){return o===null||o.nativeEvent!==N?(o={blockedOn:l,domEventName:f,eventSystemFlags:g,nativeEvent:N,targetContainers:[j]},l!==null&&(l=Xo(l),l!==null&&nl(l)),o):(o.eventSystemFlags|=g,l=o.targetContainers,j!==null&&l.indexOf(j)===-1&&l.push(j),o)}function uu(o,l,f,g,j){switch(l){case"focusin":return Ps=Hr(Ps,o,l,f,g,j),!0;case"dragenter":return Ds=Hr(Ds,o,l,f,g,j),!0;case"mouseover":return gr=Hr(gr,o,l,f,g,j),!0;case"pointerover":var N=j.pointerId;return yo.set(N,Hr(yo.get(N)||null,o,l,f,g,j)),!0;case"gotpointercapture":return N=j.pointerId,Wr.set(N,Hr(Wr.get(N)||null,o,l,f,g,j)),!0}return!1}function ki(o){var l=Ea(o.target);if(l!==null){var f=Ht(l);if(f!==null){if(l=f.tag,l===13){if(l=Ot(f),l!==null){o.blockedOn=l,Bi(o.priority,function(){Er(f)});return}}else if(l===3&&f.stateNode.current.memoizedState.isDehydrated){o.blockedOn=f.tag===3?f.stateNode.containerInfo:null;return}}}o.blockedOn=null}function Vo(o){if(o.blockedOn!==null)return!1;for(var l=o.targetContainers;0<l.length;){var f=ue(o.domEventName,o.eventSystemFlags,l[0],o.nativeEvent);if(f===null){f=o.nativeEvent;var g=new f.constructor(f.type,f);Wn=g,f.target.dispatchEvent(g),Wn=null}else return l=Xo(f),l!==null&&nl(l),o.blockedOn=f,!1;l.shift()}return!0}function sl(o,l,f){Vo(o)&&f.delete(l)}function wo(){ya=!1,Ps!==null&&Vo(Ps)&&(Ps=null),Ds!==null&&Vo(Ds)&&(Ds=null),gr!==null&&Vo(gr)&&(gr=null),yo.forEach(sl),Wr.forEach(sl)}function oi(o,l){o.blockedOn===l&&(o.blockedOn=null,ya||(ya=!0,t.unstable_scheduleCallback(t.unstable_NormalPriority,wo)))}function wa(o){function l(j){return oi(j,o)}if(0<go.length){oi(go[0],o);for(var f=1;f<go.length;f++){var g=go[f];g.blockedOn===o&&(g.blockedOn=null)}}for(Ps!==null&&oi(Ps,o),Ds!==null&&oi(Ds,o),gr!==null&&oi(gr,o),yo.forEach(l),Wr.forEach(l),f=0;f<Ar.length;f++)g=Ar[f],g.blockedOn===o&&(g.blockedOn=null);for(;0<Ar.length&&(f=Ar[0],f.blockedOn===null);)ki(f),f.blockedOn===null&&Ar.shift()}var Ui=E.ReactCurrentBatchConfig,sr=!0;function tf(o,l,f,g){var j=Sn,N=Ui.transition;Ui.transition=null;try{Sn=1,qn(o,l,f,g)}finally{Sn=j,Ui.transition=N}}function ai(o,l,f,g){var j=Sn,N=Ui.transition;Ui.transition=null;try{Sn=4,qn(o,l,f,g)}finally{Sn=j,Ui.transition=N}}function qn(o,l,f,g){if(sr){var j=ue(o,l,f,g);if(j===null)ml(o,l,g,G,f),ic(o,g);else if(uu(j,o,l,f,g))g.stopPropagation();else if(ic(o,g),l&4&&-1<qr.indexOf(o)){for(;j!==null;){var N=Xo(j);if(N!==null&&tl(N),N=ue(o,l,f,g),N===null&&ml(o,l,g,G,f),N===j)break;j=N}j!==null&&g.stopPropagation()}else ml(o,l,g,null,f)}}var G=null;function ue(o,l,f,g){if(G=null,o=Fn(g),o=Ea(o),o!==null)if(l=Ht(o),l===null)o=null;else if(f=l.tag,f===13){if(o=Ot(l),o!==null)return o;o=null}else if(f===3){if(l.stateNode.current.memoizedState.isDehydrated)return l.tag===3?l.stateNode.containerInfo:null;o=null}else l!==o&&(o=null);return G=o,null}function Me(o){switch(o){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(Cr()){case Ns:return 1;case ps:return 4;case _r:case we:return 16;case wt:return 536870912;default:return 16}default:return 16}}var Re=null,Ke=null,dt=null;function Lt(){if(dt)return dt;var o,l=Ke,f=l.length,g,j="value"in Re?Re.value:Re.textContent,N=j.length;for(o=0;o<f&&l[o]===j[o];o++);var U=f-o;for(g=1;g<=U&&l[f-g]===j[N-g];g++);return dt=j.slice(o,1<g?1-g:void 0)}function Ct(o){var l=o.keyCode;return"charCode"in o?(o=o.charCode,o===0&&l===13&&(o=13)):o=l,o===10&&(o=13),32<=o||o===13?o:0}function Tt(){return!0}function cn(){return!1}function wn(o){function l(f,g,j,N,U){this._reactName=f,this._targetInst=j,this.type=g,this.nativeEvent=N,this.target=U,this.currentTarget=null;for(var oe in o)o.hasOwnProperty(oe)&&(f=o[oe],this[oe]=f?f(N):N[oe]);return this.isDefaultPrevented=(N.defaultPrevented!=null?N.defaultPrevented:N.returnValue===!1)?Tt:cn,this.isPropagationStopped=cn,this}return ne(l.prototype,{preventDefault:function(){this.defaultPrevented=!0;var f=this.nativeEvent;f&&(f.preventDefault?f.preventDefault():typeof f.returnValue!="unknown"&&(f.returnValue=!1),this.isDefaultPrevented=Tt)},stopPropagation:function(){var f=this.nativeEvent;f&&(f.stopPropagation?f.stopPropagation():typeof f.cancelBubble!="unknown"&&(f.cancelBubble=!0),this.isPropagationStopped=Tt)},persist:function(){},isPersistent:Tt}),l}var Vs={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(o){return o.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},Et=wn(Vs),_n=ne({},Vs,{view:0,detail:0}),os=wn(_n),zn,Tr,yr,Wi=ne({},_n,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:il,button:0,buttons:0,relatedTarget:function(o){return o.relatedTarget===void 0?o.fromElement===o.srcElement?o.toElement:o.fromElement:o.relatedTarget},movementX:function(o){return"movementX"in o?o.movementX:(o!==yr&&(yr&&o.type==="mousemove"?(zn=o.screenX-yr.screenX,Tr=o.screenY-yr.screenY):Tr=zn=0,yr=o),zn)},movementY:function(o){return"movementY"in o?o.movementY:Tr}}),rl=wn(Wi),qi=ne({},Wi,{dataTransfer:0}),nf=wn(qi),oc=ne({},_n,{relatedTarget:0}),va=wn(oc),xa=ne({},Vs,{animationName:0,elapsedTime:0,pseudoElement:0}),sf=wn(xa),ac=ne({},Vs,{clipboardData:function(o){return"clipboardData"in o?o.clipboardData:window.clipboardData}}),lc=wn(ac),du=ne({},Vs,{data:0}),rf=wn(du),fu={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},of={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"},mu={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function hu(o){var l=this.nativeEvent;return l.getModifierState?l.getModifierState(o):(o=mu[o])?!!l[o]:!1}function il(){return hu}var wh=ne({},_n,{key:function(o){if(o.key){var l=fu[o.key]||o.key;if(l!=="Unidentified")return l}return o.type==="keypress"?(o=Ct(o),o===13?"Enter":String.fromCharCode(o)):o.type==="keydown"||o.type==="keyup"?of[o.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:il,charCode:function(o){return o.type==="keypress"?Ct(o):0},keyCode:function(o){return o.type==="keydown"||o.type==="keyup"?o.keyCode:0},which:function(o){return o.type==="keypress"?Ct(o):o.type==="keydown"||o.type==="keyup"?o.keyCode:0}}),ba=wn(wh),vh=ne({},Wi,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),_u=wn(vh),af=ne({},_n,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:il}),lf=wn(af),ol=ne({},Vs,{propertyName:0,elapsedTime:0,pseudoElement:0}),xh=wn(ol),bh=ne({},Wi,{deltaX:function(o){return"deltaX"in o?o.deltaX:"wheelDeltaX"in o?-o.wheelDeltaX:0},deltaY:function(o){return"deltaY"in o?o.deltaY:"wheelDeltaY"in o?-o.wheelDeltaY:"wheelDelta"in o?-o.wheelDelta:0},deltaZ:0,deltaMode:0}),cf=wn(bh),vg=[9,13,27,32],pu=c&&"CompositionEvent"in window,al=null;c&&"documentMode"in document&&(al=document.documentMode);var xg=c&&"TextEvent"in window&&!al,gu=c&&(!pu||al&&8<al&&11>=al),vn=" ",yu=!1;function kh(o,l){switch(o){case"keyup":return vg.indexOf(l.keyCode)!==-1;case"keydown":return l.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function wu(o){return o=o.detail,typeof o=="object"&&"data"in o?o.data:null}var ll=!1;function uf(o,l){switch(o){case"compositionend":return wu(l);case"keypress":return l.which!==32?null:(yu=!0,vn);case"textInput":return o=l.data,o===vn&&yu?null:o;default:return null}}function bg(o,l){if(ll)return o==="compositionend"||!pu&&kh(o,l)?(o=Lt(),dt=Ke=Re=null,ll=!1,o):null;switch(o){case"paste":return null;case"keypress":if(!(l.ctrlKey||l.altKey||l.metaKey)||l.ctrlKey&&l.altKey){if(l.char&&1<l.char.length)return l.char;if(l.which)return String.fromCharCode(l.which)}return null;case"compositionend":return gu&&l.locale!=="ko"?null:l.data;default:return null}}var xs={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 vo(o){var l=o&&o.nodeName&&o.nodeName.toLowerCase();return l==="input"?!!xs[o.type]:l==="textarea"}function df(o,l,f,g){mt(g),l=Si(l,"onChange"),0<l.length&&(f=new Et("onChange","change",null,f,g),o.push({event:f,listeners:l}))}var cc=null,Hi=null;function ff(o){vr(o,0)}function Go(o){var l=pl(o);if(bt(l))return o}function jh(o,l){if(o==="change")return l}var Sh=!1;if(c){var mf;if(c){var hf="oninput"in document;if(!hf){var _f=document.createElement("div");_f.setAttribute("oninput","return;"),hf=typeof _f.oninput=="function"}mf=hf}else mf=!1;Sh=mf&&(!document.documentMode||9<document.documentMode)}function Nh(){cc&&(cc.detachEvent("onpropertychange",pf),Hi=cc=null)}function pf(o){if(o.propertyName==="value"&&Go(Hi)){var l=[];df(l,Hi,o,Fn(o)),ze(ff,l)}}function kg(o,l,f){o==="focusin"?(Nh(),cc=l,Hi=f,cc.attachEvent("onpropertychange",pf)):o==="focusout"&&Nh()}function $h(o){if(o==="selectionchange"||o==="keyup"||o==="keydown")return Go(Hi)}function Ch(o,l){if(o==="click")return Go(l)}function gf(o,l){if(o==="input"||o==="change")return Go(l)}function cl(o,l){return o===l&&(o!==0||1/o===1/l)||o!==o&&l!==l}var wr=typeof Object.is=="function"?Object.is:cl;function Vi(o,l){if(wr(o,l))return!0;if(typeof o!="object"||o===null||typeof l!="object"||l===null)return!1;var f=Object.keys(o),g=Object.keys(l);if(f.length!==g.length)return!1;for(g=0;g<f.length;g++){var j=f[g];if(!d.call(l,j)||!wr(o[j],l[j]))return!1}return!0}function ul(o){for(;o&&o.firstChild;)o=o.firstChild;return o}function uc(o,l){var f=ul(o);o=0;for(var g;f;){if(f.nodeType===3){if(g=o+f.textContent.length,o<=l&&g>=l)return{node:f,offset:l-o};o=g}e:{for(;f;){if(f.nextSibling){f=f.nextSibling;break e}f=f.parentNode}f=void 0}f=ul(f)}}function vu(o,l){return o&&l?o===l?!0:o&&o.nodeType===3?!1:l&&l.nodeType===3?vu(o,l.parentNode):"contains"in o?o.contains(l):o.compareDocumentPosition?!!(o.compareDocumentPosition(l)&16):!1:!1}function yf(){for(var o=window,l=Ue();l instanceof o.HTMLIFrameElement;){try{var f=typeof l.contentWindow.location.href=="string"}catch{f=!1}if(f)o=l.contentWindow;else break;l=Ue(o.document)}return l}function ka(o){var l=o&&o.nodeName&&o.nodeName.toLowerCase();return l&&(l==="input"&&(o.type==="text"||o.type==="search"||o.type==="tel"||o.type==="url"||o.type==="password")||l==="textarea"||o.contentEditable==="true")}function Eh(o){var l=yf(),f=o.focusedElem,g=o.selectionRange;if(l!==f&&f&&f.ownerDocument&&vu(f.ownerDocument.documentElement,f)){if(g!==null&&ka(f)){if(l=g.start,o=g.end,o===void 0&&(o=l),"selectionStart"in f)f.selectionStart=l,f.selectionEnd=Math.min(o,f.value.length);else if(o=(l=f.ownerDocument||document)&&l.defaultView||window,o.getSelection){o=o.getSelection();var j=f.textContent.length,N=Math.min(g.start,j);g=g.end===void 0?N:Math.min(g.end,j),!o.extend&&N>g&&(j=g,g=N,N=j),j=uc(f,N);var U=uc(f,g);j&&U&&(o.rangeCount!==1||o.anchorNode!==j.node||o.anchorOffset!==j.offset||o.focusNode!==U.node||o.focusOffset!==U.offset)&&(l=l.createRange(),l.setStart(j.node,j.offset),o.removeAllRanges(),N>g?(o.addRange(l),o.extend(U.node,U.offset)):(l.setEnd(U.node,U.offset),o.addRange(l)))}}for(l=[],o=f;o=o.parentNode;)o.nodeType===1&&l.push({element:o,left:o.scrollLeft,top:o.scrollTop});for(typeof f.focus=="function"&&f.focus(),f=0;f<l.length;f++)o=l[f],o.element.scrollLeft=o.left,o.element.scrollTop=o.top}}var dc=c&&"documentMode"in document&&11>=document.documentMode,Gi=null,wf=null,ja=null,vf=!1;function xu(o,l,f){var g=f.window===f?f.document:f.nodeType===9?f:f.ownerDocument;vf||Gi==null||Gi!==Ue(g)||(g=Gi,"selectionStart"in g&&ka(g)?g={start:g.selectionStart,end:g.selectionEnd}:(g=(g.ownerDocument&&g.ownerDocument.defaultView||window).getSelection(),g={anchorNode:g.anchorNode,anchorOffset:g.anchorOffset,focusNode:g.focusNode,focusOffset:g.focusOffset}),ja&&Vi(ja,g)||(ja=g,g=Si(wf,"onSelect"),0<g.length&&(l=new Et("onSelect","select",null,l,f),o.push({event:l,listeners:g}),l.target=Gi)))}function Sa(o,l){var f={};return f[o.toLowerCase()]=l.toLowerCase(),f["Webkit"+o]="webkit"+l,f["Moz"+o]="moz"+l,f}var Mr={animationend:Sa("Animation","AnimationEnd"),animationiteration:Sa("Animation","AnimationIteration"),animationstart:Sa("Animation","AnimationStart"),transitionend:Sa("Transition","TransitionEnd")},Ko={},Ah={};c&&(Ah=document.createElement("div").style,"AnimationEvent"in window||(delete Mr.animationend.animation,delete Mr.animationiteration.animation,delete Mr.animationstart.animation),"TransitionEvent"in window||delete Mr.transitionend.transition);function Na(o){if(Ko[o])return Ko[o];if(!Mr[o])return o;var l=Mr[o],f;for(f in l)if(l.hasOwnProperty(f)&&f in Ah)return Ko[o]=l[f];return o}var Th=Na("animationend"),bu=Na("animationiteration"),dl=Na("animationstart"),Vr=Na("transitionend"),xo=new Map,fc="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 Gr(o,l){xo.set(o,l),a(l,[o])}for(var mc=0;mc<fc.length;mc++){var $a=fc[mc],bo=$a.toLowerCase(),ku=$a[0].toUpperCase()+$a.slice(1);Gr(bo,"on"+ku)}Gr(Th,"onAnimationEnd"),Gr(bu,"onAnimationIteration"),Gr(dl,"onAnimationStart"),Gr("dblclick","onDoubleClick"),Gr("focusin","onFocus"),Gr("focusout","onBlur"),Gr(Vr,"onTransitionEnd"),u("onMouseEnter",["mouseout","mouseover"]),u("onMouseLeave",["mouseout","mouseover"]),u("onPointerEnter",["pointerout","pointerover"]),u("onPointerLeave",["pointerout","pointerover"]),a("onChange","change click focusin focusout input keydown keyup selectionchange".split(" ")),a("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" ")),a("onBeforeInput",["compositionend","keypress","textInput","paste"]),a("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" ")),a("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" ")),a("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var ko="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(" "),fl=new Set("cancel close invalid load scroll toggle".split(" ").concat(ko));function jo(o,l,f){var g=o.type||"unknown-event";o.currentTarget=f,on(g,l,void 0,o),o.currentTarget=null}function vr(o,l){l=(l&4)!==0;for(var f=0;f<o.length;f++){var g=o[f],j=g.event;g=g.listeners;e:{var N=void 0;if(l)for(var U=g.length-1;0<=U;U--){var oe=g[U],le=oe.instance,Ce=oe.currentTarget;if(oe=oe.listener,le!==N&&j.isPropagationStopped())break e;jo(j,oe,Ce),N=le}else for(U=0;U<g.length;U++){if(oe=g[U],le=oe.instance,Ce=oe.currentTarget,oe=oe.listener,le!==N&&j.isPropagationStopped())break e;jo(j,oe,Ce),N=le}}}if(At)throw o=rt,At=!1,rt=null,o}function Ln(o,l){var f=l[hl];f===void 0&&(f=l[hl]=new Set);var g=o+"__bubble";f.has(g)||(ju(l,o,2,!1),f.add(g))}function Jo(o,l,f){var g=0;l&&(g|=4),ju(f,o,g,l)}var Ca="_reactListening"+Math.random().toString(36).slice(2);function ji(o){if(!o[Ca]){o[Ca]=!0,r.forEach(function(f){f!=="selectionchange"&&(fl.has(f)||Jo(f,!1,o),Jo(f,!0,o))});var l=o.nodeType===9?o:o.ownerDocument;l===null||l[Ca]||(l[Ca]=!0,Jo("selectionchange",!1,l))}}function ju(o,l,f,g){switch(Me(l)){case 1:var j=tf;break;case 4:j=ai;break;default:j=qn}f=j.bind(null,l,f,o),j=void 0,!Ze||l!=="touchstart"&&l!=="touchmove"&&l!=="wheel"||(j=!0),g?j!==void 0?o.addEventListener(l,f,{capture:!0,passive:j}):o.addEventListener(l,f,!0):j!==void 0?o.addEventListener(l,f,{passive:j}):o.addEventListener(l,f,!1)}function ml(o,l,f,g,j){var N=g;if((l&1)===0&&(l&2)===0&&g!==null)e:for(;;){if(g===null)return;var U=g.tag;if(U===3||U===4){var oe=g.stateNode.containerInfo;if(oe===j||oe.nodeType===8&&oe.parentNode===j)break;if(U===4)for(U=g.return;U!==null;){var le=U.tag;if((le===3||le===4)&&(le=U.stateNode.containerInfo,le===j||le.nodeType===8&&le.parentNode===j))return;U=U.return}for(;oe!==null;){if(U=Ea(oe),U===null)return;if(le=U.tag,le===5||le===6){g=N=U;continue e}oe=oe.parentNode}}g=g.return}ze(function(){var Ce=N,Ye=Fn(f),Qe=[];e:{var He=xo.get(o);if(He!==void 0){var pt=Et,vt=o;switch(o){case"keypress":if(Ct(f)===0)break e;case"keydown":case"keyup":pt=ba;break;case"focusin":vt="focus",pt=va;break;case"focusout":vt="blur",pt=va;break;case"beforeblur":case"afterblur":pt=va;break;case"click":if(f.button===2)break e;case"auxclick":case"dblclick":case"mousedown":case"mousemove":case"mouseup":case"mouseout":case"mouseover":case"contextmenu":pt=rl;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":pt=nf;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":pt=lf;break;case Th:case bu:case dl:pt=sf;break;case Vr:pt=xh;break;case"scroll":pt=os;break;case"wheel":pt=cf;break;case"copy":case"cut":case"paste":pt=lc;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":pt=_u}var jt=(l&4)!==0,Ls=!jt&&o==="scroll",xe=jt?He!==null?He+"Capture":null:He;jt=[];for(var de=Ce,ke;de!==null;){ke=de;var st=ke.stateNode;if(ke.tag===5&&st!==null&&(ke=st,xe!==null&&(st=Fe(de,xe),st!=null&&jt.push(Rr(de,st,ke)))),Ls)break;de=de.return}0<jt.length&&(He=new pt(He,vt,null,f,Ye),Qe.push({event:He,listeners:jt}))}}if((l&7)===0){e:{if(He=o==="mouseover"||o==="pointerover",pt=o==="mouseout"||o==="pointerout",He&&f!==Wn&&(vt=f.relatedTarget||f.fromElement)&&(Ea(vt)||vt[Ni]))break e;if((pt||He)&&(He=Ye.window===Ye?Ye:(He=Ye.ownerDocument)?He.defaultView||He.parentWindow:window,pt?(vt=f.relatedTarget||f.toElement,pt=Ce,vt=vt?Ea(vt):null,vt!==null&&(Ls=Ht(vt),vt!==Ls||vt.tag!==5&&vt.tag!==6)&&(vt=null)):(pt=null,vt=Ce),pt!==vt)){if(jt=rl,st="onMouseLeave",xe="onMouseEnter",de="mouse",(o==="pointerout"||o==="pointerover")&&(jt=_u,st="onPointerLeave",xe="onPointerEnter",de="pointer"),Ls=pt==null?He:pl(pt),ke=vt==null?He:pl(vt),He=new jt(st,de+"leave",pt,f,Ye),He.target=Ls,He.relatedTarget=ke,st=null,Ea(Ye)===Ce&&(jt=new jt(xe,de+"enter",vt,f,Ye),jt.target=ke,jt.relatedTarget=Ls,st=jt),Ls=st,pt&&vt)t:{for(jt=pt,xe=vt,de=0,ke=jt;ke;ke=xr(ke))de++;for(ke=0,st=xe;st;st=xr(st))ke++;for(;0<de-ke;)jt=xr(jt),de--;for(;0<ke-de;)xe=xr(xe),ke--;for(;de--;){if(jt===xe||xe!==null&&jt===xe.alternate)break t;jt=xr(jt),xe=xr(xe)}jt=null}else jt=null;pt!==null&&xf(Qe,He,pt,jt,!1),vt!==null&&Ls!==null&&xf(Qe,Ls,vt,jt,!0)}}e:{if(He=Ce?pl(Ce):window,pt=He.nodeName&&He.nodeName.toLowerCase(),pt==="select"||pt==="input"&&He.type==="file")var $t=jh;else if(vo(He))if(Sh)$t=gf;else{$t=$h;var Pt=kg}else(pt=He.nodeName)&&pt.toLowerCase()==="input"&&(He.type==="checkbox"||He.type==="radio")&&($t=Ch);if($t&&($t=$t(o,Ce))){df(Qe,$t,f,Ye);break e}Pt&&Pt(o,He,Ce),o==="focusout"&&(Pt=He._wrapperState)&&Pt.controlled&&He.type==="number"&&Ve(He,"number",He.value)}switch(Pt=Ce?pl(Ce):window,o){case"focusin":(vo(Pt)||Pt.contentEditable==="true")&&(Gi=Pt,wf=Ce,ja=null);break;case"focusout":ja=wf=Gi=null;break;case"mousedown":vf=!0;break;case"contextmenu":case"mouseup":case"dragend":vf=!1,xu(Qe,f,Ye);break;case"selectionchange":if(dc)break;case"keydown":case"keyup":xu(Qe,f,Ye)}var Dt;if(pu)e:{switch(o){case"compositionstart":var Zt="onCompositionStart";break e;case"compositionend":Zt="onCompositionEnd";break e;case"compositionupdate":Zt="onCompositionUpdate";break e}Zt=void 0}else ll?kh(o,f)&&(Zt="onCompositionEnd"):o==="keydown"&&f.keyCode===229&&(Zt="onCompositionStart");Zt&&(gu&&f.locale!=="ko"&&(ll||Zt!=="onCompositionStart"?Zt==="onCompositionEnd"&&ll&&(Dt=Lt()):(Re=Ye,Ke="value"in Re?Re.value:Re.textContent,ll=!0)),Pt=Si(Ce,Zt),0<Pt.length&&(Zt=new rf(Zt,o,null,f,Ye),Qe.push({event:Zt,listeners:Pt}),Dt?Zt.data=Dt:(Dt=wu(f),Dt!==null&&(Zt.data=Dt)))),(Dt=xg?uf(o,f):bg(o,f))&&(Ce=Si(Ce,"onBeforeInput"),0<Ce.length&&(Ye=new rf("onBeforeInput","beforeinput",null,f,Ye),Qe.push({event:Ye,listeners:Ce}),Ye.data=Dt))}vr(Qe,l)})}function Rr(o,l,f){return{instance:o,listener:l,currentTarget:f}}function Si(o,l){for(var f=l+"Capture",g=[];o!==null;){var j=o,N=j.stateNode;j.tag===5&&N!==null&&(j=N,N=Fe(o,f),N!=null&&g.unshift(Rr(o,N,j)),N=Fe(o,l),N!=null&&g.push(Rr(o,N,j))),o=o.return}return g}function xr(o){if(o===null)return null;do o=o.return;while(o&&o.tag!==5);return o||null}function xf(o,l,f,g,j){for(var N=l._reactName,U=[];f!==null&&f!==g;){var oe=f,le=oe.alternate,Ce=oe.stateNode;if(le!==null&&le===g)break;oe.tag===5&&Ce!==null&&(oe=Ce,j?(le=Fe(f,N),le!=null&&U.unshift(Rr(f,le,oe))):j||(le=Fe(f,N),le!=null&&U.push(Rr(f,le,oe)))),f=f.return}U.length!==0&&o.push({event:l,listeners:U})}var hc=/\r\n?/g,Mh=/\u0000|\uFFFD/g;function Su(o){return(typeof o=="string"?o:""+o).replace(hc,`
|
|
38
|
+
`).replace(Mh,"")}function _c(o,l,f){if(l=Su(l),Su(o)!==l&&f)throw Error(n(425))}function pc(){}var Nu=null,bf=null;function $u(o,l){return o==="textarea"||o==="noscript"||typeof l.children=="string"||typeof l.children=="number"||typeof l.dangerouslySetInnerHTML=="object"&&l.dangerouslySetInnerHTML!==null&&l.dangerouslySetInnerHTML.__html!=null}var kf=typeof setTimeout=="function"?setTimeout:void 0,Rh=typeof clearTimeout=="function"?clearTimeout:void 0,Lh=typeof Promise=="function"?Promise:void 0,Ih=typeof queueMicrotask=="function"?queueMicrotask:typeof Lh<"u"?function(o){return Lh.resolve(null).then(o).catch(jg)}:kf;function jg(o){setTimeout(function(){throw o})}function Cu(o,l){var f=l,g=0;do{var j=f.nextSibling;if(o.removeChild(f),j&&j.nodeType===8)if(f=j.data,f==="/$"){if(g===0){o.removeChild(j),wa(l);return}g--}else f!=="$"&&f!=="$?"&&f!=="$!"||g++;f=j}while(f);wa(l)}function Yo(o){for(;o!=null;o=o.nextSibling){var l=o.nodeType;if(l===1||l===3)break;if(l===8){if(l=o.data,l==="$"||l==="$!"||l==="$?")break;if(l==="/$")return null}}return o}function jf(o){o=o.previousSibling;for(var l=0;o;){if(o.nodeType===8){var f=o.data;if(f==="$"||f==="$!"||f==="$?"){if(l===0)return o;l--}else f==="/$"&&l++}o=o.previousSibling}return null}var Ki=Math.random().toString(36).slice(2),Ji="__reactFiber$"+Ki,So="__reactProps$"+Ki,Ni="__reactContainer$"+Ki,hl="__reactEvents$"+Ki,Oh="__reactListeners$"+Ki,_l="__reactHandles$"+Ki;function Ea(o){var l=o[Ji];if(l)return l;for(var f=o.parentNode;f;){if(l=f[Ni]||f[Ji]){if(f=l.alternate,l.child!==null||f!==null&&f.child!==null)for(o=jf(o);o!==null;){if(f=o[Ji])return f;o=jf(o)}return l}o=f,f=o.parentNode}return null}function Xo(o){return o=o[Ji]||o[Ni],!o||o.tag!==5&&o.tag!==6&&o.tag!==13&&o.tag!==3?null:o}function pl(o){if(o.tag===5||o.tag===6)return o.stateNode;throw Error(n(33))}function No(o){return o[So]||null}var Sf=[],$o=-1;function Zo(o){return{current:o}}function En(o){0>$o||(o.current=Sf[$o],Sf[$o]=null,$o--)}function Vn(o,l){$o++,Sf[$o]=o.current,o.current=l}var li={},$s=Zo(li),br=Zo(!1),Co=li;function Yi(o,l){var f=o.type.contextTypes;if(!f)return li;var g=o.stateNode;if(g&&g.__reactInternalMemoizedUnmaskedChildContext===l)return g.__reactInternalMemoizedMaskedChildContext;var j={},N;for(N in f)j[N]=l[N];return g&&(o=o.stateNode,o.__reactInternalMemoizedUnmaskedChildContext=l,o.__reactInternalMemoizedMaskedChildContext=j),j}function rr(o){return o=o.childContextTypes,o!=null}function Eo(){En(br),En($s)}function Eu(o,l,f){if($s.current!==li)throw Error(n(168));Vn($s,l),Vn(br,f)}function Ph(o,l,f){var g=o.stateNode;if(l=l.childContextTypes,typeof g.getChildContext!="function")return f;g=g.getChildContext();for(var j in g)if(!(j in l))throw Error(n(108,ge(o)||"Unknown",j));return ne({},f,g)}function gl(o){return o=(o=o.stateNode)&&o.__reactInternalMemoizedMergedChildContext||li,Co=$s.current,Vn($s,o),Vn(br,br.current),!0}function Au(o,l,f){var g=o.stateNode;if(!g)throw Error(n(169));f?(o=Ph(o,l,Co),g.__reactInternalMemoizedMergedChildContext=o,En(br),En($s),Vn($s,o)):En(br),Vn(br,f)}var Ao=null,Tu=!1,Qo=!1;function ir(o){Ao===null?Ao=[o]:Ao.push(o)}function Mu(o){Tu=!0,ir(o)}function Xi(){if(!Qo&&Ao!==null){Qo=!0;var o=0,l=Sn;try{var f=Ao;for(Sn=1;o<f.length;o++){var g=f[o];do g=g(!0);while(g!==null)}Ao=null,Tu=!1}catch(j){throw Ao!==null&&(Ao=Ao.slice(o+1)),Mn(Ns,Xi),j}finally{Sn=l,Qo=!1}}return null}var yl=[],wl=0,vl=null,Ru=0,kr=[],Kr=0,Zi=null,Qi=1,eo="";function Aa(o,l){yl[wl++]=Ru,yl[wl++]=vl,vl=o,Ru=l}function Nf(o,l,f){kr[Kr++]=Qi,kr[Kr++]=eo,kr[Kr++]=Zi,Zi=o;var g=Qi;o=eo;var j=32-nr(g)-1;g&=~(1<<j),f+=1;var N=32-nr(l)+j;if(30<N){var U=j-j%5;N=(g&(1<<U)-1).toString(32),g>>=U,j-=U,Qi=1<<32-nr(l)+j|f<<j|g,eo=N+o}else Qi=1<<N|f<<j|g,eo=o}function Lu(o){o.return!==null&&(Aa(o,1),Nf(o,1,0))}function Iu(o){for(;o===vl;)vl=yl[--wl],yl[wl]=null,Ru=yl[--wl],yl[wl]=null;for(;o===Zi;)Zi=kr[--Kr],kr[Kr]=null,eo=kr[--Kr],kr[Kr]=null,Qi=kr[--Kr],kr[Kr]=null}var Jr=null,Lr=null,Gn=!1,$i=null;function Dh(o,l){var f=nt(5,null,null,0);f.elementType="DELETED",f.stateNode=l,f.return=o,l=o.deletions,l===null?(o.deletions=[f],o.flags|=16):l.push(f)}function Fh(o,l){switch(o.tag){case 5:var f=o.type;return l=l.nodeType!==1||f.toLowerCase()!==l.nodeName.toLowerCase()?null:l,l!==null?(o.stateNode=l,Jr=o,Lr=Yo(l.firstChild),!0):!1;case 6:return l=o.pendingProps===""||l.nodeType!==3?null:l,l!==null?(o.stateNode=l,Jr=o,Lr=null,!0):!1;case 13:return l=l.nodeType!==8?null:l,l!==null?(f=Zi!==null?{id:Qi,overflow:eo}:null,o.memoizedState={dehydrated:l,treeContext:f,retryLane:1073741824},f=nt(18,null,null,0),f.stateNode=l,f.return=o,o.child=f,Jr=o,Lr=null,!0):!1;default:return!1}}function $f(o){return(o.mode&1)!==0&&(o.flags&128)===0}function gc(o){if(Gn){var l=Lr;if(l){var f=l;if(!Fh(o,l)){if($f(o))throw Error(n(418));l=Yo(f.nextSibling);var g=Jr;l&&Fh(o,l)?Dh(g,f):(o.flags=o.flags&-4097|2,Gn=!1,Jr=o)}}else{if($f(o))throw Error(n(418));o.flags=o.flags&-4097|2,Gn=!1,Jr=o}}}function zh(o){for(o=o.return;o!==null&&o.tag!==5&&o.tag!==3&&o.tag!==13;)o=o.return;Jr=o}function xl(o){if(o!==Jr)return!1;if(!Gn)return zh(o),Gn=!0,!1;var l;if((l=o.tag!==3)&&!(l=o.tag!==5)&&(l=o.type,l=l!=="head"&&l!=="body"&&!$u(o.type,o.memoizedProps)),l&&(l=Lr)){if($f(o))throw Bh(),Error(n(418));for(;l;)Dh(o,l),l=Yo(l.nextSibling)}if(zh(o),o.tag===13){if(o=o.memoizedState,o=o!==null?o.dehydrated:null,!o)throw Error(n(317));e:{for(o=o.nextSibling,l=0;o;){if(o.nodeType===8){var f=o.data;if(f==="/$"){if(l===0){Lr=Yo(o.nextSibling);break e}l--}else f!=="$"&&f!=="$!"&&f!=="$?"||l++}o=o.nextSibling}Lr=null}}else Lr=Jr?Yo(o.stateNode.nextSibling):null;return!0}function Bh(){for(var o=Lr;o;)o=Yo(o.nextSibling)}function Ta(){Lr=Jr=null,Gn=!1}function Cf(o){$i===null?$i=[o]:$i.push(o)}var Ef=E.ReactCurrentBatchConfig;function qe(o,l,f){if(o=f.ref,o!==null&&typeof o!="function"&&typeof o!="object"){if(f._owner){if(f=f._owner,f){if(f.tag!==1)throw Error(n(309));var g=f.stateNode}if(!g)throw Error(n(147,o));var j=g,N=""+o;return l!==null&&l.ref!==null&&typeof l.ref=="function"&&l.ref._stringRef===N?l.ref:(l=function(U){var oe=j.refs;U===null?delete oe[N]:oe[N]=U},l._stringRef=N,l)}if(typeof o!="string")throw Error(n(284));if(!f._owner)throw Error(n(290,o))}return o}function Kn(o,l){throw o=Object.prototype.toString.call(l),Error(n(31,o==="[object Object]"?"object with keys {"+Object.keys(l).join(", ")+"}":o))}function Ou(o){var l=o._init;return l(o._payload)}function Af(o){function l(xe,de){if(o){var ke=xe.deletions;ke===null?(xe.deletions=[de],xe.flags|=16):ke.push(de)}}function f(xe,de){if(!o)return null;for(;de!==null;)l(xe,de),de=de.sibling;return null}function g(xe,de){for(xe=new Map;de!==null;)de.key!==null?xe.set(de.key,de):xe.set(de.index,de),de=de.sibling;return xe}function j(xe,de){return xe=it(xe,de),xe.index=0,xe.sibling=null,xe}function N(xe,de,ke){return xe.index=ke,o?(ke=xe.alternate,ke!==null?(ke=ke.index,ke<de?(xe.flags|=2,de):ke):(xe.flags|=2,de)):(xe.flags|=1048576,de)}function U(xe){return o&&xe.alternate===null&&(xe.flags|=2),xe}function oe(xe,de,ke,st){return de===null||de.tag!==6?(de=ur(ke,xe.mode,st),de.return=xe,de):(de=j(de,ke),de.return=xe,de)}function le(xe,de,ke,st){var $t=ke.type;return $t===M?Ye(xe,de,ke.props.children,st,ke.key):de!==null&&(de.elementType===$t||typeof $t=="object"&&$t!==null&&$t.$$typeof===L&&Ou($t)===de.type)?(st=j(de,ke.props),st.ref=qe(xe,de,ke),st.return=xe,st):(st=Bt(ke.type,ke.key,ke.props,null,xe.mode,st),st.ref=qe(xe,de,ke),st.return=xe,st)}function Ce(xe,de,ke,st){return de===null||de.tag!==4||de.stateNode.containerInfo!==ke.containerInfo||de.stateNode.implementation!==ke.implementation?(de=Fr(ke,xe.mode,st),de.return=xe,de):(de=j(de,ke.children||[]),de.return=xe,de)}function Ye(xe,de,ke,st,$t){return de===null||de.tag!==7?(de=Tn(ke,xe.mode,st,$t),de.return=xe,de):(de=j(de,ke),de.return=xe,de)}function Qe(xe,de,ke){if(typeof de=="string"&&de!==""||typeof de=="number")return de=ur(""+de,xe.mode,ke),de.return=xe,de;if(typeof de=="object"&&de!==null){switch(de.$$typeof){case z:return ke=Bt(de.type,de.key,de.props,null,xe.mode,ke),ke.ref=qe(xe,null,de),ke.return=xe,ke;case F:return de=Fr(de,xe.mode,ke),de.return=xe,de;case L:var st=de._init;return Qe(xe,st(de._payload),ke)}if(ye(de)||V(de))return de=Tn(de,xe.mode,ke,null),de.return=xe,de;Kn(xe,de)}return null}function He(xe,de,ke,st){var $t=de!==null?de.key:null;if(typeof ke=="string"&&ke!==""||typeof ke=="number")return $t!==null?null:oe(xe,de,""+ke,st);if(typeof ke=="object"&&ke!==null){switch(ke.$$typeof){case z:return ke.key===$t?le(xe,de,ke,st):null;case F:return ke.key===$t?Ce(xe,de,ke,st):null;case L:return $t=ke._init,He(xe,de,$t(ke._payload),st)}if(ye(ke)||V(ke))return $t!==null?null:Ye(xe,de,ke,st,null);Kn(xe,ke)}return null}function pt(xe,de,ke,st,$t){if(typeof st=="string"&&st!==""||typeof st=="number")return xe=xe.get(ke)||null,oe(de,xe,""+st,$t);if(typeof st=="object"&&st!==null){switch(st.$$typeof){case z:return xe=xe.get(st.key===null?ke:st.key)||null,le(de,xe,st,$t);case F:return xe=xe.get(st.key===null?ke:st.key)||null,Ce(de,xe,st,$t);case L:var Pt=st._init;return pt(xe,de,ke,Pt(st._payload),$t)}if(ye(st)||V(st))return xe=xe.get(ke)||null,Ye(de,xe,st,$t,null);Kn(de,st)}return null}function vt(xe,de,ke,st){for(var $t=null,Pt=null,Dt=de,Zt=de=0,dr=null;Dt!==null&&Zt<ke.length;Zt++){Dt.index>Zt?(dr=Dt,Dt=null):dr=Dt.sibling;var In=He(xe,Dt,ke[Zt],st);if(In===null){Dt===null&&(Dt=dr);break}o&&Dt&&In.alternate===null&&l(xe,Dt),de=N(In,de,Zt),Pt===null?$t=In:Pt.sibling=In,Pt=In,Dt=dr}if(Zt===ke.length)return f(xe,Dt),Gn&&Aa(xe,Zt),$t;if(Dt===null){for(;Zt<ke.length;Zt++)Dt=Qe(xe,ke[Zt],st),Dt!==null&&(de=N(Dt,de,Zt),Pt===null?$t=Dt:Pt.sibling=Dt,Pt=Dt);return Gn&&Aa(xe,Zt),$t}for(Dt=g(xe,Dt);Zt<ke.length;Zt++)dr=pt(Dt,xe,Zt,ke[Zt],st),dr!==null&&(o&&dr.alternate!==null&&Dt.delete(dr.key===null?Zt:dr.key),de=N(dr,de,Zt),Pt===null?$t=dr:Pt.sibling=dr,Pt=dr);return o&&Dt.forEach(function(Dl){return l(xe,Dl)}),Gn&&Aa(xe,Zt),$t}function jt(xe,de,ke,st){var $t=V(ke);if(typeof $t!="function")throw Error(n(150));if(ke=$t.call(ke),ke==null)throw Error(n(151));for(var Pt=$t=null,Dt=de,Zt=de=0,dr=null,In=ke.next();Dt!==null&&!In.done;Zt++,In=ke.next()){Dt.index>Zt?(dr=Dt,Dt=null):dr=Dt.sibling;var Dl=He(xe,Dt,In.value,st);if(Dl===null){Dt===null&&(Dt=dr);break}o&&Dt&&Dl.alternate===null&&l(xe,Dt),de=N(Dl,de,Zt),Pt===null?$t=Dl:Pt.sibling=Dl,Pt=Dl,Dt=dr}if(In.done)return f(xe,Dt),Gn&&Aa(xe,Zt),$t;if(Dt===null){for(;!In.done;Zt++,In=ke.next())In=Qe(xe,In.value,st),In!==null&&(de=N(In,de,Zt),Pt===null?$t=In:Pt.sibling=In,Pt=In);return Gn&&Aa(xe,Zt),$t}for(Dt=g(xe,Dt);!In.done;Zt++,In=ke.next())In=pt(Dt,xe,Zt,In.value,st),In!==null&&(o&&In.alternate!==null&&Dt.delete(In.key===null?Zt:In.key),de=N(In,de,Zt),Pt===null?$t=In:Pt.sibling=In,Pt=In);return o&&Dt.forEach(function(N$){return l(xe,N$)}),Gn&&Aa(xe,Zt),$t}function Ls(xe,de,ke,st){if(typeof ke=="object"&&ke!==null&&ke.type===M&&ke.key===null&&(ke=ke.props.children),typeof ke=="object"&&ke!==null){switch(ke.$$typeof){case z:e:{for(var $t=ke.key,Pt=de;Pt!==null;){if(Pt.key===$t){if($t=ke.type,$t===M){if(Pt.tag===7){f(xe,Pt.sibling),de=j(Pt,ke.props.children),de.return=xe,xe=de;break e}}else if(Pt.elementType===$t||typeof $t=="object"&&$t!==null&&$t.$$typeof===L&&Ou($t)===Pt.type){f(xe,Pt.sibling),de=j(Pt,ke.props),de.ref=qe(xe,Pt,ke),de.return=xe,xe=de;break e}f(xe,Pt);break}else l(xe,Pt);Pt=Pt.sibling}ke.type===M?(de=Tn(ke.props.children,xe.mode,st,ke.key),de.return=xe,xe=de):(st=Bt(ke.type,ke.key,ke.props,null,xe.mode,st),st.ref=qe(xe,de,ke),st.return=xe,xe=st)}return U(xe);case F:e:{for(Pt=ke.key;de!==null;){if(de.key===Pt)if(de.tag===4&&de.stateNode.containerInfo===ke.containerInfo&&de.stateNode.implementation===ke.implementation){f(xe,de.sibling),de=j(de,ke.children||[]),de.return=xe,xe=de;break e}else{f(xe,de);break}else l(xe,de);de=de.sibling}de=Fr(ke,xe.mode,st),de.return=xe,xe=de}return U(xe);case L:return Pt=ke._init,Ls(xe,de,Pt(ke._payload),st)}if(ye(ke))return vt(xe,de,ke,st);if(V(ke))return jt(xe,de,ke,st);Kn(xe,ke)}return typeof ke=="string"&&ke!==""||typeof ke=="number"?(ke=""+ke,de!==null&&de.tag===6?(f(xe,de.sibling),de=j(de,ke),de.return=xe,xe=de):(f(xe,de),de=ur(ke,xe.mode,st),de.return=xe,xe=de),U(xe)):f(xe,de)}return Ls}var To=Af(!0),Uh=Af(!1),Pu=Zo(null),Du=null,bl=null,Fu=null;function zu(){Fu=bl=Du=null}function Tf(o){var l=Pu.current;En(Pu),o._currentValue=l}function kl(o,l,f){for(;o!==null;){var g=o.alternate;if((o.childLanes&l)!==l?(o.childLanes|=l,g!==null&&(g.childLanes|=l)):g!==null&&(g.childLanes&l)!==l&&(g.childLanes|=l),o===f)break;o=o.return}}function Ma(o,l){Du=o,Fu=bl=null,o=o.dependencies,o!==null&&o.firstContext!==null&&((o.lanes&l)!==0&&(Ir=!0),o.firstContext=null)}function ns(o){var l=o._currentValue;if(Fu!==o)if(o={context:o,memoizedValue:l,next:null},bl===null){if(Du===null)throw Error(n(308));bl=o,Du.dependencies={lanes:0,firstContext:o}}else bl=bl.next=o;return l}var sn=null;function Fs(o){sn===null?sn=[o]:sn.push(o)}function Bu(o,l,f,g){var j=l.interleaved;return j===null?(f.next=f,Fs(l)):(f.next=j.next,j.next=f),l.interleaved=f,to(o,g)}function to(o,l){o.lanes|=l;var f=o.alternate;for(f!==null&&(f.lanes|=l),f=o,o=o.return;o!==null;)o.childLanes|=l,f=o.alternate,f!==null&&(f.childLanes|=l),f=o,o=o.return;return f.tag===3?f.stateNode:null}var ci=!1;function ea(o){o.updateQueue={baseState:o.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function tn(o,l){o=o.updateQueue,l.updateQueue===o&&(l.updateQueue={baseState:o.baseState,firstBaseUpdate:o.firstBaseUpdate,lastBaseUpdate:o.lastBaseUpdate,shared:o.shared,effects:o.effects})}function Mo(o,l){return{eventTime:o,lane:l,tag:0,payload:null,callback:null,next:null}}function no(o,l,f){var g=o.updateQueue;if(g===null)return null;if(g=g.shared,(xn&2)!==0){var j=g.pending;return j===null?l.next=l:(l.next=j.next,j.next=l),g.pending=l,to(o,f)}return j=g.interleaved,j===null?(l.next=l,Fs(g)):(l.next=j.next,j.next=l),g.interleaved=l,to(o,f)}function Uu(o,l,f){if(l=l.updateQueue,l!==null&&(l=l.shared,(f&4194240)!==0)){var g=l.lanes;g&=o.pendingLanes,f|=g,l.lanes=f,zi(o,f)}}function Wh(o,l){var f=o.updateQueue,g=o.alternate;if(g!==null&&(g=g.updateQueue,f===g)){var j=null,N=null;if(f=f.firstBaseUpdate,f!==null){do{var U={eventTime:f.eventTime,lane:f.lane,tag:f.tag,payload:f.payload,callback:f.callback,next:null};N===null?j=N=U:N=N.next=U,f=f.next}while(f!==null);N===null?j=N=l:N=N.next=l}else j=N=l;f={baseState:g.baseState,firstBaseUpdate:j,lastBaseUpdate:N,shared:g.shared,effects:g.effects},o.updateQueue=f;return}o=f.lastBaseUpdate,o===null?f.firstBaseUpdate=l:o.next=l,f.lastBaseUpdate=l}function Wu(o,l,f,g){var j=o.updateQueue;ci=!1;var N=j.firstBaseUpdate,U=j.lastBaseUpdate,oe=j.shared.pending;if(oe!==null){j.shared.pending=null;var le=oe,Ce=le.next;le.next=null,U===null?N=Ce:U.next=Ce,U=le;var Ye=o.alternate;Ye!==null&&(Ye=Ye.updateQueue,oe=Ye.lastBaseUpdate,oe!==U&&(oe===null?Ye.firstBaseUpdate=Ce:oe.next=Ce,Ye.lastBaseUpdate=le))}if(N!==null){var Qe=j.baseState;U=0,Ye=Ce=le=null,oe=N;do{var He=oe.lane,pt=oe.eventTime;if((g&He)===He){Ye!==null&&(Ye=Ye.next={eventTime:pt,lane:0,tag:oe.tag,payload:oe.payload,callback:oe.callback,next:null});e:{var vt=o,jt=oe;switch(He=l,pt=f,jt.tag){case 1:if(vt=jt.payload,typeof vt=="function"){Qe=vt.call(pt,Qe,He);break e}Qe=vt;break e;case 3:vt.flags=vt.flags&-65537|128;case 0:if(vt=jt.payload,He=typeof vt=="function"?vt.call(pt,Qe,He):vt,He==null)break e;Qe=ne({},Qe,He);break e;case 2:ci=!0}}oe.callback!==null&&oe.lane!==0&&(o.flags|=64,He=j.effects,He===null?j.effects=[oe]:He.push(oe))}else pt={eventTime:pt,lane:He,tag:oe.tag,payload:oe.payload,callback:oe.callback,next:null},Ye===null?(Ce=Ye=pt,le=Qe):Ye=Ye.next=pt,U|=He;if(oe=oe.next,oe===null){if(oe=j.shared.pending,oe===null)break;He=oe,oe=He.next,He.next=null,j.lastBaseUpdate=He,j.shared.pending=null}}while(!0);if(Ye===null&&(le=Qe),j.baseState=le,j.firstBaseUpdate=Ce,j.lastBaseUpdate=Ye,l=j.shared.interleaved,l!==null){j=l;do U|=j.lane,j=j.next;while(j!==l)}else N===null&&(j.shared.lanes=0);Da|=U,o.lanes=U,o.memoizedState=Qe}}function qh(o,l,f){if(o=l.effects,l.effects=null,o!==null)for(l=0;l<o.length;l++){var g=o[l],j=g.callback;if(j!==null){if(g.callback=null,g=f,typeof j!="function")throw Error(n(191,j));j.call(g)}}}var Ra={},zs=Zo(Ra),jl=Zo(Ra),Ci=Zo(Ra);function Gs(o){if(o===Ra)throw Error(n(174));return o}function Sl(o,l){switch(Vn(Ci,l),Vn(jl,o),Vn(zs,Ra),o=l.nodeType,o){case 9:case 11:l=(l=l.documentElement)?l.namespaceURI:Be(null,"");break;default:o=o===8?l.parentNode:l,l=o.namespaceURI||null,o=o.tagName,l=Be(l,o)}En(zs),Vn(zs,l)}function Nl(){En(zs),En(jl),En(Ci)}function Hh(o){Gs(Ci.current);var l=Gs(zs.current),f=Be(l,o.type);l!==f&&(Vn(jl,o),Vn(zs,f))}function yc(o){jl.current===o&&(En(zs),En(jl))}var as=Zo(0);function $l(o){for(var l=o;l!==null;){if(l.tag===13){var f=l.memoizedState;if(f!==null&&(f=f.dehydrated,f===null||f.data==="$?"||f.data==="$!"))return l}else if(l.tag===19&&l.memoizedProps.revealOrder!==void 0){if((l.flags&128)!==0)return l}else if(l.child!==null){l.child.return=l,l=l.child;continue}if(l===o)break;for(;l.sibling===null;){if(l.return===null||l.return===o)return null;l=l.return}l.sibling.return=l.return,l=l.sibling}return null}var Mf=[];function ms(){for(var o=0;o<Mf.length;o++)Mf[o]._workInProgressVersionPrimary=null;Mf.length=0}var wc=E.ReactCurrentDispatcher,vc=E.ReactCurrentBatchConfig,bs=0,ls=null,hs=null,Cs=null,Yr=!1,La=!1,xc=0,Sg=0;function or(){throw Error(n(321))}function bc(o,l){if(l===null)return!1;for(var f=0;f<l.length&&f<o.length;f++)if(!wr(o[f],l[f]))return!1;return!0}function kc(o,l,f,g,j,N){if(bs=N,ls=l,l.memoizedState=null,l.updateQueue=null,l.lanes=0,wc.current=o===null||o.memoizedState===null?r_:$g,o=f(g,j),La){N=0;do{if(La=!1,xc=0,25<=N)throw Error(n(301));N+=1,Cs=hs=null,l.updateQueue=null,wc.current=Cg,o=f(g,j)}while(La)}if(wc.current=Al,l=hs!==null&&hs.next!==null,bs=0,Cs=hs=ls=null,Yr=!1,l)throw Error(n(300));return o}function Rf(){var o=xc!==0;return xc=0,o}function ui(){var o={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return Cs===null?ls.memoizedState=Cs=o:Cs=Cs.next=o,Cs}function di(){if(hs===null){var o=ls.alternate;o=o!==null?o.memoizedState:null}else o=hs.next;var l=Cs===null?ls.memoizedState:Cs.next;if(l!==null)Cs=l,hs=o;else{if(o===null)throw Error(n(310));hs=o,o={memoizedState:hs.memoizedState,baseState:hs.baseState,baseQueue:hs.baseQueue,queue:hs.queue,next:null},Cs===null?ls.memoizedState=Cs=o:Cs=Cs.next=o}return Cs}function Ei(o,l){return typeof l=="function"?l(o):l}function Lf(o){var l=di(),f=l.queue;if(f===null)throw Error(n(311));f.lastRenderedReducer=o;var g=hs,j=g.baseQueue,N=f.pending;if(N!==null){if(j!==null){var U=j.next;j.next=N.next,N.next=U}g.baseQueue=j=N,f.pending=null}if(j!==null){N=j.next,g=g.baseState;var oe=U=null,le=null,Ce=N;do{var Ye=Ce.lane;if((bs&Ye)===Ye)le!==null&&(le=le.next={lane:0,action:Ce.action,hasEagerState:Ce.hasEagerState,eagerState:Ce.eagerState,next:null}),g=Ce.hasEagerState?Ce.eagerState:o(g,Ce.action);else{var Qe={lane:Ye,action:Ce.action,hasEagerState:Ce.hasEagerState,eagerState:Ce.eagerState,next:null};le===null?(oe=le=Qe,U=g):le=le.next=Qe,ls.lanes|=Ye,Da|=Ye}Ce=Ce.next}while(Ce!==null&&Ce!==N);le===null?U=g:le.next=oe,wr(g,l.memoizedState)||(Ir=!0),l.memoizedState=g,l.baseState=U,l.baseQueue=le,f.lastRenderedState=g}if(o=f.interleaved,o!==null){j=o;do N=j.lane,ls.lanes|=N,Da|=N,j=j.next;while(j!==o)}else j===null&&(f.lanes=0);return[l.memoizedState,f.dispatch]}function Cl(o){var l=di(),f=l.queue;if(f===null)throw Error(n(311));f.lastRenderedReducer=o;var g=f.dispatch,j=f.pending,N=l.memoizedState;if(j!==null){f.pending=null;var U=j=j.next;do N=o(N,U.action),U=U.next;while(U!==j);wr(N,l.memoizedState)||(Ir=!0),l.memoizedState=N,l.baseQueue===null&&(l.baseState=N),f.lastRenderedState=N}return[N,g]}function Vh(){}function If(o,l){var f=ls,g=di(),j=l(),N=!wr(g.memoizedState,j);if(N&&(g.memoizedState=j,Ir=!0),g=g.queue,Sc(Kh.bind(null,f,g,o),[o]),g.getSnapshot!==l||N||Cs!==null&&Cs.memoizedState.tag&1){if(f.flags|=2048,jc(9,Gh.bind(null,f,g,j,l),void 0,null),As===null)throw Error(n(349));(bs&30)!==0||so(f,l,j)}return j}function so(o,l,f){o.flags|=16384,o={getSnapshot:l,value:f},l=ls.updateQueue,l===null?(l={lastEffect:null,stores:null},ls.updateQueue=l,l.stores=[o]):(f=l.stores,f===null?l.stores=[o]:f.push(o))}function Gh(o,l,f,g){l.value=f,l.getSnapshot=g,Of(l)&&Jh(o)}function Kh(o,l,f){return f(function(){Of(l)&&Jh(o)})}function Of(o){var l=o.getSnapshot;o=o.value;try{var f=l();return!wr(o,f)}catch{return!0}}function Jh(o){var l=to(o,1);l!==null&&_i(l,o,1,-1)}function Yh(o){var l=ui();return typeof o=="function"&&(o=o()),l.memoizedState=l.baseState=o,o={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:Ei,lastRenderedState:o},l.queue=o,o=o.dispatch=ro.bind(null,ls,o),[l.memoizedState,o]}function jc(o,l,f,g){return o={tag:o,create:l,destroy:f,deps:g,next:null},l=ls.updateQueue,l===null?(l={lastEffect:null,stores:null},ls.updateQueue=l,l.lastEffect=o.next=o):(f=l.lastEffect,f===null?l.lastEffect=o.next=o:(g=f.next,f.next=o,o.next=g,l.lastEffect=o)),o}function Xh(){return di().memoizedState}function hn(o,l,f,g){var j=ui();ls.flags|=o,j.memoizedState=jc(1|l,f,void 0,g===void 0?null:g)}function Es(o,l,f,g){var j=di();g=g===void 0?null:g;var N=void 0;if(hs!==null){var U=hs.memoizedState;if(N=U.destroy,g!==null&&bc(g,U.deps)){j.memoizedState=jc(l,f,N,g);return}}ls.flags|=o,j.memoizedState=jc(1|l,f,N,g)}function ar(o,l){return hn(8390656,8,o,l)}function Sc(o,l){return Es(2048,8,o,l)}function Nc(o,l){return Es(4,2,o,l)}function Pf(o,l){return Es(4,4,o,l)}function Zh(o,l){if(typeof l=="function")return o=o(),l(o),function(){l(null)};if(l!=null)return o=o(),l.current=o,function(){l.current=null}}function Qh(o,l,f){return f=f!=null?f.concat([o]):null,Es(4,4,Zh.bind(null,l,o),f)}function qu(){}function $c(o,l){var f=di();l=l===void 0?null:l;var g=f.memoizedState;return g!==null&&l!==null&&bc(l,g[1])?g[0]:(f.memoizedState=[o,l],o)}function e_(o,l){var f=di();l=l===void 0?null:l;var g=f.memoizedState;return g!==null&&l!==null&&bc(l,g[1])?g[0]:(o=o(),f.memoizedState=[o,l],o)}function t_(o,l,f){return(bs&21)===0?(o.baseState&&(o.baseState=!1,Ir=!0),o.memoizedState=f):(wr(f,l)||(f=Rs(),ls.lanes|=f,Da|=f,o.baseState=!0),l)}function Ng(o,l){var f=Sn;Sn=f!==0&&4>f?f:4,o(!0);var g=vc.transition;vc.transition={};try{o(!1),l()}finally{Sn=f,vc.transition=g}}function Df(){return di().memoizedState}function n_(o,l,f){var g=Do(o);if(f={lane:g,action:f,hasEagerState:!1,eagerState:null,next:null},Hu(o))El(l,f);else if(f=Bu(o,l,f,g),f!==null){var j=Sr();_i(f,o,g,j),s_(f,l,g)}}function ro(o,l,f){var g=Do(o),j={lane:g,action:f,hasEagerState:!1,eagerState:null,next:null};if(Hu(o))El(l,j);else{var N=o.alternate;if(o.lanes===0&&(N===null||N.lanes===0)&&(N=l.lastRenderedReducer,N!==null))try{var U=l.lastRenderedState,oe=N(U,f);if(j.hasEagerState=!0,j.eagerState=oe,wr(oe,U)){var le=l.interleaved;le===null?(j.next=j,Fs(l)):(j.next=le.next,le.next=j),l.interleaved=j;return}}catch{}finally{}f=Bu(o,l,j,g),f!==null&&(j=Sr(),_i(f,o,g,j),s_(f,l,g))}}function Hu(o){var l=o.alternate;return o===ls||l!==null&&l===ls}function El(o,l){La=Yr=!0;var f=o.pending;f===null?l.next=l:(l.next=f.next,f.next=l),o.pending=l}function s_(o,l,f){if((f&4194240)!==0){var g=l.lanes;g&=o.pendingLanes,f|=g,l.lanes=f,zi(o,f)}}var Al={readContext:ns,useCallback:or,useContext:or,useEffect:or,useImperativeHandle:or,useInsertionEffect:or,useLayoutEffect:or,useMemo:or,useReducer:or,useRef:or,useState:or,useDebugValue:or,useDeferredValue:or,useTransition:or,useMutableSource:or,useSyncExternalStore:or,useId:or,unstable_isNewReconciler:!1},r_={readContext:ns,useCallback:function(o,l){return ui().memoizedState=[o,l===void 0?null:l],o},useContext:ns,useEffect:ar,useImperativeHandle:function(o,l,f){return f=f!=null?f.concat([o]):null,hn(4194308,4,Zh.bind(null,l,o),f)},useLayoutEffect:function(o,l){return hn(4194308,4,o,l)},useInsertionEffect:function(o,l){return hn(4,2,o,l)},useMemo:function(o,l){var f=ui();return l=l===void 0?null:l,o=o(),f.memoizedState=[o,l],o},useReducer:function(o,l,f){var g=ui();return l=f!==void 0?f(l):l,g.memoizedState=g.baseState=l,o={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:o,lastRenderedState:l},g.queue=o,o=o.dispatch=n_.bind(null,ls,o),[g.memoizedState,o]},useRef:function(o){var l=ui();return o={current:o},l.memoizedState=o},useState:Yh,useDebugValue:qu,useDeferredValue:function(o){return ui().memoizedState=o},useTransition:function(){var o=Yh(!1),l=o[0];return o=Ng.bind(null,o[1]),ui().memoizedState=o,[l,o]},useMutableSource:function(){},useSyncExternalStore:function(o,l,f){var g=ls,j=ui();if(Gn){if(f===void 0)throw Error(n(407));f=f()}else{if(f=l(),As===null)throw Error(n(349));(bs&30)!==0||so(g,l,f)}j.memoizedState=f;var N={value:f,getSnapshot:l};return j.queue=N,ar(Kh.bind(null,g,N,o),[o]),g.flags|=2048,jc(9,Gh.bind(null,g,N,f,l),void 0,null),f},useId:function(){var o=ui(),l=As.identifierPrefix;if(Gn){var f=eo,g=Qi;f=(g&~(1<<32-nr(g)-1)).toString(32)+f,l=":"+l+"R"+f,f=xc++,0<f&&(l+="H"+f.toString(32)),l+=":"}else f=Sg++,l=":"+l+"r"+f.toString(32)+":";return o.memoizedState=l},unstable_isNewReconciler:!1},$g={readContext:ns,useCallback:$c,useContext:ns,useEffect:Sc,useImperativeHandle:Qh,useInsertionEffect:Nc,useLayoutEffect:Pf,useMemo:e_,useReducer:Lf,useRef:Xh,useState:function(){return Lf(Ei)},useDebugValue:qu,useDeferredValue:function(o){var l=di();return t_(l,hs.memoizedState,o)},useTransition:function(){var o=Lf(Ei)[0],l=di().memoizedState;return[o,l]},useMutableSource:Vh,useSyncExternalStore:If,useId:Df,unstable_isNewReconciler:!1},Cg={readContext:ns,useCallback:$c,useContext:ns,useEffect:Sc,useImperativeHandle:Qh,useInsertionEffect:Nc,useLayoutEffect:Pf,useMemo:e_,useReducer:Cl,useRef:Xh,useState:function(){return Cl(Ei)},useDebugValue:qu,useDeferredValue:function(o){var l=di();return hs===null?l.memoizedState=o:t_(l,hs.memoizedState,o)},useTransition:function(){var o=Cl(Ei)[0],l=di().memoizedState;return[o,l]},useMutableSource:Vh,useSyncExternalStore:If,useId:Df,unstable_isNewReconciler:!1};function Ai(o,l){if(o&&o.defaultProps){l=ne({},l),o=o.defaultProps;for(var f in o)l[f]===void 0&&(l[f]=o[f]);return l}return l}function Ff(o,l,f,g){l=o.memoizedState,f=f(g,l),f=f==null?l:ne({},l,f),o.memoizedState=f,o.lanes===0&&(o.updateQueue.baseState=f)}var Vu={isMounted:function(o){return(o=o._reactInternals)?Ht(o)===o:!1},enqueueSetState:function(o,l,f){o=o._reactInternals;var g=Sr(),j=Do(o),N=Mo(g,j);N.payload=l,f!=null&&(N.callback=f),l=no(o,N,j),l!==null&&(_i(l,o,j,g),Uu(l,o,j))},enqueueReplaceState:function(o,l,f){o=o._reactInternals;var g=Sr(),j=Do(o),N=Mo(g,j);N.tag=1,N.payload=l,f!=null&&(N.callback=f),l=no(o,N,j),l!==null&&(_i(l,o,j,g),Uu(l,o,j))},enqueueForceUpdate:function(o,l){o=o._reactInternals;var f=Sr(),g=Do(o),j=Mo(f,g);j.tag=2,l!=null&&(j.callback=l),l=no(o,j,g),l!==null&&(_i(l,o,g,f),Uu(l,o,g))}};function i_(o,l,f,g,j,N,U){return o=o.stateNode,typeof o.shouldComponentUpdate=="function"?o.shouldComponentUpdate(g,N,U):l.prototype&&l.prototype.isPureReactComponent?!Vi(f,g)||!Vi(j,N):!0}function zf(o,l,f){var g=!1,j=li,N=l.contextType;return typeof N=="object"&&N!==null?N=ns(N):(j=rr(l)?Co:$s.current,g=l.contextTypes,N=(g=g!=null)?Yi(o,j):li),l=new l(f,N),o.memoizedState=l.state!==null&&l.state!==void 0?l.state:null,l.updater=Vu,o.stateNode=l,l._reactInternals=o,g&&(o=o.stateNode,o.__reactInternalMemoizedUnmaskedChildContext=j,o.__reactInternalMemoizedMaskedChildContext=N),l}function Gu(o,l,f,g){o=l.state,typeof l.componentWillReceiveProps=="function"&&l.componentWillReceiveProps(f,g),typeof l.UNSAFE_componentWillReceiveProps=="function"&&l.UNSAFE_componentWillReceiveProps(f,g),l.state!==o&&Vu.enqueueReplaceState(l,l.state,null)}function Bf(o,l,f,g){var j=o.stateNode;j.props=f,j.state=o.memoizedState,j.refs={},ea(o);var N=l.contextType;typeof N=="object"&&N!==null?j.context=ns(N):(N=rr(l)?Co:$s.current,j.context=Yi(o,N)),j.state=o.memoizedState,N=l.getDerivedStateFromProps,typeof N=="function"&&(Ff(o,l,N,f),j.state=o.memoizedState),typeof l.getDerivedStateFromProps=="function"||typeof j.getSnapshotBeforeUpdate=="function"||typeof j.UNSAFE_componentWillMount!="function"&&typeof j.componentWillMount!="function"||(l=j.state,typeof j.componentWillMount=="function"&&j.componentWillMount(),typeof j.UNSAFE_componentWillMount=="function"&&j.UNSAFE_componentWillMount(),l!==j.state&&Vu.enqueueReplaceState(j,j.state,null),Wu(o,f,j,g),j.state=o.memoizedState),typeof j.componentDidMount=="function"&&(o.flags|=4194308)}function Tl(o,l){try{var f="",g=l;do f+=ae(g),g=g.return;while(g);var j=f}catch(N){j=`
|
|
39
|
+
Error generating stack: `+N.message+`
|
|
40
|
+
`+N.stack}return{value:o,source:l,stack:j,digest:null}}function Ml(o,l,f){return{value:o,source:null,stack:f??null,digest:l??null}}function Uf(o,l){try{console.error(l.value)}catch(f){setTimeout(function(){throw f})}}var Ia=typeof WeakMap=="function"?WeakMap:Map;function lr(o,l,f){f=Mo(-1,f),f.tag=3,f.payload={element:null};var g=l.value;return f.callback=function(){lo||(lo=!0,Yf=g),Uf(o,l)},f}function Bs(o,l,f){f=Mo(-1,f),f.tag=3;var g=o.type.getDerivedStateFromError;if(typeof g=="function"){var j=l.value;f.payload=function(){return g(j)},f.callback=function(){Uf(o,l)}}var N=o.stateNode;return N!==null&&typeof N.componentDidCatch=="function"&&(f.callback=function(){Uf(o,l),typeof g!="function"&&(hi===null?hi=new Set([this]):hi.add(this));var U=l.stack;this.componentDidCatch(l.value,{componentStack:U!==null?U:""})}),f}function Ti(o,l,f){var g=o.pingCache;if(g===null){g=o.pingCache=new Ia;var j=new Set;g.set(l,j)}else j=g.get(l),j===void 0&&(j=new Set,g.set(l,j));j.has(f)||(j.add(f),o=We.bind(null,o,l,f),l.then(o,o))}function Ro(o){do{var l;if((l=o.tag===13)&&(l=o.memoizedState,l=l!==null?l.dehydrated!==null:!0),l)return o;o=o.return}while(o!==null);return null}function Lo(o,l,f,g,j){return(o.mode&1)===0?(o===l?o.flags|=65536:(o.flags|=128,f.flags|=131072,f.flags&=-52805,f.tag===1&&(f.alternate===null?f.tag=17:(l=Mo(-1,1),l.tag=2,no(f,l,1))),f.lanes|=1),o):(o.flags|=65536,o.lanes=j,o)}var Mi=E.ReactCurrentOwner,Ir=!1;function Us(o,l,f,g){l.child=o===null?Uh(l,null,f,g):To(l,o.child,f,g)}function o_(o,l,f,g,j){f=f.render;var N=l.ref;return Ma(l,j),g=kc(o,l,f,g,N,j),f=Rf(),o!==null&&!Ir?(l.updateQueue=o.updateQueue,l.flags&=-2053,o.lanes&=~j,ks(o,l,j)):(Gn&&f&&Lu(l),l.flags|=1,Us(o,l,g,j),l.child)}function Ku(o,l,f,g,j){if(o===null){var N=f.type;return typeof N=="function"&&!fn(N)&&N.defaultProps===void 0&&f.compare===null&&f.defaultProps===void 0?(l.tag=15,l.type=N,a_(o,l,N,g,j)):(o=Bt(f.type,null,g,l,l.mode,j),o.ref=l.ref,o.return=l,l.child=o)}if(N=o.child,(o.lanes&j)===0){var U=N.memoizedProps;if(f=f.compare,f=f!==null?f:Vi,f(U,g)&&o.ref===l.ref)return ks(o,l,j)}return l.flags|=1,o=it(N,g),o.ref=l.ref,o.return=l,l.child=o}function a_(o,l,f,g,j){if(o!==null){var N=o.memoizedProps;if(Vi(N,g)&&o.ref===l.ref)if(Ir=!1,l.pendingProps=g=N,(o.lanes&j)!==0)(o.flags&131072)!==0&&(Ir=!0);else return l.lanes=o.lanes,ks(o,l,j)}return Io(o,l,f,g,j)}function l_(o,l,f){var g=l.pendingProps,j=g.children,N=o!==null?o.memoizedState:null;if(g.mode==="hidden")if((l.mode&1)===0)l.memoizedState={baseLanes:0,cachePool:null,transitions:null},Vn(Pa,Pr),Pr|=f;else{if((f&1073741824)===0)return o=N!==null?N.baseLanes|f:f,l.lanes=l.childLanes=1073741824,l.memoizedState={baseLanes:o,cachePool:null,transitions:null},l.updateQueue=null,Vn(Pa,Pr),Pr|=o,null;l.memoizedState={baseLanes:0,cachePool:null,transitions:null},g=N!==null?N.baseLanes:f,Vn(Pa,Pr),Pr|=g}else N!==null?(g=N.baseLanes|f,l.memoizedState=null):g=f,Vn(Pa,Pr),Pr|=g;return Us(o,l,j,f),l.child}function Wf(o,l){var f=l.ref;(o===null&&f!==null||o!==null&&o.ref!==f)&&(l.flags|=512,l.flags|=2097152)}function Io(o,l,f,g,j){var N=rr(f)?Co:$s.current;return N=Yi(l,N),Ma(l,j),f=kc(o,l,f,g,N,j),g=Rf(),o!==null&&!Ir?(l.updateQueue=o.updateQueue,l.flags&=-2053,o.lanes&=~j,ks(o,l,j)):(Gn&&g&&Lu(l),l.flags|=1,Us(o,l,f,j),l.child)}function Rl(o,l,f,g,j){if(rr(f)){var N=!0;gl(l)}else N=!1;if(Ma(l,j),l.stateNode===null)Zu(o,l),zf(l,f,g),Bf(l,f,g,j),g=!0;else if(o===null){var U=l.stateNode,oe=l.memoizedProps;U.props=oe;var le=U.context,Ce=f.contextType;typeof Ce=="object"&&Ce!==null?Ce=ns(Ce):(Ce=rr(f)?Co:$s.current,Ce=Yi(l,Ce));var Ye=f.getDerivedStateFromProps,Qe=typeof Ye=="function"||typeof U.getSnapshotBeforeUpdate=="function";Qe||typeof U.UNSAFE_componentWillReceiveProps!="function"&&typeof U.componentWillReceiveProps!="function"||(oe!==g||le!==Ce)&&Gu(l,U,g,Ce),ci=!1;var He=l.memoizedState;U.state=He,Wu(l,g,U,j),le=l.memoizedState,oe!==g||He!==le||br.current||ci?(typeof Ye=="function"&&(Ff(l,f,Ye,g),le=l.memoizedState),(oe=ci||i_(l,f,oe,g,He,le,Ce))?(Qe||typeof U.UNSAFE_componentWillMount!="function"&&typeof U.componentWillMount!="function"||(typeof U.componentWillMount=="function"&&U.componentWillMount(),typeof U.UNSAFE_componentWillMount=="function"&&U.UNSAFE_componentWillMount()),typeof U.componentDidMount=="function"&&(l.flags|=4194308)):(typeof U.componentDidMount=="function"&&(l.flags|=4194308),l.memoizedProps=g,l.memoizedState=le),U.props=g,U.state=le,U.context=Ce,g=oe):(typeof U.componentDidMount=="function"&&(l.flags|=4194308),g=!1)}else{U=l.stateNode,tn(o,l),oe=l.memoizedProps,Ce=l.type===l.elementType?oe:Ai(l.type,oe),U.props=Ce,Qe=l.pendingProps,He=U.context,le=f.contextType,typeof le=="object"&&le!==null?le=ns(le):(le=rr(f)?Co:$s.current,le=Yi(l,le));var pt=f.getDerivedStateFromProps;(Ye=typeof pt=="function"||typeof U.getSnapshotBeforeUpdate=="function")||typeof U.UNSAFE_componentWillReceiveProps!="function"&&typeof U.componentWillReceiveProps!="function"||(oe!==Qe||He!==le)&&Gu(l,U,g,le),ci=!1,He=l.memoizedState,U.state=He,Wu(l,g,U,j);var vt=l.memoizedState;oe!==Qe||He!==vt||br.current||ci?(typeof pt=="function"&&(Ff(l,f,pt,g),vt=l.memoizedState),(Ce=ci||i_(l,f,Ce,g,He,vt,le)||!1)?(Ye||typeof U.UNSAFE_componentWillUpdate!="function"&&typeof U.componentWillUpdate!="function"||(typeof U.componentWillUpdate=="function"&&U.componentWillUpdate(g,vt,le),typeof U.UNSAFE_componentWillUpdate=="function"&&U.UNSAFE_componentWillUpdate(g,vt,le)),typeof U.componentDidUpdate=="function"&&(l.flags|=4),typeof U.getSnapshotBeforeUpdate=="function"&&(l.flags|=1024)):(typeof U.componentDidUpdate!="function"||oe===o.memoizedProps&&He===o.memoizedState||(l.flags|=4),typeof U.getSnapshotBeforeUpdate!="function"||oe===o.memoizedProps&&He===o.memoizedState||(l.flags|=1024),l.memoizedProps=g,l.memoizedState=vt),U.props=g,U.state=vt,U.context=le,g=Ce):(typeof U.componentDidUpdate!="function"||oe===o.memoizedProps&&He===o.memoizedState||(l.flags|=4),typeof U.getSnapshotBeforeUpdate!="function"||oe===o.memoizedProps&&He===o.memoizedState||(l.flags|=1024),g=!1)}return Ju(o,l,f,g,N,j)}function Ju(o,l,f,g,j,N){Wf(o,l);var U=(l.flags&128)!==0;if(!g&&!U)return j&&Au(l,f,!1),ks(o,l,N);g=l.stateNode,Mi.current=l;var oe=U&&typeof f.getDerivedStateFromError!="function"?null:g.render();return l.flags|=1,o!==null&&U?(l.child=To(l,o.child,null,N),l.child=To(l,null,oe,N)):Us(o,l,oe,N),l.memoizedState=g.state,j&&Au(l,f,!0),l.child}function qf(o){var l=o.stateNode;l.pendingContext?Eu(o,l.pendingContext,l.pendingContext!==l.context):l.context&&Eu(o,l.context,!1),Sl(o,l.containerInfo)}function c_(o,l,f,g,j){return Ta(),Cf(j),l.flags|=256,Us(o,l,f,g),l.child}var Yu={dehydrated:null,treeContext:null,retryLane:0};function ta(o){return{baseLanes:o,cachePool:null,transitions:null}}function u_(o,l,f){var g=l.pendingProps,j=as.current,N=!1,U=(l.flags&128)!==0,oe;if((oe=U)||(oe=o!==null&&o.memoizedState===null?!1:(j&2)!==0),oe?(N=!0,l.flags&=-129):(o===null||o.memoizedState!==null)&&(j|=1),Vn(as,j&1),o===null)return gc(l),o=l.memoizedState,o!==null&&(o=o.dehydrated,o!==null)?((l.mode&1)===0?l.lanes=1:o.data==="$!"?l.lanes=8:l.lanes=1073741824,null):(U=g.children,o=g.fallback,N?(g=l.mode,N=l.child,U={mode:"hidden",children:U},(g&1)===0&&N!==null?(N.childLanes=0,N.pendingProps=U):N=Jn(U,g,0,null),o=Tn(o,g,f,null),N.return=l,o.return=l,N.sibling=o,l.child=N,l.child.memoizedState=ta(f),l.memoizedState=Yu,o):Ll(l,U));if(j=o.memoizedState,j!==null&&(oe=j.dehydrated,oe!==null))return Eg(o,l,U,g,oe,j,f);if(N){N=g.fallback,U=l.mode,j=o.child,oe=j.sibling;var le={mode:"hidden",children:g.children};return(U&1)===0&&l.child!==j?(g=l.child,g.childLanes=0,g.pendingProps=le,l.deletions=null):(g=it(j,le),g.subtreeFlags=j.subtreeFlags&14680064),oe!==null?N=it(oe,N):(N=Tn(N,U,f,null),N.flags|=2),N.return=l,g.return=l,g.sibling=N,l.child=g,g=N,N=l.child,U=o.child.memoizedState,U=U===null?ta(f):{baseLanes:U.baseLanes|f,cachePool:null,transitions:U.transitions},N.memoizedState=U,N.childLanes=o.childLanes&~f,l.memoizedState=Yu,g}return N=o.child,o=N.sibling,g=it(N,{mode:"visible",children:g.children}),(l.mode&1)===0&&(g.lanes=f),g.return=l,g.sibling=null,o!==null&&(f=l.deletions,f===null?(l.deletions=[o],l.flags|=16):f.push(o)),l.child=g,l.memoizedState=null,g}function Ll(o,l){return l=Jn({mode:"visible",children:l},o.mode,0,null),l.return=o,o.child=l}function Cc(o,l,f,g){return g!==null&&Cf(g),To(l,o.child,null,f),o=Ll(l,l.pendingProps.children),o.flags|=2,l.memoizedState=null,o}function Eg(o,l,f,g,j,N,U){if(f)return l.flags&256?(l.flags&=-257,g=Ml(Error(n(422))),Cc(o,l,U,g)):l.memoizedState!==null?(l.child=o.child,l.flags|=128,null):(N=g.fallback,j=l.mode,g=Jn({mode:"visible",children:g.children},j,0,null),N=Tn(N,j,U,null),N.flags|=2,g.return=l,N.return=l,g.sibling=N,l.child=g,(l.mode&1)!==0&&To(l,o.child,null,U),l.child.memoizedState=ta(U),l.memoizedState=Yu,N);if((l.mode&1)===0)return Cc(o,l,U,null);if(j.data==="$!"){if(g=j.nextSibling&&j.nextSibling.dataset,g)var oe=g.dgst;return g=oe,N=Error(n(419)),g=Ml(N,g,void 0),Cc(o,l,U,g)}if(oe=(U&o.childLanes)!==0,Ir||oe){if(g=As,g!==null){switch(U&-U){case 4:j=2;break;case 16:j=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:j=32;break;case 536870912:j=268435456;break;default:j=0}j=(j&(g.suspendedLanes|U))!==0?0:j,j!==0&&j!==N.retryLane&&(N.retryLane=j,to(o,j),_i(g,o,j,-1))}return fd(),g=Ml(Error(n(421))),Cc(o,l,U,g)}return j.data==="$?"?(l.flags|=128,l.child=o.child,l=_e.bind(null,o),j._reactRetry=l,null):(o=N.treeContext,Lr=Yo(j.nextSibling),Jr=l,Gn=!0,$i=null,o!==null&&(kr[Kr++]=Qi,kr[Kr++]=eo,kr[Kr++]=Zi,Qi=o.id,eo=o.overflow,Zi=l),l=Ll(l,g.children),l.flags|=4096,l)}function Xu(o,l,f){o.lanes|=l;var g=o.alternate;g!==null&&(g.lanes|=l),kl(o.return,l,f)}function Hf(o,l,f,g,j){var N=o.memoizedState;N===null?o.memoizedState={isBackwards:l,rendering:null,renderingStartTime:0,last:g,tail:f,tailMode:j}:(N.isBackwards=l,N.rendering=null,N.renderingStartTime=0,N.last=g,N.tail=f,N.tailMode=j)}function d_(o,l,f){var g=l.pendingProps,j=g.revealOrder,N=g.tail;if(Us(o,l,g.children,f),g=as.current,(g&2)!==0)g=g&1|2,l.flags|=128;else{if(o!==null&&(o.flags&128)!==0)e:for(o=l.child;o!==null;){if(o.tag===13)o.memoizedState!==null&&Xu(o,f,l);else if(o.tag===19)Xu(o,f,l);else if(o.child!==null){o.child.return=o,o=o.child;continue}if(o===l)break e;for(;o.sibling===null;){if(o.return===null||o.return===l)break e;o=o.return}o.sibling.return=o.return,o=o.sibling}g&=1}if(Vn(as,g),(l.mode&1)===0)l.memoizedState=null;else switch(j){case"forwards":for(f=l.child,j=null;f!==null;)o=f.alternate,o!==null&&$l(o)===null&&(j=f),f=f.sibling;f=j,f===null?(j=l.child,l.child=null):(j=f.sibling,f.sibling=null),Hf(l,!1,j,f,N);break;case"backwards":for(f=null,j=l.child,l.child=null;j!==null;){if(o=j.alternate,o!==null&&$l(o)===null){l.child=j;break}o=j.sibling,j.sibling=f,f=j,j=o}Hf(l,!0,f,null,N);break;case"together":Hf(l,!1,null,null,void 0);break;default:l.memoizedState=null}return l.child}function Zu(o,l){(l.mode&1)===0&&o!==null&&(o.alternate=null,l.alternate=null,l.flags|=2)}function ks(o,l,f){if(o!==null&&(l.dependencies=o.dependencies),Da|=l.lanes,(f&l.childLanes)===0)return null;if(o!==null&&l.child!==o.child)throw Error(n(153));if(l.child!==null){for(o=l.child,f=it(o,o.pendingProps),l.child=f,f.return=l;o.sibling!==null;)o=o.sibling,f=f.sibling=it(o,o.pendingProps),f.return=l;f.sibling=null}return l.child}function Il(o,l,f){switch(l.tag){case 3:qf(l),Ta();break;case 5:Hh(l);break;case 1:rr(l.type)&&gl(l);break;case 4:Sl(l,l.stateNode.containerInfo);break;case 10:var g=l.type._context,j=l.memoizedProps.value;Vn(Pu,g._currentValue),g._currentValue=j;break;case 13:if(g=l.memoizedState,g!==null)return g.dehydrated!==null?(Vn(as,as.current&1),l.flags|=128,null):(f&l.child.childLanes)!==0?u_(o,l,f):(Vn(as,as.current&1),o=ks(o,l,f),o!==null?o.sibling:null);Vn(as,as.current&1);break;case 19:if(g=(f&l.childLanes)!==0,(o.flags&128)!==0){if(g)return d_(o,l,f);l.flags|=128}if(j=l.memoizedState,j!==null&&(j.rendering=null,j.tail=null,j.lastEffect=null),Vn(as,as.current),g)break;return null;case 22:case 23:return l.lanes=0,l_(o,l,f)}return ks(o,l,f)}var f_,Qu,Or,ed;f_=function(o,l){for(var f=l.child;f!==null;){if(f.tag===5||f.tag===6)o.appendChild(f.stateNode);else if(f.tag!==4&&f.child!==null){f.child.return=f,f=f.child;continue}if(f===l)break;for(;f.sibling===null;){if(f.return===null||f.return===l)return;f=f.return}f.sibling.return=f.return,f=f.sibling}},Qu=function(){},Or=function(o,l,f,g){var j=o.memoizedProps;if(j!==g){o=l.stateNode,Gs(zs.current);var N=null;switch(f){case"input":j=at(o,j),g=at(o,g),N=[];break;case"select":j=ne({},j,{value:void 0}),g=ne({},g,{value:void 0}),N=[];break;case"textarea":j=ct(o,j),g=ct(o,g),N=[];break;default:typeof j.onClick!="function"&&typeof g.onClick=="function"&&(o.onclick=pc)}an(f,g);var U;f=null;for(Ce in j)if(!g.hasOwnProperty(Ce)&&j.hasOwnProperty(Ce)&&j[Ce]!=null)if(Ce==="style"){var oe=j[Ce];for(U in oe)oe.hasOwnProperty(U)&&(f||(f={}),f[U]="")}else Ce!=="dangerouslySetInnerHTML"&&Ce!=="children"&&Ce!=="suppressContentEditableWarning"&&Ce!=="suppressHydrationWarning"&&Ce!=="autoFocus"&&(i.hasOwnProperty(Ce)?N||(N=[]):(N=N||[]).push(Ce,null));for(Ce in g){var le=g[Ce];if(oe=j!=null?j[Ce]:void 0,g.hasOwnProperty(Ce)&&le!==oe&&(le!=null||oe!=null))if(Ce==="style")if(oe){for(U in oe)!oe.hasOwnProperty(U)||le&&le.hasOwnProperty(U)||(f||(f={}),f[U]="");for(U in le)le.hasOwnProperty(U)&&oe[U]!==le[U]&&(f||(f={}),f[U]=le[U])}else f||(N||(N=[]),N.push(Ce,f)),f=le;else Ce==="dangerouslySetInnerHTML"?(le=le?le.__html:void 0,oe=oe?oe.__html:void 0,le!=null&&oe!==le&&(N=N||[]).push(Ce,le)):Ce==="children"?typeof le!="string"&&typeof le!="number"||(N=N||[]).push(Ce,""+le):Ce!=="suppressContentEditableWarning"&&Ce!=="suppressHydrationWarning"&&(i.hasOwnProperty(Ce)?(le!=null&&Ce==="onScroll"&&Ln("scroll",o),N||oe===le||(N=[])):(N=N||[]).push(Ce,le))}f&&(N=N||[]).push("style",f);var Ce=N;(l.updateQueue=Ce)&&(l.flags|=4)}},ed=function(o,l,f,g){f!==g&&(l.flags|=4)};function Ol(o,l){if(!Gn)switch(o.tailMode){case"hidden":l=o.tail;for(var f=null;l!==null;)l.alternate!==null&&(f=l),l=l.sibling;f===null?o.tail=null:f.sibling=null;break;case"collapsed":f=o.tail;for(var g=null;f!==null;)f.alternate!==null&&(g=f),f=f.sibling;g===null?l||o.tail===null?o.tail=null:o.tail.sibling=null:g.sibling=null}}function Ks(o){var l=o.alternate!==null&&o.alternate.child===o.child,f=0,g=0;if(l)for(var j=o.child;j!==null;)f|=j.lanes|j.childLanes,g|=j.subtreeFlags&14680064,g|=j.flags&14680064,j.return=o,j=j.sibling;else for(j=o.child;j!==null;)f|=j.lanes|j.childLanes,g|=j.subtreeFlags,g|=j.flags,j.return=o,j=j.sibling;return o.subtreeFlags|=g,o.childLanes=f,l}function Ag(o,l,f){var g=l.pendingProps;switch(Iu(l),l.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return Ks(l),null;case 1:return rr(l.type)&&Eo(),Ks(l),null;case 3:return g=l.stateNode,Nl(),En(br),En($s),ms(),g.pendingContext&&(g.context=g.pendingContext,g.pendingContext=null),(o===null||o.child===null)&&(xl(l)?l.flags|=4:o===null||o.memoizedState.isDehydrated&&(l.flags&256)===0||(l.flags|=1024,$i!==null&&(cd($i),$i=null))),Qu(o,l),Ks(l),null;case 5:yc(l);var j=Gs(Ci.current);if(f=l.type,o!==null&&l.stateNode!=null)Or(o,l,f,g,j),o.ref!==l.ref&&(l.flags|=512,l.flags|=2097152);else{if(!g){if(l.stateNode===null)throw Error(n(166));return Ks(l),null}if(o=Gs(zs.current),xl(l)){g=l.stateNode,f=l.type;var N=l.memoizedProps;switch(g[Ji]=l,g[So]=N,o=(l.mode&1)!==0,f){case"dialog":Ln("cancel",g),Ln("close",g);break;case"iframe":case"object":case"embed":Ln("load",g);break;case"video":case"audio":for(j=0;j<ko.length;j++)Ln(ko[j],g);break;case"source":Ln("error",g);break;case"img":case"image":case"link":Ln("error",g),Ln("load",g);break;case"details":Ln("toggle",g);break;case"input":Nt(g,N),Ln("invalid",g);break;case"select":g._wrapperState={wasMultiple:!!N.multiple},Ln("invalid",g);break;case"textarea":ie(g,N),Ln("invalid",g)}an(f,N),j=null;for(var U in N)if(N.hasOwnProperty(U)){var oe=N[U];U==="children"?typeof oe=="string"?g.textContent!==oe&&(N.suppressHydrationWarning!==!0&&_c(g.textContent,oe,o),j=["children",oe]):typeof oe=="number"&&g.textContent!==""+oe&&(N.suppressHydrationWarning!==!0&&_c(g.textContent,oe,o),j=["children",""+oe]):i.hasOwnProperty(U)&&oe!=null&&U==="onScroll"&&Ln("scroll",g)}switch(f){case"input":ot(g),me(g,N,!0);break;case"textarea":ot(g),et(g);break;case"select":case"option":break;default:typeof N.onClick=="function"&&(g.onclick=pc)}g=j,l.updateQueue=g,g!==null&&(l.flags|=4)}else{U=j.nodeType===9?j:j.ownerDocument,o==="http://www.w3.org/1999/xhtml"&&(o=Ge(f)),o==="http://www.w3.org/1999/xhtml"?f==="script"?(o=U.createElement("div"),o.innerHTML="<script><\/script>",o=o.removeChild(o.firstChild)):typeof g.is=="string"?o=U.createElement(f,{is:g.is}):(o=U.createElement(f),f==="select"&&(U=o,g.multiple?U.multiple=!0:g.size&&(U.size=g.size))):o=U.createElementNS(o,f),o[Ji]=l,o[So]=g,f_(o,l,!1,!1),l.stateNode=o;e:{switch(U=is(f,g),f){case"dialog":Ln("cancel",o),Ln("close",o),j=g;break;case"iframe":case"object":case"embed":Ln("load",o),j=g;break;case"video":case"audio":for(j=0;j<ko.length;j++)Ln(ko[j],o);j=g;break;case"source":Ln("error",o),j=g;break;case"img":case"image":case"link":Ln("error",o),Ln("load",o),j=g;break;case"details":Ln("toggle",o),j=g;break;case"input":Nt(o,g),j=at(o,g),Ln("invalid",o);break;case"option":j=g;break;case"select":o._wrapperState={wasMultiple:!!g.multiple},j=ne({},g,{value:void 0}),Ln("invalid",o);break;case"textarea":ie(o,g),j=ct(o,g),Ln("invalid",o);break;default:j=g}an(f,j),oe=j;for(N in oe)if(oe.hasOwnProperty(N)){var le=oe[N];N==="style"?$n(o,le):N==="dangerouslySetInnerHTML"?(le=le?le.__html:void 0,le!=null&&Nn(o,le)):N==="children"?typeof le=="string"?(f!=="textarea"||le!=="")&&Qt(o,le):typeof le=="number"&&Qt(o,""+le):N!=="suppressContentEditableWarning"&&N!=="suppressHydrationWarning"&&N!=="autoFocus"&&(i.hasOwnProperty(N)?le!=null&&N==="onScroll"&&Ln("scroll",o):le!=null&&A(o,N,le,U))}switch(f){case"input":ot(o),me(o,g,!1);break;case"textarea":ot(o),et(o);break;case"option":g.value!=null&&o.setAttribute("value",""+pe(g.value));break;case"select":o.multiple=!!g.multiple,N=g.value,N!=null?Ie(o,!!g.multiple,N,!1):g.defaultValue!=null&&Ie(o,!!g.multiple,g.defaultValue,!0);break;default:typeof j.onClick=="function"&&(o.onclick=pc)}switch(f){case"button":case"input":case"select":case"textarea":g=!!g.autoFocus;break e;case"img":g=!0;break e;default:g=!1}}g&&(l.flags|=4)}l.ref!==null&&(l.flags|=512,l.flags|=2097152)}return Ks(l),null;case 6:if(o&&l.stateNode!=null)ed(o,l,o.memoizedProps,g);else{if(typeof g!="string"&&l.stateNode===null)throw Error(n(166));if(f=Gs(Ci.current),Gs(zs.current),xl(l)){if(g=l.stateNode,f=l.memoizedProps,g[Ji]=l,(N=g.nodeValue!==f)&&(o=Jr,o!==null))switch(o.tag){case 3:_c(g.nodeValue,f,(o.mode&1)!==0);break;case 5:o.memoizedProps.suppressHydrationWarning!==!0&&_c(g.nodeValue,f,(o.mode&1)!==0)}N&&(l.flags|=4)}else g=(f.nodeType===9?f:f.ownerDocument).createTextNode(g),g[Ji]=l,l.stateNode=g}return Ks(l),null;case 13:if(En(as),g=l.memoizedState,o===null||o.memoizedState!==null&&o.memoizedState.dehydrated!==null){if(Gn&&Lr!==null&&(l.mode&1)!==0&&(l.flags&128)===0)Bh(),Ta(),l.flags|=98560,N=!1;else if(N=xl(l),g!==null&&g.dehydrated!==null){if(o===null){if(!N)throw Error(n(318));if(N=l.memoizedState,N=N!==null?N.dehydrated:null,!N)throw Error(n(317));N[Ji]=l}else Ta(),(l.flags&128)===0&&(l.memoizedState=null),l.flags|=4;Ks(l),N=!1}else $i!==null&&(cd($i),$i=null),N=!0;if(!N)return l.flags&65536?l:null}return(l.flags&128)!==0?(l.lanes=f,l):(g=g!==null,g!==(o!==null&&o.memoizedState!==null)&&g&&(l.child.flags|=8192,(l.mode&1)!==0&&(o===null||(as.current&1)!==0?Ts===0&&(Ts=3):fd())),l.updateQueue!==null&&(l.flags|=4),Ks(l),null);case 4:return Nl(),Qu(o,l),o===null&&ji(l.stateNode.containerInfo),Ks(l),null;case 10:return Tf(l.type._context),Ks(l),null;case 17:return rr(l.type)&&Eo(),Ks(l),null;case 19:if(En(as),N=l.memoizedState,N===null)return Ks(l),null;if(g=(l.flags&128)!==0,U=N.rendering,U===null)if(g)Ol(N,!1);else{if(Ts!==0||o!==null&&(o.flags&128)!==0)for(o=l.child;o!==null;){if(U=$l(o),U!==null){for(l.flags|=128,Ol(N,!1),g=U.updateQueue,g!==null&&(l.updateQueue=g,l.flags|=4),l.subtreeFlags=0,g=f,f=l.child;f!==null;)N=f,o=g,N.flags&=14680066,U=N.alternate,U===null?(N.childLanes=0,N.lanes=o,N.child=null,N.subtreeFlags=0,N.memoizedProps=null,N.memoizedState=null,N.updateQueue=null,N.dependencies=null,N.stateNode=null):(N.childLanes=U.childLanes,N.lanes=U.lanes,N.child=U.child,N.subtreeFlags=0,N.deletions=null,N.memoizedProps=U.memoizedProps,N.memoizedState=U.memoizedState,N.updateQueue=U.updateQueue,N.type=U.type,o=U.dependencies,N.dependencies=o===null?null:{lanes:o.lanes,firstContext:o.firstContext}),f=f.sibling;return Vn(as,as.current&1|2),l.child}o=o.sibling}N.tail!==null&&Yt()>Pl&&(l.flags|=128,g=!0,Ol(N,!1),l.lanes=4194304)}else{if(!g)if(o=$l(U),o!==null){if(l.flags|=128,g=!0,f=o.updateQueue,f!==null&&(l.updateQueue=f,l.flags|=4),Ol(N,!0),N.tail===null&&N.tailMode==="hidden"&&!U.alternate&&!Gn)return Ks(l),null}else 2*Yt()-N.renderingStartTime>Pl&&f!==1073741824&&(l.flags|=128,g=!0,Ol(N,!1),l.lanes=4194304);N.isBackwards?(U.sibling=l.child,l.child=U):(f=N.last,f!==null?f.sibling=U:l.child=U,N.last=U)}return N.tail!==null?(l=N.tail,N.rendering=l,N.tail=l.sibling,N.renderingStartTime=Yt(),l.sibling=null,f=as.current,Vn(as,g?f&1|2:f&1),l):(Ks(l),null);case 22:case 23:return dd(),g=l.memoizedState!==null,o!==null&&o.memoizedState!==null!==g&&(l.flags|=8192),g&&(l.mode&1)!==0?(Pr&1073741824)!==0&&(Ks(l),l.subtreeFlags&6&&(l.flags|=8192)):Ks(l),null;case 24:return null;case 25:return null}throw Error(n(156,l.tag))}function Tg(o,l){switch(Iu(l),l.tag){case 1:return rr(l.type)&&Eo(),o=l.flags,o&65536?(l.flags=o&-65537|128,l):null;case 3:return Nl(),En(br),En($s),ms(),o=l.flags,(o&65536)!==0&&(o&128)===0?(l.flags=o&-65537|128,l):null;case 5:return yc(l),null;case 13:if(En(as),o=l.memoizedState,o!==null&&o.dehydrated!==null){if(l.alternate===null)throw Error(n(340));Ta()}return o=l.flags,o&65536?(l.flags=o&-65537|128,l):null;case 19:return En(as),null;case 4:return Nl(),null;case 10:return Tf(l.type._context),null;case 22:case 23:return dd(),null;case 24:return null;default:return null}}var td=!1,Hn=!1,Ec=typeof WeakSet=="function"?WeakSet:Set,gt=null;function Oa(o,l){var f=o.ref;if(f!==null)if(typeof f=="function")try{f(null)}catch(g){re(o,l,g)}else f.current=null}function na(o,l,f){try{f()}catch(g){re(o,l,g)}}var Vf=!1;function Oo(o,l){if(Nu=sr,o=yf(),ka(o)){if("selectionStart"in o)var f={start:o.selectionStart,end:o.selectionEnd};else e:{f=(f=o.ownerDocument)&&f.defaultView||window;var g=f.getSelection&&f.getSelection();if(g&&g.rangeCount!==0){f=g.anchorNode;var j=g.anchorOffset,N=g.focusNode;g=g.focusOffset;try{f.nodeType,N.nodeType}catch{f=null;break e}var U=0,oe=-1,le=-1,Ce=0,Ye=0,Qe=o,He=null;t:for(;;){for(var pt;Qe!==f||j!==0&&Qe.nodeType!==3||(oe=U+j),Qe!==N||g!==0&&Qe.nodeType!==3||(le=U+g),Qe.nodeType===3&&(U+=Qe.nodeValue.length),(pt=Qe.firstChild)!==null;)He=Qe,Qe=pt;for(;;){if(Qe===o)break t;if(He===f&&++Ce===j&&(oe=U),He===N&&++Ye===g&&(le=U),(pt=Qe.nextSibling)!==null)break;Qe=He,He=Qe.parentNode}Qe=pt}f=oe===-1||le===-1?null:{start:oe,end:le}}else f=null}f=f||{start:0,end:0}}else f=null;for(bf={focusedElem:o,selectionRange:f},sr=!1,gt=l;gt!==null;)if(l=gt,o=l.child,(l.subtreeFlags&1028)!==0&&o!==null)o.return=l,gt=o;else for(;gt!==null;){l=gt;try{var vt=l.alternate;if((l.flags&1024)!==0)switch(l.tag){case 0:case 11:case 15:break;case 1:if(vt!==null){var jt=vt.memoizedProps,Ls=vt.memoizedState,xe=l.stateNode,de=xe.getSnapshotBeforeUpdate(l.elementType===l.type?jt:Ai(l.type,jt),Ls);xe.__reactInternalSnapshotBeforeUpdate=de}break;case 3:var ke=l.stateNode.containerInfo;ke.nodeType===1?ke.textContent="":ke.nodeType===9&&ke.documentElement&&ke.removeChild(ke.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(n(163))}}catch(st){re(l,l.return,st)}if(o=l.sibling,o!==null){o.return=l.return,gt=o;break}gt=l.return}return vt=Vf,Vf=!1,vt}function Ac(o,l,f){var g=l.updateQueue;if(g=g!==null?g.lastEffect:null,g!==null){var j=g=g.next;do{if((j.tag&o)===o){var N=j.destroy;j.destroy=void 0,N!==void 0&&na(l,f,N)}j=j.next}while(j!==g)}}function nd(o,l){if(l=l.updateQueue,l=l!==null?l.lastEffect:null,l!==null){var f=l=l.next;do{if((f.tag&o)===o){var g=f.create;f.destroy=g()}f=f.next}while(f!==l)}}function sd(o){var l=o.ref;if(l!==null){var f=o.stateNode;switch(o.tag){case 5:o=f;break;default:o=f}typeof l=="function"?l(o):l.current=o}}function io(o){var l=o.alternate;l!==null&&(o.alternate=null,io(l)),o.child=null,o.deletions=null,o.sibling=null,o.tag===5&&(l=o.stateNode,l!==null&&(delete l[Ji],delete l[So],delete l[hl],delete l[Oh],delete l[_l])),o.stateNode=null,o.return=null,o.dependencies=null,o.memoizedProps=null,o.memoizedState=null,o.pendingProps=null,o.stateNode=null,o.updateQueue=null}function rd(o){return o.tag===5||o.tag===3||o.tag===4}function m_(o){e:for(;;){for(;o.sibling===null;){if(o.return===null||rd(o.return))return null;o=o.return}for(o.sibling.return=o.return,o=o.sibling;o.tag!==5&&o.tag!==6&&o.tag!==18;){if(o.flags&2||o.child===null||o.tag===4)continue e;o.child.return=o,o=o.child}if(!(o.flags&2))return o.stateNode}}function Gf(o,l,f){var g=o.tag;if(g===5||g===6)o=o.stateNode,l?f.nodeType===8?f.parentNode.insertBefore(o,l):f.insertBefore(o,l):(f.nodeType===8?(l=f.parentNode,l.insertBefore(o,f)):(l=f,l.appendChild(o)),f=f._reactRootContainer,f!=null||l.onclick!==null||(l.onclick=pc));else if(g!==4&&(o=o.child,o!==null))for(Gf(o,l,f),o=o.sibling;o!==null;)Gf(o,l,f),o=o.sibling}function Kf(o,l,f){var g=o.tag;if(g===5||g===6)o=o.stateNode,l?f.insertBefore(o,l):f.appendChild(o);else if(g!==4&&(o=o.child,o!==null))for(Kf(o,l,f),o=o.sibling;o!==null;)Kf(o,l,f),o=o.sibling}var Ws=null,Ri=!1;function An(o,l,f){for(f=f.child;f!==null;)_s(o,l,f),f=f.sibling}function _s(o,l,f){if(tr&&typeof tr.onCommitFiberUnmount=="function")try{tr.onCommitFiberUnmount(Rn,f)}catch{}switch(f.tag){case 5:Hn||Oa(f,l);case 6:var g=Ws,j=Ri;Ws=null,An(o,l,f),Ws=g,Ri=j,Ws!==null&&(Ri?(o=Ws,f=f.stateNode,o.nodeType===8?o.parentNode.removeChild(f):o.removeChild(f)):Ws.removeChild(f.stateNode));break;case 18:Ws!==null&&(Ri?(o=Ws,f=f.stateNode,o.nodeType===8?Cu(o.parentNode,f):o.nodeType===1&&Cu(o,f),wa(o)):Cu(Ws,f.stateNode));break;case 4:g=Ws,j=Ri,Ws=f.stateNode.containerInfo,Ri=!0,An(o,l,f),Ws=g,Ri=j;break;case 0:case 11:case 14:case 15:if(!Hn&&(g=f.updateQueue,g!==null&&(g=g.lastEffect,g!==null))){j=g=g.next;do{var N=j,U=N.destroy;N=N.tag,U!==void 0&&((N&2)!==0||(N&4)!==0)&&na(f,l,U),j=j.next}while(j!==g)}An(o,l,f);break;case 1:if(!Hn&&(Oa(f,l),g=f.stateNode,typeof g.componentWillUnmount=="function"))try{g.props=f.memoizedProps,g.state=f.memoizedState,g.componentWillUnmount()}catch(oe){re(f,l,oe)}An(o,l,f);break;case 21:An(o,l,f);break;case 22:f.mode&1?(Hn=(g=Hn)||f.memoizedState!==null,An(o,l,f),Hn=g):An(o,l,f);break;default:An(o,l,f)}}function cr(o){var l=o.updateQueue;if(l!==null){o.updateQueue=null;var f=o.stateNode;f===null&&(f=o.stateNode=new Ec),l.forEach(function(g){var j=Le.bind(null,o,g);f.has(g)||(f.add(g),g.then(j,j))})}}function fi(o,l){var f=l.deletions;if(f!==null)for(var g=0;g<f.length;g++){var j=f[g];try{var N=o,U=l,oe=U;e:for(;oe!==null;){switch(oe.tag){case 5:Ws=oe.stateNode,Ri=!1;break e;case 3:Ws=oe.stateNode.containerInfo,Ri=!0;break e;case 4:Ws=oe.stateNode.containerInfo,Ri=!0;break e}oe=oe.return}if(Ws===null)throw Error(n(160));_s(N,U,j),Ws=null,Ri=!1;var le=j.alternate;le!==null&&(le.return=null),j.return=null}catch(Ce){re(j,l,Ce)}}if(l.subtreeFlags&12854)for(l=l.child;l!==null;)h_(l,o),l=l.sibling}function h_(o,l){var f=o.alternate,g=o.flags;switch(o.tag){case 0:case 11:case 14:case 15:if(fi(l,o),oo(o),g&4){try{Ac(3,o,o.return),nd(3,o)}catch(jt){re(o,o.return,jt)}try{Ac(5,o,o.return)}catch(jt){re(o,o.return,jt)}}break;case 1:fi(l,o),oo(o),g&512&&f!==null&&Oa(f,f.return);break;case 5:if(fi(l,o),oo(o),g&512&&f!==null&&Oa(f,f.return),o.flags&32){var j=o.stateNode;try{Qt(j,"")}catch(jt){re(o,o.return,jt)}}if(g&4&&(j=o.stateNode,j!=null)){var N=o.memoizedProps,U=f!==null?f.memoizedProps:N,oe=o.type,le=o.updateQueue;if(o.updateQueue=null,le!==null)try{oe==="input"&&N.type==="radio"&&N.name!=null&&ut(j,N),is(oe,U);var Ce=is(oe,N);for(U=0;U<le.length;U+=2){var Ye=le[U],Qe=le[U+1];Ye==="style"?$n(j,Qe):Ye==="dangerouslySetInnerHTML"?Nn(j,Qe):Ye==="children"?Qt(j,Qe):A(j,Ye,Qe,Ce)}switch(oe){case"input":Se(j,N);break;case"textarea":Te(j,N);break;case"select":var He=j._wrapperState.wasMultiple;j._wrapperState.wasMultiple=!!N.multiple;var pt=N.value;pt!=null?Ie(j,!!N.multiple,pt,!1):He!==!!N.multiple&&(N.defaultValue!=null?Ie(j,!!N.multiple,N.defaultValue,!0):Ie(j,!!N.multiple,N.multiple?[]:"",!1))}j[So]=N}catch(jt){re(o,o.return,jt)}}break;case 6:if(fi(l,o),oo(o),g&4){if(o.stateNode===null)throw Error(n(162));j=o.stateNode,N=o.memoizedProps;try{j.nodeValue=N}catch(jt){re(o,o.return,jt)}}break;case 3:if(fi(l,o),oo(o),g&4&&f!==null&&f.memoizedState.isDehydrated)try{wa(l.containerInfo)}catch(jt){re(o,o.return,jt)}break;case 4:fi(l,o),oo(o);break;case 13:fi(l,o),oo(o),j=o.child,j.flags&8192&&(N=j.memoizedState!==null,j.stateNode.isHidden=N,!N||j.alternate!==null&&j.alternate.memoizedState!==null||(od=Yt())),g&4&&cr(o);break;case 22:if(Ye=f!==null&&f.memoizedState!==null,o.mode&1?(Hn=(Ce=Hn)||Ye,fi(l,o),Hn=Ce):fi(l,o),oo(o),g&8192){if(Ce=o.memoizedState!==null,(o.stateNode.isHidden=Ce)&&!Ye&&(o.mode&1)!==0)for(gt=o,Ye=o.child;Ye!==null;){for(Qe=gt=Ye;gt!==null;){switch(He=gt,pt=He.child,He.tag){case 0:case 11:case 14:case 15:Ac(4,He,He.return);break;case 1:Oa(He,He.return);var vt=He.stateNode;if(typeof vt.componentWillUnmount=="function"){g=He,f=He.return;try{l=g,vt.props=l.memoizedProps,vt.state=l.memoizedState,vt.componentWillUnmount()}catch(jt){re(g,f,jt)}}break;case 5:Oa(He,He.return);break;case 22:if(He.memoizedState!==null){sa(Qe);continue}}pt!==null?(pt.return=He,gt=pt):sa(Qe)}Ye=Ye.sibling}e:for(Ye=null,Qe=o;;){if(Qe.tag===5){if(Ye===null){Ye=Qe;try{j=Qe.stateNode,Ce?(N=j.style,typeof N.setProperty=="function"?N.setProperty("display","none","important"):N.display="none"):(oe=Qe.stateNode,le=Qe.memoizedProps.style,U=le!=null&&le.hasOwnProperty("display")?le.display:null,oe.style.display=Dn("display",U))}catch(jt){re(o,o.return,jt)}}}else if(Qe.tag===6){if(Ye===null)try{Qe.stateNode.nodeValue=Ce?"":Qe.memoizedProps}catch(jt){re(o,o.return,jt)}}else if((Qe.tag!==22&&Qe.tag!==23||Qe.memoizedState===null||Qe===o)&&Qe.child!==null){Qe.child.return=Qe,Qe=Qe.child;continue}if(Qe===o)break e;for(;Qe.sibling===null;){if(Qe.return===null||Qe.return===o)break e;Ye===Qe&&(Ye=null),Qe=Qe.return}Ye===Qe&&(Ye=null),Qe.sibling.return=Qe.return,Qe=Qe.sibling}}break;case 19:fi(l,o),oo(o),g&4&&cr(o);break;case 21:break;default:fi(l,o),oo(o)}}function oo(o){var l=o.flags;if(l&2){try{e:{for(var f=o.return;f!==null;){if(rd(f)){var g=f;break e}f=f.return}throw Error(n(160))}switch(g.tag){case 5:var j=g.stateNode;g.flags&32&&(Qt(j,""),g.flags&=-33);var N=m_(o);Kf(o,N,j);break;case 3:case 4:var U=g.stateNode.containerInfo,oe=m_(o);Gf(o,oe,U);break;default:throw Error(n(161))}}catch(le){re(o,o.return,le)}o.flags&=-3}l&4096&&(o.flags&=-4097)}function Jf(o,l,f){gt=o,__(o)}function __(o,l,f){for(var g=(o.mode&1)!==0;gt!==null;){var j=gt,N=j.child;if(j.tag===22&&g){var U=j.memoizedState!==null||td;if(!U){var oe=j.alternate,le=oe!==null&&oe.memoizedState!==null||Hn;oe=td;var Ce=Hn;if(td=U,(Hn=le)&&!Ce)for(gt=j;gt!==null;)U=gt,le=U.child,U.tag===22&&U.memoizedState!==null?g_(j):le!==null?(le.return=U,gt=le):g_(j);for(;N!==null;)gt=N,__(N),N=N.sibling;gt=j,td=oe,Hn=Ce}p_(o)}else(j.subtreeFlags&8772)!==0&&N!==null?(N.return=j,gt=N):p_(o)}}function p_(o){for(;gt!==null;){var l=gt;if((l.flags&8772)!==0){var f=l.alternate;try{if((l.flags&8772)!==0)switch(l.tag){case 0:case 11:case 15:Hn||nd(5,l);break;case 1:var g=l.stateNode;if(l.flags&4&&!Hn)if(f===null)g.componentDidMount();else{var j=l.elementType===l.type?f.memoizedProps:Ai(l.type,f.memoizedProps);g.componentDidUpdate(j,f.memoizedState,g.__reactInternalSnapshotBeforeUpdate)}var N=l.updateQueue;N!==null&&qh(l,N,g);break;case 3:var U=l.updateQueue;if(U!==null){if(f=null,l.child!==null)switch(l.child.tag){case 5:f=l.child.stateNode;break;case 1:f=l.child.stateNode}qh(l,U,f)}break;case 5:var oe=l.stateNode;if(f===null&&l.flags&4){f=oe;var le=l.memoizedProps;switch(l.type){case"button":case"input":case"select":case"textarea":le.autoFocus&&f.focus();break;case"img":le.src&&(f.src=le.src)}}break;case 6:break;case 4:break;case 12:break;case 13:if(l.memoizedState===null){var Ce=l.alternate;if(Ce!==null){var Ye=Ce.memoizedState;if(Ye!==null){var Qe=Ye.dehydrated;Qe!==null&&wa(Qe)}}}break;case 19:case 17:case 21:case 22:case 23:case 25:break;default:throw Error(n(163))}Hn||l.flags&512&&sd(l)}catch(He){re(l,l.return,He)}}if(l===o){gt=null;break}if(f=l.sibling,f!==null){f.return=l.return,gt=f;break}gt=l.return}}function sa(o){for(;gt!==null;){var l=gt;if(l===o){gt=null;break}var f=l.sibling;if(f!==null){f.return=l.return,gt=f;break}gt=l.return}}function g_(o){for(;gt!==null;){var l=gt;try{switch(l.tag){case 0:case 11:case 15:var f=l.return;try{nd(4,l)}catch(le){re(l,f,le)}break;case 1:var g=l.stateNode;if(typeof g.componentDidMount=="function"){var j=l.return;try{g.componentDidMount()}catch(le){re(l,j,le)}}var N=l.return;try{sd(l)}catch(le){re(l,N,le)}break;case 5:var U=l.return;try{sd(l)}catch(le){re(l,U,le)}}}catch(le){re(l,l.return,le)}if(l===o){gt=null;break}var oe=l.sibling;if(oe!==null){oe.return=l.return,gt=oe;break}gt=l.return}}var y_=Math.ceil,Tc=E.ReactCurrentDispatcher,id=E.ReactCurrentOwner,Xr=E.ReactCurrentBatchConfig,xn=0,As=null,cs=null,js=0,Pr=0,Pa=Zo(0),Ts=0,mi=null,Da=0,ao=0,Mc=0,Fa=null,jr=null,od=0,Pl=1/0,Zr=null,lo=!1,Yf=null,hi=null,ad=!1,Li=null,Po=0,Rc=0,Xf=null,Lc=-1,Ic=0;function Sr(){return(xn&6)!==0?Yt():Lc!==-1?Lc:Lc=Yt()}function Do(o){return(o.mode&1)===0?1:(xn&2)!==0&&js!==0?js&-js:Ef.transition!==null?(Ic===0&&(Ic=Rs()),Ic):(o=Sn,o!==0||(o=window.event,o=o===void 0?16:Me(o.type)),o)}function _i(o,l,f,g){if(50<Rc)throw Rc=0,Xf=null,Error(n(185));vs(o,f,g),((xn&2)===0||o!==As)&&(o===As&&((xn&2)===0&&(ao|=f),Ts===4&&Fo(o,js)),Dr(o,g),f===1&&xn===0&&(l.mode&1)===0&&(Pl=Yt()+500,Tu&&Xi()))}function Dr(o,l){var f=o.callbackNode;gs(o,l);var g=Fi(o,o===As?js:0);if(g===0)f!==null&&nn(f),o.callbackNode=null,o.callbackPriority=0;else if(l=g&-g,o.callbackPriority!==l){if(f!=null&&nn(f),l===1)o.tag===0?Mu(Qf.bind(null,o)):ir(Qf.bind(null,o)),Ih(function(){(xn&6)===0&&Xi()}),f=null;else{switch(ga(g)){case 1:f=Ns;break;case 4:f=ps;break;case 16:f=_r;break;case 536870912:f=wt;break;default:f=_r}f=tt(f,Zf.bind(null,o))}o.callbackPriority=l,o.callbackNode=f}}function Zf(o,l){if(Lc=-1,Ic=0,(xn&6)!==0)throw Error(n(327));var f=o.callbackNode;if(J()&&o.callbackNode!==f)return null;var g=Fi(o,o===As?js:0);if(g===0)return null;if((g&30)!==0||(g&o.expiredLanes)!==0||l)l=Oc(o,g);else{l=g;var j=xn;xn|=2;var N=tm();(As!==o||js!==l)&&(Zr=null,Pl=Yt()+500,ia(o,l));do try{v();break}catch(oe){em(o,oe)}while(!0);zu(),Tc.current=N,xn=j,cs!==null?l=0:(As=null,js=0,l=Ts)}if(l!==0){if(l===2&&(j=si(o),j!==0&&(g=j,l=ld(o,j))),l===1)throw f=mi,ia(o,0),Fo(o,g),Dr(o,Yt()),f;if(l===6)Fo(o,g);else{if(j=o.current.alternate,(g&30)===0&&!w_(j)&&(l=Oc(o,g),l===2&&(N=si(o),N!==0&&(g=N,l=ld(o,N))),l===1))throw f=mi,ia(o,0),Fo(o,g),Dr(o,Yt()),f;switch(o.finishedWork=j,o.finishedLanes=g,l){case 0:case 1:throw Error(n(345));case 2:B(o,jr,Zr);break;case 3:if(Fo(o,g),(g&130023424)===g&&(l=od+500-Yt(),10<l)){if(Fi(o,0)!==0)break;if(j=o.suspendedLanes,(j&g)!==g){Sr(),o.pingedLanes|=o.suspendedLanes&j;break}o.timeoutHandle=kf(B.bind(null,o,jr,Zr),l);break}B(o,jr,Zr);break;case 4:if(Fo(o,g),(g&4194240)===g)break;for(l=o.eventTimes,j=-1;0<g;){var U=31-nr(g);N=1<<U,U=l[U],U>j&&(j=U),g&=~N}if(g=j,g=Yt()-g,g=(120>g?120:480>g?480:1080>g?1080:1920>g?1920:3e3>g?3e3:4320>g?4320:1960*y_(g/1960))-g,10<g){o.timeoutHandle=kf(B.bind(null,o,jr,Zr),g);break}B(o,jr,Zr);break;case 5:B(o,jr,Zr);break;default:throw Error(n(329))}}}return Dr(o,Yt()),o.callbackNode===f?Zf.bind(null,o):null}function ld(o,l){var f=Fa;return o.current.memoizedState.isDehydrated&&(ia(o,l).flags|=256),o=Oc(o,l),o!==2&&(l=jr,jr=f,l!==null&&cd(l)),o}function cd(o){jr===null?jr=o:jr.push.apply(jr,o)}function w_(o){for(var l=o;;){if(l.flags&16384){var f=l.updateQueue;if(f!==null&&(f=f.stores,f!==null))for(var g=0;g<f.length;g++){var j=f[g],N=j.getSnapshot;j=j.value;try{if(!wr(N(),j))return!1}catch{return!1}}}if(f=l.child,l.subtreeFlags&16384&&f!==null)f.return=l,l=f;else{if(l===o)break;for(;l.sibling===null;){if(l.return===null||l.return===o)return!0;l=l.return}l.sibling.return=l.return,l=l.sibling}}return!0}function Fo(o,l){for(l&=~Mc,l&=~ao,o.suspendedLanes|=l,o.pingedLanes&=~l,o=o.expirationTimes;0<l;){var f=31-nr(l),g=1<<f;o[f]=-1,l&=~g}}function Qf(o){if((xn&6)!==0)throw Error(n(327));J();var l=Fi(o,0);if((l&1)===0)return Dr(o,Yt()),null;var f=Oc(o,l);if(o.tag!==0&&f===2){var g=si(o);g!==0&&(l=g,f=ld(o,g))}if(f===1)throw f=mi,ia(o,0),Fo(o,l),Dr(o,Yt()),f;if(f===6)throw Error(n(345));return o.finishedWork=o.current.alternate,o.finishedLanes=l,B(o,jr,Zr),Dr(o,Yt()),null}function ud(o,l){var f=xn;xn|=1;try{return o(l)}finally{xn=f,xn===0&&(Pl=Yt()+500,Tu&&Xi())}}function ra(o){Li!==null&&Li.tag===0&&(xn&6)===0&&J();var l=xn;xn|=1;var f=Xr.transition,g=Sn;try{if(Xr.transition=null,Sn=1,o)return o()}finally{Sn=g,Xr.transition=f,xn=l,(xn&6)===0&&Xi()}}function dd(){Pr=Pa.current,En(Pa)}function ia(o,l){o.finishedWork=null,o.finishedLanes=0;var f=o.timeoutHandle;if(f!==-1&&(o.timeoutHandle=-1,Rh(f)),cs!==null)for(f=cs.return;f!==null;){var g=f;switch(Iu(g),g.tag){case 1:g=g.type.childContextTypes,g!=null&&Eo();break;case 3:Nl(),En(br),En($s),ms();break;case 5:yc(g);break;case 4:Nl();break;case 13:En(as);break;case 19:En(as);break;case 10:Tf(g.type._context);break;case 22:case 23:dd()}f=f.return}if(As=o,cs=o=it(o.current,null),js=Pr=l,Ts=0,mi=null,Mc=ao=Da=0,jr=Fa=null,sn!==null){for(l=0;l<sn.length;l++)if(f=sn[l],g=f.interleaved,g!==null){f.interleaved=null;var j=g.next,N=f.pending;if(N!==null){var U=N.next;N.next=j,g.next=U}f.pending=g}sn=null}return o}function em(o,l){do{var f=cs;try{if(zu(),wc.current=Al,Yr){for(var g=ls.memoizedState;g!==null;){var j=g.queue;j!==null&&(j.pending=null),g=g.next}Yr=!1}if(bs=0,Cs=hs=ls=null,La=!1,xc=0,id.current=null,f===null||f.return===null){Ts=1,mi=l,cs=null;break}e:{var N=o,U=f.return,oe=f,le=l;if(l=js,oe.flags|=32768,le!==null&&typeof le=="object"&&typeof le.then=="function"){var Ce=le,Ye=oe,Qe=Ye.tag;if((Ye.mode&1)===0&&(Qe===0||Qe===11||Qe===15)){var He=Ye.alternate;He?(Ye.updateQueue=He.updateQueue,Ye.memoizedState=He.memoizedState,Ye.lanes=He.lanes):(Ye.updateQueue=null,Ye.memoizedState=null)}var pt=Ro(U);if(pt!==null){pt.flags&=-257,Lo(pt,U,oe,N,l),pt.mode&1&&Ti(N,Ce,l),l=pt,le=Ce;var vt=l.updateQueue;if(vt===null){var jt=new Set;jt.add(le),l.updateQueue=jt}else vt.add(le);break e}else{if((l&1)===0){Ti(N,Ce,l),fd();break e}le=Error(n(426))}}else if(Gn&&oe.mode&1){var Ls=Ro(U);if(Ls!==null){(Ls.flags&65536)===0&&(Ls.flags|=256),Lo(Ls,U,oe,N,l),Cf(Tl(le,oe));break e}}N=le=Tl(le,oe),Ts!==4&&(Ts=2),Fa===null?Fa=[N]:Fa.push(N),N=U;do{switch(N.tag){case 3:N.flags|=65536,l&=-l,N.lanes|=l;var xe=lr(N,le,l);Wh(N,xe);break e;case 1:oe=le;var de=N.type,ke=N.stateNode;if((N.flags&128)===0&&(typeof de.getDerivedStateFromError=="function"||ke!==null&&typeof ke.componentDidCatch=="function"&&(hi===null||!hi.has(ke)))){N.flags|=65536,l&=-l,N.lanes|=l;var st=Bs(N,oe,l);Wh(N,st);break e}}N=N.return}while(N!==null)}O(f)}catch($t){l=$t,cs===f&&f!==null&&(cs=f=f.return);continue}break}while(!0)}function tm(){var o=Tc.current;return Tc.current=Al,o===null?Al:o}function fd(){(Ts===0||Ts===3||Ts===2)&&(Ts=4),As===null||(Da&268435455)===0&&(ao&268435455)===0||Fo(As,js)}function Oc(o,l){var f=xn;xn|=2;var g=tm();(As!==o||js!==l)&&(Zr=null,ia(o,l));do try{v_();break}catch(j){em(o,j)}while(!0);if(zu(),xn=f,Tc.current=g,cs!==null)throw Error(n(261));return As=null,js=0,Ts}function v_(){for(;cs!==null;)C(cs)}function v(){for(;cs!==null&&!Je();)C(cs)}function C(o){var l=Oe(o.alternate,o,Pr);o.memoizedProps=o.pendingProps,l===null?O(o):cs=l,id.current=null}function O(o){var l=o;do{var f=l.alternate;if(o=l.return,(l.flags&32768)===0){if(f=Ag(f,l,Pr),f!==null){cs=f;return}}else{if(f=Tg(f,l),f!==null){f.flags&=32767,cs=f;return}if(o!==null)o.flags|=32768,o.subtreeFlags=0,o.deletions=null;else{Ts=6,cs=null;return}}if(l=l.sibling,l!==null){cs=l;return}cs=l=o}while(l!==null);Ts===0&&(Ts=5)}function B(o,l,f){var g=Sn,j=Xr.transition;try{Xr.transition=null,Sn=1,ee(o,l,f,g)}finally{Xr.transition=j,Sn=g}return null}function ee(o,l,f,g){do J();while(Li!==null);if((xn&6)!==0)throw Error(n(327));f=o.finishedWork;var j=o.finishedLanes;if(f===null)return null;if(o.finishedWork=null,o.finishedLanes=0,f===o.current)throw Error(n(177));o.callbackNode=null,o.callbackPriority=0;var N=f.lanes|f.childLanes;if(ii(o,N),o===As&&(cs=As=null,js=0),(f.subtreeFlags&2064)===0&&(f.flags&2064)===0||ad||(ad=!0,tt(_r,function(){return J(),null})),N=(f.flags&15990)!==0,(f.subtreeFlags&15990)!==0||N){N=Xr.transition,Xr.transition=null;var U=Sn;Sn=1;var oe=xn;xn|=4,id.current=null,Oo(o,f),h_(f,o),Eh(bf),sr=!!Nu,bf=Nu=null,o.current=f,Jf(f),en(),xn=oe,Sn=U,Xr.transition=N}else o.current=f;if(ad&&(ad=!1,Li=o,Po=j),N=o.pendingLanes,N===0&&(hi=null),bi(f.stateNode),Dr(o,Yt()),l!==null)for(g=o.onRecoverableError,f=0;f<l.length;f++)j=l[f],g(j.value,{componentStack:j.stack,digest:j.digest});if(lo)throw lo=!1,o=Yf,Yf=null,o;return(Po&1)!==0&&o.tag!==0&&J(),N=o.pendingLanes,(N&1)!==0?o===Xf?Rc++:(Rc=0,Xf=o):Rc=0,Xi(),null}function J(){if(Li!==null){var o=ga(Po),l=Xr.transition,f=Sn;try{if(Xr.transition=null,Sn=16>o?16:o,Li===null)var g=!1;else{if(o=Li,Li=null,Po=0,(xn&6)!==0)throw Error(n(331));var j=xn;for(xn|=4,gt=o.current;gt!==null;){var N=gt,U=N.child;if((gt.flags&16)!==0){var oe=N.deletions;if(oe!==null){for(var le=0;le<oe.length;le++){var Ce=oe[le];for(gt=Ce;gt!==null;){var Ye=gt;switch(Ye.tag){case 0:case 11:case 15:Ac(8,Ye,N)}var Qe=Ye.child;if(Qe!==null)Qe.return=Ye,gt=Qe;else for(;gt!==null;){Ye=gt;var He=Ye.sibling,pt=Ye.return;if(io(Ye),Ye===Ce){gt=null;break}if(He!==null){He.return=pt,gt=He;break}gt=pt}}}var vt=N.alternate;if(vt!==null){var jt=vt.child;if(jt!==null){vt.child=null;do{var Ls=jt.sibling;jt.sibling=null,jt=Ls}while(jt!==null)}}gt=N}}if((N.subtreeFlags&2064)!==0&&U!==null)U.return=N,gt=U;else e:for(;gt!==null;){if(N=gt,(N.flags&2048)!==0)switch(N.tag){case 0:case 11:case 15:Ac(9,N,N.return)}var xe=N.sibling;if(xe!==null){xe.return=N.return,gt=xe;break e}gt=N.return}}var de=o.current;for(gt=de;gt!==null;){U=gt;var ke=U.child;if((U.subtreeFlags&2064)!==0&&ke!==null)ke.return=U,gt=ke;else e:for(U=de;gt!==null;){if(oe=gt,(oe.flags&2048)!==0)try{switch(oe.tag){case 0:case 11:case 15:nd(9,oe)}}catch($t){re(oe,oe.return,$t)}if(oe===U){gt=null;break e}var st=oe.sibling;if(st!==null){st.return=oe.return,gt=st;break e}gt=oe.return}}if(xn=j,Xi(),tr&&typeof tr.onPostCommitFiberRoot=="function")try{tr.onPostCommitFiberRoot(Rn,o)}catch{}g=!0}return g}finally{Sn=f,Xr.transition=l}}return!1}function Q(o,l,f){l=Tl(f,l),l=lr(o,l,1),o=no(o,l,1),l=Sr(),o!==null&&(vs(o,1,l),Dr(o,l))}function re(o,l,f){if(o.tag===3)Q(o,o,f);else for(;l!==null;){if(l.tag===3){Q(l,o,f);break}else if(l.tag===1){var g=l.stateNode;if(typeof l.type.getDerivedStateFromError=="function"||typeof g.componentDidCatch=="function"&&(hi===null||!hi.has(g))){o=Tl(f,o),o=Bs(l,o,1),l=no(l,o,1),o=Sr(),l!==null&&(vs(l,1,o),Dr(l,o));break}}l=l.return}}function We(o,l,f){var g=o.pingCache;g!==null&&g.delete(l),l=Sr(),o.pingedLanes|=o.suspendedLanes&f,As===o&&(js&f)===f&&(Ts===4||Ts===3&&(js&130023424)===js&&500>Yt()-od?ia(o,0):Mc|=f),Dr(o,l)}function be(o,l){l===0&&((o.mode&1)===0?l=1:(l=pr,pr<<=1,(pr&130023424)===0&&(pr=4194304)));var f=Sr();o=to(o,l),o!==null&&(vs(o,l,f),Dr(o,f))}function _e(o){var l=o.memoizedState,f=0;l!==null&&(f=l.retryLane),be(o,f)}function Le(o,l){var f=0;switch(o.tag){case 13:var g=o.stateNode,j=o.memoizedState;j!==null&&(f=j.retryLane);break;case 19:g=o.stateNode;break;default:throw Error(n(314))}g!==null&&g.delete(l),be(o,f)}var Oe;Oe=function(o,l,f){if(o!==null)if(o.memoizedProps!==l.pendingProps||br.current)Ir=!0;else{if((o.lanes&f)===0&&(l.flags&128)===0)return Ir=!1,Il(o,l,f);Ir=(o.flags&131072)!==0}else Ir=!1,Gn&&(l.flags&1048576)!==0&&Nf(l,Ru,l.index);switch(l.lanes=0,l.tag){case 2:var g=l.type;Zu(o,l),o=l.pendingProps;var j=Yi(l,$s.current);Ma(l,f),j=kc(null,l,g,o,j,f);var N=Rf();return l.flags|=1,typeof j=="object"&&j!==null&&typeof j.render=="function"&&j.$$typeof===void 0?(l.tag=1,l.memoizedState=null,l.updateQueue=null,rr(g)?(N=!0,gl(l)):N=!1,l.memoizedState=j.state!==null&&j.state!==void 0?j.state:null,ea(l),j.updater=Vu,l.stateNode=j,j._reactInternals=l,Bf(l,g,o,f),l=Ju(null,l,g,!0,N,f)):(l.tag=0,Gn&&N&&Lu(l),Us(null,l,j,f),l=l.child),l;case 16:g=l.elementType;e:{switch(Zu(o,l),o=l.pendingProps,j=g._init,g=j(g._payload),l.type=g,j=l.tag=Xt(g),o=Ai(g,o),j){case 0:l=Io(null,l,g,o,f);break e;case 1:l=Rl(null,l,g,o,f);break e;case 11:l=o_(null,l,g,o,f);break e;case 14:l=Ku(null,l,g,Ai(g.type,o),f);break e}throw Error(n(306,g,""))}return l;case 0:return g=l.type,j=l.pendingProps,j=l.elementType===g?j:Ai(g,j),Io(o,l,g,j,f);case 1:return g=l.type,j=l.pendingProps,j=l.elementType===g?j:Ai(g,j),Rl(o,l,g,j,f);case 3:e:{if(qf(l),o===null)throw Error(n(387));g=l.pendingProps,N=l.memoizedState,j=N.element,tn(o,l),Wu(l,g,null,f);var U=l.memoizedState;if(g=U.element,N.isDehydrated)if(N={element:g,isDehydrated:!1,cache:U.cache,pendingSuspenseBoundaries:U.pendingSuspenseBoundaries,transitions:U.transitions},l.updateQueue.baseState=N,l.memoizedState=N,l.flags&256){j=Tl(Error(n(423)),l),l=c_(o,l,g,f,j);break e}else if(g!==j){j=Tl(Error(n(424)),l),l=c_(o,l,g,f,j);break e}else for(Lr=Yo(l.stateNode.containerInfo.firstChild),Jr=l,Gn=!0,$i=null,f=Uh(l,null,g,f),l.child=f;f;)f.flags=f.flags&-3|4096,f=f.sibling;else{if(Ta(),g===j){l=ks(o,l,f);break e}Us(o,l,g,f)}l=l.child}return l;case 5:return Hh(l),o===null&&gc(l),g=l.type,j=l.pendingProps,N=o!==null?o.memoizedProps:null,U=j.children,$u(g,j)?U=null:N!==null&&$u(g,N)&&(l.flags|=32),Wf(o,l),Us(o,l,U,f),l.child;case 6:return o===null&&gc(l),null;case 13:return u_(o,l,f);case 4:return Sl(l,l.stateNode.containerInfo),g=l.pendingProps,o===null?l.child=To(l,null,g,f):Us(o,l,g,f),l.child;case 11:return g=l.type,j=l.pendingProps,j=l.elementType===g?j:Ai(g,j),o_(o,l,g,j,f);case 7:return Us(o,l,l.pendingProps,f),l.child;case 8:return Us(o,l,l.pendingProps.children,f),l.child;case 12:return Us(o,l,l.pendingProps.children,f),l.child;case 10:e:{if(g=l.type._context,j=l.pendingProps,N=l.memoizedProps,U=j.value,Vn(Pu,g._currentValue),g._currentValue=U,N!==null)if(wr(N.value,U)){if(N.children===j.children&&!br.current){l=ks(o,l,f);break e}}else for(N=l.child,N!==null&&(N.return=l);N!==null;){var oe=N.dependencies;if(oe!==null){U=N.child;for(var le=oe.firstContext;le!==null;){if(le.context===g){if(N.tag===1){le=Mo(-1,f&-f),le.tag=2;var Ce=N.updateQueue;if(Ce!==null){Ce=Ce.shared;var Ye=Ce.pending;Ye===null?le.next=le:(le.next=Ye.next,Ye.next=le),Ce.pending=le}}N.lanes|=f,le=N.alternate,le!==null&&(le.lanes|=f),kl(N.return,f,l),oe.lanes|=f;break}le=le.next}}else if(N.tag===10)U=N.type===l.type?null:N.child;else if(N.tag===18){if(U=N.return,U===null)throw Error(n(341));U.lanes|=f,oe=U.alternate,oe!==null&&(oe.lanes|=f),kl(U,f,l),U=N.sibling}else U=N.child;if(U!==null)U.return=N;else for(U=N;U!==null;){if(U===l){U=null;break}if(N=U.sibling,N!==null){N.return=U.return,U=N;break}U=U.return}N=U}Us(o,l,j.children,f),l=l.child}return l;case 9:return j=l.type,g=l.pendingProps.children,Ma(l,f),j=ns(j),g=g(j),l.flags|=1,Us(o,l,g,f),l.child;case 14:return g=l.type,j=Ai(g,l.pendingProps),j=Ai(g.type,j),Ku(o,l,g,j,f);case 15:return a_(o,l,l.type,l.pendingProps,f);case 17:return g=l.type,j=l.pendingProps,j=l.elementType===g?j:Ai(g,j),Zu(o,l),l.tag=1,rr(g)?(o=!0,gl(l)):o=!1,Ma(l,f),zf(l,g,j),Bf(l,g,j,f),Ju(null,l,g,!0,o,f);case 19:return d_(o,l,f);case 22:return l_(o,l,f)}throw Error(n(156,l.tag))};function tt(o,l){return Mn(o,l)}function ft(o,l,f,g){this.tag=o,this.key=f,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=l,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=g,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function nt(o,l,f,g){return new ft(o,l,f,g)}function fn(o){return o=o.prototype,!(!o||!o.isReactComponent)}function Xt(o){if(typeof o=="function")return fn(o)?1:0;if(o!=null){if(o=o.$$typeof,o===Z)return 11;if(o===P)return 14}return 2}function it(o,l){var f=o.alternate;return f===null?(f=nt(o.tag,l,o.key,o.mode),f.elementType=o.elementType,f.type=o.type,f.stateNode=o.stateNode,f.alternate=o,o.alternate=f):(f.pendingProps=l,f.type=o.type,f.flags=0,f.subtreeFlags=0,f.deletions=null),f.flags=o.flags&14680064,f.childLanes=o.childLanes,f.lanes=o.lanes,f.child=o.child,f.memoizedProps=o.memoizedProps,f.memoizedState=o.memoizedState,f.updateQueue=o.updateQueue,l=o.dependencies,f.dependencies=l===null?null:{lanes:l.lanes,firstContext:l.firstContext},f.sibling=o.sibling,f.index=o.index,f.ref=o.ref,f}function Bt(o,l,f,g,j,N){var U=2;if(g=o,typeof o=="function")fn(o)&&(U=1);else if(typeof o=="string")U=5;else e:switch(o){case M:return Tn(f.children,j,N,l);case D:U=8,j|=8;break;case H:return o=nt(12,f,l,j|2),o.elementType=H,o.lanes=N,o;case R:return o=nt(13,f,l,j),o.elementType=R,o.lanes=N,o;case T:return o=nt(19,f,l,j),o.elementType=T,o.lanes=N,o;case te:return Jn(f,j,N,l);default:if(typeof o=="object"&&o!==null)switch(o.$$typeof){case q:U=10;break e;case I:U=9;break e;case Z:U=11;break e;case P:U=14;break e;case L:U=16,g=null;break e}throw Error(n(130,o==null?o:typeof o,""))}return l=nt(U,f,l,j),l.elementType=o,l.type=g,l.lanes=N,l}function Tn(o,l,f,g){return o=nt(7,o,g,l),o.lanes=f,o}function Jn(o,l,f,g){return o=nt(22,o,g,l),o.elementType=te,o.lanes=f,o.stateNode={isHidden:!1},o}function ur(o,l,f){return o=nt(6,o,null,l),o.lanes=f,o}function Fr(o,l,f){return l=nt(4,o.children!==null?o.children:[],o.key,l),l.lanes=f,l.stateNode={containerInfo:o.containerInfo,pendingChildren:null,implementation:o.implementation},l}function Ii(o,l,f,g,j){this.tag=l,this.containerInfo=o,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=ri(0),this.expirationTimes=ri(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=ri(0),this.identifierPrefix=g,this.onRecoverableError=j,this.mutableSourceEagerHydrationData=null}function za(o,l,f,g,j,N,U,oe,le){return o=new Ii(o,l,f,oe,le),l===1?(l=1,N===!0&&(l|=8)):l=0,N=nt(3,null,null,l),o.current=N,N.stateNode=o,N.memoizedState={element:g,isDehydrated:f,cache:null,transitions:null,pendingSuspenseBoundaries:null},ea(N),o}function x$(o,l,f){var g=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:F,key:g==null?null:""+g,children:o,containerInfo:l,implementation:f}}function lx(o){if(!o)return li;o=o._reactInternals;e:{if(Ht(o)!==o||o.tag!==1)throw Error(n(170));var l=o;do{switch(l.tag){case 3:l=l.stateNode.context;break e;case 1:if(rr(l.type)){l=l.stateNode.__reactInternalMemoizedMergedChildContext;break e}}l=l.return}while(l!==null);throw Error(n(171))}if(o.tag===1){var f=o.type;if(rr(f))return Ph(o,f,l)}return l}function cx(o,l,f,g,j,N,U,oe,le){return o=za(f,g,!0,o,j,N,U,oe,le),o.context=lx(null),f=o.current,g=Sr(),j=Do(f),N=Mo(g,j),N.callback=l??null,no(f,N,j),o.current.lanes=j,vs(o,j,g),Dr(o,g),o}function x_(o,l,f,g){var j=l.current,N=Sr(),U=Do(j);return f=lx(f),l.context===null?l.context=f:l.pendingContext=f,l=Mo(N,U),l.payload={element:o},g=g===void 0?null:g,g!==null&&(l.callback=g),o=no(j,l,U),o!==null&&(_i(o,j,U,N),Uu(o,j,U)),U}function b_(o){if(o=o.current,!o.child)return null;switch(o.child.tag){case 5:return o.child.stateNode;default:return o.child.stateNode}}function ux(o,l){if(o=o.memoizedState,o!==null&&o.dehydrated!==null){var f=o.retryLane;o.retryLane=f!==0&&f<l?f:l}}function Mg(o,l){ux(o,l),(o=o.alternate)&&ux(o,l)}function b$(){return null}var dx=typeof reportError=="function"?reportError:function(o){console.error(o)};function Rg(o){this._internalRoot=o}k_.prototype.render=Rg.prototype.render=function(o){var l=this._internalRoot;if(l===null)throw Error(n(409));x_(o,l,null,null)},k_.prototype.unmount=Rg.prototype.unmount=function(){var o=this._internalRoot;if(o!==null){this._internalRoot=null;var l=o.containerInfo;ra(function(){x_(null,o,null,null)}),l[Ni]=null}};function k_(o){this._internalRoot=o}k_.prototype.unstable_scheduleHydration=function(o){if(o){var l=rc();o={blockedOn:null,target:o,priority:l};for(var f=0;f<Ar.length&&l!==0&&l<Ar[f].priority;f++);Ar.splice(f,0,o),f===0&&ki(o)}};function Lg(o){return!(!o||o.nodeType!==1&&o.nodeType!==9&&o.nodeType!==11)}function j_(o){return!(!o||o.nodeType!==1&&o.nodeType!==9&&o.nodeType!==11&&(o.nodeType!==8||o.nodeValue!==" react-mount-point-unstable "))}function fx(){}function k$(o,l,f,g,j){if(j){if(typeof g=="function"){var N=g;g=function(){var Ce=b_(U);N.call(Ce)}}var U=cx(l,g,o,0,null,!1,!1,"",fx);return o._reactRootContainer=U,o[Ni]=U.current,ji(o.nodeType===8?o.parentNode:o),ra(),U}for(;j=o.lastChild;)o.removeChild(j);if(typeof g=="function"){var oe=g;g=function(){var Ce=b_(le);oe.call(Ce)}}var le=za(o,0,!1,null,null,!1,!1,"",fx);return o._reactRootContainer=le,o[Ni]=le.current,ji(o.nodeType===8?o.parentNode:o),ra(function(){x_(l,le,f,g)}),le}function S_(o,l,f,g,j){var N=f._reactRootContainer;if(N){var U=N;if(typeof j=="function"){var oe=j;j=function(){var le=b_(U);oe.call(le)}}x_(l,U,o,j)}else U=k$(f,l,o,j,g);return b_(U)}tl=function(o){switch(o.tag){case 3:var l=o.stateNode;if(l.current.memoizedState.isDehydrated){var f=Ms(l.pendingLanes);f!==0&&(zi(l,f|1),Dr(l,Yt()),(xn&6)===0&&(Pl=Yt()+500,Xi()))}break;case 13:ra(function(){var g=to(o,1);if(g!==null){var j=Sr();_i(g,o,1,j)}}),Mg(o,1)}},nl=function(o){if(o.tag===13){var l=to(o,134217728);if(l!==null){var f=Sr();_i(l,o,134217728,f)}Mg(o,134217728)}},Er=function(o){if(o.tag===13){var l=Do(o),f=to(o,l);if(f!==null){var g=Sr();_i(f,o,l,g)}Mg(o,l)}},rc=function(){return Sn},Bi=function(o,l){var f=Sn;try{return Sn=o,l()}finally{Sn=f}},Hs=function(o,l,f){switch(l){case"input":if(Se(o,f),l=f.name,f.type==="radio"&&l!=null){for(f=o;f.parentNode;)f=f.parentNode;for(f=f.querySelectorAll("input[name="+JSON.stringify(""+l)+'][type="radio"]'),l=0;l<f.length;l++){var g=f[l];if(g!==o&&g.form===o.form){var j=No(g);if(!j)throw Error(n(90));bt(g),Se(g,j)}}}break;case"textarea":Te(o,f);break;case"select":l=f.value,l!=null&&Ie(o,!!f.multiple,l,!1)}},ce=ud,je=ra;var j$={usingClientEntryPoint:!1,Events:[Xo,pl,No,mt,se,ud]},nm={findFiberByHostInstance:Ea,bundleType:0,version:"18.3.1",rendererPackageName:"react-dom"},S$={bundleType:nm.bundleType,version:nm.version,rendererPackageName:nm.rendererPackageName,rendererConfig:nm.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:E.ReactCurrentDispatcher,findHostInstanceByFiber:function(o){return o=Ut(o),o===null?null:o.stateNode},findFiberByHostInstance:nm.findFiberByHostInstance||b$,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 N_=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!N_.isDisabled&&N_.supportsFiber)try{Rn=N_.inject(S$),tr=N_}catch{}}return pi.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=j$,pi.createPortal=function(o,l){var f=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!Lg(l))throw Error(n(200));return x$(o,l,null,f)},pi.createRoot=function(o,l){if(!Lg(o))throw Error(n(299));var f=!1,g="",j=dx;return l!=null&&(l.unstable_strictMode===!0&&(f=!0),l.identifierPrefix!==void 0&&(g=l.identifierPrefix),l.onRecoverableError!==void 0&&(j=l.onRecoverableError)),l=za(o,1,!1,null,null,f,!1,g,j),o[Ni]=l.current,ji(o.nodeType===8?o.parentNode:o),new Rg(l)},pi.findDOMNode=function(o){if(o==null)return null;if(o.nodeType===1)return o;var l=o._reactInternals;if(l===void 0)throw typeof o.render=="function"?Error(n(188)):(o=Object.keys(o).join(","),Error(n(268,o)));return o=Ut(l),o=o===null?null:o.stateNode,o},pi.flushSync=function(o){return ra(o)},pi.hydrate=function(o,l,f){if(!j_(l))throw Error(n(200));return S_(null,o,l,!0,f)},pi.hydrateRoot=function(o,l,f){if(!Lg(o))throw Error(n(405));var g=f!=null&&f.hydratedSources||null,j=!1,N="",U=dx;if(f!=null&&(f.unstable_strictMode===!0&&(j=!0),f.identifierPrefix!==void 0&&(N=f.identifierPrefix),f.onRecoverableError!==void 0&&(U=f.onRecoverableError)),l=cx(l,null,o,1,f??null,j,!1,N,U),o[Ni]=l.current,ji(o),g)for(o=0;o<g.length;o++)f=g[o],j=f._getVersion,j=j(f._source),l.mutableSourceEagerHydrationData==null?l.mutableSourceEagerHydrationData=[f,j]:l.mutableSourceEagerHydrationData.push(f,j);return new k_(l)},pi.render=function(o,l,f){if(!j_(l))throw Error(n(200));return S_(null,o,l,!1,f)},pi.unmountComponentAtNode=function(o){if(!j_(o))throw Error(n(40));return o._reactRootContainer?(ra(function(){S_(null,null,o,!1,function(){o._reactRootContainer=null,o[Ni]=null})}),!0):!1},pi.unstable_batchedUpdates=ud,pi.unstable_renderSubtreeIntoContainer=function(o,l,f,g){if(!j_(f))throw Error(n(200));if(o==null||o._reactInternals===void 0)throw Error(n(38));return S_(o,l,f,!1,g)},pi.version="18.3.1-next-f1338f8080-20240426",pi}var vx;function Fk(){if(vx)return Pg.exports;vx=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(),Pg.exports=L$(),Pg.exports}var xx;function I$(){if(xx)return $_;xx=1;var e=Fk();return $_.createRoot=e.createRoot,$_.hydrateRoot=e.hydrateRoot,$_}var O$=I$();const P$=iv(O$),zk=[{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"]}];zk.map(e=>({id:e.id,label:e.label}));function D$(e){return`theme-${String(e||"").trim()||"dark"}`}function bx(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(D$(e))}catch{}}const Gy=[{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}],Ky=[{id:"compact",label:"Compact",density:.85},{id:"standard",label:"Standard",density:1},{id:"spacious",label:"Spacious",density:1.2}];function F$(e){const t=String(e).trim();return Gy.find(n=>n.id===t)||Gy[1]}function z$(e){const t=String(e).trim();return Ky.find(n=>n.id===t)||Ky[1]}function kx(e){try{const t=document.documentElement,n=F$(e.font_scale||"md"),r=z$(e.header_density||"standard");t.style.setProperty("--font-scale",String(n.scale)),t.style.setProperty("--header-density",String(r.density))}catch{}}const zg={sm:"(max-width: 767.98px)",md:"(max-width: 1023.98px)",short:"(max-height: 500px)"};function B$(e){try{return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia(e).matches}catch{return!1}}function jx(e){const[t,n]=_.useState(()=>B$(e));return _.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const r=window.matchMedia(e),i=()=>n(r.matches);return i(),typeof r.addEventListener=="function"?r.addEventListener("change",i):r.addListener(i),()=>{typeof r.removeEventListener=="function"?r.removeEventListener("change",i):r.removeListener(i)}},[e]),t}let rm=null;function U$(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))),i=Math.max(0,Math.round(e-t.height-Math.max(0,t.offsetTop)));return{vvHeight:r,keyboardInset:i}}function W$(){if(rm)return rm;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:a,keyboardInset:u}=U$(window.innerHeight,{height:e.height,offsetTop:e.offsetTop,scale:e.scale||1});t.style.setProperty("--vv-height",`${a}px`),t.style.setProperty("--keyboard-inset",`${u}px`)},i=()=>{n||(n=window.requestAnimationFrame(r))};return r(),e.addEventListener("resize",i),e.addEventListener("scroll",i),window.addEventListener("orientationchange",i),rm=()=>{e.removeEventListener("resize",i),e.removeEventListener("scroll",i),window.removeEventListener("orientationchange",i),n&&window.cancelAnimationFrame(n),t.style.removeProperty("--vv-height"),t.style.removeProperty("--keyboard-inset"),rm=null},rm}var Xp=Fk();function md(...e){return e.filter(Boolean).join(" ")}function Pi({value:e,options:t,placeholder:n="Select…",disabled:r=!1,loading:i=!1,searchable:a=!0,searchPlaceholder:u="Search…",allowCustom:c=!1,clearable:d=!1,minPopoverWidth:m=240,variant:h="panel",className:p,triggerClassName:y,ariaLabel:w,id:x,includeValueOption:k=!1,onOpen:b,customOptionLabel:S,validateCustomValue:$,onChange:A,renderOption:E,renderValue:z}){const F=_.useRef(null),M=_.useRef(null),D=_.useRef(null),H=_.useRef(b),q=_.useId(),I=x||`af-select-${q.replace(/[^a-zA-Z0-9_-]/g,"")}`,Z=`${I}-listbox`,[R,T]=_.useState(!1),[P,L]=_.useState(""),[te,X]=_.useState(0),[V,ne]=_.useState("bottom"),[W,Y]=_.useState({left:0,top:0,width:0});_.useEffect(()=>{H.current=b},[b]);const K=_.useMemo(()=>{if(!k)return t;const ye=String(e??"").trim();return!ye||t.some(Ie=>Ie.value===ye)?t:[...t,{value:ye,label:ye}]},[k,t,e]),fe=_.useMemo(()=>{const ye=String(e??"");return K.find(Ie=>Ie.value===ye)||null},[K,e]),ae=_.useMemo(()=>(fe==null?void 0:fe.label)||String(e||"").trim()||"",[fe,e]),ve=_.useMemo(()=>{const ye=P.trim().toLowerCase();return ye?K.filter(Ie=>Ie.label.toLowerCase().includes(ye)||Ie.value.toLowerCase().includes(ye)):K},[K,P]),ge=_.useMemo(()=>{if(!c)return null;const ye=P.trim();if(!ye||K.some(ie=>ie.value===ye))return null;const ct=($==null?void 0:$(ye,{options:K}))||"";return{value:ye,label:S?S(ye):`Use "${ye}"`,disabled:!!ct,reason:ct}},[c,S,K,P,$]),pe=_.useMemo(()=>{const ye=ge?[ge,...ve]:ve;if(ye.length>0)return ye;const Ie=String(e??"").trim();return i&&Ie?[{value:Ie,label:ae||Ie}]:ye},[ge,ve,i,ae,e]),$e=_.useCallback(()=>{const ye=F.current;if(!ye)return;const Ie=ye.getBoundingClientRect(),ct=Math.max(Ie.width,m),ie=Math.max(8,Math.min(Ie.left,window.innerWidth-ct-8)),Te=window.innerHeight-Ie.bottom,et=Ie.top,Ge=Te>=220||Te>=et?"bottom":"top";ne(Ge);const Be=Ge==="bottom"?Ie.bottom+6:Ie.top-6;Y({left:ie,top:Be,width:ct})},[m]),De=_.useCallback(()=>{T(!1),L("")},[]);_.useEffect(()=>{var ye;R&&((ye=H.current)==null||ye.call(H))},[R]),_.useEffect(()=>{if(!R)return;$e();const ye=()=>$e();return window.addEventListener("resize",ye),window.addEventListener("scroll",ye,!0),()=>{window.removeEventListener("resize",ye),window.removeEventListener("scroll",ye,!0)}},[R,$e]),_.useEffect(()=>{if(!R)return;const ye=Ie=>{var ie,Te;const ct=Ie.target;ct&&((ie=F.current)!=null&&ie.contains(ct)||(Te=M.current)!=null&&Te.contains(ct)||De())};return document.addEventListener("mousedown",ye,!0),()=>document.removeEventListener("mousedown",ye,!0)},[R,De]),_.useEffect(()=>{if(!R)return;const ye=Math.max(0,pe.findIndex(Ie=>Ie.value===e));X(ye===-1?0:ye),a&&setTimeout(()=>{var Ie;return(Ie=D.current)==null?void 0:Ie.focus()},0)},[R,a,e,pe]);const ot=ye=>{var ct;const Ie=pe.find(ie=>ie.value===ye);Ie!=null&&Ie.disabled||(A(ye),De(),(ct=F.current)==null||ct.focus())},bt=ye=>{var Ie,ct;if(ye.key==="Escape")return ye.preventDefault(),De(),(Ie=F.current)==null||Ie.focus(),!0;if(ye.key==="Tab")return De(),(ct=F.current)==null||ct.focus(),!1;if(ye.key==="ArrowDown")return ye.preventDefault(),X(ie=>Math.min(ie+1,Math.max(0,pe.length-1))),!0;if(ye.key==="ArrowUp")return ye.preventDefault(),X(ie=>Math.max(ie-1,0)),!0;if(ye.key==="Home")return ye.preventDefault(),X(0),!0;if(ye.key==="End")return ye.preventDefault(),X(Math.max(0,pe.length-1)),!0;if(ye.key==="Enter"){ye.preventDefault();const ie=pe[te];return ie&&ot(ie.value),!0}return!1},Ue=ye=>{if(!r){if(R){if(bt(ye))return;if(ye.key===" "&&!a){ye.preventDefault();const Ie=pe[te];Ie&&ot(Ie.value)}return}(ye.key==="Enter"||ye.key===" "||ye.key==="ArrowDown"||ye.key==="ArrowUp")&&(ye.preventDefault(),T(!0))}},at=!!String(e||"").trim(),Nt=at?ae:n,ut=ge!=null&&ge.disabled?ge.reason||"Unavailable":"",Se=R&&pe.length>0?`${I}-opt-${te}`:void 0,me=s.jsx("span",{className:md("af-select-value",!at&&"af-select-value--placeholder"),children:i&&!at?"Loading…":Nt}),Ve=z?z(fe,String(e||"")):me;return s.jsxs("span",{className:md("af-select",h==="pin"?"af-select--pin":"af-select--panel",p),children:[s.jsxs("button",{ref:F,id:I,type:"button",className:md("af-select-trigger",d&&at&&"af-select-trigger--clearable",y),disabled:r,onMouseDown:ye=>ye.stopPropagation(),onClick:ye=>{ye.stopPropagation(),!r&&T(Ie=>!Ie)},onKeyDown:Ue,role:a?void 0:"combobox","aria-haspopup":"listbox","aria-expanded":R,"aria-controls":R?Z:void 0,"aria-activedescendant":a?void 0:Se,"aria-label":w,children:[Ve,s.jsx("span",{className:md("af-select-caret",R&&"af-select-caret--open"),children:"▾"})]}),d&&at?s.jsx("button",{type:"button",className:"af-select-clear-btn","aria-label":"Clear selection",disabled:r,onMouseDown:ye=>{ye.preventDefault(),ye.stopPropagation()},onClick:ye=>{var Ie;ye.preventDefault(),ye.stopPropagation(),A(""),De(),(Ie=F.current)==null||Ie.focus()},title:"Clear",children:"×"}):null,R?Xp.createPortal(s.jsxs("div",{ref:M,className:md("af-select-popover",V==="top"&&"af-select-popover--top"),style:{position:"fixed",left:`${W.left}px`,top:`${W.top}px`,width:`${W.width}px`},onMouseDown:ye=>ye.stopPropagation(),onClick:ye=>ye.stopPropagation(),onWheel:ye=>ye.stopPropagation(),onKeyDown:bt,tabIndex:-1,children:[a?s.jsxs("div",{className:"af-select-search",children:[s.jsx("input",{ref:D,className:"af-select-search-input",value:P,onChange:ye=>L(ye.target.value),placeholder:u,onKeyDown:bt,role:"combobox","aria-expanded":!0,"aria-controls":Z,"aria-activedescendant":Se,"aria-invalid":!!ut,"aria-describedby":ut?`${I}-custom-error`:void 0}),ut?s.jsx("div",{id:`${I}-custom-error`,className:"af-select-custom-error",role:"alert",children:ut}):null]}):null,s.jsx("div",{className:"af-select-options",role:"listbox",id:Z,"aria-label":w,children:i&&pe.length===0?s.jsx("div",{className:"af-select-empty",children:"Loading…"}):pe.length===0?s.jsx("div",{className:"af-select-empty",children:"No results"}):pe.map((ye,Ie)=>{var Be;const ct=ye.value===e,ie=Ie===te,Te=String(ye.group||"").trim(),et=Ie>0?String(((Be=pe[Ie-1])==null?void 0:Be.group)||"").trim():"",Ge=!!Te&&Te!==et;return s.jsxs(Ne.Fragment,{children:[Ge?s.jsx("div",{className:"af-select-group",role:"presentation",children:Te}):null,s.jsx("div",{id:`${I}-opt-${Ie}`,role:"option","aria-selected":ct,className:md("af-select-option",ct&&"af-select-option--selected",ie&&"af-select-option--highlighted",ye.disabled&&"af-select-option--disabled"),title:ye.disabled?ye.reason||"Unavailable":void 0,onMouseEnter:()=>X(Ie),onMouseDown:Rt=>{Rt.preventDefault(),Rt.stopPropagation()},onClick:()=>ot(ye.value),"aria-disabled":ye.disabled?!0:void 0,children:E?E(ye,{selected:ct,highlighted:ie}):s.jsxs(s.Fragment,{children:[s.jsxs("span",{className:"af-select-option-label",children:[s.jsx("span",{children:ye.label}),ye.reason?s.jsx("small",{className:"af-select-option-reason",children:ye.reason}):null]}),ct?s.jsx("span",{className:"af-select-check",children:"✓"}):null]})})]},ye.value)})})]}),document.body):null]})}function q$(e){const t=new Set,n=[];for(const r of e||[]){if(!r||typeof r!="object")continue;const i=String(r.name||"").trim();!i||t.has(i)||(t.add(i),n.push({name:i,display_name:typeof r.display_name=="string"?r.display_name:void 0}))}return n.sort((r,i)=>r.name.localeCompare(i.name)),n}function H$(e){const t=new Set,n=[];for(const r of e||[]){const i=String(r||"").trim();!i||t.has(i)||(t.add(i),n.push(i))}return n.sort(),n}function Bk(e){const t=e.disabled===!0,n=e.layout||"stack",r=e.allowGatewayDefault!==!1,i=String(e.gatewayDefaultLabel||"(gateway default)"),a=String(e.providerLabel||"Provider"),u=String(e.modelLabel||"Model"),c=String(e.providerPlaceholder||"(select)"),d=String(e.modelPlaceholder||"(select)"),m=String(e.provider||"").trim(),h=String(e.model||"").trim(),p=q$(e.providers),y=H$(e.models),w=t||!!e.loadingProviders,x=t||!!e.loadingModels,k=[...r?[{value:"",label:i}]:[],...p.map(S=>({value:S.name,label:S.display_name?`${S.display_name} (${S.name})`:S.name}))],b=[...r?[{value:"",label:i}]:[],...y.map(S=>({value:S,label:S}))];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:a}),s.jsx(Pi,{value:m,options:k,placeholder:r?i:c,disabled:w,loading:!!e.loadingProviders,searchable:!0,allowCustom:e.allowCustomProvider===!0,clearable:r,variant:"panel",triggerClassName:e.selectClassName,ariaLabel:a,onChange:S=>e.onChange({provider:String(S||"").trim(),model:""})}),e.loadingProviders?s.jsx("div",{className:"mono muted",style:{fontSize:"12px",marginTop:"6px"},children:"Loading providers…"}):null,e.providerError?s.jsx("div",{className:"mono",style:{color:"var(--error)",fontSize:"12px",marginTop:"6px"},children:e.providerError}):null]}),s.jsxs("div",{style:n==="row"?{flex:"1 1 260px",minWidth:240}:void 0,children:[s.jsx("label",{children:u}),s.jsx(Pi,{value:h,options:b,placeholder:r?i:d,disabled:x,loading:!!e.loadingModels,searchable:!0,allowCustom:e.allowCustomModel===!0,clearable:r,variant:"panel",triggerClassName:e.selectClassName,ariaLabel:u,onChange:S=>e.onChange({provider:m,model:String(S||"").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 V$(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 G$(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 Sx(e){const t=V$(e);return t===!1?"off":t?String(t.num_draft_tokens):""}function K$(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 J$(e){const t=G$(e.capabilities),n=Sx(e.value),r=(t==null?void 0:t.supported_depths.map(String))||[],i=Sx(t==null?void 0:t.default),a=e.inheritLabel||"Workflow / Gateway default",u=i?`${a} (${i==="off"?"Off":`depth ${i}`})`:a,c=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(Pi,{ariaLabel:"MTP depth",value:n,placeholder:u,disabled:e.disabled||e.loading,options:[{value:"",label:u},{value:"off",label:"Off"},...r.map(d=>({value:d,label:`Depth ${d}`})),...n&&n!=="off"&&!r.includes(n)?[{value:n,label:`Depth ${n} (saved; not available)`}]:[]],onChange:d=>e.onChange(K$(d))}),c&&!e.hideNote?s.jsx("div",{role:"status",className:"af-pmp__hint",children:c}):null]})}const Y$="Reasoning and MTP choices appear when the gateway can describe the selected model.",X$="Reasoning choices appear when the gateway can describe the selected model.";function Uk(e){var ne,W;const t=e.disabled===!0,n=e.value||{provider:"",model:""},r=!String(n.provider||"").trim()&&!String(n.model||"").trim(),[i,a]=_.useState(!r),u=r&&!i,c=_.useRef(r);_.useEffect(()=>{r&&!c.current&&a(!1),c.current=r},[r]);const[d,m]=_.useState([]),[h,p]=_.useState(!1),[y,w]=_.useState(""),[x,k]=_.useState([]),[b,S]=_.useState(!1),[$,A]=_.useState(""),E=_.useRef(e);E.current=e,_.useEffect(()=>{if(u||t)return;let Y=!0;return p(!0),(async()=>{try{const K=await E.current.fetchProviders();if(!Y)return;m(Array.isArray(K)?K:[]),w("")}catch(K){if(!Y)return;m([]),w(`#FALLBACK provider discovery failed: ${String((K==null?void 0:K.message)||K)}`)}finally{Y&&p(!1)}})(),()=>{Y=!1}},[u,t]);const z=String(n.provider||"").trim();_.useEffect(()=>{if(!z||t){k([]),A(""),S(!1);return}let Y=!0;return k([]),S(!0),A(""),(async()=>{try{const K=await E.current.fetchModels(z);if(!Y)return;k(Array.isArray(K)?K:[])}catch(K){if(!Y)return;k([]),A(`#FALLBACK model discovery failed: ${String((K==null?void 0:K.message)||K)}`)}finally{Y&&S(!1)}})(),()=>{Y=!1}},[z,t]);const F=_.useMemo(()=>{const Y=[...d];return z&&!Y.some(K=>K.name===z)&&Y.unshift({name:z}),Y},[d,z]),M=String(n.model||"").trim(),D=_.useMemo(()=>{const Y=[...x];return M&&!Y.includes(M)&&Y.unshift(M),Y},[x,M]),H=e.defaultModeLabel||"Gateway default",q=e.customModeLabel||"Custom",I=z||((ne=e.effectiveDefault)==null?void 0:ne.provider)||"",Z=M||(z?"":(W=e.effectiveDefault)==null?void 0:W.model)||"",[R,T]=_.useState({levels:[],error:"",loading:!1}),P=!!e.fetchModelCapabilities,[L,te]=_.useState();_.useEffect(()=>{let Y=!0;if(te(void 0),T({levels:[],error:"",loading:P&&!!Z}),!(!P||!Z||t))return E.current.fetchModelCapabilities(Z,I).then(K=>{var ge;if(!Y)return;if(K!=null&&K.error)throw new Error(String(K.error));te(K);const fe=(K==null?void 0:K.capabilities)||K||{},ae=fe.reasoning_levels||fe.thinking_levels,ve=Array.isArray(ae)?[...new Set(ae.filter(pe=>typeof pe=="string"&&!!pe.trim()))]:[];!ve.length&&fe.thinking_support===!0&&((ge=fe.thinking_control)!=null&&ge.prompt_disable_token)&&ve.push("off","auto"),T({levels:ve,error:"",loading:!1})}).catch(K=>{Y&&T({levels:[],error:String((K==null?void 0:K.message)||K),loading:!1})}),()=>{Y=!1}},[I,Z,P,t]);const X=e.inheritLabel||"Workflow / Gateway default",V=!u||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":u,className:`af-pmp__seg-btn${u?" is-active":""}`,onClick:()=>{a(!1),e.onChange({...n,provider:"",model:"",...P?{reasoning:""}:{}})},disabled:t,children:H}),s.jsx("button",{type:"button",role:"tab","aria-selected":!u,className:`af-pmp__seg-btn${u?"":" is-active"}`,onClick:()=>{a(!0)},disabled:t,children:q})]}),u?s.jsx("div",{className:"af-pmp__hint",children:e.defaultHint||"The gateway picks its configured default provider and model for this task."}):s.jsx(Bk,{provider:z,model:M,providers:F,models:D,disabled:t,loadingProviders:h,loadingModels:b,providerError:y||void 0,modelError:$||void 0,providerLabel:e.providerLabel,modelLabel:e.modelLabel,allowGatewayDefault:!1,allowCustomProvider:e.allowCustom!==!1,allowCustomModel:e.allowCustom!==!1,onChange:Y=>e.onChange({...n,provider:Y.provider,model:Y.model,...P?{reasoning:""}:{}})}),V&&P&&(R.levels.length>0||n.reasoning)?s.jsxs("div",{className:"af-pmp__reasoning",children:[s.jsx("label",{children:e.reasoningLabel||"Reasoning effort"}),s.jsx(Pi,{ariaLabel:e.reasoningLabel||"Reasoning effort",placeholder:X,value:n.reasoning||"",options:[{value:"",label:X},...R.levels.map(Y=>({value:Y,label:Y})),...n.reasoning&&!R.levels.includes(n.reasoning)?[{value:n.reasoning,label:`${n.reasoning} (saved; not advertised)`}]:[]],disabled:t||R.loading,onChange:Y=>e.onChange({...n,reasoning:Y})})]}):null,V&&e.enableSpeculation?s.jsx(J$,{value:n.speculation,inheritLabel:X,onChange:Y=>e.onChange({...n,speculation:Y}),capabilities:L,disabled:t,loading:R.loading,hideNote:!!R.error}):null,V&&R.error?s.jsxs("div",{role:"status",className:"af-pmp__hint","data-discovery":"unavailable",children:[e.enableSpeculation?Y$:X$,s.jsxs("details",{className:"af-pmp__details",children:[s.jsx("summary",{children:"Technical details"}),s.jsx("span",{children:R.error})]})]}):null]})}function Nx(...e){return e.filter(Boolean).join(" ")}function Z$({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:i="neutral",showGatewayUrl:a=!1,gatewayUrl:u="",gatewayUrlPlaceholder:c="http://127.0.0.1:8080",onGatewayUrlChange:d,userId:m,userPlaceholder:h="admin",onUserIdChange:p,token:y,tokenPlaceholder:w="Paste Gateway user token",showToken:x=!1,onTokenChange:k,onShowTokenChange:b,remember:S=!1,rememberLabel:$="Remember this browser",onRememberChange:A,loading:E=!1,submitting:z=!1,submitDisabled:F=!1,submitLabel:M="Sign in",submittingLabel:D="Signing in...",closeLabel:H="Close",signOutLabel:q="Sign out",showClose:I=!1,showSignOut:Z=!1,error:R,message:T,className:P,onSubmit:L,onClose:te,onSignOut:X}){const V=E||z,ne=V||F||!String(m||"").trim()||!String(y||"").trim(),W=Y=>{Y.preventDefault(),!ne&&L()};return s.jsxs("form",{className:Nx("af-gateway-signin",P),onSubmit:W,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:Nx("af-gateway-signin__status",`af-gateway-signin__status--${i}`),children:r})}),s.jsxs("div",{className:"af-gateway-signin__form",children:[a?s.jsxs(s.Fragment,{children:[s.jsx("label",{className:"af-gateway-signin__label",htmlFor:"gateway-session-url",children:"Gateway URL"}),s.jsx("input",{id:"gateway-session-url",value:u,onChange:Y=>d==null?void 0:d(Y.target.value),placeholder:c,autoComplete:"url",disabled:V})]}):null,s.jsx("label",{className:"af-gateway-signin__label",htmlFor:"gateway-session-user",children:"Gateway user"}),s.jsx("input",{id:"gateway-session-user",value:m,onChange:Y=>p(Y.target.value),placeholder:h,autoComplete:"username",disabled:V}),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:x?"text":"password",value:y,onChange:Y=>k(Y.target.value),placeholder:w,autoComplete:"off","data-1p-ignore":"","data-lpignore":"true","data-bwignore":"",spellCheck:!1,disabled:V}),s.jsx("button",{className:"af-gateway-signin__secondary",type:"button",onClick:()=>b==null?void 0:b(!x),disabled:V,children:x?"Hide":"Show"})]}),s.jsxs("label",{className:"af-gateway-signin__checkbox",children:[s.jsx("input",{type:"checkbox",checked:!!S,onChange:Y=>A==null?void 0:A(Y.target.checked),disabled:V}),$]})]}),R?s.jsx("div",{className:"af-gateway-signin__message af-gateway-signin__message--error",children:R}):null,!R&&T?s.jsx("div",{className:"af-gateway-signin__message af-gateway-signin__message--ok",children:T}):null,s.jsxs("div",{className:"af-gateway-signin__actions",children:[I?s.jsx("button",{className:"af-gateway-signin__secondary",type:"button",onClick:te,disabled:V,children:H}):null,Z?s.jsx("button",{className:"af-gateway-signin__secondary",type:"button",onClick:()=>void(X==null?void 0:X()),disabled:V,children:q}):null,s.jsx("button",{className:"af-gateway-signin__primary",type:"submit",disabled:ne,children:z?D:M})]})]})}function Q$(e){return e==="light"?"Light":"Dark"}function e2(e){const t=e.themes&&e.themes.length?e.themes:zk,n=e.showSwatches!==!1,r=e.variant||"panel",i=_.useMemo(()=>{const u={};for(const c of t)u[c.id]=c;return u},[t]),a=_.useMemo(()=>t.map(u=>({value:u.id,label:u.label,group:Q$(u.group)})),[t]);return s.jsx(Pi,{value:e.value,options:a,placeholder:e.placeholder||"Select theme…",disabled:e.disabled===!0,searchable:!0,allowCustom:!1,clearable:!1,variant:r,className:e.className,triggerClassName:e.triggerClassName,onChange:u=>e.onChange(String(u||"").trim()),renderValue:(u,c)=>{const d=String(c||"").trim(),m=i[d],h=(m==null?void 0:m.label)||d||e.placeholder||"Select theme…",p=(m==null?void 0:m.swatches)||null,y=!d;return s.jsxs("span",{className:"af-theme-value",children:[s.jsx("span",{className:`af-theme-label ${y?"af-theme-label--placeholder":""}`.trim(),children:h}),n&&p?s.jsx("span",{className:"af-theme-swatches","aria-hidden":"true",children:p.map((w,x)=>s.jsx("span",{className:"af-theme-swatch",style:{background:w}},`${d}:${x}`))}):null]})},renderOption:(u,c)=>{const d=String(u.value||"").trim(),m=i[d],h=(m==null?void 0:m.swatches)||null;return s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"af-theme-option-label",children:u.label}),s.jsxs("span",{className:"af-theme-option-right",children:[n&&h?s.jsx("span",{className:"af-theme-swatches","aria-hidden":"true",children:h.map((p,y)=>s.jsx("span",{className:"af-theme-swatch",style:{background:p}},`${d}:${y}`))}):null,c.selected?s.jsx("span",{className:"af-select-check",children:"✓"}):null]})]})}})}function t2(e){const t=e.scales&&e.scales.length?e.scales:Gy,n=e.variant||"panel",r=_.useMemo(()=>t.map(i=>({value:i.id,label:i.label})),[t]);return s.jsx(Pi,{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:i=>e.onChange(String(i||"").trim())})}function n2(e){const t=e.densities&&e.densities.length?e.densities:Ky,n=e.variant||"panel",r=_.useMemo(()=>t.map(i=>({value:i.id,label:i.label})),[t]);return s.jsx(Pi,{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:i=>e.onChange(String(i||"").trim())})}const s2=new Set(["board","inbox","server","agent","playCircle","list","gear"]);function r2(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"})]});case"image":return s.jsxs(s.Fragment,{children:[s.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),s.jsx("circle",{cx:"9",cy:"9",r:"2"}),s.jsx("path",{d:"M21 15l-3.1-3.1a2 2 0 0 0-2.8 0L6 21"})]});case"video":return s.jsxs(s.Fragment,{children:[s.jsx("rect",{x:"2",y:"6",width:"14",height:"12",rx:"2"}),s.jsx("path",{d:"M16 10.5l5.2-3.1a.5.5 0 0 1 .8.4v8.4a.5.5 0 0 1-.8.4L16 13.5"})]});case"camera":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M14.5 4h-5L7 7H4a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-3z"}),s.jsx("circle",{cx:"12",cy:"13",r:"3"})]});case"music":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M9 18V5l12-2v13"}),s.jsx("circle",{cx:"6",cy:"18",r:"3"}),s.jsx("circle",{cx:"18",cy:"16",r:"3"})]});case"database":return s.jsxs(s.Fragment,{children:[s.jsx("ellipse",{cx:"12",cy:"5",rx:"9",ry:"3"}),s.jsx("path",{d:"M3 5v14a9 3 0 0 0 18 0V5"}),s.jsx("path",{d:"M3 12a9 3 0 0 0 18 0"})]});case"branch":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M6 3v12"}),s.jsx("circle",{cx:"18",cy:"6",r:"3"}),s.jsx("circle",{cx:"6",cy:"18",r:"3"}),s.jsx("path",{d:"M18 9a9 9 0 0 1-9 9"})]});case"loop":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M17 2l4 4-4 4"}),s.jsx("path",{d:"M3 11v-1a4 4 0 0 1 4-4h14"}),s.jsx("path",{d:"M7 22l-4-4 4-4"}),s.jsx("path",{d:"M21 13v1a4 4 0 0 1-4 4H3"})]});case"variable":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M8 21s-4-3-4-9 4-9 4-9"}),s.jsx("path",{d:"M16 3s4 3 4 9-4 9-4 9"}),s.jsx("path",{d:"M15 9l-6 6"}),s.jsx("path",{d:"M9 9l6 6"})]});case"minus":return s.jsx("path",{d:"M5 12h14"});case"divide":return s.jsxs(s.Fragment,{children:[s.jsx("circle",{cx:"12",cy:"6",r:"1.25",fill:"currentColor",stroke:"none"}),s.jsx("path",{d:"M5 12h14"}),s.jsx("circle",{cx:"12",cy:"18",r:"1.25",fill:"currentColor",stroke:"none"})]});case"function":return s.jsxs(s.Fragment,{children:[s.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),s.jsx("path",{d:"M9 17c2 0 2.8-1 2.8-2.8V10c0-2 1-3.3 3.2-3"}),s.jsx("path",{d:"M9 11.2h5.7"})]});case"zoomIn":return s.jsxs(s.Fragment,{children:[s.jsx("circle",{cx:"11",cy:"11",r:"8"}),s.jsx("path",{d:"M21 21l-4.35-4.35"}),s.jsx("path",{d:"M11 8v6"}),s.jsx("path",{d:"M8 11h6"})]});case"zoomOut":return s.jsxs(s.Fragment,{children:[s.jsx("circle",{cx:"11",cy:"11",r:"8"}),s.jsx("path",{d:"M21 21l-4.35-4.35"}),s.jsx("path",{d:"M8 11h6"})]});case"fitView":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M8 3H5a2 2 0 0 0-2 2v3"}),s.jsx("path",{d:"M21 8V5a2 2 0 0 0-2-2h-3"}),s.jsx("path",{d:"M3 16v3a2 2 0 0 0 2 2h3"}),s.jsx("path",{d:"M16 21h3a2 2 0 0 0 2-2v-3"})]});case"lock":return s.jsxs(s.Fragment,{children:[s.jsx("rect",{x:"4",y:"11",width:"16",height:"10",rx:"2"}),s.jsx("path",{d:"M8 11V7a4 4 0 0 1 8 0v4"})]});default:return null}}function Xe({name:e,size:t=16,className:n,title:r,...i}){const a=r?void 0:!0,u=s2.has(e);return s.jsxs("svg",{width:t,height:t,viewBox:u?"0 0 16 16":"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:u?1.4:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,"aria-hidden":a,role:r?"img":"presentation",...i,children:[r?s.jsx("title",{children:r}):null,r2(e)]})}const Pm="api/gateway",ih="api/connection/gateway";function yt(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?`${Pm}/${t}`:Pm}function ov(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 i2(e){const t=String(e||""),n=`/${Pm}/`;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 i of r.split("/")){const a=i.replace(/%2e/gi,".");if(a==="."||a==="..")throw new Error(`Not a gateway API path: ${JSON.stringify(t)} (a "." or ".." segment).`)}return t.slice(1)}function o2(e){return!String(e.unavailableReason||"").trim()&&!e.busy}function a2(e){return o2(e)?!e.checked:null}let l2=0;function _o(e){const{label:t,checked:n,onChange:r,description:i,reasonVisible:a=!0,describedBy:u,hint:c,busy:d=!1,variant:m="inline",ariaLabel:h,className:p,id:y,action:w}=e,x=String(e.unavailableReason||"").trim(),k=!!x,b=u||(y?`${y}-reason`:k?`af-switch-reason-${++l2}`:void 0),S=["af-switch",m==="row"?"af-switch--row":m==="sm"?"af-switch--sm":"",k?"af-switch--unavailable":"",p||""].filter(Boolean).join(" "),$=E=>{const z=a2({checked:n,unavailableReason:x,busy:d});if(z===null){E.preventDefault();return}r==null||r(z)},A=s.jsxs("button",{type:"button",role:"switch",id:y,className:S,"data-action":w,"aria-checked":n?"true":"false","aria-disabled":k?"true":void 0,"aria-describedby":k?b:void 0,"aria-busy":d?"true":void 0,"aria-label":h,"aria-description":i?void 0:c,title:k?c?`${x}
|
|
41
|
+
${c}`:x:c,onClick:$,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}),i?s.jsx("span",{className:"af-switch__desc",children:i}):null]})]});return!k||u?A:s.jsxs("span",{className:m==="row"?"af-switch-wrap af-switch-wrap--row":"af-switch-wrap",children:[A,s.jsx("span",{id:b,className:a?"af-switch__reason":"af-switch__reason af-switch__reason--hidden",children:x})]})}function c2(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,i=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:a=>{var u;return(u=e.onChange)==null?void 0:u.call(e,a.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:[i,s.jsx("span",{id:r,className:"af-switch__reason",children:t})]}):i}const u2=150,av="data-af-tip";function d2(e,t,n,r=6,i=8){let a="top",u=e.top-r-t.height;if(u<i){const m=e.bottom+r;(m+t.height<=n.height-i||n.height-e.bottom>e.top)&&(u=m,a="bottom")}let d=(e.left+e.right)/2-t.width/2;return d=Math.max(i,Math.min(d,n.width-i-t.width)),u=Math.max(i,Math.min(u,n.height-i-t.height)),{top:Math.round(u),left:Math.round(d),side:a}}let $x=0;function Wk(e){return e?String(e.getAttribute(av)||"").trim():""}function Bg(e,t){const n=e;if(!n||typeof n.closest!="function")return null;const r=n.closest(`[${av}]`);return!r||!t.contains(r)||!Wk(r)?null:r}function f2(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,i=typeof t.delayMs=="number"&&t.delayMs>=0?t.delayMs:u2;$x+=1;const a=n.createElement("div");a.className="af-tooltip",a.setAttribute("role","tooltip");const u=`af-tooltip-${$x}`;a.setAttribute("id",u),a.hidden=!0,(n.body||n.documentElement).appendChild(a);let c=null,d=null,m=null,h=null,p=!1,y=null;const w=()=>{m&&clearTimeout(m),m=null,d=null},x=()=>{h&&clearTimeout(h),h=null},k=()=>{if(!c)return;const P=c.getBoundingClientRect(),L=a.getBoundingClientRect(),te=d2(P,{width:L.width,height:L.height},{width:r.innerWidth,height:r.innerHeight});a.style.top=`${te.top}px`,a.style.left=`${te.left}px`,a.setAttribute("data-side",te.side)},b=()=>{if(w(),x(),!c)return;String(c.getAttribute("aria-describedby")||"").split(/\s+/).includes(u)&&(y?c.setAttribute("aria-describedby",y):c.removeAttribute("aria-describedby")),y=null,c=null,a.hidden=!0,a.textContent=""},S=P=>{w(),x(),c&&c!==P&&b();const L=Wk(P);if(!L||P.isConnected===!1)return;if(c=P,a.textContent=L,a.hidden=!1,String(P.getAttribute("aria-label")||"").trim()!==L){const X=P.getAttribute("aria-describedby");y=X&&X!==u?X:null,P.setAttribute("aria-describedby",y?`${y} ${u}`:u)}k()},$=P=>{x(),c!==P&&d!==P&&(w(),d=P,m=setTimeout(()=>{const L=d;m=null,d=null,L&&S(L)},i))},A=()=>{w(),c&&(x(),h=setTimeout(b,100))},E=P=>{try{if(typeof P.matches=="function")return P.matches(":focus-visible")}catch{}return p},z=P=>{if(P.pointerType==="touch")return;if(a.contains(P.target)){x();return}const te=Bg(P.target,e);te&&$(te)},F=P=>{const te=P.relatedTarget||null;if(!(te&&(a.contains(te)||c&&c.contains(te)||d&&d.contains(te)))){if(d&&!c){w();return}c&&A()}},M=P=>{const L=P.relatedTarget||null;L&&(a.contains(L)||c&&c.contains(L))||A()},D=P=>{const L=Bg(P.target,e);L&&E(L)&&$(L)},H=P=>{const L=Bg(P.target,e);L&&(L===c||L===d)&&b()},q=()=>{p=!1,b()},I=P=>{if(P.key==="Escape"||P.key==="Esc"){c?(P.preventDefault(),b()):w();return}!P.metaKey&&!P.ctrlKey&&!P.altKey&&(p=!0)},Z=()=>b(),R=e;R.addEventListener("pointerover",z),R.addEventListener("pointerout",F),R.addEventListener("focusin",D),R.addEventListener("focusout",H),a.addEventListener("pointerover",z),a.addEventListener("pointerout",M),n.addEventListener("pointerdown",q,!0),r.addEventListener("keydown",I,!0),r.addEventListener("scroll",Z,!0),r.addEventListener("resize",Z);let T=!1;return()=>{T||(T=!0,b(),R.removeEventListener("pointerover",z),R.removeEventListener("pointerout",F),R.removeEventListener("focusin",D),R.removeEventListener("focusout",H),a.removeEventListener("pointerover",z),a.removeEventListener("pointerout",M),n.removeEventListener("pointerdown",q,!0),r.removeEventListener("keydown",I,!0),r.removeEventListener("scroll",Z,!0),r.removeEventListener("resize",Z),a.parentNode&&a.parentNode.removeChild(a))}}const C_=new WeakMap;function m2(e){let t=C_.get(e);t||(t={count:0,release:f2(e)},C_.set(e,t)),t.count+=1;let n=!1;return()=>{if(n)return;n=!0;const r=C_.get(e);r&&(r.count-=1,r.count<=0&&(r.release(),C_.delete(e)))}}function Yd(){_.useEffect(()=>{if(!(typeof document>"u"))return m2(document)},[])}function Cx(e){Yd();const t=Ne.Children.only(e.children),n=String(e.content||"").trim();return n?Ne.cloneElement(t,{[av]:n}):t}async function Jy(e=ih){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 h2(e,t=ih){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 i=r&&typeof r=="object"&&r.detail?String(r.detail):`HTTP ${n.status}`;throw new Error(i)}return r}async function qk(e=ih){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 Ug(e){let t=String(e||"").trim();for(let n=0;n<2&&t;n+=1){try{const a=JSON.parse(t);if(typeof a=="string"&&a!==t){t=a.trim();continue}}catch{}const r=t[0],i=t[t.length-1];if(r==='"'&&i==='"'||r==="'"&&i==="'"){t=t.slice(1,-1).trim();continue}break}return t.replace(/\/+$/,"")}function Hk(e){var a,u;if(!e)return{label:"Signed out",tone:"warn"};if(!e.has_session)return{label:"Signed out",tone:"warn"};const t=e.gateway||{},n=(a=t.principal)==null?void 0:a.user_id,r=(u=t.principal)==null?void 0:u.runtime_id;if(t.ok&&n)return{label:`Signed in as ${n}${r?` · runtime ${r}`:""}`,tone:"ok"};if(t.ok)return{label:"Signed in",tone:"ok"};const i=t.error||t.detail;return typeof i=="string"&&i.trim()?{label:"Session rejected — sign in again",tone:"err"}:{label:"Sign in required",tone:"err"}}function _2(e){const t=e.connectionPath||ih,[n,r]=_.useState(!1),[i,a]=_.useState(!1),[u,c]=_.useState(null),[d,m]=_.useState(!1);_.useEffect(()=>{e.isOpen||m(!1)},[e.isOpen]);const[h,p]=_.useState(e.defaultGatewayUrl||"http://127.0.0.1:8080"),[y,w]=_.useState("admin"),[x,k]=_.useState(""),[b,S]=_.useState(!1),[$,A]=_.useState(!0),[E,z]=_.useState(""),[F,M]=_.useState(""),D=_.useMemo(()=>Hk(u),[u]),H=R=>{var T;c(R),(T=e.onStatusChange)==null||T.call(e,R)},q=_.useRef(!1);if(_.useEffect(()=>{var T;if(!e.isOpen)return;const R=!q.current;if(q.current=!0,R&&e.initialStatus!==void 0&&e.initialStatus!==null){const P=e.initialStatus;H(P),typeof P.gateway_url=="string"&&P.gateway_url.trim()&&p(Ug(P.gateway_url));const L=(T=P.gateway)==null?void 0:T.principal;L!=null&&L.user_id&&w(L.user_id);return}r(!0),z(""),Jy(t).then(P=>{var te;H(P),typeof P.gateway_url=="string"&&P.gateway_url.trim()&&p(Ug(P.gateway_url));const L=(te=P.gateway)==null?void 0:te.principal;L!=null&&L.user_id&&w(L.user_id)}).catch(P=>z(`Failed to load connection status: ${String((P==null?void 0:P.message)||P)}`)).finally(()=>r(!1))},[e.isOpen]),_.useEffect(()=>{if(!e.isOpen)return;const R=T=>{T.key==="Escape"&&!T.defaultPrevented&&!e.blocking&&(T.preventDefault(),e.onClose())};return window.addEventListener("keydown",R),()=>window.removeEventListener("keydown",R)},[e.isOpen,e.blocking,e.onClose]),!e.isOpen||d)return null;const I=async()=>{a(!0),z(""),M("");try{const R=Ug(h);p(R);const T=await h2({gateway_url:R,gateway_user_id:y,gateway_token:x,persist:$},t);H(T),k(""),m(!0),e.onClose()}catch(R){z(String((R==null?void 0:R.message)||R))}finally{a(!1)}},Z=async()=>{a(!0),z(""),M("");try{await qk(t),k("");const R=await Jy(t).catch(()=>null);H(R),M("Signed out. This browser no longer holds a gateway session.")}catch(R){z(String((R==null?void 0:R.message)||R))}finally{a(!1)}};return s.jsx("div",{className:"af-connect-overlay",role:"presentation",onMouseDown:R=>{!e.blocking&&R.target===R.currentTarget&&e.onClose()},children:s.jsx("div",{className:"af-connect-modal",role:"dialog","aria-modal":"true","aria-label":"Gateway connection",children:s.jsx(Z$,{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:D.label,statusTone:D.tone,showGatewayUrl:!0,gatewayUrl:h,onGatewayUrlChange:R=>p(R),userId:y,onUserIdChange:w,token:x,tokenPlaceholder:u!=null&&u.has_session?"(browser session already signed in)":"Paste Gateway user token",showToken:b,onTokenChange:k,onShowTokenChange:S,remember:$,rememberLabel:"Keep this browser signed in",onRememberChange:A,loading:n,submitting:i,submittingLabel:"Signing in...",showClose:!e.blocking,onClose:e.onClose,showSignOut:!e.blocking&&!!(u!=null&&u.has_session),onSignOut:Z,error:E,message:F,onSubmit:I})})})}function p2(e){return!!(e&&e.ok===!0&&e.has_session===!0)}function g2(e){const t=e||{},n=t.connectionPath||ih,r=t.variant||"dismissable",i=_.useRef(t.onStatusChange);i.current=t.onStatusChange;const a=_.useRef(r);a.current=r;const u=_.useRef(!!t.autoOpenMidSession);u.current=!!t.autoOpenMidSession;const[c,d]=_.useState(null),[m,h]=_.useState("loading"),[p,y]=_.useState(!1),w=_.useRef(!1),x=_.useRef(!1),k=_.useRef("loading"),b=_.useRef("none"),S=_.useRef(!1),$=_.useRef(0),A=_.useCallback(T=>{var L;$.current+=1,d(T),(L=i.current)==null||L.call(i,T);const P=p2(T);if(P)h("connected"),k.current="connected",w.current=!1,b.current="none",x.current||y(!1);else if(T!==null){const te=k.current;h("disconnected"),k.current="disconnected",te!=="disconnected"&&(b.current=S.current?"signout":te==="connected"?"mid":"boot");const X=a.current==="blocking"||b.current!=="mid"||u.current;!w.current&&X&&y(!0)}T!==null&&(x.current=P)},[]),E=_.useCallback(async()=>{const T=$.current;try{const P=await Jy(n);if($.current!==T)return;A(P)}catch{if($.current!==T)return;A(null)}},[n,A]),[z,F]=_.useState(!1),[M,D]=_.useState(null),H=_.useCallback(async()=>{F(!0),D(null),$.current+=1;let T=null;try{await qk(n)}catch(P){T=String((P==null?void 0:P.message)||P||"Sign-out request failed")}S.current=!0;try{await E()}finally{S.current=!1}D(T),F(!1)},[n,E]),q=_.useRef(!1);_.useEffect(()=>{q.current||(q.current=!0,E())},[E]);const I=_.useCallback(()=>{y(!0)},[]),Z=_.useCallback(()=>{const T=k.current;r==="blocking"&&T==="disconnected"||(T==="disconnected"&&(w.current=!0),y(!1))},[r]),R=_.useMemo(()=>({isOpen:p,onClose:Z,blocking:r==="blocking"&&m!=="connected",appName:t.appName,connectionPath:n,defaultGatewayUrl:t.defaultGatewayUrl,initialStatus:c,onStatusChange:A}),[p,Z,r,m,t.appName,n,t.defaultGatewayUrl,c,A]);return{status:c,phase:m,connected:m==="connected",modalOpen:p,signingOut:z,signOutError:M,openModal:I,refresh:E,signOut:H,modalProps:R}}function y2(){return globalThis.crypto}function w2(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 Ga(){const e=y2();if(e&&typeof e.randomUUID=="function")try{return e.randomUUID()}catch{}if(e&&typeof e.getRandomValues=="function")return w2(e.getRandomValues(new Uint8Array(16)));throw new Error("randomId: Web Crypto (crypto.getRandomValues) is unavailable")}function Zp(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 v2(){return Ga()}function x2(){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 i=t.slice(n+1).trim();let a=i;try{a=decodeURIComponent(i)}catch{}a&&!e.includes(a)&&e.push(a)}}catch{}return e}async function b2(e){const t=e.commandsPath||yt("commands"),n=v2(),r=JSON.stringify({command_id:n,run_id:e.runId,type:"inject_guidance",payload:{guidance:e.guidance}}),i=e.csrfToken!==void 0?[e.csrfToken]:x2();i.length===0&&i.push("");let a=null;for(const u of i){const c=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json",...u?{"x-abstract-csrf":u}:{}},body:r}),d=await c.json().catch(()=>null);if(!c.ok){const m=d&&typeof d=="object"&&d.detail?String(d.detail):`HTTP ${c.status}`;if(a=new Error(m),c.status===403&&d&&typeof d=="object"&&d.reason_code==="csrf_required")continue;throw a}return{accepted:!!(d!=null&&d.accepted),duplicate:!!(d!=null&&d.duplicate),seq:Number((d==null?void 0:d.seq)??0)}}throw a||new Error("Steer submit failed")}function k2(e){const[t,n]=_.useState(""),[r,i]=_.useState({kind:"idle"}),a=_.useRef(!1),u=_.useRef(0);_.useEffect(()=>{u.current+=1,i({kind:"idle"})},[e.runId]);const c=!e.disabled&&t.trim().length>0&&r.kind!=="sending",d=_.useMemo(()=>e.parked?"Run is waiting — your guidance delivers at its next wake (steers do not wake runs).":"Delivers at the run's next loop boundary.",[e.parked]),m=async()=>{var w;const p=t.trim();if(!p||a.current||e.disabled)return;a.current=!0;const y=u.current;i({kind:"sending"});try{const x=e.submit?await e.submit(e.runId,p):await b2({runId:e.runId,guidance:p,commandsPath:e.commandsPath});if(u.current!==y)return;if(!x.accepted&&!x.duplicate){i({kind:"error",detail:"The gateway did not accept this steer (accepted=false)."});return}i({kind:"queued",seq:x.seq,duplicate:x.duplicate}),n(""),(w=e.onSent)==null||w.call(e,{...x,guidance:p})}catch(x){u.current===y&&i({kind:"error",detail:String((x==null?void 0:x.message)||x)})}finally{a.current=!1}},h=p=>{p.key==="Enter"&&(p.metaKey||p.ctrlKey)&&(p.preventDefault(),m())};return s.jsxs("div",{className:`af-steer${e.className?` ${e.className}`:""}`,children:[s.jsxs("div",{className:"af-steer__row",children:[s.jsx("textarea",{className:"af-steer__input",value:t,rows:2,placeholder:e.placeholder||"Steer this run…","aria-label":e.ariaLabel||"Steer message",disabled:e.disabled||r.kind==="sending",onChange:p=>{n(p.target.value),(r.kind==="error"||r.kind==="queued")&&i({kind:"idle"})},onKeyDown:h}),s.jsx("button",{type:"button",className:"af-steer__send",disabled:!c,onClick:()=>void m(),title:"Send guidance (Cmd/Ctrl+Enter)",children:r.kind==="sending"?"Sending…":"Steer"})]}),s.jsx("div",{className:"af-steer__status",role:"status","aria-live":"polite",children:r.kind==="queued"?s.jsxs("span",{className:"af-steer__ok",children:[r.duplicate?`Already queued (seq ${r.seq}).`:`Queued (seq ${r.seq}).`," ",d," ","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:d})})]})}const Wg={neutral:"var(--text-secondary)",muted:"var(--text-muted)",accent:"var(--accent)",info:"var(--info)",success:"var(--success)",warning:"var(--warning)",error:"var(--error)"},j2=/^var\(--[a-z0-9-]+\)$/i;function S2(e,t){const n=e||"neutral";if(n==="custom"){const r=String(t||"").trim();return j2.test(r)?r:Wg.neutral}return Wg[n]||Wg.neutral}function Vk(e,t,n){return[e,`${e}--${t.tone||"neutral"}`,t.size==="sm"?`${e}--sm`:"",n||"",t.className||""].filter(Boolean).join(" ")}function Gk(e){return{"--af-chip-hue":S2(e.tone,e.hue)}}function Ex(e){return s.jsxs("span",{className:Vk("af-chip",e,e.onRemove?"af-chip--removable":""),style:Gk(e),title:e.title,children:[s.jsx("span",{className:"af-chip__label",children:e.children}),e.onRemove?s.jsx("button",{type:"button",className:"af-chip__remove","aria-label":e.removeLabel||"Remove",onClick:t=>{var n;t.stopPropagation(),(n=e.onRemove)==null||n.call(e)},children:s.jsxs("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.6",strokeLinecap:"round",children:[s.jsx("path",{d:"M18 6L6 18"}),s.jsx("path",{d:"M6 6l12 12"})]})}):null]})}function N2(e){return s.jsx("button",{type:"button",className:Vk("af-chip",e,"af-chip--button"),style:Gk(e),title:e.title,onClick:e.onClick,"aria-pressed":typeof e.pressed=="boolean"?e.pressed:void 0,"aria-expanded":typeof e.expanded=="boolean"?e.expanded:void 0,"aria-label":e.ariaLabel,disabled:e.disabled,tabIndex:e.tabIndex,children:s.jsx("span",{className:"af-chip__label",children:e.children})})}function $2(e){const t=e.closeOnEscape!==!1,n=_.useRef(null);return _.useEffect(()=>{if(!e.open||!t)return;const r=i=>{i.key!=="Escape"||i.defaultPrevented||(i.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 C2={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"},E2={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"}},A2={framework:C2,apps:E2},bp=A2;function Kk(){return{...bp.framework}}function T2(){return Object.keys(bp.apps).sort()}function M2(e,t){const n=Object.prototype.hasOwnProperty.call(bp.apps,e)?bp.apps[e]:void 0;if(!n)throw new Error(`appIdentity: unknown application id "${e}" (known: ${T2().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 $d(e){return typeof e=="string"?e.trim():""}function Ax(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=$d(n.abstractgateway),i=$d(n.abstractframework);return{framework:i||null,gateway:r||null,...r&&!i?{frameworkNote:"not installed on the gateway host"}:{},...r?{}:{gatewayNote:"unavailable (the gateway did not report its version)"}}}function R2(e){const t=Kk();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 L2(e){const t=e||{},n=$d(t.framework),r=$d(t.gateway);return[["AbstractFramework",n||$d(t.frameworkNote)||"not reported"],["AbstractGateway",r||$d(t.gatewayNote)||"not connected"]]}const I2='a[href], button:not(:disabled), input:not(:disabled), select:not(:disabled), textarea:not(:disabled), [tabindex]:not([tabindex="-1"])';function O2(e,t,n){if(e.key!=="Tab"||!t)return;const r=Array.from(t.querySelectorAll(I2));if(r.length===0){e.preventDefault();return}const i=r[0],a=r[r.length-1],u=!!n&&t.contains(n);e.shiftKey?(n===i||!u)&&(e.preventDefault(),a.focus()):(n===a||!u)&&(e.preventDefault(),i.focus())}function P2(e){const t=Kk();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:L2(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:R2(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 D2(e){Yd();const t=_.useRef(null),n=_.useRef(null),r=_.useId(),i=_.useRef(e.onClose);return i.current=e.onClose,_.useEffect(()=>{var c;if(!e.open)return;const a=document.activeElement;(c=t.current)==null||c.focus();const u=d=>{if(!d.defaultPrevented){if(d.key==="Escape"){d.preventDefault(),i.current();return}O2(d,n.current,document.activeElement)}};return window.addEventListener("keydown",u),()=>{window.removeEventListener("keydown",u),a&&typeof a.focus=="function"&&a.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:a=>a.stopPropagation(),children:s.jsx(P2,{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(Xe,{name:"x",size:16})})})})}):null}function F2(e){const{connection:t}=e,n=t.phase,r=t.signingOut===!0,[i,a]=_.useState(!1);Yd();const u=e.about,c=r?"Signing out…":n==="connected"?"Disconnect":n==="loading"?"Connecting…":"Connect",d=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(Xe,{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(Xe,{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(Xe,{name:"contrast",size:16})}):null,u?s.jsx("button",{type:"button",className:"af-topbar__btn af-topbar__btn--about","aria-label":u.label||`About ${u.identity.name}`,"data-af-tip":u.label||`About ${u.identity.name}`,"aria-haspopup":"dialog",onClick:()=>{var m;a(!0),(m=u.onOpen)==null||m.call(u)},children:s.jsx(Xe,{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:d,"aria-label":d,children:[s.jsx("span",{className:`af-topbar__dot af-topbar__dot--${n}`,"aria-hidden":"true"}),s.jsx("span",{className:"af-topbar__pill-label",children:c})]}),u?s.jsx(D2,{open:i,onClose:()=>a(!1),identity:u.identity,versions:u.versions}):null]})}const lp={theme:"dark",font_scale:"md",header_density:"standard"};function z2(e){const t=e&&typeof e=="object"?e:{};return{theme:typeof t.theme=="string"&&t.theme?t.theme:lp.theme,font_scale:typeof t.font_scale=="string"&&t.font_scale?t.font_scale:lp.font_scale,header_density:typeof t.header_density=="string"&&t.header_density?t.header_density:lp.header_density}}function B2(e){return`af_appearance_${e}_v1`}function U2(e,t){const n=B2(e),r=_.useMemo(()=>({...lp,...(t==null?void 0:t.defaults)||{}}),[JSON.stringify((t==null?void 0:t.defaults)||{})]),[i,a]=_.useState(()=>{let u=r;try{const c=localStorage.getItem(n)??(t!=null&&t.legacyKey?localStorage.getItem(t.legacyKey):null);c&&(u=z2({...r,...JSON.parse(c)}))}catch{}try{bx(u.theme),kx({font_scale:u.font_scale,header_density:u.header_density})}catch{}return u});return _.useEffect(()=>{bx(i.theme),kx({font_scale:i.font_scale,header_density:i.header_density});try{localStorage.setItem(n,JSON.stringify(i))}catch{}},[n,i]),[i,a]}function W2(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(e2,{value:e.value.theme,onChange:t=>e.onChange({...e.value,theme:t})}),s.jsx("label",{className:"af-appearance__label",children:"Font size"}),s.jsx(t2,{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(n2,{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 Yy(e){return e?[e.provider,e.model].map(t=>String(t||"").trim()).filter(Boolean).join(" / "):""}function Tx(e,t,n=!1){if(n)return"unknown";if(!e)return"";const r=e[t];return!r||!r.configured?"not set":Yy(r)||"not set"}function q2(e,t){var n;return e.stt_provider?Yy({provider:e.stt_provider,model:e.stt_model}):(n=t==null?void 0:t.stt)!=null&&n.configured?Yy(t.stt):""}function Jk(e,t){return`${Math.max(0,Math.floor((t-e)/1e3))} s`}function H2(e,t,n){return`Transcribing… ${Jk(e,t)}${n?` · ${n}`:""}`}const Qp=()=>{var e;return(e=globalThis.navigator)==null?void 0:e.mediaDevices};function Xy(e){var i;const t=Zp("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(!((i=Qp())!=null&&i.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 V2(e){const t=Qp();if(!t||typeof t.enumerateDevices!="function")return{devices:[],labelled:!1};const r=(await t.enumerateDevices()).filter(u=>u.kind===e),i=r.some(u=>!!u.label);return{devices:r.filter(u=>u.deviceId&&u.deviceId!=="default"&&u.deviceId!=="communications").map((u,c)=>({id:String(u.deviceId),label:String(u.label||`${e==="audioinput"?"Microphone":"Speaker"} ${c+1}`)})),labelled:i}}async function G2(){const e=Qp();if(!(e!=null&&e.getUserMedia))throw new Error(Zp("the microphone")||"This browser cannot record audio.");(await e.getUserMedia({audio:!0})).getTracks().forEach(n=>n.stop())}async function Yk(e){const t=Qp();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 eg(){const e=globalThis;return e.AudioContext||e.webkitAudioContext||null}function Xk(){const e=eg();return!!(e&&e.prototype&&typeof e.prototype.createMediaStreamDestination=="function")}function K2(e,t,n=1){const r=eg();if(!r)return()=>{};const i=new r,a=i.createMediaStreamSource(e),u=i.createAnalyser();u.fftSize=1024,a.connect(u);const c=new Float32Array(u.fftSize);let d=!0;const h=setInterval(()=>{if(!d)return;u.getFloatTimeDomainData(c);let p=0;for(let y=0;y<c.length;y+=1)p+=c[y]*c[y];t(Math.min(1,Math.sqrt(p/c.length)*4*n))},50);return()=>{var p;d=!1,clearInterval(h);try{a.disconnect()}catch{}(p=i.close)==null||p.call(i)}}const J2=.02;async function Y2(e){var a;const t=globalThis.MediaRecorder;if(typeof t!="function")throw Object.assign(new Error("This browser cannot record audio."),{name:"NotSupportedError"});const n=await Yk(e.deviceId);let r=0;const i=K2(n,u=>{var c;r=Math.max(r,u),(c=e.onLevel)==null||c.call(e,u)},e.gain??1);try{const u=new t(n),c=[],d=new Promise((h,p)=>{u.ondataavailable=y=>(y==null?void 0:y.data)&&c.push(y.data),u.onstop=()=>h(),u.onerror=y=>p((y==null?void 0:y.error)||new Error("Recording failed."))});u.start(),await new Promise(h=>{var y;const p=setTimeout(h,e.ms??3e3);(y=e.signal)==null||y.addEventListener("abort",()=>{clearTimeout(p),h()},{once:!0})}),u.stop(),await d;const m=String(u.mimeType||"audio/webm");return{blob:new Blob(c,{type:m}),peak:r,mime:m}}finally{i(),n.getTracks().forEach(u=>u.stop()),(a=e.onLevel)==null||a.call(e,0)}}async function X2(e,t={}){var i;const n=eg();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 a=e instanceof Blob?await e.arrayBuffer():e,u=await r.decodeAudioData(a.slice(0)),c=r.createGain();c.gain.value=lv(t.volume),c.connect(r.destination);const d=r.createBufferSource();d.buffer=u,d.connect(c),await new Promise(m=>{d.onended=()=>m(),d.start()})}finally{(i=r.close)==null||i.call(r)}}async function Z2(e={}){var r,i;const t=eg();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 a=n.createGain();a.connect(n.destination);const u=.3*lv(e.volume),c=n.currentTime+.02;[660,880].forEach((d,m)=>{const h=n.createOscillator(),p=n.createGain();h.frequency.value=d,h.connect(p),p.connect(a);const y=c+m*.22;p.gain.setValueAtTime(0,y),p.gain.linearRampToValueAtTime(u,y+.02),p.gain.exponentialRampToValueAtTime(1e-4,y+.2),h.start(y),h.stop(y+.21)}),await new Promise(d=>setTimeout(d,520))}finally{(i=n.close)==null||i.call(n)}}function lv(e){const t=Number(e);return e==null||e===""||!Number.isFinite(t)?1:Math.min(1,Math.max(0,t))}async function*Q2(e){var r,i,a;const t=new AbortController,n=()=>t.abort();(r=e.signal)!=null&&r.aborted?n():(i=e.signal)==null||i.addEventListener("abort",n,{once:!0});try{const u=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(!u.ok){const h=await u.json().catch(()=>null),p=h&&typeof h=="object"&&h.detail?String(h.detail):`HTTP ${u.status}`;throw new Error(p)}if(!u.body)throw new Error("TTS stream has no body");const c=u.body.getReader(),d=new TextDecoder;let m="";for(;;){const{done:h,value:p}=await c.read();m+=h?d.decode():d.decode(p,{stream:!0}),h&&m.trim()&&(m+=`
|
|
42
|
+
`);let y;for(;(y=m.indexOf(`
|
|
43
|
+
`))>=0;){const w=m.slice(0,y).trim();if(m=m.slice(y+1),!w)continue;let x=null;try{x=JSON.parse(w)}catch{throw new Error("TTS stream returned invalid JSON.")}if(x&&x.type==="error")throw new Error(String(x.error||"TTS stream error"));const k=x&&typeof x.audio_b64=="string"?x.audio_b64:"";if(k){const b=atob(k),S=new Uint8Array(b.length);for(let $=0;$<b.length;$+=1)S[$]=b.charCodeAt($);yield S.buffer}if(x&&(x.type==="done"||x.type==="cancelled"))return}if(h)throw new Error("TTS stream ended before synthesis completed.")}}finally{(a=e.signal)==null||a.removeEventListener("abort",n),t.abort()}}function im(e,t){const n=String((t==null?void 0:t.message)||t||"").trim().replace(/\.$/,"");return n?`${e}: ${n}.`:`${e}.`}const eC=350;function tC(){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 nC(){if(typeof window>"u")return!1;const e=window;return!!(e!=null&&e.AudioContext||e!=null&&e.webkitAudioContext)}function sC(){const e=window.MediaRecorder,t=r=>{var i;try{return!!((i=e==null?void 0:e.isTypeSupported)!=null&&i.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 qg(e,t){var i;const n=t.slice(0),r=(i=e.decodeAudioData)==null?void 0:i.bind(e);if(typeof r!="function")throw new Error("decodeAudioData not available");try{const a=r(n);if(a&&typeof a.then=="function")return await a}catch{}return await new Promise((a,u)=>{try{r(n,a,u)}catch(c){u(c)}})}function rC(e){const t=new Uint8Array(e);if(t.length<44)return null;const n=a=>String.fromCharCode(t[a],t[a+1],t[a+2],t[a+3]);if(n(0)!=="RIFF"||n(8)!=="WAVE")return null;const r=new DataView(e);let i=12;for(;i+8<=t.length;){const a=n(i),u=r.getUint32(i+4,!0);if(a==="data")return t.slice(0,i+8);i+=8+u+u%2}return null}function iC(e,t){const n=new Uint8Array(t),r=new Uint8Array(e.length+n.length);r.set(e,0),r.set(n,e.length);const i=new DataView(r.buffer);return i.setUint32(4,r.length-8,!0),i.setUint32(e.length-4,n.length,!0),r.buffer}function oC(){const e=globalThis,t=e==null?void 0:e.AudioContext;return!!(t&&t.prototype&&typeof t.prototype.setSinkId=="function")}const E_=new WeakMap;function aC(e,t){const n=e;if(!(typeof n.setSinkId!="function"||E_.get(e)===t)){E_.set(e,t);try{Promise.resolve(n.setSinkId(t)).catch(()=>E_.delete(e))}catch{E_.delete(e)}}}function lC(e){const t=_.useRef(e);t.current=e;const n=Se=>{var me,Ve;return(Ve=(me=t.current).on_error)==null?void 0:Ve.call(me,Se)},r=_.useMemo(()=>nC()&&(typeof e.tts=="function"||typeof e.tts_stream=="function"),[e.tts,e.tts_stream]),i=_.useMemo(()=>tC()&&typeof e.transcribe=="function",[e.transcribe]),[a,u]=_.useState({key:"",status:"idle"}),c=_.useRef(a),d=_.useCallback(Se=>{c.current=Se,u(me=>me.key===Se.key&&me.status===Se.status?me:Se)},[]),m=_.useRef(""),h=_.useRef(""),p=_.useRef(null),y=_.useRef(null),w=_.useRef(null),x=_.useRef(null),k=_.useRef(0),b=_.useRef(0),S=_.useRef(0),$=_.useRef(null),A=_.useRef([]),E=_.useRef(0),z=_.useRef(!0),F=_.useRef(!1),M=()=>{try{const Se=globalThis,me=(Se==null?void 0:Se.AudioContext)||(Se==null?void 0:Se.webkitAudioContext);if(!me)return null;if(!p.current){const Ie=new me,ct=Ie.createGain();ct.gain.value=1,ct.connect(Ie.destination),p.current=Ie,y.current=ct}const Ve=p.current,ye=y.current;if(!Ve||!ye)return null;aC(Ve,t.current.output_device_id||""),ye.gain.value=lv(t.current.volume);try{Ve.state==="suspended"&&Ve.resume()}catch{}return{ctx:Ve,gain:ye}}catch{return null}},D=_.useCallback(()=>{const Se=w.current;if(w.current=null,!!Se){try{Se.onended=null}catch{}try{Se.stop()}catch{}try{Se.disconnect()}catch{}}},[]),H=_.useCallback(()=>{var Se;D(),S.current+=1,(Se=$.current)==null||Se.abort(),$.current=null,A.current=[],E.current=0,z.current=!0,F.current=!1,h.current="",m.current="",x.current=null,k.current=0,b.current=0,d({key:"",status:"idle"})},[D,d]);_.useEffect(()=>()=>{var Se,me;H();try{(Se=y.current)==null||Se.disconnect()}catch{}try{(me=p.current)==null||me.close()}catch{}p.current=null,y.current=null,x.current=null},[]);const q=async(Se,me,Ve)=>{const ye=S.current,Ie=M();if(!Ie)throw new Error("TTS playback is not supported in this browser");const{ctx:ct,gain:ie}=Ie;try{ct.state==="suspended"&&await ct.resume()}catch{}if(ye!==S.current)return;D();const Te=ct.createBufferSource();Te.buffer=me,Te.connect(ie);const et=Number.isFinite(Number(me.duration))?Number(me.duration):0,Ge=Math.max(0,Math.min(Number(Ve||0),et>0?Math.max(0,et-.01):0));b.current=ct.currentTime-Ge,k.current=Ge,w.current=Te,m.current=Se,Te.onended=()=>{w.current===Te&&(w.current=null,k.current=0,b.current=0,m.current="",d({key:"",status:"idle"}))},Te.start(0,Ge),d({key:Se,status:"playing"})},I=(Se,me)=>{if(me!==S.current)return;const Ve=M();if(!Ve)return;const ye=A.current,Ie=E.current;if(Ie>=ye.length){z.current&&(m.current="",k.current=0,b.current=0,d({key:"",status:"idle"}));return}const ct=ye[Ie],{ctx:ie,gain:Te}=Ve;D();const et=ie.createBufferSource();et.buffer=ct,et.connect(Te);const Ge=Number.isFinite(Number(ct.duration))?Number(ct.duration):0,Be=Math.max(0,Math.min(Number(k.current||0),Ge>0?Math.max(0,Ge-.01):0));b.current=ie.currentTime-Be,w.current=et,m.current=Se,et.onended=()=>{me===S.current&&w.current===et&&(w.current=null,E.current=Ie+1,k.current=0,I(Se,me))};try{ie.state==="suspended"&&ie.resume()}catch{}et.start(0,Be),d({key:Se,status:"playing"})},Z=async(Se,me,Ve)=>{var Te;const ye=M();if(!ye){n==null||n("This browser cannot play spoken replies.");return}D();const Ie=++S.current;(Te=$.current)==null||Te.abort();const ct=new AbortController;$.current=ct,A.current=[],E.current=0,z.current=!1,F.current=!1,x.current=null,k.current=0,b.current=0,m.current=Se,h.current=Se,d({key:Se,status:"loading"}),n==null||n("");let ie=null;try{for await(const et of Ve(me,ct.signal)){if(Ie!==S.current)return;let Ge;try{Ge=await qg(ye.ctx,et),ie||(ie=rC(et))}catch{if(!ie)continue;try{Ge=await qg(ye.ctx,iC(ie,et))}catch{continue}}if(Ie!==S.current)return;A.current.push(Ge),!w.current&&!F.current&&(h.current="",I(Se,Ie))}if(Ie!==S.current)return;if(z.current=!0,A.current.length===0){n==null||n("Reading aloud failed: the voice engine returned no audio."),H();return}!w.current&&!F.current&&I(Se,Ie)}catch(et){if(Ie!==S.current)return;n==null||n(im("Reading aloud failed",et)),H()}finally{$.current===ct&&($.current=null)}},R=_.useCallback(async(Se,me)=>{var Be;const Ve=String(Se||"").trim(),ye=String(me||"").trim();if(!Ve||!ye)return;const Ie=t.current.tts,ct=t.current.tts_stream;if(typeof Ie!="function"&&typeof ct!="function"){n==null||n("Reading aloud is not available on this gateway.");return}const ie=M();if(!ie){n==null||n("This browser cannot play spoken replies.");return}const Te=c.current,et=Te.key===Ve;if(et&&Te.status==="playing"){if(w.current){const Rt=Math.max(0,ie.ctx.currentTime-Number(b.current||0));k.current=Rt}else k.current=0;F.current=!0,D(),d({key:Ve,status:"paused"});return}if(et&&Te.status==="paused"){if(A.current.length>0){n==null||n(""),F.current=!1,d({key:Ve,status:"playing"}),I(Ve,S.current);return}const Rt=x.current;if(Rt){n==null||n(""),F.current=!1;try{await q(Ve,Rt,k.current)}catch(Nn){n==null||n(im("Reading aloud failed",Nn)),d({key:"",status:"idle"})}return}}if(et&&Te.status==="loading")return;if(typeof ct=="function"){await Z(Ve,ye,ct);return}D(),S.current+=1,(Be=$.current)==null||Be.abort(),$.current=null;const Ge=S.current;A.current=[],E.current=0,z.current=!0,F.current=!1,x.current=null,k.current=0,b.current=0,m.current=Ve,h.current=Ve,d({key:Ve,status:"loading"}),n==null||n("");try{const Rt=await Ie(ye);if(h.current!==Ve||S.current!==Ge)return;const Nn=await qg(ie.ctx,Rt);if(h.current!==Ve||S.current!==Ge)return;x.current=Nn,k.current=0,await q(Ve,Nn,0)}catch(Rt){if(S.current!==Ge)return;h.current===Ve&&(h.current="",m.current="",d({key:"",status:"idle"})),n==null||n(im("Reading aloud failed",Rt))}},[]),[T,P]=_.useState(!1),[L,te]=_.useState(!1),X=_.useRef(!1),V=_.useRef(i);V.current=i;const ne=_.useCallback(Se=>{X.current=Se,P(me=>me===Se?me:Se)},[]),W=_.useRef(!1),Y=_.useRef(null),K=_.useRef(null),fe=_.useRef([]),ae=_.useRef(""),ve=_.useRef(0),ge=_.useRef(!1),[pe,$e]=_.useState(0),De=_.useRef(0),ot=_.useRef(null);function bt(){var me,Ve;try{(Ve=(me=Y.current)==null?void 0:me.getTracks)==null||Ve.call(me).forEach(ye=>{try{ye.stop()}catch{}})}catch{}Y.current=null;const Se=ot.current;ot.current=null;try{Se==null||Se.close()}catch{}}const Ue=_.useCallback(()=>{ve.current+=1,ge.current=!1;const Se=K.current;if(Se){Se.onstop=null,Se.ondataavailable=null,Se.onerror=null;try{Se.stop()}catch{}}K.current=null,bt(),ne(!1),W.current=!1,te(!1),$e(0),fe.current=[]},[ne]);_.useEffect(()=>()=>Ue(),[Ue]);async function at(Se,me){var ct,ie;if(n==null||n(""),W.current)return;const Ve=De.current?Date.now()-De.current:1/0;if(!Se||!Se.size||Ve<eC){$e(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 ye=t.current.transcribe;if(typeof ye!="function"){n==null||n("Speech to text is not available on this gateway.");return}W.current=!0;const Ie=ve.current;te(!0),$e(Date.now());try{const Te=await ye(Se,me),et=typeof Te=="string"||!Te?{text:String(Te||"")}:Te,Ge=String(et.text||"").trim();if(Ie!==ve.current)return;Ge?(ie=(ct=t.current).on_transcript)==null||ie.call(ct,Ge,{...et,text:Ge}):n==null||n("Nothing was heard. Check the microphone in Settings → Voice (Test), then try again.")}catch(Te){if(Ie===ve.current){const et=String((Te==null?void 0:Te.message)||Te||"").trim().replace(/\.$/,"");n==null||n(et?`Transcription failed: ${et}.`:"Transcription failed.")}}finally{Ie===ve.current&&(W.current=!1,te(!1),$e(0))}}const Nt=_.useCallback(async()=>{if(n==null||n(""),!V.current){n==null||n(Zp("the microphone")??"Voice recording is not supported in this browser (MediaRecorder/getUserMedia unavailable).");return}if(W.current||ge.current||X.current||K.current)return;fe.current=[];const Se=ve.current;ge.current=!0;try{const me=await Yk(t.current.input_device_id||"");if(Se!==ve.current){me.getTracks().forEach(ie=>ie.stop());return}Y.current=me;const Ve=sC();ae.current=Ve;let ye=me;const Ie=Number(t.current.input_gain??1);if(Number.isFinite(Ie)&&Ie>0&&Ie!==1&&Xk()){const ie=globalThis.AudioContext||globalThis.webkitAudioContext,Te=new ie,et=Te.createGain();et.gain.value=Ie;const Ge=Te.createMediaStreamDestination();Te.createMediaStreamSource(me).connect(et),et.connect(Ge),ot.current=Te,ye=Ge.stream}const ct=Ve?new MediaRecorder(ye,{mimeType:Ve}):new MediaRecorder(ye);K.current=ct,ct.ondataavailable=ie=>{if(Se===ve.current)try{ie!=null&&ie.data&&fe.current.push(ie.data)}catch{}},ct.onerror=()=>{Se===ve.current&&(n==null||n("Recording failed. Try again, or pick another microphone in Settings → Voice."))},ct.onstop=()=>{if(Se===ve.current){ne(!1),bt(),K.current=null;try{const ie=new Blob(fe.current,{type:ae.current||""});at(ie,ae.current)}catch(ie){n==null||n(im("The recording could not be prepared",ie))}}},ct.start(),De.current=Date.now(),$e(De.current),ne(!0)}catch(me){if(Se!==ve.current)return;bt(),K.current=null,ne(!1),$e(0),n==null||n(Xy(me))}finally{Se===ve.current&&(ge.current=!1)}},[]),ut=_.useCallback(()=>{const Se=K.current;if(!(!X.current||!Se)){ne(!1);try{Se.stop()}catch(me){n==null||n(im("The recording could not stop",me))}}},[]);return _.useEffect(()=>{if(!T||t.current.stop_on_pointerup===!1)return;const Se=()=>ut();return window.addEventListener("pointerup",Se),window.addEventListener("pointercancel",Se),()=>{window.removeEventListener("pointerup",Se),window.removeEventListener("pointercancel",Se)}},[T]),{tts_supported:r,tts_playback:a,toggle_tts:R,stop_tts:H,voice_ptt_supported:i,voice_ptt_recording:T,voice_ptt_busy:L,start_voice_ptt_recording:Nt,stop_voice_ptt_recording:ut,cancel_voice_ptt_recording:Ue,voice_ptt_since:pe}}const cC={diary:"var(--accent)",question:"#e7b45a",dream:"#c084dd",interest:"#7bd88a",lesson:"#6ea8d8",world_model:"#5eead4"};function Mx(e){const t=String(e||"");return t.length>14?`${t.slice(0,10)}…${t.slice(-4)}`:t}function Hg(e){const[t,n]=_.useState(!1),[r,i]=_.useState(null),a=_.useRef(!1),u=typeof e.entryId=="string"&&e.entryId.trim()?e.entryId.trim():null,c=e.kind&&cC[e.kind]||"var(--text-muted)",d=_.useCallback(async()=>{if(!(!u||!e.onOpen||a.current)){a.current=!0,n(!0),i(null);try{await e.onOpen(u)}catch(m){i(String((m==null?void 0:m.message)||m||"could not open"))}finally{a.current=!1,n(!1)}}},[u,e.onOpen]);return!u||!e.onOpen?s.jsxs("span",{className:["af-memory-hint","af-memory-hint--text",e.className||""].filter(Boolean).join(" "),title:e.title,children:[s.jsx("span",{className:"af-memory-hint__dot",style:{background:c},"aria-hidden":"true"}),s.jsx("span",{className:"af-memory-hint__label",children:e.label}),u&&e.showId!==!1?s.jsx("code",{className:"af-memory-hint__id",children:Mx(u)}):null]}):s.jsxs("span",{className:["af-memory-hint",e.className||""].filter(Boolean).join(" "),children:[s.jsxs("button",{type:"button",className:"af-memory-hint__btn",onClick:()=>void d(),disabled:t,title:e.title||(e.command?e.command:`open ${u}`),"aria-label":`Open ${e.kind||"memory"} entry: ${e.label}`,children:[s.jsx("span",{className:"af-memory-hint__dot",style:{background:c},"aria-hidden":"true"}),s.jsx("span",{className:"af-memory-hint__label",children:e.label}),e.showId!==!1?s.jsx("code",{className:"af-memory-hint__id",children:Mx(u)}):null,s.jsx("span",{className:"af-memory-hint__act","aria-hidden":"true",children:t?"…":"↗"})]}),e.command?s.jsx("code",{className:"af-memory-hint__cmd",children:e.command}):null,r?s.jsx("span",{className:"af-memory-hint__err",role:"alert",children:r}):null]})}const A_=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 uC({value:e,onChange:t,fetchCatalog:n,intro:r,delivery:i=!0,quality:a=!0,showReset:u=!0,defaultHint:c,voiceDefaultLabel:d}){var F,M,D,H;const m=_.useRef(n);m.current=n;const[h,p]=_.useState({}),[y,w]=_.useState(""),[x,k]=_.useState(!1);_.useEffect(()=>{let q=!0;return k(!0),p({}),w(""),m.current(e.provider,e.model).then(I=>{q&&(p(I),w(I.error?String(I.error):""))}).catch(I=>{q&&w(String((I==null?void 0:I.message)||I))}).finally(()=>{q&&k(!1)}),()=>{q=!1}},[e.provider,e.model]);const b=Array.isArray(h.items)?h.items:[...Array.isArray(h.profiles)?h.profiles.map(q=>({...q,voice_kind:"profile"})):[],...Array.isArray(h.voices)?h.voices.map(q=>({...q,voice_kind:"voice"})):[]],S=q=>JSON.stringify([q.provider||"",q.model||"",q.voice_kind==="profile"?"profile":"voice",q.id]),$=b.find(q=>q.id===(e.profile||e.voice)&&q.voice_kind==="profile"==!!e.profile&&(!e.provider||!q.provider||q.provider===e.provider)&&(!e.model||!q.model||q.model===e.model)),A=$?S($):e.profile||e.voice?JSON.stringify([e.provider||"",e.model||"",e.profile?"profile":"voice",e.profile||e.voice]):"",E=b.filter(q=>(q==null?void 0:q.id)&&(!e.provider||!q.provider||q.provider===e.provider)).map(q=>({value:S(q),label:`${q.label||q.name||q.id}${!e.provider&&q.provider?` · ${q.provider}`:""}`}));A&&!E.some(q=>q.value===A)&&E.unshift({value:A,label:`${e.profile||e.voice} (saved)`});const z=q=>t({...e,...q});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(Uk,{defaultHint:c,value:{provider:e.provider||"",model:e.model||""},onChange:q=>t({...e,...q,voice:"",profile:""}),fetchProviders:async()=>{const q=await m.current();if(q.error&&!A_(q.tts_providers||q.providers).length)throw new Error(q.error);return A_(q.tts_providers||q.providers).map(I=>({name:I}))},fetchModels:async q=>{var Z;const I=await m.current(q);return A_(((Z=I.tts_models_by_provider)==null?void 0:Z[q])||I.tts_models||I.models)},providerLabel:"Speech provider",modelLabel:"Speech model"}),s.jsxs("label",{children:["Voice / profile",s.jsx(Pi,{ariaLabel:"AI voice",placeholder:d||"Gateway / provider default",value:A,disabled:x,options:[{value:"",label:d||"Gateway / provider default"},...E],onChange:q=>{if(!q){z({voice:"",profile:""});return}const[I,Z,R,T]=JSON.parse(q);z({provider:I||e.provider||"",model:Z||(I&&I!==e.provider?"":e.model)||"",voice:R==="voice"?T:"",profile:R==="profile"?T:""})}})]}),x?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,i?s.jsxs(s.Fragment,{children:[s.jsxs("label",{children:["Speaking speed",s.jsxs("select",{"aria-label":"Speech speed",value:e.speed??"",onChange:q=>z({speed:q.target.value?Number(q.target.value):void 0}),children:[s.jsx("option",{value:"",children:"Gateway default"}),[.5,.75,1,1.25,1.5,2].map(q=>s.jsxs("option",{value:q,children:[q,"×"]},q))]})]}),a&&((M=(F=h.controls)==null?void 0:F.quality_preset)!=null&&M.supported)?s.jsxs("label",{children:["Quality",s.jsxs("select",{"aria-label":"Speech quality",value:e.quality_preset||"",onChange:q=>z({quality_preset:q.target.value}),children:[s.jsx("option",{value:"",children:"Gateway default"}),A_(h.controls.quality_preset.values).map(q=>s.jsx("option",{value:q,children:q},q))]})]}):null,(H=(D=h.controls)==null?void 0:D.instructions)!=null&&H.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:q=>z({instructions:q.target.value})})]}):null]}):null,u?s.jsx("button",{type:"button",onClick:()=>t({}),children:"Reset to Gateway defaults"}):null]})}const Vg=yt("automations"),dC=yt("trigger-sources"),fC=yt("me/email"),mC=yt("automations/schedule-preview");class Rx 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 hC(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 i={status:e,code:r.reason_code,message:r.message};return typeof r.field=="string"&&(i.field=r.field),typeof r.command_id=="string"&&(i.command_id=r.command_id),i}}return{status:e,code:"invalid_response",message:`The gateway answered HTTP ${e} without an automation error envelope.`}}function Gg(e){const t=new URLSearchParams;for(const[r,i]of Object.entries(e))i!==void 0&&t.set(r,String(i));const n=t.toString();return n?`?${n}`:""}function _C(){return Ga()}function pC(e){const t=e.newId??_C,n=i=>`${Vg}/${encodeURIComponent(i)}`;async function r(i,a,u){const c={accept:"application/json",...e.headers?e.headers():{}},d={method:i,headers:c};u!==void 0&&(c["content-type"]="application/json",d.body=JSON.stringify(u));const m=await e.fetch(ov(e.baseUrl,a),d),h=await m.text();let p,y=!1;if(h)try{p=JSON.parse(h),y=!0}catch{y=!1}if(!m.ok)throw new Rx(hC(m.status,p));if(!y||p===null||typeof p!="object")throw new Rx({status:m.status,code:"invalid_response",message:`The gateway answered ${i} ${a} with a body that is not a JSON object.`});return p}return{listAutomations:(i={})=>r("GET",`${Vg}${Gg({status:i.status,cursor:i.cursor,limit:i.limit})}`),getAutomation:i=>r("GET",n(i)),createAutomation:i=>r("POST",Vg,i),reviseAutomation:(i,a)=>r("PATCH",n(i),{command_id:a.command_id??t(),...a.expected_revision!==void 0?{expected_revision:a.expected_revision}:{},changes:a.changes}),sendAutomationCommand:(i,a)=>r("POST",`${n(i)}/commands`,{command_id:a.command_id??t(),type:a.type,...a.payload!==void 0?{payload:a.payload}:{}}),listOccurrences:(i,a={})=>r("GET",`${n(i)}/occurrences${Gg({cursor:a.cursor,limit:a.limit})}`),discuss:(i,a)=>r("POST",`${n(i)}/discuss`,{request_id:a.request_id??t(),occurrence_index:a.occurrence_index,prompt:a.prompt}),markSeen:(i,a)=>r("POST",`${n(i)}/seen`,{attention_cursor:a}),listAttention:(i,a={})=>r("GET",`${n(i)}/attention${Gg({cursor:a.cursor,limit:a.limit})}`),listTriggerSources:()=>r("GET",dC),getMyEmail:()=>r("GET",fC),previewSchedule:i=>r("POST",mC,{trigger:i})}}function Zk(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(i=>typeof i=="string"&&(!n||n.includes(i))):null}function Qk(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 gC(e){const t=["prompt","tools","provider","model","temperature","seed","max_iterations","max_in_tokens","system","_limits"],n={};for(const i of t)i in e&&(n[i]=e[i]);const r=e._runtime;if(r&&typeof r=="object"){const i={};for(const a of["allowed_tools","provider","model","thinking","speculation","stream"])a in r&&(i[a]=r[a]);Object.keys(i).length&&(n._runtime=i)}return n}function Zy(e){return e.flow_id==="@default"?"@default":`${"bundle_ref"in e?e.bundle_ref:""}:${e.flow_id}`}const yC={active:"Active",pause:"Pause",resume:"Resume",run_now:"Run now",stop_current:"Stop current",revise:"Edit",archive:"Archive",unarchive:"Unarchive",discuss:"Discuss"},wC={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.`},vC="Next scheduled run: {time}.",xC="Growing context: later runs see this run in their history.",bC={run_now:{name:"playCircle"}},kC={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."},jC={legend:"When",kind_every:"Repeat",kind_daily:"Daily",kind_weekly:"Weekly",kind_monthly:"Monthly",kind_once:"Once at…",every_label:"Every",at_label:"at",time_label:"Time of day",days_legend:"On",days:{mon:"Mon",tue:"Tue",wed:"Wed",thu:"Thu",fri:"Fri",sat:"Sat",sun:"Sun"},day_label:"on day",last_day:"last",once_label:"Run once at",time_zone_line:"in {time_zone} (your account's time zone)",time_zone_line_automation:"in {time_zone} (this automation's time zone)",time_zone_hint:"Daily, weekly, monthly and one-time runs keep this wall-clock time when daylight saving time changes. A day the month does not have (31 in April) runs on its last day. Repeat runs at a fixed interval in UTC.",time_zone_change:"Change in preferences",time_zone_change_hint:"Your account's time zone is set in your preferences; new automations use it.",time_zone_default:"Gateway default ({time_zone})",time_zone_search:"Search time zones",describing:"Checking the schedule…",incomplete:"Incomplete schedule.",error_at:"Pick the time of day (HH:MM).",error_days:"Pick at least one day.",error_day:"Pick a day of the month: 1 to 31, or last.",error_once:"Pick the date and time to run once."},cv={labels:yC,hints:wC,run_now_next_run_line:vC,run_now_growing_line:xC,icons:bC,email:kC,schedule:jC},SC=/^([1-9][0-9]*)([smhd])$/,NC={s:["second","seconds"],m:["minute","minutes"],h:["hour","hours"],d:["day","days"]};function oh(e){if(typeof e!="string")return null;const t=SC.exec(e);return t?{amount:Number(t[1]),unit:t[2]}:null}function $C(e){const t=oh(e);if(!t)return`every ${e}`;const[n,r]=NC[t.unit];return t.amount===1?`every ${n}`:`every ${t.amount} ${r}`}function Qy(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 uv(e,t){return e.source_id==="schedule"?KC(t,e.source_version):e.source_id==="manual"&&e.source_version===1?"manual runs only":tg(e)?aj(e.config):`${e.source_id}@${e.source_version}`}function ej(e){return e==="growing"?"Growing — each run sees the previous runs":"Independent — each run starts fresh"}const CC={active:"Active",paused:"Paused",completed:"Completed",failed:"Failed",archived:"Archived"},mn=cv.email,tj="email.received",nj=1,EC="1h",AC="60s",sj=60,dv=100,ew=1e3,Lx=200,Ix=200,Ox=50;function tg(e){return!!e&&e.source_id===tj&&e.source_version===nj}function ng(e){return!!e&&e.effective_enabled===!0}function rj(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 TC=/[\s<>,;:"()[\]]/;function tw(e){const t=e.trim().toLowerCase(),n=t.indexOf("@");return n<=0||n===t.length-1?!1:!t.slice(n+1).includes("@")&&!TC.test(t)}function MC(e){const t=e.trim().toLowerCase();return!!t&&!t.includes("@")&&t.includes(".")&&!t.startsWith(".")&&!t.endsWith(".")&&!/[\s<>,;:"()[\]/*]/.test(t)}const ij={usesModel:!0,every:null,maxBatch:null,fromIn:"",fromDomainIn:"",toIn:"",subjectContains:"",hasAttachment:"any"};function fv(e){return e?EC:AC}function oj(e){const t=oh(e);return t?t.amount*{s:1,m:60,h:3600,d:86400}[t.unit]:null}function Kg(e,t,n,r,i){const a=rj(e);if(!a.length)return null;const u=a.filter(c=>!n(c));return u.length&&i.push(`${t}: ${u.join(", ")} ${u.length===1?"is not":"are not"} ${r}.`),a.length>Lx&&i.push(`${t}: at most ${Lx} entries.`),a}function RC(e){const t=[],n={uses_model:e.usesModel};e.every===null?n.every=fv(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&&(oj(n.every)??0)<sj&&t.push("The check interval is at least 60 seconds."),e.maxBatch===null?n.max_batch=dv:!Number.isInteger(e.maxBatch)||e.maxBatch<1||e.maxBatch>ew?t.push(`At most this many emails per run: a whole number from 1 to ${ew}.`):n.max_batch=e.maxBatch;const r={},i=Kg(e.fromIn,mn.from_in,tw,"an email address",t);i&&(r.from_in=i);const a=Kg(e.fromDomainIn,mn.from_domain_in,MC,"a domain like example.com",t);a&&(r.from_domain_in=a);const u=Kg(e.toIn,mn.to_in,tw,"an email address",t);u&&(r.to_in=u);const c=e.subjectContains.trim();return c&&(c.length>Ix||/[\r\n]/.test(c)?t.push(`${mn.subject_contains}: one line of at most ${Ix} characters.`):r.subject_contains=c),e.hasAttachment==="yes"?r.has_attachment=!0:e.hasAttachment==="no"&&(r.has_attachment=!1),Object.keys(r).length&&(n.filter=r),{config:n,errors:t}}function aj(e){const t=e,n=t.filter??{},r=["when an email arrives"],i=[...n.from_in??[],...n.from_domain_in??[]];i.length&&r.push(`from ${i.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 a=typeof t.every=="string"?t.every:fv(t.uses_model!==!1);r.push(`checked ${$C(a)}`);const u=typeof t.max_batch=="number"?t.max_batch:dv;return r.push(`up to ${u} per run`),r.join(" · ")}const Rm={mode:"self",addresses:""};function nw(e){if(e.mode==="self")return{recipients:["self"],errors:[]};const t=[],n=rj(e.addresses).filter(i=>i!=="self");n.length||t.push("Name at least one address the automation may email, or choose Only me.");const r=n.filter(i=>!tw(i));return r.length&&t.push(`${mn.recipients_list}: ${r.join(", ")} ${r.length===1?"is not an email address":"are not email addresses"}.`),n.length+1>Ox&&t.push(`At most ${Ox-1} addresses.`),{recipients:["self",...n],errors:t}}function LC(e){const t=(e??[]).filter(n=>n!=="self");return t.length?{mode:"list",addresses:t.join(", ")}:{mode:"self",addresses:""}}function IC(e){const t=(e??["self"]).filter(n=>n!=="self");return t.length?`Me and ${t.join(", ")}`:"Only me"}function lj(e,t=["self"]){return{channels:e?["console","email"]:["console"],...t.some(n=>n!=="self")?{recipients:t}:{}}}function cj(e){return!!e&&Array.isArray(e.channels)&&e.channels.includes("email")}function OC(e){return cj(e)?"In the console and by email":"In the console"}const uo={pause:"automation.pause",resume:"automation.resume",run_now:"automation.run_now",stop_current:"automation.stop_current",archive:"automation.archive",unarchive:"automation.unarchive"},PC=new Set(["running","waiting","backoff"]);function DC(e,t=[]){return e.current_occurrence!=null}function uj(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 dj(e,t){return e.next_run_at&&e.next_run_local?`${yj(e.next_run_local,e.time_zone)} (${FC(e.next_run_at,t)})`:e.status==="paused"?"none while paused":"none scheduled"}function FC(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 i=Math.floor(r/60);return i<24?`in ${i} h${r%60?` ${r%60} min`:""}`:`in ${Math.floor(i/24)} d${i%24?` ${i%24} h`:""}`}function Dm(e,t=[],n=!1){const r=new Set(e.capabilities),i=e.status,a=DC(e,t),u=(h,p,y)=>n?{enabled:!1,reason:"Working…"}:e.legacy?{enabled:!1,reason:"Legacy schedule: managed with its existing controls."}:r.has(h)?i==="archived"?{enabled:!1,reason:"Archived: history is kept, nothing runs."}:p?{enabled:!0}:{enabled:!1,reason:y}:{enabled:!1,reason:"Not permitted for this automation."},c=i==="active"||i==="paused",d=i==="active"?"pause":"resume";return{active:n?{enabled:!1,reason:"Working…"}:e.legacy?{enabled:!1,reason:"Legacy schedule: managed with its existing controls."}:i==="archived"?{enabled:!1,reason:"Archived: history is kept, nothing runs."}:c?r.has(d)?{enabled:!0}:{enabled:!1,reason:"Not permitted for this automation."}:{enabled:!1,reason:"The automation has ended."},pause:u("pause",i==="active",i==="paused"?"Already paused.":"The automation has ended."),resume:u("resume",i==="paused",i==="active"?"Already running on schedule.":"The automation has ended."),run_now:u("run_now",c&&!a,a?"An occurrence is in progress.":"The automation has ended."),stop_current:u("stop_current",a,"Nothing is running."),revise:u("revise",!0,""),archive:u("archive",!0,""),unarchive:n?{enabled:!1,reason:"Working…"}:e.legacy?{enabled:!1,reason:"Legacy schedule: managed with its existing controls."}:i!=="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 zC(e){return e.status==="active"?uo.pause:uo.resume}function BC(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 UC(e){return[...e].sort((t,n)=>t.index-n.index).map(t=>{const n=BC(t),r=`${t.attempts} ${t.attempts===1?"attempt":"attempts"}`,i=n==="failed"?`Failed after ${r}`:n==="waiting"?"Waiting for you":n==="notified"?"Notified":n==="running"?"Running":null,a=t.status==="completed"&&t.attempts>1?`completed after ${r}`:t.status;return{row:t,tone:n,notable:n==="failed"||n==="waiting"||n==="notified",badge:i,statusText:a,canDiscuss:!PC.has(t.status)}})}function WC(e){const t=e.attention.items;return t.length?t[t.length-1].cursor:null}function fj(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 qC={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 kp(e){return{title:qC[e.code]??`The gateway refused the request (${e.code}).`,detail:e.message}}function mv(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 mj(e,t){var a,u,c;const n=e.trigger,r=n.source_id==="schedule"||tg(n)?n.config.every:void 0,i=t?t.target.input_data.prompt:void 0;return{title:e.title,every:typeof r=="string"?r:null,calendar:GC(n)?ZC(n.config):null,context:e.context_mode,growingMaxTokens:Number(((u=(a=t==null?void 0:t.context)==null?void 0:a.growing)==null?void 0:u.max_tokens)??e.growing_max_tokens??Fm),prompt:typeof i=="string"?i:null,toolApproval:t?t.policy.tool_approval:null,tools:Zk(t==null?void 0:t.target.input_data),notifyEmail:t?cj(t.notify):null,emailRecipients:t?LC((c=t.notify)==null?void 0:c.recipients):null}}function HC(e,t,n){var d;const r=[],i={},a=t.title.trim();a?a.length>120?r.push("Title is at most 120 characters."):a!==e.title&&(i.title=a):r.push("Title is required.");const u=mj(e,n);if(t.every!==u.every&&t.every!==null){const m=tg(e.trigger);if(!oh(t.every))r.push("Interval must be a whole number of minutes, hours or days.");else if(m&&(oj(t.every)??0)<sj)r.push("The check interval is at least 60 seconds.");else{const h={...e.trigger.config,every:t.every};m&&delete h.start_at,i.trigger={source_id:e.trigger.source_id,source_version:e.trigger.source_version,config:h}}}if(t.calendar&&u.calendar&&JSON.stringify(t.calendar)!==JSON.stringify(u.calendar)){const m=_v(t.calendar);if(!m.config)r.push(...m.errors);else{const h=e.trigger.config,p={...m.config,...typeof h.time_zone=="string"?{time_zone:h.time_zone}:{},...typeof h.count=="number"?{count:h.count}:{},...typeof h.until=="string"?{until:h.until}:{}};i.trigger={source_id:e.trigger.source_id,source_version:e.trigger.source_version,config:p}}}const c=t.context==="growing"?t.growingMaxTokens??u.growingMaxTokens:u.growingMaxTokens;if(_j(c)||r.push(hj),(t.context!==e.context_mode||c!==u.growingMaxTokens)&&(i.context=pj(t.context,c)),n&&typeof u.prompt=="string"&&typeof t.prompt=="string"&&t.prompt.trim()!==u.prompt.trim()){const m=t.prompt.trim();m?i.target={bundle_ref:n.target.bundle_ref,flow_id:n.target.flow_id,input_data:{...n.target.input_data,prompt:m}}:r.push("Task is required.")}if(n&&t.tools!==void 0&&JSON.stringify(t.tools)!==JSON.stringify(u.tools)){const m=i.target||{bundle_ref:n.target.bundle_ref,flow_id:n.target.flow_id,input_data:n.target.input_data};i.target={...m,input_data:Qk(m.input_data||{},t.tools)}}if(n&&t.toolApproval&&t.toolApproval!==u.toolApproval&&(i.policy={tool_approval:t.toolApproval}),n&&typeof t.notifyEmail=="boolean"){const m=nw(t.notifyEmail?t.emailRecipients??Rm:u.emailRecipients??Rm),h=nw(u.emailRecipients??Rm).recipients;m.errors.length?r.push(...m.errors):(t.notifyEmail!==u.notifyEmail||JSON.stringify(m.recipients)!==JSON.stringify(h))&&(i.notify=lj(t.notifyEmail,m.recipients))}if(r.length)return{errors:r};if(n&&t.target&&Zy(t.target)!==Zy(n.target)){const m=((d=i.target)==null?void 0:d.input_data)||n.target.input_data;i.target={...t.target,input_data:gC(m)}}return Object.keys(i).length?i:null}const Fm=5e4,VC="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.",hj="Max growing context must be a positive whole number of tokens.";function _j(e){return Number.isSafeInteger(e)&&e>0}function pj(e,t){return{mode:e,...t!==Fm?{growing:{max_tokens:t}}:{}}}const us=cv.schedule,jp=["mon","tue","wed","thu","fri","sat","sun"],gj=["daily","weekly","monthly"],hv=2;function GC(e){return e.source_id==="schedule"&&e.source_version===hv}function KC(e,t=hv){const n=e==null?void 0:e.schedule_rule_text;return typeof n=="string"&&n?n:`schedule@${t}`}const JC=/^(\d{4}-\d{2}-\d{2})T(\d{2}:\d{2})/;function yj(e,t){if(!e)return"";const n=JC.exec(e);return n?`${n[1]} ${n[2]}${t?` ${t}`:""}`:e}function YC(e,t="account"){return(t==="account"?us.time_zone_line:us.time_zone_line_automation).replace("{time_zone}",e)}const XC=/^([01][0-9]|2[0-3]):[0-5][0-9]$/;function wj(e){return gj.includes(e.kind)}function _v(e){const t=[];if(XC.test(e.at)||t.push(us.error_at),e.kind==="weekly"){const n=jp.filter(r=>e.days.includes(r));return n.length||t.push(us.error_days),t.length?{config:null,errors:t}:{config:{kind:"weekly",days:n,at:e.at},errors:t}}return e.kind==="monthly"?(e.day==="last"||Number.isInteger(e.day)&&e.day>=1&&e.day<=31||t.push(us.error_day),t.length?{config:null,errors:t}:{config:{kind:"monthly",day:e.day,at:e.at},errors:t}):t.length?{config:null,errors:t}:{config:{kind:"daily",at:e.at},errors:t}}function ZC(e){const t=e,n=typeof t.at=="string"?t.at:"";return t.kind==="daily"?{kind:"daily",at:n}:t.kind==="weekly"?{kind:"weekly",at:n,days:Array.isArray(t.days)?jp.filter(r=>t.days.includes(r)):[]}:t.kind==="monthly"?{kind:"monthly",at:n,day:t.day==="last"?"last":Number(t.day)}:null}const QC=[{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 vj(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 eE(e){const t=e.trim().split(`
|
|
56
|
+
`)[0].trim();return t.length>120?`${t.slice(0,119)}…`:t}const tE=/^\d{4}-\d{2}-\d{2}T([01][0-9]|2[0-3]):[0-5][0-9]$/;function Px(e,t){const n={};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 r=vj(e.until);r?n.until=r:t.push("Stop at must be a date and time (UTC).")}return n}function nE(e){const t=[],n=e.when;if(n.kind==="once"){const c=(n.at||"").trim().slice(0,16);return tE.test(c)?{config:{kind:"once",at:c},errors:t}:{config:null,errors:[us.error_once]}}if(wj(n)){const c=_v(n),d=Px(e,c.errors);return c.config&&!c.errors.length?{config:{...c.config,...d},errors:[]}:{config:null,errors:c.errors}}const r=n.amount;let i=null;!Number.isInteger(r)||r<1?t.push("The interval must be a whole number of at least 1."):i=`${r}${n.unit}`;let a=null;e.startAt&&(a=vj(e.startAt),a||t.push("First run must be a date and time (UTC)."));const u=Px(e,t);return t.length||!i?{config:null,errors:t}:{config:{kind:"every",every:i,...a?{start_at:a}:{},...u},errors:t}}function xj(e){const t=nE(e);return t.config?{trigger:{source_id:"schedule",source_version:hv,config:t.config},errors:[]}:{trigger:null,errors:t.errors}}function sE(e){return e.kind==="every"||e.kind==="once"||wj(e)}function bj(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 i=(e.title??"").trim()||eE(r);i.length>120&&n.push("Title is at most 120 characters.");const a=e.trigger==="email",u=a?RC(e.email??ij):null,c=a?null:xj(e);n.push(...u?u.errors:c.errors);const d=e.notifyEmail&&e.emailRecipients&&e.emailRecipients.mode==="list"?nw(e.emailRecipients):null;d&&n.push(...d.errors);const m=e.growingMaxTokens??Fm;if(e.context==="growing"&&!_j(m)&&n.push(hj),n.length||!t.target)return{ok:!1,errors:n};const h={...t.target,input_data:{...t.target.input_data??{},prompt:r}},p={request_id:t.requestId,title:i,target:h,trigger:u?{source_id:tj,source_version:nj,config:u.config}:c.trigger,context:pj(e.context,e.context==="growing"?m:Fm),policy:{tool_approval:e.toolApproval??"auto"}};return e.notifyEmail===!0&&(p.notify=lj(!0,d==null?void 0:d.recipients)),{ok:!0,body:p}}const rE="Tools run without asking (you approve them now by creating this automation)";function iE(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 oE(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 kj={ask_user:"Question for you",tool_approval:"Approval needed",event:"Waiting for an event"};class aE{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||lE(n.error))&&this.open.delete(t)}}function lE(e){return mv(e)&&e.status>0&&e.code!=="invalid_response"}function cE(){return Ga()}class uE{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 Dx(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}const dE="08:00",fE=["mon"],jj={at:dE,days:[...fE],day:1};function pv(e,t){return e==="weekly"?{kind:e,at:t.at,days:[...t.days]}:e==="monthly"?{kind:e,at:t.at,day:t.day}:{kind:e,at:t.at}}function gv(e,t){return{...e,at:t.at,...t.kind==="weekly"?{days:[...t.days]}:{},...t.kind==="monthly"?{day:t.day}:{}}}function Fx(e){return gv(jj,e)}const mE=[...Array.from({length:31},(e,t)=>String(t+1)),"last"];function Sj(e){const t=e.value,n=r=>{if(t.kind!=="weekly")return;const i=t.days.includes(r);e.onChange({...t,days:jp.filter(a=>a===r?!i:t.days.includes(a))})};return s.jsxs("div",{className:"af-schedule__calendar","data-calendar-kind":t.kind,children:[t.kind==="weekly"?s.jsxs("div",{className:"af-auto__row af-schedule__days",role:"group","aria-label":us.days_legend,children:[s.jsx("span",{children:us.days_legend}),jp.map(r=>s.jsx(N2,{className:"af-schedule__day",pressed:t.days.includes(r),disabled:e.disabled,onClick:()=>n(r),tone:"accent",children:s.jsx("span",{"data-day":r,children:us.days[r]})},r))]}):null,s.jsxs("div",{className:"af-auto__row",children:[t.kind==="monthly"?s.jsxs(s.Fragment,{children:[s.jsx("label",{htmlFor:`${e.idBase}-month-day`,children:us.day_label}),s.jsx("select",{id:`${e.idBase}-month-day`,name:"calendar_day",value:String(t.day),disabled:e.disabled,onChange:r=>e.onChange({...t,day:r.target.value==="last"?"last":Number(r.target.value)}),children:mE.map(r=>s.jsx("option",{value:r,children:r==="last"?us.last_day:r},r))})]}):null,s.jsx("label",{htmlFor:`${e.idBase}-at`,children:us.at_label}),s.jsx("input",{id:`${e.idBase}-at`,name:"calendar_at",type:"time",step:60,required:!0,value:t.at,disabled:e.disabled,"aria-label":us.time_label,onChange:r=>e.onChange({...t,at:r.target.value.slice(0,5)})})]})]})}function hE(e){return s.jsxs("p",{className:"af-schedule__tz","data-time-zone":e.timeZone,children:[s.jsx(Cx,{content:us.time_zone_hint,children:s.jsx("span",{tabIndex:0,className:"af-schedule__tz-text",children:YC(e.timeZone,e.whose??"account")})}),e.onOpenPreferences&&(e.whose??"account")==="account"?s.jsxs(s.Fragment,{children:[" · ",s.jsx(Cx,{content:us.time_zone_change_hint,children:s.jsx("button",{type:"button",className:"af-auto__link af-schedule__tz-change",onClick:e.onOpenPreferences,children:us.time_zone_change})})]}):null]})}function _E(e){const t=e;return typeof(t==null?void 0:t.message)=="string"&&t.message?t.message:String(e)}function Nj(e,t,n=250){const r=e?JSON.stringify(e):"",[i,a]=_.useState({phase:"idle"}),u=_.useRef(0),c=_.useRef(t);return c.current=t,_.useEffect(()=>{const d=++u.current;if(!r){a({phase:"idle"});return}a({phase:"loading"});const m=setTimeout(()=>{c.current(JSON.parse(r)).then(h=>{u.current===d&&a({phase:"ok",description:h})},h=>{u.current===d&&a({phase:"error",message:_E(h)})})},n);return()=>clearTimeout(m)},[r,n]),i}function $j(e){const t=e.state;return t.phase==="ok"?s.jsxs(s.Fragment,{children:[e.showZone===!1?null:s.jsx(hE,{timeZone:t.description.time_zone,whose:e.whose,onOpenPreferences:e.onOpenPreferences}),s.jsx("p",{className:"af-schedule__preview","aria-live":"polite","data-preview":"served",children:t.description.first_run_sentence})]}):t.phase==="error"?s.jsx("p",{className:"af-schedule__preview af-auto__warn",role:"alert","data-preview":"error",children:t.message}):s.jsx("p",{className:"af-schedule__preview","aria-live":"polite","data-preview":t.phase,children:t.phase==="loading"?us.describing:e.incompleteText??us.incomplete})}function zx(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 sw(e){const t=e.disabled===!0,n=_.useMemo(()=>zx([...e.options||[],...e.value||[]]),[e.options,e.value]),r=_.useMemo(()=>zx(e.value||[]),[e.value]),[i,a]=_.useState(!1),[u,c]=_.useState(""),d=_.useMemo(()=>{const p=u.trim().toLowerCase();return p?n.filter(y=>y.toLowerCase().includes(p)):n},[n,u]),m=_.useMemo(()=>new Set(r),[r]),h=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:()=>a(p=>!p),disabled:t||!n.length,"aria-expanded":i,children:[i?"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(p=>s.jsxs("button",{type:"button",disabled:t,"aria-label":`Remove ${p}`,className:"af_multi_select_chip",title:p,onClick:()=>{if(t)return;const y=new Set(m);y.delete(p),e.onChange(Array.from(y.values()))},children:[p,t?null:s.jsx("span",{className:"af_multi_select_chip_x",children:"×"})]},p))}):null,i?s.jsxs("div",{className:"af_multi_select_panel",children:[s.jsx("input",{className:"mono",value:u,onChange:p=>c(String(p.target.value||"")),placeholder:"filter…","aria-label":"Filter options",disabled:t}),s.jsxs("div",{className:"af_multi_select_list",style:{maxHeight:`${h}px`},children:[d.map(p=>{const y=m.has(p);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 x=new Set(m);w.target.checked?x.add(p):x.delete(p),e.onChange(Array.from(x.values()))}}),s.jsx("span",{children:p})]},p)}),d.length?null:s.jsx("div",{className:"mono muted",children:"(no matches)"})]})]}):null]})}function Cj(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(sw,{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 Ej="@default",Aj="No workflows available for this app — ask your admin.",Tj={shared:"Shared",mine:"Mine"};class Fl extends Error{constructor(t){super(t),this.name="WorkflowPickerContractError"}}function pE(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 gE(e={}){return e.allVersions?"bundles?all_versions=true":"bundles"}function yE(e,t={}){return e===null?gE(t):pE(e,t)}function Ha(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function fr(e){return typeof e=="string"?e.trim():""}const T_="update the gateway";function wE(e,t){var c,d;const n=Ha(e.default_agent_workflows);if(!n)return{status:"unavailable",reason:"the gateway does not report a default workflow"};const r=Ha(n[t]);if(!r)return{status:"unavailable",reason:fr((d=Ha((c=Ha(e.default_agent_workflows_unavailable))==null?void 0:c[t]))==null?void 0:d.reason)||`no default workflow for ${t}`};const i=fr(r.bundle_id),a=fr(r.flow_id);if(!i||!a)return{status:"unavailable",reason:"the gateway's default workflow is missing its bundle or flow"};const u=fr(r.bundle_version);return{status:"ok",name:fr(r.name)||a,bundleId:i,bundleVersion:u,flowId:a,workflowId:fr(r.workflow_id)||`${i}${u?`@${u}`:""}:${a}`}}function vE(e,t,n={}){var c;const r=Ha(e);if(!r)throw new Fl("The gateway's workflow list is not a JSON object.");const i=fr(r.executable_for);if(t===null){if(i)throw new Fl(`Asked for every workflow, the gateway listed only ${i}.`)}else if(i!==t)throw new Fl(i?`The gateway listed workflows for ${i}, not ${t}.`:`This gateway does not filter workflows per app (no executable_for in its answer): ${T_}.`);if(!Array.isArray(r.items))throw new Fl("The gateway's workflow list has no items.");const a=[];for(const d of r.items){const m=Ha(d),h=fr(m==null?void 0:m.bundle_id);if(!m||!h)throw new Fl("The gateway listed a workflow without a bundle id.");const p=Ha(m.owner),y=fr(p==null?void 0:p.kind);if(y!=="gateway"&&y!=="user")throw new Fl(`The gateway did not say who owns ${h} (owner missing): ${T_}.`);if(typeof m.shipped!="boolean")throw new Fl(`The gateway did not say whether ${h} ships with it (shipped missing): ${T_}.`);const w=fr(m.bundle_version),x=Array.isArray(m.entrypoints)?m.entrypoints:[];for(const k of x){const b=Ha(k),S=fr(b==null?void 0:b.flow_id);if(!b||!S)continue;const $=Array.isArray(b.interfaces)?b.interfaces.map(fr).filter(Boolean):[];if(t===null){if(!$.length)continue}else if(!$.includes(t))throw new Fl(`The gateway offered ${h}:${S}, which does not declare ${t}: ${T_}.`);a.push({value:fr(b.workflow_id)||`${h}${w?`@${w}`:""}:${S}`,bundleId:h,bundleVersion:w,flowId:S,name:fr(b.name)||fr((c=Ha(m.metadata))==null?void 0:c.name)||h,description:fr(b.description)||fr(m.description),registryScope:fr(m.registry_scope)||"private",group:y==="user"?"mine":"shared",shipped:m.shipped,interfaces:$,...t===null?{showInterfaces:!0}:{}})}}const u=n.defaultInterface??t;return{interfaceId:t,entries:a,gatewayDefault:u?wE(r,u):{status:"unavailable",reason:"no interface named for the gateway default"}}}function xE(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:Tj[n],entries:e.filter(r=>r.group===n).sort(t)})).filter(n=>n.entries.length>0)}const bE={"abstractcode.agent.v1":"Code agent","abstractassistant.agent.v1":"Assistant","abstractcode.coding.v1":"Coding",tools:"tools",event:"event",chat:"chat"};function kE(e){return bE[e]??e}function jE(e,t=[]){const n=e.bundleVersion?`@${e.bundleVersion}`:"";return e.showInterfaces?[[...new Set(e.interfaces.map(kE))].join(", "),n].filter(Boolean).join(" · "):n}function SE(e){return e.value}function NE(e){return e?e.status==="unavailable"?e.reason:`${e.name}${e.bundleVersion?` @${e.bundleVersion}`:""}`:""}function $E(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 CE(e,t=!0){const n=(e==null?void 0:e.entries)??[],r=[];t&&r.push({key:"default",value:Ej,name:"Gateway default",detail:NE((e==null?void 0:e.gatewayDefault)??null),group:null,entry:null});for(const i of xE(n))for(const a of i.entries)r.push({key:a.value,value:a.value,name:a.name,detail:jE(a,n),title:SE(a),group:i.id,entry:a});return r}async function EE(e,t,n){var a;const r=await fetch(ov(e,yt(t)),{credentials:"include",headers:{Accept:"application/json"},signal:n}),i=await r.json().catch(()=>null);if(!r.ok){const u=((a=i==null?void 0:i.detail)==null?void 0:a.message)||(i==null?void 0:i.message)||(typeof(i==null?void 0:i.detail)=="string"?i.detail:"");throw new Error(u||`The gateway answered ${r.status}.`)}return i}function AE(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 Mj(e){const{interfaceId:t,defaultInterface:n,allVersions:r=!1,enabled:i=!0,gatewayBaseUrl:a,reloadKey:u}=e,c=_.useRef(e.request);c.current=e.request;const[d,m]=_.useState(0),[h,p]=_.useState({status:"idle",data:null,error:""});_.useEffect(()=>{if(!i){p({status:"idle",data:null,error:""});return}const w=new AbortController;p(b=>({...b,status:"loading",error:""}));const x=yE(t,{allVersions:r});return(c.current?c.current(x,{signal:w.signal}):EE(a,x,w.signal)).then(b=>{w.signal.aborted||p({status:"ready",data:vE(b,t,{defaultInterface:n}),error:""})}).catch(b=>{w.signal.aborted||p({status:"error",data:null,error:AE(b)})}),()=>w.abort()},[t,n,r,i,a,u,d]);const y=_.useCallback(()=>m(w=>w+1),[]);return{...h,reload:y}}function TE(e){if(!e||typeof window>"u")return{};const t=e.getBoundingClientRect(),n=window.innerWidth,r=window.innerHeight,i=Math.min(Math.max(t.width,300),440,n-32),a=Math.max(16,Math.min(t.left,n-16-i)),u=r-t.bottom-16;return u>=220||u>=t.top?{position:"fixed",left:a,width:i,top:t.bottom+4,maxHeight:Math.max(160,u)}:{position:"fixed",left:a,width:i,bottom:r-t.top+4,maxHeight:Math.max(160,t.top-16)}}function Rj(...e){return e.filter(Boolean).join(" ")}function Lj(e){const t=Mj({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),i=_.useId().replace(/:/g,""),a=`${i}-list`,[u,c]=_.useState(!1),[d,m]=_.useState(-1),h=_.useRef(null),p=_.useRef(null),[y,w]=_.useState({}),x=_.useMemo(()=>CE(n.data,r),[n.data,r]),k=x.find(M=>M.value===e.value),b=k?{name:k.name,detail:k.detail}:e.currentLabel?{name:e.currentLabel.name,detail:e.currentLabel.detail||""}:n.status==="loading"?{name:"Loading workflows…",detail:""}:{name:e.value===Ej?"Gateway default":"Choose a workflow",detail:""},S=String(e.unavailableReason||"").trim(),$=!S&&n.status==="ready",A=_.useCallback(()=>{c(!1),m(-1)},[]),E=_.useCallback(()=>{if(!$)return;w(TE(p.current)),c(!0);const M=x.findIndex(D=>D.value===e.value);m(M>=0?M:0)},[$,x,e.value]),z=_.useCallback(M=>{var D;A(),M.value!==e.value&&e.onChange(M.value,M.entry),(D=p.current)==null||D.focus()},[A,e]);_.useEffect(()=>{if(!u)return;const M=H=>{h.current&&!h.current.contains(H.target)&&A()},D=()=>A();return document.addEventListener("mousedown",M),document.addEventListener("touchstart",M),window.addEventListener("resize",D),()=>{document.removeEventListener("mousedown",M),document.removeEventListener("touchstart",M),window.removeEventListener("resize",D)}},[u,A]),_.useEffect(()=>{var D;if(!u||d<0)return;const M=typeof document<"u"?document.getElementById(`${i}-opt-${d}`):null;(D=M==null?void 0:M.scrollIntoView)==null||D.call(M,{block:"nearest"})},[u,d,i]);const F=M=>{if(!u){["Enter"," ","ArrowDown","ArrowUp"].includes(M.key)&&(M.preventDefault(),E());return}if(M.key==="Escape"){M.preventDefault(),A();return}if(M.key==="Tab"){A();return}if(M.key==="Enter"||M.key===" "){M.preventDefault(),d>=0&&x[d]&&z(x[d]);return}const D=$E(M.key,d,x.length);D!==null&&(M.preventDefault(),m(D))};return s.jsxs("div",{ref:h,className:Rj("af-workflow-picker",e.className),"data-interface":e.interfaceId??"any",children:[s.jsxs("button",{ref:p,id:e.id,type:"button",role:"combobox",className:"af-workflow-picker__trigger","aria-label":e.ariaLabel||"Workflow","aria-describedby":`${i}-value`,"aria-haspopup":"listbox","aria-expanded":u,"aria-controls":a,"aria-activedescendant":u&&d>=0?`${i}-opt-${d}`:void 0,"aria-disabled":$?void 0:!0,title:S||void 0,onClick:()=>u?A():E(),onKeyDown:F,children:[s.jsxs("span",{className:"af-workflow-picker__value",id:`${i}-value`,children:[s.jsx("span",{className:"af-workflow-picker__name",children:b.name}),b.detail?s.jsx("span",{className:"af-workflow-picker__detail",children:b.detail}):null]}),s.jsx("span",{className:"af-workflow-picker__caret","aria-hidden":"true"})]}),u?s.jsx(ME,{id:a,idBase:i,rows:x,value:e.value,highlight:d,ariaLabel:e.ariaLabel||"Workflow",style:y,onHighlight:m,onChoose:z}):null,n.status==="error"?s.jsx("span",{className:"af-workflow-picker__error",role:"alert",children:n.error}):n.status==="ready"&&x.every(M=>!M.entry)&&!r?s.jsx("span",{className:"af-workflow-picker__empty",role:"status",children:Aj}):null]})}function ME(e){const t=(a,u)=>s.jsxs("div",{id:`${e.idBase}-opt-${u}`,role:"option","aria-selected":a.value===e.value,"data-value":a.value,title:a.title,className:Rj("af-workflow-picker__option",u===e.highlight&&"af-workflow-picker__option--highlighted",a.value===e.value&&"af-workflow-picker__option--selected"),onMouseEnter:()=>e.onHighlight(u),onMouseDown:c=>c.preventDefault(),onClick:()=>e.onChoose(a),children:[s.jsx("span",{className:"af-workflow-picker__name",children:a.name}),a.detail?s.jsx("span",{className:"af-workflow-picker__detail",children:a.detail}):null]},a.key),n=e.rows.map((a,u)=>({row:a,index:u})),r=n.filter(a=>a.row.group===null),i=["shared","mine"].map(a=>({g:a,items:n.filter(u=>u.row.group===a)})).filter(a=>a.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(a=>t(a.row,a.index)),i.map(({g:a,items:u})=>s.jsxs("div",{role:"group","aria-labelledby":`${e.idBase}-g-${a}`,"data-group":a,children:[s.jsx("div",{id:`${e.idBase}-g-${a}`,className:"af-workflow-picker__group",role:"presentation",children:Tj[a]}),u.map(c=>t(c.row,c.index))]},a)),i.length===0?s.jsx("p",{className:"af-workflow-picker__empty",children:Aj}):null]})}function RE(e){const t=Zy(e.target);return s.jsxs("div",{className:"af-auto__field",children:[s.jsx("span",{children:"Workflow"}),s.jsx(Lj,{...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 LE(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}`:"",i=e.flow_id!=="@default"?e.flow_id:(n==null?void 0:n.status)==="ok"?n.flowId:"";if(!r||!i||!t.request)throw new Error("Workflow inputs could not be checked. Refresh the workflow list and try again.");const a=r.lastIndexOf("@"),u=a<0?r:r.slice(0,a),c=a<0?"":r.slice(a+1),d=await t.request(`bundles/${encodeURIComponent(u)}/flows/${encodeURIComponent(i)}/input_schema${c?`?bundle_version=${encodeURIComponent(c)}`:""}`,{signal:new AbortController().signal}),m=(d==null?void 0:d.input_data_schema)||d;if(!m||typeof m!="object"||!m.properties)throw new Error("This workflow does not report its input requirements. Choose another workflow.");const h={...d.defaults||{}};for(const[x,k]of Object.entries(m.properties))k&&"default"in k&&(h[x]=k.default);Object.assign(h,e.input_data||{});const p=(Array.isArray(m.required)?m.required:[]).filter(x=>h[x]===void 0);if(p.length)throw new Error(`This workflow needs additional inputs: ${p.join(", ")}. Configure a new automation from that workflow's input form, or choose a compatible workflow.`);return{...e,input_data:h}}function rw(e){if(ng(e.status))return null;const t=mn.not_set_up,n=mn.open_my_email,r=t.endsWith(n)?t.slice(0,t.length-n.length):`${t} `,i=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,i?s.jsxs("span",{className:"af-email__cause",children:[" (",i,")"]}):null]})}function IE(e){const t=e.value,n=c=>e.onChange({...t,...c}),r=c=>`${e.idBase}-email-${c}`,i=oh(fv(t.usesModel)),a=t.every??(i&&i.unit==="s"?{amount:Math.max(1,Math.round(i.amount/60)),unit:"m"}:{amount:i?i.amount:1,unit:i?i.unit:"h"}),u=e.disabled===!0;return s.jsxs("div",{className:"af-email__trigger","data-field":"email-trigger",children:[s.jsxs("div",{className:"af-auto__row",children:[s.jsx("span",{children:mn.every_label}),s.jsx("input",{type:"number",min:1,step:1,value:String(a.amount),disabled:u,"aria-label":"Check interval amount",name:"email_every_amount",onChange:c=>n({every:{amount:Number(c.target.value),unit:a.unit}})}),s.jsxs("select",{value:a.unit,disabled:u,"aria-label":"Check interval unit",name:"email_every_unit",onChange:c=>n({every:{amount:a.amount,unit:c.target.value}}),children:[s.jsx("option",{value:"m",children:"minutes"}),s.jsx("option",{value:"h",children:"hours"}),s.jsx("option",{value:"d",children:"days"})]})]}),s.jsx("p",{className:"af-auto__hint","data-email-rule":"interval",children:mn.interval_rule}),s.jsxs("label",{className:"af-auto__field",htmlFor:r("batch"),children:[s.jsx("span",{children:mn.max_batch_label}),s.jsx("input",{id:r("batch"),name:"email_max_batch",type:"number",min:1,max:ew,step:1,disabled:u,value:String(t.maxBatch??dv),onChange:c=>n({maxBatch:c.target.value.trim()===""?null:Number(c.target.value)})})]}),s.jsx("p",{className:"af-auto__hint",children:mn.max_batch_hint}),s.jsxs("fieldset",{className:"af-auto__field af-email__filters",disabled:u,children:[s.jsx("legend",{children:mn.filters_legend}),s.jsxs("label",{className:"af-auto__field",htmlFor:r("from"),children:[s.jsx("span",{children:mn.from_in}),s.jsx("input",{id:r("from"),name:"email_from_in",value:t.fromIn,spellCheck:!1,placeholder:"alice@example.com, billing@example.org",onChange:c=>n({fromIn:c.target.value})})]}),s.jsxs("label",{className:"af-auto__field",htmlFor:r("domain"),children:[s.jsx("span",{children:mn.from_domain_in}),s.jsx("input",{id:r("domain"),name:"email_from_domain_in",value:t.fromDomainIn,spellCheck:!1,placeholder:"example.com",onChange:c=>n({fromDomainIn:c.target.value})})]}),s.jsxs("label",{className:"af-auto__field",htmlFor:r("to"),children:[s.jsx("span",{children:mn.to_in}),s.jsx("input",{id:r("to"),name:"email_to_in",value:t.toIn,spellCheck:!1,onChange:c=>n({toIn:c.target.value})})]}),s.jsxs("label",{className:"af-auto__field",htmlFor:r("subject"),children:[s.jsx("span",{children:mn.subject_contains}),s.jsx("input",{id:r("subject"),name:"email_subject_contains",value:t.subjectContains,maxLength:200,onChange:c=>n({subjectContains:c.target.value})})]}),s.jsxs("label",{className:"af-auto__field",htmlFor:r("attach"),children:[s.jsx("span",{children:mn.has_attachment}),s.jsxs("select",{id:r("attach"),name:"email_has_attachment",value:t.hasAttachment,onChange:c=>n({hasAttachment:c.target.value}),children:[s.jsx("option",{value:"any",children:mn.has_attachment_any}),s.jsx("option",{value:"yes",children:mn.has_attachment_yes}),s.jsx("option",{value:"no",children:mn.has_attachment_no})]})]}),s.jsx("p",{className:"af-auto__hint",children:mn.list_hint})]})]})}function OE(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(_o,{variant:"row",action:"notify-email",label:mn.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:[mn.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:mn.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"})})," ",mn.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"})})," ",mn.recipients_list]}),e.recipients.mode==="list"?s.jsx("textarea",{name:"email_recipient_list","aria-label":mn.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:mn.recipients_hint})]}):null]})}const PE={active:"play",paused:"pause",completed:"check",failed:"error",archived:"archive"};function Ij(e){const t=String(e.status),n=PE[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:CC[t]??t}),n?s.jsx(Xe,{name:n,size:e.iconSize??11,className:"af-auto__status-icon"}):null]})}const iw="Discuss — fork at this occurrence (own workspace, automation files read-only)",sg=e=>s.jsx("div",{className:"af-auto-text","data-unformatted":"true",children:e});function DE(e){return mv(e)?e:{status:0,code:"client_error",message:e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}}function Bx(e){const t=e.path.split(new RegExp("(?<=[/\\\\_-])"));return s.jsx("code",{className:"af-auto__path-text",children:t.map((n,r)=>s.jsxs(Ne.Fragment,{children:[n,r<t.length-1?s.jsx("wbr",{}):null]},r))})}function FE(e,t){const n=e.trigger,r=t.find(i=>i.id===n.source_id&&i.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 zE(e){const t=e.summary,n=uj(t),r=FE(t,e.triggerSources),i=dj(t,e.nowMs??Date.now());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(Ij,{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:[uv(t.trigger,t),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:ej(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:i}),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 a;return(a=e.onOpenWorkspace)==null?void 0:a.call(e,t.automation_id)},children:[s.jsx(Xe,{name:"folder",size:14,className:"af-auto__path-icon"}),s.jsx(Bx,{path:t.workspace_root})]}):s.jsxs("span",{className:"af-auto__path af-auto__path--static",children:[s.jsx(Xe,{name:"folder",size:14,className:"af-auto__path-icon"}),s.jsx(Bx,{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:fj(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 BE(e){var u,c;const t=e.definition,n=e.renderText??sg,r=t.target.input_data.prompt,i=t.policy.retry,a=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(Xe,{name:"chevronRight",size:14,className:"af-auto__definition-chevron"}),s.jsx(Xe,{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," · ",uv(t.trigger,e.served),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:[ej(t.context.mode),t.context.mode==="growing"?` · ${Number(((u=t.context.growing)==null?void 0:u.max_tokens)??5e4).toLocaleString()} tokens`:""]}),s.jsx("dt",{children:"Tools"}),s.jsx("dd",{"data-def":"tool_approval",children:a==="ask"?"Ask before each tool call (ask)":a==="auto"?"Run without asking (auto)":String(a)}),s.jsx("dt",{children:"Notify"}),s.jsx("dd",{"data-def":"notify",children:OC(t.notify)}),(c=t.notify)!=null&&c.channels.includes("email")?s.jsxs(s.Fragment,{children:[s.jsx("dt",{children:"Recipients"}),s.jsx("dd",{"data-def":"email_recipients",children:IC(t.notify.recipients)})]}):null,s.jsx("dt",{children:"Retries"}),s.jsxs("dd",{"data-def":"retry",children:[i.max_attempts," ",i.max_attempts===1?"attempt":"attempts",", backoff ",i.backoff.initial," ×",i.backoff.factor," up to ",i.backoff.max]}),s.jsx("dt",{children:"Revision"}),s.jsx("dd",{"data-def":"revision",children:t.revision})]})]})}const ah=cv,ca=ah.labels,Bo={active:"play",pause:"pause",resume:"play",run_now:ah.icons.run_now.name,stop_current:"stop",revise:"edit",archive:"archive",unarchive:"unarchive",discuss:"chat"},ow=ah.hints,UE=ah.run_now_next_run_line,WE=ah.run_now_growing_line;function Sp(e,t){const n=[ow[e]];return e==="run_now"&&t&&(t.next_run_local&&n.push(UE.replace("{time}",yj(t.next_run_local,t.time_zone))),t.context_mode==="growing"&&n.push(WE)),n.join(`
|
|
58
|
+
`)}function qE(e,t,n){const r=new Map;for(const u of t){const c=e[u];if(c.enabled)continue;const d=c.reason??"Not available now.";r.set(d,[...r.get(d)??[],u])}const i=[],a={};return[...r.entries()].forEach(([u,c],d)=>{const m=`${n}-why-${d}`;i.push({id:m,text:`${c.map(h=>ca[h]).join(", ")}: ${u}`});for(const h of c)a[h]=m}),{lines:i,describedBy:a}}function Ur(e){return s.jsxs(s.Fragment,{children:[s.jsx(Xe,{name:e.icon,size:14,className:"af-auto__btn-icon"}),s.jsx("span",{children:e.label})]})}function HE(e){const t=Dm(e.summary,e.occurrences,e.busy),n=e.summary.status==="archived",i=qE(t,["active","run_now","stop_current","revise",n?"unarchive":"archive"],e.idBase??`af-auto-${e.summary.automation_id}`),a=(u,c,d)=>{const m=Sp(u,e.summary);return s.jsx("button",{type:"button",className:`af-auto__btn${d!=null&&d.danger?" af-auto__btn--danger":""}`,"data-action":(d==null?void 0:d.action)??u,disabled:!t[u].enabled,title:t[u].enabled?m:`${t[u].reason}
|
|
59
|
+
${m}`,"aria-description":m,"aria-describedby":i.describedBy[u],"aria-pressed":d==null?void 0:d.pressed,onClick:c,children:s.jsx(Ur,{icon:Bo[u],label:(d==null?void 0:d.label)??ca[u]})},u)};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(_o,{className:"af-auto__switch",action:"active",label:ca.active,checked:e.summary.status==="active",unavailableReason:t.active.enabled?null:t.active.reason??"Not available now.",describedBy:i.describedBy.active,busy:e.busy,hint:Sp("active",e.summary),onChange:()=>e.onCommand(zC(e.summary))},"active"),a("run_now",()=>e.onCommand(uo.run_now)),a("stop_current",()=>e.onCommand(uo.stop_current)),a("revise",e.onToggleRevise,{pressed:e.reviseOpen,action:"edit"}),n?a("unarchive",()=>e.onCommand(uo.unarchive)):a("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(Xe,{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(Xe,{name:"x",size:12})}):null]}):null})]}),i.lines.length?s.jsxs("p",{className:"af-auto__reasons",children:[s.jsx(Xe,{name:"info",size:12,className:"af-auto__reasons-icon"}),i.lines.map(u=>s.jsx("span",{id:u.id,children:u.text},u.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(uo.archive),children:s.jsx(Ur,{icon:"archive",label:"Archive"})}),s.jsx("button",{type:"button",className:"af-auto__btn","data-action":"archive-cancel",onClick:e.onCancelArchive,children:s.jsx(Ur,{icon:"x",label:"Keep it"})})]})]}):null]})}const Ux=[["m","minutes"],["h","hours"],["d","days"]];function VE(e,t){const n=b=>{const S=e.elements.namedItem(b);return S&&typeof S.value=="string"?S.value:null},r=n("every_amount"),i=n("every_unit"),a=r!==null&&i!==null?`${r.trim()}${i}`:t.every,u=e.elements.namedItem("context"),c=u&&(u.value==="growing"||u.value==="independent")?u.value:t.context,d=n("prompt"),m=e.elements.namedItem("tool_approval"),h=m&&(m.value==="auto"||m.value==="ask")?m.value:t.toolApproval??null,p=e.elements.namedItem("notify_email"),y=p&&typeof p.checked=="boolean"?p.checked:t.notifyEmail??null,w=e.elements.namedItem("email_recipients"),x=n("email_recipient_list"),k=w&&(w.value==="self"||w.value==="list")?{mode:w.value,addresses:x??""}:t.emailRecipients??null;return{title:n("title")??t.title,every:a,context:c,growingMaxTokens:n("growing_max_tokens")===null?t.growingMaxTokens:Number(n("growing_max_tokens")),prompt:d??t.prompt??null,toolApproval:h,notifyEmail:y,emailRecipients:k}}function GE(e){var F;const t=mj(e.summary,e.definition),[n,r]=_.useState(),[i,a]=_.useState(t.tools??null),[u,c]=_.useState(t.context),[d,m]=_.useState(!!t.notifyEmail),[h,p]=_.useState(((F=t.calendar)==null?void 0:F.kind)??null),[y,w]=_.useState(t.calendar?Fx(t.calendar):null),x=h&&y?pv(h,y):null,k=(()=>{if(!x)return null;const M=_v(x);if(!M.config)return null;const D=e.summary.trigger.config.time_zone;return{source_id:e.summary.trigger.source_id,source_version:e.summary.trigger.source_version,config:{...M.config,...typeof D=="string"?{time_zone:D}:{}}}})(),b=Nj(k,e.previewSchedule),S=t.every?oh(t.every):null,$=S&&S.unit==="s"?[["s","seconds"],...Ux]:Ux,A=`af-auto-revise-${e.summary.automation_id}`,E=ng(e.emailStatus),z=tg(e.summary.trigger);return s.jsxs("form",{className:"af-auto__revise","aria-labelledby":`${A}-heading`,onSubmit:M=>{M.preventDefault(),e.onSubmit({...VE(M.currentTarget,t),...x?{calendar:x}:{},...n?{target:n}:{},...e.availableTools!==void 0?{tools:i}:{}})},onKeyDown:M=>{M.key==="Escape"&&e.onCancel&&(M.preventDefault(),e.onCancel())},children:[e.heading===null?s.jsx("span",{id:`${A}-heading`,hidden:!0,children:"Edit automation"}):s.jsxs("h3",{className:"af-auto__form-title",id:`${A}-heading`,children:[s.jsx(Xe,{name:"edit",size:14})," ",e.heading??"Edit automation"]}),e.definition&&e.workflowPickerOptions?s.jsx(RE,{target:n||e.definition.target,options:e.workflowPickerOptions,onChange:r}):null,s.jsxs("label",{className:"af-auto__field",htmlFor:`${A}-title`,children:[s.jsx("span",{children:"Title"}),s.jsx("input",{id:`${A}-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:`${A}-prompt`,children:[s.jsx("span",{children:"Task"}),s.jsx("textarea",{id:`${A}-prompt`,name:"prompt",defaultValue:t.prompt,rows:Math.min(10,Math.max(3,t.prompt.split(`
|
|
60
|
+
`).length+1)),required:!0})]}):null,S?s.jsxs("fieldset",{className:"af-auto__field",children:[s.jsx("legend",{children:z?mn.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:S.amount,"aria-label":"Interval amount"}),s.jsx("select",{name:"every_unit",defaultValue:S.unit,"aria-label":"Interval unit",children:$.map(([M,D])=>s.jsx("option",{value:M,children:D},M))})]}),z?s.jsx("p",{className:"af-auto__hint","data-email-rule":"interval",children:mn.interval_rule}):null]}):x?s.jsxs("fieldset",{className:"af-auto__field","data-field":"calendar",children:[s.jsx("legend",{children:us.legend}),s.jsx("div",{className:"af-auto__row",role:"radiogroup","aria-label":"Schedule kind",children:gj.map(M=>s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:`${A}-calendar-kind`,value:M,checked:x.kind===M,disabled:e.busy,onChange:()=>p(M)})," ",us[`kind_${M}`]]},M))}),s.jsx(Sj,{value:x,onChange:M=>w(D=>gv(D??Fx(M),M)),idBase:A,disabled:e.busy}),s.jsx($j,{state:b,whose:"automation"})]}):s.jsx("p",{className:"af-auto__hint",children:"This trigger has no interval to change."}),s.jsxs("fieldset",{className:"af-auto__field",children:[s.jsx("legend",{children:"Context"}),s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:"context",value:"independent",defaultChecked:t.context==="independent",onChange:()=>c("independent")})," Independent — each run starts fresh"]}),s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:"context",value:"growing",defaultChecked:t.context==="growing",onChange:()=>c("growing")})," Growing — each run sees the previous runs"]}),s.jsx("div",{hidden:u!=="growing",children:s.jsxs("label",{className:"af-auto__field",children:[s.jsx("span",{children:"Max growing context (tokens)"}),s.jsx("input",{name:"growing_max_tokens",type:"number",min:1,step:1,disabled:e.busy||u!=="growing",defaultValue:t.growingMaxTokens}),s.jsx("span",{className:"af-auto__hint",children:VC})]})})]}),t.toolApproval?s.jsxs("fieldset",{className:"af-auto__field",children:[s.jsx("legend",{children:"Tools"}),e.availableTools!==void 0?s.jsx(Cj,{availableTools:e.availableTools,value:i,onChange:a,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"}),E?null:s.jsx(rw,{status:e.emailStatus,onOpenMyEmail:e.onOpenMyEmail}),s.jsx(c2,{variant:"row",action:"notify-email",name:"notify_email",label:mn.notify_label,defaultChecked:!!t.notifyEmail,onChange:m,unavailableReason:!E&&!t.notifyEmail?"Connect a mailbox first.":null}),s.jsxs("p",{className:"af-auto__hint",children:[mn.notify_hint," Turn on Email result to choose yourself or other email addresses."]}),s.jsx("div",{hidden:!d,children:s.jsxs("fieldset",{className:"af-auto__field",disabled:!d,"data-field":"email-recipients",children:[s.jsx("legend",{children:mn.recipients_legend}),s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:"email_recipients",value:"self",defaultChecked:t.emailRecipients.mode==="self"})," ",mn.recipients_self]}),s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:"email_recipients",value:"list",defaultChecked:t.emailRecipients.mode==="list",disabled:!E&&t.emailRecipients.mode!=="list"})," ",mn.recipients_list]}),s.jsx("textarea",{name:"email_recipient_list","aria-label":mn.recipients_list,rows:2,spellCheck:!1,defaultValue:t.emailRecipients.addresses,disabled:!E&&t.emailRecipients.mode!=="list"}),s.jsx("p",{className:"af-auto__hint",children:mn.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(M=>s.jsx("li",{children:M},M))}):null,s.jsxs("div",{className:"af-auto__row",children:[s.jsx("button",{type:"submit",className:"af-auto__btn af-auto__btn--primary","data-action":"edit-save",disabled:e.busy,children:s.jsx(Ur,{icon:"check",label: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(Ur,{icon:"x",label:"Cancel"})}):null]})]})}function aw(e,t){const n=e.elements.namedItem(t);return n&&typeof n.value=="string"?n.value.trim():""}function KE(e){const t=e.wait,n=`${e.idBase}-${t.run_id}-${t.wait_key}-prompt`,r=u=>e.onAnswerWait(t.run_id,t.wait_key,u),i=e.renderText??sg,a=u=>s.jsxs("div",{className:"af-auto-wait__prompt",id:n,children:[s.jsx("span",{className:"af-auto-wait__kind",children:kj[t.kind]??"Waiting"}),t.prompt?i(t.prompt):s.jsxs("span",{children:[" ",u]})]});if(t.kind==="tool_approval"){const u=iE(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:[a("A tool call needs your approval."),u&&u.length?s.jsx("ul",{className:"af-auto-wait__calls","aria-label":"Tool calls to approve",children:u.map((c,d)=>s.jsxs("li",{"data-tool":c.name,children:[s.jsx("code",{className:"af-auto-wait__tool",children:c.name}),s.jsx("pre",{className:"af-auto-wait__args",children:JSON.stringify(c.arguments,null,2)})]},c.call_id??`${c.name}:${d}`))}):s.jsx("p",{className:"af-auto__hint",children:"The gateway did not list the tool calls; open the run to see them before approving."}),s.jsxs("div",{className:"af-auto__row",children:[s.jsx("button",{type:"button",className:"af-auto__btn af-auto__btn--primary","data-action":"wait-approve",disabled:e.busy,onClick:()=>r({approved:!0}),children:s.jsx(Ur,{icon:"check",label:"Approve"})}),s.jsx("button",{type:"button",className:"af-auto__btn af-auto__btn--danger","data-action":"wait-deny",disabled:e.busy,onClick:()=>r({approved:!1}),children:s.jsx(Ur,{icon:"x",label:"Deny"})})]})]})}return t.kind==="event"?s.jsxs("form",{className:"af-auto-wait af-auto-wait--event","data-wait-key":t.wait_key,"data-wait-kind":t.kind,"aria-labelledby":n,onSubmit:u=>{var d;u.preventDefault();const c=oE(aw(u.currentTarget,"payload"));c.ok?r({payload:c.payload}):(d=e.onWaitError)==null||d.call(e,c.error)},children:[a("The run waits for an event."),s.jsx("textarea",{name:"payload",rows:3,"aria-label":"Event payload (JSON)",placeholder:'{"key": "value"}',disabled:e.busy}),s.jsx("div",{className:"af-auto__row",children:s.jsx("button",{type:"submit",className:"af-auto__btn af-auto__btn--primary","data-action":"wait-send-event",disabled:e.busy,children:s.jsx(Ur,{icon:"send",label:"Send event"})})})]}):t.kind==="ask_user"?s.jsxs("form",{className:"af-auto-wait af-auto-wait--ask_user","data-wait-key":t.wait_key,"data-wait-kind":t.kind,"aria-labelledby":n,onSubmit:u=>{u.preventDefault();const c=aw(u.currentTarget,"response");c&&r({response:c})},children:[a("The run is waiting for your input."),t.choices&&t.choices.length?s.jsx("div",{className:"af-auto__row",role:"group","aria-label":"Choices",children:t.choices.map(u=>s.jsx("button",{type:"button",className:"af-auto__btn","data-action":"wait-choice",disabled:e.busy,onClick:()=>r({response:u}),children:u},u))}):null,s.jsxs("div",{className:"af-auto__row",children:[s.jsx("input",{name:"response","aria-label":"Your answer",placeholder:"Your answer",disabled:e.busy}),s.jsx("button",{type:"submit",className:"af-auto__btn af-auto__btn--primary","data-action":"wait-answer",disabled:e.busy,children:s.jsx(Ur,{icon:"send",label:"Answer"})})]})]}):s.jsxs("div",{className:"af-auto-wait",role:"group","data-wait-key":t.wait_key,"data-wait-kind":String(t.kind),"aria-labelledby":n,children:[a("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 JE(e){const{row:t,tone:n,badge:r,statusText:i}=e.view,a=`af-auto-occ-${t.run_id}`,u=e.renderText??sg,c=e.discuss.enabled&&e.view.canDiscuss&&!e.busy,d=e.discuss.enabled?e.view.canDiscuss?null:"Available once this occurrence finishes.":e.discuss.reason??"Not available.",m=(y,w)=>e.renderTurn?e.renderTurn({kind:y,role:y==="trigger"?"user":"assistant",text:w,index:t.index,runId:t.run_id}):u(w),h=e.renderTurn?" af-auto-turn--card":"",p=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":`${a}-h`,children:[s.jsxs("div",{className:`af-auto-turn af-auto-turn--trigger${h}`,"data-turn":"trigger",children:[s.jsxs("div",{className:"af-auto-turn__meta",id:`${a}-h`,children:[s.jsxs("span",{className:"af-auto-turn__index",children:["#",t.index]})," · ",t.trigger.summary," · fired ",Qy(t.fired_at)]}),s.jsx("div",{className:"af-auto-turn__text",children:m("trigger",t.user_turn)})]}),s.jsxs("div",{className:`af-auto-turn af-auto-turn--answer${h}`,"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:i}),t.finished_at?s.jsxs("span",{children:[" · ",Qy(t.finished_at)]}):null]}),t.notify?s.jsxs("div",{className:"af-auto-notify","data-notify":"true",children:[s.jsx("strong",{children:t.notify.title}),t.notify.body?s.jsx("div",{className:"af-auto-notify__body",children:u(t.notify.body)}):null]}):null,t.failure?s.jsxs("div",{className:"af-auto-failure","data-failure":t.failure.reason_code,children:[s.jsx("strong",{children:t.failure.reason_code}),": ",t.failure.message," ",s.jsxs("span",{className:"af-auto-turn__muted",children:["(after ",t.failure.attempts," ",t.failure.attempts===1?"attempt":"attempts",")"]})]}):null,t.answer?s.jsx("div",{className:"af-auto-turn__text",children:m("answer",t.answer)}):s.jsx("div",{className:"af-auto-turn__empty",children:p}),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(Xe,{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(KE,{wait:y,busy:e.busy,idBase:a,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(Ur,{icon:"list",label:"Open run ledger"})}),e.onOpenResource?s.jsx("button",{type:"button",className:"af-auto__btn","data-action":"open-ledger-json",onClick:()=>{var 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(Ur,{icon:"file",label:"Ledger (JSON)"})}):null,t.workspace_url&&e.onOpenWorkspace?s.jsx("button",{type:"button",className:"af-auto__btn","data-action":"open-workspace",title:"Browse this run's folder",onClick:()=>{var y;return(y=e.onOpenWorkspace)==null?void 0:y.call(e,t.run_id)},children:s.jsx(Ur,{icon:"folder",label:"Workspace"})}):null]})]}),e.discussOpen?s.jsxs("form",{className:"af-auto-discuss","aria-label":`${iw}, from occurrence ${t.index}`,onSubmit:y=>{y.preventDefault();const w=aw(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(Ur,{icon:"send",label:"Start discussion"})}),s.jsx("button",{type:"button",className:"af-auto__btn","data-action":"discuss-cancel",onClick:e.onDiscussCancel,children:s.jsx(Ur,{icon:"x",label:"Cancel"})})]})]}):s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"af-auto__btn af-auto__btn--quiet","data-action":"discuss",disabled:!c,title:ow.discuss,"aria-description":ow.discuss,"aria-describedby":d?`${a}-discuss-why`:void 0,onClick:()=>e.onDiscussOpen(t.index),children:s.jsx(Ur,{icon:Bo.discuss,label:iw})}),d?s.jsx("span",{className:"af-auto__reasons",id:`${a}-discuss-why`,children:d}):null]})]})]})}const YE=5e3,XE={[uo.pause]:"Automation paused.",[uo.resume]:"Automation active.",[uo.run_now]:"Run requested.",[uo.stop_current]:"Stop requested.",[uo.unarchive]:"Unarchived: it is paused until you make it active."};function ZE(e){var fe;const{summary:t,busy:n}=e,r=e.renderText??sg,i=_.useId(),a=_.useRef(null),[u,c]=_.useState(!1),d=e.editOpen!==void 0,h=Dm(t,e.occurrences,!1).revise.enabled&&(d?e.editOpen===!0:u),p=_.useRef(null);h?(!p.current||p.current.summary.automation_id!==t.automation_id)&&(p.current={summary:t,definition:e.definition}):p.current=null;const y=p.current,w=_.useRef(e.onEditOpenChange);w.current=e.onEditOpenChange;const x=ae=>{var ve;d||c(ae),(ve=w.current)==null||ve.call(w,ae)},[k,b]=_.useState([]),[S,$]=_.useState(!1),[A,E]=_.useState(null),[z,F]=_.useState(null),[M,D]=_.useState(null);_.useEffect(()=>{if(!M)return;const ae=setTimeout(()=>D(null),YE);return()=>clearTimeout(ae)},[M]),_.useEffect(()=>{var ve;if(!h)return;b([]);const ae=Dx(a.current,['.af-auto__revise [name="title"]']);ae==null||ae.focus(),(ve=ae==null?void 0:ae.scrollIntoView)==null||ve.call(ae,{block:"nearest"})},[h,t.automation_id]);const[H,q]=_.useState(null);_.useEffect(()=>{var ae;H&&((ae=Dx(a.current,[...H,".af-auto__notice",".af-auto__title"]))==null||ae.focus(),q(null))},[H]);const I=_.useRef(null);I.current||(I.current=new aE(e.newId??cE));const Z=I.current,R=ae=>F(DE(ae)),T=(ae,ve,ge)=>{F(null),D(null),ve(Z.idFor(ae)).then(pe=>{Z.settle(ae,{ok:!0}),ge(pe)},pe=>{Z.settle(ae,{ok:!1,error:pe}),R(pe)})},P=WC(t),L=_.useRef(e.onSeen);L.current=e.onSeen;const te=_.useRef(null);te.current||(te.current=new uE),_.useEffect(()=>{const ae=te.current,ve=P?`${t.automation_id}|${P}`:null;if(!P||!ae.next(ve,t))return;const ge=t;L.current(P).then(()=>ae.succeeded(ve),pe=>{ae.failed(ve,ge),R(pe)})});const X=Dm(t,e.occurrences,n),V=UC(e.occurrences),ne=t.occurrence_count-e.occurrences.length,W=z??e.error??null,Y=W?kp(W):null,K=t.attention;return s.jsxs("section",{ref:a,className:`af-auto${e.className?` ${e.className}`:""}`,...e.hideHeader?{"aria-label":t.title}:{"aria-labelledby":i},"aria-busy":n,"data-text-rendering":e.renderText?"rich":"unformatted",children:[e.hideHeader?null:s.jsxs(s.Fragment,{children:[s.jsx(zE,{summary:t,workflowLabel:(fe=e.definition)==null?void 0:fe.target.workflow_id,triggerSources:e.triggerSources,titleId:i,nowMs:e.nowMs,onOpenWorkspace:e.onOpenWorkspace}),s.jsx(HE,{summary:t,occurrences:e.occurrences,busy:n,confirmingArchive:S,reviseOpen:h,notice:M,onDismissNotice:()=>D(null),idBase:`${i}-ctl`,onCommand:ae=>T(`command:${ae}`,ve=>e.onCommand(ae,void 0,{command_id:ve}),()=>{ae===uo.archive?($(!1),D("Archive requested."),q(['[data-action="archive"]'])):D(XE[ae]??"Command sent.")}),onToggleRevise:()=>{b([]),x(!h)},onAskArchive:()=>$(!0),onCancelArchive:()=>{$(!1),q(['[data-action="archive"]'])}})]}),h&&y?s.jsx(GE,{summary:y.summary,definition:y.definition,busy:n,errors:k,availableTools:e.availableTools,workflowPickerOptions:e.workflowPickerOptions,emailStatus:e.emailStatus,onOpenMyEmail:e.onOpenMyEmail,previewSchedule:e.previewSchedule,onCancel:()=>{x(!1),q(['[data-action="edit"]'])},onSubmit:ae=>{const ve=y.summary,ge=HC(ve,ae,y.definition);if(ge===null){b(["Nothing changed."]);return}if("errors"in ge){b(ge.errors);return}b([]),T(`revise:${ve.revision}:${JSON.stringify(ge)}`,async pe=>{const $e=ae.target&&ge.target?{...ge,target:await(e.prepareTarget?e.prepareTarget(ge.target):LE(ge.target,e.workflowPickerOptions))}:ge;return e.onRevise($e,ve.revision,{command_id:pe})},()=>{D("Saved; applies from the next run."),x(!1),q(['[data-action="edit"]'])})}}):e.definition?s.jsx(BE,{definition:e.definition,renderText:r,served:t}):null,Y?s.jsxs("div",{className:"af-auto__error",role:"alert","data-code":W==null?void 0:W.code,children:[s.jsx(Xe,{name:"error",size:14,className:"af-auto__btn-icon"}),s.jsxs("span",{className:"af-auto__error-text",children:[s.jsx("strong",{children:Y.title})," ",s.jsx("span",{children:Y.detail})]}),z?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:()=>F(null),children:s.jsx(Xe,{name:"x",size:12})}):null]}):null,K.items.length||K.waits.length?s.jsx("section",{className:"af-auto__attention","aria-label":"Needs attention",children:s.jsxs("ul",{children:[K.items.map(ae=>s.jsxs("li",{className:`af-auto__attention-item af-auto__attention-item--${ae.kind}`,"data-cursor":ae.cursor,children:[s.jsx("span",{className:`af-auto-badge af-auto-badge--${ae.kind==="failure"?"failed":"notified"}`,children:ae.kind==="failure"?"Failed":"Notified"})," ",s.jsx("strong",{children:ae.title})," ",s.jsxs("span",{className:"af-auto-turn__muted",children:["#",ae.index," · ",Qy(ae.at)]}),ae.body?s.jsx("div",{className:"af-auto__attention-body",children:r(ae.body)}):null]},ae.cursor)),K.waits.map(ae=>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":ae.kind,children:kj[ae.kind]??"Waiting for you"})," ",s.jsxs("span",{className:"af-auto-turn__muted",children:["#",ae.index]}),ae.prompt?s.jsx("div",{className:"af-auto__attention-body",children:r(ae.prompt)}):null]},`${ae.run_id}:${ae.wait_key}`))]})}):null,ne>0?s.jsx("button",{type:"button",className:"af-auto__btn af-auto__more","data-action":"load-more",disabled:n,onClick:e.onLoadMore,children:s.jsx(Ur,{icon:"history",label:`Load earlier occurrences (${ne} more)`})}):null,V.length?s.jsx("ol",{className:"af-auto__timeline","aria-label":"Occurrences",children:V.map(ae=>{const ve=`[data-index="${ae.row.index}"]`;return s.jsx(JE,{view:ae,busy:n,discuss:X.discuss,renderText:r,renderTurn:e.renderTurn,onOpenWorkspace:e.onOpenWorkspace,onOpenResource:e.onOpenResource?ge=>{var pe;F(null);try{Promise.resolve((pe=e.onOpenResource)==null?void 0:pe.call(e,ge)).catch(R)}catch($e){R($e)}}:void 0,discussOpen:A===ae.row.index,onOpenRun:e.onOpenRun,onAnswerWait:(ge,pe,$e)=>{F(null),e.onAnswerWait(ge,pe,$e).then(()=>D("Answer sent."),R)},onWaitError:ge=>F({status:0,code:"invalid_payload",message:ge}),onDiscussOpen:E,onDiscussCancel:()=>{E(null),q([`${ve} [data-action="discuss"]`])},onDiscussSubmit:(ge,pe)=>T(`discuss:${ge}:${pe}`,$e=>e.onDiscuss(ge,pe,{request_id:$e}),$e=>{E(null),D(`Discussion started (session ${$e.session_id}).`),q([`${ve} [data-action="discuss"]`])})},ae.row.run_id)})}):s.jsx("p",{className:"af-auto__empty",children:"No occurrences yet."})]})}const Oj=72;function QE(e,t=Oj){const n=Math.max(1,Math.floor(t)),r=new Array(n).fill(0),i=e.length;if(!i)return r;const a=i/n;let u=0;for(let c=0;c<n;c+=1){const d=Math.floor(c*a),m=Math.max(d+1,Math.floor((c+1)*a));let h=0;for(let p=d;p<m&&p<i;p+=1){const y=Math.abs(Number(e[p])||0);y>h&&(h=y)}r[c]=h,h>u&&(u=h)}return u<=0?r:r.map(c=>c/u)}function M_(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),i=String(t%60).padStart(2,"0");return n>0?`${n}:${String(r).padStart(2,"0")}:${i}`:`${r}:${i}`}function eA(e,t,n){return!(t>0)||!(n>0)?0:Math.min(n,Math.max(0,e/t*n))}function tA(e,t){const[n,r]=_.useState({peaks:t??null,note:""});return _.useEffect(()=>{if(t){r({peaks:t,note:""});return}let i=!0;r({peaks:null,note:""});const a=typeof window<"u"?window.AudioContext||window.webkitAudioContext:void 0;if(!e||!a||typeof fetch!="function"){r({peaks:null,note:"Waveform unavailable in this browser."});return}return(async()=>{let u=null;try{const c=await(await fetch(e)).arrayBuffer();u=new a;const d=await u.decodeAudioData(c);i&&r({peaks:QE(d.getChannelData(0)),note:""})}catch(c){i&&r({peaks:null,note:`Waveform unavailable: ${c instanceof Error?c.message:String(c)}`})}finally{u&&u.close().catch(()=>{})}})(),()=>{i=!1}},[e,t]),n}function rg(e){const t=_.useRef(null),n=_.useRef(null),[r,i]=_.useState(!1),[a,u]=_.useState(0),[c,d]=_.useState(null),[m,h]=_.useState(""),{peaks:p,note:y}=tA(e.src,e.peaks),w=p??new Array(Oj).fill(0),x=c&&c>0?Math.min(1,a/c):0,k=e.name?`Audio ${e.name}`:"Audio",b=_.useCallback(()=>{const E=t.current;E&&(E.paused?E.play().catch(z=>h(z instanceof Error?z.message:String(z))):E.pause())},[]),S=_.useCallback(E=>{const z=t.current;!z||!Number.isFinite(E)||(z.currentTime=E,u(E))},[]),$=E=>{var F;const z=(F=n.current)==null?void 0:F.getBoundingClientRect();!z||!c||S(eA(E-z.left,z.width,c))},A=E=>{if(!c)return;const z=E.key==="ArrowRight"||E.key==="ArrowUp"?5:E.key==="ArrowLeft"||E.key==="ArrowDown"?-5:0;z?(E.preventDefault(),S(Math.min(c,Math.max(0,a+z)))):E.key==="Home"?(E.preventDefault(),S(0)):E.key==="End"?(E.preventDefault(),S(c)):(E.key===" "||E.key==="Enter")&&(E.preventDefault(),b())};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:()=>i(!0),onPause:()=>i(!1),onEnded:()=>i(!1),onTimeUpdate:E=>u(E.currentTarget.currentTime),onLoadedMetadata:E=>d(Number.isFinite(E.currentTarget.duration)?E.currentTarget.duration:null),onDurationChange:E=>d(Number.isFinite(E.currentTarget.duration)?E.currentTarget.duration:null),onError:()=>h("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 ${k}`:`Play ${k}`,title:r?"Pause":"Play",onClick:b,children:s.jsx(Xe,{name:r?"pause":"play",size:16})}),s.jsx("div",{ref:n,className:"af-audio__wave",role:"slider",tabIndex:0,"aria-label":`Seek in ${k}`,"aria-valuemin":0,"aria-valuemax":Math.round(c??0),"aria-valuenow":Math.round(a),"aria-valuetext":`${M_(a)} of ${M_(c)}`,title:y||void 0,"data-waveform":p?"decoded":"flat",onKeyDown:A,onPointerDown:E=>{var z,F;(F=(z=E.currentTarget).setPointerCapture)==null||F.call(z,E.pointerId),$(E.clientX)},onPointerMove:E=>{E.buttons&1&&$(E.clientX)},children:s.jsx("svg",{viewBox:`0 0 ${w.length*2} 32`,preserveAspectRatio:"none","aria-hidden":"true",focusable:"false",children:w.map((E,z)=>{const F=Math.max(1.5,E*30),M=(z+.5)/w.length<=x;return s.jsx("rect",{className:M?"af-audio__bar af-audio__bar--played":"af-audio__bar",x:z*2+.3,y:16-F/2,width:1.4,height:F,rx:.6},z)})})}),s.jsxs("span",{className:"af-audio__time","aria-hidden":"true",children:[M_(a)," / ",M_(c)]}),m?s.jsx("p",{className:"af-audio__error",role:"alert",children:m}):null]})}const ru=e=>new Set(e.split(/\s+/).filter(Boolean)),nA=ru("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"),sA=ru("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"),rA=ru("if then else elif fi for while do done case esac in function return export local readonly set unset echo exit source"),iA=ru("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"),Wx=ru("true false null yes no on off"),oA={c:{line:["//"],block:["/*","*/"],strings:['"',"'","`"],keywords:nA},python:{line:["#"],strings:['"',"'"],triple:!0,keywords:sA},shell:{line:["#"],strings:['"',"'"],keywords:rA},sql:{line:["--"],block:["/*","*/"],strings:["'",'"'],keywords:iA},data:{line:["#"],strings:['"',"'"],keywords:Wx},json:{line:[],strings:['"'],keywords:Wx},css:{line:[],block:["/*","*/"],strings:['"',"'"],keywords:ru("")},markup:{line:[],block:["<!--","-->"],strings:['"',"'"],keywords:ru("")}},aA={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 yv(e){const t=String(e||"").trim().toLowerCase(),n=t.split("/").pop()||t;if(n==="dockerfile"||n==="makefile")return"shell";const r=n.lastIndexOf("."),i=r>=0?n.slice(r+1):n;return aA[i]||""}const lA=e=>e>="0"&&e<="9",cA=e=>/[A-Za-z_$]/.test(e),qx=e=>/[A-Za-z0-9_$]/.test(e);function Pj(e,t){const n=String(e??""),r=oA[t];if(!r)return n?[{kind:"plain",text:n}]:[];const i=[];let a="";const u=(d,m)=>{if(m){if(d==="plain"){a+=m;return}a&&i.push({kind:"plain",text:a}),a="",i.push({kind:d,text:m})}};let c=0;for(;c<n.length;){const d=n[c];if(r.line.find(h=>n.startsWith(h,c))){const h=n.indexOf(`
|
|
61
|
+
`,c),p=h===-1?n.length:h;u("comment",n.slice(c,p)),c=p;continue}if(r.block&&n.startsWith(r.block[0],c)){const h=n.indexOf(r.block[1],c+r.block[0].length),p=h===-1?n.length:h+r.block[1].length;u("comment",n.slice(c,p)),c=p;continue}if(r.strings.includes(d)){const h=r.triple&&n.startsWith(d.repeat(3),c)?d.repeat(3):"";if(h){const w=n.indexOf(h,c+3),x=w===-1?n.length:w+3;u("string",n.slice(c,x)),c=x;continue}let p=c+1;for(;p<n.length&&n[p]!==d&&(d==="`"||n[p]!==`
|
|
62
|
+
`);)p+=n[p]==="\\"?2:1;const y=Math.min(n.length,p+1);u("string",n.slice(c,y)),c=y;continue}if(lA(d)&&!(c>0&&qx(n[c-1]))){let h=c+1;for(;h<n.length&&/[0-9a-fA-FxXoObB._]/.test(n[h]);)h+=1;u("number",n.slice(c,h)),c=h;continue}if(cA(d)){let h=c+1;for(;h<n.length&&qx(n[h]);)h+=1;const p=n.slice(c,h),y=t==="sql"?r.keywords.has(p.toLowerCase()):r.keywords.has(p);u(y?"keyword":"plain",p),c=h;continue}u("plain",d),c+=1}return a&&i.push({kind:"plain",text:a}),i}function R_({text:e,language:t="",lineNumbers:n=!0,className:r,ariaLabel:i}){const a=yv(t),u=Pj(e,a),c=n?String(e??"").split(`
|
|
63
|
+
`).length:0;return s.jsx("pre",{className:`af-code${n?" af-code--numbered":""}${r?` ${r}`:""}`,"data-language":a||"text","aria-label":i,style:n?{"--af-code-gutter":`${String(c).length+1}ch`}:void 0,children:s.jsx("code",{children:n?uA(u).map((d,m)=>s.jsxs("span",{className:"af-code__line","data-line":m+1,children:[d.map((h,p)=>Hx(h,p)),`
|
|
64
|
+
`]},m)):u.map((d,m)=>Hx(d,m))})})}function Hx(e,t){return e.kind==="plain"?s.jsx(Ne.Fragment,{children:e.text},t):s.jsx("span",{className:`af-code__${e.kind}`,children:e.text},t)}function uA(e){const t=[[]];for(const n of e)n.text.split(`
|
|
65
|
+
`).forEach((i,a)=>{a>0&&t.push([]),i&&t[t.length-1].push({kind:n.kind,text:i})});return t}const Dj=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],jm=6e4,Sm=60*jm,L_=24*Sm;function lh(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)?lh(Number(t)):Date.parse(t)}function Vx(e){return e<10?`0${e}`:String(e)}function Gx(e,t){const n=lh(e);if(!Number.isFinite(n))return"";const r=new Date(n),i=r.getFullYear()===new Date(t).getFullYear();return`${Dj[r.getMonth()]} ${r.getDate()}${i?"":`, ${r.getFullYear()}`}`}function Fj(e){const t=lh(e);if(!Number.isFinite(t))return"";const n=new Date(t);return`${Dj[n.getMonth()]} ${n.getDate()}, ${n.getFullYear()}, ${Vx(n.getHours())}:${Vx(n.getMinutes())}`}function Np(e,t){const n=lh(e);if(!Number.isFinite(n)||!Number.isFinite(t))return"";const r=t-n;if(r<0){const a=-r;if(a<jm)return"due now";if(a<Sm)return`in ${Math.round(a/jm)} min`;if(a<L_)return`in ${Math.round(a/Sm)} h`;const u=Math.round(a/L_);return u<7?`in ${u} ${u===1?"day":"days"}`:Gx(n,t)}if(r<jm)return"just now";if(r<Sm)return`${Math.floor(r/jm)} min ago`;if(r<L_)return`${Math.floor(r/Sm)} h ago`;const i=Math.floor(r/L_);return i===1?"yesterday":i<7?`${i} days ago`:Gx(n,t)}const dA=new Set("png jpg jpeg gif webp bmp ico avif".split(" ")),fA=new Set("mp3 wav ogg oga opus m4a aac flac weba".split(" ")),mA=new Set("txt log csv tsv rst adoc org tex diff patch lock".split(" "));function hA(e){const t=String(e||"").split("/").pop()||"",n=t.lastIndexOf(".");return n>0?t.slice(n+1).toLowerCase():t.toLowerCase()}function lw(e,t=""){const n=hA(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":dA.has(n)||r.startsWith("image/")&&r!=="image/svg+xml"?"image":fA.has(n)||r.startsWith("audio/")?"audio":yv(e)?"code":mA.has(n)||r.startsWith("text/")?"text":["application/javascript","application/xml","application/x-yaml","application/toml"].includes(r)?"code":"binary"}function Kx(e){return e==="markdown"||e==="code"||e==="json"||e==="text"}function wv(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 _A(e){const t=e.kind??lw(e.name,e.contentType),n=wv(e.sizeBytes),r=e.modified!==void 0?Np(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(Xe,{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:Fj(e.modified),dateTime:new Date(lh(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(Xe,{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(Xe,{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(pA,{kind:t,p:e})]})})]})}function pA({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(I_,{});case"audio":return t.url?s.jsx(rg,{src:t.url,name:t.name}):s.jsx(I_,{});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(I_,{});case"markdown":return t.renderMarkdown?s.jsx("div",{className:"af-file-viewer__markdown",children:t.renderMarkdown(n)}):s.jsx(R_,{text:n,language:""});case"json":{let r=n,i="";try{r=JSON.stringify(JSON.parse(n),null,2)}catch{i=t.partialNote?"":"Not valid JSON; shown as text."}return s.jsxs(s.Fragment,{children:[i?s.jsx("p",{className:"af-file-viewer__muted",children:i}):null,s.jsx(R_,{text:r,language:"json"})]})}case"code":return s.jsx(R_,{text:n,language:t.name});case"text":return s.jsx(R_,{text:n,language:"",lineNumbers:!1});default:return s.jsx(I_,{})}}function I_(){return s.jsx("p",{className:"af-file-viewer__muted",children:"No preview for this file type. Use Download to open it."})}function Nm(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 Wc(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 Jx(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(Wc,{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 On={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."},ti=On;function gA(e){return e==="any_except_denied"?ti.postureAnyExceptDenied:ti.postureAllowedOnly}function yA(e){return e==="any_except_denied"?ti.postureAnyExceptDeniedHelp:ti.postureAllowedOnlyHelp}function Yx(e){return e==="ro"?ti.accessRead:e==="deny"?ti.accessDenied:ti.accessReadWrite}function wA(e){return e==="gateway"?ti.gatewayHelp:e==="account"?ti.accountHelp:e==="session"?ti.sessionHelp:ti.runHelp}const Xx={deny:0,ro:1,rw:2},Jg=["rw","ro","deny"];function vA(e){if(e===null)return{allowed:[...Jg],reasons:{}};const t=e==="deny"?ti.capRefused:ti.capReadOnly,n=Jg.filter(i=>Xx[i]<=Xx[e]),r={};for(const i of Jg)n.includes(i)||(r[i]=t);return{allowed:n,reasons:r}}function xA(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 i=e!=="gateway"&&n.configured===!1,a=t.can_edit===!1,u=new Map(((r==null?void 0:r.folders)??[]).map(w=>[w.path,w.cap])),c=r,d=i?c.folders.map(w=>({path:w.path,mode:w.mode})):n.folders,m=i?c.posture:n.posture,h=i?c.default_mode??n.default_mode:n.default_mode,p=!i&&!a,y=d.map(w=>{const x=e==="gateway"?null:u.get(w.path)??null,{allowed:k,reasons:b}=vA(x);return{path:w.path,mode:w.mode,cap:x,allowed:k,reasons:b,builtin:!1,editable:p}});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:m,following:i,rows:y,everythingElse:m==="any_except_denied"?{mode:h,editable:p}:null,canAdd:p,gatewayLine:e==="gateway"?null:`${ti.gatewayPrefix} ${c.gateway_summary}`,summary:e==="gateway"?n.summary:c.summary,locked:a}}function bA(e,t){return t==="any_except_denied"?"deny":e==="gateway"?"rw":"ro"}function ch(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 kA(e,t,n,r){return ch(e,{...t,folders:t.folders.map(i=>i.path===n?{path:n,mode:r}:i)})}function jA(e,t,n){return ch(e,{...t,posture:n})}function SA(e,t,n){return ch(e,{...t,default_mode:n})}function NA(e,t,n,r){const i=String(n).trim();return ch(e,{...t,folders:[...t.folders,{path:i,mode:bA(e,t.posture)}]})}function $A(e,t,n){return ch(e,{...t,folders:t.folders.filter(r=>r.path!==n)})}function CA(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 EA(e){let t=String(e||"");for(;t.endsWith("/");)t=t.slice(0,-1);return t}function AA(e="me",t=Pm){return`${EA(t)}/workspace/effective/${encodeURIComponent(e)}`}const Zx=e=>e==="ro"||e==="rw"||e==="deny",TA=e=>e==="ro"||e==="rw",MA=e=>e==="allowed_only"||e==="any_except_denied",Qx="The gateway answered with an older workspace model (it needs the round-11 workspace API).";function RA(e){const t=e&&typeof e=="object"?e:{};if("shared_workspace"in t)throw new Error(Qx);if(!(MA(t.posture)&&(TA(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"&&Zx(r.mode)&&Zx(r.cap))))throw new Error(`The gateway answered without the effective workspaces (posture, default_mode, folders with cap, summary, gateway_summary). ${Qx}`);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 zm(e,t="me",n=Pm){const r=AA(t,n);return async(i,a)=>RA(await e(r,{method:"POST",body:a?{workspace:i,session:a}:{workspace:i}}))}function ig(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 eb(e){const t=ig(e).trim()||"The gateway refused the change.";return`${t}${/[.!?]$/.test(t)?"":"."} ${ti.notSaved}`}const LA=e=>!!e&&typeof e=="object"&&"policy"in e&&"effective"in e;function IA(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 zj(e){Yd();const t=e.idPrefix||"af-workspace",[n,r]=_.useState(null),[i,a]=_.useState({}),[u,c]=_.useState(null),[d,m]=_.useState(""),[h,p]=_.useState(null),y=String(e.unavailableReason||"").trim(),w=e.level,x=e.level==="run"?IA(e.value,e.effective):e.state,k=e.level==="run"?e.effective:e.state,b=h&&h.base===k?h.value:x,S=b?xA(w,b):null,$=P=>{if(e.level==="run"){const L=e,te=P.configured===!1?null:{posture:P.posture,default_mode:P.default_mode,folders:P.folders};return Promise.resolve(L.onChange(te))}return e.save(P)};async function A(P,L){if(n!==null||y)return!1;r(P),c(null),a(te=>{const X={...te};return delete X[P],X});try{const te=await $(L);return LA(te)&&p({base:k,value:te}),c(P),!0}catch(te){return a(X=>({...X,[P]:eb(te)})),!1}finally{r(null)}}const E=P=>i[P]?s.jsx("span",{className:"af-workspace__refusal",role:"alert","data-workspace":"refusal",children:i[P]}):u===P?s.jsx("span",{className:"af-workspace__saved",role:"status","data-workspace":"saved",children:On.saved}):null,z=(P,L)=>s.jsx("span",{className:"af-workspace__access-tag","data-workspace":"access","data-access":P,"data-af-tip":L,tabIndex:L?0:void 0,children:Yx(P)}),F=(P,L,te,X,V)=>s.jsx("span",{className:"af-workspace__access",role:"group","aria-label":P,"data-workspace":V,"data-access":L,children:te.map(ne=>{const W=!!ne.reason||!!y;return s.jsx("button",{type:"button",className:"af-workspace__access-btn","aria-pressed":L===ne.value?"true":"false","aria-disabled":W?"true":void 0,"data-af-tip":ne.reason||void 0,"data-action":`${V}-${ne.value}`,onClick:()=>W||n!==null||ne.value===L?void 0:X(ne.value),children:ne.text},ne.value)})}),M=P=>{if(P.builtin)return z("deny",On.builtinRefused);if(!P.editable||!b)return z(P.mode);const L=b.policy;return s.jsxs(s.Fragment,{children:[F(`${On.accessLabel} ${P.path}`,P.mode,["rw","ro","deny"].map(te=>({value:te,text:Yx(te),reason:P.reasons[te]})),te=>void A(P.path,kA(w,L,P.path,te)),"workspace-mode"),s.jsx("button",{type:"button",className:"af-workspace__icon-btn","data-action":"workspace-remove","aria-label":`${On.remove} ${P.path}`,"data-af-tip":`${On.remove} ${P.path}`,"aria-disabled":y||n!==null?"true":void 0,onClick:()=>y||n!==null?void 0:void A(P.path,$A(w,L,P.path)),children:s.jsx(Xe,{name:"x",size:16})})]})};async function D(P){if(!b||!S||!S.canAdd)return;const L=P.trim();L&&await A("add",NA(w,b.policy,L))&&m("")}async function H(){if(!e.choose||n!==null||y)return;let P;try{P=await e.choose()}catch(L){a(te=>({...te,add:eb(L)}));return}P&&await D(P)}const q=S?S.rows.filter(P=>P.mode!=="deny"):[],I=S?S.rows.filter(P=>P.mode==="deny"):[],Z=P=>s.jsxs("li",{className:"af-workspace__row","data-workspace":P.builtin?"builtin":"row","data-path":P.path,"data-mode":P.mode,"data-cap":P.cap??void 0,children:[s.jsx("code",{className:"af-workspace__path",children:P.path}),s.jsx("span",{className:"af-workspace__controls",children:M(P)}),E(P.path)]},`${P.builtin?"builtin:":""}${P.path}`),R=w==="account"?On.followGateway:On.useDefault,T=w==="account"?On.followGatewayHelp:On.useDefaultHelp;return s.jsx(Nm,{id:t,className:`af-workspace af-workspace--${w}${e.className?` ${e.className}`:""}`,title:w==="gateway"?On.gatewayTitle:On.title,help:wA(w),children:e.loadError?s.jsx("p",{className:"af-workspace__refusal",role:"alert","data-workspace":"load-error",children:e.loadError}):!S||!b?s.jsx("p",{className:"af-workspace__note","data-workspace":"loading",children:On.loading}):s.jsxs("div",{className:"af-workspace__body","data-level":w,"data-following":S.following?"true":"false",children:[S.gatewayLine?s.jsx("p",{className:"af-workspace__gateway","data-workspace":"gateway-line",children:S.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(_o,{variant:"row",label:R,description:T,checked:S.following,busy:n==="follow",unavailableReason:y||(S.locked?On.locked:null),reasonVisible:!1,describedBy:y?`${t}-blocked`:void 0,action:w==="account"?"workspace-follow-gateway":"workspace-use-default",onChange:P=>void A("follow",CA(b,P))}),E("follow")]}):null,s.jsxs("div",{className:"af-workspace__posture","data-workspace":"posture","data-posture":S.posture,children:[S.following||S.locked?s.jsx("span",{className:"af-workspace__badge",children:gA(S.posture)}):F(On.postureLabel,S.posture,[{value:"allowed_only",text:On.postureAllowedOnly},{value:"any_except_denied",text:On.postureAnyExceptDenied}],P=>void A("posture",jA(w,b.policy,P)),"workspace-posture"),s.jsx("span",{className:"af-workspace__note","data-workspace":"posture-help",children:yA(S.posture)}),E("posture")]}),s.jsxs("ul",{className:"af-workspace__list","aria-label":On.title,"data-workspace":"list",children:[q.length?s.jsx("li",{className:"af-workspace__caption","data-workspace":"caption-allowed",children:On.allowedTitle}):null,q.map(Z),I.length?s.jsx("li",{className:"af-workspace__caption","data-workspace":"caption-refused",children:On.deniedTitle}):null,I.map(Z),S.everythingElse?s.jsxs("li",{className:"af-workspace__row","data-workspace":"everything-else","data-mode":S.everythingElse.mode,children:[s.jsx("span",{className:"af-workspace__name",children:On.everythingElse}),s.jsx("span",{className:"af-workspace__controls",children:S.everythingElse.editable?F(`${On.accessLabel} ${On.everythingElse}`,S.everythingElse.mode,[{value:"rw",text:On.accessReadWrite},{value:"ro",text:On.accessRead}],P=>void A("everything-else",SA(w,b.policy,P)),"workspace-default"):z(S.everythingElse.mode)}),E("everything-else")]}):null,S.canAdd?s.jsxs("li",{className:"af-workspace__add","data-workspace":"add",children:[s.jsx("input",{type:"text",className:"af-workspace__input","aria-label":On.addPlaceholder,placeholder:On.addPlaceholder,value:d,disabled:!!y||n==="add",spellCheck:!1,autoCapitalize:"off",autoCorrect:"off",onChange:P=>m(P.target.value),onKeyDown:P=>{P.key==="Enter"?(P.preventDefault(),D(d)):P.key==="Escape"&&(P.preventDefault(),m(""),a(L=>{const te={...L};return delete te.add,te}))}}),s.jsx("button",{type:"button",className:"af-workspace__add-btn","data-action":"workspace-add",disabled:!!y||!d.trim()||n!==null,onClick:()=>void D(d),children:On.add}),e.choose?s.jsx("button",{type:"button",className:"af-workspace__add-btn","data-action":"workspace-choose",disabled:!!y||n!==null,onClick:()=>void H(),children:On.choose}):null,E("add")]}):null]}),S.posture==="allowed_only"&&!q.length?s.jsx("p",{className:"af-workspace__note","data-workspace":"empty",children:On.emptyAllowed}):null,w==="session"||w==="run"?s.jsx("p",{className:"af-workspace__note","data-workspace":"private",children:On.privateNote}):null,s.jsx("p",{className:"af-workspace__effective","data-workspace":"effective",children:S.summary}),e.footer?s.jsx("div",{className:"af-workspace__footer",children:e.footer}):null]})})}const OA=["provider","model","voice","profile","speed","quality_preset","instructions"];function PA(e){const t={};for(const n of OA){const r=e[n];r!==void 0&&r!==""&&r!==null&&(t[n]=r)}return t}function DA(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 FA=[{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 zA(e){return[e.provider,e.model,e.profile||e.voice].filter(Boolean).join(" · ")}function BA(e){return[e.stt_provider,e.stt_model].filter(Boolean).join(" · ")}const UA=[{value:"",label:"Gateway default"},{value:"standard",label:"Balanced"},{value:"low",label:"Faster (lower quality)"},{value:"high",label:"Higher quality (slower)"}],tb=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):[],om=e=>`${Math.round(e*100)} %`;function WA(e){var bt,Ue,at,Nt,ut,Se;const t=e.overrideOwner||"this app",n=!!e.unavailableReason,r=_.useRef(e.fetchCatalog);r.current=e.fetchCatalog;const i=_.useRef(e.fetchDefaults);i.current=e.fetchDefaults;const[a,u]=_.useState({}),[c,d]=_.useState({value:null,failed:!1}),m=e.defaults!==void 0?{value:e.defaults,failed:!1}:c,h=e.defaults!==void 0,[p,y]=_.useState(""),[w,x]=_.useState({devices:[],labelled:!0}),[k,b]=_.useState({devices:[],labelled:!0}),[S,$]=_.useState(""),[A,E]=_.useState({text:"",tone:"info"}),[z,F]=_.useState({phase:"idle",message:"",tone:"info"}),[M,D]=_.useState(0),H=e.outputSelectable??oC(),q=Xk(),I=e.value,Z=e.nested?"flat":"card",R=me=>e.onChange({...I,...me}),T=I.reply_volume===void 0?1:Math.min(1,Math.max(0,Number(I.reply_volume)||0)),P=I.input_gain===void 0?1:Math.min(1.5,Math.max(.5,Number(I.input_gain)||1));_.useEffect(()=>{if(n)return;let me=!0;return r.current().then(Ve=>me&&u(Ve||{})).catch(()=>me&&u({})),h||i.current().then(Ve=>me&&d({value:Ve||{},failed:!1})).catch(()=>me&&d({value:null,failed:!0})),()=>{me=!1}},[n,h]);const L=e.listDevices||V2,te=()=>{H&&L("audiooutput").then(x).catch(()=>x({devices:[],labelled:!1})),L("audioinput").then(b).catch(()=>b({devices:[],labelled:!1}))};_.useEffect(()=>{n||te()},[H,n]);const X=()=>{$(""),G2().then(te).catch(me=>$(Xy(me)))},V=()=>{E({text:"Playing a short chime…",tone:"info"}),Z2({deviceId:H&&I.output_device||"",volume:T}).then(()=>E({text:"Chime played. Heard nothing? Pick another output or raise the volume.",tone:"ok"})).catch(me=>E({text:`The speaker test failed: ${String((me==null?void 0:me.message)||me).replace(/\.$/,"")}.`,tone:"error"}))},ne=()=>{F({phase:"recording",message:"Recording 3 seconds — say something.",tone:"info"}),Y2({deviceId:I.input_device||"",ms:3e3,gain:P,onLevel:D}).then(async({blob:me,peak:Ve})=>{if(Ve<J2){F({phase:"idle",message:"The microphone recorded silence. Pick another input, or raise its level in the system sound settings.",tone:"error"});return}F({phase:"playing",message:"Playing it back…",tone:"info"}),await X2(me,{deviceId:H&&I.output_device||"",volume:T}),F({phase:"idle",message:`The microphone works (peak level ${om(Ve)}).`,tone:"ok"}),te()}).catch(me=>F({phase:"idle",message:Xy(me),tone:"error"}))},W=Tx(m.value,"tts",m.failed),Y=Tx(m.value,"stt",m.failed),K=[(bt=m.value)==null?void 0:bt.tts,(Ue=m.value)==null?void 0:Ue.stt].map(me=>me&&!me.configured?me.note:"").filter(Boolean),fe=[(at=m.value)==null?void 0:at.tts,(Nt=m.value)==null?void 0:Nt.stt].map(me=>{var Ve;return me&&me.configured?String(((Ve=me.hint)==null?void 0:Ve.sentence)||"").trim():""}).filter(Boolean),ae=!!((Se=(ut=a.controls)==null?void 0:ut.quality_preset)!=null&&Se.supported),ve=I.output_device||"",ge=[{value:"",label:"System default"},...w.devices.map(me=>({value:me.id,label:me.label})),...ve&&!w.devices.some(me=>me.id===ve)?[{value:ve,label:"Saved speaker (not connected)"}]:[]],pe=I.input_device||"",$e=[{value:"",label:"System default"},...k.devices.map(me=>({value:me.id,label:me.label})),...pe&&!k.devices.some(me=>me.id===pe)?[{value:pe,label:"Saved microphone (not connected)"}]:[]],De=!k.labelled||H&&!w.labelled,ot=z.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(Nm,{variant:Z,title:"Engines",help:"Which engines speak and listen.",children:[s.jsx(Jx,{label:"Text → speech",setting:"tts",defaultSummary:W,overrideSummary:zA(I),overrideOwner:t,open:p==="tts",onToggle:()=>y(p==="tts"?"":"tts"),onReset:()=>R({provider:"",model:"",voice:"",profile:""}),disabled:n,children:s.jsx(uC,{value:I,onChange:me=>e.onChange({...I,...me}),fetchCatalog:e.fetchCatalog,intro:null,quality:!1,showReset:!1,voiceDefaultLabel:"Gateway default"})}),s.jsx(Jx,{label:"Speech → text",setting:"stt",defaultSummary:Y,overrideSummary:BA(I),overrideOwner:t,open:p==="stt",onToggle:()=>y(p==="stt"?"":"stt"),onReset:()=>R({stt_provider:"",stt_model:""}),disabled:n,children:s.jsx(Uk,{value:{provider:I.stt_provider||"",model:I.stt_model||""},onChange:me=>R({stt_provider:me.provider,stt_model:me.model}),fetchProviders:async()=>{const me=await r.current();return tb(me.stt_providers).map(Ve=>({name:Ve}))},fetchModels:async me=>{var ye;const Ve=await r.current(me);return tb(((ye=Ve.stt_models_by_provider)==null?void 0:ye[me])||Ve.stt_models)},inheritLabel:"Gateway default",providerLabel:"Transcription provider",modelLabel:"Transcription model"})}),m.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,K.map(me=>s.jsx("p",{className:"af-settings-group__help","data-voice-note":"unset",children:me},me)),fe.map(me=>s.jsx("p",{className:"af-settings-group__help","data-voice-note":"hint",role:"note",children:me},me))]}),s.jsxs(Nm,{variant:Z,title:"Output",children:[s.jsx(Wc,{label:"Output device",setting:"output-device",help:H?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:V,children:"Test"}),children:s.jsx(Pi,{ariaLabel:"Output device",placeholder:"System default",value:H?ve:"",options:ge,disabled:n||!H,searchable:!1,onOpen:te,onChange:me=>R({output_device:me})})}),A.text?s.jsx("p",{className:`af-voice-note af-voice-note--${A.tone}`,role:"status","data-voice-note":"speaker",children:A.text}):null,s.jsxs(Wc,{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(T*100),disabled:n,"aria-valuetext":om(T),onChange:me=>R({reply_volume:Number(me.currentTarget.value)/100})}),s.jsx("span",{className:"af-voice-range__value",children:om(T)})]})]}),s.jsxs(Nm,{variant:Z,title:"Microphone",children:[s.jsx(Wc,{label:"Input device",setting:"input-device",trailing:s.jsx("button",{type:"button",className:"af-setting-btn","data-action":"test-microphone",disabled:n||ot,onClick:ne,children:z.phase==="recording"?"Recording…":z.phase==="playing"?"Playing…":"Test"}),children:s.jsx(Pi,{ariaLabel:"Input device",placeholder:"System default",value:pe,options:$e,disabled:n,searchable:!1,onOpen:te,onChange:me=>R({input_device:me})})}),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(M*100),children:s.jsx("span",{className:"af-voice-meter__fill",style:{width:`${Math.round(M*100)}%`}})}),z.message?s.jsx("p",{className:`af-voice-note af-voice-note--${z.tone}`,role:"status","data-voice-note":"microphone",children:z.message}):null,De&&!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:X,children:"Show names"})]}):null,S?s.jsx("p",{className:"af-voice-note af-voice-note--error",role:"status",children:S}):null,s.jsx(Wc,{label:"Spoken language",setting:"stt-language",help:"Naming it skips detection: transcription is faster.",children:s.jsx(Pi,{ariaLabel:"Spoken language",placeholder:"Detect automatically",value:I.stt_language||"",options:FA,disabled:n,searchable:!1,onChange:me=>R({stt_language:me})})}),q?s.jsxs(Wc,{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(P*100),disabled:n,"aria-valuetext":om(P),onChange:me=>R({input_gain:Number(me.currentTarget.value)/100})}),s.jsx("span",{className:"af-voice-range__value",children:om(P)})]}):null]}),s.jsxs(Nm,{variant:Z,title:"Replies",children:[s.jsx("div",{className:"af-setting-row af-setting-row--switch","data-setting":"read-aloud",children:s.jsx(_o,{label:"Read aloud",description:"Speak each new reply.",variant:"row",checked:I.read_aloud===!0,unavailableReason:n?e.unavailableReason:null,reasonVisible:!1,onChange:me=>R({read_aloud:me})})}),s.jsx(Wc,{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(Pi,{ariaLabel:"Voice latency",placeholder:"Gateway default",value:ae&&I.quality_preset||"",options:UA,disabled:n||!ae,searchable:!1,onChange:me=>R({quality_preset:me})})})]})]})}function og(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 qA(e){if(e==null)return"";if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}}function HA(e){const t=String(e.role||"message").trim()||"message",n=String(e.title||"").trim(),r=String(e.ts||"").trim(),i=[t];return n&&i.push(n),r&&i.push(r),i.join(" · ")}function VA(e){return e.endsWith(`
|
|
66
|
+
`)?e:`${e}
|
|
67
|
+
`}function GA(e){return String(e||"").trimStart().startsWith("```")}function KA(e,t){const r=[`# ${String((t==null?void 0:t.heading)||"Chat").trim()||"Chat"}`,""];for(const i of e){const a=HA(i);r.push(`## ${a}`,"");const u=String(i.content||""),c=og(u);c!==null&&!GA(u)?r.push("```json",qA(c).trimEnd(),"```",""):r.push(VA(u).trimEnd(),""),r.push("---","")}for(;r.length&&!r[r.length-1].trim();)r.pop();return r.length&&r[r.length-1]==="---"&&r.pop(),`${r.join(`
|
|
68
|
+
`).trimEnd()}
|
|
69
|
+
`}async function tc(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 i=document.execCommand("copy")===!0;return document.body.removeChild(r),i}catch{return!1}}function JA(e){const t=String(e.filename||"").trim()||"export.txt",n=String(e.text||""),r=String(e.mime),i=new Blob([n],{type:r}),a=URL.createObjectURL(i),u=document.createElement("a");u.href=a,u.download=t,document.body.appendChild(u),u.click(),u.remove(),window.setTimeout(()=>URL.revokeObjectURL(a),1e3)}const YA=3,XA=Number.MAX_SAFE_INTEGER;function Bj(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Uj(e){return Array.isArray(e)}function ZA(e){if(e==null)return"";if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}}function Cd({kind:e,children:t}){return s.jsx("span",{className:`pc-json-token ${e}`,children:t})}function QA(e){const t=JSON.stringify(e.value),n=t.length>96||t.includes("\\n")||t.includes("\\r")||t.includes("\\t"),[r,i]=_.useState(!n||e.expansionMode==="unfolded");return _.useEffect(()=>{n&&i(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:()=>i(a=>!a),"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:()=>i(!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(Cd,{kind:"string",children:t})}function eT(e,t,n){return e===null?s.jsx(Cd,{kind:"null",children:"null"}):typeof e=="string"?s.jsx(QA,{value:e,expansionMode:t,expansionVersion:n}):typeof e=="number"?s.jsx(Cd,{kind:"number",children:String(e)}):typeof e=="boolean"?s.jsx(Cd,{kind:"boolean",children:e?"true":"false"}):s.jsx(Cd,{kind:"string",children:JSON.stringify(String(e))})}function tT(e){return Uj(e)?e.length===1?"1 item":`${e.length} items`:Bj(e)?Object.keys(e).length===1?"1 key":`${Object.keys(e).length} keys`:""}function Wj(e){const{label:t,value:n,depth:r,collapseAfterDepth:i,expansionMode:a,expansionVersion:u,trailingComma:c}=e,d=r*14,m=Bj(n),h=Uj(n),p=m||h,y=r<i,[w,x]=_.useState(y);_.useEffect(()=>{x(y)},[y,u]);const k=t?s.jsxs(s.Fragment,{children:[s.jsx(Cd,{kind:"key",children:JSON.stringify(t)}),": "]}):null;if(!p)return s.jsxs("div",{className:"pc-json-viewer__line",style:{paddingLeft:d},children:[k,eT(n,a,u),c?",":""]});const b=h?"[":"{",S=h?"]":"}",$=tT(n),A=w?`${b}`:`${b}…${S}${$?` (${$})`:""}`,E=h?n.map((z,F)=>({key:String(F),label:void 0,value:z})):Object.entries(n).map(([z,F])=>({key:z,label:z,value:F}));return s.jsxs("details",{className:"pc-json-viewer__details",open:w,onToggle:z=>x(z.currentTarget.open),children:[s.jsxs("summary",{className:"pc-json-viewer__summary",style:{paddingLeft:d},children:[k,s.jsx("span",{className:"pc-json-viewer__caret","aria-hidden":"true",children:w?"▾":"▸"}),s.jsx("span",{className:"pc-json-viewer__punct",children:A}),!w&&c?s.jsx("span",{className:"pc-json-viewer__punct",children:","}):null]}),w?s.jsx("div",{className:"pc-json-viewer__children",children:E.length===0?s.jsxs("div",{className:"pc-json-viewer__line",style:{paddingLeft:d},children:[s.jsx("span",{className:"pc-json-viewer__punct",children:S}),c?",":""]}):s.jsxs(s.Fragment,{children:[E.map((z,F)=>{const M=F===E.length-1;return s.jsx(Wj,{label:z.label,value:z.value,depth:r+1,collapseAfterDepth:i,expansionMode:a,expansionVersion:u,trailingComma:!M},`${r}:${t||"root"}:${z.key}`)}),s.jsxs("div",{className:"pc-json-viewer__line",style:{paddingLeft:d},children:[s.jsx("span",{className:"pc-json-viewer__punct",children:S}),c?",":""]})]})}):null]})}function nT(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 mr(e){const{value:t,className:n,showCopy:r=!0}=e,[i,a]=_.useState({mode:"folded",version:0}),[u,c]=_.useState("idle"),d=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):YA,m=i.mode==="unfolded"?XA:d,h=_.useMemo(()=>typeof t=="string"?nT(t):t,[t]),p=_.useMemo(()=>ZA(t),[t]),y=["pc-json-viewer",n].filter(Boolean).join(" ");_.useEffect(()=>{a(x=>({mode:"folded",version:x.version+1}))},[h]);const w=()=>{a(x=>({mode:x.mode==="unfolded"?"folded":"unfolded",version:x.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":i.mode==="unfolded",children:i.mode==="unfolded"?"Fold all":"Unfold all"}),r?s.jsx("button",{type:"button",className:"pc-btn pc-json-viewer__copy",onClick:()=>void tc(p).then(x=>{c(x?"copied":"failed"),window.setTimeout(()=>c("idle"),2e3)}),children:u==="copied"?"Copied":u==="failed"?"Copy failed — select and copy":"Copy JSON"}):null]}),s.jsx("div",{className:"pc-json-viewer__tree",role:"tree","aria-label":"JSON viewer",children:s.jsx(Wj,{value:h,depth:0,collapseAfterDepth:m,expansionMode:i.mode,expansionVersion:i.version,trailingComma:!1})})]})}function sT({code:e,lang:t}){const[n,r]=_.useState("idle"),i=_.useRef(null);_.useEffect(()=>()=>{i.current!==null&&window.clearTimeout(i.current)},[]);const a=Pj(e,yv(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 u=await tc(e);r(u?"copied":"failed"),i.current!==null&&window.clearTimeout(i.current),i.current=window.setTimeout(()=>r("idle"),900)},children:s.jsx(Xe,{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:a.map((u,c)=>u.kind==="plain"?s.jsx(Ne.Fragment,{children:u.text},c):s.jsx("span",{className:`af-code__${u.kind}`,children:u.text},c))})})]})}function am(e,t){const n=String(e??"");if(!t||!t.needles.length)return[n];const r=[],i=n.toLowerCase();let a=0;for(;a<n.length;){let u=-1,c="";for(let h=0;h<t.needlesLower.length;h++){const p=t.needlesLower[h];if(!p)continue;const y=i.indexOf(p,a);if(y===-1)continue;const w=t.needles[h]||"";w&&(u===-1||y<u||y===u&&w.length>c.length)&&(u=y,c=w)}if(u===-1||!c){r.push(n.slice(a));break}u>a&&r.push(n.slice(a,u));const d=t.hits===0&&t.id?t.id:void 0,m=n.slice(u,u+c.length);r.push(s.jsx("span",{id:d,className:t.className,children:m},`hl:${t.hits}`)),t.hits+=1,a=u+c.length}return r}function qj(e){const t=String(e||"").trim();if(t&&/^(https?:|mailto:|tel:|#|\/)/i.test(t))return t}const cw="http://same-origin.invalid/";function rT(e){try{const t=new URL(e,cw);return t.protocol==="http:"&&t.origin===new URL(cw).origin}catch{return!1}}function Hj(e){const t=String(e||"").trim();return qj(t)??(t&&rT(t)?t:void 0)}let Jc=null;function iT(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??cw;let i,a;try{i=new URL(r).origin,a=new URL(t,r)}catch{return!1}return a.protocol!=="http:"&&a.protocol!=="https:"?!1:a.origin===i}function Vj(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 nb(e){return!!e&&/[\p{L}\p{N}]/u.test(e)}function qa(e,t){const n=[],r=String(e??"");let i=0,a="";const u=()=>{if(a){for(const c of am(a,t))n.push(c);a=""}};for(;i<r.length;){const c=r[i];if(c==="!"&&r[i+1]==="["){const d=r.indexOf("]",i+2);if(d!==-1&&r[d+1]==="("){const m=r.indexOf(")",d+2);if(m!==-1){const h=r.slice(i+2,d),p=Hj(r.slice(d+2,m));if(p&&Jc&&!Jc(p)){u(),n.push(Vj(`img:${i}`,p,h)),i=m+1;continue}if(p){u(),n.push(s.jsxs("span",{className:"pc-md_image_inline",children:[s.jsx("img",{className:"pc-md_img",src:p,alt:h,loading:"lazy"}),h?s.jsx("span",{className:"pc-md_img_caption",children:t?am(h,t):h}):null]},`img:${i}`)),i=m+1;continue}}}}if(c==="["){const d=r.indexOf("]",i+1);if(d!==-1&&r[d+1]==="("){const m=r.indexOf(")",d+2);if(m!==-1){const h=r.slice(i+1,d),p=qj(r.slice(d+2,m));if(p){u(),n.push(s.jsx("a",{className:"pc-md_link",href:p,target:p.startsWith("#")?void 0:"_blank",rel:"noreferrer",children:qa(h,t)},`link:${i}`)),i=m+1;continue}}}}if(c==="`"){const d=r.indexOf("`",i+1);if(d!==-1){u();const m=r.slice(i+1,d);n.push(s.jsx("code",{children:t?am(m,t):m},`code:${i}`)),i=d+1;continue}}if(c==="_"&&!nb(r[i-1])){const d=r[i+1]==="_"?"__":"_",m=d.length;if(r[i+m]&&!/\s/.test(r[i+m])&&r[i+m]!=="_"){let h=r.indexOf(d,i+m);for(;h!==-1&&(/\s/.test(r[h-1]||" ")||nb(r[h+m])||m===1&&r[h+1]==="_");)h=r.indexOf(d,h+1);if(h!==-1&&h>i+m){u();const p=r.slice(i+m,h),y=qa(p,t);n.push(m===2?s.jsx("strong",{children:y},`ubold:${i}`):s.jsx("em",{children:y},`uem:${i}`)),i=h+m;continue}}}if(c==="*"&&r[i+1]==="*"){const d=r.indexOf("**",i+2);if(d!==-1){u();const m=r.slice(i+2,d);n.push(s.jsx("strong",{children:t?am(m,t):m},`bold:${i}`)),i=d+2;continue}}if(c==="*"&&r[i+1]!=="*"){const d=r.indexOf("*",i+1);if(d!==-1){u();const m=r.slice(i+1,d);n.push(s.jsx("em",{children:t?am(m,t):m},`em:${i}`)),i=d+1;continue}}a+=c,i+=1}return u(),n}function oT(e){return String(e??"").replace(/\r\n/g,`
|
|
70
|
+
`).replace(/\r/g,`
|
|
71
|
+
`).split(`
|
|
72
|
+
`)}function cp(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 aT(e){const t=[];for(const i of e){const a=cp(i);a?t.push(a):t.length>0&&i.trim()&&(t[t.length-1].content+=` ${i.trim()}`)}const n=[],r=[];for(const i of t){for(;r.length>0&&i.indent<r[r.length-1].indent;)r.pop();let a=r.length>0?r[r.length-1]:null;if(a&&i.indent>a.indent){const u=a.node.items,c=u[u.length-1];if(c){const d={ordered:i.ordered,start:i.start,items:[]};c.children.push(d),r.push({indent:i.indent,node:d}),a=r[r.length-1]}}else if(a&&a.node.ordered!==i.ordered){r.pop();const u=r.length>0?r[r.length-1]:null,c={ordered:i.ordered,start:i.start,items:[]};if(u){const d=u.node.items,m=d[d.length-1];m?m.children.push(c):u.node.items.push({content:"",children:[c]})}else n.push(c);r.push({indent:i.indent,node:c}),a=r[r.length-1]}if(!a){const u={ordered:i.ordered,start:i.start,items:[]};n.push(u),r.push({indent:i.indent,node:u}),a=r[r.length-1]}a.node.items.push({content:i.content,children:[]})}return n}function Gj(e,t,n){const r=e.items.map((i,a)=>s.jsxs("li",{children:[qa(i.content,t),i.children.map((u,c)=>Gj(u,t,`${n}:${a}:${c}`))]},`${n}:li:${a}`));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 lT(e,t,n){return aT(e).map((r,i)=>Gj(r,t,`${n}:${i}`))}function sb(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 rb(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 ib=/^(#{1,5})\s+(.*)$/;function ob(e){return e.trim().startsWith("```")}function ab(e){return e.trimStart().startsWith(">")}function xi(e){const t=Jc;Jc=e.images==="link"?e.inlineImage||iT:null;try{return cT(e)}finally{Jc=t}}function cT({text:e,className:t,highlight:n,highlights:r,highlightClassName:i,highlightId:a}){const u=oT(e),c=[],d=[];Array.isArray(r)&&d.push(...r),typeof n=="string"&&n.trim()&&d.push(n);const m=Array.from(new Set(d.map(w=>String(w??"").trim()).filter(Boolean))).filter(w=>w.length>=4),h=m.length?{needles:m,needlesLower:m.map(w=>w.toLowerCase()),className:i||"pc-md_hl",id:a,hits:0}:null;let p=0;for(;p<u.length;){const w=String(u[p]??"");if(!w.trim()){p+=1;continue}const x=w.trim();if(/^([-_*])(\s*\1){2,}$/.test(x)){c.push(s.jsx("hr",{className:"pc-md_hr"},`hr:${p}`)),p+=1;continue}const k=w.match(/^\s*!\[([^\]]*)\]\(([^)]+)\)\s*$/);if(k){const $=Hj(k[2]||"");if($&&Jc&&!Jc($)){c.push(s.jsx("p",{className:"pc-md_p",children:Vj(`img:${p}`,$,k[1]||"")},`p:${p}`)),p+=1;continue}if($){const A=k[1]||"";c.push(s.jsxs("figure",{className:"pc-md_figure",children:[s.jsx("img",{className:"pc-md_img",src:$,alt:A,loading:"lazy"}),A?s.jsx("figcaption",{children:qa(A,h)}):null]},`figure:${p}`)),p+=1;continue}}if(ob(w)){const A=w.trim().replace(/```/g,"").trim(),E=[];for(p+=1;p<u.length&&!String(u[p]??"").trim().startsWith("```");)E.push(String(u[p]??"")),p+=1;p<u.length&&(p+=1);const z=E.join(`
|
|
73
|
+
`);c.push(s.jsx(sT,{code:z,lang:A},`pre:${p}`));continue}const b=w.match(ib);if(b){const $=b[1].length,A=b[2]||"",E=qa(A,h);$===1?c.push(s.jsx("h1",{children:E},`h1:${p}`)):$===2?c.push(s.jsx("h2",{children:E},`h2:${p}`)):$===3?c.push(s.jsx("h3",{children:E},`h3:${p}`)):$===4?c.push(s.jsx("h4",{children:E},`h4:${p}`)):c.push(s.jsx("h5",{children:E},`h5:${p}`)),p+=1;continue}if(ab(w)){const $=[];for(;p<u.length&&String(u[p]??"").trimStart().startsWith(">");){const E=String(u[p]??"").trimStart();$.push(E.replace(/^>\s?/,"")),p+=1}c.push(s.jsx("blockquote",{className:"pc-md_quote",children:$.map((A,E)=>s.jsxs(Ne.Fragment,{children:[qa(A,h),E<$.length-1?s.jsx("br",{}):null]},`q:${p}:${E}`))},`quote:${p}`));continue}if(w.includes("|")&&p+1<u.length&&rb(String(u[p+1]??""))){const $=sb(w),A=Math.max(1,$.length),E=[];for(p+=2;p<u.length;){const z=String(u[p]??"");if(!z.trim()||!z.includes("|"))break;const F=sb(z),M=[];for(let D=0;D<A;D++)M.push(F[D]??"");E.push(M),p+=1}c.push(s.jsx("div",{className:"pc-md_table_wrap",children:s.jsxs("table",{className:"pc-md_table",children:[s.jsx("thead",{children:s.jsx("tr",{children:$.slice(0,A).map((z,F)=>s.jsx("th",{children:qa(z,h)},`th:${p}:${F}`))})}),s.jsx("tbody",{children:E.map((z,F)=>s.jsx("tr",{children:z.map((M,D)=>s.jsx("td",{children:qa(M,h)},`td:${p}:${F}:${D}`))},`tr:${p}:${F}`))})]})},`table:${p}`));continue}if(cp(w)){const $=[];for(;p<u.length;){const A=String(u[p]??"");if(!A.trim()||A.trimStart().startsWith("```"))break;if(cp(A)||/^\s{2,}\S/.test(A)){$.push(A),p+=1;continue}break}c.push(s.jsx(Ne.Fragment,{children:lT($,h,`list:${p}`)},`list:${p}`));continue}const S=[];for(;p<u.length&&String(u[p]??"").trim()&&!(S.length>0&&cp(String(u[p]??"")));){const $=String(u[p]??"");if(S.length>0&&(ib.test($)||ob($)||ab($))||S.length>0&&$.includes("|")&&p+1<u.length&&rb(String(u[p+1]??"")))break;S.push($),p+=1}c.push(s.jsx("p",{className:"pc-md_p",children:S.map(($,A)=>s.jsxs(Ne.Fragment,{children:[qa($,h),A<S.length-1?s.jsx("br",{}):null]},`pl:${p}:${A}`))},`p:${p}`))}const y=["pc-md",t].filter(Boolean).join(" ");return s.jsx("div",{className:y,children:c})}function Kj(e){const t=String(e.text??""),n=_.useMemo(()=>og(t),[t]),r=["pc-chat-content",e.className].filter(Boolean).join(" ");return n!==null?s.jsx("div",{className:r,children:s.jsx(mr,{value:n,collapseAfterDepth:e.jsonCollapseAfterDepth})}):e.renderMarkdown?s.jsx("div",{className:r,children:e.renderMarkdown(t)}):s.jsx("div",{className:r,children:s.jsx(xi,{text:t,images:e.images,inlineImage:e.inlineImage})})}function $m(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Hl(e){return typeof e=="string"?e.trim():""}function uT(e){var i;const t=$m(e);if(!t)return null;const n=$m(t.sandbox);if(n&&Hl(n.kind))return n;const r=$m((i=$m(t.output))==null?void 0:i.sandbox);return r&&Hl(r.kind)?r:null}function uw(e){const t=uT(e);if(!t)return null;const n=Hl(t.kind),r=Hl(t.label)||n,i=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 a=[],u=Hl(t.private_workspace);u&&a.push({path:u,mode:"Read & write",private:!0});for(const d of Array.isArray(t.allowed)?t.allowed:[]){const m=$m(d),h=Hl(m==null?void 0:m.path);h&&a.push({path:h,mode:Hl(m==null?void 0:m.mode)==="ro"?"Read-only":"Read & write"})}for(const d of Array.isArray(t.refused)?t.refused:[]){const m=Hl(d);m&&a.push({path:m,mode:"Refused"})}if(n==="unsandboxed")return{state:"unsandboxed",kind:n,label:r,line:`Sandbox: ${r}`,rows:[],builtinRefused:0};const c=a.length;return{state:"sandboxed",kind:n,label:r,line:`Sandbox: ${r} · ${c} ${c===1?"workspace":"workspaces"} enforced`,rows:a,builtinRefused:i}}function Jj({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 Yj(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}}function dT(e){const t=Yj(e);if(!t||typeof t!="object"||Array.isArray(t))return{label:"input",value:t==null?"":String(t)};const n=Object.entries(t),i=["command","query","url","file_path","path","pattern","name"].map(a=>n.find(([u])=>u===a)).find(Boolean)||n[0];return i?{label:i[0].replace(/_/g," "),value:typeof i[1]=="string"?i[1]:JSON.stringify(i[1])??""}:{label:"",value:""}}function Xj({tool:e,showCopy:t=!0}){const[n,r]=_.useState(!1),i=Yj(e.arguments),a=dT(e.arguments),u=["file path","path"].includes(a.label)&&a.value.length>60?`${a.value.split(/[\\/]/).pop()} · ${a.value.slice(0,24)}…`:a.value,c=e.error&&/^File ['"].+['"] does not exist\.?$/.test(e.error)?"File not found. Expand for the exact path.":e.error&&e.error.length>180?`${e.error.slice(0,100)}…${e.error.slice(-70)}`:e.error,d={running:"Running",waiting:"Approval needed",completed:"Done",failed:"Failed"},m=e.startedAt&&e.endedAt?Date.parse(e.endedAt)-Date.parse(e.startedAt):NaN,h=i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i):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(Xe,{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:a.value,children:a.value?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"pc-tool-activity__key",children:a.label}),u]}):"No parameters"}),s.jsx("span",{className:"pc-tool-activity__status",children:d[e.status]}),Number.isFinite(m)&&m>=0?s.jsxs("span",{className:"pc-tool-activity__duration",children:[(m/1e3).toFixed(1),"s"]}):null,s.jsx("span",{className:"pc-tool-activity__chevron","aria-hidden":"true",children:s.jsx(Xe,{name:"chevronRight",size:13})}),e.error?s.jsx("span",{className:"pc-tool-activity__error",title:e.error,children:c}):null]}),s.jsxs("div",{className:"pc-tool-activity__detail",children:[s.jsx(Jj,{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 tc(JSON.stringify(e,null,2))),children:[s.jsx(Xe,{name:"copy",size:13}),n?"Copied":"Copy details"]}):null]}),h?s.jsx("dl",{className:"pc-tool-activity__parameters",children:h.map(([p,y])=>s.jsxs(Ne.Fragment,{children:[s.jsx("dt",{children:p}),s.jsx("dd",{children:y&&typeof y=="object"?s.jsx(mr,{value:y}):s.jsx("code",{children:typeof y=="string"?y:JSON.stringify(y)})})]},p))}):e.arguments===void 0?s.jsx("p",{children:"Arguments are unavailable in this ledger."}):s.jsx(mr,{value:i}),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(mr,{value:e.output})})]}):null]})]})}function Zj({tools:e,showCopy:t}){const n=r=>e.filter(i=>i.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(Xe,{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(Xj,{tool:r,showCopy:t},r.id))]})}const Nr="not reported",Qr=e=>e===void 0?Nr:Math.round(e).toLocaleString(),yi=e=>{if(e===void 0)return Nr;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`},Qj=e=>e===void 0?Nr:`${Math.round(e).toLocaleString()} tok/s`,fT=(e,t)=>t>0?`${Math.round(e/t*100)}%`:"",Yc=(e,t,n=`${t}s`)=>`${e.toLocaleString()} ${e===1?t:n}`,mT=e=>{const t=e.split("#")[0].replace(/\/+$/,"");return t.slice(t.lastIndexOf("/")+1)||e};function hT(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 $p(e){const t=[],n=(e.models||[]).map(mT),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 _T(e){const t=e.modelCalls||[],n=[],r=[{label:"Input",value:Qr(e.inputTokens)},{label:"Output",value:Qr(e.outputTokens)}];if(e.reasoningTokens!==void 0&&r.push({label:"Reasoning",value:Qr(e.reasoningTokens),hint:"part of output"}),r.push({label:"Total",value:Qr(e.totalTokens)}),n.push({heading:`Usage · ${Yc(e.llmCalls,"model call")}`,rows:r}),e.measuredCacheCalls){const a=e.cachedTokens||0,u=e.fedTokens||0,c=[{label:"Reused from cache",value:`${Qr(a)}${a+u?` (${fT(a,a+u)})`:""}`},{label:"Newly processed",value:Qr(e.fedTokens)},{label:"Outcome",value:hT(t.map(d=>d.cacheOutcome))||(e.cacheOutcomes||[]).join(" · ")||Nr},{label:"Backend",value:(e.cacheBackends||[]).join(", ")||Nr}];e.measuredCacheCalls!==e.llmCalls&&c.push({label:"Measured on",value:`${e.measuredCacheCalls} of ${e.llmCalls} calls`}),n.push({heading:"Prompt cache",rows:c})}else e.llmCalls&&n.push({heading:"Prompt cache",rows:[{label:"Cache reuse",value:Nr}]});const i=t.filter(a=>a.inputTokens!==void 0);return i.length===1&&t.length===1?n.push({heading:"Context",rows:[{label:"Prompt size",value:`${Qr(i[0].inputTokens)} tokens`}]}):i.length>1&&n.push({heading:"Context",rows:[{label:"First → last call",value:`${Qr(i[0].inputTokens)} → ${Qr(i[i.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((a,u)=>[String(u+1),Qr(a.inputTokens),a.cachedTokens===void 0?"—":Qr(a.cachedTokens),a.fedTokens===void 0?"—":Qr(a.fedTokens),Qr(a.outputTokens),a.cacheOutcome||"—"])}}),{kind:"tokens",title:"Tokens",headline:e.totalTokens===void 0?Nr:`${e.totalTokens.toLocaleString()} total`,sections:n,footer:$p(e)}}function O_(e,t,n,r){if(e===void 0)return Nr;const i=[yi(e)];return t!==void 0&&i.push(`${t.toLocaleString()} ${r}${n!==void 0?` at ${Qj(n)}`:""}`),i.join(" · ")}function pT(e){var m,h,p;const t=e.modelCalls||[],n=[],r=e.durationMs,i=[{label:"Wall clock",value:yi(r)}];if(i.push({label:"Model",value:e.genTimeMs===void 0?Nr:`${yi(e.genTimeMs)} · ${Yc(e.timedCalls||0,"call")}${e.timedCalls!==e.llmCalls?` (of ${e.llmCalls})`:""}`}),i.push({label:"Tools",value:e.toolTimeMs!==void 0?`${yi(e.toolTimeMs)} · ${Yc(e.toolBatches||0,"batch","batches")}`:e.toolCalls?Nr:"none",hint:e.toolTimeIncludesApproval?"includes approval wait":void 0}),r!==void 0&&e.genTimeMs!==void 0){const y=r-e.genTimeMs-(e.toolTimeMs||0);i.push({label:"Orchestration",value:y>=0?yi(y):"overlaps (parallel runs)",hint:"wall − model − tools: routing, hand-offs, model load"})}n.push({heading:"Turn",rows:i});const a=[],u=e.ttftCalls||0,c=e.promptPhaseCalls||0;e.promptPhaseMs!==void 0?a.push({label:u&&u===c?"Prefill (TTFT)":"Prefill",value:O_(e.promptPhaseMs,e.promptPhaseNewTokens,e.promptPhaseTokensPerSecond,"new tok"),hint:u===c?"measured time to first token":u?`TTFT measured on ${u} of ${c}; rest from provider rate`:"derived: prompt ÷ provider rate"}):e.prefillMs!==void 0&&e.prefillNewTokensPerSecond!==void 0?a.push({label:"Prefill",value:O_(e.prefillMs,e.prefillNewTokens,e.prefillNewTokensPerSecond,"new tok"),hint:"derived: prompt ÷ provider rate"}):e.prefillMs!==void 0?a.push({label:"Prefill",value:`${yi(e.prefillMs)}${e.promptTokensPerSecond!==void 0?` at ${Qj(e.promptTokensPerSecond)}`:""}`,hint:"provider rate over all prompt tokens, restored included"}):a.push({label:"Prefill",value:Nr}),e.cachedTokens&&(e.promptPhaseMs??e.prefillMs)!==void 0&&a.push({label:"Restored",value:`${e.cachedTokens.toLocaleString()} tok from cache`,hint:"not recomputed"}),a.push({label:"Generation",value:e.generationPhaseMs!==void 0?O_(e.generationPhaseMs,e.generationPhaseTokens,e.generationPhaseTokensPerSecond,"tok"):O_(e.decodeMs,e.outputTokens,e.generationTokensPerSecond,"tok")}),e.measuredSpeedCalls&&e.measuredSpeedCalls!==e.llmCalls&&a.push({label:"Speeds from",value:`${e.measuredSpeedCalls} of ${e.llmCalls} calls`}),n.push({heading:"Model",rows:a});const d=e.speculation;if(d){const y=(d.draftKinds||[]).map(x=>x.toUpperCase()).join(", "),w=[{label:"Mode",value:`${d.used?"on":"off"}${y?` · ${y}`:""}${(m=d.modes)!=null&&m.length?` (${d.modes.join(", ")})`:""}`,hint:d.calls!==e.llmCalls||d.used!==d.calls?`used on ${d.used} of ${e.llmCalls} calls`:void 0},{label:"Acceptance",value:d.acceptanceRate===void 0?Nr:`${Math.round(d.acceptanceRate*100)}% · ${Qr(d.acceptedTokens)} of ${Qr(d.draftedTokens)} drafted`}];((h=d.draftLengths)!=null&&h.length||d.rounds!==void 0)&&w.push({label:"Draft length",value:`${(p=d.draftLengths)!=null&&p.length?`${d.draftLengths.join("/")} tok/round`:Nr}${d.rounds!==void 0?` · ${d.rounds.toLocaleString()} rounds`:""}`}),n.push({heading:"Speculation",rows:w})}return e.slowestToolBatch&&n.push({heading:"Tools",rows:[{label:"Total",value:`${yi(e.toolTimeMs)} · ${Yc(e.toolBatches||0,"batch","batches")}`},{label:"Slowest",value:`${yi(e.slowestToolBatch.ms)} · ${eS(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?"—":`${yi(y.promptMs)}${y.promptSource==="rate"?"*":""}`,y.promptNewTokensPerSecond===void 0?"—":Math.round(y.promptNewTokensPerSecond).toLocaleString(),y.generationMs===void 0?"—":yi(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?Nr:`${yi(r)} wall clock`,sections:n,footer:$p(e)}}function eS(e){return e.tools.length===1?`${e.tools[0]} ×${e.calls}`:`${Yc(e.calls,"call")} (${e.tools.join(", ")})`}function gT(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:$p(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 i=Object.entries(e.toolBreakdown||{}).sort((c,d)=>d[1].calls-c[1].calls||c[0].localeCompare(d[0]));i.length&&t.push({heading:"By tool",table:{columns:["Tool","Calls","Failed","Time"],rows:i.map(([c,d])=>[c,d.calls.toLocaleString(),d.failed.toLocaleString(),d.ms!==void 0?`${yi(d.ms)}${d.sharedBatches?" +shared":""}`:d.sharedBatches?"shared":Nr])},note:i.some(([,c])=>c.sharedBatches)?"A batch that mixed tools ran them together; its time is not split between them.":void 0});const a=i.filter(([,c])=>c.errors&&Object.keys(c.errors).length);a.length&&t.push({heading:"Failures",rows:a.map(([c,d])=>({label:c,value:Object.entries(d.errors).sort((m,h)=>h[1]-m[1]).map(([m,h])=>h>1?`${m} ×${h}`:m).join(" · ")}))});const u=[{label:"Tool time",value:e.toolTimeMs===void 0?Nr:`${yi(e.toolTimeMs)} · ${Yc(e.toolBatches||0,"batch","batches")}`}];return e.slowestToolBatch&&u.push({label:"Slowest batch",value:`${yi(e.slowestToolBatch.ms)} · ${eS(e.slowestToolBatch)}`}),t.push({heading:"Timing",rows:u,note:e.toolTimeIncludesApproval?"Gated calls are timed from request to result, so this includes waiting for your approval.":void 0}),{kind:"tools",title:"Tools",headline:`${Yc(e.toolCalls,"call")}${e.toolsFailed?` · ${e.toolsFailed} failed`:""}`,sections:t,footer:$p(e)}}function Yg(e,t){return e==="tokens"?_T(t):e==="time"?pT(t):gT(t)}function yT(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(i=>s.jsxs(Ne.Fragment,{children:[s.jsx("dt",{children:i.label}),s.jsxs("dd",{children:[s.jsx("span",{className:i.value===Nr?"pc-stat-detail-value pc-stat-detail-value--absent":"pc-stat-detail-value",children:i.value}),i.hint?s.jsx("span",{className:"pc-stat-detail-hint",children:i.hint}):null]})]},i.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(i=>s.jsx("th",{scope:"col",children:i},i))})}),s.jsx("tbody",{children:n.table.rows.map((i,a)=>s.jsx("tr",{children:i.map((u,c)=>s.jsx("td",{children:u},c))},a))})]}):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 Ba=8;function wT(e){const[t,n]=_.useState(!!e.defaultOpen),[r,i]=_.useState(null),a=_.useRef(null),u=_.useRef(null),c=_.useRef(null),d=`pc-stat-${_.useId().replace(/[^a-zA-Z0-9_-]/g,"")}`,m=_.useCallback(()=>{c.current!==null&&window.clearTimeout(c.current),c.current=null},[]),h=_.useCallback(()=>{m(),n(!0)},[m]),p=_.useCallback(()=>{m(),c.current=window.setTimeout(()=>n(!1),120)},[m]);_.useEffect(()=>m,[m]),_.useLayoutEffect(()=>{if(!t){i(null);return}const k=()=>{const b=a.current,S=u.current;if(!b||!S)return;const $=b.getBoundingClientRect(),A=S.offsetWidth,E=S.offsetHeight,z=window.innerWidth,F=window.innerHeight,M=$.top-Ba-E,D=$.bottom+Ba,H=M>=Ba?M:D+E<=F-Ba?D:Math.max(Ba,F-Ba-E),q=Math.min(Math.max(Ba,$.left),Math.max(Ba,z-Ba-A));i({top:H,left:q})};return k(),window.addEventListener("resize",k),window.addEventListener("scroll",k,!0),()=>{window.removeEventListener("resize",k),window.removeEventListener("scroll",k,!0)}},[t]),_.useEffect(()=>{if(!t)return;const k=b=>{b.key==="Escape"&&n(!1)};return document.addEventListener("keydown",k),()=>document.removeEventListener("keydown",k)},[t]);const y=typeof e.onClick=="function",w=y?"button":"span",x=t?s.jsx(yT,{detail:e.detail,id:d,panelRef:u,onMouseEnter:m,onMouseLeave:p,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:a,...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?d:void 0,"data-stat-kind":e.detail.kind,onMouseEnter:h,onMouseLeave:p,onFocus:h,onBlur:()=>n(!1),onKeyDown:k=>{k.key==="Escape"&&n(!1)},onClick:y?()=>{var k;return(k=e.onClick)==null?void 0:k.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})]}),x&&typeof document<"u"?Xp.createPortal(x,document.body):x]})}function vT(e){const t=e.totalTokens!==void 0?Yg("tokens",e):null,n=Yg("tools",e),r=e.durationMs!==void 0?Yg("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 xT(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 bT=new Set(["blob:","data:","http:","https:"]);function lb(e){const t=String(e||"").trim();if(t)try{const n=typeof window<"u"&&window.location?window.location.href:"http://same-origin.invalid/";return bT.has(new URL(t,n).protocol)?t:void 0}catch{return}}function kT({item:e}){const[t,n]=_.useState(!1),r=lb(e.src),i=e.href?lb(e.href):void 0,a=e.kind==="image"||e.kind==="audio"||e.kind==="video"?e.kind:null;if(!a||!r&&!i)return null;const u=a==="image"?"Image":a==="video"?"Video":"Audio",c=String(e.label||"").trim()||`Generated ${u.toLowerCase()}`,d=()=>n(!0);return s.jsxs("figure",{className:`pc-chat-media__item pc-chat-media__item--${a}`,children:[r&&a==="image"?s.jsx("img",{className:"pc-chat-media__image",src:r,alt:c,loading:"lazy",onError:d}):null,r&&a==="video"?s.jsx("video",{className:"pc-chat-media__video",src:r,controls:!0,playsInline:!0,preload:"metadata","aria-label":c,onError:d}):null,r&&a==="audio"?s.jsx(rg,{className:"pc-chat-media__audio",src:r,name:c}):null,t?s.jsxs("div",{className:"pc-chat-media__error",role:"note",children:[u," could not be decoded by this browser",i?"; open the raw file with the link.":"."]}):null,i?s.jsx("figcaption",{className:"pc-chat-media__caption",children:s.jsx("a",{className:"pc-chat-media__link",href:i,target:"_blank",rel:"noopener noreferrer",children:c})}):null]})}function vv(e){var z;const t=e.message,n=_.useMemo(()=>xT(t),[t.kind,t.level,t.role,t.title]),r=String(t.ts||"").trim(),i=_.useMemo(()=>{if(!r)return"";const F=new Date(r);return Number.isFinite(F.getTime())?F.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):""},[r]),[a,u]=_.useState("idle"),c=_.useRef(null);_.useEffect(()=>()=>{c.current!==null&&window.clearTimeout(c.current)},[]);const d=t.live,m=!d&&typeof e.onSpeakToggle=="function"&&n.variant==="assistant"&&!!String(t.content||"").trim(),h=m&&((z=e.getSpeakState)==null?void 0:z.call(e,t))||"idle",p=h==="loading"?"loader":h==="playing"?"pause":"speaker",y=h==="loading"?"Generating audio…":h==="playing"?"Pause":h==="paused"?"Resume":"Speak (TTS)",w=e.showCopy!==!1,x=Array.isArray(e.attachments)?e.attachments:Array.isArray(t.attachments)?t.attachments:[],k=t.statistics,b=t.stats,S=_.useMemo(()=>Array.isArray(e.stats)?e.stats:Array.isArray(b)?b:k?vT(k):[],[e.stats,b,k]),$=Array.isArray(t.media)?t.media:[],A=String(d?d.reasoning||"":t.reasoning||""),E=!!String(t.content||"").trim();return t.toolActivity?s.jsx(Xj,{tool:t.toolActivity,showCopy:e.showCopy}):s.jsxs("div",{className:["pc-chat-item",`pc-chat-item--${n.variant}`,d?"pc-chat-item--live":"",e.className].filter(Boolean).join(" "),...d?{"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(Xe,{name:n.icon,size:14})}),s.jsx("span",{className:"pc-chat-role",children:n.label}),d?s.jsxs("span",{className:"pc-chat-live-indicator",title:d.label?`Pending: ${d.label}`:"The reply is still being written",children:[s.jsx("span",{className:"pc-chat-live-dot","aria-hidden":"true"}),d.label||"streaming"]}):null,d!=null&&d.caption?s.jsx("span",{className:"pc-chat-live-caption",children:d.caption}):null,s.jsx("span",{className:"pc-chat-header-spacer"}),i?s.jsx("span",{className:"pc-chat-time",children:i}):null,s.jsxs("div",{className:"pc-chat-header-actions",children:[m?s.jsx("button",{className:"pc-chat-icon-btn",type:"button","aria-label":y,title:y,onClick:()=>{var F;return(F=e.onSpeakToggle)==null?void 0:F.call(e,t)},children:s.jsx(Xe,{name:p,size:22,className:h==="loading"?"pc-chat-speak-spinner":void 0})}):null,w?s.jsx("button",{className:`pc-chat-icon-btn ${a!=="idle"?`pc-chat-icon-btn--${a}`:""}`.trim(),type:"button","aria-label":"Copy message",title:a==="idle"?"Copy":a==="copied"?"Copied":"Copy failed",onClick:async()=>{const F=await tc(String(t.content||""));u(F?"copied":"failed"),c.current!==null&&window.clearTimeout(c.current),c.current=window.setTimeout(()=>u("idle"),900)},children:s.jsx(Xe,{name:"copy",size:22})}):null]})]}),A.trim()?s.jsxs("details",{className:"pc-chat-thinking",children:[s.jsx("summary",{children:"Thinking"}),s.jsx("div",{className:"pc-chat-thinking-body",children:A})]}):null,E||!d&&!$.length?s.jsx("div",{className:"pc-chat-body",children:s.jsx(Kj,{text:String(t.content||""),renderMarkdown:e.renderMarkdown,jsonCollapseAfterDepth:e.jsonCollapseAfterDepth,images:e.images||(n.variant==="user"?"inline":"link"),inlineImage:e.inlineImage})}):null,$.length?s.jsx("div",{className:"pc-chat-media",children:$.slice(0,24).map((F,M)=>s.jsx(kT,{item:F},F.id||`${F.kind}:${F.src}:${M}`))}):null,x.length?s.jsx("div",{className:"pc-chat-attachments","aria-label":"Attachments",children:x.slice(0,24).map((F,M)=>{const D=String(F.label||"").trim()||"attachment",H=String(F.target||"").trim(),q=String(F.title||"").trim(),I=!!F.disabled||typeof F.onClick!="function";return s.jsxs("button",{type:"button",className:"pc-chat-attachment-chip",title:q||D,onClick:I?void 0:F.onClick,disabled:I,children:[s.jsx(Xe,{name:"paperclip",size:14}),H?s.jsx("span",{className:`pc-chat-attachment-target pc-chat-attachment-target--${H}`,children:H}):null,s.jsx("span",{className:"pc-chat-attachment-name",children:D})]},F.id||`${D}:${M}`)})}):null,S.length?s.jsx("div",{className:"pc-chat-stats","aria-label":"Stats",children:S.slice(0,12).map((F,M)=>{const D=String(F.label||"").trim();if(!D)return null;if(F.detail)return s.jsx(wT,{label:D,detail:F.detail,icon:F.icon,onClick:F.onClick},F.id||`${D}:${M}`);const H=String(F.title||"").trim(),q=typeof F.onClick=="function",I=q?"button":"span";return s.jsxs(I,{...q?{type:"button"}:{},className:["pc-chat-stat",q?"pc-chat-stat--clickable":""].filter(Boolean).join(" "),title:H||void 0,onClick:q?()=>{var Z;return(Z=F.onClick)==null?void 0:Z.call(F)}:void 0,children:[F.icon?s.jsx("span",{className:"pc-chat-stat-icon","aria-hidden":"true",children:F.icon}):null,s.jsx("span",{className:"pc-chat-stat-label",children:D})]},F.id||`${D}:${M}`)})}):null]})}function jT(e,t){const n=Math.max(0,Math.trunc(t));return e.scrollHeight-e.scrollTop-e.clientHeight<=n}function xv(e){const t=typeof e.autoScrollThresholdPx=="number"&&Number.isFinite(e.autoScrollThresholdPx)?e.autoScrollThresholdPx:120,n=e.autoScroll!==!1,r=_.useRef(null),i=_.useRef(null),[a,u]=_.useState(!0),c=_.useMemo(()=>Array.isArray(e.messages)?e.messages:[],[e.messages]),d=_.useMemo(()=>{var p;const h=[];for(const y of c){const w=h[h.length-1];y.toolActivity&&((p=w==null?void 0:w[0])!=null&&p.toolActivity)&&w[0].runId===y.runId?w.push(y):h.push([y])}return h},[c]);_.useEffect(()=>{if(!n)return;const h=r.current;if(!h)return;const p=()=>{u(jT(h,t))};return h.addEventListener("scroll",p,{passive:!0}),p(),()=>h.removeEventListener("scroll",p)},[n,t]);const m=_.useMemo(()=>{let h=0;for(const p of c)if(h+=String(p.content??"").length,Array.isArray(p.media))for(const y of p.media)h+=String((y==null?void 0:y.src)??"").length+1;return`${c.length}:${h}:${String(e.afterKey??"")}`},[c,e.afterKey]);return _.useEffect(()=>{if(!n||!a)return;const h=r.current;h&&(h.scrollTop=h.scrollHeight)},[n,a,m]),_.useEffect(()=>{if(!n)return;const h=r.current;if(!h)return;const p=()=>{a&&(h.scrollTop=h.scrollHeight)};return h.addEventListener("load",p,!0),h.addEventListener("loadedmetadata",p,!0),()=>{h.removeEventListener("load",p,!0),h.removeEventListener("loadedmetadata",p,!0)}},[n,a]),s.jsxs("div",{ref:r,className:["pc-chat-thread",e.className].filter(Boolean).join(" "),children:[c.length?null:e.empty||null,d.map((h,p)=>{var x;const y=h[0],w=String(y.id||"")||String(y.ts||"")+":"+String(y.role||"")+":"+p;return y.toolActivity?s.jsx(Zj,{tools:h.map(k=>k.toolActivity),showCopy:(x=e.messageProps)==null?void 0:x.showCopy},w):s.jsx(vv,{message:y,...e.messageProps||{}},w)}),e.after,s.jsx("div",{ref:i})]})}const bv=Ne.forwardRef(function(t,n){const r=typeof t.rows=="number"&&Number.isFinite(t.rows)?Math.max(1,Math.trunc(t.rows)):3,i=!!t.disabled,a=!!t.busy,u=!i&&!a&&!!String(t.value||"").trim();return s.jsxs("div",{className:["pc-composer",t.className].filter(Boolean).join(" "),children:[t.leading,s.jsx("textarea",{ref:n,className:["pc-composer__textarea",t.textareaClassName].filter(Boolean).join(" "),value:t.value,onChange:c=>t.onChange(c.target.value),rows:r,style:{"--pc-composer-rows":String(r)},spellCheck:!1,autoCorrect:"off",autoCapitalize:"off",autoComplete:"off",placeholder:t.placeholder||"","aria-label":t.ariaLabel||t.placeholder||"Message",disabled:i,autoFocus:!!t.autoFocus,onPaste:t.onPaste,onKeyDown:c=>{c.key!=="Enter"||c.shiftKey||c.nativeEvent.isComposing||c.keyCode===229||(c.preventDefault(),u&&t.onSubmit())}}),s.jsxs("div",{className:"pc-composer__row",children:[s.jsx("div",{className:"pc-composer__actions",children:t.actions}),s.jsx("button",{type:"button",className:t.sendButtonClassName||"pc-btn",disabled:!u,onClick:()=>t.onSubmit(),children:a?t.busyLabel||"Thinking…":t.sendLabel||"Send"})]}),t.overlay]})});function Cm(e){if(!e)return!1;for(let t=0;t<e.length;t+=1)if(e[t]==="Files")return!0;return!1}function cb(e){var r;const t=e==null?void 0:e.items;if(!t||!t.length)return null;let n=0;for(let i=0;i<t.length;i+=1)((r=t[i])==null?void 0:r.kind)==="file"&&(n+=1);return n>0?n:null}function ub(e){return e===1?"Drop file to attach":typeof e=="number"&&e>1?`Drop ${e} files to attach`:"Drop files to attach"}function kv(e){const t=[],n=[],r=e==null?void 0:e.items;if(r&&r.length){for(let a=0;a<r.length;a+=1){const u=r[a];if(!u||u.kind!=="file")continue;const c=typeof u.webkitGetAsEntry=="function"?u.webkitGetAsEntry():null,d=typeof u.getAsFile=="function"?u.getAsFile():null;c!=null&&c.isDirectory?n.push(c.name||(d==null?void 0:d.name)||"folder"):d&&t.push(d)}return{files:t,folders:n}}const i=e==null?void 0:e.files;if(i)for(let a=0;a<i.length;a+=1)i[a]&&t.push(i[a]);return{files:t,folders:n}}function tS(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 ST={"image/png":"png","image/jpeg":"jpg","image/gif":"gif","image/webp":"webp","image/heic":"heic","image/tiff":"tiff","image/bmp":"bmp"};function lm(e){return String(e).padStart(2,"0")}function NT(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 i=ST[String(t||"").toLowerCase()]||r.split(".").pop()||"bin",a=`${n.getFullYear()}-${lm(n.getMonth()+1)}-${lm(n.getDate())} at ${lm(n.getHours())}.${lm(n.getMinutes())}.${lm(n.getSeconds())}`;return`${String(t||"").startsWith("image/")||!r?"Pasted image":"Pasted file"} ${a}.${i}`}function nS(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}=kv(e);return r.map(i=>{const a=NT(i.name,i.type,t);return a===i.name?i:new File([i],a,{type:i.type,lastModified:i.lastModified})})}class $T{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 Em="llm.delta",kd="llm.delta_end";function CT(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Pc(e){return typeof e=="string"&&e.trim()!==""}function ET(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0}function sS(e){return"reason"in e}function rS(e,t){const n=CT(e),r=n==null?void 0:n.kind,i=t||(typeof r=="string"&&r?r:n&&"reason"in n?kd:Em),a=d=>{throw new Error(`Malformed ${i} event from the gateway: ${d}`)};if(t!==void 0&&t!==Em&&t!==kd&&a(`unknown event name ${JSON.stringify(t)}`),!n)return a("the payload is not an object");r!==void 0&&r!==Em&&r!==kd&&a(`unknown kind ${JSON.stringify(r)}`),r!==void 0&&t!==void 0&&r!==t&&a(`kind ${JSON.stringify(r)} does not match the event name`),Pc(n.run_id)||a("run_id is missing"),Pc(n.call_id)||a("call_id is missing"),ET(n.seq)||a("seq is not a non-negative integer");const u=t||r?(t||r)===kd:"reason"in n;n.root_run_id!==void 0&&!Pc(n.root_run_id)&&a("root_run_id is not a run id"),n.parent_run_id!==void 0&&n.parent_run_id!==null&&!Pc(n.parent_run_id)&&a("parent_run_id is neither a run id nor null");const c={run_id:n.run_id,...Pc(n.root_run_id)?{root_run_id:n.root_run_id}:{},...n.parent_run_id!==void 0?{parent_run_id:n.parent_run_id}:{},...Pc(n.node_id)?{node_id:n.node_id}:{},call_id:n.call_id,seq:n.seq};return u?(["completed","failed","cancelled","unavailable"].includes(String(n.reason))||a(`unknown reason ${JSON.stringify(n.reason)}`),n.detail!==void 0&&n.detail!==null&&typeof n.detail!="string"&&a("detail is not a string"),{kind:kd,...c,reason:n.reason,...Pc(n.detail)?{detail:n.detail}:{}}):(typeof n.text!="string"&&a("text is not a string"),n.channel!=="content"&&n.channel!=="reasoning"&&a(`unknown channel ${JSON.stringify(n.channel)}`),typeof n.snapshot!="boolean"&&a("snapshot is not a boolean"),{kind:Em,...c,text:n.text,channel:n.channel,snapshot:n.snapshot})}function AT(e,t){if(e!==Em&&e!==kd)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 rS(n,e)}const TT={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 MT(e){return`This reply is not streamed: ${e?TT[e]||`the gateway reported "${e}"`:"the gateway gave no reason"}. It appears when it is complete.`}const db=1024*1024,RT="1 MiB",LT=25*1024*1024,iS=(e,t)=>`${yt(`runs/${encodeURIComponent(e)}/workspace`)}/content?${new URLSearchParams({path:t})}`;function IT(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 OT(e,t,n){var m;const r=new TextDecoder;let i="",a=0;const u=(m=e.body)==null?void 0:m.getReader();if(u){for(;a<t;){const{done:h,value:p}=await u.read();if(h)break;const y=p.subarray(0,t-a);a+=y.length,i+=r.decode(y,{stream:!0})}await u.cancel().catch(()=>{})}else i=(await e.text()).slice(0,t),a=i.length;const c=IT(e)??n,d=c!==void 0?c>a:a>=t;return{text:i,received:a,total:c,partial:d}}function PT(e){return`Showing the first ${RT} of ${e!==void 0?wv(e):"a file of unknown size"}; download for the rest.`}function DT(e){try{return decodeURIComponent(e)}catch{return e}}function FT(e,t,n){const r=`${yt(`runs/${encodeURIComponent(t)}/workspace`)}/content?`,i=n.split("/").slice(0,-1),a=d=>{if(/^[a-z][a-z0-9+.-]*:/i.test(d)||d.startsWith("/")||d.startsWith("#"))return null;const m=[...i];for(const h of d.split(/[?#]/,1)[0].split("/"))if(!(!h||h==="."))if(h===".."){if(!m.length)return null;m.pop()}else m.push(DT(h));return m.length?iS(t,m.join("/")):null},u=d=>{let m="",h=0;for(;h<d.length;){if(d[h]==="!"&&d[h+1]==="["){const p=d.indexOf("]",h+2);if(p!==-1&&d[p+1]==="("){const y=d.indexOf(")",p+2);if(y!==-1){const w=d.slice(h+2,p),x=d.slice(p+2,y).trim(),k=x.startsWith(r)?x:a(x);m+=k?``:`[image: ${w||x}](${x})`,h=y+1;continue}}}m+=d[h],h+=1}return m};let c=!1;return e.split(`
|
|
75
|
+
`).map(d=>/^\s*(```|~~~)/.test(d)?(c=!c,d):c?d:u(d)).join(`
|
|
76
|
+
`)}function zT(e,t,n,r){const[i,a]=_.useState({status:"idle"});return _.useEffect(()=>{if(!n||!t){a({status:"idle"});return}const u=new AbortController;let c="";const d=lw(n.name);if(d==="binary"){a({status:"ready",kind:"binary",contentType:"",partial:!1});return}if((d==="image"||d==="audio"||d==="pdf")&&typeof n.size_bytes=="number"&&n.size_bytes>LT){a({status:"error",kind:d,message:`Too large to preview (${wv(n.size_bytes)}); use Download.`});return}a({status:"loading",kind:d});const m=Kx(d);return(async()=>{var h;try{const p=await e(iS(t,n.path),{signal:u.signal,...m?{headers:{Range:`bytes=0-${db-1}`}}:{}});if(!p.ok)throw new Error(`Preview failed (HTTP ${p.status}): ${await p.text().catch(()=>"")||p.statusText||"no reason given"}`);const y=p.headers.get("content-type")||"",w=lw(n.name,y);if(Kx(w)){const x=await OT(p,db,n.size_bytes);if(u.signal.aborted)return;a({status:"ready",kind:w,contentType:y,text:w==="markdown"?FT(x.text,t,n.path):x.text,partial:x.partial,total:x.total});return}if(w==="image"||w==="audio"||w==="pdf"){const x=await p.blob();if(u.signal.aborted)return;c=URL.createObjectURL(x.type?x:new Blob([x],{type:w==="pdf"?"application/pdf":y})),a({status:"ready",kind:w,contentType:y,url:c,partial:!1});return}await((h=p.body)==null?void 0:h.cancel().catch(()=>{})),u.signal.aborted||a({status:"ready",kind:"binary",contentType:y,partial:!1})}catch(p){u.signal.aborted||a({status:"error",kind:d,message:String((p==null?void 0:p.message)||p)})}})(),()=>{u.abort(),c&&URL.revokeObjectURL(c)}},[e,t,n==null?void 0:n.path,n==null?void 0:n.name,n==null?void 0:n.size_bytes,r]),i}function BT(e){return s.jsx(_A,{...e,nowMs:e.nowMs??Date.now(),renderMarkdown:t=>s.jsx(xi,{text:t})})}function UT(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:PT(e.total)}:{}}}const jv=e=>yt(`runs/${encodeURIComponent(e)}/workspace`);function WT(e){return jv(e)}function qT(e,t){return`${jv(e)}/files?${new URLSearchParams({path:t,recursive:"false"})}`}function HT(e,t){return`${jv(e)}/content?${new URLSearchParams({path:t})}`}async function Xd(e,t){let n="";try{const r=await e.text();try{const i=JSON.parse(r),a=(i==null?void 0:i.detail)??(i==null?void 0:i.error)??(i==null?void 0:i.message);n=typeof a=="string"?a:a&&typeof a.message=="string"?a.message:r}catch{n=r}}catch{n=""}return new Error(`${t} (HTTP ${e.status}): ${n.trim()||e.statusText||"no reason given"}`)}function VT(e,t){const n=e&&typeof e=="object"&&!Array.isArray(e)?e:null,r=u=>{throw new Error(`Unexpected /workspace/files response from the gateway: ${u}.`)};if(!n)return r("not an object");Array.isArray(n.entries)||r("no `entries` list"),typeof n.truncated!="boolean"&&r("no `truncated` flag");const i=n.entries.map((u,c)=>{const d=u&&typeof u=="object"?u:{};return(typeof d.name!="string"||typeof d.path!="string"||d.type!=="file"&&d.type!=="dir")&&r(`entry ${c+1} lacks a name, path or file/dir type`),d}),a=n.hidden&&typeof n.hidden=="object"&&!Array.isArray(n.hidden)?n.hidden:void 0;return{path:typeof n.path=="string"?n.path:t,entries:i,truncated:n.truncated,...a?{hidden:a}:{}}}async function GT(e,t,n){const r=await e(WT(t),{signal:n});if(!r.ok)throw await Xd(r,"The workspace is not available");const i=await r.json();if(!i||typeof i.workspace_root!="string"||typeof i.exists!="boolean")throw new Error("Unexpected /workspace response from the gateway: no `workspace_root` / `exists`.");return i}async function KT(e,t,n,r){const i=await e(qT(t,n),{signal:r});if(!i.ok)throw await Xd(i,"The folder could not be listed");return VT(await i.json(),n)}async function JT(e,t,n,r){const i=await e(HT(t,n),{signal:r});if(!i.ok)throw await Xd(i,"The file could not be read");return await i.blob()}async function YT(e,t,n,r){const i=await GT(e,t,r);return{where:i,listing:i.exists?await KT(e,t,n,r):null}}function XT(e){const t=String(e||"").split("/").filter(Boolean),n=[{label:"Workspace",path:""}];return t.forEach((r,i)=>n.push({label:r,path:t.slice(0,i+1).join("/")})),n}function ZT(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 QT(e){return[...e].sort((t,n)=>t.type===n.type?t.name.localeCompare(n.name):t.type==="dir"?-1:1)}function eM(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 tM=new Set(["image/png","image/jpeg","image/gif","image/webp","image/avif","image/bmp","application/pdf","text/plain","application/json"]);function nM(e){const t=String(e||"").split(";",1)[0].trim().toLowerCase();return tM.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 oS(e,t,n){const r=n==="open"?nM(e.type):{mode:"download"},i=r.mode==="open"&&r.type!==e.type?new Blob([e],{type:r.type}):e,a=URL.createObjectURL(i);if(r.mode==="open")window.open(a,"_blank","noopener");else{const u=document.createElement("a");u.href=a,u.download=t,document.body.appendChild(u),u.click(),u.remove()}window.setTimeout(()=>URL.revokeObjectURL(a),6e4)}async function sM(e,t,n){const r=await e(i2(t),{signal:n.signal});if(!r.ok)throw await Xd(r,`${n.name} could not be read`);oS(await r.blob(),n.name,n.mode??"open")}function rM(e){const t=String(e||"").split(/[\\/]/).filter(Boolean);return t.length?t[t.length-1]:String(e||"")}function iM(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 oM(e){try{return await navigator.clipboard.writeText(e),!0}catch{return!1}}function aS(e){var Z;const{fetchGateway:t,runId:n}=e,[r,i]=_.useState({runId:n,path:""}),a=r.runId===n?r.path:"",[u,c]=_.useState(null),[d,m]=_.useState(""),[h,p]=_.useState(""),[y,w]=_.useState(!!n),[x,k]=_.useState(""),[b,S]=_.useState(!1),[$,A]=_.useState(0),[E,z]=_.useState(null),F=E&&E.runId===n&&!e.onSelectFile?E.entry:null,M=zT(t,n,F,`${e.refreshKey??""}:${$}`);_.useEffect(()=>{if(!n)return;const R=new AbortController;return w(!0),m(""),(async()=>{try{const T=await YT(t,n,a,R.signal);R.signal.aborted||c({runId:n,...T})}catch(T){R.signal.aborted||m(String((T==null?void 0:T.message)||T))}finally{R.signal.aborted||w(!1)}})(),()=>R.abort()},[t,n,a,$,e.refreshKey]),_.useEffect(()=>p(""),[n]);const D=u&&u.runId===n?u:null,H=_.useCallback(async R=>{k(R.path),m("");try{oS(await JT(t,n,R.path),R.name,"download")}catch(T){m(String((T==null?void 0:T.message)||T))}finally{k("")}},[t,n]),q=(D==null?void 0:D.where.workspace_root)||"",I=e.nowMs??Date.now();return s.jsx(aM,{title:e.title,note:e.note,where:(D==null?void 0:D.where)??null,path:a,listing:(D==null?void 0:D.listing)??null,error:d,notice:h,loading:y,fileBusy:x,selectedPath:e.onSelectFile?e.selectedPath:F==null?void 0:F.path,className:e.className,nowMs:I,openingFolder:b,onNavigate:R=>{z(null),i({runId:n,path:R})},onRefresh:()=>A(R=>R+1),onFile:R=>void H(R),onSelectFile:e.onSelectFile??(R=>z({runId:n,entry:R})),onClose:e.onClose,onCopyPath:q?()=>{(e.copyText||oM)(q).then(R=>p(R?"Path copied.":"Could not copy; select the path instead."))}:void 0,onOpenFolder:e.onOpenFolder&&iM(D==null?void 0:D.where)?()=>{S(!0),p(""),e.onOpenFolder().then(()=>p("Folder opened on this machine.")).catch(R=>p(`Open folder failed: ${String((R==null?void 0:R.message)||R)}`)).finally(()=>S(!1))}:void 0,preview:F?s.jsx(BT,{name:F.name,path:F.path,sizeBytes:F.size_bytes,modified:F.mtime,nowMs:I,...UT(M),actions:(Z=e.fileActions)==null?void 0:Z.call(e,F),onDownload:()=>void H(F),onClose:()=>z(null)}):null})}function aM(e){var a,u,c,d;const t=e.listing?eM(e.listing):"",n=(u=(a=e.where)==null?void 0:a.host)==null?void 0:u.hostname,r=((c=e.where)==null?void 0:c.workspace_root)||"",i=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(Xe,{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(Xe,{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(Xe,{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:rM(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(Xe,{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(Xe,{name:"copy",size:14})}):null,n&&((d=e.where.host)==null?void 0:d.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:XT(e.path).map((m,h,p)=>h===p.length-1?s.jsx("span",{"aria-current":"page",children:m.label},m.path):s.jsxs(Ne.Fragment,{children:[s.jsx("button",{type:"button",className:"pc-ws__crumb",onClick:()=>e.onNavigate(m.path),children:m.label}),s.jsx("span",{className:"pc-ws__muted",children:" / "})]},m.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:QT(e.listing.entries).map(m=>s.jsx("li",{className:`pc-ws__entry${e.selectedPath===m.path?" is-selected":""}`,"data-type":m.type,"data-path":m.path,children:m.type==="dir"?s.jsxs("button",{type:"button",className:"pc-ws__name","data-action":"open-dir",onClick:()=>e.onNavigate(m.path),children:[s.jsx(Xe,{name:"folder",size:14})," ",s.jsxs("span",{className:"pc-ws__label",children:[m.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===m.path,title:`Preview ${m.name}`,onClick:()=>{var h;return(h=e.onSelectFile)==null?void 0:h.call(e,m)},children:[s.jsx(Xe,{name:"file",size:14})," ",s.jsx("span",{className:"pc-ws__label",children:m.name})]}):s.jsxs("span",{className:"pc-ws__name",children:[s.jsx(Xe,{name:"file",size:14})," ",s.jsx("span",{className:"pc-ws__label",children:m.name})]}),s.jsxs("span",{className:"pc-ws__meta",children:[s.jsx("span",{className:"pc-ws__size",children:ZT(m.size_bytes)}),m.mtime!==void 0&&Np(m.mtime,i)?s.jsx("time",{className:"pc-ws__time",title:Fj(m.mtime),"data-meta":"modified",children:Np(m.mtime,i)}):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===m.path,onClick:()=>{var h;return(h=e.onFile)==null?void 0:h.call(e,m,"download")},title:"Download","aria-label":`Download ${m.name}`,children:s.jsx(Xe,{name:"download",size:14})}):null]})},m.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 lM={registry_scope:"tenant_catalog",bundle_id:"docs-qa",bundle_version:"0.1.1",flow_id:"docsqa001"},lS="docs";function cM(e){return yt(`docs/corpus?${new URLSearchParams({app:String(e||"")})}`)}function Xg(e){return`${String(e||"app")}-docs-assistant:${Ga()}`}function uM(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}),{...lM,session_id:e.sessionId,kind:lS,input_data:t}}function cS(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 dM(e){const t=e&&typeof e=="object"?e:{},n=c=>typeof c=="number"&&Number.isFinite(c)&&c>0?Math.trunc(c):0,r=n(t.dropped_messages);if(!r)return"";const i=n(t.replayed_messages),a=n(t.dropped_tokens),u=n(t.max_tokens);return`Earlier messages not replayed: ${r.toLocaleString("en-US")}${a?` (~${a.toLocaleString("en-US")} tokens)`:""}. The model read the newest ${i.toLocaleString("en-US")} message${i===1?"":"s"}`+(u?` (history window: the most recent ${u.toLocaleString("en-US")} tokens of whole messages).`:".")}async function*fM(e,t){const n=e.getReader(),r=new TextDecoder;let i="";const a=()=>{n.cancel().catch(()=>{})};t==null||t.addEventListener("abort",a,{once:!0});try{for(;;){const{value:u,done:c}=await n.read();if(c)break;i+=r.decode(u,{stream:!0}).replace(/\r\n/g,`
|
|
77
|
+
`);let d=i.indexOf(`
|
|
78
|
+
|
|
79
|
+
`);for(;d>=0;){const m=i.slice(0,d);i=i.slice(d+2);let h="message";const p=[];for(const y of m.split(`
|
|
80
|
+
`))y.startsWith("event:")?h=y.slice(6).trim():y.startsWith("data:")&&p.push(y.slice(5).replace(/^ /,""));p.length&&(yield{event:h,data:p.join(`
|
|
81
|
+
`)}),d=i.indexOf(`
|
|
82
|
+
|
|
83
|
+
`)}}}finally{t==null||t.removeEventListener("abort",a)}}function mM(e,t){return new Promise((n,r)=>{if(t.aborted)return r(new DOMException("Aborted","AbortError"));const i=setTimeout(()=>{t.removeEventListener("abort",a),n()},e),a=()=>{clearTimeout(i),r(new DOMException("Aborted","AbortError"))};t.addEventListener("abort",a,{once:!0})})}async function Yl(e,t){if(!e.ok)throw await Xd(e,t);return e.json()}function hM(e){const t=e.pollMs??1e3,n=e.timeoutMs??18e4;let r=null;return async(i,a)=>{var x;const{fetchGateway:u,source:c}=e;if(r===null){const k=await u(cM(c.app),{signal:a.signal,headers:{Accept:"application/json"}}),b=await Yl(k,`The ${c.name} documentation could not be read, so nothing was asked`),S=typeof(b==null?void 0:b.text)=="string"?b.text:"";if(!S.trim())throw new Error(`The gateway returned an empty ${c.name} documentation corpus, so nothing was asked.`);r=S}const d=String(r),m=[];for(const k of a.files||[]){const b=new FormData;b.append("session_id",a.sessionId),b.append("file",k,k.name||"upload.bin"),b.append("filename",k.name||"upload.bin"),k.type&&b.append("content_type",k.type);const S=await Yl(await u(yt("attachments/upload"),{method:"POST",body:b,signal:a.signal}),`"${k.name}" could not be attached`),$=S==null?void 0:S.attachment;if(!$||typeof $.$artifact!="string"||!$.$artifact)throw new Error(`"${k.name}" could not be attached: the gateway returned no attachment reference.`);m.push($)}const h=await Yl(await u(yt("runs/start"),{method:"POST",signal:a.signal,headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(uM({question:i,docs:d,appName:c.name,sessionId:a.sessionId,attachments:m}))}),"The docs-qa workflow could not start"),p=String((h==null?void 0:h.run_id)||"");if(!p)throw new Error("The gateway did not return a run id for the docs-qa workflow.");const y=new AbortController,w=()=>y.abort();a.signal.addEventListener("abort",w,{once:!0}),a.onText&&(async()=>{var k;try{const b=await u(yt(`runs/${encodeURIComponent(p)}/ledger/stream?after=0`),{signal:y.signal,headers:{Accept:"text/event-stream"}});if(!b.ok||!b.body)return;let S="",$="";for await(const A of fM(b.body,y.signal)){const E=AT(A.event,A.data);!E||sS(E)||E.channel!=="content"||E.run_id!==p||(E.call_id!==S&&(S=E.call_id,$=""),$=E.snapshot?E.text:$+E.text,(k=a.onText)==null||k.call(a,$))}}catch{}})();try{const k=Date.now()+n;for(;;){await mM(t,a.signal);const b=await Yl(await u(yt(`runs/${encodeURIComponent(p)}`),{signal:a.signal}),"The docs-qa run could not be read"),S=String((b==null?void 0:b.status)||"").toLowerCase();if(S==="completed"){(x=a.onHistory)==null||x.call(a,(b==null?void 0:b.session_history)??null);const $=cS(b);if(!$)throw new Error(`The docs-qa run ${p} completed without an answer.`);return $}if(S==="failed"||S==="cancelled"){const $=b==null?void 0:b.error,A=typeof $=="string"?$:typeof($==null?void 0:$.message)=="string"?$.message:"";throw new Error(`The docs-qa run ${S}${A?`: ${A}`:""}.`)}if(S==="waiting")throw new Error(`The docs-qa run ${p} is waiting for input it should never need. Inspect it in Observer.`);if(Date.now()>=k)throw new Error(`The docs-qa run ${p} is still running after ${Math.round(n/1e3)} s. It stays in the gateway's history.`)}}finally{a.signal.removeEventListener("abort",w),y.abort()}}}async function _M(e,t,n={}){const r=new URLSearchParams({root_only:"true",kind:lS,limit:"500",include_ledger_len:"false"}),i=await Yl(await e(yt(`runs?${r}`),{signal:n.signal}),"The docs assistant history could not be read"),a=`${String(t||"app")}-docs-assistant:`,u=new Map;for(const d of Array.isArray(i==null?void 0:i.items)?i.items:[]){const m=String((d==null?void 0:d.session_id)||"");if(!m.startsWith(a)||!(d!=null&&d.run_id))continue;const h=u.get(m)||{runs:[],updatedAt:""};h.runs.push({id:String(d.run_id),created:String(d.created_at||"")});const p=String(d.updated_at||d.created_at||"");p>h.updatedAt&&(h.updatedAt=p),u.set(m,h)}const c=[...u.entries()].sort((d,m)=>d[1].updatedAt<m[1].updatedAt?1:-1).slice(0,n.max??20);return Promise.all(c.map(async([d,m])=>{var y;const h=m.runs.sort((w,x)=>w.created<x.created?-1:1).map(w=>w.id);let p="";try{const w=await Yl(await e(yt(`runs/${encodeURIComponent(h[0])}/input_data`),{signal:n.signal}),"");p=String(((y=w==null?void 0:w.input_data)==null?void 0:y.prompt)||"").trim()}catch{p=""}return{sessionId:d,title:p||"Untitled question",updatedAt:m.updatedAt,runIds:h}}))}async function pM(e,t,n,r){var a;const i=[];for(const u of t.runIds){const[c,d]=await Promise.all([Yl(await e(yt(`runs/${encodeURIComponent(u)}/input_data`),{signal:r}),"A past question could not be read"),Yl(await e(yt(`runs/${encodeURIComponent(u)}`),{signal:r}),"A past answer could not be read")]),m=String(((a=c==null?void 0:c.input_data)==null?void 0:a.prompt)||"").trim();m&&i.push({id:`u-${u}`,role:"user",content:m,ts:String((d==null?void 0:d.created_at)||"")||void 0});const h=cS(d),p=String((d==null?void 0:d.status)||"").toLowerCase();i.push(h?{id:`a-${u}`,role:"assistant",title:n,content:h,ts:String((d==null?void 0:d.updated_at)||"")||void 0}:{id:`a-${u}`,role:"assistant",title:n,level:"warn",content:p==="completed"?"This answer was empty.":`No answer: the run is ${p||"unknown"}.`})}return i}function gM(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:[Np(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(Xe,{name:"archive",size:16})})]})},r.sessionId))}):s.jsx("div",{className:"pc-docs-history__note",children:"No past conversations yet."})}const yM=/^image\/(png|jpe?g|gif|webp|avif|bmp|svg\+xml)$/i;function wM(e){const t=_.useRef(null),[n,r]=_.useState(!1),i=!!e.blockedNotice,a=!!e.busy,u=e.files||[],c=typeof e.onAddFiles=="function"&&!i,d=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(m=>s.jsx("button",{type:"button",className:"pc-docs-assistant__suggestion",disabled:a||i,onClick:()=>{var h;return(h=e.onSuggestion)==null?void 0:h.call(e,m)},children:m},m))}):null]});return s.jsxs("div",{className:`pc-docs-assistant${n?" is-dragging":""}`,onDragOver:m=>{var h;!c||!Cm((h=m.dataTransfer)==null?void 0:h.types)||(m.preventDefault(),r(!0))},onDragLeave:()=>r(!1),onDrop:m=>{var p,y;if(!c)return;m.preventDefault(),r(!1);const h=kv(m.dataTransfer);h.files.length&&((p=e.onAddFiles)==null||p.call(e,h.files)),h.folders.length&&((y=e.onNotice)==null||y.call(e,tS(h.folders)))},children:[s.jsx(xv,{className:"pc-docs-assistant__thread",messages:e.messages,autoScroll:!0,empty:d,messageProps:{showCopy:!0}}),i?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(bv,{value:e.draft,onChange:e.onDraftChange,onSubmit:e.onSend,placeholder:e.placeholder||`Ask about ${e.source.name}…`,ariaLabel:`Question about ${e.source.name}`,disabled:i,busy:a,rows:1,sendLabel:"Send",busyLabel:"Answering…",onPaste:m=>{var p;if(!c)return;const h=nS(m.clipboardData);h.length&&(m.preventDefault(),(p=e.onAddFiles)==null||p.call(e,h))},leading:u.length?s.jsx("div",{className:"pc-chat-attachments pc-docs-assistant__files",role:"list","aria-label":"Attached files",children:u.map(m=>s.jsxs("span",{role:"listitem",className:"pc-chat-attachment-chip",children:[s.jsx(Xe,{name:"paperclip",size:14}),s.jsx("span",{className:"pc-chat-attachment-name",children:m.name}),e.onRemoveFile&&!a?s.jsx("button",{type:"button",className:"pc-docs-assistant__file-remove","aria-label":`Remove ${m.name}`,"data-af-tip":`Remove ${m.name}`,onClick:()=>{var h;return(h=e.onRemoveFile)==null?void 0:h.call(e,m.id)},children:s.jsx(Xe,{name:"x",size:12})}):null]},m.id))}):null,actions:s.jsxs(s.Fragment,{children:[c?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:a,onClick:()=>{var m;return(m=t.current)==null?void 0:m.click()},children:s.jsx(Xe,{name:"paperclip",size:16})}),s.jsx("input",{ref:t,type:"file",multiple:!0,hidden:!0,"aria-hidden":"true",tabIndex:-1,onChange:m=>{var p;const h=Array.from(m.currentTarget.files||[]);m.currentTarget.value="",h.length&&((p=e.onAddFiles)==null||p.call(e,h))}})]}):null,a&&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(Xe,{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 P_(){return new Date().toISOString()}function vM(e){Yd();const{source:t}=e,n=_.useRef(e.fetchGateway);n.current=e.fetchGateway;const r=_.useMemo(()=>e.ask||hM({fetchGateway:(I,Z)=>n.current(I,Z),source:t}),[e.ask,t.app,t.name]),i=_.useRef(Xg(t.app)),[a,u]=_.useState([]),c=_.useRef(a);c.current=a;const[d,m]=_.useState(""),[h,p]=_.useState([]),[y,w]=_.useState(!1),[x,k]=_.useState(""),b=_.useRef(null),[S,$]=_.useState(!1),[A,E]=_.useState({state:"loading",items:[]});_.useEffect(()=>()=>{var I;return(I=b.current)==null?void 0:I.abort()},[]);const z=_.useCallback(async()=>{E(I=>({...I,state:"loading"}));try{const I=await _M((Z,R)=>n.current(Z,R),t.app);E({state:"ready",items:I})}catch(I){E({state:"error",items:[],error:String((I==null?void 0:I.message)||I)})}},[t.app]),F=_.useCallback(async I=>{var Z;(Z=b.current)==null||Z.abort(),E(R=>({...R,state:"loading"}));try{const R=await pM((T,P)=>n.current(T,P),I,t.name);i.current=I.sessionId,u(R),k(""),$(!1),E(T=>({...T,state:"ready"}))}catch(R){E(T=>({...T,state:"error",error:String((R==null?void 0:R.message)||R)}))}},[t.name]),M=_.useCallback(async I=>{try{const Z=await n.current(yt(`sessions/${encodeURIComponent(I.sessionId)}/archive`),{method:"POST"});if(!Z.ok)throw await Xd(Z,"The conversation could not be archived");i.current===I.sessionId&&(i.current=Xg(t.app),u([])),E(R=>({...R,items:R.items.filter(T=>T.sessionId!==I.sessionId)}))}catch(Z){E(R=>({...R,state:"error",error:String((Z==null?void 0:Z.message)||Z)}))}},[t.app]);_.useEffect(()=>{var I;e.connected||(I=b.current)==null||I.abort()},[e.connected]),_.useEffect(()=>()=>{for(const I of h)I.preview&&URL.revokeObjectURL(I.preview)},[]);const D=_.useCallback(I=>{k(""),p(Z=>[...Z,...I.map(R=>({id:Ga(),file:R,preview:yM.test(R.type)&&typeof URL<"u"&&typeof URL.createObjectURL=="function"?URL.createObjectURL(R):void 0}))])},[]),H=_.useCallback(async I=>{const Z=String(I||"").trim();if(!Z||y||!e.connected)return;const R=h;m(""),p([]),k("");const T=R.filter(Y=>Y.preview).map(Y=>({kind:"image",src:Y.preview,label:Y.file.name})),P=R.map(Y=>({id:Y.id,label:Y.file.name,title:Y.file.name,disabled:!0})),L={id:`u-${Ga()}`,role:"user",content:Z,ts:P_(),...T.length?{media:T}:{},...P.length?{attachments:P}:{}},te=`a-${Ga()}`,X=[...c.current,L],V={id:te,role:"assistant",title:t.name,content:"",ts:P_(),live:{callId:te,reasoning:"",label:"answering"}};u([...X,V]),w(!0);const ne=new AbortController;b.current=ne;const W=Y=>u([...X,Y]);try{const Y=await r(Z,{signal:ne.signal,sessionId:i.current,files:R.map(K=>K.file),onText:K=>{ne.signal.aborted||W({...V,content:K,live:{callId:te,reasoning:"",label:"streaming"}})},onHistory:K=>k(dM(K))});ne.signal.aborted||W({id:te,role:"assistant",title:t.name,content:Y,ts:P_()})}catch(Y){const K=ne.signal.aborted;W({id:te,role:"assistant",title:t.name,level:K?"warn":"error",content:K?"Stopped. Nothing more will be shown for this question.":String((Y==null?void 0:Y.message)||Y||"The docs assistant failed."),ts:P_()})}finally{b.current===ne&&(b.current=null),w(!1)}},[r,y,h,e.connected,t.name]),q=()=>{var I;(I=b.current)==null||I.abort(),i.current=Xg(t.app),u([]),p([]),m(""),k("")};return s.jsxs($2,{open:e.open,onClose:e.onClose,label:"Docs assistant",title:s.jsxs("span",{className:"pc-docs-assistant__title",children:[s.jsx(Xe,{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${S?" is-active":""}`,"aria-label":"Past conversations","data-af-tip":"Past conversations","aria-pressed":S,disabled:!e.connected||y,onClick:()=>{const I=!S;$(I),I&&z()},children:s.jsx(Xe,{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:!a.length&&!d&&!h.length&&!S,onClick:()=>{q(),$(!1)},children:s.jsx(Xe,{name:"compose",size:16})})]}),children:[S?s.jsx("div",{className:"pc-docs-assistant pc-docs-assistant--history",children:s.jsx(gM,{items:A.items,state:A.state,error:A.error,nowMs:Date.now(),activeSessionId:i.current,onOpen:I=>void F(I),onArchive:I=>void M(I)})}):null,s.jsx("div",{hidden:S,style:{display:S?"none":"contents"},children:s.jsx(wM,{source:t,messages:a,draft:d,onDraftChange:m,onSend:()=>void H(d),onStop:()=>{var I;return(I=b.current)==null?void 0:I.abort()},busy:y,blockedNotice:e.connected?void 0:"Connect to the gateway to use the docs assistant.",files:h.map(I=>({id:I.id,name:I.file.name})),onAddFiles:D,onNotice:k,onRemoveFile:I=>p(Z=>{const R=Z.find(T=>T.id===I);return R!=null&&R.preview&&URL.revokeObjectURL(R.preview),Z.filter(T=>T.id!==I)}),notice:x,suggestions:e.suggestions,onSuggestion:I=>void H(I),placeholder:e.placeholder})})]})}const Qn=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},up=e=>Array.isArray(e)?e.map(Qn):[],bn=e=>typeof e=="string"?e:"",cm=e=>bn(e.runtime_call_id||e.call_uid),um=e=>bn(e.call_id||e.id);function uS(e,t){const n=t.record,r=Qn(n.effect);if(r.type!=="tool_calls")return[];const i=Qn(n.result),a=up(Qn(r.payload).tool_calls),u=a.length||n.status!=="waiting"?a:up(Qn(Qn(i.wait).details).tool_calls),c=up(i.results),d=u.length?u:c,m=[];return d.forEach((h,p)=>{let y=cm(h)?c.filter(F=>cm(F)===cm(h)):[];!y.length&&um(h)&&u.filter(F=>um(F)===um(h)).length===1&&(y=c.filter(F=>um(F)===um(h)));const w=u.length?y.length===1?y[0]:u.length===c.length?c[p]:{}:h,x=cm(h)||cm(w)||`${bn(n.idempotency_key)||bn(n.step_id)||t.cursor}:${p}`,k=`${t.runId}:${x}`,b=e.get(k),S=bn(h.name||w.name)||(b==null?void 0:b.name);if(!S)return;const $=n.status==="completed"||n.status==="failed",A=n.status==="failed"||w.success===!1||!!w.error,E=h.arguments??w.arguments??(b==null?void 0:b.arguments),z={...b,id:k,runId:t.runId,name:S,arguments:E,status:$?A?"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)}:{},...uw(w)?{sandbox:uw(w)}:{},startedAt:(b==null?void 0:b.startedAt)||bn(n.started_at)||void 0,endedAt:$&&bn(n.ended_at)||(b==null?void 0:b.endedAt)};b&&["completed","failed"].includes(b.status)&&!$||(e.set(k,z),m.push(z))}),m}function jd(e){if(e==null||e===""||typeof e=="boolean")return;const t=Number(e);return Number.isFinite(t)&&t>=0?t:void 0}function la(e,t){for(const n of t){const r=e==null?void 0:e[n];if(r==null||r===""||typeof r=="boolean")continue;const i=Number(r);if(Number.isFinite(i)&&i>=0)return Math.trunc(i)}}function dS(e){if(typeof e=="string")try{return Qn(JSON.parse(e))}catch{return{}}return Qn(e)}function hd(e,t){if(t===void 0||t==="")return e;const n=e||[];return n.includes(t)||n.push(t),n}function xM(e){return la(e,["reasoning_tokens","thinking_tokens"])??la(Qn(e.completion_tokens_details),["reasoning_tokens"])??la(Qn(e.output_tokens_details),["reasoning_tokens"])}function bM(e){const t=Qn(typeof e=="string"&&e.trim().startsWith("{")?dS(e):e);return bn(t.error_class)}function kM(e){const t=new Map;for(const n of e){const r=n.record;if(Qn(r.effect).type!=="emit_event")continue;const i=Qn(r.result);if(bn(i.name)!=="abstract.progress")continue;const a=Qn(i.payload);if(bn(a.kind)!=="llm"||!bn(a.step_id))continue;const u=`${bn(a.run_id)||n.runId}:${bn(a.step_id)}`,c=t.get(u)||{},d=jd(a.ttft_s);d!==void 0&&(c.ttftS=d),c.provider=c.provider||bn(a.provider)||void 0,c.model=c.model||bn(a.model)||void 0,t.set(u,c)}return t}function Zg(e){var k,b,S,$;const t=new Map,n=new Set,r=new Set,i={llmCalls:0,toolCalls:0,changedFiles:[]};let a=1/0,u=-1/0,c=!1,d=0,m=0,h=0;const p=kM(e),y=[],w=new Set;for(const A of e){const E=A.record,z=`${A.runId}:${E.step_id||A.cursor}:${E.status}`;if(n.has(z))continue;n.add(z);for(const pe of[E.started_at,E.ended_at]){const $e=Date.parse(bn(pe));Number.isFinite($e)&&(a=Math.min(a,$e),u=Math.max(u,$e))}for(const pe of uS(t,A))pe.status==="waiting"&&w.add(pe.id);if(Qn(E.effect).type!=="llm_call"||E.status!=="completed")continue;i.llmCalls+=1;const F=Qn(E.result),M=Qn(F.output),D=Qn(F.usage||F.token_usage||F.tokens||M.usage||M.token_usage||M.tokens),H=la(D,["input_tokens","prompt_tokens","prompt","input","in"]),q=la(D,["output_tokens","completion_tokens","completion","output","out"]),I=la(D,["total_tokens","total"])??(H!==void 0||q!==void 0?(H||0)+(q||0):void 0);I!==void 0&&(H===void 0||q===void 0||H+q!==I)&&(c=!0),H!==void 0&&(i.inputTokens=(i.inputTokens||0)+H),q!==void 0&&(i.outputTokens=(i.outputTokens||0)+q),I!==void 0&&(i.totalTokens=(i.totalTokens||0)+I);const Z=jd(F.gen_time??M.gen_time);Z!==void 0&&(i.genTimeMs=(i.genTimeMs||0)+Z,i.timedCalls=(i.timedCalls||0)+1);const R=Qn(F.metadata||M.metadata),T=Qn(R.performance),P=jd(T.prompt_tokens_per_second),L=jd(T.generation_tokens_per_second),te=Qn(R.prompt_cache),X=jd(te.cached_tokens),V=jd(te.fed_tokens);if(P!==void 0||L!==void 0){if(i.measuredSpeedCalls=(i.measuredSpeedCalls||0)+1,P!==void 0&&P>0&&(i.promptTokensPerSecond=(i.promptTokensPerSecond||0)+P,H!==void 0)){const pe=H/P*1e3;i.prefillMs=(i.prefillMs||0)+pe,V!==void 0&&(d+=V,m+=pe)}L!==void 0&&L>0&&(i.generationTokensPerSecond=(i.generationTokensPerSecond||0)+L,q!==void 0&&(i.decodeMs=(i.decodeMs||0)+q/L*1e3))}if(X!==void 0||V!==void 0){i.measuredCacheCalls=(i.measuredCacheCalls||0)+1,i.cachedTokens=(i.cachedTokens||0)+(X||0),i.fedTokens=(i.fedTokens||0)+(V||0);const pe=bn(te.outcome);if(pe){const $e=i.cacheOutcomes||[];$e.includes(pe)||$e.push(pe),i.cacheOutcomes=$e}}const ne=bn(E.step_id)||void 0,W=ne&&p.get(`${A.runId}:${ne}`)||{},Y=Qn(F.route),K={runId:A.runId};ne&&(K.stepId=ne),bn(E.started_at)&&(K.startedAt=bn(E.started_at));const fe=bn(F.model||M.model)||bn(Y.model)||W.model,ae=bn(Y.provider)||bn(Qn(R._provider_request).provider)||W.provider||bn(F.provider);fe&&(K.model=fe),ae&&(K.provider=ae),fe&&(i.models=hd(i.models,fe)),ae&&(i.providers=hd(i.providers,ae)),(I===void 0||H!==void 0&&q!==void 0&&H+q===I)&&(H!==void 0&&(K.inputTokens=H),q!==void 0&&(K.outputTokens=q)),I!==void 0&&(K.totalTokens=I);const ve=xM(D);ve!==void 0&&(K.reasoningTokens=ve,i.reasoningTokens=(i.reasoningTokens||0)+ve),X!==void 0&&(K.cachedTokens=X),V!==void 0&&(K.fedTokens=V),bn(te.outcome)&&(K.cacheOutcome=bn(te.outcome)),bn(te.backend)&&(K.cacheBackend=bn(te.backend),i.cacheBackends=hd(i.cacheBackends,K.cacheBackend)),Z!==void 0&&(K.genTimeMs=Z),P!==void 0&&P>0&&(K.promptTokensPerSecond=P),L!==void 0&&L>0&&(K.generationTokensPerSecond=L),W.ttftS!==void 0?(K.ttftMs=W.ttftS*1e3,K.promptMs=K.ttftMs,K.promptSource="ttft",i.ttftMs=(i.ttftMs||0)+K.ttftMs,i.ttftCalls=(i.ttftCalls||0)+1):K.promptTokensPerSecond!==void 0&&H!==void 0&&(K.promptMs=H/K.promptTokensPerSecond*1e3,K.promptSource="rate"),K.promptMs!==void 0&&(i.promptPhaseMs=(i.promptPhaseMs||0)+K.promptMs,i.promptPhaseCalls=(i.promptPhaseCalls||0)+1,V!==void 0&&K.promptMs>0&&(K.promptNewTokensPerSecond=V/(K.promptMs/1e3),i.promptPhaseNewTokens=(i.promptPhaseNewTokens||0)+V,h+=K.promptMs)),K.ttftMs!==void 0&&Z!==void 0&&Z>=K.ttftMs?K.generationMs=Z-K.ttftMs:K.generationTokensPerSecond!==void 0&&q!==void 0&&(K.generationMs=q/K.generationTokensPerSecond*1e3),K.generationMs!==void 0&&q!==void 0&&(i.generationPhaseMs=(i.generationPhaseMs||0)+K.generationMs,i.generationPhaseTokens=(i.generationPhaseTokens||0)+q);const ge=Qn(R.speculation);if(Object.keys(ge).length){const pe={};bn(ge.mode)&&(pe.mode=bn(ge.mode)),typeof ge.used=="boolean"&&(pe.used=ge.used),bn(ge.draft_kind)&&(pe.draftKind=bn(ge.draft_kind));const $e=la(ge,["accepted_tokens"]),De=la(ge,["drafted_tokens"]),ot=la(ge,["rounds"]),bt=la(ge,["num_draft_tokens"]);$e!==void 0&&(pe.acceptedTokens=$e),De!==void 0&&(pe.draftedTokens=De),$e!==void 0&&De&&(pe.acceptanceRate=$e/De),ot!==void 0&&(pe.rounds=ot),bt!==void 0&&(pe.draftLength=bt),K.speculation=pe;const Ue=i.speculation||(i.speculation={calls:0,used:0});Ue.calls+=1,pe.used&&(Ue.used+=1),pe.mode&&(Ue.modes=hd(Ue.modes,pe.mode)),pe.draftKind&&(Ue.draftKinds=hd(Ue.draftKinds,pe.draftKind)),$e!==void 0&&De!==void 0&&(Ue.acceptedTokens=(Ue.acceptedTokens||0)+$e,Ue.draftedTokens=(Ue.draftedTokens||0)+De),ot!==void 0&&(Ue.rounds=(Ue.rounds||0)+ot),bt!==void 0&&(Ue.draftLengths=hd(Ue.draftLengths,bt))}y.push(K)}y.length&&(y.every(A=>A.startedAt)&&y.sort((A,E)=>Date.parse(A.startedAt)-Date.parse(E.startedAt)),i.modelCalls=y),h>0&&i.promptPhaseNewTokens!==void 0&&(i.promptPhaseTokensPerSecond=i.promptPhaseNewTokens/(h/1e3)),i.generationPhaseMs&&i.generationPhaseTokens!==void 0&&(i.generationPhaseTokensPerSecond=i.generationPhaseTokens/(i.generationPhaseMs/1e3)),(k=i.speculation)!=null&&k.draftedTokens&&(i.speculation.acceptanceRate=(i.speculation.acceptedTokens||0)/i.speculation.draftedTokens),i.measuredSpeedCalls&&(i.promptTokensPerSecond!==void 0&&(i.promptTokensPerSecond/=i.measuredSpeedCalls),i.generationTokensPerSecond!==void 0&&(i.generationTokensPerSecond/=i.measuredSpeedCalls)),m>0&&(i.prefillNewTokens=d,i.prefillNewTokensPerSecond=d/(m/1e3));const x=new Map;for(const A of t.values()){if(A.status==="waiting"){i.toolsWaiting=(i.toolsWaiting||0)+1;continue}if(A.status==="running"){i.toolsRunning=(i.toolsRunning||0)+1;continue}if(!["completed","failed"].includes(A.status))continue;i.toolCalls+=1;const E=A.status==="failed";E&&(i.toolsFailed=(i.toolsFailed||0)+1);const z=i.toolBreakdown||(i.toolBreakdown={}),F=z[A.name]||(z[A.name]={calls:0,failed:0});if(F.calls+=1,E){F.failed+=1;const I=bM(A.output);I&&((F.errors||(F.errors={}))[I]=(((b=F.errors)==null?void 0:b[I])||0)+1)}const M=Date.parse(bn(A.startedAt)),D=Date.parse(bn(A.endedAt));if(Number.isFinite(M)&&Number.isFinite(D)&&D>=M){const I=`${A.runId}|${A.startedAt}|${A.endedAt}`,Z=x.get(I)||{ms:D-M,calls:0,names:new Map,waited:!1};Z.calls+=1,Z.names.set(A.name,(Z.names.get(A.name)||0)+1),w.has(A.id)&&(Z.waited=!0),x.set(I,Z)}if(A.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(A.name))continue;const H=dS(A.arguments),q=bn(H.destination||H.destination_path||H.file_path||H.path||H.filename);q&&r.add(q)}for(const A of x.values()){i.toolBatches=(i.toolBatches||0)+1,i.toolTimeMs=(i.toolTimeMs||0)+A.ms,A.waited&&(i.toolTimeIncludesApproval=!0);const E=[...A.names.keys()].sort();(!i.slowestToolBatch||A.ms>i.slowestToolBatch.ms)&&(i.slowestToolBatch={ms:A.ms,calls:A.calls,tools:E});const z=(S=i.toolBreakdown)==null?void 0:S[E[0]];if(E.length===1&&z)z.ms=(z.ms||0)+A.ms;else for(const F of E){const M=($=i.toolBreakdown)==null?void 0:$[F];M&&(M.sharedBatches=(M.sharedBatches||0)+1)}}return i.changedFiles=[...r],c&&(delete i.inputTokens,delete i.outputTokens),Number.isFinite(a)&&Number.isFinite(u)&&(i.durationMs=Math.max(0,u-a)),{tools:[...t.values()],statistics:i}}function jM(e){const t=Qn(Qn(e).ledgers);return Object.entries(t).flatMap(([n,r])=>up(Qn(r).items).map((i,a)=>({runId:n,cursor:Number(i.cursor)||a+1,record:Object.keys(Qn(i.record)).length?Qn(i.record):i})))}function SM(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 NM(e){return(e instanceof Error?e.message:String(e||"Unknown error")).trim()||"Unknown error"}function $M(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 CM(e){var M;const t=e.interaction,[n,r]=_.useState(""),[i,a]=_.useState(()=>t.kind==="event-wait"&&t.initialPayload||""),[u,c]=_.useState(null),[d,m]=_.useState(!1),[h,p]=_.useState(""),[y,w]=_.useState(null),x=`${t.kind}:${t.id}`,k=_.useRef(x),b=_.useRef(!1),S=_.useRef(!1),$=_.useRef(!0),A=_.useRef(0);k.current!==x&&(k.current=x,b.current=!1,S.current=!1,A.current+=1);const E=!!e.disabled||u!==null||d||b.current||S.current,z=async(D,H)=>{var Z;if(e.disabled||b.current||S.current)return;const q=x,I=++A.current;b.current=!0,w(null),p(""),c(D);try{if(await H(),!$.current||k.current!==q||A.current!==I)return;S.current=!0,m(!0),p("Response sent. Waiting for the workflow to continue.")}catch(R){if(!$.current||k.current!==q||A.current!==I)return;w({submission:D,message:NM(R)}),p("The action failed. You can try again."),(Z=e.onError)==null||Z.call(e,R)}finally{if(!$.current||k.current!==q||A.current!==I)return;b.current=!1,c(null)}};_.useEffect(()=>{r(""),a(t.kind==="event-wait"&&t.initialPayload||""),w(null),c(null),m(!1),p("")},[x]),_.useEffect(()=>($.current=!0,()=>{$.current=!1,A.current+=1,b.current=!1}),[]);const F=()=>{y&&z(y.submission,()=>SM(t,y.submission))};return s.jsxs("section",{className:"pc-workflow-interaction","aria-labelledby":`pc-workflow-interaction-${x}`,children:[s.jsxs("div",{className:"pc-workflow-interaction__heading",children:[s.jsx(Xe,{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-${x}`,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}),(M=t.choices)!=null&&M.length?s.jsx("div",{className:"pc-workflow-interaction__choices","aria-label":"Choices",children:t.choices.map(D=>s.jsxs("button",{type:"button",className:"pc-workflow-interaction__choice",disabled:E||D.disabled,onClick:()=>void z({kind:"choice",answer:D.id},()=>t.onSubmit(D.id)),children:[s.jsx("span",{children:D.label}),D.description?s.jsx("small",{children:D.description}):null]},D.id))}):null,t.allowFreeText!==!1?s.jsxs("div",{className:"pc-workflow-interaction__entry",children:[s.jsx("textarea",{"aria-label":"Response",value:n,onChange:D=>r(D.target.value),placeholder:t.freeTextPlaceholder||"Type a response",rows:2,disabled:E,onKeyDown:D=>{D.key!=="Enter"||D.shiftKey||D.nativeEvent.isComposing||D.keyCode===229||(D.preventDefault(),n.trim()&&z({kind:"free-text",answer:n},()=>t.onSubmit(n)))}},`${x}:text`),s.jsx("button",{type:"button",className:"pc-btn",disabled:E||!n.trim(),onClick:()=>void z({kind:"free-text",answer:n},()=>t.onSubmit(n)),children:(u==null?void 0:u.kind)==="free-text"?"Sending…":t.submitLabel||"Submit"})]}):null]}):t.kind==="tool-approval"?s.jsxs("div",{className:"pc-workflow-interaction__body",children:[s.jsxs("div",{className:"pc-workflow-interaction__prompt",children:["Allow ",s.jsx("strong",{children:t.toolName})," to run?"]}),t.detail?s.jsx("div",{className:"pc-workflow-interaction__detail",children:t.detail}):null,s.jsxs("div",{className:"pc-workflow-interaction__buttons",children:[s.jsx("button",{type:"button",className:"pc-workflow-interaction__deny",disabled:E,onClick:()=>void z({kind:"deny"},t.onDeny),children:(u==null?void 0:u.kind)==="deny"?"Denying…":t.denyLabel||"Deny"}),s.jsx("button",{type:"button",className:"pc-btn",disabled:E,onClick:()=>void z({kind:"approve"},t.onApprove),children:(u==null?void 0:u.kind)==="approve"?"Approving…":t.approveLabel||"Approve"}),t.onApproveAll?s.jsx("button",{type:"button",className:"pc-workflow-interaction__allow-all",disabled:E,onClick:()=>void z({kind:"approve-all"},t.onApproveAll),children:(u==null?void 0:u.kind)==="approve-all"?"Approving…":t.approveAllLabel||"Allow all"}):null]}),t.onApproveAll&&t.approveAllDescription?s.jsx("p",{className:"pc-workflow-interaction__scope",children:t.approveAllDescription}):null]}):s.jsxs("div",{className:"pc-workflow-interaction__body",children:[s.jsx("div",{className:"pc-workflow-interaction__prompt",children:t.prompt}),s.jsxs("label",{className:"pc-workflow-interaction__entry",children:[s.jsx("span",{children:t.payloadLabel||(t.eventName?`Payload for ${t.eventName}`:"Event payload")}),s.jsx("textarea",{value:i,onChange:D=>a(D.target.value),placeholder:t.payloadPlaceholder||"Enter payload",rows:2,"aria-label":t.payloadLabel||(t.eventName?`Payload for ${t.eventName}`:"Event payload"),disabled:E},`${x}:payload`)]}),s.jsx("div",{className:"pc-workflow-interaction__buttons",children:s.jsx("button",{type:"button",className:"pc-btn",disabled:E,onClick:()=>void z({kind:"event",payload:i},()=>t.onSend(i)),children:(u==null?void 0:u.kind)==="event"?"Sending…":t.sendLabel||"Send event"})})]}),y?s.jsx($M,{message:y.message,onRetry:F,disabled:E}):null,s.jsx("div",{className:"pc-workflow-interaction__outcome","aria-live":"polite",children:h})]})}function D_(e){return(e instanceof Error?e.message:String(e||"Unknown error")).trim()||"Unknown error"}function EM(e){Yd();const[t,n]=_.useState(!1),[r,i]=_.useState(!1),[a,u]=_.useState(!1),[c,d]=_.useState(null),m=_.useRef(!0),h=_.useRef(!1),p=_.useRef(!1),y=_.useRef(!1),w=_.useRef(0),x=_.useRef(0),k=_.useRef(0);_.useEffect(()=>(m.current=!0,()=>{m.current=!1,w.current+=1,x.current+=1,k.current+=1,h.current=!1,p.current=!1,y.current=!1}),[]);const b=!!e.blockedNotice,S=!!e.disabled||b,$=!!e.busy||t,A=t||!!e.busy&&!e.sendWhileBusy,E=e.stopState||null,z=(E==null?void 0:E.phase)==="stopping",F=typeof e.onFiles=="function",M=_.useRef(null),[D,H]=_.useState(null),[q,I]=_.useState(""),Z=_.useRef(e.onFiles);Z.current=e.onFiles;const R=_.useRef(S);R.current=S;const T=async(K,fe)=>{const ae=Z.current;if(ae){if(R.current){d({action:"attach",message:"attachments are unavailable right now."});return}if(fe.length)d({action:"attach",message:tS(fe)});else if(K.length)d(null);else{d({action:"attach",message:"the drop contained no files."});return}if(K.length){I(`Attaching ${K.length} ${K.length===1?"file":"files"}…`);try{await ae(K)}catch(ve){m.current&&d({action:"attach",message:D_(ve)})}}}},P=_.useRef(T);P.current=T,_.useEffect(()=>{if(!F||typeof window>"u")return;const K=new $T;let fe=0;const ae=Ue=>!!(M.current&&Ue instanceof Node&&M.current.contains(Ue)),ve=()=>{K.reset(),fe&&window.clearInterval(fe),fe=0,H(null)},ge=()=>{fe||(fe=window.setInterval(()=>{K.active(Date.now())||ve()},250))},pe=Ue=>{var ut;if(!Cm((ut=Ue.dataTransfer)==null?void 0:ut.types))return;K.enter(Date.now());const at=ae(Ue.target),Nt=cb(Ue.dataTransfer);H(Se=>Se&&Se.over===at&&Se.count===(Nt??Se.count)?Se:{count:Nt??(Se==null?void 0:Se.count)??null,over:at}),ge()},$e=Ue=>{var Nt;if(!Cm((Nt=Ue.dataTransfer)==null?void 0:Nt.types))return;Ue.preventDefault(),K.over(Date.now());const at=ae(Ue.target);Ue.dataTransfer&&(Ue.dataTransfer.dropEffect=at&&!R.current?"copy":"none"),H(ut=>ut&&ut.over===at?ut:{count:(ut==null?void 0:ut.count)??cb(Ue.dataTransfer),over:at}),ge()},De=Ue=>{var at;Cm((at=Ue.dataTransfer)==null?void 0:at.types)&&(K.leave(Date.now())||ve())},ot=Ue=>{var me;if(!Cm((me=Ue.dataTransfer)==null?void 0:me.types))return;const at=ae(Ue.target),Nt=Ue.defaultPrevented&&!at;if(Ue.preventDefault(),ve(),Nt)return;if(!at){d({action:"attach",message:"drop files on the conversation to attach them."});return}const{files:ut,folders:Se}=kv(Ue.dataTransfer);P.current(ut,Se)},bt=Ue=>{Ue.key==="Escape"&&K.depth>0&&ve()};return window.addEventListener("dragenter",pe),window.addEventListener("dragover",$e),window.addEventListener("dragleave",De),window.addEventListener("drop",ot),window.addEventListener("dragend",ve),window.addEventListener("blur",ve),window.addEventListener("keydown",bt),()=>{window.removeEventListener("dragenter",pe),window.removeEventListener("dragover",$e),window.removeEventListener("dragleave",De),window.removeEventListener("drop",ot),window.removeEventListener("dragend",ve),window.removeEventListener("blur",ve),window.removeEventListener("keydown",bt),fe&&window.clearInterval(fe)}},[F]);const L=K=>{if(!F||S)return;const fe=nS(K.clipboardData);fe.length&&(K.preventDefault(),T(fe,[]))},te=D?s.jsxs("div",{className:["pc-workflow-chat__dropzone",D.over?"is-over":"",S?"is-disabled":""].filter(Boolean).join(" "),"aria-hidden":"true",children:[s.jsx("span",{className:"pc-workflow-chat__dropzone-icon",children:s.jsx(Xe,{name:"paperclip",size:18})}),s.jsxs("span",{className:"pc-workflow-chat__dropzone-text",children:[s.jsx("strong",{children:S?"Attachments are unavailable right now":ub(D.count)}),S?null:s.jsx("span",{children:D.over?"Release to upload to this conversation":"Drop anywhere on the conversation"})]})]}):null,X=D?S?"Attachments are unavailable right now":ub(D.count):q,V=async()=>{const K=String(e.draft||"");if(S||h.current||!e.sendWhileBusy&&e.busy||!K.trim())return;const fe=++w.current;h.current=!0,d(null),n(!0);try{await e.onSend(K)}catch(ae){m.current&&w.current===fe&&d({action:"send",message:D_(ae)})}finally{m.current&&w.current===fe&&(h.current=!1,n(!1))}},ne=async()=>{if(S||p.current||!e.onCancel)return;const K=++x.current;p.current=!0,d(null),i(!0);try{await e.onCancel()}catch(fe){m.current&&x.current===K&&d({action:"cancel",message:D_(fe)})}finally{m.current&&x.current===K&&(p.current=!1,i(!1))}},W=async()=>{if(S||y.current||!e.onAttach)return;const K=++k.current;y.current=!0,d(null),u(!0);try{await e.onAttach()}catch(fe){m.current&&k.current===K&&d({action:"attach",message:D_(fe)})}finally{m.current&&k.current===K&&(y.current=!1,u(!1))}},Y=()=>{c&&(c.action==="send"&&V(),c.action==="cancel"&&ne(),c.action==="attach"&&W())};return s.jsxs("section",{ref:M,className:["pc-workflow-chat",D?"pc-workflow-chat--dragging":"",D!=null&&D.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(xv,{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(CM,{interaction:e.interaction,disabled:S}):null,b?s.jsx("div",{className:"pc-workflow-chat__blocked",role:"status",children:e.blockedNotice}):null]}),afterKey:`${e.interaction?`${e.interaction.kind}:${e.interaction.id}`:""}:${b?"blocked":""}`})}),c?s.jsxs("div",{className:"pc-workflow-chat__error",role:"alert",children:[s.jsxs("span",{children:["Could not ",c.action==="send"?"send this message":c.action==="attach"?"attach a file":"stop the run",": ",c.message]}),s.jsx("button",{type:"button",onClick:Y,disabled:S,children:"Try again"})]}):null,s.jsxs("div",{className:"pc-workflow-chat__composer",children:[s.jsx(bv,{value:e.draft,onChange:e.onDraftChange,onSubmit:()=>void V(),placeholder:e.placeholder||"Send a message",ariaLabel:"Message",disabled:S,busy:A,sendLabel:e.sendLabel,busyLabel:e.busyLabel,rows:2,leading:e.attachments?s.jsx("div",{className:"pc-workflow-chat__attachments",children:e.attachments}):null,overlay:te,onPaste:F?L: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:S||a,onClick:()=>void W(),children:[s.jsx(Xe,{name:"paperclip",size:16}),s.jsx("span",{children:a?"Attaching…":"Attach"})]}):null,e.composerExtras,$&&e.onCancel?s.jsxs("button",{type:"button",className:"pc-workflow-chat__stop",disabled:S||r||z,onClick:()=>void ne(),children:[s.jsx(Xe,{name:"x",size:14}),s.jsx("span",{children:r||z?"Stopping…":"Stop"})]}):E?s.jsx("span",{className:`pc-workflow-chat__stop-state pc-workflow-chat__stop-state--${E.phase}`,role:"status","aria-live":"polite",children:E.label}):null]})}),F?s.jsx("div",{className:"pc-sr-only",role:"status","aria-live":"polite",children:X}):null]}),e.footer?s.jsx("footer",{className:"pc-workflow-chat__footer",children:e.footer}):null]})}function AM(e){return e.toolApprovalGranted?null:e.interaction}const fb={messages:[],records:[],run:null,interaction:null,status:"idle",displayStatus:"",loading:!1,error:null,connection:"idle",toolApprovalGranted:!1,stop:null};function Jt(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Ft(e){return typeof e=="string"?e.trim():e==null?"":typeof e=="number"||typeof e=="boolean"?String(e):""}function Am(e){return Array.isArray(e)?e:[]}function gi(e){return Ft(e==null?void 0:e.status).toLowerCase()||"unknown"}function Js(e){return["completed","failed","cancelled"].includes(e.toLowerCase())}function zl(e){const t=Jt(e),n=Number((t==null?void 0:t.status)??(t==null?void 0:t.statusCode));return n===401||n===403}function TM(e){const t=Jt(e);return Number((t==null?void 0:t.status)??(t==null?void 0:t.statusCode))}function Qg(e){const t=n=>{if(Array.isArray(n))return n.map(t);const r=Jt(n);if(!r)return n;const i={};for(const a of Object.keys(r).sort())i[a]=t(r[a]);return i};try{return JSON.stringify(t(e))}catch{return"[unserializable]"}}function dw(e){if(typeof e=="string")return e.trim();const t=Jt(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 _d(e){const t=dw(e);if(t)return t;if(!Jt(e)&&!Array.isArray(e))return"";try{return JSON.stringify(e,null,2)}catch{return""}}function mb(e){if(!e)return"";for(const r of["prompt","request","task","message","query","input"]){const i=Ft(e[r]);if(i)return i}const t=Jt(e.context);for(const r of["task","message"]){const i=Ft(t==null?void 0:t[r]);if(i)return i}const n=Am(t==null?void 0:t.messages);for(let r=n.length-1;r>=0;r-=1){const i=Jt(n[r]);if(Ft(i==null?void 0:i.role).toLowerCase()!=="user")continue;const a=Ft(i==null?void 0:i.content);if(a)return a}return""}function fS(e){const t=Jt(e.result);return Jt(t==null?void 0:t.wait)}function ey(e){return e?Ft(e.reason)==="subworkflow"||Ft(e.wait_key).startsWith("subworkflow:"):!1}function hb(e,t){return!!(e&&e.runId===t.runId&&Ft(e.wait.wait_key)===Ft(t.wait.wait_key))}function fw(e){return Jt(e.effect)||{}}function MM(e,t){return Ft(e.run_id)||t}function _b(e){return Ft(e.ended_at)||Ft(e.started_at)||void 0}function pb(e){const t=new Set,n=m=>{const h=Ft(m);h&&t.add(h)},r=Jt(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 i=fw(e),a=Jt(i.payload);Ft(i.type)==="start_subworkflow"&&(n(a==null?void 0:a.sub_run_id),n(a==null?void 0:a.subRunId),n(a==null?void 0:a.child_run_id));const u=fS(e),c=Jt(u==null?void 0:u.details);n(c==null?void 0:c.sub_run_id),n(c==null?void 0:c.subRunId),n(c==null?void 0:c.child_run_id);const d=Ft(u==null?void 0:u.wait_key);return d.startsWith("subworkflow:")&&n(d.slice(12)),[...t]}class RM{constructor(t,n={}){this.transport=t,this.options=n,this.snapshot={...fb},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({...fb})}dispose(){this.reset(),this.subscribers.clear()}async load(t){const n=Ft(t);if(this.reset(),!n)return;const r=++this.generation,i=new AbortController;this.controller=i,this.rootRunId=n,this.set({...this.snapshot,loading:!0,status:"loading",error:null,connection:"connecting"});try{const[a,u]=await Promise.all([this.transport.getRun(n,i.signal),this.transport.getHistory(n,i.signal)]);if(!this.live(r))return;const c=Jt(a),d=Jt(c==null?void 0:c.waiting),m=gi(c);if(await this.ingestHistory(u,n,r),!this.live(r))return;if(this.set({...this.snapshot,run:c,status:m,loading:!1,...d&&!Js(m)?{interaction:this.interactionWith({runId:n,wait:d})}:{}}),c&&this.updateRunState(n,c),d)for(const h of pb({result:{wait:d}}))h!==n&&this.catchUpAndWatch(h,r);await this.catchUpAndWatch(n,r),this.pollRootLifecycle(n,r)}catch(a){!i.signal.aborted&&this.live(r)&&this.fail(a)}}async sendCommand(t,n={}){var h,p;t==="cancel"&&(this.toolApprovalStopped=!0,this.revokeToolApproval(),this.stopRequested=!0,this.recomputeStop());const r=Ft(n.wait_key),i=t==="resume"?r?this.interactionRunId()||this.rootRunId:this.rootRunId:t==="emit_event"?this.interactionRunId()||this.rootRunId:this.rootRunId;if(!i)throw new Error("No workflow run is loaded");const a=t==="resume"&&r&&((h=this.snapshot.interaction)==null?void 0:h.stepId)||"",u=`${i}\0${t}\0${a}\0${Qg(n)}`;let c=this.commandIds.get(u);c||(c=this.newCommandId(),this.commandIds.set(u,c));const d=this.generation,m=(p=this.controller)==null?void 0:p.signal;try{const y=await this.transport.submitCommand({command_id:c,run_id:i,type:t,payload:n,...this.options.clientId?{client_id:this.options.clientId}:{}},m);if(!this.live(d))return y;const w=Jt(y);if(w&&w.accepted===!1)throw t==="cancel"&&(this.stopRequested=!1,this.recomputeStop()),new Error(Ft(w.detail)||"Gateway did not accept the command");return this.commandIds.delete(u),i===this.rootRunId&&["pause","resume","cancel"].includes(t)&&this.refreshRunState(i,d),y}catch(y){throw this.live(d)&&this.fail(y,!1),y}}resume(t){const n=this.requireInteraction();return this.sendCommand("resume",{wait_key:Ft(n.wait.wait_key),payload:{response:t}})}approve(t,n){const r=this.requireInteraction();if(Js(this.snapshot.status))throw new Error("This run has already ended.");if(n&&(r.runId!==n.runId||Ft(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 i=this.generation;return this.sendCommand("resume",{wait_key:Ft(r.wait.wait_key),payload:{approved:!!t}}).then(a=>{if(!this.live(i))return a;const u=this.occurrenceKey(r);return this.approvedWaits.add(u),t&&this.isToolApproval(r)&&!this.grantedToolWaits.has(u)&&(this.grantedToolWaits.add(u),this.set({...this.snapshot})),a})}async approveWithPolicyChange(t,n){const r=this.generation,i=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)||i!==this.approvalEpoch||this.toolApprovalStopped||Js(this.snapshot.status))&&n()}async allowAllToolsForRun(t){const n=this.generation,r=this.approvalEpoch,i=this.requireInteraction();if(!this.isToolApproval(i))throw new Error("This is not a tool approval request.");await this.approve(!0,t),!(!this.live(n)||r!==this.approvalEpoch||Js(this.snapshot.status))&&(this.approvedWaits.add(`${t.runId}:${t.waitKey}${i.stepId?`:${i.stepId}`:""}`),this.set({...this.snapshot,autoApproveTools:!0}))}revokeToolApproval(){this.approvalEpoch+=1,this.toolApprovalSuspended=!0,this.set({...this.snapshot,autoApproveTools:!1})}setToolApprovalPolicy(t){Qg(t)!==Qg(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}:${Ft(t.wait.wait_key)}${t.stepId?`:${t.stepId}`:""}`}interactionWith(t){const n=this.snapshot.interaction;return n&&ey(t.wait)&&!ey(n.wait)?n:n&&hb(n,t)&&t.stepId===void 0&&n.stepId!==void 0?{...t,stepId:n.stepId}:t}adoptDurableWait(t,n){const r=Jt(n.waiting);if(!r||gi(n)!=="waiting"||ey(r)||Js(this.snapshot.status)||this.resolvedWaits.has(`${t}:${Ft(r.wait_key)}`))return;const i=this.interactionWith({runId:t,wait:r}),a=this.snapshot.interaction;a&&hb(a,i)&&a.stepId===i.stepId||this.set({...this.snapshot,interaction:i})}coveredByStandingPermission(t,n){var r;return t.loading||this.toolApprovalStopped||this.toolApprovalSuspended||!this.toolApprovalPolicy&&!t.autoApproveTools||Js(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:!!Ft(n.wait.wait_key)}present(t){const n=t.interaction,r=n?this.occurrenceKey(n):"",i=!!(n&&this.isToolApproval(n)&&(this.grantedToolWaits.has(r)||!this.approvedWaits.has(r)&&this.coveredByStandingPermission({...t,loading:!1},n)));if(!i&&!this.snapshot.toolApprovalGranted&&!t.toolApprovalGranted)return t.toolApprovalGranted===!1?t:{...t,toolApprovalGranted:!1};let a=!1;const u=t.messages.map(c=>{var h;const d=c.toolActivity;if(!d||((h=this.toolActivities.get(d.id))==null?void 0:h.status)!=="waiting")return c;const m=i&&d.runId===(n==null?void 0:n.runId)?"running":"waiting";return d.status===m?c:(a=!0,this.toolMessage({...d,status:m}))});return{...t,toolApprovalGranted:i,...a?{messages:u}:{}}}toolCallsMatch(t,n){var i;const r=Am((i=Jt(t.wait.details))==null?void 0:i.tool_calls);return r.length>0&&r.every(a=>{var c;const u=Ft((c=Jt(a))==null?void 0:c.name);return!!u&&n.includes(u)})}isToolApproval(t){const n=Jt(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:Ft(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 i=this.generation,a=this.approvalEpoch;this.approve(!0,n).catch(u=>{if(this.live(i)){if(this.grantedToolWaits.delete(r),a!==this.approvalEpoch){this.set({...this.snapshot});return}this.toolApprovalSuspended=!0,this.set({...this.snapshot,autoApproveTools:!1}),this.fail(u,!1)}})}emitEvent(t){return this.sendCommand("emit_event",t)}cancel(){return this.sendCommand("cancel",{})}requireInteraction(){if(!this.snapshot.interaction)throw new Error("This workflow is not waiting for input");if(!Ft(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 i=Jt(await this.transport.getRun(t,(r=this.controller)==null?void 0:r.signal));if(!this.live(n))return;i&&this.updateRunState(t,i)}catch(i){if(!this.live(n))return;if(zl(i))throw i;this.fail(i,!1)}if(await this.catchUp(t,n),!this.live(n)||Js(gi(this.runStates.get(t)||null)))return;this.childCatchUpAttempts.delete(t),this.watch(t,n)}catch(i){if(!this.live(n))return;if(this.watchedRuns.delete(t),t===this.rootRunId)throw i;if(zl(i)){this.fail(i);return}const a=(this.childCatchUpAttempts.get(t)||0)+1;if(this.childCatchUpAttempts.set(t,a),this.fail(i,!1),a>=5)return;await this.waitForRetry(Math.min(2e3,150*2**(a-1))),this.live(n)&&this.catchUpAndWatch(t,n)}}}async catchUp(t,n){var r;for(let i=0;i<100&&this.live(n);i+=1){const a=this.cursors.get(t)||0,u=await this.transport.getLedger(t,a,(r=this.controller)==null?void 0:r.signal);if(!this.live(n))return;const c=Jt(u),d=Array.isArray(u)?u:Am(c==null?void 0:c.items);for(const h of d)this.ingestItem(t,h);const m=Number(c==null?void 0:c.next_after);if(!d.length||!Number.isFinite(m)||m<=a)break;this.cursors.set(t,m)}}async watch(t,n){try{await this.followStream(t,n)}finally{this.live(n)&&this.closeLiveRepliesVia(t)}}async followStream(t,n){var i;let r=0;for(;this.live(n)&&!Js(gi(this.runStates.get(t)||null));){const a=this.cursors.get(t)||0;this.set({...this.snapshot,connection:r?"reconnecting":"connecting"});try{let u=!1;const c=()=>{!this.live(n)||u||(u=!0,this.set({...this.snapshot,connection:"connected",error:null}))};if(this.dropLiveRepliesVia(t),await this.transport.streamLedger(t,a,m=>{this.live(n)&&(c(),this.ingestItem(t,m))},this.controller.signal,c,m=>{this.live(n)&&(c(),this.ingestDelta(t,m))}),!this.live(n)||(await this.catchUp(t,n),!this.live(n)))return;const d=Jt(await this.transport.getRun(t,(i=this.controller)==null?void 0:i.signal));if(!this.live(n))return;d&&this.updateRunState(t,d),r+=1}catch(u){if(!this.live(n))return;if(r+=1,this.fail(u,!1),zl(u)){this.set({...this.snapshot,connection:"disconnected"});return}}if(r>=5||!this.live(n))break;await this.waitForRetry(Math.min(2e3,150*2**(r-1)))}if(this.live(n)){if(Js(gi(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 i=Jt(t);if(!i)return;const a=Jt(i.session),u=Am(a==null?void 0:a.turns).map(Jt).filter(m=>!!m);if(await this.hydrateHistoricalSessionRuns(u,n,r),!this.live(r))return;for(const m of u){const h=Ft(m==null?void 0:m.run_id)||n;this.ingestSessionTurn(m,n,h!==n&&this.historicalRuns.get(h)||null)}const c=`turn:${n}:user`;if(!this.seenMessages.has(c)){const m=mb(Jt(i.input_data));m&&this.addMessage({id:c,role:"user",content:m})}const d=Jt(i.ledgers);if(d)for(const[m,h]of Object.entries(d)){const p=Jt(h);for(const y of Am(p==null?void 0:p.items))this.ingestItem(m,y)}}ingestSessionTurn(t,n,r){if(!t)return;const i=Ft(t.run_id)||n,a=Jt(t.input_data)||Jt(t.input)||{},u=Ft(t.prompt)||mb(a);u&&this.addMessage({id:`turn:${i}:user`,role:"user",content:u,ts:Ft(t.created_at)||void 0});const c=this.historicalRunFailures.get(i);if(c){const p=Ft(t.answer)||dw(t.output),y=c.missing?"is unavailable because the run no longer exists":"could not be restored",w=p?` Saved reply (not verified as the final result): ${p}`:"";this.addMessage({id:`history:${i}:unavailable`,role:"system",level:"warn",title:"History",content:`The final output for an earlier turn ${y}.${w}`});return}const m=(r&&Js(gi(r))?_d(r.output):"")||(r?Ft(t.answer)||dw(t.output):""),h=this.historicalEvidence.get(i);for(const p of(h==null?void 0:h.tools)||[])this.upsertTool(p);m&&this.addRunAssistantMessage(i,{id:`final:${i}`,role:"assistant",content:m,runId:i,statistics:h==null?void 0:h.statistics,ts:Ft(t.updated_at)||void 0})}async hydrateHistoricalSessionRuns(t,n,r){const i=[...new Set(t.map(d=>Ft(d.run_id)).filter(d=>d&&d!==n&&!this.historicalRuns.has(d)&&!this.historicalRunFailures.has(d)))];if(!i.length||!this.live(r))return;let a=0,u=!1;const c=async()=>{var d,m,h;for(;!u&&this.live(r);){const p=i[a++];if(!p)return;try{const y=Jt(await this.transport.getRun(p,(d=this.controller)==null?void 0:d.signal));if(!this.live(r))return;if(y){this.historicalRuns.set(p,y);try{const w=await this.transport.getHistory(p,(m=this.controller)==null?void 0:m.signal);if(!this.live(r))return;this.historicalEvidence.set(p,Zg(jM(w)))}catch(w){if(!this.live(r))return;if(zl(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(p,null),this.historicalRunFailures.set(p,{missing:!1,detail:"gateway returned an invalid historical run snapshot"})}catch(y){if(!this.live(r))return;const w=TM(y)===404;this.historicalRuns.set(p,null),this.historicalRunFailures.set(p,{missing:w,detail:y instanceof Error?y.message:Ft((h=Jt(y))==null?void 0:h.detail)||"request failed"}),zl(y)&&(u=!0,this.fail(y))}}};if(await Promise.all(Array.from({length:Math.min(4,i.length)},()=>c())),u&&this.live(r))for(const d of i)!this.historicalRuns.has(d)&&!this.historicalRunFailures.has(d)&&(this.historicalRuns.set(d,null),this.historicalRunFailures.set(d,{missing:!1,detail:"authorization expired before this historical run could be restored"}))}ingestItem(t,n){const r=Jt(n),i=Jt(r==null?void 0:r.record)||r;if(!i)return;const a=MM(i,t),u=Number(r==null?void 0:r.cursor),c=Number.isFinite(u)&&u>0?u:(this.cursors.get(a)||0)+1,d=`${a}:${c}`;if(!this.seenRecords.has(d)){if(this.seenRecords.add(d),this.cursors.set(a,Math.max(this.cursors.get(a)||0,c)),this.set({...this.snapshot,records:[...this.snapshot.records,{cursor:c,record:i,runId:a}]}),this.foldRecord(a,i,d),this.snapshot.messages.some(m=>m.id===`final:${this.rootRunId}`)){const m=Zg(this.snapshot.records).statistics;this.set({...this.snapshot,messages:this.snapshot.messages.map(h=>h.id===`final:${this.rootRunId}`?{...h,statistics:m}:h)})}for(const m of pb(i))m!==a&&this.catchUpAndWatch(m,this.generation)}}foldRecord(t,n,r){var h,p,y;const i=fw(n),a=Ft(i.type).toLowerCase(),u=Jt(n.result),c=Ft(n.status).toLowerCase(),d=_b(n);if(this.foldStopEvidence(t,n,a,c),["llm_call","tool_calls"].includes(a)&&["started","running"].includes(c)){const w=Date.parse(d||"");(!Number.isFinite(w)||w>=this.displayStatusAt)&&(Number.isFinite(w)&&(this.displayStatusAt=w),this.snapshot.displayStatus&&this.set({...this.snapshot,displayStatus:""}))}if(a==="answer_user"&&c==="completed"){const w=_d(u)||_d(Jt(i.payload));w&&this.addRunAssistantMessage(t,{id:`answer:${t}:${r}`,role:"assistant",content:w,ts:d})}if(a==="emit_event"&&c==="completed"){const w=Jt(i.payload)||{},x=Jt(u),k=Ft(w.name)||Ft(x==null?void 0:x.name),b=w.payload!==void 0?w.payload:x==null?void 0:x.payload;if(["abstract.message","abstractcode.message"].includes(k)){const S=_d(b);if(S){const $=Ft((h=Jt(b))==null?void 0:h.level).toLowerCase(),A=$==="error"?"error":["warn","warning"].includes($)?"warn":"info";this.addMessage({id:`event:${t}:${r}`,role:"system",title:"Workflow",content:S,level:A,ts:d})}}if(["abstract.status","abstractcode.status"].includes(k)){const S=Jt(b),$=S?S.status??S.text??S.value:b,A=Date.parse(d||"");!Js(this.snapshot.status)&&typeof $=="string"&&(!Number.isFinite(A)||A>=this.displayStatusAt)&&(Number.isFinite(A)&&(this.displayStatusAt=A),this.set({...this.snapshot,displayStatus:$.trim()}))}if(["abstract.tool_execution","abstractcode.tool_execution","abstract.tool_result","abstractcode.tool_result"].includes(k)){const S=_d(b);S&&this.addMessage({id:`event:${t}:${r}`,role:"system",title:"Tool activity",content:S,ts:d})}}const m=fS(n);if(c==="waiting"&&m&&!Js(this.snapshot.status)&&!Js(gi(this.runStates.get(t)||null))&&(this.resolvedWaits.delete(`${t}:${Ft(m.wait_key)}`),this.set({...this.snapshot,interaction:this.interactionWith({runId:t,wait:m,...Ft(n.step_id)?{stepId:Ft(n.step_id)}:{}})})),a==="tool_calls")for(const w of uS(this.toolActivities,{runId:t,cursor:this.cursors.get(t)||0,record:n}))this.upsertTool(w);if(a==="resume"&&(u==null?void 0:u.resumed)===!0){const w=Ft((p=Jt(i.payload))==null?void 0:p.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,i){let a=!1;if(r==="llm_call"){const u=Ft(n.step_id);if(u){const c=`${t}:${u}`;i==="started"?(this.openLlmSteps.add(c),a=!0):["completed","failed","cancelled","waiting"].includes(i)&&(a=this.openLlmSteps.delete(c)||a),["completed","failed","cancelled"].includes(i)&&this.closeLiveReply(c)}}if(r==="emit_event"&&i==="completed"){const u=Jt(fw(n).payload)||{},c=Jt(n.result),d=Ft(u.name)||Ft(c==null?void 0:c.name),m=Jt(u.payload!==void 0?u.payload:c==null?void 0:c.payload);d==="abstract.status"&&Ft(m==null?void 0:m.killed_by)==="kill_switch"&&(this.forcedStop=m,a=!0)}a&&this.recomputeStop()}recomputeStop(){let t=null;this.forcedStop?t={phase:"forced",label:Ft(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,i=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 a=[this.rootRunId,...[...this.watchedRuns].filter(c=>c!==this.rootRunId)];let u=!1;for(const c of a)try{await this.catchUp(c,t)}catch(d){u=!0,this.live(t)&&(this.fail(d,!1),i=this.snapshot.error)}!u&&i&&this.snapshot.error===i&&(this.set({...this.snapshot,error:null}),i=null),r=Math.min(5e3,r*2)}}finally{this.generation===t&&(this.stopFollowing=!1)}}}addMessage(t){const n=Ft(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(a=>a.id===n.id);if(r<0){this.addMessage(n);return}const i=[...this.snapshot.messages];i[r]=n,this.set({...this.snapshot,messages:i})}addRunAssistantMessage(t,n){this.closeLiveRepliesOfRun(t);const r=`answer:${t}:`,i=`final:${t}`;this.snapshot.messages.some(a=>a.role==="assistant"&&a.content===n.content&&(a.id===i||String(a.id||"").startsWith(r)))||this.addMessage(n)}ingestDelta(t,n){let r;try{r=rS(n)}catch(d){this.fail(d,!1);return}const i=`${r.run_id}:${r.call_id}`;if(sS(r)){if(r.reason==="unavailable"){this.noteStreamUnavailable(r);return}if(r.reason==="cancelled"&&r.detail==="reinvoked"){this.closeLiveReply(i,"restarted");return}this.closeLiveReply(i,r.reason==="completed"?void 0:r.reason);return}if(this.closedLiveCalls.has(i)||this.runEnded(r.run_id)||this.runEnded(this.rootRunId))return;const a=this.liveReplies.get(i)||{runId:r.run_id,callId:r.call_id,nodeId:r.node_id||"",via:t,text:"",reasoning:"",seq:{content:-1,reasoning:-1}},u=r.channel==="reasoning"?"reasoning":"text",c=a.seq[r.channel];if(r.snapshot){if(r.seq<c)return;a[u]=r.text}else{if(r.seq<=c)return;a[u]+=r.text}a.seq[r.channel]=r.seq,a.via=t,this.liveReplies.set(i,a),this.liveDirty.add(i),this.scheduleLiveRender()}runEnded(t){return Js(gi(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 i=this.liveMessage(r),a=t.findIndex(u=>u.id===i.id);a<0?t.push(i):t[a]=i,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 i=`live:${r.runId}:${r.callId}`,a=this.snapshot.messages.findIndex(c=>c.id===i);if(a<0)return;const u=[...this.snapshot.messages];if(n==="restarted"){const c=this.restartNote(t);this.seenMessages.add(String(c.id)),u[a]=c}else if(n){const c=`live-end:${r.runId}:${r.callId}`;this.seenMessages.add(c),u[a]={id:c,role:"system",level:"warn",title:"Reply",runId:r.runId,content:n==="failed"?"The reply stopped because the model call failed.":"The reply stopped because the model call was cancelled."}}else u.splice(a,1);this.set({...this.snapshot,messages:u})}restartNote(t){const n=t.slice(0,t.indexOf(":"));return{id:`live-end:${t}`,role:"system",level:"info",title:"Reply",runId:n,content:"Reply restarted: the model call was interrupted and is running again."}}noteStreamUnavailable(t){const n=`${t.run_id}:${t.call_id}`;this.closeLiveReply(n),this.addMessage({id:`stream-unavailable:${t.run_id}:${t.detail||"unknown"}`,role:"system",level:"info",title:"Reply",runId:t.run_id,content:MT(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 i of[...this.liveReplies.values()])this.closeLiveReply(`${i.runId}:${i.callId}`,r);this.closedLiveCalls.clear(),this.shownLiveCalls.clear();return}this.closeLiveRepliesVia(t,r);for(const i of[...this.closedLiveCalls])i.startsWith(`${t}:`)&&this.closedLiveCalls.delete(i);for(const i of[...this.shownLiveCalls])i.startsWith(`${t}:`)&&this.shownLiveCalls.delete(i)}dropLiveRepliesVia(t){const n=new Set;for(const[r,i]of this.liveReplies)i.via===t&&(this.liveReplies.delete(r),this.liveDirty.delete(r),n.add(`live:${i.runId}:${i.callId}`));n.size&&this.set({...this.snapshot,messages:this.snapshot.messages.filter(r=>!n.has(String(r.id)))})}fail(t,n=!0){var r,i,a;zl(t)&&(this.approvalEpoch+=1,this.toolApprovalStopped=!0,this.toolApprovalSuspended=!0,(i=(r=this.options).onAuthError)==null||i.call(r,t)),this.set({...this.snapshot,error:t instanceof Error?t.message:Ft((a=Jt(t))==null?void 0:a.detail)||String(t),...zl(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,i=>i.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 a;if(this.runStates.set(t,n),Js(gi(n))&&this.endLiveRepliesOfRun(t,gi(n)),t!==this.rootRunId){Js(gi(n))&&((a=this.snapshot.interaction)==null?void 0:a.runId)===t?this.set({...this.snapshot,interaction:null}):this.adoptDurableWait(t,n);return}const r=gi(n),i=Js(r);if(i){const u=_d(n.output);u&&this.upsertFinal(t,u,_b(n))}this.set({...this.snapshot,run:n,status:r,...i?{interaction:null,autoApproveTools:!1,displayStatus:""}:{}}),i||this.adoptDurableWait(t,n),(this.stopRequested||this.forcedStop)&&this.recomputeStop()}upsertFinal(t,n,r){this.closeLiveRepliesOfRun(t);const i=`final:${t}`;this.seenMessages.add(i);const a={id:i,role:"assistant",content:n,ts:r,runId:t,statistics:Zg(this.snapshot.records).statistics},u=this.snapshot.messages.findIndex(d=>d.id===i||String(d.id||"").startsWith(`answer:${t}:`)&&d.content===n);if(u<0){this.set({...this.snapshot,messages:[...this.snapshot.messages,a]});return}const c=[...this.snapshot.messages];c[u]=a,this.set({...this.snapshot,messages:c})}async refreshRunState(t,n){var r;try{const i=Jt(await this.transport.getRun(t,(r=this.controller)==null?void 0:r.signal));i&&this.live(n)&&this.updateRunState(t,i)}catch(i){this.live(n)&&this.fail(i,!1)}}async pollRootLifecycle(t,n){var r;for(;this.live(n)&&this.rootRunId===t&&!Js(gi(this.runStates.get(t)||null));){if(await this.waitForRetry(2e3),!this.live(n)||this.rootRunId!==t||Js(gi(this.runStates.get(t)||null)))return;try{const i=Jt(await this.transport.getRun(t,(r=this.controller)==null?void 0:r.signal));i&&this.live(n)&&this.rootRunId===t&&this.updateRunState(t,i)}catch(i){if(!this.live(n))return;if(zl(i)){this.fail(i);return}this.fail(i,!1)}}}waitForRetry(t){var i;const n=(i=this.controller)==null?void 0:i.signal;if(!n||n.aborted)return Promise.resolve();const r=n;return new Promise(a=>{const u=setTimeout(d,t),c=()=>{clearTimeout(u),d()};function d(){r.removeEventListener("abort",c),a()}r.addEventListener("abort",c,{once:!0})})}}function LM(e){const t=_.useMemo(()=>new RM(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(i=>t.subscribe(i),()=>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 Dc(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function zr(e){return typeof e=="string"?e.trim():e==null?"":typeof e=="number"||typeof e=="boolean"?String(e):""}function gb(e){return["session","workflow","run","global"].includes(e)?e:null}function Wl(e){return{scope:zr(e==null?void 0:e.scope).toLowerCase(),name:zr(e==null?void 0:e.name)||zr(e==null?void 0:e.event_name),scopeId:zr(e==null?void 0:e.scope_id)||zr(e==null?void 0:e.scopeId),sessionId:zr(e==null?void 0:e.session_id)||zr(e==null?void 0:e.sessionId),workflowId:zr(e==null?void 0:e.workflow_id)||zr(e==null?void 0:e.workflowId),runId:zr(e==null?void 0:e.run_id)||zr(e==null?void 0:e.runId)}}function IM(e,t){const n=e.wait,r=zr(n.wait_key),i=[Wl(n),Wl(Dc(n.details))];for(const a of t){if(a.runId!==e.runId)continue;const u=a.record,c=Dc(u.result),d=Dc(c==null?void 0:c.wait),m=Dc(u.effect),h=Dc(m==null?void 0:m.payload);zr(d==null?void 0:d.wait_key)!==r&&zr(h==null?void 0:h.wait_key)!==r||i.push(Wl(u),Wl(h),Wl(Dc(h==null?void 0:h.details)),Wl(d),Wl(Dc(d==null?void 0:d.details)))}return i}function ty(e,t){return t.scopeId?t.scopeId:e==="session"?t.sessionId:e==="workflow"?t.workflowId:e==="run"?t.runId:"global"}function mS(e,t,n){return{scope:e,scopeId:t,name:n,...e==="session"?{sessionId:t}:{},...e==="workflow"?{workflowId:t}:{},...e==="run"?{runId:t}:{}}}function OM(e,t,n){if(!n)return null;const r=`evt:${t}:${n}:`;if(!e.startsWith(r))return null;const i=e.slice(r.length);return i?mS(t,n,i):null}function PM(e,t=[],n){if(!e)return{target:null,error:"No event wait is available."};const r=zr(e.wait.wait_key),i=/^evt:(session|workflow|run|global):/.exec(r);if(!i)return{target:null,error:"The gateway did not provide a canonical event wait key."};const a=gb(i[1]);if(!a)return{target:null,error:"The event wait uses an unsupported scope."};const u=IM(e,Array.isArray(t)?t:[]),c=new Map;for(const y of u){const w=gb(y.scope);if(!w||!y.name)continue;if(w!==a)return{target:null,error:"Event metadata conflicts with the canonical wait scope."};const x=`evt:${w}:`,k=`:${y.name}`;if(!r.startsWith(x)||!r.endsWith(k)||r.length<=x.length+k.length)return{target:null,error:"Event metadata does not exactly match the canonical wait key."};const b=r.slice(x.length,-k.length),S=ty(w,y);if(S&&S!==b)return{target:null,error:"Event metadata conflicts with the canonical wait target."};const $=mS(w,b,y.name);c.set(`${$.scope}\0${$.scopeId}\0${$.name}`,$)}if(c.size>1)return{target:null,error:"Multiple event targets match this wait; routing is unavailable."};if(c.size===1)return{target:[...c.values()][0]};const d=new Set;a==="run"&&d.add(e.runId),a==="global"&&d.add("global");for(const y of u){const w=ty(a,y);w&&d.add(w)}if(zr(n==null?void 0:n.run_id)===e.runId){const y=Wl(n||null),w=ty(a,y);w&&d.add(w)}const h=[...d].map(y=>OM(r,a,y)).filter(y=>!!y),p=new Map(h.map(y=>[`${y.scope}\0${y.scopeId}\0${y.name}`,y]));return p.size===1?{target:[...p.values()][0]}:p.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 hS(e){return s.jsx(Kj,{text:e,images:"link"})}const DM={trigger:"Trigger",answer:"Automation"};function _S(e,t){return s.jsx(vv,{...t,message:{id:`${e.runId}:${e.kind}`,role:e.role,content:e.text,title:DM[e.kind],runId:e.runId},images:"link"})}const FM={renderText:hS,renderTurn:_S};function zM(e){const{fetchGateway:t,messageProps:n,...r}=e,i=r.onOpenResource??(t?a=>sM(t,a.url,{name:a.name}):void 0);return s.jsx(ZE,{...r,onOpenResource:i,...FM,renderTurn:a=>_S(a,n)})}function BM(e,t,n={}){if(!e)return null;const r=e.wait,i=`${e.runId}:${r.wait_key}:${e.stepId||""}`,a=r.details||{};if(a.mode==="approval_required"||a.kind==="tool_approval"){const c=Array.isArray(a.tool_calls)?a.tool_calls:[],d={runId:e.runId,waitKey:String(r.wait_key||""),stepId:e.stepId},m=[...new Set(c.map(p=>String((p==null?void 0:p.name)||"tool")))],h=n.onPermissionsAll;return{id:i,kind:"tool-approval",title:`${c.length||"Requested"} ${c.length===1?"action needs":"actions need"} permission`,toolName:m.join(", ")||"the requested tools",description:"Review the targets below. Allow once approves this batch only.",detail:s.jsxs("div",{className:"pc-approval-summary",children:[s.jsx(Zj,{tools:c.map((p,y)=>({id:String((p==null?void 0:p.call_id)||(p==null?void 0:p.id)||y),runId:e.runId,name:(p==null?void 0:p.name)||"Tool",arguments:p==null?void 0:p.arguments,status:"waiting"}))}),s.jsxs("details",{children:[s.jsx("summary",{children:"Review full tool arguments (JSON)"}),s.jsx(mr,{value:c.length?c:a})]})]}),approveLabel:"Allow once",denyLabel:"Deny",approveAllLabel:h?"Allow all enabled tools":void 0,approveAllDescription:h?"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:h?async()=>{await t.approveWithPolicyChange(d,()=>{h()})}:void 0,onApprove:async()=>{await t.approve(!0,d)},onDeny:async()=>{await t.approve(!1,d)}}}if(r.reason==="user"||r.reason==="ask_user")return{id:i,kind:"ask-user",title:"A question for you",prompt:String(r.prompt||a.prompt||"How would you like to continue?"),allowFreeText:r.allow_free_text!==!1,choices:(Array.isArray(r.choices)?r.choices:[]).map(c=>typeof c=="object"&&c!==null?{id:String(c.value??c.id??c.label),label:String(c.label??c.text??c.value??c.id),description:c.description}:{id:String(c),label:String(c)}),onSubmit:async c=>{await t.resume(c)}};const u=String(r.wait_key||"");if(r.reason==="event"||u.startsWith("evt:")){const c=PM(e,n.records||[],n.currentRun??null),d=c.target,m=(d==null?void 0:d.name)||"";return{id:i,kind:"event-wait",title:d?"Waiting for an event":"Event routing unavailable",eventName:m,prompt:String(r.prompt||`This workflow will continue when “${m||"its trigger"}” arrives.`),description:d?"You can also send the expected event here.":`This event cannot be sent safely. ${c.error}`,initialPayload:"{}",payloadLabel:"Event data (JSON)",sendLabel:"Send event",onSend:async h=>{if(!d)throw new Error(c.error);const p=JSON.parse(h||"{}"),y={name:d.name,scope:d.scope,payload:p};d.scope==="session"?y.session_id=d.scopeId:d.scope==="workflow"?y.workflow_id=d.scopeId:d.scope==="run"&&(y.run_id=d.scopeId),await t.emitEvent(y)}}}return null}const UM={app:"observer",name:"AbstractObserver"},WM=["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 qM(e){const t=_.useRef(e.gateway);t.current=e.gateway;const n=(r,i)=>t.current.fetch_gateway(r,i);return s.jsx(vM,{open:e.open,onClose:e.onClose,source:UM,fetchGateway:n,connected:e.connected,topOffset:e.topOffset,placeholder:"Ask about the observer…",suggestions:WM})}function HM(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 VM(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 GM(e,t,n){return e<=0?-1:t<0?n?e-1:0:(t+(n?e-1:1))%e}const KM='a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';function JM(e){return typeof document>"u"?!1:Array.from(document.querySelectorAll('[role="dialog"][aria-modal="true"]')).some(t=>t!==e)}function YM(e){const[t,n]=_.useReducer(HM,!1),r=_.useRef(null),i=_.useRef(null),a=_.useRef(!1);return _.useEffect(()=>{n({type:"page_change"})},[e.page]),_.useEffect(()=>{n({type:"layout_change"})},[e.is_drawer]),_.useEffect(()=>{var u;if(t){a.current=!0;const c=i.current,d=(c==null?void 0:c.querySelector(".shell_nav_item.active"))||(c==null?void 0:c.querySelector(".shell_nav_item"));d==null||d.focus();const m=h=>{if(h.key==="Escape"){n({type:"escape",default_prevented:h.defaultPrevented,other_modal_open:JM(i.current)});return}if(h.key!=="Tab"||!i.current)return;const p=Array.from(i.current.querySelectorAll(KM)).filter(w=>w.offsetParent!==null||w===document.activeElement),y=GM(p.length,p.indexOf(document.activeElement),h.shiftKey);y>=0&&(h.preventDefault(),p[y].focus())};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)}a.current&&(a.current=!1,(u=r.current)==null||u.focus())},[t]),{open:t,set_open:u=>n({type:u?"open":"close"}),toggle_ref:r,sidebar_ref:i,attrs:VM(e.is_drawer,t)}}function XM(e,t){return[...e.filter(n=>!n.local_error),t].map(n=>({role:n.role,content:n.content}))}function F_(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?Math.trunc(e):0}function ZM(e){const t=F_(e==null?void 0:e.dropped_messages);if(!e||t<=0)return null;const n=F_(e.replayed_messages),r=F_(e.dropped_tokens),i=F_(e.max_tokens),a=[`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"}`+(i?` (history window: the most recent ${i.toLocaleString("en-US")} tokens of whole messages).`:".")];return e.oversize_turn_kept&&a.push("Your latest message alone is larger than the window; it was sent whole."),a.join(" ")}function QM(e){const t=ZM(e.history);return t?s.jsx(vv,{message:{role:"system",level:"info",title:"History",content:t}}):null}const eR="api/local/reveal",tR="sw.js",mw="#run/";function nR(e){return`${mw}${encodeURIComponent(String(e||"").trim())}`}function pS(e){const t=String(e||"");if(!t.startsWith(mw))return"";const n=t.slice(mw.length).split("?")[0];if(!n||n.includes("/"))return"";try{return decodeURIComponent(n).trim()}catch{return""}}function sR(e){return`Run ${e} cannot be opened: it does not exist on this gateway, or your account cannot see it.`}function rR(e){const t=pS(e.hash);if(t)return t;const n=u=>/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(u),r=u=>{const c=u.split("/").filter(Boolean);return c.length?c[c.length-1].trim():""},i=r(String(e.hash||"").replace(/^#/,""));if(n(i))return i;const a=r(String(e.pathname||""));return n(a)?a:""}const iR={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"},oR=new Set(["wait","resume","memory","model","node"]),aR=new Set(["abstract.status","abstract.progress","abstract.steer_seen","abstract.summary"]),lR={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 cR(e){const t=String(e||"").trim();return t?iR[t]||"other":"node"}function uR(e,t,n){return n?!1:e==="event"?aR.has(String(t||"").trim()):oR.has(e)}const dR=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 fR(e){const t=new TextEncoder().encode(e),n=t.length*8,r=t.length+9+63>>6<<6,i=new Uint8Array(r);i.set(t),i[t.length]=128;const a=new DataView(i.buffer);a.setUint32(r-8,Math.floor(n/4294967296)),a.setUint32(r-4,n>>>0);const u=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),c=new Uint32Array(64);for(let d=0;d<r;d+=64){for(let S=0;S<16;S++)c[S]=a.getUint32(d+S*4);for(let S=16;S<64;S++){const $=c[S-15],A=c[S-2],E=($>>>7|$<<25)^($>>>18|$<<14)^$>>>3,z=(A>>>17|A<<15)^(A>>>19|A<<13)^A>>>10;c[S]=c[S-16]+E+c[S-7]+z>>>0}let[m,h,p,y,w,x,k,b]=u;for(let S=0;S<64;S++){const $=(w>>>6|w<<26)^(w>>>11|w<<21)^(w>>>25|w<<7),A=w&x^~w&k,E=b+$+A+dR[S]+c[S]>>>0,z=(m>>>2|m<<30)^(m>>>13|m<<19)^(m>>>22|m<<10),F=m&h^m&p^h&p,M=z+F>>>0;b=k,k=x,x=w,w=y+E>>>0,y=p,p=h,h=m,m=E+M>>>0}u[0]=u[0]+m>>>0,u[1]=u[1]+h>>>0,u[2]=u[2]+p>>>0,u[3]=u[3]+y>>>0,u[4]=u[4]+w>>>0,u[5]=u[5]+x>>>0,u[6]=u[6]+k>>>0,u[7]=u[7]+b>>>0}return Array.from(u,d=>d.toString(16).padStart(8,"0")).join("")}const hw="$slim";function mR(e){return!!(e&&typeof e=="object"&&!Array.isArray(e)&&e[hw]&&typeof e[hw]=="object")}function hR(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||""),i=n.effect&&typeof n.effect=="object"?n.effect.payload:null;r&&i&&typeof i=="object"&&!t.has(r)&&t.set(r,i)}return t}function _R(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 i of e.messages)i&&typeof i=="object"&&n.push({...i})}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 pR(e,t){const n=e&&e[hw];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 i;if(n.kind==="started_payload_field"){const u=String(n.field||"");if(!(u in r))return{state:"missing",reason:`the started record has no "${u}" field`};i=r[u]}else if(n.kind==="started_messages_layout"){if(i=Array.isArray(n.layout)?_R(r,n.layout.map(String)):null,!i)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(i))return{state:"missing",reason:"appendix on a non-list value"};const u=i.map(d=>d&&typeof d=="object"?{...d}:d),c=[...n.appendix].sort((d,m)=>Number((d==null?void 0:d.at)??-1)-Number((m==null?void 0:m.at)??-1));for(const d of c){const m=Number(d==null?void 0:d.at);if(!Number.isInteger(m)||m<0||m>u.length)return{state:"missing",reason:"appendix position out of range"};u.splice(m,0,d.item)}i=u}return fR(JSON.stringify(i))!==String(n.sha256||"")?{state:"unverified",value:i,reason:"checksum differs from the record"}:{state:"resolved",value:i}}function gR(e,t){const n=[],r=[],i=(a,u,c)=>{if(c>14)return a;if(mR(a)){const d=pR(a,t);return d.state==="missing"?(n.push({path:u,reason:d.reason}),a):(d.state==="unverified"&&r.push({path:u,reason:d.reason}),d.value)}if(Array.isArray(a)){let d=null;return a.forEach((m,h)=>{const p=i(m,`${u}[${h}]`,c+1);p!==m&&((d??(d=[...a]))[h]=p)}),d??a}if(a&&typeof a=="object"){let d=null;for(const m of Object.keys(a)){const h=i(a[m],u?`${u}.${m}`:m,c+1);h!==a[m]&&((d??(d={...a}))[m]=h)}return d??a}return a};return{value:i(e,"",0),unresolved:n,unverified:r}}function yb(e){const t=Date.parse(String(e||""));return Number.isFinite(t)?t:null}function gS(e){const t=e==null?void 0:e.result;return t&&typeof t=="object"&&Array.isArray(t.results)?t.results:[]}function yR(e,t){return e?String(e.status||"")==="failed"||e.error?!0:t==="tool"&&gS(e).some(n=>n&&n.success===!1):!1}function wR(e){var n;const t=String((e==null?void 0:e.idempotency_key)||"").trim();return String(((n=e==null?void 0:e.effect)==null?void 0:n.type)||"")==="tool_calls"&&t?`idem:${t}`:String((e==null?void 0:e.step_id)||"")}function ag(e,t){var m,h,p,y,w,x;const n=String(t||"").trim(),r=(e||[]).filter(k=>k&&k.record&&String(k.run_id||k.record.run_id||"").trim()===n).sort((k,b)=>(k.cursor||0)-(b.cursor||0)),i=hR(r.map(k=>k.record)),a=new Map,u=[];for(const k of r){const b=k.record,$=wR(b)||`cursor:${k.cursor}`;let A=a.get($);A||(A={cursor:k.cursor,started:null,latest:b,latest_cursor:k.cursor},a.set($,A),u.push($)),String(b.status||"")==="started"&&!A.started&&(A.started=b),k.cursor>=A.latest_cursor&&(A.latest=b,A.latest_cursor=k.cursor)}let c=0;const d=[];for(const k of u){const b=a.get(k),S=gR(b.latest,i),$=S.value,A=String(((m=$==null?void 0:$.effect)==null?void 0:m.type)||((p=(h=b.started)==null?void 0:h.effect)==null?void 0:p.type)||"").trim(),E=cR(A),z=E==="event"?String(((w=(y=$==null?void 0:$.effect)==null?void 0:y.payload)==null?void 0:w.name)||"").trim():"";E==="llm_call"&&(c+=1);const F=yR($,E),M=String(((x=b.started)==null?void 0:x.started_at)||($==null?void 0:$.started_at)||""),D=String(($==null?void 0:$.ended_at)||""),H=yb(M),q=yb(D);d.push({id:`${n}:${k}`,run_id:n,step_id:String(($==null?void 0:$.step_id)||""),node_id:String(($==null?void 0:$.node_id)||""),kind:E,effect_type:A,event_name:z,status:String(($==null?void 0:$.status)||""),cursor:b.cursor,started_at:M,ended_at:D,duration_ms:H!==null&&q!==null?Math.max(0,q-H):null,started:b.started,record:$,failed:F,housekeeping:uR(E,z,F),cycle:c,unresolved:S.unresolved,unverified:S.unverified})}return d}function vR(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 xR={view:"cycles",only:"all",all_steps:!1,q:""};function bR(e,t,n){const r=String(t.q||"").trim().toLowerCase();return e.filter(i=>!(t.only==="llm"&&i.kind!=="llm_call"||t.only==="tools"&&i.kind!=="tool"||t.only==="failed"&&!i.failed||t.only==="all"&&!t.all_steps&&i.housekeeping||r&&!n(i).includes(r)))}const kR=["all","llm","tools","failed"];function wb(e){const t=String(e||""),n=t.indexOf("?");if(n<0)return{...xR};const r=new URLSearchParams(t.slice(n+1)),i=String(r.get("only")||"");return{view:r.get("view")==="steps"?"steps":"cycles",only:kR.includes(i)?i:"all",all_steps:r.get("all")==="1",q:String(r.get("q")||"")}}function jR(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 i=r.toString();return i?`${n}?${i}`:n}function Ld(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 yS(e){if(typeof e!="string")return e??{};try{return JSON.parse(e)}catch{return e}}function wS(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:yS(t.arguments??((r=t.function)==null?void 0:r.arguments))}}):[]}function vb(e){const t={role:String((e==null?void 0:e.role)||"?"),content:Ld(e==null?void 0:e.content)},n=wS(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 xb(e){const t=Number(e);return Number.isFinite(t)&&e!==null&&e!==void 0?t:null}const SR={"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 uh(e){var x,k,b,S,$,A,E;const t=e.record||{},n=((k=(x=e.started)==null?void 0:x.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:{},i=r.usage||r.token_usage||{},a=[],u=e.unverified.map(z=>`${z.path}: ${z.reason}`);for(const z of e.unresolved){const F=SR[z.path];F&&a.push(`${F}: ${z.reason}`)}const c=($=(S=r==null?void 0:r.metadata)==null?void 0:S._provider_request)==null?void 0:$.payload;let d="",m=[],h="";if(c&&Array.isArray(c.messages)){h="sent";for(const z of c.messages)String((z==null?void 0:z.role)||"")==="system"&&!m.length?d+=(d?`
|
|
85
|
+
|
|
86
|
+
`:"")+Ld(z.content):m.push(vb(z))}else(Array.isArray(n.messages)||typeof n.prompt=="string")&&(h="payload",m=(Array.isArray(n.messages)?n.messages:[]).map(vb),typeof n.prompt=="string"&&n.prompt.trim()&&m.push({role:"user",content:n.prompt}));!d&&typeof n.system_prompt=="string"&&(d=n.system_prompt);const y=(Array.isArray(n.tools)?n.tools:Array.isArray(c==null?void 0:c.tools)?c.tools:[]).filter(z=>z&&typeof z=="object").map(z=>{const F=z.function&&typeof z.function=="object"?z.function:z;return{name:String(F.name||"?"),description:String(F.description||""),schema:F.parameters??F.input_schema??null}}),w=(A=r==null?void 0:r.metadata)!=null&&A._provider_request&&typeof r.metadata._provider_request=="object"?r.metadata._provider_request:{};return{provider:String(n.provider||r.provider||w.provider||(c==null?void 0:c.provider)||""),model:String(n.model||r.model||w.model||(c==null?void 0:c.model)||""),tokens_in:xb(i.prompt_tokens??i.input_tokens),tokens_out:xb(i.completion_tokens??i.output_tokens),system:d,messages:m,messages_source:h,tools:y,response:Ld(r.content??r.response??""),tool_calls:wS(r.tool_calls),reasoning:Ld(r.reasoning??((E=r==null?void 0:r.metadata)==null?void 0:E.reasoning)??""),missing:a,unverified:u}}function dh(e){var i,a,u,c;const t=((a=(i=e.record)==null?void 0:i.effect)==null?void 0:a.payload)||((c=(u=e.started)==null?void 0:u.effect)==null?void 0:c.payload)||{},n=(Array.isArray(t.tool_calls)?t.tool_calls:[]).map(d=>{var m,h;return{name:String((d==null?void 0:d.name)||((m=d==null?void 0:d.function)==null?void 0:m.name)||"?"),arguments:yS((d==null?void 0:d.arguments)??((h=d==null?void 0:d.function)==null?void 0:h.arguments)),call_id:String((d==null?void 0:d.call_id)||(d==null?void 0:d.id)||"")}}),r=gS(e.record).map(d=>({name:String((d==null?void 0:d.name)||"?"),success:typeof(d==null?void 0:d.success)=="boolean"?d.success:null,output:(d==null?void 0:d.output)==null?"":Ld(d.output),error:(d==null?void 0:d.error)==null?"":Ld(d.error),call_id:String((d==null?void 0:d.call_id)||""),raw:d}));return{calls:n,results:r}}function NR(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 fh(e){var r,i,a;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(((i=t==null?void 0:t.details)==null?void 0:i.sub_run_id)||((a=e==null?void 0:e.result)==null?void 0:a.sub_run_id)||n||"").trim()}function vS(e){var n,r,i,a,u,c,d,m,h,p,y;const t=e.record||{};switch(e.kind){case"llm_call":{const w=uh(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=dh(e).calls;if(!w.length)return"";const x=`${w[0].name}(${NR(w[0].arguments)})`;return w.length>1?`${x} +${w.length-1} more`:x}case"event":return e.event_name;case"subflow":{const w=fh(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(((a=(i=t==null?void 0:t.result)==null?void 0:i.wait)==null?void 0:a.reason)||((c=(u=t==null?void 0:t.effect)==null?void 0:u.payload)==null?void 0:c.reason)||"");case"ask":return String(((m=(d=t==null?void 0:t.effect)==null?void 0:d.payload)==null?void 0:m.prompt)||"");case"answer":return String(((p=(h=t==null?void 0:t.effect)==null?void 0:h.payload)==null?void 0:p.message)||((y=t==null?void 0:t.result)==null?void 0:y.message)||"");default:return e.effect_type}}function xS(e){return e.kind==="llm_call"?uh(e).model:""}function $R(e,t){var r,i;const n=[e.kind,e.effect_type,e.event_name,e.node_id,t,e.status,vS(e),xS(e)];try{n.push(JSON.stringify(((i=(r=e.started)==null?void 0:r.effect)==null?void 0:i.payload)??null)),n.push(JSON.stringify(e.record??null))}catch{}return n.join(`
|
|
87
|
+
`).toLowerCase()}function CR(e){var r,i;const t=Array.from(new Set((e||[]).map(a=>{var u;return String(a.run_id||((u=a.record)==null?void 0:u.run_id)||"").trim()}).filter(Boolean))),n={llm_calls:0,tokens:0,tool_calls:0,tool_failures:0,failed_steps:0};for(const a of t)for(const u of ag(e,a))if((u.failed||String(u.status||"")==="failed")&&(n.failed_steps+=1),u.kind==="llm_call"){n.llm_calls+=1;const c=((i=(r=u.record)==null?void 0:r.result)==null?void 0:i.usage)||{};n.tokens+=Number(c.total_tokens??Number(c.prompt_tokens??c.input_tokens??0)+Number(c.completion_tokens??c.output_tokens??0))||0}else if(u.kind==="tool"){const c=dh(u);n.tool_calls+=Math.max(c.calls.length,c.results.length),n.tool_failures+=c.results.filter(d=>d.success===!1).length}return n}function ER(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`:""}`),e.failed_steps&&t.push(`${e.failed_steps} failed step${e.failed_steps===1?"":"s"}`),t.join(" · ")}function Vt(){return new Date().toISOString()}function AR(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}function Br(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 Wt(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,a=String(e||"").replace(/\r\n/g,`
|
|
88
|
+
`).replace(/\r/g,`
|
|
89
|
+
`).split(`
|
|
90
|
+
`),u=a.slice(0,Math.max(1,r)).join(`
|
|
91
|
+
`),c=a.length>r,d=u.length>n?`${u.slice(0,Math.max(0,n-1))}…`:u;return c&&d===u?`${u}…`:d}function jn(e,t){const n=String(e||"");return n.length<=t?n:`${n.slice(0,Math.max(0,t-1))}…`}function bb(e){const t=String(e||"").trim();return t&&t.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")||"untitled"}function It(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 TR(e){const t=Date.now()-e,n=Math.floor(t/1e3),r=Math.floor(n/60),i=Math.floor(r/60),a=Math.floor(i/24);return n<60?"just now":r<60?`${r}m ago`:i<24?`${i}h ago`:a<=3?`${a}d ago`:new Date(e).toLocaleDateString(void 0,{month:"short",day:"numeric"})}function Xc(e){const t=It(e);return t===null?"—":TR(t)}function Bm(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),i=Math.floor(r/24),a=t%60,u=n%60,c=r%24;return i>0?`${i}d ${c}h`:r>0?`${r}h ${u}m`:n>0?`${n}m ${a}s`:`${t}s`}function cu(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),i=r%60,a=Math.floor(r/60),u=a%24,c=Math.floor(a/24);return c>0?`${c}d ${u}h`:a>0?`${a}h ${i}m`:r>0?`${r}m ${n}s`:`${Math.max(0,t)}s`}function Bd(e){const t=It(e);return t===null?"—":new Date(t).toLocaleString()}function Pn(...e){for(const t of e){const n=String(t??"").trim();if(n)return n}return""}function MR(...e){for(const t of e){const n=Number(t);if(Number.isFinite(n))return n}return null}function ds(e){const t=String(e||"").trim().toLowerCase();return t==="completed"||t==="failed"||t==="cancelled"}function Ud(e){const t=String(e||"").trim().toLowerCase();return t==="running"||t==="waiting"}function Ed(e){return String((e==null?void 0:e.started_at)||(e==null?void 0:e.created_at)||"").trim()}function RR(e){const t=String((e==null?void 0:e.status)||"").trim();return ds(t)?String((e==null?void 0:e.finished_at)||(e==null?void 0:e.updated_at)||"").trim():""}function mh(e,t=Date.now()){const n=It(Ed(e));if(n===null)return-1;const r=It(RR(e));return Math.max(0,(r!==null?r:t)-n)}function iu(e,t=Date.now()){return cu(mh(e,t))}function LR(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 Cp(e){var n;const t=((n=e==null?void 0:e.output)==null?void 0:n.stop_reason)??(e==null?void 0:e.stop_reason)??null;return t&&typeof t=="object"?t:null}function Um(e){const t=String((e==null?void 0:e.status)??"").trim().toLowerCase(),n=t==="completed"||t==="failed"||t==="cancelled";return e!=null&&e.paused&&!n?"paused":t==="completed"&&(e!=null&&e.stop_reason)&&e.stop_reason.finished===!1?"stopped":t||"unknown"}function _a(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 IR={all:"All",llm:"LLM calls",tools:"Tools",failed:"Failed"};function fo(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}function da(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 ny(e){return`${e.toLocaleString("en-US")} chars`}function Sv(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(da,{title:"Raw JSON",copy:fo(t),on_copy:e.on_copy,children:s.jsx("div",{className:"rs_json mono",children:s.jsx(mr,{value:t,collapseAfterDepth:2,showCopy:!1})})})}function OR(e){const t=uh(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(da,{title:"System",meta:ny(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(da,{title:"Messages",meta:`${t.messages.length}${t.messages_source==="sent"?" · as sent":""}`,copy:fo(t.messages),on_copy:e.on_copy,children:s.jsx("ol",{className:"rs_messages",children:t.messages.map((r,i)=>{var a;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,(a=r.tool_calls)==null?void 0:a.map((u,c)=>s.jsx("pre",{className:"rs_text mono",children:`${u.name}(${fo(u.arguments)})`},c))]},i)})})}):null,t.tools.length?s.jsx(da,{title:"Tools offered",meta:String(t.tools.length),copy:fo(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(da,{title:"Response",meta:t.tool_calls.length?`${t.tool_calls.length} tool call${t.tool_calls.length===1?"":"s"}`:t.response?ny(t.response.length):"empty",copy:t.response||fo(t.tool_calls),open:!0,on_copy:e.on_copy,children:[t.response?s.jsx("div",{className:"rs_markdown",children:s.jsx(xi,{text:t.response})}):null,t.tool_calls.map((r,i)=>s.jsx("pre",{className:"rs_text mono",children:`${r.name}(${fo(r.arguments)})`},i)),!t.response&&!t.tool_calls.length?s.jsx("p",{className:"rs_muted",children:"No text and no tool call."}):null]}),t.reasoning?s.jsx(da,{title:"Reasoning",meta:ny(t.reasoning.length),copy:t.reasoning,on_copy:e.on_copy,children:s.jsx("pre",{className:"rs_text",children:t.reasoning})}):null,s.jsx(Sv,{step:e.step,on_copy:e.on_copy})]})}function PR(e){const t=dh(e.step);return s.jsxs(s.Fragment,{children:[s.jsx(da,{title:"Calls",meta:String(t.calls.length),copy:fo(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}(${fo(n.arguments)})`},r))}),s.jsxs(da,{title:"Results",meta:String(t.results.length),copy:fo(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(Jj,{sandbox:uw(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(Sv,{step:e.step,on_copy:e.on_copy})]})}function DR(e){var i,a,u;const t=e.step.record||{},n=((a=(i=e.step.started)==null?void 0:i.effect)==null?void 0:a.payload)??((u=t==null?void 0:t.effect)==null?void 0:u.payload),r=e.step.kind==="subflow"?fh(t):"";return s.jsxs(s.Fragment,{children:[r&&e.on_open_run?s.jsxs("p",{className:"rs_line_actions",children:[s.jsx("span",{className:"mono",children:r}),s.jsx("button",{type:"button",className:"btn btn_sm",onClick:()=>{var c;return(c=e.on_open_run)==null?void 0:c.call(e,r)},children:"Open"})]}):null,t.error?s.jsx("pre",{className:"rs_text rs_error",children:typeof t.error=="string"?t.error:fo(t.error)}):null,n!=null?s.jsx(da,{title:"Payload",copy:fo(n),on_copy:e.on_copy,children:s.jsx("div",{className:"rs_json mono",children:s.jsx(mr,{value:n,collapseAfterDepth:2,showCopy:!1})})}):null,t.result!==void 0&&t.result!==null?s.jsx(da,{title:"Result",copy:fo(t.result),on_copy:e.on_copy,children:s.jsx("div",{className:"rs_json mono",children:s.jsx(mr,{value:t.result,collapseAfterDepth:2,showCopy:!1})})}):null,s.jsx(Sv,{step:e.step,on_copy:e.on_copy})]})}function FR(e){const t=e.step,n=vS(t),r=xS(t),i=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:lR[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 ${_a(i)}`,children:i||"—"}),s.jsx("span",{className:"rs_dur",children:t.duration_ms!==null?cu(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(OR,{step:t,on_copy:e.on_copy}):t.kind==="tool"?s.jsx(PR,{step:t,on_copy:e.on_copy}):s.jsx(DR,{step:t,on_copy:e.on_copy,on_open_run:e.on_open_run})}):null]})}function zR(e){const{state:t}=e,n=_.useMemo(()=>ag(e.items,e.run_id),[e.items,e.run_id]),[r,i]=_.useState({}),a=x=>e.node_label(x.run_id,x.node_id),u=_.useMemo(()=>new Map,[n]),d=bR(n,t,x=>{let k=u.get(x.id);return k===void 0&&(k=$R(x,a(x)),u.set(x.id,k)),k}),m=n.some(x=>x.kind==="llm_call"),h=n.reduce((x,k)=>k.kind==="llm_call"?x+1:x,0),p=n.length-d.length,y=x=>e.on_state({...t,...x}),w=x=>s.jsx(FR,{step:x,node_label:a(x),open:r[x.id]===!0,on_toggle:()=>i(k=>({...k,[x.id]:!k[x.id]})),on_copy:e.on_copy,on_open_run:e.on_open_run},x.id);return s.jsxs("div",{className:"rs_view",children:[s.jsxs("div",{className:"rs_count",children:[s.jsxs("span",{children:[d.length," of ",n.length," steps",m?` · ${h} cycle${h===1?"":"s"}`:"",p&&t.only==="all"&&!t.all_steps&&!t.q?` · ${p} housekeeping hidden`:""]}),e.run_options.length>1?s.jsx("select",{className:"seg_select mono",value:e.run_id,onChange:x=>e.on_select_run(String(x.target.value||"")),"aria-label":"Run",children:e.run_options.map(x=>s.jsxs("option",{value:x,children:[jn(x,14),e.run_llm_counts[x]?` · ${e.run_llm_counts[x]} LLM`:""]},x))}):null]}),s.jsxs("div",{className:"rs_toolbar",children:[s.jsx("div",{className:"seg_toggle",role:"radiogroup","aria-label":"Layout",children:["cycles","steps"].map(x=>s.jsx("button",{type:"button",role:"radio","aria-checked":t.view===x,className:`seg_btn ${t.view===x?"active":""}`,onClick:()=>y({view:x}),children:x==="cycles"?"Cycles":"Steps"},x))}),s.jsx("div",{className:"seg_toggle",role:"radiogroup","aria-label":"Show",children:["all","llm","tools","failed"].map(x=>s.jsx("button",{type:"button",role:"radio","data-filter":x,"aria-checked":t.only===x,className:`seg_btn ${t.only===x?"active":""}`,onClick:()=>y({only:x}),children:IR[x]},x))}),s.jsx("input",{className:"rs_search",type:"search",value:t.q,onChange:x=>y({q:x.target.value}),placeholder:"Search steps","aria-label":"Search steps",autoComplete:"off",spellCheck:!1}),t.only==="all"?s.jsx(_o,{label:"All steps",action:"show-all-steps",hint:"Also list status events, waits, resumes and memory bookkeeping.",checked:t.all_steps,onChange:x=>y({all_steps:x})}):null]}),n.length?null:s.jsx("p",{className:"rs_muted",children:"No steps recorded for this run yet."}),n.length&&!d.length?s.jsx("p",{className:"rs_muted",children:"No step matches."}):null,t.view==="cycles"&&m?vR(d).map(x=>s.jsxs("section",{className:"rs_cycle","data-cycle":x.cycle,children:[s.jsx("h3",{className:"rs_cycle_head",children:x.cycle===0?"Before the first call":`Cycle ${x.cycle}`}),x.steps.map(w)]},x.cycle)):d.map(w)]})}function BR(e){const[t,n]=_.useState(!1),r=e.answer.length>kb,i=t||!r?e.answer:`${e.answer.slice(0,kb).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 ${_a(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(xi,{text:i}),r?s.jsx("button",{type:"button",className:"rs_link","aria-expanded":t,onClick:()=>n(a=>!a),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 kb=600,jb="—";function pd(e){return typeof e=="string"&&e?e:void 0}function UR(e){return e.endsWith("+00:00")||e.endsWith("Z")}function sy(e){if(!e||typeof e!="object")return e;const t=e,n={...e},r=pd(t.next_run_at)??pd(t.next_fire_at);let i=pd(t.next_run_local),a=pd(t.time_zone)??"";return!i&&!a&&r&&UR(r)&&(i=r,a="UTC"),r?n.next_run_at=r:delete n.next_run_at,i?n.next_run_local=i:delete n.next_run_local,n.time_zone=a,n.schedule_rule_text=pd(t.schedule_rule_text)??jb,n.schedule_text=pd(t.schedule_text)??jb,n}function WR(e){return{...e,listAutomations:async t=>{const n=await e.listAutomations(t);return{...n,items:(n.items??[]).map(sy)}},getAutomation:async t=>{const n=await e.getAutomation(t);return n!=null&&n.summary?{...n,summary:sy(n.summary)}:n},createAutomation:async t=>{const n=await e.createAutomation(t);return n!=null&&n.summary?{...n,summary:sy(n.summary)}:n}}}const qR="@default:",Id="abstractcode.agent.v1";function Sb(e,t){var n;return e?e.kind==="default"?e.interface===Id?"@default":"":((n=t.find(r=>r.bundleId===e.bundle_id&&r.flowId===e.flow_id))==null?void 0:n.value)??"":""}function HR(e,t){return e==="@default"?{kind:"default",interface:Id}:t?{kind:"bundle",bundle_id:t.bundleId,flow_id:t.flowId}:null}function VR(e){return e?e.kind==="default"?`${qR}${e.interface}`:`${e.bundle_id}:${e.flow_id}`:""}function GR(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 KR(e){const t={};for(const[n,r]of Object.entries(e||{}))if(typeof r=="string"){const i=r.trim();i&&(t[n]=i)}else r!==void 0&&(t[n]=r);return t}const JR={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; daily, weekly or monthly at a time of day; or once), when an email arrives, or when you ask; manage it on the Automations page."};function YR(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 XR="#launch/automate";function ZR(e){const t=pS(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 _w={when:"every",calendar:jj,email:ij,notify_email:!1,email_recipients:Rm,amount:"24",unit:"h",once_at:"",context:"independent",growing_max_tokens:String(Fm),tool_approval:"auto",title:"",start_at:"",count:"",until:""},Nb={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."},bS=["use_context"],QR="This choice also sets the workflow's Use Context input: the workflow always reads the history the automation gives it.";function Nv(e,t,n=!1){const r=e.when==="every",i=e.when==="daily"||e.when==="weekly"||e.when==="monthly";return{prompt:t,when:e.when==="once"?{kind:"once",at:e.once_at}:i?pv(e.when,e.calendar):{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||i)&&e.count.trim()?{count:Number(e.count)}:{},...(r||i)&&e.until?{until:e.until}:{}}}function eL(e){if(e.when==="email")return null;const t=Nv(e,"preview");return sE(t.when)?xj(t).trigger:null}function tL(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:[mn.not_set_up]};const n=KR(t.input_data),r=typeof n.prompt=="string"?n.prompt:"";delete n.prompt;for(const a of bS)delete n[a];delete n.workspace_root;let i;try{i=GR(t.choice,t.bundle_ref_for,n)}catch(a){return{ok:!1,errors:[String((a==null?void 0:a.message)||a)]}}return bj(Nv(e,r,t.email_usable===!0),{target:i,requestId:t.request_id})}function nL(e,t=!1){if(e.when==="email"){if(!t)return"";const n=bj(Nv(e,"preview",!0),{target:{flow_id:"@default",interface:Id},requestId:"preview"});return n.ok?`Runs ${aj(n.body.trigger.config)}.`:""}return""}class sL{constructor(t){yn(this,"key","");yn(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 rL(e,t,n){const r=tL(e,{...t,request_id:""});if(!r.ok)return r;const{request_id:i,...a}=r.body,u=n.id_for(JSON.stringify(a));return{ok:!0,body:{...r.body,request_id:u}}}function oa(e){return typeof e=="string"?e:e??null}function z_(e){var t,n,r,i,a,u;return{run_id:String((e==null?void 0:e.run_id)||"").trim(),workflow_id:oa(e==null?void 0:e.workflow_id),status:typeof(e==null?void 0:e.status)=="string"?String(e.status):"",created_at:oa(e==null?void 0:e.created_at),updated_at:oa(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:oa(e==null?void 0:e.parent_run_id),session_id:oa(e==null?void 0:e.session_id),actor_id:oa(e==null?void 0:e.actor_id),session_kind:oa(e==null?void 0:e.session_kind),automation_id:oa(e==null?void 0:e.automation_id),role:oa(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,pause_reason:oa(e==null?void 0:e.pause_reason),is_draft:(e==null?void 0:e.is_draft)===!0,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():((i=e==null?void 0:e.schedule)==null?void 0:i.interval)??null,schedule_target_workflow_id:typeof((a=e==null?void 0:e.schedule)==null?void 0:a.target_workflow_id)=="string"?String(e.schedule.target_workflow_id).trim():((u=e==null?void 0:e.schedule)==null?void 0:u.target_workflow_id)??null,current_node:typeof(e==null?void 0:e.current_node)=="string"?String(e.current_node).trim():(e==null?void 0:e.current_node)??null,llm_calls:typeof(e==null?void 0:e.llm_calls)=="number"?Number(e.llm_calls):(e==null?void 0:e.llm_calls)??null,tool_calls:typeof(e==null?void 0:e.tool_calls)=="number"?Number(e.tool_calls):(e==null?void 0:e.tool_calls)??null,tokens_total:typeof(e==null?void 0:e.tokens_total)=="number"?Number(e.tokens_total):(e==null?void 0:e.tokens_total)??null,error:(e==null?void 0:e.error)??null,waiting:(e==null?void 0:e.waiting)??null,archived:(e==null?void 0:e.archived)===!0}}function iL(e,t){const n=new Set(e.map(i=>String((i==null?void 0:i.run_id)||""))),r=[...e];for(const i of t){const a=String((i==null?void 0:i.run_id)||"");!a||n.has(a)||(n.add(a),r.push(i))}return r}function lg(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 kS(e){const t=lg(e);return t==="occurrence"?typeof e.occurrence_index=="number"?`occurrence #${e.occurrence_index}`:"occurrence":t==="legacy"?"legacy schedule":t||""}function oL(e){var n,r,i;const t=(i=(r=(n=e==null?void 0:e.capabilities)==null?void 0:n.contracts)==null?void 0:r.common)==null?void 0:i.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 Xl(e){return e.legacy===!0||e.capabilities.includes("legacy")}function jS(e,t=Date.now()){const n=Xl(e),r=e.last_occurrence,i=r&&r.attempts>1?` after ${r.attempts} attempts`:"",a=e.attention.unread||e.attention.pending_waits>0;return{id:e.automation_id,title:e.title,cadence:uv(e.trigger,e),next_run:dj(e,t),current:uj(e),state:e.status,last:r?r.excerpt:"",last_status:r?`#${r.index} ${r.status}${i}`:"no runs yet",attention:a?fj(e):null,legacy:n}}function SS(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 aL(e,t){const n=Dm(e,[],t),r=SS(e),i=t?{enabled:!1,reason:"Working…"}:Xl(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:i}}function lL(e,t){const n=a=>({enabled:!1,reason:a});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",i=e.status==="active"||e.status==="paused";return{legacy_pause:r?n("Already suspended."):i?{enabled:!0}:n("The schedule has ended."),legacy_resume:r?{enabled:!0}:n(i?"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 cL(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 uL=/^([1-9][0-9]*)([smhd])$/;function dL(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 fL(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(),i=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(),a=String(n.target_flow_id||(t==null?void 0:t.flow_id)||"").trim();if(!i||!a)throw new Error("The legacy schedule does not name its target workflow.");const u=[],c={..._w},d=typeof n.interval=="string"?n.interval.trim():"";if(!d)c.when="once",u.push("The legacy schedule ran once; pick the date and time to run.");else{const y=uL.exec(d);let w=y?Number(y[1]):0,x=y?y[2]:"";x==="s"&&w%60===0&&(w=w/60,x="m"),x==="m"||x==="h"||x==="d"?(c.amount=String(w),c.unit=x):u.push(`The legacy interval "${d}" is not a whole number of minutes, hours or days; choose an interval.`)}typeof n.repeat_count=="number"&&n.repeat_count>=1&&(c.count=String(n.repeat_count));const m=dL(n.repeat_until);m&&(c.until=m),c.context=n.share_context===!1?"independent":"growing";const h=t&&typeof t.input_data=="object"&&t.input_data&&!Array.isArray(t.input_data)?t.input_data:{},p={};for(const[y,w]of Object.entries(h))y==="workflow_selection"||y.startsWith("_")||(p[y]=w);return{choice:{kind:"bundle",bundle_id:i,flow_id:a},input_data:p,form:c,notes:u}}const mL={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 hL(e,t,n){return{answer_wait:async(r,i,a)=>{await e.submit_command({command_id:t(),run_id:r,type:"resume",payload:{wait_key:i,payload:a},client_id:"web_pwa"})},legacy_command:async(r,i,a)=>{await e.submit_command({command_id:t(),run_id:r,type:i,payload:a,client_id:"web_pwa"})},now_iso:n}}function _L(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 ry(e){return e.show_archived||e.status_filter==="archived"?e.items:e.items.filter(t=>t.status!=="archived")}function $b(e){return e.items.filter(t=>t.status==="archived").length}function $v(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 pL=3e4,B_=50;function Oi(e){return mv(e)?e:{status:0,code:"client_error",message:e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}}function iy(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,i)=>i.index-r.index)}class gL{constructor(t,n,r=[1500,4e3]){yn(this,"state",{...mL});yn(this,"listeners",new Set);yn(this,"list_seq",0);yn(this,"detail_seq",0);yn(this,"sources_loaded",!1);yn(this,"client");yn(this,"preview_schedule",t=>this.client.previewSchedule(t));yn(this,"definitions",new Map);this.host=n,this.followups_ms=r,this.client=WR(t)}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 i=await this.client.listAutomations({...this.state.status_filter?{status:this.state.status_filter}:{},...n?{cursor:n}:{},limit:B_});if(t.push(...i.items),!i.next_cursor)return t;n=i.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 ng(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,i=r?n.find(a=>a.automation_id===r.automation_id):void 0;this.set({items:n,loaded:!0,loading:!1,list_error:null,refreshed_at:Date.now(),...r&&i?{detail:{...r,summary:i}}:{}}),r&&await this.reload_occurrences(r.automation_id)}catch(n){if(t!==this.list_seq)return;this.set({loading:!1,loaded:!0,list_error:Oi(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 i;const n=String(t||"").trim(),r=++this.detail_seq;if(!n){this.set({selected_id:"",detail:null});return}this.set({selected_id:n,notice:"",...((i=this.state.detail)==null?void 0:i.automation_id)!==n?{detail:null}:{}});try{const a=this.state.items.find(d=>d.automation_id===n);if(a&&Xl(a)){this.set({detail:{automation_id:n,summary:a,definition:null,occurrences:[],next_cursor:null,error:null}});return}const[u,c]=await Promise.all([this.client.getAutomation(n),this.client.listOccurrences(n,{limit:B_})]);if(r!==this.detail_seq)return;this.set({detail:{automation_id:n,summary:a??u.summary,definition:u.definition,occurrences:iy([],c.items),next_cursor:c.next_cursor,error:null}}),await this.load_trigger_sources()}catch(a){if(r!==this.detail_seq)return;this.set({error:Oi(a)})}}async reload_occurrences(t){const n=this.state.detail;if(!n||n.automation_id!==t||Xl(n.summary))return;const[r,i]=await Promise.all([this.client.getAutomation(t),this.client.listOccurrences(t,{limit:B_})]),a=this.state.detail;if(!a||a.automation_id!==t)return;const u=this.state.items.find(c=>c.automation_id===t);this.set({detail:{...a,summary:u??r.summary,definition:r.definition,occurrences:iy(a.occurrences,i.items),next_cursor:a.occurrences.length>i.items.length?a.next_cursor:i.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:B_}),r=this.state.detail;if(!r||r.automation_id!==t.automation_id)return;this.set({detail:{...r,occurrences:iy(r.occurrences,n.items),next_cursor:n.next_cursor}})}catch(n){this.set({error:Oi(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,i){this.set({busy:!0});try{const a=await this.client.sendAutomationCommand(t,{type:n,...r?{payload:r}:{},...i?{command_id:i}:{}});return await this.after_change(t),a}catch(a){throw Oi(a)}finally{this.set({busy:!1})}}async revise(t,n,r,i){this.set({busy:!0});try{const a=await this.client.reviseAutomation(t,{changes:n,...r!==null?{expected_revision:r}:{},...i?{command_id:i}:{}});return await this.after_change(t),a}catch(a){throw Oi(a)}finally{this.set({busy:!1})}}definition(t){if(Xl(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 i=this.definitions.get(n);if(i&&i.revision===t.revision)return i.answer;const a=this.client.getAutomation(n).then(u=>u.definition??null);return a.catch(()=>this.definitions.delete(n)),this.definitions.set(n,{revision:t.revision,answer:a}),a}async discuss(t,n,r,i){this.set({busy:!0});try{const a=await this.client.discuss(t,{occurrence_index:n,prompt:r,...i?{request_id:i}:{}});return this.set({notice:$v(n,a)}),a}catch(a){throw Oi(a)}finally{this.set({busy:!1})}}async seen(t,n){try{await this.client.markSeen(t,n)}catch(r){throw Oi(r)}}async answer_wait(t,n,r,i){var a;this.set({busy:!0});try{const u=(((a=this.state.detail)==null?void 0:a.occurrences)||[]).flatMap(c=>c.waits).find(c=>c.run_id===n&&c.wait_key===r);if(!u)throw new Error(`No loaded wait ${r} on run ${n}; reload the automation.`);await this.host.answer_wait(n,r,_L(u.kind,i)),await this.after_change(t)}catch(u){throw Oi(u)}finally{this.set({busy:!1})}}async row_action(t,n){const r=`automation.${n}`;this.set({error:null,notice:""});try{await this.command(t.automation_id,r),this.set({notice:n==="run_now"&&t.status==="paused"?`Run now sent to “${t.title}”; it stays paused.`:n==="pause"||n==="resume"?Cb(t.title,n==="resume"):`${yL[n]} sent to “${t.title}”.`,confirm_archive_id:""})}catch(i){this.set({error:Oi(i)})}}set_show_archived(t){this.set({show_archived:t})}ask_archive(t){this.set({confirm_archive_id:t})}async legacy_action(t,n){if(!Xl(t))throw new Error("legacy_action on a non-legacy automation");const r=cL(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}”.`:Cb(t.title,n==="legacy_resume")}),await this.refresh()}catch(i){this.set({error:Oi(i)})}finally{this.set({busy:!1})}}report_error(t){this.set({error:Oi(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 Cb(e,t){return t?`“${e}” is active: it runs on its schedule.`:`“${e}” is paused: scheduled runs are skipped.`}const yL={run_now:"Run now",archive:"Archive"};function wL(e){const t=(n,r,i)=>s.jsx("button",{type:"button",role:"radio","aria-checked":e.mode===n,className:`seg_btn ${e.mode===n?"active":""}`,"data-mode":n,title:i,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:JR[e.mode]})]})}function vL(e){const t=e.form,n=ng(e.email_status),r=t.when==="email"&&!n?"every":t.when,i=nL(t,n);return s.jsxs("div",{className:"automate_fields",children:[s.jsxs("fieldset",{"data-section":"when",children:[s.jsx("legend",{children:us.legend}),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"})})," ",us.kind_every]}),["daily","weekly","monthly"].map(a=>s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:"automate_when",value:a,checked:r===a,disabled:e.disabled,onChange:()=>e.on_change({when:a})})," ",us[`kind_${a}`]]},a)),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"})})," ",us.kind_once]}),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"})})," ",mn.trigger_label]})]}),n?null:s.jsx(rw,{status:e.email_status,onOpenMyEmail:e.on_open_my_email}),r==="email"?s.jsx(IE,{value:t.email,onChange:a=>e.on_change({email:a}),disabled:e.disabled,idBase:"automate"}):r==="daily"||r==="weekly"||r==="monthly"?s.jsx(Sj,{value:pv(r,t.calendar),onChange:a=>e.on_change({calendar:gv(t.calendar,a)}),idBase:"automate",disabled:e.disabled}):r==="every"?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"automate_row",role:"group","aria-label":"Presets",children:QC.map(a=>a.when.kind==="every"?s.jsx("button",{type:"button",className:"btn btn_sm","data-preset":a.label,"aria-pressed":Number(t.amount)===a.when.amount&&t.unit===a.when.unit,disabled:e.disabled,onClick:()=>{a.when.kind==="every"&&e.on_change({amount:String(a.when.amount),unit:a.when.unit})},children:a.label},a.label):null)}),s.jsxs("div",{className:"automate_row",children:[s.jsx("span",{children:us.every_label}),s.jsx("input",{type:"number",min:1,step:1,value:t.amount,disabled:e.disabled,"aria-label":"Interval amount",onChange:a=>e.on_change({amount:a.target.value})}),s.jsxs("select",{value:t.unit,disabled:e.disabled,"aria-label":"Interval unit",onChange:a=>e.on_change({unit:a.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:us.once_label}),s.jsx("input",{type:"datetime-local",value:t.once_at,disabled:e.disabled,onChange:a=>e.on_change({once_at:a.target.value})})]}),r==="email"?s.jsx("div",{className:"automate_preview","aria-live":"polite","data-preview":"true",children:i||"Incomplete email trigger."}):s.jsx("div",{className:"automate_preview automate_preview--served",children:s.jsx($j,{state:e.served,onOpenPreferences:e.on_open_preferences,showZone:r!=="every"})})]}),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) — ",Nb.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"})," — ",Nb.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:a=>e.on_change({growing_max_tokens:a.target.value})})]}):null,s.jsx("p",{className:"help_text muted","data-context-owns":"use_context",children:QR})]}),s.jsxs("fieldset",{"data-section":"tools",children:[s.jsx("legend",{children:"Tools"}),e.available_tools&&e.on_tools_change?s.jsx(Cj,{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:mn.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"})})," ",rE,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(rw,{status:e.email_status,onOpenMyEmail:e.on_open_my_email}),s.jsx(OE,{notifyEmail:n&&t.notify_email,onNotifyEmailChange:a=>e.on_change({notify_email:a}),recipients:n?t.email_recipients:Rm,onRecipientsChange:a=>e.on_change({email_recipients:a}),disabled:e.disabled||!n,idBase:"automate"})]})]})}function xL(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"||t.when==="daily"||t.when==="weekly"||t.when==="monthly"?s.jsxs(s.Fragment,{children:[t.when==="every"?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})})]}):null,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 bL(e,t){const n=String(t||"").trim();return n||`Loading ${String(e||"").trim()||"data"}…`}function nc(e){const t=bL(e.what,e.label),n=e.size==="block"?"block":"inline";return s.jsxs("div",{className:`af_loading af_loading_${n}${e.className?` ${e.className}`:""}`,role:"status","aria-live":"polite","aria-busy":"true",children:[s.jsx("span",{className:"af_loading_spin","aria-hidden":"true",children:s.jsx(Xe,{name:"loader",size:n==="block"?20:16})}),s.jsx("span",{className:"af_loading_text",children:t})]})}function Xs(){return Ga()}const NS=Zp("voice and camera")??"Voice and camera are not supported in this browser (getUserMedia unavailable).",$S="Copy failed — select and copy";function CS(){var t;const e=globalThis.navigator;return typeof((t=e==null?void 0:e.mediaDevices)==null?void 0:t.getUserMedia)=="function"}function kL(e){var i;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{(i=r==null?void 0:r.focus)==null||i.call(r)}catch{}}}async function hh(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 kL(t)}const jL=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 SL(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 i=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),a=new Uint32Array(64),u=(c,d)=>c>>>d|c<<32-d;for(let c=0;c<n.length;c+=64){for(let b=0;b<16;b++)a[b]=r.getUint32(c+b*4,!1);for(let b=16;b<64;b++){const S=u(a[b-15],7)^u(a[b-15],18)^a[b-15]>>>3,$=u(a[b-2],17)^u(a[b-2],19)^a[b-2]>>>10;a[b]=a[b-16]+S+a[b-7]+$>>>0}let[d,m,h,p,y,w,x,k]=[i[0],i[1],i[2],i[3],i[4],i[5],i[6],i[7]];for(let b=0;b<64;b++){const S=u(y,6)^u(y,11)^u(y,25),$=y&w^~y&x,A=k+S+$+jL[b]+a[b]>>>0,E=u(d,2)^u(d,13)^u(d,22),z=d&m^d&h^m&h,F=E+z>>>0;k=x,x=w,w=y,y=p+A>>>0,p=h,h=m,m=d,d=A+F>>>0}i[0]=i[0]+d>>>0,i[1]=i[1]+m>>>0,i[2]=i[2]+h>>>0,i[3]=i[3]+p>>>0,i[4]=i[4]+y>>>0,i[5]=i[5]+w>>>0,i[6]=i[6]+x>>>0,i[7]=i[7]+k>>>0}return Array.from(i,c=>c.toString(16).padStart(8,"0")).join("")}async function NL(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 i=await n.digest("SHA-256",t);return Array.from(new Uint8Array(i),a=>a.toString(16).padStart(2,"0")).join("")}return SL(t)}const $L=/^[a-zA-Z0-9_-]+$/;function Eb(e){return $L.test(String(e||"").trim())}async function CL(e){const t=String(e||"");return NL(t)}async function EL(e){const t=String(e||"").trim();if(!t)throw new Error("session_id is required");if(Eb(t)){const r=`session_memory_${t}`;if(Eb(r))return r}return`session_memory_sha_${(await CL(t)).slice(0,32)}`}const ES="abstractobserver_voice";function AL(){var e;try{const t=(e=globalThis.localStorage)==null?void 0:e.getItem(ES),n=t?JSON.parse(t):null;return n&&typeof n=="object"&&!Array.isArray(n)?n:{}}catch{return{}}}const pw=new Set;function TL(e){var t;try{(t=globalThis.localStorage)==null||t.setItem(ES,JSON.stringify(e||{}))}catch{}for(const n of pw)n(e||{})}function AS(){const[e,t]=_.useState(()=>AL());return _.useEffect(()=>(pw.add(t),()=>{pw.delete(t)}),[]),[e,TL]}function TS(e,t){const[n,r]=_.useState({value:null,failed:!1});return _.useEffect(()=>{if(!t||!e){r({value:null,failed:!1});return}let i=!0;return e.voice_defaults().then(a=>i&&r({value:a||{},failed:!1})).catch(()=>i&&r({value:null,failed:!0})),()=>{i=!1}},[e,t]),n}function ML(e){const t=e.gateway;return s.jsx(WA,{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 RL=18e4;function LL(e,t,n,r=()=>{}){return async function*(i,a){r(),yield*Q2({path:e.gateway_url(yt(`runs/${encodeURIComponent(t)}/voice/tts/stream`)),headers:e.auth_headers(),signal:a,body:{text:i,request_id:Xs(),...PA(n())}})}}function IL(e,t,n,r,i=()=>{},a=RL){return async(u,c)=>{i();const d=String(c||u.type||"").toLowerCase(),m=d.includes("mp4")?"m4a":d.includes("ogg")?"ogg":d.includes("wav")?"wav":"webm",h=new File([u],`recording.${m}`,{type:d||"audio/webm"}),p=await e.attachments_upload(t,h,{filename:h.name,content_type:h.type});i();let y;const w=await Promise.race([e.audio_transcribe(n,{audio_artifact:p,request_id:Xs(),...DA(r())}),new Promise((x,k)=>{y=setTimeout(()=>k(new Error(`the gateway did not answer within ${Math.round(a/1e3)} s`)),a)})]).finally(()=>clearTimeout(y));return i(),{text:String(w.text||""),provider:w.provider,model:w.model}}}function MS(e){const{gateway:t,prefs:n}=e,r=String(e.session_id||"").trim(),[i,a]=_.useState("");_.useEffect(()=>{let w=!0;if(!r){a("");return}return EL(r).then(x=>w&&a(x)).catch(()=>w&&a("")),()=>{w=!1}},[r]);const u=`${r}|${i}`,c=_.useRef(u);c.current=u;const d=_.useRef(n);d.current=n;const m=_.useRef(e);m.current=e;const h=()=>{if(c.current!==u)throw new Error("Voice session changed.")},p=!!(t&&i&&r),y=lC({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:p?LL(t,i,()=>d.current,h):void 0,transcribe:p?IL(t,r,i,()=>d.current,h):void 0,on_transcript:w=>{c.current===u&&m.current.on_transcript(w)},on_error:w=>{c.current===u&&m.current.on_error(w)}});return _.useEffect(()=>{var w;return y.stop_tts(),(w=y.cancel_voice_ptt_recording)==null||w.call(y),()=>{var x;y.stop_tts(),(x=y.cancel_voice_ptt_recording)==null||x.call(y)}},[u,y.stop_tts,y.cancel_voice_ptt_recording]),{...y,run_id:i}}function RS(e,t,n){const r=_.useRef(null);_.useEffect(()=>{const i=(n==null?void 0:n.key)||"";if(r.current===null){r.current=i;return}!i||i===r.current||(r.current=i,t&&e.tts_supported&&(n!=null&&n.text.trim())&&e.toggle_tts(i,n.text))},[n==null?void 0:n.key,n==null?void 0:n.text,t,e.tts_supported,e.toggle_tts])}function OL(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 PL=350;function LS(e){const{voice:t}=e,n=_.useRef(!1),r=_.useRef(!1),i=_.useRef(0),a=()=>{if(r.current){r.current=!1,t.stop_voice_ptt_recording();return}n.current=!0,i.current=Date.now(),t.start_voice_ptt_recording().then(()=>{!n.current&&!r.current&&t.stop_voice_ptt_recording()})},u=()=>{if(n.current){if(n.current=!1,Date.now()-i.current<PL){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",u),window.addEventListener("pointercancel",u),window.addEventListener("blur",w),()=>{window.removeEventListener("pointerup",u),window.removeEventListener("pointercancel",u),window.removeEventListener("blur",w)}},[t.stop_voice_ptt_recording]),_.useEffect(()=>{t.voice_ptt_recording||(r.current=!1)},[t.voice_ptt_recording]);const c=t.voice_ptt_since||0,d=OL(!!c),m=q2(e.prefs,e.defaults),h=t.voice_ptt_recording?`Recording… ${c?Jk(c,d):""}`.trim():t.voice_ptt_busy?H2(c||d,d,m):"",y=!CS()?NS: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&&a()},onPointerUp:u,onPointerCancel:u,onKeyDown:w=>{[" ","Enter"].includes(w.key)&&!w.repeat&&(w.preventDefault(),a())},onKeyUp:w=>{[" ","Enter"].includes(w.key)&&(w.preventDefault(),u())},children:s.jsx(Xe,{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(Xe,{name:"x",size:14})}):null,h?s.jsx("span",{role:"status",className:"voice_status mono","data-voice-status":!0,children:h}):null,e.error?s.jsx("span",{role:"alert",className:"voice_error","data-voice-error":!0,children:e.error}):null]})}function DL(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(Xe,{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 FL="abstractobserver";function zL(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,i,a)=>e.stream_ledger(t,{after:n,on_step:r,signal:i,on_open:a}),submitCommand:t=>e.submit_command(t)}}function BL(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 UL=new Set(["completed","failed","cancelled"]);function WL(e){var q;const{gateway:t,discussion:n}=e,r=_.useMemo(()=>zL(t),[t]),[i,a]=_.useState(((q=n.session)==null?void 0:q.run_id)||""),[u,c]=_.useState(""),[d,m]=_.useState(!1),[h,p]=_.useState(""),{controller:y,snapshot:w}=LM({transport:r,runId:i,enabled:e.connected,clientId:FL}),x=n.session,k=!!i&&!UL.has(w.status)&&w.status!=="idle",b=AM(w),[S]=AS(),$=TS(e.connected?t:null,e.connected),[A,E]=_.useState(""),z=MS({gateway:e.connected?t:null,session_id:(x==null?void 0:x.session_id)||e.voice_session_id||"",prefs:S,on_error:E,on_transcript:I=>c(Z=>Z.trim()?`${Z.trimEnd()}
|
|
92
|
+
${I}`:I)}),F=_.useMemo(()=>{for(let I=w.messages.length-1;I>=0;I-=1){const Z=w.messages[I];if(Z.role==="assistant")return Z.live?null:{key:String(Z.id||""),text:String(Z.content||"")}}return null},[w.messages]);RS(z,S.read_aloud===!0,F);const M=I=>z.tts_playback.key&&z.tts_playback.key===String(I.id||"")?z.tts_playback.status:"idle",D=async I=>{var R;const Z=I.trim();if(Z){m(!0);try{if(x){const T=String(((R=w.run)==null?void 0:R.workflow_id)||""),P=BL(T),L=await t.start_run(P.flow_id,{prompt:Z},{bundle_id:P.bundle_id,session_id:x.session_id});a(L)}else{const T=await e.on_fork(n.automation_id,n.occurrence_index,Z);a(T.run_id)}c("")}finally{m(!1)}}},H=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(Xe,{name:"chevronRight",size:13,className:"flip_x"})," ",n.automation_title]}),s.jsxs("span",{className:"discussion_title",children:[s.jsx(Xe,{name:"chat",size:15})," Discussion — fork at #",n.occurrence_index]}),s.jsx("span",{className:"pane_spacer"}),x?s.jsxs(s.Fragment,{children:[s.jsxs("button",{type:"button",className:`btn btn_sm${h==="own"?" active":""}`,"data-action":"discussion-files",onClick:()=>p(h==="own"?"":"own"),title:x.workspace_root,children:[s.jsx(Xe,{name:"folder",size:14})," Its files"]}),s.jsxs("button",{type:"button",className:`btn btn_sm${h==="mounted"?" active":""}`,"data-action":"automation-files",onClick:()=>p(h==="mounted"?"":"mounted"),title:x.mounted_workspace,children:[s.jsx(Xe,{name:"folder",size:14})," Automation files"]})]}):null]});return s.jsxs("section",{className:"pane auto_detail auto_discussion","data-discussion-session":(x==null?void 0:x.session_id)||void 0,children:[h&&x?s.jsx(aS,{fetchGateway:t.fetch_gateway,runId:h==="own"?x.run_id:n.automation_id,title:h==="own"?"Discussion files":"Automation files",note:h==="own"?"The discussion's own writable folder.":"Mounted read-only for the discussion's file tools; nothing is written back.",onClose:()=>p(""),refreshKey:w.status}):null,s.jsx(EM,{header:H,messages:w.messages,draft:u,onDraftChange:c,onSend:D,busy:k||d,busyLabel:d?x?"Starting…":"Forking the automation…":b?"Waiting for you":"Working…",onCancel:k?()=>y.cancel():void 0,stopState:w.stop??null,disabled:!e.connected,interaction:BM(b,y,{records:w.records,currentRun:w.run}),placeholder:x?"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(LS,{voice:z,defaults:$.value,prefs:S,blocked:e.connected?null:"Connect to the gateway first.",error:A}),messageProps:z.tts_supported?{onSpeakToggle:I=>{E(""),z.toggle_tts(String(I.id||""),String(I.content||""))},getSpeakState:M}:void 0,footer:w.error?s.jsx("div",{className:"observe_context_card error",role:"alert",children:w.error}):null})]})}const qL=On.title;function Ab(e){return`${qL}: ${e}`}const HL=["workspace_access_mode","workspace_allowed_paths"];function VL(e){return!!(e&&typeof e=="object"&&!Array.isArray(e)&&Array.isArray(e.folders))}function IS(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 VL(t)?t:null}function OS(e,t){const n={...e||{}};for(const r of HL)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 GL(e,t){const n=e.target;return{target:{bundle_ref:n.bundle_ref,flow_id:n.flow_id,input_data:OS(n.input_data,t)}}}const KL=3e4,gw=new WeakMap;function JL(e,t,n=Date.now()){let r=gw.get(e);r||gw.set(e,r=new Map);const i=JSON.stringify(t),a=r.get(i);if(a&&n-a.at<KL)return a.answer;const u=zm(e)(t).then(c=>c.summary);return u.catch(()=>r==null?void 0:r.delete(i)),r.set(i,{at:n,answer:u}),u}function YL(e){gw.delete(e)}function PS(e){const[t,n]=_.useState(null),r=JSON.stringify(e.value);return _.useEffect(()=>{if(!e.connected||!e.request){n(null);return}let i=!0;return JL(e.request,e.value).then(a=>i&&n(Ab(a))).catch(a=>i&&n(Ab(ig(a)))),()=>{i=!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 XL(e){const{connected:t,request:n,value:r}=e,[i,a]=_.useState(null),[u,c]=_.useState(null),d=JSON.stringify(r);_.useEffect(()=>{if(!t){a(null),c(null);return}let y=!0;return c(null),zm(n)(r).then(w=>y&&a(w)).catch(w=>y&&c(`Could not read your workspaces: ${ig(w)}`)),()=>{y=!1}},[t,d,n]);const m=e.on_change,h=_.useCallback(async y=>{const w=await zm(n)(y);await m(y),a(w),YL(n)},[n,m]),p=t?e.disabled?"Saving…":null:"Connect to your gateway to choose workspaces.";return s.jsx(zj,{level:"run",idPrefix:e.id_prefix,value:r,effective:i,onChange:h,loadError:t?u:p,unavailableReason:p,footer:e.footer})}class ZL{constructor(){yn(this,"made",new Map);yn(this,"current",new Map)}record(t,n,r){if(this.current.set(t,r),n===null)return;let i=this.made.get(t);i||this.made.set(t,i=new Set),i.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 i=n;for(;r&&r.has(i+1);)i+=1;return i}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:OS(n.target.input_data,r)}}}}async function QL(e,t,n,r,i){const a=t.expected(n.automation_id,n.summary.revision);await e.revise(n.automation_id,GL(n.definition,r),a,i),t.record(n.automation_id,a,r)}function DS(e){return`abstractobserver_list_open_${e}`}function FS(){try{return typeof localStorage>"u"?null:localStorage}catch{return null}}function e3(e,t=FS()){try{return(t==null?void 0:t.getItem(DS(e)))!=="0"}catch{return!0}}function t3(e,t,n=FS()){try{n==null||n.setItem(DS(e),t?"1":"0")}catch{}}function Ep(e){const[t,n]=_.useState(()=>e3(e)),r=_.useCallback(()=>{n(i=>{const a=!i;return t3(e,a),a})},[e]);return[t,r]}function Ap(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(Xe,{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 n3=5e3,s3=[["","All"],["active","Active"],["paused","Paused"],["completed","Completed"],["failed","Failed"],["archived","Archived"]],r3={pause:ca.pause,resume:ca.resume,run_now:ca.run_now,edit:ca.revise,archive:`${ca.archive}…`,discuss:ca.discuss},i3={pause:Bo.pause,resume:Bo.resume,run_now:Bo.run_now,edit:Bo.revise,archive:Bo.archive,discuss:Bo.discuss},o3={pause:"pause",resume:"resume",run_now:"run_now",edit:"revise",archive:"archive",discuss:"discuss"},a3={legacy_pause:Bo.pause,legacy_resume:Bo.resume,legacy_run_now:Bo.run_now,open_run:"list",recreate:"refresh"};function l3(e){return s.jsx("span",{className:"auto_state","data-field":"state",children:s.jsx(Ij,{status:e.status})})}function U_(e){return s.jsxs("span",{className:`auto_fact${e.className?` ${e.className}`:""}`,"data-field":e.field,title:e.label,children:[s.jsx(Xe,{name:e.icon,size:12}),s.jsx("span",{children:e.children})]})}const c3={legacy_pause:"Suspend",legacy_resume:"Resume",legacy_run_now:"Run now",open_run:"Open run",recreate:"Recreate as automation"},u3="On: the schedule runs at its times. Off: suspended, scheduled runs are skipped until it is on again.";function Tb(e){const t=e.busy||e.ctl.enabled?null:e.ctl.reason||"Not available now.";return s.jsx(_o,{variant:"sm",className:"auto_switch",action:"active",id:`auto-active-${e.summary.automation_id}`,label:ca.active,checked:e.summary.status==="active",unavailableReason:t,busy:e.busy,hint:e.hint,onChange:e.onChange})}function d3(e){const[t,n]=_.useState(void 0),{summary:r,ws:i}=e;return _.useEffect(()=>{let a=!0;return i.definition(r).then(u=>a&&n(u?IS(u):void 0),()=>a&&n(void 0)),()=>{a=!1}},[r.automation_id,r.revision,i.definition]),t===void 0?null:s.jsx(PS,{request:i.request,connected:i.connected,value:t,refresh_key:r.revision??""})}function f3(e){const t=e.summary,n=jS(t),r=e.state.selected_id===t.automation_id,i=e.state.busy,a=(d,m,h,p,y,w,x,k)=>s.jsxs("button",{type:"button",className:`btn btn_sm auto_action${x?" auto_action_icon":""}${y?` ${y}`:""}`,"data-action":d,disabled:!h.enabled,title:[x?m:null,h.enabled?null:h.reason,k].filter(Boolean).join(`
|
|
93
|
+
`)||void 0,"aria-label":x?m:void 0,"aria-description":k,onClick:p,children:[w?s.jsx(Xe,{name:w,size:13}):null,x?null:s.jsx("span",{children:m})]},d);let u;if(n.legacy){const d=lL(t,i),m=t.status==="paused"?"legacy_resume":"legacy_pause",h=["legacy_run_now","open_run","recreate"];u=[s.jsx(Tb,{summary:t,busy:i,ctl:d[m],hint:u3,onChange:()=>e.h.on_legacy_action(t,m)},"active"),...h.map(p=>a(p,c3[p],d[p],()=>e.h.on_legacy_action(t,p),void 0,a3[p]))]}else{const d=aL(t,i),m=t.status==="active"?"pause":"resume",h=["run_now","edit","discuss","archive"];u=[s.jsx(Tb,{summary:t,busy:i,ctl:d.active,hint:Sp("active",t),onChange:()=>e.h.on_row_action(t,m)},"active"),...h.map(p=>a(p,r3[p],d[p],()=>e.h.on_row_action(t,p),p==="archive"?"danger auto_action_end":void 0,i3[p],p==="archive",Sp(o3[p],t)))]}const c=e.state.confirm_archive_id===t.automation_id;return s.jsxs("li",{className:`auto_row${r?" selected":""}`,"data-automation-id":t.automation_id,"data-legacy":n.legacy?"true":void 0,children:[s.jsxs("button",{type:"button",className:"auto_row_main",onClick:()=>e.h.on_select(t.automation_id),"aria-current":r?"true":void 0,children:[s.jsxs("span",{className:"auto_row_title",children:[n.title,n.legacy?s.jsx("span",{className:"chip scheduled",children:"legacy"}):null,s.jsx(l3,{status:n.state}),n.attention?s.jsxs("span",{className:"chip warn auto_row_attention","data-field":"attention",children:[s.jsx(Xe,{name:"warning",size:12})," ",n.attention]}):null]}),s.jsxs("span",{className:"auto_row_facts",children:[s.jsx(U_,{icon:"refresh",field:"cadence",label:"When it runs",children:n.cadence}),n.current?s.jsx(U_,{icon:"loader",field:"current",label:"Running now",className:"auto_row_current",children:n.current}):null,s.jsxs(U_,{icon:"clock",field:"next",label:"Next run",children:["next: ",n.next_run]}),s.jsx(U_,{icon:"info",field:"last-status",label:"Last run",children:n.last_status})]}),e.ws&&!n.legacy?s.jsx(d3,{summary:t,ws:e.ws}):null,n.last?s.jsx("span",{className:"auto_row_excerpt","data-field":"excerpt",children:hS(n.last)}):null]}),s.jsx("div",{className:"auto_row_actions",role:"toolbar","aria-label":`Controls for ${n.title}`,children:u}),c?s.jsxs("div",{className:"auto_row_confirm",role:"group","aria-label":"Confirm archive",children:[s.jsxs("span",{children:["Archive “",n.title,"”? Its history stays readable; it will not run again."]}),s.jsxs("button",{type:"button",className:"btn btn_sm danger auto_action","data-action":"archive-confirm",disabled:i,onClick:()=>e.h.on_confirm_archive(t),children:[s.jsx(Xe,{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(Xe,{name:"x",size:13}),s.jsx("span",{children:"Keep it"})]})]}):null]})}function m3(e){const t=e.state,n=e.list?e.list.open:!0,r=t.error??t.list_error,i=r?kp(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(Ap,{open:n,on_toggle:e.list.on_toggle,controls:"auto_list_body",title:"Automations",count:ry(t).length}):s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"pane_title",children:"Automations"}),s.jsx("span",{className:"pane_count",children:ry(t).length})]}),s.jsx("span",{className:"pane_spacer"}),s.jsx("select",{className:"seg_select",value:t.status_filter,onChange:a=>e.h.on_status_filter(a.target.value),"aria-label":"Filter by status",children:s3.map(([a,u])=>s.jsx("option",{value:a,children:u},a||"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(Xe,{name:t.loading?"loader":"refresh",size:14})}),s.jsxs("a",{className:`btn btn_sm auto_new${e.available.available?"":" disabled"}`,"data-action":"new",href:XR,"aria-disabled":!e.available.available,title:"New automation: opens Launch in Automate mode","aria-label":"New automation",onClick:a=>{a.preventDefault(),e.available.available&&e.h.on_new()},children:[s.jsx(Xe,{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}),i?s.jsxs("div",{className:"observe_context_card error auto_list_error",role:"alert","data-code":r==null?void 0:r.code,children:[s.jsx(Xe,{name:"error",size:14}),s.jsxs("span",{className:"auto_list_msg",children:[s.jsx("strong",{children:i.title})," ",s.jsx("span",{children:i.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(Xe,{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(Xe,{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(Xe,{name:"x",size:12})}):null]}):null}),e.available.available&&!t.loaded&&t.loading?s.jsx(nc,{what:"automations"}):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,$b(t)>0&&t.status_filter!=="archived"?s.jsx("div",{className:"auto_show_archived",children:s.jsx(_o,{variant:"sm",action:"show-archived",label:`Archived (${$b(t)})`,hint:"List archived automations too. Their history stays readable; they do not run.",checked:t.show_archived,onChange:a=>e.h.on_show_archived(a)})}):null,s.jsx("ul",{className:"auto_rows",children:ry(t).map(a=>s.jsx(f3,{summary:a,state:t,h:e.h,ws:e.ws},a.automation_id))})]})]})}function h3(e,t,n,r){const i=e.state,a=i.detail;if(!a||Xl(a.summary))return null;const u=a.automation_id;return{summary:a.summary,...a.definition?{definition:a.definition}:{},occurrences:a.occurrences,triggerSources:i.trigger_sources,busy:i.busy,...a.error?{error:a.error}:{},onRevise:async(c,d,m)=>{if(!r)return e.revise(u,c,d,m==null?void 0:m.command_id);const h=r.expected(u,d),p=await e.revise(u,r.changes(u,c),h,m==null?void 0:m.command_id);return r.note(u,h),p},onCommand:(c,d,m)=>e.command(u,c,d,m==null?void 0:m.command_id),onDiscuss:async(c,d,m)=>{const h=await e.discuss(u,c,d,m==null?void 0:m.request_id);return t.on_open_session(h,$v(c,h),c),h},onSeen:c=>e.seen(u,c),onLoadMore:()=>void e.load_more(),onOpenRun:c=>t.on_open_run(c),...t.on_open_workspace?{onOpenWorkspace:t.on_open_workspace}:{},...t.fetch_gateway?{fetchGateway:t.fetch_gateway}:{},onAnswerWait:(c,d,m)=>e.answer_wait(u,c,d,m),...n?{editOpen:n.open,onEditOpenChange:n.on_change}:{},emailStatus:i.email_status,previewSchedule:e.preview_schedule,...t.on_open_my_email?{onOpenMyEmail:()=>{var c;return(c=t.on_open_my_email)==null?void 0:c.call(t)}}:{}}}function _3(e){var c,d;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(nc,{what:"automation",size:"block"})});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 (",iw.toLowerCase(),")."]})});if(Xl(t.summary)){const m=jS(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:m.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 (",m.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=h3(e.ctl,e.host,e.edit,n==null?void 0:n.revisions),i=e.ctl,a=t.definition,u=IS(a);return s.jsxs("section",{className:"pane auto_detail",children:[e.browser??null,n&&a?s.jsx("div",{className:"auto_workspaces","data-section":"workspaces","data-editing":(c=e.edit)!=null&&c.open?"true":void 0,children:(d=e.edit)!=null&&d.open?s.jsx(s.Fragment,{children:s.jsx(XL,{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:u,disabled:i.state.busy,on_change:m=>QL(i,n.revisions,{automation_id:t.automation_id,summary:t.summary,definition:a},m,Ga())})}):s.jsx(PS,{request:n.request,connected:n.connected,value:u,refresh_key:t.summary.revision??""})}):null,r?s.jsx(zM,{...r,workflowPickerOptions:e.workflowPickerOptions,availableTools:e.availableTools}):null]})}function p3(e,t){if(t==="edit")return{kind:"edit"};if(t!=="discuss")return{kind:"forward"};const n=SS(e);return n===null?{kind:"none"}:{kind:"discuss",index:n}}function g3(e){const t=e.ctl,n=_.useRef(null);n.current||(n.current=new ZL);const r=e.workspace_request?{request:e.workspace_request,connected:e.active,definition:A=>t.definition(A)}:void 0,[i,a]=Ep("automations"),[u,c]=_.useState(null),d=A=>c(E=>({...A,opened:((E==null?void 0:E.opened)||0)+1})),[m,h]=_.useState(""),[p,y]=_.useState("");_.useSyncExternalStore(A=>t.subscribe(A),()=>t.state,()=>t.state);const[w,x]=_.useState(()=>typeof document>"u"||document.visibilityState!=="hidden");_.useEffect(()=>{const A=()=>x(document.visibilityState!=="hidden");return document.addEventListener("visibilitychange",A),()=>document.removeEventListener("visibilitychange",A)},[]),_.useEffect(()=>{if(!e.active||!w||!e.available.available)return;t.refresh();const A=window.setInterval(()=>void t.refresh(),pL);return()=>window.clearInterval(A)},[t,e.active,w,e.available.available]);const k=t.state.detail,b=t.state.notice;_.useEffect(()=>{if(!b)return;const A=window.setTimeout(()=>t.dismiss_notice(),n3);return()=>window.clearTimeout(A)},[t,b]);const S={...e.host,on_open_workspace:A=>h(E=>E===A?"":A),fetch_gateway:e.gateway.fetch_gateway,on_open_session:(A,E,z)=>{e.host.on_open_session(A,E,z),k&&d({automation_id:k.automation_id,automation_title:k.summary.title,occurrence_index:z,session:A})}},$={...e.h,on_select:A=>{c(null),h(""),A!==p&&y(""),e.h.on_select(A)},on_dismiss_notice:()=>t.dismiss_notice(),on_dismiss_error:()=>t.dismiss_error(),on_row_action:(A,E)=>{const z=p3(A,E);z.kind==="forward"?e.h.on_row_action(A,E):z.kind==="edit"?(c(null),h(""),y(A.automation_id),e.h.on_select(A.automation_id)):z.kind==="discuss"&&(e.h.on_select(A.automation_id),d({automation_id:A.automation_id,automation_title:A.title,occurrence_index:z.index}))}};return s.jsxs("div",{className:`page auto_page${i?"":" list_collapsed"}`,children:[s.jsx(m3,{state:t.state,available:e.available,h:$,list:{open:i,on_toggle:a},ws:r}),u?s.jsx(WL,{gateway:e.gateway,discussion:u,connected:e.active,voice_session_id:e.voice_session_id||"",on_fork:async(A,E,z)=>{const F=await t.discuss(A,E,z);return e.host.on_open_session(F,$v(E,F),E),c(M=>M&&{...M,session:F}),F},on_close:()=>c(null)},u.opened):s.jsx(_3,{workflowPickerOptions:e.workflowPickerOptions,availableTools:e.availableTools,ctl:t,host:S,h:$,edit:{open:!!k&&p===k.automation_id,on_change:A=>y(A&&k?k.automation_id:"")},workspaces:e.workspace_request?{request:e.workspace_request,connected:e.active,revisions:n.current}:void 0,browser:m?s.jsx(aS,{fetchGateway:e.gateway.fetch_gateway,runId:m,title:m===(k==null?void 0:k.automation_id)?"Automation files":"Run files",onClose:()=>h("")}):void 0})]})}function y3(e){return s.jsx(_o,{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 w3(e){return s.jsx("div",{className:`settings_choice ${e.checked?"on":""}`,children:s.jsx(_o,{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 v3="On: the schedule runs at its times. Off: suspended, scheduled runs are skipped until it is on again.";function x3(e){return s.jsx(_o,{variant:"sm",action:"schedule-active",className:"observe_schedule_switch",label:"Active",hint:v3,checked:e.active,unavailableReason:e.unavailableReason,busy:e.busy,onChange:e.onChange})}function b3(e){return s.jsx(_o,{variant:"sm",action:"mindmap-live",label:"Live",hint:"Refresh the map as new memory arrives.",checked:e.checked,onChange:e.onChange})}function k3(e){return s.jsx(_o,{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 Mb={framework:null,gateway:null,gatewayNote:"checking…"};function j3(){const e="0.8.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 S3(){return M2("abstractobserver",j3())}async function N3(e){let t;try{t=await e.gateway_about()}catch(n){return Ax(null,n instanceof Error?n.message||n.name:String(n))}return Ax(t)}class Tp{constructor(t){this._maxSize=Tp._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=Tp._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 $3(e){try{return new URL(String(e)),!0}catch{return!1}}function C3({baseUrl:e,endpoint:t}){const n=String(t||"api/gateway/host/metrics/gpu");return $3(n)?n:e&&String(e).trim()?new URL(n,String(e)).toString():n}async function E3({token:e,getToken:t}){if(typeof t=="function"){const n=await t();return n==null?"":String(n)}return e==null?"":String(e)}function A3({token:e}){const t=String(e||"").trim();return t?{Authorization:`Bearer ${t}`}:{}}function T3(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(a=>Number(a&&a.utilization_gpu_pct)).filter(a=>Number.isFinite(a));return r.length?r.reduce((a,u)=>a+u,0)/r.length:null}return null}async function M3({baseUrl:e,endpoint:t,token:n,getToken:r,signal:i,fetchImpl:a}={}){const u=C3({baseUrl:e,endpoint:t}),c=await E3({token:n,getToken:r}),d=a||globalThis.fetch;if(typeof d!="function")return{ok:!1,status:0,error:"fetch_unavailable",payload:null};let m;try{m=await d(u,{method:"GET",headers:{Accept:"application/json",...A3({token:c})},signal:i})}catch(p){return{ok:!1,status:0,error:"network_error",detail:p instanceof Error?p.message:String(p),payload:null}}let h=null;try{h=await m.json()}catch{h=null}return{ok:m.ok,status:m.status,error:m.ok?null:"http_error",payload:h}}const dm=Object.freeze({tickMs:1500,historySize:20,endpoint:"api/gateway/host/metrics/gpu",baseUrl:"",mode:"full"});function R3(e){return Number.isFinite(e)?Math.min(1,Math.max(0,e)):0}function Rb(e,t,n){return Number.isFinite(e)?Math.min(n,Math.max(t,e)):t}function Lb(e,t){const n=Number(e);return Number.isFinite(n)?Math.floor(n):t}function oy(e,t=1){const n=Rb(Number(e)/100,0,1),r=Math.round(140-140*n),i=Rb(Number(t),0,1);return i>=1?`hsl(${r} 85% 55%)`:`hsl(${r} 85% 55% / ${i})`}function Ib(e){const t={...dm,...e||{}};return t.tickMs=Math.max(250,Lb(t.tickMs,dm.tickMs)),t.historySize=Math.max(1,Math.min(200,Lb(t.historySize,dm.historySize))),t.endpoint=String(t.endpoint||dm.endpoint),t.baseUrl=String(t.baseUrl||""),t.mode=String(t.mode||dm.mode).trim().toLowerCase(),t.mode!=="icon"&&(t.mode="full"),t}function L3(){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 I3{constructor(t,n={}){if(!t||typeof t!="object")throw new TypeError("target element is required");this._target=t,this._opts=Ib(n),this._buffer=new Tp(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=L3();const r=document.createElement("div");r.className=this._opts.mode==="icon"?"wrap icon":"wrap";const i=document.createElement("div");i.className="top";const a=document.createElement("div");a.className="label",a.textContent="GPU";const u=document.createElement("div");u.className="value muted",u.textContent="—",i.appendChild(a),i.appendChild(u);const c=document.createElement("div");c.className="bars",r.appendChild(i),r.appendChild(c),t.appendChild(n),t.appendChild(r),this._els={wrap:r,value:u,bars:c},this._mounted=!0,this._rebuildBars(),this._render()}start(){this.mount(),!this._running&&(this._running=!0,this._timer_gen+=1,this._poll_loop(this._timer_gen))}stop(){this._running=!1,this._timer_gen+=1,this._timer&&(clearTimeout(this._timer),this._timer=null),this._resumeTimer&&(clearTimeout(this._resumeTimer),this._resumeTimer=null),this._abort&&(this._abort.abort(),this._abort=null)}destroy(){this.stop(),this._target&&this._mounted&&(this._target.textContent=""),this._mounted=!1,this._els=null}setOptions(t){const n=Ib({...this._opts,...t||{}}),r=n.historySize!==this._opts.historySize,i=n.tickMs!==this._opts.tickMs,a=n.mode!==this._opts.mode;this._opts=n,a&&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()),i&&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:i}=this._els,a=this._buffer.values(),u=this._buffer.last(),c=Number.isFinite(u)?Math.max(0,Math.min(100,u)):null;c==null?(r.textContent=t?"N/A":"—",r.classList.add("muted")):(r.textContent=`${c.toFixed(0)}%`,r.classList.remove("muted")),n&&(n.title=c==null?"GPU —":`GPU ${c.toFixed(0)}%`,c==null?(n.style.removeProperty("--monitor-gpu-accent"),n.style.removeProperty("--monitor-gpu-accent-glow")):(n.style.setProperty("--monitor-gpu-accent",oy(c,.95)),n.style.setProperty("--monitor-gpu-accent-glow",oy(c,.35))));const d=Array.from(i.children),m=Math.max(0,d.length-a.length),h=Math.max(2,i&&typeof i.clientHeight=="number"&&i.clientHeight>0?i.clientHeight:34);for(let p=0;p<d.length;p+=1){const y=d[p],w=p-m,x=w>=0?a[w]:null,k=Number.isFinite(x)?x:null,b=k==null?0:R3(k/100),S=Math.max(2,Math.min(h,Math.round(b*h)));y.style.height=`${S}px`,y.style.background=k==null?"":oy(k),y.className="bar",k==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 i=await M3({baseUrl:this._opts.baseUrl,endpoint:this._opts.endpoint,token:t,getToken:n,signal:this._abort.signal}),a=i&&i.payload,u=a&&typeof a=="object"?a.supported!==!1:!0,c=T3(a);if(!i.ok){if(this._buffer.push(null),this._render({error:!0}),i.status===401||i.status===403){const d=String(this._token||"").trim(),m=typeof this._getToken=="function";if(!r&&(!!d||m))return;this._stoppedForAuth=!0,this.stop()}else i.status===429&&(this.stop(),this._resumeTimer=setTimeout(()=>{this._resumeTimer=null,this._mounted&&this.start()},3e4));return}if(!u||c==null){this._buffer.push(null),this._render();return}this._buffer.push(c),this._render()}async _poll_loop(t){!this._running||t!==this._timer_gen||(await this._tick(),!(!this._running||t!==this._timer_gen)&&(this._timer=setTimeout(()=>{this._timer=null,this._poll_loop(t)},this._opts.tickMs)))}}function O3(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 i=this._shadow||this;this._controller=new I3(i,{}),this._upgradeProperty("token"),this._upgradeProperty("getToken"),this._upgradeProperty("mode")}_upgradeProperty(i){if(!Object.prototype.hasOwnProperty.call(this,i))return;const a=this[i];try{delete this[i]}catch{}this[i]=a}connectedCallback(){this._controller.setOptions(this._readAttrs());const i=()=>{this.isConnected&&this._controller.start()};typeof queueMicrotask=="function"?queueMicrotask(i):Promise.resolve().then(i)}disconnectedCallback(){this._controller.destroy()}attributeChangedCallback(){this._controller.setOptions(this._readAttrs())}_readAttrs(){const i=this.getAttribute("tick-ms"),a=this.getAttribute("history-size"),u=this.getAttribute("endpoint"),c=this.getAttribute("base-url"),d=this.getAttribute("mode");return{...i!=null?{tickMs:i}:{},...a!=null?{historySize:a}:{},...u!=null?{endpoint:u}:{},...c!=null?{baseUrl:c}:{},...d!=null?{mode:d}:{}}}set token(i){this._controller.token=i}get token(){return this._controller.token}set getToken(i){this._controller.getToken=i}get getToken(){return this._controller.getToken}set tickMs(i){this._controller.setOptions({tickMs:i})}get tickMs(){return this._controller.options.tickMs}set historySize(i){this._controller.setOptions({historySize:i})}get historySize(){return this._controller.options.historySize}set endpoint(i){this._controller.setOptions({endpoint:i})}get endpoint(){return this._controller.options.endpoint}set baseUrl(i){this._controller.setOptions({baseUrl:i})}get baseUrl(){return this._controller.options.baseUrl}set mode(i){this._controller.setOptions({mode:i})}get mode(){return this._controller.options.mode}}globalThis.customElements.define(e,n)}function Wd(e){return String(e||"").trim().toLowerCase()}function cg(e){return`${(e==null?void 0:e.filename)||""} ${(e==null?void 0:e.source_path)||""}`.trim().toLowerCase()}function Lm(e,t){return t.some(n=>e.endsWith(n))}function P3(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 D3(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 F3(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 zS(e,t){var u,c,d,m,h;const n=Wd(e==null?void 0:e.content_type),r=cg(e),i=[e==null?void 0:e.semantic_kind,e==null?void 0:e.render_kind,e==null?void 0:e.task,(u=e==null?void 0:e.tags)==null?void 0:u.semantic_kind,(c=e==null?void 0:e.tags)==null?void 0:c.render_kind,(d=e==null?void 0:e.tags)==null?void 0:d.task,(m=e==null?void 0:e.tags)==null?void 0:m.kind,(h=e==null?void 0:e.tags)==null?void 0:h.type].map(p=>String(p||"").trim().toLowerCase()).filter(Boolean).join(" ");if(/(^|[^a-z0-9])(code|source_code|script|program|executable)([^a-z0-9]|$)/i.test(i)||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")||Lm(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 a=String(t||"").replace(/\r\n/g,`
|
|
108
|
+
`).replace(/\r/g,`
|
|
109
|
+
`).split(`
|
|
110
|
+
`);return BS(a)}function z3(e){const n=String(e||"").replace(/\r\n/g,`
|
|
111
|
+
`).replace(/\r/g,`
|
|
112
|
+
`).split(`
|
|
113
|
+
`),r=n.findIndex(u=>/^Markdown Content:\s*$/i.test(u.trim()));if(r===-1)return null;const i=[];for(const u of n.slice(0,r)){const c=u.match(/^\s*([A-Za-z][A-Za-z0-9 /_-]{1,40}):\s*(.+?)\s*$/);c&&i.push({label:c[1].trim(),value:c[2].trim()})}const a=n.slice(r+1).join(`
|
|
114
|
+
`).trim();return!i.length&&!a?null:{metadata:i,body:a}}function B3(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(i=>i.split(n).length);if(r[0]>=3&&r.every(i=>Math.abs(i-r[0])<=1))return!0}return!1}function U3(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:BS(e)}function BS(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 W3(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 i=t.replace(/\r\n/g,`
|
|
115
|
+
`).replace(/\r/g,`
|
|
116
|
+
`).split(`
|
|
117
|
+
`).map(d=>d.trim()).filter(Boolean).slice(0,80);if(i.length<12)return!1;const a=i.filter(d=>d.length<=28).length,u=i.filter(d=>/^[,.;:()†]+$/.test(d)).length;return i.filter(d=>/^(abstract\.?|introduction|references|appendix|figure\s+\d+|table\s+\d+)\b/i.test(d)).length>=2&&(a/i.length>=.45||u>=2)}function q3(e,t){var m;const n=String(t||""),r=P3(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 i=n.replace(/\r\n/g,`
|
|
118
|
+
`).replace(/\r/g,`
|
|
119
|
+
`).split(`
|
|
120
|
+
`),a=i.map(h=>h.trim()).filter(Boolean);if(a.length<2||W3(n)||B3(i)||U3(i))return!1;const u=((m=n.match(/[A-Za-z][A-Za-z'-]+/g))==null?void 0:m.length)||0,c=i.filter(h=>!h.trim()).length,d=a.filter(h=>/[A-Za-z]{3,}/.test(h)&&h.length>=12).length;return u>=24&&d>=2&&(c>=1||a[0].length<=140)}function Im(e){const t=Wd(e==null?void 0:e.modality),n=Wd(e==null?void 0:e.content_type),r=cg(e),i=D3(e);return t==="image"||n.startsWith("image/")||Lm(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(i)||Lm(r,[".wav",".mp3",".m4a",".aac",".flac",".ogg",".opus",".aiff",".mid",".midi"])?"audio":t==="video"||n.startsWith("video/")||Lm(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")||zS(e,"")?"text":"binary"}function Mp(e,t){const n=Wd(e==null?void 0:e.content_type),r=cg(e),i=String(t||"").trim();return n.includes("html")||r.endsWith(".html")||r.endsWith(".htm")||F3(t)?"html":zS(e,t)?"code":n.includes("markdown")||r.endsWith(".md")||r.endsWith(".markdown")?"markdown":n.includes("json")||r.endsWith(".json")||r.endsWith(".jsonl")||(i.startsWith("{")||i.startsWith("["))&&og(i)!==null?"json":q3(e,t)?"markdown":"text"}function Cv(e,t=""){const n=Im(e);if(n==="image"||n==="video")return n;if(n==="audio"){const r=(e==null?void 0:e.tags)||{},i=[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(a=>String(a||"").trim().toLowerCase()).filter(Boolean).join(" ");return/(^|[^a-z0-9])(voice|tts|speech)([^a-z0-9]|$)/i.test(i)?"voice":/(^|[^a-z0-9])(music|song|instrumental|t2m)([^a-z0-9]|$)/i.test(i)?"music":/(^|[^a-z0-9])(sound|sfx|recording)([^a-z0-9]|$)/i.test(i)?"sound":"audio"}if(n==="binary"){const r=Wd(e==null?void 0:e.modality),i=Wd(e==null?void 0:e.content_type),a=cg(e);return r==="document"||i.includes("pdf")||Lm(a,[".pdf",".doc",".docx",".ppt",".pptx",".xls",".xlsx"])?"document":"other"}return Mp(e,t)}function ay(e){var m,h;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],i=[];let a=0,u="";const c=p=>" ".repeat(Math.max(0,p)),d=(p,y)=>{const w=p.match(/^(<\/?|<!)([^\s/>]+)([\s\S]*?)(\/?>)$/);if(!w||p.length<=120||p.startsWith("</")||p.startsWith("<!"))return[`${c(y)}${p.trim()}`];const x=(w[3]||"").trim();if(!x)return[`${c(y)}${p.trim()}`];const k=x.match(/[^\s="'<>`]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'<>`]+))?/g)||[x];return[`${c(y)}${w[1]}${w[2]}`,...k.map(b=>`${c(y+1)}${b.trim()}`),`${c(y)}${w[4]}`]};for(const p of r){const y=String(p||"");if(!y.trim())continue;const w=y.trim().toLowerCase();if(w.startsWith("</")){const k=((m=w.match(/^<\/\s*([a-z0-9:-]+)/))==null?void 0:m[1])||"";u&&k===u&&(u=""),a=Math.max(0,a-1),i.push(`${c(a)}${y.trim()}`);continue}if(y.trimStart().startsWith("<")){i.push(...d(y,a));const k=((h=w.match(/^<\s*([a-z0-9:-]+)/))==null?void 0:h[1])||"";/\/>\s*$/.test(y)||w.startsWith("<!")||n.has(k)||(a+=1,(k==="script"||k==="style")&&(u=k));continue}if(u){const k=y.trim();k&&i.push(...k.split(`
|
|
123
|
+
`).map(b=>`${c(a)}${b.trimEnd()}`));continue}const x=y.replace(/\s+/g," ").trim();x&&i.push(`${c(a)}${x}`)}return i.join(`
|
|
124
|
+
`)}const H3=/^\s*<runtime_metadata>\s*([\s\S]*?)\s*<\/runtime_metadata>\s*/i;function Ev(e){const t=typeof e=="string"?e:String(e??""),n=H3.exec(t);if(!n)return{text:t.trim(),metadata:null,stripped:!1};let r=null;try{const i=JSON.parse(String(n[1]||"").trim());i&&typeof i=="object"&&!Array.isArray(i)&&(r=i)}catch{r=null}return{text:t.slice(n[0].length).trim(),metadata:r,stripped:!0}}function US(...e){const t={};for(const n of e)if(!(!n||typeof n!="object"||Array.isArray(n)))for(const[r,i]of Object.entries(n))i==null||String(i).trim()===""||(t[r]=i);return Object.keys(t).length?t:null}function yw(e){if(e==null)return"";if(typeof e=="string")return e.trim();if(Array.isArray(e))return e.map(t=>yw(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=yw(t);if(n)return n}}return""}function WS(e){const t=Ev(yw(e));return{text:t.text,runtime_metadata:t.metadata}}function V3(e){var r,i;if(!e)return{text:"",runtime_metadata:null};const t=typeof e.prompt=="string"?String(e.prompt).trim():"";if(t){const a=Ev(t);return{text:a.text,runtime_metadata:a.metadata}}const n=[(r=e.context)==null?void 0:r.messages,e.messages,e.conversation,e.history].filter(Array.isArray);for(const a of n)for(let u=a.length-1;u>=0;u-=1){const c=a[u],d=String((c==null?void 0:c.role)||(c==null?void 0:c.speaker)||"").trim().toLowerCase();if(d&&d!=="user"&&d!=="human")continue;const m=WS((c==null?void 0:c.content)??(c==null?void 0:c.text)??c);if(m.text)return{text:m.text,runtime_metadata:US(m.runtime_metadata,c!=null&&c.runtime_metadata&&typeof c.runtime_metadata=="object"?c.runtime_metadata:null,(i=c==null?void 0:c.metadata)!=null&&i.runtime_metadata&&typeof c.metadata.runtime_metadata=="object"?c.metadata.runtime_metadata:null)}}return{text:"",runtime_metadata:null}}function G3(e,t=6){var a,u;if(!e)return[];const r=[(a=e.context)==null?void 0:a.messages,e.messages,e.conversation,e.history].filter(Array.isArray).find(c=>c.length)||[],i=[];for(const c of r){const d=String((c==null?void 0:c.role)||(c==null?void 0:c.speaker)||(c==null?void 0:c.author)||"").trim().toLowerCase()||"message",m=WS((c==null?void 0:c.content)??(c==null?void 0:c.text)??(c==null?void 0:c.message)??c),h=m.text;if(!h)continue;const p=String((c==null?void 0:c.ts)||(c==null?void 0:c.timestamp)||(c==null?void 0:c.created_at)||(c==null?void 0:c.time)||"").trim(),y=US(m.runtime_metadata,c!=null&&c.runtime_metadata&&typeof c.runtime_metadata=="object"?c.runtime_metadata:null,(u=c==null?void 0:c.metadata)!=null&&u.runtime_metadata&&typeof c.metadata.runtime_metadata=="object"?c.metadata.runtime_metadata:null);i.push({role:d,text:h,ts:p,runtime_metadata:y})}return i.slice(Math.max(0,i.length-Math.max(1,t)))}function qS(e){const t=String(e||"").trim().toLowerCase().replace(/\s+/g," ");return t==="please respond:"||t==="please respond"||t==="type response..."||t==="type response"}function K3(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 HS="inferred from the call's arguments (regex heuristic) — not a declared risk tier; declared tiers replace this when the grant API ships";function VS(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(),i=[];return(t.includes("execute_command")||t.includes("terminal")||r)&&i.push("Shell"),/[;&|]?\s*(rm|rmdir|mv|chmod|chown|sudo)\b/.test(r)&&i.push("Destructive risk"),/(^|\s)(curl|wget|scp|ssh|nc|ncat|ftp)\b/.test(r)&&i.push("Network"),/(^|\s)(cat|sed|rg|grep|ls|find|pwd)\b/.test(r)&&!/[>|]\s*\S/.test(r)&&i.push("Read path"),/[>|]\s*\S|(^|\s)(tee|touch|mkdir|cp)\b/.test(r)&&i.push("Filesystem write"),i.length||i.push("Tool call"),Array.from(new Set(i)).slice(0,4)}function Av(e,t){const n=String((e==null?void 0:e.reason)||"").trim().toLowerCase(),r=K3(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 GS(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 KS(e,t){const n=String((e==null?void 0:e.prompt)||"").trim(),r=Ev(n),i=V3(t);return r.text&&!qS(r.text)?{text:r.text,runtime_metadata:r.metadata}:i.text?i:{text:r.text||n,runtime_metadata:r.metadata}}function J3(e,t){return KS(e,t).text}function Y3(e,t){return e||String(t||"").trim()||{}}function Uo(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 ou(e){const t=String(e.status||"unknown").trim()||"unknown";return s.jsx("span",{className:`run_status_pill ${_a(t)}`,children:t})}function X3(e){var a;const t=String((e==null?void 0:e.status)||"").trim().toLowerCase();if(ds(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(),i=Array.isArray((a=n==null?void 0:n.details)==null?void 0:a.tool_calls)?n.details.tool_calls:[];return i.length?Av(n,i):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 Wm(e){const t=e==null?void 0:e.error;return t?typeof t=="string"?Wt(t,{max_chars:220,max_lines:2}):Wt(Br(t,400),{max_chars:220,max_lines:2}):""}function Z3(e){const t=X3(e);if(t)return t;const n=Wm(e);if(n)return n;const r=String((e==null?void 0:e.current_node)||"").trim();if(r)return`Current node: ${r}`;const i=String((e==null?void 0:e.status)||"").trim().toLowerCase();return i==="running"?"Running":ds(i)?"Terminal":"No current activity reported"}function JS(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 Ob(e){const t=JS(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:{},i=Pn(e==null?void 0:e.modality,t==null?void 0:t.modality,n==null?void 0:n.modality,r.modality).toLowerCase();if(i)return i;const a=Pn(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 a.startsWith("image/")?"image":a.startsWith("audio/")?"audio":a.startsWith("video/")?"video":a.includes("pdf")?"document":a.startsWith("text/")||a.includes("json")||a.includes("markdown")||a.includes("csv")?"text":"artifact"}function Q3(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 eI(e,t){if(!e||typeof e!="object")return null;const n=Q3(e),r=JS(e),i=e!=null&&e.metadata&&typeof e.metadata=="object"?e.metadata:e!=null&&e.meta&&typeof e.meta=="object"?e.meta:{},a=n!=null&&n.descriptor&&typeof n.descriptor=="object"?n.descriptor:e!=null&&e.descriptor&&typeof e.descriptor=="object"?e.descriptor:{},u=Pn(n.artifact_id,e.artifact_id,e.$artifact,e.id,r.artifact_id,r.$artifact,r.id,i.artifact_id,i.$artifact);if(!u)return null;const c={...r.tags&&typeof r.tags=="object"?r.tags:{},...i.tags&&typeof i.tags=="object"?i.tags:{},...n.tags&&typeof n.tags=="object"?n.tags:{},...e.tags&&typeof e.tags=="object"?e.tags:{}},d={};for(const[E,z]of Object.entries(c)){const F=String(E||"").trim();F&&(d[F]=String(z??""))}const m=Pn(n.filename,e.filename,r.filename,i.filename,d.filename,d.name,e.name,r.name),h=Pn(n.source_path,e.source_path,r.source_path,i.source_path,e.path,r.path,d.path,d.source_path,d.file_path),p=Pn(n.content_type,e.content_type,e.mime_type,e.mime,r.content_type,r.mime_type,r.mime,i.content_type,d.content_type),y=Pn(n.render_kind,a.render_kind,e.render_kind,d.render_kind),w=Pn(n.semantic_kind,a.semantic_kind,e.semantic_kind,d.semantic_kind,d.artifact_type),x=n.access&&typeof n.access=="object"?n.access:e.access&&typeof e.access=="object"?e.access:{},k=n.producer&&typeof n.producer=="object"?n.producer:e.producer&&typeof e.producer=="object"?e.producer:a.producer&&typeof a.producer=="object"?a.producer:{},b=n.provenance&&typeof n.provenance=="object"?n.provenance:e.provenance&&typeof e.provenance=="object"?e.provenance:a.provenance&&typeof a.provenance=="object"?a.provenance:{},S=n.generation&&typeof n.generation=="object"?n.generation:e.generation&&typeof e.generation=="object"?e.generation:a.generation&&typeof a.generation=="object"?a.generation:{},$=n.media&&typeof n.media=="object"?n.media:e.media&&typeof e.media=="object"?e.media:a.media&&typeof a.media=="object"?a.media:{},A=n.links&&typeof n.links=="object"?n.links:e.links&&typeof e.links=="object"?e.links:a.links&&typeof a.links=="object"?a.links:{};return{artifact_id:u,run_id:Pn(n.run_id,e.run_id,r.run_id,i.run_id,d.run_id,b.run_id),content_type:p,modality:Pn(n.modality,e.modality,a.modality,d.modality)||Ob({...e,ref:r,metadata:i,tags:d}),semantic_kind:w||Ob({...e,ref:r,metadata:i,tags:d}),render_kind:y||Cv({content_type:p,filename:m,source_path:h,modality:Pn(n.modality,e.modality,d.modality),tags:d}),task:Pn(n.task,a.task,e.task,d.task,d.provider_task),classification_source:Pn(n.classification_source,a.classification_source,e.classification_source),session_id:Pn(n.session_id,a.session_id,e.session_id,d.session_id),workflow_id:Pn(n.workflow_id,a.workflow_id,e.workflow_id,d.workflow_id,d.workflow),node_id:Pn(n.node_id,a.node_id,e.node_id,d.node_id,d.node),step_id:Pn(n.step_id,a.step_id,e.step_id,d.step_id),effect_id:Pn(n.effect_id,a.effect_id,e.effect_id,d.effect_id,d.effect_idempotency_key),turn_id:Pn(n.turn_id,a.turn_id,e.turn_id,d.turn_id,d.turn),ledger_cursor:Pn(n.ledger_cursor,a.ledger_cursor,e.ledger_cursor,d.ledger_cursor,d.step_cursor),parent_run_id:Pn(n.parent_run_id,a.parent_run_id,e.parent_run_id,d.parent_run_id),actor_id:Pn(n.actor_id,a.actor_id,e.actor_id,d.actor_id),title:Pn(n.title,e.title,d.title,d.label,d.name),created_at:Pn(n.created_at,e.created_at,r.created_at,i.created_at,d.created_at),size_bytes:MR(n.size_bytes,e.size_bytes,r.size_bytes,i.size_bytes,d.size_bytes),filename:m,source_path:h,sha256:Pn(n.sha256,e.sha256,r.sha256,i.sha256,d.sha256),tags:d,producer:k,provenance:b,generation:S,media:$,source_refs:Array.isArray(n.source_refs)?n.source_refs:Array.isArray(e.source_refs)?e.source_refs:[],access:x,links:A,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(Pn(n.classification_source,a.classification_source,e.classification_source))),descriptor:a,source:t,raw:e}}function Rp(e){return e.filename||e.title||(e.source_path?e.source_path.split("/").filter(Boolean).slice(-1)[0]:"")||jn(e.artifact_id,16)}function tI(e,t){if(t==="type")return Pd(e);if(t==="run")return e.run_id||"(no run)";if(t==="turn")return ww(e);if(t==="node")return Od(e)||"(node unknown)";if(t==="workflow")return Tv(e)||"(workflow unknown)";if(t==="location"){const i=(e.source_path||e.filename||"").split("/").filter(Boolean);return i.length>1?i.slice(0,-1).join("/"):"(root)"}if(t==="source")return qm(e)||e.source||"artifact";const n=It(e.created_at);return n===null?"(unknown time)":new Date(n).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}function Tv(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 Od(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 i=String((e==null?void 0:e.source_path)||t.path||"").trim().match(/(?:^|[._:/-])(node-[A-Za-z0-9_-]+)/);return i!=null&&i[1]?String(i[1]):""}function ww(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=Od(e),i=It(e==null?void 0:e.created_at),a=i===null?"unknown time":new Date(i).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}),u=e!=null&&e.run_id?jn(String(e.run_id),10):"unknown run";return r?`${u} · ${r} · ${a}`:`${u} · ${a}`}function Pb(e){if(!e)return"provenance unavailable";const t=[],n=Tv(e),r=Od(e),i=qm(e),a=YS(e);return n&&t.push(n),r&&t.push(r),i&&t.push(i),a&&t.push(a),t.length?t.join(" · "):"provenance unavailable"}function Vc(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 i=r===0?0:n>=10?1:2;return`${n.toFixed(i)} ${t[r]}`}function Pd(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,a=>a.toUpperCase())}function nI(e){return e==="html"?"HTML":e==="json"?"JSON":e==="audio"?"Unclassified audio":e==="code"?"Code":e.slice(0,1).toUpperCase()+e.slice(1)}function sI(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 rI(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 Db(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 iI(e){const t=Bd(e.created_at),n=Xc(e.created_at);return t==="—"?"Created —":`${t}${n&&n!=="—"?` (${n})`:""}`}function Fb(e){var i;const t=e.tags||{},n=String(((i=e.access)==null?void 0:i.last_accessed_at)||t.last_accessed_at||t.accessed_at||t.updated_at||e.created_at||"").trim(),r=Bd(n);return r==="—"?"—":r}function zb(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 i=qm(e),a=Pd(e);return i?`${a} ${i}`:`${a} artifact`}function qm(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 YS(e){var r,i,a,u,c,d,m,h;if(!e)return"";const t=Pn((r=e.producer)==null?void 0:r.provider,(i=e.producer)==null?void 0:i.provider_id,(a=e.provenance)==null?void 0:a.provider,(u=e.generation)==null?void 0:u.provider),n=Pn((c=e.producer)==null?void 0:c.model,(d=e.producer)==null?void 0:d.model_id,(m=e.provenance)==null?void 0:m.model,(h=e.generation)==null?void 0:h.model);return t&&n?`${t} / ${n}`:t||n}function oI(e){var t,n,r,i;return e?Pn((t=e.generation)==null?void 0:t.prompt,(n=e.generation)==null?void 0:n.input,(r=e.generation)==null?void 0:r.text,(i=e.provenance)==null?void 0:i.prompt):""}function Bb(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),i=Number(t.height??t.image_height??t.video_height),a=Number(t.sample_rate??t.sample_rate_hz),u=Number(t.channels);if(Number.isFinite(n)&&n>0){const d=[`${n>=60?`${Math.floor(n/60)}m ${Math.round(n%60)}s`:`${n.toFixed(n>=10?1:2)}s`}`];return Number.isFinite(a)&&a>0&&d.push(`${Math.round(a/1e3)} kHz`),Number.isFinite(u)&&u>0&&d.push(`${u} ch`),d.join(" · ")}if(Number.isFinite(r)&&Number.isFinite(i)&&r>0&&i>0)return`${Math.round(r)} x ${Math.round(i)}`;const c=Number(t.page_count??t.pages);return Number.isFinite(c)&&c>0?`${Math.round(c)} pages`:""}function Ub(e){return e.source_path||e.filename||""}function Lp(e,t,n){const r=e.run_id&&t[e.run_id]||null;if(!r)return e;const i=Uo(r,n),a={...e.tags||{}};return i&&!a.workflow&&(a.workflow=i),i&&!a.workflow_id&&(a.workflow_id=i),{...e,workflow_id:e.workflow_id||i,tags:a}}function vw(e,t,n,r=""){const i=Lp(e,t,n),a=Cv(i,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"}[a]||Pd(i)}function Wa(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 W_(e){var a,u,c;const t=e,n=t==null?void 0:t.effect;if(!n||typeof n!="object"||String(n.type||"")!=="emit_event")return null;const r=String(((a=n==null?void 0:n.payload)==null?void 0:a.name)||((u=n==null?void 0:n.payload)==null?void 0:u.event_name)||"").trim();if(!r)return null;const i=(c=n==null?void 0:n.payload)==null?void 0:c.payload;return{name:r,payload:i}}function Zd(e){const t=e,n=t==null?void 0:t.details;if(!n||typeof n!="object")return[];if(Array.isArray(n))return n.filter(i=>i&&typeof i=="object"&&typeof i.name=="string");const r=n==null?void 0:n.tool_calls;return Array.isArray(r)?r:[]}function aI(e){var i,a;const t=String((e==null?void 0:e.status)||"").trim(),n=String(((i=e==null?void 0:e.effect)==null?void 0:i.type)||"").trim(),r=(a=e==null?void 0:e.effect)!=null&&a.payload&&typeof e.effect.payload=="object"?String(e.effect.payload.name||"").trim():"";return n==="emit_event"&&r?r:n||t||"record"}function XS(e){if(!e||typeof e!="object")return"Ledger record";const t=String(e.node_id||"").trim(),n=String(e.status||"").trim(),r=aI(e),i=Wa(e);if(i){const a=String(i.reason||"").trim();if(String(i.prompt||"").trim())return`${t||"node"} is waiting for a response`;if(a)return`${t||"node"} is waiting (${a})`}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 gd(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):Br(e,320),n=typeof e.duration=="number"?Number(e.duration):-1;return{text:t,duration:n}}return{text:Br(e,320),duration:-1}}function ZS(e){var u,c,d,m,h,p,y,w,x;if(!e||typeof e!="object")return"";const t=String(((u=e==null?void 0:e.effect)==null?void 0:u.type)||"").trim(),n=e==null?void 0:e.result,r=k=>typeof k=="string"?k.trim():k==null?"":typeof k=="number"||typeof k=="boolean"?String(k):"",i=k=>{if(!k||typeof k!="object")return"";const b=k,S=[b.response,b.answer,b.message,b.text,b.content];for(const $ of S){const A=r($);if(A)return A}return""};if(t==="answer_user"){const k=r(n==null?void 0:n.message)||r((c=n==null?void 0:n.output)==null?void 0:c.message)||r((d=n==null?void 0:n.output)==null?void 0:d.response)||r((h=(m=e==null?void 0:e.effect)==null?void 0:m.payload)==null?void 0:h.message)||r((y=(p=e==null?void 0:e.effect)==null?void 0:p.payload)==null?void 0:y.text)||r((x=(w=e==null?void 0:e.effect)==null?void 0:w.payload)==null?void 0:x.content);if(k)return k}if(t==="llm_call"){const k=i(n)||r(n==null?void 0:n.output)||i(n==null?void 0:n.output)||r(n==null?void 0:n.response);if(k)return k}return r(n==null?void 0:n.output)||i(n==null?void 0:n.output)||i(n)||r(n==null?void 0:n.response)}function dp(e){var i;const t=String((e==null?void 0:e.node_id)||""),n=String((e==null?void 0:e.status)||""),r=String(((i=e==null?void 0:e.effect)==null?void 0:i.type)||"");return`${t||"(node?)"} • ${n||"(status?)"} • ${r||"(effect?)"}`}function lI(e){return!!(e&&String(e.status||"")==="waiting")}function cI(e){var n,r;const t=[];for(const i of e||[]){const a=i.record;if(String(((n=a==null?void 0:a.effect)==null?void 0:n.type)||"").trim()!=="llm_call")continue;const c=(r=a==null?void 0:a.effect)!=null&&r.payload&&typeof a.effect.payload=="object"?a.effect.payload:{},d=a!=null&&a.result&&typeof a.result=="object"?a.result:{},m=(d==null?void 0:d.usage)||(d==null?void 0:d.token_usage)||{},h=typeof c.prompt=="string"?c.prompt:Array.isArray(c.messages)?Br(c.messages,1800):"",p=typeof d.content=="string"?d.content:typeof d.response=="string"?d.response:typeof a.result=="string"?String(a.result):"",y=It(a.started_at),w=It(a.ended_at),x=Number(m.prompt_tokens??m.input_tokens??0)||0,k=Number(m.completion_tokens??m.output_tokens??0)||0;t.push({id:`${String(i.run_id||a.run_id||"")}:${i.cursor}`,cursor:Number(i.cursor||0),ts:String(a.ended_at||a.started_at||""),run_id:String(i.run_id||a.run_id||"").trim(),node_id:String(a.node_id||"").trim(),provider:String(c.provider||d.provider||d.runtime_provider||"").trim(),model:String(c.model||d.model||d.runtime_model||"").trim(),prompt_preview:Wt(h,{max_chars:1200,max_lines:10}),response_preview:Wt(p,{max_chars:1200,max_lines:10}),missing_response:!String(p||"").trim(),tokens:{prompt:x,completion:k,total:Number(m.total_tokens??x+k)||0},duration_ms:y!==null&&w!==null?Math.max(0,w-y):typeof d.gen_time=="number"?Number(d.gen_time)*1e3:null,status:String(a.status||"").trim(),error:a.error?Br(a.error,500):"",raw:a})}return t.sort((i,a)=>(It(a.ts)??0)-(It(i.ts)??0))}function Wb(e){const t=e.size||18,n=Im(e.artifact),r=Cv(e.artifact,""),i=`artifact_glyph ${r==="code"?"code":n}`,a={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:i,children:s.jsxs("svg",{...a,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:i,children:s.jsxs("svg",{...a,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:i,children:s.jsxs("svg",{...a,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:i,children:s.jsxs("svg",{...a,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:i,children:s.jsxs("svg",{...a,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:i,children:s.jsxs("svg",{...a,children:[s.jsx("path",{d:"M7 3h7l5 5v13H7z"}),s.jsx("path",{d:"M14 3v6h6"}),s.jsx("path",{d:"M9 14h8"})]})})}const uI=2,dI=Number.MAX_SAFE_INTEGER;function fI(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 mI(e){const t=String(e||"");if(typeof DOMParser>"u")return[{kind:"text",text:ay(t)||t}];try{const n=new DOMParser().parseFromString(t,"text/html"),r=[];n.doctype&&r.push({kind:"doctype",name:n.doctype.name||"html"});const i=a=>{if(a.nodeType===Node.TEXT_NODE){const u=String(a.textContent||"").trim();return u?{kind:"text",text:u}:null}if(a.nodeType===Node.COMMENT_NODE)return{kind:"comment",text:String(a.textContent||"")};if(a.nodeType===Node.ELEMENT_NODE){const u=a,c=Array.from(u.attributes||[]).map(m=>({name:m.name,value:m.value})),d=Array.from(u.childNodes||[]).map(i).filter(Boolean);return{kind:"element",tag:u.tagName.toLowerCase(),attrs:c,children:d}}return null};if(n.documentElement){const a=i(n.documentElement);a&&r.push(a)}return r.length?r:[{kind:"text",text:ay(t)||t}]}catch{return[{kind:"text",text:ay(t)||t}]}}function ly(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(Ne.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 QS(e){const t=e.node,n=e.depth*14,r=e.depth<e.collapseAfterDepth,[i,a]=_.useState(r);if(_.useEffect(()=>{a(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(ly,{tag:t.tag,attrs:t.attrs,selfClosing:!0})});const u=t.children.find(c=>c.kind==="text");return s.jsxs("details",{className:"html-tree__details",open:i,onToggle:c=>a(c.currentTarget.open),children:[s.jsxs("summary",{className:"html-tree__summary",style:{paddingLeft:n},children:[s.jsx("span",{className:"html-tree__caret","aria-hidden":"true",children:i?"▾":"▸"}),s.jsx(ly,{tag:t.tag,attrs:t.attrs}),!i&&u?s.jsxs("span",{className:"html-tree__summary_text",children:[" ",fI(u.text)]}):null]}),i?s.jsxs("div",{className:"html-tree__children",children:[t.children.map((c,d)=>s.jsx(QS,{node:c,depth:e.depth+1,collapseAfterDepth:e.collapseAfterDepth,expansionMode:e.expansionMode,expansionVersion:e.expansionVersion},`${e.depth}:${t.kind}:${t.tag}:${d}`)),s.jsx("div",{className:"html-tree__line",style:{paddingLeft:n},children:s.jsx(ly,{tag:t.tag,attrs:[],closing:!0})})]}):null]})}function hI(e){const t=_.useMemo(()=>mI(e.text),[e.text]),[n,r]=_.useState({mode:"folded",version:0}),i=n.mode==="unfolded"?dI:uI;_.useEffect(()=>{r(u=>({mode:"folded",version:u.version+1}))},[e.text]);const a=()=>{r(u=>({mode:u.mode==="unfolded"?"folded":"unfolded",version:u.version+1}))};return s.jsxs("div",{className:`${e.className} structured html_source_preview`,children:[s.jsx("div",{className:"html-tree__toolbar",children:s.jsx("button",{type:"button",className:"btn html-tree__toggle",onClick:a,"aria-expanded":n.mode==="unfolded",children:n.mode==="unfolded"?"Fold all":"Unfold all"})}),s.jsx("div",{className:"html-tree__tree",role:"tree","aria-label":"HTML source tree",children:t.map((u,c)=>s.jsx(QS,{node:u,depth:0,collapseAfterDepth:i,expansionMode:n.mode,expansionVersion:n.version},`root:${c}`))})]})}function _I(e){var r;const t=z3(e.text);if(!t)return s.jsx("div",{className:`${e.className} structured markdown_preview`,children:s.jsx(xi,{text:e.text})});const n=((r=t.metadata.find(i=>i.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(i=>{const a=/^https?:\/\//i.test(i.value);return s.jsxs("div",{children:[s.jsx("dt",{children:i.label}),s.jsx("dd",{children:a?s.jsx("a",{href:i.value,target:"_blank",rel:"noreferrer",children:i.value}):i.value})]},`${i.label}:${i.value}`)})}):null,s.jsx(xi,{text:t.body||e.text})]})}function eN(e){const t=String(e.text||""),n=Mp(e.artifact,t);if(n==="json"){const r=og(t);if(r!==null)return s.jsx("div",{className:`${e.className} structured`,children:s.jsx(mr,{value:r,collapseAfterDepth:4,showCopy:!1})})}return n==="markdown"?s.jsx(_I,{text:t,className:e.className}):n==="html"?s.jsx(hI,{text:t,className:e.className}):s.jsx("pre",{className:`mono ${e.className}`,children:t})}function pI(e){const t=e.preview,n=e.artifact;return n?t.loading?s.jsx("div",{className:"runtime_inline_preview empty",children:"Loading preview…"}):t.error?s.jsx("div",{className:"runtime_inline_preview empty danger",children:t.error}):t.kind==="image"&&t.url?s.jsx("img",{className:"runtime_inline_preview media",src:t.url,alt:Rp(n)}):t.kind==="audio"&&t.url?s.jsx(rg,{className:"runtime_inline_preview audio",src:t.url,name:Rp(n)}):t.kind==="video"&&t.url?s.jsx("video",{className:"runtime_inline_preview media",src:t.url,controls:!0}):s.jsx(eN,{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 Mv(e){const t=e==null?void 0:e.waiting;return t&&typeof t=="object"?t:null}function tN(e){const t=Mv(e);return String((t==null?void 0:t.reason)||(e==null?void 0:e.waiting_reason)||"").trim().toLowerCase()}function qb(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 gI(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 Rv(e){const t=String((e==null?void 0:e.status)||"").trim().toLowerCase();if(ds(t)||t!=="waiting")return"none";const n=Mv(e),r=tN(e);return Zd(n).length?"tool_approval":r==="until"||String((e==null?void 0:e.role)||"").trim()==="controller"?"scheduled":r==="subworkflow"?"subworkflow":r==="event"?qb(n)?"user_response":"external_event":r==="user"||qb(n)?"user_response":"unknown_wait"}function yI(e){const t=Mv(e),n=Zd(t),r=Rv(e);return r==="tool_approval"?`Tool approval: ${gI(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 wI(e){const t=Rv(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.":ds(n)?"Open the ledger and artifacts for the final outcome.":"Open the run to inspect current activity."}function Hb(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 vI(e,t={}){const n=t.now_ms??Date.now(),r=t.workflow_label??"",i=String(e.status||"unknown").trim().toLowerCase()||"unknown",a=Rv(e),u=ds(i),c=mh(e,n),d=It(e.updated_at||e.created_at)??0,m=i==="running"&&c>=14400*1e3,h=yI(e)||Hb(e)||(e.current_node?`Current node: ${e.current_node}`:i==="running"?"Running":u?"Terminal":"No current activity reported");let p="all";a==="tool_approval"?p="tool_approval":a==="user_response"?p="user_wait":a==="scheduled"?p="scheduled":a==="subworkflow"||a==="external_event"?p="subflows":i==="failed"?p="failed":i==="running"?p="running":u&&(p="finished");const y=a==="tool_approval"?0:a==="user_response"?1:a==="unknown_wait"?2:i==="failed"?3:m?4:i==="running"?5:a!=="none"?6:u?8:7,w=a==="tool_approval"||a==="user_response",x=a==="tool_approval"?"Open approval":a==="user_response"?"Open wait":"Open Observe",k=[e.run_id,e.workflow_id,r,e.session_id,e.parent_run_id,e.status,e.current_node,tN(e),h,Hb(e)].join(" ").toLowerCase();return{run:e,run_id:String(e.run_id||"").trim(),status:i,wait_kind:a,queue:p,attention_rank:y,reason:h,expected_action:wI(e),action_label:x,search_text:k,is_terminal:u,needs_user_action:w,is_stale:m,duration_ms:c,updated_ms:d}}function xI(e,t={}){const n=t.now_ms??Date.now(),r=t.workflow_label_by_id??{};return e.map(i=>vI(i,{now_ms:n,workflow_label:r[String(i.workflow_id||"")]||String(i.workflow_id||"")}))}function bI(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 kI(e,t){const n=t.queue,i=(t.query??"").trim().toLowerCase();return e.filter(a=>{if(n==="attention"){if(!(a.needs_user_action||a.status==="failed"||a.is_stale||a.wait_kind==="unknown_wait"))return!1}else if(n!=="all"&&a.queue!==n)return!1;return!i||a.search_text.includes(i)})}function jI(e,t){const n=[...e];return n.sort((r,i)=>{if(t==="recent")return i.updated_ms-r.updated_ms;if(t==="oldest")return r.updated_ms-i.updated_ms;if(t==="duration")return i.duration_ms-r.duration_ms;if(t==="tokens")return(Number(i.run.tokens_total||0)||0)-(Number(r.run.tokens_total||0)||0);if(t==="workflow")return String(r.run.workflow_id||"").localeCompare(String(i.run.workflow_id||""));const a=r.attention_rank-i.attention_rank;return a!==0?a:i.updated_ms-r.updated_ms}),n}function SI(e){const[t,n]=_.useState("attention"),[r,i]=Ep("system_queues"),[a,u]=Ep("system_runs"),[c,d]=_.useState(""),[m,h]=_.useState("attention"),[p,y]=_.useState(""),w=_.useMemo(()=>{const L={};for(const te of e.artifacts){const X=String(te.run_id||"").trim();X&&(L[X]=(L[X]||0)+1)}return L},[e.artifacts]),x=_.useMemo(()=>xI(e.runs,{workflow_label_by_id:e.workflow_label_by_id}),[e.runs,e.workflow_label_by_id]),k=_.useMemo(()=>bI(x),[x]),b=_.useMemo(()=>{const L=kI(x,{queue:t,query:c});return jI(L,m)},[x,t,c,m]),S=b.find(L=>String(L.run_id||"")===p)||b.find(L=>String(L.run_id||"")===e.selected_run_id)||b[0]||null,$=(S==null?void 0:S.run)||null,A=String(($==null?void 0:$.run_id)||"").trim(),E=String(($==null?void 0:$.session_id)||"").trim(),z=_.useMemo(()=>E?new Set(e.runs.filter(L=>String(L.session_id||"").trim()===E).map(L=>String(L.run_id||"").trim()).filter(Boolean)):new Set,[e.runs,E]),F=E?z.size:0,M=_.useMemo(()=>E?e.artifacts.filter(L=>String(L.session_id||"").trim()===E||z.has(String(L.run_id||"").trim())).length:0,[e.artifacts,E,z]),D=$!=null&&$.waiting&&typeof $.waiting=="object"?$.waiting:null,H=D?Zd(D):[],q=(S==null?void 0:S.reason)||(D?Av(D,H):""),I=(S==null?void 0:S.expected_action)||(D?GS(D,H):""),Z=D?J3(D,null):"",R=A&&w[A]||0,T=ds($==null?void 0:$.status),P=[{key:"attention",label:"Needs attention",count:k.attention},{key:"user_wait",label:"Needs my response",count:k.user_wait},{key:"tool_approval",label:"Tool approvals",count:k.tool_approval},{key:"running",label:"Running",count:k.running},{key:"failed",label:"Failed",count:k.failed},{key:"scheduled",label:"Scheduled",count:k.scheduled},{key:"subflows",label:"Subflows / external events",count:k.subflows},{key:"finished",label:"Finished",count:k.finished},{key:"all",label:"All loaded",count:k.all}];return s.jsxs("div",{className:`runtime_ops_layout${r?"":" queues_collapsed"}${a?"":" 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(Ap,{open:r,on_toggle:i,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(Xe,{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:[P.map(L=>s.jsxs("button",{className:`runtime_ops_filter ${t===L.key?"selected":""}`,"aria-pressed":t===L.key,onClick:()=>n(L.key),children:[s.jsx("span",{children:L.label}),s.jsx("strong",{children:L.count.toLocaleString()})]},L.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${a?"":" list_collapsed"}`,children:[s.jsxs("div",{className:"pane_header runtime_ops_list_header",children:[s.jsx(Ap,{open:a,on_toggle:u,controls:"runtime_ops_runs",title:"Runs",count:b.length.toLocaleString()}),s.jsx("div",{className:"pane_spacer"}),s.jsx("input",{value:c,onChange:L=>d(L.target.value),placeholder:"Search workflow, run, node, status, error"}),s.jsxs("select",{className:"seg_select",value:m,onChange:L=>h(L.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:!a,children:[!b.length&&e.loading&&!e.runs.length?s.jsx(nc,{what:"activity"}):null,!b.length&&!(e.loading&&!e.runs.length)?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."}):null,b.map(L=>{const te=L.run,X=String(te.run_id||"").trim(),V=w[X]||0;return s.jsxs("div",{className:`raised runtime_ops_row ${X===A?"selected":""}`,"aria-current":X===A?"true":void 0,tabIndex:0,onClick:()=>{y(X),e.on_select_run(X)},onKeyDown:ne=>{(ne.key==="Enter"||ne.key===" ")&&(ne.preventDefault(),y(X),e.on_select_run(X))},children:[s.jsxs("div",{className:"runtime_ops_row_top",children:[s.jsx("strong",{className:"runtime_ops_row_name",children:Uo(te,e.workflow_label_by_id)}),L.is_stale?s.jsx("span",{className:"chip warn",children:"stale"}):null,s.jsx(ou,{status:te.status})]}),s.jsxs("div",{className:"runtime_ops_row_sub",children:[s.jsx("span",{className:"mono",children:jn(X,18)}),s.jsx("span",{children:Xc(te.updated_at||te.created_at)}),s.jsx("span",{children:iu(te)}),s.jsx("span",{className:"runtime_ops_row_reason",title:L.reason,children:L.reason})]}),s.jsxs("div",{className:"runtime_ops_row_foot",children:[s.jsxs("span",{className:"runtime_ops_row_facts",children:[s.jsxs("span",{children:[Number(te.llm_calls||0).toLocaleString()," llm"]}),s.jsxs("span",{children:[Number(te.tool_calls||0).toLocaleString()," tools"]}),s.jsxs("span",{children:[Number(te.tokens_total||0).toLocaleString()," tok"]}),s.jsxs("span",{children:[V.toLocaleString()," artifacts"]})]}),s.jsxs("div",{className:"runtime_ops_actions",children:[L.needs_user_action?s.jsx("button",{className:"btn primary",onClick:ne=>{ne.stopPropagation(),e.on_open_run(X)},children:L.action_label}):s.jsx("button",{className:"btn",onClick:ne=>{ne.stopPropagation(),e.on_open_run(X)},children:"Open"}),s.jsx("button",{className:"btn",onClick:ne=>{ne.stopPropagation(),e.on_open_ledger(X)},children:"Ledger"}),s.jsx("button",{className:"btn",onClick:ne=>{ne.stopPropagation(),e.on_select_run(X),e.on_open_logs()},children:"Logs"}),s.jsx("button",{className:"btn",onClick:ne=>{ne.stopPropagation(),e.on_filter_artifacts(X)},children:"Artifacts"})]})]})]},X)})]})]}),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"}),$?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"pane_spacer"}),s.jsx(ou,{status:$.status})]}):null]}),s.jsx("div",{className:"pane_body scroll runtime_ops_inspector_body",children:$?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"runtime_ops_inspector_head",children:[s.jsx("h3",{children:Uo($,e.workflow_label_by_id)}),s.jsx("span",{className:"mono",children:jn(A,28)})]}),s.jsxs("div",{className:"runtime_ops_decision",children:[s.jsx("strong",{children:(S==null?void 0:S.reason)||Z3($)}),s.jsx("span",{children:(S==null?void 0:S.expected_action)||(String($.status||"").toLowerCase()==="waiting"?"This run is paused until the pending wait is resolved or the run is cancelled.":T?"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:Bd(Ed($))})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Elapsed"}),s.jsx("strong",{children:iu($)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Last event"}),s.jsx("strong",{children:Bd($.updated_at||$.created_at)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Session"}),s.jsx("strong",{className:"mono",children:$.session_id?jn(String($.session_id),18):"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Node"}),s.jsx("strong",{className:"mono",children:$.current_node||"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Visible artifacts"}),s.jsx("strong",{children:R.toLocaleString()})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Provider calls"}),s.jsx("strong",{children:Number($.llm_calls||0).toLocaleString()})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Tokens"}),s.jsx("strong",{children:Number($.tokens_total||0).toLocaleString()})]})]}),E?s.jsxs("section",{className:"runtime_ops_session_context",children:[s.jsxs("div",{children:[s.jsx("span",{className:"run_hero_eyebrow",children:"Session context"}),s.jsx("strong",{className:"mono",children:jn(E,30)})]}),s.jsxs("div",{className:"runtime_ops_session_facts",children:[s.jsxs("span",{children:[F.toLocaleString()," loaded run",F===1?"":"s"]}),s.jsxs("span",{children:[M.toLocaleString()," visible artifact",M===1?"":"s"]})]}),s.jsxs("div",{className:"runtime_detail_actions compact",children:[s.jsx("button",{className:"btn",onClick:()=>e.on_filter_session_artifacts(E),children:"Open session artifacts"}),s.jsx("button",{className:"btn",onClick:()=>void tc(E),children:"Copy session id"})]})]}):null,D?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:q})]}),s.jsx("p",{children:I}),Z?s.jsxs("div",{className:"runtime_ops_wait_request",children:[s.jsx("span",{children:"Request"}),s.jsx(xi,{text:Z})]}):s.jsx("div",{className:"runtime_ops_wait_request muted",children:"No explicit prompt is attached to this wait. Open Observe or the ledger for full run context before responding."}),H.length?s.jsx("div",{className:"runtime_ops_wait_tools",children:H.map((L,te)=>s.jsxs(Ne.Fragment,{children:[s.jsx("span",{className:"chip mono warn",children:String((L==null?void 0:L.name)||"tool")}),VS(L).map(X=>s.jsxs("span",{className:"chip muted",title:HS,children:[X,"~"]},`${te}:${X}`))]},`${String((L==null?void 0:L.name)||"tool")}:${te}`))}):null,s.jsxs("details",{className:"runtime_raw_details",children:[s.jsx("summary",{className:"muted",children:"Raw wait payload"}),s.jsx(mr,{value:D,collapseAfterDepth:3,showCopy:!0})]})]}):null,Wm($)?s.jsx("div",{className:"warn_callout",children:Wm($)}):null,s.jsxs("div",{className:"runtime_detail_actions",children:[s.jsx("button",{className:"btn primary",onClick:()=>e.on_open_run(A),children:"Open Observe"}),s.jsx("button",{className:"btn",onClick:()=>e.on_open_ledger(A),children:"Open ledger"}),s.jsx("button",{className:"btn",onClick:()=>e.on_filter_artifacts(A),children:"Open artifacts"}),s.jsx("button",{className:"btn",onClick:e.on_open_logs,children:"Open logs"}),s.jsx("button",{className:"btn",onClick:()=>void tc(A),children:"Copy run id"})]})]}):s.jsx("div",{className:"empty_state_inline",children:"Select a run to inspect why it is active or blocked."})})]})]})}function NI(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"}],i=_.useMemo(()=>new Set(e.type_filters),[e.type_filters]),a=Math.max(0,Number(e.artifact_total_count||0)),u=!!e.query.trim()||e.type_filters.length>0||e.date_filter!=="all"||e.scope!=="all"||!!e.artifact_run_filter.trim(),c=Math.max(1,Number(e.artifact_page_size||500)),d=Math.max(1,Math.ceil(a/c)),m=Math.min(Math.max(0,Number(e.artifact_page||0)),d-1),h=a?m*c+1:0,p=Math.min(a,m*c+e.artifacts.length),y=_.useMemo(()=>{const R={},T=e.artifact_type_facets&&Object.keys(e.artifact_type_facets).length?e.artifact_type_facets:e.artifact_facets,P=(T==null?void 0:T.semantic_kind)||{},L=(T==null?void 0:T.render_kind)||{};for(const te of n)R[te]=Number(P[te]||L[te]||0);return R.audio=Number(P.audio||0),R.other=Number(P.other||0)+Number(P.artifact||0)+Number(P.binary||0)+Number(P["(none)"]||0),R},[e.artifact_facets,e.artifact_type_facets]),w=R=>{const T=new Set(i);T.has(R)?T.delete(R):T.add(R),e.on_type_filters_change(Array.from(T.values()))},x=_.useMemo(()=>{const R={waiting:[],running:[],failed:[],cancelled:[],completed:[],other:[]};for(const T of e.runs){const P=String(T.status||"").trim().toLowerCase();P==="waiting"?R.waiting.push(T):P==="running"?R.running.push(T):P==="failed"?R.failed.push(T):P==="cancelled"?R.cancelled.push(T):P==="completed"?R.completed.push(T):R.other.push(T)}return R},[e.runs]),k=t!=null&&t.run_id&&e.run_by_id[t.run_id]||null,b=e.artifact_run_filter?Uo(e.run_by_id[e.artifact_run_filter],e.workflow_label_by_id):"",S=_.useMemo(()=>{var P;const R=new Set,T=((P=e.artifact_facets)==null?void 0:P.run_id)||{};for(const L of Object.keys(T))L&&L!=="(none)"&&R.add(L);for(const L of e.artifacts)L.run_id&&R.add(L.run_id);for(const L of e.active_runs)L.run_id&&R.add(String(L.run_id));return Array.from(R).map(L=>e.run_by_id[L]||{run_id:L,workflow_id:null,status:"",created_at:null,updated_at:null}).sort((L,te)=>{const X=Ud(L.status)?0:1,V=Ud(te.status)?0:1;if(X!==V)return X-V;const ne=It(L.updated_at||L.created_at)??0;return(It(te.updated_at||te.created_at)??0)-ne}).slice(0,160)},[e.artifacts,e.active_runs,e.run_by_id,e.artifact_facets]),$=R=>{e.on_artifact_run_filter_change(R),e.on_session_filter_change(""),e.on_scope_change(R?"run":"all")},A=R=>e.gateway_connected?Math.max(0,Number(R||0)).toLocaleString():"—",E=e.selected_run_id&&e.run_by_id[e.selected_run_id]||null,z=_.useMemo(()=>{const R=e.runtime_log_query.trim().toLowerCase(),T=e.runtime_ledger_log_items||[];return R?T.filter(P=>{var X,V;const L=P.record||{};return[P.cursor,L.run_id,L.node_id,L.status,(X=L.effect)==null?void 0:X.type,L.started_at,L.ended_at,Br(((V=L.effect)==null?void 0:V.payload)??{},900),Br(L.result??{},900)].join(" ").toLowerCase().includes(R)}):T},[e.runtime_ledger_log_items,e.runtime_log_query]),F=_.useMemo(()=>{const R=e.runtime_log_query.trim().toLowerCase(),T=cI(e.runtime_ledger_log_items);return R?T.filter(P=>[P.provider,P.model,P.run_id,P.node_id,P.status,P.error,P.prompt_preview,P.response_preview,P.tokens.prompt,P.tokens.completion,P.tokens.total].join(" ").toLowerCase().includes(R)):T},[e.runtime_ledger_log_items,e.runtime_log_query]),M=F.reduce((R,T)=>R+(Number(T.tokens.total)||0),0),D=F.filter(R=>R.missing_response||R.error).length,H=_.useMemo(()=>{const R=e.runtime_log_query.trim().toLowerCase(),T=String(e.audit_log_text||"").replace(/\r\n/g,`
|
|
126
|
+
`).replace(/\r/g,`
|
|
127
|
+
`).split(`
|
|
128
|
+
`).filter(Boolean);return R?T.filter(P=>P.toLowerCase().includes(R)):T},[e.audit_log_text,e.runtime_log_query]),q=e.runtime_log_source==="run_ledger"||e.runtime_log_source==="provider_calls",I=e.runtime_log_source==="run_ledger"?"Selected Run Ledger":e.runtime_log_source==="provider_calls"?"Provider Calls":"Gateway HTTP Audit",Z=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:jn(e.artifact_run_filter,18)})]}):null,e.session_id?s.jsxs("span",{className:"chip muted",children:["session ",s.jsx("span",{className:"mono",children:jn(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:A(x.waiting.length)})]}),s.jsxs("div",{className:"metric_tile",children:[s.jsx("span",{children:"Running"}),s.jsx("strong",{children:A(x.running.length)})]}),s.jsxs("div",{className:"metric_tile",children:[s.jsx("span",{children:"Failed"}),s.jsx("strong",{children:A(x.failed.length)})]}),s.jsxs("div",{className:"metric_tile",children:[s.jsxs("span",{children:["Artifacts",u?" (filtered)":""]}),s.jsx("strong",{children:A(a)})]})]})]}),s.jsx("nav",{className:"runtime_mode_tabs",role:"tablist","aria-label":"System sections",children:["activity","artifacts","memory","logs"].map(R=>s.jsxs("button",{role:"tab","aria-selected":e.tab===R,className:`runtime_mode_tab ${e.tab===R?"active":""}`,onClick:()=>e.on_tab_change(R),children:[s.jsx(Xe,{name:R==="activity"?"history":R==="artifacts"?"download":R==="memory"?"agent":"terminal",size:14}),s.jsx("span",{children:R==="activity"?"Activity":R==="artifacts"?"Artifacts":R==="memory"?"Memory":"Logs"})]},R))}),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(SI,{gateway_connected:e.gateway_connected,loading:e.runs_loading,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=>{$(R),e.on_select_run(R),e.on_tab_change("artifacts")},on_filter_session_artifacts:R=>{R&&(e.on_artifact_run_filter_change(""),e.on_session_filter_change(R),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:R=>e.on_query_change(R.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:R=>{const T=R.target.value;T!=="run"&&e.on_artifact_run_filter_change(""),T==="session"?e.on_session_filter_change(e.session_id):e.on_session_filter_change(""),e.on_scope_change(T)},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:R=>e.on_group_by_change(R.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:R=>e.on_sort_by_change(R.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(Xe,{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(R=>{const T=i.has(R),P=y[R]||0,L=nI(R);return s.jsxs("button",{type:"button","aria-pressed":T,"aria-label":`${L} artifact type filter. Type filters combine with OR.`,title:`${L}: ${T?"in the filter":"not in the filter"}. Type filters combine with OR.`,className:`artifact_filter_chip ${T?"active":""}`,onClick:()=>w(R),children:[s.jsx("span",{children:L}),s.jsx("span",{className:"artifact_chip_count",children:e.gateway_connected?P.toLocaleString():"—"})]},R)}),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(R=>s.jsx("button",{type:"button","aria-pressed":e.date_filter===R.value,className:`artifact_filter_chip ${e.date_filter===R.value?"active":""}`,onClick:()=>e.on_date_filter_change(R.value),children:R.label},R.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:b||jn(e.artifact_run_filter,18)}),".",s.jsx("button",{className:"btn",onClick:()=>$(""),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 ",Vc(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:S.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:()=>$(""),children:[s.jsx("strong",{children:"All artifacts"}),s.jsx("span",{children:e.gateway_connected?`${a.toLocaleString()} match${a===1?"":"es"}`:"counts unavailable"})]}),S.map(R=>{const T=String(R.run_id||"").trim(),P=T===e.artifact_run_filter||T===(t==null?void 0:t.run_id);return s.jsxs("button",{className:`artifact_filter_run ${P?"selected":""}`,onClick:()=>$(T),title:T,children:[s.jsx("strong",{children:Uo(R,e.workflow_label_by_id)}),s.jsx("span",{className:"mono",children:jn(T,15)}),s.jsx("span",{children:iu(R)})]},T)})]})]}),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:a?`${h.toLocaleString()}-${p.toLocaleString()} of ${a.toLocaleString()}`:"0 items"}),s.jsx("div",{className:"pane_spacer"}),d>1?s.jsxs("div",{className:"artifact_pagination","aria-label":"Artifact pages",children:[s.jsx("button",{className:"btn",onClick:()=>e.on_artifact_page_change(0),disabled:m<=0,children:"First"}),s.jsx("button",{className:"btn",onClick:()=>e.on_artifact_page_change(m-1),disabled:m<=0,children:"Prev"}),s.jsxs("span",{className:"muted artifact_page_label",children:["Page ",(m+1).toLocaleString()," / ",d.toLocaleString()]}),s.jsx("button",{className:"btn",onClick:()=>e.on_artifact_page_change(m+1),disabled:m>=d-1,children:"Next"}),s.jsx("button",{className:"btn",onClick:()=>e.on_artifact_page_change(d-1),disabled:m>=d-1,children:"Last"})]}):null]}),s.jsxs("div",{className:"pane_body scroll artifact_browser_body",children:[!e.artifact_groups.length&&e.loading?s.jsx(nc,{what:"artifacts",size:"block"}):null,!e.artifact_groups.length&&!e.loading?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."}):null,s.jsx("div",{className:"artifact_group_list",children:e.artifact_groups.map(R=>s.jsxs("section",{className:"artifact_group",children:[s.jsxs("div",{className:"artifact_group_header",children:[s.jsx("span",{children:R.key}),s.jsx("span",{className:"artifact_group_count",children:R.items.length})]}),R.items.map(T=>{var V;const P=T.run_id&&e.run_by_id[T.run_id]||null,L=P?Uo(P,e.workflow_label_by_id):Tv(T),te=Bb(T),X=Number(((V=T.access)==null?void 0:V.access_count)||0)||0;return s.jsxs("button",{className:`artifact_row ${(t==null?void 0:t.artifact_id)===T.artifact_id?"selected":""}`,onClick:()=>{e.on_select_artifact(T.artifact_id),T.run_id&&e.on_select_run(T.run_id)},title:T.artifact_id,children:[s.jsx(Wb,{artifact:T,size:18}),s.jsxs("div",{className:"artifact_row_main",children:[s.jsxs("div",{className:"artifact_row_title",children:[s.jsx("strong",{children:zb(Lp(T,e.run_by_id,e.workflow_label_by_id))}),s.jsx("span",{className:"artifact_type_badge",children:Pd(T)}),T.render_kind&&T.render_kind!==T.semantic_kind?s.jsx("span",{className:"artifact_type_badge muted",children:T.render_kind}):null,T.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"})," ",iI(T)]}),s.jsxs("span",{children:[s.jsx("b",{children:"Size"})," ",Vc(T.size_bytes)]}),s.jsxs("span",{children:[s.jsx("b",{children:"Last seen"})," ",Fb(T)]}),X?s.jsxs("span",{children:[s.jsx("b",{children:"Accesses"})," ",X.toLocaleString()]}):null,te?s.jsxs("span",{children:[s.jsx("b",{children:"Media"})," ",te]}):null,T.content_type?s.jsxs("span",{children:[s.jsx("b",{children:"MIME"})," ",T.content_type]}):null]}),s.jsxs("div",{className:"artifact_row_facts secondary",children:[L?s.jsxs("span",{children:[s.jsx("b",{children:"Workflow"})," ",L]}):null,T.run_id?s.jsxs("span",{className:"mono",children:[s.jsx("b",{children:"Run"})," ",jn(T.run_id,13)]}):null,s.jsxs("span",{children:[s.jsx("b",{children:"Turn"})," ",ww(T)]}),Od(T)?s.jsxs("span",{className:"mono",children:[s.jsx("b",{children:"Node"})," ",Od(T)]}):null,qm(T)?s.jsxs("span",{children:[s.jsx("b",{children:"Source"})," ",qm(T)]}):null]}),s.jsxs("div",{className:"artifact_row_facts tertiary",children:[s.jsxs("span",{className:"mono",children:[s.jsx("b",{children:"ID"})," ",jn(T.artifact_id,22)]}),s.jsxs("span",{children:[s.jsx("b",{children:"Provenance"})," ",Pb(T)]})]}),Ub(T)?s.jsx("div",{className:"artifact_row_path mono",children:Ub(T)}):null]})]},T.artifact_id)})]},R.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?vw(t,e.run_by_id,e.workflow_label_by_id,e.embedded_preview.text):vw(t,e.run_by_id,e.workflow_label_by_id)}):null]}),t?s.jsxs(s.Fragment,{children:[(()=>{var V,ne,W,Y,K,fe,ae;const R=oI(t),T=YS(t),P=Bb(t),L=Number(((V=t.access)==null?void 0:V.access_count)||0)||0,te=Pn((ne=t.links)==null?void 0:ne.provider_trace,(W=t.links)==null?void 0:W.provider_trace_url,(Y=t.links)==null?void 0:Y.provider_trace_id),X=Pn((K=t.links)==null?void 0:K.audit,(fe=t.links)==null?void 0:fe.audit_tail,(ae=t.links)==null?void 0:ae.audit_url);return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"artifact_detail_header",children:[s.jsx(Wb,{artifact:t,size:22}),s.jsxs("div",{children:[s.jsx("div",{className:"artifact_detail_title",children:zb(Lp(t,e.run_by_id,e.workflow_label_by_id))}),s.jsxs("div",{className:"artifact_detail_subtitle",children:[Pd(t)," • ",t.render_kind||e.embedded_preview.render_kind||t.modality||"artifact"," • ",t.content_type||"unknown MIME"," • ",Vc(t.size_bytes),t.legacy_inferred?" • legacy inferred":""]})]})]}),s.jsx(pI,{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:Pd(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:Bd(t.created_at)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Size"}),s.jsx("strong",{children:Vc(t.size_bytes)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Last seen"}),s.jsx("strong",{children:Fb(t)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Accesses"}),s.jsx("strong",{children:L?L.toLocaleString():"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Run"}),s.jsx("strong",{className:"mono",children:t.run_id?jn(t.run_id,24):"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Workflow"}),s.jsx("strong",{children:k?Uo(k,e.workflow_label_by_id):"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Turn"}),s.jsx("strong",{children:ww(t)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Node"}),s.jsx("strong",{className:"mono",children:Od(t)||"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Provider/model"}),s.jsx("strong",{children:T||"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Media facts"}),s.jsx("strong",{children:P||"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Trace"}),s.jsx("strong",{children:t.provider_trace_available?"available":"not recorded"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Provenance"}),s.jsx("strong",{children:Pb(t)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Artifact id"}),s.jsx("strong",{className:"mono",children:jn(t.artifact_id,30)})]}),t.sha256?s.jsxs("div",{children:[s.jsx("span",{children:"sha256"}),s.jsx("strong",{className:"mono",children:jn(t.sha256,30)})]}):null]}),R?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:R})]}):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(mr,{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:()=>$(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:()=>{te&&window.open(te,"_blank","noopener,noreferrer")},disabled:!te,children:"Open provider trace"}),s.jsx("button",{className:"btn",onClick:()=>{X?window.open(X,"_blank","noopener,noreferrer"):e.on_tab_change("logs")},disabled:!X&&!t.audit_available,children:"Open audit trail"}),s.jsx("button",{className:"btn",onClick:()=>void tc(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(mr,{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:I}),s.jsx("div",{className:"mono muted",children:Z})]}),s.jsxs("div",{className:"actions",style:{marginTop:0},children:[q&&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:()=>{q?e.on_refresh_runtime_ledger(e.selected_run_id):e.on_refresh_audit()},disabled:q?e.runtime_ledger_log_loading:e.audit_log_loading,children:[s.jsx(Xe,{name:"refresh",size:14}),q?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:R=>e.on_runtime_log_query_change(R.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:E?Uo(E,e.workflow_label_by_id):e.selected_run_id?jn(e.selected_run_id,24):"No run selected"}),e.selected_run_id?s.jsx("em",{className:"mono",children:jn(e.selected_run_id,34)}):null]}),s.jsxs("div",{children:[s.jsx("span",{children:"Session"}),s.jsx("strong",{className:"mono",children:E!=null&&E.session_id?jn(String(E.session_id),28):e.session_id?jn(e.session_id,28):"—"})]}),s.jsxs("div",{className:"runtime_log_context_actions",children:[s.jsx("button",{className:"btn",onClick:()=>e.on_open_run(e.selected_run_id),disabled:!e.selected_run_id,children:"Open Observe"}),s.jsx("button",{className:"btn",onClick:()=>$(e.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&&!z.length&&e.runtime_ledger_log_loading?s.jsx(nc,{what:"ledger"}):null,e.selected_run_id&&!z.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:z.map(R=>{var K,fe;const T=R.record||{},P=String(((K=T==null?void 0:T.effect)==null?void 0:K.type)||"").trim(),L=String((T==null?void 0:T.status)||"").trim(),te=String((T==null?void 0:T.node_id)||"").trim(),X=Pn(T==null?void 0:T.ended_at,T==null?void 0:T.started_at,T==null?void 0:T.ts),V=Wa(T),ne=XS(T),W=P?Wt(Br(((fe=T==null?void 0:T.effect)==null?void 0:fe.payload)??{},1200),{max_chars:1200,max_lines:6}):"",Y=ZS(T)||(V?`Waiting for ${String(V.reason||"input")}`:"")||((T==null?void 0:T.result)!==void 0?Br(T.result,700):"");return s.jsxs("article",{className:`runtime_log_event ${_a(L)}`,children:[s.jsxs("div",{className:"runtime_log_event_header",children:[s.jsxs("span",{className:"mono",children:["#",R.cursor]}),s.jsx(ou,{status:L||"record"}),P?s.jsx("span",{className:"chip mono muted",children:P}):null,te?s.jsx("strong",{className:"mono",children:te}):null,X?s.jsx("span",{className:"mono muted",children:Bd(X)}):null]}),s.jsxs("div",{className:"runtime_log_event_body",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Request / activity"}),s.jsx("p",{children:[ne||dp(T),W&&W!=="{}"?W:""].filter(Boolean).join(`
|
|
129
|
+
`)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Outcome"}),s.jsx("p",{children:Wt(Y||"—",{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(mr,{value:T,collapseAfterDepth:3,showCopy:!0})]})]},`${e.selected_run_id}:${R.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:E?Uo(E,e.workflow_label_by_id):e.selected_run_id?jn(e.selected_run_id,24):"No run selected"}),e.selected_run_id?s.jsx("em",{className:"mono",children:jn(e.selected_run_id,34)}):null]}),s.jsxs("div",{children:[s.jsx("span",{children:"Provider calls"}),s.jsx("strong",{children:F.length.toLocaleString()}),s.jsx("em",{className:"mono",children:M?`${M.toLocaleString()} tokens`:"tokens not recorded"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Issues"}),s.jsx("strong",{children:D.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&&!F.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:F.map(R=>s.jsxs("article",{className:`provider_activity ${R.error||R.missing_response?"danger":""}`,children:[s.jsxs("div",{className:"provider_activity_header",children:[s.jsxs("div",{children:[s.jsx("h4",{children:[R.provider||"provider unknown",R.model||"model unknown"].join(" / ")}),s.jsxs("div",{className:"timeline_subtitle",children:[R.node_id?s.jsx("span",{className:"mono",children:R.node_id}):null,R.run_id?s.jsx("span",{className:"mono",children:jn(R.run_id,16)}):null,s.jsx("span",{children:cu(R.duration_ms)}),R.status?s.jsx(ou,{status:R.status}):null]})]}),s.jsxs("div",{className:"provider_tokens mono",children:[R.tokens.total?R.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:R.prompt_preview||"No prompt payload captured"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Response / error"}),s.jsx("p",{children:R.response_preview||R.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(mr,{value:R.raw,collapseAfterDepth:3,showCopy:!0})]})]},R.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:H.length?H.join(`
|
|
130
|
+
`):"(audit tail not loaded or no lines match search)"})]})]}):null]})}function $I(e){const[t,n]=_.useState(""),r=Array.isArray(e.wait.choices)?e.wait.choices:[],i=e.wait.allow_free_text!==!1,a=e.disabled===!0,u=String(e.wait.prompt||"").trim();return s.jsxs(s.Fragment,{children:[r.length?s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Expected response"}),s.jsxs("select",{className:"mono",value:t,onChange:c=>n(c.target.value),children:[s.jsx("option",{value:"",children:"(select)"}),r.map((c,d)=>s.jsx("option",{value:String(c),children:String(c)},d))]})]}):null,i?s.jsxs("div",{className:"field",children:[s.jsx("label",{children:r.length?"Or type a response":u?"Your answer":"Response to resume this wait"}),s.jsx("textarea",{className:"mono wait_response_input",value:t,onChange:c=>n(c.target.value),placeholder:u?"Type your answer to the request above…":"Type the response the workflow is waiting for…",rows:4})]}):null,s.jsx("div",{className:"actions",children:s.jsx("button",{className:"btn primary",disabled:a||!t.trim(),onClick:()=>e.on_submit(t.trim()),children:"Submit response"})})]})}function Vb(e,t,n){if(lg(e)==="automation"){const r=String(e.automation_id||e.run_id||"").trim();return n[r]||"Automation"}return Uo(e,t)}function Gb(e){const t=lg(e.run);return t?s.jsx("span",{className:"chip scheduled run_tree_tag","data-tag":t,children:kS(e.run)}):null}function CI(e){const t=e.selected_run_id.trim(),n=e.list?e.list.open:!0,r=e.root_run_id.trim()||t,i=e.sections.reduce((a,u)=>a+u.rows.reduce((c,d)=>{const m=[d.run,...d.children];return c+m.filter(h=>Ud(h.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(Ap,{open:n,on_toggle:e.list.on_toggle,controls:"run_nav_controls run_nav_tree",title:"Runs",count:`${e.total_runs.toLocaleString()} runs • ${i.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 • ",i.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(Xe,{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:a=>e.on_search(a.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(a=>s.jsx("button",{className:`seg_btn ${e.filter===a?"active":""}`,onClick:()=>e.on_filter(a),children:a},a))}),s.jsxs("select",{className:"seg_select",value:e.group_by,onChange:a=>e.on_group_by(a.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&&e.loading?s.jsx(nc,{what:"runs"}):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(a=>s.jsxs("section",{className:"run_tree_section",children:[s.jsxs("div",{className:"run_tree_section_header",children:[s.jsx("span",{children:a.label}),s.jsx("span",{className:"mono",children:a.rows.length})]}),a.rows.map(u=>{const c=u.run,d=String(c.run_id||"").trim(),m=d===t;return s.jsxs("div",{className:"run_tree_group",children:[s.jsxs("button",{className:`run_tree_item ${m?"selected":""} ${d===r?"root_context":""}`,onClick:()=>e.on_select(d,d),title:d,children:[s.jsxs("div",{className:"run_tree_item_top",children:[s.jsx("span",{className:"run_tree_label",children:Vb(c,e.workflow_label_by_id,e.automation_titles)}),s.jsx(Gb,{run:c}),c.status?s.jsx(ou,{status:Um(c)}):null]}),s.jsxs("div",{className:"run_tree_meta",children:[s.jsx("span",{className:"mono",children:jn(d,13)}),s.jsx("span",{children:Ed(c)?Xc(Ed(c)):"no start"}),s.jsx("span",{children:iu(c)})]})]}),u.children.length?s.jsx("div",{className:"run_tree_children",children:u.children.map(h=>{const p=String(h.run_id||"").trim();return s.jsxs("button",{className:`run_tree_item run_tree_child ${p===t?"selected":""}`,onClick:()=>e.on_select(p,d),title:p,children:[s.jsxs("div",{className:"run_tree_item_top",children:[s.jsx("span",{className:"run_tree_label",children:Vb(h,e.workflow_label_by_id,e.automation_titles)}),s.jsx(Gb,{run:h}),s.jsx(ou,{status:Um(h)})]}),s.jsxs("div",{className:"run_tree_meta",children:[s.jsx("span",{className:"mono",children:jn(p,13)}),s.jsx("span",{children:Ed(h)?Xc(Ed(h)):"child"}),s.jsx("span",{children:iu(h)})]})]},p)})}):null]},d)})]},a.key))]})]})}class EI{constructor(){yn(this,"_buffer","");yn(this,"_current",{data_lines:[]})}push(t,n){for(this._buffer+=t;;){const r=this._buffer.indexOf(`
|
|
131
|
+
`);if(r===-1)return;const i=this._buffer.slice(0,r);this._buffer=this._buffer.slice(r+1);const a=i.endsWith("\r")?i.slice(0,-1):i;if(a.startsWith(":"))continue;if(a===""){if(this._current.data_lines.length>0||this._current.event||this._current.id){const m={id:this._current.id,event:this._current.event,data:this._current.data_lines.join(`
|
|
132
|
+
`)};n(m)}this._current={data_lines:[]};continue}const u=a.indexOf(":"),c=u===-1?a:a.slice(0,u),d=u===-1?"":a.slice(u+1).trimStart();if(c==="id"){this._current.id=d;continue}if(c==="event"){this._current.event=d;continue}if(c==="data"){this._current.data_lines.push(d);continue}}}}const Gt=ov;function Ys(e,t=3e4){const n=AbortSignal.timeout(t),r=AbortSignal.any,i=e?typeof r=="function"?r([e,n]):e:n;return nN.set(i,t),i}const nN=new WeakMap;class AI extends Error{constructor(n){super(n);yn(this,"name","GatewayTimeout")}}class TI extends Error{constructor(n){super(n);yn(this,"name","Superseded")}}async function rn(e,t){try{return await globalThis.fetch(e,t)}catch(n){throw sN(n,e,t)}}async function cy(e,t,n){try{return await e.json()}catch(r){throw sN(r,t,n)}}function sN(e,t,n){{const r=String((e==null?void 0:e.name)||"");if(r!=="AbortError"&&r!=="TimeoutError")return e;const i=n==null?void 0:n.signal,a=i==null?void 0:i.reason,u=r==="TimeoutError"||String((a==null?void 0:a.name)||"")==="TimeoutError";let c=String(t);try{const d=new URL(t,typeof location<"u"?location.href:"http://localhost/");c=`${String((n==null?void 0:n.method)||"GET").toUpperCase()} ${d.pathname}${d.search?"?"+d.searchParams.toString().slice(0,60):""}`}catch{}if(u){const d=i&&nN.get(i)||3e4;return new AI(`${c}: no answer within ${Math.round(d/1e3)} s — the gateway is busy`)}return new TI(`${c}: superseded`)}}function xw(){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 Kt(e){const t=(e||"").trim(),n={};return t&&(n.Authorization=`Bearer ${t}`),{...n,...xw()}}async function Ss(e){try{const t=await e.text();return t!=null&&t.trim()?t.trim():`${e.status}`}catch{return`${e.status}`}}class MI extends Error{constructor(n,r){super(r);yn(this,"status");this.name="GatewayRequestError",this.status=n}}async function Fc(e,t){let n="";try{n=(await e.text()).trim()}catch{n=""}let r=n;try{const i=JSON.parse(n),a=i&&typeof i=="object"?i.detail:void 0;typeof a=="string"&&a.trim()?r=a.trim():a&&typeof a=="object"&&typeof a.message=="string"&&a.message.trim()&&(r=a.message.trim())}catch{}return new MI(e.status,`${t} (HTTP ${e.status}): ${r||e.statusText||"no reason given"}`)}async function RI(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 uy{constructor(t){yn(this,"_cfg");yn(this,"fetch_gateway",(t,n)=>fetch(Gt(this._cfg.base_url,t),{...n,headers:{...n==null?void 0:n.headers,...Kt(this._cfg.auth_token)}}));this._cfg={...t,base_url:(t.base_url||"").trim()}}async start_run(t,n,r){const i=String((r==null?void 0:r.bundle_id)||"").trim(),a=(r==null?void 0:r.session_id)===null||(r==null?void 0:r.session_id)===void 0?"":String(r.session_id||"").trim(),u=String(t||"").trim(),c=String((r==null?void 0:r.interface)||"").trim();if(u==="@default"&&(!c||i))throw new Error("start_run: flow_id '@default' needs `interface` and no bundle_id");const d={input_data:n||{}};i&&(d.bundle_id=i),u&&(d.flow_id=u),u==="@default"&&(d.interface=c),a&&(d.session_id=a),r!=null&&r.workspace&&(d.workspace=r.workspace);const m=await rn(Gt(this._cfg.base_url,yt("runs/start")),{method:"POST",headers:{"Content-Type":"application/json",...Kt(this._cfg.auth_token)},body:JSON.stringify(d)});if(!m.ok)throw new Error(await RI(m)||`start_run failed: ${m.status}`);const h=await m.json(),p=h==null?void 0:h.run_id;if(typeof p!="string"||!p)throw new Error("start_run: missing run_id");return p}async list_mcp_servers(){for(const t of[yt("mcp/servers"),yt("mcp"),yt("discovery/mcp")])try{const n=await rn(Gt(this._cfg.base_url,t),{headers:{...Kt(this._cfg.auth_token)},signal:Ys()});if(n.status===404||!n.ok)continue;const r=await n.json(),i=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(!i)continue;return i.map(a=>({name:String((a==null?void 0:a.name)||(a==null?void 0:a.id)||"").trim(),url:typeof(a==null?void 0:a.url)=="string"?a.url:void 0,description:typeof(a==null?void 0:a.description)=="string"?a.description:void 0,auth_required:typeof(a==null?void 0:a.auth_required)=="boolean"?a.auth_required:void 0})).filter(a=>a.name)}catch{return null}return null}async list_skills(){for(const t of[yt("skills"),yt("skills/registry")])try{const n=await rn(Gt(this._cfg.base_url,t),{headers:{...Kt(this._cfg.auth_token)},signal:Ys()});if(n.status===404||!n.ok)continue;const r=await n.json(),i=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(!i)continue;return i.map(a=>({name:String((a==null?void 0:a.name)||(a==null?void 0:a.id)||"").trim(),description:typeof(a==null?void 0:a.description)=="string"?a.description:void 0,version:typeof(a==null?void 0:a.version)=="string"?a.version:void 0,trust_level:typeof(a==null?void 0:a.trust_level)=="string"?a.trust_level:void 0,blocked:typeof(a==null?void 0:a.blocked)=="boolean"?a.blocked:void 0,requires_review:typeof(a==null?void 0:a.requires_review)=="boolean"?a.requires_review:void 0,tree_hash:typeof(a==null?void 0:a.tree_hash)=="string"?a.tree_hash:void 0,reasons:Array.isArray(a==null?void 0:a.reasons)?a.reasons.map(u=>String(u||"")).filter(Boolean):void 0})).filter(a=>a.name)}catch{return null}return null}async get_run(t){const n=await rn(Gt(this._cfg.base_url,yt(`runs/${encodeURIComponent(t)}`)),{headers:{...Kt(this._cfg.auth_token)}});if(!n.ok)throw new Error(`get_run failed: ${await Ss(n)}`);return await n.json()}async find_run(t){const n=await rn(Gt(this._cfg.base_url,yt(`runs/${encodeURIComponent(t)}`)),{headers:{...Kt(this._cfg.auth_token)}});if(n.status===404||n.status===403)return null;if(!n.ok)throw await Fc(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 i=new URLSearchParams;(n==null?void 0:n.include_subruns)===!1&&i.set("include_subruns","false"),(n==null?void 0:n.include_session)===!0&&i.set("include_session","true"),typeof(n==null?void 0:n.session_turn_limit)=="number"&&Number.isFinite(n.session_turn_limit)&&i.set("session_turn_limit",String(Math.max(1,Math.trunc(n.session_turn_limit)))),n!=null&&n.ledger_mode&&i.set("ledger_mode",String(n.ledger_mode)),typeof(n==null?void 0:n.ledger_max_items)=="number"&&Number.isFinite(n.ledger_max_items)&&i.set("ledger_max_items",String(Math.max(0,Math.trunc(n.ledger_max_items))));const a=Gt(this._cfg.base_url,yt(`runs/${encodeURIComponent(r)}/history_bundle?${i.toString()}`)),u=await rn(a,{headers:{...Kt(this._cfg.auth_token)}});if(!u.ok)throw new Error(`get_run_history_bundle failed: ${await Ss(u)}`);return await u.json()}async list_runs(t){const n=typeof(t==null?void 0:t.limit)=="number"?t.limit:50,r=String((t==null?void 0:t.status)||"").trim(),i=String((t==null?void 0:t.workflow_id)||"").trim(),a=String((t==null?void 0:t.session_id)||"").trim(),u=(t==null?void 0:t.root_only)===!0,c=new URLSearchParams;c.set("limit",String(n)),r&&c.set("status",r),i&&c.set("workflow_id",i),a&&c.set("session_id",a),u&&c.set("root_only","true"),(t==null?void 0:t.archived_only)===!0&&c.set("archived_only","true"),typeof(t==null?void 0:t.include_ledger_len)=="boolean"&&c.set("include_ledger_len",String(t.include_ledger_len)),typeof(t==null?void 0:t.include_metrics)=="boolean"&&c.set("include_metrics",String(t.include_metrics)),typeof(t==null?void 0:t.include_drafts)=="boolean"&&c.set("include_drafts",String(t.include_drafts));const d=Gt(this._cfg.base_url,yt(`runs?${c.toString()}`)),m=await rn(d,{headers:{...Kt(this._cfg.auth_token)},signal:Ys()});if(!m.ok)throw new Error(`list_runs failed: ${await Ss(m)}`);return await cy(m,d,{signal:Ys()})}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=Gt(this._cfg.base_url,yt(`audit/tail?max_bytes=${encodeURIComponent(String(n))}`)),i=await rn(r,{headers:{...Kt(this._cfg.auth_token)}});if(!i.ok)throw new Error(`audit_log_tail failed: ${await Ss(i)}`);return await i.json()}async gateway_about(){const t=await rn(Gt(this._cfg.base_url,yt("about")),{headers:{...Kt(this._cfg.auth_token)},signal:Ys(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 rn(Gt(this._cfg.base_url,yt(`runs/${encodeURIComponent(n)}/input_data`)),{headers:{...Kt(this._cfg.auth_token)}});if(!r.ok)throw new Error(`get_run_input_data failed: ${await Ss(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 i=typeof(n==null?void 0:n.limit)=="number"?n.limit:200,a=typeof(n==null?void 0:n.offset)=="number"?Math.max(0,Math.floor(n.offset)):0,u=Gt(this._cfg.base_url,yt(`runs/${encodeURIComponent(r)}/artifacts?limit=${encodeURIComponent(String(i))}&offset=${encodeURIComponent(String(a))}`)),c=await rn(u,{headers:{...Kt(this._cfg.auth_token)}});if(!c.ok)throw new Error(`list_run_artifacts failed: ${await Ss(c)}`);return await c.json()}async list_session_artifacts(t,n){const r=String(t||"").trim();if(!r)throw new Error("list_session_artifacts: session_id is required");const i=typeof(n==null?void 0:n.limit)=="number"?n.limit:200,a=typeof(n==null?void 0:n.offset)=="number"?Math.max(0,Math.floor(n.offset)):0,u=Gt(this._cfg.base_url,yt(`sessions/${encodeURIComponent(r)}/artifacts?limit=${encodeURIComponent(String(i))}&offset=${encodeURIComponent(String(a))}`)),c=await rn(u,{headers:{...Kt(this._cfg.auth_token)}});if(!c.ok)throw new Error(`list_session_artifacts failed: ${await Ss(c)}`);return await c.json()}async search_artifacts(t){const n=new URLSearchParams;n.set("scope",String((t==null?void 0:t.scope)||"all").trim()||"all");const r=String((t==null?void 0:t.session_id)||"").trim(),i=String((t==null?void 0:t.run_id)||"").trim(),a=String((t==null?void 0:t.modality)||"").trim(),u=String((t==null?void 0:t.artifact_kind)||"").trim(),c=String((t==null?void 0:t.semantic_kind)||"").trim(),d=String((t==null?void 0:t.render_kind)||"").trim(),m=String((t==null?void 0:t.workflow_id)||"").trim(),h=String((t==null?void 0:t.node_id)||"").trim(),p=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(),x=String((t==null?void 0:t.cursor)||"").trim(),k=String((t==null?void 0:t.order_by)||"").trim(),b=String((t==null?void 0:t.order)||"").trim(),S=String((t==null?void 0:t.created_after)||"").trim(),$=String((t==null?void 0:t.created_before)||"").trim(),A=typeof(t==null?void 0:t.limit)=="number"?t.limit:500,E=typeof(t==null?void 0:t.offset)=="number"?Math.max(0,Math.floor(t.offset)):0;r&&n.set("session_id",r),i&&n.set("run_id",i),a&&n.set("modality",a),u&&n.set("artifact_kind",u),c&&n.set("semantic_kind",c),d&&n.set("render_kind",d),m&&n.set("workflow_id",m),h&&n.set("node_id",h),p&&n.set("content_type",p),y&&n.set("query",y),w&&n.set("tags",w),x&&n.set("cursor",x),k&&n.set("order_by",k),b&&n.set("order",b),S&&n.set("created_after",S),$&&n.set("created_before",$),t!=null&&t.include_stats&&n.set("include_stats","true"),n.set("limit",String(A)),n.set("offset",String(E));const z=await rn(Gt(this._cfg.base_url,yt(`artifacts/search?${n.toString()}`)),{headers:{...Kt(this._cfg.auth_token)}});if(!z.ok)throw new Error(`search_artifacts failed: ${await Ss(z)}`);return await z.json()}async artifact_stats(t){const n=new URLSearchParams;n.set("scope",String((t==null?void 0:t.scope)||"all").trim()||"all");for(const i of["session_id","run_id","modality","semantic_kind","render_kind","workflow_id","node_id","content_type","query","tags","created_after","created_before"]){const a=String((t==null?void 0:t[i])||"").trim();a&&n.set(i,a)}const r=await rn(Gt(this._cfg.base_url,yt(`artifacts/stats?${n.toString()}`)),{headers:{...Kt(this._cfg.auth_token)}});if(!r.ok)throw new Error(`artifact_stats failed: ${await Ss(r)}`);return await r.json()}async download_run_artifact_content(t,n,r){const i=String(t||"").trim(),a=String(n||"").trim();if(!i)throw new Error("download_run_artifact_content: run_id is required");if(!a)throw new Error("download_run_artifact_content: artifact_id is required");const u=String((r==null?void 0:r.access)||"").trim(),c=u?`?access=${encodeURIComponent(u)}`:"",d=Gt(this._cfg.base_url,yt(`runs/${encodeURIComponent(i)}/artifacts/${encodeURIComponent(a)}/content${c}`)),m=await rn(d,{headers:{...Kt(this._cfg.auth_token)}});if(!m.ok)throw new Error(`download_run_artifact_content failed: ${await Ss(m)}`);return await m.blob()}async list_entities(){const t=await rn(Gt(this._cfg.base_url,yt("entities")),{headers:{...Kt(this._cfg.auth_token)},signal:Ys()});if(!t.ok)throw new Error(`list_entities failed: ${await Ss(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 rn(Gt(this._cfg.base_url,yt("entities/spec/phases")),{headers:{...Kt(this._cfg.auth_token)},signal:Ys()});if(!t.ok)throw new Error(`get_entity_phases_spec failed: ${await Ss(t)}`);return await t.json()}async get_entity_cognition(t){const n=await rn(Gt(this._cfg.base_url,yt(`entities/${encodeURIComponent(t)}/cognition`)),{headers:{...Kt(this._cfg.auth_token)},signal:Ys()});if(!n.ok)throw new Error(`get_entity_cognition failed: ${await Ss(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 rn(Gt(this._cfg.base_url,yt(`entities/${encodeURIComponent(n)}/card`)),{headers:{...Kt(this._cfg.auth_token)},signal:Ys()});if(!r.ok)throw new Error(`get_entity_card failed: ${await Ss(r)}`);return await r.json()}async read_entity_diary_entry(t,n){const r=String(t||"").trim(),i=String(n||"").trim();if(!r||!i)throw new Error("read_entity_diary_entry: name and entry_id are required");const a=Gt(this._cfg.base_url,yt(`entities/${encodeURIComponent(r)}/diary/${encodeURIComponent(i)}?reason=${encodeURIComponent("observer board hint chip")}`)),u=await rn(a,{headers:{...Kt(this._cfg.auth_token)},signal:Ys()});if(!u.ok)throw new Error(`read_entity_diary_entry failed: ${await Ss(u)}`);return await u.json()}async get_ledger(t,n){const r=Number((n==null?void 0:n.after)||0),i=Number((n==null?void 0:n.limit)||0),a=Gt(this._cfg.base_url,yt(`runs/${encodeURIComponent(t)}/ledger?after=${encodeURIComponent(String(r))}&limit=${encodeURIComponent(String(i))}`)),u=await rn(a,{headers:{...Kt(this._cfg.auth_token)},signal:Ys(n==null?void 0:n.signal)});if(!u.ok)throw new Error(`get_ledger failed: ${u.status}`);const c=await cy(u,a,{signal:Ys()}),d=Array.isArray(c==null?void 0:c.items)?c.items:[],m=typeof(c==null?void 0:c.next_after)=="number"?c.next_after:r;return{items:d,next_after:m}}async get_ledger_batch(t){const n=Array.isArray(t==null?void 0:t.runs)?t.runs:[],r=Number((t==null?void 0:t.limit)||0),i=await rn(Gt(this._cfg.base_url,yt("runs/ledger/batch")),{method:"POST",headers:{"Content-Type":"application/json",...Kt(this._cfg.auth_token)},body:JSON.stringify({runs:n,limit:r}),signal:Ys()});if(!i.ok)throw new Error(`get_ledger_batch failed: ${i.status}`);const a=await cy(i,Gt(this._cfg.base_url,yt("runs/ledger/batch")),{method:"POST",signal:Ys()}),c=(a&&typeof a=="object"?a:{}).runs;return{runs:c&&typeof c=="object"?c:{}}}async generate_run_summary(t,n){const r=String(t||"").trim();if(!r)throw new Error("generate_run_summary: run_id is required");const i={include_subruns:(n==null?void 0:n.include_subruns)!==!1},a=typeof(n==null?void 0:n.provider)=="string"?String(n.provider).trim():"";a&&(i.provider=a);const u=typeof(n==null?void 0:n.model)=="string"?String(n.model).trim():"";u&&(i.model=u);const c=await rn(Gt(this._cfg.base_url,yt(`runs/${encodeURIComponent(r)}/summary`)),{method:"POST",headers:{"Content-Type":"application/json",...Kt(this._cfg.auth_token)},body:JSON.stringify(i)});if(!c.ok)throw await Fc(c,"The gateway could not summarize this run");return await c.json()}async run_chat(t,n){const r=String(t||"").trim();if(!r)throw new Error("run_chat: run_id is required");const i={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)},a=typeof(n==null?void 0:n.provider)=="string"?String(n.provider).trim():"";a&&(i.provider=a);const u=typeof(n==null?void 0:n.model)=="string"?String(n.model).trim():"";u&&(i.model=u);const c=await rn(Gt(this._cfg.base_url,yt(`runs/${encodeURIComponent(r)}/chat`)),{method:"POST",headers:{"Content-Type":"application/json",...Kt(this._cfg.auth_token)},body:JSON.stringify(i)});if(!c.ok)throw await Fc(c,"The gateway could not answer");return await c.json()}async audio_transcribe(t,n){const r=String(t||"").trim();if(!r)throw new Error("audio_transcribe: run_id is required");const i=n==null?void 0:n.audio_artifact;if(!i||typeof i!="object")throw new Error("audio_transcribe: audio_artifact is required");if(!String(i.$artifact||"").trim())throw new Error("audio_transcribe: audio_artifact.$artifact is required");const u={audio_artifact:i};for(const h of["language","provider","model","request_id"]){const p=String((n==null?void 0:n[h])||"").trim();p&&(u[h]=p)}const c=await rn(Gt(this._cfg.base_url,yt(`runs/${encodeURIComponent(r)}/audio/transcribe`)),{method:"POST",headers:{"Content-Type":"application/json",...Kt(this._cfg.auth_token)},body:JSON.stringify(u)});if(!c.ok)throw await Fc(c,"The gateway refused the transcription");const d=await c.json(),m=String((d==null?void 0:d.text)||"");return{ok:!!(d!=null&&d.ok),run_id:String((d==null?void 0:d.run_id)||""),request_id:String((d==null?void 0:d.request_id)||""),text:m,transcript_artifact:d==null?void 0:d.transcript_artifact,provider:d!=null&&d.provider?String(d.provider):null,model:d!=null&&d.model?String(d.model):null,duration_ms:Number.isFinite(Number(d==null?void 0:d.duration_ms))?Number(d.duration_ms):null}}async voice_defaults(){const t=await rn(Gt(this._cfg.base_url,yt("voice/defaults")),{headers:{...Kt(this._cfg.auth_token)},signal:Ys()});if(!t.ok)throw await Fc(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 i=await rn(Gt(this._cfg.base_url,yt(`voice/voices?${r.toString()}`)),{headers:{...Kt(this._cfg.auth_token)},signal:Ys()});if(!i.ok)throw await Fc(i,"The gateway could not list its voices");return await i.json()}gateway_url(t){return Gt(this._cfg.base_url,t)}auth_headers(){return Kt(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 i=String((n==null?void 0:n.text)||"").trim();if(!i)throw new Error("voice_tts: text is required");const a={text:i},u=String((n==null?void 0:n.voice)||"").trim();u&&(a.voice=u);const c=String((n==null?void 0:n.format)||"").trim();c&&(a.format=c);const d=String((n==null?void 0:n.request_id)||"").trim();d&&(a.request_id=d);const m=await rn(Gt(this._cfg.base_url,yt(`runs/${encodeURIComponent(r)}/voice/tts`)),{method:"POST",headers:{"Content-Type":"application/json",...Kt(this._cfg.auth_token)},body:JSON.stringify(a)});if(!m.ok)throw new Error(`voice_tts failed: ${await Ss(m)}`);const h=await m.json();return{ok:!!(h!=null&&h.ok),run_id:String((h==null?void 0:h.run_id)||""),request_id:String((h==null?void 0:h.request_id)||""),audio_artifact:h==null?void 0:h.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 i={include_subruns:(n==null?void 0:n.include_subruns)!==!1,messages:Array.isArray(n==null?void 0:n.messages)?n.messages:[]},a=typeof(n==null?void 0:n.provider)=="string"?String(n.provider).trim():"";a&&(i.provider=a);const u=typeof(n==null?void 0:n.model)=="string"?String(n.model).trim():"";u&&(i.model=u);const c=typeof(n==null?void 0:n.title)=="string"?String(n.title).trim():"";c&&(i.title=c);const d=await rn(Gt(this._cfg.base_url,yt(`runs/${encodeURIComponent(r)}/chat_threads`)),{method:"POST",headers:{"Content-Type":"application/json",...Kt(this._cfg.auth_token)},body:JSON.stringify(i)});if(!d.ok)throw new Error(`save_chat_thread failed: ${await Ss(d)}`);return await d.json()}async list_bundles(){const t=await rn(Gt(this._cfg.base_url,yt("bundles")),{headers:{...Kt(this._cfg.auth_token)},signal:Ys()});if(!t.ok)throw new Error(`list_bundles failed: ${t.status}`);return await t.json()}async list_apps(){return await this.get_gateway_json("apps")}async get_gateway_json(t,n){const r=await rn(Gt(this._cfg.base_url,yt(t)),{headers:{...Kt(this._cfg.auth_token)},signal:n??Ys()});if(!r.ok)throw new Error(await Ss(r));return await r.json()}async reload_bundles(){const t=await rn(Gt(this._cfg.base_url,yt("bundles/reload")),{method:"POST",headers:{...Kt(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,i=(n==null?void 0:n.reload)!==!1,a=new FormData;a.set("overwrite",r?"true":"false"),a.set("reload",i?"true":"false"),a.set("file",t,t.name||"upload.flow");const u=await rn(Gt(this._cfg.base_url,yt("bundles/upload")),{method:"POST",headers:{...Kt(this._cfg.auth_token)},body:a});if(!u.ok)throw new Error(`upload_bundle failed: ${await Ss(u)}`);return await u.json()}async attachments_upload(t,n,r){const i=String(t||"").trim();if(!i)throw new Error("attachments_upload: session_id is required");if(!n)throw new Error("attachments_upload: file is required");const a=String((r==null?void 0:r.filename)||"").trim()||String((n==null?void 0:n.name)||"").trim()||"upload.bin",u=String((r==null?void 0:r.content_type)||"").trim()||String((n==null?void 0:n.type)||"").trim(),c=new FormData;c.append("session_id",i),c.append("file",n,a),c.append("filename",a),u&&c.append("content_type",u);const d=await rn(Gt(this._cfg.base_url,yt("attachments/upload")),{method:"POST",headers:{...Kt(this._cfg.auth_token)},body:c});if(!d.ok)throw new Error(`attachments_upload failed: ${await Ss(d)}`);const m=await d.json(),h=m==null?void 0:m.attachment;if(!h||typeof h!="object")throw new Error("attachments_upload: missing attachment");if(!String(h.$artifact||"").trim())throw new Error("attachments_upload: missing attachment.$artifact");return h}async remove_bundle(t,n){const r=String(t||"").trim();if(!r)throw new Error("remove_bundle: bundle_id is required");const i=new URLSearchParams,a=String((n==null?void 0:n.bundle_version)||"").trim();a&&i.set("bundle_version",a),i.set("reload",(n==null?void 0:n.reload)===!1?"false":"true");const u=Gt(this._cfg.base_url,yt(`bundles/${encodeURIComponent(r)}?${i.toString()}`)),c=await rn(u,{method:"DELETE",headers:{...Kt(this._cfg.auth_token)}});if(!c.ok)throw new Error(`remove_bundle failed: ${await Ss(c)}`);return await c.json()}async discovery_tools(){const t=await rn(Gt(this._cfg.base_url,yt("discovery/tools")),{headers:{...Kt(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=Gt(this._cfg.base_url,yt(`discovery/providers?include_models=${encodeURIComponent(String(n))}`)),i=await rn(r,{headers:{...Kt(this._cfg.auth_token)}});if(!i.ok)throw new Error(`discovery_providers failed: ${i.status}`);return await i.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 rn(Gt(this._cfg.base_url,yt(`discovery/providers/${encodeURIComponent(n)}/models`)),{headers:{...Kt(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 rn(Gt(this._cfg.base_url,yt(`bundles/${encodeURIComponent(n)}`)),{headers:{...Kt(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(),i=String(n||"").trim();if(!r)throw new Error("get_bundle_flow: bundle_id is required");if(!i)throw new Error("get_bundle_flow: flow_id is required");const a=await rn(Gt(this._cfg.base_url,yt(`bundles/${encodeURIComponent(r)}/flows/${encodeURIComponent(i)}`)),{headers:{...Kt(this._cfg.auth_token)}});if(!a.ok)throw new Error(`get_bundle_flow failed: ${a.status}`);return await a.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 rn(Gt(this._cfg.base_url,yt(`workflows/${encodeURIComponent(n)}/flow`)),{headers:{...Kt(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 rn(Gt(this._cfg.base_url,yt("discovery/capabilities")),{headers:{...Kt(this._cfg.auth_token)},signal:Ys()});if(!t.ok)throw new Error(`discovery_capabilities failed: ${await Ss(t)}`);return await t.json()}automations_client(){const t=this._cfg.auth_token;return pC({fetch:(n,r)=>fetch(n,r),baseUrl:this._cfg.base_url,headers:()=>Kt(t)})}async submit_command(t){const n=await rn(Gt(this._cfg.base_url,yt("commands")),{method:"POST",headers:{"Content-Type":"application/json",...Kt(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(),i=typeof(t==null?void 0:t.limit)=="number"&&Number.isFinite(t.limit)?Number(t.limit):500,a={scope:n,order:r,limit:i},u=String((t==null?void 0:t.run_id)||"").trim();u&&(a.run_id=u);const c=String((t==null?void 0:t.session_id)||"").trim();c&&(a.session_id=c);const d=String((t==null?void 0:t.owner_id)||"").trim();d&&(a.owner_id=d),t!=null&&t.all_owners&&(a.all_owners=!0);const m=String((t==null?void 0:t.subject)||"").trim();m&&(a.subject=m);const h=String((t==null?void 0:t.predicate)||"").trim();h&&(a.predicate=h);const p=String((t==null?void 0:t.object)||"").trim();p&&(a.object=p);const y=String((t==null?void 0:t.since)||"").trim();y&&(a.since=y);const w=String((t==null?void 0:t.until)||"").trim();w&&(a.until=w);const x=String((t==null?void 0:t.active_at)||"").trim();x&&(a.active_at=x);const k=String((t==null?void 0:t.query_text)||"").trim();k&&(a.query_text=k),typeof(t==null?void 0:t.min_score)=="number"&&Number.isFinite(t.min_score)&&(a.min_score=Number(t.min_score));const b=await rn(Gt(this._cfg.base_url,yt("kg/query")),{method:"POST",headers:{"Content-Type":"application/json",...Kt(this._cfg.auth_token)},body:JSON.stringify(a)});if(!b.ok)throw new Error(`kg_query failed: ${await Ss(b)}`);return await b.json()}async stream_ledger(t,n){var p;const r=Number((n==null?void 0:n.after)||0),i=n.on_step,a=n.signal,u=Gt(this._cfg.base_url,yt(`runs/${encodeURIComponent(t)}/ledger/stream?after=${encodeURIComponent(String(r))}`)),c=await rn(u,{headers:{Accept:"text/event-stream",...Kt(this._cfg.auth_token)},signal:a});if(!c.ok)throw await Fc(c,"The ledger stream was refused");if(!c.body)throw new Error("stream_ledger: response body is missing");(p=n.on_open)==null||p.call(n);const d=c.body.getReader(),m=new TextDecoder("utf-8"),h=new EI;for(;;){const{value:y,done:w}=await d.read();if(w)return;const x=m.decode(y,{stream:!0});h.push(x,k=>{if(!(k.event!=="step"||!k.data))try{const b=JSON.parse(k.data);b&&typeof b.cursor=="number"&&b.record&&i(b)}catch{}})}}}function LI(e,t=()=>({})){return async(n,r)=>{var c;const i=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)}:{}}),a=await i.text();let u=null;try{u=a?JSON.parse(a):null}catch{u=null}if(!i.ok)throw new Error(typeof(u==null?void 0:u.detail)=="string"?u.detail:typeof((c=u==null?void 0:u.detail)==null?void 0:c.message)=="string"?u.detail.message:a||`Gateway request failed (${i.status})`);return u}}function II({connected:e,request:t,value:n,onChange:r,disabled:i}){const[a,u]=_.useState(null),[c,d]=_.useState(null),m=JSON.stringify(n);_.useEffect(()=>{if(!e){u(null),d(null);return}let y=!0;return d(null),zm(t)(n).then(w=>y&&u(w)).catch(w=>y&&d(`Could not read your workspaces: ${ig(w)}`)),()=>{y=!1}},[e,m,t]);const h=_.useCallback(async y=>{const w=await zm(t)(y);u(w),r(y)},[t,r]),p=e?i?"The run is starting.":null:"Connect to your gateway to choose workspaces.";return s.jsx(zj,{level:"run",idPrefix:"observer-launch-workspace",value:n,effective:a,onChange:h,loadError:e?c:p,unavailableReason:p})}function OI(e){const t=(e||"").trim();return t?{Authorization:`Bearer ${t}`}:{}}class PI{constructor(t){yn(this,"_cfg");this._cfg={...t,url:(t.url||"").trim()}}async call_tool(t){const n=String((t==null?void 0:t.name)||"").trim(),r=String((t==null?void 0:t.call_id)||(t==null?void 0:t.id)||Xs()),i=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 a={jsonrpc:"2.0",id:Xs(),method:"tools/call",params:{name:n,arguments:i}},u=await fetch(this._cfg.url,{method:"POST",headers:{"Content-Type":"application/json",...OI(this._cfg.auth_token)},body:JSON.stringify(a)});if(!u.ok)return{call_id:r,name:n,success:!1,output:null,error:`Worker HTTP ${u.status}`};const c=await u.json().catch(()=>null),d=c==null?void 0:c.result,m=!!(d!=null&&d.isError),p=(Array.isArray(d==null?void 0:d.content)?d.content:[]).find(w=>w&&w.type==="text"&&typeof w.text=="string"),y=(p==null?void 0:p.text)??"";return m?{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 Kb{constructor(t,n){yn(this,"pending",[]);yn(this,"scheduled",!1);yn(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 Jb(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 DI(e,t){const n=It(e.updated_at||e.created_at)??0;return(It(t.updated_at||t.created_at)??0)-n}function FI(e,t){const n=t.query.trim().toLowerCase(),r=[...e],i={};for(const y of r){const w=String(y.run_id||"").trim();w&&(i[w]=y)}for(const y of e){const w=Jb(y);if(String(y.role||"")==="occurrence"&&w&&!i[w]){const x={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};i[w]=x,r.push(x)}}const a={},u={};for(const y of r){const w=String(y.run_id||"").trim();if(!w)continue;const x=Jb(y,t.parent_hint?t.parent_hint(w):"");u[w]=x,x&&(a[x]||(a[x]=[])).push(y)}const c=y=>{const w=String(y.status||"").trim().toLowerCase();return t.filter==="all"?!0:t.filter==="active"?Ud(w):t.filter==="waiting"?w==="waiting":t.filter==="terminal"?ds(w):t.filter==="failed"?w==="failed":!0},d=y=>{if(!n)return!0;const w=String(y.workflow_id||y.schedule_target_workflow_id||"").trim(),x=w?t.workflow_label_by_id[w]||w:"";return[y.run_id,w,x,y.session_id,y.status,y.session_kind,y.automation_id].join(" ").toLowerCase().includes(n)},m=[];for(const y of r){const w=String(y.run_id||"").trim();if(!w)continue;const x=u[w];(!x||!i[x])&&m.push(w)}const h={},p=y=>{if(t.group_by==="workflow"){const x=String(y.schedule_target_workflow_id||y.workflow_id||"").trim()||"(unknown workflow)";return{key:x,label:t.workflow_label_by_id[x]||x}}if(t.group_by==="session"){const x=String(y.session_id||"").trim()||"(no session)";return{key:x,label:x}}const w=String(y.status||"").trim().toLowerCase()||"unknown";return Ud(w)?{key:"active",label:"Active"}:w==="failed"?{key:"failed",label:"Failed"}:ds(w)?{key:"finished",label:"Finished"}:{key:w,label:w}};for(const y of m){const w=i[y];if(!w)continue;const x=[...a[y]||[]].sort(DI),k=x.some(S=>c(S)&&d(S));if(!(c(w)&&d(w))&&!k)continue;const b=p(w);h[b.key]||(h[b.key]={key:b.key,label:b.label,rows:[]}),h[b.key].rows.push({run:w,children:x})}return Object.values(h).sort((y,w)=>{const x={active:0,waiting:1,failed:2,finished:3},k=x[y.key]??10,b=x[w.key]??10;return k!==b?k-b:y.label.localeCompare(w.label)})}const Yb=60;function qd(e){try{const t=JSON.stringify(e);return t===void 0?String(e):t}catch{return String(e)}}function dy(e,t,n){return`${e.toLocaleString("en-US")} ${e===1?t:n}`}function Ip(e){if(e===void 0)return"undefined";if(typeof e=="string")return e.length<=Yb&&!e.includes(`
|
|
133
|
+
`)?JSON.stringify(e):`text (${dy(e.length,"char","chars")})`;if(e===null||typeof e!="object")return qd(e);const t=qd(e);return t.length<=Yb?t:Array.isArray(e)?`list (${dy(e.length,"item","items")})`:`object (${dy(Object.keys(e).length,"key","keys")})`}function zI(e){return e===void 0?!1:e&&typeof e=="object"&&!Array.isArray(e)?Object.values(e).some(t=>Ip(t)!==qd(t)):Ip(e)!==qd(e)}function BI(e){if(e===void 0)return"";if(e&&typeof e=="object"&&!Array.isArray(e)){const t=Object.keys(e);return t.length?`{${t.map(n=>`${n}: ${Ip(e[n])}`).join(", ")}}`:"{}"}return Ip(e)}function Ad(e){return It(e)}function UI(e){return e==null||e===""?"":typeof e=="string"?e:qd(e)}function Xb(e){return e.length?e[e.length-1]:null}function Zb(e,t){var r,i;const n=String(e.status||"").trim().toLowerCase();if(n==="started"||n==="running")return"running";if(n==="waiting"){const a=(i=(r=e.record)==null?void 0:r.result)==null?void 0:i.wait;if(String((a==null?void 0:a.reason)||"")==="subworkflow"){const u=fh(e.record);if(u&&t(u)==="running")return"running"}return"waiting"}return n==="failed"?"failed":n==="completed"||e.ended_at?"done":"running"}function WI(e,t){return e.t===null||t.t===null?e.t===null&&(t.t!==null||e.seq<t.seq):e.t<t.t||e.t===t.t&&e.seq<t.seq}function Qb(e){const t=new Map;for(const i of[...e].sort((a,u)=>a.seq-u.seq)){const a=t.get(i.rid)||[];a.push(i),t.set(i.rid,a)}const n=Array.from(t.values()),r=[];for(;n.some(i=>i.length);){let i=null;for(const a of n)if(a.length){if(!i){i=a;continue}WI(a[0],i[0])&&(i=a)}r.push(i.shift())}return r}function qI(e){return Ad(e.ended_at)??Ad(e.started_at)}function HI(e,t,n){var k,b,S,$,A,E,z,F,M,D;const r=String(t||"").trim();if(!r)return{};const i=[],a=new Set;for(const H of e||[]){const q=String((H==null?void 0:H.run_id)||((k=H==null?void 0:H.record)==null?void 0:k.run_id)||"").trim();q&&!a.has(q)&&(a.add(q),i.push(q))}i.sort((H,q)=>H===r?-1:q===r?1:0);const u=new Map;for(const H of i)u.set(H,ag(e,H));const c=(H,q)=>{const I=String(n(H,q)||"").trim();return!I||H!==r&&I===q?"":I},d=new Map,m=(H,q=0)=>{if(d.has(H))return d.get(H)??null;d.set(H,null);const I=q<6?Xb(u.get(H)||[]):null,Z=I?Zb(I,R=>m(R,q+1)):null;return d.set(H,Z),Z},h=new Map,p=(H,q)=>{let I=h.get(H);return I||(I={facts:{node_id:q,graph_id:H,run_ids:[],status:"done",visits:0,first_ms:null,last_ms:null,duration_ms:0,last_effect:"",last_status:"",llm:null,tools:[],waits:[],subruns:[],last_result_summary:"",last_result:void 0,last_error:"",context:null,records:[]},steps:[],records:[]},h.set(H,I)),I};let y=0;for(const H of i)for(const q of u.get(H)||[]){const I=String(q.node_id||"").trim();if(!I)continue;const Z=c(H,I);if(!Z)continue;const R=p(Z,I);R.steps.push({step:q,rid:H,t:qI(q),seq:y++}),R.facts.run_ids.includes(H)||R.facts.run_ids.push(H)}const w=(e||[]).filter(H=>H&&H.record).map((H,q)=>({x:H,i:q})).sort((H,q)=>{const I=i.indexOf(String(H.x.run_id||H.x.record.run_id||"").trim()),Z=i.indexOf(String(q.x.run_id||q.x.record.run_id||"").trim());return I!==Z?I-Z:(H.x.cursor||0)-(q.x.cursor||0)||H.i-q.i});y=0;for(const{x:H}of w){const q=String(H.run_id||H.record.run_id||"").trim(),I=String(H.record.node_id||"").trim();if(!q||!I)continue;const Z=c(q,I),R=Z?h.get(Z):void 0;R&&R.records.push({rec:H.record,rid:q,t:Ad(H.record.ended_at)??Ad(H.record.started_at),seq:y++})}const x={};for(const[H,q]of h){const I=q.facts,Z=Qb(q.steps).map(K=>K.step),R=Xb(Z);I.visits=Z.length,I.status=Zb(R,K=>m(K)),I.last_effect=R.effect_type,I.last_status=R.status;let T=0,P=0,L=0,te=!1,X=0,V=null;const ne=new Map;for(const K of Z){const fe=Ad(K.started_at),ae=Ad(K.ended_at)??fe;if(fe!==null&&(I.first_ms=I.first_ms===null?fe:Math.min(I.first_ms,fe)),ae!==null&&(I.last_ms=I.last_ms===null?ae:Math.max(I.last_ms,ae)),typeof K.duration_ms=="number"&&(I.duration_ms+=K.duration_ms),K.kind==="llm_call"){X+=1,V=K;const ge=((S=(b=K.record)==null?void 0:b.result)==null?void 0:S.usage)||((A=($=K.record)==null?void 0:$.result)==null?void 0:A.token_usage)||null;if(ge&&typeof ge=="object"){const pe=Number(ge.prompt_tokens??ge.input_tokens),$e=Number(ge.completion_tokens??ge.output_tokens),De=Number(ge.total_tokens);(Number.isFinite(pe)||Number.isFinite($e)||Number.isFinite(De))&&(te=!0,T+=Number.isFinite(pe)?pe:0,P+=Number.isFinite($e)?$e:0,L+=Number.isFinite(De)?De:(Number.isFinite(pe)?pe:0)+(Number.isFinite($e)?$e:0))}}else if(K.kind==="tool"){const ge=dh(K),pe=ge.calls.length?ge.calls.map($e=>$e.name):ge.results.map($e=>$e.name);for(const $e of pe){const De=ne.get($e)||{name:$e,calls:0,failed:0};De.calls+=1,ne.set($e,De)}for(const $e of ge.results){if($e.success!==!1)continue;const De=ne.get($e.name)||{name:$e.name,calls:0,failed:0};De.failed+=1,ne.set($e.name,De)}}const ve=UI((E=K.record)==null?void 0:E.error);ve&&(I.last_error=ve),K.record&&Object.prototype.hasOwnProperty.call(K.record,"result")&&K.record.result!==void 0&&K.record.result!==null&&(I.last_result=K.record.result)}if(I.last_result_summary=BI(I.last_result),I.tools=Array.from(ne.values()),X&&V){const K=uh(V);if(I.llm={calls:X,model:K.model,provider:K.provider},te&&(I.llm.tokens={in:T,out:P,total:L}),K.messages.length||K.system){const fe=K.system?[{role:"system",content:K.system},...K.messages]:[...K.messages];I.context={provider:K.provider,model:K.model,messages_source:K.messages_source,messages:fe}}}I.records=Qb(q.records).map(K=>K.rec);const W=I.status==="waiting"||I.status==="running"&&String(R.status)==="waiting"?String(((M=(F=(z=R.record)==null?void 0:z.result)==null?void 0:F.wait)==null?void 0:M.wait_key)||""):"",Y=new Set;for(const K of I.records){const fe=(D=K==null?void 0:K.result)==null?void 0:D.wait;if(String(K.status||"")==="waiting"&&fe&&typeof fe=="object"){const ve=String(fe.wait_key||""),ge=`${String(fe.reason||"")}|${ve}`;if(!Y.has(ge)){Y.add(ge);const pe={reason:String(fe.reason||""),wait_key:ve,open:!1};typeof fe.prompt=="string"&&fe.prompt&&(pe.prompt=fe.prompt),I.waits.push(pe)}}const ae=fh(K);ae&&!I.subruns.includes(ae)&&I.subruns.push(ae)}if(W)for(const K of I.waits)K.open=K.wait_key===W;x[H]=I}return x}function VI(e){const t={};for(const[n,r]of Object.entries(e||{}))t[n]=r.status;return t}function GI(e){const{records:t,context:n,...r}=e;return JSON.stringify(r,null,2)}function KI(e){return e.records.map(t=>qd(t)).join(`
|
|
134
|
+
`)}function JI(e){return e.context?JSON.stringify(e.context,null,2):""}function fy(e){return typeof e=="number"&&Number.isFinite(e)?new Date(e).toISOString():null}function YI(e){const t=new Map(e.nodes.map(r=>[r.id,r])),n=e.current_id?t.get(e.current_id):void 0;return{run_id:e.run_id,status:e.status,state:e.state,finished:e.finished,as_of:fy(e.now_ms)||"",current_node:n?{id:n.id,label:n.label,type:n.type,status:e.status_of(n.id)}:null,nodes:e.nodes.map(r=>{const i=e.facts[r.id];return{id:r.id,label:r.label,type:r.type,status:e.status_of(r.id),visits:i?i.visits:0,first_at:i?fy(i.first_ms):null,last_at:i?fy(i.last_ms):null,duration_ms:i?i.duration_ms:0,llm:i?i.llm:null,tools:i?i.tools:[],waits:i?i.waits:[],subruns:i?i.subruns:[],last_result_summary:i?i.last_result_summary:"",last_error:i?i.last_error:""}}),edges:e.edges.map(r=>({source:r.source,target:r.target}))}}const XI={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"},ZI=[{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 QI(){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:[ZI.map(n=>s.jsxs("div",{className:"pin-legend-row",children:[s.jsx("span",{className:"pin-legend-shape",style:{color:XI[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[])'})]})]})]})]})}const bw={execution:"#FFFFFF",string:"#FF00FF",number:"#00FF00",boolean:"#FF0000",object:"#00FFFF",json_schema:"#00FFFF",artifact:"#5EEAD4",artifact_image:"#19D3B8",artifact_audio:"#22D3EE",artifact_text:"#D946EF",artifact_video:"#A855F7",artifacts:"#2DD4BF",artifacts_image:"#0F766E",artifacts_audio:"#0891B2",artifacts_text:"#C026D3",artifacts_video:"#7C3AED",workspace_file:"#84CC16",workspace_folder:"#65A30D",memory:"#00C49A",assertion:"#00B8D4",assertions:"#00B8D4",array:"#FF8800",tools:"#FF8800",provider:"#00D2FF",model:"#9D4EDD",provider_text:"#00D2FF",model_text:"#9D4EDD",provider_image:"#19D3B8",model_image:"#9D4EDD",provider_video:"#A855F7",model_video:"#9D4EDD",provider_voice:"#22D3EE",model_voice:"#9D4EDD",provider_music:"#F59E0B",model_music:"#9D4EDD",agent:"#4488FF",any:"#888888"};function e4(e){return typeof e=="string"&&Object.prototype.hasOwnProperty.call(bw,e)}function t4(e){return e4(e)?bw[e]:bw.any}function n4(e){switch(e){case"execution":return"triangle";case"boolean":return"diamond";case"array":case"tools":case"assertions":return"square";case"agent":return"hexagon";default:return"circle"}}const s4=280,r4=6,i4=360,o4=1500;function rN(e,t=s4,n=r4){const r=String(e??"");let i=r.length,a=-1;for(let u=0;u<n&&(a=r.indexOf(`
|
|
135
|
+
`,a+1),a!==-1);u+=1)u===n-1&&(i=Math.min(i,a));return i=Math.min(i,t),i>=r.length?{shown:r,clamped:!1}:{shown:`${r.slice(0,i).trimEnd()}…`,clamped:!0}}function Ya(e){if(e===void 0)return"";if(typeof e=="string")return e;if(e===null||typeof e=="number"||typeof e=="boolean"||typeof e=="bigint")return String(e);try{return JSON.stringify(e,null,2)??String(e)}catch{return String(e)}}function a4(e){return e===null||["string","number","boolean"].includes(typeof e)}function e0(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function l4(e){if(Array.isArray(e)){const t=e.length,n=`array · ${t} item${t===1?"":"s"}`;if(!t)return{head:n,items:[],item_word:"items"};if(e.every(a4))return{head:n,items:e.map(a=>String(a)),item_word:"items"};const r=new Map;for(const a of e)r.set(e0(a),(r.get(e0(a))||0)+1);const i=[...r.entries()].map(([a,u])=>`${u} ${a}${u===1||a==="null"?"":"s"}`);return{head:`${n} (${i.join(", ")})`,items:[],item_word:"items"}}if(e&&typeof e=="object"){const t=e,n=Object.keys(t);return n.length===1&&typeof t.$artifact=="string"?{head:`artifact ${String(t.$artifact)}`,items:[],item_word:"keys"}:{head:`object · ${n.length} key${n.length===1?"":"s"}`,items:n,item_word:"keys"}}return{head:Ya(e),items:[],item_word:"items"}}function c4(e,t=i4){let n=0;for(let r=0;r<e.length;r+=1)if(n+=e[r].length+(r?2:0),n>t)return r;return e.length}function ug(e){const[t,n]=_.useState("");_.useEffect(()=>{if(!t)return;const i=window.setTimeout(()=>n(""),o4);return()=>window.clearTimeout(i)},[t]);const r=`Copy ${e.label}`;return s.jsx("button",{type:"button",className:`ap_copy_btn${t?` is_${t}`:""}${e.className?` ${e.className}`:""}`,title:r,"aria-label":r,onClick:async i=>{if(i.stopPropagation(),e.on_copy){e.on_copy(e.text),n("copied");return}n(await hh(e.text)?"copied":"failed")},children:t==="copied"?"copied":t==="failed"?"copy failed":"⧉"})}function iN(e){const t=e.size??12,n=t/2,r=e.filled?"currentColor":"none",i=n4(e.type);let a;if(i==="triangle")a=s.jsx("polygon",{points:`0,0 ${t},${n} 0,${t}`,fill:r,stroke:"currentColor",strokeWidth:"1.5"});else if(i==="diamond")a=s.jsx("polygon",{points:`${n},0 ${t},${n} ${n},${t} 0,${n}`,fill:r,stroke:"currentColor",strokeWidth:"1.5"});else if(i==="square")a=s.jsx("rect",{x:"1",y:"1",width:t-2,height:t-2,fill:r,stroke:"currentColor",strokeWidth:"1.5"});else if(i==="hexagon"){const u=[[n,0],[t,t*.25],[t,t*.75],[n,t],[0,t*.75],[0,t*.25]].map(([c,d])=>`${c},${d}`).join(" ");a=s.jsx("polygon",{points:u,fill:r,stroke:"currentColor",strokeWidth:"1.5"})}else a=s.jsx("circle",{cx:n,cy:n,r:n-1,fill:r,stroke:"currentColor",strokeWidth:"1.5"});return s.jsx("svg",{className:"ap_pin_glyph","data-pin-shape":i,width:t,height:t,viewBox:`0 0 ${t} ${t}`,style:{color:t4(e.type)},"aria-hidden":"true",children:a})}function u4(e){const[t,n]=_.useState(!1),{shown:r,clamped:i}=rN(e.text);return e.text?s.jsxs("span",{className:"ap_pin_string",children:[s.jsx("span",{className:"ap_pin_text",children:t||!i?e.text:r}),i?s.jsx("button",{type:"button",className:"ap_link_btn","aria-expanded":t,onClick:()=>n(a=>!a),children:t?"show less":`show all (${e.text.length.toLocaleString("en-US")} chars)`}):null]}):s.jsx("span",{className:"ap_pin_muted",children:"empty text"})}function d4(e){const[t,n]=_.useState(!1),r=c4(e.items),a=r<e.items.length&&!t?e.items.slice(0,r):e.items;return s.jsxs("span",{className:"ap_json_items",children:[s.jsx("span",{className:"ap_json_list",children:a.join(", ")}),r<e.items.length?s.jsx("button",{type:"button",className:"ap_link_btn","aria-expanded":t,onClick:()=>n(u=>!u),children:t?"show less":`show all ${e.items.length.toLocaleString("en-US")} ${e.word}`}):null]})}function f4(e){const[t,n]=_.useState(!1),r=l4(e.value);return s.jsxs("div",{className:"ap_json",children:[s.jsxs("div",{className:"ap_json_head",children:[s.jsxs("span",{className:"ap_json_shape mono",children:[r.head,r.items.length?":":""]}),r.items.length?s.jsx(d4,{items:r.items,word:r.item_word}):null]}),s.jsxs("details",{className:"ap_json_details",open:t,onToggle:i=>n(i.currentTarget.open),children:[s.jsx("summary",{className:"mono",children:"full JSON"}),t?s.jsx("pre",{className:"ap_json_body mono",children:Ya(e.value)}):null]})]})}function Hm(e){const t=e.value;return t===void 0?s.jsx("span",{className:"ap_pin_muted",children:"—"}):t===null?s.jsx("code",{className:"ap_pin_scalar ap_pin_muted",children:"null"}):typeof t=="string"?s.jsx(u4,{text:t}):typeof t=="number"||typeof t=="boolean"||typeof t=="bigint"?s.jsx("code",{className:"ap_pin_scalar",children:String(t)}):typeof t=="object"?s.jsx(f4,{value:t}):s.jsx("code",{className:"ap_pin_scalar",children:String(t)})}function m4(e){return e.state==="value"?Ya(e.value):e.state==="not_provided"&&e.flow_default?Ya(e.flow_default.value):null}function h4(e){const{pin:t}=e;if(t.state==="value")return s.jsx(Hm,{value:t.value});if(t.state==="not_provided")return s.jsxs("div",{className:"ap_pin_muted ap_pin_unsent",children:[s.jsx("span",{children:"not provided"}),t.flow_default?s.jsxs("div",{className:"ap_pin_default",children:[s.jsx("span",{className:"ap_pin_default_label",children:"flow default"})," ",s.jsx(Hm,{value:t.flow_default.value})]}):null,t.required&&!t.flow_default?s.jsx("span",{className:"ap_pin_required",children:" · required"}):null]});const n=t.state==="unknown"?"not loaded":e.side==="out"?e.outputs_final?"not in the run's output":"no output until the run ends":"no value";return s.jsx("span",{className:"ap_pin_muted",title:n,children:"—"})}function _4(e){const{pin:t}=e,n=t.typed?t.type:"untyped",r=m4(t);return s.jsxs("li",{className:`ap_pin ap_pin_${t.state} ap_copyable`,"data-pin-id":t.id,"data-pin-state":t.state,children:[s.jsxs("span",{className:"ap_pin_head",title:t.description||void 0,children:[s.jsx(iN,{type:t.type,filled:t.state==="value"}),s.jsx("span",{className:"ap_pin_name",children:t.label}),s.jsx("span",{className:"ap_pin_type mono",children:n}),r!==null?s.jsx(ug,{text:r,label:t.state==="value"?t.label:`${t.label} flow default`,on_copy:e.on_copy}):null]}),s.jsx("div",{className:"ap_pin_value",children:s.jsx(h4,{pin:t,side:e.side,outputs_final:e.outputs_final})})]})}function t0(e){const t=e.also||[],n=e.outputs_final===!0;return s.jsxs("div",{className:"ap_pins","aria-label":e.label,children:[e.pins.length?s.jsx("ul",{className:"ap_pin_list",children:e.pins.map(r=>s.jsx(_4,{pin:r,side:e.side,outputs_final:n,on_copy:e.on_copy},r.id))}):s.jsx("p",{className:"ap_pin_muted ap_pins_empty",children:e.empty_text||"no pins"}),t.length?s.jsxs("div",{className:"ap_pins_also",children:[s.jsx("div",{className:"ap_pins_also_label",children:e.also_label||"also on the wire"}),s.jsx("ul",{className:"ap_pin_list",children:t.map(([r,i])=>s.jsxs("li",{className:"ap_pin ap_pin_also ap_copyable","data-pin-id":r,"data-pin-state":"also",children:[s.jsxs("span",{className:"ap_pin_head",children:[s.jsx(iN,{type:"any",filled:!0}),s.jsx("span",{className:"ap_pin_name",children:r}),s.jsx("span",{className:"ap_pin_type mono",children:"not a pin"}),i!==void 0?s.jsx(ug,{text:Ya(i),label:r,on_copy:e.on_copy}):null]}),s.jsx("div",{className:"ap_pin_value",children:s.jsx(Hm,{value:i})})]},r))})]}):null]})}const kw=5*6e4;function p4(e){const t=new Map,n=new Map;for(const r of e||[]){const i=String((r==null?void 0:r.run_id)||"").trim();i&&t.set(i,r)}for(const r of t.values()){const i=String((r==null?void 0:r.parent_run_id)||"").trim();if(!i)continue;const a=n.get(i)||[];a.push(r),n.set(i,a)}return{by_id:t,children_of:n}}function Lv(e,t){const{by_id:n,children_of:r}=p4(e);return{by_id:n,children_of:r,now_ms:Date.now(),...t||{}}}function oN(e,t){var i;const n=(i=t.details)==null?void 0:i.get(String((e==null?void 0:e.run_id)||"")),r=(n==null?void 0:n.waiting)??(e==null?void 0:e.waiting);return r&&typeof r=="object"?r:null}function g4(e,t){return String((t==null?void 0:t.reason)||(e==null?void 0:e.waiting_reason)||"").trim().toLowerCase()}function y4(e,t,n){var a,u;const r=(a=t.details)==null?void 0:a.get(String((e==null?void 0:e.run_id)||""));return(e==null?void 0:e.paused)===!0||(r==null?void 0:r.paused)===!0||String((n==null?void 0:n.wait_key)||"").startsWith("pause:")?!0:String(((u=n==null?void 0:n.details)==null?void 0:u.kind)||"").trim().toLowerCase()==="pause"}function n0(e){return e?String(e.prompt||"").trim()?!0:Array.isArray(e.choices)&&e.choices.length>0:!1}function jw(e){return It((e==null?void 0:e.updated_at)||(e==null?void 0:e.created_at)||"")}function Qs(e){const t=Math.max(0,Math.floor(e/1e3)),n=Math.floor(t/60),r=Math.floor(n/60),i=Math.floor(r/24);return i>0?`${i}d ${r%24}h`:r>0?`${r}h ${n%60}m`:n>0?`${n}m`:`${t}s`}function w4(e,t){return e===null?"":Qs(t-e)}function s0(e,t){if(e===null)return"";const n=new Date(e).toISOString().slice(11,16),r=e-t;return r>0?`${n} UTC (in ${Bm(r)})`:`${n} UTC (due)`}function Td(e,t){const n=String(e||"").replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-1)}…`:n}const v4=6e4;function x4(e,t){var u;const n=oN(e,t),r=String(((u=n==null?void 0:n.details)==null?void 0:u.sub_run_id)||"").trim();if(r&&t.by_id.has(r))return t.by_id.get(r)||null;const a=(t.children_of.get(String((e==null?void 0:e.run_id)||""))||[]).filter(c=>!ds(String((c==null?void 0:c.status)||"")));return a.length?(a.sort((c,d)=>(jw(d)??0)-(jw(c)??0)),a[0]):null}function dg(e){const t=String(e||"").trim();if(!t)return"";const n=t.match(/^visual_react_agent_(.+)$/);if(n){const c=n[1],d=c.match(/^(.+?)_(\d+)_(\d+)_(\d+)_(.+)$/);if(d){const m=d[1];let h=d[5];return h.startsWith(`${m}_`)?h=h.slice(m.length+1):h=h.replace(/^[^_]+_/,""),h||c}return c}const r=t.indexOf("@"),i=t.indexOf(":",r<0?0:r),a=r>=0?t.slice(0,r):i>=0?t.slice(0,i):t,u=i>=0?t.slice(i+1):"";return u&&!/^[0-9a-f]{8,}$/i.test(u)?u:a||ni(t)}function b4(e){const t=String(e||"").trim(),n=ni(t);return n&&n!==t?`${n} — ${t}`:t}function aN(e,t){var r,i;const n=String((e==null?void 0:e.run_id)||"");return String(((i=(r=t.details)==null?void 0:r.get(n))==null?void 0:i.current_node)||(e==null?void 0:e.current_node)||"").trim()}function ni(e){const t=String(e||"").trim();if(!t)return"";const n=t.includes("@")?t.split(":")[0]:t,[r,i]=n.split("@"),a=String(r||"").split(".").pop()||r||"";return i?`${a} ${i}`:a}function Hd(e){const t=String(e||"").trim();return t.length>14?`${t.slice(0,6)}…${t.slice(-6)}`:t}function Vd(e,t,n=0){const r=k4(e,t,n);return{...r,brief:r.brief||r.text}}function k4(e,t,n=0){var S,$,A,E,z,F,M,D,H,q;const r=t.now_ms,i=typeof t.stall_after_ms=="number"?t.stall_after_ms:kw,a=String((e==null?void 0:e.run_id)||"").trim(),u=String((e==null?void 0:e.status)||"").trim().toLowerCase(),c=oN(e,t),d=g4(e,c),m=jw(e),h=String((e==null?void 0:e.role)||"").trim(),p={verb:"waiting",lane:"waiting_on",object:"",actor:"unknown",actor_run_id:"",action:"inspect",since_ms:m,stale_ms:null,stalled:!1,open_step:"",unresolved:!1,text:"",brief:""},y=w4(m,r),w=y?` · ${y}`:"";if(ds(u)){const I=Um(e),Z=String((e==null?void 0:e.error)||"").trim(),R=(S=t.details)==null?void 0:S.get(a),T=It((e==null?void 0:e.created_at)||""),P=It((e==null?void 0:e.updated_at)||""),L=T!==null&&P!==null&&P>=T?Qs(P-T):"";let te=I;I==="failed"?te=Z?`failed: ${Td(Z,120)}`:"failed":I==="completed"?te=L?`completed in ${L}`:"completed":I==="stopped"?te="stopped before the turn finished":I==="cancelled"&&(te="cancelled");const X=String((R==null?void 0:R.error)||"").trim();return I==="failed"&&!Z&&X&&(te=`failed: ${Td(X,120)}`),{...p,verb:"done",lane:"done",object:te,actor:"none",action:"open_run",text:te}}if(h==="controller"){const I=($=t.automations)==null?void 0:$.get(String((e==null?void 0:e.automation_id)||a)),Z=It((c==null?void 0:c.until)||""),R=(I==null?void 0:I.next_fire_ms)??Z,T=[];I!=null&&I.current&&!ds(I.current.status)?T.push(`run #${I.current.index} in progress`):d==="subworkflow"&&T.push("a run is in progress"),(I==null?void 0:I.status)==="paused"?T.push("paused: scheduled runs are skipped"):R!==null?T.push(`next run in ${Bm(Math.max(0,R-r))}`):(I==null?void 0:I.status)==="completed"||(I==null?void 0:I.status)==="failed"?T.push(`${I.status}: no next run`):T.push("next run not scheduled"),I!=null&&I.last&&T.push(`last #${I.last.index} ${I.last.status}`),I&&T.push(`${I.occurrence_count} turn${I.occurrence_count===1?"":"s"}`);const P=T.join(" · ");return{...p,verb:"scheduled",lane:"scheduled",object:P,actor:"clock",action:"open_run",text:P}}if((e==null?void 0:e.is_draft)===!0){const I="draft · not started";return{...p,verb:"scheduled",lane:"scheduled",object:I,actor:"none",action:"open_run",text:I}}if(u==="running"){const I=((A=t.pulses)==null?void 0:A.get(a))||null,Z=I&&I.ended_ms===null&&I.started_ms!==null?I:null,R=Math.max(m??0,(I==null?void 0:I.ended_ms)??0,(I==null?void 0:I.started_ms)??0)||null,T=R?Math.max(0,r-R):null,P=T!==null&&T>i,L=Z?`${Z.effect||Z.node_id||"step"} open ${Qs(r-Z.started_ms)}`:"",te=String(((z=(E=t.details)==null?void 0:E.get(a))==null?void 0:z.current_node)||(e==null?void 0:e.current_node)||"").trim(),X=["running"];return te&&X.push(`step ${te}`),L?X.push(L):T!==null&&X.push(`last step ${Qs(T)} ago`),P&&X.push("no progress"),{...p,verb:"running",lane:"working",object:L||te||"",actor:"runtime",action:"open_run",stale_ms:T,stalled:P,open_step:L,text:X.join(" · ")}}if(u!=="waiting"){if((e==null?void 0:e.is_scheduled)===!0){const Z=e!=null&&e.schedule_interval?`scheduled · every ${e.schedule_interval}`:"scheduled";return{...p,verb:"scheduled",lane:"scheduled",object:Z,actor:"clock",action:"open_run",text:Z}}const I=u?`${u}${w}`:"state unknown";return{...p,object:I,text:I,action:"inspect"}}if(y4(e,t,c)){const I=`paused${w} · resume when ready`;return{...p,verb:"paused",lane:"needs_you",object:"paused",actor:"you",action:"resume",text:I}}const x=Zd(c);if(x.length){const I=x.map(T=>String((T==null?void 0:T.name)||"tool").trim()).filter(Boolean),Z=`${I.slice(0,3).join(", ")}${I.length>3?` +${I.length-3}`:""}`,R=`needs your approval: ${Z||"tool call"}${w}`;return{...p,verb:"needs_you",lane:"needs_you",object:`approval: ${Z}`,actor:"you",action:"approve",text:R}}if(d==="user"){if(n0(c)){const R=Td(String((c==null?void 0:c.prompt)||""),80),T=R?`asks: ${R}${w}`:`asks a question${w}`;return{...p,verb:"needs_you",lane:"needs_you",object:R||"a question",actor:"you",action:"answer",text:T,brief:`asks a question${w}`}}if(((F=t.details)==null?void 0:F.has(a))===!0){const R=`waits for your answer${w}`;return{...p,verb:"needs_you",lane:"needs_you",object:"your answer",actor:"you",action:"answer",text:R}}const Z=`needs you: question, approval or pause${w}`;return{...p,verb:"needs_you",lane:"needs_you",object:"question, approval or pause",actor:"you",action:"open_run",unresolved:!0,text:Z}}if(d==="subworkflow"){const I=n<4?x4(e,t):null;if(!I){const P=String(((M=c==null?void 0:c.details)==null?void 0:M.sub_run_id)||"").trim(),L=P?(D=t.fates)==null?void 0:D.get(P):void 0,X=aN(e,t)||L&&dg(L.workflow_id)||Hd(P);if(L&&L.status==="missing"){const ne=`stuck: subrun ${X} no longer exists${w}`;return{...p,verb:"needs_you",lane:"needs_you",object:`subrun ${X} (missing)`,actor:"you",action:"open_run",stuck:!0,stuck_facts:{subrun:X,status:"missing",ended_ms:null},text:ne}}if(L&&ds(L.status)){const ne=It(L.updated_at),W=ne!==null?Math.max(0,t.now_ms-ne):null;if(W!==null&&W<=v4){const ae=`its subrun ${X} ${L.status} ${Qs(W)} ago · resuming${w}`;return{...p,verb:"running",lane:"working",object:`subrun ${X}`,actor:"runtime",action:"open_run",text:ae}}const Y=W!==null?` ${Qs(W)} ago`:"",K=L.status==="cancelled"?"was cancelled":L.status==="failed"?"failed":`ended ${L.status}`,fe=`stuck: subrun ${X} ${K}${Y}, this run was not resumed${w}`;return{...p,verb:"needs_you",lane:"needs_you",object:`subrun ${X} (${L.status})`,actor:"you",action:"open_run",stuck:!0,stuck_facts:{subrun:X,status:L.status,ended_ms:W},text:fe}}if(P){const ne=`waiting for its subrun ${X} to finish${w}`;return{...p,object:`subrun ${X}`,actor:"run",actor_run_id:P,action:"open_subrun",text:ne}}const V=`waiting for a subrun to finish${w}`;return{...p,object:"a subrun",actor:"run",action:"open_run",text:V}}const Z=Vd(I,t,n+1),R=ni(String(I.workflow_id||""))||Hd(String(I.run_id||""));if(Z.verb==="running"){const P=[`running subrun ${R}`];return Z.open_step?P.push(Z.open_step):Z.stale_ms!==null&&P.push(`last step ${Qs(Z.stale_ms)} ago`),Z.stalled&&P.push("no progress"),{...p,verb:"running",lane:"working",object:`subrun ${R}`,actor:"run",actor_run_id:String(I.run_id||""),action:"open_subrun",stale_ms:Z.stale_ms,stalled:Z.stalled,open_step:Z.open_step,text:P.join(" · ")}}const T=`waiting for subrun ${R}: ${Z.brief||Z.text}`;return{...p,verb:"waiting",lane:"waiting_on",object:`subrun ${R}`,actor:"run",actor_run_id:String(I.run_id||""),action:"open_subrun",unresolved:Z.unresolved,text:T}}if(d==="until"){const I=It((c==null?void 0:c.until)||""),Z=I!==null?`sleeps until ${s0(I,r)}`:`sleeps until an unknown time${w}`,R=(e==null?void 0:e.is_scheduled)===!0;return{...p,...R?{verb:"scheduled",lane:"scheduled"}:{},object:"the clock",actor:"clock",action:"open_run",text:Z}}if(d==="event"){if(n0(c)){const P=Td(String((c==null?void 0:c.prompt)||""),80),L=P?`asks: ${P}${w}`:`asks a question${w}`;return{...p,verb:"needs_you",lane:"needs_you",object:P||"a question",actor:"you",action:"answer",text:L,brief:`asks a question${w}`}}const I=It((c==null?void 0:c.until)||""),Z=String(((H=c==null?void 0:c.details)==null?void 0:H.event)||((q=c==null?void 0:c.details)==null?void 0:q.name)||"").trim(),R=Z?`event ${Z}`:"an event",T=I!==null?`waiting for ${R} until ${s0(I,r)}`:`waiting for ${R}${w}`;return{...p,object:R,actor:"external",action:"open_run",text:T}}if(d==="job"){const I=`waiting for a delegated tool job${w}`;return{...p,object:"a delegated tool job",actor:"runtime",action:"open_run",text:I}}const k=String((c==null?void 0:c.wait_key)||"").trim(),b=`waiting, reason unknown${k?` (${k})`:""}${w} · inspect`;return{...p,object:"unknown",actor:"unknown",action:"inspect",text:b}}function lN(e,t,n,r){if(String((e==null?void 0:e.role)||"").trim()==="controller")return(r==null?void 0:r.status)==="paused"?"paused":"scheduled";if(t.stuck)return"stuck";const i=Um({status:e==null?void 0:e.status,paused:(e==null?void 0:e.paused)===!0||t.verb==="paused",stop_reason:n??null});return t.verb==="running"&&i==="waiting"?"running":i}const my={automation:"⟳",agent:"◉",run:"▭"};function cN(e,t){var d;const n=String((e==null?void 0:e.role)||"").trim(),r=String((e==null?void 0:e.session_kind)||"").trim(),i=String((e==null?void 0:e.automation_id)||"").trim(),a=i?(d=t.automations)==null?void 0:d.get(i):void 0,u=ni(String((e==null?void 0:e.workflow_id)||""));if(n==="controller"||n==="occurrence"||n==="descendant"||n==="discussion"||r==="automation"){const m=[];return n==="occurrence"&&typeof(e==null?void 0:e.occurrence_index)=="number"?m.push(`occurrence #${e.occurrence_index}`):n==="descendant"&&typeof(e==null?void 0:e.occurrence_index)=="number"?m.push(`occurrence #${e.occurrence_index} · subrun`):n==="discussion"&&m.push("discussion"),u&&n!=="controller"&&m.push(u),n==="controller"&&a&&m.push(a.cadence),{kind:"automation",glyph:my.automation,label:(a==null?void 0:a.title)||"",secondary:m.join(" · "),automation_id:i,id_hint:i}}const c=String((e==null?void 0:e.session_id)||"").trim();if(c){const m=[u,String((e==null?void 0:e.parent_run_id)||"").trim()?"subrun":""].filter(Boolean);return{kind:"agent",glyph:my.agent,label:"session",secondary:m.join(" · "),automation_id:"",id_hint:c}}return{kind:"run",glyph:my.run,label:"",secondary:u,automation_id:"",id_hint:""}}function uN(e,t,n){var p,y,w;const r=String((e==null?void 0:e.automation_id)||"").trim(),i=r?(p=t.automations)==null?void 0:p.get(r):void 0;if(i!=null&&i.title)return{text:i.title,source:"automation",untitled:!1};const a=String(((y=e==null?void 0:e.brief)==null?void 0:y.title)||"").trim();if(a)return{text:a,source:"brief",untitled:!1};const u=String(((w=e==null?void 0:e.brief)==null?void 0:w.task_excerpt)||"").trim();if(u)return{text:Td(u,80),source:"brief",untitled:!1};const c=String((e==null?void 0:e.session_kind)||"").trim(),d=String((e==null?void 0:e.role)||"").trim();return!(!!r||c==="automation"||d==="occurrence"||d==="descendant"||d==="controller")&&(n!=null&&n.excerpt)?{text:Td(n.excerpt,80),source:"excerpt",untitled:!1}:{text:ni(String((e==null?void 0:e.workflow_id)||""))||"(workflow?)",source:"workflow",untitled:!0}}function j4(e){var r;const t=String((e==null?void 0:e.source_id)||"").trim(),n=String(((r=e==null?void 0:e.config)==null?void 0:r.every)||"").trim();return t==="schedule"?n?`every ${n}`:"scheduled":t==="manual"?"manual":t==="email_received"?"on email":t||""}function _h(e){var y,w,x,k,b,S,$,A;const t=e!=null&&e.summary&&typeof e.summary=="object"?e.summary:null,n=e!=null&&e.definition&&typeof e.definition=="object"?e.definition:null,r=String((t==null?void 0:t.automation_id)||(e==null?void 0:e.automation_id)||"").trim();if(!r)return null;const i=(y=n==null?void 0:n.target)!=null&&y.input_data&&typeof n.target.input_data=="object"?n.target.input_data:{},a=t!=null&&t.last_occurrence&&typeof t.last_occurrence=="object"?t.last_occurrence:null,u=t!=null&&t.current_occurrence&&typeof t.current_occurrence=="object"?t.current_occurrence:null,c=Array.isArray(i==null?void 0:i.tools)?i.tools.map(E=>String(E)).filter(Boolean):[],d=Array.isArray((w=n==null?void 0:n.notify)==null?void 0:w.channels)?n.notify.channels.map(E=>String(E)):[],m=Array.isArray(t==null?void 0:t.capabilities)?t.capabilities.map(E=>String(E)):[],h=i!=null&&i._runtime&&typeof i._runtime=="object"?i._runtime:{},p=E=>Array.isArray(E)?E.map(z=>String(z)).filter(Boolean):null;return{automation_id:r,title:String((t==null?void 0:t.title)||(n==null?void 0:n.title)||"").trim(),status:String((t==null?void 0:t.status)||"").trim(),cadence:j4((t==null?void 0:t.trigger)||(n==null?void 0:n.trigger)),next_fire_ms:It((t==null?void 0:t.next_run_at)||(t==null?void 0:t.next_fire_at)||""),last:a?{index:Number(a.index||0),status:String(a.status||""),fired_ms:It(a.fired_at||""),finished_ms:It(a.finished_at||"")}:null,occurrence_count:typeof(t==null?void 0:t.occurrence_count)=="number"?t.occurrence_count:0,current:u?{index:Number(u.index||0),run_id:String(u.run_id||""),status:String(u.status||"")}:null,context_mode:String((t==null?void 0:t.context_mode)||((x=n==null?void 0:n.context)==null?void 0:x.mode)||"").trim(),growing_max_tokens:typeof(t==null?void 0:t.growing_max_tokens)=="number"?t.growing_max_tokens:null,model:String((i==null?void 0:i.model)||"").trim(),provider:String((i==null?void 0:i.provider)||"").trim(),tools:c,max_iterations:typeof(i==null?void 0:i.max_iterations)=="number"?i.max_iterations:null,tool_approval:String(((k=n==null?void 0:n.policy)==null?void 0:k.tool_approval)||"").trim(),allowed_tools:p(h.allowed_tools),untrusted_input_tools:p((b=n==null?void 0:n.policy)==null?void 0:b.untrusted_input_tools),email_allowed_recipients:p((S=n==null?void 0:n.policy)==null?void 0:S.email_allowed_recipients),workspace_access_mode:String((i==null?void 0:i.workspace_access_mode)||"").trim(),notify_channels:d,task:String((i==null?void 0:i.prompt)||(($=i==null?void 0:i.context)==null?void 0:$.task)||"").trim(),workspace_root:String((t==null?void 0:t.workspace_root)||(n==null?void 0:n.workspace_root)||"").trim(),can_revise:m.includes("revise"),capabilities:m,legacy:(t==null?void 0:t.legacy)===!0,schedule_rule_text:String((t==null?void 0:t.schedule_rule_text)||"").trim(),next_run_local:String((t==null?void 0:t.next_run_local)||"").trim(),paused_reason:String((t==null?void 0:t.paused_reason)||"").trim(),context_used_tokens:typeof(t==null?void 0:t.context_used_tokens)=="number"&&Number.isFinite(t.context_used_tokens)&&t.context_used_tokens>=0?t.context_used_tokens:null,last_run_id:String((a==null?void 0:a.run_id)||"").trim(),last_excerpt:String((a==null?void 0:a.excerpt)||"").trim(),last_notification_text:String(((A=t==null?void 0:t.last_notification)==null?void 0:A.text)||"").trim()}}function S4(e,t,n){var i;const r=n!=null&&n.record&&typeof n.record=="object"?n.record:n;return!r||typeof r!="object"?null:{run_id:String(e||"").trim(),ledger_len:Number(t||0),node_id:String(r.node_id||"").trim(),effect:String(((i=r==null?void 0:r.effect)==null?void 0:i.type)||"").trim(),status:String(r.status||"").trim(),started_ms:It(r.started_at||""),ended_ms:It(r.ended_at||"")}}function kn(e){return typeof e=="string"?e:e==null?"":String(e)}function r0(e,t){const n=kn(e).trim();return n.length<=t?n:`${n.slice(0,Math.max(0,t-1))}…`}function dN(e){const t=kn(e==null?void 0:e.targetHandle),n=kn(e==null?void 0:e.sourceHandle);return!!(t==="exec-in"||n==="exec-out"||t.includes("exec")||n.includes("exec"))}function fN(e){if(!e||typeof e!="object")return"";const t=e!=null&&e.data&&typeof e.data=="object"?e.data:{};return kn((t==null?void 0:t.nodeType)||(e==null?void 0:e.type)||"").trim()}function mN(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=kn(n).trim();if(!r)return"";if(r.includes(":")){const i=r.split(":",2);if(i.length===2&&i[1])return i[1].trim()}return r}function N4(e){const t=kn(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(fN(r)==="on_flow_start"){const i=kn(r==null?void 0:r.id).trim();if(i)return i}return""}function hy(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 fm(e,t){const n=kn(e).trim(),r=kn(t).trim();return r?n?`${n}::${r}`:r:""}function $4(e){const t=e.root&&typeof e.root=="object"?e.root:{};if(!e.expand_subflows)return t;const n=[],r=[],i=new Set,a=(u,c,d,m)=>{if(!u||typeof u!="object"||n.length>=e.max_nodes||r.length>=e.max_edges)return;const h=Array.isArray(u.nodes)?u.nodes:[],p=Array.isArray(u.edges)?u.edges:[];for(const y of h){const w=kn(y==null?void 0:y.id).trim();if(!w)continue;const x=fm(c,w);if(!x||i.has(x))continue;const k=hy(y),b={...y,id:x,position:{x:k.x+d.x,y:k.y+d.y}};if(n.push(b),i.add(x),n.length>=e.max_nodes)break}for(const y of p){if(!dN(y))continue;const w=kn(y==null?void 0:y.source).trim(),x=kn(y==null?void 0:y.target).trim();if(!w||!x)continue;const k=fm(c,w),b=fm(c,x);if(!k||!b)continue;const S=kn(y==null?void 0:y.id).trim(),$=S?`${k}->${b}::${S}`:`${k}->${b}`;if(r.push({...y,id:$,source:k,target:b}),r.length>=e.max_edges)break}if(!(m>=e.max_depth))for(const y of h){if(n.length>=e.max_nodes||r.length>=e.max_edges)return;if(fN(y)!=="subflow")continue;const w=mN(y);if(!w)continue;const x=e.flow_by_id[w];if(!x||typeof x!="object")continue;const k=fm(c,kn(y==null?void 0:y.id));if(!k)continue;const b=N4(x);if(!b)continue;const $=(Array.isArray(x.nodes)?x.nodes:[]).find(H=>kn(H==null?void 0:H.id).trim()===b)||null;if(!$)continue;const A=hy(y),E=hy($),M={x:A.x+d.x+240-E.x,y:A.y+d.y+0-E.y},D=fm(k,b);r.push({id:`${k}=>${D}`,source:k,target:D,sourceHandle:"exec-out",targetHandle:"exec-in"}),a(x,k,M,m+1)}};return a(t,"",{x:0,y:0},0),{...t,id:kn(t.id),nodes:n,edges:r}}function C4(e){const t=kn(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 E4(e){const t=e.nodes.filter(a=>e.keep_id(a.id)),n=new Set(t.map(a=>a.id)),r={};for(const a of e.edges)r[a.source]||(r[a.source]=[]),r[a.source].push(a.target);const i=new Map;for(const a of t){const u=new Set,c=(r[a.id]||[]).slice();for(;c.length;){const d=c.pop();if(!d||u.has(d))continue;if(u.add(d),n.has(d)){const h=`${a.id}->${d}`;i.has(h)||i.set(h,{id:h,source:a.id,target:d});continue}const m=r[d]||[];for(const h of m)u.has(h)||c.push(h);if(i.size>=e.max_edges)break}if(i.size>=e.max_edges)break}return{nodes:t,edges:Array.from(i.values())}}function i0(e,t){const i=Math.max(t.w*8,160),a=Math.max(t.h*8,120),u=Math.max(160,Math.min(i,e.w)),c=Math.max(120,Math.min(a,e.h));return{x:e.x,y:e.y,w:u,h:c}}const A4=new Set(["completed","failed","cancelled","stopped"]),hN={running:"here",waiting:"waiting here",failed:"failed here",done:"here",none:"here"},_N={running:"running",waiting:"waiting",failed:"failed",done:"done",none:"not visited"},pN={user:"waiting for you",subworkflow:"waiting for its subrun",until:"waiting for the clock",event:"waiting for an event",job:"waiting for a tool job"};function gN(e){const t=(e==null?void 0:e.waits.find(n=>n.open))||null;return t?pN[t.reason]||`waiting (${t.reason||"reason not recorded"})`:"waiting, reason not recorded"}function zc(e){return e==="running"?3:e==="waiting"?2:0}function o0(e){if(typeof e!="number"||!Number.isFinite(e))return"";const t=new Date(e);return[t.getHours(),t.getMinutes(),t.getSeconds()].map(n=>String(n).padStart(2,"0")).join(":")}const a0=typeof window>"u"?_.useEffect:_.useLayoutEffect;function T4(e){const t=e.status;if(t==="none")return null;let n;return t==="running"?n=s.jsx("circle",{className:"flow_badge_spin",r:4,fill:"none",strokeDasharray:"18 8"}):t==="waiting"?n=s.jsx("path",{d:"M -2 -3.5 V 3.5 M 2 -3.5 V 3.5"}):t==="failed"?n=s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M 0 -4 V 1"}),s.jsx("circle",{className:"flow_badge_dot",cx:0,cy:3.6,r:.9})]}):n=s.jsx("path",{d:"M -3.5 0.2 L -1 2.8 L 3.6 -2.6"}),s.jsxs(s.Fragment,{children:[s.jsx("circle",{className:"flow_badge_bg",r:8.5}),n]})}function fp(e){const[t,n]=_.useState("idle"),r=_.useRef(null);return _.useEffect(()=>()=>{r.current!==null&&window.clearTimeout(r.current)},[]),s.jsx("button",{type:"button",className:e.className||"btn flow_copy_btn",title:e.title,"aria-label":e.title,disabled:e.disabled,"data-copy-state":t,onClick:async i=>{i.stopPropagation();const a=await hh(e.get_text());n(a?"copied":"failed"),r.current!==null&&window.clearTimeout(r.current),r.current=window.setTimeout(()=>n("idle"),1500)},children:s.jsx("span",{"aria-live":"polite",children:t==="copied"?e.copied??"Copied":t==="failed"?e.failed??$S:e.label})})}function l0(e){const[t,n]=_.useState(!1),{shown:r,clamped:i}=rN(e.text);return s.jsxs("span",{className:"flow_facts_text",children:[s.jsx("span",{children:t||!i?e.text:r}),i?s.jsx("button",{type:"button",className:"flow_link_btn","aria-expanded":t,onClick:()=>n(a=>!a),children:t?"show less":`show all (${e.text.length.toLocaleString("en-US")} chars)`}):null]})}function M4(e){const[t,n]=_.useState(!1),r=zI(e.value);return s.jsxs("span",{className:"flow_facts_text",children:[s.jsx("code",{className:"flow_facts_summary",children:e.summary}),r?s.jsx("button",{type:"button",className:"flow_link_btn","aria-expanded":t,onClick:()=>n(i=>!i),children:t?"show less":"show all"}):null,r&&t?s.jsx("pre",{className:"flow_facts_json",children:JSON.stringify(e.value,null,2)}):null]})}function R4(e){const{node:t,facts:n,status:r}=e,i=r==="waiting"?gN(n):_N[r],a=n?[`${n.visits.toLocaleString("en-US")} visit${n.visits===1?"":"s"}`,n.first_ms!==null?`first ${o0(n.first_ms)}`:"",n.last_ms!==null?`last ${o0(n.last_ms)}`:"",`${cu(n.duration_ms)} in steps`].filter(Boolean):[],u=(n==null?void 0:n.llm)||null;return s.jsxs("div",{className:"flow_facts",children:[s.jsxs("div",{className:"flow_facts_head",children:[s.jsx("span",{className:"flow_facts_title",children:t.label}),s.jsx("span",{className:"flow_facts_type",children:t.type})]}),s.jsxs("div",{className:"flow_facts_status",children:[s.jsx("span",{className:"flow_status_chip","data-run-status":r,children:i}),e.here?s.jsx("span",{className:"flow_facts_here",children:hN[r]}):null]}),n?s.jsxs("dl",{className:"flow_facts_rows",children:[s.jsxs("div",{className:"flow_facts_row",children:[s.jsx("dt",{children:"Visits"}),s.jsx("dd",{children:a.join(" · ")})]}),u?s.jsxs("div",{className:"flow_facts_row",children:[s.jsx("dt",{children:"LLM"}),s.jsx("dd",{children:[u.model||"model not recorded",u.provider||"provider not recorded",`${u.calls.toLocaleString("en-US")} call${u.calls===1?"":"s"}`,u.tokens?`${u.tokens.in.toLocaleString("en-US")} in · ${u.tokens.out.toLocaleString("en-US")} out tokens`:""].filter(Boolean).join(" · ")})]}):null,n.tools.length?s.jsxs("div",{className:"flow_facts_row",children:[s.jsx("dt",{children:"Tools"}),s.jsx("dd",{children:s.jsxs("table",{className:"flow_facts_tools",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{scope:"col",children:"tool"}),s.jsx("th",{scope:"col",children:"calls"}),s.jsx("th",{scope:"col",children:"failed"})]})}),s.jsx("tbody",{children:n.tools.map(c=>s.jsxs("tr",{"data-failed":c.failed>0?"true":void 0,children:[s.jsx("td",{children:c.name}),s.jsx("td",{children:c.calls}),s.jsx("td",{children:c.failed})]},c.name))})]})})]}):null,n.waits.length?s.jsxs("div",{className:"flow_facts_row",children:[s.jsx("dt",{children:"Waits"}),s.jsx("dd",{children:s.jsx("ul",{className:"flow_facts_list",children:n.waits.map((c,d)=>s.jsxs("li",{children:[s.jsx("span",{children:pN[c.reason]||c.reason||"reason not recorded"}),c.open?s.jsx("span",{className:"flow_facts_open",children:" · now"}):null,c.prompt?s.jsxs(s.Fragment,{children:[" · ",s.jsx(l0,{text:c.prompt})]}):null]},`${c.reason}|${c.wait_key}|${d}`))})})]}):null,n.subruns.length?s.jsxs("div",{className:"flow_facts_row",children:[s.jsx("dt",{children:"Subruns"}),s.jsx("dd",{className:"flow_facts_subruns",children:n.subruns.map(c=>s.jsx("button",{type:"button",className:"flow_link_btn mono",title:e.on_open_run?`Open run ${c}`:`${c} (opening runs is not wired here)`,disabled:!e.on_open_run,onClick:()=>{var d;return(d=e.on_open_run)==null?void 0:d.call(e,c)},children:Hd(c)},c))})]}):null,n.last_result_summary?s.jsxs("div",{className:"flow_facts_row",children:[s.jsx("dt",{children:"Result"}),s.jsx("dd",{children:s.jsx(M4,{summary:n.last_result_summary,value:n.last_result})})]}):null,n.last_error?s.jsxs("div",{className:"flow_facts_row flow_facts_error",children:[s.jsx("dt",{children:"Error"}),s.jsx("dd",{children:s.jsx(l0,{text:n.last_error})})]}):null]}):s.jsx("p",{className:"flow_facts_none",children:e.finished?"Not visited in this run.":"Not visited yet."}),s.jsxs("div",{className:"flow_facts_actions",children:[s.jsx(fp,{label:"Copy facts (JSON)",disabled:!n,get_text:()=>n?GI(n):""}),s.jsx(fp,{label:"Copy records (JSONL)",disabled:!n||!n.records.length,get_text:()=>n?KI(n):""}),n!=null&&n.context?s.jsx(fp,{label:"Copy context",get_text:()=>JI(n)}):null]})]})}function L4(e){var mt;const t=typeof e.now_ms=="number"?e.now_ms:Date.now(),n=e.flow,r=kn(e.active_node_id),i=e.recent_nodes||{},a=e.visited_nodes||{},u=e.highlight_path===!0,c=typeof e.vertical_compact=="number"?Math.max(.4,Math.min(1,e.vertical_compact)):.78,{nodes:d,edges:m,bounds:h}=_.useMemo(()=>{const se=$4({root:n||{},flow_by_id:e.flow_by_id||{},expand_subflows:e.expand_subflows===!0,max_depth:3,max_nodes:700,max_edges:900}),ce=Array.isArray(se.nodes)?se.nodes:[],je=Array.isArray(se.edges)?se.edges:[];let Ae=[];for(const Pe of ce){const Ut=kn(Pe==null?void 0:Pe.id).trim();if(!Ut)continue;const St=Pe!=null&&Pe.position&&typeof Pe.position=="object"?Pe.position:{},Mn=typeof St.x=="number"?St.x:0,nn=typeof St.y=="number"?St.y:0,Je=Pe!=null&&Pe.data&&typeof Pe.data=="object"?Pe.data:{},en=kn((Je==null?void 0:Je.label)||(Pe==null?void 0:Pe.label)||Ut)||Ut,Yt=kn((Je==null?void 0:Je.nodeType)||(Pe==null?void 0:Pe.type)||"unknown")||"unknown",Cr=kn((Je==null?void 0:Je.headerColor)||(Pe==null?void 0:Pe.headerColor)||"")||"",Ns=Je!=null&&Je.eventConfig&&typeof Je.eventConfig=="object"?Je.eventConfig:null,ps=Ns&&typeof Ns.schedule=="string"?kn(Ns.schedule).trim():"",_r=Ns&&typeof Ns.recurrent=="boolean"?!!Ns.recurrent:void 0,we=Yt==="subflow"?mN(Pe):"",wt=ps||_r!==void 0||we?{schedule:ps||void 0,recurrent:_r,subflow_id:we||void 0}:void 0;Ae.push({id:Ut,x:Mn,y:nn,label:en,type:Yt,color:Cr,meta:wt})}const ze={};for(const Pe of Ae)ze[Pe.id]=Pe;let Fe=[];for(const Pe of je){if(!dN(Pe))continue;const Ut=kn(Pe==null?void 0:Pe.source).trim(),St=kn(Pe==null?void 0:Pe.target).trim();!Ut||!St||Fe.push({id:kn((Pe==null?void 0:Pe.id)||`${Ut}->${St}`),source:Ut,target:St})}const Ze=new Set(Ae.map(Pe=>Pe.id));if(Fe=Fe.filter(Pe=>Ze.has(Pe.source)&&Ze.has(Pe.target)),e.simplify===!0){const Ut=E4({nodes:Ae,edges:Fe,keep_id:St=>{if(r&&St===r)return!0;const Mn=ze[St];if(!Mn)return!1;const nn=kn(Mn.type).trim().toLowerCase();return nn==="on_flow_start"||nn==="on_flow_end"||nn==="subflow"?!0:!C4(nn)},max_edges:900});Ae=Ut.nodes,Fe=Ut.edges}if(e.prefer_vertical===!0&&Ae.length>=2){const Pe=Ae.map(Je=>Je.x),Ut=Ae.map(Je=>Je.y),St=Math.max(...Pe)-Math.min(...Pe),Mn=Math.max(...Ut)-Math.min(...Ut);St>=Mn&&(Ae=Ae.map(Je=>({...Je,x:Je.y,y:Je.x})));const nn=Math.min(...Ae.map(Je=>Je.y));Ae=Ae.map(Je=>({...Je,y:nn+(Je.y-nn)*c}))}const lt={};for(const Pe of Ae)lt[Pe.id]=Pe;const ht=160,_t=56,kt=ht/2,At=_t/2;let rt=0,zt=0,dn=0,on=0;Ae.length&&(rt=Math.min(...Ae.map(Pe=>Pe.x)),zt=Math.min(...Ae.map(Pe=>Pe.y)),dn=Math.max(...Ae.map(Pe=>Pe.x+ht)),on=Math.max(...Ae.map(Pe=>Pe.y+_t)));let Ht=0;if(Fe.length){const Pe=new Set(Fe.map(Ut=>`${Ut.source}->${Ut.target}`));for(const Ut of Fe){if(!Pe.has(`${Ut.target}->${Ut.source}`))continue;const St=lt[Ut.source],Mn=lt[Ut.target];if(!St||!Mn)continue;const nn=St.x+kt,Je=St.y+At,en=Mn.x+kt,Yt=Mn.y+At,Cr=Math.max(1,Math.hypot(en-nn,Yt-Je)),Ns=Math.max(28,Math.min(72,Cr*.14)),ps=Math.min(200,Ns*3.5);ps>Ht&&(Ht=ps)}}const Ot=60+Ht,ts={x:rt-Ot,y:zt-Ot,w:dn-rt+Ot*2,h:on-zt+Ot*2,node_w:ht,node_h:_t};return{nodes:Ae,edges:Fe,bounds:ts}},[n,e.flow_by_id,e.expand_subflows,e.simplify,e.prefer_vertical,r,c]),p=_.useRef(null),[y,w]=_.useState(()=>({x:h.x,y:h.y,w:h.w,h:h.h})),x=_.useRef(y);x.current=y,_.useEffect(()=>{w({x:h.x,y:h.y,w:h.w,h:h.h})},[h.x,h.y,h.w,h.h]);const k=_.useRef(new Map),b=_.useRef(null),S=_.useMemo(()=>{const se=new Set;for(const ce of m)se.add(`${ce.source}->${ce.target}`);return se},[m]),[$,A]=_.useState(null),[E,z]=_.useState(null),F=_.useRef({}),M=_.useRef(null),D=_.useRef(null),H=_.useRef(null),q=_.useRef(!1),Z=`flow_facts_${_.useId().replace(/[^a-zA-Z0-9_-]/g,"")}`,R=()=>{D.current!==null&&window.clearTimeout(D.current),D.current=null},T=se=>{const ce=F.current[se];if(!ce||typeof window>"u")return;const je=ce.getBoundingClientRect(),Ae=window.innerWidth,ze=Math.min(400,Ae-16);let Fe=je.right+10,Ze=je.top;Fe+ze>Ae-8&&(Fe=je.left-10-ze),Fe<8&&(Fe=Math.min(Math.max(8,je.left),Math.max(8,Ae-ze-8)),Ze=je.bottom+8),z(lt=>lt&<.top===Ze&<.left===Fe&<.width===ze?lt:{top:Ze,left:Fe,width:ze})},P=(se,ce)=>{R(),T(se),A({id:se,mode:ce})},L=se=>{R(),D.current=window.setTimeout(()=>A(ce=>ce&&ce.id===se&&ce.mode!=="pinned"?null:ce),200)},te=(se,ce)=>{if(R(),$&&$.id===se&&$.mode==="pinned"){A(null);return}T(se),A({id:se,mode:"pinned"}),ce&&window.setTimeout(()=>{var je;return(je=M.current)==null?void 0:je.focus()},0)};_.useEffect(()=>()=>R(),[]),a0(()=>{$&&T($.id)},[$==null?void 0:$.id,y.x,y.y,y.w,y.h]);const X=()=>{const se=M.current;if(!se)return;const ce=se.offsetHeight,je=window.innerHeight;z(Ae=>{if(!Ae||Ae.top+ce<=je-8)return Ae;const ze=Math.max(8,je-8-ce);return ze===Ae.top?Ae:{...Ae,top:ze}})};a0(()=>{$&&E&&X()},[$==null?void 0:$.id,E==null?void 0:E.top,E==null?void 0:E.left,E==null?void 0:E.width]);const V=!!E;_.useEffect(()=>{const se=M.current;if(!$||!se||typeof ResizeObserver>"u")return;const ce=new ResizeObserver(()=>X());return ce.observe(se),()=>ce.disconnect()},[$==null?void 0:$.id,V]),_.useEffect(()=>{if(!$)return;const se=Ae=>{var ze;Ae.key==="Escape"&&(A(null),$.mode!=="hover"&&(q.current=!0,(ze=F.current[$.id])==null||ze.focus(),q.current=!1))},ce=Ae=>{var Fe;const ze=Ae.target;ze&&((Fe=M.current)!=null&&Fe.contains(ze))||ze&&typeof ze.closest=="function"&&ze.closest("[data-flow-node]")||A(null)},je=()=>T($.id);return document.addEventListener("keydown",se,!0),document.addEventListener("pointerdown",ce,!0),window.addEventListener("resize",je),window.addEventListener("scroll",je,!0),()=>{document.removeEventListener("keydown",se,!0),document.removeEventListener("pointerdown",ce,!0),window.removeEventListener("resize",je),window.removeEventListener("scroll",je,!0)}},[$==null?void 0:$.id,$==null?void 0:$.mode]);const ne=`${y.x} ${y.y} ${y.w} ${y.h}`,W={};for(const se of d)W[se.id]=se;const Y=se=>{let ce=kn(se).trim();if(!ce)return"";if(W[ce])return ce;for(;ce.includes("::");)if(ce=ce.slice(0,Math.max(0,ce.lastIndexOf("::"))),W[ce])return ce;return""},K=Y(r),fe={};for(const[se,ce]of Object.entries(i)){if(typeof ce!="number")continue;const je=Y(se);je&&(fe[je]=Math.max(fe[je]||0,ce))}const ae={};if(u)for(const[se,ce]of Object.entries(a)){if(typeof ce!="number")continue;const je=Y(se);je&&(ae[je]=typeof ae[je]=="number"?Math.min(ae[je],ce):ce)}const ve=kn(e.schedule_next_in).trim(),ge=kn(e.schedule_interval).trim(),pe=e.node_last_ms&&typeof e.node_last_ms=="object"?e.node_last_ms:{},$e=se=>{try{const ce=new Date(se),je=String(ce.getHours()).padStart(2,"0"),Ae=String(ce.getMinutes()).padStart(2,"0");return`${je}:${Ae}`}catch{return""}},De=(se,ce)=>{var Fe,Ze;const je=kn((Fe=se.meta)==null?void 0:Fe.schedule).trim();if(!(((Ze=se.meta)==null?void 0:Ze.recurrent)===!0))return ce&&ve?`next ${ve}`:je&&je.length<=12&&!je.includes("T")?`in ${je}`:"scheduled";const ze=je||ge;return ze?ce&&ve?`${ze} • next ${ve}`:`every ${ze}`:ce&&ve?`next ${ve}`:"scheduled"},ot=se=>{var ht;const ce=kn((ht=se.meta)==null?void 0:ht.subflow_id).trim(),je=ce&&e.flow_by_id?e.flow_by_id[ce]:null,ze=kn(je==null?void 0:je.name).trim()||ce||se.label||se.id,Fe=typeof pe[se.id]=="number"?Number(pe[se.id]):null,Ze=Fe!==null?$e(Fe):"",lt=Ze?`last ${Ze}`:"subflow";return{label:ze,sub:lt}},bt=(se,ce)=>{let je=se.label||se.id,Ae=se.type;if(se.type==="on_schedule")Ae=De(se,ce);else if(se.type==="subflow"){const ze=ot(se);je=ze.label,Ae=ze.sub}return{label:je,type:Ae}},Ue=kn(e.run_status).trim().toLowerCase(),at=e.run_line||null,Nt=kn(e.run_id).trim(),ut=!!(Ue||at||Nt),Se=Ue?A4.has(Ue):at?at.verb==="done":!1,me=Ue==="failed"||Ue==="cancelled",Ve=e.node_facts||{},ye=e.node_status||VI(Ve),Ie={};for(const[se,ce]of Object.entries(ye)){const je=Y(se);if(!je)continue;let Ae=ce;Se&&(Ae==="running"||Ae==="waiting")&&(Ae=me?"failed":"done");const ze=((mt=Ve[se])==null?void 0:mt.last_ms)??(typeof pe[se]=="number"?pe[se]:0),Fe=Ie[je];if(!Fe){Ie[je]={s:Ae,t:ze};continue}const Ze=zc(Ae),lt=zc(Fe.s);(Ze!==lt?Ze>lt:ze!==Fe.t?ze>Fe.t:Ae==="failed"&&Fe.s!=="failed")&&(Ie[je]={s:Ae,t:ze})}const ct=se=>{var ce;return((ce=Ie[se])==null?void 0:ce.s)||"none"};let ie=K;if(!ie&&ut){let se=null;for(const[ce,je]of Object.entries(Ie))(Se?me&&je.s==="failed":zc(je.s)>0)&&(!se||zc(je.s)>zc(se.s)||zc(je.s)===zc(se.s)&&je.t>se.t)&&(se={id:ce,...je});ie=se?se.id:""}const Te=se=>Se&&Ue==="cancelled"&&se==="failed"?"cancelled here":hN[se],et=new Set;let Ge=null,Be=null;for(const[se,ce]of Object.entries(Ve)){if(!ce||ce.visits<=0)continue;const je=Y(se);je&&et.add(je),ce.first_ms!==null&&(Ge=Ge===null?ce.first_ms:Math.min(Ge,ce.first_ms)),ce.last_ms!==null&&(Be=Be===null?ce.last_ms:Math.max(Be,ce.last_ms))}for(const[se,ce]of Object.entries(a)){if(typeof ce!="number")continue;const je=Y(se);je&&et.add(je)}if(Ge===null||Be===null){const se=Object.values(pe).filter(ce=>typeof ce=="number"&&Number.isFinite(ce));se.length>=2&&(Ge=Math.min(...se),Be=Math.max(...se))}const Rt=Ge!==null&&Be!==null&&Be>=Ge?Be-Ge:null,Nn=se=>se?se==="waiting"?"waiting, reason not loaded":se:"state not loaded",Qt=(at==null?void 0:at.text)||Nn(Ue),rs=_a(Ue||(at?{running:"running",needs_you:"waiting",paused:"paused",waiting:"waiting",scheduled:"scheduled",done:""}[at.verb]??"":"")),Dn=ie?W[ie]:void 0,$n=kn(e.current_node_label).trim()||(Dn?bt(Dn,ie===K).label:""),Cn=!!$n&&(!Se||me),an=`${et.size.toLocaleString("en-US")} node${et.size===1?"":"s"} visited${Rt!==null?` in ${cu(Rt)}`:""}`,is=ut?s.jsxs("div",{className:"flow_banner","data-phase":Se?"finished":"ongoing",children:[s.jsx("span",{className:`chip ${rs}`,children:Se?"finished":"ongoing"}),s.jsx("span",{className:"flow_banner_text",children:Qt}),Cn?s.jsxs("span",{className:"flow_banner_at",children:["· at ",s.jsx("strong",{children:$n})]}):null,Se&&n?s.jsxs("span",{className:"flow_banner_meta",children:["· ",an]}):null]}):s.jsxs("div",{className:"flow_banner","data-phase":"none",children:[s.jsx("span",{className:"chip muted",children:"no run"}),s.jsx("span",{className:"flow_banner_text",children:"the workflow only — open a run to see where it is"})]});if(!n)return ut?s.jsxs("div",{className:"graph_wrap",children:[is,s.jsx("div",{className:"graph_empty mono",children:"(no graph loaded)"})]}):s.jsx("div",{className:"graph_empty mono",children:"(no graph loaded)"});const Wn=(se,ce,je)=>{const Ae=je||x.current,ze=p.current;if(!ze)return{x:se,y:ce};const Fe=ze.getBoundingClientRect(),Ze=Fe.width>0?(se-Fe.left)/Fe.width:0,lt=Fe.height>0?(ce-Fe.top)/Fe.height:0;return{x:Ae.x+Ze*Ae.w,y:Ae.y+lt*Ae.h}},Fn=(se,ce,je)=>{const Ae=je||x.current,ze=Math.max(.12,Math.min(8,ce)),Fe=Ae.w*ze,Ze=Ae.h*ze,lt=Ae.w>0?(se.x-Ae.x)/Ae.w:.5,ht=Ae.h>0?(se.y-Ae.y)/Ae.h:.5,_t=se.x-lt*Fe,kt=se.y-ht*Ze;w(i0({x:_t,y:kt,w:Fe,h:Ze},h))},Hs=(se,ce,je)=>{const Ae=je||x.current,ze=p.current;if(!ze)return;const Fe=ze.getBoundingClientRect(),Ze=.88,lt=Fe.width>0?se/Fe.width*Ae.w*Ze:0,ht=Fe.height>0?ce/Fe.height*Ae.h*Ze:0;w(_t=>i0({x:(je||_t).x-lt,y:(je||_t).y-ht,w:(je||_t).w,h:(je||_t).h},h))},es=(se,ce,je,Ae)=>{const ze=h.node_w,Fe=h.node_h,Ze=Math.abs(je),lt=Math.abs(Ae);if(Ze<1e-6&<<1e-6)return{x:se,y:ce};const ht=Ze>1e-6?ze/2/Ze:Number.POSITIVE_INFINITY,_t=lt>1e-6?Fe/2/lt:Number.POSITIVE_INFINITY,kt=Math.min(ht,_t);return{x:se+je*kt,y:ce+Ae*kt}},he=()=>JSON.stringify(YI({run_id:Nt,status:Ue,state:Qt,finished:Se,now_ms:t,current_id:ie,nodes:d.map(se=>({id:se.id,label:bt(se,!1).label,type:se.type})),edges:m,facts:Ve,status_of:ct}),null,2),Ee=$?W[$.id]:void 0;return s.jsxs("div",{className:"graph_wrap",children:[is,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:h.x,y:h.y,w:h.w,h:h.h}),title:"Recenter",children:"⤢"}),s.jsx("button",{className:"btn graph_corner_btn",type:"button",onClick:()=>{const se=p.current;if(!se)return;const ce=se.getBoundingClientRect(),je=Wn(ce.left+ce.width/2,ce.top+ce.height/2);Fn(je,.84)},title:"Zoom in",children:"+"}),s.jsx("button",{className:"btn graph_corner_btn",type:"button",onClick:()=>{const se=p.current;if(!se)return;const ce=se.getBoundingClientRect(),je=Wn(ce.left+ce.width/2,ce.top+ce.height/2);Fn(je,1.18)},title:"Zoom out",children:"−"}),s.jsx(fp,{className:"btn graph_corner_btn flow_copy_state_btn",title:"Copy run state (JSON: where the run is and what each node did)",label:"⧉",copied:"✓",failed:"!",get_text:he})]}),s.jsx(QI,{})]}),s.jsxs("svg",{ref:p,className:"graph_svg",viewBox:ne,role:"group","aria-label":"Workflow execution graph",onWheel:se=>{se.preventDefault();const ce=Wn(se.clientX,se.clientY),je=typeof se.deltaY=="number"?se.deltaY:0,Ae=typeof se.deltaMode=="number"?Number(se.deltaMode):0,ze=Ae===1?je*24:Ae===2?je*800:je,Fe=45e-5*1.15*1.1;let Ze=Math.exp(ze*Fe);Ze=Math.max(.86,Math.min(1.16,Ze)),Fn(ce,Ze)},onPointerDown:se=>{var je,Ae;(Ae=(je=se.currentTarget).setPointerCapture)==null||Ae.call(je,se.pointerId),k.current.set(se.pointerId,{x:se.clientX,y:se.clientY});const ce=Array.from(k.current.values());if(ce.length===1)b.current={mode:"pan",start_view:x.current,start_client:{x:se.clientX,y:se.clientY},start_dist:0,anchor_svg:{x:0,y:0}};else if(ce.length>=2){H.current=null;const ze=ce[0],Fe=ce[1],Ze=ze.x-Fe.x,lt=ze.y-Fe.y,ht=Math.max(1,Math.hypot(Ze,lt)),_t={x:(ze.x+Fe.x)/2,y:(ze.y+Fe.y)/2},kt=x.current;b.current={mode:"pinch",start_view:kt,start_client:_t,start_dist:ht,anchor_svg:Wn(_t.x,_t.y,kt)}}},onPointerMove:se=>{if(!k.current.has(se.pointerId))return;k.current.set(se.pointerId,{x:se.clientX,y:se.clientY});const ce=b.current;if(!ce)return;const je=Array.from(k.current.values());if(ce.mode==="pan"&&je.length===1){const Ae=se.clientX-ce.start_client.x,ze=se.clientY-ce.start_client.y;Hs(Ae,ze,ce.start_view)}else if(ce.mode==="pinch"&&je.length>=2){const Ae=je[0],ze=je[1],Fe=Ae.x-ze.x,Ze=Ae.y-ze.y,lt=Math.max(1,Math.hypot(Fe,Ze)),ht=ce.start_dist/lt;Fn(ce.anchor_svg,ht,ce.start_view)}},onPointerUp:se=>{k.current.delete(se.pointerId),k.current.size===0&&(b.current=null);const ce=H.current;H.current=null,ce&&k.current.size===0&&Math.hypot(se.clientX-ce.x,se.clientY-ce.y)<5&&te(ce.id,!1)},onPointerCancel:se=>{k.current.delete(se.pointerId),k.current.size===0&&(b.current=null),H.current=null},children:[s.jsxs("defs",{children:[s.jsx("marker",{id:"arrow",viewBox:"0 0 10 10",refX:"9",refY:"5",markerWidth:"8",markerHeight:"8",orient:"auto-start-reverse",children:s.jsx("path",{d:"M 0 0 L 10 5 L 0 10 z",fill:"rgba(148,163,184,0.55)"})}),s.jsxs("filter",{id:"glow",children:[s.jsx("feGaussianBlur",{stdDeviation:"3",result:"coloredBlur"}),s.jsxs("feMerge",{children:[s.jsx("feMergeNode",{in:"coloredBlur"}),s.jsx("feMergeNode",{in:"SourceGraphic"})]})]})]}),m.map(se=>{const ce=W[se.source],je=W[se.target];if(!ce||!je)return null;const Ae=ce.x+h.node_w/2,ze=ce.y+h.node_h/2,Fe=je.x+h.node_w/2,Ze=je.y+h.node_h/2,lt=Fe-Ae,ht=Ze-ze,_t=es(Ae,ze,lt,ht),kt=es(Fe,Ze,-lt,-ht),At=se.source!==se.target&&S.has(`${se.target}->${se.source}`),rt=Math.max(1,Math.hypot(lt,ht)),zt=-ht/rt,dn=lt/rt,on=String(se.source)<String(se.target)?1:-1,Ot=Math.abs(lt)>=Math.abs(ht)?lt>=0:ht>=0,ts=!At||Ot,Pe=Math.max(28,Math.min(72,rt*.14)),Ut=Math.min(200,Pe*3.5),St=At&&!ts?Ut*on:0,Mn=(_t.x+kt.x)/2+zt*St,nn=(_t.y+kt.y)/2+dn*St,Je=At&&!ts?`M ${_t.x} ${_t.y} Q ${Mn} ${nn} ${kt.x} ${kt.y}`:`M ${_t.x} ${_t.y} L ${kt.x} ${kt.y}`,en=u&&ae&&ae[se.source]!==void 0&&ae[se.target]!==void 0;return s.jsx("path",{d:Je,className:`graph_edge ${en?"visited":""}`,markerEnd:"url(#arrow)",fill:"none"},se.id)}),d.map(se=>{const je=(typeof fe[se.id]=="number"?fe[se.id]:0)>t,Ae=K&&se.id===K,ze=u&&ae&&ae[se.id]!==void 0,Fe=ct(se.id),Ze=!!ie&&se.id===ie,lt=`graph_node ${Ae?"active":je?"recent":""} ${ze?"visited":""}${Ze?" here":""}`,ht=se.color||"rgba(255,255,255,0.16)",{label:_t,type:kt}=bt(se,!!Ae),At=r0(_t,22),rt=r0(kt,22),zt=Ze?Te(Fe):"",dn=zt?Math.round(zt.length*6.2+14):0,on=Fe==="waiting"?gN(Ve[se.id]):_N[Fe],Ht=($==null?void 0:$.id)===se.id;return s.jsxs("g",{ref:Ot=>{F.current[se.id]=Ot},className:lt,transform:`translate(${se.x}, ${se.y})`,"data-flow-node":se.id,"data-run-status":Fe,tabIndex:0,role:"button","aria-label":`${_t} (${kt}): ${on}${zt?`, ${zt}`:""}`,"aria-haspopup":"dialog","aria-expanded":Ht,"aria-describedby":Ht?Z:void 0,onPointerDown:Ot=>{H.current={id:se.id,x:Ot.clientX,y:Ot.clientY}},onMouseEnter:()=>{($==null?void 0:$.mode)!=="pinned"&&(R(),!Ht&&(D.current=window.setTimeout(()=>{b.current||P(se.id,"hover")},150)))},onMouseLeave:()=>{Ht&&($==null?void 0:$.mode)==="hover"?L(se.id):($==null?void 0:$.mode)!=="pinned"&&R()},onFocus:()=>{q.current||Ht&&($==null?void 0:$.mode)==="pinned"||P(se.id,"focus")},onBlur:Ot=>{var ts;Ht&&($==null?void 0:$.mode)==="focus"&&!((ts=M.current)!=null&&ts.contains(Ot.relatedTarget))&&L(se.id)},onKeyDown:Ot=>{Ot.key!=="Enter"&&Ot.key!==" "||(Ot.preventDefault(),te(se.id,!0))},children:[Fe==="running"||Fe==="waiting"||Fe==="failed"||Ze?s.jsx("rect",{className:"flow_node_ring",x:-5,y:-5,width:h.node_w+10,height:h.node_h+10,rx:16,ry:16}):null,s.jsx("rect",{className:"graph_node_bg",width:h.node_w,height:h.node_h,rx:12,ry:12}),s.jsx("rect",{className:"graph_node_bar",width:h.node_w,height:6,rx:12,ry:12,fill:ht}),s.jsx("text",{className:"graph_node_label",x:12,y:28,children:At}),s.jsx("text",{className:"graph_node_type",x:12,y:46,children:rt}),se.type==="on_schedule"?s.jsx("text",{className:"graph_node_icon",x:h.node_w-18,y:18,children:"⏰"}):null,Fe!=="none"?s.jsx("g",{className:"flow_status_badge",transform:`translate(${h.node_w-12}, 0)`,"aria-hidden":"true",children:s.jsx(T4,{status:Fe})}):null,zt?s.jsxs("g",{className:"flow_here_chip",transform:`translate(${h.node_w-26-dn}, -9)`,"aria-hidden":"true",children:[s.jsx("rect",{width:dn,height:18,rx:9,ry:9}),s.jsx("text",{x:7,y:12.5,children:zt})]}):null]},se.id)})]}),$&&Ee&&E&&typeof document<"u"?Xp.createPortal(s.jsx("div",{ref:M,id:Z,className:"flow_facts_pop",role:"dialog","aria-label":`About the node ${bt(Ee,Ee.id===K).label}`,tabIndex:-1,style:{top:E.top,left:E.left,width:E.width},onMouseEnter:R,onMouseLeave:()=>$.mode==="hover"?L($.id):void 0,onBlur:se=>{$.mode==="focus"&&!se.currentTarget.contains(se.relatedTarget)&&L($.id)},children:s.jsx(R4,{node:{id:Ee.id,...bt(Ee,Ee.id===K)},facts:Ve[Ee.id]||null,status:ct(Ee.id),here:Ee.id===ie,finished:Se,on_open_run:e.on_open_run})}),document.body):null]})}function $r(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=$r(e[n]))!==""&&(t+=(t&&" ")+r);else for(let n in e)e[n]&&(t+=(t&&" ")+n);return t}var _y={exports:{}},py={},gy={exports:{}},yy={};/**
|
|
136
|
+
* @license React
|
|
137
|
+
* use-sync-external-store-shim.production.js
|
|
138
|
+
*
|
|
139
|
+
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
|
140
|
+
*
|
|
141
|
+
* This source code is licensed under the MIT license found in the
|
|
142
|
+
* LICENSE file in the root directory of this source tree.
|
|
143
|
+
*/var c0;function I4(){if(c0)return yy;c0=1;var e=rh();function t(p,y){return p===y&&(p!==0||1/p===1/y)||p!==p&&y!==y}var n=typeof Object.is=="function"?Object.is:t,r=e.useState,i=e.useEffect,a=e.useLayoutEffect,u=e.useDebugValue;function c(p,y){var w=y(),x=r({inst:{value:w,getSnapshot:y}}),k=x[0].inst,b=x[1];return a(function(){k.value=w,k.getSnapshot=y,d(k)&&b({inst:k})},[p,w,y]),i(function(){return d(k)&&b({inst:k}),p(function(){d(k)&&b({inst:k})})},[p]),u(w),w}function d(p){var y=p.getSnapshot;p=p.value;try{var w=y();return!n(p,w)}catch{return!0}}function m(p,y){return y()}var h=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?m:c;return yy.useSyncExternalStore=e.useSyncExternalStore!==void 0?e.useSyncExternalStore:h,yy}var u0;function O4(){return u0||(u0=1,gy.exports=I4()),gy.exports}/**
|
|
144
|
+
* @license React
|
|
145
|
+
* use-sync-external-store-shim/with-selector.production.js
|
|
146
|
+
*
|
|
147
|
+
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
|
148
|
+
*
|
|
149
|
+
* This source code is licensed under the MIT license found in the
|
|
150
|
+
* LICENSE file in the root directory of this source tree.
|
|
151
|
+
*/var d0;function P4(){if(d0)return py;d0=1;var e=rh(),t=O4();function n(m,h){return m===h&&(m!==0||1/m===1/h)||m!==m&&h!==h}var r=typeof Object.is=="function"?Object.is:n,i=t.useSyncExternalStore,a=e.useRef,u=e.useEffect,c=e.useMemo,d=e.useDebugValue;return py.useSyncExternalStoreWithSelector=function(m,h,p,y,w){var x=a(null);if(x.current===null){var k={hasValue:!1,value:null};x.current=k}else k=x.current;x=c(function(){function S(F){if(!$){if($=!0,A=F,F=y(F),w!==void 0&&k.hasValue){var M=k.value;if(w(M,F))return E=M}return E=F}if(M=E,r(A,F))return M;var D=y(F);return w!==void 0&&w(M,D)?(A=F,M):(A=F,E=D)}var $=!1,A,E,z=p===void 0?null:p;return[function(){return S(h())},z===null?void 0:function(){return S(z())}]},[h,p,y,w]);var b=i(m,x[0],x[1]);return u(function(){k.hasValue=!0,k.value=b},[b]),d(b),b},py}var f0;function D4(){return f0||(f0=1,_y.exports=P4()),_y.exports}var F4=D4();const z4=iv(F4),B4={},m0=e=>{let t;const n=new Set,r=(h,p)=>{const y=typeof h=="function"?h(t):h;if(!Object.is(y,t)){const w=t;t=p??(typeof y!="object"||y===null)?y:Object.assign({},t,y),n.forEach(x=>x(t,w))}},i=()=>t,d={setState:r,getState:i,getInitialState:()=>m,subscribe:h=>(n.add(h),()=>n.delete(h)),destroy:()=>{(B4?"production":void 0)!=="production"&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),n.clear()}},m=t=e(r,i,d);return d},U4=e=>e?m0(e):m0,{useDebugValue:W4}=Ne,{useSyncExternalStoreWithSelector:q4}=z4,H4=e=>e;function yN(e,t=H4,n){const r=q4(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return W4(r),r}const h0=(e,t)=>{const n=U4(e),r=(i,a=t)=>yN(n,i,a);return Object.assign(r,n),r},V4=(e,t)=>e?h0(e,t):h0;function hr(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,i]of e)if(!Object.is(i,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 G4={value:()=>{}};function fg(){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 mp(n)}function mp(e){this._=e}function K4(e,t){return e.trim().split(/^|\s+/).map(function(n){var r="",i=n.indexOf(".");if(i>=0&&(r=n.slice(i+1),n=n.slice(0,i)),n&&!t.hasOwnProperty(n))throw new Error("unknown type: "+n);return{type:n,name:r}})}mp.prototype=fg.prototype={constructor:mp,on:function(e,t){var n=this._,r=K4(e+"",n),i,a=-1,u=r.length;if(arguments.length<2){for(;++a<u;)if((i=(e=r[a]).type)&&(i=J4(n[i],e.name)))return i;return}if(t!=null&&typeof t!="function")throw new Error("invalid callback: "+t);for(;++a<u;)if(i=(e=r[a]).type)n[i]=_0(n[i],e.name,t);else if(t==null)for(i in n)n[i]=_0(n[i],e.name,null);return this},copy:function(){var e={},t=this._;for(var n in t)e[n]=t[n].slice();return new mp(e)},call:function(e,t){if((i=arguments.length-2)>0)for(var n=new Array(i),r=0,i,a;r<i;++r)n[r]=arguments[r+2];if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(a=this._[e],r=0,i=a.length;r<i;++r)a[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],i=0,a=r.length;i<a;++i)r[i].value.apply(t,n)}};function J4(e,t){for(var n=0,r=e.length,i;n<r;++n)if((i=e[n]).name===t)return i.value}function _0(e,t,n){for(var r=0,i=e.length;r<i;++r)if(e[r].name===t){e[r]=G4,e=e.slice(0,r).concat(e.slice(r+1));break}return n!=null&&e.push({name:t,value:n}),e}var Sw="http://www.w3.org/1999/xhtml";const p0={svg:"http://www.w3.org/2000/svg",xhtml:Sw,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function mg(e){var t=e+="",n=t.indexOf(":");return n>=0&&(t=e.slice(0,n))!=="xmlns"&&(e=e.slice(n+1)),p0.hasOwnProperty(t)?{space:p0[t],local:e}:e}function Y4(e){return function(){var t=this.ownerDocument,n=this.namespaceURI;return n===Sw&&t.documentElement.namespaceURI===Sw?t.createElement(e):t.createElementNS(n,e)}}function X4(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function wN(e){var t=mg(e);return(t.local?X4:Y4)(t)}function Z4(){}function Iv(e){return e==null?Z4:function(){return this.querySelector(e)}}function Q4(e){typeof e!="function"&&(e=Iv(e));for(var t=this._groups,n=t.length,r=new Array(n),i=0;i<n;++i)for(var a=t[i],u=a.length,c=r[i]=new Array(u),d,m,h=0;h<u;++h)(d=a[h])&&(m=e.call(d,d.__data__,h,a))&&("__data__"in d&&(m.__data__=d.__data__),c[h]=m);return new Di(r,this._parents)}function eO(e){return e==null?[]:Array.isArray(e)?e:Array.from(e)}function tO(){return[]}function vN(e){return e==null?tO:function(){return this.querySelectorAll(e)}}function nO(e){return function(){return eO(e.apply(this,arguments))}}function sO(e){typeof e=="function"?e=nO(e):e=vN(e);for(var t=this._groups,n=t.length,r=[],i=[],a=0;a<n;++a)for(var u=t[a],c=u.length,d,m=0;m<c;++m)(d=u[m])&&(r.push(e.call(d,d.__data__,m,u)),i.push(d));return new Di(r,i)}function xN(e){return function(){return this.matches(e)}}function bN(e){return function(t){return t.matches(e)}}var rO=Array.prototype.find;function iO(e){return function(){return rO.call(this.children,e)}}function oO(){return this.firstElementChild}function aO(e){return this.select(e==null?oO:iO(typeof e=="function"?e:bN(e)))}var lO=Array.prototype.filter;function cO(){return Array.from(this.children)}function uO(e){return function(){return lO.call(this.children,e)}}function dO(e){return this.selectAll(e==null?cO:uO(typeof e=="function"?e:bN(e)))}function fO(e){typeof e!="function"&&(e=xN(e));for(var t=this._groups,n=t.length,r=new Array(n),i=0;i<n;++i)for(var a=t[i],u=a.length,c=r[i]=[],d,m=0;m<u;++m)(d=a[m])&&e.call(d,d.__data__,m,a)&&c.push(d);return new Di(r,this._parents)}function kN(e){return new Array(e.length)}function mO(){return new Di(this._enter||this._groups.map(kN),this._parents)}function Op(e,t){this.ownerDocument=e.ownerDocument,this.namespaceURI=e.namespaceURI,this._next=null,this._parent=e,this.__data__=t}Op.prototype={constructor:Op,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 hO(e){return function(){return e}}function _O(e,t,n,r,i,a){for(var u=0,c,d=t.length,m=a.length;u<m;++u)(c=t[u])?(c.__data__=a[u],r[u]=c):n[u]=new Op(e,a[u]);for(;u<d;++u)(c=t[u])&&(i[u]=c)}function pO(e,t,n,r,i,a,u){var c,d,m=new Map,h=t.length,p=a.length,y=new Array(h),w;for(c=0;c<h;++c)(d=t[c])&&(y[c]=w=u.call(d,d.__data__,c,t)+"",m.has(w)?i[c]=d:m.set(w,d));for(c=0;c<p;++c)w=u.call(e,a[c],c,a)+"",(d=m.get(w))?(r[c]=d,d.__data__=a[c],m.delete(w)):n[c]=new Op(e,a[c]);for(c=0;c<h;++c)(d=t[c])&&m.get(y[c])===d&&(i[c]=d)}function gO(e){return e.__data__}function yO(e,t){if(!arguments.length)return Array.from(this,gO);var n=t?pO:_O,r=this._parents,i=this._groups;typeof e!="function"&&(e=hO(e));for(var a=i.length,u=new Array(a),c=new Array(a),d=new Array(a),m=0;m<a;++m){var h=r[m],p=i[m],y=p.length,w=wO(e.call(h,h&&h.__data__,m,r)),x=w.length,k=c[m]=new Array(x),b=u[m]=new Array(x),S=d[m]=new Array(y);n(h,p,k,b,S,w,t);for(var $=0,A=0,E,z;$<x;++$)if(E=k[$]){for($>=A&&(A=$+1);!(z=b[A])&&++A<x;);E._next=z||null}}return u=new Di(u,r),u._enter=c,u._exit=d,u}function wO(e){return typeof e=="object"&&"length"in e?e:Array.from(e)}function vO(){return new Di(this._exit||this._groups.map(kN),this._parents)}function xO(e,t,n){var r=this.enter(),i=this,a=this.exit();return typeof e=="function"?(r=e(r),r&&(r=r.selection())):r=r.append(e+""),t!=null&&(i=t(i),i&&(i=i.selection())),n==null?a.remove():n(a),r&&i?r.merge(i).order():i}function bO(e){for(var t=e.selection?e.selection():e,n=this._groups,r=t._groups,i=n.length,a=r.length,u=Math.min(i,a),c=new Array(i),d=0;d<u;++d)for(var m=n[d],h=r[d],p=m.length,y=c[d]=new Array(p),w,x=0;x<p;++x)(w=m[x]||h[x])&&(y[x]=w);for(;d<i;++d)c[d]=n[d];return new Di(c,this._parents)}function kO(){for(var e=this._groups,t=-1,n=e.length;++t<n;)for(var r=e[t],i=r.length-1,a=r[i],u;--i>=0;)(u=r[i])&&(a&&u.compareDocumentPosition(a)^4&&a.parentNode.insertBefore(u,a),a=u);return this}function jO(e){e||(e=SO);function t(p,y){return p&&y?e(p.__data__,y.__data__):!p-!y}for(var n=this._groups,r=n.length,i=new Array(r),a=0;a<r;++a){for(var u=n[a],c=u.length,d=i[a]=new Array(c),m,h=0;h<c;++h)(m=u[h])&&(d[h]=m);d.sort(t)}return new Di(i,this._parents).order()}function SO(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}function NO(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this}function $O(){return Array.from(this)}function CO(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var r=e[t],i=0,a=r.length;i<a;++i){var u=r[i];if(u)return u}return null}function EO(){let e=0;for(const t of this)++e;return e}function AO(){return!this.node()}function TO(e){for(var t=this._groups,n=0,r=t.length;n<r;++n)for(var i=t[n],a=0,u=i.length,c;a<u;++a)(c=i[a])&&e.call(c,c.__data__,a,i);return this}function MO(e){return function(){this.removeAttribute(e)}}function RO(e){return function(){this.removeAttributeNS(e.space,e.local)}}function LO(e,t){return function(){this.setAttribute(e,t)}}function IO(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function OO(e,t){return function(){var n=t.apply(this,arguments);n==null?this.removeAttribute(e):this.setAttribute(e,n)}}function PO(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 DO(e,t){var n=mg(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?RO:MO:typeof t=="function"?n.local?PO:OO:n.local?IO:LO)(n,t))}function jN(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function FO(e){return function(){this.style.removeProperty(e)}}function zO(e,t,n){return function(){this.style.setProperty(e,t,n)}}function BO(e,t,n){return function(){var r=t.apply(this,arguments);r==null?this.style.removeProperty(e):this.style.setProperty(e,r,n)}}function UO(e,t,n){return arguments.length>1?this.each((t==null?FO:typeof t=="function"?BO:zO)(e,t,n??"")):Gd(this.node(),e)}function Gd(e,t){return e.style.getPropertyValue(t)||jN(e).getComputedStyle(e,null).getPropertyValue(t)}function WO(e){return function(){delete this[e]}}function qO(e,t){return function(){this[e]=t}}function HO(e,t){return function(){var n=t.apply(this,arguments);n==null?delete this[e]:this[e]=n}}function VO(e,t){return arguments.length>1?this.each((t==null?WO:typeof t=="function"?HO:qO)(e,t)):this.node()[e]}function SN(e){return e.trim().split(/^|\s+/)}function Ov(e){return e.classList||new NN(e)}function NN(e){this._node=e,this._names=SN(e.getAttribute("class")||"")}NN.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 $N(e,t){for(var n=Ov(e),r=-1,i=t.length;++r<i;)n.add(t[r])}function CN(e,t){for(var n=Ov(e),r=-1,i=t.length;++r<i;)n.remove(t[r])}function GO(e){return function(){$N(this,e)}}function KO(e){return function(){CN(this,e)}}function JO(e,t){return function(){(t.apply(this,arguments)?$N:CN)(this,e)}}function YO(e,t){var n=SN(e+"");if(arguments.length<2){for(var r=Ov(this.node()),i=-1,a=n.length;++i<a;)if(!r.contains(n[i]))return!1;return!0}return this.each((typeof t=="function"?JO:t?GO:KO)(n,t))}function XO(){this.textContent=""}function ZO(e){return function(){this.textContent=e}}function QO(e){return function(){var t=e.apply(this,arguments);this.textContent=t??""}}function e5(e){return arguments.length?this.each(e==null?XO:(typeof e=="function"?QO:ZO)(e)):this.node().textContent}function t5(){this.innerHTML=""}function n5(e){return function(){this.innerHTML=e}}function s5(e){return function(){var t=e.apply(this,arguments);this.innerHTML=t??""}}function r5(e){return arguments.length?this.each(e==null?t5:(typeof e=="function"?s5:n5)(e)):this.node().innerHTML}function i5(){this.nextSibling&&this.parentNode.appendChild(this)}function o5(){return this.each(i5)}function a5(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function l5(){return this.each(a5)}function c5(e){var t=typeof e=="function"?e:wN(e);return this.select(function(){return this.appendChild(t.apply(this,arguments))})}function u5(){return null}function d5(e,t){var n=typeof e=="function"?e:wN(e),r=t==null?u5:typeof t=="function"?t:Iv(t);return this.select(function(){return this.insertBefore(n.apply(this,arguments),r.apply(this,arguments)||null)})}function f5(){var e=this.parentNode;e&&e.removeChild(this)}function m5(){return this.each(f5)}function h5(){var e=this.cloneNode(!1),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function _5(){var e=this.cloneNode(!0),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function p5(e){return this.select(e?_5:h5)}function g5(e){return arguments.length?this.property("__data__",e):this.node().__data__}function y5(e){return function(t){e.call(this,t,this.__data__)}}function w5(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 v5(e){return function(){var t=this.__on;if(t){for(var n=0,r=-1,i=t.length,a;n<i;++n)a=t[n],(!e.type||a.type===e.type)&&a.name===e.name?this.removeEventListener(a.type,a.listener,a.options):t[++r]=a;++r?t.length=r:delete this.__on}}}function x5(e,t,n){return function(){var r=this.__on,i,a=y5(t);if(r){for(var u=0,c=r.length;u<c;++u)if((i=r[u]).type===e.type&&i.name===e.name){this.removeEventListener(i.type,i.listener,i.options),this.addEventListener(i.type,i.listener=a,i.options=n),i.value=t;return}}this.addEventListener(e.type,a,n),i={type:e.type,name:e.name,value:t,listener:a,options:n},r?r.push(i):this.__on=[i]}}function b5(e,t,n){var r=w5(e+""),i,a=r.length,u;if(arguments.length<2){var c=this.node().__on;if(c){for(var d=0,m=c.length,h;d<m;++d)for(i=0,h=c[d];i<a;++i)if((u=r[i]).type===h.type&&u.name===h.name)return h.value}return}for(c=t?x5:v5,i=0;i<a;++i)this.each(c(r[i],t,n));return this}function EN(e,t,n){var r=jN(e),i=r.CustomEvent;typeof i=="function"?i=new i(t,n):(i=r.document.createEvent("Event"),n?(i.initEvent(t,n.bubbles,n.cancelable),i.detail=n.detail):i.initEvent(t,!1,!1)),e.dispatchEvent(i)}function k5(e,t){return function(){return EN(this,e,t)}}function j5(e,t){return function(){return EN(this,e,t.apply(this,arguments))}}function S5(e,t){return this.each((typeof t=="function"?j5:k5)(e,t))}function*N5(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var r=e[t],i=0,a=r.length,u;i<a;++i)(u=r[i])&&(yield u)}var AN=[null];function Di(e,t){this._groups=e,this._parents=t}function ph(){return new Di([[document.documentElement]],AN)}function $5(){return this}Di.prototype=ph.prototype={constructor:Di,select:Q4,selectAll:sO,selectChild:aO,selectChildren:dO,filter:fO,data:yO,enter:mO,exit:vO,join:xO,merge:bO,selection:$5,order:kO,sort:jO,call:NO,nodes:$O,node:CO,size:EO,empty:AO,each:TO,attr:DO,style:UO,property:VO,classed:YO,text:e5,html:r5,raise:o5,lower:l5,append:c5,insert:d5,remove:m5,clone:p5,datum:g5,on:b5,dispatch:S5,[Symbol.iterator]:N5};function mo(e){return typeof e=="string"?new Di([[document.querySelector(e)]],[document.documentElement]):new Di([[e]],AN)}function C5(e){let t;for(;t=e.sourceEvent;)e=t;return e}function zo(e,t){if(e=C5(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 i=t.getBoundingClientRect();return[e.clientX-i.left-t.clientLeft,e.clientY-i.top-t.clientTop]}}return[e.pageX,e.pageY]}const E5={passive:!1},Vm={capture:!0,passive:!1};function wy(e){e.stopImmediatePropagation()}function Dd(e){e.preventDefault(),e.stopImmediatePropagation()}function TN(e){var t=e.document.documentElement,n=mo(e).on("dragstart.drag",Dd,Vm);"onselectstart"in t?n.on("selectstart.drag",Dd,Vm):(t.__noselect=t.style.MozUserSelect,t.style.MozUserSelect="none")}function MN(e,t){var n=e.document.documentElement,r=mo(e).on("dragstart.drag",null);t&&(r.on("click.drag",Dd,Vm),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 q_=e=>()=>e;function Nw(e,{sourceEvent:t,subject:n,target:r,identifier:i,active:a,x:u,y:c,dx:d,dy:m,dispatch:h}){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:i,enumerable:!0,configurable:!0},active:{value:a,enumerable:!0,configurable:!0},x:{value:u,enumerable:!0,configurable:!0},y:{value:c,enumerable:!0,configurable:!0},dx:{value:d,enumerable:!0,configurable:!0},dy:{value:m,enumerable:!0,configurable:!0},_:{value:h}})}Nw.prototype.on=function(){var e=this._.on.apply(this._,arguments);return e===this._?this:e};function A5(e){return!e.ctrlKey&&!e.button}function T5(){return this.parentNode}function M5(e,t){return t??{x:e.x,y:e.y}}function R5(){return navigator.maxTouchPoints||"ontouchstart"in this}function L5(){var e=A5,t=T5,n=M5,r=R5,i={},a=fg("start","drag","end"),u=0,c,d,m,h,p=0;function y(E){E.on("mousedown.drag",w).filter(r).on("touchstart.drag",b).on("touchmove.drag",S,E5).on("touchend.drag touchcancel.drag",$).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function w(E,z){if(!(h||!e.call(this,E,z))){var F=A(this,t.call(this,E,z),E,z,"mouse");F&&(mo(E.view).on("mousemove.drag",x,Vm).on("mouseup.drag",k,Vm),TN(E.view),wy(E),m=!1,c=E.clientX,d=E.clientY,F("start",E))}}function x(E){if(Dd(E),!m){var z=E.clientX-c,F=E.clientY-d;m=z*z+F*F>p}i.mouse("drag",E)}function k(E){mo(E.view).on("mousemove.drag mouseup.drag",null),MN(E.view,m),Dd(E),i.mouse("end",E)}function b(E,z){if(e.call(this,E,z)){var F=E.changedTouches,M=t.call(this,E,z),D=F.length,H,q;for(H=0;H<D;++H)(q=A(this,M,E,z,F[H].identifier,F[H]))&&(wy(E),q("start",E,F[H]))}}function S(E){var z=E.changedTouches,F=z.length,M,D;for(M=0;M<F;++M)(D=i[z[M].identifier])&&(Dd(E),D("drag",E,z[M]))}function $(E){var z=E.changedTouches,F=z.length,M,D;for(h&&clearTimeout(h),h=setTimeout(function(){h=null},500),M=0;M<F;++M)(D=i[z[M].identifier])&&(wy(E),D("end",E,z[M]))}function A(E,z,F,M,D,H){var q=a.copy(),I=zo(H||F,z),Z,R,T;if((T=n.call(E,new Nw("beforestart",{sourceEvent:F,target:y,identifier:D,active:u,x:I[0],y:I[1],dx:0,dy:0,dispatch:q}),M))!=null)return Z=T.x-I[0]||0,R=T.y-I[1]||0,function P(L,te,X){var V=I,ne;switch(L){case"start":i[D]=P,ne=u++;break;case"end":delete i[D],--u;case"drag":I=zo(X||te,z),ne=u;break}q.call(L,E,new Nw(L,{sourceEvent:te,subject:T,target:y,identifier:D,active:ne,x:I[0]+Z,y:I[1]+R,dx:I[0]-V[0],dy:I[1]-V[1],dispatch:q}),M)}}return y.filter=function(E){return arguments.length?(e=typeof E=="function"?E:q_(!!E),y):e},y.container=function(E){return arguments.length?(t=typeof E=="function"?E:q_(E),y):t},y.subject=function(E){return arguments.length?(n=typeof E=="function"?E:q_(E),y):n},y.touchable=function(E){return arguments.length?(r=typeof E=="function"?E:q_(!!E),y):r},y.on=function(){var E=a.on.apply(a,arguments);return E===a?y:E},y.clickDistance=function(E){return arguments.length?(p=(E=+E)*E,y):Math.sqrt(p)},y}function Pv(e,t,n){e.prototype=t.prototype=n,n.constructor=e}function RN(e,t){var n=Object.create(e.prototype);for(var r in t)n[r]=t[r];return n}function gh(){}var Gm=.7,Pp=1/Gm,Fd="\\s*([+-]?\\d+)\\s*",Km="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",ha="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",I5=/^#([0-9a-f]{3,8})$/,O5=new RegExp(`^rgb\\(${Fd},${Fd},${Fd}\\)$`),P5=new RegExp(`^rgb\\(${ha},${ha},${ha}\\)$`),D5=new RegExp(`^rgba\\(${Fd},${Fd},${Fd},${Km}\\)$`),F5=new RegExp(`^rgba\\(${ha},${ha},${ha},${Km}\\)$`),z5=new RegExp(`^hsl\\(${Km},${ha},${ha}\\)$`),B5=new RegExp(`^hsla\\(${Km},${ha},${ha},${Km}\\)$`),g0={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};Pv(gh,Jm,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:y0,formatHex:y0,formatHex8:U5,formatHsl:W5,formatRgb:w0,toString:w0});function y0(){return this.rgb().formatHex()}function U5(){return this.rgb().formatHex8()}function W5(){return LN(this).formatHsl()}function w0(){return this.rgb().formatRgb()}function Jm(e){var t,n;return e=(e+"").trim().toLowerCase(),(t=I5.exec(e))?(n=t[1].length,t=parseInt(t[1],16),n===6?v0(t):n===3?new vi(t>>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):n===8?H_(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?H_(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=O5.exec(e))?new vi(t[1],t[2],t[3],1):(t=P5.exec(e))?new vi(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=D5.exec(e))?H_(t[1],t[2],t[3],t[4]):(t=F5.exec(e))?H_(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=z5.exec(e))?k0(t[1],t[2]/100,t[3]/100,1):(t=B5.exec(e))?k0(t[1],t[2]/100,t[3]/100,t[4]):g0.hasOwnProperty(e)?v0(g0[e]):e==="transparent"?new vi(NaN,NaN,NaN,0):null}function v0(e){return new vi(e>>16&255,e>>8&255,e&255,1)}function H_(e,t,n,r){return r<=0&&(e=t=n=NaN),new vi(e,t,n,r)}function q5(e){return e instanceof gh||(e=Jm(e)),e?(e=e.rgb(),new vi(e.r,e.g,e.b,e.opacity)):new vi}function $w(e,t,n,r){return arguments.length===1?q5(e):new vi(e,t,n,r??1)}function vi(e,t,n,r){this.r=+e,this.g=+t,this.b=+n,this.opacity=+r}Pv(vi,$w,RN(gh,{brighter(e){return e=e==null?Pp:Math.pow(Pp,e),new vi(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=e==null?Gm:Math.pow(Gm,e),new vi(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new vi(Zc(this.r),Zc(this.g),Zc(this.b),Dp(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:x0,formatHex:x0,formatHex8:H5,formatRgb:b0,toString:b0}));function x0(){return`#${Gc(this.r)}${Gc(this.g)}${Gc(this.b)}`}function H5(){return`#${Gc(this.r)}${Gc(this.g)}${Gc(this.b)}${Gc((isNaN(this.opacity)?1:this.opacity)*255)}`}function b0(){const e=Dp(this.opacity);return`${e===1?"rgb(":"rgba("}${Zc(this.r)}, ${Zc(this.g)}, ${Zc(this.b)}${e===1?")":`, ${e})`}`}function Dp(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function Zc(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function Gc(e){return e=Zc(e),(e<16?"0":"")+e.toString(16)}function k0(e,t,n,r){return r<=0?e=t=n=NaN:n<=0||n>=1?e=t=NaN:t<=0&&(e=NaN),new Wo(e,t,n,r)}function LN(e){if(e instanceof Wo)return new Wo(e.h,e.s,e.l,e.opacity);if(e instanceof gh||(e=Jm(e)),!e)return new Wo;if(e instanceof Wo)return e;e=e.rgb();var t=e.r/255,n=e.g/255,r=e.b/255,i=Math.min(t,n,r),a=Math.max(t,n,r),u=NaN,c=a-i,d=(a+i)/2;return c?(t===a?u=(n-r)/c+(n<r)*6:n===a?u=(r-t)/c+2:u=(t-n)/c+4,c/=d<.5?a+i:2-a-i,u*=60):c=d>0&&d<1?0:u,new Wo(u,c,d,e.opacity)}function V5(e,t,n,r){return arguments.length===1?LN(e):new Wo(e,t,n,r??1)}function Wo(e,t,n,r){this.h=+e,this.s=+t,this.l=+n,this.opacity=+r}Pv(Wo,V5,RN(gh,{brighter(e){return e=e==null?Pp:Math.pow(Pp,e),new Wo(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?Gm:Math.pow(Gm,e),new Wo(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,i=2*n-r;return new vi(vy(e>=240?e-240:e+120,i,r),vy(e,i,r),vy(e<120?e+240:e-120,i,r),this.opacity)},clamp(){return new Wo(j0(this.h),V_(this.s),V_(this.l),Dp(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=Dp(this.opacity);return`${e===1?"hsl(":"hsla("}${j0(this.h)}, ${V_(this.s)*100}%, ${V_(this.l)*100}%${e===1?")":`, ${e})`}`}}));function j0(e){return e=(e||0)%360,e<0?e+360:e}function V_(e){return Math.max(0,Math.min(1,e||0))}function vy(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 IN=e=>()=>e;function G5(e,t){return function(n){return e+n*t}}function K5(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 J5(e){return(e=+e)==1?ON:function(t,n){return n-t?K5(t,n,e):IN(isNaN(t)?n:t)}}function ON(e,t){var n=t-e;return n?G5(e,n):IN(isNaN(e)?t:e)}const S0=(function e(t){var n=J5(t);function r(i,a){var u=n((i=$w(i)).r,(a=$w(a)).r),c=n(i.g,a.g),d=n(i.b,a.b),m=ON(i.opacity,a.opacity);return function(h){return i.r=u(h),i.g=c(h),i.b=d(h),i.opacity=m(h),i+""}}return r.gamma=e,r})(1);function Vl(e,t){return e=+e,t=+t,function(n){return e*(1-n)+t*n}}var Cw=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,xy=new RegExp(Cw.source,"g");function Y5(e){return function(){return e}}function X5(e){return function(t){return e(t)+""}}function Z5(e,t){var n=Cw.lastIndex=xy.lastIndex=0,r,i,a,u=-1,c=[],d=[];for(e=e+"",t=t+"";(r=Cw.exec(e))&&(i=xy.exec(t));)(a=i.index)>n&&(a=t.slice(n,a),c[u]?c[u]+=a:c[++u]=a),(r=r[0])===(i=i[0])?c[u]?c[u]+=i:c[++u]=i:(c[++u]=null,d.push({i:u,x:Vl(r,i)})),n=xy.lastIndex;return n<t.length&&(a=t.slice(n),c[u]?c[u]+=a:c[++u]=a),c.length<2?d[0]?X5(d[0].x):Y5(t):(t=d.length,function(m){for(var h=0,p;h<t;++h)c[(p=d[h]).i]=p.x(m);return c.join("")})}var N0=180/Math.PI,Ew={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function PN(e,t,n,r,i,a){var u,c,d;return(u=Math.sqrt(e*e+t*t))&&(e/=u,t/=u),(d=e*n+t*r)&&(n-=e*d,r-=t*d),(c=Math.sqrt(n*n+r*r))&&(n/=c,r/=c,d/=c),e*r<t*n&&(e=-e,t=-t,d=-d,u=-u),{translateX:i,translateY:a,rotate:Math.atan2(t,e)*N0,skewX:Math.atan(d)*N0,scaleX:u,scaleY:c}}var G_;function Q5(e){const t=new(typeof DOMMatrix=="function"?DOMMatrix:WebKitCSSMatrix)(e+"");return t.isIdentity?Ew:PN(t.a,t.b,t.c,t.d,t.e,t.f)}function eP(e){return e==null||(G_||(G_=document.createElementNS("http://www.w3.org/2000/svg","g")),G_.setAttribute("transform",e),!(e=G_.transform.baseVal.consolidate()))?Ew:(e=e.matrix,PN(e.a,e.b,e.c,e.d,e.e,e.f))}function DN(e,t,n,r){function i(m){return m.length?m.pop()+" ":""}function a(m,h,p,y,w,x){if(m!==p||h!==y){var k=w.push("translate(",null,t,null,n);x.push({i:k-4,x:Vl(m,p)},{i:k-2,x:Vl(h,y)})}else(p||y)&&w.push("translate("+p+t+y+n)}function u(m,h,p,y){m!==h?(m-h>180?h+=360:h-m>180&&(m+=360),y.push({i:p.push(i(p)+"rotate(",null,r)-2,x:Vl(m,h)})):h&&p.push(i(p)+"rotate("+h+r)}function c(m,h,p,y){m!==h?y.push({i:p.push(i(p)+"skewX(",null,r)-2,x:Vl(m,h)}):h&&p.push(i(p)+"skewX("+h+r)}function d(m,h,p,y,w,x){if(m!==p||h!==y){var k=w.push(i(w)+"scale(",null,",",null,")");x.push({i:k-4,x:Vl(m,p)},{i:k-2,x:Vl(h,y)})}else(p!==1||y!==1)&&w.push(i(w)+"scale("+p+","+y+")")}return function(m,h){var p=[],y=[];return m=e(m),h=e(h),a(m.translateX,m.translateY,h.translateX,h.translateY,p,y),u(m.rotate,h.rotate,p,y),c(m.skewX,h.skewX,p,y),d(m.scaleX,m.scaleY,h.scaleX,h.scaleY,p,y),m=h=null,function(w){for(var x=-1,k=y.length,b;++x<k;)p[(b=y[x]).i]=b.x(w);return p.join("")}}}var tP=DN(Q5,"px, ","px)","deg)"),nP=DN(eP,", ",")",")"),sP=1e-12;function $0(e){return((e=Math.exp(e))+1/e)/2}function rP(e){return((e=Math.exp(e))-1/e)/2}function iP(e){return((e=Math.exp(2*e))-1)/(e+1)}const oP=(function e(t,n,r){function i(a,u){var c=a[0],d=a[1],m=a[2],h=u[0],p=u[1],y=u[2],w=h-c,x=p-d,k=w*w+x*x,b,S;if(k<sP)S=Math.log(y/m)/t,b=function(M){return[c+M*w,d+M*x,m*Math.exp(t*M*S)]};else{var $=Math.sqrt(k),A=(y*y-m*m+r*k)/(2*m*n*$),E=(y*y-m*m-r*k)/(2*y*n*$),z=Math.log(Math.sqrt(A*A+1)-A),F=Math.log(Math.sqrt(E*E+1)-E);S=(F-z)/t,b=function(M){var D=M*S,H=$0(z),q=m/(n*$)*(H*iP(t*D+z)-rP(z));return[c+q*w,d+q*x,m*H/$0(t*D+z)]}}return b.duration=S*1e3*t/Math.SQRT2,b}return i.rho=function(a){var u=Math.max(.001,+a),c=u*u,d=c*c;return e(u,c,d)},i})(Math.SQRT2,2,4);var Kd=0,Tm=0,mm=0,FN=1e3,Fp,Mm,zp=0,au=0,hg=0,Ym=typeof performance=="object"&&performance.now?performance:Date,zN=typeof window=="object"&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(e){setTimeout(e,17)};function Dv(){return au||(zN(aP),au=Ym.now()+hg)}function aP(){au=0}function Bp(){this._call=this._time=this._next=null}Bp.prototype=BN.prototype={constructor:Bp,restart:function(e,t,n){if(typeof e!="function")throw new TypeError("callback is not a function");n=(n==null?Dv():+n)+(t==null?0:+t),!this._next&&Mm!==this&&(Mm?Mm._next=this:Fp=this,Mm=this),this._call=e,this._time=n,Aw()},stop:function(){this._call&&(this._call=null,this._time=1/0,Aw())}};function BN(e,t,n){var r=new Bp;return r.restart(e,t,n),r}function lP(){Dv(),++Kd;for(var e=Fp,t;e;)(t=au-e._time)>=0&&e._call.call(void 0,t),e=e._next;--Kd}function C0(){au=(zp=Ym.now())+hg,Kd=Tm=0;try{lP()}finally{Kd=0,uP(),au=0}}function cP(){var e=Ym.now(),t=e-zp;t>FN&&(hg-=t,zp=e)}function uP(){for(var e,t=Fp,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:Fp=n);Mm=e,Aw(r)}function Aw(e){if(!Kd){Tm&&(Tm=clearTimeout(Tm));var t=e-au;t>24?(e<1/0&&(Tm=setTimeout(C0,e-Ym.now()-hg)),mm&&(mm=clearInterval(mm))):(mm||(zp=Ym.now(),mm=setInterval(cP,FN)),Kd=1,zN(C0))}}function E0(e,t,n){var r=new Bp;return t=t==null?0:+t,r.restart(i=>{r.stop(),e(i+t)},t,n),r}var dP=fg("start","end","cancel","interrupt"),fP=[],UN=0,A0=1,Tw=2,hp=3,T0=4,Mw=5,_p=6;function _g(e,t,n,r,i,a){var u=e.__transition;if(!u)e.__transition={};else if(n in u)return;mP(e,n,{name:t,index:r,group:i,on:dP,tween:fP,time:a.time,delay:a.delay,duration:a.duration,ease:a.ease,timer:null,state:UN})}function Fv(e,t){var n=Ho(e,t);if(n.state>UN)throw new Error("too late; already scheduled");return n}function pa(e,t){var n=Ho(e,t);if(n.state>hp)throw new Error("too late; already running");return n}function Ho(e,t){var n=e.__transition;if(!n||!(n=n[t]))throw new Error("transition not found");return n}function mP(e,t,n){var r=e.__transition,i;r[t]=n,n.timer=BN(a,0,n.time);function a(m){n.state=A0,n.timer.restart(u,n.delay,n.time),n.delay<=m&&u(m-n.delay)}function u(m){var h,p,y,w;if(n.state!==A0)return d();for(h in r)if(w=r[h],w.name===n.name){if(w.state===hp)return E0(u);w.state===T0?(w.state=_p,w.timer.stop(),w.on.call("interrupt",e,e.__data__,w.index,w.group),delete r[h]):+h<t&&(w.state=_p,w.timer.stop(),w.on.call("cancel",e,e.__data__,w.index,w.group),delete r[h])}if(E0(function(){n.state===hp&&(n.state=T0,n.timer.restart(c,n.delay,n.time),c(m))}),n.state=Tw,n.on.call("start",e,e.__data__,n.index,n.group),n.state===Tw){for(n.state=hp,i=new Array(y=n.tween.length),h=0,p=-1;h<y;++h)(w=n.tween[h].value.call(e,e.__data__,n.index,n.group))&&(i[++p]=w);i.length=p+1}}function c(m){for(var h=m<n.duration?n.ease.call(null,m/n.duration):(n.timer.restart(d),n.state=Mw,1),p=-1,y=i.length;++p<y;)i[p].call(e,h);n.state===Mw&&(n.on.call("end",e,e.__data__,n.index,n.group),d())}function d(){n.state=_p,n.timer.stop(),delete r[t];for(var m in r)return;delete e.__transition}}function pp(e,t){var n=e.__transition,r,i,a=!0,u;if(n){t=t==null?null:t+"";for(u in n){if((r=n[u]).name!==t){a=!1;continue}i=r.state>Tw&&r.state<Mw,r.state=_p,r.timer.stop(),r.on.call(i?"interrupt":"cancel",e,e.__data__,r.index,r.group),delete n[u]}a&&delete e.__transition}}function hP(e){return this.each(function(){pp(this,e)})}function _P(e,t){var n,r;return function(){var i=pa(this,e),a=i.tween;if(a!==n){r=n=a;for(var u=0,c=r.length;u<c;++u)if(r[u].name===t){r=r.slice(),r.splice(u,1);break}}i.tween=r}}function pP(e,t,n){var r,i;if(typeof n!="function")throw new Error;return function(){var a=pa(this,e),u=a.tween;if(u!==r){i=(r=u).slice();for(var c={name:t,value:n},d=0,m=i.length;d<m;++d)if(i[d].name===t){i[d]=c;break}d===m&&i.push(c)}a.tween=i}}function gP(e,t){var n=this._id;if(e+="",arguments.length<2){for(var r=Ho(this.node(),n).tween,i=0,a=r.length,u;i<a;++i)if((u=r[i]).name===e)return u.value;return null}return this.each((t==null?_P:pP)(n,e,t))}function zv(e,t,n){var r=e._id;return e.each(function(){var i=pa(this,r);(i.value||(i.value={}))[t]=n.apply(this,arguments)}),function(i){return Ho(i,r).value[t]}}function WN(e,t){var n;return(typeof t=="number"?Vl:t instanceof Jm?S0:(n=Jm(t))?(t=n,S0):Z5)(e,t)}function yP(e){return function(){this.removeAttribute(e)}}function wP(e){return function(){this.removeAttributeNS(e.space,e.local)}}function vP(e,t,n){var r,i=n+"",a;return function(){var u=this.getAttribute(e);return u===i?null:u===r?a:a=t(r=u,n)}}function xP(e,t,n){var r,i=n+"",a;return function(){var u=this.getAttributeNS(e.space,e.local);return u===i?null:u===r?a:a=t(r=u,n)}}function bP(e,t,n){var r,i,a;return function(){var u,c=n(this),d;return c==null?void this.removeAttribute(e):(u=this.getAttribute(e),d=c+"",u===d?null:u===r&&d===i?a:(i=d,a=t(r=u,c)))}}function kP(e,t,n){var r,i,a;return function(){var u,c=n(this),d;return c==null?void this.removeAttributeNS(e.space,e.local):(u=this.getAttributeNS(e.space,e.local),d=c+"",u===d?null:u===r&&d===i?a:(i=d,a=t(r=u,c)))}}function jP(e,t){var n=mg(e),r=n==="transform"?nP:WN;return this.attrTween(e,typeof t=="function"?(n.local?kP:bP)(n,r,zv(this,"attr."+e,t)):t==null?(n.local?wP:yP)(n):(n.local?xP:vP)(n,r,t))}function SP(e,t){return function(n){this.setAttribute(e,t.call(this,n))}}function NP(e,t){return function(n){this.setAttributeNS(e.space,e.local,t.call(this,n))}}function $P(e,t){var n,r;function i(){var a=t.apply(this,arguments);return a!==r&&(n=(r=a)&&NP(e,a)),n}return i._value=t,i}function CP(e,t){var n,r;function i(){var a=t.apply(this,arguments);return a!==r&&(n=(r=a)&&SP(e,a)),n}return i._value=t,i}function EP(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=mg(e);return this.tween(n,(r.local?$P:CP)(r,t))}function AP(e,t){return function(){Fv(this,e).delay=+t.apply(this,arguments)}}function TP(e,t){return t=+t,function(){Fv(this,e).delay=t}}function MP(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?AP:TP)(t,e)):Ho(this.node(),t).delay}function RP(e,t){return function(){pa(this,e).duration=+t.apply(this,arguments)}}function LP(e,t){return t=+t,function(){pa(this,e).duration=t}}function IP(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?RP:LP)(t,e)):Ho(this.node(),t).duration}function OP(e,t){if(typeof t!="function")throw new Error;return function(){pa(this,e).ease=t}}function PP(e){var t=this._id;return arguments.length?this.each(OP(t,e)):Ho(this.node(),t).ease}function DP(e,t){return function(){var n=t.apply(this,arguments);if(typeof n!="function")throw new Error;pa(this,e).ease=n}}function FP(e){if(typeof e!="function")throw new Error;return this.each(DP(this._id,e))}function zP(e){typeof e!="function"&&(e=xN(e));for(var t=this._groups,n=t.length,r=new Array(n),i=0;i<n;++i)for(var a=t[i],u=a.length,c=r[i]=[],d,m=0;m<u;++m)(d=a[m])&&e.call(d,d.__data__,m,a)&&c.push(d);return new Xa(r,this._parents,this._name,this._id)}function BP(e){if(e._id!==this._id)throw new Error;for(var t=this._groups,n=e._groups,r=t.length,i=n.length,a=Math.min(r,i),u=new Array(r),c=0;c<a;++c)for(var d=t[c],m=n[c],h=d.length,p=u[c]=new Array(h),y,w=0;w<h;++w)(y=d[w]||m[w])&&(p[w]=y);for(;c<r;++c)u[c]=t[c];return new Xa(u,this._parents,this._name,this._id)}function UP(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 WP(e,t,n){var r,i,a=UP(t)?Fv:pa;return function(){var u=a(this,e),c=u.on;c!==r&&(i=(r=c).copy()).on(t,n),u.on=i}}function qP(e,t){var n=this._id;return arguments.length<2?Ho(this.node(),n).on.on(e):this.each(WP(n,e,t))}function HP(e){return function(){var t=this.parentNode;for(var n in this.__transition)if(+n!==e)return;t&&t.removeChild(this)}}function VP(){return this.on("end.remove",HP(this._id))}function GP(e){var t=this._name,n=this._id;typeof e!="function"&&(e=Iv(e));for(var r=this._groups,i=r.length,a=new Array(i),u=0;u<i;++u)for(var c=r[u],d=c.length,m=a[u]=new Array(d),h,p,y=0;y<d;++y)(h=c[y])&&(p=e.call(h,h.__data__,y,c))&&("__data__"in h&&(p.__data__=h.__data__),m[y]=p,_g(m[y],t,n,y,m,Ho(h,n)));return new Xa(a,this._parents,t,n)}function KP(e){var t=this._name,n=this._id;typeof e!="function"&&(e=vN(e));for(var r=this._groups,i=r.length,a=[],u=[],c=0;c<i;++c)for(var d=r[c],m=d.length,h,p=0;p<m;++p)if(h=d[p]){for(var y=e.call(h,h.__data__,p,d),w,x=Ho(h,n),k=0,b=y.length;k<b;++k)(w=y[k])&&_g(w,t,n,k,y,x);a.push(y),u.push(h)}return new Xa(a,u,t,n)}var JP=ph.prototype.constructor;function YP(){return new JP(this._groups,this._parents)}function XP(e,t){var n,r,i;return function(){var a=Gd(this,e),u=(this.style.removeProperty(e),Gd(this,e));return a===u?null:a===n&&u===r?i:i=t(n=a,r=u)}}function qN(e){return function(){this.style.removeProperty(e)}}function ZP(e,t,n){var r,i=n+"",a;return function(){var u=Gd(this,e);return u===i?null:u===r?a:a=t(r=u,n)}}function QP(e,t,n){var r,i,a;return function(){var u=Gd(this,e),c=n(this),d=c+"";return c==null&&(d=c=(this.style.removeProperty(e),Gd(this,e))),u===d?null:u===r&&d===i?a:(i=d,a=t(r=u,c))}}function eD(e,t){var n,r,i,a="style."+t,u="end."+a,c;return function(){var d=pa(this,e),m=d.on,h=d.value[a]==null?c||(c=qN(t)):void 0;(m!==n||i!==h)&&(r=(n=m).copy()).on(u,i=h),d.on=r}}function tD(e,t,n){var r=(e+="")=="transform"?tP:WN;return t==null?this.styleTween(e,XP(e,r)).on("end.style."+e,qN(e)):typeof t=="function"?this.styleTween(e,QP(e,r,zv(this,"style."+e,t))).each(eD(this._id,e)):this.styleTween(e,ZP(e,r,t),n).on("end.style."+e,null)}function nD(e,t,n){return function(r){this.style.setProperty(e,t.call(this,r),n)}}function sD(e,t,n){var r,i;function a(){var u=t.apply(this,arguments);return u!==i&&(r=(i=u)&&nD(e,u,n)),r}return a._value=t,a}function rD(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,sD(e,t,n??""))}function iD(e){return function(){this.textContent=e}}function oD(e){return function(){var t=e(this);this.textContent=t??""}}function aD(e){return this.tween("text",typeof e=="function"?oD(zv(this,"text",e)):iD(e==null?"":e+""))}function lD(e){return function(t){this.textContent=e.call(this,t)}}function cD(e){var t,n;function r(){var i=e.apply(this,arguments);return i!==n&&(t=(n=i)&&lD(i)),t}return r._value=e,r}function uD(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,cD(e))}function dD(){for(var e=this._name,t=this._id,n=HN(),r=this._groups,i=r.length,a=0;a<i;++a)for(var u=r[a],c=u.length,d,m=0;m<c;++m)if(d=u[m]){var h=Ho(d,t);_g(d,e,n,m,u,{time:h.time+h.delay+h.duration,delay:0,duration:h.duration,ease:h.ease})}return new Xa(r,this._parents,e,n)}function fD(){var e,t,n=this,r=n._id,i=n.size();return new Promise(function(a,u){var c={value:u},d={value:function(){--i===0&&a()}};n.each(function(){var m=pa(this,r),h=m.on;h!==e&&(t=(e=h).copy(),t._.cancel.push(c),t._.interrupt.push(c),t._.end.push(d)),m.on=t}),i===0&&a()})}var mD=0;function Xa(e,t,n,r){this._groups=e,this._parents=t,this._name=n,this._id=r}function HN(){return++mD}var Ua=ph.prototype;Xa.prototype={constructor:Xa,select:GP,selectAll:KP,selectChild:Ua.selectChild,selectChildren:Ua.selectChildren,filter:zP,merge:BP,selection:YP,transition:dD,call:Ua.call,nodes:Ua.nodes,node:Ua.node,size:Ua.size,empty:Ua.empty,each:Ua.each,on:qP,attr:jP,attrTween:EP,style:tD,styleTween:rD,text:aD,textTween:uD,remove:VP,tween:gP,delay:MP,duration:IP,ease:PP,easeVarying:FP,end:fD,[Symbol.iterator]:Ua[Symbol.iterator]};function hD(e){return((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2}var _D={time:null,delay:0,duration:250,ease:hD};function pD(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 gD(e){var t,n;e instanceof Xa?(t=e._id,e=e._name):(t=HN(),(n=_D).time=Dv(),e=e==null?null:e+"");for(var r=this._groups,i=r.length,a=0;a<i;++a)for(var u=r[a],c=u.length,d,m=0;m<c;++m)(d=u[m])&&_g(d,e,t,m,u,n||pD(d,t));return new Xa(r,this._parents,e,t)}ph.prototype.interrupt=hP;ph.prototype.transition=gD;const K_=e=>()=>e;function yD(e,{sourceEvent:t,target:n,transform:r,dispatch:i}){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:i}})}function Va(e,t,n){this.k=e,this.x=t,this.y=n}Va.prototype={constructor:Va,scale:function(e){return e===1?this:new Va(this.k*e,this.x,this.y)},translate:function(e,t){return e===0&t===0?this:new Va(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 Ka=new Va(1,0,0);Va.prototype;function by(e){e.stopImmediatePropagation()}function hm(e){e.preventDefault(),e.stopImmediatePropagation()}function wD(e){return(!e.ctrlKey||e.type==="wheel")&&!e.button}function vD(){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 M0(){return this.__zoom||Ka}function xD(e){return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*(e.ctrlKey?10:1)}function bD(){return navigator.maxTouchPoints||"ontouchstart"in this}function kD(e,t,n){var r=e.invertX(t[0][0])-n[0][0],i=e.invertX(t[1][0])-n[1][0],a=e.invertY(t[0][1])-n[0][1],u=e.invertY(t[1][1])-n[1][1];return e.translate(i>r?(r+i)/2:Math.min(0,r)||Math.max(0,i),u>a?(a+u)/2:Math.min(0,a)||Math.max(0,u))}function VN(){var e=wD,t=vD,n=kD,r=xD,i=bD,a=[0,1/0],u=[[-1/0,-1/0],[1/0,1/0]],c=250,d=oP,m=fg("start","zoom","end"),h,p,y,w=500,x=150,k=0,b=10;function S(T){T.property("__zoom",M0).on("wheel.zoom",D,{passive:!1}).on("mousedown.zoom",H).on("dblclick.zoom",q).filter(i).on("touchstart.zoom",I).on("touchmove.zoom",Z).on("touchend.zoom touchcancel.zoom",R).style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}S.transform=function(T,P,L,te){var X=T.selection?T.selection():T;X.property("__zoom",M0),T!==X?z(T,P,L,te):X.interrupt().each(function(){F(this,arguments).event(te).start().zoom(null,typeof P=="function"?P.apply(this,arguments):P).end()})},S.scaleBy=function(T,P,L,te){S.scaleTo(T,function(){var X=this.__zoom.k,V=typeof P=="function"?P.apply(this,arguments):P;return X*V},L,te)},S.scaleTo=function(T,P,L,te){S.transform(T,function(){var X=t.apply(this,arguments),V=this.__zoom,ne=L==null?E(X):typeof L=="function"?L.apply(this,arguments):L,W=V.invert(ne),Y=typeof P=="function"?P.apply(this,arguments):P;return n(A($(V,Y),ne,W),X,u)},L,te)},S.translateBy=function(T,P,L,te){S.transform(T,function(){return n(this.__zoom.translate(typeof P=="function"?P.apply(this,arguments):P,typeof L=="function"?L.apply(this,arguments):L),t.apply(this,arguments),u)},null,te)},S.translateTo=function(T,P,L,te,X){S.transform(T,function(){var V=t.apply(this,arguments),ne=this.__zoom,W=te==null?E(V):typeof te=="function"?te.apply(this,arguments):te;return n(Ka.translate(W[0],W[1]).scale(ne.k).translate(typeof P=="function"?-P.apply(this,arguments):-P,typeof L=="function"?-L.apply(this,arguments):-L),V,u)},te,X)};function $(T,P){return P=Math.max(a[0],Math.min(a[1],P)),P===T.k?T:new Va(P,T.x,T.y)}function A(T,P,L){var te=P[0]-L[0]*T.k,X=P[1]-L[1]*T.k;return te===T.x&&X===T.y?T:new Va(T.k,te,X)}function E(T){return[(+T[0][0]+ +T[1][0])/2,(+T[0][1]+ +T[1][1])/2]}function z(T,P,L,te){T.on("start.zoom",function(){F(this,arguments).event(te).start()}).on("interrupt.zoom end.zoom",function(){F(this,arguments).event(te).end()}).tween("zoom",function(){var X=this,V=arguments,ne=F(X,V).event(te),W=t.apply(X,V),Y=L==null?E(W):typeof L=="function"?L.apply(X,V):L,K=Math.max(W[1][0]-W[0][0],W[1][1]-W[0][1]),fe=X.__zoom,ae=typeof P=="function"?P.apply(X,V):P,ve=d(fe.invert(Y).concat(K/fe.k),ae.invert(Y).concat(K/ae.k));return function(ge){if(ge===1)ge=ae;else{var pe=ve(ge),$e=K/pe[2];ge=new Va($e,Y[0]-pe[0]*$e,Y[1]-pe[1]*$e)}ne.zoom(null,ge)}})}function F(T,P,L){return!L&&T.__zooming||new M(T,P)}function M(T,P){this.that=T,this.args=P,this.active=0,this.sourceEvent=null,this.extent=t.apply(T,P),this.taps=0}M.prototype={event:function(T){return T&&(this.sourceEvent=T),this},start:function(){return++this.active===1&&(this.that.__zooming=this,this.emit("start")),this},zoom:function(T,P){return this.mouse&&T!=="mouse"&&(this.mouse[1]=P.invert(this.mouse[0])),this.touch0&&T!=="touch"&&(this.touch0[1]=P.invert(this.touch0[0])),this.touch1&&T!=="touch"&&(this.touch1[1]=P.invert(this.touch1[0])),this.that.__zoom=P,this.emit("zoom"),this},end:function(){return--this.active===0&&(delete this.that.__zooming,this.emit("end")),this},emit:function(T){var P=mo(this.that).datum();m.call(T,this.that,new yD(T,{sourceEvent:this.sourceEvent,target:S,transform:this.that.__zoom,dispatch:m}),P)}};function D(T,...P){if(!e.apply(this,arguments))return;var L=F(this,P).event(T),te=this.__zoom,X=Math.max(a[0],Math.min(a[1],te.k*Math.pow(2,r.apply(this,arguments)))),V=zo(T);if(L.wheel)(L.mouse[0][0]!==V[0]||L.mouse[0][1]!==V[1])&&(L.mouse[1]=te.invert(L.mouse[0]=V)),clearTimeout(L.wheel);else{if(te.k===X)return;L.mouse=[V,te.invert(V)],pp(this),L.start()}hm(T),L.wheel=setTimeout(ne,x),L.zoom("mouse",n(A($(te,X),L.mouse[0],L.mouse[1]),L.extent,u));function ne(){L.wheel=null,L.end()}}function H(T,...P){if(y||!e.apply(this,arguments))return;var L=T.currentTarget,te=F(this,P,!0).event(T),X=mo(T.view).on("mousemove.zoom",Y,!0).on("mouseup.zoom",K,!0),V=zo(T,L),ne=T.clientX,W=T.clientY;TN(T.view),by(T),te.mouse=[V,this.__zoom.invert(V)],pp(this),te.start();function Y(fe){if(hm(fe),!te.moved){var ae=fe.clientX-ne,ve=fe.clientY-W;te.moved=ae*ae+ve*ve>k}te.event(fe).zoom("mouse",n(A(te.that.__zoom,te.mouse[0]=zo(fe,L),te.mouse[1]),te.extent,u))}function K(fe){X.on("mousemove.zoom mouseup.zoom",null),MN(fe.view,te.moved),hm(fe),te.event(fe).end()}}function q(T,...P){if(e.apply(this,arguments)){var L=this.__zoom,te=zo(T.changedTouches?T.changedTouches[0]:T,this),X=L.invert(te),V=L.k*(T.shiftKey?.5:2),ne=n(A($(L,V),te,X),t.apply(this,P),u);hm(T),c>0?mo(this).transition().duration(c).call(z,ne,te,T):mo(this).call(S.transform,ne,te,T)}}function I(T,...P){if(e.apply(this,arguments)){var L=T.touches,te=L.length,X=F(this,P,T.changedTouches.length===te).event(T),V,ne,W,Y;for(by(T),ne=0;ne<te;++ne)W=L[ne],Y=zo(W,this),Y=[Y,this.__zoom.invert(Y),W.identifier],X.touch0?!X.touch1&&X.touch0[2]!==Y[2]&&(X.touch1=Y,X.taps=0):(X.touch0=Y,V=!0,X.taps=1+!!h);h&&(h=clearTimeout(h)),V&&(X.taps<2&&(p=Y[0],h=setTimeout(function(){h=null},w)),pp(this),X.start())}}function Z(T,...P){if(this.__zooming){var L=F(this,P).event(T),te=T.changedTouches,X=te.length,V,ne,W,Y;for(hm(T),V=0;V<X;++V)ne=te[V],W=zo(ne,this),L.touch0&&L.touch0[2]===ne.identifier?L.touch0[0]=W:L.touch1&&L.touch1[2]===ne.identifier&&(L.touch1[0]=W);if(ne=L.that.__zoom,L.touch1){var K=L.touch0[0],fe=L.touch0[1],ae=L.touch1[0],ve=L.touch1[1],ge=(ge=ae[0]-K[0])*ge+(ge=ae[1]-K[1])*ge,pe=(pe=ve[0]-fe[0])*pe+(pe=ve[1]-fe[1])*pe;ne=$(ne,Math.sqrt(ge/pe)),W=[(K[0]+ae[0])/2,(K[1]+ae[1])/2],Y=[(fe[0]+ve[0])/2,(fe[1]+ve[1])/2]}else if(L.touch0)W=L.touch0[0],Y=L.touch0[1];else return;L.zoom("touch",n(A(ne,W,Y),L.extent,u))}}function R(T,...P){if(this.__zooming){var L=F(this,P).event(T),te=T.changedTouches,X=te.length,V,ne;for(by(T),y&&clearTimeout(y),y=setTimeout(function(){y=null},w),V=0;V<X;++V)ne=te[V],L.touch0&&L.touch0[2]===ne.identifier?delete L.touch0:L.touch1&&L.touch1[2]===ne.identifier&&delete L.touch1;if(L.touch1&&!L.touch0&&(L.touch0=L.touch1,delete L.touch1),L.touch0)L.touch0[1]=this.__zoom.invert(L.touch0[0]);else if(L.end(),L.taps===2&&(ne=zo(ne,this),Math.hypot(p[0]-ne[0],p[1]-ne[1])<b)){var W=mo(this).on("dblclick.zoom");W&&W.apply(this,arguments)}}}return S.wheelDelta=function(T){return arguments.length?(r=typeof T=="function"?T:K_(+T),S):r},S.filter=function(T){return arguments.length?(e=typeof T=="function"?T:K_(!!T),S):e},S.touchable=function(T){return arguments.length?(i=typeof T=="function"?T:K_(!!T),S):i},S.extent=function(T){return arguments.length?(t=typeof T=="function"?T:K_([[+T[0][0],+T[0][1]],[+T[1][0],+T[1][1]]]),S):t},S.scaleExtent=function(T){return arguments.length?(a[0]=+T[0],a[1]=+T[1],S):[a[0],a[1]]},S.translateExtent=function(T){return arguments.length?(u[0][0]=+T[0][0],u[1][0]=+T[1][0],u[0][1]=+T[0][1],u[1][1]=+T[1][1],S):[[u[0][0],u[0][1]],[u[1][0],u[1][1]]]},S.constrain=function(T){return arguments.length?(n=T,S):n},S.duration=function(T){return arguments.length?(c=+T,S):c},S.interpolate=function(T){return arguments.length?(d=T,S):d},S.on=function(){var T=m.on.apply(m,arguments);return T===m?S:T},S.clickDistance=function(T){return arguments.length?(k=(T=+T)*T,S):Math.sqrt(k)},S.tapDistance=function(T){return arguments.length?(b=+T,S):b},S}const pg=_.createContext(null),jD=pg.Provider,Za={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.`},GN=Za.error001();function fs(e,t){const n=_.useContext(pg);if(n===null)throw new Error(GN);return yN(n,e,t)}const er=()=>{const e=_.useContext(pg);if(e===null)throw new Error(GN);return _.useMemo(()=>({getState:e.getState,setState:e.setState,subscribe:e.subscribe,destroy:e.destroy}),[e])},SD=e=>e.userSelectionActive?"none":"all";function Xm({position:e,children:t,className:n,style:r,...i}){const a=fs(SD),u=`${e}`.split("-");return Ne.createElement("div",{className:$r(["react-flow__panel",n,...u]),style:{...r,pointerEvents:a},...i},t)}function ND({proOptions:e,position:t="bottom-right"}){return e!=null&&e.hideAttribution?null:Ne.createElement(Xm,{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"},Ne.createElement("a",{href:"https://reactflow.dev",target:"_blank",rel:"noopener noreferrer","aria-label":"React Flow attribution"},"React Flow"))}const $D=({x:e,y:t,label:n,labelStyle:r={},labelShowBg:i=!0,labelBgStyle:a={},labelBgPadding:u=[2,4],labelBgBorderRadius:c=2,children:d,className:m,...h})=>{const p=_.useRef(null),[y,w]=_.useState({x:0,y:0,width:0,height:0}),x=$r(["react-flow__edge-textwrapper",m]);return _.useEffect(()=>{if(p.current){const k=p.current.getBBox();w({x:k.x,y:k.y,width:k.width,height:k.height})}},[n]),typeof n>"u"||!n?null:Ne.createElement("g",{transform:`translate(${e-y.width/2} ${t-y.height/2})`,className:x,visibility:y.width?"visible":"hidden",...h},i&&Ne.createElement("rect",{width:y.width+2*u[0],x:-u[0],y:-u[1],height:y.height+2*u[1],className:"react-flow__edge-textbg",style:a,rx:c,ry:c}),Ne.createElement("text",{className:"react-flow__edge-text",y:y.height/2,dy:"0.3em",ref:p,style:r},n),d)};var CD=_.memo($D);const Bv=e=>({width:e.offsetWidth,height:e.offsetHeight}),Jd=(e,t=0,n=1)=>Math.min(Math.max(e,t),n),Uv=(e={x:0,y:0},t)=>({x:Jd(e.x,t[0][0],t[1][0]),y:Jd(e.y,t[0][1],t[1][1])}),R0=(e,t,n)=>e<t?Jd(Math.abs(e-t),1,50)/50:e>n?-Jd(Math.abs(e-n),1,50)/50:0,KN=(e,t)=>{const n=R0(e.x,35,t.width-35)*20,r=R0(e.y,35,t.height-35)*20;return[n,r]},JN=e=>{var t;return((t=e.getRootNode)==null?void 0:t.call(e))||(window==null?void 0:window.document)},YN=(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)}),Zm=({x:e,y:t,width:n,height:r})=>({x:e,y:t,x2:e+n,y2:t+r}),XN=({x:e,y:t,x2:n,y2:r})=>({x:e,y:t,width:n-e,height:r-t}),L0=e=>({...e.positionAbsolute||{x:0,y:0},width:e.width||0,height:e.height||0}),ED=(e,t)=>XN(YN(Zm(e),Zm(t))),Rw=(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)},AD=e=>ho(e.width)&&ho(e.height)&&ho(e.x)&&ho(e.y),ho=e=>!isNaN(e)&&isFinite(e),qs=Symbol.for("internals"),ZN=["Enter"," ","Escape"],TD=(e,t)=>{},MD=e=>"nativeEvent"in e;function Lw(e){var i,a;const t=MD(e)?e.nativeEvent:e,n=((a=(i=t.composedPath)==null?void 0:i.call(t))==null?void 0:a[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 QN=e=>"clientX"in e,Zl=(e,t)=>{var a,u;const n=QN(e),r=n?e.clientX:(a=e.touches)==null?void 0:a[0].clientX,i=n?e.clientY:(u=e.touches)==null?void 0:u[0].clientY;return{x:r-((t==null?void 0:t.left)??0),y:i-((t==null?void 0:t.top)??0)}},Up=()=>{var e;return typeof navigator<"u"&&((e=navigator==null?void 0:navigator.userAgent)==null?void 0:e.indexOf("Mac"))>=0},yh=({id:e,path:t,labelX:n,labelY:r,label:i,labelStyle:a,labelShowBg:u,labelBgStyle:c,labelBgPadding:d,labelBgBorderRadius:m,style:h,markerEnd:p,markerStart:y,interactionWidth:w=20})=>Ne.createElement(Ne.Fragment,null,Ne.createElement("path",{id:e,style:h,d:t,fill:"none",className:"react-flow__edge-path",markerEnd:p,markerStart:y}),w&&Ne.createElement("path",{d:t,fill:"none",strokeOpacity:0,strokeWidth:w,className:"react-flow__edge-interaction"}),i&&ho(n)&&ho(r)?Ne.createElement(CD,{x:n,y:r,label:i,labelStyle:a,labelShowBg:u,labelBgStyle:c,labelBgPadding:d,labelBgBorderRadius:m}):null);yh.displayName="BaseEdge";function _m(e,t,n){return n===void 0?n:r=>{const i=t().edges.find(a=>a.id===e);i&&n(r,{...i})}}function e1({sourceX:e,sourceY:t,targetX:n,targetY:r}){const i=Math.abs(n-e)/2,a=n<e?n+i:n-i,u=Math.abs(r-t)/2,c=r<t?r+u:r-u;return[a,c,i,u]}function t1({sourceX:e,sourceY:t,targetX:n,targetY:r,sourceControlX:i,sourceControlY:a,targetControlX:u,targetControlY:c}){const d=e*.125+i*.375+u*.375+n*.125,m=t*.125+a*.375+c*.375+r*.125,h=Math.abs(d-e),p=Math.abs(m-t);return[d,m,h,p]}var lu;(function(e){e.Strict="strict",e.Loose="loose"})(lu||(lu={}));var Kc;(function(e){e.Free="free",e.Vertical="vertical",e.Horizontal="horizontal"})(Kc||(Kc={}));var Qm;(function(e){e.Partial="partial",e.Full="full"})(Qm||(Qm={}));var Jl;(function(e){e.Bezier="default",e.Straight="straight",e.Step="step",e.SmoothStep="smoothstep",e.SimpleBezier="simplebezier"})(Jl||(Jl={}));var eh;(function(e){e.Arrow="arrow",e.ArrowClosed="arrowclosed"})(eh||(eh={}));var Mt;(function(e){e.Left="left",e.Top="top",e.Right="right",e.Bottom="bottom"})(Mt||(Mt={}));function I0({pos:e,x1:t,y1:n,x2:r,y2:i}){return e===Mt.Left||e===Mt.Right?[.5*(t+r),n]:[t,.5*(n+i)]}function n1({sourceX:e,sourceY:t,sourcePosition:n=Mt.Bottom,targetX:r,targetY:i,targetPosition:a=Mt.Top}){const[u,c]=I0({pos:n,x1:e,y1:t,x2:r,y2:i}),[d,m]=I0({pos:a,x1:r,y1:i,x2:e,y2:t}),[h,p,y,w]=t1({sourceX:e,sourceY:t,targetX:r,targetY:i,sourceControlX:u,sourceControlY:c,targetControlX:d,targetControlY:m});return[`M${e},${t} C${u},${c} ${d},${m} ${r},${i}`,h,p,y,w]}const Wv=_.memo(({sourceX:e,sourceY:t,targetX:n,targetY:r,sourcePosition:i=Mt.Bottom,targetPosition:a=Mt.Top,label:u,labelStyle:c,labelShowBg:d,labelBgStyle:m,labelBgPadding:h,labelBgBorderRadius:p,style:y,markerEnd:w,markerStart:x,interactionWidth:k})=>{const[b,S,$]=n1({sourceX:e,sourceY:t,sourcePosition:i,targetX:n,targetY:r,targetPosition:a});return Ne.createElement(yh,{path:b,labelX:S,labelY:$,label:u,labelStyle:c,labelShowBg:d,labelBgStyle:m,labelBgPadding:h,labelBgBorderRadius:p,style:y,markerEnd:w,markerStart:x,interactionWidth:k})});Wv.displayName="SimpleBezierEdge";const O0={[Mt.Left]:{x:-1,y:0},[Mt.Right]:{x:1,y:0},[Mt.Top]:{x:0,y:-1},[Mt.Bottom]:{x:0,y:1}},RD=({source:e,sourcePosition:t=Mt.Bottom,target:n})=>t===Mt.Left||t===Mt.Right?e.x<n.x?{x:1,y:0}:{x:-1,y:0}:e.y<n.y?{x:0,y:1}:{x:0,y:-1},P0=(e,t)=>Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2));function LD({source:e,sourcePosition:t=Mt.Bottom,target:n,targetPosition:r=Mt.Top,center:i,offset:a}){const u=O0[t],c=O0[r],d={x:e.x+u.x*a,y:e.y+u.y*a},m={x:n.x+c.x*a,y:n.y+c.y*a},h=RD({source:d,sourcePosition:t,target:m}),p=h.x!==0?"x":"y",y=h[p];let w=[],x,k;const b={x:0,y:0},S={x:0,y:0},[$,A,E,z]=e1({sourceX:e.x,sourceY:e.y,targetX:n.x,targetY:n.y});if(u[p]*c[p]===-1){x=i.x||$,k=i.y||A;const M=[{x,y:d.y},{x,y:m.y}],D=[{x:d.x,y:k},{x:m.x,y:k}];u[p]===y?w=p==="x"?M:D:w=p==="x"?D:M}else{const M=[{x:d.x,y:m.y}],D=[{x:m.x,y:d.y}];if(p==="x"?w=u.x===y?D:M:w=u.y===y?M:D,t===r){const R=Math.abs(e[p]-n[p]);if(R<=a){const T=Math.min(a-1,a-R);u[p]===y?b[p]=(d[p]>e[p]?-1:1)*T:S[p]=(m[p]>n[p]?-1:1)*T}}if(t!==r){const R=p==="x"?"y":"x",T=u[p]===c[R],P=d[R]>m[R],L=d[R]<m[R];(u[p]===1&&(!T&&P||T&&L)||u[p]!==1&&(!T&&L||T&&P))&&(w=p==="x"?M:D)}const H={x:d.x+b.x,y:d.y+b.y},q={x:m.x+S.x,y:m.y+S.y},I=Math.max(Math.abs(H.x-w[0].x),Math.abs(q.x-w[0].x)),Z=Math.max(Math.abs(H.y-w[0].y),Math.abs(q.y-w[0].y));I>=Z?(x=(H.x+q.x)/2,k=w[0].y):(x=w[0].x,k=(H.y+q.y)/2)}return[[e,{x:d.x+b.x,y:d.y+b.y},...w,{x:m.x+S.x,y:m.y+S.y},n],x,k,E,z]}function ID(e,t,n,r){const i=Math.min(P0(e,t)/2,P0(t,n)/2,r),{x:a,y:u}=t;if(e.x===a&&a===n.x||e.y===u&&u===n.y)return`L${a} ${u}`;if(e.y===u){const m=e.x<n.x?-1:1,h=e.y<n.y?1:-1;return`L ${a+i*m},${u}Q ${a},${u} ${a},${u+i*h}`}const c=e.x<n.x?1:-1,d=e.y<n.y?-1:1;return`L ${a},${u+i*d}Q ${a},${u} ${a+i*c},${u}`}function Iw({sourceX:e,sourceY:t,sourcePosition:n=Mt.Bottom,targetX:r,targetY:i,targetPosition:a=Mt.Top,borderRadius:u=5,centerX:c,centerY:d,offset:m=20}){const[h,p,y,w,x]=LD({source:{x:e,y:t},sourcePosition:n,target:{x:r,y:i},targetPosition:a,center:{x:c,y:d},offset:m});return[h.reduce((b,S,$)=>{let A="";return $>0&&$<h.length-1?A=ID(h[$-1],S,h[$+1],u):A=`${$===0?"M":"L"}${S.x} ${S.y}`,b+=A,b},""),p,y,w,x]}const gg=_.memo(({sourceX:e,sourceY:t,targetX:n,targetY:r,label:i,labelStyle:a,labelShowBg:u,labelBgStyle:c,labelBgPadding:d,labelBgBorderRadius:m,style:h,sourcePosition:p=Mt.Bottom,targetPosition:y=Mt.Top,markerEnd:w,markerStart:x,pathOptions:k,interactionWidth:b})=>{const[S,$,A]=Iw({sourceX:e,sourceY:t,sourcePosition:p,targetX:n,targetY:r,targetPosition:y,borderRadius:k==null?void 0:k.borderRadius,offset:k==null?void 0:k.offset});return Ne.createElement(yh,{path:S,labelX:$,labelY:A,label:i,labelStyle:a,labelShowBg:u,labelBgStyle:c,labelBgPadding:d,labelBgBorderRadius:m,style:h,markerEnd:w,markerStart:x,interactionWidth:b})});gg.displayName="SmoothStepEdge";const qv=_.memo(e=>{var t;return Ne.createElement(gg,{...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])})});qv.displayName="StepEdge";function OD({sourceX:e,sourceY:t,targetX:n,targetY:r}){const[i,a,u,c]=e1({sourceX:e,sourceY:t,targetX:n,targetY:r});return[`M ${e},${t}L ${n},${r}`,i,a,u,c]}const Hv=_.memo(({sourceX:e,sourceY:t,targetX:n,targetY:r,label:i,labelStyle:a,labelShowBg:u,labelBgStyle:c,labelBgPadding:d,labelBgBorderRadius:m,style:h,markerEnd:p,markerStart:y,interactionWidth:w})=>{const[x,k,b]=OD({sourceX:e,sourceY:t,targetX:n,targetY:r});return Ne.createElement(yh,{path:x,labelX:k,labelY:b,label:i,labelStyle:a,labelShowBg:u,labelBgStyle:c,labelBgPadding:d,labelBgBorderRadius:m,style:h,markerEnd:p,markerStart:y,interactionWidth:w})});Hv.displayName="StraightEdge";function J_(e,t){return e>=0?.5*e:t*25*Math.sqrt(-e)}function D0({pos:e,x1:t,y1:n,x2:r,y2:i,c:a}){switch(e){case Mt.Left:return[t-J_(t-r,a),n];case Mt.Right:return[t+J_(r-t,a),n];case Mt.Top:return[t,n-J_(n-i,a)];case Mt.Bottom:return[t,n+J_(i-n,a)]}}function s1({sourceX:e,sourceY:t,sourcePosition:n=Mt.Bottom,targetX:r,targetY:i,targetPosition:a=Mt.Top,curvature:u=.25}){const[c,d]=D0({pos:n,x1:e,y1:t,x2:r,y2:i,c:u}),[m,h]=D0({pos:a,x1:r,y1:i,x2:e,y2:t,c:u}),[p,y,w,x]=t1({sourceX:e,sourceY:t,targetX:r,targetY:i,sourceControlX:c,sourceControlY:d,targetControlX:m,targetControlY:h});return[`M${e},${t} C${c},${d} ${m},${h} ${r},${i}`,p,y,w,x]}const Wp=_.memo(({sourceX:e,sourceY:t,targetX:n,targetY:r,sourcePosition:i=Mt.Bottom,targetPosition:a=Mt.Top,label:u,labelStyle:c,labelShowBg:d,labelBgStyle:m,labelBgPadding:h,labelBgBorderRadius:p,style:y,markerEnd:w,markerStart:x,pathOptions:k,interactionWidth:b})=>{const[S,$,A]=s1({sourceX:e,sourceY:t,sourcePosition:i,targetX:n,targetY:r,targetPosition:a,curvature:k==null?void 0:k.curvature});return Ne.createElement(yh,{path:S,labelX:$,labelY:A,label:u,labelStyle:c,labelShowBg:d,labelBgStyle:m,labelBgPadding:h,labelBgBorderRadius:p,style:y,markerEnd:w,markerStart:x,interactionWidth:b})});Wp.displayName="BezierEdge";const Vv=_.createContext(null),PD=Vv.Provider;Vv.Consumer;const DD=()=>_.useContext(Vv),FD=e=>"id"in e&&"source"in e&&"target"in e,zD=({source:e,sourceHandle:t,target:n,targetHandle:r})=>`reactflow__edge-${e}${t||""}-${n}${r||""}`,Ow=(e,t)=>typeof e>"u"?"":typeof e=="string"?e:`${t?`${t}__`:""}${Object.keys(e).sort().map(r=>`${r}=${e[r]}`).join("&")}`,BD=(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)),UD=(e,t)=>{if(!e.source||!e.target)return t;let n;return FD(e)?n={...e}:n={...e,id:zD(e)},BD(n,t)?t:t.concat(n)},Pw=({x:e,y:t},[n,r,i],a,[u,c])=>{const d={x:(e-n)/i,y:(t-r)/i};return a?{x:u*Math.round(d.x/u),y:c*Math.round(d.y/c)}:d},r1=({x:e,y:t},[n,r,i])=>({x:e*i+n,y:t*i+r}),Qc=(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],i={x:e.position.x-n,y:e.position.y-r};return{...i,positionAbsolute:e.positionAbsolute?{x:e.positionAbsolute.x-n,y:e.positionAbsolute.y-r}:i}},yg=(e,t=[0,0])=>{if(e.length===0)return{x:0,y:0,width:0,height:0};const n=e.reduce((r,i)=>{const{x:a,y:u}=Qc(i,t).positionAbsolute;return YN(r,Zm({x:a,y:u,width:i.width||0,height:i.height||0}))},{x:1/0,y:1/0,x2:-1/0,y2:-1/0});return XN(n)},i1=(e,t,[n,r,i]=[0,0,1],a=!1,u=!1,c=[0,0])=>{const d={x:(t.x-n)/i,y:(t.y-r)/i,width:t.width/i,height:t.height/i},m=[];return e.forEach(h=>{const{width:p,height:y,selectable:w=!0,hidden:x=!1}=h;if(u&&!w||x)return!1;const{positionAbsolute:k}=Qc(h,c),b={x:k.x,y:k.y,width:p||0,height:y||0},S=Rw(d,b),$=typeof p>"u"||typeof y>"u"||p===null||y===null,A=a&&S>0,E=(p||0)*(y||0);($||A||S>=E||h.dragging)&&m.push(h)}),m},o1=(e,t)=>{const n=e.map(r=>r.id);return t.filter(r=>n.includes(r.source)||n.includes(r.target))},a1=(e,t,n,r,i,a=.1)=>{const u=t/(e.width*(1+a)),c=n/(e.height*(1+a)),d=Math.min(u,c),m=Jd(d,r,i),h=e.x+e.width/2,p=e.y+e.height/2,y=t/2-h*m,w=n/2-p*m;return{x:y,y:w,zoom:m}},qc=(e,t=0)=>e.transition().duration(t);function F0(e,t,n,r){return(t[n]||[]).reduce((i,a)=>{var u,c;return`${e.id}-${a.id}-${n}`!==r&&i.push({id:a.id||null,type:n,nodeId:e.id,x:(((u=e.positionAbsolute)==null?void 0:u.x)??0)+a.x+a.width/2,y:(((c=e.positionAbsolute)==null?void 0:c.y)??0)+a.y+a.height/2}),i},[])}function WD(e,t,n,r,i,a){const{x:u,y:c}=Zl(e),m=t.elementsFromPoint(u,c).find(x=>x.classList.contains("react-flow__handle"));if(m){const x=m.getAttribute("data-nodeid");if(x){const k=Gv(void 0,m),b=m.getAttribute("data-handleid"),S=a({nodeId:x,id:b,type:k});if(S){const $=i.find(A=>A.nodeId===x&&A.type===k&&A.id===b);return{handle:{id:b,type:k,nodeId:x,x:($==null?void 0:$.x)||n.x,y:($==null?void 0:$.y)||n.y},validHandleResult:S}}}}let h=[],p=1/0;if(i.forEach(x=>{const k=Math.sqrt((x.x-n.x)**2+(x.y-n.y)**2);if(k<=r){const b=a(x);k<=p&&(k<p?h=[{handle:x,validHandleResult:b}]:k===p&&h.push({handle:x,validHandleResult:b}),p=k)}}),!h.length)return{handle:null,validHandleResult:l1()};if(h.length===1)return h[0];const y=h.some(({validHandleResult:x})=>x.isValid),w=h.some(({handle:x})=>x.type==="target");return h.find(({handle:x,validHandleResult:k})=>w?x.type==="target":y?k.isValid:!0)||h[0]}const qD={source:null,target:null,sourceHandle:null,targetHandle:null},l1=()=>({handleDomNode:null,isValid:!1,connection:qD,endHandle:null});function c1(e,t,n,r,i,a,u){const c=i==="target",d=u.querySelector(`.react-flow__handle[data-id="${e==null?void 0:e.nodeId}-${e==null?void 0:e.id}-${e==null?void 0:e.type}"]`),m={...l1(),handleDomNode:d};if(d){const h=Gv(void 0,d),p=d.getAttribute("data-nodeid"),y=d.getAttribute("data-handleid"),w=d.classList.contains("connectable"),x=d.classList.contains("connectableend"),k={source:c?p:n,sourceHandle:c?y:r,target:c?n:p,targetHandle:c?r:y};m.connection=k,w&&x&&(t===lu.Strict?c&&h==="source"||!c&&h==="target":p!==n||y!==r)&&(m.endHandle={nodeId:p,handleId:y,type:h},m.isValid=a(k))}return m}function HD({nodes:e,nodeId:t,handleId:n,handleType:r}){return e.reduce((i,a)=>{if(a[qs]){const{handleBounds:u}=a[qs];let c=[],d=[];u&&(c=F0(a,u,"source",`${t}-${n}-${r}`),d=F0(a,u,"target",`${t}-${n}-${r}`)),i.push(...c,...d)}return i},[])}function Gv(e,t){return e||(t!=null&&t.classList.contains("target")?"target":t!=null&&t.classList.contains("source")?"source":null)}function ky(e){e==null||e.classList.remove("valid","connecting","react-flow__handle-valid","react-flow__handle-connecting")}function VD(e,t){let n=null;return t?n="valid":e&&!t&&(n="invalid"),n}function u1({event:e,handleId:t,nodeId:n,onConnect:r,isTarget:i,getState:a,setState:u,isValidConnection:c,edgeUpdaterType:d,onEdgeUpdateEnd:m}){const h=JN(e.target),{connectionMode:p,domNode:y,autoPanOnConnect:w,connectionRadius:x,onConnectStart:k,panBy:b,getNodes:S,cancelConnection:$}=a();let A=0,E;const{x:z,y:F}=Zl(e),M=h==null?void 0:h.elementFromPoint(z,F),D=Gv(d,M),H=y==null?void 0:y.getBoundingClientRect();if(!H||!D)return;let q,I=Zl(e,H),Z=!1,R=null,T=!1,P=null;const L=HD({nodes:S(),nodeId:n,handleId:t,handleType:D}),te=()=>{if(!w)return;const[ne,W]=KN(I,H);b({x:ne,y:W}),A=requestAnimationFrame(te)};u({connectionPosition:I,connectionStatus:null,connectionNodeId:n,connectionHandleId:t,connectionHandleType:D,connectionStartHandle:{nodeId:n,handleId:t,type:D},connectionEndHandle:null}),k==null||k(e,{nodeId:n,handleId:t,handleType:D});function X(ne){const{transform:W}=a();I=Zl(ne,H);const{handle:Y,validHandleResult:K}=WD(ne,h,Pw(I,W,!1,[1,1]),x,L,fe=>c1(fe,p,n,t,i?"target":"source",c,h));if(E=Y,Z||(te(),Z=!0),P=K.handleDomNode,R=K.connection,T=K.isValid,u({connectionPosition:E&&T?r1({x:E.x,y:E.y},W):I,connectionStatus:VD(!!E,T),connectionEndHandle:K.endHandle}),!E&&!T&&!P)return ky(q);R.source!==R.target&&P&&(ky(q),q=P,P.classList.add("connecting","react-flow__handle-connecting"),P.classList.toggle("valid",T),P.classList.toggle("react-flow__handle-valid",T))}function V(ne){var W,Y;(E||P)&&R&&T&&(r==null||r(R)),(Y=(W=a()).onConnectEnd)==null||Y.call(W,ne),d&&(m==null||m(ne)),ky(q),$(),cancelAnimationFrame(A),Z=!1,T=!1,R=null,P=null,h.removeEventListener("mousemove",X),h.removeEventListener("mouseup",V),h.removeEventListener("touchmove",X),h.removeEventListener("touchend",V)}h.addEventListener("mousemove",X),h.addEventListener("mouseup",V),h.addEventListener("touchmove",X),h.addEventListener("touchend",V)}const z0=()=>!0,GD=e=>({connectionStartHandle:e.connectionStartHandle,connectOnClick:e.connectOnClick,noPanClassName:e.noPanClassName}),KD=(e,t,n)=>r=>{const{connectionStartHandle:i,connectionEndHandle:a,connectionClickStartHandle:u}=r;return{connecting:(i==null?void 0:i.nodeId)===e&&(i==null?void 0:i.handleId)===t&&(i==null?void 0:i.type)===n||(a==null?void 0:a.nodeId)===e&&(a==null?void 0:a.handleId)===t&&(a==null?void 0:a.type)===n,clickConnecting:(u==null?void 0:u.nodeId)===e&&(u==null?void 0:u.handleId)===t&&(u==null?void 0:u.type)===n}},d1=_.forwardRef(({type:e="source",position:t=Mt.Top,isValidConnection:n,isConnectable:r=!0,isConnectableStart:i=!0,isConnectableEnd:a=!0,id:u,onConnect:c,children:d,className:m,onMouseDown:h,onTouchStart:p,...y},w)=>{var H,q;const x=u||null,k=e==="target",b=er(),S=DD(),{connectOnClick:$,noPanClassName:A}=fs(GD,hr),{connecting:E,clickConnecting:z}=fs(KD(S,x,e),hr);S||(q=(H=b.getState()).onError)==null||q.call(H,"010",Za.error010());const F=I=>{const{defaultEdgeOptions:Z,onConnect:R,hasDefaultEdges:T}=b.getState(),P={...Z,...I};if(T){const{edges:L,setEdges:te}=b.getState();te(UD(P,L))}R==null||R(P),c==null||c(P)},M=I=>{if(!S)return;const Z=QN(I);i&&(Z&&I.button===0||!Z)&&u1({event:I,handleId:x,nodeId:S,onConnect:F,isTarget:k,getState:b.getState,setState:b.setState,isValidConnection:n||b.getState().isValidConnection||z0}),Z?h==null||h(I):p==null||p(I)},D=I=>{const{onClickConnectStart:Z,onClickConnectEnd:R,connectionClickStartHandle:T,connectionMode:P,isValidConnection:L}=b.getState();if(!S||!T&&!i)return;if(!T){Z==null||Z(I,{nodeId:S,handleId:x,handleType:e}),b.setState({connectionClickStartHandle:{nodeId:S,type:e,handleId:x}});return}const te=JN(I.target),X=n||L||z0,{connection:V,isValid:ne}=c1({nodeId:S,id:x,type:e},P,T.nodeId,T.handleId||null,T.type,X,te);ne&&F(V),R==null||R(I),b.setState({connectionClickStartHandle:null})};return Ne.createElement("div",{"data-handleid":x,"data-nodeid":S,"data-handlepos":t,"data-id":`${S}-${x}-${e}`,className:$r(["react-flow__handle",`react-flow__handle-${t}`,"nodrag",A,m,{source:!k,target:k,connectable:r,connectablestart:i,connectableend:a,connecting:z,connectionindicator:r&&(i&&!E||a&&E)}]),onMouseDown:M,onTouchStart:M,onClick:$?D:void 0,ref:w,...y},d)});d1.displayName="Handle";var qp=_.memo(d1);const f1=({data:e,isConnectable:t,targetPosition:n=Mt.Top,sourcePosition:r=Mt.Bottom})=>Ne.createElement(Ne.Fragment,null,Ne.createElement(qp,{type:"target",position:n,isConnectable:t}),e==null?void 0:e.label,Ne.createElement(qp,{type:"source",position:r,isConnectable:t}));f1.displayName="DefaultNode";var Dw=_.memo(f1);const m1=({data:e,isConnectable:t,sourcePosition:n=Mt.Bottom})=>Ne.createElement(Ne.Fragment,null,e==null?void 0:e.label,Ne.createElement(qp,{type:"source",position:n,isConnectable:t}));m1.displayName="InputNode";var h1=_.memo(m1);const _1=({data:e,isConnectable:t,targetPosition:n=Mt.Top})=>Ne.createElement(Ne.Fragment,null,Ne.createElement(qp,{type:"target",position:n,isConnectable:t}),e==null?void 0:e.label);_1.displayName="OutputNode";var p1=_.memo(_1);const Kv=()=>null;Kv.displayName="GroupNode";const JD=e=>({selectedNodes:e.getNodes().filter(t=>t.selected),selectedEdges:e.edges.filter(t=>t.selected)}),Y_=e=>e.id;function YD(e,t){return hr(e.selectedNodes.map(Y_),t.selectedNodes.map(Y_))&&hr(e.selectedEdges.map(Y_),t.selectedEdges.map(Y_))}const g1=_.memo(({onSelectionChange:e})=>{const t=er(),{selectedNodes:n,selectedEdges:r}=fs(JD,YD);return _.useEffect(()=>{const i={nodes:n,edges:r};e==null||e(i),t.getState().onSelectionChange.forEach(a=>a(i))},[n,r,e]),null});g1.displayName="SelectionListener";const XD=e=>!!e.onSelectionChange;function ZD({onSelectionChange:e}){const t=fs(XD);return e||t?Ne.createElement(g1,{onSelectionChange:e}):null}const QD=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 yd(e,t){_.useEffect(()=>{typeof e<"u"&&t(e)},[e])}function gn(e,t,n){_.useEffect(()=>{typeof t<"u"&&n({[e]:t})},[t])}const e6=({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,onConnect:i,onConnectStart:a,onConnectEnd:u,onClickConnectStart:c,onClickConnectEnd:d,nodesDraggable:m,nodesConnectable:h,nodesFocusable:p,edgesFocusable:y,edgesUpdatable:w,elevateNodesOnSelect:x,minZoom:k,maxZoom:b,nodeExtent:S,onNodesChange:$,onEdgesChange:A,elementsSelectable:E,connectionMode:z,snapGrid:F,snapToGrid:M,translateExtent:D,connectOnClick:H,defaultEdgeOptions:q,fitView:I,fitViewOptions:Z,onNodesDelete:R,onEdgesDelete:T,onNodeDrag:P,onNodeDragStart:L,onNodeDragStop:te,onSelectionDrag:X,onSelectionDragStart:V,onSelectionDragStop:ne,noPanClassName:W,nodeOrigin:Y,rfId:K,autoPanOnConnect:fe,autoPanOnNodeDrag:ae,onError:ve,connectionRadius:ge,isValidConnection:pe,nodeDragThreshold:$e})=>{const{setNodes:De,setEdges:ot,setDefaultNodesAndEdges:bt,setMinZoom:Ue,setMaxZoom:at,setTranslateExtent:Nt,setNodeExtent:ut,reset:Se}=fs(QD,hr),me=er();return _.useEffect(()=>{const Ve=r==null?void 0:r.map(ye=>({...ye,...q}));return bt(n,Ve),()=>{Se()}},[]),gn("defaultEdgeOptions",q,me.setState),gn("connectionMode",z,me.setState),gn("onConnect",i,me.setState),gn("onConnectStart",a,me.setState),gn("onConnectEnd",u,me.setState),gn("onClickConnectStart",c,me.setState),gn("onClickConnectEnd",d,me.setState),gn("nodesDraggable",m,me.setState),gn("nodesConnectable",h,me.setState),gn("nodesFocusable",p,me.setState),gn("edgesFocusable",y,me.setState),gn("edgesUpdatable",w,me.setState),gn("elementsSelectable",E,me.setState),gn("elevateNodesOnSelect",x,me.setState),gn("snapToGrid",M,me.setState),gn("snapGrid",F,me.setState),gn("onNodesChange",$,me.setState),gn("onEdgesChange",A,me.setState),gn("connectOnClick",H,me.setState),gn("fitViewOnInit",I,me.setState),gn("fitViewOnInitOptions",Z,me.setState),gn("onNodesDelete",R,me.setState),gn("onEdgesDelete",T,me.setState),gn("onNodeDrag",P,me.setState),gn("onNodeDragStart",L,me.setState),gn("onNodeDragStop",te,me.setState),gn("onSelectionDrag",X,me.setState),gn("onSelectionDragStart",V,me.setState),gn("onSelectionDragStop",ne,me.setState),gn("noPanClassName",W,me.setState),gn("nodeOrigin",Y,me.setState),gn("rfId",K,me.setState),gn("autoPanOnConnect",fe,me.setState),gn("autoPanOnNodeDrag",ae,me.setState),gn("onError",ve,me.setState),gn("connectionRadius",ge,me.setState),gn("isValidConnection",pe,me.setState),gn("nodeDragThreshold",$e,me.setState),yd(e,De),yd(t,ot),yd(k,Ue),yd(b,at),yd(D,Nt),yd(S,ut),null},B0={display:"none"},t6={position:"absolute",width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0px, 0px, 0px, 0px)",clipPath:"inset(100%)"},y1="react-flow__node-desc",w1="react-flow__edge-desc",n6="react-flow__aria-live",s6=e=>e.ariaLiveMessage;function r6({rfId:e}){const t=fs(s6);return Ne.createElement("div",{id:`${n6}-${e}`,"aria-live":"assertive","aria-atomic":"true",style:t6},t)}function i6({rfId:e,disableKeyboardA11y:t}){return Ne.createElement(Ne.Fragment,null,Ne.createElement("div",{id:`${y1}-${e}`,style:B0},"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."," "),Ne.createElement("div",{id:`${w1}-${e}`,style:B0},"Press enter or space to select an edge. You can then press delete to remove it or escape to cancel."),!t&&Ne.createElement(r6,{rfId:e}))}var th=(e=null,t={actInsideInputWithModifier:!0})=>{const[n,r]=_.useState(!1),i=_.useRef(!1),a=_.useRef(new Set([])),[u,c]=_.useMemo(()=>{if(e!==null){const m=(Array.isArray(e)?e:[e]).filter(p=>typeof p=="string").map(p=>p.split("+")),h=m.reduce((p,y)=>p.concat(...y),[]);return[m,h]}return[[],[]]},[e]);return _.useEffect(()=>{const d=typeof document<"u"?document:null,m=(t==null?void 0:t.target)||d;if(e!==null){const h=w=>{if(i.current=w.ctrlKey||w.metaKey||w.shiftKey,(!i.current||i.current&&!t.actInsideInputWithModifier)&&Lw(w))return!1;const k=W0(w.code,c);a.current.add(w[k]),U0(u,a.current,!1)&&(w.preventDefault(),r(!0))},p=w=>{if((!i.current||i.current&&!t.actInsideInputWithModifier)&&Lw(w))return!1;const k=W0(w.code,c);U0(u,a.current,!0)?(r(!1),a.current.clear()):a.current.delete(w[k]),w.key==="Meta"&&a.current.clear(),i.current=!1},y=()=>{a.current.clear(),r(!1)};return m==null||m.addEventListener("keydown",h),m==null||m.addEventListener("keyup",p),window.addEventListener("blur",y),()=>{m==null||m.removeEventListener("keydown",h),m==null||m.removeEventListener("keyup",p),window.removeEventListener("blur",y)}}},[e,r]),n};function U0(e,t,n){return e.filter(r=>n||r.length===t.size).some(r=>r.every(i=>t.has(i)))}function W0(e,t){return t.includes(e)?"code":"key"}function v1(e,t,n,r){var u,c;if(!e.parentNode)return n;const i=t.get(e.parentNode),a=Qc(i,r);return v1(i,t,{x:(n.x??0)+a.x,y:(n.y??0)+a.y,z:(((u=i[qs])==null?void 0:u.z)??0)>(n.z??0)?((c=i[qs])==null?void 0:c.z)??0:n.z??0},r)}function x1(e,t,n){e.forEach(r=>{var i;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:a,y:u,z:c}=v1(r,e,{...r.position,z:((i=r[qs])==null?void 0:i.z)??0},t);r.positionAbsolute={x:a,y:u},r[qs].z=c,n!=null&&n[r.id]&&(r[qs].isParent=!0)}})}function jy(e,t,n,r){const i=new Map,a={},u=r?1e3:0;return e.forEach(c=>{var y;const d=(ho(c.zIndex)?c.zIndex:0)+(c.selected?u:0),m=t.get(c.id),h={...c,positionAbsolute:{x:c.position.x,y:c.position.y}};c.parentNode&&(a[c.parentNode]=!0);const p=(m==null?void 0:m.type)&&(m==null?void 0:m.type)!==c.type;Object.defineProperty(h,qs,{enumerable:!1,value:{handleBounds:p||(y=m==null?void 0:m[qs])==null?void 0:y.handleBounds,z:d}}),i.set(c.id,h)}),x1(i,n,a),i}function b1(e,t={}){const{getNodes:n,width:r,height:i,minZoom:a,maxZoom:u,d3Zoom:c,d3Selection:d,fitViewOnInitDone:m,fitViewOnInit:h,nodeOrigin:p}=e(),y=t.initial&&!m&&h;if(c&&d&&(y||!t.initial)){const x=n().filter(b=>{var $;const S=t.includeHiddenNodes?b.width&&b.height:!b.hidden;return($=t.nodes)!=null&&$.length?S&&t.nodes.some(A=>A.id===b.id):S}),k=x.every(b=>b.width&&b.height);if(x.length>0&&k){const b=yg(x,p),{x:S,y:$,zoom:A}=a1(b,r,i,t.minZoom??a,t.maxZoom??u,t.padding??.1),E=Ka.translate(S,$).scale(A);return typeof t.duration=="number"&&t.duration>0?c.transform(qc(d,t.duration),E):c.transform(d,E),!0}}return!1}function o6(e,t){return e.forEach(n=>{const r=t.get(n.id);r&&t.set(r.id,{...r,[qs]:r[qs],selected:n.selected})}),new Map(t)}function a6(e,t){return t.map(n=>{const r=e.find(i=>i.id===n.id);return r&&(n.selected=r.selected),n})}function X_({changedNodes:e,changedEdges:t,get:n,set:r}){const{nodeInternals:i,edges:a,onNodesChange:u,onEdgesChange:c,hasDefaultNodes:d,hasDefaultEdges:m}=n();e!=null&&e.length&&(d&&r({nodeInternals:o6(e,i)}),u==null||u(e)),t!=null&&t.length&&(m&&r({edges:a6(t,a)}),c==null||c(t))}const wd=()=>{},l6={zoomIn:wd,zoomOut:wd,zoomTo:wd,getZoom:()=>1,setViewport:wd,getViewport:()=>({x:0,y:0,zoom:1}),fitView:()=>!1,setCenter:wd,fitBounds:wd,project:e=>e,screenToFlowPosition:e=>e,flowToScreenPosition:e=>e,viewportInitialized:!1},c6=e=>({d3Zoom:e.d3Zoom,d3Selection:e.d3Selection}),u6=()=>{const e=er(),{d3Zoom:t,d3Selection:n}=fs(c6,hr);return _.useMemo(()=>n&&t?{zoomIn:i=>t.scaleBy(qc(n,i==null?void 0:i.duration),1.2),zoomOut:i=>t.scaleBy(qc(n,i==null?void 0:i.duration),1/1.2),zoomTo:(i,a)=>t.scaleTo(qc(n,a==null?void 0:a.duration),i),getZoom:()=>e.getState().transform[2],setViewport:(i,a)=>{const[u,c,d]=e.getState().transform,m=Ka.translate(i.x??u,i.y??c).scale(i.zoom??d);t.transform(qc(n,a==null?void 0:a.duration),m)},getViewport:()=>{const[i,a,u]=e.getState().transform;return{x:i,y:a,zoom:u}},fitView:i=>b1(e.getState,i),setCenter:(i,a,u)=>{const{width:c,height:d,maxZoom:m}=e.getState(),h=typeof(u==null?void 0:u.zoom)<"u"?u.zoom:m,p=c/2-i*h,y=d/2-a*h,w=Ka.translate(p,y).scale(h);t.transform(qc(n,u==null?void 0:u.duration),w)},fitBounds:(i,a)=>{const{width:u,height:c,minZoom:d,maxZoom:m}=e.getState(),{x:h,y:p,zoom:y}=a1(i,u,c,d,m,(a==null?void 0:a.padding)??.1),w=Ka.translate(h,p).scale(y);t.transform(qc(n,a==null?void 0:a.duration),w)},project:i=>{const{transform:a,snapToGrid:u,snapGrid:c}=e.getState();return console.warn("[DEPRECATED] `project` is deprecated. Instead use `screenToFlowPosition`. There is no need to subtract the react flow bounds anymore! https://reactflow.dev/api-reference/types/react-flow-instance#screen-to-flow-position"),Pw(i,a,u,c)},screenToFlowPosition:i=>{const{transform:a,snapToGrid:u,snapGrid:c,domNode:d}=e.getState();if(!d)return i;const{x:m,y:h}=d.getBoundingClientRect(),p={x:i.x-m,y:i.y-h};return Pw(p,a,u,c)},flowToScreenPosition:i=>{const{transform:a,domNode:u}=e.getState();if(!u)return i;const{x:c,y:d}=u.getBoundingClientRect(),m=r1(i,a);return{x:m.x+c,y:m.y+d}},viewportInitialized:!0}:l6,[t,n])};function Jv(){const e=u6(),t=er(),n=_.useCallback(()=>t.getState().getNodes().map(k=>({...k})),[]),r=_.useCallback(k=>t.getState().nodeInternals.get(k),[]),i=_.useCallback(()=>{const{edges:k=[]}=t.getState();return k.map(b=>({...b}))},[]),a=_.useCallback(k=>{const{edges:b=[]}=t.getState();return b.find(S=>S.id===k)},[]),u=_.useCallback(k=>{const{getNodes:b,setNodes:S,hasDefaultNodes:$,onNodesChange:A}=t.getState(),E=b(),z=typeof k=="function"?k(E):k;if($)S(z);else if(A){const F=z.length===0?E.map(M=>({type:"remove",id:M.id})):z.map(M=>({item:M,type:"reset"}));A(F)}},[]),c=_.useCallback(k=>{const{edges:b=[],setEdges:S,hasDefaultEdges:$,onEdgesChange:A}=t.getState(),E=typeof k=="function"?k(b):k;if($)S(E);else if(A){const z=E.length===0?b.map(F=>({type:"remove",id:F.id})):E.map(F=>({item:F,type:"reset"}));A(z)}},[]),d=_.useCallback(k=>{const b=Array.isArray(k)?k:[k],{getNodes:S,setNodes:$,hasDefaultNodes:A,onNodesChange:E}=t.getState();if(A){const F=[...S(),...b];$(F)}else if(E){const z=b.map(F=>({item:F,type:"add"}));E(z)}},[]),m=_.useCallback(k=>{const b=Array.isArray(k)?k:[k],{edges:S=[],setEdges:$,hasDefaultEdges:A,onEdgesChange:E}=t.getState();if(A)$([...S,...b]);else if(E){const z=b.map(F=>({item:F,type:"add"}));E(z)}},[]),h=_.useCallback(()=>{const{getNodes:k,edges:b=[],transform:S}=t.getState(),[$,A,E]=S;return{nodes:k().map(z=>({...z})),edges:b.map(z=>({...z})),viewport:{x:$,y:A,zoom:E}}},[]),p=_.useCallback(({nodes:k,edges:b})=>{const{nodeInternals:S,getNodes:$,edges:A,hasDefaultNodes:E,hasDefaultEdges:z,onNodesDelete:F,onEdgesDelete:M,onNodesChange:D,onEdgesChange:H}=t.getState(),q=(k||[]).map(P=>P.id),I=(b||[]).map(P=>P.id),Z=$().reduce((P,L)=>{const te=!q.includes(L.id)&&L.parentNode&&P.find(V=>V.id===L.parentNode);return(typeof L.deletable=="boolean"?L.deletable:!0)&&(q.includes(L.id)||te)&&P.push(L),P},[]),R=A.filter(P=>typeof P.deletable=="boolean"?P.deletable:!0),T=R.filter(P=>I.includes(P.id));if(Z||T){const P=o1(Z,R),L=[...T,...P],te=L.reduce((X,V)=>(X.includes(V.id)||X.push(V.id),X),[]);if((z||E)&&(z&&t.setState({edges:A.filter(X=>!te.includes(X.id))}),E&&(Z.forEach(X=>{S.delete(X.id)}),t.setState({nodeInternals:new Map(S)}))),te.length>0&&(M==null||M(L),H&&H(te.map(X=>({id:X,type:"remove"})))),Z.length>0&&(F==null||F(Z),D)){const X=Z.map(V=>({id:V.id,type:"remove"}));D(X)}}},[]),y=_.useCallback(k=>{const b=AD(k),S=b?null:t.getState().nodeInternals.get(k.id);return!b&&!S?[null,null,b]:[b?k:L0(S),S,b]},[]),w=_.useCallback((k,b=!0,S)=>{const[$,A,E]=y(k);return $?(S||t.getState().getNodes()).filter(z=>{if(!E&&(z.id===A.id||!z.positionAbsolute))return!1;const F=L0(z),M=Rw(F,$);return b&&M>0||M>=$.width*$.height}):[]},[]),x=_.useCallback((k,b,S=!0)=>{const[$]=y(k);if(!$)return!1;const A=Rw($,b);return S&&A>0||A>=$.width*$.height},[]);return _.useMemo(()=>({...e,getNodes:n,getNode:r,getEdges:i,getEdge:a,setNodes:u,setEdges:c,addNodes:d,addEdges:m,toObject:h,deleteElements:p,getIntersectingNodes:w,isNodeIntersecting:x}),[e,n,r,i,a,u,c,d,m,h,p,w,x])}const d6={actInsideInputWithModifier:!1};var f6=({deleteKeyCode:e,multiSelectionKeyCode:t})=>{const n=er(),{deleteElements:r}=Jv(),i=th(e,d6),a=th(t);_.useEffect(()=>{if(i){const{edges:u,getNodes:c}=n.getState(),d=c().filter(h=>h.selected),m=u.filter(h=>h.selected);r({nodes:d,edges:m}),n.setState({nodesSelectionActive:!1})}},[i]),_.useEffect(()=>{n.setState({multiSelectionActive:a})},[a])};function m6(e){const t=er();_.useEffect(()=>{let n;const r=()=>{var a,u;if(!e.current)return;const i=Bv(e.current);(i.height===0||i.width===0)&&((u=(a=t.getState()).onError)==null||u.call(a,"004",Za.error004())),t.setState({width:i.width||500,height:i.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 Yv={position:"absolute",width:"100%",height:"100%",top:0,left:0},h6=(e,t)=>e.x!==t.x||e.y!==t.y||e.zoom!==t.k,Z_=e=>({x:e.x,y:e.y,zoom:e.k}),vd=(e,t)=>e.target.closest(`.${t}`),q0=(e,t)=>t===2&&Array.isArray(e)&&e.includes(2),H0=e=>{const t=e.ctrlKey&&Up()?10:1;return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*t},_6=e=>({d3Zoom:e.d3Zoom,d3Selection:e.d3Selection,d3ZoomHandler:e.d3ZoomHandler,userSelectionActive:e.userSelectionActive}),p6=({onMove:e,onMoveStart:t,onMoveEnd:n,onPaneContextMenu:r,zoomOnScroll:i=!0,zoomOnPinch:a=!0,panOnScroll:u=!1,panOnScrollSpeed:c=.5,panOnScrollMode:d=Kc.Free,zoomOnDoubleClick:m=!0,elementsSelectable:h,panOnDrag:p=!0,defaultViewport:y,translateExtent:w,minZoom:x,maxZoom:k,zoomActivationKeyCode:b,preventScrolling:S=!0,children:$,noWheelClassName:A,noPanClassName:E})=>{const z=_.useRef(),F=er(),M=_.useRef(!1),D=_.useRef(!1),H=_.useRef(null),q=_.useRef({x:0,y:0,zoom:0}),{d3Zoom:I,d3Selection:Z,d3ZoomHandler:R,userSelectionActive:T}=fs(_6,hr),P=th(b),L=_.useRef(0),te=_.useRef(!1),X=_.useRef();return m6(H),_.useEffect(()=>{if(H.current){const V=H.current.getBoundingClientRect(),ne=VN().scaleExtent([x,k]).translateExtent(w),W=mo(H.current).call(ne),Y=Ka.translate(y.x,y.y).scale(Jd(y.zoom,x,k)),K=[[0,0],[V.width,V.height]],fe=ne.constrain()(Y,K,w);ne.transform(W,fe),ne.wheelDelta(H0),F.setState({d3Zoom:ne,d3Selection:W,d3ZoomHandler:W.on("wheel.zoom"),transform:[fe.x,fe.y,fe.k],domNode:H.current.closest(".react-flow")})}},[]),_.useEffect(()=>{Z&&I&&(u&&!P&&!T?Z.on("wheel.zoom",V=>{if(vd(V,A))return!1;V.preventDefault(),V.stopImmediatePropagation();const ne=Z.property("__zoom").k||1,W=Up();if(V.ctrlKey&&a&&W){const $e=zo(V),De=H0(V),ot=ne*Math.pow(2,De);I.scaleTo(Z,ot,$e,V);return}const Y=V.deltaMode===1?20:1;let K=d===Kc.Vertical?0:V.deltaX*Y,fe=d===Kc.Horizontal?0:V.deltaY*Y;!W&&V.shiftKey&&d!==Kc.Vertical&&(K=V.deltaY*Y,fe=0),I.translateBy(Z,-(K/ne)*c,-(fe/ne)*c,{internal:!0});const ae=Z_(Z.property("__zoom")),{onViewportChangeStart:ve,onViewportChange:ge,onViewportChangeEnd:pe}=F.getState();clearTimeout(X.current),te.current||(te.current=!0,t==null||t(V,ae),ve==null||ve(ae)),te.current&&(e==null||e(V,ae),ge==null||ge(ae),X.current=setTimeout(()=>{n==null||n(V,ae),pe==null||pe(ae),te.current=!1},150))},{passive:!1}):typeof R<"u"&&Z.on("wheel.zoom",function(V,ne){if(!S||vd(V,A))return null;V.preventDefault(),R.call(this,V,ne)},{passive:!1}))},[T,u,d,Z,I,R,P,a,S,A,t,e,n]),_.useEffect(()=>{I&&I.on("start",V=>{var Y,K;if(!V.sourceEvent||V.sourceEvent.internal)return null;L.current=(Y=V.sourceEvent)==null?void 0:Y.button;const{onViewportChangeStart:ne}=F.getState(),W=Z_(V.transform);M.current=!0,q.current=W,((K=V.sourceEvent)==null?void 0:K.type)==="mousedown"&&F.setState({paneDragging:!0}),ne==null||ne(W),t==null||t(V.sourceEvent,W)})},[I,t]),_.useEffect(()=>{I&&(T&&!M.current?I.on("zoom",null):T||I.on("zoom",V=>{var W;const{onViewportChange:ne}=F.getState();if(F.setState({transform:[V.transform.x,V.transform.y,V.transform.k]}),D.current=!!(r&&q0(p,L.current??0)),(e||ne)&&!((W=V.sourceEvent)!=null&&W.internal)){const Y=Z_(V.transform);ne==null||ne(Y),e==null||e(V.sourceEvent,Y)}}))},[T,I,e,p,r]),_.useEffect(()=>{I&&I.on("end",V=>{if(!V.sourceEvent||V.sourceEvent.internal)return null;const{onViewportChangeEnd:ne}=F.getState();if(M.current=!1,F.setState({paneDragging:!1}),r&&q0(p,L.current??0)&&!D.current&&r(V.sourceEvent),D.current=!1,(n||ne)&&h6(q.current,V.transform)){const W=Z_(V.transform);q.current=W,clearTimeout(z.current),z.current=setTimeout(()=>{ne==null||ne(W),n==null||n(V.sourceEvent,W)},u?150:0)}})},[I,u,p,n,r]),_.useEffect(()=>{I&&I.filter(V=>{const ne=P||i,W=a&&V.ctrlKey;if((p===!0||Array.isArray(p)&&p.includes(1))&&V.button===1&&V.type==="mousedown"&&(vd(V,"react-flow__node")||vd(V,"react-flow__edge")))return!0;if(!p&&!ne&&!u&&!m&&!a||T||!m&&V.type==="dblclick"||vd(V,A)&&V.type==="wheel"||vd(V,E)&&(V.type!=="wheel"||u&&V.type==="wheel"&&!P)||!a&&V.ctrlKey&&V.type==="wheel"||!ne&&!u&&!W&&V.type==="wheel"||!p&&(V.type==="mousedown"||V.type==="touchstart")||Array.isArray(p)&&!p.includes(V.button)&&(V.type==="mousedown"||V.type==="touchstart"))return!1;const Y=Array.isArray(p)&&p.includes(V.button)||!V.button||V.button<=1;return(!V.ctrlKey||V.type==="wheel")&&Y})},[T,I,i,a,u,m,p,h,P]),Ne.createElement("div",{className:"react-flow__renderer",ref:H,style:Yv},$)},g6=e=>({userSelectionActive:e.userSelectionActive,userSelectionRect:e.userSelectionRect});function y6(){const{userSelectionActive:e,userSelectionRect:t}=fs(g6,hr);return e&&t?Ne.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 V0(e,t){const n=e.find(r=>r.id===t.parentNode);if(n){const r=t.position.x+t.width-n.width,i=t.position.y+t.height-n.height;if(r>0||i>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),i>0&&(n.style.height+=i),t.position.x<0){const a=Math.abs(t.position.x);n.position.x=n.position.x-a,n.style.width+=a,t.position.x=0}if(t.position.y<0){const a=Math.abs(t.position.y);n.position.y=n.position.y-a,n.style.height+=a,t.position.y=0}n.width=n.style.width,n.height=n.style.height}}}function w6(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,i)=>{const a=e.filter(c=>c.id===i.id);if(a.length===0)return r.push(i),r;const u={...i};for(const c of a)if(c)switch(c.type){case"select":{u.selected=c.selected;break}case"position":{typeof c.position<"u"&&(u.position=c.position),typeof c.positionAbsolute<"u"&&(u.positionAbsolute=c.positionAbsolute),typeof c.dragging<"u"&&(u.dragging=c.dragging),u.expandParent&&V0(r,u);break}case"dimensions":{typeof c.dimensions<"u"&&(u.width=c.dimensions.width,u.height=c.dimensions.height),typeof c.updateStyle<"u"&&(u.style={...u.style||{},...c.dimensions}),typeof c.resizing=="boolean"&&(u.resizing=c.resizing),u.expandParent&&V0(r,u);break}case"remove":return r}return r.push(u),r},n)}function v6(e,t){return w6(e,t)}const Gl=(e,t)=>({id:e,type:"select",selected:t});function Md(e,t){return e.reduce((n,r)=>{const i=t.includes(r.id);return!r.selected&&i?(r.selected=!0,n.push(Gl(r.id,!0))):r.selected&&!i&&(r.selected=!1,n.push(Gl(r.id,!1))),n},[])}const Sy=(e,t)=>n=>{n.target===t.current&&(e==null||e(n))},x6=e=>({userSelectionActive:e.userSelectionActive,elementsSelectable:e.elementsSelectable,dragging:e.paneDragging}),k1=_.memo(({isSelecting:e,selectionMode:t=Qm.Full,panOnDrag:n,onSelectionStart:r,onSelectionEnd:i,onPaneClick:a,onPaneContextMenu:u,onPaneScroll:c,onPaneMouseEnter:d,onPaneMouseMove:m,onPaneMouseLeave:h,children:p})=>{const y=_.useRef(null),w=er(),x=_.useRef(0),k=_.useRef(0),b=_.useRef(),{userSelectionActive:S,elementsSelectable:$,dragging:A}=fs(x6,hr),E=()=>{w.setState({userSelectionActive:!1,userSelectionRect:null}),x.current=0,k.current=0},z=R=>{a==null||a(R),w.getState().resetSelectedElements(),w.setState({nodesSelectionActive:!1})},F=R=>{if(Array.isArray(n)&&(n!=null&&n.includes(2))){R.preventDefault();return}u==null||u(R)},M=c?R=>c(R):void 0,D=R=>{const{resetSelectedElements:T,domNode:P}=w.getState();if(b.current=P==null?void 0:P.getBoundingClientRect(),!$||!e||R.button!==0||R.target!==y.current||!b.current)return;const{x:L,y:te}=Zl(R,b.current);T(),w.setState({userSelectionRect:{width:0,height:0,startX:L,startY:te,x:L,y:te}}),r==null||r(R)},H=R=>{const{userSelectionRect:T,nodeInternals:P,edges:L,transform:te,onNodesChange:X,onEdgesChange:V,nodeOrigin:ne,getNodes:W}=w.getState();if(!e||!b.current||!T)return;w.setState({userSelectionActive:!0,nodesSelectionActive:!1});const Y=Zl(R,b.current),K=T.startX??0,fe=T.startY??0,ae={...T,x:Y.x<K?Y.x:K,y:Y.y<fe?Y.y:fe,width:Math.abs(Y.x-K),height:Math.abs(Y.y-fe)},ve=W(),ge=i1(P,ae,te,t===Qm.Partial,!0,ne),pe=o1(ge,L).map(De=>De.id),$e=ge.map(De=>De.id);if(x.current!==$e.length){x.current=$e.length;const De=Md(ve,$e);De.length&&(X==null||X(De))}if(k.current!==pe.length){k.current=pe.length;const De=Md(L,pe);De.length&&(V==null||V(De))}w.setState({userSelectionRect:ae})},q=R=>{if(R.button!==0)return;const{userSelectionRect:T}=w.getState();!S&&T&&R.target===y.current&&(z==null||z(R)),w.setState({nodesSelectionActive:x.current>0}),E(),i==null||i(R)},I=R=>{S&&(w.setState({nodesSelectionActive:x.current>0}),i==null||i(R)),E()},Z=$&&(e||S);return Ne.createElement("div",{className:$r(["react-flow__pane",{dragging:A,selection:e}]),onClick:Z?void 0:Sy(z,y),onContextMenu:Sy(F,y),onWheel:Sy(M,y),onMouseEnter:Z?void 0:d,onMouseDown:Z?D:void 0,onMouseMove:Z?H:m,onMouseUp:Z?q:void 0,onMouseLeave:Z?I:h,ref:y,style:Yv},p,Ne.createElement(y6,null))});k1.displayName="Pane";function j1(e,t){if(!e.parentNode)return!1;const n=t.get(e.parentNode);return n?n.selected?!0:j1(n,t):!1}function G0(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 b6(e,t,n,r){return Array.from(e.values()).filter(i=>(i.selected||i.id===r)&&(!i.parentNode||!j1(i,e))&&(i.draggable||t&&typeof i.draggable>"u")).map(i=>{var a,u;return{id:i.id,position:i.position||{x:0,y:0},positionAbsolute:i.positionAbsolute||{x:0,y:0},distance:{x:n.x-(((a=i.positionAbsolute)==null?void 0:a.x)??0),y:n.y-(((u=i.positionAbsolute)==null?void 0:u.y)??0)},delta:{x:0,y:0},extent:i.extent,parentNode:i.parentNode,width:i.width,height:i.height,expandParent:i.expandParent}})}function k6(e,t){return!t||t==="parent"?t:[t[0],[t[1][0]-(e.width||0),t[1][1]-(e.height||0)]]}function S1(e,t,n,r,i=[0,0],a){const u=k6(e,e.extent||r);let c=u;if(e.extent==="parent"&&!e.expandParent)if(e.parentNode&&e.width&&e.height){const h=n.get(e.parentNode),{x:p,y}=Qc(h,i).positionAbsolute;c=h&&ho(p)&&ho(y)&&ho(h.width)&&ho(h.height)?[[p+e.width*i[0],y+e.height*i[1]],[p+h.width-e.width+e.width*i[0],y+h.height-e.height+e.height*i[1]]]:c}else a==null||a("005",Za.error005()),c=u;else if(e.extent&&e.parentNode&&e.extent!=="parent"){const h=n.get(e.parentNode),{x:p,y}=Qc(h,i).positionAbsolute;c=[[e.extent[0][0]+p,e.extent[0][1]+y],[e.extent[1][0]+p,e.extent[1][1]+y]]}let d={x:0,y:0};if(e.parentNode){const h=n.get(e.parentNode);d=Qc(h,i).positionAbsolute}const m=c&&c!=="parent"?Uv(t,c):t;return{position:{x:m.x-d.x,y:m.y-d.y},positionAbsolute:m}}function Ny({nodeId:e,dragItems:t,nodeInternals:n}){const r=t.map(i=>({...n.get(i.id),position:i.position,positionAbsolute:i.positionAbsolute}));return[e?r.find(i=>i.id===e):r[0],r]}const K0=(e,t,n,r)=>{const i=t.querySelectorAll(e);if(!i||!i.length)return null;const a=Array.from(i),u=t.getBoundingClientRect(),c={x:u.width*r[0],y:u.height*r[1]};return a.map(d=>{const m=d.getBoundingClientRect();return{id:d.getAttribute("data-handleid"),position:d.getAttribute("data-handlepos"),x:(m.left-u.left-c.x)/n,y:(m.top-u.top-c.y)/n,...Bv(d)}})};function pm(e,t,n){return n===void 0?n:r=>{const i=t().nodeInternals.get(e);i&&n(r,{...i})}}function Fw({id:e,store:t,unselect:n=!1,nodeRef:r}){const{addSelectedNodes:i,unselectNodesAndEdges:a,multiSelectionActive:u,nodeInternals:c,onError:d}=t.getState(),m=c.get(e);if(!m){d==null||d("012",Za.error012(e));return}t.setState({nodesSelectionActive:!1}),m.selected?(n||m.selected&&u)&&(a({nodes:[m],edges:[]}),requestAnimationFrame(()=>{var h;return(h=r==null?void 0:r.current)==null?void 0:h.blur()})):i([e])}function j6(){const e=er();return _.useCallback(({sourceEvent:n})=>{const{transform:r,snapGrid:i,snapToGrid:a}=e.getState(),u=n.touches?n.touches[0].clientX:n.clientX,c=n.touches?n.touches[0].clientY:n.clientY,d={x:(u-r[0])/r[2],y:(c-r[1])/r[2]};return{xSnapped:a?i[0]*Math.round(d.x/i[0]):d.x,ySnapped:a?i[1]*Math.round(d.y/i[1]):d.y,...d}},[])}function $y(e){return(t,n,r)=>e==null?void 0:e(t,r)}function N1({nodeRef:e,disabled:t=!1,noDragClassName:n,handleSelector:r,nodeId:i,isSelectable:a,selectNodesOnDrag:u}){const c=er(),[d,m]=_.useState(!1),h=_.useRef([]),p=_.useRef({x:null,y:null}),y=_.useRef(0),w=_.useRef(null),x=_.useRef({x:0,y:0}),k=_.useRef(null),b=_.useRef(!1),S=_.useRef(!1),$=j6();return _.useEffect(()=>{if(e!=null&&e.current){const A=mo(e.current),E=({x:M,y:D})=>{const{nodeInternals:H,onNodeDrag:q,onSelectionDrag:I,updateNodePositions:Z,nodeExtent:R,snapGrid:T,snapToGrid:P,nodeOrigin:L,onError:te}=c.getState();p.current={x:M,y:D};let X=!1,V={x:0,y:0,x2:0,y2:0};if(h.current.length>1&&R){const W=yg(h.current,L);V=Zm(W)}if(h.current=h.current.map(W=>{const Y={x:M-W.distance.x,y:D-W.distance.y};P&&(Y.x=T[0]*Math.round(Y.x/T[0]),Y.y=T[1]*Math.round(Y.y/T[1]));const K=[[R[0][0],R[0][1]],[R[1][0],R[1][1]]];h.current.length>1&&R&&!W.extent&&(K[0][0]=W.positionAbsolute.x-V.x+R[0][0],K[1][0]=W.positionAbsolute.x+(W.width??0)-V.x2+R[1][0],K[0][1]=W.positionAbsolute.y-V.y+R[0][1],K[1][1]=W.positionAbsolute.y+(W.height??0)-V.y2+R[1][1]);const fe=S1(W,Y,H,K,L,te);return X=X||W.position.x!==fe.position.x||W.position.y!==fe.position.y,W.position=fe.position,W.positionAbsolute=fe.positionAbsolute,W}),!X)return;Z(h.current,!0,!0),m(!0);const ne=i?q:$y(I);if(ne&&k.current){const[W,Y]=Ny({nodeId:i,dragItems:h.current,nodeInternals:H});ne(k.current,W,Y)}},z=()=>{if(!w.current)return;const[M,D]=KN(x.current,w.current);if(M!==0||D!==0){const{transform:H,panBy:q}=c.getState();p.current.x=(p.current.x??0)-M/H[2],p.current.y=(p.current.y??0)-D/H[2],q({x:M,y:D})&&E(p.current)}y.current=requestAnimationFrame(z)},F=M=>{var L;const{nodeInternals:D,multiSelectionActive:H,nodesDraggable:q,unselectNodesAndEdges:I,onNodeDragStart:Z,onSelectionDragStart:R}=c.getState();S.current=!0;const T=i?Z:$y(R);(!u||!a)&&!H&&i&&((L=D.get(i))!=null&&L.selected||I()),i&&a&&u&&Fw({id:i,store:c,nodeRef:e});const P=$(M);if(p.current=P,h.current=b6(D,q,P,i),T&&h.current){const[te,X]=Ny({nodeId:i,dragItems:h.current,nodeInternals:D});T(M.sourceEvent,te,X)}};if(t)A.on(".drag",null);else{const M=L5().on("start",D=>{const{domNode:H,nodeDragThreshold:q}=c.getState();q===0&&F(D);const I=$(D);p.current=I,w.current=(H==null?void 0:H.getBoundingClientRect())||null,x.current=Zl(D.sourceEvent,w.current)}).on("drag",D=>{var Z,R;const H=$(D),{autoPanOnNodeDrag:q,nodeDragThreshold:I}=c.getState();if(!b.current&&S.current&&q&&(b.current=!0,z()),!S.current){const T=H.xSnapped-(((Z=p==null?void 0:p.current)==null?void 0:Z.x)??0),P=H.ySnapped-(((R=p==null?void 0:p.current)==null?void 0:R.y)??0);Math.sqrt(T*T+P*P)>I&&F(D)}(p.current.x!==H.xSnapped||p.current.y!==H.ySnapped)&&h.current&&S.current&&(k.current=D.sourceEvent,x.current=Zl(D.sourceEvent,w.current),E(H))}).on("end",D=>{if(S.current&&(m(!1),b.current=!1,S.current=!1,cancelAnimationFrame(y.current),h.current)){const{updateNodePositions:H,nodeInternals:q,onNodeDragStop:I,onSelectionDragStop:Z}=c.getState(),R=i?I:$y(Z);if(H(h.current,!1,!1),R){const[T,P]=Ny({nodeId:i,dragItems:h.current,nodeInternals:q});R(D.sourceEvent,T,P)}}}).filter(D=>{const H=D.target;return!D.button&&(!n||!G0(H,`.${n}`,e))&&(!r||G0(H,r,e))});return A.call(M),()=>{A.on(".drag",null)}}}},[e,t,n,r,a,c,i,u,$]),d}function $1(){const e=er();return _.useCallback(n=>{const{nodeInternals:r,nodeExtent:i,updateNodePositions:a,getNodes:u,snapToGrid:c,snapGrid:d,onError:m,nodesDraggable:h}=e.getState(),p=u().filter($=>$.selected&&($.draggable||h&&typeof $.draggable>"u")),y=c?d[0]:5,w=c?d[1]:5,x=n.isShiftPressed?4:1,k=n.x*y*x,b=n.y*w*x,S=p.map($=>{if($.positionAbsolute){const A={x:$.positionAbsolute.x+k,y:$.positionAbsolute.y+b};c&&(A.x=d[0]*Math.round(A.x/d[0]),A.y=d[1]*Math.round(A.y/d[1]));const{positionAbsolute:E,position:z}=S1($,A,r,i,void 0,m);$.position=z,$.positionAbsolute=E}return $});a(S,!0,!1)},[])}const zd={ArrowUp:{x:0,y:-1},ArrowDown:{x:0,y:1},ArrowLeft:{x:-1,y:0},ArrowRight:{x:1,y:0}};var gm=e=>{const t=({id:n,type:r,data:i,xPos:a,yPos:u,xPosOrigin:c,yPosOrigin:d,selected:m,onClick:h,onMouseEnter:p,onMouseMove:y,onMouseLeave:w,onContextMenu:x,onDoubleClick:k,style:b,className:S,isDraggable:$,isSelectable:A,isConnectable:E,isFocusable:z,selectNodesOnDrag:F,sourcePosition:M,targetPosition:D,hidden:H,resizeObserver:q,dragHandle:I,zIndex:Z,isParent:R,noDragClassName:T,noPanClassName:P,initialized:L,disableKeyboardA11y:te,ariaLabel:X,rfId:V,hasHandleBounds:ne})=>{const W=er(),Y=_.useRef(null),K=_.useRef(M),fe=_.useRef(D),ae=_.useRef(r),ve=A||$||h||p||y||w,ge=$1(),pe=pm(n,W.getState,p),$e=pm(n,W.getState,y),De=pm(n,W.getState,w),ot=pm(n,W.getState,x),bt=pm(n,W.getState,k),Ue=ut=>{const{nodeDragThreshold:Se}=W.getState();if(A&&(!F||!$||Se>0)&&Fw({id:n,store:W,nodeRef:Y}),h){const me=W.getState().nodeInternals.get(n);me&&h(ut,{...me})}},at=ut=>{if(!Lw(ut))if(ZN.includes(ut.key)&&A){const Se=ut.key==="Escape";Fw({id:n,store:W,unselect:Se,nodeRef:Y})}else!te&&$&&m&&Object.prototype.hasOwnProperty.call(zd,ut.key)&&(W.setState({ariaLiveMessage:`Moved selected node ${ut.key.replace("Arrow","").toLowerCase()}. New position, x: ${~~a}, y: ${~~u}`}),ge({x:zd[ut.key].x,y:zd[ut.key].y,isShiftPressed:ut.shiftKey}))};_.useEffect(()=>()=>{Y.current&&(q==null||q.unobserve(Y.current))},[]),_.useEffect(()=>{if(Y.current&&!H){const ut=Y.current;(!L||!ne)&&(q==null||q.unobserve(ut),q==null||q.observe(ut))}},[H,L,ne]),_.useEffect(()=>{const ut=ae.current!==r,Se=K.current!==M,me=fe.current!==D;Y.current&&(ut||Se||me)&&(ut&&(ae.current=r),Se&&(K.current=M),me&&(fe.current=D),W.getState().updateNodeDimensions([{id:n,nodeElement:Y.current,forceUpdate:!0}]))},[n,r,M,D]);const Nt=N1({nodeRef:Y,disabled:H||!$,noDragClassName:T,handleSelector:I,nodeId:n,isSelectable:A,selectNodesOnDrag:F});return H?null:Ne.createElement("div",{className:$r(["react-flow__node",`react-flow__node-${r}`,{[P]:$},S,{selected:m,selectable:A,parent:R,dragging:Nt}]),ref:Y,style:{zIndex:Z,transform:`translate(${c}px,${d}px)`,pointerEvents:ve?"all":"none",visibility:L?"visible":"hidden",...b},"data-id":n,"data-testid":`rf__node-${n}`,onMouseEnter:pe,onMouseMove:$e,onMouseLeave:De,onContextMenu:ot,onClick:Ue,onDoubleClick:bt,onKeyDown:z?at:void 0,tabIndex:z?0:void 0,role:z?"button":void 0,"aria-describedby":te?void 0:`${y1}-${V}`,"aria-label":X},Ne.createElement(PD,{value:n},Ne.createElement(e,{id:n,data:i,type:r,xPos:a,yPos:u,selected:m,isConnectable:E,sourcePosition:M,targetPosition:D,dragging:Nt,dragHandle:I,zIndex:Z})))};return t.displayName="NodeWrapper",_.memo(t)};const S6=e=>{const t=e.getNodes().filter(n=>n.selected);return{...yg(t,e.nodeOrigin),transformString:`translate(${e.transform[0]}px,${e.transform[1]}px) scale(${e.transform[2]})`,userSelectionActive:e.userSelectionActive}};function N6({onSelectionContextMenu:e,noPanClassName:t,disableKeyboardA11y:n}){const r=er(),{width:i,height:a,x:u,y:c,transformString:d,userSelectionActive:m}=fs(S6,hr),h=$1(),p=_.useRef(null);if(_.useEffect(()=>{var x;n||(x=p.current)==null||x.focus({preventScroll:!0})},[n]),N1({nodeRef:p}),m||!i||!a)return null;const y=e?x=>{const k=r.getState().getNodes().filter(b=>b.selected);e(x,k)}:void 0,w=x=>{Object.prototype.hasOwnProperty.call(zd,x.key)&&h({x:zd[x.key].x,y:zd[x.key].y,isShiftPressed:x.shiftKey})};return Ne.createElement("div",{className:$r(["react-flow__nodesselection","react-flow__container",t]),style:{transform:d}},Ne.createElement("div",{ref:p,className:"react-flow__nodesselection-rect",onContextMenu:y,tabIndex:n?void 0:-1,onKeyDown:n?void 0:w,style:{width:i,height:a,top:c,left:u}}))}var $6=_.memo(N6);const C6=e=>e.nodesSelectionActive,C1=({children:e,onPaneClick:t,onPaneMouseEnter:n,onPaneMouseMove:r,onPaneMouseLeave:i,onPaneContextMenu:a,onPaneScroll:u,deleteKeyCode:c,onMove:d,onMoveStart:m,onMoveEnd:h,selectionKeyCode:p,selectionOnDrag:y,selectionMode:w,onSelectionStart:x,onSelectionEnd:k,multiSelectionKeyCode:b,panActivationKeyCode:S,zoomActivationKeyCode:$,elementsSelectable:A,zoomOnScroll:E,zoomOnPinch:z,panOnScroll:F,panOnScrollSpeed:M,panOnScrollMode:D,zoomOnDoubleClick:H,panOnDrag:q,defaultViewport:I,translateExtent:Z,minZoom:R,maxZoom:T,preventScrolling:P,onSelectionContextMenu:L,noWheelClassName:te,noPanClassName:X,disableKeyboardA11y:V})=>{const ne=fs(C6),W=th(p),Y=th(S),K=Y||q,fe=Y||F,ae=W||y&&K!==!0;return f6({deleteKeyCode:c,multiSelectionKeyCode:b}),Ne.createElement(p6,{onMove:d,onMoveStart:m,onMoveEnd:h,onPaneContextMenu:a,elementsSelectable:A,zoomOnScroll:E,zoomOnPinch:z,panOnScroll:fe,panOnScrollSpeed:M,panOnScrollMode:D,zoomOnDoubleClick:H,panOnDrag:!W&&K,defaultViewport:I,translateExtent:Z,minZoom:R,maxZoom:T,zoomActivationKeyCode:$,preventScrolling:P,noWheelClassName:te,noPanClassName:X},Ne.createElement(k1,{onSelectionStart:x,onSelectionEnd:k,onPaneClick:t,onPaneMouseEnter:n,onPaneMouseMove:r,onPaneMouseLeave:i,onPaneContextMenu:a,onPaneScroll:u,panOnDrag:K,isSelecting:!!ae,selectionMode:w},e,ne&&Ne.createElement($6,{onSelectionContextMenu:L,noPanClassName:X,disableKeyboardA11y:V})))};C1.displayName="FlowRenderer";var E6=_.memo(C1);function A6(e){return fs(_.useCallback(n=>e?i1(n.nodeInternals,{x:0,y:0,width:n.width,height:n.height},n.transform,!0):n.getNodes(),[e]))}function T6(e){const t={input:gm(e.input||h1),default:gm(e.default||Dw),output:gm(e.output||p1),group:gm(e.group||Kv)},n={},r=Object.keys(e).filter(i=>!["input","default","output","group"].includes(i)).reduce((i,a)=>(i[a]=gm(e[a]||Dw),i),n);return{...t,...r}}const M6=({x:e,y:t,width:n,height:r,origin:i})=>!n||!r?{x:e,y:t}:i[0]<0||i[1]<0||i[0]>1||i[1]>1?{x:e,y:t}:{x:e-n*i[0],y:t-r*i[1]},R6=e=>({nodesDraggable:e.nodesDraggable,nodesConnectable:e.nodesConnectable,nodesFocusable:e.nodesFocusable,elementsSelectable:e.elementsSelectable,updateNodeDimensions:e.updateNodeDimensions,onError:e.onError}),E1=e=>{const{nodesDraggable:t,nodesConnectable:n,nodesFocusable:r,elementsSelectable:i,updateNodeDimensions:a,onError:u}=fs(R6,hr),c=A6(e.onlyRenderVisibleElements),d=_.useRef(),m=_.useMemo(()=>{if(typeof ResizeObserver>"u")return null;const h=new ResizeObserver(p=>{const y=p.map(w=>({id:w.target.getAttribute("data-id"),nodeElement:w.target,forceUpdate:!0}));a(y)});return d.current=h,h},[]);return _.useEffect(()=>()=>{var h;(h=d==null?void 0:d.current)==null||h.disconnect()},[]),Ne.createElement("div",{className:"react-flow__nodes",style:Yv},c.map(h=>{var z,F,M;let p=h.type||"default";e.nodeTypes[p]||(u==null||u("003",Za.error003(p)),p="default");const y=e.nodeTypes[p]||e.nodeTypes.default,w=!!(h.draggable||t&&typeof h.draggable>"u"),x=!!(h.selectable||i&&typeof h.selectable>"u"),k=!!(h.connectable||n&&typeof h.connectable>"u"),b=!!(h.focusable||r&&typeof h.focusable>"u"),S=e.nodeExtent?Uv(h.positionAbsolute,e.nodeExtent):h.positionAbsolute,$=(S==null?void 0:S.x)??0,A=(S==null?void 0:S.y)??0,E=M6({x:$,y:A,width:h.width??0,height:h.height??0,origin:e.nodeOrigin});return Ne.createElement(y,{key:h.id,id:h.id,className:h.className,style:h.style,type:p,data:h.data,sourcePosition:h.sourcePosition||Mt.Bottom,targetPosition:h.targetPosition||Mt.Top,hidden:h.hidden,xPos:$,yPos:A,xPosOrigin:E.x,yPosOrigin:E.y,selectNodesOnDrag:e.selectNodesOnDrag,onClick:e.onNodeClick,onMouseEnter:e.onNodeMouseEnter,onMouseMove:e.onNodeMouseMove,onMouseLeave:e.onNodeMouseLeave,onContextMenu:e.onNodeContextMenu,onDoubleClick:e.onNodeDoubleClick,selected:!!h.selected,isDraggable:w,isSelectable:x,isConnectable:k,isFocusable:b,resizeObserver:m,dragHandle:h.dragHandle,zIndex:((z=h[qs])==null?void 0:z.z)??0,isParent:!!((F=h[qs])!=null&&F.isParent),noDragClassName:e.noDragClassName,noPanClassName:e.noPanClassName,initialized:!!h.width&&!!h.height,rfId:e.rfId,disableKeyboardA11y:e.disableKeyboardA11y,ariaLabel:h.ariaLabel,hasHandleBounds:!!((M=h[qs])!=null&&M.handleBounds)})}))};E1.displayName="NodeRenderer";var L6=_.memo(E1);const I6=(e,t,n)=>n===Mt.Left?e-t:n===Mt.Right?e+t:e,O6=(e,t,n)=>n===Mt.Top?e-t:n===Mt.Bottom?e+t:e,J0="react-flow__edgeupdater",Y0=({position:e,centerX:t,centerY:n,radius:r=10,onMouseDown:i,onMouseEnter:a,onMouseOut:u,type:c})=>Ne.createElement("circle",{onMouseDown:i,onMouseEnter:a,onMouseOut:u,className:$r([J0,`${J0}-${c}`]),cx:I6(t,r,e),cy:O6(n,r,e),r,stroke:"transparent",fill:"transparent"}),P6=()=>!0;var xd=e=>{const t=({id:n,className:r,type:i,data:a,onClick:u,onEdgeDoubleClick:c,selected:d,animated:m,label:h,labelStyle:p,labelShowBg:y,labelBgStyle:w,labelBgPadding:x,labelBgBorderRadius:k,style:b,source:S,target:$,sourceX:A,sourceY:E,targetX:z,targetY:F,sourcePosition:M,targetPosition:D,elementsSelectable:H,hidden:q,sourceHandleId:I,targetHandleId:Z,onContextMenu:R,onMouseEnter:T,onMouseMove:P,onMouseLeave:L,edgeUpdaterRadius:te,onEdgeUpdate:X,onEdgeUpdateStart:V,onEdgeUpdateEnd:ne,markerEnd:W,markerStart:Y,rfId:K,ariaLabel:fe,isFocusable:ae,isUpdatable:ve,pathOptions:ge,interactionWidth:pe})=>{const $e=_.useRef(null),[De,ot]=_.useState(!1),[bt,Ue]=_.useState(!1),at=er(),Nt=_.useMemo(()=>`url('#${Ow(Y,K)}')`,[Y,K]),ut=_.useMemo(()=>`url('#${Ow(W,K)}')`,[W,K]);if(q)return null;const Se=Qt=>{var an;const{edges:Un,addSelectedEdges:rs,unselectNodesAndEdges:Dn,multiSelectionActive:$n}=at.getState(),Cn=Un.find(is=>is.id===n);Cn&&(H&&(at.setState({nodesSelectionActive:!1}),Cn.selected&&$n?(Dn({nodes:[],edges:[Cn]}),(an=$e.current)==null||an.blur()):rs([n])),u&&u(Qt,Cn))},me=_m(n,at.getState,c),Ve=_m(n,at.getState,R),ye=_m(n,at.getState,T),Ie=_m(n,at.getState,P),ct=_m(n,at.getState,L),ie=(Qt,Un)=>{if(Qt.button!==0)return;const{edges:rs,isValidConnection:Dn}=at.getState(),$n=Un?$:S,Cn=(Un?Z:I)||null,an=Un?"target":"source",is=Dn||P6,Wn=Un,Fn=rs.find(he=>he.id===n);Ue(!0),V==null||V(Qt,Fn,an);const Hs=he=>{Ue(!1),ne==null||ne(he,Fn,an)};u1({event:Qt,handleId:Cn,nodeId:$n,onConnect:he=>X==null?void 0:X(Fn,he),isTarget:Wn,getState:at.getState,setState:at.setState,isValidConnection:is,edgeUpdaterType:an,onEdgeUpdateEnd:Hs})},Te=Qt=>ie(Qt,!0),et=Qt=>ie(Qt,!1),Ge=()=>ot(!0),Be=()=>ot(!1),Rt=!H&&!u,Nn=Qt=>{var Un;if(ZN.includes(Qt.key)&&H){const{unselectNodesAndEdges:rs,addSelectedEdges:Dn,edges:$n}=at.getState();Qt.key==="Escape"?((Un=$e.current)==null||Un.blur(),rs({edges:[$n.find(an=>an.id===n)]})):Dn([n])}};return Ne.createElement("g",{className:$r(["react-flow__edge",`react-flow__edge-${i}`,r,{selected:d,animated:m,inactive:Rt,updating:De}]),onClick:Se,onDoubleClick:me,onContextMenu:Ve,onMouseEnter:ye,onMouseMove:Ie,onMouseLeave:ct,onKeyDown:ae?Nn:void 0,tabIndex:ae?0:void 0,role:ae?"button":"img","data-testid":`rf__edge-${n}`,"aria-label":fe===null?void 0:fe||`Edge from ${S} to ${$}`,"aria-describedby":ae?`${w1}-${K}`:void 0,ref:$e},!bt&&Ne.createElement(e,{id:n,source:S,target:$,selected:d,animated:m,label:h,labelStyle:p,labelShowBg:y,labelBgStyle:w,labelBgPadding:x,labelBgBorderRadius:k,data:a,style:b,sourceX:A,sourceY:E,targetX:z,targetY:F,sourcePosition:M,targetPosition:D,sourceHandleId:I,targetHandleId:Z,markerStart:Nt,markerEnd:ut,pathOptions:ge,interactionWidth:pe}),ve&&Ne.createElement(Ne.Fragment,null,(ve==="source"||ve===!0)&&Ne.createElement(Y0,{position:M,centerX:A,centerY:E,radius:te,onMouseDown:Te,onMouseEnter:Ge,onMouseOut:Be,type:"source"}),(ve==="target"||ve===!0)&&Ne.createElement(Y0,{position:D,centerX:z,centerY:F,radius:te,onMouseDown:et,onMouseEnter:Ge,onMouseOut:Be,type:"target"})))};return t.displayName="EdgeWrapper",_.memo(t)};function D6(e){const t={default:xd(e.default||Wp),straight:xd(e.bezier||Hv),step:xd(e.step||qv),smoothstep:xd(e.step||gg),simplebezier:xd(e.simplebezier||Wv)},n={},r=Object.keys(e).filter(i=>!["default","bezier"].includes(i)).reduce((i,a)=>(i[a]=xd(e[a]||Wp),i),n);return{...t,...r}}function X0(e,t,n=null){const r=((n==null?void 0:n.x)||0)+t.x,i=((n==null?void 0:n.y)||0)+t.y,a=(n==null?void 0:n.width)||t.width,u=(n==null?void 0:n.height)||t.height;switch(e){case Mt.Top:return{x:r+a/2,y:i};case Mt.Right:return{x:r+a,y:i+u/2};case Mt.Bottom:return{x:r+a/2,y:i+u};case Mt.Left:return{x:r,y:i+u/2}}}function Z0(e,t){return e?e.length===1||!t?e[0]:t&&e.find(n=>n.id===t)||null:null}const F6=(e,t,n,r,i,a)=>{const u=X0(n,e,t),c=X0(a,r,i);return{sourceX:u.x,sourceY:u.y,targetX:c.x,targetY:c.y}};function z6({sourcePos:e,targetPos:t,sourceWidth:n,sourceHeight:r,targetWidth:i,targetHeight:a,width:u,height:c,transform:d}){const m={x:Math.min(e.x,t.x),y:Math.min(e.y,t.y),x2:Math.max(e.x+n,t.x+i),y2:Math.max(e.y+r,t.y+a)};m.x===m.x2&&(m.x2+=1),m.y===m.y2&&(m.y2+=1);const h=Zm({x:(0-d[0])/d[2],y:(0-d[1])/d[2],width:u/d[2],height:c/d[2]}),p=Math.max(0,Math.min(h.x2,m.x2)-Math.max(h.x,m.x)),y=Math.max(0,Math.min(h.y2,m.y2)-Math.max(h.y,m.y));return Math.ceil(p*y)>0}function Q0(e){var r,i,a,u,c;const t=((r=e==null?void 0:e[qs])==null?void 0:r.handleBounds)||null,n=t&&(e==null?void 0:e.width)&&(e==null?void 0:e.height)&&typeof((i=e==null?void 0:e.positionAbsolute)==null?void 0:i.x)<"u"&&typeof((a=e==null?void 0:e.positionAbsolute)==null?void 0:a.y)<"u";return[{x:((u=e==null?void 0:e.positionAbsolute)==null?void 0:u.x)||0,y:((c=e==null?void 0:e.positionAbsolute)==null?void 0:c.y)||0,width:(e==null?void 0:e.width)||0,height:(e==null?void 0:e.height)||0},t,!!n]}const B6=[{level:0,isMaxLevel:!0,edges:[]}];function U6(e,t,n=!1){let r=-1;const i=e.reduce((u,c)=>{var h,p;const d=ho(c.zIndex);let m=d?c.zIndex:0;if(n){const y=t.get(c.target),w=t.get(c.source),x=c.selected||(y==null?void 0:y.selected)||(w==null?void 0:w.selected),k=Math.max(((h=w==null?void 0:w[qs])==null?void 0:h.z)||0,((p=y==null?void 0:y[qs])==null?void 0:p.z)||0,1e3);m=(d?c.zIndex:0)+(x?k:0)}return u[m]?u[m].push(c):u[m]=[c],r=m>r?m:r,u},{}),a=Object.entries(i).map(([u,c])=>{const d=+u;return{edges:c,level:d,isMaxLevel:d===r}});return a.length===0?B6:a}function W6(e,t,n){const r=fs(_.useCallback(i=>e?i.edges.filter(a=>{const u=t.get(a.source),c=t.get(a.target);return(u==null?void 0:u.width)&&(u==null?void 0:u.height)&&(c==null?void 0:c.width)&&(c==null?void 0:c.height)&&z6({sourcePos:u.positionAbsolute||{x:0,y:0},targetPos:c.positionAbsolute||{x:0,y:0},sourceWidth:u.width,sourceHeight:u.height,targetWidth:c.width,targetHeight:c.height,width:i.width,height:i.height,transform:i.transform})}):i.edges,[e,t]));return U6(r,t,n)}const q6=({color:e="none",strokeWidth:t=1})=>Ne.createElement("polyline",{style:{stroke:e,strokeWidth:t},strokeLinecap:"round",strokeLinejoin:"round",fill:"none",points:"-5,-4 0,0 -5,4"}),H6=({color:e="none",strokeWidth:t=1})=>Ne.createElement("polyline",{style:{stroke:e,fill:e,strokeWidth:t},strokeLinecap:"round",strokeLinejoin:"round",points:"-5,-4 0,0 -5,4 -5,-4"}),ek={[eh.Arrow]:q6,[eh.ArrowClosed]:H6};function V6(e){const t=er();return _.useMemo(()=>{var i,a;return Object.prototype.hasOwnProperty.call(ek,e)?ek[e]:((a=(i=t.getState()).onError)==null||a.call(i,"009",Za.error009(e)),null)},[e])}const G6=({id:e,type:t,color:n,width:r=12.5,height:i=12.5,markerUnits:a="strokeWidth",strokeWidth:u,orient:c="auto-start-reverse"})=>{const d=V6(t);return d?Ne.createElement("marker",{className:"react-flow__arrowhead",id:e,markerWidth:`${r}`,markerHeight:`${i}`,viewBox:"-10 -10 20 20",markerUnits:a,orient:c,refX:"0",refY:"0"},Ne.createElement(d,{color:n,strokeWidth:u})):null},K6=({defaultColor:e,rfId:t})=>n=>{const r=[];return n.edges.reduce((i,a)=>([a.markerStart,a.markerEnd].forEach(u=>{if(u&&typeof u=="object"){const c=Ow(u,t);r.includes(c)||(i.push({id:c,color:u.color||e,...u}),r.push(c))}}),i),[]).sort((i,a)=>i.id.localeCompare(a.id))},A1=({defaultColor:e,rfId:t})=>{const n=fs(_.useCallback(K6({defaultColor:e,rfId:t}),[e,t]),(r,i)=>!(r.length!==i.length||r.some((a,u)=>a.id!==i[u].id)));return Ne.createElement("defs",null,n.map(r=>Ne.createElement(G6,{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})))};A1.displayName="MarkerDefinitions";var J6=_.memo(A1);const Y6=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}),T1=({defaultMarkerColor:e,onlyRenderVisibleElements:t,elevateEdgesOnSelect:n,rfId:r,edgeTypes:i,noPanClassName:a,onEdgeUpdate:u,onEdgeContextMenu:c,onEdgeMouseEnter:d,onEdgeMouseMove:m,onEdgeMouseLeave:h,onEdgeClick:p,edgeUpdaterRadius:y,onEdgeDoubleClick:w,onEdgeUpdateStart:x,onEdgeUpdateEnd:k,children:b})=>{const{edgesFocusable:S,edgesUpdatable:$,elementsSelectable:A,width:E,height:z,connectionMode:F,nodeInternals:M,onError:D}=fs(Y6,hr),H=W6(t,M,n);return E?Ne.createElement(Ne.Fragment,null,H.map(({level:q,edges:I,isMaxLevel:Z})=>Ne.createElement("svg",{key:q,style:{zIndex:q},width:E,height:z,className:"react-flow__edges react-flow__container"},Z&&Ne.createElement(J6,{defaultColor:e,rfId:r}),Ne.createElement("g",null,I.map(R=>{const[T,P,L]=Q0(M.get(R.source)),[te,X,V]=Q0(M.get(R.target));if(!L||!V)return null;let ne=R.type||"default";i[ne]||(D==null||D("011",Za.error011(ne)),ne="default");const W=i[ne]||i.default,Y=F===lu.Strict?X.target:(X.target??[]).concat(X.source??[]),K=Z0(P.source,R.sourceHandle),fe=Z0(Y,R.targetHandle),ae=(K==null?void 0:K.position)||Mt.Bottom,ve=(fe==null?void 0:fe.position)||Mt.Top,ge=!!(R.focusable||S&&typeof R.focusable>"u"),pe=typeof u<"u"&&(R.updatable||$&&typeof R.updatable>"u");if(!K||!fe)return D==null||D("008",Za.error008(K,R)),null;const{sourceX:$e,sourceY:De,targetX:ot,targetY:bt}=F6(T,K,ae,te,fe,ve);return Ne.createElement(W,{key:R.id,id:R.id,className:$r([R.className,a]),type:ne,data:R.data,selected:!!R.selected,animated:!!R.animated,hidden:!!R.hidden,label:R.label,labelStyle:R.labelStyle,labelShowBg:R.labelShowBg,labelBgStyle:R.labelBgStyle,labelBgPadding:R.labelBgPadding,labelBgBorderRadius:R.labelBgBorderRadius,style:R.style,source:R.source,target:R.target,sourceHandleId:R.sourceHandle,targetHandleId:R.targetHandle,markerEnd:R.markerEnd,markerStart:R.markerStart,sourceX:$e,sourceY:De,targetX:ot,targetY:bt,sourcePosition:ae,targetPosition:ve,elementsSelectable:A,onEdgeUpdate:u,onContextMenu:c,onMouseEnter:d,onMouseMove:m,onMouseLeave:h,onClick:p,edgeUpdaterRadius:y,onEdgeDoubleClick:w,onEdgeUpdateStart:x,onEdgeUpdateEnd:k,rfId:r,ariaLabel:R.ariaLabel,isFocusable:ge,isUpdatable:pe,pathOptions:"pathOptions"in R?R.pathOptions:void 0,interactionWidth:R.interactionWidth})})))),b):null};T1.displayName="EdgeRenderer";var X6=_.memo(T1);const Z6=e=>`translate(${e.transform[0]}px,${e.transform[1]}px) scale(${e.transform[2]})`;function Q6({children:e}){const t=fs(Z6);return Ne.createElement("div",{className:"react-flow__viewport react-flow__container",style:{transform:t}},e)}function eF(e){const t=Jv(),n=_.useRef(!1);_.useEffect(()=>{!n.current&&t.viewportInitialized&&e&&(setTimeout(()=>e(t),1),n.current=!0)},[e,t.viewportInitialized])}const tF={[Mt.Left]:Mt.Right,[Mt.Right]:Mt.Left,[Mt.Top]:Mt.Bottom,[Mt.Bottom]:Mt.Top},M1=({nodeId:e,handleType:t,style:n,type:r=Jl.Bezier,CustomComponent:i,connectionStatus:a})=>{var F,M,D;const{fromNode:u,handleId:c,toX:d,toY:m,connectionMode:h}=fs(_.useCallback(H=>({fromNode:H.nodeInternals.get(e),handleId:H.connectionHandleId,toX:(H.connectionPosition.x-H.transform[0])/H.transform[2],toY:(H.connectionPosition.y-H.transform[1])/H.transform[2],connectionMode:H.connectionMode}),[e]),hr),p=(F=u==null?void 0:u[qs])==null?void 0:F.handleBounds;let y=p==null?void 0:p[t];if(h===lu.Loose&&(y=y||(p==null?void 0:p[t==="source"?"target":"source"])),!u||!y)return null;const w=c?y.find(H=>H.id===c):y[0],x=w?w.x+w.width/2:(u.width??0)/2,k=w?w.y+w.height/2:u.height??0,b=(((M=u.positionAbsolute)==null?void 0:M.x)??0)+x,S=(((D=u.positionAbsolute)==null?void 0:D.y)??0)+k,$=w==null?void 0:w.position,A=$?tF[$]:null;if(!$||!A)return null;if(i)return Ne.createElement(i,{connectionLineType:r,connectionLineStyle:n,fromNode:u,fromHandle:w,fromX:b,fromY:S,toX:d,toY:m,fromPosition:$,toPosition:A,connectionStatus:a});let E="";const z={sourceX:b,sourceY:S,sourcePosition:$,targetX:d,targetY:m,targetPosition:A};return r===Jl.Bezier?[E]=s1(z):r===Jl.Step?[E]=Iw({...z,borderRadius:0}):r===Jl.SmoothStep?[E]=Iw(z):r===Jl.SimpleBezier?[E]=n1(z):E=`M${b},${S} ${d},${m}`,Ne.createElement("path",{d:E,fill:"none",className:"react-flow__connection-path",style:n})};M1.displayName="ConnectionLine";const nF=e=>({nodeId:e.connectionNodeId,handleType:e.connectionHandleType,nodesConnectable:e.nodesConnectable,connectionStatus:e.connectionStatus,width:e.width,height:e.height});function sF({containerStyle:e,style:t,type:n,component:r}){const{nodeId:i,handleType:a,nodesConnectable:u,width:c,height:d,connectionStatus:m}=fs(nF,hr);return!(i&&a&&c&&u)?null:Ne.createElement("svg",{style:e,width:c,height:d,className:"react-flow__edges react-flow__connectionline react-flow__container"},Ne.createElement("g",{className:$r(["react-flow__connection",m])},Ne.createElement(M1,{nodeId:i,handleType:a,style:t,type:n,CustomComponent:r,connectionStatus:m})))}function tk(e,t){return _.useRef(null),er(),_.useMemo(()=>t(e),[e])}const R1=({nodeTypes:e,edgeTypes:t,onMove:n,onMoveStart:r,onMoveEnd:i,onInit:a,onNodeClick:u,onEdgeClick:c,onNodeDoubleClick:d,onEdgeDoubleClick:m,onNodeMouseEnter:h,onNodeMouseMove:p,onNodeMouseLeave:y,onNodeContextMenu:w,onSelectionContextMenu:x,onSelectionStart:k,onSelectionEnd:b,connectionLineType:S,connectionLineStyle:$,connectionLineComponent:A,connectionLineContainerStyle:E,selectionKeyCode:z,selectionOnDrag:F,selectionMode:M,multiSelectionKeyCode:D,panActivationKeyCode:H,zoomActivationKeyCode:q,deleteKeyCode:I,onlyRenderVisibleElements:Z,elementsSelectable:R,selectNodesOnDrag:T,defaultViewport:P,translateExtent:L,minZoom:te,maxZoom:X,preventScrolling:V,defaultMarkerColor:ne,zoomOnScroll:W,zoomOnPinch:Y,panOnScroll:K,panOnScrollSpeed:fe,panOnScrollMode:ae,zoomOnDoubleClick:ve,panOnDrag:ge,onPaneClick:pe,onPaneMouseEnter:$e,onPaneMouseMove:De,onPaneMouseLeave:ot,onPaneScroll:bt,onPaneContextMenu:Ue,onEdgeUpdate:at,onEdgeContextMenu:Nt,onEdgeMouseEnter:ut,onEdgeMouseMove:Se,onEdgeMouseLeave:me,edgeUpdaterRadius:Ve,onEdgeUpdateStart:ye,onEdgeUpdateEnd:Ie,noDragClassName:ct,noWheelClassName:ie,noPanClassName:Te,elevateEdgesOnSelect:et,disableKeyboardA11y:Ge,nodeOrigin:Be,nodeExtent:Rt,rfId:Nn})=>{const Qt=tk(e,T6),Un=tk(t,D6);return eF(a),Ne.createElement(E6,{onPaneClick:pe,onPaneMouseEnter:$e,onPaneMouseMove:De,onPaneMouseLeave:ot,onPaneContextMenu:Ue,onPaneScroll:bt,deleteKeyCode:I,selectionKeyCode:z,selectionOnDrag:F,selectionMode:M,onSelectionStart:k,onSelectionEnd:b,multiSelectionKeyCode:D,panActivationKeyCode:H,zoomActivationKeyCode:q,elementsSelectable:R,onMove:n,onMoveStart:r,onMoveEnd:i,zoomOnScroll:W,zoomOnPinch:Y,zoomOnDoubleClick:ve,panOnScroll:K,panOnScrollSpeed:fe,panOnScrollMode:ae,panOnDrag:ge,defaultViewport:P,translateExtent:L,minZoom:te,maxZoom:X,onSelectionContextMenu:x,preventScrolling:V,noDragClassName:ct,noWheelClassName:ie,noPanClassName:Te,disableKeyboardA11y:Ge},Ne.createElement(Q6,null,Ne.createElement(X6,{edgeTypes:Un,onEdgeClick:c,onEdgeDoubleClick:m,onEdgeUpdate:at,onlyRenderVisibleElements:Z,onEdgeContextMenu:Nt,onEdgeMouseEnter:ut,onEdgeMouseMove:Se,onEdgeMouseLeave:me,onEdgeUpdateStart:ye,onEdgeUpdateEnd:Ie,edgeUpdaterRadius:Ve,defaultMarkerColor:ne,noPanClassName:Te,elevateEdgesOnSelect:!!et,disableKeyboardA11y:Ge,rfId:Nn},Ne.createElement(sF,{style:$,type:S,component:A,containerStyle:E})),Ne.createElement("div",{className:"react-flow__edgelabel-renderer"}),Ne.createElement(L6,{nodeTypes:Qt,onNodeClick:u,onNodeDoubleClick:d,onNodeMouseEnter:h,onNodeMouseMove:p,onNodeMouseLeave:y,onNodeContextMenu:w,selectNodesOnDrag:T,onlyRenderVisibleElements:Z,noPanClassName:Te,noDragClassName:ct,disableKeyboardA11y:Ge,nodeOrigin:Be,nodeExtent:Rt,rfId:Nn})))};R1.displayName="GraphView";var rF=_.memo(R1);const zw=[[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY],[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY]],Bl={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:zw,nodeExtent:zw,nodesSelectionActive:!1,userSelectionActive:!1,userSelectionRect:null,connectionNodeId:null,connectionHandleId:null,connectionHandleType:"source",connectionPosition:{x:0,y:0},connectionStatus:null,connectionMode:lu.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:TD,isValidConnection:void 0},iF=()=>V4((e,t)=>({...Bl,setNodes:n=>{const{nodeInternals:r,nodeOrigin:i,elevateNodesOnSelect:a}=t();e({nodeInternals:jy(n,r,i,a)})},getNodes:()=>Array.from(t().nodeInternals.values()),setEdges:n=>{const{defaultEdgeOptions:r={}}=t();e({edges:n.map(i=>({...r,...i}))})},setDefaultNodesAndEdges:(n,r)=>{const i=typeof n<"u",a=typeof r<"u",u=i?jy(n,new Map,t().nodeOrigin,t().elevateNodesOnSelect):new Map;e({nodeInternals:u,edges:a?r:[],hasDefaultNodes:i,hasDefaultEdges:a})},updateNodeDimensions:n=>{const{onNodesChange:r,nodeInternals:i,fitViewOnInit:a,fitViewOnInitDone:u,fitViewOnInitOptions:c,domNode:d,nodeOrigin:m}=t(),h=d==null?void 0:d.querySelector(".react-flow__viewport");if(!h)return;const p=window.getComputedStyle(h),{m22:y}=new window.DOMMatrixReadOnly(p.transform),w=n.reduce((k,b)=>{const S=i.get(b.id);if(S){const $=Bv(b.nodeElement);!!($.width&&$.height&&(S.width!==$.width||S.height!==$.height||b.forceUpdate))&&(i.set(S.id,{...S,[qs]:{...S[qs],handleBounds:{source:K0(".source",b.nodeElement,y,m),target:K0(".target",b.nodeElement,y,m)}},...$}),k.push({id:S.id,type:"dimensions",dimensions:$}))}return k},[]);x1(i,m);const x=u||a&&!u&&b1(t,{initial:!0,...c});e({nodeInternals:new Map(i),fitViewOnInitDone:x}),(w==null?void 0:w.length)>0&&(r==null||r(w))},updateNodePositions:(n,r=!0,i=!1)=>{const{triggerNodeChanges:a}=t(),u=n.map(c=>{const d={id:c.id,type:"position",dragging:i};return r&&(d.positionAbsolute=c.positionAbsolute,d.position=c.position),d});a(u)},triggerNodeChanges:n=>{const{onNodesChange:r,nodeInternals:i,hasDefaultNodes:a,nodeOrigin:u,getNodes:c,elevateNodesOnSelect:d}=t();if(n!=null&&n.length){if(a){const m=v6(n,c()),h=jy(m,i,u,d);e({nodeInternals:h})}r==null||r(n)}},addSelectedNodes:n=>{const{multiSelectionActive:r,edges:i,getNodes:a}=t();let u,c=null;r?u=n.map(d=>Gl(d,!0)):(u=Md(a(),n),c=Md(i,[])),X_({changedNodes:u,changedEdges:c,get:t,set:e})},addSelectedEdges:n=>{const{multiSelectionActive:r,edges:i,getNodes:a}=t();let u,c=null;r?u=n.map(d=>Gl(d,!0)):(u=Md(i,n),c=Md(a(),[])),X_({changedNodes:c,changedEdges:u,get:t,set:e})},unselectNodesAndEdges:({nodes:n,edges:r}={})=>{const{edges:i,getNodes:a}=t(),u=n||a(),c=r||i,d=u.map(h=>(h.selected=!1,Gl(h.id,!1))),m=c.map(h=>Gl(h.id,!1));X_({changedNodes:d,changedEdges:m,get:t,set:e})},setMinZoom:n=>{const{d3Zoom:r,maxZoom:i}=t();r==null||r.scaleExtent([n,i]),e({minZoom:n})},setMaxZoom:n=>{const{d3Zoom:r,minZoom:i}=t();r==null||r.scaleExtent([i,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(),a=r().filter(c=>c.selected).map(c=>Gl(c.id,!1)),u=n.filter(c=>c.selected).map(c=>Gl(c.id,!1));X_({changedNodes:a,changedEdges:u,get:t,set:e})},setNodeExtent:n=>{const{nodeInternals:r}=t();r.forEach(i=>{i.positionAbsolute=Uv(i.position,n)}),e({nodeExtent:n,nodeInternals:new Map(r)})},panBy:n=>{const{transform:r,width:i,height:a,d3Zoom:u,d3Selection:c,translateExtent:d}=t();if(!u||!c||!n.x&&!n.y)return!1;const m=Ka.translate(r[0]+n.x,r[1]+n.y).scale(r[2]),h=[[0,0],[i,a]],p=u==null?void 0:u.constrain()(m,h,d);return u.transform(c,p),r[0]!==p.x||r[1]!==p.y||r[2]!==p.k},cancelConnection:()=>e({connectionNodeId:Bl.connectionNodeId,connectionHandleId:Bl.connectionHandleId,connectionHandleType:Bl.connectionHandleType,connectionStatus:Bl.connectionStatus,connectionStartHandle:Bl.connectionStartHandle,connectionEndHandle:Bl.connectionEndHandle}),reset:()=>e({...Bl})}),Object.is),Xv=({children:e})=>{const t=_.useRef(null);return t.current||(t.current=iF()),Ne.createElement(jD,{value:t.current},e)};Xv.displayName="ReactFlowProvider";const L1=({children:e})=>_.useContext(pg)?Ne.createElement(Ne.Fragment,null,e):Ne.createElement(Xv,null,e);L1.displayName="ReactFlowWrapper";const oF={input:h1,default:Dw,output:p1,group:Kv},aF={default:Wp,straight:Hv,step:qv,smoothstep:gg,simplebezier:Wv},lF=[0,0],cF=[15,15],uF={x:0,y:0,zoom:1},dF={width:"100%",height:"100%",overflow:"hidden",position:"relative",zIndex:0},I1=_.forwardRef(({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,className:i,nodeTypes:a=oF,edgeTypes:u=aF,onNodeClick:c,onEdgeClick:d,onInit:m,onMove:h,onMoveStart:p,onMoveEnd:y,onConnect:w,onConnectStart:x,onConnectEnd:k,onClickConnectStart:b,onClickConnectEnd:S,onNodeMouseEnter:$,onNodeMouseMove:A,onNodeMouseLeave:E,onNodeContextMenu:z,onNodeDoubleClick:F,onNodeDragStart:M,onNodeDrag:D,onNodeDragStop:H,onNodesDelete:q,onEdgesDelete:I,onSelectionChange:Z,onSelectionDragStart:R,onSelectionDrag:T,onSelectionDragStop:P,onSelectionContextMenu:L,onSelectionStart:te,onSelectionEnd:X,connectionMode:V=lu.Strict,connectionLineType:ne=Jl.Bezier,connectionLineStyle:W,connectionLineComponent:Y,connectionLineContainerStyle:K,deleteKeyCode:fe="Backspace",selectionKeyCode:ae="Shift",selectionOnDrag:ve=!1,selectionMode:ge=Qm.Full,panActivationKeyCode:pe="Space",multiSelectionKeyCode:$e=Up()?"Meta":"Control",zoomActivationKeyCode:De=Up()?"Meta":"Control",snapToGrid:ot=!1,snapGrid:bt=cF,onlyRenderVisibleElements:Ue=!1,selectNodesOnDrag:at=!0,nodesDraggable:Nt,nodesConnectable:ut,nodesFocusable:Se,nodeOrigin:me=lF,edgesFocusable:Ve,edgesUpdatable:ye,elementsSelectable:Ie,defaultViewport:ct=uF,minZoom:ie=.5,maxZoom:Te=2,translateExtent:et=zw,preventScrolling:Ge=!0,nodeExtent:Be,defaultMarkerColor:Rt="#b1b1b7",zoomOnScroll:Nn=!0,zoomOnPinch:Qt=!0,panOnScroll:Un=!1,panOnScrollSpeed:rs=.5,panOnScrollMode:Dn=Kc.Free,zoomOnDoubleClick:$n=!0,panOnDrag:Cn=!0,onPaneClick:an,onPaneMouseEnter:is,onPaneMouseMove:Wn,onPaneMouseLeave:Fn,onPaneScroll:Hs,onPaneContextMenu:es,children:he,onEdgeUpdate:Ee,onEdgeContextMenu:mt,onEdgeDoubleClick:se,onEdgeMouseEnter:ce,onEdgeMouseMove:je,onEdgeMouseLeave:Ae,onEdgeUpdateStart:ze,onEdgeUpdateEnd:Fe,edgeUpdaterRadius:Ze=10,onNodesChange:lt,onEdgesChange:ht,noDragClassName:_t="nodrag",noWheelClassName:kt="nowheel",noPanClassName:At="nopan",fitView:rt=!1,fitViewOptions:zt,connectOnClick:dn=!0,attributionPosition:on,proOptions:Ht,defaultEdgeOptions:Ot,elevateNodesOnSelect:ts=!0,elevateEdgesOnSelect:Pe=!1,disableKeyboardA11y:Ut=!1,autoPanOnConnect:St=!0,autoPanOnNodeDrag:Mn=!0,connectionRadius:nn=20,isValidConnection:Je,onError:en,style:Yt,id:Cr,nodeDragThreshold:Ns,...ps},_r)=>{const we=Cr||"1";return Ne.createElement("div",{...ps,style:{...Yt,...dF},ref:_r,className:$r(["react-flow",i]),"data-testid":"rf__wrapper",id:Cr},Ne.createElement(L1,null,Ne.createElement(rF,{onInit:m,onMove:h,onMoveStart:p,onMoveEnd:y,onNodeClick:c,onEdgeClick:d,onNodeMouseEnter:$,onNodeMouseMove:A,onNodeMouseLeave:E,onNodeContextMenu:z,onNodeDoubleClick:F,nodeTypes:a,edgeTypes:u,connectionLineType:ne,connectionLineStyle:W,connectionLineComponent:Y,connectionLineContainerStyle:K,selectionKeyCode:ae,selectionOnDrag:ve,selectionMode:ge,deleteKeyCode:fe,multiSelectionKeyCode:$e,panActivationKeyCode:pe,zoomActivationKeyCode:De,onlyRenderVisibleElements:Ue,selectNodesOnDrag:at,defaultViewport:ct,translateExtent:et,minZoom:ie,maxZoom:Te,preventScrolling:Ge,zoomOnScroll:Nn,zoomOnPinch:Qt,zoomOnDoubleClick:$n,panOnScroll:Un,panOnScrollSpeed:rs,panOnScrollMode:Dn,panOnDrag:Cn,onPaneClick:an,onPaneMouseEnter:is,onPaneMouseMove:Wn,onPaneMouseLeave:Fn,onPaneScroll:Hs,onPaneContextMenu:es,onSelectionContextMenu:L,onSelectionStart:te,onSelectionEnd:X,onEdgeUpdate:Ee,onEdgeContextMenu:mt,onEdgeDoubleClick:se,onEdgeMouseEnter:ce,onEdgeMouseMove:je,onEdgeMouseLeave:Ae,onEdgeUpdateStart:ze,onEdgeUpdateEnd:Fe,edgeUpdaterRadius:Ze,defaultMarkerColor:Rt,noDragClassName:_t,noWheelClassName:kt,noPanClassName:At,elevateEdgesOnSelect:Pe,rfId:we,disableKeyboardA11y:Ut,nodeOrigin:me,nodeExtent:Be}),Ne.createElement(e6,{nodes:e,edges:t,defaultNodes:n,defaultEdges:r,onConnect:w,onConnectStart:x,onConnectEnd:k,onClickConnectStart:b,onClickConnectEnd:S,nodesDraggable:Nt,nodesConnectable:ut,nodesFocusable:Se,edgesFocusable:Ve,edgesUpdatable:ye,elementsSelectable:Ie,elevateNodesOnSelect:ts,minZoom:ie,maxZoom:Te,nodeExtent:Be,onNodesChange:lt,onEdgesChange:ht,snapToGrid:ot,snapGrid:bt,connectionMode:V,translateExtent:et,connectOnClick:dn,defaultEdgeOptions:Ot,fitView:rt,fitViewOptions:zt,onNodesDelete:q,onEdgesDelete:I,onNodeDragStart:M,onNodeDrag:D,onNodeDragStop:H,onSelectionDrag:T,onSelectionDragStart:R,onSelectionDragStop:P,noPanClassName:At,nodeOrigin:me,rfId:we,autoPanOnConnect:St,autoPanOnNodeDrag:Mn,onError:en,connectionRadius:nn,isValidConnection:Je,nodeDragThreshold:Ns}),Ne.createElement(ZD,{onSelectionChange:Z}),he,Ne.createElement(ND,{proOptions:Ht,position:on}),Ne.createElement(i6,{rfId:we,disableKeyboardA11y:Ut})))});I1.displayName="ReactFlow";const O1=({id:e,x:t,y:n,width:r,height:i,style:a,color:u,strokeColor:c,strokeWidth:d,className:m,borderRadius:h,shapeRendering:p,onClick:y,selected:w})=>{const{background:x,backgroundColor:k}=a||{},b=u||x||k;return Ne.createElement("rect",{className:$r(["react-flow__minimap-node",{selected:w},m]),x:t,y:n,rx:h,ry:h,width:r,height:i,fill:b,stroke:c,strokeWidth:d,shapeRendering:p,onClick:y?S=>y(S,e):void 0})};O1.displayName="MiniMapNode";var fF=_.memo(O1);const mF=e=>e.nodeOrigin,hF=e=>e.getNodes().filter(t=>!t.hidden&&t.width&&t.height),Cy=e=>e instanceof Function?e:()=>e;function _F({nodeStrokeColor:e="transparent",nodeColor:t="#e2e2e2",nodeClassName:n="",nodeBorderRadius:r=5,nodeStrokeWidth:i=2,nodeComponent:a=fF,onClick:u}){const c=fs(hF,hr),d=fs(mF),m=Cy(t),h=Cy(e),p=Cy(n),y=typeof window>"u"||window.chrome?"crispEdges":"geometricPrecision";return Ne.createElement(Ne.Fragment,null,c.map(w=>{const{x,y:k}=Qc(w,d).positionAbsolute;return Ne.createElement(a,{key:w.id,x,y:k,width:w.width,height:w.height,style:w.style,selected:w.selected,className:p(w),color:m(w),borderRadius:r,strokeColor:h(w),strokeWidth:i,shapeRendering:y,onClick:u,id:w.id})}))}var pF=_.memo(_F);const gF=200,yF=150,wF=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?ED(yg(t,e.nodeOrigin),n):n,rfId:e.rfId}},vF="react-flow__minimap-desc";function P1({style:e,className:t,nodeStrokeColor:n="transparent",nodeColor:r="#e2e2e2",nodeClassName:i="",nodeBorderRadius:a=5,nodeStrokeWidth:u=2,nodeComponent:c,maskColor:d="rgb(240, 240, 240, 0.6)",maskStrokeColor:m="none",maskStrokeWidth:h=1,position:p="bottom-right",onClick:y,onNodeClick:w,pannable:x=!1,zoomable:k=!1,ariaLabel:b="React Flow mini map",inversePan:S=!1,zoomStep:$=10,offsetScale:A=5}){const E=er(),z=_.useRef(null),{boundingRect:F,viewBB:M,rfId:D}=fs(wF,hr),H=(e==null?void 0:e.width)??gF,q=(e==null?void 0:e.height)??yF,I=F.width/H,Z=F.height/q,R=Math.max(I,Z),T=R*H,P=R*q,L=A*R,te=F.x-(T-F.width)/2-L,X=F.y-(P-F.height)/2-L,V=T+L*2,ne=P+L*2,W=`${vF}-${D}`,Y=_.useRef(0);Y.current=R,_.useEffect(()=>{if(z.current){const ae=mo(z.current),ve=$e=>{const{transform:De,d3Selection:ot,d3Zoom:bt}=E.getState();if($e.sourceEvent.type!=="wheel"||!ot||!bt)return;const Ue=-$e.sourceEvent.deltaY*($e.sourceEvent.deltaMode===1?.05:$e.sourceEvent.deltaMode?1:.002)*$,at=De[2]*Math.pow(2,Ue);bt.scaleTo(ot,at)},ge=$e=>{const{transform:De,d3Selection:ot,d3Zoom:bt,translateExtent:Ue,width:at,height:Nt}=E.getState();if($e.sourceEvent.type!=="mousemove"||!ot||!bt)return;const ut=Y.current*Math.max(1,De[2])*(S?-1:1),Se={x:De[0]-$e.sourceEvent.movementX*ut,y:De[1]-$e.sourceEvent.movementY*ut},me=[[0,0],[at,Nt]],Ve=Ka.translate(Se.x,Se.y).scale(De[2]),ye=bt.constrain()(Ve,me,Ue);bt.transform(ot,ye)},pe=VN().on("zoom",x?ge:null).on("zoom.wheel",k?ve:null);return ae.call(pe),()=>{ae.on("zoom",null)}}},[x,k,S,$]);const K=y?ae=>{const ve=zo(ae);y(ae,{x:ve[0],y:ve[1]})}:void 0,fe=w?(ae,ve)=>{const ge=E.getState().nodeInternals.get(ve);w(ae,ge)}:void 0;return Ne.createElement(Xm,{position:p,style:e,className:$r(["react-flow__minimap",t]),"data-testid":"rf__minimap"},Ne.createElement("svg",{width:H,height:q,viewBox:`${te} ${X} ${V} ${ne}`,role:"img","aria-labelledby":W,ref:z,onClick:K},b&&Ne.createElement("title",{id:W},b),Ne.createElement(pF,{onClick:fe,nodeColor:r,nodeStrokeColor:n,nodeBorderRadius:a,nodeClassName:i,nodeStrokeWidth:u,nodeComponent:c}),Ne.createElement("path",{className:"react-flow__minimap-mask",d:`M${te-L},${X-L}h${V+L*2}v${ne+L*2}h${-V-L*2}z
|
|
152
|
+
M${M.x},${M.y}h${M.width}v${M.height}h${-M.width}z`,fill:d,fillRule:"evenodd",stroke:m,strokeWidth:h,pointerEvents:"none"})))}P1.displayName="MiniMap";var xF=_.memo(P1);function bF(){return Ne.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 32"},Ne.createElement("path",{d:"M32 18.133H18.133V32h-4.266V18.133H0v-4.266h13.867V0h4.266v13.867H32z"}))}function kF(){return Ne.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 5"},Ne.createElement("path",{d:"M0 0h32v4.2H0z"}))}function jF(){return Ne.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 30"},Ne.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 SF(){return Ne.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 25 32"},Ne.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 NF(){return Ne.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 25 32"},Ne.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 Rd=({children:e,className:t,...n})=>Ne.createElement("button",{type:"button",className:$r(["react-flow__controls-button",t]),...n},e);Rd.displayName="ControlButton";const $F=e=>({isInteractive:e.nodesDraggable||e.nodesConnectable||e.elementsSelectable,minZoomReached:e.transform[2]<=e.minZoom,maxZoomReached:e.transform[2]>=e.maxZoom}),D1=({style:e,showZoom:t=!0,showFitView:n=!0,showInteractive:r=!0,fitViewOptions:i,onZoomIn:a,onZoomOut:u,onFitView:c,onInteractiveChange:d,className:m,children:h,position:p="bottom-left"})=>{const y=er(),[w,x]=_.useState(!1),{isInteractive:k,minZoomReached:b,maxZoomReached:S}=fs($F,hr),{zoomIn:$,zoomOut:A,fitView:E}=Jv();if(_.useEffect(()=>{x(!0)},[]),!w)return null;const z=()=>{$(),a==null||a()},F=()=>{A(),u==null||u()},M=()=>{E(i),c==null||c()},D=()=>{y.setState({nodesDraggable:!k,nodesConnectable:!k,elementsSelectable:!k}),d==null||d(!k)};return Ne.createElement(Xm,{className:$r(["react-flow__controls",m]),position:p,style:e,"data-testid":"rf__controls"},t&&Ne.createElement(Ne.Fragment,null,Ne.createElement(Rd,{onClick:z,className:"react-flow__controls-zoomin",title:"zoom in","aria-label":"zoom in",disabled:S},Ne.createElement(bF,null)),Ne.createElement(Rd,{onClick:F,className:"react-flow__controls-zoomout",title:"zoom out","aria-label":"zoom out",disabled:b},Ne.createElement(kF,null))),n&&Ne.createElement(Rd,{className:"react-flow__controls-fitview",onClick:M,title:"fit view","aria-label":"fit view"},Ne.createElement(jF,null)),r&&Ne.createElement(Rd,{className:"react-flow__controls-interactive",onClick:D,title:"toggle interactivity","aria-label":"toggle interactivity"},k?Ne.createElement(NF,null):Ne.createElement(SF,null)),h)};D1.displayName="Controls";var CF=_.memo(D1),qo;(function(e){e.Lines="lines",e.Dots="dots",e.Cross="cross"})(qo||(qo={}));function EF({color:e,dimensions:t,lineWidth:n}){return Ne.createElement("path",{stroke:e,strokeWidth:n,d:`M${t[0]/2} 0 V${t[1]} M0 ${t[1]/2} H${t[0]}`})}function AF({color:e,radius:t}){return Ne.createElement("circle",{cx:t,cy:t,r:t,fill:e})}const TF={[qo.Dots]:"#91919a",[qo.Lines]:"#eee",[qo.Cross]:"#e2e2e2"},MF={[qo.Dots]:1,[qo.Lines]:1,[qo.Cross]:6},RF=e=>({transform:e.transform,patternId:`pattern-${e.rfId}`});function F1({id:e,variant:t=qo.Dots,gap:n=20,size:r,lineWidth:i=1,offset:a=2,color:u,style:c,className:d}){const m=_.useRef(null),{transform:h,patternId:p}=fs(RF,hr),y=u||TF[t],w=r||MF[t],x=t===qo.Dots,k=t===qo.Cross,b=Array.isArray(n)?n:[n,n],S=[b[0]*h[2]||1,b[1]*h[2]||1],$=w*h[2],A=k?[$,$]:S,E=x?[$/a,$/a]:[A[0]/a,A[1]/a];return Ne.createElement("svg",{className:$r(["react-flow__background",d]),style:{...c,position:"absolute",width:"100%",height:"100%",top:0,left:0},ref:m,"data-testid":"rf__background"},Ne.createElement("pattern",{id:p+e,x:h[0]%S[0],y:h[1]%S[1],width:S[0],height:S[1],patternUnits:"userSpaceOnUse",patternTransform:`translate(-${E[0]},-${E[1]})`},x?Ne.createElement(AF,{color:y,radius:$/a}):Ne.createElement(EF,{dimensions:A,color:y,lineWidth:i})),Ne.createElement("rect",{x:"0",y:"0",width:"100%",height:"100%",fill:`url(#${p+e})`}))}F1.displayName="Background";var LF=_.memo(F1);function z1(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,i=typeof n.y=="number"&&Number.isFinite(n.y)?n.y:null,a=typeof n.zoom=="number"&&Number.isFinite(n.zoom)?n.zoom:null;if(r===null||i===null||a===null)return null;const u=typeof t.maxAbsTranslate=="number"&&Number.isFinite(t.maxAbsTranslate)?Math.abs(t.maxAbsTranslate):1e6;if(Math.abs(r)>u||Math.abs(i)>u)return null;const c=typeof t.minZoom=="number"&&Number.isFinite(t.minZoom)?t.minZoom:.025,d=typeof t.maxZoom=="number"&&Number.isFinite(t.maxZoom)?t.maxZoom:6,m=Math.min(c,d),h=Math.max(c,d);return{x:r,y:i,zoom:Math.min(h,Math.max(m,a))}}function Hp(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 IF(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(),i=t.slice(n+1).toLowerCase();if(r==="ex"){const a=i.indexOf("-"),u=a>0?i.slice(0,a):i;return u==="person"?"person":u==="org"?"org":u==="concept"?"concept":u==="claim"?"claim":u==="event"?"event":u==="doc"?"doc":u==="thing"?"thing":"entity"}return r==="schema"||r==="skos"||r==="dcterms"||r==="rdf"||r==="cito"?"vocab":"entity"}function OF(e){const t=String(e||"").trim();if(!t)return"";const n=t.indexOf(":");if(n<=0||n>=t.length-1)return Hp(t);const r=t.slice(0,n).toLowerCase(),i=t.slice(n+1);if(r==="ex"){const a=i.indexOf("-");if(a>0&&a<i.length-1)return i.slice(a+1)}return Hp(t)}function Bw(e){const r=Math.max(1,Math.ceil(Math.sqrt(e.length))),i={};for(let a=0;a<e.length;a++){const u=Math.floor(a/r),c=a%r;i[e[a]]={x:c*240,y:u*120}}return i}function Uw(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 B1(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 PF(e,t){const n={},r=e.length;if(!r)return n;const i=Math.max(260,Math.sqrt(r)*150),a=t%360*Math.PI/180;for(let u=0;u<r;u++){const c=a+2*Math.PI*u/r;n[e[u]]={x:i*Math.cos(c),y:i*Math.sin(c)}}return n}function nk(e,t,n){var x;const r={};if(!e.length)return r;const i=new Map;for(const k of e)i.set(k,new Set);for(const k of t){const b=String((k==null?void 0:k.source)||"").trim(),S=String((k==null?void 0:k.target)||"").trim();if(!b||!S||b===S)continue;const $=i.get(b),A=i.get(S);$&&$.add(S),A&&A.add(b)}let a=e[0],u=-1;for(const k of e){const b=((x=i.get(k))==null?void 0:x.size)??0;(b>u||b===u&&k.localeCompare(a)<0)&&(a=k,u=b)}const c=new Map,d=[];for(c.set(a,0),d.push(a);d.length;){const k=d.shift(),b=c.get(k)??0,S=Array.from(i.get(k)??[]);S.sort(($,A)=>$.localeCompare(A));for(const $ of S)c.has($)||(c.set($,b+1),d.push($))}let m=0;for(const k of c.values())m=Math.max(m,k);for(const k of e)c.has(k)||c.set(k,m+1);const h=new Map;for(const k of e){const b=c.get(k)??0,S=h.get(b);S?S.push(k):h.set(b,[k])}const p=Array.from(h.keys()).sort((k,b)=>k-b),y=260,w=n%360*Math.PI/180;for(const k of p){const b=h.get(k)||[];if(b.sort((E,z)=>E.localeCompare(z)),k===0){if(b.length===1)r[b[0]]={x:0,y:0};else for(let z=0;z<b.length;z++){const F=w+2*Math.PI*z/b.length;r[b[z]]={x:80*Math.cos(F),y:80*Math.sin(F)}}continue}const S=y*k,$=b.length;if($===1){r[b[0]]={x:S,y:0};continue}const A=w+k*.35;for(let E=0;E<$;E++){const z=A+2*Math.PI*E/$;r[b[E]]={x:S*Math.cos(z),y:S*Math.sin(z)}}}return r}function Sd(e,t={}){const n=t.kind??"grid",r=typeof t.seed=="number"&&Number.isFinite(t.seed)?Math.trunc(t.seed):0,i=e.nodes.map(a=>a.id);if(n==="grid")return Bw(i);if(n==="circle")return PF(i,r);if(n==="radial")return nk(i,e.edges,r);if(n==="force"){const a=nk(i,e.edges,r),u=B1(r||1),c=Math.max(10,Math.min(42,Math.sqrt(i.length)*2.75)),d={};for(const m of i){const h=a[m]||{x:0,y:0};d[m]={x:h.x+(u()-.5)*c,y:h.y+(u()-.5)*c}}return d}return Bw(i)}function DF(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 FF(e,t={}){const n=!!(t.groupEdges??!0),r=Math.max(1,t.maxEdgeLabelPredicates??3),i=DF(e),a=new Set;for(const y of i){const w=String(y.subject||"").trim(),x=String(y.object||"").trim();w&&a.add(w),x&&a.add(x)}const u=Array.from(a);u.sort((y,w)=>y.localeCompare(w));const c=Bw(u),d=u.map(y=>({id:y,type:"default",data:{label:OF(y),kind:IF(y)},position:c[y]||{x:0,y:0}})),m=new Map,h=(y,w)=>{const x=String(y.subject||"").trim(),k=String(y.object||"").trim(),b=String(y.predicate||"").trim();return n?`edge:${x}:${k}`:`edge:${w}:${x}:${b}:${k}`};for(let y=0;y<i.length;y++){const w=i[y],x=h(w,y),k=m.get(x);k?k.push(w):m.set(x,[w])}const p=[];for(const[y,w]of m.entries()){const x=w[0],k=String(x.subject||"").trim(),b=String(x.object||"").trim();if(!k||!b)continue;const S=new Map;for(const M of w){const D=String(M.predicate||"").trim();D&&S.set(D,(S.get(D)||0)+1)}const $=Array.from(S.entries());$.sort((M,D)=>D[1]-M[1]||M[0].localeCompare(D[0]));const E=$.slice(0,r).map(([M,D])=>D>1?`${Hp(M)}×${D}`:Hp(M)).join(" | "),z=$.length>r?` +${$.length-r}`:"",F=`${E}${z}`.trim();p.push({id:y,source:k,target:b,label:F,animated:!1,data:{assertions:w,predicateSummary:F}})}return{nodes:d,edges:p}}function zF(e,t,n,r={}){const i=r.directed!==!1,a=String(t||"").trim(),u=String(n||"").trim();if(!a||!u)return null;if(a===u)return{nodeIds:[a],edgeIds:[]};const c=new Map,d=(k,b,S)=>{const $=c.get(k);$?$.push({to:b,edgeId:S}):c.set(k,[{to:b,edgeId:S}])};for(const k of e.edges)d(k.source,k.target,k.id),i||d(k.target,k.source,k.id);const m=[a],h=new Map,p=new Map;for(h.set(a,null),p.set(a,null);m.length;){const k=m.shift(),b=c.get(k)||[];for(const S of b)if(!h.has(S.to)){if(h.set(S.to,k),p.set(S.to,S.edgeId),S.to===u){m.length=0;break}m.push(S.to)}}if(!h.has(u))return null;const y=[],w=[];let x=u;for(;x;){y.push(x);const k=p.get(x);k&&w.push(k),x=h.get(x)||null}return y.reverse(),w.reverse(),{nodeIds:y,edgeIds:w}}const sk={seed:1,dt:1,springLength:240,springStrength:.03,repulsionStrength:9e3,centeringStrength:.003,damping:.85,maxSpeed:90,maxRepulsionNodes:320};function Q_(e,t={}){const n={...sk,...t,seed:typeof t.seed=="number"&&Number.isFinite(t.seed)?Math.trunc(t.seed):sk.seed},r=e.nodes.map(w=>w.id),i=r.length,a=new Float64Array(2*i),u=new Float64Array(2*i),c=new Float64Array(2*i),d=new Map;for(let w=0;w<i;w++)d.set(r[w],w);const m=t.positions??Sd(e,{kind:"force",seed:n.seed}),h=B1(n.seed||1),p=Math.max(8,Math.min(38,Math.sqrt(i)*2.25));for(let w=0;w<i;w++){const x=r[w],k=m[x],b=typeof(k==null?void 0:k.x)=="number"&&Number.isFinite(k.x)?k.x:(h()-.5)*500,S=typeof(k==null?void 0:k.y)=="number"&&Number.isFinite(k.y)?k.y:(h()-.5)*500;a[2*w]=b+(h()-.5)*p,a[2*w+1]=S+(h()-.5)*p,u[2*w]=0,u[2*w+1]=0}const y=[];for(const w of e.edges){const x=d.get(String((w==null?void 0:w.source)||"").trim()),k=d.get(String((w==null?void 0:w.target)||"").trim());typeof x!="number"||typeof k!="number"||x===k||y.push(x,k)}return{nodeIds:r,pos:a,vel:u,acc:c,edges:new Uint32Array(y),options:n,tick:0}}function BF(e,t=1){const n=e.nodeIds.length;if(!n)return;const r=e.options,i=r.dt;for(let a=0;a<Math.max(1,Math.trunc(t));a++){if(e.acc.fill(0),n<=r.maxRepulsionNodes){const w=r.repulsionStrength;for(let x=0;x<n;x++){const k=e.pos[2*x],b=e.pos[2*x+1];for(let S=x+1;S<n;S++){const $=e.pos[2*S]-k,A=e.pos[2*S+1]-b,E=$*$+A*A+1e-6,z=1/Math.sqrt(E),F=w/E,M=F*$*z,D=F*A*z;e.acc[2*x]-=M,e.acc[2*x+1]-=D,e.acc[2*S]+=M,e.acc[2*S+1]+=D}}}const c=r.springLength,d=r.springStrength,m=e.edges;for(let w=0;w<m.length;w+=2){const x=m[w],k=m[w+1],b=e.pos[2*x],S=e.pos[2*x+1],$=e.pos[2*k],A=e.pos[2*k+1],E=$-b,z=A-S,F=E*E+z*z+1e-6,M=Math.sqrt(F),D=d*(M-c),H=D*E/M,q=D*z/M;e.acc[2*x]+=H,e.acc[2*x+1]+=q,e.acc[2*k]-=H,e.acc[2*k+1]-=q}const h=r.centeringStrength;for(let w=0;w<n;w++)e.acc[2*w]+=-h*e.pos[2*w],e.acc[2*w+1]+=-h*e.pos[2*w+1];const p=r.damping,y=r.maxSpeed;for(let w=0;w<n;w++){let x=(e.vel[2*w]+e.acc[2*w]*i)*p,k=(e.vel[2*w+1]+e.acc[2*w+1]*i)*p;const b=Math.sqrt(x*x+k*k);if(b>y){const S=y/b;x*=S,k*=S}e.vel[2*w]=x,e.vel[2*w+1]=k,e.pos[2*w]+=x*i,e.pos[2*w+1]+=k*i}e.tick+=1}}function UF(e){const t=e.nodeIds.length;if(!t)return 0;let n=0;for(let r=0;r<t;r++){const i=e.vel[2*r],a=e.vel[2*r+1];n+=Math.sqrt(i*i+a*a)}return n/t}function WF(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 rk(e,t="session"){const n=String(e??"").trim().toLowerCase();return n==="run"||n==="session"||n==="global"||n==="all"?n:t}function qF(){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 HF(){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 U1(e,t,n,r){const i=typeof e=="number"&&Number.isFinite(e)?e:r;return Math.min(n,Math.max(t,i))}function ym(e){const t=U1(e,.6,2.4,1),n=240*t,r=9e3*t*t;return{springLength:n,repulsionStrength:r}}const nh="abstractuic_amx_saved_layouts_v1",Ww=.025,qw=6,W1=1e6;function Zv(){if(typeof window>"u")return null;try{return window.localStorage}catch{return null}}function Hw(e,t="grid"){const n=String(e??"").trim().toLowerCase();return n==="grid"||n==="circle"||n==="radial"||n==="force"?n:t}function VF(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 ik(e){const t=Zv();if(!t)return null;const n=String(e??"").trim();if(!n)return null;try{const r=t.getItem(nh);if(!r)return null;const i=JSON.parse(r),a=i&&typeof i=="object"&&!Array.isArray(i)?i:null;if(!a)return null;const u=a[n],c=u&&typeof u=="object"&&!Array.isArray(u)?u:null;if(!c)return null;const d=c.version===1?1:null;if(d===null)return null;const m=Hw(c.kind,"grid"),h=typeof c.seed=="number"&&Number.isFinite(c.seed)?Math.trunc(c.seed):Uw(n),p=c.positions&&typeof c.positions=="object"&&!Array.isArray(c.positions)?c.positions:null,y={};if(p)for(const[k,b]of Object.entries(p)){const S=VF(b);S&&(y[String(k)]=S)}const w=z1(c.viewport,{minZoom:Ww,maxZoom:qw,maxAbsTranslate:W1})??void 0,x=typeof c.saved_at=="string"&&c.saved_at.trim()?c.saved_at.trim():"";return{version:d,kind:m,seed:h,positions:y,viewport:w,saved_at:x}}catch{return null}}function GF(e,t){const n=Zv();if(!n)return;const r=String(e??"").trim();if(r)try{const i=n.getItem(nh),a=i?JSON.parse(i):null,u=a&&typeof a=="object"&&!Array.isArray(a)?{...a}:{};u[r]=t,n.setItem(nh,JSON.stringify(u))}catch{}}function KF(e){const t=Zv();if(!t)return;const n=String(e??"").trim();if(n)try{const r=t.getItem(nh);if(!r)return;const i=JSON.parse(r),a=i&&typeof i=="object"&&!Array.isArray(i)?{...i}:null;if(!a||!(n in a))return;delete a[n],t.setItem(nh,JSON.stringify(a))}catch{}}function JF(e){const t=String(e??"").trim();if(!t)return;const n=Number(t);if(Number.isFinite(n))return n}function Ey(e,t){const n=!!(t!=null&&t.allowZero),r=!!(t!=null&&t.allowNegativeOne),i=String(e??"").trim();if(!i)return;const a=Number(i);if(!Number.isFinite(a))return;const u=Math.trunc(a);if(r&&u===-1)return-1;if(!(!n&&u<=0)&&!(n&&u<0))return u}function YF(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,i=[];return n&&i.push(`recall_level=${n}`),r&&(typeof r.limit=="number"&&i.push(`limit=${r.limit}`),typeof r.min_score=="number"&&i.push(`min_score=${r.min_score}`),typeof r.max_input_tokens=="number"&&i.push(`max_input_tokens=${r.max_input_tokens}`)),i.length?i.join(" · "):null}function XF(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 i=typeof e.confidence=="number"&&Number.isFinite(e.confidence)?e.confidence:null;i!==null&&t.push(`confidence=${i.toFixed(3)}`);const a=e.provenance&&typeof e.provenance=="object"&&!Array.isArray(e.provenance)?e.provenance:null;if(a){const m=typeof a.writer_run_id=="string"?a.writer_run_id.trim():"",h=typeof a.writer_workflow_id=="string"?a.writer_workflow_id.trim():"";m&&t.push(`writer_run_id=${m}`),h&&t.push(`writer_workflow_id=${h}`)}const u=e.attributes&&typeof e.attributes=="object"&&!Array.isArray(e.attributes)?e.attributes:null,c=u&&u._retrieval&&typeof u._retrieval=="object"&&!Array.isArray(u._retrieval)?u._retrieval:null,d=c&&typeof c.score=="number"&&Number.isFinite(c.score)?c.score:null;return d!==null&&t.push(`score=${d.toFixed(3)}`),t.length?t.join(" · "):null}function ZF(e,t){const n=String(e??""),r=String(t??"").trim();if(!r)return n;const i=n.toLowerCase().indexOf(r.toLowerCase());if(i<0)return n;const a=n.slice(0,i),u=n.slice(i,i+r.length),c=n.slice(i+r.length);return s.jsxs(s.Fragment,{children:[a,s.jsx("span",{className:"amx-hl",children:u}),c]})}function wm(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 QF(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 vm(e){const t=QF(e);if(t===null)return"";const n=new Date(t),r=n.getUTCFullYear(),i=String(n.getUTCMonth()+1).padStart(2,"0"),a=String(n.getUTCDate()).padStart(2,"0"),u=String(n.getUTCHours()).padStart(2,"0"),c=String(n.getUTCMinutes()).padStart(2,"0");return`${r}/${i}/${a} ${u}:${c}`}function q1(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 Ay(e,t){const n=String(e??"").trim().toLowerCase();return!!(n&&t.has(n))}function e8(e,t={}){const n=Math.max(1,t.maxPredicates??3),r=new Map;for(const d of e){const m=String((d==null?void 0:d.predicate)||"").trim();m&&r.set(m,(r.get(m)||0)+1)}const i=Array.from(r.entries());i.sort((d,m)=>m[1]-d[1]||d[0].localeCompare(m[0]));const u=i.slice(0,n).map(([d,m])=>{const h=q1(d);return m>1?`${h}×${m}`:h}).join(" | "),c=i.length>n?` +${i.length-n}`:"";return`${u}${c}`.trim()}function t8({resetKey:e,queryMode:t,items:n,activeMemoryText:r,packets:i,packetsVersion:a,packedCount:u,dropped:c,estimatedTokens:d,effort:m,warnings:h,onQuery:p,onItemsReplace:y,onOpenSpan:w,onOpenTranscript:x}){var qn;const k=_.useRef(null),b=_.useMemo(()=>{const G=n==null?void 0:n[0],ue=n==null?void 0:n[n.length-1],Me=G?`${G.subject}|${G.predicate}|${G.object}`:"",Re=ue?`${ue.subject}|${ue.predicate}|${ue.object}`:"";return`${(n==null?void 0:n.length)||0}:${Me}:${Re}`},[n]),S=String(e??b),$=t==="replace"?"replace":"override",[A,E]=_.useState(null),[z,F]=_.useState(null),[M,D]=_.useState(!1),[H,q]=_.useState(""),[I,Z]=_.useState(!1),[R,T]=_.useState("");_.useEffect(()=>{E(null),F(null),q(""),D(!1),T(""),Z(!1)},[S]);const[P,L]=_.useState(""),[te,X]=_.useState(!0),[V,ne]=_.useState(!1),[W,Y]=_.useState(!0),[K]=_.useState(()=>({compact:qF(),show:!1})),fe=K.compact,[ae,ve]=_.useState(K.show),[ge,pe]=_.useState(!1),$e=S,De=_.useMemo(()=>Uw($e),[$e]),[ot,bt]=_.useState("grid"),[Ue,at]=_.useState(De),[Nt,ut]=_.useState(!1),[Se,me]=_.useState(1),Ve=_.useRef(null),ye=_.useRef(null),Ie=_.useRef(!1),[ct,ie]=_.useState(0),Te=_.useRef(null),et=_.useRef(0),Ge=_.useRef(0),Be=_.useRef(0),Rt=_.useRef(0),[Nn,Qt]=_.useState(!1),[Un,rs]=_.useState(""),[Dn,$n]=_.useState({}),Cn=_.useRef({});_.useEffect(()=>{Cn.current=Dn},[Dn]);const[an,is]=_.useState(""),[Wn,Fn]=_.useState(""),Hs=_.useMemo(()=>{var ue;const G=(ue=n==null?void 0:n[0])==null?void 0:ue.scope;return rk(G,"session")},[n]),[es,he]=_.useState(Hs),[Ee,mt]=_.useState("standard"),[se,ce]=_.useState(""),[je,Ae]=_.useState(""),[ze,Fe]=_.useState(""),[Ze,lt]=_.useState(""),[ht,_t]=_.useState(""),[kt,At]=_.useState(""),[rt,zt]=_.useState(""),[dn,on]=_.useState("qwen/qwen3-next-80b");_.useEffect(()=>{he(Hs)},[S]);const Ht=Array.isArray(n)?n:[],Ot=typeof r=="string"?r:"",ts=Array.isArray(i)?i:[],Pe=typeof a=="number"?a:void 0,Ut=typeof u=="number"?u:void 0,St=typeof c=="number"?c:void 0,Mn=typeof d=="number"?d:void 0,nn=m,Je=h,en=$==="override"&&(A!=null&&A.items)&&Array.isArray(A.items)?A.items:Ht,Yt=typeof(A==null?void 0:A.active_memory_text)=="string"&&A.active_memory_text.trim()?A.active_memory_text:Ot,Cr=(A==null?void 0:A.effort)??nn,Ns=(A==null?void 0:A.warnings)??Je,ps=_.useMemo(()=>new Set(["rdf:type","schema:name","skos:preflabel","skos:altlabel","dcterms:title","dcterms:identifier"]),[]),_r=_.useMemo(()=>W?en:(en||[]).filter(G=>!Ay(G==null?void 0:G.predicate,ps)),[en,W,ps]),we=_.useMemo(()=>FF(en,{groupEdges:te}),[en,te]),wt=_.useMemo(()=>{if(W)return we;const G=[];for(const ue of we.edges){const Re=(ue&&ue.data&&Array.isArray(ue.data.assertions)?ue.data.assertions:[]).filter(dt=>!Ay(dt==null?void 0:dt.predicate,ps));if(!Re.length)continue;const Ke=e8(Re);G.push({...ue,label:Ke,data:{...ue.data,assertions:Re,predicateSummary:Ke}})}return{nodes:we.nodes,edges:G}},[we,W,ps]),Rn=_.useMemo(()=>wt.nodes.map(G=>G.id),[wt.nodes]),tr=_.useMemo(()=>{const G=Rn[0]||"",ue=Rn[Rn.length-1]||"";return`${Rn.length}:${G}:${ue}`},[Rn]),bi=_.useMemo(()=>{var ue;const G=new Map;for(const Me of wt.nodes)G.set(Me.id,String(((ue=Me.data)==null?void 0:ue.label)||Me.id));return G},[wt.nodes]),nr=_.useMemo(()=>{var ue;const G=new Map;for(const Me of wt.nodes)G.set(Me.id,String(((ue=Me.data)==null?void 0:ue.kind)||""));return G},[wt.nodes]),po=P.trim().toLowerCase(),sc=_.useMemo(()=>{var ue;if(!po)return new Set;const G=new Set;for(const Me of wt.nodes){const Re=String(Me.id||"").toLowerCase(),Ke=String(((ue=Me.data)==null?void 0:ue.label)||"").toLowerCase();(Re.includes(po)||Ke.includes(po))&&G.add(Me.id)}return G},[wt.nodes,po]),Qa=_.useCallback((G,ue)=>{const Me={};for(const Re of Rn){const Ke=G[Re]||ue[Re];Me[Re]=Ke?{x:Ke.x,y:Ke.y}:{x:0,y:0}}return Me},[Rn]);_.useEffect(()=>{$n(G=>{const ue=Sd(wt,{kind:ot,seed:Ue}),Me={};for(const Re of Rn){const Ke=G[Re]||ue[Re];Me[Re]=Ke?{x:Ke.x,y:Ke.y}:{x:0,y:0}}return Me})},[wt,ot,Ue,Rn,tr]),_.useEffect(()=>{if(!Ie.current)return;const G=k.current;if(!(!G||typeof G.fitView!="function")&&Rn.length){Ie.current=!1;try{G.fitView({padding:.2,duration:0})}catch{try{G.fitView({padding:.2})}catch{}}}},[Rn.length,tr,Dn]),_.useEffect(()=>{ut(!1),Ve.current=null,ye.current=null,Ie.current=!1,et.current=0,Ge.current=0,Be.current=0;const G=ik($e);if(G&&Object.keys(G.positions||{}).length){if(bt(G.kind),at(G.seed),Qt(!0),rs(G.saved_at||""),G.viewport){ye.current=G.viewport;const Ke=k.current;if(Ke&&typeof Ke.setViewport=="function"){try{Ke.setViewport(G.viewport,{duration:0})}catch{try{Ke.setViewport(G.viewport)}catch{}}ye.current=null}}else Ie.current=!0;const Re=Sd(wt,{kind:G.kind,seed:G.seed});$n(Qa(G.positions,Re));return}Qt(!1),rs("");const ue=Uw($e);at(ue);const Me=Sd(wt,{kind:ot,seed:ue});$n(Me),ot==="force"&&wt.nodes.length>0&&wt.nodes.length<=320&&(Ve.current=Q_(wt,{seed:ue,positions:Me,...ym(Se)}),ut(!0))},[$e]);const ws=_.useMemo(()=>{const G=String(an||"").trim(),ue=String(Wn||"").trim();return!G||!ue?null:zF(wt,G,ue,{directed:V})},[wt,an,Wn,V]),pr=!!(ws&&String(an||"").trim()&&String(Wn||"").trim()),Ms=_.useMemo(()=>{const G=String(an||"").trim(),ue=String(Wn||"").trim();if(!G||!ue)return null;const Me=V,Re=new Map,Ke=(Ct,Tt)=>{const cn=Re.get(Ct);cn?cn.push(Tt):Re.set(Ct,[Tt])};for(const Ct of wt.edges)Ke(Ct.source,Ct.target),Me||Ke(Ct.target,Ct.source);const dt=new Set,Lt=[];for(dt.add(G),Lt.push(G);Lt.length;){const Ct=Lt.shift(),Tt=Re.get(Ct)||[];for(const cn of Tt)dt.has(cn)||(dt.add(cn),Lt.push(cn))}return{reachableFromStart:dt.size,endReachable:dt.has(ue),nodes:wt.nodes.length,edges:wt.edges.length,assertions:_r.length}},[V,wt.edges,wt.nodes.length,Wn,an,_r.length]),Fi=_.useMemo(()=>new Set((ws==null?void 0:ws.nodeIds)||[]),[ws]),el=_.useMemo(()=>new Set((ws==null?void 0:ws.edgeIds)||[]),[ws]),[gs,si]=_.useState(""),[Rs,ri]=_.useState(""),vs=!!(String(gs||"").trim()||String(Rs||"").trim()),ii=_.useMemo(()=>{const G=new Set,ue=new Set,Me=String(gs||"").trim(),Re=String(Rs||"").trim();if(Me){G.add(Me);for(const Ke of wt.edges)(Ke.source===Me||Ke.target===Me)&&(ue.add(Ke.id),G.add(Ke.source),G.add(Ke.target));return{nodes:G,edges:ue}}if(Re){const Ke=wt.edges.find(dt=>dt.id===Re);Ke&&(ue.add(Ke.id),G.add(Ke.source),G.add(Ke.target))}return{nodes:G,edges:ue}},[wt.edges,Rs,gs]);_.useEffect(()=>{si(""),ri(""),is(""),Fn("")},[S]);const[zi,Sn]=_.useState(!1);_.useEffect(()=>{Sn(!1)},[S]),_.useEffect(()=>{Nt||(Ve.current=null)},[Nt]),_.useEffect(()=>{if(ot!=="force")return;const G=Ve.current;if(!G)return;const ue=ym(Se);G.options.springLength=ue.springLength,G.options.repulsionStrength=ue.repulsionStrength},[ot,Se]),_.useEffect(()=>{ot!=="force"&&Nt&&ut(!1)},[ot,Nt]),_.useEffect(()=>{if(!Nt||ot!=="force"||wt.nodes.length===0||typeof window>"u"||typeof window.requestAnimationFrame!="function")return;Ve.current||(Ve.current=Q_(wt,{seed:Ue,positions:Cn.current,...ym(Se)}));let G=0,ue=0,Me=0;const Re=wt.nodes.length<=140?2:1,Ke=1600,dt=.08,Lt=Ct=>{if(G=window.requestAnimationFrame(Lt),Ct-ue<33)return;ue=Ct;const Tt=Ve.current;if(!Tt){ut(!1);return}BF(Tt,Re),Me+=Re,$n(WF(Tt)),(UF(Tt)<=dt||Me>=Ke)&&ut(!1)};return G=window.requestAnimationFrame(Lt),()=>{window.cancelAnimationFrame(G)}},[wt,ot,Nt,Ue]);const ga=_.useMemo(()=>wt.nodes.map(G=>{var _n;const ue=Fi.has(G.id),Me=sc.has(G.id),Re=gs===G.id,Ke=vs&&ii.nodes.has(G.id),dt=wm((_n=G.data)==null?void 0:_n.kind),Lt="rgba(34, 211, 238, 0.88)",Ct=Me?"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)":"",Tt=ue?"rgba(168, 85, 247, 0.9)":Me?Lt:dt.stroke,cn=Re?"0 0 0 2px rgba(255,255,255,0.20), 0 18px 46px rgba(0,0,0,0.55)":Ke?"0 0 0 1px rgba(96, 165, 250, 0.28), 0 12px 34px rgba(0,0,0,0.45)":void 0,wn=Ct&&cn?`${Ct}, ${cn}`:cn||Ct||void 0,Vs=ue?"rgba(168, 85, 247, 0.10)":Me?"rgba(34, 211, 238, 0.08)":dt.bg,Et=pr?ue||Re?1:.16:vs?Ke||Re?1:.1:1;return{...G,position:Dn[G.id]?{x:Dn[G.id].x,y:Dn[G.id].y}:G.position,style:{...G.style||{},border:`1px solid ${Tt}`,borderRadius:10,background:Vs,color:"rgba(255,255,255,0.92)",opacity:Et,padding:8,fontSize:12,boxShadow:wn,width:180,cursor:"pointer"}}}),[wt.nodes,pr,sc,Dn,gs,Fi,vs,ii.nodes]),tl=_.useMemo(()=>wt.edges.map(G=>{const ue=el.has(G.id),Me=Rs===G.id,Re=vs&&ii.edges.has(G.id),Ke=ue?"rgba(168, 85, 247, 0.9)":vs?Re||Me?"rgba(96, 165, 250, 0.55)":"rgba(255,255,255,0.14)":"rgba(255,255,255,0.18)",dt=ue?2.75:vs?Re||Me?2.25:1.25:1.5,Lt=Me?"drop-shadow(0 0 10px rgba(168, 85, 247, 0.25))":void 0,Ct=ue?"rgba(168, 85, 247, 0.9)":pr?"rgba(255,255,255,0.10)":"rgba(255,255,255,0.28)",Tt=pr?ue||Me?1:.1:vs?Re||Me?1:.08:1,cn=pr?ue||Me?1:0:vs?Re||Me?1:0:1,wn=pr?ue||Me?String(G.label||""):"":String(G.label||"");return{...G,label:wn,style:{...G.style||{},stroke:Ke,strokeWidth:dt,filter:Lt,opacity:Tt},animated:!1,markerEnd:{type:eh.ArrowClosed,color:Ct,width:20,height:20},labelShowBg:!0,labelBgPadding:[6,3],labelBgBorderRadius:10,labelBgStyle:{fill:`rgba(0, 0, 0, ${.38*cn})`,stroke:`rgba(255, 255, 255, ${.14*cn})`,strokeWidth:1},labelStyle:{fill:`rgba(255, 255, 255, ${.92*cn})`,fontSize:10,fontWeight:600,letterSpacing:.2,textTransform:"lowercase"}}}),[wt.edges,pr,Rs,el,vs,ii.edges]),nl=_.useMemo(()=>{if(!Rs)return[];const G=wt.edges.find(Me=>Me.id===Rs),ue=G&&G.data&&Array.isArray(G.data.assertions)?G.data.assertions:[];return Array.isArray(ue)?ue:[]},[wt.edges,Rs]),Er=_.useMemo(()=>Rs&&wt.edges.find(G=>G.id===Rs)||null,[wt.edges,Rs]),rc=_.useMemo(()=>{const G=String(gs||"").trim();return G?en.filter(ue=>!ue||typeof ue!="object"||!(ue.subject===G||ue.object===G)?!1:W?!0:!Ay(ue.predicate,ps)):[]},[en,gs,W,ps]),Bi=_.useMemo(()=>Rs?nl:rc,[nl,Rs,rc]),ya=_.useMemo(()=>{const G=new Map;for(const ue of Bi){if(!ue||typeof ue!="object")continue;const Me=ue.provenance&&typeof ue.provenance=="object"&&!Array.isArray(ue.provenance)?ue.provenance:null,Re=Me&&typeof Me.span_id=="string"?Me.span_id.trim():"",Ke=Me&&typeof Me.writer_run_id=="string"?Me.writer_run_id.trim():"",dt=typeof ue.owner_id=="string"?ue.owner_id.trim():"",Lt=Ke||dt;if(!Lt||!Re)continue;const Ct=`${Lt}|${Re}`,Tt=G.get(Ct),cn=typeof ue.observed_at=="string"?ue.observed_at.trim():"";Tt?(Tt.count+=1,cn&&(!Tt.last_observed_at||cn>Tt.last_observed_at)&&(Tt.last_observed_at=cn,Tt.last_observed_at_fmt=vm(cn),Tt.assertion=ue)):G.set(Ct,{span_run_id:Lt,span_id:Re,writer_run_id:Ke,count:1,last_observed_at:cn,last_observed_at_fmt:vm(cn),assertion:ue})}return Array.from(G.values()).sort((ue,Me)=>String(Me.last_observed_at||"").localeCompare(String(ue.last_observed_at||"")))},[Bi]),go=_.useMemo(()=>{const G=new Map;for(const ue of Bi){if(!ue||typeof ue!="object")continue;const Me=ue.provenance&&typeof ue.provenance=="object"&&!Array.isArray(ue.provenance)?ue.provenance:null,Re=Me&&typeof Me.span_id=="string"?Me.span_id.trim():"",Ke=Me&&typeof Me.writer_run_id=="string"?Me.writer_run_id.trim():"";if(!Ke||Re)continue;const dt=G.get(Ke),Lt=typeof ue.observed_at=="string"?ue.observed_at.trim():"";dt?(dt.count+=1,Lt&&(!dt.last_observed_at||Lt>dt.last_observed_at)&&(dt.last_observed_at=Lt,dt.last_observed_at_fmt=vm(Lt),dt.assertion=ue)):G.set(Ke,{run_id:Ke,count:1,last_observed_at:Lt,last_observed_at_fmt:vm(Lt),assertion:ue})}return Array.from(G.values()).sort((ue,Me)=>String(Me.last_observed_at||"").localeCompare(String(ue.last_observed_at||"")))},[Bi]),Ps=_.useCallback(G=>{const ue=String(G.run_id||"").trim(),Me=typeof G.span_id=="string"?String(G.span_id).trim():"";if(ue){if(x){try{x({run_id:ue,span_id:Me||void 0,assertion:G.assertion})}catch{}return}if(w&&Me)try{w({run_id:ue,span_id:Me,assertion:G.assertion})}catch{}}},[w,x]),Ds=_.useCallback(async G=>{var Me;const ue=String(G??"");if(ue){try{if(typeof((Me=navigator.clipboard)==null?void 0:Me.writeText)=="function"){await navigator.clipboard.writeText(ue);return}}catch{}try{const Re=document.createElement("textarea");Re.value=ue,Re.style.position="fixed",Re.style.left="-9999px",document.body.appendChild(Re),Re.select(),document.execCommand("copy"),document.body.removeChild(Re)}catch{}}},[]),gr=_.useCallback(()=>{const G=k.current;if(!(!G||typeof G.fitView!="function")){if(gs&&typeof G.getNode=="function"){const ue=G.getNode(gs);if(ue){G.fitView({nodes:[ue],padding:.55,duration:350});return}}G.fitView({padding:.2,duration:350})}},[gs]),yo=_.useCallback(G=>{const ue=G.kind,Me=Math.trunc(G.seed);ut(!1),Ve.current=null,ye.current=null,bt(ue),at(Me);const Re=Sd(wt,{kind:ue,seed:Me});$n(Re),ue==="force"&&(G.autoPlay??!0)&&wt.nodes.length>0&&wt.nodes.length<=320&&(Ve.current=Q_(wt,{seed:Me,positions:Re,...ym(Se)}),ut(!0))},[wt,Se]),Wr=_.useCallback(()=>{if(ot==="force"){if(Nt){ut(!1);return}Ve.current=Q_(wt,{seed:Ue,positions:Cn.current,...ym(Se)}),ut(!0)}},[wt,ot,Nt,Ue,Se]);_.useEffect(()=>()=>{typeof window>"u"||typeof window.cancelAnimationFrame=="function"&&Rt.current&&window.cancelAnimationFrame(Rt.current)},[]);const Ar=_.useCallback(()=>{const G=k.current;if(!G||typeof G.getViewport!="function"||!Rn.length)return null;const ue=Te.current;if(!ue)return null;const Me=ue.getBoundingClientRect();if(!Number.isFinite(Me.width)||!Number.isFinite(Me.height)||Me.width<64||Me.height<64)return null;const Re=G.getViewport(),Ke=typeof(Re==null?void 0:Re.zoom)=="number"&&Number.isFinite(Re.zoom)?Re.zoom:null,dt=typeof(Re==null?void 0:Re.x)=="number"&&Number.isFinite(Re.x)?Re.x:null,Lt=typeof(Re==null?void 0:Re.y)=="number"&&Number.isFinite(Re.y)?Re.y:null;if(Ke===null||dt===null||Lt===null||Ke<=0)return null;const Ct=140,Tt=Math.min(Rn.length,180),cn=Cn.current;let wn=0,Vs=0;for(const Et of Rn){const _n=cn[Et];if(!_n||!Number.isFinite(_n.x)||!Number.isFinite(_n.y))continue;Vs+=1;const os=[{x:_n.x,y:_n.y},{x:_n.x+90,y:_n.y+24}];for(const zn of os){const Tr=zn.x*Ke+dt,yr=zn.y*Ke+Lt;if(Tr>-Ct&&Tr<Me.width+Ct&&yr>-Ct&&yr<Me.height+Ct)return!1}if(wn++,wn>=Tt)break}return Vs?!0:null},[Rn]),qr=_.useCallback(G=>{typeof window>"u"||typeof window.requestAnimationFrame!="function"||Rt.current||(Rt.current=window.requestAnimationFrame(()=>{Rt.current=0;const ue=Ar();if(ue===null){if(Be.current>=12)return;Be.current+=1,window.setTimeout(()=>qr(`${G}:probe`),120);return}if(ue!==!0){Be.current=0,Ge.current=0;return}Be.current=0;const Me=k.current;if(Me&&typeof Me.fitView=="function")try{Me.fitView({padding:.2,duration:0})}catch{try{Me.fitView({padding:.2})}catch{}}if(Ge.current+=1,Ge.current>=4&&et.current<1){Ge.current=0,et.current+=1,ie(Re=>Re+1);return}Ge.current<8&&window.setTimeout(()=>qr(`${G}:retry`),220)}))},[Ar]);_.useEffect(()=>{Ge.current=0,et.current=0,Be.current=0,qr("mount")},[S,qr]),_.useEffect(()=>{qr("graph change")},[tr,qr]),_.useEffect(()=>{const G=Te.current;if(!G||typeof window>"u"||typeof ResizeObserver!="function")return;const ue=new ResizeObserver(()=>qr("resize"));return ue.observe(G),()=>ue.disconnect()},[qr]);const ic=_.useCallback(()=>{const G=new Date().toISOString(),ue={};for(const Lt of Rn){const Ct=Cn.current[Lt];Ct&&typeof Ct.x=="number"&&typeof Ct.y=="number"&&(ue[Lt]={x:Ct.x,y:Ct.y})}const Me=k.current,Re=Me&&typeof Me.toObject=="function"?Me.toObject():null,Ke=Re&&Re.viewport?Re.viewport:Me&&typeof Me.getViewport=="function"?Me.getViewport():null,dt=z1(Ke,{minZoom:Ww,maxZoom:qw,maxAbsTranslate:W1})??void 0;GF($e,{version:1,kind:ot,seed:Ue,positions:ue,viewport:dt,saved_at:G}),Qt(!0),rs(G),ut(!1)},[$e,ot,Ue,Rn]),Hr=_.useCallback(()=>{const G=ik($e);if(!G)return;ut(!1),Ve.current=null,bt(G.kind),at(G.seed),Qt(!0),rs(G.saved_at||""),ye.current=G.viewport||null,Ie.current=!G.viewport;const ue=Sd(wt,{kind:G.kind,seed:G.seed});if($n(Qa(G.positions,ue)),G.viewport){const Me=k.current;if(Me&&typeof Me.setViewport=="function"){try{Me.setViewport(G.viewport,{duration:0})}catch{try{Me.setViewport(G.viewport)}catch{}}ye.current=null}}},[Qa,wt,$e]),uu=_.useCallback(()=>{KF($e),Qt(!1),rs("")},[$e]),ki=_.useCallback(G=>{if(!Array.isArray(G)||G.length===0)return;let ue=!1;$n(Me=>{let Re=Me,Ke=!1;for(const dt of G){const Lt=dt&&typeof dt=="object"&&"id"in dt&&typeof dt.id=="string"?String(dt.id):"",Ct=(dt==null?void 0:dt.type)==="position"?dt==null?void 0:dt.position:null;Lt&&Ct&&typeof Ct.x=="number"&&typeof Ct.y=="number"&&(Ke||(Re={...Me},Ke=!0),Re[Lt]={x:Ct.x,y:Ct.y},dt!=null&&dt.dragging&&(ue=!0))}return Ke?Re:Me}),ue&&Nt&&ut(!1)},[Nt]),Vo=_.useMemo(()=>{const G=new Map;for(const ue of wt.edges)G.set(ue.id,ue);return G},[wt.edges]),sl=_.useMemo(()=>{var Re;if(!ws)return[];const G=ws.nodeIds||[],ue=ws.edgeIds||[],Me=[];for(let Ke=0;Ke<Math.min(G.length-1,ue.length);Ke++){const dt=G[Ke],Lt=G[Ke+1],Ct=ue[Ke],Tt=Vo.get(Ct),cn=String(((Re=Tt==null?void 0:Tt.data)==null?void 0:Re.predicateSummary)||(Tt==null?void 0:Tt.label)||"").trim(),wn=Tt&&Tt.source===dt&&Tt.target===Lt?"forward":Tt&&Tt.source===Lt&&Tt.target===dt?"reverse":"unknown";Me.push({from:dt,to:Lt,edgeId:Ct,predicate:cn,dir:wn})}return Me},[Vo,ws]),wo=_.useCallback(async()=>{if(p){q(""),T(""),D(!0);try{const G=JF(ht),ue=Ey(kt,{allowZero:!0,allowNegativeOne:!0}),Me=Ey(rt,{allowZero:!0}),Re=await p({scope:es,owner_id:void 0,recall_level:Ee,query_text:se||void 0,subject:je||void 0,predicate:ze||void 0,object:Ze||void 0,min_score:G,limit:ue,max_input_tokens:Me,model:dn||void 0});E(Re),F("live query"),$==="replace"&&y&&Re&&Array.isArray(Re.items)&&y(Re.items,{kind:"live query",result:Re})}catch(G){const ue=G instanceof Error?G.message:String(G);q(ue||"Query failed")}finally{D(!1)}}},[kt,rt,ht,dn,Ze,y,p,ze,$,se,Ee,es,je]),oi=_.useCallback(async()=>{if(!p)return;const G=String(an||"").trim(),ue=String(Wn||"").trim();if(!G||!ue)return;const Me=Math.max(200,Ey(kt)??80),Re=60;T(""),q(""),Z(!0);try{const Ke=[],dt=new Set,Lt=Et=>{if(!Et||typeof Et!="object"||typeof Et.subject!="string"||typeof Et.predicate!="string"||typeof Et.object!="string")return;const _n=`${Et.subject}|${Et.predicate}|${Et.object}|${String(Et.observed_at||"")}|${String(Et.scope||"")}|${String(Et.owner_id||"")}`;dt.has(_n)||(dt.add(_n),Ke.push(Et))};for(const Et of en)Lt(Et);const Ct=V,Tt=new Set,cn=[G],wn=new Set([G]),Vs=async Et=>{const _n=await p({scope:es,recall_level:Ee,min_score:0,limit:Me,subject:Et,query_text:void 0,max_input_tokens:0,model:void 0});if(_n&&Array.isArray(_n.items)){for(const os of _n.items)if(Lt(os),typeof os.subject=="string"&&os.subject.trim()===Et&&typeof os.object=="string"){const zn=os.object.trim();zn&&!wn.has(zn)&&(wn.add(zn),cn.push(zn))}}if(!Ct){const os=await p({scope:es,recall_level:Ee,min_score:0,limit:Me,object:Et,query_text:void 0,max_input_tokens:0,model:void 0});if(os&&Array.isArray(os.items)){for(const zn of os.items)if(Lt(zn),typeof zn.object=="string"&&zn.object.trim()===Et&&typeof zn.subject=="string"){const Tr=zn.subject.trim();Tr&&!wn.has(Tr)&&(wn.add(Tr),cn.push(Tr))}}}};for(;cn.length&&Tt.size<Re&&!wn.has(ue);){const Et=cn.shift();!Et||Tt.has(Et)||(Tt.add(Et),await Vs(Et))}E({ok:!0,count:Ke.length,items:Ke,active_memory_text:Yt,raw:{expanded_for_path:!0,expanded_nodes:Tt.size,discovered_nodes:wn.size,merged:Ke.length,directed:Ct}}),F("expanded neighborhood"),$==="replace"&&y&&y(Ke,{kind:"expanded neighborhood",result:{ok:!0,count:Ke.length,items:Ke,active_memory_text:Yt,raw:{expanded_for_path:!0,expanded_nodes:Tt.size,discovered_nodes:wn.size,merged:Ke.length,directed:Ct}}})}catch(Ke){const dt=Ke instanceof Error?Ke.message:String(Ke);T(dt||"Expand neighborhood failed")}finally{Z(!1)}},[V,Yt,en,kt,y,p,Wn,an,$,Ee,es]),wa=_.useCallback(()=>{E(null),F(null),q(""),D(!1),T(""),Z(!1),is(""),Fn(""),si(""),ri("")},[]),Ui="Search KG",sr=wt.nodes.length,tf=wt.edges.length,ai=_r.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:ot,onChange:G=>bt(Hw(G.target.value,ot)),disabled:!Rn.length,children:[s.jsx("option",{value:"grid",children:"grid (deterministic)"}),s.jsx("option",{value:"radial",children:"radial (bfs)"}),s.jsx("option",{value:"circle",children:"circle"}),s.jsx("option",{value:"force",children:"force (simulation)"})]}),ot==="force"?s.jsxs("label",{className:"amx-graphbar-spread",children:[s.jsx("span",{className:"amx-graphbar-title",children:"spread"}),s.jsx("input",{type:"range",min:"0.7",max:"2.2",step:"0.1",value:Se,onChange:G=>me(U1(Number(G.target.value),.7,2.2,1))}),s.jsxs("span",{className:"amx-small",children:[Se.toFixed(1),"×"]})]}):null,s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>yo({kind:ot,seed:Ue}),disabled:!Rn.length,children:"Apply"}),s.jsx("button",{type:"button",className:"amx-btn",onClick:Wr,disabled:!Rn.length||ot!=="force",children:Nt?"Pause simulation":"Play simulation"})]})}),s.jsxs("div",{className:"amx-graph","aria-label":"Knowledge graph",ref:Te,children:[s.jsx(Xv,{children:s.jsxs(I1,{nodes:ga,edges:tl,defaultViewport:{x:0,y:0,zoom:1},minZoom:Ww,maxZoom:qw,onInit:G=>{k.current=G;const ue=ye.current;if(ue&&typeof G.setViewport=="function")try{G.setViewport(ue,{duration:0})}catch{try{G.setViewport(ue)}catch{}}if(Ie.current&&typeof G.fitView=="function")try{G.fitView({padding:.2,duration:0})}catch{try{G.fitView({padding:.2})}catch{}}ye.current=null,Ie.current=!1,qr("init")},nodesDraggable:!0,nodesConnectable:!1,elementsSelectable:!0,onNodesChange:ki,onNodeClick:(G,ue)=>{ri(""),si(ue.id)},onEdgeClick:(G,ue)=>{si(""),ri(ue.id)},onPaneClick:()=>{si(""),ri("")},children:[s.jsx(CF,{className:"amx-flow-controls",children:s.jsx(Rd,{type:"button",className:`amx-control-legend ${ge?"amx-control-legend-active":""}`,onClick:()=>pe(G=>!G),title:ge?"Hide node color legend":"Show node color legend","aria-label":ge?"Hide node color legend":"Show node color legend",children:s.jsx(HF,{})})}),s.jsx(Xm,{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:()=>ve(G=>!G),title:ae?"Hide minimap preview":"Show minimap preview","aria-label":ae?"Hide minimap preview":"Show minimap preview",children:ae?"minimap on":"minimap off"})})}),ae?s.jsx(xF,{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:fe?120:160,height:fe?80:110,marginBottom:56},nodeColor:G=>{var ue;return wm((ue=G.data)==null?void 0:ue.kind).minimap}}):null,ge?s.jsxs(Xm,{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:G,label:ue})=>s.jsx("span",{className:"amx-legend-item",style:{borderColor:wm(G).stroke},children:ue},G))})]}):null,s.jsx(LF,{gap:20,size:1,color:"rgba(255,255,255,0.06)"})]})},ct),s.jsxs("details",{className:"amx-panel amx-controls",children:[s.jsxs("summary",{children:[s.jsx("span",{className:"amx-controls-title",children:Ui}),s.jsxs("span",{className:"amx-small",children:[ai," assertions · ",sr," nodes · ",tf," edges"]})]}),s.jsxs("div",{className:"amx-toolbar",style:{marginTop:10},children:[s.jsxs("div",{className:"amx-toolbar-grid",children:[s.jsxs("label",{children:["search / highlight",s.jsx("input",{value:P,onChange:G=>L(G.target.value),placeholder:"filter nodes by id/label"})]}),s.jsxs("label",{children:["group edges",s.jsxs("select",{value:String(te),onChange:G=>X(G.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(W),onChange:G=>Y(G.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(V),onChange:G=>ne(G.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:ot,onChange:G=>bt(Hw(G.target.value,ot)),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:Ue,onChange:G=>at(Math.trunc(Number(G.target.value||0)||0))})]})]}),s.jsxs("div",{className:"amx-actions",style:{marginTop:10},children:[s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>yo({kind:ot,seed:Ue}),disabled:!Rn.length,children:"Apply layout"}),ot==="force"?s.jsx("button",{type:"button",className:"amx-btn",onClick:Wr,disabled:!Rn.length,children:Nt?"Pause simulation":"Play simulation"}):null,s.jsx("button",{type:"button",className:"amx-btn",onClick:ic,disabled:!Rn.length,children:"Save layout"}),Nn?s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"amx-btn",onClick:Hr,children:"Load saved"}),s.jsx("button",{type:"button",className:"amx-btn",onClick:uu,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.",Nn?s.jsxs("span",{children:[" ","(saved",Un?`: ${Un}`:"",")"]}):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:an,onChange:G=>is(G.target.value),children:[s.jsx("option",{value:"",children:"(none)"}),Rn.map(G=>s.jsx("option",{value:G,children:(()=>{const ue=bi.get(G)||G;return ue===G?ue:`${ue} (${G})`})()},G))]})]}),s.jsxs("label",{children:["path end",s.jsxs("select",{value:Wn,onChange:G=>Fn(G.target.value),children:[s.jsx("option",{value:"",children:"(none)"}),Rn.map(G=>s.jsx("option",{value:G,children:(()=>{const ue=bi.get(G)||G;return ue===G?ue:`${ue} (${G})`})()},G))]})]})]}),ws?s.jsx("div",{className:"amx-small",style:{marginTop:10},children:sl.map((G,ue)=>{const Me=bi.get(G.from)||G.from,Re=bi.get(G.to)||G.to,Ke=G.dir==="reverse"?" ← ":" → ",dt=G.predicate?` (${G.predicate})`:"";return s.jsxs("div",{children:[ue===0?s.jsx("span",{children:Me}):null,Ke,s.jsxs("span",{children:[Re,dt]})]},`${G.edgeId}:${ue}`)})}):an&&Wn?s.jsxs("div",{className:"amx-small",style:{marginTop:10,opacity:.9},children:["No path found in the current subgraph (",(Ms==null?void 0:Ms.assertions)??ai," assertions · ",(Ms==null?void 0:Ms.nodes)??wt.nodes.length," nodes ·"," ",(Ms==null?void 0:Ms.edges)??wt.edges.length," edges). Start reaches ",(Ms==null?void 0:Ms.reachableFromStart)??0," nodes.",p?s.jsx("div",{style:{marginTop:10},children:s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>void oi(),disabled:I,children:I?"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:se,onChange:G=>ce(G.target.value),placeholder:"e.g. emotion chip"})]}),s.jsxs("label",{children:["subject (exact)",s.jsx("input",{value:je,onChange:G=>Ae(G.target.value),placeholder:"e.g. ex:person-data"})]}),s.jsxs("label",{children:["predicate (exact)",s.jsx("input",{value:ze,onChange:G=>Fe(G.target.value),placeholder:"e.g. schema:about"})]}),s.jsxs("label",{children:["object (exact)",s.jsx("input",{value:Ze,onChange:G=>lt(G.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:G=>_t(G.target.value),placeholder:"(auto)"})]}),s.jsxs("label",{children:["limit",s.jsx("input",{type:"number",min:"-1",step:"1",value:kt,onChange:G=>At(G.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:es,onChange:G=>he(rk(G.target.value,es)),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:Ee,onChange:G=>mt(G.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:rt,onChange:G=>zt(G.target.value),placeholder:"(auto)"})]}),s.jsxs("label",{children:["model (budgeting)",s.jsx("input",{value:dn,onChange:G=>on(G.target.value),placeholder:"qwen/qwen3-next-80b"})]})]})]}),s.jsxs("div",{className:"amx-actions",children:[s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>void wo(),disabled:!p||M,children:M?"Querying…":"Query store"}),s.jsx("button",{type:"button",className:"amx-btn",onClick:wa,disabled:!A&&!H&&!M,children:"Reset to step output"}),A?s.jsxs("span",{className:"amx-small",children:["showing: ",z||"live query"]}):s.jsx("span",{className:"amx-small",children:"showing: step output"}),H?s.jsx("span",{className:"amx-small",style:{color:"var(--error, rgba(255, 80, 80, 0.95))"},children:H}):null,R?s.jsx("span",{className:"amx-small",style:{color:"var(--error, rgba(255, 80, 80, 0.95))"},children:R}):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 G=YF(Cr);return G?s.jsx("div",{className:"amx-small",style:{marginBottom:8,opacity:.9},children:G}):null})(),(()=>{const G=Ns;if(!G)return null;const ue=typeof G=="string"?G:Array.isArray(G)?G.map(Me=>String(Me)).join(" · "):JSON.stringify(G);return!ue||!ue.trim()?null:s.jsx("div",{className:"amx-small",style:{marginBottom:8,color:"var(--warning, rgba(255, 180, 90, 0.95))"},children:ue})})(),s.jsx("div",{className:"amx-small",style:{marginBottom:8,opacity:.9},children:(()=>{const G=(A==null?void 0:A.packets_version)??Pe,ue=(A==null?void 0:A.packed_count)??Ut,Me=(A==null?void 0:A.dropped)??St,Re=(A==null?void 0:A.estimated_tokens)??Mn,Ke=[];return typeof G=="number"&&Ke.push(`packets_v${G}`),typeof ue=="number"&&Ke.push(`packed=${ue}`),typeof Me=="number"&&Ke.push(`dropped=${Me}`),typeof Re=="number"&&Ke.push(`est_tokens=${Re}`),Ke.length?Ke.join(" · "):"No packetization stats (set max_input_tokens > 0)."})()}),s.jsx("div",{className:"amx-active-memory",children:ZF(Yt||"(empty)",P)}),(()=>{const G=A!=null&&A.packets&&Array.isArray(A.packets)?A.packets:ts;return!Array.isArray(G)||G.length===0?null:s.jsxs("div",{style:{marginTop:10},children:[s.jsxs("button",{type:"button",className:"amx-btn",onClick:()=>Sn(ue=>!ue),children:[zi?"Hide":"Show"," packets (",G.length,")"]}),zi?s.jsx("div",{className:"amx-list",style:{marginTop:10},children:G.slice(0,120).map((ue,Me)=>{const Re=ue&&typeof ue=="object"&&!Array.isArray(ue)?ue:null,Ke=Re&&typeof Re.statement=="string"?Re.statement:typeof ue=="string"?ue:"",dt=Re&&(typeof Re.retrieval_score=="number"||typeof Re.retrieval_score=="string")?Re.retrieval_score:null,Lt=Re&&typeof Re.observed_at=="string"?Re.observed_at:null;return s.jsxs("div",{className:"amx-item",children:[s.jsx("div",{className:"amx-mono",children:Ke||"(packet)"}),Lt||dt!==null?s.jsxs("div",{className:"amx-small",children:[Lt?`[${Lt}]`:null,Lt&&dt!==null?" ":null,dt!==null?`score:${dt}`:null]}):null]},Me)})}):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."}),gs?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:bi.get(gs)||gs}),s.jsxs("div",{className:"amx-small",children:["kind=",nr.get(gs)||"entity"," · id=",gs]})]}),s.jsxs("div",{className:"amx-actions",children:[s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>void Ds(gs),children:"Copy id"}),s.jsx("button",{type:"button",className:"amx-btn",onClick:gr,children:"Focus"})]})]}):Er&&Er.source&&Er.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:[Er.source," —",String(Er.label||((qn=Er.data)==null?void 0:qn.predicateSummary)||"").trim()||"?","→ ",Er.target]}),s.jsxs("div",{className:"amx-small",children:["edge_id=",Er.id]})]}),s.jsxs("div",{className:"amx-actions",children:[s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>void Ds(Er.id),children:"Copy id"}),s.jsx("button",{type:"button",className:"amx-btn",onClick:gr,children:"Fit"})]})]}):s.jsx("div",{className:"amx-small",style:{marginBottom:10,opacity:.9},children:"(no selection)"}),s.jsx("div",{className:"amx-list",children:Bi.slice(0,80).map((G,ue)=>{const Me=String(G.subject||"").trim(),Re=String(G.predicate||"").trim(),Ke=String(G.object||"").trim(),dt=bi.get(Me)||Me,Lt=bi.get(Ke)||Ke,Ct=nr.get(Me)||"entity",Tt=nr.get(Ke)||"entity",cn=wm(Ct),wn=wm(Tt),Vs=vm(G.observed_at),Et=XF(G),_n=G.provenance&&typeof G.provenance=="object"&&!Array.isArray(G.provenance)?G.provenance:null,os=_n&&typeof _n.span_id=="string"?_n.span_id.trim():"",zn=_n&&typeof _n.writer_run_id=="string"?_n.writer_run_id.trim():"",Tr=typeof G.owner_id=="string"?G.owner_id.trim():"",yr=zn||Tr,Wi=!!((x||w)&&os&&yr),rl=!!(x&&zn&&!os),qi=Wi||rl;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:cn.stroke,background:cn.bg},title:Me,onClick:()=>{Me&&(ri(""),si(Me))},children:dt||Me||"(subject)"}),s.jsx("span",{className:"amx-arrow",children:"—"}),s.jsx("span",{className:"amx-predicate",title:Re,children:q1(Re)||"(predicate)"}),s.jsx("span",{className:"amx-arrow",children:"→"}),s.jsx("button",{type:"button",className:"amx-term",style:{borderColor:wn.stroke,background:wn.bg},title:Ke,onClick:()=>{Ke&&(ri(""),si(Ke))},children:Lt||Ke||"(object)"})]}),s.jsxs("div",{className:"amx-triple-meta",children:[Vs?s.jsxs("span",{className:"amx-small",title:String(G.observed_at||""),children:["[",Vs,"]"]}):null,Et?s.jsx("span",{className:"amx-small",children:Et}):null]}),os||zn?s.jsxs("div",{className:"amx-triple-actions",children:[os?s.jsxs("span",{className:"amx-small",children:["span:",os]}):null,zn?s.jsxs("span",{className:"amx-small",children:["run:",zn]}):null,qi?s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>{if(Wi&&os&&yr){Ps({run_id:yr,span_id:os,assertion:G});return}rl&&zn&&Ps({run_id:zn,assertion:G})},children:"Open transcript"}):null]}):null]},ue)})})]}),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)."}),ya.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:ya.slice(0,60).map(G=>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:",G.span_id]}),s.jsxs("div",{className:"amx-small",children:["run_id=",G.span_run_id," · assertions=",G.count,G.last_observed_at_fmt?` · last=[${G.last_observed_at_fmt}]`:""]})]}),w||x?s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>Ps({run_id:G.span_run_id,span_id:G.span_id,assertion:G.assertion}),children:"Open transcript"}):null]},`${G.span_run_id}|${G.span_id}`))})]}):null,x&&go.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:go.slice(0,40).map(G=>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:",G.run_id]}),s.jsxs("div",{className:"amx-small",children:["assertions=",G.count,G.last_observed_at_fmt?` · last=[${G.last_observed_at_fmt}]`:""]})]}),s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>Ps({run_id:G.run_id,assertion:G.assertion}),children:"Open transcript"})]},G.run_id))})]}):null,!ya.length&&!(x&&go.length)?s.jsx("div",{className:"amx-small",children:"(no provenance)"}):null]})]})]})})}function Kl({open:e,title:t,children:n,actions:r,variant:i="default",onClose:a}){const u=_.useId();if(_.useEffect(()=>{if(!e)return;const d=m=>{m.key==="Escape"&&a()};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[e,a]),!e)return null;const c=i==="fullscreen";return s.jsx("div",{className:`modal_backdrop${c?" fullscreen":""}`,onMouseDown:d=>{d.target===d.currentTarget&&a()},children:s.jsxs("div",{className:`modal_panel${c?" fullscreen":""}`,role:"dialog","aria-modal":"true","aria-labelledby":u,children:[s.jsxs("div",{className:"modal_header",children:[s.jsx("div",{className:"modal_title",id:u,children:t}),s.jsx("button",{className:"btn",onClick:a,children:"Close"})]}),s.jsx("div",{className:"modal_body",children:n}),r?s.jsx("div",{className:"modal_footer",children:r}):null]})})}function Ty(e,t="session"){const n=String(e||"").trim().toLowerCase();return n==="run"||n==="session"||n==="global"||n==="all"?n:t}function ql(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 Hc(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"),i=String(t.getUTCDate()).padStart(2,"0"),a=String(t.getUTCHours()).padStart(2,"0"),u=String(t.getUTCMinutes()).padStart(2,"0");return`${n}/${r}/${i} ${a}:${u}`}function n8(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=ql(t);return n!==null?Hc(n):t}function Qv(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,`
|
|
153
|
+
`).replace(/\\n/g,`
|
|
154
|
+
`).replace(/\\t/g," "):""}function H1(e){return String(e??"").replace(/[*_`~]/g,"")}function ep(e,t){const n=!!(t!=null&&t.strip_punct),r=Qv(e);let i=H1(r).replace(/\s+/g," ").trim().toLowerCase();return n&&(i=i.replace(/[^\p{L}\p{N}\s]+/gu,"").replace(/\s+/g," ").trim()),i}function tp(e,t){const n=String(t??"").trim();if(!n)return!1;const r=ep(n,{strip_punct:!1});if(!r)return!1;if(ep(String(e??""),{strip_punct:!1}).includes(r))return!0;const a=ep(n,{strip_punct:!0});return a?ep(String(e??""),{strip_punct:!0}).includes(a):!1}function ok(e){const t=Qv(e).trim();if(!t)return[];const n=[],r=u=>{const c=String(u??"").replace(/\s+/g," ").trim();c&&(c.length<6||n.includes(c)||n.push(c))},i=t.search(/[`*_~]/);if(i>0){const u=t.slice(0,i);u.replace(/\s+/g," ").trim().length>=10&&r(u)}const a=[/`([^`]+)`/g,/\*\*([^*]+)\*\*/g,/__([^_]+)__/g,/\*([^*]+)\*/g,/_([^_]+)_/g];for(const u of a){let c;for(;(c=u.exec(t))!==null;){const d=String(c[1]??"").trim();d&&r(d)}}return r(H1(t)),n}function s8(e){const t=String(e??"").replace(/\r\n/g,`
|
|
155
|
+
`).replace(/\r/g,`
|
|
156
|
+
`);if(!t)return null;const n=t.split(`
|
|
157
|
+
`);let r;const i=[],a=[];let u=null,c=[],d=!1;const m=()=>{if(!u)return;const y=c.join(`
|
|
158
|
+
`).trim();y&&a.push({role:u,lines:[y]}),u=null,c=[]};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 x=y.match(/^\s*(USER|ASSISTANT|SYSTEM)\s*:\s*(.*)$/i);if(x){d=!0,m();const k=String(x[1]||"").trim().toLowerCase();u=k==="user"?"user":k==="assistant"?"assistant":"system";const b=String(x[2]??"");c=b?[b]:[];continue}u?c.push(y):i.push(y)}if(m(),!d||!a.length)return null;const h=i.join(`
|
|
159
|
+
`).trim(),p={messages:[]};r&&(p.created_at=r),h&&p.messages.push({role:"system",content:h});for(const y of a)p.messages.push({role:y.role,content:y.lines.join(`
|
|
160
|
+
`)});return p.messages.length?p:null}function ak(e,t){const n=String(e||""),r=String(t||"");return r>n?r:n}function lk(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(),i=String((e==null?void 0:e.observed_at)||"").trim(),a=String((e==null?void 0:e.scope)||"").trim(),u=String((e==null?void 0:e.owner_id)||"").trim();return`${t}|${n}|${r}|${i}|${a}|${u}`}function r8(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(),i=String((e==null?void 0:e.object)||"").trim(),a=String((e==null?void 0:e.scope)||"").trim(),u=String((e==null?void 0:e.owner_id)||"").trim(),c=[];a&&c.push(`scope=${a}`),u&&c.push(`owner=${u}`);const d=c.length?` (${c.join(", ")})`:"";return`${t?`[${t}] `:""}${n} --${r}--> ${i}${d}`}function i8({gateway:e,selected_run_id:t,selected_session_id:n}){const[r,i]=_.useState(String(t||"").trim()),[a,u]=_.useState(String(n||"").trim()),[c,d]=_.useState("all"),m=c==="all",[h,p]=_.useState(!0),[y,w]=_.useState(750),[x,k]=_.useState(5e3),[b,S]=_.useState([]),[$,A]=_.useState(void 0),[E,z]=_.useState(""),[F,M]=_.useState(!1),[D,H]=_.useState([]),[q,I]=_.useState(!1),[Z,R]=_.useState(!1),[T,P]=_.useState(""),[L,te]=_.useState(""),[X,V]=_.useState(""),[ne,W]=_.useState(""),[Y,K]=_.useState("artifact"),[fe,ae]=_.useState(null),[ve,ge]=_.useState(""),[pe,$e]=_.useState(null),De=_.useRef(!1),ot=_.useMemo(()=>{const he=pe,Ee=he!=null&&he.attributes&&typeof he.attributes=="object"&&!Array.isArray(he.attributes)?he.attributes:null;return(Ee&&typeof Ee.evidence_quote=="string"?String(Ee.evidence_quote):"").trim()},[pe]),bt=_.useMemo(()=>{const he=fe,Ee=he&&typeof he=="object"&&!Array.isArray(he)?he:null,mt=Ee&&typeof Ee.note=="string"?String(Ee.note):"";return Qv(mt).trim()},[fe]),Ue=_.useMemo(()=>{const he=fe&&typeof fe=="object"&&!Array.isArray(fe)?fe:null,Ee=he&&Array.isArray(he.messages)?he.messages:null;return Array.isArray(Ee)?Ee:null},[fe]),at=_.useMemo(()=>{const he=bt,Ee=ot;return!he||!Ee?!1:tp(he,Ee)},[ot,bt]),Nt=_.useMemo(()=>{const he=Ue,Ee=ot;if(!he||!Ee)return[];const mt=[];for(let se=0;se<Math.min(he.length,500);se++){const ce=he[se],je=(ce==null?void 0:ce.content)==null?"":String(ce.content);tp(je,Ee)&&mt.push(se)}return mt},[ot,Ue]),ut=_.useMemo(()=>new Set(Nt),[Nt]),Se=Nt.length?Nt[0]:null,me=_.useCallback(he=>{const Ee=document.getElementById(`source_msg_${he}`);Ee&&typeof Ee.scrollIntoView=="function"&&Ee.scrollIntoView({block:"center",behavior:"smooth"})},[]),Ve=_.useCallback(()=>{const he=document.getElementById("source_note_hit_0")||document.getElementById("source_note_msg_hit_0");he&&typeof he.scrollIntoView=="function"&&he.scrollIntoView({block:"center",behavior:"smooth"})},[]);_.useEffect(()=>{if(q&&!(Z||T)&&!De.current){if(Se!==null){De.current=!0,window.setTimeout(()=>me(Se),0);return}if(at){De.current=!0,window.setTimeout(()=>Ve(),0);return}}},[me,Ve,T,Se,Z,at,q]);const ye=_.useRef(new Set),Ie=_.useRef(""),ct=_.useRef(null),ie=_.useRef(null);_.useEffect(()=>{i(String(t||"").trim())},[t]),_.useEffect(()=>{u(String(n||"").trim())},[n]);const Te=_.useMemo(()=>{const he=String(r||"").trim(),Ee=String(a||"").trim();return`mindmap:${c}:${he}:${Ee}`},[r,a,c]),et=_.useMemo(()=>{let he=null,Ee=null;for(const mt of b){const se=ql(mt==null?void 0:mt.observed_at);se!==null&&(he=he===null?se:Math.min(he,se),Ee=Ee===null?se:Math.max(Ee,se))}return{min_ms:he,max_ms:Ee}},[b]),Ge=1e3,Be=_.useMemo(()=>{const he=et.min_ms,Ee=et.max_ms;if(typeof he!="number"||typeof Ee!="number"||!Number.isFinite(he)||!Number.isFinite(Ee))return null;if(Ee<=he)return{min_ms:he,max_ms:he,real_max_ms:Ee};const mt=he+Math.ceil((Ee-he)/Ge)*Ge;return{min_ms:he,max_ms:mt,real_max_ms:Ee}},[et.max_ms,et.min_ms]),[Rt,Nn]=_.useState(!0),[Qt,Un]=_.useState(null);_.useEffect(()=>{Rt&&Be&&Un(Be.max_ms)},[Rt,Be]);const rs=_.useMemo(()=>{const he=typeof Qt=="number"?Qt:null;return he===null?b:b.filter(Ee=>{const mt=ql(Ee==null?void 0:Ee.observed_at);return mt===null?!0:mt<=he})},[b,Qt]),Dn=_.useCallback((he,Ee)=>{const mt=Array.isArray(he)?he:[],se=String(Ie.current||"").trim(),ce=new Set,je=[];let Ae="";for(const ze of mt){if(!ze||typeof ze!="object"||typeof ze.subject!="string"||typeof ze.predicate!="string"||typeof ze.object!="string")continue;const Fe=lk(ze);if(ce.has(Fe))continue;ce.add(Fe),je.push(ze);const Ze=String(ze.observed_at||"").trim();Ze&&(Ae=ak(Ae,Ze))}S(je),A(Ee==null?void 0:Ee.warnings),ye.current=ce,Ie.current=Ae||se},[]),$n=_.useCallback(async he=>{const Ee=Ty(he.scope,"session"),mt=String(he.subject||"").trim(),se=String(he.predicate||"").trim(),ce=String(he.object||"").trim(),je=String(he.since||"").trim(),Ae=String(he.until||"").trim(),ze=String(he.active_at||"").trim(),Fe=String(he.query_text||"").trim(),Ze=typeof he.min_score=="number"&&Number.isFinite(he.min_score)?Number(he.min_score):void 0,lt=he.order==="asc"?"asc":"desc",ht=typeof he.limit=="number"&&Number.isFinite(he.limit)?Number(he.limit):0,_t=String(r||"").trim(),kt=String(a||"").trim(),At={scope:Ee,all_owners:m,limit:ht,order:lt};mt&&(At.subject=mt),se&&(At.predicate=se),ce&&(At.object=ce),je&&(At.since=je),Ae&&(At.until=Ae),ze&&(At.active_at=ze),Fe&&(At.query_text=Fe),typeof Ze=="number"&&(At.min_score=Ze),m||(Ee==="run"?_t&&(At.run_id=_t):Ee==="session"?kt?At.session_id=kt:_t&&(At.run_id=_t):Ee==="all"&&(_t?At.run_id=_t:kt&&(At.session_id=kt)));try{const rt=await e.kg_query(At),zt=Array.isArray(rt==null?void 0:rt.items)?rt.items:[],dn=rt==null?void 0:rt.warnings;return{ok:(rt==null?void 0:rt.ok)!==!1,count:Number((rt==null?void 0:rt.count)||zt.length),items:zt,warnings:dn,raw:rt}}catch(rt){const zt=rt instanceof Error?rt.message:String(rt);if(zt.includes("Run '")&&zt.includes("not found")&&!kt&&(Ee==="session"||Ee==="all")&&_t){const on=await e.kg_query({...At,run_id:void 0,session_id:_t}),Ht=Array.isArray(on==null?void 0:on.items)?on.items:[],Ot=on==null?void 0:on.warnings;return{ok:(on==null?void 0:on.ok)!==!1,count:Number((on==null?void 0:on.count)||Ht.length),items:Ht,warnings:Ot,raw:on}}throw new Error(zt||"KG query failed")}},[m,e,r,a]),Cn=_.useCallback(async he=>{var se;const Ee=String(he.run_id||"").trim(),mt=String(he.span_id||"").trim();if(!(!Ee||!mt)){I(!0),R(!0),P(""),V(Ee),W(mt),K("artifact"),te(`source span:${mt}`),ae(null),ge(""),$e(he.assertion&&typeof he.assertion=="object"?he.assertion:null),De.current=!1;try{const ce=[Ee],je=typeof((se=he.assertion)==null?void 0:se.owner_id)=="string"?String(he.assertion.owner_id).trim():"";je&&je!==Ee&&ce.push(je);let Ae=null,ze=null;for(const Fe of ce)try{ze=await(await e.download_run_artifact_content(Fe,mt)).text(),Fe!==Ee&&V(Fe);break}catch(Ze){Ae=Ze instanceof Error?Ze.message:String(Ze)}if(ze==null)throw new Error(Ae||"Failed to load source span");ge(ze);try{const Fe=JSON.parse(ze);ae(Fe)}catch{ae(null)}}catch(ce){const je=ce instanceof Error?ce.message:String(ce);P(je||"Failed to load source span")}finally{R(!1)}}},[e]),an=_.useCallback(async he=>{const Ee=String(he.run_id||"").trim();if(!Ee)return null;try{const mt=await e.list_run_artifacts(Ee,{limit:200}),ce=(Array.isArray(mt==null?void 0:mt.items)?mt.items:[]).map(Ze=>{const lt=typeof(Ze==null?void 0:Ze.artifact_id)=="string"?String(Ze.artifact_id).trim():"",ht=Ze!=null&&Ze.tags&&typeof Ze.tags=="object"&&!Array.isArray(Ze.tags)?Ze.tags:null,_t=ht&&typeof ht.kind=="string"?String(ht.kind).trim():"";return{artifact_id:lt,kind:_t}}).filter(Ze=>!!(Ze.artifact_id&&(Ze.kind==="conversation_span"||Ze.kind==="memory_note")));if(!ce.length)return null;if(ce.length===1)return ce[0].artifact_id;const je=he.assertion,Ae=je!=null&&je.attributes&&typeof je.attributes=="object"&&!Array.isArray(je.attributes)?je.attributes:null,Fe=(Ae&&typeof Ae.evidence_quote=="string"?String(Ae.evidence_quote):"").trim();if(!Fe)return null;for(const Ze of ce.slice(0,10))try{const ht=await(await e.download_run_artifact_content(Ee,Ze.artifact_id)).text(),_t=JSON.parse(ht);if(_t&&typeof _t=="object"){const kt=typeof _t.note=="string"?String(_t.note):"";if(kt&&kt.includes(Fe))return Ze.artifact_id;const At=Array.isArray(_t.messages)?_t.messages:null;if(At){for(const rt of At.slice(0,200))if(((rt==null?void 0:rt.content)==null?"":String(rt.content)).includes(Fe))return Ze.artifact_id}}}catch{}}catch{}return null},[e]),is=_.useCallback(async he=>{const Ee=String(he.run_id||"").trim();if(Ee){I(!0),R(!0),P(""),V(Ee),W(""),K("run_input"),te(`transcript run:${Ee}`),ae(null),ge(""),$e(he.assertion&&typeof he.assertion=="object"?he.assertion:null),De.current=!1;try{const mt=await an({run_id:Ee,assertion:he.assertion});if(mt){await Cn({run_id:Ee,span_id:mt,assertion:he.assertion});return}const se=await e.get_run_input_data(Ee),ce=se&&typeof se=="object"&&!Array.isArray(se)?se.input_data:null,je={kind:"run_input_data",run_id:Ee};if(se&&typeof(se==null?void 0:se.workflow_id)=="string"&&(je.workflow_id=String(se.workflow_id)),ce&&typeof ce=="object"&&!Array.isArray(ce)){const Ae=ce.context,Fe=(Ae&&typeof Ae=="object"&&Array.isArray(Ae.messages)?Ae.messages:null)||(Array.isArray(ce.messages)?ce.messages:null);Array.isArray(Fe)&&(je.messages=Fe);const Ze=["text","prompt","task","message"];for(const lt of Ze){const ht=ce[lt];if(typeof ht=="string"&&ht.trim()){je.note=ht.trim();break}}je.input_data=ce}!je.messages&&!je.note&&(je.note=JSON.stringify(ce??se??{},null,2));try{const Ae=await e.get_run(Ee),ze=Ae&&typeof(Ae==null?void 0:Ae.created_at)=="string"?String(Ae.created_at):"";ze&&(je.created_at=ze)}catch{}ae(je),ge(JSON.stringify(se,null,2))}catch(mt){const se=mt instanceof Error?mt.message:String(mt);P(se||"Failed to load run input transcript")}finally{R(!1)}}},[e,Cn,an]),Wn=_.useCallback(async()=>{z(""),M(!0);try{const he=c==="all"?"all":c,Ee=await $n({scope:he,limit:0,order:"desc"});Dn(Ee.items||[],{warnings:Ee.warnings}),ct.current={scope:he}}catch(he){const Ee=he instanceof Error?he.message:String(he);z(Ee||"Load failed")}finally{M(!1)}},[$n,Dn,c]);_.useEffect(()=>{b.length||Wn()},[]);const Fn=_.useCallback(async he=>{const Ee=Ty(he.scope,"session");return ie.current=he,await $n({scope:Ee,subject:he.subject,predicate:he.predicate,object:he.object,query_text:he.query_text,min_score:he.min_score,since:he.since,until:he.until,active_at:he.active_at,limit:typeof he.limit=="number"?he.limit:0,order:"desc"})},[$n]),Hs=_.useCallback((he,Ee)=>{var mt;if((Ee==null?void 0:Ee.kind)==="live query"){const se=ie.current;se&&(ct.current={scope:Ty(se.scope,"session"),subject:typeof se.subject=="string"?se.subject:void 0,predicate:typeof se.predicate=="string"?se.predicate:void 0,object:typeof se.object=="string"?se.object:void 0})}Dn(he,{warnings:(mt=Ee==null?void 0:Ee.result)==null?void 0:mt.warnings})},[Dn]),es=_.useCallback(async()=>{const he=ct.current;if(!he)return;const Ee=String(Ie.current||"").trim(),mt=await $n({scope:he.scope,subject:he.subject,predicate:he.predicate,object:he.object,since:Ee||void 0,order:"asc",limit:0}),se=Array.isArray(mt.items)?mt.items:[];if(!se.length)return;const je=Date.now()+Math.max(250,Math.min(2e4,x)),Ae=ye.current,ze=[],Fe=[];let Ze=String(Ie.current||"").trim();for(const lt of se){if(!lt||typeof lt!="object"||typeof lt.subject!="string"||typeof lt.predicate!="string"||typeof lt.object!="string")continue;const ht=lk(lt);if(Ae.has(ht))continue;Ae.add(ht),ze.push(lt),Fe.push({id:ht,assertion:lt,expires_at_ms:je});const _t=String(lt.observed_at||"").trim();_t&&(Ze=ak(Ze,_t))}ze.length&&(Ie.current=Ze,S(lt=>{const ht=lt.concat(ze);return ht.sort((_t,kt)=>String((kt==null?void 0:kt.observed_at)||"").localeCompare(String((_t==null?void 0:_t.observed_at)||""))),ht}),H(lt=>{const ht=lt.concat(Fe);return ht.sort((_t,kt)=>kt.expires_at_ms-_t.expires_at_ms),ht.slice(0,30)}))},[x,$n]);return _.useEffect(()=>{if(!h)return;let he=!1,Ee=null;const mt=async()=>{if(!he){try{await es()}catch{}he||(Ee=window.setTimeout(()=>void mt(),Math.max(250,Math.min(6e4,y))))}};return mt(),()=>{he=!0,Ee!==null&&window.clearTimeout(Ee)}},[h,y,es]),_.useEffect(()=>{if(!D.length)return;const he=window.setInterval(()=>{const Ee=Date.now();H(mt=>mt.filter(se=>se.expires_at_ms>Ee))},250);return()=>window.clearInterval(he)},[D.length]),s.jsxs("div",{className:"mindmap_root",children:[s.jsxs("div",{className:"mindmap_bar",children:[s.jsx("button",{className:"btn",onClick:()=>void Wn(),disabled:F,children:F?"Loading…":"Load snapshot"}),s.jsxs("label",{className:"field_inline",children:[s.jsx("span",{className:"mono muted",children:"source"}),s.jsxs("select",{value:c,onChange:he=>{const Ee=String(he.target.value||"").trim();(Ee==="all"||Ee==="global"||Ee==="session"||Ee==="run")&&d(Ee)},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(b3,{checked:h,onChange:p}),c==="session"?s.jsxs("label",{className:"field_inline",children:[s.jsx("span",{className:"mono muted",children:"session_id"}),s.jsx("input",{className:"mono",value:a,onChange:he=>u(String(he.target.value||"")),placeholder:"(required)"})]}):null,c==="run"?s.jsxs("label",{className:"field_inline",children:[s.jsx("span",{className:"mono muted",children:"run_id"}),s.jsx("input",{className:"mono",value:r,onChange:he=>i(String(he.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:he=>w(Math.max(250,Number(he.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:x,onChange:he=>k(Math.max(250,Number(he.target.value||0)||5e3))})]})})]})]}),E?s.jsx("div",{className:"mindmap_error mono",children:E}):null,s.jsxs("div",{className:"mindmap_explorer",children:[s.jsx(t8,{title:"mindmap",resetKey:Te,queryMode:"replace",items:rs,warnings:$,onQuery:Fn,onItemsReplace:Hs,onOpenSpan:({run_id:he,span_id:Ee,assertion:mt})=>{Cn({run_id:he,span_id:Ee,assertion:mt})},onOpenTranscript:({run_id:he,span_id:Ee,assertion:mt})=>{const se=String(he||"").trim(),ce=typeof Ee=="string"?String(Ee).trim():"";se&&(ce?Cn({run_id:se,span_id:ce,assertion:mt}):is({run_id:se,assertion:mt}))}},Te),D.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:D.slice().sort((he,Ee)=>Ee.expires_at_ms-he.expires_at_ms).slice(0,12).map(he=>s.jsx("div",{className:"mindmap_recent_item mono",children:r8(he.assertion)},he.id))})]}):null,Be?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:Hc(Math.min(typeof Qt=="number"?Qt:Be.max_ms,Be.real_max_ms))}),s.jsx("input",{className:"mindmap_slider",type:"range",min:Be.min_ms,max:Be.max_ms,step:Ge,value:typeof Qt=="number"?Qt:Be.max_ms,onChange:he=>{const Ee=Number(he.target.value||0);Un(Ee),Nn(Ee>=Be.max_ms)}}),s.jsxs("div",{className:"mindmap_timeline_counts mono muted",children:[rs.length.toLocaleString(),"/",b.length.toLocaleString()]})]})}):null]}),s.jsxs(Kl,{open:q,title:L||"source",onClose:()=>{I(!1)},children:[Z?s.jsx("div",{className:"mono muted",children:"Loading…"}):null,T?s.jsx("div",{className:"mindmap_error mono",children:T}):null,!Z&&!T?s.jsxs("div",{className:"source_span",children:[(()=>{const he=pe;if(!he)return null;const Ee=String(he.subject||"").trim(),mt=String(he.predicate||"").trim(),se=String(he.object||"").trim(),ce=Hc(ql(he.observed_at)),je=he.attributes&&typeof he.attributes=="object"&&!Array.isArray(he.attributes)?he.attributes:null,Ae=je&&typeof je.evidence_quote=="string"?String(je.evidence_quote):"",ze=je&&typeof je.original_context=="string"?String(je.original_context):"";return s.jsxs("div",{className:"source_header",children:[s.jsxs("div",{className:"mono source_triple",title:`${Ee} --${mt}--> ${se}`,children:[Ee," ",s.jsxs("span",{className:"muted",children:["—",mt,"→"]})," ",se," ",ce?s.jsxs("span",{className:"muted",children:["[",ce,"]"]}):null]}),Ae?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:Ae}),ze?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:ze})]}):null]}):null]})})(),s.jsxs("div",{className:"mono muted",style:{marginBottom:10},children:["run_id=",X," · ",Y==="artifact"?`span_id=${ne}`:"source=input_data"]}),s.jsxs("div",{className:"source_actions",children:[Se!==null?s.jsx("button",{className:"btn",onClick:()=>me(Se),children:"Jump to evidence"}):null,Se===null&&at?s.jsx("button",{className:"btn",onClick:()=>Ve(),children:"Jump to evidence"}):null]}),(()=>{const he=fe,Ee=he&&typeof he=="object"&&!Array.isArray(he)?he:null,mt=Ue,se=bt,ce=Ee&&typeof Ee.created_at=="string"?String(Ee.created_at):"",je=ce?ql(ce):null,Ae=je!==null?Hc(je):ce,ze=Ee&&Ee.span&&typeof Ee.span=="object"&&!Array.isArray(Ee.span)?Ee.span:null,Fe=ze&&typeof ze.from_timestamp=="string"?String(ze.from_timestamp):"",Ze=ze&&typeof ze.to_timestamp=="string"?String(ze.to_timestamp):"",lt=Fe?ql(Fe):null,ht=Ze?ql(Ze):null,_t=lt!==null&&ht!==null?`${Hc(lt)} → ${Hc(ht)}`:"";if(se){const kt=s8(se);if(kt){const At=ot,rt=At?kt.messages.findIndex(Ht=>tp(Ht.content,At)):-1,zt=At?ok(At):[],dn=kt.created_at||ce,on=dn?n8(dn):ce?Ae:"";return s.jsx("div",{className:"source_chat",children:kt.messages.map((Ht,Ot)=>{const ts=Ht.role,Pe=!!(At&&tp(Ht.content,At)),Ut=ts==="user"?"USER":ts==="assistant"?"ASSISTANT":"SYSTEM";return s.jsxs("div",{id:Ot===rt?"source_note_msg_hit_0":void 0,className:`source_msg source_${ts} ${Pe?"source_match":""}`,children:[s.jsxs("div",{className:"source_msg_meta mono muted",children:[s.jsxs("span",{children:["#",Ot+1," · ",Ut,Pe?s.jsx("span",{className:"source_match_badge",children:"evidence"}):null]}),on?s.jsx("span",{title:dn||"",children:on}):null]}),s.jsx("div",{className:"source_msg_body",children:s.jsx(xi,{text:Ht.content,highlights:Pe&&zt.length?zt:void 0,highlightClassName:"source_note_hit",highlightId:Ot===rt?"source_note_hit_0":void 0})})]},`note_msg:${Ot}`)})})}return s.jsxs("div",{className:"source_note",children:[ce?s.jsx("div",{className:"mono muted",style:{marginBottom:10},children:s.jsxs("span",{title:ce,children:["created_at=",Ae]})}):null,s.jsx(xi,{text:se,highlights:ot?ok(ot):void 0,highlightClassName:"source_note_hit",highlightId:"source_note_hit_0"})]})}if(mt){const kt=new Map;for(const rt of mt){const zt=typeof(rt==null?void 0:rt.role)=="string"?String(rt.role):"unknown";kt.set(zt,(kt.get(zt)||0)+1)}const At=Array.from(kt.entries()).sort((rt,zt)=>zt[1]-rt[1]||rt[0].localeCompare(zt[0])).map(([rt,zt])=>`${rt}×${zt}`).join(" · ");return s.jsxs("div",{className:"source_chat",children:[ce?s.jsxs("div",{className:"mono muted",style:{marginBottom:10},children:[s.jsxs("span",{title:ce,children:["created_at=",Ae]})," · messages=",mt.length]}):null,_t?s.jsxs("div",{className:"mono muted",style:{marginBottom:10},children:["span=",_t]}):null,At?s.jsxs("div",{className:"mono muted",style:{marginBottom:10},children:["participants: ",At]}):null,mt.slice(0,200).map((rt,zt)=>{var St,Mn;const dn=typeof(rt==null?void 0:rt.role)=="string"?String(rt.role):"unknown",on=(rt==null?void 0:rt.content)==null?"":String(rt.content),Ht=typeof(rt==null?void 0:rt.timestamp)=="string"?String(rt.timestamp):"",Ot=Ht?ql(Ht):null,ts=Ot!==null?Hc(Ot):Ht,Pe=typeof(rt==null?void 0:rt.message_id)=="string"?String(rt.message_id):typeof((St=rt==null?void 0:rt.metadata)==null?void 0:St.message_id)=="string"?String(rt.metadata.message_id):typeof((Mn=rt==null?void 0:rt.metadata)==null?void 0:Mn.id)=="string"?String(rt.metadata.id):"",Ut=ut.has(zt);return s.jsxs("div",{id:`source_msg_${zt}`,className:`source_msg source_${dn} ${Ut?"source_match":""}`,children:[s.jsxs("div",{className:"source_msg_meta mono muted",children:[s.jsxs("span",{children:["#",zt+1," · ",dn,Ut?s.jsx("span",{className:"source_match_badge",children:"evidence"}):null,Pe?s.jsx("span",{className:"source_msg_id",children:Pe}):null]}),Ht?s.jsx("span",{title:Ht,children:ts}):null]}),s.jsx("div",{className:"source_msg_body",children:s.jsx(xi,{text:on})})]},zt)})]})}return s.jsx("pre",{className:"mono source_raw",style:{whiteSpace:"pre-wrap",wordBreak:"break-word"},children:(typeof he=="string"?he:ve)||"(empty)"})})()]}):null]})]})}const o8=6e4,a8=10*6e4;function l8(e){return Math.min(a8,o8*2**Math.max(0,e-1))}function wg(){return{value_version:"",value:null,has_value:!1,attempt_version:"",inflight:!1,failures:0,failed_at:null,error:""}}function c8(e,t,n,r){const i=[],a=new Set;for(const u of e||[]){const c=String((u==null?void 0:u.id)||"").trim();if(!c||a.has(c))continue;a.add(c);const d=t.get(c);if(!d){i.push({id:c,version:String(u.version||"")});continue}if(!d.inflight){if(d.failed_at!==null){n-d.failed_at>=l8(d.failures)&&i.push({id:c,version:String(u.version||"")});continue}r!=null&&r.immutable&&d.has_value||d.value_version!==String(u.version||"")&&i.push({id:c,version:String(u.version||"")})}}return i}function u8(e,t){const n=e.get(t.id)||wg();e.set(t.id,{...n,attempt_version:t.version,inflight:!0})}function d8(e,t,n){const r=e.get(t.id)||wg();e.set(t.id,{...r,value:n,has_value:!0,value_version:t.version,attempt_version:t.version,inflight:!1,failures:0,failed_at:null,error:""})}function f8(e,t,n,r){const i=e.get(t.id)||wg();e.set(t.id,{...i,attempt_version:t.version,inflight:!1,failures:i.failures+1,failed_at:r,error:String((n==null?void 0:n.message)||n||"failed")})}function m8(e,t,n){const r=new Map;for(const i of e||[]){const a=t.get(i.id);!a||!a.has_value||a.value===null||n!=null&&n.current_only&&a.value_version!==i.version||r.set(i.id,a.value)}return r}function h8(e,t){var i;let n=0;const r=new Set;for(const a of e||[])r.has(a.id)||(r.add(a.id),(i=t.get(a.id))!=null&&i.inflight&&(n+=1));return n}function _8(e,t,n){const r=new Set;for(const i of e||[]){const a=String((i==null?void 0:i.id)||"").trim();if(!a||r.has(a))continue;const u=t.get(a);if(!u||u.inflight){r.add(a);continue}u.failed_at===null&&(!u.has_value||n!=null&&n.current_only&&u.value_version!==String(i.version||""))&&r.add(a)}return r}function ys(e){return String((e==null?void 0:e.run_id)||"").trim()}function ck(e){const t=e!=null&&e.waiting&&typeof e.waiting=="object"?e.waiting:null;return String((t==null?void 0:t.reason)||(e==null?void 0:e.waiting_reason)||"").trim().toLowerCase()}function p8(e){const t=new Map;for(const n of e||[]){const r=String((n==null?void 0:n.automation_id)||"").trim();if(!r)continue;String((n==null?void 0:n.role)||"").trim()==="controller"?t.set(r,String((n==null?void 0:n.updated_at)||"")):t.has(r)||t.set(r,"")}return Array.from(t,([n,r])=>({id:n,version:r}))}function g8(e){if(String((e==null?void 0:e.automation_id)||"").trim())return!1;const t=String((e==null?void 0:e.role)||"").trim();return t==="occurrence"||t==="descendant"||t==="controller"?!1:String((e==null?void 0:e.session_kind)||"").trim()!=="automation"}function y8(e){return(e||[]).filter(t=>ys(t)&&g8(t)).map(t=>({id:ys(t),version:""}))}const w8=6e4;function v8(e,t=Date.now(),n=w8){const r=[];for(const i of e||[]){if(!ys(i)||String((i==null?void 0:i.status)||"").trim().toLowerCase()!=="running")continue;const a=typeof(i==null?void 0:i.ledger_len)=="number"?i.ledger_len:null;if(a===null||a<1)continue;const u=It((i==null?void 0:i.updated_at)||(i==null?void 0:i.created_at)||"");u!==null&&t-u<n||r.push({id:ys(i),version:String(a)})}return r}function x8(e){return{after:Math.max(0,Math.floor(e)-1),limit:1}}function b8(e,t){const n=[],r=new Set,i=a=>{r.has(ys(a))||(r.add(ys(a)),n.push({id:ys(a),version:String((a==null?void 0:a.updated_at)||"")}))};for(const a of e||[]){if(!ys(a)||String((a==null?void 0:a.status)||"").trim().toLowerCase()!=="waiting")continue;const u=ck(a);(u==="user"||t&&u==="subworkflow")&&i(a)}if(t){const a=new Set;for(const c of t){const d=String((c==null?void 0:c.parent_run_id)||"").trim();d&&!ds(String((c==null?void 0:c.status)||""))&&a.add(d)}let u=0;for(const c of t){if(u>=k8)break;!ys(c)||String((c==null?void 0:c.status)||"").trim().toLowerCase()!=="waiting"||ck(c)==="subworkflow"&&!a.has(ys(c))&&(i(c),u+=1)}}return n}const k8=50,j8=e=>({run_id:e,status:"missing",updated_at:"",workflow_id:"",error:"not found"});function S8(e,t){return{run_id:e,status:String((t==null?void 0:t.status)||"").trim().toLowerCase(),updated_at:String((t==null?void 0:t.updated_at)||(t==null?void 0:t.created_at)||"").trim(),workflow_id:String((t==null?void 0:t.workflow_id)||"").trim(),error:String((t==null?void 0:t.error)||"").trim()}}function N8(e,t){var i,a;const n=[],r=new Set;for(const u of e.values()){const c=String(((a=(i=u==null?void 0:u.waiting)==null?void 0:i.details)==null?void 0:a.sub_run_id)||"").trim();!c||t.has(c)||r.has(c)||(r.add(c),n.push({id:c,version:""}))}return n}function $8(e,t){var u;const n=Array.isArray(t==null?void 0:t.pin_ids)?t.pin_ids.map(c=>String(c)):[],r=(u=t==null?void 0:t.input_data)==null?void 0:u.prompt,a=(n.includes("prompt")||n.length===0)&&typeof r=="string"?r.trim():"";return{run_id:e,excerpt:a}}const C8=12;function uk(e,t,n=C8){const r=[],i=new Set;for(const a of e||[]){let u=0;for(const c of a||[]){const d=ys(c);!d||i.has(d)||(t===null?u>=n:!t.has(d))||(i.add(d),r.push(c),u+=1)}}return r}const Vp="abstractobserver_board_cache_v1:",E8=400,Vw=6e5;function A8(e,t){const n=new Map;if(!e)return n;try{const r=e.getItem(Vp+t);if(!r)return n;const i=JSON.parse(r);if(!Array.isArray(i))return n;for(const a of i){const u=String((a==null?void 0:a.id)||"").trim();!u||a.value===null||a.value===void 0||n.set(u,{...wg(),value:a.value,has_value:!0,value_version:String(a.version??"")})}}catch{return new Map}return n}function T8(e,t,n){if(e)try{let r=[];for(const[a,u]of n)!u.has_value||u.value===null||u.inflight||u.failed_at!==null||r.push({id:a,version:u.value_version,value:u.value});r=r.slice(-E8);let i=JSON.stringify(r);for(;i.length>Vw&&r.length;)r=r.slice(Math.max(1,Math.floor(r.length/4))),i=JSON.stringify(r);r.length?e.setItem(Vp+t,i):e.removeItem(Vp+t)}catch{}}function V1(){try{return typeof sessionStorage>"u"?null:sessionStorage}catch{return null}}const M8=4,Qd={automation:0,wait_detail:1,pulse:1,run_brief:2,outcome:3};class R8{constructor(t=M8){yn(this,"queue",[]);yn(this,"seq",0);yn(this,"active",0);yn(this,"peak",0);this.limit=t}get queued(){return this.queue.length}submit(t,n){this.queue.push({priority:t,seq:this.seq++,task:n}),this.queue.sort((r,i)=>r.priority-i.priority||r.seq-i.seq),this.pump()}pump(){for(;this.active<this.limit&&this.queue.length;){const t=this.queue.shift();this.active+=1,this.peak=Math.max(this.peak,this.active),Promise.resolve().then(t.task).catch(()=>{}).finally(()=>{this.active-=1,this.pump()})}}}const dk=new WeakMap;function L8(e){let t=dk.get(e);return t||(t=new R8,dk.set(e,t)),t}const fk=new WeakMap;function I8(e){let t=fk.get(e);return t||(t=e.automations_client(),fk.set(e,t)),t}function O8(e){return e.map(t=>`${t.id}@${t.version}`).sort().join("|")}const mk=new WeakMap;function P8(e,t,n){let r=mk.get(e);r||(r=new Map,mk.set(e,r));let i=r.get(t);return i||(i=n!=null&&n.persist?A8(n.storage===void 0?V1():n.storage,t):new Map,r.set(t,i)),i}const My=new Map;function D8(e,t){if(typeof setTimeout>"u")return;const n=My.get(e);n!==void 0&&clearTimeout(n),My.set(e,setTimeout(()=>{My.delete(e),T8(V1(),e,t)},250))}function ef(e,t,n,r){const i=_.useRef({client:null,entries:new Map,gen:0});i.current.client!==(e||null)&&(i.current={client:e||null,entries:e?P8(e,r.scope,{persist:r.persist}):new Map,gen:i.current.gen+1});const[a,u]=_.useReducer(x=>x+1,0),c=O8(t),d=Math.floor(Date.now()/3e4),m=_.useRef(n);m.current=n,_.useEffect(()=>{const x=i.current;if(!x.client)return;const k=x.client,b=x.gen,S=c8(t,x.entries,Date.now(),{immutable:r.immutable});if(!S.length)return;const $=L8(k);for(const A of S)u8(x.entries,A),$.submit(r.priority,async()=>{try{const E=await m.current(k,A);if(i.current.gen!==b)return;d8(x.entries,A,E),r.persist&&D8(r.scope,x.entries)}catch(E){if(i.current.gen!==b)return;f8(x.entries,A,E,Date.now())}u()});u()},[e,c,d,a,r.priority,r.immutable]);const h=_.useMemo(()=>m8(t,i.current.entries,{current_only:r.current_only}),[c,a,r.current_only,e]),p=_.useMemo(()=>h8(t,i.current.entries),[c,a,e]),y=_.useMemo(()=>_8(t,i.current.entries,{current_only:r.current_only}),[c,a,r.current_only,e]),w=_.useMemo(()=>x=>{const k=i.current.entries.get(x);k&&!k.inflight&&i.current.entries.set(x,{...k,value_version:"\0stale",failed_at:null,failures:0}),u()},[]);return{map:h,pending:p,loading:y,invalidate:w}}function F8(e){var r;const t=_h(e);if(!t)return null;const n=typeof(e==null?void 0:e.active_revision)=="number"?e.active_revision:typeof((r=e==null?void 0:e.definition)==null?void 0:r.revision)=="number"?e.definition.revision:null;return{brief:t,revision:n,raw:e}}function z8(e){var c,d,m;const t=e!=null&&e.definition&&typeof e.definition=="object"?e.definition:{},n=(c=e==null?void 0:e.summary)!=null&&c.trigger&&typeof e.summary.trigger=="object"?e.summary.trigger:t!=null&&t.trigger&&typeof t.trigger=="object"?t.trigger:{},r=n!=null&&n.config&&typeof n.config=="object"?n.config:{},i=(d=t==null?void 0:t.policy)!=null&&d.retry&&typeof t.policy.retry=="object"?t.policy.retry:null,a=i!=null&&i.backoff&&typeof i.backoff=="object"?i.backoff:{},u=typeof r.count=="number"&&Number.isFinite(r.count)&&r.count>0?r.count:null;return{trigger_source:String((n==null?void 0:n.source_id)||"").trim(),stop_after:u,stop_at_ms:It(typeof r.until=="string"?r.until:""),workflow_id:String(((m=t==null?void 0:t.target)==null?void 0:m.workflow_id)||"").trim(),retry:i?{max_attempts:typeof i.max_attempts=="number"?i.max_attempts:null,initial:String(a.initial??"").trim(),factor:typeof a.factor=="number"?a.factor:null,max:String(a.max??"").trim()}:null}}function B8(e,t){const n=_.useMemo(()=>p8(t),[t]),r=ef(e,n,async(a,u)=>F8(await I8(a).getAutomation(u.id)),{scope:"automation",priority:Qd.automation}),i=_.useMemo(()=>{const a=new Map,u=new Map;for(const[c,d]of r.map)a.set(c,d.brief),d.revision!==null&&u.set(c,d.revision);return{map:a,revisions:u}},[r.map]);return{map:i.map,revisions:i.revisions,records:r.map,pending:r.pending,loading:r.loading,invalidate:r.invalidate}}function U8(e,t){const n=_.useMemo(()=>y8(t),[t]),r=ef(e,n,async(i,a)=>$8(a.id,await i.get_run_input_data(a.id)),{scope:"excerpt_v2",priority:Qd.run_brief,immutable:!0,persist:!0});return{map:r.map,pending:r.pending,loading:r.loading}}function W8(e,t){const n=_.useMemo(()=>v8(t,Date.now()),[t]),r=ef(e,n,async(i,a)=>{const u=Number(String(a.version).split(":")[0]||0),c=await i.get_ledger(a.id,x8(u)),d=Array.isArray(c==null?void 0:c.items)?c.items:[];return d.length?S4(a.id,u,d[d.length-1]):null},{scope:"pulse",priority:Qd.pulse});return{map:r.map,pending:r.pending,loading:r.loading}}const q8=!0;function H8(e,t,n){const r=_.useMemo(()=>b8(t,n),[t,n]),i=ef(e,r,async(a,u)=>await a.get_run(u.id),{scope:"wait_detail",priority:Qd.wait_detail,current_only:q8});return{map:i.map,pending:i.pending,loading:i.loading}}function V8(e,t,n){const r=_.useMemo(()=>N8(t,n),[t,n]),i=ef(e,r,async(a,u)=>{try{return S8(u.id,await a.get_run(u.id))}catch(c){if(/\b404\b|not found/i.test(String((c==null?void 0:c.message)||c||"")))return j8(u.id);throw c}},{scope:"subrun_fate",priority:Qd.wait_detail});return{map:i.map,pending:i.pending,loading:i.loading}}const G8=!0;function K8(e){return(e||[]).filter(t=>ys(t)&&ds(String((t==null?void 0:t.status)||""))).map(t=>({id:ys(t),version:""}))}function J8(e){const t=e!=null&&e.output&&typeof e.output=="object"?e.output:null;return typeof(t==null?void 0:t.response)=="string"?t.response.trim():typeof(t==null?void 0:t._last_output)=="string"?t._last_output.trim():""}function Y8(e){const t=e==null?void 0:e.total;return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:null}async function X8(e,t){const[n,r]=await Promise.all([e.get_run(t),e.list_run_artifacts(t,{limit:1}).then(Y8,()=>null)]);return{answer:J8(n),artifacts:r}}function Z8(e,t){const n=_.useMemo(()=>K8(t),[t]),r=ef(e,n,async(i,a)=>await X8(i,a.id),{scope:"outcome",priority:Qd.outcome,immutable:G8,persist:!0});return{map:r.map,pending:r.pending,loading:r.loading}}function Q8(){const e=typeof IntersectionObserver<"u",[t,n]=_.useState(()=>e?new Set:null),r=_.useRef(new Map),i=_.useRef(new Set),a=_.useMemo(()=>(c,d)=>{const m=r.current.get(c);if(m&&m.el===d||(m&&(m.observer.disconnect(),r.current.delete(c)),!d||!e))return;const h=new IntersectionObserver(p=>{let y=!1;for(const w of p){const x=String(w.target.dataset.runId||"").trim();x&&(w.isIntersecting?!i.current.has(x):i.current.has(x))&&(w.isIntersecting?i.current.add(x):i.current.delete(x),y=!0)}y&&n(new Set(i.current))},{root:d,rootMargin:"100% 0px 100% 0px"});r.current.set(c,{el:d,observer:h});for(const p of Array.from(d.querySelectorAll("[data-run-id]")))h.observe(p)},[e]),u=_.useMemo(()=>()=>{for(const{el:c,observer:d}of r.current.values()){d.disconnect();for(const m of Array.from(c.querySelectorAll("[data-run-id]")))d.observe(m)}},[]);return _.useEffect(()=>()=>{for(const{observer:c}of r.current.values())c.disconnect();r.current.clear()},[]),{visible:t,attach:a,refresh:u}}const hk=200,_k=500,ez=6e4,tz=1e4,nz=15e3,sz=["llm_calls","tool_calls","tokens_total"];function rz(e,t){if(!t)return e;const n={...e};for(const r of sz){const i=e[r];i==null&&(n[r]=t[r]??null)}return t.archived===!0&&(n.archived=!0),n}function Ry(e){return!String((e==null?void 0:e.parent_run_id)||"").trim()||String((e==null?void 0:e.role)||"").trim()==="occurrence"}class iz{constructor(t){yn(this,"sweep_rows",[]);yn(this,"sweep_at",null);yn(this,"sweep_started_at",null);yn(this,"sweep_inflight",!1);yn(this,"active_rows",[]);yn(this,"active_complete",!1);yn(this,"early",!1);yn(this,"active_at",null);yn(this,"seeded",!1);this.epoch=t}sweep_due(t,n=!1){if(this.sweep_inflight)return!1;if(this.sweep_started_at===null)return!0;const r=t-this.sweep_started_at;return r>=ez||this.early&&r>=nz?!0:n&&r>=tz}begin_sweep(t){this.sweep_inflight=!0,this.sweep_started_at=t,this.early=!1}apply_sweep(t,n){this.sweep_inflight=!1,this.sweep_rows=(t||[]).filter(r=>!!ys(r)),this.sweep_at=n}fail_sweep(){this.sweep_inflight=!1}adopt_sweep(t){this.sweep_rows=t.sweep_rows,this.sweep_at=t.sweep_at}adopt_active(t){t.active_at!==null&&(this.active_rows=t.active_rows,this.active_at=t.active_at,this.active_complete=t.active_complete,this.seeded=t.seeded)}snapshot(){return{active_rows:this.active_rows,sweep_rows:this.sweep_rows,active_at:this.active_at,sweep_at:this.sweep_at}}seed(t){return!t||this.active_at!==null||!Array.isArray(t.active_rows)?!1:(this.active_rows=t.active_rows.filter(n=>!!ys(n)),this.sweep_rows=Array.isArray(t.sweep_rows)?t.sweep_rows.filter(n=>!!ys(n)):[],this.active_at=typeof t.active_at=="number"?t.active_at:null,this.sweep_at=typeof t.sweep_at=="number"?t.sweep_at:null,this.active_complete=!1,this.seeded=!0,this.active_rows.length>0||this.sweep_rows.length>0)}apply_active(t,n,r){this.active_at=Date.now(),this.seeded=!1;const i=new Set(this.active_rows.map(ys)),a=new Set,u=[];for(const c of[...t||[],...n||[]]){const d=ys(c);!d||a.has(d)||(a.add(d),u.push(c))}if(this.active_rows=u,this.active_complete=r,r)for(const c of i)a.has(c)||(this.early=!0)}view(){const t=new Map;for(const c of this.sweep_rows)t.set(ys(c),c);const n=new Set,r=[];for(const c of this.active_rows)n.add(ys(c)),r.push(rz(c,t.get(ys(c))));const i=new Map(r.map(c=>[ys(c),c])),a=[...r],u=r.filter(c=>Ry(c)&&!t.has(ys(c)));for(const c of this.sweep_rows){const d=ys(c),m=i.get(d);if(m){Ry(m)&&u.push(m);continue}this.active_complete&&!ds(String((c==null?void 0:c.status)||""))||a.push(c),Ry(c)&&u.push(c)}return{roots:u,all:a}}}function oz(e,t){return`${Vp}runs:${String(e||"").trim()}:${String(t||"").trim()}`}function az(e,t){if(!e)return null;try{const n=e.getItem(t);if(!n)return null;const r=JSON.parse(n);return!r||typeof r!="object"||!Array.isArray(r.active_rows)?null:{active_rows:r.active_rows,sweep_rows:Array.isArray(r.sweep_rows)?r.sweep_rows:[],active_at:typeof r.active_at=="number"?r.active_at:null,sweep_at:typeof r.sweep_at=="number"?r.sweep_at:null}}catch{return null}}function lz(e,t,n){if(e)try{let r=JSON.stringify(n);if(r.length>Vw&&(r=JSON.stringify({...n,sweep_rows:[]})),r.length>Vw){e.removeItem(t);return}e.setItem(t,r)}catch{}}function pk(){try{return typeof localStorage>"u"?null:localStorage}catch{return null}}const Gw=new WeakMap;let Kw=null;function cz(e,t){let n=Gw.get(e);if(!n||n.epoch!==t){const r=Kw;n=new iz(t),r&&r.epoch===t&&(r.sweep_at!==null&&n.adopt_sweep(r),n.adopt_active(r)),Gw.set(e,n)}return Kw=n,n}function uz(e){return Gw.get(e)||null}function gk(e){return Kw===e}const np=["needs_you","working","waiting_on","scheduled","done"],G1={needs_you:"Needs you",working:"Working",waiting_on:"Waiting on…",scheduled:"Scheduled",done:"Done"},dz={needs_you:"only you can move these",working:"an agent is on it",waiting_on:"something else must happen first",scheduled:"will start by itself",done:"read the outcome"},fz={needs_you:"nothing needs you",working:"no agent is working",waiting_on:"nothing is blocked",scheduled:"nothing scheduled",done:"no recent runs"},mz=8;function hz(){return{needs_you:[],working:[],waiting_on:[],scheduled:[],done:[]}}function Zs(e){return String((e==null?void 0:e.run_id)||"").trim()}function Ly(e){const t=String((e==null?void 0:e.role)||"").trim();return!String((e==null?void 0:e.parent_run_id)||"").trim()||t==="occurrence"||t==="controller"}function _z(e,t,n,r){const i=(e==null?void 0:e.paused)===!0||(n==null?void 0:n.paused)===!0;return lN({...e,paused:i},t,Cp(n),r??null)}function ua(e,t){const n=String(e||"").trim();return n.length>t?`${n.slice(0,t-1)}…`:n}function sp(e,t,n,r){var x,k;const i=Zs(e),a=(x=t.details)==null?void 0:x.get(i),u=(a==null?void 0:a.waiting)??(e==null?void 0:e.waiting),c=u&&typeof u=="object"?u:null,d=Zd(c),m=String((e==null?void 0:e.status)||"").trim().toLowerCase(),h=String((e==null?void 0:e.automation_id)||"").trim(),p=h?((k=t.automations)==null?void 0:k.get(h))??null:null,y=n.actor_run_id?t.by_id.get(n.actor_run_id):void 0,w=It((c==null?void 0:c.until)||"");return{run_id:i,lane:n.lane,line:n,title:uN(e,t,r),subject:cN(e,t),status_word:_z(e,n,a,p),workflow_id:String((e==null?void 0:e.workflow_id)||"").trim(),role:String((e==null?void 0:e.role)||"").trim(),wait_key:String((c==null?void 0:c.wait_key)||"").trim(),tool_names:d.map(b=>String((b==null?void 0:b.name)||"tool")).filter(Boolean),pending_calls:d.map(b=>({name:String((b==null?void 0:b.name)||"tool"),arguments:(b==null?void 0:b.arguments)??null})),prompt:String((c==null?void 0:c.prompt)||"").trim(),allow_free_text:(c==null?void 0:c.allow_free_text)!==!1,since_ms:It((c==null?void 0:c.since)||(e==null?void 0:e.updated_at)||(e==null?void 0:e.created_at)||""),duration_ms:mh(e,t.now_ms),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,failed:m==="failed",error:String((e==null?void 0:e.error)||(a==null?void 0:a.error)||"").trim(),paused:n.verb==="paused",archived:(e==null?void 0:e.archived)===!0,automation_id:h,tag:lg(e),tag_label:kS(e),actor_run_label:y?ni(String(y.workflow_id||""))||"subrun":"",blocks:[],chain:[],asks:[],stuck:!!n.stuck,next_fire_ms:String((e==null?void 0:e.role)||"").trim()==="controller"?(p==null?void 0:p.next_fire_ms)??w:w,automation:p,task:(p==null?void 0:p.task)||String((r==null?void 0:r.excerpt)||"").trim(),row:e}}function pz(e){const t=new Date(e),n=r=>String(r).padStart(2,"0");return`${n(t.getHours())}:${n(t.getMinutes())}:${n(t.getSeconds())}`}const rp=(e,t)=>e===null?t===null?0:1:t===null?-1:e-t,yk=(e,t)=>e===null?t===null?0:1:t===null?-1:t-e;function gz(e){return e.needs_you.sort((t,n)=>Number(t.stuck&&!t.asks.length)-Number(n.stuck&&!n.asks.length)||rp(t.since_ms,n.since_ms)),e.working.sort((t,n)=>Number(n.line.stalled)-Number(t.line.stalled)||yk(t.line.stale_ms,n.line.stale_ms)||rp(t.since_ms,n.since_ms)),e.waiting_on.sort((t,n)=>rp(t.since_ms,n.since_ms)),e.scheduled.sort((t,n)=>rp(t.next_fire_ms,n.next_fire_ms)),e.done.sort((t,n)=>Number(n.failed)-Number(t.failed)||yk(t.since_ms,n.since_ms)),e}function wk(e){var w,x,k;const t=hz(),n=[],r=[],i=new Set;for(const b of e.active||[]){const S=Zs(b);!S||i.has(S)||(i.add(S),(ds(b==null?void 0:b.status)?r:n).push(b))}for(const b of e.done||[]){const S=Zs(b);!S||i.has(S)||(i.add(S),ds(b==null?void 0:b.status)&&r.push(b))}const a=Lv([...n,...r],{details:e.details,fates:e.fates,pulses:e.pulses,automations:e.automations,now_ms:e.now_ms,stall_after_ms:e.stall_after_ms}),u=new Map(n.map(b=>[Zs(b),b])),c=new Map,d=b=>{const S=Zs(b);let $=c.get(S);return $||($=Vd(b,a),c.set(S,$)),$},m=b=>Ly(b)||!u.has(String((b==null?void 0:b.parent_run_id)||"").trim()),h=b=>It(String((b==null?void 0:b.updated_at)||(b==null?void 0:b.created_at)||""))??0,p=b=>(a.children_of.get(b)||[]).filter(S=>u.has(Zs(S))&&!Ly(S)).sort((S,$)=>h($)-h(S)),y=new Set;for(const b of n){if(!m(b))continue;const S=d(b);if(String((b==null?void 0:b.role)||"").trim()==="controller"){const q=String((b==null?void 0:b.automation_id)||"").trim()||Zs(b);if(y.has(q))continue;y.add(q);const I=sp(b,a,S,(w=e.run_briefs)==null?void 0:w.get(Zs(b)));t[I.lane].push(I);continue}const $=sp(b,a,S,(x=e.run_briefs)==null?void 0:x.get(Zs(b))),A=[],E=[];let z=S.verb==="running",F=!!S.stuck,M=0;const D=(q,I)=>{var P;const Z=d(q),R=I<6?p(Zs(q)):[],T=R.length>0;if(A.length>=mz)M+=1;else{const L=T?aN(q,a):"";A.push({run_id:Zs(q),depth:I,name:dg(String((q==null?void 0:q.workflow_id)||""))||Hd(Zs(q)),title:b4(String((q==null?void 0:q.workflow_id)||""))||Zs(q),words:T?L?`waits at ${L} ↓`:"waits for ↓":Z.brief||Z.text,stuck:!!Z.stuck,asks:Z.lane==="needs_you"&&!Z.stuck,running:Z.verb==="running"&&!T,stuck_facts:Z.stuck_facts,since_ms:It(String((q==null?void 0:q.updated_at)||(q==null?void 0:q.created_at)||""))})}I>0?(Z.lane==="needs_you"&&!Z.stuck&&E.push(sp(q,a,Z,(P=e.run_briefs)==null?void 0:P.get(Zs(q)))),Z.stuck&&(F=!0),Z.verb==="running"&&(z=!0)):T&&Z.lane==="needs_you"&&!Z.stuck&&E.push($);for(const L of R)D(L,I+1)};D(b,0),M&&A.push({run_id:"",depth:1,name:`+${M} more`,title:"",words:"",stuck:!1,asks:!1,running:!1}),F&&!E.length&&($.status_word="stuck"),$.chain=A.length>1?A:[],$.asks=E,$.stuck=F;const H=S.lane==="needs_you"&&!S.stuck;if($.lane=H||E.length||F?"needs_you":z?"working":S.lane,E.length){const q=E.map(I=>I.since_ms).filter(I=>I!==null);q.length&&($.since_ms=Math.min(...q))}t[$.lane].push($)}for(const b of r){if(!Ly(b)&&a.by_id.has(String((b==null?void 0:b.parent_run_id)||"").trim()))continue;const S=sp(b,a,d(b),(k=e.run_briefs)==null?void 0:k.get(Zs(b)));t.done.push(S)}return gz(t)}function yz(e,t){const r=(t&&t.length?t:e||[]).filter(a=>Zs(a)&&!ds(a==null?void 0:a.status)),i=[...t||[],...e||[]].filter(a=>Zs(a)&&ds(a==null?void 0:a.status));return{active:r,done:i}}const K1="board_stall_after_ms",ex=[{ms:5*6e4,label:"5m"},{ms:15*6e4,label:"15m"},{ms:60*6e4,label:"1h"}];function J1(e){try{const t=Number(e==null?void 0:e.getItem(K1));return ex.some(n=>n.ms===t)?t:kw}catch{return kw}}function Y1(e){var t;return((t=ex.find(n=>n.ms===e))==null?void 0:t.label)||Qs(e)}function wz(){try{return typeof localStorage>"u"?null:localStorage}catch{return null}}function X1(e){const t=String((e==null?void 0:e.actor_id)||"").trim();return t&&t.toLowerCase()!=="gateway"?t:""}const Z1=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],Gp=e=>String(e).padStart(2,"0");function eu(e,t=Date.now()){const n=new Date(e),r=n.getFullYear()===new Date(t).getFullYear()?"":` ${n.getFullYear()}`;return`${Z1[n.getMonth()]} ${n.getDate()}${r}, ${Gp(n.getHours())}:${Gp(n.getMinutes())}`}function vz(e){const t=new Date(e);return`${Z1[t.getUTCMonth()]} ${t.getUTCDate()}, ${Gp(t.getUTCHours())}:${Gp(t.getUTCMinutes())} UTC`}function Jw(e,t=Date.now()){const n=e-t;return n>0?`in ${Qs(n)}`:`${Qs(-n)} ago`}function xz(e){if(!e.length)return"a tool call";const t=new Map;for(const r of e)t.set(r,(t.get(r)||0)+1);const n=Array.from(t,([r,i])=>i>1?`${r} ×${i}`:r);return`${n.slice(0,3).join(", ")}${n.length>3?` and ${n.length-3} more`:""}`}const tu=e=>e.split(" ").join(" ");function tx(e,t){const n=e.since_ms!==null?` since ${tu(eu(e.since_ms,t))} ${tu(`(${Qs(Math.max(0,t-e.since_ms))})`)}`:"",r=e.line.action;if(e.line.verb==="paused")return{who:"",text:`paused${n}`};if(e.line.stuck)return{who:"",text:`stuck${n}`};const i=X1(e.row);return r==="approve"?{who:i,text:`needs approval for ${xz(e.tool_names)}${n}`}:r==="answer"?{who:i,text:`${e.prompt?"asks":"waits for an answer"}${n}`}:e.line.unresolved?{who:i,text:`needs you${n} · question, approval or pause`}:{who:i,text:`needs you${n}`}}function Om(e){if(typeof e=="string")return e;if(e==null||typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e)}catch{return String(e)}}function Yw(e,t=0){const r=(e.arguments&&typeof e.arguments=="object"&&!Array.isArray(e.arguments)?Object.entries(e.arguments):[]).map(([i,a])=>`${i}: ${t>0?ua(Om(a),t):Om(a)}`);return`${e.name}(${r.join(", ")})`}function bz(e){const t=e.arguments;return t==null?"":typeof t!="object"||Array.isArray(t)?Om(t):Object.entries(t).map(([n,r])=>Array.isArray(r)&&r.length&&r.every(i=>i===null||typeof i!="object")?`${n}:
|
|
161
|
+
${r.map(i=>Om(i)).join(`
|
|
162
|
+
`)}`:`${n}: ${Om(r)}`).join(`
|
|
163
|
+
`)}const gp=600,yp=4e3;function Q1(e,t){var n;if(e.lane!=="needs_you")return null;if(e.line.verb==="paused"){const r=String((t==null?void 0:t.pause_reason)||((n=e.row)==null?void 0:n.pause_reason)||"").trim();return r?{text:ua(r,gp),full:ua(r,yp)}:null}if(e.line.action==="approve"&&e.pending_calls.length){const r=e.pending_calls.map(a=>Yw(a,120)).join(" · "),i=e.pending_calls.map(a=>Yw(a)).join(`
|
|
164
|
+
`);return{text:ua(r,gp),full:ua(i,yp)}}return e.prompt?{text:ua(e.prompt,gp),full:ua(e.prompt,yp)}:null}function kz(e,t){if(e.lane!=="done"||e.failed)return null;const n=String((t==null?void 0:t.answer)||"").trim();return n?{text:ua(n,gp),full:ua(n,yp)}:null}function e$(e,t){const n=[];return e.role==="controller"||(e.duration_ms>=0&&n.push(Qs(e.duration_ms)),e.tokens_total!==null&&n.push(`${e.tokens_total.toLocaleString("en-US")} tk`),e.tool_calls!==null&&n.push(`${e.tool_calls} tool${e.tool_calls===1?"":"s"}`),e.lane==="done"&&typeof(t==null?void 0:t.artifacts)=="number"&&n.push(`${t.artifacts} artifact${t.artifacts===1?"":"s"}`)),n}function nx(e){var n;const t=String(((n=e.row)==null?void 0:n.session_id)||"").trim();return!t||e.automation_id||e.subject.kind==="automation"||t.startsWith("automation:")?"":t}function jz(e,t,n){return`${String(e||"").split("#")[0]}#session=${encodeURIComponent(t)}&run=${encodeURIComponent(n)}`}const vk="Install the AbstractCode web app (npx @abstractframework/code) to open this conversation";function xk(e){return e.lane!=="done"&&e.role!=="controller"}const Sz={automation:"automation",brief:"run brief",excerpt:"prompt",workflow:"untitled"};function Kp(e){var t;if(e.title.source==="excerpt"&&e.task)return e.task;if(e.title.source==="brief"){const n=(t=e.row)==null?void 0:t.brief;return String((n==null?void 0:n.title)||(n==null?void 0:n.task_excerpt)||e.title.text).trim()}return e.title.text}const Nz=[25e3,5e4,1e5,2e5];function t$(e,t){const n=e.schedule_rule_text||e.cadence||"",r=e.current&&!ds(e.current.status)?e.current:null;let i="",a="";e.status==="paused"?(i="paused",a=e.paused_reason||"scheduled runs are skipped while paused"):r?(i=`run #${r.index} in progress`,a=e.next_fire_ms!==null?`next run ${eu(e.next_fire_ms,t)}`:""):e.next_fire_ms!==null?(i=`next ${tu(Jw(e.next_fire_ms,t))}`,a=`next run ${eu(e.next_fire_ms,t)}${e.next_run_local?` · ${e.next_run_local} (owner's zone)`:""}`):e.status==="completed"||e.status==="failed"?i=`${e.status}: no next run`:e.cadence!=="manual"&&(i="no next run");const u=[n,i].filter(Boolean),c={text:Iy(u),title:[n,a].filter(Boolean).join(" · "),parts:u},d=tu(`${e.occurrence_count} turn${e.occurrence_count===1?"":"s"}`);if(!e.last)return{schedule:c,last:{text:Iy(["no run yet",d]),title:"this automation has not run",failed:!1,parts:["no run yet",d],failure:""}};const m=e.last,h=m.status==="failed",p=m.fired_ms!==null?tu(Jw(m.fired_ms,t)):"",y=h?String(e.last_notification_text||e.last_excerpt||"").trim():"",x=!!(r&&r.index===m.index)?`#${m.index} started${p?` ${p}`:""}`:`last #${m.index} ${h?"✗ failed":m.status}${p?` ${p}`:""}`,k=m.fired_ms!==null&&m.finished_ms!==null&&m.finished_ms>=m.fired_ms?Qs(m.finished_ms-m.fired_ms):"",b=[x,d],S=[`#${m.index} ${m.status}`,m.fired_ms!==null?`fired ${eu(m.fired_ms,t)}`:"",k?`took ${k}`:"",y].filter(Boolean).join(" · ");return{schedule:c,last:{text:Iy(b),title:S,failed:h,parts:b,failure:y}}}function Iy(e){return e.join(" · ").split(" ").join(" ")}function $z(e){const t=String(e.context_mode||"").trim();if(t!=="growing")return{mode:t,used:null,budget:null,label:t?`${t} context`:"",ratio:null};const n=typeof e.growing_max_tokens=="number"&&e.growing_max_tokens>0?e.growing_max_tokens:null,r=typeof e.context_used_tokens=="number"&&e.context_used_tokens>=0?e.context_used_tokens:null,i=n===null?"context":r===null?`context · ${Ql(n)} budget`:`context ${Ql(r)} / ${Ql(n)}`;return{mode:t,used:r,budget:n,label:i,ratio:r!==null&&n!==null?Math.min(1,r/n):null}}function Cz(e){return{context:{mode:"growing",growing:{max_tokens:e}}}}function Ez(e){const t=String(e??"").trim();if(!/^\d+$/.test(t))return null;const n=Number(t);return Number.isSafeInteger(n)&&n>0?n:null}const Az={phase:"idle",custom:"",error:"",optimistic:null};function Tz(e,t){switch(t.type){case"open":return e.phase==="idle"?{...e,phase:"choose",error:""}:e;case"close":return e.phase==="choose"?{...e,phase:"idle",custom:""}:e;case"custom":return{...e,custom:t.value};case"save":return e.phase==="choose"?{phase:"saving",custom:"",error:"",optimistic:{value:t.value,base:t.base}}:e;case"saved":return e.phase==="saving"?{...e,phase:"idle"}:e;case"failed":return e.phase==="saving"?{phase:"idle",custom:"",error:t.error||"the change was not saved",optimistic:null}:e}}function Mz(e,t){const n=t.optimistic;return n&&n.base===e.growing_max_tokens?n.value:e.growing_max_tokens}async function Rz(e,t,n,r){try{return await e(t,Cz(r),n),{type:"saved"}}catch(i){return{type:"failed",error:Oi(i).message||"the change was not saved"}}}function Lz(e,t){if(!e){const c={enabled:!1,reason:"automation details are loading"};return{run_now:c,toggle:{command:"automation.pause",label:"Pause schedule",state:c}}}const n=e.current&&!ds(e.current.status)?e.current:null,r={automation_id:e.automation_id,title:e.title,status:e.status,capabilities:e.capabilities,legacy:e.legacy,current_occurrence:n?{index:n.index,run_id:n.run_id,status:n.status}:null,occurrence_count:e.occurrence_count},i=Dm(r,[],t),a=e.status==="paused",u=a&&e.paused_reason&&i.resume.enabled?{enabled:!0,reason:`paused by the gateway: ${e.paused_reason}`}:i.resume;return{run_now:i.run_now,toggle:a?{command:"automation.resume",label:"Resume schedule",state:u}:{command:"automation.pause",label:"Pause schedule",state:i.pause}}}async function Iz(e,t,n){try{return await e(t,n),null}catch(r){return Oi(r).message||"the command was not sent"}}const Bc={run:"Run",spend:"Spend",automation:"Automation",schedule:"Schedule",policy:"Policy",after:"After each run",where:"Where"};function Xw(e,t){return`${e.toLocaleString("en-US")} ${t}${e===1?"":"s"}`}function xm(e,t,n,r,i=!1){return n===null?null:{id:e,label:t,value:i?vz(n):eu(n,r),aside:Jw(n,r),copy:new Date(n).toISOString()}}function Oz(e){const t=e.line;return t.verb==="paused"?"you, to resume it":t.action==="approve"?`your approval of ${Xw(e.pending_calls.length||e.tool_names.length||1,"tool call")}`:t.action==="answer"?e.prompt?"your answer to a question":"your answer":t.unresolved?"you: a question, an approval or a resume":t.actor==="clock"?"the clock":t.actor==="external"?t.object||"an external event":t.actor==="run"?t.object||"a subrun":t.object||"unknown"}function bk(e,t){if(!t)return null;const n=ni(t);return{id:e,label:"Workflow",value:n||t,aside:n&&n!==t?t:"",aside_mono:!0,copy:t}}const ln=(e,t)=>{t&&e.push(t)};function Pz(e,t){var m,h,p;const{now_ms:n}=t,r=e.automation,i=t.facts??null,a=e.row,u=e.role==="controller",c=[];if(!u){const y=[];if(!e.automation_id){const S=Kp(e);ln(y,{id:"title",label:"Title",value:S,long:!0,source:Sz[e.title.source]}),e.task&&e.task!==S&&ln(y,{id:"task",label:"Task",value:e.task,long:!0,source:"prompt"})}ln(y,bk("workflow",e.workflow_id)),ln(y,{id:"run_id",label:"Run id",value:e.run_id,mono:!0});const w=String((a==null?void 0:a.session_id)||"").trim();w&&ln(y,{id:"session",label:"Session",value:w,mono:!0}),ln(y,xm("started","Started",It((a==null?void 0:a.created_at)||""),n)),ln(y,xm("last_activity","Last activity",It((a==null?void 0:a.updated_at)||""),n));const x=String((a==null?void 0:a.actor_id)||"").trim();if(ln(y,x?{id:"started_by",label:"Started by",value:x,source:X1(a)?"":"not a person"}:{id:"started_by",label:"Started by",value:"not on this row"}),ln(y,{id:"state",label:"State",value:e.failed&&e.error?`failed: ${e.error}`:e.lane==="needs_you"?e.line.brief:e.line.text,long:!0}),e.lane==="needs_you"||e.lane==="waiting_on")if(ln(y,{id:"wait_kind",label:"Waiting for",value:Oz(e)}),ln(y,xm("wait_since","Since",e.since_ms,n)),e.line.verb==="paused"){const S=String(((m=t.detail)==null?void 0:m.pause_reason)||(a==null?void 0:a.pause_reason)||"").trim();S&&ln(y,{id:"pause_reason",label:"Reason",value:S,long:!0})}else e.pending_calls.length?e.pending_calls.forEach((S,$)=>ln(y,{id:`tool_call_${$}`,label:$===0?"Tool calls":"",value:bz(S),chips:[S.name],long:!0,copy:Yw(S)})):e.prompt&&ln(y,{id:"question",label:"Question",value:e.prompt,long:!0});e.lane==="working"&&ln(y,{id:"no_progress",label:"No progress",value:`marked after ${Y1(t.stall_after_ms)} without a ledger step`,source:"board header"}),c.push({id:"run",title:Bc.run,rows:y});const k=[],b=e.lane!=="done";e.duration_ms>=0&&ln(k,{id:"duration",label:"Duration",value:Qs(e.duration_ms),aside:b?"so far":""}),e.tokens_total!==null&&ln(k,{id:"tokens",label:"Tokens",value:e.tokens_total.toLocaleString("en-US"),source:"whole run tree"}),e.llm_calls!==null&&ln(k,{id:"llm_calls",label:"LLM calls",value:e.llm_calls.toLocaleString("en-US")}),e.tool_calls!==null&&ln(k,{id:"tool_calls",label:"Tool calls",value:e.tool_calls.toLocaleString("en-US")}),typeof((h=t.outcome)==null?void 0:h.artifacts)=="number"&&ln(k,{id:"artifacts",label:"Artifacts",value:t.outcome.artifacts.toLocaleString("en-US")}),e.tokens_total===null&&e.llm_calls===null&&e.tool_calls===null&&ln(k,{id:"metrics",label:"Metrics",value:"not measured yet: the 60 s metrics sweep fills them"}),c.push({id:"spend",title:Bc.spend,rows:k})}if(r){const y=[];ln(y,{id:"title",label:"Title",value:r.title||"untitled",long:!0,source:r.title?"automation":""}),r.task&&ln(y,{id:"task",label:"Task",value:r.task,long:!0}),ln(y,{id:"automation_id",label:"Automation id",value:r.automation_id,mono:!0}),ln(y,bk("target_workflow",(i==null?void 0:i.workflow_id)||(u?"":e.workflow_id))),typeof t.revision=="number"&&ln(y,{id:"revision",label:"Revision",value:String(t.revision)}),r.status&&ln(y,{id:"status",label:"Status",value:r.status}),c.push({id:"automation",title:Bc.automation,rows:y});const w=[];ln(w,{id:"trigger",label:"Trigger",value:r.cadence||"not on the record",source:(i==null?void 0:i.trigger_source)||""}),r.status==="paused"?ln(w,{id:"next",label:"Next run",value:"none while paused: scheduled runs are skipped"}):ln(w,xm("next","Next run",r.next_fire_ms,n,!0)||{id:"next",label:"Next run",value:"none scheduled"});const x=r.current&&!ds(r.current.status)?r.current:null;if(x&&ln(w,{id:"current",label:"In progress",value:`#${x.index} ${x.status}`}),r.last&&!(x&&x.index===r.last.index)){const S=r.last.fired_ms!==null&&r.last.finished_ms!==null&&r.last.finished_ms>=r.last.fired_ms?Qs(r.last.finished_ms-r.last.fired_ms):"",$=r.last.fired_ms!==null?eu(r.last.fired_ms,n):"";ln(w,{id:"last",label:"Last run",value:`#${r.last.index} ${r.last.status}`,aside:[S,$].filter(Boolean).join(" · ")})}ln(w,{id:"turns",label:"Turns",value:String(r.occurrence_count)}),(i==null?void 0:i.stop_after)!==null&&(i==null?void 0:i.stop_after)!==void 0&&ln(w,{id:"stop_after",label:"Stop after",value:Xw(i.stop_after,"run")}),(i==null?void 0:i.stop_at_ms)!==null&&(i==null?void 0:i.stop_at_ms)!==void 0&&ln(w,xm("stop_at","Stop at",i.stop_at_ms,n,!0)),c.push({id:"schedule",title:Bc.schedule,rows:w});const k=[];if(r.context_mode){const S=r.context_mode==="growing"&&typeof r.growing_max_tokens=="number"&&r.growing_max_tokens>0?`capped at ${Ql(r.growing_max_tokens)} tokens`:"";ln(k,{id:"context",label:"Context",value:r.context_mode,aside:S})}ln(k,r.tools.length?{id:"tools",label:"Tools",value:r.tools.join(", "),chips:r.tools}:{id:"tools",label:"Tools",value:"flow default",source:"flow"});const b=[r.model,r.provider].filter(Boolean).join(" · ");if(b&&ln(k,{id:"model",label:"Model",value:b}),r.max_iterations!==null&&ln(k,{id:"max_iterations",label:"Max iterations",value:String(r.max_iterations)}),r.tool_approval&&ln(k,{id:"tool_approval",label:"Tool approval",value:r.tool_approval}),r.untrusted_input_tools&&ln(k,r.untrusted_input_tools.length?{id:"untrusted",label:"Untrusted input",value:r.untrusted_input_tools.join(", "),chips:r.untrusted_input_tools}:{id:"untrusted",label:"Untrusted input",value:"no tool marked"}),r.email_allowed_recipients&&ln(k,{id:"recipients",label:"Email to",value:r.email_allowed_recipients.length?r.email_allowed_recipients.join(", "):"nobody"}),i!=null&&i.retry){const S=i.retry,$=[S.initial?`backoff ${S.initial}`:"",S.factor!==null?`× ${S.factor}`:"",S.max?`up to ${S.max}`:""].filter(Boolean).join(" ");ln(k,{id:"retry",label:"Retry",value:S.max_attempts!==null?Xw(S.max_attempts,"attempt"):"on failure",aside:$})}c.push({id:"policy",title:Bc.policy,rows:k}),c.push({id:"after",title:Bc.after,rows:[r.notify_channels.length?{id:"notify",label:"Notify",value:r.notify_channels.join(", "),chips:r.notify_channels}:{id:"notify",label:"Notify",value:"nobody"}]})}const d=String(((p=t.detail)==null?void 0:p.workspace_root)||(r==null?void 0:r.workspace_root)||"").trim();return d&&c.push({id:"where",title:Bc.where,rows:[{id:"workspace",label:"Workspace",value:d,mono:!0,source:r!=null&&r.workspace_access_mode?r.workspace_access_mode.split("_").join(" "):""}]}),c.filter(y=>y.rows.length>0)}const Zw={"12h":12*36e5,"24h":24*36e5,"48h":48*36e5,"72h":72*36e5,"7d":7*864e5,"14d":14*864e5,"1m":30*864e5,all:null},Oy={"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"},kk="48h";function jk(e,t,n=Date.now()){const r=Zw[t]??null;if(r===null)return{visible:e,hidden_count:0};const i=n-r,a=[];let u=0;for(const c of e)c.since_ms===null||c.since_ms>=i?a.push(c):u+=1;return{visible:a,hidden_count:u}}const Py=4;function Dz(e){var a;const t=(a=e==null?void 0:e.discoveries)==null?void 0:a.dreams_signals_brief;if(!t||typeof t!="object"||Array.isArray(t))return null;const n=typeof t.count=="number"&&Number.isInteger(t.count)&&t.count>0?t.count:0;if(!n)return null;const r=u=>Array.isArray(u)?u.filter(c=>typeof c=="string").map(c=>c.trim()).filter(Boolean):[],i=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:i}}function Sk(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 Fz(e){var c,d;const t=m=>{var p;const h=(p=e==null?void 0:e[m])==null?void 0:p.open;return Array.isArray(h)?h.map(Sk).filter(y=>y!==null):[]},n=t("questions"),r=t("problems"),i=(c=e==null?void 0:e.lessons)==null?void 0:c.lessons,a=Array.isArray(i)?i.map(Sk).filter(m=>m!==null):[],u=typeof((d=e==null?void 0:e.lessons)==null?void 0:d.total)=="number"?e.lessons.total:a.length;return{questions:n.slice(0,Py),questions_total:n.length,problems:r.slice(0,Py),problems_total:r.length,lessons:a.slice(0,Py),lessons_total:u}}function Ql(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`}function zz(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 Bz=6e4;function Dy(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 Fy(e){const t=String(e||"").trim();return t.length>72?`${t.slice(0,70)}…`:t}function wp(e){return e.toLowerCase().replace(/[_-]+/g," ")}function Uz(e){var m,h;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(p=>p&&typeof p=="string");if(!r.length)return null;const i=[];for(const p of r){i.push({needle:wp(p),phase:p});const y=(m=n[p])==null?void 0:m.spoken_synonyms;if(Array.isArray(y))for(const w of y){const x=wp(String(w||"").trim());x&&i.push({needle:x,phase:p})}}const u=(typeof t.initial_phase=="string"&&r.includes(t.initial_phase)?t.initial_phase:null)??(r.includes("sleep")?"sleep":null);if(!u)return null;const c=[],d=(h=t==null?void 0:t.state_mode_axis)==null?void 0:h.words;if(d&&typeof d=="object"&&!Array.isArray(d))for(const[p,y]of Object.entries(d)){const w=String((y==null?void 0:y.phase)||"").trim(),x=wp(String(p||"").trim());x&&r.includes(w)&&c.push({needle:x,phase:w})}return{phases:r,synonyms:i,modes:c,initial:u,version:typeof t.version=="number"?t.version:null,sha256:String((e==null?void 0:e.sha256)||"").trim()}}const Wz=["asleep","sleep","dream"],qz=["rest"],Hz=["awake","idle"];function Vz(e,t){const n=String(e||"").trim().toLowerCase();if(!n)return"unknown";if(t){const r=wp(n),i=t.synonyms.filter(u=>r.includes(u.needle)).sort((u,c)=>c.needle.length-u.needle.length);if(i.length)return i[0].phase;const a=t.modes.filter(u=>r.includes(u.needle)).sort((u,c)=>c.needle.length-u.needle.length);return a.length?a[0].phase:n.includes("task")&&!n.includes("no_task")&&t.phases.includes("work")?"work":Wz.some(u=>n.includes(u))?t.initial:qz.some(u=>n.includes(u))&&t.phases.includes("personal")?"personal":Hz.some(u=>n.includes(u))?t.initial:n.includes("stop")?"stopped":n.includes("pause")?"paused":n}return n.includes("visit")?"visit":n.includes("sleep")||n.includes("dream")?"sleep":n.includes("personal")||n.includes("own_time")||n.includes("own time")?"personal":n.includes("task")&&!n.includes("no_task")||n.includes("work")?"work":n.includes("awake")||n.includes("idle")?"sleep":n.includes("stop")?"stopped":n.includes("pause")?"paused":n.includes("rest")?"resting":n}const Gz=new Set(["visit","work","personal","sleep","paused","resting","stopped","unknown"]),Kz=new Set(["visit","work","personal","sleep","paused","resting","stopped","unknown"]);function Jz(e){if(!e)return Gz;const t=e.phases.filter(n=>Kz.has(n));return new Set([...t,"paused","stopped","unknown"])}const Yz={needs_you:3,working:3,waiting_on:2,scheduled:2,done:3};function co(e){return s.jsx("span",{className:`mc_sk${e.className?` ${e.className}`:""}`,style:e.width?{width:e.width}:void 0,"aria-hidden":"true"})}function Xz(e){return s.jsx(s.Fragment,{children:Array.from({length:e.n},(t,n)=>s.jsxs("div",{className:"mc_card mc_card_skeleton","aria-hidden":"true",children:[s.jsxs("div",{className:"mc_card_head",children:[s.jsx(co,{className:"mc_sk_title",width:n%2?"72%":"58%"}),s.jsx(co,{className:"mc_sk_pill"})]}),s.jsx(co,{width:"88%"}),s.jsx(co,{width:"46%"})]},n))})}function sh(e){return s.jsx("div",{className:"mc_sk_row",role:"status","aria-busy":"true","aria-label":`loading ${e.what}`,title:`loading ${e.what}…`,children:s.jsx(co,{width:e.width||"84%"})})}const Zz="mc_entities mc_entities_reserved",Qz="mc_entities mc_entities_empty",eB=4,n$=12;function tB(e){return s.jsx(s.Fragment,{children:Array.from({length:e.n},(t,n)=>s.jsxs("div",{className:"mc_entity_cell",children:[s.jsxs("div",{className:"mc_entity mc_entity_skeleton","aria-hidden":"true",children:[s.jsx(co,{className:"mc_sk_title",width:n%2?"64%":"48%"}),s.jsx(co,{className:"mc_sk_chip"}),s.jsx(co,{width:"70%"}),s.jsx(co,{width:"42%"}),s.jsx(co,{width:"56%"})]}),s.jsx(co,{className:"mc_sk_hints",width:"120px"})]},n))})}const Ja={},nB=["needs_you","working","waiting_on"];function sB(e,t){switch(t.type){case"ask":return e.phase==="idle"?{phase:"confirm",total:t.total}:e;case"keep":return e.phase==="confirm"?{phase:"idle"}:e;case"start":return e.phase==="confirm"?{phase:"busy",total:t.total,done:0,failed:0}:e;case"progress":return e.phase==="busy"?{...e,done:t.done,failed:t.failed}:e;case"finish":return e.phase==="busy"?{phase:"sent",total:e.total,failed:e.failed}:e;case"dismiss":return e.phase==="sent"?{phase:"idle"}:e}}async function s$(e,t,n){var d;const r=Math.max(1,Math.floor((n==null?void 0:n.concurrency)??3)),i=n!=null&&n.waves&&n.waves.length?n.waves.map(m=>[...m]):[[...e]];let a=0,u=0;const c=[];for(const m of i){if(!m.length)continue;if(n!=null&&n.batch){const y=a,w=u;let x=[];try{x=await n.batch(m,(k,b)=>{var S;return(S=n.on_progress)==null?void 0:S.call(n,y+k,w+b)})}catch(k){x=m.map(b=>({run_id:b,error:String((k==null?void 0:k.message)||k||"cancel failed")}))}for(const k of x)a+=1,k.error&&(u+=1,c.push({run_id:k.run_id,error:k.error}));(d=n.on_progress)==null||d.call(n,a,u);continue}let h=0;const p=async()=>{var y;for(;h<m.length;){const w=m[h++],x=await ox(t,w);a+=1,x.type==="failed"&&(u+=1,c.push({run_id:w,error:x.error})),(y=n==null?void 0:n.on_progress)==null||y.call(n,a,u)}};await Promise.all(Array.from({length:Math.min(r,m.length)},p))}return{done:a,failed:u,failures:c}}function rB(e,t,n,r=0){const i=n??t,a=`Cancel all ${i} task${i===1?"":"s"} in ${G1[e]}`;return i<t||r>0?`${a} (${t} run${t===1?"":"s"} asked)`:a}function iB(e,t,n,r){const[i,a]=_.useReducer(sB,{phase:"idle"}),u=t.length,c=r==null?void 0:r.targets,d=c?c.ids:[...t],m=d.length,h=!!n&&u>0&&nB.includes(e),p=rB(e,c?c.cards:u,m,(c==null?void 0:c.parents)??0);return{state:i,enabled:h,label:p,ask:()=>a({type:"ask",total:m}),keep:()=>a({type:"keep"}),run:async()=>{n&&(a({type:"start",total:m}),await s$(d,n,{batch:r==null?void 0:r.on_cancel_runs,waves:c==null?void 0:c.waves,on_progress:(w,x)=>a({type:"progress",done:w,failed:x})}),a({type:"finish"}),window.setTimeout(()=>a({type:"dismiss"}),4e3))}}}function oB(e){return s.jsx("button",{type:"button",className:`btn mc_icon_btn mc_cancel mc_lane_cancel${e.open?" is_active":""}`,title:e.label,"aria-label":e.label,"aria-expanded":e.open,onClick:e.on_ask,children:s.jsx(Xe,{name:"x",size:14})})}function aB(e){const{state:t}=e;if(t.phase==="confirm")return s.jsxs("div",{className:"mc_lane_band mc_lane_band_confirm",role:"group","aria-label":e.label,children:[s.jsxs("span",{className:"mc_lane_band_q",children:[e.label,"?"]}),s.jsx("span",{className:"mc_lane_band_reach",children:gB}),s.jsxs("span",{className:"mc_lane_band_actions",children:[s.jsx("button",{type:"button",className:"btn danger mc_btn_sm",onClick:e.on_run,children:"Cancel all"}),s.jsx("button",{type:"button",className:"btn mc_btn_sm",onClick:e.on_keep,children:"Keep"})]})]});if(t.phase==="busy")return s.jsxs("div",{className:"mc_lane_band mc_lane_band_progress",role:"status","aria-live":"polite",children:[s.jsx(Xe,{name:"loader",size:14,className:"mc_spin"}),s.jsxs("span",{children:["cancelling ",t.done," / ",t.total,t.failed?` · ${t.failed} failed`:""]})]});if(t.phase==="sent"){const n=t.total-t.failed;return s.jsx("div",{className:"mc_lane_band mc_lane_band_progress",role:"status","aria-live":"polite",children:s.jsxs("span",{children:["cancel asked for ",n," task",n===1?"":"s",t.failed?` · ${t.failed} refused`:""]})})}return null}function lB(e){var i,a,u,c,d;(i=Ja.lane)==null||i.call(Ja,e.col);const t=`mc_column_title_${e.col}`,n=iB(e.col,((a=e.cancel)==null?void 0:a.run_ids)??[],(u=e.cancel)==null?void 0:u.on_cancel_run,{targets:(c=e.cancel)==null?void 0:c.targets,on_cancel_runs:(d=e.cancel)==null?void 0:d.on_cancel_runs}),r=e.count===null?" is_loading":e.count?"":" is_zero";return s.jsxs("section",{className:`mc_column mc_column_${e.col}`,"aria-labelledby":t,children:[s.jsxs("header",{className:"mc_column_head",children:[s.jsx("h2",{className:"mc_column_title",id:t,children:e.title}),n.enabled?s.jsx(oB,{label:n.label,open:n.state.phase!=="idle",on_ask:n.ask}):null,e.tools,s.jsx("span",{className:`mc_column_count${r}`,title:e.count===null?"loading":e.count_title,"aria-busy":e.count===null||void 0,children:e.count===null?"…":e.count}),e.after]}),n.enabled?s.jsx(aB,{state:n.state,label:n.label,on_run:()=>void n.run(),on_keep:n.keep}):null,e.children]})}const Os=e=>e.stopPropagation(),cB=typeof window>"u"?_.useEffect:_.useLayoutEffect;function uB(e){const{line:t}=e.card;if(t.actor==="run"){const n=e.card.actor_run_label,r=n&&!t.text.includes(n)?`run ${ua(n,28)}`:"subrun";return t.actor_run_id?s.jsx("button",{type:"button",className:"mc_actor mc_actor_run",title:`Open the subrun ${e.card.actor_run_label||""}`.trim(),onClick:i=>{i.stopPropagation(),e.on_open_run(t.actor_run_id)},onKeyDown:Os,children:r}):s.jsx("span",{className:"mc_actor mc_actor_run",title:"Another run ends this wait; it is not listed yet",children:"run"})}return t.actor==="external"?s.jsx("span",{className:"mc_actor mc_actor_external",title:`An external system ends this wait: ${t.object||"an event"}`,children:"external"}):t.actor==="unknown"?s.jsx("span",{className:"mc_actor mc_actor_unknown",title:"Nothing on the wire says what ends this wait",children:"unknown"}):null}function dB(){return s.jsxs("svg",{width:"15",height:"15",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.4",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",focusable:"false",children:[s.jsx("rect",{x:"5.5",y:"5.5",width:"8.5",height:"8.5",rx:"1.6"}),s.jsx("path",{d:"M10.5 3.6V3.1a1.6 1.6 0 0 0-1.6-1.6H3.1a1.6 1.6 0 0 0-1.6 1.6v5.8a1.6 1.6 0 0 0 1.6 1.6h.5"})]})}function sx(e){const[t,n]=_.useState("");return s.jsx("button",{type:"button",className:`mc_copy${t?` is_${t}`:""}`,title:e.title??`Copy ${e.label}`,"aria-label":`Copy ${e.label}`,onClick:async r=>{r.stopPropagation(),n(await hh(e.text)?"copied":"failed"),window.setTimeout(()=>n(""),1500)},onKeyDown:Os,children:t==="copied"?"copied":t==="failed"?"copy failed":s.jsx(dB,{})})}const fB=320,mB=6;function hB(e){const[t,n]=_.useState(!1),r=e.text,i=r.length>fB||r.split(`
|
|
165
|
+
`).length>mB;return s.jsxs("div",{className:`mc_long${i&&!t?" is_folded":""}`,children:[s.jsx("div",{className:"mc_long_text",children:r}),i?s.jsx("button",{type:"button",className:"mc_long_toggle","aria-expanded":t,onClick:()=>n(!t),children:t?"show less":`show all (${r.length.toLocaleString("en-US")} chars)`}):null]})}function _B(e){var r,i;const t=e.row,n=!!((r=t.chips)!=null&&r.length)&&!t.long;return s.jsxs("div",{className:"mc_info_row","data-row":t.id,children:[s.jsxs("dt",{className:"mc_info_label",children:[t.label,t.source?s.jsx("span",{className:"mc_source",children:t.source}):null]}),s.jsxs("dd",{className:"mc_info_value",children:[(i=t.chips)!=null&&i.length?s.jsx("span",{className:"mc_tags",children:t.chips.map((a,u)=>s.jsx("code",{className:"mc_tag",children:a},`${a}:${u}`))}):null,n||!t.value?null:t.long?s.jsx(hB,{text:t.value}):s.jsx("span",{className:`mc_info_text${t.mono?" mono":""}`,children:t.value}),t.aside?s.jsx("span",{className:`mc_info_aside${t.aside_mono?" mono":""}`,children:t.aside}):null]}),s.jsx("dd",{className:"mc_info_copy",children:t.value||t.copy?s.jsx(sx,{text:t.copy??t.value,label:(t.label||"value").toLowerCase()}):null})]})}function Nk(e,t){var d,m;const n=new Map;for(const h of t){const p=Zs(h);p&&n.set(p,h)}const r=h=>{var p;return String(((p=n.get(h))==null?void 0:p.role)||"").trim()==="controller"},i=Array.from(new Set(e.map(h=>String(h||"").trim()).filter(Boolean))),a=[];let u=0,c=0;for(const h of i){if(r(h))continue;u+=1;let p=h,y=String(((d=n.get(h))==null?void 0:d.parent_run_id)||"").trim();const w=new Set([h]);for(;y&&n.has(y)&&!w.has(y)&&!r(y);)p=y,w.add(y),y=String(((m=n.get(y))==null?void 0:m.parent_run_id)||"").trim();p!==h&&(c+=1),a.includes(p)||a.push(p)}return{ids:a,waves:a.length?[a]:[],cards:u,tasks:a.length,runs:u,parents:c}}const pB="Cancel this task: this run, its parents below the automation, and everything working under them";function r$(e,t){const n=e==null?void 0:e.ids[0];return!!(e&&n&&t&&n!==t)?"Cancel this task? Its parents and everything working under them stop too":"Cancel this run? Everything working under it stops too"}const gB="Everything working under those tasks stops too; automation schedules are not touched.";function yB(e){const[t,n]=_.useState(e.current),[r,i]=_.useState(!1),[a,u]=_.useState(""),c=!!e.on_rename,d=t.trim();return s.jsxs("div",{className:"mc_info_row mc_name_it_row","data-row":"name_it",children:[s.jsx("dt",{className:"mc_info_label",children:"Name it"}),s.jsxs("dd",{className:"mc_info_value",children:[s.jsxs("form",{className:"mc_name_it",onSubmit:async m=>{var h;if(m.preventDefault(),!(!e.on_rename||!d)){i(!0),u("");try{await e.on_rename(e.automation_id,d,e.revision),u("renamed"),(h=e.on_renamed)==null||h.call(e,e.automation_id)}catch(p){u(String((p==null?void 0:p.message)||(p==null?void 0:p.code)||p||"rename failed"))}finally{i(!1)}}},children:[s.jsx("input",{className:"mc_name_it_input","aria-label":"The automation's title",value:t,maxLength:200,disabled:!c||r,title:c?"The automation's title (the Automations page shows the same)":"Renaming is not available here",onChange:m=>n(m.target.value)}),s.jsx("button",{type:"submit",className:"btn mc_btn_sm",disabled:!c||r||!d||d===e.current,title:c?"Save the automation's title":"Renaming is not available here: this host does not wire automation revisions",children:r?"Saving":"Save"})]}),a?s.jsx("span",{className:"mc_name_it_msg",children:a}):null]}),s.jsx("dd",{className:"mc_info_copy"})]})}function i$(e){var i;const t=nx(e.card);if(!t)return null;const n=String(((i=e.code_app)==null?void 0:i.url)||"").trim(),r=e.variant==="icon";return n?s.jsx("a",{className:r?"btn mc_icon_btn mc_open_code":"btn mc_btn_sm mc_btn_quiet mc_open_code",href:jz(n,t,e.card.run_id),target:"_blank",rel:"noreferrer",title:"Open this conversation in the AbstractCode web app (new tab)","aria-label":"Open in Code",onClick:Os,onKeyDown:Os,children:r?s.jsx(Xe,{name:"terminal",size:15}):"Open in Code"}):s.jsx("span",{className:"mc_btn_wrap",title:vk,children:s.jsx("button",{type:"button",className:r?"btn mc_icon_btn":"btn mc_btn_sm mc_btn_quiet",disabled:!0,title:vk,"aria-label":"Open in Code",children:r?s.jsx(Xe,{name:"terminal",size:15}):"Open in Code"})})}function rx(e,t){switch(t.type){case"ask":return e.phase==="idle"?{phase:"confirm",error:""}:e;case"keep":return e.phase==="confirm"?{phase:"idle",error:""}:e;case"send":return e.phase==="confirm"?{phase:"busy",error:""}:e;case"done":return e.phase==="busy"?{phase:"sent",error:""}:e;case"failed":return e.phase==="busy"?{phase:"idle",error:t.error||"cancel failed"}:e}}const ix={phase:"idle",error:""};async function ox(e,t){try{const n=await e(t);return typeof n=="string"&&n?{type:"failed",error:n}:{type:"done"}}catch(n){return{type:"failed",error:String((n==null?void 0:n.message)||n||"cancel failed")}}}function ax(e){const{phase:t,error:n}=e.state,r=e.question||"Cancel this run?",i=r.startsWith("Cancel this task")?"Cancel task":r.startsWith("Stop this subrun")?"Stop subrun":"Cancel run";return[t==="confirm"||t==="busy"?s.jsxs("span",{className:"mc_confirm",role:"group","aria-label":r,children:[s.jsx("span",{className:"mc_confirm_q",children:r}),s.jsx("button",{type:"button",className:"btn danger mc_btn_sm",disabled:t==="busy",onClick:e.on_send,children:t==="busy"?"Cancelling":i}),s.jsx("button",{type:"button",className:"btn mc_btn_sm",disabled:t==="busy",onClick:()=>e.on_event({type:"keep"}),children:"Keep"})]},"confirm"):t==="sent"?s.jsx("span",{className:"mc_cancel_sent",children:"cancel requested"},"sent"):null,n?s.jsx("div",{className:"mc_act_error",role:"alert",children:n},"error"):null]}function o$(e){return s.jsx("button",{type:"button",className:e.variant==="icon"?"btn mc_icon_btn mc_cancel":"btn mc_btn_sm mc_btn_quiet mc_cancel",title:pB,"aria-label":"Cancel this task",onClick:()=>e.on_event({type:"ask"}),children:e.variant==="icon"?s.jsx(Xe,{name:"x",size:15}):"Cancel"})}function wB(e){return s.jsxs(s.Fragment,{children:[e.state.phase==="idle"?o$(e):null,ax(e)]})}function vB(e){var a;const[t,n]=_.useReducer(rx,ix),r=t.phase!=="idle"?(a=e.cancel_targets)==null?void 0:a.call(e,e.run_id):void 0,i=async()=>{n({type:"send"}),n(await a$(e.on_cancel_run,e.run_id,r,e.on_cancel_runs))};return s.jsx(wB,{state:t,on_event:n,on_send:()=>void i(),variant:e.variant,question:r$(r,e.run_id)})}async function a$(e,t,n,r){var a;if(!n||n.ids.length<=1)return ox(e,(n==null?void 0:n.ids[0])||t);const i=await s$(n.ids,e,{batch:r,waves:n.waves});return i.failed?{type:"failed",error:`${i.failed} of ${i.done} cancels failed: ${((a=i.failures[0])==null?void 0:a.error)||"cancel failed"}`}:{type:"done"}}function xB(e){const{card:t}=e,n=t.automation,r=Pz(t,{now_ms:e.now_ms,stall_after_ms:e.stall_after_ms,detail:e.detail,outcome:e.outcome,facts:e.facts,revision:e.revision}),i=t.role==="controller",a=t.automation_id&&e.on_open_automation?e.on_open_automation:null,u=!!(a||!i&&e.on_open_run||nx(t)||xk(t)&&e.on_cancel_run);return s.jsxs("div",{className:"mc_info_body",children:[r.map(c=>s.jsxs("section",{className:"mc_info_section","data-section":c.id,children:[s.jsx("h3",{className:"mc_info_section_title",children:c.title}),s.jsx("dl",{className:"mc_info_rows",children:c.rows.map(d=>s.jsxs(Ne.Fragment,{children:[s.jsx(_B,{row:d}),c.id==="automation"&&d.id==="title"&&(n!=null&&n.can_revise)?s.jsx(yB,{automation_id:t.automation_id,current:n.title,revision:e.revision??null,on_rename:e.on_rename_automation,on_renamed:e.on_renamed},`${t.automation_id}:${n.title}`):null]},d.id))})]},c.id)),t.automation_id&&!n?s.jsx("p",{className:"mc_info_note",children:"automation details are loading"}):null,u?s.jsxs("div",{className:"mc_info_actions",children:[a?s.jsx("button",{type:"button",className:"btn mc_btn_sm",onClick:()=>a(t.automation_id),children:"Open automation"}):null,!i&&e.on_open_run?s.jsx("button",{type:"button",className:"btn mc_btn_sm",onClick:()=>e.on_open_run(t.run_id),children:"Open run"}):null,s.jsx(i$,{card:t,code_app:e.code_app}),xk(t)&&e.on_cancel_run?s.jsx(vB,{run_id:t.run_id,on_cancel_run:e.on_cancel_run,on_cancel_runs:e.on_cancel_runs,cancel_targets:e.cancel_targets}):null]}):null]})}const bB=500,kB=580;let nu=null;function fa(){nu!==null&&window.clearTimeout(nu),nu=null}function $k(e,t=bB){var c;const n=e.getBoundingClientRect(),r=window.innerWidth,i=Math.min(t,r-16),a=(c=e.closest(".mc_card"))==null?void 0:c.getBoundingClientRect();if(a&&a.right+8+i<=r-8)return{top:Math.max(8,a.top),left:a.right+8,width:i,side:!0};if(a&&a.left-8-i>=8)return{top:Math.max(8,a.top),left:a.left-8-i,width:i,side:!0};const u=Math.min(Math.max(8,n.right-i),r-i-8);return{top:n.bottom+6,left:u,width:i,side:!1}}function jB(e){const{anchor:t,on_close:n,on_hover:r,...i}=e;return s.jsx(l$,{anchor:t,on_close:n,on_hover:r,label:`About ${e.card.title.text}`,children:s.jsx(xB,{...i})})}function l$(e){const t=_.useRef(null),n=e.width,[r,i]=_.useState(()=>e.anchor.current?$k(e.anchor.current,n):null),a=_.useRef(e);return a.current=e,cB(()=>{var y;const u=t.current,c=(y=e.anchor.current)==null?void 0:y.getBoundingClientRect();if(!u||!c||!r)return;const d=u.offsetHeight,m=window.innerHeight;if(r.top+d<=m-8)return;const h=c.top-6-d,p=r.side?Math.max(8,m-8-d):h>=8?h:Math.max(8,m-8-d);p!==r.top&&i({...r,top:p})},[r==null?void 0:r.left,r==null?void 0:r.width,r==null?void 0:r.top,r==null?void 0:r.side]),_.useEffect(()=>{const u=m=>{m.key==="Escape"&&a.current.on_close(!0)},c=m=>{var p,y;const h=m.target;h&&((p=a.current.anchor.current)!=null&&p.contains(h)||(y=t.current)!=null&&y.contains(h))||a.current.on_close(!1)},d=()=>{const m=a.current.anchor.current;m&&i($k(m,a.current.width))};return document.addEventListener("keydown",u,!0),document.addEventListener("pointerdown",c,!0),window.addEventListener("resize",d),window.addEventListener("scroll",d,!0),()=>{document.removeEventListener("keydown",u,!0),document.removeEventListener("pointerdown",c,!0),window.removeEventListener("resize",d),window.removeEventListener("scroll",d,!0)}},[]),r?Xp.createPortal(s.jsx("div",{ref:t,className:`mc_info_pop${e.className?` ${e.className}`:""}`,role:"dialog","aria-label":e.label,style:{top:r.top,left:r.left,width:r.width},onMouseEnter:()=>e.on_hover(!0),onMouseLeave:()=>e.on_hover(!1),onClick:Os,onKeyDown:Os,children:e.children}),document.body):null}function SB(e){const t=e.kind==="answer"?"Answer":e.kind==="task"?"Task":"Request",n=e.text.trim().split(/\s+/).filter(Boolean).length;return s.jsxs("div",{className:"mc_gp",children:[s.jsxs("div",{className:"mc_gp_head",children:[s.jsxs("span",{className:`mc_gp_kind mc_gp_kind_${e.kind}`,children:[s.jsx(Xe,{name:e.kind==="answer"?"sparkle":"chat",size:14}),s.jsx("span",{children:t})]}),e.about?s.jsx("span",{className:"mc_gp_about",title:e.about,children:e.about}):null,s.jsxs("span",{className:"mc_gp_meta",children:[n.toLocaleString("en-US")," words · ",e.text.length.toLocaleString("en-US")," chars"]}),s.jsx(sx,{text:e.text,label:`the full ${t.toLowerCase()}`,title:`Copy the full ${t.toLowerCase()}`}),e.on_close?s.jsx("button",{type:"button",className:"btn mc_icon_btn mc_gp_close",title:"Close","aria-label":"Close",onClick:e.on_close,children:s.jsx(Xe,{name:"x",size:14})}):null]}),s.jsx("div",{className:"mc_gp_body",children:s.jsx(xi,{text:e.text,images:"link",className:"mc_pop_md"})}),e.on_open?s.jsx("div",{className:"mc_gp_foot",children:s.jsx("button",{type:"button",className:"btn mc_btn_sm",onClick:e.on_open,children:"Open the run →"})}):null]})}function vp(e){const[t,n]=_.useState(""),r=_.useRef(null),i=()=>{fa(),nu=window.setTimeout(()=>n(u=>u==="hover"?"":u),200)},a=e.kind==="answer"?"answer":e.kind==="task"?"task":"request";return s.jsxs(s.Fragment,{children:[s.jsx("div",{ref:r,className:e.as_title?"mc_card_title mc_title_glimpse":`mc_glimpse mc_glimpse_${e.kind}`,title:`Read the full ${a}`,onMouseEnter:()=>{fa(),t||(nu=window.setTimeout(()=>n(u=>u||"hover"),150))},onMouseLeave:()=>t==="hover"?i():fa(),onClick:u=>{u.stopPropagation(),fa(),n(t==="pinned"?"":"pinned")},children:e.children}),t&&typeof document<"u"?s.jsx(l$,{anchor:r,label:`The full ${a}`,width:kB,className:"mc_pop_text",on_close:()=>n(""),on_hover:u=>u?fa():t==="hover"?i():void 0,children:s.jsx(SB,{kind:e.kind,text:e.full,about:e.about,on_open:e.on_open,on_close:()=>n("")})}):null]})}function NB(e){const[t,n]=_.useState(""),r=_.useRef(null),i=()=>{fa(),nu=window.setTimeout(()=>n(u=>u==="hover"?"":u),200)},a=e.card.role==="controller"?"About this automation":"About this run";return s.jsxs(s.Fragment,{children:[s.jsx("button",{ref:r,type:"button",className:"btn mc_icon_btn mc_info_btn",title:a,"aria-label":a,"aria-haspopup":"dialog","aria-expanded":t!=="",onClick:u=>{u.stopPropagation(),fa(),n(t==="pinned"?"":"pinned")},onKeyDown:Os,onMouseEnter:()=>{fa(),t||(nu=window.setTimeout(()=>n(u=>u||"hover"),150))},onMouseLeave:()=>t==="hover"?i():fa(),children:s.jsx(Xe,{name:"info",size:15})}),t&&typeof document<"u"?s.jsx(jB,{...e,anchor:r,on_close:u=>{var c;n(""),u&&((c=r.current)==null||c.focus())},on_hover:u=>u?fa():t==="hover"?i():void 0}):null]})}function $B(e){const t=e.title.text;if(e.subject.kind==="agent"||e.subject.kind==="run"){const r=ni(e.workflow_id);return{label:"",secondary:r&&r!==t?r:""}}const n=e.subject.label&&e.subject.label!==t?e.subject.label:"";return e.role==="controller"?{label:n,secondary:""}:{label:n,secondary:e.subject.secondary!==t?e.subject.secondary:""}}function c$(e){const{card:t}=e,n=e.busy||e.stale===!0,r=t.line.action,i=()=>e.on_open_run(t.run_id);return s.jsxs("div",{className:"mc_card_review_body",onClick:Os,onKeyDown:Os,children:[r==="approve"&&!t.wait_key?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,s.jsx("div",{className:"mc_card_actions",children:r==="approve"&&t.wait_key?s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"btn success mc_btn_sm",disabled:n,onClick:()=>e.on_act(t,{approved:!0}),children:n?"Resuming…":"Approve"}),s.jsx("button",{type:"button",className:"btn danger mc_btn_sm",disabled:n,onClick:()=>e.on_act(t,{approved:!1}),children:"Reject"})]}):r==="resume"&&e.on_resume?s.jsx("button",{type:"button",className:"btn primary mc_btn_sm",disabled:n,onClick:()=>e.on_resume(t),children:n?"Resuming…":"Resume"}):r==="answer"?s.jsx("button",{type:"button",className:"btn primary mc_btn_sm",onClick:i,children:"Review & answer →"}):s.jsx("button",{type:"button",className:"btn mc_btn_sm",onClick:i,children:"Open the run →"})})]})}function zy(e){const t=e.state.enabled&&!e.busy,n=e.busy?`${e.label}…`:e.state.enabled?[e.hint||e.label,e.state.reason].filter(Boolean).join(" — "):e.state.reason||"not available",r=s.jsx("button",{type:"button",className:`btn mc_icon_btn${e.className?` ${e.className}`:""}`,disabled:!t,title:n,"aria-label":e.label,onClick:e.onClick,children:s.jsx(Xe,{name:e.busy?"loader":e.icon,size:15,className:e.busy?"mc_spin":void 0})});return t?r:s.jsx("span",{className:"mc_btn_wrap",title:n,children:r})}function Qw(e){const t=e.parts.length;return s.jsx(s.Fragment,{children:e.parts.map((n,r)=>s.jsxs(Ne.Fragment,{children:[r?" ":null,s.jsxs("span",{className:"mc_unit",children:[n,r<t-1?s.jsx("span",{className:"mc_sep",children:" ·"}):null]})]},r))})}function CB(e){const{card:t}=e,n=t.automation,[r,i]=_.useReducer(Tz,Az),a=n?t$(n,e.now_ms):null,u=n?Mz(n,r):null,c=n?$z({...n,growing_max_tokens:u}):null,d=!!(n!=null&&n.can_revise&&e.on_revise_automation),m=Ez(r.custom),h=p=>{if(!n||!e.on_revise_automation||r.phase!=="choose")return;const y=e.on_revise_automation;i({type:"save",value:p,base:n.growing_max_tokens}),Rz(y,n.automation_id,e.revision??null,p).then(w=>{var x;i(w),w.type==="saved"&&((x=e.on_renamed)==null||x.call(e,n.automation_id))})};return s.jsxs(s.Fragment,{children:[a?s.jsxs("div",{className:"mc_facts",children:[s.jsx("div",{className:"mc_fact_cell mc_fact_schedule",title:a.schedule.title||void 0,children:s.jsx(Qw,{parts:a.schedule.parts})}),s.jsx("div",{className:`mc_fact_cell mc_fact_last${a.last.failed?" is_failed":""}`,title:a.last.title||void 0,children:s.jsx(Qw,{parts:a.last.parts})}),a.last.failure?s.jsx("div",{className:"mc_fact_fail",title:a.last.failure,children:a.last.failure}):null]}):e.automation_loading?s.jsxs("div",{className:"mc_facts","aria-busy":"true",children:[s.jsx(sh,{what:"the schedule",width:"90%"}),s.jsx(sh,{what:"the last run",width:"80%"})]}):s.jsx("div",{className:"mc_card_state",children:s.jsx("span",{className:"mc_state_text",title:t.line.text,children:t.line.text})}),c&&c.mode==="growing"?s.jsxs("div",{className:"mc_ctx",onClick:Os,onKeyDown:Os,children:[s.jsxs("button",{type:"button",className:`mc_ctx_bar${r.phase==="saving"?" is_saving":""}`,"aria-expanded":r.phase!=="idle","aria-label":`${c.label}: change the budget`,disabled:!d||r.phase==="saving",title:d?`${c.used!==null?`${c.used.toLocaleString("en-US")} tokens of history were replayed into the last run`:"the last run recorded no history size"} · budget ${(u==null?void 0:u.toLocaleString("en-US"))??"unset"} tokens · click to change`:`${c.label} · the budget is changed on the Automations page`,onClick:()=>i({type:r.phase==="idle"?"open":"close"}),children:[c.ratio!==null?s.jsx("span",{className:"mc_ctx_track","aria-hidden":"true",children:s.jsx("span",{className:"mc_ctx_fill",style:{width:`${Math.round(c.ratio*100)}%`}})}):null,s.jsx("span",{className:"mc_ctx_label",children:c.label})]}),r.phase==="choose"?s.jsxs("div",{className:"mc_ctx_chooser",role:"group","aria-label":"Context budget",children:[Nz.map(p=>s.jsx("button",{type:"button",className:`btn mc_btn_sm${p===u?" is_current":" mc_btn_quiet"}`,"aria-pressed":p===u,title:`${p.toLocaleString("en-US")} tokens`,onClick:()=>h(p),children:Ql(p)},p)),s.jsxs("form",{className:"mc_ctx_custom",onSubmit:p=>{p.preventDefault(),m!==null&&h(m)},children:[s.jsx("input",{type:"number",className:"mc_ctx_input",min:1,step:1e3,placeholder:"custom","aria-label":"Custom context budget, in tokens",value:r.custom,onChange:p=>i({type:"custom",value:p.target.value})}),s.jsx("button",{type:"submit",className:"btn mc_btn_sm",disabled:m===null,title:m===null?"a whole number of tokens":`set the budget to ${m.toLocaleString("en-US")} tokens`,children:"Set"})]}),s.jsx("button",{type:"button",className:"btn mc_icon_btn mc_ctx_close","aria-label":"Close",title:"Close",onClick:()=>i({type:"close"}),children:s.jsx(Xe,{name:"x",size:15})})]}):null,r.error?s.jsx("div",{className:"mc_act_error",role:"alert",children:r.error}):null]}):c&&c.label?s.jsx("span",{className:"mc_ctx_chip",title:`${c.mode} context: every run starts from the task alone`,children:c.label}):null]})}const EB={busy:"",error:""},Ck={enabled:!1,reason:"commands are not wired on this host"},AB={enabled:!0},TB="Stop this subrun and everything under it? Its parent continues and may delegate again",MB="Stop this subrun and everything under it: its parent continues and may delegate again";function RB(e){if(!e)return"a subrun ended and this run was not resumed";if(e.status==="missing")return`its subrun ${e.subrun} no longer exists on the gateway, so this run cannot be resumed`;const t=e.status==="cancelled"?"was cancelled":e.status==="failed"?"failed":`ended ${e.status}`,n=e.ended_ms!==null?` ${Qs(e.ended_ms)} ago`:"";return`its subrun ${e.subrun} ${t}${n} and this run was not resumed`}function u$(e){const t=typeof e.since_ms=="number"?` since ${tu(eu(e.since_ms,e.now_ms))} ${tu(`(${Qs(Math.max(0,e.now_ms-e.since_ms))})`)}`:"";return s.jsxs("div",{className:"mc_ask mc_ask_stuck","data-run-id":e.run_id,role:"group","aria-label":"stuck",children:[s.jsxs("div",{className:"mc_ask_head",children:[s.jsx("button",{type:"button",className:"mc_ask_who",onClick:()=>e.on_open_run(e.run_id),onKeyDown:Os,children:e.name})," ",s.jsxs("span",{className:"mc_ask_words",children:["stuck",t]})]}),s.jsxs("div",{className:"mc_stuck_why",children:[LB(RB(e.facts)),"."]}),s.jsxs("div",{className:"mc_card_actions",children:[e.on_cancel_task?s.jsx("button",{type:"button",className:"btn danger mc_btn_sm",onClick:e.on_cancel_task,children:"Cancel task"}):null,s.jsx("button",{type:"button",className:"btn mc_btn_sm",onClick:()=>e.on_open_run(e.run_id),children:"Open the run →"})]})]})}function LB(e){return e&&e[0].toUpperCase()+e.slice(1)}function IB(e){const{row:t}=e,[n,r]=_.useReducer(rx,ix),i=async()=>{e.on_cancel_run&&(r({type:"send"}),r(await ox(e.on_cancel_run,t.run_id)))},a=!t.run_id;return s.jsxs("div",{className:`mc_chain_row${t.stuck?" is_stuck":""}${t.asks?" is_ask":""}${t.running?" is_running":""}`,style:{paddingLeft:`${Math.min(t.depth,5)*14}px`},"data-run-id":t.run_id||void 0,children:[s.jsxs("div",{className:"mc_chain_main",children:[t.depth>0?s.jsx("span",{className:"mc_chain_glyph","aria-hidden":"true",children:"└"}):null,a?s.jsx("span",{className:"mc_chain_name is_more",children:t.name}):s.jsx("button",{type:"button",className:"mc_chain_name",title:`Open ${t.title||t.name}`,onClick:()=>e.on_open_run(t.run_id),onKeyDown:Os,children:t.name}),t.words?s.jsx("span",{className:"mc_chain_words",title:t.words,children:t.words}):null,e.on_cancel_run&&t.depth>0&&!a&&n.phase==="idle"?s.jsx("button",{type:"button",className:"btn mc_icon_btn mc_cancel mc_chain_cancel",title:MB,"aria-label":`Stop subrun ${t.name} only`,onClick:()=>r({type:"ask"}),children:s.jsx(Xe,{name:"x",size:13})}):null]}),n.phase!=="idle"||n.error?s.jsx("div",{className:"mc_chain_confirm",children:ax({state:n,on_event:r,on_send:()=>void i(),question:TB})}):null]})}function OB(e){const{card:t}=e,n=t.stuck&&!t.asks.length?t.chain.find(a=>a.stuck):void 0,r=new Set((e.ask_loading||"").split(",").filter(Boolean)),i=a=>!!e.busy_wait&&e.busy_wait===`${a.run_id}:${a.wait_key}:${a.since_ms??""}`;return s.jsxs("div",{className:"mc_chain",onClick:Os,onKeyDown:Os,children:[t.chain.map((a,u)=>s.jsx(IB,{row:a,on_open_run:e.on_open_run,on_cancel_run:e.on_cancel_run},a.run_id||`more-${u}`)),t.asks.map(a=>{var m;const u=(m=e.ask_detail)==null?void 0:m[a.run_id],c=Q1(a,u),d=tx(a,e.now_ms);return s.jsxs("div",{className:"mc_ask","data-run-id":a.run_id,children:[s.jsxs("div",{className:"mc_ask_head",title:a.line.text,children:[s.jsx("button",{type:"button",className:"mc_ask_who",onClick:()=>e.on_open_run(a.run_id),onKeyDown:Os,children:dg(a.workflow_id)||Hd(a.run_id)})," ",s.jsxs("span",{className:"mc_ask_words",children:[d.who?`${d.who} · `:"",d.text]})]}),!c&&r.has(a.run_id)?s.jsx(sh,{what:"the request"}):c?s.jsx(vp,{kind:"request",text:c.text,full:c.full,about:t.title.text,on_open:()=>e.on_open_run(a.run_id),children:c.text}):null,s.jsx(c$,{...e,card:a,detail:u,busy:i(a)})]},a.run_id)}),n?s.jsx(u$,{run_id:n.run_id,name:n.name,facts:n.stuck_facts,since_ms:n.since_ms,now_ms:e.now_ms,on_open_run:e.on_open_run,on_cancel_task:e.on_cancel_task}):null]})}function PB(e){var Z,R;const{card:t}=e;(Z=Ja.card)==null||Z.call(Ja,t.run_id);const[n,r]=_.useReducer(rx,ix),[i,a]=_.useState(EB),u=t.status_word,c=$B(t),d=t.role==="controller",m=t.chain.length>0,h=!d&&t.lane==="needs_you"&&!m,p=!d&&(t.lane==="needs_you"||t.lane==="working"||t.lane==="waiting_on"),y=h?Q1(t,e.detail):null,w=d?null:kz(t,e.outcome),x=e$(t,e.outcome),k=h?tx(t,e.now_ms):null,b=h&&!y&&e.detail_loading===!0,S=!d&&t.lane==="done"&&!w&&!t.failed&&e.outcome_loading===!0,$=t.title.untitled&&e.brief_loading===!0,A=p?e.on_cancel_run:void 0,E=n.phase!=="idle"&&A?(R=e.cancel_targets)==null?void 0:R.call(e,t.run_id):void 0,z=async()=>{A&&(r({type:"send"}),r(await a$(A,t.run_id,E,e.on_cancel_runs)))},F=T=>{!e.on_automation_command||i.busy||(a({busy:T,error:""}),Iz(e.on_automation_command,t.automation_id,T).then(P=>{var L;a({busy:"",error:P||""}),P||(L=e.on_renamed)==null||L.call(e,t.automation_id)}))},M=d?Lz(t.automation,i.busy!==""):null,D=n.phase!=="idle"||n.error||i.error,q=!(d||p&&(!!nx(t)||!!A))&&x.length>0,I=x.length?s.jsx("div",{className:`mc_card_metrics${q?" mc_foot_metrics":""}`,title:t.lane==="done"?"run time · tokens of the run tree · tool calls · artifacts":"time since the run started · tokens of the run tree · tool calls",children:s.jsx(Qw,{parts:x})}):null;return s.jsxs("div",{className:`mc_card mc_card_${t.lane}${t.failed?" mc_card_failed":""}${t.line.stalled?" mc_card_stalled":""}${d?" mc_card_automation":""}`,"data-lane":t.lane,"data-run-id":t.run_id,onClick:()=>e.on_open_run(t.run_id),role:"button",tabIndex:0,onKeyDown:T=>{T.key==="Enter"&&T.target===T.currentTarget&&e.on_open_run(t.run_id)},children:[s.jsxs("div",{className:"mc_card_head",children:[s.jsx("span",{className:`mc_card_glyph mc_glyph_${t.subject.kind}`,"aria-hidden":"true",children:t.subject.glyph}),$?s.jsx("span",{className:"mc_card_title",title:"loading the title…",children:s.jsx(co,{className:"mc_sk_title",width:"64%"})}):m||t.task?s.jsxs(vp,{kind:"task",text:t.title.text,full:t.task||Kp(t),about:t.subject.label||t.subject.secondary,on_open:()=>e.on_open_run(t.run_id),as_title:!0,children:[t.title.text,t.title.untitled?s.jsxs(s.Fragment,{children:[" ",s.jsx(Ex,{tone:"muted",size:"sm",className:"mc_untitled",title:"No title on the wire yet: the workflow id stands in",children:"untitled"})]}):null]}):s.jsxs("span",{className:"mc_card_title",title:Kp(t),children:[t.title.text,t.title.untitled?s.jsxs(s.Fragment,{children:[" ",s.jsx(Ex,{tone:"muted",size:"sm",className:"mc_untitled",title:"No title on the wire yet: the workflow id stands in",children:"untitled"})]}):null]}),s.jsx("span",{className:`mc_status ${_a(u)}`,children:u==="unknown"?"?":u})]}),(c.label||c.secondary||t.archived)&&!(m&&!c.label&&!t.archived&&t.chain[0]&&(c.secondary===t.chain[0].name||c.secondary===ni(t.workflow_id)))?s.jsxs("div",{className:"mc_card_subject",children:[c.label?s.jsx("span",{className:"mc_subject_label",title:c.label,children:c.label}):null,c.secondary?s.jsx("span",{className:"mc_subject_secondary",title:c.secondary,children:c.secondary}):null,t.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]}):null,d?s.jsx(CB,{...e}):m?s.jsx(OB,{...e,on_cancel_task:A?()=>r({type:"ask"}):void 0}):S?s.jsx(sh,{what:"the answer"}):w?s.jsx(vp,{kind:"answer",text:w.text,full:w.full,about:t.title.text,on_open:()=>e.on_open_run(t.run_id),children:s.jsx(xi,{text:w.text,images:"link",className:"mc_glimpse_md"})}):s.jsxs("div",{className:"mc_card_state",children:[s.jsx(uB,{card:t,on_open_run:e.on_open_run}),k?s.jsxs("span",{className:"mc_state_text",title:t.line.text,children:[k.who?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mc_who",title:`Started by ${k.who}`,children:k.who})," · "]}):null,k.text]}):s.jsx("span",{className:"mc_state_text",title:t.failed&&t.error?t.error:t.line.text!==t.line.brief?t.line.text:void 0,children:t.line.text}),t.line.stalled?s.jsx("span",{className:"mc_stall",role:"img","aria-label":"no progress",title:`No ledger step for ${Qs(t.line.stale_ms??0)}: past the ${Y1(e.stall_after_ms)} threshold set in the Working lane's head`,children:" ⚠"}):null,t.line.action==="inspect"?s.jsxs(s.Fragment,{children:[" ",s.jsx("button",{type:"button",className:"mc_inspect",onClick:T=>{T.stopPropagation(),e.on_open_run(t.run_id)},onKeyDown:Os,children:"Inspect →"})]}):null]}),b?s.jsx(sh,{what:"the request"}):y?s.jsx(vp,{kind:"request",text:y.text,full:y.full,about:t.title.text,on_open:()=>e.on_open_run(t.run_id),children:y.text}):null,h&&t.line.stuck?s.jsx(u$,{run_id:t.run_id,name:dg(t.workflow_id)||Hd(t.run_id),facts:t.line.stuck_facts,since_ms:t.since_ms,now_ms:e.now_ms,on_open_run:e.on_open_run,on_cancel_task:A?()=>r({type:"ask"}):void 0}):h?s.jsx(c$,{...e}):null,q?null:I,D?s.jsxs("div",{className:"mc_card_notice",onClick:Os,onKeyDown:Os,children:[ax({state:n,on_event:r,on_send:()=>void z(),question:r$(E,t.run_id)}),i.error?s.jsx("div",{className:"mc_act_error",role:"alert",children:i.error}):null]}):null,s.jsxs("div",{className:`mc_card_foot${d?" mc_auto_foot":""}`,onClick:Os,onKeyDown:Os,children:[d&&M?s.jsxs(s.Fragment,{children:[s.jsx(zy,{state:e.on_open_automation?AB:{enabled:!1,reason:"not available here"},label:"Open automation",hint:"Open this automation on the Automations page",icon:"loop",onClick:()=>{var T;return(T=e.on_open_automation)==null?void 0:T.call(e,t.automation_id)}}),s.jsx(zy,{state:e.on_automation_command?M.run_now:Ck,label:"Run now",icon:"playCircle",busy:i.busy==="automation.run_now",onClick:()=>F("automation.run_now")}),s.jsx(zy,{state:e.on_automation_command?M.toggle.state:Ck,label:M.toggle.label,icon:M.toggle.command==="automation.resume"?"play":"pause",busy:i.busy===M.toggle.command,onClick:()=>F(M.toggle.command)})]}):s.jsxs(s.Fragment,{children:[p?s.jsx(i$,{card:t,code_app:e.code_app,variant:"icon"}):null,A?n.phase==="idle"?o$({on_event:r,variant:"icon"}):s.jsx("span",{className:"mc_btn_wrap",title:n.phase==="sent"?"cancel requested":"Cancel this task? Answer just above",children:s.jsx("button",{type:"button",className:"btn mc_icon_btn mc_cancel is_active",disabled:!0,"aria-label":"Cancel this task",children:s.jsx(Xe,{name:"x",size:15})})}):null]}),q?I:s.jsx("span",{className:"mc_spacer"}),d?null:s.jsx(sx,{text:t.run_id,label:"the run id",title:t.run_id}),s.jsx(NB,{card:t,now_ms:e.now_ms,stall_after_ms:e.stall_after_ms,revision:e.revision,detail:e.detail,outcome:e.outcome,facts:e.facts,code_app:e.code_app,on_open_run:e.on_open_run,on_open_automation:e.on_open_automation,on_rename_automation:e.on_rename_automation,on_renamed:e.on_renamed,on_cancel_run:e.on_cancel_run,on_cancel_runs:e.on_cancel_runs,cancel_targets:e.cancel_targets})]})]})}const Ek=new WeakMap;let Ak=0;function DB(e){if(!e||typeof e!="object")return String(e??"");let t=Ek.get(e);return t===void 0&&(Ak+=1,t=Ak,Ek.set(e,t)),`#${t}`}function FB(e){try{return JSON.stringify(e)??""}catch{return String(e)}}function zB(e,t){const n=e.line,r=e.row||{},i=e.role==="controller"&&e.automation?t$(e.automation,t):null;return[e.run_id,e.lane,e.status_word,e.role,e.workflow_id,e.wait_key,e.prompt,e.allow_free_text,e.failed,e.error,e.paused,e.archived,e.automation_id,e.actor_run_label,e.task,e.title.text,e.title.untitled,e.title.source,Kp(e),e.subject.kind,e.subject.glyph,e.subject.label,e.subject.secondary,n.text,n.brief,n.verb,n.action,n.actor,n.actor_run_id,n.object,n.stalled,n.unresolved,typeof n.stale_ms=="number"?Qs(n.stale_ms):"",e.tool_names.join(","),FB(e.pending_calls),e.blocks.map(a=>`${a.run_id}:${a.title}`).join("|"),e.chain.map(a=>`${a.run_id}:${a.depth}:${a.words}:${a.stuck}:${a.asks}:${a.running}`).join("|"),e.asks.map(a=>ev(a,t)).join("|"),String(e.stuck),e.since_ms,e.next_fire_ms,e$(e).join("·"),e.llm_calls,r.session_id,r.actor_id,r.pause_reason,r.created_at,r.updated_at,r.status,DB(e.automation),e.lane==="needs_you"?tx(e,t).text:"",i?`${i.schedule.text}|${i.schedule.title}|${i.last.text}|${i.last.title}`:""].join("")}const Tk=new WeakMap;function ev(e,t){const n=Tk.get(e);if(n&&n.now_ms===t)return n.sig;const r=zB(e,t);return Tk.set(e,{now_ms:t,sig:r}),r}function BB(e,t){const n=new Set([...Object.keys(e),...Object.keys(t)]);for(const r of n)if(!(r==="card"||r==="now_ms")){if(r==="ask_detail"){const i=e[r]||{},a=t[r]||{},u=Object.keys(i),c=Object.keys(a);if(u.length!==c.length||u.some(d=>!Object.is(i[d],a[d])))return!1;continue}if(!Object.is(e[r],t[r]))return!1}return e.card===t.card&&e.now_ms===t.now_ms?!0:ev(e.card,e.now_ms)===ev(t.card,t.now_ms)}const UB=Ne.memo(PB,BB),By=8;function WB(e){var Nt,ut,Se,me,Ve,ye,Ie,ct;(Nt=Ja.page)==null||Nt.call(Ja);const t=Date.now(),[n,r]=_.useState(()=>J1(wz())),i=_.useMemo(()=>yz(e.runs,e.all_runs),[e.runs,e.all_runs]),a=_.useMemo(()=>[...i.active,...i.done],[i]),u=B8(e.client,a),c=W8(e.client,i.active),d=Q8(),m=_.useMemo(()=>Object.fromEntries(np.map(ie=>[ie,Te=>d.attach(ie,Te)])),[d.attach]),[h,p]=_.useState(""),[y,w]=_.useState(""),[x,k]=_.useState(!1),[b,S]=_.useState(()=>{try{const ie=localStorage.getItem("abstractobserver_done_window_v1");return ie&&ie in Zw?ie:kk}catch{return kk}}),$=_.useMemo(()=>wk({active:i.active,done:i.done,pulses:c.map,automations:u.map,now_ms:Date.now(),stall_after_ms:n}),[i,c.map,u.map,n]),A=_.useMemo(()=>jk($.done,b,Date.now()).visible,[$,b]),E=_.useMemo(()=>(x?A:A.slice(0,By)).map(ie=>ie.row),[A,x]),z=_.useMemo(()=>uk(np.map(ie=>ie==="done"?E:$[ie].flatMap(Te=>[Te.row,...Te.asks.map(et=>et.row)])),d.visible),[$,E,d.visible]),F=H8(e.client,z,i.active),M=_.useMemo(()=>new Set(i.active.map(ie=>Zs(ie))),[i.active]),D=V8(e.client,F.map,M),H=U8(e.client,z),q=_.useMemo(()=>uk([E],d.visible),[E,d.visible]),I=Z8(e.client,q),Z=_.useRef(new WeakMap),R=_.useMemo(()=>{const ie=new Map;for(const[Te,et]of u.records){const Ge=et.raw&&typeof et.raw=="object"?et.raw:null;let Be=Ge?Z.current.get(Ge):void 0;Be||(Be=z8(et.raw),Ge&&Z.current.set(Ge,Be)),ie.set(Te,Be)}return ie},[u.records]),T=_.useMemo(()=>H.map.size||F.map.size?wk({active:i.active,done:i.done,details:F.map,fates:D.map,pulses:c.map,automations:u.map,run_briefs:H.map,now_ms:Date.now(),stall_after_ms:n}):$,[$,H.map,i,F.map,c.map,u.map,n]),P=_.useMemo(()=>jk(T.done,b,t),[T.done,b]),L=np.map(ie=>T[ie].map(Te=>[Te.run_id,...Te.asks.map(et=>et.run_id)].join("+")).join(",")).join("|")+`|${x}|${b}`;_.useEffect(()=>{d.refresh()},[L,d.refresh]);const[te,X]=_.useState(""),[V,ne]=_.useState(null),W=e.entities===null,Y=e.entities??[],K=ie=>`${ie.run_id}:${ie.wait_key}:${ie.since_ms??""}`;_.useEffect(()=>{h&&(T.needs_you.some(ie=>K(ie)===h||ie.asks.some(Te=>K(Te)===h))||p(""))},[T,h]);async function fe(ie,Te){p(K(ie)),w("");try{await e.on_resume_wait(ie.run_id,ie.wait_key,Te)}catch(et){w(`${ie.title.text}: ${String((et==null?void 0:et.message)||et||"resume failed")}`),p("")}}async function ae(ie){if(e.on_resume_run){p(K(ie)),w("");try{const Te=await e.on_resume_run(ie.run_id);if(typeof Te=="string"&&Te)throw new Error(Te)}catch(Te){w(`${ie.title.text}: ${String((Te==null?void 0:Te.message)||Te||"resume failed")}`),p("")}}}const ve=_.useRef(e);ve.current=e;const ge=_.useRef(fe);ge.current=fe;const pe=_.useRef(ae);pe.current=ae;const $e=_.useRef(i.active);$e.current=i.active;const De=_.useMemo(()=>({open_run:ie=>ve.current.on_open_run(ie),open_automation:ie=>ve.current.on_open_automation(ie),rename:((ie,Te,et)=>ve.current.on_rename_automation(ie,Te,et)),revise:((ie,Te,et)=>ve.current.on_revise_automation(ie,Te,et)),command:((ie,Te)=>ve.current.on_automation_command(ie,Te)),cancel:(ie=>ve.current.on_cancel_run(ie)),cancel_batch:((ie,Te)=>ve.current.on_cancel_runs(ie,Te)),cancel_targets:ie=>Nk([ie],$e.current),act:(ie,Te)=>void ge.current(ie,Te),resume:ie=>void pe.current(ie)}),[]),ot=String(((ut=e.code_app)==null?void 0:ut.url)||"").trim(),bt=_.useMemo(()=>ot?{url:ot}:null,[ot]),Ue=_.useMemo(()=>ie=>{u.invalidate(ie),window.setTimeout(()=>u.invalidate(ie),2e3)},[u.invalidate]),at=ie=>({now_ms:t,stall_after_ms:n,busy:h===K(ie),on_open_run:De.open_run,on_act:De.act,on_resume:e.on_resume_run?De.resume:void 0,on_open_automation:De.open_automation,on_rename_automation:e.on_rename_automation?De.rename:void 0,on_renamed:Ue,revision:ie.automation_id?u.revisions.get(ie.automation_id)??null:null,detail:F.map.get(ie.run_id),outcome:I.map.get(ie.run_id)??null,facts:ie.automation_id?R.get(ie.automation_id)??null:null,code_app:bt,on_cancel_run:e.on_cancel_run?De.cancel:void 0,on_cancel_runs:e.on_cancel_runs?De.cancel_batch:void 0,cancel_targets:De.cancel_targets,ask_detail:ie.asks.length?Object.fromEntries(ie.asks.map(Te=>[Te.run_id,F.map.get(Te.run_id)])):void 0,ask_loading:ie.asks.length?ie.asks.filter(Te=>F.loading.has(Te.run_id)).map(Te=>Te.run_id).join(","):void 0,busy_wait:ie.asks.length?h:void 0,stale:e.runs_stale===!0?!0:void 0,on_automation_command:e.on_automation_command?De.command:void 0,on_revise_automation:e.on_revise_automation?De.revise:void 0,detail_loading:F.loading.has(ie.run_id),brief_loading:H.loading.has(ie.run_id),outcome_loading:I.loading.has(ie.run_id),automation_loading:ie.automation_id?u.loading.has(ie.automation_id):!1});return s.jsxs("div",{className:"page page_scroll mc_page",children:[y?s.jsx("div",{className:"mc_error",children:y}):null,s.jsxs("div",{className:!W&&!Y.length?Qz:Zz,"aria-busy":W||void 0,children:[s.jsxs("div",{className:"mc_entities_head",children:[s.jsxs("span",{children:["Entities",!W&&e.entities_total>Y.length?` (${Y.length} of ${e.entities_total} — open the entity app for all)`:"",!W&&!Y.length?s.jsx("span",{className:"muted mc_entities_none",children:" — no entities"}):null]}),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,W?s.jsxs("div",{className:"mc_entities_row",role:"status","aria-label":"loading entities",children:[s.jsx(nc,{what:"entities"}),s.jsx(tB,{n:e.entities_total?Math.min(e.entities_total,n$):eB})]}):null,Y.length?s.jsx("div",{className:"mc_entities_row",children:Y.map(ie=>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(ie.name)}&live=1`,target:"_blank",rel:"noreferrer",title:[ie.error,ie.age_days!==null?`${ie.age_days.toFixed(0)} days old`:"",ie.last_moment].filter(Boolean).join(" — ")||ie.name,children:[s.jsx("span",{className:"mc_entity_name",children:ie.name}),(()=>{var Qt;const Te=String(ie.live_phase||ie.state||"").trim(),et=Vz(Te,e.phase_graph),Ge=Jz(e.phase_graph).has(et)?et:"other",Be=((Qt=e.phase_graph)==null?void 0:Qt.initial)??"sleep",Rt=/awake|idle/i.test(Te)&&et===Be,Nn=Te&&Te.toLowerCase()!==et?` — wire word: ${Te}${Rt?" (settling)":""}`:"";return s.jsx("span",{className:`mc_entity_phase mc_phase_${Ge}`,title:(ie.live_phase?"phase (cognition wire)":"phase from card state — cognition wire unavailable")+Nn,children:et})})(),ie.last_moment?s.jsx("span",{className:"mc_entity_moment",title:ie.last_moment,children:ie.last_moment.replace(/_/g," ")}):null,(()=>{if(ie.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 Te=zz(ie.last_moment_at,t);return ie.working===!1?s.jsxs("span",{className:"mc_entity_live muted",title:"idle (cognition wire)",children:["idle",Te!==null?` · ${Dy(t-Te,t)} ago`:""]}):Te===null?null:Te<=Bz?s.jsx("span",{className:"mc_entity_live",title:`last moment ${Dy(t-Te,t)} ago`,children:"● active"}):s.jsxs("span",{className:"mc_entity_live muted",title:"time since the last recorded moment",children:[Dy(t-Te,t)," ago"]})})(),ie.tokens_total!==null?s.jsxs("span",{className:"muted mc_entity_spend",title:`lifetime billed tokens (home run ledger)${ie.live_visit_tokens!==null?`; open visit: ${Ql(ie.live_visit_tokens)} tk`:""}${ie.spend_warning?`; ${ie.spend_warning}`:""}`,children:[Ql(ie.tokens_total)," tk",ie.live_visit_tokens!==null?` (+${Ql(ie.live_visit_tokens)})`:"",ie.spend_warning?"*":""]}):null]}),ie.open_questions_total||ie.open_problems_total||ie.lessons_total||ie.dreams_brief?s.jsx("button",{type:"button",className:"mc_entity_hints_btn","aria-expanded":te===ie.name,title:"open questions / problems + distilled lessons + night signals from the entity card — click to expand",onClick:()=>X(te===ie.name?"":ie.name),children:[ie.open_questions_total?`${ie.open_questions_total} question${ie.open_questions_total>1?"s":""}`:"",ie.open_problems_total?`${ie.open_problems_total} problem${ie.open_problems_total>1?"s":""}`:"",ie.lessons_total?`${ie.lessons_total} lesson${ie.lessons_total>1?"s":""}`:"",ie.dreams_brief?`night: ${ie.dreams_brief.count} signal${ie.dreams_brief.count>1?"s":""}`:""].filter(Boolean).join(" · ")}):null]},ie.name))}):null,(()=>{if(!te)return null;const ie=Y.find(Ge=>Ge.name===te);if(!ie||!ie.open_questions.length&&!ie.open_problems.length&&!ie.lessons.length&&!ie.dreams_brief)return null;const Te=e.on_read_diary?async Ge=>{const Be=await e.on_read_diary(ie.name,Ge);ne({entity:ie.name,entry:(Be==null?void 0:Be.entry)??Be,seq:typeof(Be==null?void 0:Be.read_recorded_at_seq)=="number"?Be.read_recorded_at_seq:null})}:void 0,et=ie.open_questions_total-ie.open_questions.length+(ie.open_problems_total-ie.open_problems.length)+(ie.lessons_total-ie.lessons.length);return s.jsxs("div",{className:"mc_entity_hints_panel",children:[ie.open_questions.map((Ge,Be)=>s.jsx(Hg,{kind:"question",label:Ge.title||Fy(Ge.statement),entryId:Ge.entry_id,onOpen:Te,title:Ge.statement||Ge.title},`q_${Ge.record_id||Be}`)),ie.open_problems.map((Ge,Be)=>s.jsx(Hg,{kind:"problem",label:Ge.title||Fy(Ge.statement),entryId:Ge.entry_id,onOpen:Te,title:Ge.statement||Ge.title},`p_${Ge.record_id||Be}`)),ie.lessons.map((Ge,Be)=>s.jsx(Hg,{kind:"lesson",label:Ge.title||Fy(Ge.statement),entryId:Ge.entry_id,onOpen:Te,title:Ge.statement||Ge.title},`l_${Ge.record_id||Be}`)),ie.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: ",ie.dreams_brief.count,ie.dreams_brief.dreams?` across ${ie.dreams_brief.dreams} dream${ie.dreams_brief.dreams>1?"s":""}`:"",ie.dreams_brief.kinds.length?` — ${ie.dreams_brief.kinds.slice(0,6).join(", ")}${ie.dreams_brief.kinds.length>6?` +${ie.dreams_brief.kinds.length-6} more`:""}`:"",ie.dreams_brief.felt_tones.length?` · felt: ${ie.dreams_brief.felt_tones.slice(0,6).join(", ")}`:""]}):null,et>0?s.jsxs("span",{className:"muted mc_entity_hints_more",children:["+",et," more — open the entity app"]}):null]})})()]}),V?s.jsx(Kl,{open:!0,title:`${V.entity} — diary entry`,onClose:()=>ne(null),children:s.jsxs("div",{className:"mc_diary_entry",children:[s.jsx("div",{className:"mc_diary_meta muted",children:[(Se=V.entry)!=null&&Se.kind?`kind: ${V.entry.kind}`:"",(me=V.entry)!=null&&me.visibility?`visibility: ${V.entry.visibility}`:"",(Ve=V.entry)!=null&&Ve.written_at?`written: ${V.entry.written_at}`:"",(ye=V.entry)!=null&&ye.entry_id?`id: ${V.entry.entry_id}`:""].filter(Boolean).join(" · ")}),s.jsxs("div",{className:"mc_diary_recorded muted",children:["this read was recorded in ",V.entity,"’s stream",V.seq!==null?` (seq ${V.seq})`:""]}),(Ie=V.entry)!=null&&Ie.gist?s.jsx("div",{className:"mc_diary_gist",children:String(V.entry.gist)}):null,s.jsx("pre",{className:"mc_diary_text",children:String(((ct=V.entry)==null?void 0:ct.text)||"(entry carries no text)")})]})}):null,!e.gateway_connected||e.runs_refreshed_at===null||e.runs_stale||e.notice?s.jsxs("div",{className:"mc_status_line",children:[e.gateway_connected?e.runs_refreshed_at===null?s.jsx("span",{className:"mc_notice mc_loading",role:"status",children:"loading runs…"}):e.runs_stale?s.jsxs("span",{className:"mc_notice mc_loading",role:"status",children:["board as of ",pz(e.runs_refreshed_at)," — refreshing…"]}):null:s.jsx("span",{className:"mc_notice is_bad",role:"status",children:"gateway unreachable: the lanes show the last runs read"}),e.gateway_connected&&e.notice?s.jsx("span",{className:"mc_notice is_bad",role:"status",children:e.notice}):null]}):null,s.jsx("div",{className:"mc_board",children:np.map(ie=>{const Te=ie==="done"?P.visible:T[ie],et=ie==="done"&&!x?Te.slice(0,By):Te,Ge=e.runs_refreshed_at===null||ie==="done"&&e.done_loaded===!1;return s.jsxs(lB,{col:ie,title:G1[ie],count:Ge?null:Te.length,count_title:ie==="done"&&P.hidden_count?`${P.hidden_count} older run(s) outside this window`:ie==="needs_you"&&Te.length?`${Te.length} task${Te.length===1?"":"s"} · ${Te.reduce((Be,Rt)=>Be+(Rt.asks.length||(Rt.line.lane==="needs_you"&&!Rt.stuck?1:0)),0)} asks`:void 0,cancel:{run_ids:Te.map(Be=>Be.run_id),targets:Nk(Te.map(Be=>Be.run_id),i.active),on_cancel_run:e.on_cancel_run,on_cancel_runs:e.on_cancel_runs},after:ie==="working"?s.jsxs("label",{className:"mc_stall_control",title:"No progress after: a running card whose last ledger step is older than this gets the mark ⚠ and floats to the top of Working",children:[s.jsxs("span",{className:"mc_stall_word","aria-hidden":"true",children:[s.jsx("span",{className:"mc_stall_mark",children:"⚠"})," after"]}),s.jsx("select",{className:"mc_window_select mc_stall_select","aria-label":"no progress after",value:String(n),onChange:Be=>{const Rt=Number(Be.target.value);r(Rt);try{localStorage.setItem(K1,String(Rt))}catch{}},children:ex.map(Be=>s.jsx("option",{value:String(Be.ms),children:Be.label},Be.ms))})]}):null,tools:ie==="done"?s.jsx("select",{className:"mc_window_select",value:b,title:"Show terminal runs from this time window",onClick:Be=>Be.stopPropagation(),onChange:Be=>{const Rt=Be.target.value;S(Rt),k(!1);try{localStorage.setItem("abstractobserver_done_window_v1",Rt)}catch{}},children:Object.keys(Zw).map(Be=>s.jsx("option",{value:Be,children:Oy[Be]},Be))}):null,children:[s.jsx("div",{className:"mc_column_hint muted",children:dz[ie]}),s.jsxs("div",{className:"mc_column_cards",ref:m[ie],"aria-busy":Ge||void 0,children:[Ge&&!et.length?s.jsxs(s.Fragment,{children:[s.jsx(nc,{what:ie==="done"&&e.runs_refreshed_at!==null?"finished runs":"runs"}),s.jsx(Xz,{n:Yz[ie]})]}):null,et.map(Be=>s.jsx(UB,{card:Be,...at(Be)},Be.run_id)),!Te.length&&!Ge?s.jsx("div",{className:"mc_empty muted",children:ie==="done"&&P.hidden_count?`none in the ${Oy[b]} — ${P.hidden_count} older`:fz[ie]}):null,ie==="done"&&Te.length>By&&!x?s.jsxs("button",{className:"btn mc_more",onClick:()=>k(!0),children:["show all ",Te.length]}):null,ie==="done"&&P.hidden_count&&Te.length?s.jsxs("div",{className:"mc_window_note muted",title:"Widen the window above to see older terminal runs",children:["+",P.hidden_count," older outside ",Oy[b]]}):null]})]},ie)})})]})}function xt(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function qt(e){return typeof e=="string"?e.trim():""}function Bn(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function xp(e){return typeof e=="boolean"?e:null}function ei(e){return Array.isArray(e)?e.map(t=>typeof t=="string"?t.trim():String(t??"").trim()).filter(Boolean):null}function Mk(e){return typeof e=="string"?e.split(/\r?\n/).map(t=>t.trim()).filter(Boolean):ei(e)}function su(e,t){return!!e&&Object.prototype.hasOwnProperty.call(e,t)}function ss(e){return Math.round(e).toLocaleString("en-US")}function d$(e){const t=xt(e);return!!t&&(su(t,"definition")||su(t,"summary"))}function qB(e,t,n){var b,S,$,A;const r=xt((b=xt(t))==null?void 0:b.input_data),i=xt((S=xt(t))==null?void 0:S.workspace),a=d$(n)?n:null,u=a?_h(a):n??null,c=xt(a==null?void 0:a.definition),d=xt(($=xt(c==null?void 0:c.target))==null?void 0:$.input_data),m=xt(d==null?void 0:d._runtime),h=xt(c==null?void 0:c.policy),p={},y=(E,...z)=>{for(const[F,M]of z){const D=qt(M);if(D)return p[E]=F,D}return p[E]="",""},w=(E,z,...F)=>{for(const[M,D]of F){const H=z(D);if(H!==null)return p[E]=M,H}return p[E]="",[]},x=(E,...z)=>{for(const[F,M]of z){const D=Bn(M);if(D!==null)return p[E]=F,D}return p[E]="",null},k=E=>E&&E.length?E:null;return{model:y("model",["run",r==null?void 0:r.model],["automation",d==null?void 0:d.model],["automation",u==null?void 0:u.model]),provider:y("provider",["run",r==null?void 0:r.provider],["automation",d==null?void 0:d.provider],["automation",u==null?void 0:u.provider]),tools:w("tools",ei,["run",r==null?void 0:r.tools],["automation",d==null?void 0:d.tools],["automation",k(u==null?void 0:u.tools)]),tool_approval:y("tool_approval",["automation",h==null?void 0:h.tool_approval],["automation",u==null?void 0:u.tool_approval]),workspace_access_mode:y("workspace_access_mode",["run",i==null?void 0:i.workspace_access_mode],["run",r==null?void 0:r.workspace_access_mode],["automation",d==null?void 0:d.workspace_access_mode]),workspace_root:y("workspace_root",["run",(A=xt(e))==null?void 0:A.workspace_root],["run",i==null?void 0:i.workspace_root],["run",r==null?void 0:r.workspace_root],["automation",u==null?void 0:u.workspace_root],["automation",d==null?void 0:d.workspace_root]),workspace_allowed_paths:w("workspace_allowed_paths",Mk,["run",i==null?void 0:i.workspace_allowed_paths],["automation",d==null?void 0:d.workspace_allowed_paths]),workspace_ignored_paths:w("workspace_ignored_paths",Mk,["run",i==null?void 0:i.workspace_ignored_paths],["automation",d==null?void 0:d.workspace_ignored_paths]),allowed_tools:w("allowed_tools",ei,["automation",m==null?void 0:m.allowed_tools]),max_iterations:x("max_iterations",["run",r==null?void 0:r.max_iterations],["automation",d==null?void 0:d.max_iterations],["automation",u==null?void 0:u.max_iterations]),untrusted_input_tools:w("untrusted_input_tools",ei,["automation",h==null?void 0:h.untrusted_input_tools]),email_allowed_recipients:w("email_allowed_recipients",ei,["automation",h==null?void 0:h.email_allowed_recipients]),source:p}}function f$(e){const t=xt(e);if(!t)return null;if(Array.isArray(t.nodes))return t;const n=xt(t.flow);return n&&Array.isArray(n.nodes)?n:null}function tv(e){const t=xt(e==null?void 0:e.data)||{};return qt(t.nodeType)||qt(e==null?void 0:e.type)}const HB=new Set(["exec-out","exec-in","exec"]);function nv(e,t){const n=xt(e==null?void 0:e.data)||{};return(Array.isArray(n[t])&&n[t].length?n[t]:Array.isArray(e==null?void 0:e[t])?e[t]:[]).filter(i=>{const a=xt(i);if(!a)return!1;const u=qt(a.id);return!!u&&qt(a.type)!=="execution"&&!HB.has(u)})}function Rk(e,t,n,r){const i=qt(e.id),a=qt(e.type)||"any";return{id:i,label:qt(e.label)||i,type:a,typed:!0,required:e.required===!0,description:qt(e.description),state:t,value:n,flow_default:r}}function Lk(e,t,n){return{id:e,label:e,type:"any",typed:!1,required:!1,description:"",state:t,value:n,flow_default:null}}function VB(e,t,n){var M;const r=f$(e),i=r?r.nodes:[],a=i.find(D=>tv(D)==="on_flow_start")||null,u=i.filter(D=>tv(D)==="on_flow_end"),c=xt(t),d=xt(c==null?void 0:c.input_data),m=xt((M=xt(a==null?void 0:a.data))==null?void 0:M.pinDefaults)||{},h=[],p=new Set,y=D=>d?su(d,D)?{state:"value",value:d[D]}:{state:"not_provided",value:void 0}:{state:"unknown",value:void 0};for(const D of a?nv(a,"outputs"):[]){const H=qt(D.id);if(p.has(H))continue;p.add(H);const{state:q,value:I}=y(H),Z=q==="not_provided"&&su(m,H)?{value:m[H]}:null;h.push(Rk(D,q,I,Z))}for(const D of Array.isArray(c==null?void 0:c.pin_ids)?c.pin_ids:[]){const H=qt(D);if(!H||p.has(H))continue;p.add(H);const{state:q,value:I}=y(H);h.push(Lk(H,q,I))}const w=d?Object.keys(d).filter(D=>!p.has(D)).map(D=>[D,d[D]]):[],x=xt(n),k=!!x&&ds(x.status),b=x?x.output:void 0,S=xt(b),$=D=>x?S&&su(S,D)?{state:"value",value:S[D]}:{state:"absent",value:void 0}:{state:"unknown",value:void 0},A=[],E=new Set;for(const D of u)for(const H of nv(D,"inputs")){const q=qt(H.id);if(E.has(q))continue;E.add(q);const{state:I,value:Z}=$(q);A.push(Rk(H,I,Z,null))}const z=u.length>0&&E.size===0;let F=[];if(z){const D=!!x&&b!==null&&b!==void 0;A.push(Lk("output",x?D?"value":"absent":"unknown",D?b:void 0))}else S?F=Object.keys(S).filter(D=>!E.has(D)).map(D=>[D,S[D]]):x&&b!==null&&b!==void 0&&(F=[["output",b]]);return{inputs:h,outputs:A,also_sent:w,also_returned:F,end_is_passthrough:z,flow_found:!!r,start_found:!!a,end_found:u.length>0,outputs_final:k}}function Uy(e,t,n=`${t}s`){return e===1?t:n}function GB(e){const t=[],n=e.dropped_counts_complete!==!1;if(e.replayed_messages!==null){const r=e.dropped_messages!==null&&n?e.replayed_messages+e.dropped_messages:null;let i=r!==null?`replayed ${ss(e.replayed_messages)} of ${ss(r)} ${Uy(r,"message")}`:`replayed ${ss(e.replayed_messages)} ${Uy(e.replayed_messages,"message")}`;e.replayed_tokens!==null?i+=` (${ss(e.replayed_tokens)}${e.max_tokens!==null?` of ${ss(e.max_tokens)}`:""} tokens)`:e.max_tokens!==null&&(i+=` (budget ${ss(e.max_tokens)} tokens)`),t.push(i)}else e.max_tokens!==null&&t.push(`history budget ${ss(e.max_tokens)} tokens`);if(e.dropped_messages!==null)if(e.dropped_messages>0){const r=e.dropped_tokens!==null&&e.dropped_tokens>0?` (${ss(e.dropped_tokens)} tokens)`:"";t.push(`${n?"":"at least "}${ss(e.dropped_messages)} older ${Uy(e.dropped_messages,"message")} left out${r}`)}else t.push(n?"nothing left out":"left-out count incomplete");else e.dropped_counts_complete===!1&&t.push("left-out count incomplete");return e.oversize_turn_kept===!0&&t.push("the newest turn alone exceeds the budget and was kept whole"),t.join("; ")}function sv(e){var c;const t=xt(e),n=xt(t==null?void 0:t.session_history),r=xt((c=xt(t==null?void 0:t.limits))==null?void 0:c.tokens);let i=null;if(r){const d=Bn(r.estimated_used),m=Bn(r.max_tokens),h=Bn(r.max_input_tokens),p=h??m,y=Bn(r.pct),w=y!==null?y*100:d!==null&&p!==null&&p>0?d/p*100:null,x=Bn(r.warn_tokens_pct);i={used:d,max_tokens:m,max_input_tokens:h,budget:p,pct:w,warn_pct:x,over_warn:w!==null&&x!==null&&w>=x}}const a=(ei(t==null?void 0:t.flow_warnings)||[]).filter(Boolean),u={replayed_messages:Bn(n==null?void 0:n.replayed_messages),replayed_tokens:Bn(n==null?void 0:n.replayed_tokens),max_tokens:Bn(n==null?void 0:n.max_tokens),dropped_messages:Bn(n==null?void 0:n.dropped_messages),dropped_tokens:Bn(n==null?void 0:n.dropped_tokens),dropped_counts_complete:xp(n==null?void 0:n.dropped_counts_complete),oversize_turn_kept:xp(n==null?void 0:n.oversize_turn_kept)};return{has_history:!!n,policy:qt(n==null?void 0:n.policy),...u,strict:xp(n==null?void 0:n.strict),token_estimator:qt(n==null?void 0:n.token_estimator),session_kind:qt(n==null?void 0:n.session_kind),tokens:i,flow_warnings:a,window_note:n?GB(u):""}}const KB=16;function wi(e){return String((e==null?void 0:e.run_id)||"").trim()}function rv(e){return String((e==null?void 0:e.role)||"").trim()}function Ik(e){return It(e.created_at||e.updated_at||"")??0}function JB(e,t){const n=String(e||"").trim();let r=t.get(n);if(!r)return n;const i=new Set;for(;r;){const a=wi(r);if(i.add(a),rv(r)==="occurrence")return a;const u=String(r.parent_run_id||"").trim(),c=u?t.get(u):void 0;if(!c||i.has(u)||rv(c)==="controller")return a;r=c}return n}function m$(e,t){const n=String(e||"").trim(),r=new Map,i=new Map;for(const w of t||[]){const x=wi(w);x&&r.set(x,w)}for(const w of r.values()){const x=String(w.parent_run_id||"").trim();if(!x||x===wi(w))continue;const k=i.get(x)||[];k.push(w),i.set(x,k)}if(!r.has(n))return{subject_id:n,root:null,controller:null,controller_id:"",subject_found:!1,size:0};const a=JB(n,r),u=r.get(a);let c=0;const d=new Set,m=(w,x)=>{const k=wi(w);d.add(k),c+=1;const b=x<KB?[...i.get(k)||[]].filter(S=>!d.has(wi(S))):[];return b.sort((S,$)=>Ik(S)-Ik($)||wi(S).localeCompare(wi($))),{run:w,depth:x,is_subject:k===n,children:b.map(S=>m(S,x+1))}},h=m(u,0);let p=null,y="";return rv(u)==="occurrence"&&(y=String(u.parent_run_id||u.automation_id||"").trim(),p=y&&r.get(y)||null),{subject_id:n,root:h,controller:p,controller_id:y,subject_found:!0,size:c}}function h$(e){const t=[],n=r=>{t.push(r);for(const i of r.children)n(i)};return e&&n(e),t}function YB(e,t,n=Date.now()){const r=e&&"children"in e?e:(e==null?void 0:e.root)??null,i=new Map;for(const u of t||[]){const c=wi(u);c&&i.set(c,u)}const a=h$(r).map(u=>{const c=wi(u.run),d=i.get(c)??u.run,m=Bn(d==null?void 0:d.tokens_total),h=Bn(d==null?void 0:d.llm_calls),p=Bn(d==null?void 0:d.tool_calls),y=Bn(d==null?void 0:d.steps),w=mh(u.run,n),x=String(u.run.status||"").trim().toLowerCase();return{run_id:c,depth:u.depth,workflow_id:String(u.run.workflow_id||"").trim(),status:x,is_subject:u.is_subject,duration_ms:w>=0?w:null,running:!ds(x),tokens_total:m,llm_calls:h,tool_calls:p,steps:y,has_metrics:m!==null||h!==null||p!==null||y!==null,inclusive:!0}});return{rows:a,inclusive:!0,any_metrics:a.some(u=>u.has_metrics)}}function un(e,t){return{value:e,source:t,why:""}}function Xn(e,t=""){return{value:null,source:t,why:e}}const Is={wire:"not on this wire",no_default:"not provided, no default",not_automation:"not an automation run",automation_not_loaded:"automation definition not loaded",ledger_not_loaded:"ledger not loaded here",ledger_no_records:"no ledger records for this run in what is loaded",not_ended:"the run has not ended",flow_not_loaded:"flow not loaded",gateway_default:"gateway default (not reported on this wire)"};function Nd(e){return`${new Date(e).toISOString().slice(0,19).replace("T"," ")} UTC`}function XB(e){var r,i,a,u;const t=uh(e),n=xt((a=xt((i=xt((r=e.record)==null?void 0:r.result))==null?void 0:i.metadata))==null?void 0:a._provider_request);return{provider:t.provider||qt(n==null?void 0:n.provider),model:t.model||qt(n==null?void 0:n.model)||qt((u=xt(n==null?void 0:n.payload))==null?void 0:u.model)}}function ZB(e){var u,c,d,m,h;const t=xt((c=xt((u=e.started)==null?void 0:u.effect))==null?void 0:c.payload),n=xt((m=xt((d=e.record)==null?void 0:d.effect))==null?void 0:m.payload),r=xt(t==null?void 0:t.vars)&&!((h=xt(t==null?void 0:t.vars))!=null&&h.$slim)?xt(t==null?void 0:t.vars):xt(n==null?void 0:n.vars),i=xt(r==null?void 0:r._runtime),a=xt(r==null?void 0:r._limits);return{run_id:fh(e.record),workflow_id:qt(t==null?void 0:t.workflow_id)||qt(n==null?void 0:n.workflow_id),from_run_id:e.run_id,provider:qt(i==null?void 0:i.provider),model:qt(i==null?void 0:i.model),allowed_tools:ei(i==null?void 0:i.allowed_tools),max_iterations:Bn(a==null?void 0:a.max_iterations)}}function QB(e,t,n=[]){var p,y,w,x,k,b,S;const r={loaded:Array.isArray(e),subject_found:!1,runs:[],missing_run_ids:[],llm_calls:0,tool_calls:0,tool_failures:0,models:[],tools:[],subruns:[],allowlist:null,first_ms:null,last_ms:null};if(!Array.isArray(e))return r;const i=String(t||"").trim(),a=new Set;for(const $ of e){const A=String(($==null?void 0:$.run_id)||((p=$==null?void 0:$.record)==null?void 0:p.run_id)||"").trim();A&&($!=null&&$.record)&&a.add(A)}const u=new Map,c=new Map,d=[i,...n.map($=>String($||"").trim()).filter(Boolean)],m=new Set,h=[];for(;d.length;){const $=d.shift();if(!$||m.has($))continue;if(m.add($),!a.has($)){$!==i&&h.push($);continue}$===i&&(r.subject_found=!0);const A={run_id:$,llm_calls:0,tool_calls:0,tool_failures:0,steps:0};for(const E of ag(e,$)){A.steps+=1;const z=It(E.started_at),F=It(E.ended_at);for(const M of[z,F])M!==null&&((r.first_ms===null||M<r.first_ms)&&(r.first_ms=M),(r.last_ms===null||M>r.last_ms)&&(r.last_ms=M));if(E.kind==="llm_call"){A.llm_calls+=1;const M=XB(E),D=`${M.provider}\0${M.model}`,H=u.get(D)||{provider:M.provider,model:M.model,calls:0,run_ids:[]};H.calls+=1,H.run_ids.includes($)||H.run_ids.push($),u.set(D,H)}else if(E.kind==="tool"){const M=dh(E),D=new Map;for(const q of M.calls){const I=D.get(q.name)||{calls:0,results:0,failures:0};I.calls+=1,D.set(q.name,I)}for(const q of M.results){const I=D.get(q.name)||{calls:0,results:0,failures:0};I.results+=1,q.success===!1&&(I.failures+=1),D.set(q.name,I)}for(const[q,I]of D){const Z=Math.max(I.calls,I.results);A.tool_calls+=Z,A.tool_failures+=I.failures;const R=c.get(q)||{name:q,calls:0,failures:0,run_ids:[],outside_declared:null};R.calls+=Z,R.failures+=I.failures,R.run_ids.includes($)||R.run_ids.push($),c.set(q,R)}const H=ei((x=xt((w=(y=E.started)==null?void 0:y.effect)==null?void 0:w.payload))==null?void 0:x.allowed_tools)??ei((S=xt((b=(k=E.record)==null?void 0:k.effect)==null?void 0:b.payload))==null?void 0:S.allowed_tools);H!==null&&r.allowlist===null&&(r.allowlist=H)}else if(E.kind==="subflow"){const M=ZB(E);r.subruns.push(M),M.run_id&&d.push(M.run_id)}}r.llm_calls+=A.llm_calls,r.tool_calls+=A.tool_calls,r.tool_failures+=A.tool_failures,r.runs.push(A)}return r.missing_run_ids=h,r.models=[...u.values()].sort(($,A)=>A.calls-$.calls||$.model.localeCompare(A.model)),r.tools=[...c.values()].sort(($,A)=>A.calls-$.calls||$.name.localeCompare(A.name)),r}function ip(e,t){for(const[n,r]of e)if(r!=null)return un(r,n);return Xn(t)}function bd(e){const t=qt(e);return t||null}function Uc(e,t){const n=qt(e),r=qt(t);return n||r?{provider:n,model:r,calls:null}:null}const e9=new Set(["controller","occurrence","descendant","discussion"]);function t9(e,t,n,r,i,a,u=Date.now(),c={}){var on,Ht,Ot,ts,Pe,Ut,St,Mn,nn;const d=xt(e),m=xt(t),h=xt(m==null?void 0:m.input_data),p=String(c.subject_run_id||(d==null?void 0:d.run_id)||(m==null?void 0:m.run_id)||((on=c.row)==null?void 0:on.run_id)||"").trim(),y=Array.isArray(a)?a:[],w=Je=>y.find(en=>String((en==null?void 0:en.run_id)||"").trim()===Je),x={...w(p)||{},...c.row||{}};for(const Je of["workflow_id","status","created_at","updated_at","role","occurrence_index","automation_id","parent_run_id","session_id","session_kind"])d&&d[Je]!==void 0&&d[Je]!==null&&d[Je]!==""&&(x[Je]=d[Je]);const k=d$(r)?r:null,b=k?_h(k):r??null,S=xt(k==null?void 0:k.definition),$=xt(k==null?void 0:k.summary),A=xt((Ht=xt(S==null?void 0:S.target))==null?void 0:Ht.input_data),E=xt(A==null?void 0:A._runtime),z=xt(S==null?void 0:S.policy),F=qt(x.role),M=!!qt(x.automation_id)||e9.has(F)||qt(x.session_kind)==="automation",D=M?b?Is.wire:Is.automation_not_loaded:Is.not_automation,H=f$(n),q=H&&H.nodes.find(Je=>tv(Je)==="on_flow_start")||null,I=xt((Ot=xt(q==null?void 0:q.data))==null?void 0:Ot.pinDefaults),Z=new Set(q?nv(q,"outputs").map(Je=>qt(Je.id)):[]),R=Je=>h&&su(h,Je)?void 0:I&&su(I,Je)?I[Je]:void 0,T=m$(p,y),P=h$(T.root).filter(Je=>wi(Je.run)!==p&&n9(Je,p,T.root)).map(Je=>wi(Je.run)),L=QB(i,p,P),te=L.loaded?Is.ledger_no_records:Is.ledger_not_loaded,X=L.loaded&&L.subject_found,V=qB(e,t,k??b),ne=Je=>V.source[Je]==="run"?"run":V.source[Je]==="automation"?"automation":"",W=xt(d==null?void 0:d.output),Y=xt(W==null?void 0:W.meta),K=qt(x.workflow_id)||qt(m==null?void 0:m.workflow_id),fe=qt(m==null?void 0:m.bundle_version)||(K.includes("@")?K.split("@")[1].split(":")[0]:""),ae=K?un({id:K,name:ni(K),version:fe,flow_name:qt(H==null?void 0:H.name)},"run"):Xn(Is.wire),ve=M?b?un({kind:"automation",title:b.title,id:b.automation_id},"automation"):Xn(Is.automation_not_loaded):qt(x.session_id)?un({kind:"session",title:"",id:qt(x.session_id)},"run"):un({kind:"run",title:"",id:p},"run"),ge=qt(x.parent_run_id),pe=ge?w(ge):void 0,$e=Bn(x.occurrence_index);let De="";if(F==="occurrence")De=$e!==null?`occurrence #${$e}`:"occurrence";else if(F==="controller")De="automation controller (the schedule's own run)";else if(F==="discussion")De="discussion of the automation";else if(ge){const Je=qt(pe==null?void 0:pe.role),en=Bn(pe==null?void 0:pe.occurrence_index);De=`subrun of ${Je==="occurrence"&&en!==null?`occurrence #${en}`:ni(qt(pe==null?void 0:pe.workflow_id))||"a parent run (row not loaded)"}`}else De=qt(x.session_id)?"run in a session":"top-level run";const ot=un({text:De,parent_run_id:ge},"run"),Ue=[["run",Uc(h==null?void 0:h.provider,h==null?void 0:h.model)],["flow default",Uc(R("provider"),R("model"))],["automation",Uc(A==null?void 0:A.provider,A==null?void 0:A.model)],["automation",Uc(E==null?void 0:E.provider,E==null?void 0:E.model)],["automation",k?null:Uc(b==null?void 0:b.provider,b==null?void 0:b.model)]].find(([,Je])=>Je!==null)||null;let at;X&&L.models.length?at=un(L.models.map(Je=>({provider:Je.provider,model:Je.model,calls:Je.calls})),"used"):Uc(Y==null?void 0:Y.provider,Y==null?void 0:Y.model)?at=un([Uc(Y==null?void 0:Y.provider,Y==null?void 0:Y.model)],"output"):Ue?at=un([Ue[1]],Ue[0]):at=Xn(Is.gateway_default,"gateway");let Nt=null;if((at.source==="used"||at.source==="output")&&Ue&&at.value){const Je=Ue[1];at.value.some(Yt=>(!Je.provider||Yt.provider===Je.provider)&&(!Je.model||Yt.model===Je.model))||(Nt=un(Je,Ue[0]))}const ut=h&&typeof h.system=="string"?un(h.system,"run"):H?bd(R("system"))!==null?un(String(R("system")),"flow default"):Z.has("system")?Xn("none declared: not provided and the flow has no default","flow"):Xn("the flow has no system pin","flow"):Xn(Is.flow_not_loaded),Se=ip([["run",h&&typeof h.prompt=="string"&&h.prompt.trim()?h.prompt:null],["run",bd((ts=xt(h==null?void 0:h.context))==null?void 0:ts.task)],["flow default",bd(R("prompt"))],["automation",bd(A==null?void 0:A.prompt)],["automation",k?null:bd(b==null?void 0:b.task)]],Is.no_default),me=ip([["run",ei(h==null?void 0:h.tools)],["flow default",ei(R("tools"))],["automation",ei(A==null?void 0:A.tools)],["automation",ei(E==null?void 0:E.allowed_tools)],["automation",k?null:(Pe=b==null?void 0:b.tools)!=null&&Pe.length?b.tools:null]],Is.no_default),Ve=((Ut=L.subruns.find(Je=>Je.allowed_tools!==null))==null?void 0:Ut.allowed_tools)??null,ye=ip([["used",X?L.allowlist:null],["used",X?Ve:null],["automation",ei(E==null?void 0:E.allowed_tools)],["automation",k?null:(b==null?void 0:b.allowed_tools)??null]],M?D:X?"the ledger shows no enforced allowlist":te),Ie=me.value,ct=X?un(L.tools.map(Je=>({...Je,outside_declared:Ie===null?null:!Ie.includes(Je.name)})),"used"):Xn(te),ie=(Je,en)=>Je!==null&&V.source[en]?un(Je,ne(en)):Xn(D),Te=ie(bd(V.tool_approval),"tool_approval"),et=ie(V.source.untrusted_input_tools?V.untrusted_input_tools:null,"untrusted_input_tools"),Ge=ie(V.source.email_allowed_recipients?V.email_allowed_recipients:null,"email_allowed_recipients"),Be=(Je,en)=>V.source[en]?un(Je,ne(en)):Xn(Is.wire),Rt={mode:Be(V.workspace_access_mode,"workspace_access_mode"),root:Be(V.workspace_root,"workspace_root"),allowed_paths:Be(V.workspace_allowed_paths,"workspace_allowed_paths"),ignored_paths:Be(V.workspace_ignored_paths,"workspace_ignored_paths")},Nn=w(p)||x,Qt=X?un(L.llm_calls,"used"):Bn(Nn==null?void 0:Nn.llm_calls)!==null?un(Bn(Nn.llm_calls),"listing"):Xn(te),Un=X?un({calls:L.tool_calls,failures:L.tool_failures},"used"):Bn(Nn==null?void 0:Nn.tool_calls)!==null?un({calls:Bn(Nn.tool_calls),failures:null},"listing"):Xn(te),rs=T.root?((St=Jp(T.root,p))==null?void 0:St.children)||[]:[],Dn=X?un(L.subruns,"used"):rs.length?un(rs.map(Je=>({run_id:wi(Je.run),workflow_id:qt(Je.run.workflow_id),from_run_id:p,provider:"",model:"",allowed_tools:null,max_iterations:null})),"listing"):Xn(L.loaded?Is.ledger_no_records:"none among the loaded rows; ledger not loaded here"),$n=[];if(W)for(const[Je,en]of Object.entries(W)){const Yt=xt(en);Yt&&Object.keys(Yt).length===1&&typeof Yt.$artifact=="string"&&Yt.$artifact.trim()&&$n.push({pin:Je,id:Yt.$artifact.trim()})}const Cn=ds(x.status);let an;d?Cn?W&&typeof W.response=="string"&&W.response.trim()?an=un(W.response,"output"):typeof d.output=="string"&&d.output.trim()?an=un(d.output,"output"):qt(d.error)?an=un(qt(d.error),"run"):an=Xn("the output carries no response text"):an=Xn(Is.not_ended):an=Xn("run detail not loaded");const is=It(x.created_at||""),Wn=Cn?It(x.updated_at||""):null,Fn=mh(x,u),Hs=Fn>=0?un(Fn,"run"):L.first_ms!==null&&L.last_ms!==null?un(L.last_ms-L.first_ms,"used"):Xn(Is.wire),es=X?((Mn=L.subruns.find(Je=>Je.max_iterations!==null))==null?void 0:Mn.max_iterations)??null:null,he=ip([["used",es],["run",Bn(h==null?void 0:h.max_iterations)],["flow default",Bn(R("max_iterations"))],["automation",Bn(A==null?void 0:A.max_iterations)],["automation",k?null:(b==null?void 0:b.max_iterations)??null]],Is.no_default),Ee=Bn(Y==null?void 0:Y.iterations)!==null?un(Bn(Y==null?void 0:Y.iterations),"output"):Xn(Cn?"the output carries no iteration count":Is.not_ended),mt=sv(e).tokens,se=xt($==null?void 0:$.trigger)||xt(S==null?void 0:S.trigger),ce=xt(se==null?void 0:se.config),je=b!=null&&b.cadence?un({text:b.cadence,start_ms:It((ce==null?void 0:ce.start_at)||"")},"automation"):Xn(D),Ae=M?un({index:$e,count:b?b.occurrence_count:null},b?"automation":"run"):Xn(Is.not_automation),ze=Bn(ce==null?void 0:ce.count)!==null?un(Bn(ce==null?void 0:ce.count),"automation"):Xn(M&&se?"no count limit":D,M&&se?"automation":""),Fe=It((ce==null?void 0:ce.until)||""),Ze=Fe!==null?un(Fe,"automation"):Xn(M&&se?"no end date":D,M&&se?"automation":""),lt=xt(z==null?void 0:z.retry),ht=xt(lt==null?void 0:lt.backoff),_t=z?un({max_attempts:Bn(lt==null?void 0:lt.max_attempts),backoff_initial:qt(ht==null?void 0:ht.initial),backoff_factor:Bn(ht==null?void 0:ht.factor),backoff_max:qt(ht==null?void 0:ht.max),failure:qt(z.failure),misfire:qt(z.misfire),serial:xp(z.serial)},"automation"):Xn(D),kt=S&&Array.isArray((nn=xt(S.notify))==null?void 0:nn.channels)?un(ei(S.notify.channels),"automation"):Xn(D),At=sv(e),rt=b!=null&&b.context_mode||At.has_history?un({mode:(b==null?void 0:b.context_mode)||"",growing_max_tokens:(b==null?void 0:b.growing_max_tokens)??null,replayed_messages:At.replayed_messages,replayed_tokens:At.replayed_tokens,dropped_messages:At.dropped_messages,dropped_tokens:At.dropped_tokens},b!=null&&b.context_mode?"automation":"run"):Xn(M?D:"no session history on this run"),zt=Rt.root.value?un(Rt.root.value,Rt.root.source):Xn(Is.wire);let dn;if(!M)dn=Xn(Is.not_automation);else if(!b)dn=Xn(Is.automation_not_loaded);else{const Je=b.status;if(Je==="paused")dn=un({kind:"none",at_ms:null,text:"no next run (paused)"},"automation");else if(Je==="completed")dn=un(b.last&&$e!==null&&b.last.index===$e?{kind:"last",at_ms:null,text:"this was the last (stop reached)"}:{kind:"none",at_ms:null,text:"no next run (completed: stop reached)"},"automation");else if(Je==="archived")dn=un({kind:"none",at_ms:null,text:"no next run (archived)"},"automation");else if(Je==="failed")dn=un({kind:"none",at_ms:null,text:"no next run (the automation failed)"},"automation");else if(b.next_fire_ms!==null){const en=Bm(b.next_fire_ms-u);dn=un({kind:"next_at",at_ms:b.next_fire_ms,text:`next occurrence at ${Nd(b.next_fire_ms)}${en?` (in ${en})`:""}`},"automation")}else qt(se==null?void 0:se.source_id)==="manual"?dn=un({kind:"on_trigger",at_ms:null,text:"next run when someone runs it"},"automation"):qt(se==null?void 0:se.source_id)==="email_received"?dn=un({kind:"on_trigger",at_ms:null,text:"next run when a matching email arrives"},"automation"):dn=Xn("no next fire time on this wire","automation")}return{subject_id:p,is_automation:M,who:{workflow:ae,subject:ve,role:ot,model:at,model_declared:Nt,system_prompt:ut,task:Se},access:{tools_allowed:me,runtime_allowlist:ye,tools_called:ct,tool_approval:Te,untrusted_input_tools:et,email_recipients:Ge,operator_email:qt(E==null?void 0:E.operator_email),workspace:Rt},does:{llm_calls:Qt,tool_calls:Un,subruns:Dn,artifacts:$n,outcome:an,children_not_loaded:L.missing_run_ids},how_long:{started_ms:is,finished_ms:Wn,running:!Cn,duration:Hs,max_iterations:he,iterations_used:Ee,tokens:mt,cadence:je,next_fire_ms:(b==null?void 0:b.next_fire_ms)??null,occurrence:Ae,stop_after:ze,stop_at:Ze,retry:_t},after:{notify:kt,context:rt,outputs_to:zt,next:dn},ledger:L}}function Jp(e,t){if(wi(e.run)===t)return e;for(const n of e.children){const r=Jp(n,t);if(r)return r}return null}function n9(e,t,n){const r=n?Jp(n,t):null;return!!r&&r!==e&&!!Jp(r,wi(e.run))}const s9=["status","updated_at","current_node","paused","error","waiting"],r9=["workflow_id","created_at","parent_run_id","session_id","automation_id","role","occurrence_index","session_kind"];function _$(e,t){if(!t||typeof t!="object"||String(t.run_id||"").trim()&&String(t.run_id).trim()!==String(e.run_id||"").trim())return!1;const n=It(e.updated_at||""),r=It(t.updated_at||"");return n===null||r===null?!0:r>=n}function p$(e,t){if(!t||typeof t!="object")return e;const n={...e};for(const r of r9)(n[r]===void 0||n[r]===null||n[r]==="")&&t[r]!==void 0&&t[r]!==null&&(n[r]=t[r]);if(_$(e,t))for(const r of s9)Object.prototype.hasOwnProperty.call(t,r)&&(n[r]=t[r]);return n}function i9(e,t){const n=String(t.run_id||"").trim();let r=!1;const i=(e||[]).map(a=>String((a==null?void 0:a.run_id)||"").trim()!==n?a:(r=!0,{...a,...t}));return r||i.push(t),i}function Zn(e){return s.jsx("p",{className:`ap_note ap_note_${e.kind}`,role:e.kind==="error"?"alert":void 0,children:e.children})}function ec(e){return s.jsxs("section",{className:"ap_block","data-block":e.id,"aria-labelledby":`ap_${e.id}_title`,children:[s.jsxs("header",{className:"ap_block_head",children:[s.jsx("h2",{id:`ap_${e.id}_title`,className:"ap_block_title",children:e.title}),e.meta?s.jsx("span",{className:"ap_block_meta",children:e.meta}):null]}),e.children]})}const o9={approve:"Review approval",answer:"Answer",resume:"Resume",open_subrun:"Open subrun",inspect:"Inspect"};function g$(e,t,n,r){return lN(e,t,n??null,r??null)}function a9(e,t){const n=o9[e.action],r=e.action==="open_subrun"?e.actor_run_id:t;return n&&r?{action:e.action,label:n,run_id:r}:null}function l9(e){const{line:t}=e;if(t.actor==="none")return null;if(t.actor==="run"&&t.actor_run_id){const r=e.ctx.by_id.get(t.actor_run_id),i=ni(String((r==null?void 0:r.workflow_id)||""))||"subrun (row not loaded)";return s.jsxs("button",{type:"button",className:"ap_actor ap_actor_run",title:`Ended by run ${t.actor_run_id}`,onClick:()=>e.on_open_run(t.actor_run_id),children:["run ",i]})}const n=t.actor==="run"?"a run":t.actor;return s.jsx("span",{className:`ap_actor ap_actor_${t.actor}`,title:"Who ends this state",children:n})}function c9(e){return s.jsx("button",{type:"button",className:"btn btn_icon ap_copy",title:`Copy run id ${e.run_id}`,"aria-label":"Copy run id",onClick:()=>{e.on_copy?e.on_copy(e.run_id):hh(e.run_id)},children:"⧉"})}const u9={used:"Read from the run's ledger: what it actually did",output:"Read from the run's own output",run:"Read from this run's detail and inputs","flow default":"The flow's default for a pin the run was not sent (the runtime applies it)",flow:"Read from the flow declaration",automation:"Read from the automation definition, not from this run's inputs",listing:"Read from the run listing: counts include every run below this one",gateway:"The gateway's own default; this wire does not report it"};function y$(e){return e.source?s.jsx("span",{className:"ap_source","data-source":e.source,title:u9[e.source],children:e.source}):null}function d9(e){return s.jsx("span",{className:"ap_absent",children:e.fact.source==="gateway"?e.fact.why:`— ${e.fact.why||"not on this wire"}`})}function ma(e){return s.jsxs("div",{className:"ap_prow ap_copyable","data-row":e.id,children:[s.jsx("dt",{className:"ap_prow_label",children:e.label}),s.jsx("dd",{className:"ap_prow_value",children:e.children}),s.jsxs("dd",{className:"ap_prow_meta",children:[s.jsx(y$,{source:e.source||""}),e.copy?s.jsx(ug,{text:e.copy,label:e.label.toLowerCase()}):null]})]})}function Yn(e){const{fact:t}=e,n=t.value!==null;return s.jsx(ma,{id:e.id,label:e.label,source:t.source,copy:n?e.copy?e.copy(t.value):Ya(t.value):null,children:n?e.render?e.render(t.value):s.jsx(Hm,{value:t.value}):s.jsx(d9,{fact:t})})}function Ul(e){return e.items.length?s.jsx("span",{className:"ap_tags",children:e.items.map((t,n)=>s.jsx("code",{className:"ap_tag",children:t},`${t}:${n}`))}):s.jsx("span",{className:"ap_muted",children:e.empty||"none"})}function bm(e){return s.jsxs("section",{className:"ap_pgroup","data-group":e.id,"aria-labelledby":`ap_pg_${e.id}`,children:[s.jsxs("h3",{className:"ap_pgroup_title",id:`ap_pg_${e.id}`,children:[e.title," ",s.jsx("span",{className:"ap_pgroup_q",children:e.question})]}),s.jsx("dl",{className:"ap_ptable",children:e.children})]})}function Wy(e){return[e.provider,e.model].filter(Boolean).join(" · ")||"model not recorded on the call"}function f9(e,t){if(e.length!==t.length)return!1;const n=new Set(e);return t.every(r=>n.has(r))}function aa(e,t,n=`${t}s`){return`${ss(e)} ${e===1?t:n}`}function m9(e){var z,F;const{prof:t,p:n,line:r,ctx:i}=e,a=[];n.loading.input_data&&a.push(s.jsx(Zn,{kind:"loading",children:"loading the run's inputs…"},"li")),n.errors.input_data&&a.push(s.jsxs(Zn,{kind:"error",children:["inputs unavailable: ",n.errors.input_data]},"ei")),n.loading.detail&&a.push(s.jsx(Zn,{kind:"loading",children:"loading the run detail…"},"ld")),n.errors.detail&&a.push(s.jsxs(Zn,{kind:"error",children:["run detail unavailable: ",n.errors.detail]},"ed")),n.loading.flow&&a.push(s.jsx(Zn,{kind:"loading",children:"loading the flow (its defaults)…"},"lf")),n.loading.records&&a.push(s.jsx(Zn,{kind:"loading",children:"loading the ledger…"},"lr")),n.errors.records&&a.push(s.jsxs(Zn,{kind:"error",children:["ledger unavailable: ",n.errors.records]},"er")),t.is_automation&&!n.automation_body&&!n.automation&&a.push(s.jsx(Zn,{kind:"absent",children:"automation definition not loaded: tool policy unknown"},"na"));const u=M=>{const D=i.by_id.get(M);return ni(String((D==null?void 0:D.workflow_id)||""))||"a run (row not loaded)"},c=(M,D)=>s.jsx("button",{type:"button",className:"ap_link_btn ap_run_link",title:`Open run ${M}`,"data-run-id":M,onClick:()=>n.on_open_run(M),children:D}),{who:d,access:m,does:h,how_long:p,after:y}=t,w=m.workspace,x=w.root.value&&n.on_reveal_workspace?s.jsx("button",{type:"button",className:"ap_link_btn",onClick:()=>{var M;return(M=n.on_reveal_workspace)==null?void 0:M.call(n)},children:"show folder"}):null,k=t.ledger.runs,b=M=>k.length>1?s.jsx("span",{className:"ap_breakdown",children:k.map((D,H)=>s.jsxs("span",{"data-run-id":D.run_id,children:[H?" · ":"",ss(M(D))," ",D.run_id===t.subject_id?"in this run":s.jsxs(s.Fragment,{children:["in ",c(D.run_id,u(D.run_id))]})]},D.run_id))}):null,S=h.children_not_loaded,$=S.length?s.jsxs("span",{className:"ap_breakdown","data-children-not-loaded":S.length,children:["children's calls live in their own view (",aa(S.length,"subrun")," not loaded here:"," ",S.map((M,D)=>s.jsxs("span",{children:[D?", ":"",c(M,u(M))]},M)),")"]}):null,A=M=>M.source==="listing"?s.jsx("span",{className:"ap_breakdown",children:"tree-inclusive: this run and every run below it"}):null,E=M=>s.jsx(Ul,{items:M.map(D=>D==="self"&&m.operator_email?`self (${m.operator_email})`:D),empty:"none"});return s.jsxs(ec,{id:"profile",title:"Agent profile",meta:"who it is · what it can reach · what it does · for how long · what comes after",children:[a,s.jsxs("div",{className:"ap_profile",children:[s.jsxs(bm,{id:"who",title:"Who",question:"is this agent",children:[s.jsx(Yn,{id:"workflow",label:"Workflow",fact:d.workflow,render:M=>s.jsxs("span",{children:[M.name||M.id,M.flow_name?s.jsxs("span",{className:"ap_muted",children:[" · flow “",M.flow_name,"”"]}):null]}),copy:M=>M.id}),s.jsx(Yn,{id:"subject",label:"Subject",fact:d.subject,render:M=>M.kind==="automation"?s.jsx(Hm,{value:M.title||"untitled automation"}):s.jsx("span",{children:M.kind==="session"?"a session (id on copy)":"a standalone run (id on copy)"}),copy:M=>M.id}),s.jsx(Yn,{id:"role",label:"Role",fact:d.role,render:M=>{var D,H;return s.jsxs("span",{children:[M.text,M.parent_run_id&&t.is_automation&&((D=p.occurrence.value)==null?void 0:D.count)!==null&&((H=p.occurrence.value)==null?void 0:H.count)!==void 0&&M.text.startsWith("occurrence")?s.jsxs("span",{className:"ap_muted",children:[" of ",ss(p.occurrence.value.count)," so far"]}):null,M.parent_run_id?s.jsxs(s.Fragment,{children:[" · ",c(M.parent_run_id,"open parent")]}):null]})},copy:M=>M.parent_run_id||M.text}),s.jsx(Yn,{id:"model",label:"Model · provider",fact:d.model,render:M=>{var D;return s.jsxs("span",{className:"ap_stack",children:[M.map((H,q)=>s.jsxs("span",{children:[Wy(H),H.calls!==null?s.jsxs("span",{className:"ap_muted",children:[" × ",aa(H.calls,"call")]}):null]},q)),(D=d.model_declared)!=null&&D.value?s.jsxs("span",{className:"ap_finding",children:["asked for ",Wy(d.model_declared.value)," ",s.jsx(y$,{source:d.model_declared.source})]}):null]})},copy:M=>M.map(Wy).join(`
|
|
166
|
+
`)}),s.jsx(Yn,{id:"system",label:"System prompt",fact:d.system_prompt}),s.jsx(Yn,{id:"task",label:"Task",fact:d.task})]}),s.jsxs(bm,{id:"access",title:"Access",question:"what it may use",children:[s.jsx(Yn,{id:"tools_allowed",label:"May call",fact:m.tools_allowed,render:M=>s.jsx(Ul,{items:M})}),s.jsx(Yn,{id:"runtime_allowlist",label:"Runtime allowlist",fact:m.runtime_allowlist,render:M=>m.tools_allowed.value&&M.length&&f9(M,m.tools_allowed.value)?s.jsxs("span",{children:["the same ",aa(M.length,"tool")," as above"]}):s.jsx(Ul,{items:M})}),s.jsx(Yn,{id:"tools_called",label:"Did call",fact:m.tools_called,render:M=>s.jsxs("span",{className:"ap_stack",children:[M.length?s.jsx("span",{className:"ap_tags",children:M.map(D=>s.jsxs("span",{className:`ap_tool_use ${D.outside_declared?"ap_tool_outside":""}`,"data-tool":D.name,children:[s.jsxs("code",{className:"ap_tag",children:[D.name," × ",ss(D.calls),D.failures?`, ${ss(D.failures)} failed`:""]}),D.outside_declared?s.jsx("span",{className:"ap_finding",children:"called outside the declared list"}):null]},D.name))}):s.jsx("span",{className:"ap_muted",children:"none in the loaded ledger"}),$]})}),s.jsx(Yn,{id:"tool_approval",label:"Tool approval",fact:m.tool_approval,render:M=>s.jsx("span",{children:M})}),s.jsx(Yn,{id:"untrusted_input_tools",label:"Untrusted-input tools",fact:m.untrusted_input_tools,render:M=>s.jsx(Ul,{items:M})}),s.jsx(Yn,{id:"email_recipients",label:"Email recipients",fact:m.email_recipients,render:E}),s.jsx(Yn,{id:"workspace",label:"Workspace",fact:w.mode,render:M=>s.jsxs("span",{className:"ap_workspace",children:[s.jsx("span",{children:M||"mode not set"}),w.root.value?s.jsx("code",{className:"ap_path",children:w.root.value}):null,x]}),copy:M=>w.root.value?`${M}
|
|
167
|
+
${w.root.value}`:M}),w.allowed_paths.value!==null?s.jsx(Yn,{id:"allowed_paths",label:"Allowed paths",fact:w.allowed_paths,render:M=>s.jsx(Ul,{items:M})}):null,w.ignored_paths.value!==null?s.jsx(Yn,{id:"ignored_paths",label:"Ignored paths",fact:w.ignored_paths,render:M=>s.jsx(Ul,{items:M})}):null]}),s.jsxs(bm,{id:"does",title:"Does",question:"what it did",children:[s.jsx(ma,{id:"now",label:"Now",source:"run",copy:r.text,children:s.jsx("span",{className:r.stalled?"ap_stalled_text":void 0,children:r.text})}),s.jsx(Yn,{id:"llm_calls",label:"LLM calls",fact:h.llm_calls,render:M=>s.jsxs("span",{className:"ap_stack",children:[s.jsx("span",{children:ss(M)}),h.llm_calls.source==="used"?b(D=>D.llm_calls):A(h.llm_calls)]})}),s.jsx(Yn,{id:"tool_calls",label:"Tool calls",fact:h.tool_calls,render:M=>s.jsxs("span",{className:"ap_stack",children:[s.jsxs("span",{children:[ss(M.calls),M.failures?`, ${ss(M.failures)} failed`:M.failures===0&&M.calls?", none failed":""]}),h.tool_calls.source==="used"?b(D=>D.tool_calls):A(h.tool_calls),h.tool_calls.source==="used"?$:null]})}),s.jsx(Yn,{id:"subruns",label:"Delegated subruns",fact:h.subruns,render:M=>M.length?s.jsx("span",{className:"ap_stack",children:M.map((D,H)=>{const q=[[D.provider,D.model].filter(Boolean).join(" · "),D.allowed_tools!==null?aa(D.allowed_tools.length,"tool"):"",D.max_iterations!==null?`max ${ss(D.max_iterations)} iterations`:""].filter(Boolean),I=ni(D.workflow_id)||"subrun";return s.jsxs("span",{className:"ap_subrun",children:[D.run_id?c(D.run_id,I):s.jsxs("span",{children:[I," (not started yet)"]}),q.length?s.jsxs("span",{className:"ap_muted",children:[" · handed ",q.join(" · ")]}):null]},`${D.run_id}:${H}`)})}):s.jsx("span",{className:"ap_muted",children:"none"})}),h.artifacts.length?s.jsx(ma,{id:"artifacts",label:"Artifacts",source:"output",copy:h.artifacts.map(M=>M.id).join(`
|
|
168
|
+
`),children:s.jsxs("span",{children:[aa(h.artifacts.length,"artifact"),": ",s.jsx(Ul,{items:h.artifacts.map(M=>M.pin)})]})}):null,s.jsx(Yn,{id:"outcome",label:"Outcome",fact:h.outcome})]}),s.jsxs(bm,{id:"how_long",title:"How long",question:"it runs and may run",children:[s.jsx(ma,{id:"started",label:"Started",source:p.started_ms!==null?"run":"",copy:p.started_ms!==null?new Date(p.started_ms).toISOString():null,children:p.started_ms!==null?s.jsx("span",{children:Nd(p.started_ms)}):s.jsx("span",{className:"ap_absent",children:"— not on this wire"})}),s.jsx(ma,{id:"finished",label:"Finished",source:p.finished_ms!==null?"run":"",copy:p.finished_ms!==null?new Date(p.finished_ms).toISOString():null,children:p.finished_ms!==null?s.jsx("span",{children:Nd(p.finished_ms)}):s.jsx("span",{className:"ap_muted",children:p.running?"so far (still active)":"— not on this wire"})}),s.jsx(Yn,{id:"duration",label:"Duration",fact:p.duration,render:M=>s.jsxs("span",{children:[cu(M),p.running?" so far":""]}),copy:M=>String(M)}),s.jsx(Yn,{id:"max_iterations",label:"Max iterations",fact:p.max_iterations}),s.jsx(Yn,{id:"iterations_used",label:"Iterations used",fact:p.iterations_used}),s.jsx(ma,{id:"token_limit",label:"Token limit",source:p.tokens?"run":"",copy:p.tokens?Ya(((F=(z=n.detail)==null?void 0:z.limits)==null?void 0:F.tokens)??p.tokens):null,children:p.tokens&&(p.tokens.used!==null||p.tokens.budget!==null)?s.jsxs("span",{children:[p.tokens.used!==null?ss(p.tokens.used):"—",p.tokens.budget!==null?` of ${ss(p.tokens.budget)}`:""," tokens",p.tokens.pct!==null?` (${p.tokens.pct<10&&p.tokens.pct>0?p.tokens.pct.toFixed(1):Math.round(p.tokens.pct)}%)`:""]}):s.jsx("span",{className:"ap_absent",children:"— no token estimate on this run"})}),s.jsx(Yn,{id:"cadence",label:"Cadence",fact:p.cadence,render:M=>s.jsxs("span",{children:[M.text,M.start_ms!==null?s.jsxs("span",{className:"ap_muted",children:[" · since ",Nd(M.start_ms)]}):null,p.next_fire_ms!==null?s.jsxs("span",{children:[" · next ",Nd(p.next_fire_ms)]}):null]})}),s.jsx(Yn,{id:"occurrences",label:"Occurrences",fact:p.occurrence,render:M=>s.jsxs("span",{children:[M.index!==null?`#${ss(M.index)}`:"this run",M.count!==null?` of ${ss(M.count)} so far`:""," · ",p.stop_after.value!==null?`stops after ${aa(p.stop_after.value,"scheduled occurrence")}`:p.stop_after.why," · ",p.stop_at.value!==null?`stops at ${Nd(p.stop_at.value)}`:p.stop_at.why]})}),s.jsx(Yn,{id:"retry",label:"Retry policy",fact:p.retry,render:M=>s.jsx("span",{children:[M.max_attempts!==null?aa(M.max_attempts,"attempt"):"",M.backoff_initial?`backoff ${M.backoff_initial}${M.backoff_factor!==null?` ×${M.backoff_factor}`:""}${M.backoff_max?` up to ${M.backoff_max}`:""}`:"",M.failure?`on failure: ${M.failure}`:"",M.misfire?`misfire: ${M.misfire}`:"",M.serial===!0?"serial":M.serial===!1?"may overlap":""].filter(Boolean).join(" · ")||"no retry fields set"})})]}),s.jsxs(bm,{id:"after",title:"After",question:"what it may do next",children:[s.jsx(Yn,{id:"notify",label:"Notifies",fact:y.notify,render:M=>s.jsx(Ul,{items:M.map(D=>D==="email"?"email → the owner's registered address (not on this wire)":D),empty:"nobody (no channel)"})}),s.jsx(Yn,{id:"context_plan",label:"Context",fact:y.context,render:M=>s.jsxs("span",{className:"ap_stack",children:[s.jsx("span",{children:M.mode==="growing"?`growing${M.growing_max_tokens!==null?` (cap ${ss(M.growing_max_tokens)} tokens)`:""}: each occurrence replays the session so far`:M.mode==="independent"?"independent: each occurrence starts fresh":M.mode||"session history"}),M.replayed_messages!==null||M.replayed_tokens!==null?s.jsxs("span",{className:"ap_muted",children:["this run replayed ",M.replayed_messages!==null?aa(M.replayed_messages,"message"):"?",M.replayed_tokens!==null?` (${ss(M.replayed_tokens)} tokens)`:"",M.dropped_messages!==null?`, left out ${aa(M.dropped_messages,"message")}${M.dropped_tokens?` (${ss(M.dropped_tokens)} tokens)`:""}`:""]}):null]})}),s.jsx(Yn,{id:"outputs_to",label:"Outputs go to",fact:y.outputs_to,render:M=>s.jsxs("span",{className:"ap_workspace",children:[s.jsx("code",{className:"ap_path",children:M}),x,h.artifacts.length?s.jsxs("span",{className:"ap_muted",children:["· ",aa(h.artifacts.length,"artifact")," in the output"]}):null]})}),s.jsx(Yn,{id:"next",label:"Next",fact:y.next,render:M=>s.jsx("span",{children:M.text}),copy:M=>M.at_ms!==null?new Date(M.at_ms).toISOString():M.text})]})]})]})}function h9(e){const{p:t}=e,n=_.useMemo(()=>VB(t.flow,t.input_data,t.detail),[t.flow,t.input_data,t.detail]),r=n.inputs.filter(c=>c.state==="value").length,i=t.loading.flow?s.jsx(Zn,{kind:"loading",children:"loading the flow…"}):t.errors.flow?s.jsxs(Zn,{kind:"error",children:["the flow did not load (",t.errors.flow,"): pin types unknown"]}):n.flow_found?n.start_found?null:s.jsx(Zn,{kind:"absent",children:"the flow has no On Flow Start node"}):s.jsx(Zn,{kind:"absent",children:"no flow JSON for this run: pin types unknown"}),a=t.loading.input_data?s.jsx(Zn,{kind:"loading",children:"loading the run's inputs…"}):t.errors.input_data?s.jsxs(Zn,{kind:"error",children:["inputs unavailable: ",t.errors.input_data]}):t.input_data?s.jsx(Zn,{kind:"info",children:"values as the run holds them now: the gateway reads the run's current variables, so a pin the run writes back (context) shows its latest value"}):null,u=t.loading.detail?s.jsx(Zn,{kind:"loading",children:"loading the run detail…"}):t.errors.detail?s.jsxs(Zn,{kind:"error",children:["output unavailable: ",t.errors.detail]}):n.flow_found&&!n.end_found?s.jsx(Zn,{kind:"absent",children:"the flow has no On Flow End node"}):n.end_is_passthrough?s.jsx(Zn,{kind:"info",children:"the end declares no pins: the run returns its last node's output"}):t.detail&&!n.outputs_final?s.jsx(Zn,{kind:"info",children:"values appear when the run ends"}):null;return s.jsxs(ec,{id:"pins",title:"Inputs → Outputs",children:[i,s.jsxs("div",{className:"ap_io",children:[s.jsxs("div",{className:"ap_io_col",children:[s.jsxs("h3",{className:"ap_io_title",children:["Inputs",n.inputs.length?s.jsxs("span",{className:"ap_io_meta",children:[n.inputs.length," pin",n.inputs.length===1?"":"s",t.input_data?` · ${r} provided`:""]}):null]}),a,s.jsx(t0,{side:"in",label:"Inputs",pins:n.inputs,also:n.also_sent,also_label:"also sent",empty_text:n.flow_found||t.input_data?"no input pins":"—"})]}),s.jsx("div",{className:"ap_io_arrow","aria-hidden":"true",children:"→"}),s.jsxs("div",{className:"ap_io_col",children:[s.jsxs("h3",{className:"ap_io_title",children:["Outputs",n.outputs.length?s.jsx("span",{className:"ap_io_meta",children:n.end_is_passthrough?"pass-through":`${n.outputs.length} pin${n.outputs.length===1?"":"s"}`}):null]}),u,s.jsx(t0,{side:"out",label:"Outputs",pins:n.outputs,also:n.also_returned,also_label:"also returned",outputs_final:n.outputs_final,empty_text:n.flow_found?"no output pins":"—"})]})]})]})}function _9(e){var c,d,m;const{p:t}=e,n=_.useMemo(()=>sv(t.detail),[t.detail]);if(t.loading.detail&&!t.detail)return s.jsx(ec,{id:"context",title:"Context",children:s.jsx(Zn,{kind:"loading",children:"loading the run detail…"})});if(!t.detail)return s.jsx(ec,{id:"context",title:"Context",children:t.errors.detail?s.jsxs(Zn,{kind:"error",children:["run detail unavailable: ",t.errors.detail]}):s.jsx(Zn,{kind:"absent",children:"run detail not loaded"})});const r=n.tokens,i=(r==null?void 0:r.pct)!==null&&(r==null?void 0:r.pct)!==void 0?`${r.pct<10&&r.pct>0?r.pct.toFixed(1):Math.round(r.pct)}%`:"",a=[n.policy,n.strict===!0?"strict":"",n.session_kind?`${n.session_kind} session`:""].filter(Boolean),u=(c=t.detail)==null?void 0:c.session_history;return s.jsx(ec,{id:"context",title:"Context",children:s.jsxs("dl",{className:"ap_ptable",children:[s.jsx(ma,{id:"window",label:"Window",source:n.has_history?"run":"",copy:n.has_history?Ya(u):null,children:n.has_history?s.jsx("span",{className:"ap_window_note",children:n.window_note||"the session-history receipt carries no counts"}):s.jsx("span",{className:"ap_absent",children:"— no session history replayed into this run"})}),n.has_history?s.jsxs(ma,{id:"history_policy",label:"History policy",source:"run",copy:a.length?a.join(" · "):null,children:[a.length?a.join(" · "):s.jsx("span",{className:"ap_absent",children:"— not on this wire"}),n.token_estimator?s.jsx("span",{className:"ap_source",title:n.token_estimator,children:"estimated"}):null]}):null,s.jsx(ma,{id:"tokens",label:"Tokens",source:r?"run":"",copy:r?Ya(((m=(d=t.detail)==null?void 0:d.limits)==null?void 0:m.tokens)??r):null,children:r&&(r.used!==null||r.budget!==null)?s.jsxs("span",{className:`ap_gauge_wrap ${r.over_warn?"ap_gauge_over":""}`,children:[s.jsxs("span",{className:"ap_gauge_text",children:[r.used!==null?ss(r.used):"—",r.budget!==null?` of ${ss(r.budget)}`:"",r.max_input_tokens!==null?" input":""," tokens",i?` (${i})`:"",r.warn_pct!==null?` · warns at ${r.warn_pct}%`:""]}),r.pct!==null?s.jsxs("span",{className:"ap_gauge",role:"meter","aria-label":"Context tokens used","aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":Math.round(Math.min(100,r.pct)),children:[s.jsx("span",{className:"ap_gauge_fill",style:{width:`${Math.min(100,Math.max(0,r.pct))}%`}}),r.warn_pct!==null?s.jsx("span",{className:"ap_gauge_warn",style:{left:`${Math.min(100,Math.max(0,r.warn_pct))}%`}}):null]}):null]}):s.jsx("span",{className:"ap_absent",children:"— no token estimate on this run"})}),s.jsx(ma,{id:"flow_warnings",label:"Flow warnings",source:t.detail?"run":"",copy:n.flow_warnings.length?n.flow_warnings.join(`
|
|
169
|
+
`):null,children:n.flow_warnings.length?s.jsx("ul",{className:"ap_warnings",children:n.flow_warnings.map((h,p)=>s.jsx("li",{children:h},p))}):s.jsx("span",{className:"ap_muted",children:"none"})})]})})}function w$(e){const t=ni(String(e.workflow_id||""))||"(workflow?)";return String(e.role||"").trim()==="occurrence"&&typeof e.occurrence_index=="number"?`occurrence #${e.occurrence_index} · ${t}`:t}function v$(e){const{node:t,ctx:n}=e,r=t.run,i=Vd(r,n),a=g$(r,i),u=String(r.run_id||"");return s.jsxs("li",{className:"ap_tree_item",children:[s.jsxs("button",{type:"button",className:`ap_tree_node ${t.is_subject?"ap_tree_subject":""}`,"aria-current":t.is_subject?"true":void 0,title:`Open run ${u}`,"data-run-id":u,onClick:()=>e.on_open_run(u),children:[s.jsx("span",{className:`chip ${_a(a)}`,children:a}),s.jsx("span",{className:"ap_tree_name",children:w$(r)}),s.jsx("span",{className:`ap_tree_line ${i.stalled?"ap_stalled":""}`,children:i.text})]}),t.children.length?s.jsx("ul",{className:"ap_tree_children",children:t.children.map(c=>s.jsx(v$,{node:c,ctx:n,on_open_run:e.on_open_run},String(c.run.run_id)))}):null]})}function op(e){return e===null?"—":ss(e)}function p9(e){var A,E;const t=typeof e.now_ms=="number"?e.now_ms:Date.now(),n=_.useMemo(()=>p$(e.run,e.detail),[e.run,e.detail]),r=String(n.run_id||"").trim(),i=_$(e.run,e.detail),a=_.useMemo(()=>e.automation??(e.automation_body?_h(e.automation_body):null),[e.automation,e.automation_body]),u=_.useMemo(()=>i9(e.runs||[],n),[e.runs,n]),c=_.useMemo(()=>{const z=new Map;e.detail&&i&&z.set(r,e.detail);const F=new Map;return a!=null&&a.automation_id&&F.set(a.automation_id,a),Lv(u,{now_ms:t,details:z,pulses:e.pulses,automations:F,stall_after_ms:e.stall_after_ms})},[u,e.detail,i,r,a,t,e.pulses,e.stall_after_ms]),d=Vd(n,c),m=cN(n,c),h=String(((E=(A=e.input_data)==null?void 0:A.input_data)==null?void 0:E.prompt)||"").trim(),p=uN(n,c,h?{excerpt:h}:null),y=g$(n,d,Cp(e.detail),e.automation),w=[m.label&&m.label!==p.text?m.label:"",m.secondary].filter(Boolean),x=a9(d,r),k=_.useMemo(()=>t9(e.detail,e.input_data,e.flow,e.automation_body??a,e.records,u,t,{subject_run_id:r,row:n}),[e.detail,e.input_data,e.flow,e.automation_body,a,e.records,u,t,r,n]),b=_.useMemo(()=>m$(r,u),[r,u]),S=_.useMemo(()=>YB(b,u,t),[b,u,t]),$=(a==null?void 0:a.title)||"automation";return s.jsxs("article",{className:"ap_page","data-run-id":r,children:[s.jsxs("header",{className:"ap_header",children:[s.jsxs("div",{className:"ap_title_row",children:[s.jsx("span",{className:`ap_mark ap_mark_${m.kind}`,title:m.kind,children:m.glyph}),s.jsx("h1",{className:`ap_title ${p.untitled?"ap_untitled":""}`,title:`Title from: ${p.source}`,children:p.text}),p.untitled?s.jsx("span",{className:"ap_untitled_tag",children:"untitled"}):null,s.jsx("span",{className:`chip ${_a(y,Cp(e.detail))}`,children:y}),s.jsx(c9,{run_id:r,on_copy:e.on_copy})]}),w.length?s.jsx("div",{className:"ap_subject_line",children:w.join(" · ")}):null,s.jsxs("div",{className:`ap_state ap_verb_${d.verb} ${d.stalled?"ap_stalled":""}`,"data-lane":d.lane,children:[s.jsx("span",{className:"ap_state_text",children:d.text}),s.jsx(l9,{line:d,ctx:c,on_open_run:e.on_open_run}),x?s.jsx("button",{type:"button",className:`btn ${d.actor==="you"?"primary":""} ap_action`,onClick:()=>e.on_action(x.action,x.run_id),children:x.label}):null]}),e.loading.detail?s.jsx(Zn,{kind:"loading",children:"reading the run detail… (the line above is from the listing row)"}):null,e.errors.detail?s.jsxs(Zn,{kind:"error",children:["run detail unavailable: ",e.errors.detail," (the line above is from the listing row)"]}):null,e.detail&&!i?s.jsx(Zn,{kind:"info",children:"the listing row is newer than the detail: the line above is from the row"}):null]}),s.jsx(m9,{prof:k,p:e,line:d,ctx:c}),s.jsx(h9,{p:e}),s.jsx(_9,{p:e}),s.jsx(ec,{id:"tree",title:"Run tree",meta:b.size?`${b.size} run${b.size===1?"":"s"}`:void 0,children:b.root?s.jsxs(s.Fragment,{children:[b.controller_id?s.jsxs("button",{type:"button",className:"ap_tree_parent",title:`Open the automation's controller run ${b.controller_id}`,"data-run-id":b.controller_id,onClick:()=>e.on_open_run(b.controller_id),children:[s.jsx("span",{className:"ap_mark ap_mark_automation",children:"⟳"}),s.jsx("span",{className:"ap_tree_name",children:$}),s.jsxs("span",{className:"ap_tree_line",children:[b.controller?Vd(b.controller,c).text:"controller (row not loaded)"," · other occurrences not shown"]})]}):null,s.jsx("ul",{className:`ap_tree ${b.controller_id?"ap_tree_under_parent":""}`,children:s.jsx(v$,{node:b.root,ctx:c,on_open_run:e.on_open_run})})]}):s.jsx(Zn,{kind:"absent",children:"this run is not among the loaded rows"})}),s.jsxs(ec,{id:"spend",title:"Spend",meta:"tree-inclusive",children:[S.any_metrics?null:s.jsx(Zn,{kind:"absent",children:"token and call counts not loaded: these rows were listed without metrics"}),S.rows.length?s.jsx("div",{className:"ap_table_wrap",children:s.jsxs("table",{className:"ap_spend",children:[s.jsx("caption",{children:"Tree-inclusive: each row counts its own run and every run below it, so rows do not add up."}),s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{scope:"col",children:"Run"}),s.jsx("th",{scope:"col",children:"Time"}),s.jsx("th",{scope:"col",children:"Tokens"}),s.jsx("th",{scope:"col",children:"LLM calls"}),s.jsx("th",{scope:"col",children:"Tool calls"}),s.jsx("th",{scope:"col",children:"Steps"})]})}),s.jsx("tbody",{children:S.rows.map(z=>{const F=c.by_id.get(z.run_id);return s.jsxs("tr",{className:z.is_subject?"ap_spend_subject":void 0,"data-run-id":z.run_id,children:[s.jsxs("th",{scope:"row",className:"ap_copyable",style:{"--ap-depth":z.depth},children:[s.jsx("span",{className:"ap_spend_name",children:F?w$(F):"run (row not loaded)"}),s.jsx(ug,{text:z.run_id,label:"run id"})]}),s.jsx("td",{children:z.duration_ms===null?"—":`${cu(z.duration_ms)}${z.running?" so far":""}`}),s.jsx("td",{children:op(z.tokens_total)}),s.jsx("td",{children:op(z.llm_calls)}),s.jsx("td",{children:op(z.tool_calls)}),s.jsx("td",{children:op(z.steps)})]},z.run_id)})})]})}):s.jsx(Zn,{kind:"absent",children:"no rows"})]}),s.jsxs(ec,{id:"ask",title:"Ask",children:[s.jsx("p",{className:"ap_window_note",children:e.ask_window_note||"Ask a question about this run and the runs below it."}),s.jsx("button",{type:"button",className:"btn primary ap_ask",onClick:()=>e.on_ask(),children:"Ask about this run"})]})]})}const Ok={key:"",loading:!1,input_data:null,input_error:"",flow:null,flow_error:"",automation_body:null,automation:null,automation_error:"",runs:[],runs_error:""},ap=500,Yp="http://127.0.0.1:8080";function Pk(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 km(e){const t=String(e||"").trim();return t.startsWith("abstractcode.")?`abstract.${t.slice(13)}`:t}function qy(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 Hy(e){const t=String(e||"").trim();return t.startsWith("abstract.")||t.startsWith("abstractcode.")}function g9(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 y9(e){if(!e||typeof e!="object")return[];const t=Array.isArray(e.nodes)?e.nodes:[];if(!t.length)return[];let n=null;for(const c of t){if(!c||typeof c!="object")continue;const d=c.data&&typeof c.data=="object"?c.data:{};if(String(d.nodeType||c.type||"").trim()==="on_flow_start"){n=c;break}}if(!n)return[];const r=n.data&&typeof n.data=="object"?n.data:{},i=Array.isArray(r.outputs)?r.outputs:[],a=r.pinDefaults&&typeof r.pinDefaults=="object"?r.pinDefaults:{},u=[];for(const c of i){if(!c||typeof c!="object")continue;const d=String(c.id||"").trim();if(!d)continue;const m=String(c.type||"").trim();if(m==="execution"||d==="exec-out"||d==="exec")continue;const h=String(c.label||d).trim()||d,p={id:d,label:h,type:m||"unknown"};a&&Object.prototype.hasOwnProperty.call(a,d)&&(p.default=a[d]),u.push(p)}return u}function Vy(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 w9(){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)||Yp),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:Yp,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 v9(e){localStorage.setItem("abstractobserver_settings",JSON.stringify({...e,auth_token:""}))}function x9(e){if(!e||typeof e!="object"||Array.isArray(e))return[];const t=[],n=(i,a)=>{const u=String(a??"").trim();u&&(t.some(c=>c.label===i&&c.value===u)||t.push({label:i,value:u}))},r=String(e.display??"").trim().replace(/^\[/,"").replace(/\]$/,"");return n("time",r||e.local_datetime),n("tz",e.timezone),n("country",e.country),n("user",e.user),t}function Dk(e){const t=x9(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 b9(){return typeof window>"u"?"":rR(window.location)}function k9(){try{const e="abstractobserver_session_id_v1",t=window.sessionStorage.getItem(e);if(t&&t.trim())return t.trim();const n=`obs_${Xs()}`;return window.sessionStorage.setItem(e,n),n}catch{return""}}function j9(){var Zf,ld,cd,w_,Fo,Qf,ud,ra,dd,ia,em,tm,fd,Oc,v_;const[e,t]=_.useState("board"),[n,r]=_.useState(()=>w9()),i=typeof window<"u"&&((Zf=window.__ABSTRACT_UI_CONFIG__)==null?void 0:Zf.monitor_gpu)===!0,a=typeof window<"u"&&(((ld=window.__ABSTRACT_UI_CONFIG__)==null?void 0:ld.entity_app_url)||"").trim().replace(/\/+$/,"")||"http://127.0.0.1:3007",u=_.useRef(null),[c,d]=_.useState(""),[m,h]=_.useState(""),[p,y]=_.useState(()=>b9()),[w,x]=_.useState(""),[k,b]=_.useState(""),[S,$]=_.useState(""),[A,E]=_.useState("{}"),[z]=_.useState(()=>k9()),[F,M]=_.useState(null),[D,H]=_.useState(!1),[q,I]=_.useState(""),[Z,R]=_.useState(!1),[T,P]=_.useState(""),[L,te]=_.useState(!1),X=g2({appName:"AbstractObserver",variant:"dismissable",defaultGatewayUrl:typeof window<"u"&&((cd=window.__ABSTRACT_UI_CONFIG__)==null?void 0:cd.gateway_url)||Yp,onStatusChange:v=>xc(v)}),[V,ne]=_.useState(null),[W,Y]=_.useState(null),[K,fe]=_.useState(!1),[ae,ve]=_.useState(null),[ge,pe]=_.useState("once"),[$e,De]=_.useState(!1),[ot,bt]=_.useState(null);function Ue(v){pe(v),De(!0)}const[at,Nt]=_.useState(""),[ut,Se]=_.useState(_w),[me,Ve]=_.useState([]),[ye,Ie]=_.useState(null),[ct,ie]=_.useState(!1),[Te,et]=_.useState([]),Ge=_.useRef(new sL(Xs)),[Be,Rt]=_.useState({available:!1,reason:"Sign in to a gateway to use automations."}),[Nn,Qt]=U2("abstractobserver",{legacyKey:"abstractobserver_settings"}),[Un,rs]=_.useState(!1),[Dn,$n]=_.useState(!1),[Cn,an]=_.useState([]),[is,Wn]=_.useState([]),[Fn,Hs]=_.useState([]),[es,he]=_.useState(!1),[Ee,mt]=_.useState(null),[se,ce]=_.useState(null),[je,Ae]=_.useState(0),[ze,Fe]=_.useState(""),Ze=_.useRef(!1),lt=_.useRef(0),ht=_.useRef(0),[_t,kt]=_.useState(!1),[At,rt]=_.useState([]),[zt,dn]=_.useState([]),[on,Ht]=_.useState({}),[Ot,ts]=_.useState(!1),[Pe,Ut]=_.useState(!1),[St,Mn]=_.useState(!1),[nn,Je]=_.useState([]),[en,Yt]=_.useState([]),Cr=_.useRef(0),Ns=_.useRef(null);Ns.current||(Ns.current=new Kb(v=>window.setTimeout(v,40),v=>Je(C=>C.concat(v))));const ps=_.useRef(null);ps.current||(ps.current=new Kb(v=>window.setTimeout(v,40),v=>Yt(C=>C.concat(v))));const _r=_.useRef({scanned:0,found:null}),[we,wt]=_.useState(null),[Rn,tr]=_.useState(""),[bi,nr]=_.useState(!1),po=_.useRef(null),[sc,Qa]=_.useState({}),[ws,pr]=_.useState({}),[Ms,Fi]=_.useState(!1),[el,gs]=_.useState(""),[si,Rs]=_.useState(!0),[ri,vs]=_.useState(""),[ii,zi]=_.useState(!1),[Sn,ga]=_.useState(!1),[tl,nl]=_.useState(6),[Er,rc]=_.useState("standard"),[Bi,ya]=_.useState(""),[go,Ps]=_.useState(""),[Ds,gr]=_.useState(!1),[yo,Wr]=_.useState(!1),[Ar,qr]=_.useState("pause"),[ic,Hr]=_.useState(""),[uu,ki]=_.useState(""),[Vo,sl]=_.useState(""),wo=_.useRef(null),oi=_.useRef(null),[wa,Ui]=_.useState(!1),sr=_.useRef(null),[tf,ai]=_.useState(""),[qn,G]=_.useState(Ok),ue=_.useRef(0),[Me,Re]=_.useState(""),[Ke,dt]=_.useState(""),[Lt,Ct]=_.useState(""),[Tt,cn]=_.useState(!1),[wn,Vs]=_.useState("idle"),[Et,_n]=_.useState([]),[os,zn]=_.useState(null),Tr=_.useRef(null),[yr,Wi]=_.useState(!1),[rl,qi]=_.useState(""),[nf,oc]=_.useState(""),[va,xa]=_.useState(""),[sf,ac]=_.useState([]),[lc,du]=_.useState(!1),[rf,fu]=_.useState(""),[of,mu]=_.useState(""),[hu,il]=_.useState(!1),[wh,ba]=_.useState(""),vh=_.useMemo(()=>{if(!Et.length)return"";try{return JSON.stringify(Et.map(v=>({role:v.role,content:v.content,ts:v.ts})))}catch{return"1"}},[Et]),_u=_.useMemo(()=>Et.length?va?vh!==va:!0:!1,[vh,Et.length,va]),af=_.useMemo(()=>sf.map(v=>{const C=String(v.title||"").trim()||`Chat ${String(v.thread_id||"").slice(0,8)}`,O=String(v.created_at||"").trim(),B=O?O.replace("T"," ").slice(0,19):"",ee=String(v.run_id||"").trim()?String(v.run_id).slice(0,8):"",J=[C,B&&`(${B})`,ee&&`run ${ee}`].filter(Boolean).join(" • ");return{value:String(v.thread_id||""),label:J}}),[sf]);_.useEffect(()=>{i&&O3()},[i]),_.useEffect(()=>{if(!i)return;const v=u.current;v&&(v.token=n.gateway_auth_mode==="direct"&&n.auth_token||"")},[i,n.auth_token,n.gateway_auth_mode]);const[,lf]=_.useState([]),[ol,xh]=_.useState([]),bh=(v,C)=>{const O=Date.now();xh(B=>{const ee=B.findIndex(Q=>Q.title===v);if(ee<0)return[...B,{title:v,preview:C,count:1,at:O}].slice(-4);const J=[...B];return J[ee]={title:v,preview:C,count:J[ee].count+1,at:O},J})},cf=ol.length?ol.map(v=>{const C=new Date(v.at),O=`${String(C.getHours()).padStart(2,"0")}:${String(C.getMinutes()).padStart(2,"0")}`;return`${v.title}: ${v.preview} · ${O}${v.count>1?` ×${v.count}`:""}`}).join(" — "):"",[vg,pu]=_.useState(!1),al=_.useRef(""),xg=_.useRef("");_.useEffect(()=>{var C,O;const v=String(((O=(C=V==null?void 0:V.gateway)==null?void 0:C.principal)==null?void 0:O.user_id)||"").trim();al.current=v||(L&&n.gateway_auth_mode==="direct"?"direct":"")},[V,L,n.gateway_auth_mode]);const[gu,vn]=_.useState(""),[yu,kh]=_.useState(""),[wu,ll]=_.useState("all"),[uf,bg]=_.useState("status"),[xs,vo]=_.useState("ledger"),df=jx(zg.md),cc=jx(`${zg.sm}, ${zg.short}`),Hi=YM({is_drawer:df,page:e}),ff=Hi.open,Go=Hi.set_open,[jh,Sh]=Ep("observe_runs"),mf=Hi.toggle_ref,hf=Hi.sidebar_ref,_f=_.useRef(null),[Nh,pf]=_.useState(()=>wb(typeof window<"u"?window.location.hash:"")),[kg,$h]=_.useState(""),[Ch,gf]=_.useState(""),[cl,wr]=_.useState(""),[Vi,ul]=_.useState(null),[uc,vu]=_.useState({}),[yf,ka]=_.useState(!1),[Eh,dc]=_.useState(""),[Gi,wf]=_.useState(!1),[ja,vf]=_.useState(!1),[xu,Sa]=_.useState(()=>Date.now()),[Mr,Ko]=_.useState(""),[Ah,Na]=_.useState({}),[Th,bu]=_.useState({}),dl=_.useRef([]),Vr=_.useRef(null),xo=_.useRef(""),fc=_.useRef({}),Gr=_.useRef({}),mc=_.useRef({}),$a=_.useRef(new Set),[bo,ku]=_.useState([]),ko=_.useRef(""),fl=_.useRef({}),jo=_.useRef(null),vr=_.useRef(null),Ln=_.useRef(0),Jo=_.useRef({}),Ca=_.useRef(!1),ji=_.useRef(new Set),[ju,ml]=_.useState(""),[Rr,Si]=_.useState(""),xr=_.useRef(""),xf=()=>({artifact_id:"",kind:"binary",render_kind:"",text:"",url:"",loading:!1,error:""}),[hc,Mh]=_.useState("activity"),[Su,_c]=_.useState([]),[pc,Nu]=_.useState(0),[bf,$u]=_.useState(0),[kf,Rh]=_.useState({}),[Lh,Ih]=_.useState({}),[jg,Cu]=_.useState(!1),[Yo,jf]=_.useState(""),[Ki,Ji]=_.useState(""),[So,Ni]=_.useState("all"),[hl,Oh]=_.useState(""),[_l,Ea]=_.useState([]),[Xo,pl]=_.useState("all"),[No,Sf]=_.useState("type"),[$o,Zo]=_.useState("newest"),[En,Vn]=_.useState(""),[li,$s]=_.useState(""),[br,Co]=_.useState(""),[Yi,rr]=_.useState(0),[Eo,Eu]=_.useState(()=>xf()),[Ph,gl]=_.useState(!1),[Au,Ao]=_.useState(""),[Tu,Qo]=_.useState(""),[ir,Mu]=_.useState(""),[Xi,yl]=_.useState("text"),[wl,vl]=_.useState(null),[Ru,kr]=_.useState(!1),[Kr,Zi]=_.useState(""),[Qi,eo]=_.useState(""),[Aa,Nf]=_.useState(""),[Lu,Iu]=_.useState(!1),[Jr,Lr]=_.useState(""),[Gn,$i]=_.useState("run_ledger"),[Dh,Fh]=_.useState(""),[$f,gc]=_.useState([]),[zh,xl]=_.useState(""),[Bh,Ta]=_.useState(!1),[Cf,Ef]=_.useState(""),qe=_.useMemo(()=>new uy({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]),Kn=_.useMemo(()=>new gL(qe.automations_client(),hL(qe,Xs,Vt)),[qe]),Ou=_.useSyncExternalStore(v=>Kn.subscribe(v),()=>Kn.state),Af=YR(n.gateway_url),To=Af?()=>{window.open(Af,"_blank","noopener,noreferrer")}:void 0,Uh=Nj($e&&ge==="automate"&&L?eL(ut):null,Kn.preview_schedule);_.useEffect(()=>{$e&&ge==="automate"&&L&&Kn.load_email_status()},[e,ge,L,Kn]),_.useEffect(()=>{const v=()=>{const C=ZR(window.location.hash);if(C){if(C.page==="run"){y(C.run_id),pf(wb(window.location.hash));return}if(C.page==="launch"){Ue(C.mode);return}t(C.page)}};return v(),window.addEventListener("hashchange",v),()=>window.removeEventListener("hashchange",v)},[]);const Pu=_.useMemo(()=>{const v={};for(const C of Ou.items)v[C.automation_id]=C.title;return v},[Ou.items]),Du=_.useMemo(()=>S3(),[]),[bl,Fu]=_.useState(Mb),zu=_.useRef(0);function Tf(){const v=++zu.current;Fu(Mb),N3(qe).then(C=>{v===zu.current&&Fu(C)})}const kl=_.useMemo(()=>n.worker_url.trim()?new PI({url:n.worker_url.trim(),auth_token:n.worker_token}):null,[n.worker_url,n.worker_token]),Ma=_.useMemo(()=>LI(qe.fetch_gateway,xw),[qe]),ns=nn.length?nn[nn.length-1].record:null,sn=_.useMemo(()=>Wa(ns),[ns]),Fs=_.useMemo(()=>{const v=S.trim();if(!F||!v||String(F.bundle_id||"").trim()&&String(F.bundle_id||"").trim()!==v)return null;const C=Array.isArray(F.entrypoints)?F.entrypoints:[];if(!C.length)return null;const O=k.trim();if(O)return C.find(ee=>String(ee.flow_id||"").trim()===O)||null;if(C.length===1)return C[0];const B=String(F.default_entrypoint||"").trim();return B&&C.find(ee=>String(ee.flow_id||"").trim()===B)||null},[F,S,k]),Bu=_.useMemo(()=>{const v=Fs==null?void 0:Fs.inputs;return Array.isArray(v)?v:[]},[Fs]),to=_.useMemo(()=>y9(Vi),[Vi]),ci=_.useMemo(()=>Bu.length?Bu:to,[Bu,to]),ea=_.useMemo(()=>{const v=typeof(we==null?void 0:we.workflow_id)=="string"?String(we.workflow_id):"",C=Pk(v);if(C&&F&&String(F.bundle_id||"").trim()===C.bundle_id){const ee=(Array.isArray(F.entrypoints)?F.entrypoints:[]).find(J=>String((J==null?void 0:J.flow_id)||"").trim()===C.flow_id);if(ee&&ee.node_index&&typeof ee.node_index=="object")return ee.node_index}const O=Fs==null?void 0:Fs.node_index;return O&&typeof O=="object"?O:{}},[we,F,Fs]);_.useEffect(()=>{v9(n)},[n]),_.useEffect(()=>()=>{jo.current&&jo.current.abort(),vr.current&&vr.current.abort(),wo.current&&window.clearTimeout(wo.current),oi.current&&window.clearTimeout(oi.current),Vr.current&&window.clearTimeout(Vr.current),sr.current&&window.clearTimeout(sr.current)},[]);const tn=_.useMemo(()=>{const v=A.trim();if(!v)return{};try{const C=JSON.parse(v);return typeof C!="object"||C===null||Array.isArray(C)?null:C}catch{return null}},[A]),Mo=typeof(tn==null?void 0:tn.prompt)=="string"?String(tn.prompt):"",no=typeof(tn==null?void 0:tn.provider)=="string"?String(tn.provider):"",Uu=typeof(tn==null?void 0:tn.model)=="string"?String(tn.model):"",Wh=typeof(tn==null?void 0:tn.workspace_root)=="string"?String(tn.workspace_root):"",Wu=_.useMemo(()=>{const v=tn==null?void 0:tn.workspace;return v&&typeof v=="object"&&!Array.isArray(v)?v:null},[tn]),qh=ci.length>0&&!!S.trim(),Ra=v=>{const C=String(v||"").trim().toLowerCase();return C==="object"||C==="memory"||C==="assertion"||C==="assertions"||C==="any"};_.useEffect(()=>{pr({})},[S,k]),_.useEffect(()=>{tn!==null&&Qa(v=>{const C={};for(const O of ci){if(!O||typeof O!="object")continue;const B=String(O.id||"").trim();if(!B)continue;const ee=String(O.type||"").trim();if(!Ra(ee))continue;if(String(ws[B]||"").trim()){C[B]=typeof v[B]=="string"?v[B]:"";continue}const Q=tn==null?void 0:tn[B];Q===void 0?C[B]="":C[B]=AR(Q)}return C})},[ci,tn,ws]);const zs=at?{kind:"default",interface:at}:S.trim()&&k.trim()?{kind:"bundle",bundle_id:S.trim(),flow_id:k.trim()}:null,jl=VR(zs),Ci=Array.isArray(tn==null?void 0:tn.skills)?tn.skills.map(v=>String(v||"").trim()).filter(Boolean):[],Gs=_.useMemo(()=>{const v={};for(const C of Cn){const O=String(C.workflow_id||"").trim(),B=String(C.label||"").trim();O&&B&&(v[O]=B)}return v},[Cn]),Sl=Mj({interfaceId:null,defaultInterface:Id,request:(v,C)=>qe.get_gateway_json(v,C.signal),enabled:L,reloadKey:Cn}),Nl=_.useMemo(()=>{const v=new Set;for(const C of Array.isArray(zt)?zt:[]){const O=String((C==null?void 0:C.name)||"").trim();O&&v.add(O)}return Array.from(v).sort()},[zt]),Hh=_.useMemo(()=>{const v=[];for(const C of Array.isArray(zt)?zt:[]){const O=String((C==null?void 0:C.name)||"").trim();if(!O)continue;const B=String((C==null?void 0:C.display_name)||"").trim();v.push({name:O,display_name:B||void 0})}return v},[zt]),yc=_.useMemo(()=>{const v=new Set;for(const C of At||[]){if(!C||typeof C!="object")continue;const O=String(C.name||"").trim();O&&v.add(O)}return Array.from(v).sort()},[At]),as=_.useMemo(()=>{const v=n.maintenance_ai_provider.trim();if(!v)return{models:[],error:""};const C=on[v];return C?{models:(Array.isArray(C.models)?C.models:[]).map(B=>String(B||"").trim()).filter(Boolean),error:String(C.error||"")}:{models:[],error:""}},[on,n.maintenance_ai_provider]),$l=n.maintenance_ai_provider.trim(),Mf=!!($l&&L&&!Object.prototype.hasOwnProperty.call(on,$l));_.useEffect(()=>{const v=no.trim();if(!v||on[v]||fl.current[v])return;fl.current[v]=!0;let C=!1;return(async()=>{try{const B=await qe.discovery_provider_models(v);if(C)return;const ee=Array.isArray(B==null?void 0:B.models)?B.models:[],J=typeof(B==null?void 0:B.error)=="string"?String(B.error):"";Ht(Q=>({...Q,[v]:{models:ee,error:J||void 0}}))}catch(B){if(C)return;Ht(ee=>({...ee,[v]:{models:[],error:String((B==null?void 0:B.message)||B||"Failed to load models")}}))}finally{delete fl.current[v]}})(),()=>{C=!0}},[no,on,qe]),_.useEffect(()=>{const v=n.maintenance_ai_provider.trim();if(!v||!L||on[v]||fl.current[v])return;fl.current[v]=!0;let C=!1;return(async()=>{try{const B=await qe.discovery_provider_models(v);if(C)return;const ee=Array.isArray(B==null?void 0:B.models)?B.models:[],J=typeof(B==null?void 0:B.error)=="string"?String(B.error):"";Ht(Q=>({...Q,[v]:{models:ee,error:J||void 0}}))}catch(B){if(C)return;Ht(ee=>({...ee,[v]:{models:[],error:String((B==null?void 0:B.message)||B||"Failed to load models")}}))}finally{delete fl.current[v]}})(),()=>{C=!0}},[n.maintenance_ai_provider,on,qe,L]);function ms(v,C){const O=String(v||"").trim();if(!O)return;let B={};try{const ee=JSON.parse(A||"{}");typeof ee=="object"&&ee!==null&&!Array.isArray(ee)&&(B=ee)}catch{B={}}if(C==null){delete B[O],E(JSON.stringify(B,null,2));return}if(typeof C=="string")C?B[O]=C:delete B[O];else if(Array.isArray(C)){const ee=C.map(J=>J).filter(J=>J!=null);ee.length?B[O]=ee:delete B[O]}else B[O]=C;E(JSON.stringify(B,null,2))}async function wc(v){const C=String(v||"").trim();if(!C)return I("Missing bundle_id"),null;I(""),H(!0);try{const O=await qe.get_bundle(C);return M(O),hn({ts:Vt(),kind:"info",title:`Loaded bundle ${C}`}),O}catch(O){return M(null),I(String((O==null?void 0:O.message)||O||"Failed to load bundle")),null}finally{H(!1)}}function vc(v){const C=[],O=Array.isArray(v==null?void 0:v.items)?v.items:[];for(const B of O){const ee=String((B==null?void 0:B.bundle_id)||"").trim();if(!ee)continue;const J=Array.isArray(B==null?void 0:B.entrypoints)?B.entrypoints:[];if(J.length)for(const Q of J){const re=String((Q==null?void 0:Q.flow_id)||"").trim();if(!re||(Q==null?void 0:Q.deprecated)===!0)continue;const We=`${ee}:${re}`,be=String((Q==null?void 0:Q.name)||"").trim(),_e=be?`${ee} · ${be}`:`${ee} · ${re}`,Le=String((Q==null?void 0:Q.description)||"").trim(),tt=(Array.isArray(Q==null?void 0:Q.interfaces)?Q.interfaces:[]).some(nt=>String(nt||"").trim().length>0),ft=Array.isArray(Q==null?void 0:Q.agent_default_interfaces)?Q.agent_default_interfaces.map(nt=>String(nt||"").trim()).filter(Boolean):[];C.push({workflow_id:We,bundle_id:ee,bundle_ref:String((B==null?void 0:B.bundle_ref)||"").trim(),flow_id:re,label:_e,description:Le||void 0,has_interface:tt,agent_default_interfaces:ft})}}return C.sort((B,ee)=>B.label.localeCompare(ee.label)),C}async function bs(v=qe,C){if(Ze.current&&!(C!=null&&C.force))return;Ze.current=!0;const O=Yr.current;he(!0);const B=_e=>_e.map(z_).filter(Le=>!!Le.run_id),ee=_e=>Array.isArray(_e==null?void 0:_e.items)?_e.items:[],J=cz(v,O),Q=()=>{const _e=J.view();Wn(_e.roots),Hs(_e.all)},re=(_e,Le)=>{if(String((_e==null?void 0:_e.name)||"")==="Superseded")return;const Oe=String((_e==null?void 0:_e.message)||_e||"");if(hn({ts:Vt(),kind:"error",title:Le,preview:Wt(Oe)}),bh(Le,Wt(Oe)),(/\b40[13]\b/.test(Oe)||/unauthorized|forbidden/i.test(Oe))&&X.refresh().catch(()=>{}),/\b429\b/.test(Oe)||/too many requests/i.test(Oe)){const tt=Math.min(12e4,Math.max(15e3,ht.current*2||15e3));ht.current=tt,lt.current=Date.now()+tt,hn({ts:Vt(),kind:"info",title:`Gateway rate-limited — pausing polls ${Math.round(tt/1e3)}s`})}},We=al.current,be=We?oz(String(n.gateway_url||""),We):"";xg.current=be,be&&J.active_at===null&&J.seed(az(pk(),be))&&J.active_at!==null&&(Q(),mt(J.active_at),pu(!0));try{const[_e,Le]=await Promise.allSettled([v.list_runs({status:"running",limit:hk}),v.list_runs({status:"waiting",limit:_k})]);if(O!==Yr.current)return;if(_e.status==="rejected"&&Le.status==="rejected")throw _e.reason;_e.status==="rejected"&&re(_e.reason,"Runs listing (running) failed"),Le.status==="rejected"&&re(Le.reason,"Runs listing (waiting) failed");const Oe=_e.status==="fulfilled"?_e.value:null,tt=Le.status==="fulfilled"?Le.value:null,ft=Oe?ee(Oe):J.active_rows.filter(it=>String(it.status||"")==="running"),nt=tt?ee(tt):J.active_rows.filter(it=>String(it.status||"")==="waiting"),fn=!!(Oe&&tt)&&ft.length<hk&&nt.length<_k&&(Oe==null?void 0:Oe.has_more)!==!0&&(tt==null?void 0:tt.has_more)!==!0,Xt=J.seeded;J.apply_active(B(ft),B(nt),fn),!(Oe&&tt)&&Xt&&(J.seeded=!0),Q(),mt(Date.now()),pu(!(Oe&&tt)&&Xt),Oe&&tt&&xh([]),ht.current=0,lt.current=0,be&&Oe&&tt&&window.setTimeout(()=>lz(pk(),be,J.snapshot()),0)}catch(_e){re(_e,"Refresh runs failed");return}finally{Ze.current=!1,he(!1)}J.sweep_due(Date.now(),(C==null?void 0:C.force)===!0)&&(J.begin_sweep(Date.now()),v.list_runs({limit:200,root_only:!0,include_metrics:!0}).then(async _e=>{const Le=Number(_e==null?void 0:_e.archived_sessions);if(Number.isFinite(Le)&&Le<=0)return[_e,{items:[]}];const Oe=await v.list_runs({limit:200,root_only:!0,archived_only:!0,include_metrics:!0});return[_e,Oe]}).then(([_e,Le])=>{if(O!==Yr.current||!gk(J))return J.fail_sweep();const Oe=iL(ee(_e),ee(Le));J.apply_sweep(B(Oe),Date.now()),Q()},_e=>{J.fail_sweep(),!(O!==Yr.current||!gk(J))&&re(_e,"Refresh run metrics failed")}))}async function ls(v){var re,We,be;const C=Yr.current;te(!0),Ht({}),v.list_apps().then(_e=>{if(C!==Yr.current)return;const Oe=(Array.isArray(_e==null?void 0:_e.apps)?_e.apps:[]).find(ft=>String((ft==null?void 0:ft.id)||"")==="code"),tt=Oe&&Oe.installed===!0&&Oe.running===!0?String(Oe.url||"").trim():"";bt(tt?{url:tt}:null)}).catch(()=>{C===Yr.current&&bt(null)});const[O,,B,ee,J]=await Promise.allSettled([v.list_bundles(),bs(v),v.discovery_tools(),v.discovery_providers({include_models:!1}),v.discovery_capabilities()]);if(C!==Yr.current)return;if(O.status==="rejected"&&B.status==="rejected"&&ee.status==="rejected"){te(!1),P(Vy(O.reason,n)),hn({ts:Vt(),kind:"error",title:"Discovery failed",preview:Wt(String(O.reason||""))});return}Rt(J.status==="fulfilled"?oL(J.value):{available:!1,reason:`Could not read the gateway capabilities: ${String(((re=J.reason)==null?void 0:re.message)||J.reason)}`});let Q=0;if(O.status==="fulfilled"){const _e=vc(O.value);Q=_e.length,an(_e)}else an([]),hn({ts:Vt(),kind:"error",title:"Discovery bundles failed",preview:Wt(String(O.reason||""))});if(B.status==="fulfilled"){const _e=Array.isArray((We=B.value)==null?void 0:We.items)?B.value.items:[];rt(_e)}else rt([]),hn({ts:Vt(),kind:"error",title:"Discovery tools failed",preview:Wt(String(B.reason||""))});if(ee.status==="fulfilled"){const _e=Array.isArray((be=ee.value)==null?void 0:be.items)?ee.value.items:[];dn(_e)}else dn([]),hn({ts:Vt(),kind:"error",title:"Discovery providers failed",preview:Wt(String(ee.reason||""))});hn({ts:Vt(),kind:"info",title:"Gateway discovery loaded",preview:Wt(`workflows: ${Q}`)})}async function hs(v){var C,O;P(""),te(!1),R(!0);try{if(!(v!=null&&v.prefer_direct)&&(await X.refresh(),Cs.current))return;const B=String(n.auth_token||"").trim();if(!B){v!=null&&v.open_modal_if_needed&&X.openModal();return}const ee=String(n.gateway_url||"").trim();if(ee){const Q=ee.toLowerCase();if(!Q.startsWith("http://")&&!Q.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:"&&Q.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 We=new URL(ee),be=String(((O=window==null?void 0:window.location)==null?void 0:O.hostname)||"").trim().toLowerCase(),_e=String(We.hostname||"").trim().toLowerCase(),Le=Oe=>Oe==="localhost"||Oe==="127.0.0.1"||Oe==="::1";if(Le(_e)&&be&&!Le(be))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(re){throw new Error(String((re==null?void 0:re.message)||re||"Invalid Gateway URL"))}}const J=new uy({base_url:ee,auth_token:B});await J.list_bundles(),r(Q=>({...Q,gateway_auth_mode:"direct"})),await ls(J)}catch(B){P(Vy(B,n))}finally{R(!1)}}const Cs=_.useRef(!1),Yr=_.useRef(0),La=_.useRef(!1);function xc(v){var O,B,ee;ne(v);const C=!!(v&&v.has_session&&((O=v.gateway)!=null&&O.ok));if(Cs.current=C,C){if(La.current=!1,L&&n.gateway_auth_mode==="direct")return;const J=String(((ee=(B=v==null?void 0:v.gateway)==null?void 0:B.principal)==null?void 0:ee.user_id)||"").trim();if(r(Q=>({...Q,gateway_auth_mode:"session",auth_token:"",gateway_user:J||Q.gateway_user})),L&&n.gateway_auth_mode==="session")return;P(""),R(!0),ls(new uy({base_url:"",auth_token:""})).catch(Q=>P(Vy(Q,n))).finally(()=>R(!1));return}v&&!v.has_session&&(n.gateway_auth_mode==="session"&&bc({keep_session:!0}),String(n.auth_token||"").trim()&&!L&&!La.current&&(La.current=!0,hs({prefer_direct:!0})))}async function Sg(){if(!(_t||Z)){kt(!0);try{await qe.reload_bundles();const v=await qe.list_bundles(),C=vc(v);an(C),hn({ts:Vt(),kind:"info",title:"Bundles reloaded",preview:Wt(`workflows: ${C.length}`)})}catch(v){const C=String((v==null?void 0:v.message)||v||"Bundle reload failed");hn({ts:Vt(),kind:"error",title:"Bundle reload failed",preview:Wt(C),data:{error:C}})}finally{kt(!1)}}}async function or(v){if(bi||Z||!L)return;const C=v;if(C){nr(!0),vn("");try{const O=await qe.upload_bundle(C,{overwrite:!1,reload:!0});hn({ts:Vt(),kind:"info",title:"Bundle uploaded",preview:Wt(String((O==null?void 0:O.bundle_ref)||""))});const B=await qe.list_bundles(),ee=vc(B);an(ee)}catch(O){const B=String((O==null?void 0:O.message)||O||"Upload failed");vn(B),hn({ts:Vt(),kind:"error",title:"Upload .flow failed",preview:Wt(B),data:{error:B}})}finally{nr(!1);try{po.current&&(po.current.value="")}catch{}}}}function bc(v){Yr.current+=1,v!=null&&v.keep_session||(X.signOut().catch(()=>{}),Cs.current=!1),Hu(),$(""),b(""),wr(""),M(null),I(""),H(!1),an([]),Wn([]),Hs([]),mt(null),ce(null),Ae(0),rt([]),dn([]),Ht({}),P(""),te(!1),ne(null),r(C=>({...C,auth_token:""})),hn({ts:Vt(),kind:"info",title:"Gateway disconnected"})}async function kc(v){const C=String(v??"");C&&Es(await hh(C)?"Copied to clipboard":$S,2)}_.useEffect(()=>{const v=c.trim();if(!Ot||!v)return;let C=!1;const O=async()=>{if(!(lt.current>Date.now()))try{const ee=await qe.get_run(v);C||wt(ee)}catch{}};O();const B=window.setInterval(O,2e3);return()=>{C=!0,window.clearInterval(B)}},[Ot,c,qe]),_.useEffect(()=>{if(!L)return;let v=null,C=!1,O=!1;const B=Q=>{C||(v!==null&&window.clearTimeout(v),v=window.setTimeout(()=>void ee(),Q))},ee=async()=>{if(O)return;const Q=lt.current-Date.now();if(Q>0){B(Q+500);return}O=!0;const re=Date.now();try{await bs(qe)}finally{O=!1;const We=Date.now()-re,be=document.visibilityState==="hidden"?3e4:5e3;B(Math.max(be,We*3))}},J=()=>{document.visibilityState==="visible"&&ee()};return ee(),document.addEventListener("visibilitychange",J),()=>{C=!0,v!==null&&window.clearTimeout(v),document.removeEventListener("visibilitychange",J)}},[L,qe]);const[Rf,ui]=_.useState(null);_.useEffect(()=>{if(!L){ui(null);return}let v=!1;return(async()=>{try{const C=await qe.get_entity_phases_spec();if(v)return;const O=Uz(C);if(ui(O),O)try{const B=localStorage.getItem("abstractobserver_phase_graph_id_v1"),ee=B?JSON.parse(B):null;ee&&ee.sha256&&O.sha256&&ee.sha256!==O.sha256&&ee.version===O.version&&hn({ts:Vt(),kind:"error",title:"Phase-graph drift: served bytes changed without a version bump",preview:Wt(`v${O.version}: ${String(ee.sha256).slice(0,12)}… -> ${String(O.sha256).slice(0,12)}…`),data:{prev:ee,now:{sha256:O.sha256,version:O.version}}}),localStorage.setItem("abstractobserver_phase_graph_id_v1",JSON.stringify({sha256:O.sha256,version:O.version}))}catch{}}catch(C){if(!v){ui(null);const O=String((C==null?void 0:C.message)||C||"");/404|not found/i.test(O)||hn({ts:Vt(),kind:"info",title:"Phase-graph fetch failed — pre-wire fallback vocabulary in use (#FALLBACK)",preview:Wt(O),data:{error:O}})}}})(),()=>{v=!0}},[L]),_.useEffect(()=>{if(!L){ce(null),Ae(0),Fe("");return}let v=!1,C=null;const O=async()=>{if(!(lt.current>Date.now())){try{const B=await qe.list_entities();v||Ae(B.entities.length);const ee=B.entities.map(Q=>String((Q==null?void 0:Q.name)||(Q==null?void 0:Q.slug)||"").trim()).filter(Boolean).slice(0,n$),J=await Promise.all(ee.map(async Q=>{var re,We;try{const[be,_e]=await Promise.all([qe.get_entity_card(Q),qe.get_entity_cognition(Q).catch(()=>null)]),Le=be!=null&&be.state&&typeof be.state=="object"?be.state:null,Oe=Array.isArray(be==null?void 0:be.moments)?be.moments:[],tt=Oe.length?Oe[Oe.length-1]:null,ft=(re=_e==null?void 0:_e.spend)==null?void 0:re.lifetime,nt=(We=_e==null?void 0:_e.spend)==null?void 0:We.live_visit,fn=Array.isArray(_e==null?void 0:_e.warnings)?_e.warnings.map(it=>String(it||"")).filter(Boolean):[],Xt=Fz(be);return{name:Q,state:String((Le==null?void 0:Le.state)??(typeof(be==null?void 0:be.state)=="string"?be.state:"")).trim(),age_days:typeof(be==null?void 0:be.age_days)=="number"?be.age_days:null,last_moment:String((tt==null?void 0:tt.kind)||"").trim(),last_moment_at:String((tt==null?void 0:tt.at)||"").trim(),working:typeof(_e==null?void 0:_e.working)=="boolean"?_e.working:null,tokens_total:typeof(ft==null?void 0:ft.tokens_total)=="number"?ft.tokens_total:null,live_visit_tokens:typeof(nt==null?void 0:nt.tokens_total)=="number"?nt.tokens_total:null,spend_warning:fn.join(" | "),live_phase:typeof(_e==null?void 0:_e.phase)=="string"?_e.phase:"",open_questions:Xt.questions,open_questions_total:Xt.questions_total,open_problems:Xt.problems,open_problems_total:Xt.problems_total,lessons:Xt.lessons,lessons_total:Xt.lessons_total,dreams_brief:Dz(be),error:""}}catch(be){return{name:Q,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((be==null?void 0:be.message)||be||"card failed")}}}));v||(ce(J),Ae(B.entities.length),Fe(""))}catch(B){if(!v){ce([]);const ee=String((B==null?void 0:B.message)||B||"");Fe(/404|not found/i.test(ee)?"":ee)}}v||(C=window.setTimeout(()=>void O(),3e4))}};return O(),()=>{v=!0,C!==null&&window.clearTimeout(C)}},[L,qe]);async function di(v,C,O){const B=String(C||"").trim();if(!v||!B)throw new Error("This wait has no wait_key yet — open the run to inspect.");await qe.submit_command({command_id:Xs(),run_id:v,type:"resume",payload:{wait_key:B,payload:O||{}},client_id:"web_pwa"}),hn({ts:Vt(),kind:"info",title:"Board resume submitted",preview:Wt(`run ${v} · wait ${B}`),data:{run_id:v,wait_key:B}}),bs(qe,{force:!0}),window.setTimeout(()=>void bs(qe,{force:!0}),1200)}const Ei=_.useMemo(()=>{const v=we==null?void 0:we.session_id;return typeof v=="string"?v.trim():v==null?"":String(v||"").trim()},[we]),Lf=_.useMemo(()=>{const v=String(Ei||"").trim();return v||String(z||"").trim()},[Ei,z]);_.useEffect(()=>{L||Ct("")},[L]);const[Cl,Vh]=AS(),If=TS(L?qe:null,L),so=MS({gateway:L?qe:null,session_id:Lf,prefs:Cl,on_error:Ct,on_transcript:v=>{const C=String(v||"").trim();C&&(Re(O=>{const B=String(O||"");return B.trim()?`${B.trimEnd()}
|
|
170
|
+
${C}`:C}),window.setTimeout(()=>{var O;return(O=Tr.current)==null?void 0:O.focus()},0))}}),Gh=_.useMemo(()=>{for(let v=Et.length-1;v>=0;v-=1){const C=Et[v];if(C.role==="assistant")return C.local_error?null:{key:String(C.id||C.ts||""),text:String(C.content||"")}}return null},[Et]);RS(so,Cl.read_aloud===!0,Gh);function Kh(v,C){try{const O=URL.createObjectURL(v),B=document.createElement("a");B.href=O,B.download=C||"download",B.rel="noreferrer",document.body.appendChild(B),B.click(),document.body.removeChild(B),window.setTimeout(()=>URL.revokeObjectURL(O),5e3)}catch{}}async function Of(){const v=Ch.trim();if(!v){Es("This run recorded no workspace",2);return}try{const C=await fetch(eR,{method:"POST",headers:{"Content-Type":"application/json",...xw()},body:JSON.stringify({path:v})}),O=await C.json().catch(()=>({}));C.ok&&(O!=null&&O.ok)?Es(`Opened ${String(O.path||v)}`,2):Es(String((O==null?void 0:O.error)||`Folder reveal failed (${C.status})`),3)}catch(C){Es(String((C==null?void 0:C.message)||C||"Folder reveal failed"),3)}}async function Jh(v){const C=String((v==null?void 0:v.run_id)||"").trim(),O=String((v==null?void 0:v.artifact_id)||"").trim();if(!C||!O){Es("Artifact download needs a run id",3);return}const B=Rp(v)||O;try{const ee=await qe.download_run_artifact_content(C,O,{access:"preview"});Kh(ee,bb(B)),Es("Downloaded artifact",2)}catch(ee){Es(String((ee==null?void 0:ee.message)||ee||"Download failed"),3)}}async function Yh(v){const C=String((v==null?void 0:v.run_id)||"").trim(),O=String((v==null?void 0:v.artifact_id)||"").trim();if(!C||!O){Es("Artifact preview needs a run id",3);return}const B=Rp(v),ee=String((v==null?void 0:v.content_type)||"").trim().toLowerCase(),J=Im(v);if(Ao(B||O),Qo(""),Zi(""),yl(J),vl(v),gl(!0),ir&&(URL.revokeObjectURL(ir),Mu("")),J==="binary"){Qo(`(Binary artifact: ${ee||"unknown"}; download to view.)`);return}if(J==="text"&&typeof v.size_bytes=="number"&&v.size_bytes>15e5){Qo(`(Text artifact is ${v.size_bytes.toLocaleString()} bytes; download to view.)`);return}kr(!0);try{const Q=await qe.download_run_artifact_content(C,O,{access:"preview"});if(J==="text"){const re=await Q.text(),We=Mp(v,re),be=We==="json"?15e5:We==="markdown"?25e4:We==="html"?3e5:22e3;Qo(re.length>be&&We!=="text"?`${Vc(v.size_bytes??re.length)} ${We.toUpperCase()} artifact. Download to inspect it.`:re.length>be?`${re.slice(0,Math.max(0,be-1))}…`:re)}else Mu(URL.createObjectURL(Q))}catch(Q){Zi(String((Q==null?void 0:Q.message)||Q||"Preview failed"))}finally{kr(!1)}}_.useEffect(()=>()=>{ir&&URL.revokeObjectURL(ir)},[ir]);async function jc(v){const C=String(v.artifact_id||"").trim(),O=String(v.run_id||"").trim(),B=Im(v);if(!O||!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:`${Vc(v.size_bytes)} text artifact. Use Preview for a larger view or Download to inspect locally.`,url:"",loading:!1,error:""};try{const ee=await qe.download_run_artifact_content(O,C,{access:"preview"});if(B==="text"){const J=await ee.text(),Q=Mp(v,J),re=Q==="json"?5e5:Q==="markdown"?12e4:Q==="html"?3e5:8e3;return{artifact_id:C,kind:B,render_kind:Q,text:J.length>re&&Q!=="text"?`${Vc(v.size_bytes??J.length)} ${Q.toUpperCase()} artifact. Use Larger preview or Download to inspect it.`:J.length>re?`${J.slice(0,Math.max(0,re-1))}…`:J,url:"",loading:!1,error:""}}return{artifact_id:C,kind:B,render_kind:"",text:"",url:URL.createObjectURL(ee),loading:!1,error:""}}catch(ee){return{artifact_id:C,kind:B,render_kind:"",text:"",url:"",loading:!1,error:String((ee==null?void 0:ee.message)||ee||"Preview failed")}}}async function Xh(v){if(Eo.url&&URL.revokeObjectURL(Eo.url),!v){Eu(xf());return}const C=String(v.artifact_id||"").trim(),O=Im(v);Eu({artifact_id:C,kind:O,render_kind:"",text:"",url:"",loading:!0,error:""}),Eu(await jc(v))}function hn(v){const C=String(v.id||"").trim()||Xs();lf(O=>[{...v,id:C},...O].slice(0,800))}function Es(v,C){sl(v),oi.current&&window.clearTimeout(oi.current),Ui(!1),window.requestAnimationFrame(()=>Ui(!0)),oi.current=window.setTimeout(()=>{Ui(!1),oi.current=null},1500),wo.current&&(window.clearTimeout(wo.current),wo.current=null),C>0&&(wo.current=window.setTimeout(()=>{sl(""),wo.current=null},Math.max(1,C)*1e3))}function ar(v,C){const O=String(v||"").trim(),B=String(C||"").trim();if(!B)return"";const ee=O?String(fc.current[O]||"").trim():"";return ee?`${ee}::${B}`:B}function Sc(v,C,O){const B=String(v||"").trim(),ee=String(C||"").trim(),J=String(O||"").trim();if(!B||!ee||!J)return;const Q=ar(B,ee);Q&&(fc.current[J]=Q,Gr.current[J]=B,mc.current[J]={parent_run_id:B,parent_node_id:ee},$a.current.has(J)||($a.current.add(J),ku(re=>re.includes(J)?re:[...re,J])))}function Nc(v){const C=String(v||"").trim();if(!C)return;const O=Date.now(),B=xo.current;xo.current=C,Sa(O),Na(ee=>{const J={};for(const[be,_e]of Object.entries(ee))typeof _e=="number"&&_e>O&&(J[be]=_e);J[C]=Math.max(J[C]||0,O+2e3),B&&B!==C&&(J[B]=Math.max(J[B]||0,O+2e3));const Q=Object.keys(J);if(Q.length<=200)return J;const re=Q.sort((be,_e)=>(J[_e]||0)-(J[be]||0)).slice(0,200),We={};for(const be of re)We[be]=J[be]||0;return We}),bu(ee=>{if(typeof ee[C]=="number")return ee;const J={...ee,[C]:O};if(dl.current.push(C),dl.current.length>8e3){const Q=dl.current.splice(0,1500);for(const re of Q)delete J[re]}return J}),Vr.current&&window.clearTimeout(Vr.current),Vr.current=window.setTimeout(()=>{const ee=Date.now();Na(J=>{const Q={};for(const[re,We]of Object.entries(J))typeof We=="number"&&We>ee&&(Q[re]=We);return Q}),Sa(ee),Vr.current=null},2200)}function Pf(v,C){var nt,fn,Xt;const O=String(C||"").trim()||c.trim();Cr.current=v.cursor,(nt=Ns.current)==null||nt.push({cursor:v.cursor,record:v.record}),O&&ji.current.add(`${O}:${v.cursor}`);const B=W_(v.record),ee=B&&B.name?km(B.name):"",J=v.record,Q=typeof(J==null?void 0:J.node_id)=="string"?J.node_id:"",re=typeof(J==null?void 0:J.status)=="string"?J.status:"",We=typeof((fn=J==null?void 0:J.effect)==null?void 0:fn.type)=="string"?J.effect.type:"",be=typeof(J==null?void 0:J.run_id)=="string"?J.run_id:"",_e=be||O;if(ee==="abstract.status"&&_e===O){const{text:it,duration:Bt}=gd(B==null?void 0:B.payload);Es(it,Bt)}const Le=Q?ar(_e,Q):"";if(re==="waiting"){const it=Wa(J);if(String((it==null?void 0:it.reason)||"").trim()==="subworkflow"){const Tn=typeof((Xt=it==null?void 0:it.details)==null?void 0:Xt.sub_run_id)=="string"?String(it.details.sub_run_id):"";Tn&&Q&&Sc(_e,Q,Tn)}}if(Q&&(Nc(ar(_e,Q)),re==="waiting"||re==="running")){const it=ar(_e,Q);it&&(xo.current=it,Ko(it))}let Oe="step",tt=Le||Q||"(node?)",ft="";if(B&&B.name&&Hy(B.name))Oe=ee==="abstract.message"?"message":"event",tt=ee||B.name,ft=Wt(ee==="abstract.steer_seen"?qy(B==null?void 0:B.payload):gd(B==null?void 0:B.payload).text);else if(J!=null&&J.error)Oe="error",tt="error",ft=Wt(Br(J.error,360));else if(re==="waiting"){const it=Wa(J),Bt=String((it==null?void 0:it.reason)||"").trim();ft=Wt(Bt?`waiting • ${Bt}`:"waiting")}else J!=null&&J.result?ft=Wt(Br(J.result,360)):We?ft=Wt(We):ft=Wt(dp(J));hn({id:`step:${be||O||"?"}:${v.cursor}`,ts:String((J==null?void 0:J.ended_at)||(J==null?void 0:J.started_at)||Vt()),kind:Oe,title:tt,preview:ft,data:J,cursor:v.cursor,run_id:be||O||void 0,node_id:Le||Q,status:re,effect_type:We,emit_name:ee||(B==null?void 0:B.name)||void 0})}function Zh(v,C){var ft,nt,fn;Ln.current=Math.max(Ln.current,C.cursor);const O=`${v}:${C.cursor}`;if(!!ji.current.has(O))return;ji.current.add(O),(ft=ps.current)==null||ft.push({run_id:v,cursor:C.cursor,record:C.record});const ee=W_(C.record),J=ee&&ee.name?km(ee.name):"",Q=C.record,re=typeof(Q==null?void 0:Q.node_id)=="string"?Q.node_id:"",We=re?ar(v,re):"",be=typeof(Q==null?void 0:Q.status)=="string"?Q.status:"",_e=typeof((nt=Q==null?void 0:Q.effect)==null?void 0:nt.type)=="string"?Q.effect.type:"";if(be==="waiting"){const Xt=Wa(Q);if(String((Xt==null?void 0:Xt.reason)||"").trim()==="subworkflow"){const Bt=typeof((fn=Xt==null?void 0:Xt.details)==null?void 0:fn.sub_run_id)=="string"?String(Xt.details.sub_run_id):"";Bt&&re&&Sc(v,re,Bt),Bt&&xr.current.trim()===String(v||"").trim()&&(xr.current=Bt,Si(Bt))}}if(re&&(Nc(ar(v,re)),be==="waiting"||be==="running")){const Xt=ar(v,re);Xt&&(xo.current=Xt,Ko(Xt))}if((be==="completed"||be==="failed")&&xr.current.trim()===String(v||"").trim()){const Xt=String(Gr.current[String(v||"").trim()]||"").trim();Xt&&Xt!==c.trim()?(xr.current=Xt,Si(Xt)):(xr.current="",Si(""))}if(J==="abstract.status"&&v===c.trim()){const{text:Xt,duration:it}=gd(ee==null?void 0:ee.payload);Es(Xt,it)}let Le="step",Oe=We||re||"(node?)",tt="";if(ee&&ee.name&&Hy(ee.name))Le=J==="abstract.message"?"message":"event",Oe=`subrun • ${J||ee.name}`,tt=Wt(J==="abstract.steer_seen"?qy(ee==null?void 0:ee.payload):gd(ee==null?void 0:ee.payload).text);else if(Q!=null&&Q.error)Le="error",Oe="error",tt=Wt(Br(Q.error,360));else if(be==="waiting"){const Xt=Wa(Q),it=String((Xt==null?void 0:Xt.reason)||"").trim();tt=Wt(it?`waiting • ${it}`:"waiting")}else Q!=null&&Q.result?tt=Wt(Br(Q.result,360)):_e?tt=Wt(_e):tt=Wt(dp(Q));hn({id:`step:${v}:${C.cursor}`,ts:String((Q==null?void 0:Q.ended_at)||(Q==null?void 0:Q.started_at)||Vt()),kind:Le,title:Oe,preview:tt,data:Q,cursor:C.cursor,run_id:v,node_id:We||re,status:be,effect_type:_e,emit_name:J||(ee==null?void 0:ee.name)||""})}function Qh(v,C){var nt,fn,Xt;const O=String(v||"").trim();if(!O)return;const B=`${O}:${C.cursor}`;if(!!ji.current.has(B))return;ji.current.add(B),(nt=ps.current)==null||nt.push({run_id:O,cursor:C.cursor,record:C.record});const J=W_(C.record),Q=J&&J.name?km(J.name):"",re=C.record,We=typeof(re==null?void 0:re.node_id)=="string"?re.node_id:"",be=We?ar(O,We):"",_e=typeof(re==null?void 0:re.status)=="string"?re.status:"",Le=typeof((fn=re==null?void 0:re.effect)==null?void 0:fn.type)=="string"?re.effect.type:"";if(_e==="waiting"){const it=Wa(re);if(String((it==null?void 0:it.reason)||"").trim()==="subworkflow"){const Tn=typeof((Xt=it==null?void 0:it.details)==null?void 0:Xt.sub_run_id)=="string"?String(it.details.sub_run_id):"";Tn&&We&&Sc(O,We,Tn)}}if(We&&(Nc(ar(O,We)),_e==="waiting"||_e==="running")){const it=ar(O,We);it&&(xo.current=it,Ko(it))}if(Q==="abstract.status"&&O===c.trim()){const{text:it,duration:Bt}=gd(J==null?void 0:J.payload);Es(it,Bt)}let Oe="step",tt=be||We||"(node?)",ft="";if(J&&J.name&&Hy(J.name))Oe=Q==="abstract.message"?"message":"event",tt=`subrun • ${Q||J.name}`,ft=Wt(Q==="abstract.steer_seen"?qy(J==null?void 0:J.payload):gd(J==null?void 0:J.payload).text);else if(re!=null&&re.error)Oe="error",tt="error",ft=Wt(Br(re.error,360));else if(_e==="waiting"){const it=Wa(re),Bt=String((it==null?void 0:it.reason)||"").trim();ft=Wt(Bt?`waiting • ${Bt}`:"waiting")}else re!=null&&re.result?ft=Wt(Br(re.result,360)):Le?ft=Wt(Le):ft=Wt(dp(re));hn({id:`step:${O}:${C.cursor}`,ts:String((re==null?void 0:re.ended_at)||(re==null?void 0:re.started_at)||Vt()),kind:Oe,title:tt,preview:ft,data:re,cursor:C.cursor,run_id:O,node_id:be||We,status:_e,effect_type:Le,emit_name:Q||(J==null?void 0:J.name)||""})}async function qu(v,C){var B,ee;let O=C.after;for(;;){if((B=C.signal)!=null&&B.aborted)return O;const J=await qe.get_ledger(v,{after:O,limit:200,signal:C.signal});if((ee=C.signal)!=null&&ee.aborted)return O;const Q=Array.isArray(J.items)?J.items:[];if(!Q.length)return Cr.current=O,O;const re=O;for(let We=0;We<Q.length;We++){const be=Q[We];Pf({cursor:re+We+1,record:be},v)}O=typeof J.next_after=="number"?J.next_after:O}}async function $c(v){var J,Q,re,We;const C=String(v||"").trim();vn(""),Ut(!0),ts(!1),(J=Ns.current)==null||J.reset(),(Q=ps.current)==null||Q.reset(),_r.current={scanned:0,found:null},Je([]),Cr.current=0,Yt([]),ji.current=new Set,lf([]),$h(""),sl(""),wt(null),ai(""),gf(""),Ko(""),xo.current="",Na({}),bu({}),dl.current=[],Sa(Date.now()),fc.current=C?{[C]:""}:{},Gr.current={},mc.current={},$a.current=new Set,ku([]),ko.current="",xr.current="",Si(""),Jo.current={},Vr.current&&window.clearTimeout(Vr.current),Vr.current=null,sr.current&&window.clearTimeout(sr.current),sr.current=null,jo.current&&jo.current.abort(),vr.current&&vr.current.abort(),vr.current=null,Ln.current=0,ml("");const O=new AbortController;jo.current=O;let B=!1;try{let be="",_e="";try{const Le=await qe.get_run(C);wt(Le);const Oe=typeof(Le==null?void 0:Le.workflow_id)=="string"?String(Le.workflow_id):"",tt=Pk(Oe);tt&&(be=tt.bundle_id,_e=tt.flow_id)}catch{}try{const Le=await qe.get_run_input_data(C);typeof(Le==null?void 0:Le.bundle_id)=="string"&&(be=String(Le.bundle_id||"").trim()||be),typeof(Le==null?void 0:Le.flow_id)=="string"&&(_e=String(Le.flow_id||"").trim()||_e);const Oe=Le&&typeof Le.input_data=="object"&&Le.input_data&&!Array.isArray(Le.input_data)?Le.input_data:null;Oe&&E(JSON.stringify(Oe,null,2));const tt=Le==null?void 0:Le.workspace,ft=typeof(tt==null?void 0:tt.workspace_root)=="string"?String(tt.workspace_root).trim():"";gf(ft)}catch{gf("")}be&&_e&&($(be),b(_e),wr(_e),await wc(be)),await qu(C,{after:0,signal:O.signal});try{const Le=await qe.get_run_history_bundle(C,{include_subruns:!0,include_session:!1,ledger_mode:"tail",ledger_max_items:1}),Oe=Le&&typeof Le=="object"?Le.ledgers:null,ft=(Oe&&typeof Oe=="object"?Object.keys(Oe):[]).map(nt=>String(nt||"").trim()).filter(Boolean).filter(nt=>nt!==C);if(ft.length){for(const nt of ft)$a.current.add(nt);ku(nt=>Array.from(new Set([...nt,...ft])));try{const nt=typeof((re=Oe==null?void 0:Oe[C])==null?void 0:re.total)=="number"?Number(Oe[C].total):0;let fn="",Xt=-1;for(const it of ft){const Bt=typeof((We=Oe==null?void 0:Oe[it])==null?void 0:We.total)=="number"?Number(Oe[it].total):0;Bt>Xt&&(fn=it,Xt=Bt)}fn&&Xt>Math.max(nt*3,nt+20)&&(xr.current=fn,Si(fn))}catch{}}}catch{}ts(!0),hn({ts:Vt(),kind:"info",title:`Attached to run ${C}`,data:{run_id:C}}),B=!0}catch(be){if(O.signal.aborted||String((be==null?void 0:be.name)||"")==="Superseded")return;const _e=String((be==null?void 0:be.message)||be||"unknown error");vn(_e),hn({ts:Vt(),kind:"error",title:"Connection error",preview:Wt(_e),data:{error:_e}}),ts(!1)}finally{O.signal.aborted||Ut(!1)}if(!B||O.signal.aborted)return;(async()=>{let be=250;for(;!O.signal.aborted;){try{const _e=await qu(C,{after:Cr.current,signal:O.signal});await qe.stream_ledger(C,{after:_e,on_step:Le=>Pf(Le,C),signal:O.signal})}catch(_e){if(O.signal.aborted)break;const Le=String((_e==null?void 0:_e.message)||_e||"stream error");hn({ts:Vt(),kind:"error",title:"Ledger stream error (will retry)",preview:Wt(Le),data:{error:Le}})}if(O.signal.aborted)break;await new Promise(_e=>setTimeout(_e,be)),be=Math.min(5e3,Math.floor(be*1.6))}})()}async function e_(){const v=zs,C=(v==null?void 0:v.kind)==="bundle"?v.flow_id:(v==null?void 0:v.kind)==="default"?"@default":"",O=(v==null?void 0:v.kind)==="bundle"?v.bundle_id:"";if(!v){const B="Select a workflow first (Launch → pick a workflow).";return vn(B),B}vn(""),Ut(!0);try{let B={};const ee=A.trim();if(ee)try{if(B=JSON.parse(ee),typeof B!="object"||B===null||Array.isArray(B))throw new Error("input_data must be a JSON object")}catch(Le){const Oe=`Invalid input_data JSON: ${String((Le==null?void 0:Le.message)||Le)}`;return vn(Oe),Oe}for(const[Le,Oe]of Object.entries(B)){if(typeof Oe!="string")continue;const tt=Oe.trim();tt?B[Le]=tt:delete B[Le]}const J=(ci||[]).find(Le=>Le&&typeof Le=="object"&&Le.id==="prompt"),Q=J&&typeof J=="object"&&Object.prototype.hasOwnProperty.call(J,"default"),re=B==null?void 0:B.prompt,We=typeof re=="string"?re.trim():"";if(J&&!Q&&!We){const Le="Missing required input_data.prompt";return vn(Le),Le}const be=B.workspace&&typeof B.workspace=="object"?B.workspace:null;delete B.workspace;const _e=await qe.start_run(C,B,{...be?{workspace:be}:{},...O?{bundle_id:O}:{},...v.kind==="default"?{interface:v.interface}:{},session_id:String(z||"").trim()||null});return h(_e),d(_e),tr(""),await $c(_e),bs(),null}catch(B){const ee=String((B==null?void 0:B.message)||B||"start failed");return vn(ee),ee}finally{Ut(!1)}}async function t_(){if(Ve([]),Ie(null),!Be.available){Ve([Be.reason]);return}const v=rL(ut,{choice:zs,bundle_ref_for:C=>{var O;return((O=Cn.find(B=>B.bundle_id===C))==null?void 0:O.bundle_ref)||""},input_data:tn,email_usable:Kn.email_usable},Ge.current);if(!v.ok){Ve(v.errors);return}ie(!0);try{const C=await qe.automations_client().createAutomation(v.body);Ge.current.reset(),et([]),Se(_w),hn({ts:Vt(),kind:"info",title:"Automation created",preview:Wt(`${v.body.title} · ${C.automation_id}`)}),De(!1),t("automations"),await Kn.refresh(),await Kn.select(C.automation_id)}catch(C){const O=(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")};Ie(O)}finally{ie(!1)}}async function Ng(){if(tr(""),ge==="automate"){await t_();return}const v=await e_();if(v){tr(v);return}De(!1),vo("ledger"),t("observe")}async function Df(v){if(ms("skills",void 0),!!v){if(v.kind==="default"){Nt(v.interface),$(""),b(""),M(null);return}Nt(""),$(v.bundle_id),b(v.flow_id),wr(v.flow_id),await wc(v.bundle_id)}}async function n_(v){const[C,O]=await Promise.all([qe.get_run(v),qe.get_run_input_data(v)]),B=fL(C,O);await Df(B.choice),E(JSON.stringify(B.input_data,null,2)),Se(B.form),et([`Recreating the legacy schedule ${jn(v,14)} as an automation. The legacy schedule keeps running until you suspend it.`,...B.notes]),Ge.current.reset(),Ue("automate")}async function ro(v,C){const O=String(v||"").trim();if(!O)return;if(Pe){Es(`Still attaching — retry in a moment (${jn(O,14)})`,2500);return}vn(""),x("");const B=String((C==null?void 0:C.root_run_id)||O).trim()||O;h(B),d(O),await $c(O)}_.useEffect(()=>{const v=String(p||"").trim();if(!v)return;let C=!1;return(async()=>{try{if(L||await hs({open_modal_if_needed:!0}),C)return;vo("ledger"),t("observe");const O=await qe.find_run(v);if(C)return;if(O===null){Hu(),x(v);return}await ro(v),Li()}catch(O){C||vn(String((O==null?void 0:O.message)||O||"Failed to attach run from URL"))}finally{C||y("")}})(),()=>{C=!0}},[p]);function Hu(){var v,C;jo.current&&jo.current.abort(),jo.current=null,vr.current&&vr.current.abort(),vr.current=null,Ln.current=0,ml(""),d(""),h(""),fc.current={},Gr.current={},mc.current={},$a.current=new Set,ku([]),ko.current="",xr.current="",Si(""),Jo.current={},ai(""),Vr.current&&window.clearTimeout(Vr.current),Vr.current=null,sr.current&&window.clearTimeout(sr.current),sr.current=null,ts(!1),Ut(!1),Mn(!1),Cr.current=0,(v=Ns.current)==null||v.reset(),(C=ps.current)==null||C.reset(),_r.current={scanned:0,found:null},Je([]),Yt([]),ji.current=new Set,wt(null),lf([]),Ko(""),xo.current="",Na({}),bu({}),dl.current=[],Sa(Date.now()),Es("",-1),vn(""),_n([]),zn(null),Re(""),dt(""),cn(!1),Wi(!1),qi(""),oc(""),xa(""),ac([]),du(!1),fu(""),mu(""),il(!1),ba("")}_.useEffect(()=>{_n([]),zn(null),Re(""),dt(""),cn(!1),Wi(!1),qi(""),oc(""),xa(""),ac([]),du(!1),fu(""),mu(""),il(!1),ba("")},[c]),_.useEffect(()=>{xs==="chat"&&c.trim()&&L&&Gu()},[xs,c,L,we==null?void 0:we.workflow_id]);async function El(v,C,O){const B=String(v||"").trim();if(!B)return vn("Missing run_id"),"Missing run_id";vn("");try{const ee={},J=String((O==null?void 0:O.reason)||"").trim();J&&(ee.reason=J),await qe.submit_command({command_id:Xs(),run_id:B,type:C,payload:ee,client_id:"web_pwa"}),hn({ts:Vt(),kind:"info",title:`${C} submitted`,preview:J?`reason: ${J}`:"",data:{run_id:B,type:C,reason:J}});try{if(B===c.trim()){const Q=await qe.get_run(B);wt(Q)}}catch{}return bs(qe,{force:!0}),window.setTimeout(()=>void bs(qe,{force:!0}),900),window.setTimeout(()=>void bs(qe,{force:!0}),2400),null}catch(ee){const J=String((ee==null?void 0:ee.message)||ee||`${C} failed`);return vn(J),J}}async function s_(v,C){const O=v.map(We=>String(We||"").trim()).filter(Boolean),B=[];let ee=0,J=0,Q=0;const re=async()=>{for(;Q<O.length;){const We=O[Q++];try{await qe.submit_command({command_id:Xs(),run_id:We,type:"cancel",payload:{},client_id:"web_pwa"}),B.push({run_id:We,error:null})}catch(be){J+=1,B.push({run_id:We,error:String((be==null?void 0:be.message)||be||"cancel failed")})}ee+=1,C==null||C(ee,J)}};return await Promise.all(Array.from({length:Math.min(4,O.length)},re)),hn({ts:Vt(),kind:J?"error":"info",title:`cancel submitted ×${O.length}${J?` · ${J} failed`:""}`,preview:"",data:{run_ids:O,failed:J}}),O.length&&(bs(qe,{force:!0}),window.setTimeout(()=>void bs(qe,{force:!0}),2400)),B}async function Al(v,C){return El(c.trim(),v,C)}async function r_(v,C="Stopped from AbstractObserver"){const O=String(v||"").trim();if(!O||!window.confirm(`Cancel run ${jn(O,24)}?`))return;await El(O,"cancel",{reason:C})||Es("Cancel submitted",2)}async function $g(){var O;const v=c.trim();if(!v){vn("Select a run first.");return}if(!L){vn("Connect to the gateway first.");return}if(St)return;const C=String(((O=we==null?void 0:we.waiting)==null?void 0:O.reason)||"").trim().toLowerCase()||String(Bs||"").trim().toLowerCase();if(!Or||Mi||Lo||Ro.toLowerCase()!=="waiting"||C!=="until"){vn("This run is not a scheduled wait that can be triggered now.");return}vn(""),Mn(!0);try{const B={payload:{mode:"run_now",requested_at:Vt()}},ee=String(lr||"").trim();ee&&(B.wait_key=ee),await qe.submit_command({command_id:Xs(),run_id:v,type:"resume",payload:B,client_id:"web_pwa"}),hn({ts:Vt(),kind:"info",title:"Scheduled run triggered",preview:Wt(`run ${v}`),data:{run_id:v,until:Ti||null}});try{const J=await qe.get_run(v);wt(J)}catch{}}catch(B){vn(String((B==null?void 0:B.message)||B||"Failed to trigger scheduled run"))}finally{Mn(!1)}}async function Cg(v){const C=c.trim();if(!C)return vn("Missing run_id"),"Missing run_id";if(ii)return"Schedule update already in progress";const O=String(v.interval||"").trim();if(!/^\s*(\d+(?:\.\d+)?)\s*(ms|s|m|h|d)\s*$/i.test(O)){const ee="Invalid interval (expected like '20m', '1h', '0.5s', '250ms')";return vs(ee),ee}vs(""),vn(""),zi(!0),Ut(!0);try{await qe.submit_command({command_id:Xs(),run_id:C,type:"update_schedule",payload:{interval:O,apply_immediately:v.apply_immediately!==!1},client_id:"web_pwa"}),hn({ts:Vt(),kind:"info",title:"Schedule updated",preview:Wt(`interval: ${O}`),data:{interval:O},run_id:C});try{const ee=await qe.get_run(C);wt(ee)}catch{}return null}catch(ee){const J=String((ee==null?void 0:ee.message)||ee||"update_schedule failed");return vs(J),vn(J),J}finally{Ut(!1),zi(!1)}}async function Ai(v){const C=c.trim();if(!C)return vn("Missing run_id"),"Missing run_id";if(Ds)return"Compaction already in progress";const O=typeof(v==null?void 0:v.preserve_recent)=="number"?v.preserve_recent:tl,B=Math.max(0,Math.min(500,Math.floor(Number.isFinite(O)?O:6))),ee=(v==null?void 0:v.compression_mode)||Er,J=String((v==null?void 0:v.focus)??Bi??"").trim();Ps(""),vn(""),gr(!0),Ut(!0);try{const Q={preserve_recent:B,compression_mode:ee};return J&&(Q.focus=J),await qe.submit_command({command_id:Xs(),run_id:C,type:"compact_memory",payload:Q,client_id:"web_pwa"}),hn({ts:Vt(),kind:"info",title:"Compaction requested",preview:Wt(`mode: ${ee} • preserve_recent: ${B}`),data:Q,run_id:C}),null}catch(Q){const re=String((Q==null?void 0:Q.message)||Q||"compact_memory failed");return Ps(re),vn(re),re}finally{Ut(!1),gr(!1)}}async function Ff(){const v=c.trim();if(!v){dt("Select a run first.");return}if(!L){dt("Connect to the gateway first.");return}const C=Me.trim();if(!C||Tt)return;if(so.voice_ptt_busy){Ct("Wait for transcription to finish.");return}dt(""),Ct(""),cn(!0);const B={id:`local:${Xs()}`,role:"user",content:C,ts:Vt()};_n(ee=>[...ee,B]),Re("");try{const ee=XM(Et,B),J=n.maintenance_ai_provider.trim(),Q=n.maintenance_ai_model.trim(),re=await qe.run_chat(v,{provider:J||void 0,model:Q||void 0,include_subruns:!0,messages:ee}),We=String((re==null?void 0:re.answer)||"").trim()||"(empty response)",be=String((re==null?void 0:re.generated_at)||"").trim()||Vt();zn((re==null?void 0:re.history)??null),_n(_e=>[..._e,{id:`local:${Xs()}`,role:"assistant",content:We,ts:be}])}catch(ee){const J=LR(ee);dt(J),_n(Q=>[...Q,{id:`local:${Xs()}`,role:"assistant",content:`(error: ${J})`,ts:Vt(),local_error:!0}])}finally{cn(!1)}}function Vu(v){const C=String(v.id||v.ts||"").trim(),O=String(v.content||"").trim();!C||!O||(Ct(""),so.toggle_tts(C,O))}function i_(v){const C=String(v.id||v.ts||"").trim(),O=so.tts_playback;return!C||!O.key||O.key!==C?"idle":O.status}function zf(v){if(!Et.length)return;const C=c.trim(),O=C?`Run ${C}`:"Chat",B=KA(Et.map(ee=>({role:ee.role,content:ee.content,ts:ee.ts})),{heading:O});if(v==="download"){const ee=new Date().toISOString().slice(0,19).replace(/[:T]/g,"-"),J=`abstractobserver-chat-${bb(C||"run")}-${ee}.md`;JA({filename:J,text:B,mime:"text/markdown;charset=utf-8"});return}(async()=>{const ee=await tc(B);Vs(ee?"copied":"failed"),window.setTimeout(()=>Vs("idle"),900)})()}async function Gu(){const v=typeof(we==null?void 0:we.workflow_id)=="string"?String(we.workflow_id).trim():"";if(!v){ac([]);return}if(L&&!lc){fu(""),du(!0);try{const C=await qe.list_runs({limit:200,workflow_id:v,root_only:!0}),O=Array.isArray(C==null?void 0:C.items)?C.items:[],B=[];for(const be of O){const _e=typeof(be==null?void 0:be.run_id)=="string"?String(be.run_id).trim():"";if(!_e)continue;const Le=typeof(be==null?void 0:be.ledger_len)=="number"?Number(be.ledger_len):0;B.push({run_id:_e,ledger_len:Number.isFinite(Le)?Le:0})}if(!B.length){ac([]);return}const ee=400,J=B.map(be=>({run_id:be.run_id,after:Math.max(0,(be.ledger_len||0)-ee)})),Q=await qe.get_ledger_batch({runs:J,limit:ee}),re=[],We=new Set;for(const be of B){const _e=Q!=null&&Q.runs&&typeof Q.runs=="object"?Q.runs[be.run_id]:null,Le=Array.isArray(_e==null?void 0:_e.items)?_e.items:[];for(const Oe of Le){const tt=Oe==null?void 0:Oe.effect;if(!tt||typeof tt!="object"||String(tt.type||"")!=="emit_event")continue;const ft=tt.payload;if(!ft||typeof ft!="object"||String(ft.name||"")!=="abstract.chat.thread")continue;const nt=ft.payload;if(!nt||typeof nt!="object")continue;const fn=typeof nt.thread_id=="string"?String(nt.thread_id).trim():"";if(!fn||We.has(fn))continue;We.add(fn);const Xt=typeof nt.created_at=="string"?String(nt.created_at):"",it=typeof nt.title=="string"?String(nt.title):"",Bt=typeof nt.workflow_id=="string"?String(nt.workflow_id):v,Tn=typeof nt.run_id=="string"?String(nt.run_id):be.run_id,Jn=typeof nt.provider=="string"?String(nt.provider):"",ur=typeof nt.model=="string"?String(nt.model):"",Fr=typeof nt.message_count=="number"?Number(nt.message_count):null,Ii=nt.chat_artifact,za=Ii&&typeof Ii=="object"&&typeof Ii.$artifact=="string"?String(Ii.$artifact):"";za&&re.push({thread_id:fn,created_at:Xt,title:it||`Chat ${fn.slice(0,8)}`,run_id:Tn,workflow_id:Bt,message_count:Fr,provider:Jn,model:ur,artifact_id:za})}}re.sort((be,_e)=>String(_e.created_at||"").localeCompare(String(be.created_at||""))),ac(re)}catch(C){fu(String((C==null?void 0:C.message)||C||"Failed to load saved discussions"))}finally{du(!1)}}}async function Bf(){const v=c.trim();if(!v){qi("Select a run first.");return}if(!L){qi("Connect to the gateway first.");return}if(Et.length&&!yr){qi(""),Wi(!0);try{const C=n.maintenance_ai_provider.trim(),O=n.maintenance_ai_model.trim(),B=await qe.save_chat_thread(v,{provider:C||void 0,model:O||void 0,include_subruns:!0,messages:Et.map(Q=>({role:Q.role,content:Q.content,ts:Q.ts}))}),ee=typeof(B==null?void 0:B.created_at)=="string"?String(B.created_at):Vt();oc(ee);try{const Q=JSON.stringify(Et.map(re=>({role:re.role,content:re.content,ts:re.ts})));xa(Q)}catch{xa("1")}typeof(B==null?void 0:B.thread_id)=="string"&&String(B.thread_id).trim()&&mu(String(B.thread_id).trim());const J=!!(B!=null&&B.duplicate);Es(J?"Already saved":"Saved discussion",2),await Gu()}catch(C){qi(String((C==null?void 0:C.message)||C||"Failed to save discussion"))}finally{Wi(!1)}}}async function Tl(){const v=String(of||"").trim();if(!v)return;const C=sf.find(ee=>String(ee.thread_id||"").trim()===v)||null;if(!C){ba("Saved discussion not found (refresh list).");return}if(!L){ba("Connect to the gateway first.");return}if(hu)return;const O=Et.length>0,B=(()=>{if(!O)return!1;if(!va)return!0;try{return JSON.stringify(Et.map(J=>({role:J.role,content:J.content,ts:J.ts})))!==va}catch{return!0}})();if(!(O&&B&&!window.confirm("Replace the current chat with the selected saved discussion? Unsaved changes will be lost."))){ba(""),il(!0);try{const J=await(await qe.download_run_artifact_content(C.run_id,C.artifact_id)).text(),Q=JSON.parse(J),re=Array.isArray(Q==null?void 0:Q.messages)?Q.messages:[],We=typeof(Q==null?void 0:Q.created_at)=="string"?String(Q.created_at):String(C.created_at||""),be=[];for(let _e=0;_e<re.length;_e++){const Le=re[_e];if(!Le||typeof Le!="object")continue;const Oe=String(Le.role||"").trim()==="assistant"?"assistant":"user",tt=typeof Le.content=="string"?String(Le.content):"";if(!tt.trim())continue;const ft=typeof Le.ts=="string"?String(Le.ts):We||Vt();be.push({id:`thread:${v}:${_e}`,role:Oe,content:tt.trim(),ts:ft})}_n(be),zn(null),Re(""),dt(""),qi(""),oc(We||"");try{const _e=JSON.stringify(be.map(Le=>({role:Le.role,content:Le.content,ts:Le.ts})));xa(_e)}catch{xa("1")}Es("Loaded discussion",2)}catch(ee){ba(String((ee==null?void 0:ee.message)||ee||"Failed to load saved discussion"))}finally{il(!1)}}}async function Ml(v){const C=c.trim(),O=String((sn==null?void 0:sn.wait_key)||"").trim();if(!C||!O){vn("No active wait to resume");return}if(String((sn==null?void 0:sn.reason)||"").trim()==="subworkflow"){vn("This run is waiting on a subworkflow; attach to the child run instead of resuming manually.");return}vn(""),Mn(!0);try{await qe.submit_command({command_id:Xs(),run_id:C,type:"resume",payload:{wait_key:O,payload:v||{}},client_id:"web_pwa"}),hn({ts:Vt(),kind:"info",title:"Resume submitted",preview:Wt(`wait_key: ${O}`),data:{wait_key:O,payload:v||{}}}),ai(O);try{const B=await qe.get_run(C);wt(B)}catch{}bs(qe,{force:!0}),window.setTimeout(()=>void bs(qe,{force:!0}),900),window.setTimeout(()=>void bs(qe,{force:!0}),2400),sr.current&&window.clearTimeout(sr.current),sr.current=window.setTimeout(()=>{ai(B=>B===O?"":B)},2e3)}catch(B){vn(String((B==null?void 0:B.message)||B||"resume failed"))}finally{Mn(!1)}}async function Uf(v){if(!kl){vn("No worker configured");return}if(!St){vn(""),Mn(!0);try{const C=[];for(const O of v){const B=await kl.call_tool(O);C.push(B)}await Ml({mode:"executed",results:C})}finally{Mn(!1)}}}const Ia=_.useMemo(()=>Zd(sn),[sn]),lr=String((sn==null?void 0:sn.wait_key)||"").trim(),Bs=String((sn==null?void 0:sn.reason)||"").trim(),Ti=typeof(sn==null?void 0:sn.until)=="string"?String(sn.until):"",Ro=typeof(we==null?void 0:we.status)=="string"?String(we.status):"",Lo=!!(we!=null&&we.paused),Mi=Ro==="completed"||Ro==="failed"||Ro==="cancelled",Ir=Bs==="until"&&!!Ti,Us=!Mi&&lI(ns)&&(!!lr||Ir),o_=Bs==="user",Ku=Bs==="event"?km(g9(lr)):"",a_=Bs==="event"&&Ku==="abstract.ask",l_=Ia.length>0,Wf=Us&&lr&&(o_||a_||l_)&&tf!==lr&&e!=="board"&&!(e==="observe"&&xs==="agent"),Io=typeof((w_=sn==null?void 0:sn.details)==null?void 0:w_.sub_run_id)=="string"?String(sn.details.sub_run_id):"",Rl={run_id:c.trim(),workflow_id:typeof(we==null?void 0:we.workflow_id)=="string"?String(we.workflow_id):null,status:Ro,created_at:typeof(we==null?void 0:we.created_at)=="string"?String(we.created_at):null,updated_at:typeof(we==null?void 0:we.updated_at)=="string"?String(we.updated_at):null,session_id:typeof(we==null?void 0:we.session_id)=="string"?String(we.session_id):null,current_node:typeof(we==null?void 0:we.current_node)=="string"?String(we.current_node):null},Ju=nn.slice(-10).map(v=>{var C,O,B,ee,J,Q;return{cursor:v.cursor,node_id:String(((C=v.record)==null?void 0:C.node_id)||"").trim(),status:String(((O=v.record)==null?void 0:O.status)||"").trim(),effect_type:String(((ee=(B=v.record)==null?void 0:B.effect)==null?void 0:ee.type)||"").trim(),ts:String(((J=v.record)==null?void 0:J.ended_at)||((Q=v.record)==null?void 0:Q.started_at)||"").trim(),summary:XS(v.record)}}),qf=Av(sn,Ia),c_=GS(sn,Ia),Yu=KS(sn,tn),ta=Yu.text,u_=Yu.runtime_metadata,Ll=String((sn==null?void 0:sn.prompt)||"").trim(),Cc=G3(tn,6),Eg=!!(Ll&&qS(Ll)),Xu=!!(Ll&&!Eg),Hf=Xu?"Question from workflow":ta&&ta!==Ll?"Closest prior user request":"Request context",d_=Y3(tn,A),Zu=!!A.trim(),ks=we!=null&&we.schedule&&typeof we.schedule=="object"?we.schedule:null,Il=typeof(ks==null?void 0:ks.interval)=="string"?String(ks.interval).trim():"",f_=typeof(ks==null?void 0:ks.share_context)=="boolean"?!!ks.share_context:null,Qu=typeof(ks==null?void 0:ks.repeat_count)=="number"?Number(ks.repeat_count):null,Or=!!(we!=null&&we.is_scheduled)||!!ks,ed=Or&&!!Il,Ol=Ro==="running"&&!Lo?"Pause":"Resume",Ks=Or?Lo?"resume":"pause":Ol==="Pause"?"pause":"resume",Ag=Or?!c.trim()||Pe||St||Mi:!c.trim()||Pe||St||Mi||Ks==="resume"&&!Lo,Tg=c.trim()?Mi?"The schedule has ended.":null:"No run selected.",td=Or&&!Lo&&!Mi&&!Pe&&!St&&Ro.toLowerCase()==="waiting"&&(String(((Fo=we==null?void 0:we.waiting)==null?void 0:Fo.reason)||"").trim().toLowerCase()==="until"||Bs==="until")&&!!String(Ti||"").trim(),Hn=(Qf=we==null?void 0:we.limits)==null?void 0:Qf.tokens,Ec=typeof(Hn==null?void 0:Hn.pct)=="number"?Number(Hn.pct):null,gt=Hn==null?void 0:Hn.estimated_used,Oa=(Hn==null?void 0:Hn.max_input_tokens)??(Hn==null?void 0:Hn.max_tokens),na=_.useMemo(()=>{const v=_r.current;nn.length<v.scanned&&(v.scanned=0,v.found=null);for(let C=v.scanned;C<nn.length;C++){const O=nn[C],B=O==null?void 0:O.record;if(!B)continue;const ee=W_(B);if((ee&&ee.name?km(ee.name):"")!=="abstract.summary")continue;const Q=ee!=null&&ee.payload&&typeof ee.payload=="object"?ee.payload:{},re=typeof(Q==null?void 0:Q.text)=="string"?String(Q.text):"";re.trim()&&(v.found={cursor:O.cursor,ts:String((B==null?void 0:B.ended_at)||(B==null?void 0:B.started_at)||""),text:re,provider:typeof(Q==null?void 0:Q.provider)=="string"?String(Q.provider):void 0,model:typeof(Q==null?void 0:Q.model)=="string"?String(Q.model):void 0,generated_at:typeof(Q==null?void 0:Q.generated_at)=="string"?String(Q.generated_at):void 0,source:Q==null?void 0:Q.source})}return v.scanned=nn.length,v.found},[nn]);_.useEffect(()=>{xr.current=Rr.trim()},[Rr]),_.useEffect(()=>{const v=c.trim(),C=Io.trim();if(!(Ot&&Bs==="subworkflow"&&!!C&&C!==v)){ko.current="",Rr.trim()&&Si("");return}ko.current!==C&&(ko.current=C,xr.current=C,Si(C))},[Ot,c,Bs,Io,Rr]),_.useEffect(()=>{vu({})},[S]);const Vf=_.useMemo(()=>((Array.isArray(F==null?void 0:F.entrypoints)?F==null?void 0:F.entrypoints:[])||[]).map(C=>String((C==null?void 0:C.flow_id)||"").trim()).filter(Boolean),[F]),Oo=_.useMemo(()=>{const v=String((we==null?void 0:we.workflow_id)||"").trim();return Ot&&Or?v:""},[Ot,Or,we==null?void 0:we.workflow_id]),Ac=_.useMemo(()=>{var Q;if(!Ot||!c.trim()||!Oo.trim())return Mr;const v=String((we==null?void 0:we.status)||"").trim().toLowerCase(),C=String((we==null?void 0:we.current_node)||"").trim();if(v!=="waiting"&&v!=="running"||!C)return Mr;const O=ar(c.trim(),C);if(!O)return Mr;const B=String(Bs||((Q=we==null?void 0:we.waiting)==null?void 0:Q.reason)||"").trim().toLowerCase(),ee=typeof(ns==null?void 0:ns.node_id)=="string"?String(ns.node_id).trim():"",J=typeof(ns==null?void 0:ns.status)=="string"?String(ns.status).trim().toLowerCase():"";return v==="waiting"&&B==="until"||!Mr.trim()||(J==="waiting"||J==="running")&&!ee?O:Mr},[Ot,c,Oo,we==null?void 0:we.status,we==null?void 0:we.current_node,(ud=we==null?void 0:we.waiting)==null?void 0:ud.reason,Bs,Mr,ns]),nd=_.useMemo(()=>{const v={},C=c.trim(),O=(B,ee)=>{if(!ee)return;const J=typeof(ee==null?void 0:ee.node_id)=="string"?String(ee.node_id).trim():"";if(!J)return;const Q=ar(B,J);if(!Q)return;const re=String((ee==null?void 0:ee.ended_at)||(ee==null?void 0:ee.started_at)||"").trim(),We=It(re);We!==null&&(v[Q]=Math.max(v[Q]||0,We))};for(const B of nn)B&&B.record&&O(C,B.record);for(const B of en)B&&B.record&&O(String(B.run_id||"").trim(),B.record);return v},[nn,en,c,bo]);_.useEffect(()=>{var O;if(!Ot||!c.trim()||!Oo.trim())return;const v=String((we==null?void 0:we.current_node)||"").trim();!v||String(((O=we==null?void 0:we.waiting)==null?void 0:O.reason)||"").trim()==="subworkflow"||Nc(ar(c.trim(),v))},[Ot,c,Oo,we==null?void 0:we.current_node,(ra=we==null?void 0:we.waiting)==null?void 0:ra.reason]),_.useEffect(()=>{const v=String((Fs==null?void 0:Fs.flow_id)||"").trim();v&&(cl.trim()||wr(v))},[Fs,cl]),_.useEffect(()=>{const v=Oo.trim(),C=S.trim(),O=cl.trim();if(v){let ee=!1;return ka(!0),dc(""),qe.get_workflow_flow(v).then(J=>{if(ee)return;const Q=J==null?void 0:J.flow;ul(Q&&typeof Q=="object"?Q:null)}).catch(J=>{ee||(ul(null),dc(String((J==null?void 0:J.message)||J||"Failed to load workflow flow")))}).finally(()=>{ee||ka(!1)}),()=>{ee=!0}}if(!C||!O){ul(null),dc(""),ka(!1);return}let B=!1;return ka(!0),dc(""),qe.get_bundle_flow(C,O).then(ee=>{if(B)return;const J=ee==null?void 0:ee.flow,Q=J&&typeof J=="object"?J:null;ul(Q),Q&&vu(re=>({...re,[O]:Q}))}).catch(ee=>{B||(ul(null),dc(String((ee==null?void 0:ee.message)||ee||"Failed to load flow")))}).finally(()=>{B||ka(!1)}),()=>{B=!0}},[Oo,S,cl,qe]),_.useEffect(()=>{const v=S.trim();if(!Gi||!v||!Vi)return;let C=!1;const O=3,B=be=>{const _e=Array.isArray(be==null?void 0:be.nodes)?be.nodes:[],Le=[];for(const Oe of _e){const tt=Oe!=null&&Oe.data&&typeof Oe.data=="object"?Oe.data:{};if(String((tt==null?void 0:tt.nodeType)||(Oe==null?void 0:Oe.type)||"").trim()!=="subflow")continue;const nt=(tt==null?void 0:tt.subflowId)||(tt==null?void 0:tt.flowId),fn=typeof nt=="string"?nt.trim():"";fn&&Le.push(fn.includes(":")?fn.split(":",2)[1]:fn)}return Le},ee=new Set,J=new Set,Q=(be,_e)=>{if(!(!be||_e>=O))for(const Le of B(be)){const Oe=String(Le||"").trim();if(!Oe||ee.has(Oe))continue;ee.add(Oe),J.add(Oe);const tt=uc[Oe];tt&&Q(tt,_e+1)}};Q(Vi,0);const re=Array.from(J).filter(be=>!uc[be]).slice(0,20);return re.length?((async()=>{for(const be of re){if(C)return;try{const _e=await qe.get_bundle_flow(v,be),Le=_e==null?void 0:_e.flow,Oe=Le&&typeof Le=="object"?Le:null;if(!Oe)continue;vu(tt=>tt[be]?tt:{...tt,[be]:Oe})}catch{}}})(),()=>{C=!0}):void 0},[Gi,S,Vi,uc,qe]);const sd=_.useMemo(()=>{const C=(Array.isArray(F==null?void 0:F.flows)?F==null?void 0:F.flows:[]).map(O=>String(O||"").trim()).filter(Boolean);return C.length?Array.from(new Set(C)).sort():Array.from(new Set(Vf)).sort()},[F,Vf]);_.useEffect(()=>{Mi&&Mr.trim()&&(Ko(""),xo.current="")},[Mi,c,Mr]),_.useEffect(()=>{const v=Rr.trim(),C=c.trim();if(!(Ot&&!!v&&v!==C)){vr.current&&vr.current.abort(),vr.current=null,Ln.current=0,ju&&ml("");return}if(ju===v)return;vr.current&&vr.current.abort();const B=new AbortController;vr.current=B,Ln.current=0,ml(v),hn({ts:Vt(),kind:"info",title:`Following run ${v} (status/events)`});let ee=250;return(async()=>{for(;!B.signal.aborted;){try{await qe.stream_ledger(v,{after:Ln.current,on_step:Q=>Zh(v,Q),signal:B.signal});return}catch(Q){if(B.signal.aborted)break;const re=String((Q==null?void 0:Q.message)||Q||"stream error");hn({ts:Vt(),kind:"error",title:"Child ledger stream error (will retry)",preview:Wt(re),data:{child_run_id:v,error:re}})}if(B.signal.aborted)break;await new Promise(Q=>setTimeout(Q,ee)),ee=Math.min(5e3,Math.floor(ee*1.6))}})(),()=>{B.abort()}},[Ot,Rr,c,qe,ju]),_.useEffect(()=>{if(!Ot||!c.trim())return;let v=!1;const C=async()=>{if(!v&&!Ca.current&&bo.length&&!(lt.current>Date.now())){Ca.current=!0;try{const B=bo.map(re=>String(re||"").trim()).filter(Boolean);if(!B.length)return;const ee=B.map(re=>({run_id:re,after:Number(Jo.current[re]||0)})),J=await qe.get_ledger_batch({runs:ee,limit:200}),Q=J&&typeof J=="object"?J.runs:{};for(const re of B){if(v)return;const We=Q&&typeof Q=="object"?Q[re]:null,be=Array.isArray(We==null?void 0:We.items)?We.items:[],_e=typeof(We==null?void 0:We.next_after)=="number"?We.next_after:Number(Jo.current[re]||0),Le=Number(Jo.current[re]||0);for(let Oe=0;Oe<be.length;Oe++){const tt=be[Oe];Qh(re,{cursor:Le+Oe+1,record:tt})}Jo.current[re]=_e}}catch(B){if(v||String((B==null?void 0:B.name)||"")==="Superseded")return;hn({ts:Vt(),kind:"error",title:"Subrun digest poll failed",preview:Wt(String((B==null?void 0:B.message)||B||""))}),bh("Subrun digest poll failed",Wt(String((B==null?void 0:B.message)||B||"")))}finally{Ca.current=!1}}};C();const O=window.setInterval(()=>void C(),2e3);return()=>{v=!0,window.clearInterval(O),Ca.current=!1}},[Ot,c,bo,qe]);const io=_.useMemo(()=>{const v=c.trim(),C=[];for(const O of nn)!O||!O.record||C.push({run_id:v,cursor:O.cursor,record:O.record});for(const O of en)!O||!O.record||C.push({run_id:String(O.run_id||"").trim(),cursor:O.cursor,record:O.record});return C},[nn,en,c]),rd=_.useMemo(()=>{var C,O,B,ee;const v={};for(const J of io){const Q=String(J.run_id||((C=J.record)==null?void 0:C.run_id)||"").trim();!Q||String(((B=(O=J.record)==null?void 0:O.effect)==null?void 0:B.type)||"").trim()!=="llm_call"||String(((ee=J.record)==null?void 0:ee.status)||"")!=="started"&&(v[Q]=(v[Q]||0)+1)}return v},[io]),m_=_.useMemo(()=>{const v=Rr.trim();if(v)return v;let C="",O=-1;for(const[B,ee]of Object.entries(rd))ee>O&&(C=B,O=ee);return C||c.trim()},[rd,Rr,c]),Gf=(kg.trim()||m_).trim(),Kf=_.useMemo(()=>{var ee;const v=new Set,C=c.trim(),O=Rr.trim();C&&v.add(C),O&&v.add(O);for(const J of bo){const Q=String(J||"").trim();Q&&v.add(Q)}for(const J of io){const Q=String(J.run_id||((ee=J.record)==null?void 0:ee.run_id)||"").trim();Q&&v.add(Q)}const B=Array.from(v);return B.sort((J,Q)=>C&&J===C&&Q!==C?-1:C&&Q===C&&J!==C?1:O&&J===O&&Q!==O?-1:O&&Q===O&&J!==O?1:J<Q?-1:J>Q?1:0),B},[c,Rr,bo,io]),Ws=_.useMemo(()=>{var v;for(let C=nn.length-1;C>=0;C--){const O=ZS((v=nn[C])==null?void 0:v.record);if(O)return O}return""},[nn]);function Ri(v){pf(v);const C=c.trim();if(!(!C||typeof window>"u"))try{window.history.replaceState(null,"",jR(nR(C),v))}catch{}}const An=_.useMemo(()=>{const v=c.trim();return v&&(Fn.find(C=>String(C.run_id||"").trim()===v)||is.find(C=>String(C.run_id||"").trim()===v))||null},[Fn,is,c]),_s=_.useMemo(()=>An||(we&&String((we==null?void 0:we.run_id)||"").trim()?z_(we):null),[An,we]),cr=_s?`${String(_s.run_id||"")}|${String(_s.workflow_id||"")}|${String(_s.automation_id||"")}|${String(_s.session_id||"")}`:"",fi=String((_s==null?void 0:_s.session_id)||"").trim(),h_=String((_s==null?void 0:_s.updated_at)||""),oo=Math.floor(Date.now()/6e4);_.useEffect(()=>{if(e!=="observe"||xs!=="agent"||!fi||!L||qn.key!==cr||qn.loading)return;const v=ue.current;qe.list_runs({session_id:fi,include_metrics:!0,limit:200}).then(C=>{if(v!==ue.current)return;const O=Array.isArray(C==null?void 0:C.items)?C.items.map(z_):[];G(B=>B.key===cr?{...B,runs:O,runs_error:""}:B)}).catch(C=>{v===ue.current&&G(O=>O.key===cr?{...O,runs_error:String((C==null?void 0:C.message)||C||"failed")}:O)})},[h_,oo,qn.key,qn.loading]),_.useEffect(()=>{if(e!=="observe"||xs!=="agent"||!cr||!L||qn.key===cr)return;const v=_s,C=String(v.run_id||"").trim(),O=++ue.current;G({...Ok,key:cr,loading:!0});const B=String(v.workflow_id||"").trim(),ee=()=>{const re=B.indexOf("@"),We=re>=0?B.indexOf(":",re):-1;return re>=0&&We>re?qe.get_bundle_flow(B.slice(0,We),B.slice(We+1)):qe.get_workflow_flow(B)},J=String(v.automation_id||"").trim(),Q=String(v.session_id||"").trim();Promise.allSettled([qe.get_run_input_data(C),B?ee():Promise.reject(new Error("the run names no workflow")),J?qe.automations_client().getAutomation(J):Promise.resolve(null),Q?qe.list_runs({session_id:Q,include_metrics:!0,limit:200}):Promise.resolve({items:[]})]).then(([re,We,be,_e])=>{var ft;if(O!==ue.current)return;const Le=nt=>{var fn;return nt.status==="rejected"?String(((fn=nt.reason)==null?void 0:fn.message)||nt.reason||"failed"):""},Oe=be.status==="fulfilled"?be.value:null,tt=_e.status==="fulfilled"&&Array.isArray((ft=_e.value)==null?void 0:ft.items)?_e.value.items.map(z_):[];G({key:cr,loading:!1,input_data:re.status==="fulfilled"?re.value:null,input_error:Le(re),flow:We.status==="fulfilled"?We.value:null,flow_error:Le(We),automation_body:Oe,automation:Oe?_h(Oe):null,automation_error:Le(be),runs:tt,runs_error:Le(_e)})})},[e,xs,cr,L,qn.key]);const Jf=_.useMemo(()=>{const v=new Map;for(const C of qn.runs)String(C.run_id||"").trim()&&v.set(String(C.run_id).trim(),C);for(const C of Fn){const O=String(C.run_id||"").trim();if(!O)continue;const B=v.get(O);v.set(O,B?{...B,...C,tokens_total:C.tokens_total??B.tokens_total,llm_calls:C.llm_calls??B.llm_calls,tool_calls:C.tool_calls??B.tool_calls}:C)}return _s&&!v.has(String(_s.run_id||"").trim())&&v.set(String(_s.run_id).trim(),_s),Array.from(v.values())},[qn.runs,Fn,_s]),__=_.useMemo(()=>HI(io,c.trim(),ar),[io,c,bo]),p_=_.useMemo(()=>{if(!_s)return null;const v=p$(_s,we),C=new Map;return we&&C.set(String(v.run_id||"").trim(),we),Vd(v,Lv(Jf,{now_ms:xu,details:C}))},[_s,we,Jf,xu]),sa=String((we==null?void 0:we.status)||(An==null?void 0:An.status)||"").trim(),g_=String(Bs||((dd=we==null?void 0:we.waiting)==null?void 0:dd.reason)||(An==null?void 0:An.waiting_reason)||"").trim().toLowerCase(),y_=!!(we!=null&&we.is_scheduled||An!=null&&An.is_scheduled),Tc=!!(we!=null&&we.paused||An!=null&&An.paused),id=y_&&sa.toLowerCase()==="waiting",Xr=id&&g_==="until",xn=It(Ti),As=Xr&&xn!==null?Bm(xn-Date.now()):"",cs=Cp(we),js=y_&&Tc?"Suspended":id?"Scheduled":Um({status:sa,paused:Tc,stop_reason:cs});async function Pr(){if(L){Cu(!0),jf("");try{const v=So,C=v==="session"?String(hl||Ei||z||"").trim():"",O=v==="run"?String(En||c||"").trim():"",B=sI(Xo),ee=_l.length?_l.join(","):"",J=rI($o),Q=Math.max(0,Yi)*ap,re=await qe.search_artifacts({scope:v,session_id:C||void 0,run_id:O||void 0,query:Ki||void 0,artifact_kind:ee||void 0,created_after:B||void 0,include_stats:!0,limit:ap,offset:Q,order_by:J.order_by,order:J.order}),We=[],be=new Set;for(const ft of Array.isArray(re==null?void 0:re.items)?re.items:[]){const nt=eI(ft,"search");!nt||be.has(nt.artifact_id)||(be.add(nt.artifact_id),We.push(nt))}const _e=re!=null&&re.stats&&typeof re.stats=="object"?re.stats:{},Le=Number((_e==null?void 0:_e.total)??(re==null?void 0:re.total)??We.length),Oe=Db(re);let tt=Oe;if(_l.length)try{const ft=await qe.search_artifacts({scope:v,session_id:C||void 0,run_id:O||void 0,query:Ki||void 0,created_after:B||void 0,include_stats:!0,limit:1,offset:0,order_by:J.order_by,order:J.order});tt=Db(ft)}catch{tt=Oe}Nu(Number.isFinite(Le)?Math.max(0,Le):We.length),$u(Number((_e==null?void 0:_e.total_bytes)??(_e==null?void 0:_e.byte_total)??0)||0),Rh(Oe),Ih(tt),_c(We),Co(ft=>{var nt;return ft&&We.some(fn=>fn.artifact_id===ft)?ft:((nt=We[0])==null?void 0:nt.artifact_id)||""})}catch(v){jf(String((v==null?void 0:v.message)||v||"Failed to load artifacts")),_c([]),Nu(0),$u(0),Rh({}),Ih({}),Co("")}finally{Cu(!1)}}}async function Pa(){if(L){Iu(!0),Lr("");try{const v=await qe.audit_log_tail({max_bytes:16e4}),C=typeof(v==null?void 0:v.bytes)=="number"?Number(v.bytes):0,O=!!(v!=null&&v.truncated);eo(String((v==null?void 0:v.content)||"")),Nf(`${C.toLocaleString()} bytes${O?" (tail)":""}`)}catch(v){Lr(String((v==null?void 0:v.message)||v||"Failed to load audit log")),eo(""),Nf("")}finally{Iu(!1)}}}async function Ts(v){if(!L)return;const C=String(v||li||En||c||"").trim();if(!C){gc([]),xl(""),Ef("Select a run in Activity or Artifacts to load its runtime ledger.");return}Ta(!0),Ef("");try{const O=await qe.get_ledger(C,{after:0,limit:2e3}),B=Array.isArray(O.items)?O.items:[];gc(B.map((J,Q)=>({cursor:Q+1,record:J})));const ee=typeof O.next_after=="number"?Number(O.next_after):B.length;xl(`${B.length.toLocaleString()} record${B.length===1?"":"s"}${ee>=2e3?" (first 2,000)":""}`)}catch(O){Ef(String((O==null?void 0:O.message)||O||"Failed to load run ledger")),gc([]),xl("")}finally{Ta(!1)}}_.useEffect(()=>{L&&e==="runtime"&&Pr()},[L,e,So,hl,En,Ki,_l,Xo,$o,Yi]),_.useEffect(()=>{L&&(Lu||Qi||e==="runtime"&&Pa())},[L,e,xs]),_.useEffect(()=>{if(!L||e!=="runtime"||hc!=="logs"||Gn!=="run_ledger"&&Gn!=="provider_calls")return;const v=String(li||En||c||"").trim();v&&Ts(v)},[L,e,hc,Gn,li,En,c]);const mi=_.useMemo(()=>{const v=new Map;for(const C of[...is,...Fn]){const O=String(C.run_id||"").trim();O&&v.set(O,C)}for(const C of bo){const O=String(C||"").trim();!O||v.has(O)||v.set(O,{run_id:O,workflow_id:null,status:"",created_at:null,updated_at:null,ledger_len:null,parent_run_id:Gr.current[O]||null,session_id:Ei||null})}return c.trim()&&!v.has(c.trim())&&v.set(c.trim(),{run_id:c.trim(),workflow_id:typeof(we==null?void 0:we.workflow_id)=="string"?String(we.workflow_id):null,status:typeof(we==null?void 0:we.status)=="string"?String(we.status):"",created_at:typeof(we==null?void 0:we.created_at)=="string"?String(we.created_at):null,updated_at:typeof(we==null?void 0:we.updated_at)=="string"?String(we.updated_at):null,ledger_len:nn.length||null,parent_run_id:typeof(we==null?void 0:we.parent_run_id)=="string"?String(we.parent_run_id):null,session_id:typeof(we==null?void 0:we.session_id)=="string"?String(we.session_id):Ei||null}),Array.from(v.values()).sort((C,O)=>{const B=It(C.updated_at||C.created_at)??0;return(It(O.updated_at||O.created_at)??0)-B})},[Fn,is,c,we,nn.length,bo,Ei]),Da=_.useMemo(()=>FI(mi,{query:yu,filter:wu,group_by:uf,workflow_label_by_id:Gs,parent_hint:v=>Gr.current[v]||""}),[mi,yu,wu,uf,Gs]),ao=_.useMemo(()=>{const v={};for(const C of mi){const O=String(C.run_id||"").trim();O&&(v[O]=C)}return v},[mi]),Mc=String(li||En||c||"").trim(),Fa=Mc&&ao[Mc]||null,jr=String(hl||(Fa==null?void 0:Fa.session_id)||Ei||z||"").trim(),od=_.useMemo(()=>Su.map(v=>Lp(v,ao,Gs)),[Su,ao,Gs]);_.useEffect(()=>{rr(0)},[Ki,_l,Xo,En,$o,No,So,hl]);const Pl=Math.max(1,Math.ceil(pc/ap)),Zr=Math.min(Math.max(0,Yi),Pl-1);_.useEffect(()=>{Yi!==Zr&&rr(Zr)},[Yi,Zr]);const lo=_.useMemo(()=>od,[od,Zr]),Yf=_.useMemo(()=>{const v={};for(const C of lo){const O=No==="type"?vw(C,ao,Gs):tI(C,No);v[O]||(v[O]=[]),v[O].push(C)}return Object.entries(v).map(([C,O])=>({key:C,items:O})).sort((C,O)=>{var B,ee;if(No==="time"){const J=It((B=C.items[0])==null?void 0:B.created_at)??0,Q=It((ee=O.items[0])==null?void 0:ee.created_at)??0;if(J!==Q)return Q-J}return C.key.localeCompare(O.key)})},[lo,No,ao,Gs]),hi=_.useMemo(()=>{const v=br.trim();return v?lo.find(C=>C.artifact_id===v)||lo[0]||null:lo[0]||null},[lo,br]);_.useEffect(()=>{e!=="runtime"||hc!=="artifacts"||Xh(hi)},[e,hc,hi==null?void 0:hi.artifact_id]),_.useEffect(()=>()=>{Eo.url&&URL.revokeObjectURL(Eo.url)},[Eo.url]);const ad=_.useMemo(()=>mi.filter(v=>Ud(v.status)),[mi]);_.useEffect(()=>{if(e!=="settings"&&e!=="launch"||!L||K)return;let v=!1;return(async()=>{const[C,O]=await Promise.all([qe.list_skills(),qe.list_mcp_servers()]);v||(Y(C),ve(O),fe(!0))})(),()=>{v=!0}},[e,L,K]);function Li(){cc&&window.setTimeout(()=>{var v;return(v=_f.current)==null?void 0:v.scrollIntoView({block:"start"})},60)}function Po(v){vo(v),Li()}const Rc=[{id:"board",label:"Board",icon:s.jsx(Xe,{name:"board",size:16})},{id:"observe",label:"Observe",icon:s.jsx(Xe,{name:"history",size:16})},{id:"runtime",label:"System",icon:s.jsx(Xe,{name:"server",size:16})},{id:"automations",label:"Automations",icon:s.jsx(Xe,{name:"refresh",size:16})}],Xf={board:"Board",observe:"Observe",runtime:"System",launch:"Launch",automations:"Automations",settings:"Settings"},Lc=s.jsx(II,{connected:L,request:Ma,value:Wu,onChange:v=>ms("workspace",v===null?void 0:v),disabled:Pe||St}),Ic=s.jsx(s.Fragment,{children:zs?s.jsxs("details",{className:"launch_capabilities",style:{marginTop:"10px"},children:[s.jsxs("summary",{className:"help_text muted",style:{cursor:"pointer"},children:["Capabilities",Ci.length?` · ${Ci.length} skill${Ci.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."}),W===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."}):W.length?s.jsx("div",{className:"launch_skill_list",children:W.map(v=>{var ee;const C=Ci.includes(v.name),O=v.blocked===!0,B=v.requires_review===!0&&!O;return s.jsxs("label",{className:`launch_skill_row ${O?"is_blocked":""} ${C?"is_on":""}`,title:[v.description||"",v.tree_hash?`tree ${v.tree_hash.slice(0,16)}…`:"",O&&((ee=v.reasons)!=null&&ee.length)?`blocked: ${v.reasons.join("; ")}`:""].filter(Boolean).join(`
|
|
171
|
+
`),children:[s.jsx("input",{type:"checkbox",checked:C,disabled:O||Pe||St||ct,onChange:J=>{const Q=J.target.checked?Array.from(new Set([...Ci,v.name])):Ci.filter(re=>re!==v.name);ms("skills",Q.length?Q:void 0)}}),s.jsx("span",{className:"launch_skill_name",children:v.name}),v.trust_level?s.jsx("span",{className:`chip ${O?"danger":B?"warn":"muted"}`,children:O?"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."}),Ci.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}),Sr=s.jsxs("section",{className:"launch_workspaces","data-section":"workspaces",style:{marginTop:"10px"},children:[s.jsx("div",{className:"launch_label launch_section_title",children:"Workspaces"}),Lc,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:Wh,onChange:v=>ms("workspace_root",v.target.value||void 0),placeholder:"/path/to/workspace",disabled:Pe||St}),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."})]})})]}),Do=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:po,type:"file",accept:".flow",style:{display:"none"},onChange:v=>{const C=v.target.files&&v.target.files.length?v.target.files[0]:null;C&&or(C)}}),s.jsx("button",{type:"button",className:"btn launch_btn_upload",onClick:()=>{var v;return(v=po.current)==null?void 0:v.click()},disabled:!L||Z||bi||Pe||St,title:"Upload a .flow bundle",children:bi?"…":"Upload .flow"}),s.jsxs("button",{type:"button",className:"btn launch_btn_reload",onClick:()=>void Sg(),disabled:!L||Z||_t||Pe||St,title:"Reload picks up server-side edits",children:[s.jsx(Xe,{name:"refresh",size:14}),_t?"…":"Reload bundles"]})]})]});function _i(v){t("observe"),vo("ledger"),ro(v)}const Dr={on_select:v=>void Kn.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"){Kn.ask_archive(v.automation_id);return}Kn.row_action(v,C)},on_legacy_action:(v,C)=>{if(C==="open_run"){_i(v.automation_id);return}if(C==="recreate"){n_(v.automation_id).catch(O=>Kn.report_error(O));return}Kn.legacy_action(v,C)},on_confirm_archive:v=>void Kn.row_action(v,"archive"),on_cancel_archive:()=>Kn.ask_archive(""),on_status_filter:v=>void Kn.set_status_filter(v),on_refresh:()=>void Kn.refresh(),on_new:()=>Ue("automate"),on_show_archived:v=>Kn.set_show_archived(v)};return s.jsxs("div",{className:`app-shell shell${ff?" nav_open":""}`,children:[df&&ff?s.jsx("div",{className:"shell_nav_backdrop","aria-hidden":"true",onClick:()=>Go(!1)}):null,s.jsxs("aside",{className:"shell_sidebar",id:"shell_nav",ref:hf,...Hi.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:()=>Go(!1),children:s.jsx(Xe,{name:"x",size:16})})]}),s.jsxs("nav",{className:"shell_nav",children:[Rc.map(v=>s.jsxs("button",{className:`shell_nav_item ${e===v.id?"active":""}`,onClick:()=>{t(v.id),Go(!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:a,target:"_blank",rel:"noreferrer",title:"Open the entity app (memory graph + visits)",children:[s.jsx("span",{className:"shell_nav_icon",children:s.jsx(Xe,{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"),Go(!1)},type:"button",children:[s.jsx("span",{className:"shell_nav_icon",children:s.jsx(Xe,{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:L?"Gateway connected":Z?"Gateway: connecting…":"Gateway: signed out",children:[s.jsx("span",{className:`gateway_led ${L?"ok":Z?"warn":"err"}`,"aria-hidden":"true"}),s.jsx("span",{className:`shell_connection_label ${L&&((em=(ia=V==null?void 0:V.gateway)==null?void 0:ia.principal)!=null&&em.user_id)?"mono":""}`,children:L?((fd=(tm=V==null?void 0:V.gateway)==null?void 0:tm.principal)==null?void 0:fd.user_id)||(n.gateway_auth_mode==="direct"?"direct dev":"connected"):Z?"connecting…":"signed out"}),L&&cf?s.jsxs("span",{className:"shell_connection_notice",role:"status",title:cf,children:[ol[ol.length-1].title,ol.reduce((v,C)=>v+C.count,0)>1?` ×${ol.reduce((v,C)=>v+C.count,0)}`:""]}):null]})})]}),s.jsxs("div",{className:"shell_main",...Hi.attrs.main,children:[s.jsxs("header",{className:"shell_header",children:[s.jsx("button",{ref:mf,type:"button",className:"shell_nav_toggle","data-nav-toggle":!0,"aria-label":"Open navigation","aria-controls":"shell_nav","aria-expanded":ff,title:"Navigation",onClick:()=>Go(!0),children:s.jsx(Xe,{name:"list",size:18})}),s.jsx("div",{className:"shell_header_title",children:Xf[e]||"Observer"}),s.jsxs("div",{className:"shell_header_actions",children:[i?s.jsx("monitor-gpu",{ref:u,mode:"icon","history-size":"5","tick-ms":"1500","base-url":n.gateway_auth_mode==="session"?"":n.gateway_url,title:"GPU usage (host)",style:{"--monitor-gpu-width":"34px","--monitor-gpu-bars-height":"22px","--monitor-gpu-padding":"2px 4px","--monitor-gpu-radius":"999px","--monitor-gpu-bg":"rgba(0,0,0,0.22)","--monitor-gpu-border":"rgba(255,255,255,0.16)",flexShrink:0}}):null,s.jsx(F2,{docs:{open:Dn,onToggle:()=>$n(v=>!v),label:"Docs assistant"},appearance:{onOpen:()=>rs(!0)},about:{identity:Du,versions:bl,onOpen:Tf},connection:{phase:X.phase,signingOut:X.signingOut,onConnect:()=>X.openModal(),onDisconnect:()=>bc()}})]})]}),s.jsx(_2,{...X.modalProps}),s.jsx(W2,{open:Un,onClose:()=>rs(!1),value:Nn,onChange:Qt}),s.jsx(qM,{open:Dn,onClose:()=>$n(!1),connected:L,topOffset:44,gateway:qe}),s.jsxs("div",{className:"app-body shell_content",children:[e==="board"?L?s.jsx(WB,{gateway_connected:L,runs:is,all_runs:Fn,runs_refreshed_at:Ee,runs_stale:vg,notice:cf,entities:se,entities_total:je,entities_error:ze,on_open_run:v=>{t("observe"),vo("agent"),ro(v)},on_resume_wait:di,on_open_automation:v=>{De(!1),t("automations"),Kn.refresh().then(()=>Kn.select(v))},entity_app_href:a,on_read_diary:(v,C)=>qe.read_entity_diary_entry(v,C),phase_graph:Rf,client:qe,on_rename_automation:(v,C,O)=>Kn.revise(v,{title:C},O??null),on_revise_automation:(v,C,O)=>Kn.revise(v,C,O),on_automation_command:(v,C)=>Kn.command(v,C),on_resume_run:v=>El(v,"resume"),on_cancel_run:v=>El(v,"cancel"),on_cancel_runs:s_,code_app:ot,done_loaded:(()=>{const v=uz(qe);return v!==null&&v.epoch===Yr.current&&v.sweep_at!==null})()}):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.",T?` Last attempt: ${T}`:""]}),s.jsxs("div",{className:"row",style:{gap:"8px",alignItems:"center"},children:[s.jsx("button",{className:"btn primary",onClick:()=>X.openModal(),disabled:Z,children:Z?"Connecting…":"Sign in"}),s.jsx("button",{className:"btn",onClick:()=>void hs({open_modal_if_needed:!0}),disabled:Z,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 ${L?"ok":"warn"}`,children:Hk(V).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:()=>X.openModal(),children:"Manage connection…"}),L?s.jsx("button",{className:"btn",onClick:()=>bc(),title:"Sign this browser out of the gateway (this app's session only)",children:"Sign out"}):null]})]}),T?s.jsx("div",{className:"warn_callout",children:T}):null,s.jsx("div",{className:"settings_row",children:s.jsx(y3,{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:Yp})]}),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 hs({prefer_direct:!0}),disabled:Z,children:Z?"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(Bk,{className:"field",providerLabel:"Provider",modelLabel:"Model",providerPlaceholder:"(gateway default)",modelPlaceholder:"(gateway default)",provider:n.maintenance_ai_provider,model:n.maintenance_ai_model,providers:Hh,models:as.models,loadingProviders:Z,loadingModels:Mf,modelError:$l?as.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"}),W===null?s.jsx("div",{className:"settings_row_help",children:L?K?"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)."}):W.length?s.jsx("div",{className:"settings_choice_list",children:W.map(v=>{const C=n.assistant_skill_names.includes(v.name);return s.jsx(w3,{name:v.name,version:v.version,description:v.description,checked:C,onChange:O=>r(B=>({...B,assistant_skill_names:O?Array.from(new Set([...B.assistant_skill_names,v.name])):B.assistant_skill_names.filter(ee=>ee!==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(ML,{gateway:L?qe:null,connected:L,defaults:If,value:Cl,onChange:Vh})})]})]})}):null,s.jsx(Kl,{open:$e,title:ge==="automate"?"New automation":"Run once",variant:"fullscreen",onClose:()=>De(!1),children:s.jsx("div",{className:"launch_modal_scroll",children:s.jsx("div",{className:"page_inner constrained",children:s.jsxs("div",{className:"card",children:[s.jsx(wL,{mode:ge,automate_available:Be.available,automate_reason:Be.reason,on_change:pe}),ge==="automate"&&!Be.available&&L?s.jsx("div",{className:"warn_callout",role:"note",children:Be.reason}):null,ge==="automate"&&Te.length?s.jsx("div",{className:"help_text",role:"note",children:Te.map(v=>s.jsx("div",{children:v},v))}):null,L?null:s.jsxs("div",{className:"warn_callout",children:["Not connected."," ",s.jsx("button",{className:"btn primary",onClick:()=>X.openModal(),children:"Sign in"})," ","to launch workflows on this gateway."]}),ge==="automate"?s.jsx("div",{className:"section_title",children:"What"}):null,s.jsx("div",{className:"launch_workflow_bar",children:s.jsx(Lj,{id:"launch-workflow-picker",className:"launch_workflow_picker",interfaceId:null,defaultInterface:Id,ariaLabel:"Workflow",workflows:Sl,value:Sb(zs,((Oc=Sl.data)==null?void 0:Oc.entries)??[]),currentLabel:zs&&!Sb(zs,((v_=Sl.data)==null?void 0:v_.entries)??[])?{name:Gs[jl]||jl}:null,unavailableReason:L?Z?"Loading workflows…":null:"Sign in to load workflows.",onChange:(v,C)=>{const O=HR(v,C);O&&Df(O)}})}),s.jsxs("div",{className:"field",children:[Fs!=null&&Fs.description?s.jsx("div",{className:"help_text muted",style:{fontSize:"var(--font-size-sm)",marginTop:"6px"},children:String(Fs.description)}):null,D?s.jsx("div",{className:"help_text muted",style:{fontSize:"var(--font-size-sm)"},children:"Loading workflow…"}):null,q?s.jsx("div",{className:"mono",style:{color:"rgba(239, 68, 68, 0.9)",fontSize:"var(--font-size-sm)"},children:q}):null]}),s.jsx("div",{className:"section_divider"}),s.jsx("div",{className:"section_title",children:"Inputs"}),zs?tn===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:Vt()})]}),s.jsx("div",{className:"body mono",children:"Invalid input JSON — reselect the workflow to reset its inputs."})]}):qh?s.jsx("div",{className:"launch_inputs",children:(()=>{const v=Pe||St,C=[],O=[];for(const J of ci){if(!J||typeof J!="object")continue;const Q=String(J.id||"").trim();if(!Q||ge==="automate"&&bS.includes(Q))continue;const re=String(J.type||"").trim().toLowerCase();re==="tools"||re==="skills"||re==="mcp"||re==="mcp_servers"||Q==="skills"||Q==="mcp"||Q==="mcp_servers"||re==="array"||Ra(re)||Q==="prompt"||Q==="system"?C.push(J):O.push(J)}const B=J=>String(J||"").trim().replace(/_/g," ").replace(/\b\w/g,Q=>Q.toUpperCase()),ee=(J,Q)=>{const re=String(J.id||"").trim();if(!re)return null;const We=String(J.label||re).trim()||re,be=We===re?B(re):We,_e=String(J.type||"").trim().toLowerCase(),Le=Object.prototype.hasOwnProperty.call(J,"default"),Oe=Le?J.default:void 0,tt=Le?typeof Oe=="string"?Oe:Br(Oe,80):"",ft=tn==null?void 0:tn[re],nt=Le?`${tt}`:"";if(_e==="tools"){if(ge==="automate"&&re==="tools")return null;const it=Array.isArray(ft)?ft.map(Jn=>String(Jn||"").trim()).filter(Boolean):[],Bt=Array.isArray(Oe)?Oe.map(Jn=>String(Jn||"").trim()).filter(Boolean):[],Tn=Array.from(new Set([...yc,...it,...Bt])).sort();return s.jsxs("div",{className:"launch_field_wide",children:[s.jsx("label",{className:"launch_label",children:be}),s.jsx(sw,{options:Tn,value:it,disabled:v,placeholder:"(no tools selected)",onChange:Jn=>ms(re,Jn)})]},re)}if(_e==="skills"||re==="skills")return null;if(_e==="mcp"||_e==="mcp_servers"||re==="mcp"||re==="mcp_servers"){const it=Array.isArray(ft)?ft.map(Jn=>String(Jn||"").trim()).filter(Boolean):[];if(ae===null&&!it.length)return s.jsxs("div",{className:"launch_field_wide",children:[s.jsx("label",{className:"launch_label",children:be}),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."})]},re);const Bt=(ae||[]).map(Jn=>Jn.name),Tn=Array.from(new Set([...Bt,...it])).sort();return s.jsxs("div",{className:"launch_field_wide",children:[s.jsx("label",{className:"launch_label",children:be}),s.jsx(sw,{options:Tn,value:it,disabled:v,placeholder:"(no MCP servers selected)",onChange:Jn=>ms(re,Jn)})]},re)}if(_e==="provider"||_e==="provider_text"){const it=typeof ft=="string"?String(ft):"";return s.jsxs("div",{className:Q||"launch_field",children:[s.jsx("label",{className:"launch_label",children:be}),s.jsxs("select",{value:it,onChange:Bt=>ms(re,Bt.target.value),disabled:v,children:[s.jsx("option",{value:"",children:nt||"(select)"}),Nl.map(Bt=>s.jsx("option",{value:Bt,children:Bt},Bt))]})]},re)}if(_e==="model"||_e==="model_text"){const it=typeof ft=="string"?String(ft):"",Bt=String((tn==null?void 0:tn.provider)||"").trim(),Tn=Bt?on[Bt]:void 0,Jn=Tn&&Array.isArray(Tn.models)?Tn.models.map(ur=>String(ur||"").trim()).filter(Boolean):[];return s.jsxs("div",{className:Q||"launch_field",children:[s.jsx("label",{className:"launch_label",children:be}),Jn.length?s.jsxs("select",{value:it,onChange:ur=>ms(re,ur.target.value),disabled:v,children:[s.jsx("option",{value:"",children:nt||"(select)"}),Jn.map(ur=>s.jsx("option",{value:ur,children:ur},ur))]}):s.jsx("input",{value:it,onChange:ur=>ms(re,ur.target.value),placeholder:nt||"model id",disabled:v})]},re)}if(_e==="boolean"){const it=typeof ft=="boolean"?ft?"true":"false":"";return s.jsxs("div",{className:Q||"launch_field",children:[s.jsx("label",{className:"launch_label",children:be}),s.jsxs("select",{value:it,onChange:Bt=>{const Tn=String(Bt.target.value||"").trim();Tn?ms(re,Tn==="true"):ms(re,void 0)},disabled:v,children:[s.jsx("option",{value:"",children:nt||"(default)"}),s.jsx("option",{value:"true",children:"Yes"}),s.jsx("option",{value:"false",children:"No"})]})]},re)}if(_e==="number"){const it=typeof ft=="number"&&Number.isFinite(ft)?String(ft):"";return s.jsxs("div",{className:Q||"launch_field",children:[s.jsx("label",{className:"launch_label",children:be}),s.jsx("input",{type:"number",value:it,onChange:Bt=>{const Tn=String(Bt.target.value||"").trim();if(!Tn){ms(re,void 0);return}const Jn=Number(Tn);Number.isFinite(Jn)&&ms(re,Jn)},placeholder:nt,disabled:v})]},re)}if(_e==="array"){const it=Array.isArray(ft)?ft.map(Bt=>String(Bt||"").trim()).filter(Boolean).join(`
|
|
172
|
+
`):"";return s.jsxs("div",{className:"launch_field_wide",children:[s.jsx("label",{className:"launch_label",children:be}),s.jsx("textarea",{className:"mono",value:it,onChange:Bt=>{const Tn=String(Bt.target.value||"").split(/\r?\n/g).map(Jn=>String(Jn||"").trim()).filter(Boolean);ms(re,Tn.length?Tn:void 0)},placeholder:nt||"(one item per line)",rows:2,disabled:v})]},re)}if(Ra(_e)){const it=typeof sc[re]=="string"?sc[re]:"",Bt=String(ws[re]||"").trim();return s.jsxs("div",{className:"launch_field_wide",children:[s.jsxs("label",{className:"launch_label",children:[be," ",s.jsx("span",{className:"launch_label_type",children:_e})]}),s.jsx("textarea",{className:"mono",value:it,onChange:Tn=>{const Jn=String(Tn.target.value??"");Qa(Fr=>({...Fr,[re]:Jn}));const ur=Jn.trim();if(!ur){pr(Fr=>{const Ii={...Fr};return delete Ii[re],Ii}),ms(re,void 0);return}try{const Fr=JSON.parse(ur);pr(Ii=>{const za={...Ii};return delete za[re],za}),ms(re,Fr)}catch(Fr){pr(Ii=>({...Ii,[re]:String((Fr==null?void 0:Fr.message)||Fr||"Invalid JSON")}))}},placeholder:nt||"{...}",rows:3,disabled:v}),Bt?s.jsx("div",{className:"launch_field_error",children:Bt}):null]},re)}const fn=typeof ft=="string"?String(ft):"";return re==="prompt"||re==="system"?s.jsxs("div",{className:"launch_field_wide",children:[s.jsx("label",{className:"launch_label",children:be}),s.jsx("textarea",{value:fn,onChange:it=>ms(re,it.target.value),placeholder:nt||(re==="prompt"?"What should the agent do?":"System instructions (optional)"),rows:3,disabled:v})]},re):s.jsxs("div",{className:Q||"launch_field",children:[s.jsx("label",{className:"launch_label",children:be}),s.jsx("input",{value:fn,onChange:it=>ms(re,it.target.value),placeholder:nt,disabled:v})]},re)};return C.sort((J,Q)=>{const re={system:0,prompt:1,tools:2};return(re[String(J.id||"")]??10)-(re[String(Q.id||"")]??10)}),s.jsxs(s.Fragment,{children:[C.map(J=>ee(J)),O.length>0?s.jsx("div",{className:"launch_grid",children:O.map(J=>ee(J,"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:Mo,onChange:v=>ms("prompt",v.target.value),placeholder:"What do you want the workflow/agent to do?",rows:3,disabled:Pe||St})]}),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:no,onChange:v=>ms("provider",v.target.value),placeholder:"lmstudio / ollama / openai / ...",disabled:Pe||St})]})}),s.jsx("div",{className:"col",children:s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Model (common)"}),s.jsx("input",{value:Uu,onChange:v=>ms("model",v.target.value),placeholder:"qwen/qwen3-next-80b / gpt-4.1 / ...",disabled:Pe||St})]})})]})]}):s.jsx("div",{className:"help_text muted",style:{marginTop:"8px"},children:"Select a workflow above to configure inputs."}),ge==="automate"?s.jsxs(s.Fragment,{children:[s.jsx(vL,{form:ut,email_status:Ou.email_status,on_open_my_email:To,served:Uh,on_open_preferences:To,tools:Zk(tn||{})??void 0,available_tools:yc,on_tools_change:v=>E(JSON.stringify(Qk(tn||{},v),null,2)),disabled:ct,on_change:v=>Se(C=>({...C,...v})),workspaces:Lc}),s.jsx(xL,{form:ut,disabled:ct,on_change:v=>Se(C=>({...C,...v}))}),Ic,Do]}):s.jsxs(s.Fragment,{children:[Ic,Sr,Do]}),s.jsx("div",{className:"section_divider"}),Rn?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:Rn})]}):null,ge==="automate"&&me.length?s.jsx("ul",{className:"automate_errors",role:"alert",children:me.map(v=>s.jsx("li",{children:v},v))}):null,ge==="automate"&&ye?s.jsxs("div",{className:"observe_context_card error",role:"alert","data-code":ye.code,style:{marginBottom:"10px"},children:[s.jsx("span",{className:"chip mono danger",children:ye.code}),s.jsxs("span",{children:[s.jsx("strong",{children:kp(ye).title})," ",kp(ye).detail,ye.field?s.jsxs("span",{className:"mono",children:[" (",ye.field,")"]}):null]})]}):null,s.jsx("div",{className:"launch_actions_bar launch_actions_stack",children:(()=>{const v=ge==="automate",C=L?zs?tn===null?"Inputs contain invalid JSON":v&&!Be.available?"Automations unavailable on this gateway":Pe||St?"Attaching to a run…":Z||D?"Loading…":ct?"Submitting…":"":"Select a workflow":"Sign in first";return s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"launch_submit_btn",onClick:()=>void Ng(),disabled:!!C,title:C,children:v?ct?"Creating…":"Create automation":Pe?"Launching…":"Launch now"}),C&&!ct&&!Pe?s.jsx("span",{className:"mono muted launch_disabled_reason",children:C}):null]})})()})]})})})}),e==="automations"?s.jsx(g3,{workflowPickerOptions:{interfaceId:null,defaultInterface:Id,workflows:Sl,request:(v,C)=>qe.get_gateway_json(v,C.signal)},availableTools:yc,ctl:Kn,gateway:qe,active:e==="automations"&&L,available:Be,h:Dr,voice_session_id:z,workspace_request:Ma,host:{on_open_run:v=>_i(v),...To?{on_open_my_email:To}:{},on_open_session:(v,C)=>{hn({ts:Vt(),kind:"info",title:"Discussion started",preview:Wt(C),data:v})}}}):null,e==="runtime"?s.jsx(NI,{runs_loading:es,gateway_connected:L,tab:hc,runs:mi,active_runs:ad,all_artifacts:Su,artifacts:lo,artifact_total_count:pc,artifact_total_bytes:bf,artifact_facets:kf,artifact_type_facets:Lh,artifact_page:Zr,artifact_page_size:ap,artifact_groups:Yf,selected_artifact:hi,embedded_preview:Eo,loading:jg,error:Yo,query:Ki,scope:So,type_filters:_l,date_filter:Xo,group_by:No,sort_by:$o,artifact_run_filter:En,audit_log_text:Qi,audit_log_meta:Aa,audit_log_loading:Lu,audit_log_error:Jr,workflow_label_by_id:Gs,run_by_id:ao,selected_run_id:Mc,session_id:jr,runtime_log_source:Gn,runtime_log_query:Dh,runtime_ledger_log_items:$f,runtime_ledger_log_meta:zh,runtime_ledger_log_loading:Bh,runtime_ledger_log_error:Cf,on_tab_change:Mh,on_query_change:Ji,on_scope_change:Ni,on_session_filter_change:Oh,on_type_filters_change:Ea,on_date_filter_change:pl,on_group_by_change:Sf,on_sort_by_change:Zo,on_artifact_page_change:rr,on_artifact_run_filter_change:v=>{const C=String(v||"").trim();Vn(C),C&&$s(C),C&&So!=="run"&&Ni("run")},on_refresh_artifacts:()=>void Pr(),on_refresh_audit:()=>void Pa(),on_refresh_runtime_ledger:v=>void Ts(v),on_runtime_log_source_change:$i,on_runtime_log_query_change:Fh,on_select_run:v=>{const C=String(v||"").trim();$s(C);const O=C&&ao[C]||null,B=String((O==null?void 0:O.session_id)||"").trim();B&&Oh(B)},on_select_artifact:Co,on_preview_artifact:v=>void Yh(v),on_download_artifact:v=>void Jh(v),on_open_run:v=>{$s(String(v||"").trim()),t("observe"),vo("ledger"),ro(v)},on_open_ledger:v=>{$s(String(v||"").trim()),t("observe"),vo("ledger"),ro(v)},on_refresh_runs:()=>void bs(qe,{force:!0}),on_reconnect:()=>void hs({open_modal_if_needed:!0}),on_open_settings:()=>t("settings"),memory_panel:L?s.jsx(i8,{gateway:qe,selected_run_id:li,selected_session_id:jr}):null}):null,e==="observe"?s.jsx("div",{className:"page observe_page",children:s.jsxs("div",{className:`observatory_layout${jh?"":" list_collapsed"}`,children:[s.jsx(CI,{sections:Da,selected_run_id:c,root_run_id:m,search:yu,filter:wu,group_by:uf,loading:es,connected:L,on_sign_in:()=>X.openModal(),total_runs:mi.length,workflow_label_by_id:Gs,automation_titles:Pu,on_search:kh,on_filter:ll,on_group_by:bg,on_refresh:()=>void bs(),on_select:(v,C)=>{ro(v,{root_run_id:C||v}),Li()},list:{open:jh,on_toggle:Sh}}),s.jsxs("div",{className:"observatory_main",children:[s.jsxs("div",{className:"observe_toolbar",children:[s.jsxs("div",{className:"observe_toolbar_row",children:[c.trim()?s.jsxs("div",{className:"observe_run_identity",title:c.trim(),children:[s.jsx("span",{className:"observe_run_name",children:Gs[String((An==null?void 0:An.workflow_id)||"")]||String((An==null?void 0:An.workflow_id)||"").trim()||jn(c.trim(),22)}),s.jsx("span",{className:"chip mono muted",children:jn(c.trim(),14)}),s.jsx("span",{className:`chip ${_a(js||sa,cs)}`,title:String((cs==null?void 0:cs.headline)||""),children:js||sa||"unknown"})]}):w?s.jsx("span",{className:"observe_run_identity_empty observe_run_link_missing",role:"alert",children:sR(w)}):s.jsx("span",{className:"observe_run_identity_empty",children:"No run selected"}),s.jsx("span",{className:"observe_toolbar_spacer"}),c.trim()?s.jsxs(s.Fragment,{children:[Or?s.jsx(x3,{active:!Lo,unavailableReason:Tg,busy:Pe||St,onChange:v=>{if(!v){qr("pause"),Hr(""),ki(""),Wr(!0);return}Al("resume")}}):s.jsx("button",{className:"btn",onClick:()=>{if(Ks==="pause"){qr("pause"),Hr(""),ki(""),Wr(!0);return}Al("resume")},disabled:Ag,children:Ol}),td?s.jsx("button",{className:"btn primary",onClick:()=>void $g(),disabled:Pe||St||Mi||Lo,children:"Run now"}):null,s.jsx("button",{className:"btn danger",onClick:()=>{qr("cancel"),Hr(""),ki(""),Wr(!0)},disabled:Pe||St||Mi,children:"Cancel"}),s.jsx("button",{className:"btn btn_icon",onClick:Hu,title:"Clear the run view",children:s.jsx(Xe,{name:"x",size:14})})]}):null]}),c.trim()&&!Mi?s.jsx("div",{className:"observe_steer_row",children:s.jsx(k2,{runId:c.trim(),parked:Us,submit:(v,C)=>qe.submit_command({command_id:`steer-${Xs()}`,run_id:v,type:"inject_guidance",payload:{guidance:C},client_id:"web_pwa"}).then(O=>({accepted:!!(O!=null&&O.accepted),duplicate:!!(O!=null&&O.duplicate),seq:Number((O==null?void 0:O.seq)??0)})),onSent:()=>hn({ts:Vt(),kind:"info",title:"Steer queued",preview:"inject_guidance submitted — delivery shows as abstract.steer_seen in the ledger"})})}):null,Us||Or||gu?s.jsxs("div",{className:"observe_toolbar_context",children:[Us?s.jsxs("div",{className:"observe_context_card info",children:[s.jsxs("div",{className:"observe_context_label",children:[(()=>{const v=Or?Lo?"suspended":"scheduled":"waiting";return s.jsx("span",{className:`chip ${_a(v)}`,children:v})})(),s.jsx("span",{className:"muted",children:Bs||"unknown"})]}),s.jsxs("div",{className:"observe_context_body",children:[lr?s.jsxs("span",{className:"mono",title:lr,children:[s.jsx("span",{className:"muted",children:"wait_key"}),": ",jn(lr,46)]}):null,Bs==="event"&&Ku?s.jsxs("span",{className:"mono",children:[s.jsx("span",{className:"muted",children:"event"}),": ",Ku]}):null,Bs==="subworkflow"&&Io?s.jsxs("span",{className:"mono",children:[s.jsx("span",{className:"muted",children:"child"}),": ",jn(Io,18)]}):null,Bs==="until"&&Ti?s.jsxs("span",{className:"mono",title:Ti,children:[s.jsx("span",{className:"muted",children:"until"}),": ",jn(Ti,46)]}):null,Bs==="until"&&Ti?s.jsx("span",{className:"mono muted",children:(()=>{const v=It(Ti),C=v!==null?new Date(v).toLocaleString():Ti,O=v!==null?Bm(v-Date.now()):"";return`Next at ${C}${O?` (in ${O})`:""}`})()}):null]}),Bs==="subworkflow"&&Io?s.jsxs("div",{className:"observe_context_actions",children:[s.jsx("button",{className:"btn primary",onClick:async()=>{d(Io),await $c(Io)},disabled:Pe,children:"Attach to child"}),m.trim()&&m.trim()!==c.trim()?s.jsx("button",{className:"btn",onClick:async()=>{d(m.trim()),await $c(m.trim())},disabled:Pe,children:"Back to root"}):null]}):null]}):null,Or?s.jsxs("div",{className:"observe_context_card muted",children:[s.jsxs("div",{className:"observe_context_label",children:[s.jsx("span",{className:"chip muted",children:"schedule"}),s.jsx("span",{className:"muted",children:ed?`every ${Il}`:"once"})]}),s.jsxs("div",{className:"observe_context_body",children:[Il?s.jsxs("span",{className:"mono",children:[s.jsx("span",{className:"muted",children:"interval"}),": ",Il]}):null,s.jsxs("span",{className:"mono",children:[s.jsx("span",{className:"muted",children:"share ctx"}),": ",f_?"yes":"no"]}),typeof Qu=="number"?s.jsxs("span",{className:"mono",children:[s.jsx("span",{className:"muted",children:"repeats"}),": ",Qu]}):null]}),Ec!==null?s.jsxs("div",{className:"observe_context_budget",children:[s.jsxs("span",{className:"mono muted",children:[typeof gt=="number"&&typeof Oa=="number"?`${gt.toLocaleString()} / ${Oa.toLocaleString()}`:"",` • ${Math.round(Math.max(0,Math.min(1,Ec))*100)}%`]}),s.jsx("div",{className:"observe_budget_bar",children:s.jsx("div",{className:`observe_budget_fill ${Ec>=.9?"danger":Ec>=.75?"warn":"ok"}`,style:{width:`${Math.round(Math.max(0,Math.min(1,Ec))*100)}%`}})})]}):null,s.jsxs("div",{className:"observe_context_actions",children:[ed?s.jsx("button",{className:"btn",onClick:()=>{gs(Il||""),Rs(!0),vs(""),Fi(!0)},disabled:Pe||ii,children:"Edit schedule"}):null,ed?s.jsx("button",{className:"btn",onClick:()=>{Ps(""),ga(!0)},disabled:Pe||Ds,children:"Compact context"}):null,s.jsx("button",{className:"btn",onClick:()=>void n_(c.trim()).catch(v=>vn(String((v==null?void 0:v.message)||v))),disabled:Pe||!c.trim(),title:"Open Launch → Automate prefilled from this schedule (this schedule is not changed)",children:"Recreate as automation"})]})]}):null,gu?s.jsxs("div",{className:"observe_context_card error",children:[s.jsx("span",{className:"chip danger",children:"error"}),s.jsx("span",{className:"mono",children:gu})]}):null]}):null]}),s.jsxs("div",{className:"card panel_card card_scroll observe_viewer observe_viewer_full",ref:_f,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":xs==="agent",className:`tab ${xs==="agent"?"active":""}`,onClick:()=>Po("agent"),children:"Agent"}),s.jsx("button",{role:"tab","aria-selected":xs==="ledger",className:`tab ${xs==="ledger"?"active":""}`,onClick:()=>Po("ledger"),children:"Ledger"}),s.jsx("button",{role:"tab","aria-selected":xs==="graph",className:`tab ${xs==="graph"?"active":""}`,onClick:()=>Po("graph"),children:"Flow"}),s.jsx("button",{role:"tab","aria-selected":xs==="chat",className:`tab ${xs==="chat"?"active":""}`,onClick:()=>Po("chat"),children:"Ask"})]}),xs==="ledger"&&(nn.length>0||en.length>0)?s.jsx("div",{className:"tab_bar_controls",children:s.jsx("button",{className:"seg_action",disabled:!nn.length&&!en.length,title:"Copy full ledger as JSONL",onClick:()=>{const O=[...nn.map(J=>({run_id:c.trim()||J.record.run_id||"",cursor:J.cursor,record:J.record})),...en.map(J=>({run_id:J.run_id,cursor:J.cursor,record:J.record}))].map(J=>{var We,be;const Q=String(((We=J.record)==null?void 0:We.ended_at)||((be=J.record)==null?void 0:be.started_at)||"").trim(),re=It(Q);return{...J,_ms:re??0}});O.sort((J,Q)=>(J._ms||0)-(Q._ms||0));const ee=(O.length>5e3?O.slice(O.length-5e3):O).map(({_ms:J,...Q})=>JSON.stringify(Q)).join(`
|
|
173
|
+
`);kc(ee)},children:"Copy JSONL"})}):null,xs==="graph"?s.jsxs("div",{className:"tab_bar_controls",children:[s.jsx("button",{className:`seg_action ${Gi?"active":""}`,"aria-pressed":Gi,onClick:()=>wf(v=>!v),children:"Subflows"}),s.jsx("button",{className:`seg_action ${ja?"active":""}`,"aria-pressed":ja,onClick:()=>vf(v=>!v),children:"Path"}),sd.length?s.jsx("select",{className:"mono seg_select",value:cl,onChange:v=>wr(String(v.target.value||"")),disabled:!!Oo.trim()||!S.trim()||yf,children:sd.map(v=>s.jsx("option",{value:v,children:v},v))}):null]}):null]}),xs==="agent"?c.trim()&&_s?s.jsx(p9,{run:_s,detail:we,input_data:qn.key===cr?qn.input_data:null,flow:qn.key===cr?qn.flow:null,automation:qn.key===cr?qn.automation:null,automation_body:qn.key===cr?qn.automation_body:null,runs:Jf,records:io,stall_after_ms:J1(typeof localStorage>"u"?null:localStorage),loading:{detail:Pe&&!we,input_data:qn.key!==cr||qn.loading,flow:qn.key!==cr||qn.loading},errors:qn.key===cr?{input_data:qn.input_error||void 0,flow:qn.flow_error||void 0}:{},on_open_run:v=>void ro(v),on_ask:()=>Po("chat"),on_action:(v,C)=>{if(v==="resume"){El(C,"resume");return}if(v==="open_subrun"){ro(C);return}ai(""),Po("ledger")},on_reveal_workspace:()=>void Of(),on_copy:v=>void kc(v)}):s.jsx("div",{className:"rs_page",children:s.jsx("p",{className:"rs_notice",children:c.trim()?"Loading the run…":"Pick a run to see what its agent can do, what it was given, and where it stands."})}):null,xs==="ledger"?c.trim()?s.jsxs("div",{className:"rs_page",children:[s.jsx(BR,{status:js||sa||"unknown",duration:An?iu(An):"",facts:ER(CR(io)),error:Wm(An)||String((we==null?void 0:we.error)||"").trim(),answer:Ws||String((na==null?void 0:na.text)||"").trim(),waiting_for_user:!!(sn!=null&&sn.wait_key)&&String((sn==null?void 0:sn.reason)||"")==="user",on_answer_wait:()=>ai(""),workspace_root:Ch,on_reveal_workspace:()=>void Of(),speak:L?s.jsx(DL,{voice:so,speak_key:`outcome:${c.trim()}`,text:Wm(An)||String((we==null?void 0:we.error)||"").trim()||Ws||String((na==null?void 0:na.text)||"").trim(),error:Lt}):null,on_open_artifacts:()=>{const v=String(c||"").trim();v&&($s(v),Vn(v),Ni("run")),Mh("artifacts"),t("runtime")}}),s.jsx(zR,{items:io,run_id:Gf,run_options:Kf,run_llm_counts:rd,on_select_run:v=>$h(v),state:Nh,on_state:Ri,node_label:(v,C)=>{const O=C?(ea==null?void 0:ea[ar(v,C)])||(ea==null?void 0:ea[C]):null;return String((O==null?void 0:O.label)||C||"").trim()},on_copy:v=>void kc(v),on_open_run:v=>void ro(v,{root_run_id:m||c||v})})]}):s.jsx("div",{className:"empty_state_inline",children:"Select a run on the left to inspect it — or start one from Launch."}):null,xs==="graph"?s.jsxs(s.Fragment,{children:[Eh?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:Vt()})]}),s.jsx("div",{className:"body mono",children:Eh})]}):null,yf?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:Oo.trim()?Oo.trim():cl})]}),s.jsx("div",{className:"body mono",children:"Loading graph…"})]}):null,s.jsx("div",{className:"graph_panel",children:s.jsx(L4,{flow:Vi,flow_by_id:uc,expand_subflows:Gi,simplify:!0,prefer_vertical:!0,vertical_compact:.78,schedule_next_in:As,schedule_interval:Il,node_last_ms:nd,active_node_id:Ac,recent_nodes:Ah,visited_nodes:Th,highlight_path:ja,now_ms:xu,run_id:c.trim(),run_line:p_,run_status:js||sa,node_facts:__,on_open_run:v=>void ro(v)})})]}):null,xs==="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(Pi,{value:of,options:af,placeholder:lc?"Loading…":af.length?"Select a saved discussion…":"(none saved)",disabled:!c.trim()||!L||!af.length,loading:lc,searchable:!0,clearable:!0,onChange:v=>{mu(v),ba("")}})}),s.jsxs("div",{className:"actions",style:{justifyContent:"flex-end",marginTop:0},children:[s.jsx("button",{className:"btn",type:"button",disabled:!of.trim()||!L||hu,onClick:()=>void Tl(),children:hu?"Loading…":"Load"}),s.jsx("button",{className:"btn",type:"button",disabled:!Et.length||Tt||yr||hu,onClick:()=>{_n([]),zn(null),Re(""),dt(""),qi(""),oc(""),xa("")},children:"Clear"}),s.jsx("button",{className:"btn",type:"button",onClick:()=>void Gu(),disabled:!c.trim()||!L||lc,children:lc?"Refreshing…":"Refresh"})]})]}),s.jsxs("div",{className:"actions",style:{justifyContent:"flex-end",marginTop:"8px",flexWrap:"wrap"},children:[s.jsx("button",{className:"btn",type:"button",disabled:!Et.length||!c.trim()||!L||yr||!_u,onClick:()=>void Bf(),title:_u?"":"No changes since last save",children:yr?"Saving…":!_u&&nf?"Saved":"Save discussion"}),s.jsx("button",{className:"btn",type:"button",disabled:!Et.length,onClick:()=>zf("download"),children:"Export Markdown"}),s.jsx("button",{className:"btn",type:"button",disabled:!Et.length,onClick:()=>zf("copy"),children:wn==="copied"?"Copied":wn==="failed"?"Copy failed":"Copy Markdown"})]}),nf?s.jsxs("div",{className:"chat_hint",children:["Last saved: ",Xc(nf)]}):null,rl?s.jsx("div",{className:"chat_hint chat_hint_danger",children:rl}):null,wh?s.jsx("div",{className:"chat_hint chat_hint_danger",children:wh}):null,rf?s.jsx("div",{className:"chat_hint chat_hint_danger",children:rf}):null]})]}),Ke?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:Vt()})]}),s.jsx("div",{className:"body mono",children:Ke})]}):null,Lt?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:Vt()})]}),s.jsx("div",{className:"body mono",children:Lt})]}):null,s.jsx("div",{className:"chat_messages",style:{marginTop:"10px"},children:s.jsx(xv,{messages:Et,className:"log_scroll",after:s.jsx(QM,{history:os}),afterKey:os?`${os.replayed_messages}:${os.dropped_messages}`:null,messageProps:so.tts_supported&&L?{onSpeakToggle:Vu,getSpeakState:i_,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(bv,{ref:Tr,value:Me,onChange:Re,onSubmit:()=>void Ff(),placeholder:"Ask about this run…",disabled:!c.trim()||!L||Tt,busy:Tt||so.voice_ptt_busy,busyLabel:so.voice_ptt_busy?"Transcribing…":"Thinking…",rows:3,sendButtonClassName:"btn primary",actions:s.jsx(LS,{voice:so,defaults:If.value,prefs:Cl,blocked:L?Tt?"Wait for the answer.":null:"Connect to the gateway first."})}),CS()?null:s.jsx("div",{className:"mono muted","data-testid":"voice-https-hint",style:{fontSize:"var(--font-size-sm)",marginTop:"6px"},children:NS})]})]}):null,c.trim()?s.jsxs("div",{className:`status_bar ${wa?"pulse":""}`,children:[s.jsx("strong",{children:"Run"}),":"," ",s.jsx("span",{className:"mono",children:js||sa||"unknown"}),Xr&&As?s.jsxs("span",{className:"mono muted",children:[" • next in ",As]}):null,Vo?s.jsxs("span",{className:"mono muted",children:[" • ",Vo]}):null]}):null]})]})]})}):null,s.jsxs(Kl,{open:Ph,title:Au||"Artifact",onClose:()=>{gl(!1),Qo(""),Zi(""),kr(!1),vl(null),ir&&(URL.revokeObjectURL(ir),Mu(""))},actions:s.jsx("button",{className:"btn",onClick:()=>{gl(!1),Qo(""),Zi(""),kr(!1),vl(null),ir&&(URL.revokeObjectURL(ir),Mu(""))},children:"Close"}),children:[Ru?s.jsx("div",{className:"mono muted",style:{fontSize:"var(--font-size-sm)",marginBottom:"8px"},children:"Loading…"}):null,Kr?s.jsx("div",{className:"mono",style:{color:"rgba(239, 68, 68, 0.9)",fontSize:"var(--font-size-sm)",marginBottom:"8px"},children:Kr}):null,Xi==="image"&&ir?s.jsx("img",{className:"runtime_preview_media",src:ir,alt:Au||"Artifact preview"}):Xi==="audio"&&ir?s.jsx(rg,{className:"runtime_preview_media",src:ir,name:Au||void 0}):Xi==="video"&&ir?s.jsx("video",{className:"runtime_preview_media",controls:!0,src:ir}):s.jsx(eN,{artifact:wl,text:Tu||"(empty)",className:"runtime_preview_text"})]}),Ms?s.jsxs(Kl,{open:Ms,title:"Edit schedule",onClose:()=>{Fi(!1),gs(""),Rs(!0),vs(""),zi(!1)},actions:s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"btn",onClick:()=>{Fi(!1),gs(""),Rs(!0),vs(""),zi(!1)},disabled:Pe||ii,children:"Back"}),s.jsx("button",{className:"btn primary",onClick:async()=>{await Cg({interval:el,apply_immediately:si})||(Fi(!1),vs(""),zi(!1))},disabled:Pe||ii||!el.trim(),children:"Save"})]}),children:[ri?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:Vt()})]}),s.jsx("div",{className:"body mono",children:ri})]}):null,s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Interval"}),s.jsx("input",{className:"mono",value:el,onChange:v=>gs(String(v.target.value||"")),placeholder:"20m / 1h / 0.5s / 250ms",disabled:Pe||ii}),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:()=>gs(v),disabled:Pe||ii,children:v},v))})]}),s.jsx("div",{className:"field",children:s.jsx(k3,{checked:si,busy:Pe||ii,onChange:Rs})})]}):null,Sn?s.jsxs(Kl,{open:Sn,title:"Compact scheduled context",onClose:()=>{ga(!1),Ps(""),gr(!1)},actions:s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"btn",onClick:()=>{ga(!1),Ps(""),gr(!1)},disabled:Pe||Ds,children:"Cancel"}),s.jsx("button",{className:"btn primary",onClick:async()=>{await Ai({preserve_recent:tl,compression_mode:Er,focus:Bi})||(ga(!1),Ps(""),gr(!1))},disabled:Pe||Ds,children:Ds?"Compacting…":"Compact"})]}),children:[go?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:Vt()})]}),s.jsx("div",{className:"body mono",children:go})]}):null,s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Preserve recent turns"}),s.jsx("input",{type:"number",min:1,value:String(tl),onChange:v=>nl(Math.max(1,parseInt(v.target.value||"6",10)||6)),disabled:Pe||Ds})]}),s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Mode"}),s.jsxs("select",{value:Er,onChange:v=>rc(v.target.value),disabled:Pe||Ds,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:Bi,onChange:v=>ya(String(v.target.value||"")),placeholder:"e.g. important decisions, next steps…",disabled:Pe||Ds})]})]}):null,yo?s.jsxs(Kl,{open:yo,title:Ar==="cancel"?"Cancel run":Or?"Suspend schedule":"Pause run",onClose:()=>{Wr(!1),Hr(""),ki("")},actions:s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"btn",onClick:()=>{Wr(!1),Hr(""),ki("")},disabled:Pe||St,children:"Back"}),s.jsx("button",{className:`btn ${Ar==="cancel"?"danger":"primary"}`,onClick:async()=>{ki("");const v=await Al(Ar,{reason:ic});if(v){ki(v);return}Wr(!1),Hr(""),ki("")},disabled:Pe||St,children:Ar==="pause"?Or?"Suspend":"Pause":"Cancel"})]}),children:[uu?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:Vt()})]}),s.jsx("div",{className:"body mono",children:uu})]}):null,s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Reason (optional)"}),s.jsx("input",{className:"mono",value:ic,onChange:v=>Hr(v.target.value),placeholder:"reason…"})]})]}):null,Wf?s.jsxs(Kl,{open:Wf,title:qf,onClose:()=>{lr&&ai(lr)},actions:s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"btn",onClick:()=>{vo("ledger"),t("observe"),Li(),lr&&ai(lr)},disabled:!c.trim(),children:"Open ledger"}),s.jsx("button",{className:"btn",onClick:()=>lr&&ai(lr),disabled:St,children:"Dismiss"}),Ia.length?s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"btn danger",disabled:St,onClick:()=>Ml({approved:!1}),children:"Reject"}),s.jsx("button",{className:"btn",disabled:St,onClick:()=>Ml({approved:!0}),children:"Approve only"}),s.jsx("button",{className:"btn primary",disabled:!kl||St,onClick:()=>Uf(Ia),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:qf}),s.jsx("p",{children:c_})]}),s.jsx(ou,{status:Ro||"waiting"})]}),ta?s.jsxs("div",{className:`wait_request_card ${Xu?"":"inferred"}`,children:[s.jsx("span",{children:Hf}),s.jsx(Dk,{metadata:u_}),s.jsx(xi,{text:ta}),Xu?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."}),Cc.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:Cc.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:Xc(v.ts)}):null]}),s.jsx(Dk,{metadata:v.runtime_metadata}),s.jsx(xi,{text:Wt(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:Uo(Rl,Gs)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Run"}),s.jsx("strong",{className:"mono",children:jn(c.trim(),24)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Node"}),s.jsx("strong",{className:"mono",children:Rl.current_node||String((ns==null?void 0:ns.node_id)||"—")})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Elapsed"}),s.jsx("strong",{children:iu(Rl)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Session"}),s.jsx("strong",{className:"mono",children:Rl.session_id?jn(String(Rl.session_id),18):"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Wait key"}),s.jsx("strong",{className:"mono",children:jn(lr,28)})]})]}),Zu?s.jsxs("details",{className:"runtime_raw_details wait_full_input_details",open:!ta,children:[s.jsx("summary",{className:"mono muted",children:"Full run input JSON"}),s.jsx("div",{className:"wait_shared_json",children:s.jsx(mr,{value:d_,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:[Ju.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,Xc(v.ts)].filter(Boolean).join(" · ")})]},`${v.cursor}:${v.node_id}:${v.status}`)),Ju.length?null:s.jsx("div",{className:"empty_state_inline",children:"No ledger context is loaded. Open the ledger before deciding."})]})]})]}),Ia.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:Ia.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"}),VS(v).map(O=>s.jsxs("span",{className:"chip mono muted",title:HS,children:[O,"~"]},O))]})]}),s.jsx("div",{className:"wait_tool_args",children:s.jsx(mr,{value:(v==null?void 0:v.arguments)||{},collapseAfterDepth:3,showCopy:!0})})]},`${String((v==null?void 0:v.name)||"tool")}:${C}`))}),kl?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 r_(c.trim(),"Cancelled from wait prompt"),disabled:!c.trim()||St,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(mr,{value:sn||{},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:ta||"No explicit prompt was provided. Open the ledger for context before responding."}),s.jsx($I,{wait:sn,disabled:St,on_submit:v=>Ml({response:v})}),s.jsx("div",{className:"actions",children:s.jsx("button",{className:"btn danger",onClick:()=>void r_(c.trim(),"Cancelled from wait prompt"),disabled:!c.trim()||St,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(mr,{value:sn||{},collapseAfterDepth:3,showCopy:!0})})]})]})]}):null]})]})]})}if("serviceWorker"in navigator){window.addEventListener("load",()=>{navigator.serviceWorker.register(tR).then(t=>t.update()).catch(()=>{})});let e=!1;navigator.serviceWorker.addEventListener("controllerchange",()=>{e||(e=!0,window.location.reload())})}W$();P$.createRoot(document.getElementById("root")).render(s.jsx(Ne.StrictMode,{children:s.jsx(j9,{})}));
|
|
174
|
+
//# sourceMappingURL=index-6qXs9M-h.js.map
|